docs: architecture, roadmap and agent guide

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 14:54:09 +01:00
commit db59396e6a
3 changed files with 297 additions and 0 deletions

42
CLAUDE.md Normal file
View File

@ -0,0 +1,42 @@
# Village Politics: backend
A browser strategy game in the style of Tribal Wars (Die Stämme), with one big difference: a village has a fixed amount of building space instead of a fixed building list. Players choose what goes in that space, and multiple instances of a building type are allowed, so one village can become a farming village and another a military village.
This repo is the Laravel backend. The Nuxt client is in `../game-village-politics-frontend`.
Read [docs/architecture.md](docs/architecture.md) before you change game logic, the data model, or the event engine. The milestone plan is in [docs/roadmap.md](docs/roadmap.md). Tick its boxes as work ships.
## Game rules for the code
- **Server-authoritative.** The client sends only intents, such as `village.build {village_id, type, x, y}`. The server checks ownership, cost, space, queue, and requirements, and computes every cost, duration, and timestamp itself.
- **Lazy state.** Resources, loyalty, and recruit progress are `stored + rate × elapsed`. Before any change, settle the current value into the row, then apply the change.
- **Timed effects** are rows in `game_events`. The `game:events` worker processes them in `(fire_at, id)` order. Game logic is never a delayed queue job, because those don't keep order.
- **Config, not literals.** Game values live in `config/game/*.php` plus per-world overrides in `worlds.config`. Game code reads them through `WorldConfig`.
- **`app/Game/` is pure PHP**: no Eloquent, no facades, no `now()`. Time and config come in as arguments, so every formula can be unit tested.
- **No locks.** A village may fail, but it must never get stuck. Any new rule or config value needs a way out and, where possible, a `ConfigLint` check. The list is in the "No locks" section of the architecture doc.
- **Mutations** catch up the village's due events first. Then they run in a transaction with `lockForUpdate()` on the village row.
## Tests
Every formula in `app/Game/` gets a Pest unit test. Every action gets a feature test that moves time with `Carbon::setTestNow()`. A milestone is done when its tests are green.
## WebSocket API
The API is WS-first, the same as learn-atc. It uses native controllers in `app/Websocket/Controllers/` (blax-software/laravel-websockets). Load the `blax-websockets` skill before you write a controller or a push. HTTP is used only to log in, register (issues the Sanctum bearer token), and serve health checks. After the engine processes an event, it pushes the change to the owner's sockets with `ws_whisper`.
## Commands
```bash
docker compose up -d
docker compose exec app php artisan test # all tests
docker compose exec app php artisan test --filter=Combat # one area
docker compose exec app php artisan migrate:fresh --seed # reset local world
```
The `game:events` worker and the WS server run as supervisor programs in the `app` container (`docker/supervisor/`). Restart the container after you change engine or WS code, because both cache code at boot.
Local: `https://server-village.localhost.at` (HTTP), `wss://ws-server-village.localhost.at` (WS).
## Commits
Make small commits, one concern each, with prefixes like `feat:`, `fix:`, `test:`, `docs:`, `chore:` (the same style as learn-atc).

187
docs/architecture.md Normal file
View File

