Optimized tool selection

Ran `query_graph` 
Completed with input: {
  "question": "AI system architecture components",
  "mode": "bfs",
  "depth": 3
}

Ran `query_graph` 
Completed with input: {
  "depth": 3,
  "mode": "bfs",
  "question": "AI player bot behavior simulation AIManager"
}

Searched for files matching `**/simulation2/components/ICmpAI*`, 4 matches

Ran `get_node` 
Completed with input: {
  "label": "CCmpAIManager",
  "token_budget": "4000"
}

Ran `get_node` 
Completed with input: {
  "label": "CAIWorker",
  "token_budget": "4000"
}

Ran `get_node` 
Completed with input: {
  "label": "ICmpAIManager",
  "token_budget": "3000"
}

Ran `get_neighbors` 
Completed with input: {
  "label": "CAIWorker",
  "token_budget": 5000
}

Read [](file:///Users/hieu/Documents/0ad/source/simulation2/components/ICmpAIManager.h)

Read [](file:///Users/hieu/Documents/0ad/source/simulation2/components/ICmpAIInterface.h)

Read [](file:///Users/hieu/Documents/0ad/source/simulation2/components/CCmpAIManager.cpp#80-80), lines 80 to 220

Read [](file:///Users/hieu/Documents/0ad/source/simulation2/components/CCmpAIManager.cpp#220-220), lines 220 to 620

Searched for files matching `**/simulation/ai/**`, 20 matches

Read [](file:///Users/hieu/Documents/0ad/source/simulation2/components/CCmpAIManager.cpp#620-620), lines 620 to 870

Read [](file:///Users/hieu/Documents/0ad/binaries/data/mods/public/simulation/ai)

Read [](file:///Users/hieu/Documents/0ad/source/simulation2/components/CCmpAIManager.cpp#870-870), lines 870 to 1120

Read [](file:///Users/hieu/Documents/0ad/binaries/data/mods/public/simulation/ai/petra)

Now I have a thorough understanding of the AI system. Here's a comprehensive overview:

## How the AI System Works in 0 A.D.

The AI system is a **script-driven (JavaScript) architecture** where C++ provides the engine infrastructure and JS scripts implement the actual AI logic. It runs on a **per-turn cycle** synchronized with the simulation.

### Architecture Overview

```mermaid
flowchart TD
    subgraph C++ Engine
        ICmpAIManager[ICmpAIManager interface]
        CCmpAIManager[CCmpAIManager component]
        CAIWorker[CAIWorker]
        CAIPlayer[CAIPlayer per AI]
        ICmpAIInterface[ICmpAIInterface - game state]
        CmpPathfinder[Pathfinder data]
        CmpTerritory[Territory data]
        CommandQueue[ICmpCommandQueue]
    end

    subgraph JavaScript AI Scripts
        SharedAPI[common-api SharedScript]
        Petra[petra bot scripts]
    end

    ICmpAIManager --> CCmpAIManager
    CCmpAIManager --> CAIWorker
    CAIWorker --> CAIPlayer
    CAIWorker --> SharedAPI
    CAIPlayer --> Petra
    ICmpAIInterface --> CAIWorker
    CmpPathfinder --> CAIWorker
    CmpTerritory --> CAIWorker
    CAIWorker -->|PushCommands| CommandQueue
```

### Key Components

#### 1. **`ICmpAIManager` / `CCmpAIManager`** — The C++ Entry Point
- **File:** ICmpAIManager.h, CCmpAIManager.cpp
- A simulation system component that manages all AI players.
- Defines the turn lifecycle:
  - `AddPlayer()` — registers an AI for a player (also reveals FoW for the AI, since AIs cheat by seeing the whole map)
  - `RunGamestateInit()` — gathers full game state on first turn
  - `StartComputation()` — called at **end of turn**: gathers game state, passability map, territory map, and tells the worker to compute
  - `PushCommands()` — called at **start of next turn**: pushes computed AI commands into the `ICmpCommandQueue`

#### 2. **`CAIWorker`** — The Computation Engine
- **File:** CCmpAIManager.cpp (inner class, ~L80–L865)
- The core engine that owns:
  - A dedicated `ScriptInterface` (SpiderMonkey JS runtime) in the **same compartment** as the simulation, enabling direct data sharing
  - `m_Players` — vector of `CAIPlayer` objects (one per AI)
  - `m_SharedAIObj` — the shared JS component (loaded from `common-api`)
  - Its own **pathfinder** (`LongPathfinder` + `HierarchicalPathfinder`) so AI can compute paths without blocking the main simulation
  - Passability and territory map grids, entity templates, RNG

- **Computation flow** (`PerformComputation`, L798):
  1. Attaches `passabilityMap` and `territoryMap` to the game state
  2. Runs the **shared component**'s `onUpdate(state)` if present
  3. Calls each `CAIPlayer::Run(state, playerID, sharedAI)` → invokes the JS `HandleMessage` function

#### 3. **`CAIPlayer`** — Individual AI Instance
- Wraps a single AI bot's JS object.
- On `Initialise()`:
  - Loads scripts from `simulation/ai/<aiName>/*.js`
  - Reads `data.json` metadata (module name, constructor, `useShared` flag)
  - Calls the JS constructor with `{player, difficulty, behavior}` settings
- On `Run()`: calls the JS `HandleMessage(state, playerID, sharedAI)` method
- On `InitAI()`: calls the JS `Init(state, player, sharedAI)` method
- Commands posted by JS via `PostCommand()` are collected in `m_Commands`

#### 4. **`ICmpAIInterface`** — Game State Provider
- **File:** ICmpAIInterface.h
- Provides `GetRepresentation()` / `GetFullRepresentation()` — serializes the entire simulation world state into a JS object that AI scripts can inspect (entities, resources, positions, etc.)

#### 5. **JavaScript AI Scripts** — The Actual AI Logic
Located in ai:

- **`common-api/`** — Shared framework used by all AIs:
  - shared.js (`SharedScript`) — shared game state analysis, entity collections
  - gamestate.js — `GameState` class wrapping the raw simulation data
  - entity.js — `Entity` class wrapping individual units/buildings
  - entitycollection.js, filters.js, terrain-analysis.js, map-module.js, technology.js, resources.js, baseAI.js, class.js, utils.js

- **`petra/`** — The default/built-in AI bot:
  - `_petrabot.js` — main entry point
  - `headquarters.js` — top-level strategy coordinator
  - `baseManager.js` / `basesManager.js` — economy/base management
  - attackManager.js / attackPlan.js — military attacks
  - `defenseManager.js` / `defenseArmy.js` — defense
  - `worker.js` — worker task assignment
  - `queueManager.js` / `queue.js` / `queueplan*.js` — production queues (build/train/research)
  - navalManager.js / `transportPlan.js` — naval operations
  - `tradeManager.js`, `researchManager.js`, `diplomacyManager.js`, `victoryManager.js`, `emergencyManager.js`, buildManager.js, garrisonManager.js, startingStrategy.js, mapModule.js, `chatHelper.js`, `config.js`, `entityExtend.js`

### Turn Lifecycle

```mermaid
sequenceDiagram
    participant Sim as Simulation Turn
    participant Mgr as CCmpAIManager
    participant Worker as CAIWorker
    participant JS as AI Scripts (JS)

    Note over Sim: End of turn N
    Sim->>Mgr: StartComputation()
    Mgr->>Mgr: Gather game state (AIInterface)
    Mgr->>Mgr: Update passability & territory maps
    Mgr->>Worker: UpdateGameState(state)
    Mgr->>Worker: StartComputation() [flag: not computed]

    Note over Sim: Start of turn N+1
    Sim->>Mgr: PushCommands()
    Mgr->>Worker: GetCommands()
    Worker->>Worker: WaitToFinishComputation()
    Worker->>JS: SharedScript.onUpdate(state)
    Worker->>JS: Each AIPlayer.HandleMessage(state, player, sharedAI)
    JS-->>Worker: PostCommand() calls
    Worker-->>Mgr: Return command sets
    Mgr->>Sim: Push commands into ICmpCommandQueue
```

### Key Design Points

1. **AI sees everything** — `AddPlayer()` calls `SetLosRevealAll(player, true)`, so AIs ignore fog of war (simplifies AI logic).

2. **Shared compartment** — The AI's `ScriptInterface` shares the simulation's JS compartment, allowing efficient data passing via structured clone without cross-compartment marshalling overhead.

3. **Own pathfinder** — The AI worker has its own `LongPathfinder` and `HierarchicalPathfinder` instances, so AI path queries don't interfere with the real-time simulation pathfinder.

4. **Deterministic serialization** — The entire AI state (RNG, player objects, commands, pathfinder grids) is serialized/deserialized for savegames and multiplayer sync.

5. **Pluggable AI** — Any subdirectory under `simulation/ai/` with a `data.json` and `.js` files can be a new AI. `GetAIs()` enumerates available AIs for the UI.

6. **Shared component pattern** — The `common-api` `SharedScript` runs once per turn and pre-processes game state, so individual AI players can share expensive computations (entity filtering, terrain analysis).
