8. AI opponents (optional, server/crates/ai)
Computer opponents are opt-in: a room has none until its host adds one in the lobby. Hosts can add, remove, move, and select AI seats only during the lobby phase. AI seats count toward the normal four-player cap and toward any lower active-seat cap imposed by the selected map.
AI players are seated after human players, use colors from the tail of PLAYER_PALETTE, persist through rematches, and are removed only when the room empties of humans. They are always ready. When several seats use the same profile, their lobby names receive deterministic numeric suffixes.
Canonical profiles
The player-facing lobby supports five AI profile IDs:
- ai_2_3 — AI 2.3, a weighted composition: equal thirds Rush AI, Pressure AI, and Jeff’s AI (one-third probability each).
- jeffs_ai_v1_1 — Jeff’s AI (V1.1), the default opponent: Jeff’s AI V1.0 plus the V1.1 changes, played with the feature set fixed in
JEFF_V1_1_FEATURES(profiles.rs). On a symmetric map it decides in one frame, as if on the start it won more from (live/mirror.rs), so both starts play the same way. - rush_ai — Rush AI, an immediate infantry attack with forward construction.
- pressure_ai — Pressure AI, the AI 2.1 economy and technology with independent forward staging and a value-based response.
- eco_ai — Eco AI, an expanding economy using the SDK cut/garrison planner, Machine Gunner/Panzerfaust infantry, Command Car-supported Tanks, and capacity-triggered staged assaults.
ai_turtle is deprecated and internal-only. It remains registered for offline self-play,
diagnostics, and observer-only AI sessions, but it is not exposed in the lobby and the server
replaces it with jeffs_ai_v1_1 whenever a room has an active human player. The replacement is enforced
again at the authoritative match-start seam, so stale or crafted clients cannot put Turtle into a
human match.
The convenience inputs ai and default resolve to jeffs_ai_v1_1. The lobby exposes AI 2.3, Jeff’s AI, Rush AI, Pressure AI, Eco AI, and Jeffs Cult. Jeff’s AI V1.0 (jeffs_ai, the server-authoritative port of the locally evaluated V3 champion policy and the baseline V1.1 is measured against) is internal-only like AI 2.1. AI 2.1 remains a concrete internal profile (ai_2_1) for offline tools and
observer-only sessions, but is hidden and rejected as a direct selection in human player lobbies.
Unsupported or internal IDs fall back to Jeff’s AI when adding a seat and are ignored when changing a
seat; stale internal seats are normalized to Jeff’s AI when humans join and again at match start.
jeffs_cult — Jeffs Cult, the Cultivator AI (server/crates/ai/src/jeffs_cult/), is a
typed strategy locked to the Cultivators faction. Players can pick it in the lobby; it is not in
the random pool. It copies
soupman’s Cultivator games. Opening (build.rs): the Serf builds a Portal at once, the Portal
trains Novices up to three, the Serf builds the Three Dao Pavilion once the Portal is up, and the
first Dao is researched the moment the Pavilion finishes; the Technique Library follows the first Dao, and Shield is researched there after the first two Magic Adepts (or by 2:00). Only the Magic-first branch exists
(build.rs, build/production.rs): Magic Adepts on repeat, the natural Nexus after three Adepts
(production pauses to save for it, and stays paused while the Serf walks there, because a build
pays on arrival), a third Nexus 90 s after the natural and one more every 2 minutes up to eight while
the army can hold it (no armed enemy near our buildings, two Adepts per base, and at least the
enemy power seen), and enough Portals to
spend the extractors’ income. Dao of War comes when the first enemy Tank is seen (or by 3:45);
then the War Adept share follows the Tanks seen in the last minute (25% to 70%), and War Adepts
throw their swords at Tanks first (war.rs) once Throw Sword is researched (Throw Sword and Charge follow Dao of War when money is spare). Spare Steel after 5:00 buys a Tournament Grounds and
a Novice Portal; every Novice walks into the Grounds, four for one random Adept. Spare Oil after
6:00 buys a Shop, then Vitality and Armor for the strongest Adepts. A second Serf comes at 5:00.
Saving for a Dao or the Shield research stops every Portal; saving for a Nexus stops them all only for the first
expansion, half for later ones, gives up after 45 s (up to 90 s while the bank would cover it
within 30 s) and retries after 30 s, and lets Portals run
while the Serf walks to a paid site as long as the bank still covers it. Army
(army.rs, intel.rs): it waits at home on Novices, attacks once four Adepts are out, and after
the first Tank only with a 1.3x edge over the enemy army seen in the last minute (or 200 supply);
it reinforces the main body, retreats from fights the enemy wins by half again or from two Tanks
without War Adepts, and comes home for a real base attack (any 2 power at the main Nexus). From
three Nexuses on, each Nexus away from the staging point keeps three guards of the army’s Adept
mix (twice that at the guarded Nexus nearest the enemy, at most 30% of the army); guards fight raids
they outnumber by 1.2x, fall back toward the army from bigger ones, and join every attack. Buildings
other than extractors keep three clear tiles around them, because Adepts need lanes three tiles
wide in the path grid, and a Novice whose walk into the Grounds stalls for 10 s is stopped instead
of re-sent. Micro (magic.rs): a Magic Adept casts
Shield only where it would prevent at least half of what a fully used Shield can (the
blockable fire on uncovered fighters, and on 3x3 or larger buildings it can centre on, for as long as
the Shield survives the full drain: a Tank’s cannon pierces Shields, its coaxial machine gun does not); fighters a healthy friendly Shield (60 HP, 1 s left) already holds do not
count, and a new Shield’s centre stays 3 tiles from every healthy one, so Shields are never
stacked (overlapping Shields add no armor; each hit drains only one). Vector Field goes on a clump
of three or more enemies with no own unit in or beside it, pushing away from the army; enemies in a trench are immune and do not count.
Every AI profile plays Kriegsia unless PROFILE_FACTION_LOCKS in
server/crates/ai/src/live/factions.rs locks it to another faction; only jeffs_cult is locked
(to cultivators).
rts_ai::live_profile_faction_id is the one answer for a profile’s faction. The lobby derives
each AI seat’s faction from its profile (validated as an AI-seat request) whenever it broadcasts
the lobby or starts a match, so the faction follows any profile change or internal-profile
replacement. Profile matchups (ai-matchup, ai-arena, the balance matrix and the 120 game test)
give each side its profile’s faction. A locked profile cannot be a composition member or in the
random pool, because those hosts fix the seat’s faction before picking a member; tests enforce
this, and that every lock names a live profile and a playable faction.
server/crates/ai/src/compositions.rs defines compositions as weighted lists of registered concrete
profiles. Add another member and its positive integer weight to extend a composition; nested
compositions are deliberately not supported. Each controller chooses one member on its first host
invocation, before worker reflexes or strategy initialization, and keeps it for the whole match.
Selection uses a separate RNG seeded by the host’s match seed and player ID, so controller order
and simulation RNG consumption cannot affect the choice. The normal and prepared host paths carry
that seed in AiThinkContext (and the synthetic fixture’s PlayerView). No seed is added to the
wire or strategy observation. Equal weights mean equal probability, not forced alternation.
The lobby/request identity stays AI 2.3. Controller diagnostics expose the selected concrete profile separately; mixed decision traces identify both the composition and member. Arena manifests record the weighted member list, and their fingerprints include member policy fingerprints and selector source. Explicit AI 2.1 and Rush requests preserve their existing behavior.
Internal observer launch URLs may still use both IDs. For example, a spectator can launch an AI 2.1 versus Turtle diagnostic match with:
/?rtsLaunch=match&rtsRoom=agent-ai-selfplay&rtsRole=spectator&rtsAi=1:ai_2_1&rtsAi=2:ai_turtle&rtsStart=1
Where it runs
rts-ai owns one AiController per AI player, while Game remains AI-free. The
CanonicalAiTickDriver is the one normal live/offline profile host: before game.tick() it chooses
the host-requested normal or starting-primary-base alive policy, captures each controller’s public
start payload, fog-filtered snapshot_for(player), and worker-retreat input in stable controller
order, collects every result before enqueueing any, then enqueues ordinary SimCommands in that
same order. The driver does not tick the game or own outcome, networking, replay, scoring, or
artifact policy. AI actions therefore go through the same validation, costs, supply, placement,
and fog rules as human commands; the AI has no simulation authority of its own.
Outbound attacks use public enemy start tiles. Direct attack targets are limited to currently visible entities. The worker direct-hit retreat reflex projects recent own-worker damage into ordinary Move commands without reading private simulation state.
rts-ai may depend on the public simulation API, rules, protocol, and contract crates. It must not import the server shell, lobby internals, transport layer, or private simulation modules. New AI observations must be added as a public fog-respecting Game or snapshot surface.
Typed authoring SDK
rts_ai::sdk is the supported Rust authoring seam for custom strategies. An AiController built
with AiController::with_strategy(player, Box<dyn AiStrategy>) runs in the same canonical driver
as profile controllers. The object-safe AiStrategy: Send lifecycle calls initialize exactly
once immediately before the first step; both calls occur only on the player’s normal nine-tick,
staggered decision cadence. Strategies have no required constructor, async lifecycle, associated
types, checkpoint contract, or direct simulation access.
AiFrame is an owned, read-only normalization of public start data, the player’s
snapshot_for(player) result, the host-selected alive-player set, and controller-inferred
submitted-build bookkeeping. The frame adapter is the only production path that parses raw
start/snapshot DTOs into strategy-visible kind, state, production, upgrade, terrain, resource, and
memory facts. Its collections use stable id ordering; completed upgrades and submitted builds are
additionally sorted and deduplicated.
AiFrame::own_losses() exposes cumulative own unit/building deaths; observed_enemy_losses()
returns the same typed AiLosses per enemy player id for witnessed deaths only. Each summary has
per-kind unit/building maps, total-count helpers, and nominal Steel/Oil value, matching the Losses
tab. Missing enemy entries mean zero observed deaths, not zero actual deaths. The canonical host
passes Game::known_losses_for(player) in AiThinkContext::known_losses; prepared hosts must do
likewise. Simulation death processing accumulates witnessed losses every tick using the existing
Death-event visibility gate (team vision, smoke, concealment, firing reveals). Counts survive
checkpoints and do not depend on AI decision cadence or prior entity sightings. Disappearance,
cancellation, administrative elimination, and depleted neutral resources do not count.
Active production identifies either its typed unit kind or its typed research upgrade when one is
present in the recipient snapshot.
Entity records carry facing, the hull heading in radians (atan2(dy, dx) in world pixels, y down)
that the recipient snapshot already shows, or None for kinds without movement facing.
Entity records retain the public occupied_trench_id from that same recipient snapshot so
strategies can recognize active entrenchment without inspecting enemy research or private state.
Owned entities, currently visible allies, currently visible enemies, and remembered contacts are
separate collections. A remembered contact is stale last-seen knowledge, never a current target.
AiFrame::lifetime_mined() exposes only the controller’s own authoritative cumulative Steel/Oil
collection, excluding initial money/refunds. The canonical host gets it through
Game::lifetime_mined_for(player) and prepared hosts pass AiThinkContext::own_lifetime_mined.
The value is unchanged by Jeff’s coordinate mirror. Automatic Pump Jack deaths keep their counts
but contribute zero resource value, matching observer analysis.
Static resource locations are public, but AiResourceAmount::Unknown is retained until a
recipient-scoped resource delta or visible node reveals a quantity. The public frame never exposes
the historical synthetic remaining = 1 value or the policy-derived free_for_combat flag.
Opponent production queue length/payment state and non-owned construction activity are likewise
None, rather than false or zero, because those details are redacted by the player snapshot.
Likewise, AiBuildObservation means only that this controller inferred an outstanding submitted
build; it is not an accepted, legal, or active-build receipt.
Cultivator fighters (Novices, Adepts and Masters) carry AiEntity::cultivator, read straight from
the recipient snapshot, which already gates each field: insight, Master rank, Dao readiness and the
item glow tier are public for visible fighters; the pending Dao choice (AiDao) reaches only the
owner and allies. Owned Tournament Grounds report tournament_entrants, and
AiEntity::carried_items() lists the Shop items an owned unit carries (deliveries in flight are not
listed). Every other kind has cultivator: None. AiFrame::shields() lists the Magic Shields in sight
(AiShield: owner, caster when shown, position, HP, maximum HP, radius and ticks left); Shield HP
and radius are public for every visible Shield.
AiActions is a typed per-think builder that retains at most 256 emitted actions in helper-call
order. Its supported helpers are paid explicit-site build, build_when_funded (travel now,
wait for funding at the site), unpriced queue_build/queue_train, resume-without-repay, train, standing
production repeat, research, gather, move, atomic Move routes, attack-move, attack-move routes, direct attack, Hold Position, and Anti-Tank
Gun setup, and ordinary use_ability commands. Cultivator helpers cover free self-targeted casts (cast_self, such as a Novice’s Dao
choice), free point casts (cast_at: Throw Sword, Shield, Blink), Vector Field with its direction,
Shop purchases (buy_item, which pays the item’s Oil and refuses a second copy of the same item for
the same recipient in one step), and Tournament Grounds entry (a reserved move onto the Grounds’
exact centre, Novices only). Casts check that every unit is owned and carries a free ability of the
right targeting mode; they neither reserve their casters nor need them unreserved, so a strategy may
cast and then move the same units in one step. research_cost prices Dao research by tier: the
player’s completed Daos, each producer’s paid current Dao, and Daos emitted earlier in the step. UnitGroup
canonicalizes tactical unit IDs into a sorted, deduplicated, non-empty set; caller-ordered worker,
resource-node, and producer candidate lists are not normalized. attack_move_route reserves a
group once and emits an initial unqueued AttackMove followed by queued waypoints in order. Its
whole route must fit the local action capacity before any request or reservation changes. use_ability reserves its actors and action capacity, while native execution validates ability carrier, readiness, targeting, and cost; policies can inspect owned entities’ projected ability states.
The builder tracks Steel, Oil, and free Supply plus independent actor, resource-node, and producer
reservation namespaces. Every helper completes local preflight before changing the budget,
reservations, batch, or trace. ActionError exposes an ActionBlocker only for locally known
facts: empty input, unsupported kind, no compatible producer, insufficient same-think budget, an
already reserved id, no known candidate, or the action cap. Local success means only that an
SDK-owned action was emitted. It is not simulation acceptance, legality, completion, or atomicity,
and there are no intent IDs or task statuses. build_when_funded reserves the available
portion of a building’s cost without an affordability preflight or crediting projected income;
paid_build retains its full-cost preflight. queue_build and queue_train reserve only their actor or producer and emit ordinary manual commands without budget or supply preflight; the native scheduler handles funding.
The runtime emitter is the sole translator from SDK-owned actions to ordinary SimCommands after
the strategy returns. Built-in profiles share the same budget/reservation implementations, typed
accumulation, and emitter behind their compatibility action context. Their tactical helpers retain
the historical lack of automatic tactical reservations, while production/economy paths retain
worker and resource-node candidate order, producer order, Pump Jack payment, resume semantics,
queue flags, command traces, and Jeff’s Steel-only cross-tick submitted-build commitment. Canonical
controller ordering, all-controller observation before enqueue, worker-retreat-first ordering,
normal simulation validation, and replay logging are unchanged. The builder is deliberately not a
planner, task system, command receipt, or cross-tick scheduler.
UnitClaims<R> is an optional per-decision ownership ledger. A strategy declares its roles as an
Ord enum in command-priority order; each unit may hold several claims and the smallest owns it.
It answers owner, holder, outranking and released-this-decision queries, emits nothing, reads no
frame, and keeps no cross-decision state. Eco is its first consumer: its roles, highest first, are
Pullback, Sentry, Response, Offense, Screen and Escort. Screen and Escort are claimed before the
offensive, which takes only unclaimed combat units, and yield to every other role for commands.
Home posts and the armor reserve command only units owned below Offense. Command Car support still
follows engagement (responders, launched attackers and escort Tanks), not ownership.
PullbackMemory is an optional tactical helper shared by Jeff, Pressure, approaching Rush
Riflemen, and Eco combat units. Its pure plan accepts explicit live squad facts and currently visible enemy-unit facts;
its step adapter reads those facts from AiFrame and emits SDK Moves. The default policy pulls a
member at or below 15 HP three tiles away from the nearest visible enemy when a visible enemy is
targeting it, then excludes it from normal orders for 45 ticks. At least one squad member must
remain above the threshold. Destinations are map-clamped; the helper does not establish terrain
safety or reachability. Callers choose squad membership and keep route and combat ownership.
They suppress normal orders for returned active IDs and restore their own movement for
released IDs. The adapter remembers new retreats only after local emission succeeds; this does
not imply simulation acceptance. Jeff retains his existing squad-planner invocation and early-return
semantics, including resuming ordinary advancement when its caller sees no enemies.
The public-SDK-only reference strategy is the executable authoring specimen.
It runs through AiController::with_strategy and the canonical driver, enables Pump Jack repeat,
uses UnitGroup plus cross-tick memory to dispatch its Engineer as an attack-move scout, and is
covered by deterministic command-log and replay checks. The example is not a selectable profile or
a strength claim.
AiRulebook binds the authoritative rts-rules faction catalog to a strategy frame. Its bounded
answers cover catalog order and availability, costs, supply, production time, health, footprint,
builders, producers, prerequisites, gather capability, and train/research relationships; it owns
no duplicate definitions. projected_income estimates Steel and Oil separately from completed,
currently active own extractors at the authoritative harvest amount/interval, capped by known
remaining node stock. Inactive, unfinished and enemy extractors contribute nothing. Future
payout phases, new extractors and combat are not guaranteed. Upgrade costs/timing remain absent because their current owner is
rts-sim, and the SDK does not move that authority merely to fill a catalog row.
WorldQueries builds stable-id indexes over the frame’s owned entities, currently visible allies
and enemies, remembered contacts, and public known resources. It keeps current and remembered
knowledge distinct, filters only explicitly exhausted resources, reports known mining conflicts,
and uses stable-id tie-breaking after squared-f32 distance for nearest selection. Checked world
and tile helpers reject non-finite, overflowing, or out-of-bounds coordinates.
ground_position_is_observable reads the recipient visibility grid and rejects concealment
and covering smoke; missing visibility stays uncertain. It supports clearing an absent contact
at a visible open-ground position without claiming the enemy died or exposing hidden state.
Known building placement reuses the established AI footprint, public-resource, visible-building,
production-exit, ring traversal, and tie-breaking approximation. Results are named Invalid,
KnownBlocked, and NoKnownConflict; none claims authoritative legality, clearance, reachability,
or command acceptance. Public queries depend only on AiFrame and explicit controller-owned
failed-site exclusions. Legacy profiles retain their historical global-producer exit check through
a narrow compatibility policy, while all other placement work is shared. Dynamic pathing, target legality, full line of fire, and hidden occupancy remain outside the
public query seam. The known-ground route queries below use static terrain plus current
known footprints. The defensive planner uses static terrain routes and bounded rock-ray
checks for its recommendations; those do not establish authoritative movement or firing legality.
AiFrame::base_sites() exposes cached public base landmarks from the existing static map
analysis: a site for each original player start and each non-home resource cluster. Start sites
absorb their mapped home cluster; empty-resource starts still have a main landmark. IDs are
Start(player_id) or ResourceCluster(cluster_id) and remain stable while public map inputs are
unchanged. Cluster sites are inferred geography, not authoritative build footprints.
WorldQueries::ranked_bases(player_id) and base(player_id, rank) rank all sites relative to that
player’s original main: main is always 1, then increasing static ground path length in world
pixels, with stable site-ID ties. The existing cached start-distance fields route around blocked
terrain with cardinal/diagonal costs of 1/1.4 tiles and forbid diagonal corner cutting. Distances
ignore dynamic units and buildings and do not model a specific unit’s footprint. Each site’s
ground_distances_from_starts contains the reachable players’ distances; unreachable sites sort
last by stable ID and have AiRankedBase::distance_from_main = None. This is geographic order,
not acquisition order or ownership. Other players’ starting sites remain in the list. Depletion, destroyed
Depots, and fog never renumber sites; a Lab map edit can rebuild them.
known_base_depots(site_id) associates known Resource Depots with the nearest site within twelve
tiles, using stable-ID ties. It reports owner and owned/currently visible/remembered evidence,
including last-seen tick for remembered contacts. Current evidence supersedes memory of the same
entity. Empty evidence means unknown occupancy, never confirmed vacancy. Construction sites count
as Depot evidence; none of these queries reads hidden state. The canonical host attaches the cached
landmarks before either strategy initialization or step. The defense planner’s explicit
plan_expansion entry point may use one reachable public landmark before Depot ownership,
rejecting unknown IDs, unreachable/enemy starts, and known hostile Depot occupancy. It makes
no ownership or authoritative placement claim; ordinary plan still requires completed own Depots.
If a prospective garrison has no legal firing posts, the planner tries that landmark’s cached
terrain cut with the same reachability/occupancy/firing checks, retaining other defended sectors; unsupported lines stay explicit. Pressure uses these queries to order its
expansions; other built-in profiles retain their existing placement policies.
WorldQueries::base_depot_site(site_id, exclusions) recommends the Depot’s top-left tile for a
specific public base, using the resource-anchor geometry and mining-range/distance scoring
shared with Pressure. To build at geography rank K, callers use base(player_id, K) then pass
that site’s stable ID to this query. It tries the exact landmark footprint first when it covers
the normal Steel and Oil patch counts, then searches resource-centered alternatives. Both kinds
must remain within authoritative mining-anchor range (up to twelve Steel/three Oil patches,
or the cluster’s remaining count if fewer). Unknown stock remains unknown. Known occupied,
hostile, unreachable, exhausted or excluded sites return no recommendation. The result uses
ordinary known terrain/resource/building/exit checks while ignoring movable own unit bodies;
callers must clear friendly units from the reserved footprint. It is never an authoritative
legality or dynamic-route receipt. Landmark position itself remains geographic metadata, not a build coordinate.
ground_route and ground_route_to_build_site return deterministic public-terrain routes for a
specified mover, avoiding the authoritative static-blocker classes and diagonal corner cutting.
AiMap carries the public vehicle-forbidden overlays and tree trunks as well as ordinary terrain;
vehicle-only obstacles affect vehicle bodies, while resources and walk-through extractors do not
invent movement walls. Building placement still rejects resource footprint overlap independently.
The latter route ends
at a reachable exterior footprint ring sized for the mover’s conservative body clearance. Unit bodies and hidden/remembered entities do not affect
route geometry. Wide bodies additionally sample tile-boundary positions on a half-tile lattice,
so a physically passable two-tile lane is not rejected merely for lacking a tile-center sample.
ground_reachability exposes a reusable body-aware component with point membership checks;
callers can reject disconnected posts without pathfinding separately to every candidate.
The opt-in known_build_site_with_access layout query adds two/three-tile spacing and checks
producer escape after virtually adding a proposed footprint. It evaluates all native spawn sides,
out to six rings, and requires every component of the first full-rotation spawn ring to escape the
producer’s immediate enclosure. Existing ordinary placement APIs retain their policies. These remain known-world hints, not dynamic or hidden-world guarantees.
route_has_visible_ground_threat checks every route segment against currently
visible living enemies capable of targeting the mover, using weapon range, public trench bonus
and body margins. This is conservative dispatch policy, not authoritative pathfinding or a
promise of safety in fog; remembered contact expiry is a separate tactical concern.
Shared cut/garrison defense and Eco AI
sdk::DefensePlanner is a reusable, command-free implementation of the B defensive hybrid.
Strategies supply their frame, chosen base-site IDs, and defender budget. The result contains cut
and garrison sectors, protected economic value, relative priority, estimated ground approach time
from public enemy starting positions, and usable world-pixel slots with sector IDs. Static terrain/cut work is cached;
the caller retains the planner between decisions. Up to four defended sites, geometry compares
all cut/garrison partitions. Larger sets compare two bounded merge searches: singleton sites and
the previous surviving partition extended with new sites. Each search evaluates at most 32
candidate merges, preserving useful shared cuts across the fifth-site transition without
exponential subset enumeration. Removed sites invalidate any old group containing them. The planner does not choose expansion timing,
assign entity IDs, issue orders, or take tactical ownership from its caller.
Garrison sectors use the public base center and offer posts in a seven-to-nine-tile ring around
it. After a forward-facing first post, successive posts maximize separation around the legal
ring instead of clustering at one forward point. Known obstacles, entrenchment restrictions,
reachable paths, reserved building footprints and Engineer access still restrict available posts;
a blocked or exhausted ring leaves staffing unallocated rather than piling units onto a fallback.
with_garrison_posts_per_base(n) opts into fixed observation rings (one to sixteen posts per
completed requested base), allocating scarce budgets in rounds instead of economic weights.
reserve_posts excludes another formation’s planned posts from slot allocation without turning
friendly guards into walls for route reachability or cut geometry. Eco uses a four-post observer
planner alongside its normal hybrid planner and includes both sets when parking armor.
plan_with_expansion combines validated completed owned sites with one prospective site in the
same geometry and economic staffing allocation. It never substitutes the expansion for the owned
base set. With nonzero budget it allocates one physically supported expansion post first, so a
future site’s small asset value split across several cut sectors cannot round its entire screen
down to zero and deadlock Engineer dispatch. Remaining units follow normal economic staffing;
ordinary all-owned-base planning has no per-base minimum. plan_expansion_reserved accepts typed future building footprints. Before choosing posts, both
cut and garrison scoring reserve the structure plus a one-tile Engineer access ring and defender
body radius. Changed reservations invalidate cached placements; all sector/global slots remain
consistent. Unsupported space stays unallocated rather than duplicating a surviving post.
plan_claim uses the same combined owned/prospective geometry and reservations, while allowing
known hostile occupation of the prospective site for a deliberate territorial assault. It does
not legalize occupied construction footprints or relax the ordinary expansion helper’s checks.
Staffing combines uniquely attributed remaining-Steel/production value with decreasing urgency as enemy ground approach time increases. Each 100 remaining Steel contributes one economic value point, without a cap, active-mine bonus, or unmined discount. Thus a fresh resource-rich base counts before its mines are built, while depletion proportionally removes its resource value. Unknown nodes retain their uncertainty and use a policy-only 312.5-Steel estimate (half a full patch); that estimate is never reported as known stock. Actual active-mine counts remain diagnostics only. Production/tech building values, the nominal Depot value, approach weighting, and search methods are unchanged. Length influences whether a compact cut or garrison is selected, but does not multiply economic staffing priority. Entrenchment restrictions, static reachability, known occupancy, and firing-distance checks reject unusable posts. Unsupported sectors and unallocated defenders are explicit. Neither a cut nor a suggested slot certifies a sealed front, dynamic path clearance, command acceptance, or combat effectiveness. No map-specific choke coordinates are embedded in this policy.
Eco AI is an independent typed strategy, registered as selectable eco_ai / Eco AI. It uses
ordinary SDK actions and the same fog-filtered canonical host as other strategies. It does not
change the default opponent, composition members, or random-profile pool.
Its economy builds one Barracks and a Training Centre on one base, enables Machine Gunner auto-production, and completes Entrenchment before expanding. At two completed bases it builds an Engineering Complex, queues Tank Production research on its scaffold, then builds the first Vehicle Works and second Barracks. Panzerfaust and Methamphetamines research are queued at two bases. At three bases it requests one Command Car and targets two Works and three Barracks (the Barracks cap); at four bases it completes the third Works before resuming expansion. Expansion targets half the map’s base sites plus one (seven on Classic). After that target, all completed Works actively producing Tanks without a resource wait trigger another Works; desired capacity persists to replace destroyed Works. No stockpile or income threshold drives these decisions.
Every Barracks has standing production: Machine Gunners initially, then alternating dedicated
Machine Gunner and Panzerfaust producers once Panzerfaust research completes. Dedicated lines keep
a Panzerfaust’s Oil wait from blocking a Machine Gunner producer. Every Vehicle Works keeps Tank
auto-production enabled, including during travel, construction, research and resource waits.
Standing orders are configured once per state transition, including on unfinished buildings, and
recover after producer destruction. Eco does not maintain a spending ledger or forecast income.
It uses queue_build, queue_research, and queue_train for a missing Engineer or Command Car
without requiring funds. The native scheduler pays eligible manual orders before automatic
production for both human and AI seats. Travelling Engineers and research on unfinished buildings
become spending priorities only once their orders can start, matching player behavior. Paid automatic
jobs continue working. Supply uses the game’s fixed cap and native production waits.
Tanks form one concentrated reserve near the centroid of owned and prospective expansion base sites, weighted
by remaining Steel stock (unknown deposits use the same 312.5 planning estimate as defense scoring).
When all deposits are exhausted, the average completed-base position is the fallback. The nearest
body-clear reachable reserve anchor is chosen; disconnected components form local reserves rather
than crossing impassable terrain. Stable posts form a square grid with two-tile spacing, exclude infantry slots
and the reserved Depot footprint, and tolerate small centroid shifts without reshuffling parked units. Local combat staging also uses
separate two-tile Tank grid destinations. Bounded atomic Move
route batches reserve each Tank once and retain all queued corners, gathering armor without acquiring fights en route; idle/stalled units retry and released
responders return to reserve. Armor does not entrench. Supply and standing production remain native.
Eco targets one Command Car per completed base beyond the second, replaces losses,
and keeps Tank auto-production enabled. The car follows the greatest Tank concentration within
a nine-tile clustering radius, prioritizing attacking/mobilized Tanks over idle reserves. It parks
two tiles toward home from the cluster, uses body-aware queued routes and a two-tile destination
deadband, and casts ready Breakthrough when it can cover an engaged Tank group with visible enemies
nearby or while escorting a claim. Cars rotate casts and wait for active Breakthrough to expire. Support commands run before large infantry batches so the action cap cannot starve the car.
At four completed bases Eco queues Tank Plus, then Scout Plane research at an Engineering Complex. After the research completes, one ready Command Car launch is held for an incoming defensive incident; spare ready carriers rotate sorties toward public enemy-side base sites, excluding known friendly Depots. The reserve is a ready ability, not a stored plane unit. Defensive sorties may spend it; routine flights resume only when another ready launch can remain in reserve. Same-area sorties are deduplicated for their thirty-second lifetime, with local cooldown bookkeeping preventing repeated orders before the native snapshot updates. Defensive observations refresh before reconnaissance without issuing troop orders; the troop controller then consumes that preparation once in the same tick. Reconnaissance runs before support movement and Breakthrough, and uses only current defensive contacts and public geography. Defensive flights must be able to reach the incident within eighty percent of their lifetime, preserving observation time; an unreachable incident neither spends the reserve nor creates a covered-area record.
Recon sortie coverage is reconciled with observed living owned planes after launch; losing a plane releases coverage immediately rather than waiting for its nominal lifetime.
Eco uses the earlier visible-enemy local combat assessment, with HP-adjusted value and the existing ninety-percent local parity gate. Individual Tank retreat posts stay fixed while safe; current-visible route checks retain queued corners so the simulator follows the checked retreat instead of replanning an endpoint-only move. Current-step placement reservations keep independent retreat destinations two tiles apart, including fallback positions around new obstacles. No group waits for members to gather at these posts. It does not retain a remembered enemy formation or an armor encounter, require ninety-percent group regrouping, or hold tanks after an incident clears while waiting for a shared rally. Tanks are recruited at two per observed enemy Tank; a Scout Car alone does not mobilize them. Bounded incident/contact bookkeeping still prevents unlimited pursuit and releases a contact when its last position is visibly clear.
Each completed owned base leaves one eighth of its assigned healthy infantry on observation garrison duty, rounded down and capped at four. Seven infantry reserve none, eight reserve one, sixteen reserve two, and thirty-two or more reserve four. Counts use persistent home assignments rather than temporary combat positions, so mobilization cannot erase its own watcher quota. Guards come from that base’s local home roster; scarce bases do not import troops from another base to force a minimum. The SDK spreads the selected posts around the ring for vision. Wounded micro retains priority, assignment verifies each unit’s reachable component, and dead or unreachable guards are replaced locally. Garrison orders precede combat batches and survive outbound pushes. The normal hybrid planner staffs terrain cuts with the remaining infantry. Garrison rings are seven to nine tiles from the base center, four tiles farther than before. SDK Tank route planning reserves three world tiles from static obstacles, with native arrival padding to keep queued corners clear in execution. This is an AI waypoint preference: native Tank body-width movement, human orders, and collision/steering rules remain unchanged. Body-clear source and actual-goal attachments are bounded to twelve tiles. Production-yard egress may extend to thirty-two tiles inside connected five-tile-expanded known building clusters containing a Works. Routing considers alternate entries into matching wide components; reusable reachability precomputes endpoint membership. Normal transit does not fall back to a narrow corridor, and unit bodies do not inflate the obstacle buffer. The earlier entire-reserve expansion claim remains: tanks escort a proposed base until clear, then return to the updated reserve centroid. This is separate from defensive threat recruitment. Engineer dispatch need not wait for that escort: living infantry within ten tiles can confirm the currently observable site center is clear of visible enemies within fourteen tiles. This evidence is checked afresh at dispatch; the infantry screen’s five-second lead and the Engineer’s known route without visible ground threats are still required.
Eco permanently enables its offensive once witnessed enemy destroyed-resource value is at least
15% of its own lifetime mined Steel plus Oil (both totals must be positive). There is no 300-supply
or seven-base prerequisite. The canonical host supplies only the controller’s own collection totals
through AiFrame::lifetime_mined; starting funds/refunds are excluded. Prepared scripted hosts
forward the same player-specific Game counter through PlayerView, including observation frames. SDK loss valuation matches
observer analysis, including zero-cost automatic Pump Jack losses.
Possible enemy sites use enemy-relative geographic ranks up to Eco’s completed-base count, bounded
to half the map, excluding friendly/cleared sites. Their convex hull retains collinear boundary
bases. Eco scouts the three hull sites nearest its Tank centroid (owned Depot centroid if no Tanks).
A survey requires a living Scout Plane within eighteen tiles and a currently observable site center;
confirming an empty site additionally requires a flyover within five tiles.
It records HP-weighted nominal Steel-plus-Oil value of visible armed defenders within fourteen
tiles. Confirmed unoccupied sites are skipped; they resolve a survey without becoming zero-defense attack targets.
Unknown sites never score zero. A scouting batch stays fixed until its actual targets are cleared;
empty-only batches recompute the hull, with empty observations excluded for sixty seconds.
Once all three candidates have observations, Eco commits to weakest first, second-weakest next,
with stable-ID ties. That batch order stays fixed during combat; after it is cleared, the hull is
recomputed. Scout targeting reuses the existing spare-car/reserved-defense-flight mechanism.
Eco reports six named decisions through ordinary game all-chat: 15% attack triggered,
Not enough forces, Retreating: enemy force is overwhelming, Attacking, Counterattacking,
and Taking a new base. The threshold message means activation, not launch. Attacking requires
an accepted offensive wave order; Counterattacking requires an accepted home-response attack
order on entering fighting mode. The local below-90% strength gate reports insufficient forces;
a retreat message additionally requires an accepted movement order on entering withdrawal mode.
Wounded-unit repair micro does not report overwhelming-enemy retreats. A new expansion frontier
reports taking a base. These typed notices do not consume action capacity, reserve actors, use
randomness, or alter decisions. Duplicate unit events collapse within a decision and each category
has a ten-second simulation-time cooldown. The authoritative roster supplies sender identity.
Live and offline hosts preserve the same all-chat rows in replay chatLog, capped at the shared
10,000-entry replay limit. Ordinary observer resource/loss statistics remain; the in-game AI
diagnostics panel, trace payload, and map-analysis rendering are removed. Offline decision traces
and internal strategy map analysis remain available to tools.
Once a scouted attack queue exists, it owns the armor ahead of optional expansion escorts; infantry
expansion screening and the Engineer route check continue. A cohort with Tanks forms the shared rally line
(shared_tactics/rally_line.rs) 35 tiles short of the target along the Tanks’ ground route, facing the
target site; its infantry take Pressure-geometry posts in three ranks two tiles behind the Tank line’s
last rank. The rally line’s own gates launch the wave: when 75% of its Tanks stand in their slots (or
15 seconds after half do) they point at the target, and when 75% face within 20 degrees (or after 3
seconds) each Tank attack-moves in its own lane through the target while the wave’s infantry, ready or
not, attack-move to it. Cohort membership is frozen so ongoing production cannot postpone departure.
Infantry-only cohorts keep Pressure’s straight-axis staging 25 tiles short and the 90% healthy
purchase-value gate. Later reinforcement cohorts form in batches of at least 20; Tanks outside a
cohort take infantry-style posts while they wait.
A new target is selected only after the current site’s center/resource positions are observable,
no known enemy Depot or relevant visible enemies remain, and attackers have reached the area.
Each new target restages the surviving army. Outbound troops yield to shared wounded micro and
home-defense mobilization, resume their offensive mission after release, and do not receive normal
post/reserve commands or count as staffed home-line anchors. Expansion screens retain their roles. Each new claim sends the entire available Tank reserve in a spaced attack-move formation, with Breakthrough, before the Engineer is released once the site is observed and clear.
Construction reuses the established Jeff/Pressure outward ring placement search for ordinary
buildings. Expansion Depots use the SDK’s Pressure-derived resource-centered placement query,
which keeps Steel and Oil coverage instead of moving the Depot outward from its resource cluster.
Both paths use shared SDK footprint checks. Ordinary Eco construction additionally requests two
full clear tiles around buildings, three around Vehicle Works, including solid terrain and map
edges. It checks body-clear exits and connectivity for both new and existing vehicle producers
before accepting later construction, so a newly legal footprint cannot silently seal a factory.
Other profiles retain their existing spacing policy. Like Pressure’s expansion guards,
Eco excludes the predicted Depot footprint plus unit clearance from its infantry post assignment;
its own screen must not occupy the footprint that the Engineer is about to build. Like Rush, Eco leaves an Engineer’s active build/travel
order alone. Like Jeff, recovery waits three seconds for an unattended paid scaffold and avoids
visible fighters within ten tiles. Recovery is restricted to Eco’s Barracks, Training Centres,
Resource Depots, Engineering Complexes, and Vehicle Works: automatic Steel Mine/Pump Jack jobs
never claim the Engineer. Starting
Riflemen join the same defensive post assignment as the later infantry. Before sending the
Engineer to build or resume an expansion Depot, Eco plans all completed owned sites plus the
prospective expansion together. Only infantry assigned to the expansion screen receive its advance
orders; rear sectors retain their share of defenders. A shared cut can protect several bases;
screen readiness follows the SDK sector’s covered base IDs rather than Euclidean proximity. This plan does not guarantee one unit per base when staffing is scarce.
Eco submits Engineer-built structures when their strategy stage is ready, even with no funds.
For expansion, the Engineer waits five simulation seconds for the initial screen cohort’s advance
orders; fresh auto-produced reinforcements do not restart that lead. Surviving cohort members whose
posts change still need fresh advance time. If the cohort disappears, a new current screen forms
another wave; a changed intended Depot footprint resets the wave. Production remains enabled
throughout. New infantry join whichever sector the shared planner allocates them. Temporarily mobilized or
wounded infantry retain intended home posts and remain in the planning capacity; combat only
borrows command ownership. Planning uses the living roster, so temporary combat assignments do not shrink the layout.
Release explicitly resumes the home-post order even if a unit is still moving or attacking. The prospective frontier persists through travel and
construction, then clears immediately when its Depot completes, returning to the all-owned-base plan.
An unpaid Build order remains tracked while the Engineer waits for resources; once funded, normal
stuck travel recovery applies. Other profiles retain their existing submitted-build expiry policy.
Eco reuses the same SDK wounded-unit helper called by Pressure and Rush, with its default
15-HP threshold, three-tile backward Move, and 45-tick ownership window. Its combat roster
(Riflemen, Machine Gunners and Panzerfausts) is eligible when a visible enemy targets a
wounded member and another healthy infantry member remains. Tanks never use this wounded-unit
pullback. Pullback runs before mobilization;
active retreaters are excluded from response recruitment, infantry posts, armor routes and the
Engineer screen. When the helper releases a unit, response or defensive movement is reissued,
rather than leaving its retreat order in place. It can retreat again if it remains targeted;
it does not wait for healing. Pressure/Rush’s own integrations are unchanged.
Eco reuses Pressure’s incident memory and recruitment machinery (shared_tactics/response.rs) with opt-in cohesive orders and a defended-area
policy, replacing the original midfield boundary for Eco only. Persistent assigned infantry and
armor posts identify guard roles even while mobilization or wounded micro owns their commands;
current Attack/AttackMove state never defines a protected role. Every living owned or currently visible allied building provides an additional 20-tile reaction
bubble, including unfinished scaffolds, extractors and exhausted Depots. This reaction policy is
independent of remaining-Steel weighting for routine defensive staffing.
A visible enemy is relevant within its known weapon envelope (including public trench bonus,
and the conservative 14-tile stationary maximum for Tanks) plus two tiles of a staffed-post anchor,
within 20 tiles of a friendly building, or when targeting an assigned guard/protected building.
Visible enemy units and buildings qualify; noncombatants near a staffed post use a two-tile envelope. Admission,
refresh and release all use that same relevance policy, on either half of the map. Every incident
pins its original anchor and pursuit leash. A leashed-out contact cannot rearm merely by shifting
the same guard’s anchor; arrival at a genuinely distinct protected role can start a new incident.
Visible irrelevance or observable clear ground releases active commitment immediately; fog,
concealment and smoke preserve uncertain contacts for up to 30 seconds. Pressure’s default
home-half policy remains unchanged. Eco recruits infantry worth at least 150% of admitted enemy
purchase value scaled by last observed remaining HP (rounded up to whole resources), then separately recruits two Tanks per admitted enemy Tank. Remembered contacts retain the last observed health discount; hidden health is never queried. The defensive armored response concentrates on one armored incident (the largest nearby enemy
Tank cluster) and uses one shared launch decision. Before launch, both arms refresh their staging
geometry together when the infantry concave leaves its 15–25 tile distance band, or the Tank line
would enter a known weapon’s maximum reach plus a three-tile margin. Visible weapons and the last
observed positions of remembered Tanks in that cluster both contribute to this envelope. Tanks form a perpendicular
line three tiles behind the concave’s twenty-tile middle (normally 23 tiles from the cluster),
farther back when the visible firing envelope requires it (rebuild with four tiles of clearance
after crossing the three-tile replan margin). Slot snapping cannot move Tanks in
front of that line. Each meaningful staging update rebuilds slots and restarts assembly/facing
timing, allowing Tanks to back away from approaching enemies; small shifts retain the line. Infantry
already targeted by a visible enemy or within a visible weapon’s reach receive Hold Position so
that they keep or establish entrenchment; wounded-infantry pullback still has priority.
Other recruited infantry use the native FormationMove command to spread along a broad concave
on the friendly side of the enemy, roughly 20 tiles away. The cached line remains until it leaves
the 15–25 tile distance band, its membership changes, or an idle unit is stranded outside the band;
travelling reinforcements do not continually reset it. Infantry use ranks of at most 24, with roughly two-tile spacing along each arc and between
ranks, rather than squeezing a large force onto one line. The front rank maintains the distance
band; additional ranks stand farther back.
The army compares the combined health-adjusted responder value within 15 tiles of the Tank rally
against visible enemy value within 15 tiles of the armored incident. At 90% strength it may launch;
assembly/facing timeouts never override this strength gate. The Tank-ready trigger is literal:
if there are no friendly Tanks, or they are all lost before launch, staging infantry wait for
replacement Tanks rather than receiving an infantry-only charge fallback. Exposed infantry
still hold/fight, and wounded non-Tank pullback still takes priority. When 75% of the Tanks reach their slots
(or 15 seconds after half do), they point toward the enemy. Once 75% face it (or after three
seconds), a ready army launches Tanks and staging infantry on the same decision. Infantry launch
with attack-formation orders translating their broad lanes through the enemy rather than
collapsing onto one shared destination. Outer lanes may flank beyond a narrow enemy cluster;
this deliberately favors splash spacing over forcing every infantry unit into immediate range.
After launch the Tank line can re-aim and retarget its advance without rebuilding assembly slots;
enemy movement never sends the committed force back to staging.
The existing Eco trace includes defense_army phase, shared readiness/strength values and cohort
counts, so replay inspection can explain the decision without omniscient sensors.
An established counterattack owns its Tank cohort throughout Forming, Pointing, Reforming and
Advancing, including after its last enemy Tank disappears while non-Tank or remembered contacts
keep the battle active. Its membership is reserved before expansion/support dependency selection;
these Tanks are excluded from expansion escort candidates and the initial arrival/readiness wave.
The ordinary response command claim also outranks expansion orders. The fifty-percent global
expansion gate does not release individual counterattack ownership: spare troops may expand,
while the counterattack cohort stays assigned until the response actually clears.
Tank staging floods body-aware reachability from actual Tanks, never an unchecked centroid.
If a desired line overlaps a known Depot/building, solid terrain, trees or a public resource tile,
the entire line searches the nearest body-clear reachable alternative within twelve tiles per axis on its
original rear side, preserving its spacing and enemy standoff. Existing slots are rechecked when
new construction appears. Disconnected stragglers cannot repeatedly reset the main formation;
Tanks without a safe slot receive Hold rather than continuing a stale expansion route. No blocked
or unreachable desired slot is used as a fallback.
At launch, every eligible infantry responder joins the attack, including defenders previously
holding or entrenched under fire. Infantry cannot independently retreat or acquire a new exposure
hold while the Tank formation remains committed; wounded non-Tank pullback remains the explicit
exception. Enemy movement, weaker local readiness, losing the last enemy Tank, or handing off
between protected roles cannot send an advancing force back to formation. Only the response’s
actual clear/death/fog-memory policy ends commitment when the defensive battle clears.
After launch, previously tracked enemies remain committed targets while alive and visible even
outside the original defended role/leash; this never acquires unrelated new targets. Hidden
contacts retain only their last observed positions for the ordinary thirty-second memory and
release immediately when that ground is observably clear. A later battle
starts fresh assembly; protected-role changes before launch may also restart staging.
Eco pauses new-base expansion only when the detected defensive attack value is at least half
its total current army value. Both sides use Steel+Oil purchase cost discounted by remaining HP,
rounded up per troop to whole resources. The numerator sums admitted defensive combat contacts
at their last observed HP (including normal fog memory). The denominator sums all living,
completed owned combat troops, wherever stationed, including sentries and units outside the
response; it never uses historical army size or only nearby responders. Combat troops are units
with a positive public weapon range, excluding Workers; buildings, noncombat utility units,
dead troops and incomplete own troops do not count. A positive attack pauses expansion against
a zero-value army; zero attack never pauses, including zero versus zero. The exact comparison is
attack > 0 AND 2 * attack >= army.
This threshold is refreshed from the current observation before expansion support/claim orders
and again after response recruitment in the same decision. At or above it, prospective cover
and Tank escorts return to owned-base duties unless recruited by the response; the Engineer
cannot receive a new Depot build dispatch, and unpaid Depot travel is cancelled. Below it,
local defense still responds normally while builder readiness, prospective cover and Tank escort
continue under their usual rules. Smaller attacks do not globally replan expansion forces.
The selected site remains reserved, and paid construction and normal production continue.
The recorded rule tree shows the literal half-army test and either Pause expansion or Continue
expansion; it does not invent a separate harassment classification.
When there are no admitted enemy Tanks, the existing infantry-only response remains: each
infantry responder compares nearby healthy purchase value with 90% of the enemy value around
its contact, attacking if ready and otherwise using safe rear staging positions. Other profiles
and Eco’s strategic offensive rules are unchanged. All decisions use fog-filtered observations.
Retreaters are excluded from recruitment, and responder
orders cannot be overwritten by normal frontier/armor maintenance. Released guards get fresh
assignments; only the initial cover wave controls expansion lead time. Engineer dispatch
requires the infantry lead and a known terrain route to the actual Depot perimeter with no visible
in-range ground threats, and no active defensive response.
reinforcement training can continue during response. Defense and construction share the same
intended tile, including failed-site exclusions, submitted orders, and scaffold positions. Posts
are allocated around that reservation before assignment, with no shared-slot overflow fallback.
Expansion candidates follow SDK ground-distance rank, excluding unreachable and known hostile
sites. Completed owned Depots drive base stages; submitted commands are never treated as proof
of completed construction. Defensive assignments follow the shared cut/garrison planner and move
forward when the defended base set changes.
Army movement controller boundary
Eco, Pressure and Rush enter combat movement through the crate-private
shared_tactics::army::ArmyController<Mission>::command_army interface. It receives the current
fog-filtered AiFrame, a profile-specific mission, and the existing AiActions sink. The controller
owns persistent movement memory and coordinates its executors; its economic host supplies setup
information and calls it once per decision. Executors keep using the same action budget and issue
order: buffering a new batch would change acceptance and memory updates. Pressure preserves its
existing separate overlay sink after the legacy core; the refactor does not merge those budgets.
- Eco:
eco/army.rs::EcoArmyowns target selection, recon, command support, offensive waves, defensive assignments and their planner. The economic strategy retains construction and production. Construction exchanges expansion reservations and builder-readiness information with the army; it does not independently command combat troops. The army runs target observation, claims, recon, support, defense and offense in their previous order. - Pressure:
pressure.rs::PressureArmyowns the existing incident response, pullbacks, staging and launched routes. Its mission supplies the target, eligible units and trained-Rifleman count. The legacy host still runs the economic/core decision first; Pressure’s existing production configuration stays at the start of the army pass to preserve budget ordering. - Rush:
rush/staging.rs::RushArmyowns assembly, staging defense, pullbacks, launch memory and wave flow. Its mission is the current enemy objective. The economic strategy still computes producer rally setup before movement and retains its existing handoff timing.
The interface is shared, while engagement policy remains profile-owned. Eco’s defensive armored response now coordinates the Tank rally and infantry launch as one force, as described above; infantry-only incidents and strategic offensives retain their separate existing rules. Further policy changes belong above the infantry and Tank executors rather than in a competing host overlay.
For behavior-preserving refactors, run baseline and changed ai-matchup binaries with identical
profiles, map, seed and tick cap, saving each run with --save-replay <case> --replay-dir <dir>.
Use Classic, Crossroads, The River and Schone Tage as the key Eco-versus-Jeff cases (seed 20261203,
cap 54000 ticks); include Pressure/Rush cases when changing their controller entry points.
node scripts/compare-ai-replays.mjs <before-dir> <after-dir> [case ...] compares freshly generated
command streams, initial states, outcomes and final simulation hashes, ignoring only build SHA.
Replaying the baseline commands alone does not test the changed AI’s decisions. This is a focused
refactor check, not a requirement to preserve these policies during later intentional improvements.
Shared decision core
Each controller runs on a staggered cadence and constructs the typed AiFrame. Legacy built-in profiles
run through the crate-private LegacyProfileStrategy, which projects that frame back into the
internal AiObservation before the generic decision loop applies the selected AiProfile policy.
That compatibility projection alone preserves the historical false is_ai value, synthetic
unknown-resource amount, free_for_combat derivation, and old sorting/filtering rules; these quirks
are not represented as truthful SDK facts. The direct legacy observation constructor remains only
as a test oracle for field-for-field projection checks. Existing action helpers use the SDK-owned
typed action vocabulary and shared local per-think budget and reservation implementations to
prevent resource and supply overcommitment without changing compatibility policy.
The core also owns static map analysis derived only from StartPayload map terrain, start tiles, and static resource nodes. When nearby steel is split into fields around the Resource Depot, defensive staging and Rifleman raid readiness use the field on the map-center side, falling back to the full steel cluster for degenerate layouts. Start and resource-cluster mappings prefer candidates in the same reachable terrain component when component identity is known, with distance as the fallback for unknown components. AiStaticMapContextCache keys that analysis by stable terrain, start, and resource identity, so a Lab map edit naturally causes the next think to rebuild passability, clearance, regions, chokepoints, starts, and resource analysis. Gameplay-choke detection uses local minimum vertex cuts between high-clearance basins for broad middle passages and split-validated linear cuts across bounded passable runs for base mouths. Ranked graph-cut candidates are scanned until the target count is filled, skipping candidates that cannot be mapped. Region pairs come from region-bearing passable sides of the local split, with basin metadata as a fallback only for basin-backed candidates. Default and Low Econ each expose twelve gameplay chokes. The published observer layers show generated choke lines, base markers, resource-cluster markers, and labels; regions remain internal. The offline ai-map-analysis-debug tool loads bundled maps through the simulation map loader, runs the same static analysis, and renders the observer layers over terrain as SVG. Its choke overlay renders the exact detected choke tiles rather than choke bounding rectangles.
The economy model is also observation-owned. Engineers are construction-only and the built-in profiles retain only their starting Engineer plus any explicitly configured extra builder. On the first decision after each Resource Depot completes, the controller idempotently enables Steel Mine and Pump Jack repeat production there. The authoritative Depot queue chooses eligible in-range patches, pauses a saturated extractor kind, advances to the other repeated kind when possible, and resumes replacement production after an extractor is destroyed. Resource availability counts only completed, live extractors as current income while treating an in-progress scaffold as patch occupancy. Expansion planning can still see known resources outside current Depot coverage.
Decision traces record the selected profile ID, tick, budget and reservation deltas, strategic goals for economy, supply, expansion, tech, production, local defense, and frontal attack, plus bounded command and blocker labels. Each live AI controller exposes its latest decision trace to spectators, with the reliable-channel snapshot bounded at the AI adapter boundary. These traces and map-analysis layers are spectator-only diagnostics.
Expansion sites must be more than ten tiles (center to center) from any owned or currently visible Resource Depot, including unfinished depots and the controller’s pending Depot builds. Patches inside a known Depot’s mining range are also excluded, so occupied sites are skipped while the search continues through other resource locations.
Pressure AI
pressure_ai owns a copy of the AI 2.1 opening and Tank technology, with independent
expansion, infantry research, production, and staging. The legacy home
response, defensive panic production override, and dedicated Machine Gunner policy are disabled
for Pressure. Other profiles retain them. Construction clearance still has priority.
Pressure retries interrupted research on replacement producers so a lost Training Centre cannot
permanently lock its first wave.
The single Pressure response controller borrows mobile Riflemen, Panzerfausts, and Tanks nearest to observed attackers until their full purchase value (Steel plus Oil) reaches at least 150% of the remembered enemy unit value, or all available units are committed. It triggers only on visible enemy units on Pressure’s half of the map: the half-plane containing its original main, split by the perpendicular bisector between the two starting bases. Sightings on the enemy half never create or refresh a contact, even during offensive wave fights. When an enemy crosses that boundary, its last friendly-half position remains remembered for 30 seconds; the response never follows refreshed positions into enemy territory. All enemy units spotted on the friendly half contribute to the incident value; new recruits and replacements join as needed. Response orders are AttackMove to the nearest remembered attacker position. Each contact keeps its last visible position for 900 ticks (30 s) after it leaves vision. When all contacts expire, surviving responders return to the current staging line, including units borrowed from launched waves. Units already committed remain in the response until that timeout; the controller shares a value budget across simultaneous contacts.
server/crates/ai/src/pressure.rs intentionally copies Rush’s terrain route, stable-slot, arrival,
and cohort policy instead of calling Rush code; its staging-line geometry lives in
server/crates/ai/src/shared_tactics/staging.rs so Eco can reuse it without depending on Pressure. Its constants and persistent state are independent.
Before 4:00 the line sits 45 tiles outside the enemy start, perpendicular to the routed approach.
This keeps the opening assembly ten tiles farther from the enemy main, toward Pressure’s own main.
At 4:00 it moves to 25 tiles from the opponent’s geographically ranked second base, toward
Pressure’s original main. It is perpendicular to the straight main-to-target axis. At 8:00 it
moves to the opponent’s third base with the same 25-tile distance and perpendicular geometry.
These SDK ranks describe public geography, not knowledge that an enemy Depot exists there.
Pressure snapshots these landmarks on its first decision for the opponent, so depletion cannot
redefine base two or three between timed phase changes.
Missing ranked sites fall back toward the enemy main without duplicate queued destinations.
Riflemen and Panzerfausts occupy the front; Tanks stand three tiles behind at three-tile spacing. Units attack-move to clear slots, engaging enemies en route, and Hold Position after arriving. Later lines may span blocked terrain: their center and orientation remain exact. Blocked slots and slots disconnected from Pressure’s original main are skipped using cached static ground connectivity without diagonal corner cutting; ordinary unit movement routes around terrain. The opening wave unlocks at 90% Methamphetamines research (or completion). Before 4:00 it launches once at least one unit arrives, with five arrivals required thereafter. From 4:00 all new waves require at least ten arrivals; from 8:00 they require twenty. The research gate still applies if the opening wave has not launched. En-route units do not count.
A second-base wave receives AttackMove to base two followed by queued AttackMove to the main. A third-base wave receives AttackMove to base three, then queued AttackMoves to base two and the main. Waves launched before a time boundary retain their route. Only unlaunched recruits move to the new staging line; launched units keep their route unless borrowed by the response controller. Pressure retains ordinary attack-move combat after launch; Rush’s extractor-raiding flow is not part of this copied staging policy. Eligible offensive Riflemen additionally use the shared pull-back helper while staging or attacking outside the active response. Response ownership has priority over pull-back orders. Active retreats cannot receive staging or launch orders. Released staging members resume their slots immediately; released launched members receive their original wave route again, including its queued lower-base objectives. A later phase boundary does not replace that saved route. Construction-clearance ownership continues to take priority. Tanks and Panzerfausts also participate in the response.
Pressure includes a Training Centre in its initial tech path so its infantry research does not wait for the Tank transition. After observing nine newly trained Riflemen, it queues Panzerfausts on an owned Training Centre, including an unfinished or currently researching one. The match-local counter excludes starting Riflemen, retains casualties, and survives the Rush handoff; only owned units observed in player snapshots count. Research waits for authoritative completion, prerequisites, and payment. Once the upgrade completes, Pressure stops issuing new Rifleman orders, disables Rifleman repeat, and enables Panzerfaust repeat on every completed Barracks, including replacements. Already paid or queued Riflemen finish normally. Tank production remains under the existing policy; Pressure disables dedicated home Machine Gunner production. New Panzerfausts join Pressure’s infantry staging line and its normal arrival-counted waves. This policy and its state are independent of Rush.
Pressure expands up to five Resource Depots. It uses the SDK’s player-relative ranked base sites, skips unreachable sites, original player starts, and sites with known owned/allied/enemy or remembered Depot evidence, and first tries a Resource Depot centered on the selected site’s public map landmark. If that footprint is blocked or otherwise invalid, it uses the existing nearby footprint search covering the cluster’s available resources. Rush inherits this center-first policy after its Pressure handoff. Unknown occupancy remains unknown; ordinary authoritative placement validates each build. Blocked or exhausted sites yield to the next usable ranked site. A map with no usable site does not halt Tank production while saving for an impossible expansion.
The second Vehicle Works retains its three-completed-Depot gate and float above 500 Steel and 325 Oil. After both Vehicle Works complete, fourth and fifth Depots are surplus purchases at the full 450 Steel / 100 Oil cost. Pressure keeps queuing Tanks from resources above that purchase or a travelling Depot’s committed cost; it does not pause Tank production to save for these bases. Once five Depots are complete, the cap rises to four Vehicle Works: the same float threshold allows one additional Vehicle Works at a time, subject to the ordinary pending-build and placement limits. Completed Works, foundations, and Works planned in the current decision count toward the cap; losing a Works opens a replacement slot. All completed Vehicle Works then enable standing Tank production. Existing queues finish first; new manual Tank orders stop so they do not compete with repeat production. New and replacement Works receive the repeat allocation once, including after a later base loss. Extra Works beyond two require five currently completed Depots; lost bases can be replaced up to the five-base target.
Rush AI
rush_ai runs RushStrategy through the typed SDK and canonical controller cadence. The four
starting Riflemen join the same staging system as later infantry, facing the first living enemy
start. The starting Engineer advances toward that start between builds, stopping outside a 30-tile
exclusion radius. Movement and full construction footprints use a two-tile buffer; straight
construction approaches retain at least one tile of clearance beyond the exclusion radius. At the
standoff line, remaining buildings can be placed beside or behind the Engineer rather than
advancing closer. A near-boundary pathing correction runs before construction/travel handling. As
resources permit, the Engineer builds a Barracks, a Training Centre, then two more Barracks,
completing one building before starting the next. Failed sites are retried. Rush disables the
shared worker-retreat reflex; a lost Engineer is not replaced.
Every completed Barracks uses an attack-move rally to the staging line. Initially it alternates Riflemen and Machine Gunners through standing production allocations. When the first Training Centre completes, all Barracks disable Rifleman repeat without cancelling existing paid or queued Riflemen; later Barracks start with Machine Gunner repeat only. Methamphetamines is queued on the first decision that observes the Training Centre scaffold, followed by Entrenchment. Panzerfausts is queued on the first decision at or after two minutes (3,600 simulation ticks), behind earlier research. Once it completes, each Barracks alternates Machine Gunners and Panzerfausts. The home Resource Depot auto-builds Steel Mines and Pump Jacks to sustain income during the opening.
Thirty seconds after its fifth wave launch, Rush cancels all queued production and standing allocations at the two surviving Barracks nearest the first living enemy start, retaining at least one rear Barracks if fewer than three survive. It then hands over to the full Pressure AI economy, defense, production, and wave controller on the normal decision cadence. Retired Barracks remain idle; Pressure may use the rear Barracks and any new producers. Existing units and construction survive, while Rush wave memory is discarded. Losing its only Engineer independently arms the same thirty-second recovery handoff; Pressure can then replace the Engineer and rebuild income. Independently, cumulative owned unit and building losses worth at least 1,000 Steel trigger an immediate handoff, even before the first wave launches. This uses the SDK’s nominal Steel loss value (excluding Oil, cancellations, refunds, and administrative removals) and bypasses either thirty-second grace period, so contested staging cannot trap Rush indefinitely. Rush suspends new wave launches during that recovery grace period, preserving Rush micro for already launched units without launching a cohort just before the switch. Later waves do not postpone a handoff already armed by wave five; the earlier of the wave and recovery deadlines wins. Rush retains its original two-minute Panzerfaust gate. After handoff, Pressure uses the cumulative Rifleman production milestone for research while retaining its timed target selection and wave-size doubling. The requested Rush or AI 2.3 match identity remains unchanged; the active behavior and decision traces identify Pressure after the handoff.
Rush enables the shared wounded-unit pull-back only for Riflemen still approaching their first staging slot. Active retreats temporarily suppress slot movement, which resumes immediately when the retreat ends. Reaching staging hands ownership back to the existing staging and launched flow controllers, even if a unit subsequently moves away. Machine Gunners and Panzerfausts do not use the helper.
Rush picks a staging point 20 world-space tiles from the enemy start along a shortest octile route through the public terrain map, without cutting blocked diagonal corners. The formation is perpendicular to the smoothed local approach direction. Riflemen and Machine Gunners receive stable, spaced slots from the main line’s centre outward. Panzerfausts use a separate parallel line three tiles behind it. Blocked slots are skipped without placing front infantry into the Panzerfaust line. Only owned and currently visible buildings affect slot avoidance. Units attack-move to their slots, engaging enemies en route, and Hold Position after arriving. The first assembled wave attack-moves to the enemy start as soon as Methamphetamines reaches 90% research progress (or is already complete); if nobody has arrived yet, the trigger stays unlocked until arrivals. Subsequent waves require at least five units actually at their slots, rather than counting en-route reinforcements. Each wave launches with one group command. Launched units are never added to a later wave or pulled back to staging, and later production gathers into a fresh cohort.
If a visible enemy targets an unlaunched unit that has reached staging, all staged, unlaunched infantry attack-move to that enemy’s current position. The response remembers attackers while they remain visible, pauses wave launches, and keeps staged membership even when defenders leave their slots. Incoming recruits continue assembling normally; launched waves keep their own orders. Once all remembered attackers disappear or die, defenders return to their assigned slots and normal arrival-based wave launches resume. Unrelated visible enemies do not prolong the response.
AiActions::queue_research emits an ordinary research queue request without requiring or
reserving its eventual cost. Unlike the affordable research helper, it permits construction-
time/unpaid queues; authoritative simulation validation and payment still apply.
Launched Rush infantry raid known enemy extractors. The flow seeds reachable firing positions around recipient-visible or remembered Pump Jacks and Steel Mines, prioritizing any safely reachable Pump Jack over Steel Mines, then choosing the shorter safe route within that priority. Each weapon range uses its own shared field; the AI accounts for the extractor footprint and keeps a firing-distance margin. Visible extractors receive ordinary explicit Attack commands only from a clear, in-range firing position. Remembered extractors are scouting destinations, never direct attack targets. With no known extractors, the enemy start remains the exploration objective.
Observed armed enemy combat units contribute circular exclusion zones using public base range and nominal DPS, plus the range bonus for visible trench occupation. Hidden upgrades are not inferred. Known all-ground building blockers obstruct the route; extractors and Tank Traps remain walkable for infantry, matching authoritative obstacle classifications. Safe firing positions inside enemy coverage are excluded. Move waypoints suppress opportunistic combat while seeking a safe extractor. A unit already in a fight can escape along the least-exposure route into a region with a safe extractor approach. If no safe approach exists, the weighted field chooses a weaker crossing, moves toward that fight without stopping on buildings, and explicitly attacks a visible combat defender once it is in range. If no defender is currently visible, it uses AttackMove toward the weak approach to reacquire contact. There is no separate damage-triggered re-flow or game combat-rule change.
The flow is reevaluated from fog-filtered observations on the normal AI cadence. Orders are bounded to one per second while following the same movement mode, with immediate mode/objective changes. Last-seen combat contacts expire after five seconds; observed noncombat contacts clear immediately. Fields are shared by units with the same base weapon range. Only launched units are controlled; staging cohorts, the 90% Methamphetamines opening wait, research order, and the Engineer’s 30-tile exclusion radius remain independent of raid target selection.
Profile behavior
AI 2.0 resolves only to the ai_2_0_tank_pressure profile. The retired
ai_2_0_rifle_tank profile is not registered or accepted as an exact selectable profile. Defensive
panic does not override an already-active tech transition, so tank pressure continues its Factory
path during pressure.
AI 2.1 is the original behavior copied into Pressure, one of the AI 2.3 components. It fills in-range Steel and Oil extractor slots over time,
keeps an eight-supply buffer, opens one Barracks, expands to two Resource Depots, and reserves four
Machine Gunners for defense. It begins with Rifleman pressure, then transitions into mixed
Tank/Rifleman pressure once its tank-tech resource threshold is met. After its first Vehicle Works (Factory) completes, it seeks a third Resource Depot using the
existing expansion resource/supply trigger. The third-base step does not require surviving
opening Riflemen; the second-base step retains its four-Rifleman requirement. It requires three
completed Resource Depots before adding its second Vehicle Works at the existing larger resource
float; the Vehicle Works cap remains two. The internal ai_2_1_pre_third_base profile freezes
AI 2.1 from main commit 69d1e29a6 for comparison. Frontal waves stage in cohorts so newly produced units do not immediately
join an already-launched wave.
AI Turtle shares AI 2.1 extractor, supply, and first-Barracks cadence, but uses a two-Rifleman opening and does not launch frontal waves. It prioritizes a Training Centre, an early second Resource Depot, Entrenchment, support technology, Machine Gunners, and Anti-Tank Guns. It identifies up to three own-base chokepoints from the static map analysis, caps Machine Gunner production by planned choke-line staffing, staffs the active enemy-facing lines with Machine Gunners, and places Anti-Tank Guns on an own-side backline. Its staged intents include the two-Rifleman opening. The profile prioritizes the main choke first, can defend a second close-spawn choke, and reinforces under-staffed lines. Staged defenders emit HoldPosition once after reaching their defensive slot rather than repeating the command on every think.
The three legacy profiles are self-contained policy records in the same registry. Each profile selects whether to use the proposal economy manager; AI 2.1, Jeff’s AI, and AI Turtle enable it. None inherits behavior from a retired version or resolves through a second profile name.
Jeff’s AI is the fast-Tank timing profile developed from the standalone local bot workspace. Its
four oldest home Riflemen and two opening Machine Gunners form a six-slot defensive pocket around
the starting Resource Depot: the two outside Riflemen remain on the close flanks, the middle pair
stands forward, and the Machine Gunners occupy mirrored slots slightly behind that middle pair.
The whole pocket rotates toward a terrain-analyzed central base approach when one exists. Crossroads
uses a map-specific wall-aware rotation for both starts: its pocket faces the southwest approach
corridor around the water barriers rather than the blocked direct diagonal or the map centre. Other
open or side-lane starts retain the same shape and rotate toward the map centre.
Later surplus Riflemen fill three lateral columns before adding deeper ranks. Their destinations
reserve at least 2.75 tiles of separation from other home Rifle slots and reject disconnected
terrain and blocked firing lanes. A Machine Gunner below 50% health no longer counts toward the healthy pair and triggers a
replacement. The full Tank tech path starts immediately, Tanks do not wait for Methamphetamines,
and defensive panic does not replace the active armored production plan with infantry. After two
Tanks, one Scout Car takes temporary Factory priority and joins those Tanks as a single
vision-supported attack wave. For active jeffs_ai, once the first Tank exists or is paid in the
Factory queue, the second Resource Depot becomes the next protected oil purchase. Before any
Depot build intent or affordability requirement, two Riflemen beyond the home four advance to
separate posts at the selected natural. The Barracks can fill this six-Rifle minimum without the
usual surplus-steel reserve. While the site is being secured, only the exact Resource Depot cost
is held back; resources above that reserve remain available for Tank and other production.
Construction requires
both guards at their posts and three seconds without visible enemy contact within eleven tiles;
contact or a missing guard resets that interval. The builder uses that same secured footprint.
Once the Depot is complete, the first surplus Tank outside the containment wave and home reserve
forms behind the guards and in front of the Depot. The containment wave keeps its original rally,
the reserved Tank stays at the starting base, and guards may leave their posts to answer contact
near the expansion before returning when the area clears.
On Crossroads, the expansion guards and staged Tank face the same verified route around the water
walls as the starting-base pocket instead of the blocked direct line between player starts.
On either mirrored River start, an armored incident at the mapped natural reinforces to at least
two Tanks and two Riflemen; other maps keep the ordinary value-sized incident response.
The pair stays as the expansion garrison, is replaced after losses, and is excluded from attack
escorts and home incident reassignment. A second Factory, Methamphetamines, and other optional
spending retain their opening gates. The profile uses the shared decision and action
layers, receives only fog-filtered observations, and issues ordinary validated player commands for
spending, placement, production, and combat.
On The River, Jeff’s first expansion uses the upper-right verified Resource Depot footprint at tile
(108, 93) and its footprint-aware rotation (15, 30) from the lower-left start. The map spawns
both Workers east of their starting depot rather than rotating the Worker position, so the
lower-left instruction first moves its builder to the rotated upper-right approach tile and queues
the build. Both sides retry only the verified footprint instead of scanning adjacent blocked tiles.
The override is identified by the map dimensions, start tile, and complete twelve-Steel/three-Oil
natural cluster, so the Classic map’s matching dimensions and start tiles continue to use ordinary
expansion search.
Its local-defense envelope covers every owned building footprint, including incomplete structures, plus reserved sites for submitted build intents. The four-unit defensive pocket remains anchored to the starting Resource Depot so later construction cannot drag it out of shape; only surplus Riflemen use completed core buildings for their standing coverage. When visible enemy material enters the wider envelope, mobile defenders focus the highest-value visible target at the threatened footprint. Tanks and Panzerfausts answer armored contacts first, fully entrenched Riflemen remain in place, and an understrength Rifle-only group does not make a sacrificial intercept. Lost contact creates only a bounded two-second search incident; reaching the last contact point without reacquiring the enemy or reaching the timeout returns the units to normal defensive staging. A containment push may start once its two-Tank, one-Scout-Car core and two nearby Riflemen are available even if the generic frontal-wave size is not yet filled. The four oldest Riflemen remain reserved for the home pocket. Escort selection uses only other completed, free-for-combat Riflemen within twelve tiles of the group, takes at least two when available and up to half of those candidates, capped at six, and reselects nearby escorts when assembly times out rather than waiting on a distant reservation. The screen stands two tiles ahead of the Tanks with two-tile lateral spacing; groups larger than four use a staggered second rank so the screen covers the Tank frontage without putting all six Riflemen into one line.
Before departure, both Tanks and the Scout Car assemble around the Tanks’ center. Assembly uses an
explicit Assemble intent: its repositioning and hold commands supersede cached staging and recent
attack suppression in the live controller. The formation planner still owns the two-second retry
cadence; ordinary defensive staging remains deduplicated. Assembly does not count as launching an
attack and leaves no staging-cache entry that could block defensive retasking when assembly ends.
Spectator decision traces label this phase assemble. Exact formation
slots can launch immediately; after eight seconds the compact vehicle core plus two nearby
Riflemen is sufficient, and after twelve seconds the compact vehicle core is a hard upper bound on
assembly even if no usable screen exists. On The River, the opening group then guards its mirrored
rally for thirty seconds and requires five clear seconds after nearby contact before beginning the
crossing, giving forward pressure a chance to meet the grouped force while Smoke is available.
At the more exposed lower-left natural, any defensive incident that commits a Tank also commits its
available Tank partner and two available Riflemen; upper-right keeps its established response.
The group follows cached passability and clearance-aware
six-tile route bounds instead of straight-line hops. A four-second waypoint timeout drops distant
Rifleman laggards and advances only after the Tanks are compact and the Scout Car is close. Formation
commands refresh at most every two seconds while a waypoint is unchanged. On contact, the Tanks
stop as a shared firing core, the Riflemen occupy their spread screen, and the Scout Car remains
behind; a two-second contact memory prevents rapid movement/hold oscillation. A material home-defense
panic recalls every surviving member of the active cohort to the visible local threat and cancels
its outbound route. This active-cohort control bypasses the ordinary new-wave exclusion window so
the launched force remains under formation control without admitting newly produced units. The internal
jeffs_ai_beta_967078d profile preserves the beta build’s prior frontal controller for local arena
comparisons. jeffs_ai_pre_defense_envelope freezes the preceding Jeff defense policy; neither is
exposed in the lobby selector.
After the three-second stationary-range ramp, Jeff issues explicit Tank attacks only against a visible target that every Tank can reach from its current position. An out-of-range retained target is cancelled with Hold Position before it can pull one Tank out of the firing core. Anti-Tank Guns, Tanks, and Panzerfausts lead the target order; killable and lower-HP targets break equal-priority ties, and each 60-damage Tank shot is allocated only while the target still needs another shot. Rifle escorts independently cover bounded lateral sectors around their assigned screen slots, prioritize Panzerfausts and Machine Gunners, never explicitly chase Tanks, and return to their slot when no soft threat is inside the four-tile leash.
The Scout Car may use Smoke after the Engineering Complex prerequisite and an actual smoke charge are available and both the cast range and resulting sight lines are safe. The outbound formation also requires a stable Tank focus; a local-defense incident may react immediately so incoming Tank pressure does not bypass Smoke. Defensive Smoke is limited to a selected one- or two-Tank interceptor core; larger defensive Tank groups retain ordinary target acquisition rather than having their whole volley rewritten around a cloud. Candidate Tanks are restricted to the local engagement instead of sorting every globally visible Tank. The normal candidate is the healthy rear Tank while the forward Tank remains exposed. If Jeff’s Tanks are already firing on the rear Tank, the forward Tank becomes the smoke candidate instead. Stale or split pre-command target orders do not veto the cast, because the same decision replaces them with a coordinated volley. Immediately before the cast, the controller rejects smoke that overlaps the exposed focus, an existing cloud, or any Tank’s line to the exposed target. Once launched, the smoked Tank is excluded from volley and local-defense allocation and the Scout is excluded from the subsequent attack order. If only one local enemy Tank is available, Jeff switches fire to another shared-range target when possible; otherwise it briefly holds the grouped Tanks while Smoke gives the rifle screen a protected five-second advance window. If the Scout is just outside range, it may temporarily move to a computed launch point capped at 3.5 tiles ahead of the Tank center and 4.5 tiles laterally. It never follows an unrestricted out-of-range ability order or leaves that bounded envelope to force a cast.
Self-play and arena tools
Matchup, arena, balance, LiveSelfPlay, real-AI tests, and live-AI performance hosts all use that
driver. ProfileBackedScript survives only as a thin AiController adapter for synthetic mixed
script fixtures; its economy-only variant is an explicitly named command-filtering wrapper. It
owns no profile decision memory, map cache, pending builds, placement search, combat-stage state,
or cadence. Synthetic MineOnlyScript retains its explicitly scoped six-tick harness cadence.
This cutover intentionally changes historical offline output. The old adapter invoked both players
at tick zero and then player 1/2 at ticks 5/4 modulo six, used the default away-from-center build
search, and injected no retreat reflex. Canonical invocations begin at ticks 8/7 and repeat every
nine ticks, traces exist only on those decision ticks, retreat commands remain first even between
decisions, and production placement/stage suppression applies. In the canonical seed-7
jeffs_ai versus ai_2_1 9,000-tick lane, the first applied commands are player 2 at tick 8 and
player 1 at tick 9; representative first builds are AI 2.1 Barracks (115,12) at tick 476 and
Jeff Pump Jack (9,14) at tick 513. The lane reaches the tick cap as a draw and its replay verifies
exactly; these values document the new tooling baseline, not a balance guarantee.
The ai-matchup binary runs one fixed-horizon profile-versus-profile match until a starting Resource Depot objective win or the tick cap. A match with no objective winner at the default 25,000-tick horizon is a draw.
cd server
cargo run --bin ai-matchup -- ai_2_1 ai_turtle --seed 7 --ticks 9000 --json
cargo run --bin ai-matchup -- ai ai --ticks 25000
cargo run --bin ai-matchup -- --list-profiles
The ai-arena binary runs side-swapped seed pairs and writes a top-level arena-summary.json plus per-run replay.json, manifest.json, summary.json, decision-trace.jsonl, and brief.md files. Its defaults compare Jeff’s AI against AI Turtle. The manifest records canonical profile IDs and fingerprints, rather than a requested/resolved identity pair.
cd server
cargo run --bin ai-arena -- --candidate ai_2_1 --baseline ai_turtle --seeds 3 --ticks 9000
The repository term 120 game test means scripts/120-game-test.mjs. It requires profile IDs for
the current AI 2.3, pre-change Jeff, and post-change Jeff in that order. The runner builds ai-arena,
runs all three pairings on The River, Schone Tage, Classic, and Crossroads with five side-swapped seeds,
caps parallel work, resumes completed seed jobs when an output directory is reused, and writes
Markdown, JSON, and CSV summaries. Post-change Jeff’s 80 games run first, so the new build’s results
arrive soonest; the 40 AI vs pre-change Jeff games run last.
node scripts/120-game-test.mjs ai_2_3 jeffs_ai_pre_defense_envelope jeffs_ai
Per-seed console progress is off by default. For unattended runs, --background starts the test in
a hidden detached process and returns immediately; --status <output-directory> reads compact
progress from run-config.json without attaching to the simulation. Use --progress only when
per-seed terminal updates are wanted. Background output is retained in 120-game-test.log.
Every full run also emits an agent handoff after the release build. Background launch emits it
immediately. The handoff tells an attached coding agent to stop processing, avoid status/log polls,
and resume once at a conservative all-games-hit-the-tick-cap estimate plus ten percent. It is also
persisted as agent-handoff.json beside the reports so a resumed task has the exact wake time,
status command, and analysis path. The estimate assumes 90 seconds for one 25,000-tick game and
caps effective parallel speedup at eight to account for arena contention; use
--expected-game-seconds to calibrate a materially faster or slower host. When replay verification
is enabled, the estimate conservatively budgets a second full simulation pass for every game.
Scorecards report diagnostic economy, army, building, command, attack, damage, death, and milestone data. Material values do not break ties. Replay artifacts remain the source of player intent; decision traces are diagnostic output only.
Live match horizon and elimination
A normal room with at least two AI seats and no active humans is an AI observation session. Rooms with one or zero active humans skip the pre-match countdown and start immediately. The session remains interactive for spectators and follows the normal replay flow, but resolves no later than tick 25,000. A primary-base elimination on that tick takes precedence; otherwise the result is a draw.
AI players count as ordinary match players. A human-plus-AI match is a real match, while a lone human with no AI remains a sandbox. AI-only matches use the same starting-primary-base objective as self-play. Mixed human/AI matches use the normal live elimination rule, including eliminating an AI that has no units left even if it still owns buildings.