@ -0,0 +1,187 @@
# Architecture
## Repos and runtime
| Repo | Stack | Local URL |
|---|---|---|
| `game-village-politics` | Laravel 13, PHP 8.5 (`blaxsoftware/laravel:laravel13`), MySQL, Redis, Pest, Sanctum, blax-software/laravel-websockets | `server-village.localhost.at`, `ws-server-village.localhost.at` |
| `game-village-politics-frontend` | Nuxt 4, TypeScript, `@blax-software/networking`, `@blax-software/i18n` | `village.localhost.at` |
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
Economy/Population.php food budget, capacity, villagers, worker assignment
Economy/Settle.php stored + rate × elapsed, storage caps, food zero-crossing
Buildings/BuildingRules.php cost, time, workers, output per level
Buildings/VillageGrid.php footprint placement and overlap checks
Buildings/BuildQueue.php builders, next unblocked order
Travel/TravelTime.php
Combat/CombatResolver.php
Combat/LootCalculator.php
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 whatever budget soldiers and stationed support leave free. Villagers are the workforce.
- **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 workers as militia for a fixed time (world config). Their buildings run understaffed meanwhile, and the militia return to work automatically when the time ends.
### Workers and staffing
- 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.
### Starvation
When upkeep exceeds income, food stock drains. The engine computes the exact moment the stock reaches 0 and schedules an event there. At that point a grace timer starts (`starvation.grace`, default 24h). If the village is still in deficit when it runs out, units desert in hourly waves until upkeep fits the budget. The order is foreign support first, then own soldiers from the highest upkeep down, then villagers that are not working on farms. Farm workers never desert. The timer resets as soon as income covers upkeep again.
## Village space
- Each village has a grid of `grid_w × grid_h` cells. The world config sets the default (`village.grid`, 10 × 5 = 50 cells). The village row stores its own size, so terrain or specials can change it per village later.
- Each building type has a fixed `footprint` `[w, h]` in config, for example HQ `[3, 3]`, barracks `[3, 2]`, resource buildings `[2, 2]`, and hiding place `[1, 1]`. The level changes only the sprite, never the size.
- Each building instance has its own position `(x, y)` from M1 on. The client may send a position; otherwise the server picks the first free slot. The server validates bounds and overlap either way. Positions are stored from the start because an area budget alone can "fit" a set of buildings that cannot actually be packed onto the grid, and the M6 city view could not draw such a village.
- Levels start at 0. Level 0 is a real, primitive state: the HQ is a tent, storage is open ground, and the farm is gatherers. A new instance is built at level 0.
- 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.
- Demolishing goes through the build queue. It lowers an instance by one level and refunds `demolish_refund` × that level's cost (default 0.5). Below level 0 the instance is removed and its cells are freed.
- The wall has footprint `[0, 0]`: it surrounds the village and takes no space.
A new village starts with HQ 0, storage 0, and farm 0, auto-placed, plus starting resources from world config.
## No locks
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 < its output. |
| 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. |
| Grid full | Demolishing is always allowed, costs nothing, and refunds. Core buildings (HQ, one storage, one farm) cannot go below level 0. |
| Queue blocked | A free builder skips blocked orders. Every order can be cancelled with a refund. |
| Building requirements | Lint: the requirement graph has no cycles, and every building and level is reachable from the start village. |
| Starvation spiral | Deserters leave in the order foreign support, soldiers, non-farm villagers. Farm workers stay, so food income can't collapse. |
| Foreign support eats the host | The host can send any support home at any time. Foreign support deserts first. |
| Levy never returns | Militia return automatically on a timer. |
| All merchants killed | Merchants are trained at the market like units, so dead merchants can always be replaced. |
| Player loses every village | The player can restart on the same world with a fresh village. |
## Config
`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, grid size, staffing k, starvation grace, noble rules, and so on. `WorldConfig` merges the two and is the only reader.
A building entry looks like this (numbers start TW-like):
```php
'timber_camp' => [
'footprint' => [2, 2],
'max_per_village' => null,
'max_level' => 30,
'cost' => ['wood' => 50, 'clay' => 60, 'iron' => 40, 'factor' => 1.25],
'build_time' => ['base' => 900, 'factor' => 1.2], // seconds at world speed 1
'workers' => ['base' => 2, 'factor' => 1.12],
'production' => ['resource' => 'wood', 'base' => 30, 'factor' => 1.163],
'requires' => ['headquarters' => 1],
],
```
## Data model
| Table | Columns |
|---|---|
| `worlds` | name, slug, config json, started_at, ends_at null |
| `players` | user_id, world_id, name, points. unique(user_id, world_id) |
| `villages` | world_id, player_id null (null = barbarian), name, x, y, grid_w, grid_h, wood/clay/iron/food decimal(14,4), resources_at datetime(3), villagers, levy_until null, starving_since null, loyalty, loyalty_at, points. unique(world_id, x, y) |
| `buildings` | village_id, type, level, x, y, priority, workers (assigned, derived on settle) |
| `build_orders` | village_id, building_id null (null = new instance), type, action (build/upgrade/demolish), target_level, x, y, cost json, position, builder null, starts_at null, finishes_at null, game_event_id null |
| `unit_stacks` | village_id (where they stand), home_village_id (owner), unit, count. unique(village_id, home_village_id, unit) |
| `recruit_orders` | village_id, building_id, unit, count, done, seconds_per_unit, starts_at, finishes_at, game_event_id |
| `food_deliveries` | village_id, amount, delivered_at. Feeds the 24h import average; each row's expiry is an event |
| `movements` | world_id, player_id, type (attack/support/return/trade), mode, origin_id, target_id, units json, merchants, cargo json, catapult_target, rng_seed, sent_at, arrives_at, visible_at, destroyed_at null |
| `tribes`, `tribe_members`, `tribe_relations` | name, tag; player_id, role; tribe_id, other_tribe_id, state (ally/nap/enemy). Arrives in M6 |
| `reports` | player_id, type, payload json, read_at |
| `game_events` | world_id, type, subject_type, subject_id, fire_at datetime(3), processed_at null, attempts. index(processed_at, fire_at) |
## Event engine
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.
## Movements and encounters
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.
### Travel modes
Each movement has a mode, defined in `config/game/movement.php`:
| Mode | Speed | Visibility radius |
|---|---|---|
| sneaky | much slower | 0 (undetectable) |
| cautious | slower | small |
| normal | 1.0 | normal |
| fast | faster | large |
| fighting march | much faster | very large |
The visibility radius decides two things:
- **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
Combat uses the TW model. Attack strength is split into infantry, cavalry, and archer. Defense is weighted by the attacker's composition. Then the wall bonus applies, plus morale and luck (±25%, from world config). Losses follow `(weaker / stronger)^1.5`. Rams lower the wall before the fight, catapults hit a building after it. All of this lives in `CombatResolver` as a pure function and is tested with fixed luck.

68
docs/roadmap.md Normal file
View File

@ -0,0 +1,68 @@
# Roadmap
Each milestone ends with tests green, `ConfigLint` green, and something playable in the plain UI.
## M1: Village, economy, buildings
- [ ] Backend scaffold: Laravel 13, Docker Compose with Traefik, MySQL, Redis, Pest, Sanctum, laravel-websockets
- [ ] Frontend scaffold: Nuxt 4, TS, `ssr: false`, WS client, i18n (en), email + password login/register
- [ ] `WorldConfig` plus `config/game/world.php`, `economy.php`, `buildings.php`. Core set: headquarters, storage, farm, timber camp, clay pit, iron mine, hiding place, wall, rally point
- [ ] `ConfigLint` with the lock checks from architecture.md
- [ ] Migrations and models: worlds, players, villages, buildings, build_orders, game_events
- [ ] Seeders: default world (speed 1) and dev world (speed 100)
- [ ] `Production` + `Settle` (base trickle, staffing curve, storage caps) with unit tests
- [ ] `Population` (food budget, villagers, worker assignment by priority) with unit tests
- [ ] `BuildingRules` (cost, time, workers, output, instance_cost_factor, levels from 0) with unit tests
- [ ] `VillageGrid` (per-type footprints, bounds, overlap, auto-place, unique types) with unit tests
- [ ] `BuildQueue` (builders by HQ level, next unblocked order) with unit tests
- [ ] Event engine: `game_events`, `game:events` worker, per-village catch-up, idempotent handlers
- [ ] Actions: join world (HQ 0, storage 0, farm 0), build, upgrade, demolish with refund, cancel with refund, set priority. Feature tests with time travel
- [ ] WS controllers `village.show|build|upgrade|demolish|cancel|staff` and a `village:updated` push
- [ ] UI: resource bar with projected values, population and food budget, building table with staffing, grid as a plain table of cells, build queue with builders and countdowns
## M2: Map and barbarian villages
- [ ] Map generation and spawn placement
- [ ] Barbarian villages: seeding, optional growth over time (world config)
- [ ] `map.view {x, y, w, h}` with village owner and points
- [ ] UI: coordinate table map with jump-to and village info
## M3: Units, upkeep, starvation
- [ ] `config/game/units.php`: spear, sword, archer, light cav, heavy cav, ram, catapult, nobleman, with food upkeep
- [ ] Barracks, stable, workshop, academy as building instances (several barracks run parallel recruit queues)
- [ ] Recruiting turns villagers into soldiers; lazy per-unit completion
- [ ] Levy: draft workers as militia, automatic return
- [ ] Starvation: zero-crossing event, grace timer, desertion order
- [ ] UI: recruit forms, troops overview, food balance warnings
## M4: Attacks, combat, looting
- [ ] `TravelTime` (slowest unit, distance, unit speed, travel mode) with unit tests
- [ ] Travel modes from `movement.php`; warning time from visibility and detection radius; watchtower
- [ ] Send attack or support (host pays upkeep), send support home, recall, return trips
- [ ] `CombatResolver` and `LootCalculator` (wall, morale, luck, hiding place, rams, catapults) with unit tests
- [ ] Reports
- [ ] Incoming-attack push and UI
## M5: Trade and encounters
- [ ] Market and merchants: caravans with optional escort and travel mode, `food_deliveries` and the 24h import average
- [ ] `EncounterFinder` (closest approach of two linear paths) with unit tests
- [ ] Encounter events: field battles, caravan looting, skipping destroyed groups
- [ ] Barbarian ambushes with seeded RNG
- [ ] UI: trade form, caravan tracking, encounter reports
## M6: Conquering, tribes, multiple villages
- [ ] Loyalty (lazy regeneration), noble drop per hit, conquest transfers the village
- [ ] Coins at the academy, rising noble cost per world config
- [ ] Tribes with ally/NAP/enemy relations, applied at encounter time
- [ ] Village switcher and overviews across villages
- [ ] Inactive villages turn barbarian; restart on the same world after losing every village
## M7: City view
- [ ] Rendered village grid with sprites per building type and level (level 0 = tent, open storage, gatherers)
- [ ] Drag to place new buildings and move existing ones (server validates)
- [ ] Steam build check: static output wrapped in Electron or Tauri