ChimeraBot_garage: M5 — probe scheduler, advisory wiring, G6 ablation ON/OFF, G5 interventional eval

This commit is contained in:
2026-10-07 00:33:31 +02:00
parent da9a66aab8
commit 6a3ba390ee
10 changed files with 944 additions and 5 deletions
+34 -2
View File
@@ -34,6 +34,7 @@ import ChimeraBot/modules/ELM/elm_gun
import ChimeraBot/modules/ELM/elm_features
import ChimeraBot/chimera/observer
import ChimeraBot/chimera/dsl
import ChimeraBot/chimera/probes
const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds
## only what it scans, so this is a cap, not a limit
@@ -79,6 +80,8 @@ type ChimeraBot* = ref object of Bot
## joined to a recording round
observer: Observer ## observation-only sidecar (§12 G3/G4 telemetry)
opponentLabel: string ## telemetry filename label (env, observation-only)
probes: ProbeScheduler ## active causal probing (spec §9, M5); disabled by
## -d:chimeraNoProbes (see ProbesEnabled)
proc newChimeraBot*(): ChimeraBot =
result = ChimeraBot()
@@ -93,6 +96,8 @@ proc newChimeraBot*(): ChimeraBot =
# filename; it labels observations, it does not change behaviour.
result.opponentLabel = getEnv("CHIMERA_OPPONENT", "")
result.observer = initObserver(allKernels(), telemetryDir)
when ProbesEnabled:
result.probes = initProbeScheduler(allKernels())
setRadarColor(WHITE) # overwritten by initRadar() before the first tick
method onScannedBot*(bot: ChimeraBot, e: ScannedBotEvent) =
@@ -277,8 +282,35 @@ method run*(bot: ChimeraBot) =
commandRadar()
bot.ageEnemies() # stale scans dropped before they paint heat
let (speed, turnRate) = bot.mover.computeMove(bot.buildWorldState())
setTargetSpeed(speed)
setTurnRate(turnRate)
# Probe advisory (spec §9, M5): past the budget interval AND when the
# survival gate allows, the commanded movement this tick becomes the chosen
# probe; otherwise the TFIL command is untouched. `-d:chimeraNoProbes`
# removes this block entirely (G6 ablation OFF arm).
var cmdSpeed = speed
var cmdTurn = turnRate
when ProbesEnabled:
if bot.observer.hasCurrent:
let porigin = bot.observer.probeOrigin()
let ctx = ProbeContext(
tick: bot.tick, ourEnergy: getEnergy(),
ownX: porigin.ox, ownY: porigin.oy, ownSpeed: porigin.ospeed,
arenaW: getArenaWidth().float, arenaH: getArenaHeight().float,
enemyX: porigin.ex, enemyY: porigin.ey,
enemyGunHeat: bot.observer.enemyGunHeat(),
enemyAimedAtUs: aimedAtUs(porigin.ox, porigin.oy,
porigin.ex, porigin.ey, porigin.edir),
roundLimit: RoundSoftLimit)
let decision = bot.probes.consider(porigin, ctx)
if decision.trigger:
bot.observer.writeProbeEvent(bot.tick, $decision.candidate.kind,
decision.gate.reason, decision.entropyBefore,
decision.entropyAfter, decision.candidate.turnRate,
decision.candidate.targetSpeed)
if decision.gate.allow:
cmdSpeed = decision.candidate.targetSpeed
cmdTurn = decision.candidate.turnRate
setTargetSpeed(cmdSpeed)
setTurnRate(cmdTurn)
bot.computeGun() # gun intent, also before go()
go()
bot.observer.writeTick(bot.tick) # observation telemetry, after go()
+1
View File
@@ -260,3 +260,4 @@ task test, "Run unit tests":
exec "nim c -r --hints:off ../tests/test_oracle_g1.nim"
exec "nim c -r --hints:off ../tests/test_observer.nim"
exec "nim c -r --hints:off ../tests/test_twinsim.nim"
exec "nim c -r --hints:off ../tests/test_probes.nim"
@@ -19,7 +19,7 @@
## readiness check for the M4 twin rollout, not the twin itself.
import std/[math, os, strutils]
import ./physics, ./ledger, ./dsl, ./hedge, ./oracle
import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim
const
MaxHorizon* = 5 ## rollout horizon for the G5-metrics readiness check
@@ -51,6 +51,8 @@ type
censored, ticks: int
gapMax, gapViolations: int
enemyHeat: float64 ## ledger-derived enemy gun-heat estimate (probe gate)
round: int
opponent: string
f: File
@@ -76,6 +78,7 @@ proc initObserver*(kernels: seq[Kernel], telemetryDir = ""): Observer =
result.mems[i] = defaultMemory(kernels[i].defaultParams)
result.telemetryDir = telemetryDir
result.scanTick = -1
result.enemyHeat = 3.0
for i in 0 ..< PredSlots: result.predOrigin[i] = -1
proc resetRound(o: Observer) =
@@ -92,6 +95,7 @@ proc resetRound(o: Observer) =
o.gapViolations = 0
o.adeSum = 0; o.adeN = 0
o.fdeSum = 0; o.fdeN = 0
o.enemyHeat = 3.0 ## round-start heat (spec §5)
for i in 0 ..< PredSlots: o.predOrigin[i] = -1
proc sanitize*(s: string): string =
@@ -211,6 +215,9 @@ proc observeScan*(o: Observer, tick: int, x, y, direction, speed, energy: float6
o.lastObs = obs
o.haveLastObs = true
inc o.ticks
# Enemy gun-heat estimate (probe gate, spec §5): a fired shot pins heat to
# `1 + power/5`; writeTick decays it one per tick. Observation-only.
if obs.fireKnown: o.enemyHeat = gunHeat(obs.fire)
if obs.censored:
inc o.censored
else:
@@ -240,10 +247,39 @@ proc censorRate*(o: Observer): float64 =
proc argmaxName*(o: Observer): string = o.hedge.argmaxName()
proc posterior*(o: Observer, name: string): float64 = o.hedge.posterior(name)
proc entropy*(o: Observer): float64 = o.hedge.entropy()
proc hasCurrent*(o: Observer): bool = o.haveCur
proc enemyGunHeat*(o: Observer): float64 = o.enemyHeat
proc probeOrigin*(o: Observer): ReplayTick =
## The current causal posterior + observed enemy/own state, as the probe
## scheduler's counterfactual origin. Read-only: `mems`/`weights` are copied.
result = ReplayTick(tick: o.cur.tick, ex: o.cur.x, ey: o.cur.y,
edir: o.cur.direction, espeed: o.cur.speed,
eenergy: o.cur.energy,
ox: o.curOwnX, oy: o.curOwnY,
odir: o.curOwnDir, ospeed: o.curOwnSpeed,
lastTurn: 0.0, lastSpeed: o.cur.speed)
result.weights = o.hedge.weights
result.mems = o.mems
proc writeProbeEvent*(o: Observer, tick: int, kind, gateState: string,
entropyBefore, entropyAfter, turnRate,
targetSpeed: float64) =
## One JSONL line per triggered probe (executed or gate-blocked). The
## interventional G5' eval keys off `event==="probe"` lines.
if not o.fileOpen: return
o.f.write("{\"event\":\"probe\",\"tick\":" & $tick &
",\"kind\":\"" & kind & "\",\"gate\":\"" & gateState &
"\",\"entropyBefore\":" & $entropyBefore &
",\"entropyAfter\":" & $entropyAfter &
",\"turnRate\":" & $turnRate &
",\"targetSpeed\":" & $targetSpeed & "}\n")
flushFile(o.f)
proc writeTick*(o: Observer, tick: int) =
## One telemetry line per tick. Called after `go()`, so a scan dispatched by
## this tick is already folded in.
## this tick is already folded in. Also decays the enemy gun-heat estimate.
if o.enemyHeat > 0.0: o.enemyHeat = max(0.0, o.enemyHeat - 1.0)
if not o.fileOpen: return
let scanned = o.scanTick == tick
var line = "{\"tick\":" & $tick & ",\"scan\":" & $scanned
@@ -0,0 +1,259 @@
## CHIMERA probe scheduler — active causal probing (spec §9, milestone M5).
##
## One probe per ~25 ticks (range 20–30), survival-gated, camouflaged as ordinary
## movement noise, and selected by **expected posterior-entropy reduction** over a
## small set of candidate actions (sudden stop, reversal, speed modulation,
## direction flip). The counterfactual engine is `twinsim.rollout`: for each
## candidate we roll each of the top-K kernels forward under OUR candidate action
## and measure how far the kernels' predicted enemy reactions separate. The
## candidate that separates them most removes the most posterior entropy.
##
## Decision 2 (spec §9): probes MAY cost score. The budget is a cost ledger; the
## survival gate is what keeps the spend bounded — a probe that would get us shot
## is never issued.
##
## This module is pure and deterministic: no I/O, no clock, no RNG. Everything
## derives from the ReplayTick posterior and the ProbeContext, so reruns are
## byte-identical (pinned by tests/test_probes.nim).
##
## Behaviour kill switch: compile with `-d:chimeraNoProbes` and the bot never
## calls this scheduler (see ChimeraBot.nim), so the command path is byte-identical
## to the M1 exact-copy baseline.
import std/[math, algorithm]
import ./physics, ./dsl, ./twinsim
const
ProbesEnabled* = not defined(chimeraNoProbes)
## Compile-time kill switch. `-d:chimeraNoProbes` removes the probe advisory
## from the bot entirely (G6 ablation OFF arm; command path == M1 baseline).
DefaultInterval* = 25 ## nominal probe cadence, ticks (spec: 20–30)
MinInterval* = 20
MaxInterval* = 30
ProbeHorizon* = 5 ## ticks of enemy reaction we predict (matches G5)
TopKernels* = 3 ## hypotheses whose separation drives selection
LowEnergy* = 25.0 ## "our energy is low" gate threshold
WallMargin* = 25.0 ## "wall-pinned" band from any wall
HeatHot* = 0.5 ## "their gunHeat is (near) zero"
AimTol* = 30.0 ## body-heading proxy cone for "aimed at us"
ProbeSigma* = 6.0 ## likelihood width (units) when scoring separation
RoundSoftLimit* = 2000 ## assumed round length for the "nearly over" gate
type
ProbeKind* = enum
## Enum order is the deterministic tie-break (earlier wins).
pkSuddenStop, pkReversal, pkSpeedModulation, pkDirectionFlip
ProbeCandidate* = object
kind*: ProbeKind
turnRate*: float64
targetSpeed*: float64
GateState* = object
allow*: bool
reason*: string
ProbeContext* = object
## Everything the gate needs, all observable / estimated.
tick*: int
ourEnergy*: float64
ownX*, ownY*, ownSpeed*: float64
arenaW*, arenaH*: float64
enemyX*, enemyY*: float64
enemyGunHeat*: float64 ## from the ledger's fire channel (+ decay)
enemyAimedAtUs*: bool ## body-heading proxy; gun aim is unobservable
roundLimit*: int ## 0 disables the round-end gate
ProbeDecision* = object
trigger*: bool ## the budget fired this tick
candidate*: ProbeCandidate
gate*: GateState
entropyBefore*: float64
entropyAfter*: float64 ## expected, after the most informative probe
ProbeScheduler* = object
kernels*: seq[Kernel]
ticksSinceProbe*: int
interval*: int
probes*: int ## executed (allowed) probe count
# ── construction ─────────────────────────────────────────────────────────────
proc initProbeScheduler*(kernels: seq[Kernel],
interval = DefaultInterval): ProbeScheduler =
result.kernels = kernels
result.interval = clamp(interval, MinInterval, MaxInterval)
# ── survival gate (spec §9) ──────────────────────────────────────────────────
proc aimedAtUs*(ownX, ownY, enemyX, enemyY, enemyDir: float64,
tol = AimTol): bool =
## True when the enemy's BODY heading points within `tol` of us. Gun aim is not
## observable, so body heading is the proxy (guns that ride the body are the
## common case); this makes the gate conservative, never trigger-happy.
abs(wrap180(bearingTo(enemyX, enemyY, ownX, ownY) - enemyDir)) <= tol
proc survivalGate*(ctx: ProbeContext): GateState =
## Deny order is the spec's order, so the reason string is deterministic.
if ctx.ourEnergy < LowEnergy:
return GateState(allow: false, reason: "energy")
if ctx.enemyAimedAtUs and ctx.enemyGunHeat <= HeatHot:
return GateState(allow: false, reason: "enemy-hot-aimed")
if ctx.ownX < WallMargin or ctx.ownX > ctx.arenaW - WallMargin or
ctx.ownY < WallMargin or ctx.ownY > ctx.arenaH - WallMargin:
return GateState(allow: false, reason: "wall-pinned")
if ctx.roundLimit > 0 and ctx.roundLimit - ctx.tick < 2 * MaxInterval:
return GateState(allow: false, reason: "round-end")
GateState(allow: true, reason: "ok")
# ── candidates + camouflage ──────────────────────────────────────────────────
proc candidates*(ctx: ProbeContext): seq[ProbeCandidate] =
## Four plausible body actions. Magnitudes are deliberately modest so a probe
## reads as ordinary movement noise, not as a tell.
let cap = maxTurnRate(ctx.ownSpeed)
var rev = -ctx.ownSpeed
if abs(rev) < 1.0: rev = -3.0
rev = clamp(rev, -4.0, 4.0)
@[
ProbeCandidate(kind: pkSuddenStop, turnRate: 0.0, targetSpeed: 0.0),
ProbeCandidate(kind: pkReversal, turnRate: 0.0, targetSpeed: rev),
ProbeCandidate(kind: pkSpeedModulation, turnRate: 0.0,
targetSpeed: clamp(ctx.ownSpeed + 2.0,
MaxBackwardSpeed, MaxForwardSpeed)),
ProbeCandidate(kind: pkDirectionFlip, turnRate: min(4.0, cap),
targetSpeed: ctx.ownSpeed),
]
proc camouflage*(c: ProbeCandidate, ctx: ProbeContext): ProbeCandidate =
## Clamp a candidate into the physics envelope: an unachievable command would
## be both implausible and mispredicted by the twin's own rollout.
result.kind = c.kind
result.turnRate = clamp(c.turnRate, -maxTurnRate(ctx.ownSpeed),
maxTurnRate(ctx.ownSpeed))
result.targetSpeed = clamp(c.targetSpeed, MaxBackwardSpeed, MaxForwardSpeed)
proc plausible*(c: ProbeCandidate, ctx: ProbeContext): bool =
## Tests-only sanity predicate: camouflage output is always plausible.
abs(c.turnRate) <= maxTurnRate(ctx.ownSpeed) + 1e-9 and
c.targetSpeed >= MaxBackwardSpeed - 1e-9 and
c.targetSpeed <= MaxForwardSpeed + 1e-9
# ── entropy / information gain ───────────────────────────────────────────────
proc entropyOf*(w: openArray[float64]): float64 =
## Shannon entropy (nats) of a non-negative vector, normalized internally.
var s = 0.0
for x in w: s += x
if s <= 0.0: return 0.0
for x in w:
let p = x / s
if p > 0.0: result -= p * ln(p)
proc topIndices*(weights: openArray[float64], k: int): seq[int] =
## Indices of the k largest weights; ties broken by ascending index.
let w = @weights
var idx = newSeq[int](w.len)
for i in 0 ..< idx.len: idx[i] = i
idx.sort(proc(a, b: int): int =
let c = cmp(w[b], w[a])
if c != 0: c else: cmp(a, b))
for i in 0 ..< min(k, idx.len): result.add idx[i]
proc onehot(origin: ReplayTick, i: int): ReplayTick =
result = origin
result.weights = newSeq[float64](origin.weights.len)
result.weights[i] = 1.0
proc reactionFeature(kernels: seq[Kernel], origin: ReplayTick, idx: int,
cand: ProbeCandidate, horizon: int): seq[float64] =
## The enemy trajectory kernel `idx` predicts under OUR candidate action,
## flattened (x,y) per tick. This is the "reaction" the probe is choosing.
var plan = newSeq[PlanStep](horizon)
for h in 0 ..< horizon:
plan[h] = PlanStep(turnRate: cand.turnRate, targetSpeed: cand.targetSpeed)
let r = rollout(kernels, onehot(origin, idx), horizon, plan = plan)
for p in r.points:
result.add p.x
result.add p.y
proc expectedEntropyDrop*(kernels: seq[Kernel], origin: ReplayTick,
top: seq[int], cand: ProbeCandidate,
horizon = ProbeHorizon): float64 =
## Expected posterior-entropy reduction from issuing `cand`.
##
## Each top kernel j is treated as a possible truth: if j is true, the observed
## reaction is j's predicted trajectory, and the posterior after seeing it is
## `prior_i · N(feat_j | feat_i, σ)`. The expected drop is `Σ_j prior_j ·
## (H(prior) − H(post_j))`. Kernels that react differently to the same probe
## separate; kernels that react identically contribute nothing.
let k = top.len
if k == 0: return 0.0
var prior = newSeq[float64](k)
var s = 0.0
for j, idx in top:
prior[j] = max(0.0, origin.weights[idx])
s += prior[j]
if s <= 0.0: return 0.0
for j in 0 ..< k: prior[j] /= s
var feats = newSeq[seq[float64]](k)
for j, idx in top:
feats[j] = reactionFeature(kernels, origin, idx, cand, horizon)
let h0 = entropyOf(prior)
let twoSigma2 = 2.0 * ProbeSigma * ProbeSigma
var drop = 0.0
for j in 0 ..< k:
var post = newSeq[float64](k)
for i in 0 ..< k:
var d2 = 0.0
for m in 0 ..< feats[i].len:
let d = feats[i][m] - feats[j][m]
d2 += d * d
post[i] = prior[i] * exp(-d2 / twoSigma2)
drop += prior[j] * (h0 - entropyOf(post))
drop
# ── selection + budget ───────────────────────────────────────────────────────
proc chooseProbe*(kernels: seq[Kernel], origin: ReplayTick, ctx: ProbeContext,
horizon = ProbeHorizon): ProbeDecision =
## Pick the candidate with the largest expected entropy drop. Deterministic
## tie-break: earlier ProbeKind, then smaller action magnitude.
result.entropyBefore = entropyOf(origin.weights)
result.entropyAfter = result.entropyBefore
let top = topIndices(origin.weights, TopKernels)
var bestDrop = -Inf
var bestMag = Inf
var have = false
for cand in candidates(ctx):
let c = camouflage(cand, ctx)
let drop = expectedEntropyDrop(kernels, origin, top, c, horizon)
let mag = abs(c.turnRate) + abs(c.targetSpeed)
let better =
(not have) or drop > bestDrop + 1e-12 or
(abs(drop - bestDrop) <= 1e-12 and
(c.kind.ord < result.candidate.kind.ord or
(c.kind == result.candidate.kind and mag < bestMag)))
if better:
bestDrop = drop
bestMag = mag
result.candidate = c
have = true
if have: result.entropyAfter = result.entropyBefore - bestDrop
proc consider*(s: var ProbeScheduler, origin: ReplayTick,
ctx: ProbeContext): ProbeDecision =
## One tick of the scheduler. Increments the budget; once the interval has
## elapsed it always *triggers* (so the gate state is observable in telemetry),
## but the budget only resets when the gate ALLOWS the probe to be executed.
inc s.ticksSinceProbe
result.gate = survivalGate(ctx)
if s.ticksSinceProbe < s.interval:
return
result = chooseProbe(s.kernels, origin, ctx)
result.trigger = true
result.gate = survivalGate(ctx)
if result.gate.allow:
s.ticksSinceProbe = 0
inc s.probes