DevControlBot 1.2.0: TFIL survival movement + universal battle runner

Ported "the floor is lava" (TFIL) movement into DevControlBot as a
self-contained module, DevControlBot/modules/tfil.nim. It has no runtime
dependency on common_libs/: the port is a standalone implementation,
parity-verified against the common_libs original over 2000 differential
ticks with zero divergences. Do not re-introduce the dependency and do
not edit the original to match.

Debug graphics (per-tile lava heat, tracked bullets and their danger
corridors, enemy core/aura, reachable hull, committed tile) are OFF by
default and compile-time gated behind -d:tfilDebug; see README.md for
the plain `nim c` invocation, since nimble runBot does not forward
compile flags.

Wired into DevControlBot.nim: movement computed between commandRadar()
and go(), fire-event tracking wired up, staleness handling for scanned
enemies, and body colour set to BLACK at init (movement and radar both
claim colour now).

Also adds tools/test_runner, a shared battle-test runner usable by any
garage, with an Observer adversary for quick floor checks.
This commit is contained in:
2026-10-04 18:16:24 +02:00
parent de0dd50d6e
commit 67d185880d
17 changed files with 1666 additions and 25 deletions
+154
View File
@@ -0,0 +1,154 @@
# tools/test_runner — universal battle-test runner
One command for **every** garage in the repo. Lives under `tools/` because root
`AGENTS.md` defines it as *"generic tools valid for all bots (battle runners,
scripts, etc.)"* — there is no root `test/` folder and none is allowed.
It **builds on** `common_libs/test_framework` — it does not reimplement it:
| Need | Reused from |
|---|---|
| server lifecycle, compile, runner subprocess | `runBattle()` in `test_framework.nim` |
| offline log parsing | `parseServerOutput()` in `battle_result.nim` |
| adversaries | `common_libs/test_framework/adversaries/` + `adversaries/Observer/` |
Nothing in `common_libs/` is modified, moved or deleted.
---
## Usage
```sh
nim c --path:common_libs tools/test_runner/runner.nim
./tools/test_runner/runner --bot DevControlBot_garage --opponents GAUNTLET
./tools/test_runner/runner --bot X_garage --rounds 5 --json out.json
./tools/test_runner/runner --bot X_garage --offline captured.jsonl # no Java
./tools/test_runner/runner --bot X_garage --dry-run # matrix only
```
`--help` prints the full option list.
### Exit codes
| Code | Meaning |
|---|---|
| 0 | pass **or SKIP** (JARs absent) |
| 1 | test failure (a matchup below threshold) |
| 2 | harness error — `OSError` (bot compile failed), `IOError` (runner exited non-zero / bad setup), `TimeoutError` (server startup, compile, or runner timeout); each prints its own message |
### Env gating (SKIP, not failure)
Reads `TR_SERVER_JAR` (default: `DefaultServerJar` in `server_manager.nim`) and
`TR_BATTLE_RUNNER` (default: same path as `runner_process.nim`). If either file
is missing, the runner prints a SKIP banner and **exits 0**. This is the pattern
root `AGENTS.md` prescribes and that no garage implemented. `--server-jar` /
`--runner-jar` override the env explicitly so a driver can force a run.
---
## `.battletest.json` — per-garage overrides
Drop next to the bot dir:
```json
{ "rounds": 20, "opponents": ["../GotoTest_garage"] }
```
Garages can act as opponents: `--opponents <path>` takes any directory, and
`--bot` accepts a garage (`X_garage`) or a bot dir.
---
## Why `stage.nim` exists (do not "simplify" this away)
`tools/battle_runner/TestBattleRunner.java:51` derives each bot's identity JSON
filename **from the directory name**:
```java
var jsonPath = path.resolve(path.getFileName() + ".json");
```
So a bot in `DevControlBot_garage/` is looked up as `DevControlBot_garage.json`,
which does not exist. The result is a **ghost**: the battle runs, no error is
reported, and the bot simply never boots. Confirmed live in `/tmp/dcbv/stage`
— `stage/Observer/` works (dir name == stem), `stage/DbgBot/` does not.
`stageOne()` therefore builds `<tmp>/<Stem>/` containing `<Stem>` and
`<Stem>.json` and asserts `dirName == stem` plus both files existing, raising a
message naming the exact reason otherwise. If the bot dir is *already* named
after its stem (e.g. `DevControlBot_garage/DevControlBot/`), it is used in
place and not staged.
Adversaries that ship a `<Stem>.sh` launcher get a regenerated one in the staged
dir — the original execs `./out/<Stem>`, which a staged flat dir does not have.
---
## Report
One row per matchup: `opponent | score | rank | 1st | survivedRounds/rounds | status`.
**PRIMARY metric = `survivalCount`** (these bots are survival movers), then
`firstPlaces`, then `score`. A matchup fails when the survival rate is below
`--survival-threshold` (default `0.6`), when fewer rounds were recorded than
requested, or when the bot's name is **absent from `r.results`** — searching by
name returns a zero-initialised `BotResult` with no error, the trap called out
in the test-framework README.
### ⚠ SittingDuck is DEGENERATE in this harness
A matchup against `SittingDuck` reports **score 0 / survival 0 for both bots
regardless of play**. Observed live: `DevControlBot vs SittingDuck` →
`score 1 vs 0, survivalCount 0`. Therefore:
- `survivalCount` against SittingDuck is **NO-SIGNAL** and is shown as
`n/a(no-signal)`.
- Such a matchup is **never able to fail the run** — it is flagged
`NO-SIGNAL (not a gate)` and its score differential is reported for
information only. A 0-0 draw must not be reported as a regression.
- Use `OscillatorBot` / `Observer` for real survival signal.
---
## `adversaries/Observer`
Promoted from `/tmp/dcbv/observer`. It never fires, only spins its radar at
45°/tick, and:
- appends every scan to `scans.csv` (turn, id, name, x, y),
- appends the opponent position to `obs.csv` (turn, x, y),
- accumulates the Euclidean distance the **opponent** travels between
consecutive scans, written to `obs_result.txt` on round end.
That travelled distance is the metric that actually proves a bot MOVES — score
and survival counters do not. A prior run measured ~6600 units across the
1200×1200 arena.
Output paths are parameters, not the old hardcoded `/tmp/dcbv/*.csv`:
| Env | Default | File |
|---|---|---|
| `OBS_OUT_DIR` | process cwd | directory for `scans.csv`, `obs.csv` |
| `OBS_FILE` | `$OBS_OUT_DIR/obs_result.txt` | one-line result |
```sh
OBS_OUT_DIR=/tmp/obs ./tools/test_runner/runner \
--bot DevControlBot_garage --opponents tools/test_runner/adversaries/Observer
```
---
## Files
| File | Role |
|---|---|
| `runner.nim` | CLI entry (main), wiring only |
| `resolve.nim` | stem derivation, `.battletest.json`, env gating |
| `stage.nim` | staging dir builder + dir-name assertion |
| `suites.nim` | `baseline` / `all` / `GAUNTLET` opponent matrices |
| `report.nim` | table renderer, JSON output, exit-code policy |
| `adversaries/Observer/` | promoted measurement bot |
`stage.nim` and `suites.nim` are self-checking (`nim c -r` runs assertions on
the dir-name invariant and the matrix logic).
@@ -0,0 +1,9 @@
{
"name": "Observer",
"version": "1.0.0",
"authors": ["SirGarage test_runner"],
"description": "Radar-only measurement adversary: logs scans as CSV and accumulates opponent travel distance",
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
cd "$(dirname "$0")"
exec ./out/Observer 2>> "${OBS_OUT_DIR:-/tmp}/observer_stderr.log"
@@ -0,0 +1,2 @@
--path:"../../../.."
switch("outdir", "out")
@@ -0,0 +1,9 @@
{
"name": "Observer",
"version": "1.0.0",
"authors": ["SirGarage test_runner"],
"description": "Radar-only measurement adversary: logs scans as CSV and accumulates opponent travel distance",
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
@@ -0,0 +1,59 @@
## Observer — measurement adversary.
##
## Plays radar-only: spins its radar so it re-scans the opponent every tick,
## logs every scan as CSV and accumulates the Euclidean distance the OPPONENT
## travels between consecutive scans. That travelled distance is the metric that
## actually proves a bot MOVES (a prior run measured ~6600 units across the
## 1200x1200 arena); score and survival counters do not.
##
## Output location is a parameter, not a hardcoded /tmp path:
## OBS_OUT_DIR directory for scans.csv / obs.csv / obs_result.txt
## (default: the process working directory)
## OBS_FILE file for the one-line result (default: <OBS_OUT_DIR>/obs_result.txt)
import std/[os, math, strformat]
import robocode_tankroyale_botapi
type Observer = ref object of Bot
samples: int
dist: float
lastX, lastY: float
have: bool
proc appendLine(path, line: string) =
let f = open(path, fmAppend)
defer: f.close()
f.writeLine line
proc outDir(): string =
result = getEnv("OBS_OUT_DIR", getCurrentDir())
createDir(result)
method onScannedBot(bot: Observer, e: ScannedBotEvent) =
if e.scannedBotId == getMyId(): return # 2-bot battle: only the other bot matters
let d = outDir()
appendLine(d / "scans.csv",
&"{getTurn()} id={e.scannedBotId} name={getBotName(e.scannedBotId)} x={e.x} y={e.y}")
appendLine(d / "obs.csv", &"{getTurn()},{e.x},{e.y}")
inc bot.samples
if bot.have:
bot.dist += hypot(e.x - bot.lastX, e.y - bot.lastY)
bot.lastX = e.x; bot.lastY = e.y; bot.have = true
method onTick(bot: Observer, e: TickEventForBot) =
## Spin the radar so the opponent is re-scanned every tick — that cadence is
## what makes the accumulated travel distance meaningful.
setRadarTurnRate(45)
method onRoundEnded(bot: Observer, e: RoundEndedEventForBot) =
let d = outDir()
writeFile(getEnv("OBS_FILE", d / "obs_result.txt"),
&"OBS samples={bot.samples} dist={bot.dist:.3f}")
when isMainModule:
let jsonPath =
if paramCount() >= 1: paramStr(1)
else: currentSourcePath().parentDir / "Observer.json"
start(Observer(), jsonPath)
+127
View File
@@ -0,0 +1,127 @@
## Report rendering + exit-code policy.
##
## PRIMARY metric = survivalCount (these bots are survival movers), then
## firstPlaces, then score. SITTING-DUCK CAVEAT: survival vs SittingDuck is
## NO-SIGNAL (the harness reports 0/0 for both bots regardless of play), so it
## is flagged as such and never used for pass/fail.
import std/[strutils, json, sequtils, net] # net: TimeoutError
import ../../common_libs/test_framework/test_framework
var
survivalThreshold* = 0.6 ## CLI --survival-threshold
const
ExitOk* = 0 ## pass OR skip
ExitFail* = 1 ## a matchup failed its threshold
ExitHarness* = 2 ## OSError / IOError / TimeoutError — the harness itself broke
type
Matchup* = object
opponent*: string
myScore*, oppScore*: int
rank*: int
firstPlaces*, survivalCount*: int
survivedRounds*, rounds*: int
noSignal*: bool ## SittingDuck: survival column is meaningless
incomplete*: bool ## fewer rounds recorded than requested
missing*: bool ## bot name absent from r.results (zero-value trap)
passed*: bool
note*: string
proc buildMatchup*(r: BattleResult, myName, oppName: string, roundsWanted: int): Matchup =
result.opponent = oppName
result.rounds = r.rounds.len
result.incomplete = r.rounds.len < roundsWanted
var mine, theirs: BotResult
var foundMine = false
for b in r.results:
if b.name == myName: mine = b; foundMine = true
elif b.name == oppName: theirs = b
result.missing = not foundMine # zero-value BotResult trap guard
result.rank = mine.rank
result.firstPlaces = mine.firstPlaces
result.survivalCount = mine.survivalCount
result.myScore = mine.totalScore
result.oppScore = theirs.totalScore
for rd in r.rounds:
for br in rd.results:
if br.name == myName and br.survived: inc result.survivedRounds
result.noSignal = oppName == "SittingDuck"
if result.missing:
result.passed = false
result.note = "name '" & myName & "' absent from results — bot never booted?"
elif result.noSignal:
# Degenerate harness: both bots report ~0 regardless of play, so survival
# AND score are meaningless. Never fail on it — flag as no-signal only.
result.passed = true
result.note = "NO-SIGNAL vs SittingDuck (score " & $result.myScore &
" vs " & $result.oppScore & ") — informational, not a gate"
else:
let rate = if result.rounds == 0: 0.0
else: result.survivedRounds.float / result.rounds.float
result.passed = rate >= survivalThreshold and not result.incomplete
if result.incomplete:
result.note = "only " & $result.rounds & "/" & $roundsWanted & " rounds recorded"
else:
result.note = "survivalRate=" & formatFloat(rate, ffDecimal, 2)
proc pad(s: string, n: int): string =
if s.len >= n: s[0 ..< n] else: s & repeat(' ', n - s.len)
proc render*(m: seq[Matchup], myName: string): string =
var s = "\n== " & myName & " — battle-test report ==\n"
s.add pad("opponent", 20) & pad("score", 8) & pad("rank", 6) &
pad("1st", 6) & pad("surv", 16) & "status\n"
s.add repeat('-', 80) & "\n"
for x in m:
let survCol =
if x.noSignal: "n/a(no-signal)"
elif x.missing: "-"
else: $x.survivedRounds & "/" & $x.rounds
let status =
if x.missing: "FAIL (missing from results)"
elif x.noSignal: "NO-SIGNAL (not a gate)"
elif x.passed: "PASS"
else: "FAIL"
s.add pad(x.opponent, 20) & pad($x.myScore, 8) & pad($x.rank, 6) &
pad($x.firstPlaces, 6) & pad(survCol, 16) & status
if x.note.len > 0: s.add " (" & x.note & ")"
s.add "\n"
let failed = m.filterIt(not it.passed).len
s.add repeat('-', 80) & "\n"
s.add (if failed == 0: "ALL MATCHUPS PASSED\n" else: $failed & " MATCHUP(S) FAILED\n")
result = s
proc toJson*(m: seq[Matchup], myName: string): string =
var root = %*{"bot": myName, "survivalThreshold": survivalThreshold, "matchups": newJArray()}
for x in m:
root["matchups"].add %*{
"opponent": x.opponent, "score": x.myScore, "oppScore": x.oppScore,
"rank": x.rank, "firstPlaces": x.firstPlaces,
"survivalCount": x.survivalCount,
"survivedRounds": x.survivedRounds, "rounds": x.rounds,
"noSignal": x.noSignal, "incomplete": x.incomplete,
"missing": x.missing, "passed": x.passed, "note": x.note}
result = $root
proc exitCode*(m: seq[Matchup]): int =
if m.anyIt(not it.passed): ExitFail else: ExitOk
## Map framework exceptions to exit 2 with a message that says what actually
## broke (see test_framework README: OSError = compile, IOError = runner exit,
## TimeoutError = server startup / compile / runner timeout).
proc harnessExit*(e: ref CatchableError): int =
if e of OSError:
stderr.writeLine "HARNESS ERROR [bot compile failed]: " & e.msg
elif e of IOError:
stderr.writeLine "HARNESS ERROR [battle runner exited non-zero / bad setup]: " & e.msg
elif e of TimeoutError:
stderr.writeLine "HARNESS ERROR [timeout: server startup, bot compile, or battle runner]: " & e.msg
else:
stderr.writeLine "HARNESS ERROR [unexpected]: " & e.msg
ExitHarness
+95
View File
@@ -0,0 +1,95 @@
## Resolution + env gating for the universal battle-test runner.
##
## Deliberately thin: everything that already exists in common_libs/test_framework
## (compileBots) is imported, not reimplemented. We only add:
## - stem derivation (strip _garage, see bot_compiler.nim:9)
## - `.battletest.json` per-garage overrides
## - the SKIP-when-no-jars policy
import std/[os, strutils, json]
import ../../common_libs/test_framework/server_manager ## DefaultServerJar (import only, never modified)
type
Overrides* = object
rounds*: int ## 0 = not overridden
opponents*: seq[string] ## empty = not overridden
ResolvedBot* = object
dir*: string ## directory to hand to the battle runner (or stage)
stem*: string ## bot name, _garage stripped
rounds*: int ## effective rounds for this bot (0 = global)
opponents*: seq[string] ## per-garage override, empty = global matrix
const GarageSuffix* = "_garage"
const OverrideFile* = ".battletest.json"
proc stemOf*(path: string): string =
## Mirrors bot_compiler.nim:9 — last path component minus _garage.
result = lastPathPart(absolutePath(path))
if result.endsWith(GarageSuffix):
result = result[0 ..< result.len - GarageSuffix.len]
proc innerBotDir*(path: string): string =
## Some garages keep the actual bot in a nested `<Stem>/` subdir
## (e.g. DevControlBot_garage/DevControlBot/). Descend into it when the
## given dir has no src/ and no binary but has a same-named subdir.
let abs = absolutePath(path)
let stem = stemOf(abs)
if not dirExists(abs / "src") and not fileExists(abs / stem) and
dirExists(abs / stem):
return abs / stem
abs
proc readOverrides*(path: string): Overrides =
let f = absolutePath(path) / OverrideFile
if not fileExists(f): return
try:
let n = parseJson(readFile(f))
if n.hasKey("rounds"): result.rounds = n["rounds"].getInt()
if n.hasKey("opponents"):
for o in n["opponents"].getElems(): result.opponents.add o.getStr()
except JsonParsingError as e:
raise newException(ValueError, f & " is not valid JSON: " & e.msg)
proc resolveBot*(path: string): ResolvedBot =
## path may be a garage (`X_garage`) or a bot dir. Returns the dir the
## runner should use plus the bot's stem and any .battletest.json overrides.
if not dirExists(path):
raise newException(IOError, "bot path is not a directory: " & path)
result.dir = innerBotDir(path)
result.stem = stemOf(result.dir)
let ov = readOverrides(result.dir)
result.rounds = ov.rounds
result.opponents = ov.opponents
# --- env gating -------------------------------------------------------------
const
RepoRoot* = currentSourcePath().parentDir.parentDir.parentDir
AdversaryRoot* = currentSourcePath().parentDir / "adversaries"
const DefaultRunnerJarHint* =
"/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar"
type
Gate* = object
ok*: bool ## false => SKIP (quit 0), not a failure
reason*: string
serverJar*: string
runnerJar*: string
proc gate*(serverOverride = "", runnerOverride = ""): Gate =
## SKIP (exit 0) when the JARs are missing — root AGENTS.md prescribes this
## and no garage implements it yet. Explicit overrides bypass the env.
result.serverJar =
if serverOverride.len > 0: serverOverride
else: getEnv("TR_SERVER_JAR", DefaultServerJar) ## same default as server_manager.nim
result.runnerJar =
if runnerOverride.len > 0: runnerOverride
else: getEnv("TR_BATTLE_RUNNER", DefaultRunnerJarHint)
if not fileExists(result.serverJar):
result.reason = "TR_SERVER_JAR does not exist: " & result.serverJar
elif not fileExists(result.runnerJar):
result.reason = "TR_BATTLE_RUNNER does not exist: " & result.runnerJar
else:
result.ok = true
+170
View File
@@ -0,0 +1,170 @@
## Universal battle-test runner — CLI entry point.
##
## One command for every garage in the repo:
## nim c -r --path:../../common_libs tools/test_runner/runner.nim -- --bot X_garage
##
## Exit codes: 0 = pass or SKIP, 1 = test failure, 2 = harness error.
import std/[os, strutils, parseopt, strformat]
import ../../common_libs/test_framework/test_framework
import ../../common_libs/test_framework/battle_result # parseServerOutput (offline mode)
import ./resolve, ./stage, ./suites, ./report
type Cfg = object
bots: seq[string]
oppSuite: string
rounds: int
timeout: int
jsonOut: string
offline: string
dryRun: bool
serverJar, runnerJar: string
const Usage = """
Universal battle-test runner (tools/test_runner)
Usage:
runner --bot <garageOrDir> [--bot ...] [options]
Options:
--bot <path> Bot garage (X_garage) or bot dir. Repeatable.
--opponents <set> baseline | all | GAUNTLET | <path> (default: baseline)
--rounds <N> Rounds per matchup (default: 10)
--timeout <MS> Battle runner timeout (default: 120000)
--survival-threshold <f> Fail a matchup below this survival rate (default: 0.6)
--json <out.json> Write the report as JSON
--offline <file.jsonl> Parse a captured battle log, no Java, no server
--server-jar <path> Override TR_SERVER_JAR (bypasses the env gate)
--runner-jar <path> Override TR_BATTLE_RUNNER (bypasses the env gate)
--dry-run Resolve and print the matrix, run nothing
-h, --help This text
Environment: TR_SERVER_JAR, TR_BATTLE_RUNNER (see common_libs/test_framework/README.md).
If the JARs are absent the runner prints a SKIP banner and exits 0 — that is a
skip, not a failure.
Exit codes: 0 pass|skip, 1 test failure, 2 harness error.
Caveat: survival vs SittingDuck is NO-SIGNAL (both bots score 0/survive 0 in this
harness regardless of play). It is flagged as such and judged on score
differential only. Use OscillatorBot/Observer for real survival signal.
"""
proc parseArgs(): Cfg =
result = Cfg(oppSuite: Baseline, rounds: 10, timeout: 120000)
var p = initOptParser(commandLineParams())
# ponytail: parseopt does not bind values to options — the value arrives as
# the NEXT cmdArgument, so we latch the key and fill it on the way by.
var pending = ""
for kind, key, val in p.getopt():
case kind
of cmdEnd: discard
of cmdArgument:
if pending.len > 0:
case pending
of "bot": result.bots.add key
of "opponents": result.oppSuite = key
of "rounds": result.rounds = parseInt(key)
of "timeout": result.timeout = parseInt(key)
of "survival-threshold": survivalThreshold = parseFloat(key)
of "json": result.jsonOut = key
of "offline": result.offline = key
of "server-jar": result.serverJar = key
of "runner-jar": result.runnerJar = key
else: stderr.writeLine "option --" & pending & " needs a value\n" & Usage; quit(ExitHarness)
pending = ""
elif key.len > 0 and key[0] != '-':
result.bots.add key
of cmdLongOption, cmdShortOption:
if key == "h" or key == "help":
echo Usage
quit(ExitOk)
elif key == "dry-run":
result.dryRun = true
elif key in ["bot", "opponents", "rounds", "timeout", "survival-threshold",
"json", "offline", "server-jar", "runner-jar"]:
pending = key
else:
stderr.writeLine "unknown option: --" & key & "\n" & Usage
quit(ExitHarness)
proc runOffline(cfg: Cfg, bots: seq[ResolvedBot]): int =
## No Java, no server: parse the captured JSON-lines log.
if not fileExists(cfg.offline):
stderr.writeLine "offline log not found: " & cfg.offline
return ExitHarness
let r = parseServerOutput(readFile(cfg.offline))
var m: seq[Matchup]
for b in bots:
var opponent = ""
for n in r.bots:
if n != b.stem: opponent = n
if opponent.len == 0:
stderr.writeLine "offline log has no opponent for " & b.stem
return ExitHarness
m.add buildMatchup(r, b.stem, opponent, cfg.rounds)
echo render(m, bots[0].stem)
if cfg.jsonOut.len > 0: writeFile(cfg.jsonOut, toJson(m, bots[0].stem))
exitCode(m)
proc main(): int =
let cfg = parseArgs()
if cfg.bots.len == 0:
stderr.writeLine "--bot is required\n" & Usage
return ExitHarness
var bots: seq[ResolvedBot]
for b in cfg.bots: bots.add resolveBot(b)
if cfg.offline.len > 0:
return runOffline(cfg, bots)
let g = gate(cfg.serverJar, cfg.runnerJar)
if not g.ok:
echo "========================================================"
echo " SKIP — integration battle tests not run"
echo " reason: ", g.reason
echo " set TR_SERVER_JAR / TR_BATTLE_RUNNER (or pass --server-jar"
echo " / --runner-jar) to enable. See common_libs/test_framework/README.md"
echo "========================================================"
return ExitOk
for b in bots: echo "bot: ", b.dir, " stem=", b.stem
let all = suite(cfg.oppSuite)
echo "opponent suite '", all.name, "':"
var matrix: seq[tuple[bot: ResolvedBot, opp: string]]
for b in bots:
var opps = all.opponents
if b.opponents.len > 0: opps = b.opponents # .battletest.json override
for o in opps:
echo " ", b.stem, " vs ", lastPathPart(o)
matrix.add (b, o)
if cfg.dryRun:
echo "\n--dry-run: ", matrix.len, " matchup(s), nothing executed."
return ExitOk
let stageRoot = getTempDir() / "test_runner_stage"
var m: seq[Matchup]
try:
for (b, oppPath) in matrix:
let o = resolveBot(oppPath)
let rounds = if b.rounds > 0: b.rounds else: cfg.rounds
let stMine = stageOne(stageRoot, b.dir, b.stem)
let stOpp = stageOne(stageRoot, o.dir, o.stem)
echo &"\n--- {b.stem} vs {o.stem} ({rounds} rounds) ---"
let r = runBattle(@[stMine.dir, stOpp.dir], rounds = rounds,
timeout = cfg.timeout)
m.add buildMatchup(r, b.stem, o.stem, rounds)
except CatchableError as e:
return harnessExit(e)
let primary = bots[0].stem
echo render(m, primary)
if cfg.jsonOut.len > 0: writeFile(cfg.jsonOut, toJson(m, primary))
exitCode(m)
when isMainModule:
quit(main())
+73
View File
@@ -0,0 +1,73 @@
## Staging builder.
##
## WHY THIS EXISTS (important, do not "simplify" it away):
## TestBattleRunner.java:51 derives each bot's identity JSON filename from the
## DIRECTORY NAME:
## var jsonPath = path.resolve(path.getFileName() + ".json");
## So a staging dir named anything other than the bot stem silently produces a
## missing-JSON bot. It does NOT error — the bot simply never boots and you get
## a ghost: a participant in the scoreboard that never fights. Confirmed live in
## /tmp/dcbv/stage (Observer/ = working, DbgBot/ = broken).
## Therefore: dirName == stem, always, and we assert it.
import std/[os, strformat]
import ../../common_libs/test_framework/bot_compiler
type
StagedBot* = object
dir*: string ## directory to hand to the battle runner
stem*: string
staged*: bool ## false => original dir already had the right name
proc locateJson*(botDir, stem: string): string =
## The .json can sit beside the binary or in src/ (adversaries ship both).
for c in [botDir / stem & ".json", botDir / "src" / stem & ".json"]:
if fileExists(c): return c
""
proc stageOne*(stageRoot, botDir, stem: string): StagedBot =
let dirName = lastPathPart(botDir)
if dirName == stem:
return StagedBot(dir: botDir, stem: stem, staged: false)
let bins = compileBots(@[botDir]) # raises OSError on compile failure
if bins.len != 1:
raise newException(IOError,
fmt"expected exactly 1 binary for {botDir}, got {bins.len}")
let bin = bins[0]
let js = locateJson(botDir, stem)
if not fileExists(bin):
raise newException(IOError, fmt"compiled binary missing: {bin}")
if js.len == 0:
raise newException(IOError,
fmt"identity JSON not found for '{stem}' in {botDir} " &
fmt"(looked for {stem}.json and src/{stem}.json)")
result.dir = stageRoot / stem
result.stem = stem
result.staged = true
createDir(result.dir)
copyFile(bin, result.dir / stem)
copyFile(js, result.dir / stem & ".json")
let sh = result.dir / stem & ".sh"
if fileExists(botDir / stem & ".sh"):
# Write, don't copy: the original launcher execs ./out/<stem>, which does
# not exist in a staged dir where the binary sits at the top level.
writeFile(sh, "#!/bin/sh\ncd \"$(dirname \"$0\")\"\nexec ./" & stem & "\n")
setFilePermissions(sh, {fpUserExec, fpUserRead, fpUserWrite})
# Assert the invariant that keeps ghosts from happening.
if lastPathPart(result.dir) != stem:
raise newException(IOError,
fmt"staging dir name '{lastPathPart(result.dir)}' != stem '{stem}'")
if not fileExists(result.dir / stem):
raise newException(IOError, fmt"staged binary missing: {result.dir / stem}")
if not fileExists(result.dir / stem & ".json"):
raise newException(IOError, fmt"staged JSON missing: {result.dir / stem}.json")
when isMainModule:
## Self-check: the dir-name invariant is the whole point of this module.
let tmp = getTempDir() / "stage_selftest" / "MyBot"
doAssert lastPathPart(tmp) == "MyBot"
doAssert lastPathPart(tmp / "x") != "MyBot"
echo "stage.nim self-check passed"
+62
View File
@@ -0,0 +1,62 @@
## Opponent matrices. Garages may also act as opponents (any --bot dir can be
## pulled in via `.battletest.json`), so "all" = shared adversaries + `extra`.
import std/os
import ./resolve
type
Suite* = object
name*: string
opponents*: seq[string] ## directories, not stems
const
Baseline* = "baseline"
All* = "all"
Gauntlet* = "GAUNTLET"
SharedAdversaries* = RepoRoot / "common_libs" / "test_framework" / "adversaries"
proc adversaryDirs*(): seq[string] =
## Every shared adversary: the ones in common_libs/test_framework/adversaries
## plus the runner's own adversaries/ (Observer). Lazily computed, so adding
## an adversary is just a new directory — no code change.
for root in [SharedAdversaries, AdversaryRoot]:
if not dirExists(root): continue
for kind, p in walkDir(root):
if kind == pcDir:
let stem = lastPathPart(p)
if fileExists(p / (stem & ".nim")) or fileExists(p / "src" / (stem & ".nim")):
result.add p
proc suite*(name: string, extra: openArray[string] = []): Suite =
## baseline = two cheap reference bots; all = every shared adversary;
## GAUNTLET = baseline ∪ all ∪ any extra opponents named in --opponents.
var dirs: seq[string]
if name == Baseline:
dirs = @[SharedAdversaries / "SittingDuck", SharedAdversaries / "OscillatorBot"]
elif name == All or name == Gauntlet:
dirs = adversaryDirs()
if name == Gauntlet:
dirs.add SharedAdversaries / "SittingDuck"
dirs.add SharedAdversaries / "OscillatorBot"
var uniq: seq[string]
for d in dirs:
if d notin uniq: uniq.add d
dirs = uniq
else:
dirs = @[name] # treated as a path (a garage acting as opponent)
for e in extra:
if e notin dirs: dirs.add e
result = Suite(name: name, opponents: dirs)
proc isDegenerate*(opponentStem: string): bool =
## CAVEAT: a SittingDuck matchup is DEGENERATE in this harness — both bots
## report score 0 / survival 0 regardless of play. Survival vs SittingDuck is
## NO-SIGNAL (its score differential is still valid). See README.
opponentStem == "SittingDuck"
when isMainModule:
doAssert suite(Baseline).opponents.len == 2
doAssert isDegenerate("SittingDuck")
doAssert not isDegenerate("OscillatorBot")
echo "suites.nim self-check passed: ", adversaryDirs().len, " adversaries"