Docker Compose and Traefik labels follow learn-atc. The `app` container runs nginx and php-fpm, plus supervisor programs for the queue worker, the scheduler, the WS server, and `game:events`.
The frontend builds with `ssr: false` for every target. It is a game behind a login, so SSR buys nothing. One static build then serves both the web and a later Steam wrapper (Electron or Tauri). This is a deliberate deviation from learn-atc, which uses SSR on the web.
## Transport and auth
- Accounts are email + password, with no verification for now. Steam login comes later as a second provider.
- HTTP `POST /api/auth/register|login` returns a Sanctum bearer token. The client stores it and passes it as `getAuthToken` to the WS client. The same flow works inside a Steam wrapper, where cookies across origins would not.
- Everything else runs over WS through native controllers (`<prefix>.<method>`), for example `village.show`, `village.build`, `village.demolish`, `village.cancel`, and `village.staff`.
- Push goes to the owner's sockets with `ws_whisper('village:updated', …)` after the engine processes an event. The client then refetches or patches its state.
## Backend layers
```
app/Game/ pure rules: no Eloquent, no now(), fully unit tested
WorldConfig.php defaults from config/game/* merged with worlds.config
Economy/Production.php rates per resource from buildings, staffing, base trickle
ConfigLint.php proves the config has no locks (see "No locks")
app/Actions/ use cases: transaction + lockForUpdate + calls into app/Game
app/Engine/ game_events processing and handlers per event type
app/Websocket/Controllers/ thin: validate, authorize, call an Action, return a Resource
app/Models/ Eloquent
```
## Economy
### Resources
There are four resources: wood, clay, iron, and food. Every village gets a base trickle of wood, clay, and iron (`economy.base_production`, for example 5/h each). That trickle ignores staffing. Buildings add to it. Food comes from farms only. Storage caps all four resources.
Rates are constant between events. Any change to a rate settles the village first: it writes the current amounts and `resources_at = now`, then applies the change. Changes to rates include a build finishing, a worker change, levy, troops arriving or leaving, and a food delivery expiring.
### Population
- **Capacity** is a food budget in food/h: `nominal farm output + 24h average of food delivered to this village`. Nominal means the output at full staffing, which avoids a loop between farms, workers, and capacity (see "No locks"). Capacity is TW-like and instant: no growth timer.
- **Upkeep**: every villager eats `upkeep.villager` (for example 1 food/h), and soldiers eat per unit type (for example spear 1, heavy cav 4, noble 10). Foreign support stationed in the village counts against the host's budget.
- **Villagers** fill instantly up to `economy.villager_share` (default 80%) of the budget, minus what soldiers and stationed support eat. Villagers are the workforce. The other 20% of the farms' output is surplus that goes into storage, so food builds up; expensive units eat into it, and a big enough army pushes the village into starvation.
- **Training a soldier** turns one villager into that unit and costs resources. The soldier's upkeep takes from the budget, so villagers shrink to match, the same as TW farm space.
- **Levy**: the player can draft villagers as militia for a fixed time (`economy.levy.duration`, divided by world speed), one levy at a time. The militia still eat but don't work, so their buildings run understaffed; recruiting can only train villagers who are not drafted. A `levy.ends` event at `levy_until` settles the village and sends them back to work; the player can also end the levy early. If villagers drop below the militia count (a farm torn down, soldiers trained), the militia shrink with them.
- Each building level needs `workers` (config). Villagers are assigned to buildings automatically, highest `priority` first, then evenly. The player sets the priority per building instance.
- Output at staffing ratio `r = staffed / required` is `e^(k·(r−1))`, with `k` from world config (`staffing.k`, default 2.3). Full staffing gives 100% and an empty building gives about 10%, so output never reaches zero.
- Staffing scales resource production, and the HQ's staffing scales build speed.
### Builders
Each village has `builders` (default 2, +1 at the HQ levels listed in world config, for example 10 and 20). All orders share one queue. A free builder takes the first order that is not blocked by an order still running, for example a second upgrade of the same building instance. Build time is scaled by the HQ's level and staffing.
When upkeep exceeds income, the food stock drains. `Starvation::sync()` runs after every mutation and every event: it keeps a `food.runs_out` event at the exact moment the stock reaches 0. Once the stock is empty and the village is still in deficit, `villages.starving_since` is set and the grace timer runs (`economy.starvation.grace`, default 24h, divided by world speed). When it runs out, a `starvation.desertion` wave fires, and further waves follow every `economy.starvation.wave_every` (1h) while the deficit lasts.
A wave takes the fewest units that make income cover upkeep again: support stationed in the village first (whole groups go home, the hungriest first), then own soldiers at home from the highest upkeep down. Villagers are not stored, they follow the food budget, so they never desert; soldiers leaving frees villagers who staff the farms again. If no soldier is left and the village still goes hungry, the levy ends. Units still in training don't desert, but they finish and stand at home by the next wave. The timer stops as soon as income covers upkeep again or food comes in.
- Each village has a building space budget that grows with its headquarters: `space + village.space_per_hq_level × (HQ level − 1)` (defaults 40 and 20, so 40 at level 1, 60 at level 2). The village row stores its own base `space`, so terrain or specials can change it per village later. The new space arrives when an HQ level finishes; a queued HQ demolition already counts, and the HQ can't be demolished below what stands.
- Each building type takes a fixed `space` from config, for example HQ 9, barracks 6, resource buildings 4, and hiding place 1. The level changes only the look, never the space. A building fits when the space of all buildings plus new buildings still in the queue, plus its own, stays within the budget. The space is reserved when the order is queued.
- There are no tiles and no stored positions. The client draws the village as a low-poly isometric diorama and lays the buildings out itself (HQ in the centre, the rest around it), so where a building stands is presentation, not game state.
- Levels start at 1, as in Die Stämme, and a new instance is built at level 1. Every per-level formula uses `level − 1` as the exponent of its factor, so level 1 has the base values.
- Multiple instances per type are allowed. `max_per_village` limits types that must stay unique (HQ, rally point, wall). `instance_cost_factor` makes the n-th instance of a type more expensive, so many cheap copies don't beat upgrading.
- Basic buildings have no requirements: everything in the core set, the wall included, can be built from the start. Only advanced buildings get `requires` (type => minimum level of any instance), for example the academy (Adelshof) needs the headquarters and a barracks (Kaserne). A build option lists what is still missing.
- Demolishing goes through the build queue. It lowers an instance by one level and refunds `demolish_refund`× that level's cost (default 0.5). Taking level 1 down removes the instance (an order with target level 0) and frees its space.
Units live in `config/game/units.php` (Die Stämme-like stats): the building type that trains them, cost, food `upkeep` per hour, `build_time` per unit, attack, defence per class, speed and carry (both used from M4), and `requires` (building type => level).
- Barracks (spear, sword, archer), stable (light and heavy cavalry), workshop (ram, catapult) and academy (nobleman) are ordinary building instances. Each instance runs its own recruiting queue, so two barracks train side by side. Requirements: stable needs barracks 3, workshop barracks 5, academy headquarters 5 and barracks 1; the barracks itself needs nothing.
- Recruiting pays the full cost up front and takes the villagers at once: units in training count against the food budget like trained ones, so villagers shrink immediately and food income doesn't change while they train. A village can't queue more units than it has villagers for (`count × upkeep ≤ villagers`).
- An order's times are fixed when it is queued: it starts when the previous order at that building ends (or now), and one unit takes `build_time / speed / (1 + recruit_speed_per_level × level) / staffing`. Units arrive lazily, `done = floor(elapsed / seconds_per_unit)`, and every read or action moves them into `unit_stacks`; a `recruit.finished` event settles the rest.
- Cancelling refunds the untrained units in full and moves later orders at that building forward. Tearing a military building down refunds what it was still training.
A village may fail through war or bad play, but it must never get stuck. Every lock below has a way out in the rules, and each one marked "lint" is proven by `ConfigLint`, which runs as a Pest test against the default config and every world's overrides.
| Lock | Rule that prevents it |
|---|---|
| No villagers, no food | Farm 0 (gatherers) has nominal output > 0, so capacity is never 0. Villagers fill instantly. Wood, clay, and iron trickle regardless of staffing. |
| Farm, workers, and capacity feeding each other | Capacity uses nominal farm output, not actual output. Farms are staffed before every other building. Lint: each farm level's worker upkeep <itsoutput.|
| Next upgrade costs more than storage holds | Lint: for every building and level, the cost fits the storage cap reachable without that building, and storage's own next level fits its current cap. |
| Building space full | Demolishing is always allowed, costs nothing, and refunds. Core buildings (HQ, one storage, one farm) cannot go below level 1. Lint: the start buildings fit the space, and every type fits next to them. |
| Starvation spiral | Deserters leave in the order foreign support, soldiers, then the levy ends. Farms are staffed first, so food income recovers as soldiers leave. |
`config/game/world.php`, `economy.php`, `buildings.php`, `units.php`, and `combat.php` hold the defaults. `worlds.config` (JSON) overrides any key, the way Die Stämme world settings do: speed, unit speed, morale, night bonus, beginner protection, map size, builders, refund rate, building space, staffing k, starvation grace, noble rules, and so on. `WorldConfig` merges the two and is the only reader.
Delayed queue jobs give no global order and can fire late or get lost. When an attack and a wall upgrade on the same village fall in the same second, the order decides the result. So:
1. Every timed effect writes a `game_events` row: `type`, `subject`, `fire_at` (datetime(3)), and `processed_at`.
2. The `game:events` worker loops. It takes due rows in `(fire_at, id)` order, locks the subject village, runs the handler, and sets `processed_at`, all in one transaction. When nothing is due, it sleeps until the next `fire_at`, at most 1 s.
3. Every read or action on a village first runs `CatchUp::village($id, now)`, which processes that village's due events inline. A lagging worker therefore never shows stale state, and tests need no worker at all.
Handlers are idempotent per event row: the transaction plus `processed_at` guards against double execution.
## Map
The map is square (`map.size`, default 1000 × 1000) and split into TW-style continents of 100 × 100 for orientation (K55). New players spawn on a ring that moves outward from the center as the world fills. Barbarian villages fill the gaps, grow slowly (world config), and a village whose player has been inactive for too long turns barbarian.
`map.view {world_id, x, y, w, h}` returns the villages in a `w × h` window (at most `map.max_view` per side) centred on `x|y`, kept inside the map; without a centre it opens on the player's first village. Each village comes with its coordinates, continent, name, points, owner (null for barbarians) and whether it is the player's own. The client draws it like the Die Stämme map: a top-down field grid with coordinate rulers and continent lines.
New players spawn on the spawn ring (`SpawnRing`): radius `start_radius + sqrt(players / (π · density))`, ± `band` fields, at a random angle, never on a field next to another village. `SeedBarbarians` scatters `map.barbarians.count` barbarian villages with random low building levels within `radius` of the centre, once per world, and every barbarian village has a `barbarian.grows` event: every `growth.every_hours` (at world speed) one building goes up a level, up to `growth.max_level`.
Every group on the map is a `movement`: an attack, support, return, or trade caravan (merchants, optionally with an escort). It moves in a straight line at constant speed, so its position at time t is a linear interpolation between origin and target.
- The rally point sends an attack or support from the units at home to the village at x|y (`rally.send`; `rally.preview` shows the target, distance and travel time first). A village needs a rally point to send anything. Travel time is the slowest unit's minutes per field × distance / (world speed ×`movement.unit_speed`× mode speed), with the distance as the crow flies.
- The troops leave at once. Their arrival is a `movement.arrives` event on the target, so it runs under the target's lock and in the target's event order; a `movement.spotted` event at `visible_at` only pushes the change. Reading a village first catches up the targets of its own due groups, so the owner never sees a group that should have arrived.
- Within `movement.cancel_window` (10 real minutes) the sender can call a command back. It turns around and takes as long to get home as it had been under way.
- An attack with survivors turns into its own return trip with the loot, taking as long as the way there. Loot that doesn't fit the storage is lost on arrival.
- Support stands in the host village as unit stacks with their own `home_village_id`. The host feeds it (it counts against the host's food budget), and hunger sends it home before any own soldier deserts. The host can send any support home (`rally.sendHome`), and the owner can withdraw it (`rally.withdraw`, a `support.recalled` event on the host's queue); both start a return trip. Groups under way eat nothing.
- Barbarian villages take no support, and own villages can't be attacked.
- Beginner protection: for `combat.beginner_protection` (3 days, divided by world speed) after joining, a player can't be attacked by players and can only attack barbarians themselves.
- Every battle and every arriving support writes reports (`report.index|show|delete|readAll`): for the attacker, the defender, and every player whose support stood in the village. An attacker with no survivors learns nothing about the defence. The village payload carries the unread count, and the engine pushes `village:updated` to every village an event touched (an attacker's home, a supporter's village).
- **Warning time**: a target village sees an incoming movement once it is within `visibility radius + village detection radius`. The engine computes that moment and schedules it as an event. A watchtower raises the village's detection radius. A sneaky movement shows up only when it arrives.
- **Encounters**: another group can only engage a movement that comes within that movement's visibility radius.
### Encounters
- When a movement is sent, `EncounterFinder` (a pure function) computes its closest approach to every active movement in its bounding box. If two groups meet within range, an `encounter` event is scheduled at that exact time.
- A soldier group engages every hostile army or caravan it meets. Groups on a return trip never engage, but they can be engaged. Friendly groups (own, tribe, allies) pass each other.
- An encounter is a field battle: `CombatResolver` without wall or morale. The losing group dies. The winners carry on along their original path and schedule, so later encounters don't need recalculating, and the handler skips encounters whose group no longer exists.
- A caught caravan's escort fights first. If the escort loses, the merchants die and the winners take cargo up to their carry capacity. The rest is lost.
- Barbarian ambushes: a caravan has a small chance per hour of being ambushed, depending on its mode (sneaky never). The roll uses a seeded RNG per movement, so tests are deterministic.
### Diplomacy
Tribes arrive in M6, with ally, NAP (non-aggression pact), and enemy states between them. Until then, every other player is hostile. Hostility is checked at encounter time, not at send time.
Combat uses the TW model, in `CombatResolver` (pure, tested with fixed luck) and `config/game/combat.php`:
- Attack strength is split into infantry, cavalry and archer by each unit's class. Every defender, own or support, counts with its defence against each class, weighted by the attacker's mix. Levied militia defend with `combat.militia.defense` per head.
- The wall at level L adds `basic_defense × L` and multiplies the defence by `factor^L` (20 and 1.037). Rams lower the wall before the battle: each level L down needs `base × factor^(L − 1)` rams (2 and 1.09). Nothing drops below level 1.
- The attack is multiplied by morale and (1 + luck). Luck is drawn evenly from ±`combat.luck` (25%) with the movement's seed, so a replayed event fights the same battle. Morale is `min(1, 0.3 + 3 × defender points / attacker points)` and always 1 against barbarians. Worlds with a night bonus multiply the defence at night.
- The winner loses `(loser / winner)^1.5` of every unit, rounded per stack; the loser loses everything. Dead militia shrink the levy.
- After a won battle, surviving catapults hit the highest instance of the chosen type (headquarters by default) by the same siege rule. A damaged building's queued orders are cancelled with a full refund, since their levels no longer fit.
-`LootCalculator`: survivors carry `carry` per unit. They take wood, clay and iron evenly, above what the hiding places protect (`hides` per resource; instances add up). Food is not looted.