botWebWars/AGENTS.md

291 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# AGENTS.md - botWebWars AI Agent Guide
Welcome to **botWebWars**! This document provides architectural context, component specifications, game rule references, and developer workflows for GenAI coding agents (and human developers) working in this repository.
---
## 1. System Overview
**botWebWars** is an autonomous tactical bot arena built on a **64 × 64 discrete grid** (coordinates `(0, 0)` to `(64, 64)`). Bots register with custom names, colors, and strength values, explore the terrain, negotiate party alliances based on relative strength, maintain squad formations, and battle opposing parties in **3-bout D20 tactical confrontations**.
### Tech Stack
- **Backend**: Python 3.12, FastAPI, Uvicorn, Pydantic v2, WebSockets, Pytest.
- **Frontend**: React 19, TypeScript, Vite, Tailwind CSS v4, Lucide React icons.
- **Deployment**: Multi-stage Dockerfile (Node 22 build -> Python 3.12-slim runtime), Docker Compose.
- **Bots**:
- `botagent`: Python heuristic agent (radar scanning, frontier exploration, deterministic leader negotiation).
- `botagent_ai`: LLM-assisted Python agent (Ollama / LLM-driven strategic negotiation and pathing).
- `botagent_gear`: Vertex AI (Gemini) LLM-assisted agent (Google Cloud Vertex AI / Gemini 2.5 & 1.5 strategic reasoning).
---
## 2. Repository Layout
```
botWebWars/
├── AGENTS.md # This file: AI agent orientation and system manual
├── GAME_RULES.md # Canonical rules of engagement, movement, and scoring
├── README.md # Human-facing overview and quickstart
├── Dockerfile # Multi-stage production container build (frontend + backend)
├── docker-compose.yml # Single-service container composition on port 8000
├── backend/ # FastAPI application & game engine
│ ├── app/
│ │ ├── main.py # FastAPI entry point, CORS, static SPA serving, WebSockets
│ │ ├── game.py # Core game logic, grid state, movement, battle resolution
│ │ ├── models.py # Pydantic schemas (Player, Party, Battle, Move, etc.)
│ │ ├── config.py # App settings & environment configurations
│ │ └── api/
│ │ ├── routes.py # REST endpoints (/api/players, /api/board, /api/parties, etc.)
│ │ └── websocket.py # Connection manager for real-time WebSocket clients
│ ├── tests/
│ │ └── test_api.py # Pytest test suite for game mechanics & API routes
│ └── requirements.txt # Backend dependencies
├── frontend/ # React + Vite + TypeScript application
│ ├── src/
│ │ ├── App.tsx # Main UI shell, turn HUD, control panel, modals
│ │ ├── components/ # Grid, radar, scoreboard, battle log, player controls
│ │ ├── hooks/ # WebSocket connections and state synchronization
│ │ └── types.ts # Frontend TypeScript interfaces mirroring backend models
│ ├── package.json # Frontend dependencies and build scripts
│ └── vite.config.ts # Vite build configuration
├── botagent/ # Heuristic autonomous bot
│ ├── bot_agent.py # Autonomous client using radar, memory, and game API
│ └── README.md # Execution command examples
├── botagent_ai/ # LLM-assisted autonomous bot (Ollama)
│ ├── bot.py # Bot delegating strategic pathing/alliances to an LLM
│ ├── requirements.txt # Dependencies (ollama, requests)
│ └── INSTALL.md # Setup, Ollama configuration, and execution instructions
├── botagent_gear/ # LLM-assisted autonomous bot (Google Vertex AI / Gemini)
│ ├── bot.py # Bot delegating decisions to Vertex AI Gemini
│ ├── requirements.txt # Dependencies (google-auth, requests)
│ ├── SETUP.md # Google Cloud authentication & Vertex AI setup guide
│ ├── INSTALL.md # Installation, virtual environment, and dependency instructions
│ └── README.md # Feature overview and invocation examples
└── examples/ # Reference screenshots and board style designs
```
---
## 3. Game Rules & Mechanics (`GAME_RULES.md` Reference)
When writing bots, backend engine logic, or game simulations, adhere strictly to [GAME_RULES.md](GAME_RULES.md):
### 1. Alliances (Solo vs. Solo)
- When two solo bots encounter each other (adjacent or on same tile), they may form an alliance.
- The bot with **greater strength** (or higher score if tied) becomes the **Party Leader**.
- While alliances are voluntary, larger parties have a statistical advantage in battle.
### 2. Solo vs. Party Encounters
- A solo bot **joins** an existing party if the party leader's strength is >= the solo bot's strength.
- If the party leader is **weaker** than the solo bot, the solo bot refuses to join, and the party engages the solo bot in battle.
### 3. Party vs. Party Battles (3-Bout D20)
- Two opposing parties that encounter each other **must** battle.
- **Bout Resolution**:
- Exactly 3 bouts are conducted.
- In each bout, each party rolls a 20-sided die (D20 between 1 and 20).
- Bout Score = Squad Total Strength * D20 Roll.
- Highest score wins the bout. Best 2-out-of-3 bouts wins the overall battle.
- **Scoring & Penalties**:
- **Winning Leader**: +2 score points.
- **Winning Party Members**: +1 score point each.
- **Losing Leader**: -1 score point, stripped of leadership, removed from party, and respawned at a random open grid coordinate.
- **Losing Party Members**: 0 score penalty; all surviving followers are **absorbed** into the winning party.
### 4. Party Squad Movement
- The party leader chooses movement direction.
- Follower members follow the leader in a single-file line (each member moves to the position vacated by the bot immediately ahead of them) maintaining Chebyshev distance <= 1.
### 5. Terrain Obstacles & Diagonal Squeeze
- Mountains and forests are impassable.
- Bots can squeeze diagonally between adjacent obstacle corners, with strength penalties:
- **Solo bot**: -0.1 strength.
- **Party**: Leader loses -0.2 strength; followers each lose -0.1 strength.
- Moving along outer obstacle edges has no penalty. Minimum bot strength floor is 0.1.
### 6. Game Conclusion
- The game concludes when all bots on the board are united into a **single remaining party**.
- Final rankings/trophies (1st, 2nd, 3rd) are awarded based on **Score** (with **Strength** as the tiebreaker).
---
## 4. Backend & API Specifications
The backend serves both REST endpoints under `/api` and a live WebSocket stream at `/ws`.
### Key REST Endpoints
| Method | Path | Description |
|---|---|---|
| `GET` | `/api/health` | Container healthcheck endpoint |
| `POST` | `/api/players` | Register bot: `{"name": str, "color": str, "strength": int}` |
| `GET` | `/api/players` | List all active players, scores, and positions |
| `GET` | `/api/board` | Full board state (grid, obstacles, players, parties, current turn) |
| `POST` | `/api/board/reset` | Clear board, reset parties, and reset players |
| `GET` | `/api/players/{id}/radar` | Scans surroundings, finds closest bots, identifies allies/opponents |
| `GET` | `/api/players/{id}/memory` | Coordinate history and visited locations |
| `GET` | `/api/players/{id}/available-moves` | Valid movements in all 8 directions (evaluates terrain & obstacles) |
| `POST` | `/api/players/{id}/move` | Execute a move (`{"direction": "N"|"S"|"E"|"W"|"NE"|"NW"|"SE"|"SW"}`) |
| `POST` | `/api/players/{id}/ai-step` | Perform one autonomous decision step via internal game engine |
| `POST` | `/api/players/{id}/pass` | Pass turn to next queued entity |
| `GET` | `/api/turn` | Current turn owner, round number, and turn order |
| `GET` | `/api/parties` | List all parties, leaders, and member IDs |
| `POST` | `/api/parties` | Manually construct an alliance party |
| `POST` | `/api/battles/fight` | Initiate a 3-bout D20 battle between adjacent parties |
### Real-Time WebSocket (`/ws`)
- Automatically broadcasts state changes (`init`, `move`, `battle`, `party_formed`, `turn_change`, `game_over`).
- Client can send ping messages `{"action": "ping"}` and receives `{"event": "pong"}`.
---
## 5. Frontend Architecture
- **Path**: `frontend/`
- **Framework**: React 19 + TypeScript bundled with Vite.
- **Styling**: Tailwind CSS v4.
- **Key Features**:
- Real-time 64x64 board renderer with zoom/pan and custom obstacle textures.
- Live turn indicators, active player highlight, and party squad link lines.
- Radar visualization panel showing target distances and alignment.
- Battle modal showing animated D20 rolls, multipliers, bout winners, and score adjustments.
- Autonomous loop toggle to run rounds continuously from the browser.
---
## 6. Docker & Container Deployment
The application is containerized into a single unified image via [Dockerfile](Dockerfile) and [docker-compose.yml](docker-compose.yml):
1. **Stage 1 (`frontend-builder`)**:
- Base image: `node:22-alpine`
- Installs packages and runs `npm run build` to generate `frontend/dist`.
2. **Stage 2 (`production`)**:
- Base image: `python:3.12-slim`
- Installs backend requirements from `backend/requirements.txt`.
- Copies `backend/` source and static assets from `frontend/dist` into `frontend/dist`.
- FastAPI serves static assets at `/` and `/assets` while mounting API routes at `/api` and `/ws`.
- Built-in container healthcheck calls `curl -f http://localhost:8000/api/health`.
---
## 7. Bot Implementations
### A. Heuristic Bot: `botagent/`
- **Entry File**: `botagent/bot_agent.py`
- **Technique**: Deterministic rule-based autonomous agent.
- **Workflow**:
1. Registers bot via `POST /api/players`.
2. Polls `GET /api/turn` to wait for its turn.
3. Uses `GET /api/players/{id}/radar` to find nearest target.
4. Avoids looping using internal coordinate history.
5. Computes vector direction, evaluates diagonal obstacles, and moves.
6. Evaluates alliances vs. fights strictly according to strength hierarchy.
- **Run Command**:
```bash
python3 botagent/bot_agent.py --name CyberBot --color "#10b981" -s 4 --url http://localhost:8000/api
```
### B. LLM-Assisted Bot: `botagent_ai/`
- **Entry File**: `botagent_ai/bot.py`
- **Technique**: LLM strategic decision maker with deterministic rule safeguards.
- **LLM Integration**:
- Communicates with an LLM backend (configured for local/remote Ollama HTTP API at `/api/generate` with model `gemma4:12b`, or adaptable to OpenAI-compatible endpoints).
- Delegates discretionary decisions to the model:
- Voluntary alliances (whether to ally or keep hunting when solo meets solo).
- Navigation direction toward radar targets while balancing obstacle squeeze trade-offs.
- Mandatory rules (forced battles, forced absorption when weaker than leader) are enforced deterministically by the game engine regardless of LLM preference.
- **Configuration & Environment Variables**:
- `OLLAMA_BASE_URL` / `--ollama-url`: LLM server address (default: `http://192.168.1.220:11434`).
- `OLLAMA_MODEL` / `--ollama-model`: Model identifier (default: `gemma4:12b`).
- `BOT_SERVER_URL` / `-u`: botWebWars backend URL (default: `http://localhost:8000/api`).
- `BOT_NAME` / `-n`: Bot name.
- `BOT_COLOR` / `-c`: Bot hex color.
- `BOT_STRENGTH` / `-s`: Starting strength (1-10).
- **Run Command**:
```bash
export OLLAMA_BASE_URL="http://localhost:11434"
export OLLAMA_MODEL="gemma4:12b"
python3 botagent_ai/bot.py -n MyAIBot -s 4 -c "#8b5cf6"
```
### C. Vertex AI (Gemini) Bot: `botagent_gear/`
- **Entry File**: `botagent_gear/bot.py`
- **Technique**: Google Cloud Vertex AI (Gemini) model reasoning for spatial navigation, minimap analysis, and strategic voluntary alliances.
- **LLM Integration**:
- Communicates with Google Cloud Vertex AI generateContent REST endpoint or Google AI Studio Gemini API.
- Features structured JSON generation (`responseMimeType: application/json`) and system instruction enforcement.
- Supports multiple authentication methods:
- Interactive developer login (`gcloud auth application-default login` or `gcloud auth login`).
- Automated service account keys (`GOOGLE_APPLICATION_CREDENTIALS`).
- Direct API keys (`GEMINI_API_KEY` or `VERTEX_API_KEY`).
- **Documentation**:
- [SETUP.md](botagent_gear/SETUP.md): Google Cloud authentication, project creation, API enablement, and credentials setup.
- [INSTALL.md](botagent_gear/INSTALL.md): Virtual environment and dependency installation instructions.
- [README.md](botagent_gear/README.md): Bot overview, CLI reference, and execution examples.
- **Run Command**:
```bash
python3 botagent_gear/bot.py --name GeminiGear --color "#4285f4" -s 5
```
---
## 8. Common Developer Workflows
### Run with Docker Compose (Recommended)
```bash
docker compose up --build
```
Access UI at `http://localhost:8000`.
### Local Development (Manual Setup)
#### 1. Backend:
```bash
cd backend
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
uvicorn app.main:app --reload --port 8000
```
#### 2. Frontend:
```bash
cd frontend
npm install
npm run dev
```
#### 3. Run Backend Test Suite:
```bash
# Run locally with pytest
PYTHONPATH=backend pytest backend/tests
# Or run via docker container
docker run --rm botwebwars:test pytest backend/tests
```
---
## 9. Guidelines for GenAI Agents Modifying this Codebase
1. **Preserve Rules Fidelity**:
- Any updates to alliance logic, battles, diagonal squeezes, or victory states must match [GAME_RULES.md](GAME_RULES.md).
- Update `GAME_RULES.md` and tests in `backend/tests/test_api.py` whenever game mechanics are modified.
2. **Frontend-Backend Sync**:
- When modifying schemas in `backend/app/models.py`, update matching TypeScript interfaces in `frontend/src/types.ts`.
- Maintain WebSocket payload compatibility between `backend/app/api/websocket.py` and frontend hooks (`frontend/src/hooks/`).
3. **Bot Compatibility**:
- Ensure REST endpoint signature modifications are reflected in `botagent/bot_agent.py`, `botagent_ai/bot.py`, and `botagent_gear/bot.py`.
- Preserve CLI flag compatibility across all bot scripts.
4. **Multi-Stage Build Integrity**:
- If adding frontend build dependencies, verify `Dockerfile` compiles cleanly in stage 1 (`npm run build`) and correctly mounts to `frontend/dist` in stage 2.