Files
SirRoboGarage/docs/chimera-spec.md
T

698 lines
40 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CHIMERA — Online Neuro-Symbolic Opponent Policy-Twin with Active Causal Probing and Counterfactual Rollout (Tank Royale 1v1)
Status: design spec (M0). Nothing in this document is implemented yet, and nothing
outside this document is created by the run that produced it. CHIMERA is a plan,
not a description of code.
---
## 1. Summary & Novelty Statement
CHIMERA is an **online neuro-symbolic algorithm** that learns (clones) an opponent's
decision *policy* inside a live Robocode Tank Royale 1v1 match. Its purpose is to
answer a **counterfactual query**: *if I do X next tick, what will the enemy do for
the next 5 ticks?* The bot answers that query by running a **policy twin** — a
small executable model of the enemy's decision function — forward against the
server's physics model, under our candidate action.
The design combines three ingredients that each exist in game-AI literature but
have not, to our knowledge, been combined in Robocode / Tank Royale:
1. **An online DSL-level opponent policy-twin** — the enemy is modeled as a program
in a small domain-specific language of movement/gun/radar kernels, not as a black
box. Kernels are concrete, human-readable and fast (a 50–200 op program runs in
~1–10 µs in native Nim).
2. **Active causal probing** — the bot deliberately chooses probes whose outcome
*separates* competing hypotheses, spending a small score budget to buy
identifiability evidence.
3. **Counterfactual rollout within one match** — the twin is rolled forward 1/5/10
ticks under our candidate plan and used directly to steer behavior (predictive
bullet avoidance, position choice), never off-line.
### Honesty caveats
- This is **domain-first novelty**, not "new to game AI." Every component has
well-known ancestors; we claim the *combination in Robocode/Tank Royale* is new.
- The Robocode wiki has **zero pages** on counterfactual / opponent / imitation
modeling. It is community-edited and may under-report private bots, so "no prior
work" is an inference from public sources, not a proof.
### Related work (and why each falls short for this task)
| Work | What it does | Why it is not CHIMERA |
|---|---|---|
| **TRACE 2025** (arXiv:2503.00761) | Counterfactual probing of a reactive agent, offline, VLM-based | Offline and LLM/VLM-scale; not an in-match 30 ms budget |
| **M2I** (CVPR 2022) | Influencer → reactor decomposition | Multi-agent prediction, not control; no probing |
| **Tang 2020** (RHEA+OM) | Online opponent modeling inside a planning loop | Evolutionary planner, no explicit DSL twin, heavy compute |
| **DOMAC 2022** | Policy-conditioned opponent model | Offline/centralized training, not online 1v1 |
| **L2E 2021** | Learning to exploit | Needs pretraining corpus; exploits but does not identify |
| **OPS-DeMo 2024** | Online opponent-policy switch detection | Detects switch, does not simulate counterfactually |
| **HOP 2024, MBOM 2021** | Opponent modeling in poker/board settings | Discrete turn-based; different observability |
| **Classic Robocode: GuessFactor, Dynamic Clustering, Pattern Matching (MogBot), Play It Forward** | Predict the enemy's *future position* statistically | Position models, not policy twins; no counterfactual "if I do X" |
| **Wave Surfing** | The closest prior counterfactual | Frozen gun model + scalar danger field; not an enemy decision twin |
| **Lu 2022 zero-sum αβ** | Adversarial planning | Position estimate only, no learned policy |
---
## 2. Problem Formalization
**Setting.** Two bots, one arena, server-authoritative. We are bot A; the opponent
is bot B. The match is a sequence of discrete ticks. Each tick we send one intent
(body turn rate, target speed, gun turn rate and/or fire, radar turn rate) and
receive events describing what happened.
### Observable set
From `ScannedBotEvent` the *only* fields visible are:
```
{ scannedByBotId, scannedBotId, energy, x, y, direction, speed }
```
Everything about the enemy's internal command is **hidden**:
| Quantity | Visible? | Source of estimate |
|---|---|---|
| enemy x, y, direction, speed, energy | yes (on scan) | `ScannedBotEvent` |
| enemy turnRate | **no** | inferred from `direction` deltas |
| enemy targetSpeed | **no** | inferred (stateful) from `speed` |
| enemy gun direction, radar direction | **no** | not observable |
| enemy gunHeat | **no** | inferred from fire events |
| enemy fire decision | partial | `HitByBulletEvent` carries `bullet{ownerId,power,x,y,direction}` + damage |
| own x, y, direction, speed, energy, gunHeat | yes | own tick `botState` |
| own bullets | yes | `bulletStates` = **own bullets only** |
The own tick event carries the full own `botState` **including `gunHeat`**. Radar
radius is 1200; a scan arrives only when our own radar beam covers the enemy.
### Enemy intent vector
Define the per-tick enemy **intent** as
```
u_B(t) = ( turnRate_B(t) ∈ [-10,10],
targetSpeed_B(t) ∈ [-8,8],
fire_B(t) ∈ {0} ∪ [0.1, 3.0] )
```
This is the same control vector the API accepts; `turnRate` and `targetSpeed` are
continuous, `fire` is a rounded power (the server exposes no fire rate).
### Counterfactual query
Given the current twin posterior over enemy programs, our candidate plan
`ourPlan[1..k]`, and the believed enemy hidden state, define:
```
rollout(ourPlan, k) -> distribution over (u_B(t+1..t+k), enemy state trajectory)
```
The success metrics attached to a rollout at horizon `k` (twin-predicted enemy
position vs. realized, over held-out ticks) are:
- **ADE** — average displacement error over the horizon, in units.
- **FDE** — final displacement error, in units.
- **Fire-channel Brier score / log-loss** — calibration of the predicted
`P(fire)` per tick.
- **Identification ticks** — ticks until the posterior mass on the true kernel
exceeds threshold (see §12, G4).
---
## 3. Sensor Layer (precondition for everything)
CHIMERA assumes a **dense enemy stream**: at least one scan per tick while
tracking. This already exists as a solved component in `DevControlBot_garage`:
- Radar state machine: **SWEEP** (360° at +45°/tick, full revolution every 8 ticks)
→ **LOCK** (servo onto target bearing **plus a 5° overshoot**).
- The 5° overshoot is the mechanism: the radar *sweeps across* the bearing rather
than parking on it, so a fresh `ScannedBotEvent` arrives every tick.
- Turning by the bare bearing error, or holding at rate 0 inside a deadzone,
**stops the scans**; this is a recorded invariant and must never be reintroduced.
- SWEEP → LOCK requires `enemyCount == 1` and a target seen within
`FreshScanTurns`; LOCK → SWEEP on lost/stale (>10 ticks) or count ≠ 1.
**Dense-stream invariant:** while locked, the scan gap must satisfy `gap ≤ 1` tick.
CHIMERA's intent ledger (§4) consumes this stream; a `gap ≥ 2` tick causes
censoring, not guessing.
**Command-order invariant:** `commandRadar()` must be issued **before** `go()`, so
the radar command travels with this tick's intent. Movement is computed in the same
slot. This ordering is a real bug that is already fixed in the copy source.
---
## 4. Intent Ledger
The ledger converts the observable scan stream into per-tick intent *intervals*
(and, where ambiguous, a **CENSORED** mark). It never guesses.
### 4.1 turnRate inference
From consecutive scans:
```
Δdir = wrap180(dir(t) - dir(t-1))
```
- The physical bound is `|turnRate| ≤ 10 − 0.75·|speed|` (at the observed speed).
This yields the **interval** `[Δdir − ε, Δdir + ε] ∩ [−(10−0.75|v|), +(10−0.75|v|)]`,
with `ε` a small wrap/quantization slack.
- If successive scans are not adjacent ticks (gap), the tick is **CENSORED**.
### 4.2 targetSpeed inference (stateful)
`setTargetSpeed` is continuous; the wire exposes only realized `speed`. The
server's speed update is a sign-aware accelerate/decelerate rule (accel +1,
decel −2 per tick), with the special crossing-zero case. The ledger carries a
**speed-regime memory** and applies the three-case update verbatim:
```
case 1: v_prev == 0 -> v_new = clamp(targetSpeed, -1, +1)
case 2: sign(targetSpeed) == sign(v_prev)-> v_new = v_prev + sign(v_prev) (accelerate, step 1)
case 3: otherwise (crossing zero) -> v_new = v_prev + (1 - v_prev/2)·(-1) (brake, step 2)
```
(the exact server form is `(1 − v/2)·(−1)` applied to the sign-aware update; the
twin's step function must be unit-tested against this truth table, §12 Tier A).
Because the rule is stateful, the realized speed only bounds `targetSpeed`; the
ledger emits the interval of targetSpeeds consistent with `(v_prev, v_new)`.
### 4.3 Fire inference
- `HitByBulletEvent` carries `bullet{ownerId, power, ...}`. If `ownerId == B` and
the damage is consistent with `4·p + 2·(p − 1)` for `p > 1` (else `4·p`), we
record `fire_B(t) ≈ p`.
- Enemy **energy** drop across a tick corroborates a fire even when the bullet
has not yet connected (energy is spent at fire time), subject to cost
`= power`.
- Any residual ambiguity (multi-bullet, collision, wall damage overlapping) marks
the tick **CENSORED**.
### 4.4 Censoring
Ambiguous ticks are **excluded from Hedge updates** (no imputation, no guess).
The ledger exposes a **censoring rate** = censored / total ticks; this is tracked
and reported (§12, G3).
---
## 5. Enemy Hidden-State Tracker
The twin needs a belief over enemy internals that the wire never provides:
- **Estimated gunHeat.** Round starts at heat 3. On a fired shot, heat resets to
`1 + power/5`. Between shots, heat is a deterministic function of ticks elapsed.
Fire is only legal at heat `== 0`; the tracker maintains `gunHeatEstimate` and a
"can fire now" boolean, used by the probe gate (§9) and the twin's fire channel.
- **Enemy-view-of-us.** The enemy can only react to us when *their* radar covers
us. Their radar state is unknown, so the tracker keeps a **scan-age** estimate:
ticks since the enemy could plausibly have last seen us (bounded by radar rate
45°/tick and beam geometry). Kernels that key off "sees me" are only evaluable
when this belief is confident; otherwise the tick is down-weighted.
- **Speed-regime memory.** Persisted across ticks so the stateful speed rule (§4.2)
is invertible and the twin's propagation is exact.
---
## 6. DSL (Twin Program Language)
A twin is a **program** over observable input built from a small kernel library.
Grammar sketch:
```
Program := SensorDecl* Predicate* Action* Compose* ProfileSlot*
Sensor := sample(energy|x|y|direction|speed|scanAge|gunHeatEst|dist|bearing)
Predicate := cmp(Sensor, const) | and/or/not(Predicate) | true
Action := setTargetSpeed(expr) | setTurnRate(expr) | fire(power) | idle
Compose := mix(field (weighted), profile slot, loop counter)
Loop := repeat n | while(Predicate) max n | phase(t) % m
```
### Kernel inventory v0 (null-hypothesis set)
| # | Kernel | Essence |
|---|---|---|
| K1 | `orbit-with-hysteresis` (lock) | hold tangential orbit at a preferred range; hysteresis band prevents flip-flop |
| K2 | `anti-gravity field mix` | sum of repulsive force vectors (walls, bullets, enemy) → turn |
| K3 | `wave-perpendicular evasion` | move perpendicular to the incoming bullet wave |
| K4 | `stop-and-go` | alternate burst/stop; exploits acceleration rules |
| K5 | `corner-run` | run to a corner and bounce |
| K6 | `rammer` | drive straight at us |
| K7 | `RNG walk` (4 RNG classes) | pseudorandom turn/speed under LCG / xorshift / MT / hash-seeded classes |
| K8 | `mirror/shadow` | the **null hypothesis** program — do nothing adaptive; used as a fallback prior |
| K9 | `wall-crawl` | align to a wall, crawl it in segments (sample: Walls) |
| K10 | `static` | stationary posture + dedicated gun-purpose module (sample: TrackFire, Fire) |
Parameter slots per kernel: thresholds, preferred directions, RNG seeds, ranges.
Program size budget: **≤ 200 ops**.
---
## 7. Inference — Hedge Posterior over Kernels
The twin posterior is a weighted mixture over kernels `K1..KN` (N = 10–100),
updated online with **Hedge** (full-information setting — we always observe the
realized intent, when not censored, so EXP3 / partial feedback is unnecessary).
### Loss per tick
- **Δheading squared error** on the turn channel.
- **targetSpeed interval log-likelihood** (interval observation → log of the
probability the kernel's predicted speed lies in the ledger interval).
- **Fire Bernoulli log-loss** on `fire_B ∈ {0, p}`.
`Δloss` is scaled to ~0.01–0.1 range so that the learning rate `η` is stable.
### Update
```
w_i(t+1) = w_i(t) · exp(-η · loss_i(t)) · (1 - 1/τ) + a·(m_i - w_i(t))
```
with exponential forgetting `τ = 200` ticks default (range 50–500) and a
**Fixed-Share** term `m_i` that guarantees a mass floor `a > 0`, so a wrong-but-
resurrected kernel can recover. Update is **O(N) per tick** (sub-millisecond at
N ≤ 100).
### Prediction
The twin predicts with the **weighted mixture**, never the argmax — the marginal
distribution is what the counterfactual query needs, and it also smooths the
early-match phase where no kernel dominates.
### Round carry-over (M5.5 amendment)
The enemy bot is the **same program across the rounds of a match**, so the
posterior (and the kernel memories' internal state) is **carried across rounds**
instead of reset to uniform each round: identification compounds across rounds.
**"Round carry-over adopted at M5.5 (user-delegated decision): identification
compounds across rounds; ablation flag kept."** The ablation flag
`-d:chimeraFreshRound` restores the per-round uniform reset (G6 arm).
RNG-derived kernel-memory state is re-sampled at each round start, because a
per-round sampled parameter (e.g. Corners' `randomize()` start corner) must not
be carried.
---
## 8. Twin Rollout (Counterfactual Core)
`simulate(ourPlan[k], k=1..5)` performs:
1. **Physics step mirror.** A pure-Nim reimplementation of the server's 13-step
update order (double precision, `eps = 1e-6`), covering: max speed ±8; accel +1,
decel −2; sign-aware crossing-zero formula; max body turn `10 − 0.75·|v|`; gun 20;
radar 45; bullet speed `20 − 3·power`; damage `4p + 2(p−1)` if `p>1`; heat
`1 + p/5`; round-start heat 3; fire only at heat 0; bot-bot collision stops both
(0.6 dmg each) unless the mover is moving away; wall damage `|v|/2 − 1`.
**This mirror is unit-tested against server math truth tables (§12 Tier A)** —
a mismatch silently poisons every downstream claim.
2. **Hidden-state propagation.** §5 tracker advanced in lockstep.
3. **Output.** A distribution over the enemy's next intents per tick plus a
**fire-time estimate** (`P(fire)` per future tick).
**Use case — predictive bullet avoidance:** before committing a movement, roll the
twin forward under our candidate plan; if the twin's fire estimate spikes on ticks
where our plan sits on the enemy's gun line, the plan is penalized. This is the
concrete payoff that distinguishes CHIMERA's counterfactual from Wave Surfing's
frozen danger field.
---
## 9. Probe Scheduler
**Budget.** 1 probe per 20–30 ticks.
**Survival gating** (no probe when any holds):
- our energy is low;
- their `gunHeat` is (near) zero **and** they are aimed at us;
- we are wall-pinned.
**Camouflage.** Probe actions must be plausible as ordinary movement noise, so a
kernel-based opponent cannot detect the probe and switch policy.
**Probe set v2 (M5.5).** The candidate set covers **six probe types**: four
movement probes (sudden stop, reversal, speed modulation, direction flip), a
**GUN probe** (a low-power shot at the enemy — the probe *is* the shot, aimed to
trigger dodging/hit-response branches such as Fire's reverse-on-hit; never
issued with low energy, a hot/unaligned gun, or an enemy positioned to punish)
and a **DISTANCE probe** (approach/retreat burst — a strong target-speed step
that changes our bearing/range trajectory and triggers RamFire/Corners-like
geometry branches). Entropy-drop selection is extended to all six types.
**Information gain.** Rank candidate probes by **estimated posterior entropy
reduction** — expected drop of `H(posterior)` from the predicted separation of
hypotheses (§12, G2 uses the same notion offline).
**Decision 2 (codified):** probes **MAY cost score** (Option A). The probe budget
is a tunable **cost ledger** for the future: we buy identifiability with a small
amount of match score, and the scheduler never probes when survival gating fires.
---
## 10. Residual Head & Fusion
The DSL is a compact approximation; a **residual head** absorbs systematic
mispredictions:
- **Linear residual** (default) — per-kernel affine correction of `(turnRate,
targetSpeed)`.
- **32-unit GRU residual** (upgrade path) — online SGD at millisecond scale.
**Fusion.** The final prediction is a convex combination of the DSL-mixture
prediction and the residual model, weight tuned by realized prediction loss.
**Failure fallback (hard requirement).** If the realized-vs-predicted loss
degrades beyond thresholds, CHIMERA ramps its influence to **zero** and the bot
degrades to DevControlBot behavior. The learning system is therefore **never worse
than the copy it started from** (§12, G7).
---
## 11. Garage Plan (explanatory only — nothing created yet)
Working name: **ChimeraBot** (Decision 1 — kept; see Resolved decisions §1).
```
ChimeraBot_garage/ # follows the ROOT template, NOT DevControlBot_garage's
├── src/
│ ├── chimerabot.nim # bot type + entry point (isMainModule)
│ ├── chimerabot.json # bot metadata (name field = ChimeraBot)
│ ├── chimerabot.nimble # task: runBot
│ ├── chimerabot.sh # BotLauncher wrapper
│ ├── config.nim
│ └── chimerabot/
│ ├── twin/ # physics mirror + rollout
│ ├── ledger/ # intent ledger + hidden-state tracker
│ ├── probes/ # probe scheduler
│ └── dsl/ # kernel library + Hedge
├── tests/ # config.nims --path:"../../common_libs"
├── out/ # compiled binaries
└── AGENTS.md
```
**EXACT COPY clause.** Phase 0 behavior is **identical to DevControlBot**:
- movement is a port-independent copy of `tfil.nim`, **no runtime dependency on
`common_libs/`** — do not add one, do not edit the original;
- radar reuses the same 5°-overshoot lock design, all radar logic in **one module**;
- firing: the source copy already carries the **ELM gun** (`ELM/elm_gun.nim`,
`elm_gun_weights.txt`, firing via `computeGun`/`setFire`) — **live fire exists
from M1**; "Phase 0 never fires" is withdrawn (see Resolved decisions §3).
- identity rename only: file names, bot name, `.json` name field, wrapper script
name. The nimble task **stays `runBot`** (tasks are per-nimble, so no conflict
with other garages; only the script name changes).
**House rules carried over:** `SERVER_URL` / `SERVER_SECRET` are read by the API's
`start()`, never by bot code; `.env` is optional and never committed; every file
under a garage is committed unless gitignored; **no version bumps or tags by
agents**; `DevControlBot_garage/PLAN.md` is untouched and **no `PLAN.md` is created
for the new garage**; throwaway output goes to `/tmp` only.
---
## 12. Test Plan — the centerpiece
Three tiers, each with explicit PASS conditions, followed by the Falsification
Matrix that answers the core requirement: *if the bot is not learning, prove
whether the idea was wrong or the implementation.*
### Tier A — Unit (pure Nim, no Java)
| Area | Test | PASS condition |
|---|---|---|
| Physics mirror | speed-step truth table incl. crossing-zero; accel +1 / decel −2; clamp ±8 | exact match to server math |
| Physics mirror | turn-rate cap identities `10 − 0.75·|v|`; gun 20; radar 45; bullet speed `20−3p`; damage; heat `1+p/5` | exact |
| Intent ledger | synthetic streams with known `(turnRate, targetSpeed)` | exact turn-rate recovery; targetSpeed interval **contains** truth and width ≤ bound |
| Hedge | normalization, `η` bounds, forgetting revives a correct kernel | `Σw = 1`; revived weight rises |
| Hedge | Fixed-Share mass floor | `w_i ≥ a·m_i` for all i |
| DSL | determinism (same seed+input ⇒ same output); size budget | byte-identical reruns; ≤200 ops |
| Probes | gate truth table (survival states ⇒ allow/deny) | matches spec |
| Entropy | posterior entropy computation | exact closed-form value |
### Tier B — Integration (`common_libs/test_framework`, guard-first skip)
Guard first (`TR_SERVER_JAR` / `TR_BATTLE_RUNNER` unset ⇒ skip, exit 0), then:
- Battles vs. the **official Nim sample bots** as the **primary ground-truth suite**
(see "Benchmark opponents" below). The six repo adversaries are optional extra
diversity only — **NON-LOAD-BEARING, not ground truth**.
- **At least 3 scripted ARCHETYPE opponents written for this garage**, implementing
DSL kernels **1:1** — supplementary **scripted ground truth**, secondary to the
official suite: each emits its kernel's behavior exactly, so a correct posterior
must converge to it.
- **Twin telemetry recorded to `/tmp`** (garage rule: throwaway output lives only
in `/tmp`).
- `tests/config.nims`: `--path:"../../common_libs"`; one `test<concern>.nim` per
concern; a `test` task in the `.nimble`.
**Harness server port (user decision, recorded M2).** The harness always starts
its server on a **random free port**, never the default 7654: `SERVER_URL =
ws://127.0.0.1:<random-port>`. This also avoids the localhost→`::1` connect hang.
### Benchmark opponents — primary ground-truth suite
**Local binaries.** The official Nim sample bots are unpacked locally at
`/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7/` — a
**binary-only** distribution: 13 ELF bots + 1 team, each a folder holding
`<Bot>`, `<Bot>.sh`, `<Bot>.cmd`, `<Bot>.json`. Each bot is launched through its
`.sh` wrapper with `SERVER_URL` (+`SERVER_SECRET`) set; the API's `start()` reads
those env vars itself, not bot code.
**Ground-truth sources.** github `SirStone/robocode_tankroyale_botapi`,
`sample_bots/` — **not** `robocode-dev/tank-royale` (no Nim samples; 404s).
Available: `Corners, Crazy, Fire, MyFirstBot, MyFirstDroid, MyFirstLeader,
MyFirstTeam, PaintingBot, RamFire, SpinBot, Target, TrackFire, VelociBot, Walls`.
No SittingDuck / Walli in the Nim set.
**Verified kernel mapping (behavior table)** — ground truth for DSL identification:
| Bot | Behavior (from source) | Randomness |
|---|---|---|
| Crazy | forward 40000 + 180° turn zigzag; gun idle, radar rides gun; fire(1) on scan; reverses on wall/ram | **none** |
| SpinBot | turn 10000 + maxSpeed 5 + forward 10000 (circling); fire(3) on scan; small turn on ram | none |
| RamFire | 5°/tick idle turn; on scan faces target, forward(dist+5), rescan(); fire scaled by enemy energy on ram | none |
| Corners | run to a corner, turnGunLeft(90)/forward, sweep gun ±3, stop + smartFire(dist) on scan; start corner picked stochastically | **uses std/random + randomize() + rand(3)** |
| Walls | align to nearest wall, forward moveAmount, turnLeft 90 per segment, gun inward, fire(2) on scan, rescan() when peeking | none |
| TrackFire | sits still, turnGunRight(10); on scan align gun, fire ≤3 when aligned & heat 0, rescan() | none |
| Fire | sits still, turnGunRight(5); fire(3) if dist<50 & energy>50 else 1; dodge by reversing on hit-by-bullet | none |
**Kernel-inventory additions (DSL v0).** The table adds two kernels to §6:
**WALL-CRAWL** (Walls) — wall-aligned segment crawling; and **STATIC**
(TrackFire / Fire) — stationary posture + a dedicated gun-purpose module. Corners
is the **stochastic-origin case**: `randomize()` in `main` varies the start corner
per match, so the RNG machinery (K7) must handle **per-round sampled params**
(re-sample each round). Crazy/SpinBot are orbit/turn-set variants confirming
existing kernels.
**Version caveat / M3 kickoff checkpoint.** The local binaries tag **1.0.7**;
GitHub `main` sources may differ from that tag. Verify tag↔code correspondence
(`.json` provenance credits author Davide Cappellini) **before benchmarking** — an
M3 gate (§13).
**Repo adversaries (SittingDuck, OscillatorBot, ConstantSpinner, PatternMover,
RandomMover, WaveSurfer).** Optional extra diversity only — **NON-LOAD-BEARING,
untrusted for ground truth** (created, never properly tested). Only official Nim
samples carry ground-truth weight.
### Tier C — Mathematical falsification goals (G1..G7)
**G1 — ORACLE CONVERGENCE.** Feed the posterior the *oracle* intent stream
generated by kernel K (offline, exact, no sensor error). The Hedge weight on K
must reach **≥ 0.9** within `T*` ticks (`T*` stated per kernel). *If G1 fails, the
inference-layer implementation is buggy; the idea is exonerated.*
**G2 — IDENTIFIABILITY.** For every kernel pair `(Ki, Kj)` there exists a probe
sequence of length `≤ L` inducing enemy-intent distributions separated by
`≥ δ` (KL or total variation), computed by exhaustive short-sequence simulation
over the DSL. *If G2 fails, the DSL/library design is insufficient — an idea-level
failure, not a code bug.*
**G3 — CENSORING BUDGET.** Censored ticks ≤ **15%** across the benchmark suite.
*Higher ⇒ observability problem (data path), not induction.*
**G4 — LIVE IDENTIFICATION.** Against the official sample-bot primary suite, a
set of **behavior-diverse targets** reach posterior ≥ 0.8 within **300 ticks**
(10 s @ TPS 30) in pinned-initial-position battles.
**Metric unification (M5.5, binding).** `idTicks` is defined ONE way everywhere:
per round, the **round-relative** tick at which `max_kernel posterior > 0.8`
first holds — the posterior has committed to *some* kernel. Correctness of that
kernel (does the argmax equal the expected kernel?) is reported as a separate
diagnostic column, never absorbed into the metric. Per opponent the bench reports
**median**, **p90** and **id-fraction** (% of rounds identified) over ALL rounds
in the protocol. The old M3.5 "best round / total ticks" aggregation is retired.
**G4 pass condition: median ≤ 300 ticks AND id-fraction ≥ 80% over ≥ 3 full
8×5 runs** (24 rounds/opponent), not a single run. Primary identification set
(**8 most behavior-diverse** from the verified table): **{Crazy, SpinBot,
RamFire, Corners, Walls, TrackFire, Fire, MyFirstBot or VelociBot}**. **Corners is
the mandatory stochastic case** (its `randomize()` start-corner must be handled as
per-round sampled params). Excluded: PaintingBot (debug-painting only),
MyFirstTeam/Droid/Leader (team bots — no 1v1), `Target` (likely a static target
— verify at M3). *Failure with G1–G3 green ⇒ the idea is wrong: single-stream
induction is insufficient.*
**G5' — INTERVENTIONAL COUNTERFACTUALS.** Measured on the ticks that FOLLOW an
executed probe (the *interventional* scenario set — the only ticks where our own
action was chosen to separate the hypotheses), the twin mixture's 5-tick
enemy-reaction prediction must beat the persistence baseline (constant-velocity
carry) on **≥ 70%** of probe-following scenarios. The bar is interventional on
purpose: the twin's claim is "*if I do X, the enemy does Y*", and that claim is
only testable where X was actually chosen to separate the hypotheses. A **≥ 90%**
agreement is reported as a separate **stretch** row, never as the gate.
**G5' v2 protocol (M5.5, binding).** Results are reported separately for
**(a) the MOVING subset {Crazy, SpinBot, VelociBot, Walls}** — where
constant-velocity persistence is *not* optimal by construction — and **(b) the
full suite**. Per opponent: twin vs persistence interventional 5-tick ADE after an
executed probe, plus reaction-direction agreement. **Bar: twin ≥ persistence on
≥ 70% of MOVING-subset scenarios.** The **STATIC subset {RamFire, Corners,
TrackFire, Fire}** is reported with a **saturation analysis** (one line per static
opponent: why twin ≈ persistence by construction).
**Observational sanity floor.** Independently of the interventional bar, the
twin's 5-tick ADE must stay **≤ 2× the persistence ADE per opponent** on the full
observational set — a regression guard, not a superiority claim.
**M4 falsification (recorded verbatim).** The M4 observational eval (twin 5-tick
rollout vs persistence over ALL recorded origin ticks) had twin ADE ≤ persistence
ADE on only **20.1%** of scenarios, against the original **≥ 90%** bar — a plain
falsification of G5 *as originally stated*. Diagnosis: the observational protocol
is persistence-favourable. Over a short 5-tick horizon a constant-velocity carry
tracks the realized enemy path closely, while the twin pays for a mixture that
must re-commit after each regime change; and on an observation-only run our own
movement is itself a reaction to the enemy, so the "counterfactual" is not
intervened on at all. The result indicts the *observation-only measurement*, not
the interventional claim, which M5 tests directly.
**M3.5-vs-G6 aggregation discrepancy (recorded verbatim, M5.5).** M3.5 reported
"8/8 ≤ 300 ticks" using a **different aggregation** than G6's per-round medians:
per-opponent total/best-round ticks versus per-round medians. Under the G6
per-round aggregation the same bots show Corners 445, Crazy 2439, and an
identification fraction of only 13–40% of rounds. The "8/8" claim therefore did
not survive re-aggregation; M5.5 unifies the metric so the discrepancy cannot
recur.
**G6 — ABLATION LADDER.** `full CHIMERA ≥ (−probe) ≥ (−residual) ≥ fallback` in
identification speed; probes must cut **median** identification ticks by **≥ 20%**
(median over ≥ 3 full runs, to survive the G4 spawn-variance), under the unified
idTicks metric and measured on the **MOVING subset** as the primary read. M5.5
runs the four-way probe × carry-over arms (`full`, `−probe`, `+freshRound`,
`−probe+freshRound`); the `−residual` and `fallback` rungs arrive at M6.
*Failure (still null after probe v2) ⇒ a component-value claim is wrong.*
**G7 — NO-REGRESSION FLOOR.** ChimeraBot ≥ exact-copy DevControlBot behavior in
head-to-head and against the primary benchmark suite (official sample bots) as
well as the optional repo adversaries as extra diversity (win rate / score
bounds), i.e. learning never makes it worse when the twin is uncertain.
### Falsification Matrix
| Goal | Boundary | Failure proves |
|---|---|---|
| G1 | offline oracle | **implementation bug** (inference layer) |
| G2 | DSL/none | **library design insufficient** (idea-level) |
| G3 | data path | **observability problem** |
| G4 | go/no-go | **idea invalid** (single-stream induction insufficient) |
| G5' | interventional usefulness | **twin not decision-useful under its own actions** (idea-level) |
| G5' (M6.5 horizon sweep) | observational, horizons 1–50 | **twin loses to persistence at every long horizon** (idea-level) |
| Twinsim reconstruction (M6.5) | replay path == oracle path | **implementation bug** if they diverged — they do not (byte-equal): the M6.5 hypothesis is falsified |
| Fusion mixer (M6.5) | oracle-data predictor race | **fusion correctness bug** (command vs realized space; power-as-probability) when the residual wins on clean oracle data |
| G6 | components | **component value claims wrong** |
| G7 | safety floor | **fallback/fusion correctness bug** |
The matrix is the answer to *"if the bot is not learning, can we prove whether the
idea was wrong or the implementation?"*: G1/G3/G7 failures indict the build;
G2/G4/G5/G6 failures indict the idea or its components.
### Final status M0–M6 (recorded at M6, §13 milestone close-out)
Each goal: PASS / FAIL / UNPROVEN with the recorded numbers and the caveat.
Source artifacts: `benchmarks/g1_oracle_table.md`, `benchmarks/m5_5_g4.md`,
`benchmarks/m5_5_g5p.md`, `benchmarks/m5_5_g6.md`, `benchmarks/m6_g7.md`.
| Goal | Verdict | Recorded numbers + caveat |
|---|---:|---|
| G1 | **PASS** | 12/12 kernels identify ≤ 300 ticks; finalPost ≥ 0.90 (`g1_oracle_table.md`). In practice most identify in ≤ 161 ticks. |
| G2 | **UNPROVEN** | No dedicated separated-identification probe-sequence bench was executed; kernel-pair separability is not directly scored (only the G1 single-stream path is). |
| G3 | **PASS** | Censoring rate 0.00% across the G4/G6 sample-bot suite; well under the 15% budget. |
| G4 | **PASS** | 8/8 primary targets, every pooled median ≤ 300 ticks (5 of 8 median = 1) and id-fraction 100% over 3×5 runs (`m5_5_g4.md`). Caveat: argmax-vs-expected correctness is partial (Corners 60%, Crazy 67%, VelociBot 27%) on statics — the posterior commits to *a* static kernel, not always the right one. |
| G5' | **FAIL** | Interventional bar not met: MOVING-subset twinWin 32.8% vs ≥ 70% (FULL 23.4%); STATIC subset saturates (persistence ≈ optimal at v=0), so the twin can only match/lose there (`m5_5_g5p.md`). Caveat: this is the interventional G5' v2 protocol; per-opponent SpinBot shows 94.5% twinWin, so it is opponent-dependent, not uniformly dead. |
| G6 | **FAIL** (probe rung) / **PASS** (carry-over) | Probes give no robust ≥ 20% median id-cut on the MOVING subset — the cut sign flips and swings −550%…+83% across four 4-arm invocations (`m5_5_g6.md`). Probe component value claim is not supported. Carry-over is large and stable (reset→on gain 54–97%) → PASS. |
| G7 | **PASS** (safety floor, stated bar) | Head-to-head full-vs-inert win-rate **54.0%** over 10×5 rounds (bar ≥ 50%), survival 40/39, score margin +1621 (`m6_g7.md`). No-regression: full ≥ inert win-rate on **all 8** suite opponents. **Caveat (plain):** full's per-opponent *score margin* is smaller than inert's on 5 of 8 opponents (Corners, Crazy, RamFire, TrackFire, Walls) with equal win-rates, and full-minus-probes reached 100% on VelociBot where both full and inert got 80% — so CHIMERA is not worse by win-rate but is **not measurably better** against this suite; the fallback/fusion never degrades survival. |
### Final status — M6.5 additions (close-out)
| Item | Verdict | Recorded numbers + caveat |
|---|---:|---|
| Twinsim state reconstruction | **FALSIFIED (as a hypothesis)** | `tests/test_replay_oracle.nim`: oracle-generated telemetry replayed through `twinsim.replay()` yields the per-tick posterior + kernel-memory state **byte-equal** to the oracle path for all 12 kernels; on live telemetry (Crazy round 1) the replay posterior equals the recorded live posterior for 1396/1396 ticks (entropy and argmax identical). The state reconstruction was already faithful — no twinsim change was needed. |
| Fusion mixer | **FIXED (implementation bugs)** | The residual head dominated because (1) the fusion scored the mixture's raw turn *command* against the server-capped *realized* turn (mean turn error 3.38 raw vs 0.09 capped — the residual absorbed the `limitTurnRate` gap) and (2) fire was fed as a weighted *power* (≈1.0 wherever a high-power kernel had mass) into a Bernoulli log-loss whose channel then dominated the fusion. Fixed in `observer.nim` (cap the mixture turn; use a binarized fire probability) and `fusion.nim` (`residualTrajectory` caps the base before adding the correction). |
| Fusion smoke (ORBIT_BALLIST oracle) | **FALSIFIED (residual not marginal)** | Fusion weights before fix: mixture 0.022 / residual 0.943 / persistence 0.036. After fix: mixture **0.117** / residual **0.804** / persistence 0.079. The fix lifted the mixture but the linear residual STILL wins on clean oracle data — §10's "residual absorbs systematic mispredictions" holds only because the residual is a second full predictor, not a correction. Recorded as a falsification row. |
| Horizon sweep G5' | **FALSIFIED-ON-SUITE** | MOVING subset {Crazy, SpinBot, VelociBot, Walls}, horizons {1,5,10,25,50}, 3 full 8x5 runs (`benchmarks/m6_5_horizonsweep.md`). Origin-weighted twin/persistence ADE ratio: **4.43 / 3.44 / 2.56 / 1.49 / 1.03** at h=1/5/10/25/50 — >= 1.0 at every horizon >= 10. Per opponent at h=50: Crazy 0.98, SpinBot 0.90, VelociBot 0.77 (below 1) but Walls 1.50. The "validated-conditionally" rule (>= 3/4 moving opponents below 1 at >= 2 long horizons) fails: only SpinBot clears 2 long horizons (SpinBot 3, Crazy 1, VelociBot 1, Walls 0). Caveat: the failure narrows with horizon (h=1 ratio 4.43 -> h=50 ratio 1.03), so the twin's dynamics are not futile — they are simply not yet better than a constant-velocity carry on this suite. |
**Plain-language verdict (M6.5 close-out).** The inference layer stays sound
(G1/G3/G4 green) and the safety floor holds (G7). The M6.5 close-out killed the
last hope that the M5.5 G5' failure was a *reconstruction* artefact: `twinsim`
`replay()` reproduces the oracle per-tick state byte-equal for all 12 kernels and
matches the live recorded posterior on real telemetry, so the twin loses to
persistence because of what it predicts, not because it is fed the wrong state.
Two genuine fusion implementation bugs were found and fixed along the way (the
mixture's turn command was scored against the server-capped realized turn, and
fire was fed as a power rather than a probability), but the decisive horizon
sweep is unambiguous: on the MOVING subset, over 3 full 8x5 runs, the
twin/persistence ADE ratio is 4.43 / 3.44 / 2.56 / 1.49 / **1.03** at horizons
1/5/10/25/50 — never below 1.0 at any horizon >= 10. Only at h=50 do three of the
four moving opponents individually flip below 1 (Crazy 0.98, SpinBot 0.90,
VelociBot 0.77); Walls (1.50) and the origin-weighted suite keep the ratio above
1. The residual head still beats the mixture even on a clean ORBIT_BALLIST oracle
stream (weight 0.80 vs 0.12 after the fixes), so the residual is not a marginal
correction as §10 assumes. The honest read: CHIMERA's counterfactual rollout is
**falsified on this suite**; the parts that make the idea special (interventional
prediction, probing) are unproven or falsified at their stated bars, and the only
green results are the inference layer and the no-regression floor it did not need
to earn.
**Plain-language verdict (M6).** The inference layer is sound (G1/G3/G4 green: the
posterior identifies every sample-bot kernel fast, at zero censor cost, and the
future-handicap fallback keeps the bot no worse than its copy by win rate). Two
idea-level claims did **not** hold up: the interventional counterfactual
(G5') and the probe value (G6). The M6 residual/fusion/influence layer is green
on its safety floor (G7 PASS) but shows no measurable *benefit* yet — the sample
suite is too easy (full, inert and no-probe all win ~100% of rounds, differing
only by score margin), so the honest read is: CHIMERA has not been shown to make
this bot better, and the parts that make the idea special (interventional
prediction, probing) remain unproven or falsified at their stated bars.
---
## 13. Milestones
- **M0 — Spec** (this document).
- **M1 — Garage bootstrap + exact copy + Tier A units green.**
- **M2 — Intent ledger + oracle tests (G1).**
- **M3 — DSL + Hedge + identification benchmark (G2, G4).** Two M3 gates:
(a) verify the local sample-bots **1.0.7** tag against GitHub `main` sources;
(b) verify `tps=-1` behaviour against the installed server (Resolved decisions
§2). Nothing is benchmarked until both are done.
- **M4 — Twin rollout + counterfactual metrics (G5).**
- **M5 — Probes (G3, G6).**
- **M6 — Fusion + residual + fallback (G7).** Implemented: `residual.nim`
(online linear head; 32-GRU behind `-d:chimeraGRU`, not enabled),
`fusion.nim` (hedge over mixture/residual/persistence predictors),
`influence.nim` (loss-ramped 0..1 overlay on the TFIL command, never inside a
bullet dodge). Ablations `-d:chimeraNoFusion` / `-d:chimeraInert`. Tier A
tests (`test_residual/fusion/influence`) green; G7 head-to-head + suite PASS
on the stated bar (margins caveat above).
### Resolved decisions
| # | Question → resolution |
|---|---|
| 1 | **Name: keep `ChimeraBot`** (user decision — no rename). |
| 2 | **Benchmarks run at MAX TURN RATE / FPS.** `tps = -1` is **valid**: the installed `robocode-tankroyale-server.jar` CLI (`--tps`) defines range **`[-1..999]`** where **`-1` = maximum TPS** and `0` = paused; `applyVisualDelay` sleeps only when `tps > 0`, so `-1` runs unthrottled (see M3 gate (b)). Use `tps=-1` for CI/benchmarks. |
| 3 | **Live fire IS in scope.** Fact-check: the M1 exact-copy bootstrap **already includes the ELM gun** (`ELM/elm_gun.nim`, `elm_gun_weights.txt`; fires via `computeGun` / `setFire`) — **live fire exists from M1**, so the `DevControlBot_garage/AGENTS.md` "never fires" claim is stale vs. code. CHIMERA upgrades: **fire-timing prediction via the twin at M4**; the ELM gun remains as a **fusion baseline component (do not remove)**. |
| 4 | **Probe cost: keep default 1 probe per 20–30 ticks (nominal 25),** survival-gated; tune only on G6/G7 evidence. |
| 5 | **`T*` per kernel (G1): provisional uniform `T* = 300` ticks** until the kernel library freezes; any failure is re-estimated with diagnosis before an idea-level verdict. |