vishiyash commited on
Commit
741c8b0
·
0 Parent(s):

deploy: yvishi/ats cleaned branch

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .claude/settings.local.json +9 -0
  2. .dockerignore +12 -0
  3. .env.example +3 -0
  4. .env.hf_space.example +14 -0
  5. .gitignore +48 -0
  6. Dockerfile +48 -0
  7. README.md +660 -0
  8. __init__.py +1 -0
  9. atc_colab_adapt.ipynb +906 -0
  10. atc_env/__init__.py +8 -0
  11. atc_env/client.py +61 -0
  12. atc_env/models.py +72 -0
  13. atc_env/server/__init__.py +0 -0
  14. atc_env/server/app.py +32 -0
  15. atc_env/server/atc_environment.py +208 -0
  16. constants.py +164 -0
  17. domains/__init__.py +52 -0
  18. domains/icu.py +457 -0
  19. engine.py +363 -0
  20. graders.py +471 -0
  21. models.py +266 -0
  22. multi_agent/__init__.py +4 -0
  23. multi_agent/adapt.py +399 -0
  24. multi_agent/environment.py +782 -0
  25. multi_agent/generator.py +711 -0
  26. multi_agent/inference.py +1243 -0
  27. multi_agent/models.py +509 -0
  28. multi_agent/supervisor.py +104 -0
  29. multi_agent/visual_events.py +101 -0
  30. openenv.yaml +153 -0
  31. planner.py +185 -0
  32. pyproject.toml +54 -0
  33. results/benchmark_scores.json +31 -0
  34. scripts/benchmark_results/.gitkeep +0 -0
  35. scripts/benchmark_results/fixed_icu/episode_00000.json +620 -0
  36. scripts/benchmark_results/kimi_k26_atc/episode_00000.json +47 -0
  37. scripts/benchmark_results/kimi_k26_icu/episode_00000.json +53 -0
  38. scripts/benchmark_results/qwen25_1p5b_atc/episode_00000.json +47 -0
  39. scripts/benchmark_results/qwen25_1p5b_icu/episode_00000.json +66 -0
  40. scripts/benchmark_results/results_20260407_161519.json +245 -0
  41. scripts/benchmark_results/results_20260407_171222.json +316 -0
  42. scripts/benchmark_results/summary_20260407_161519.txt +9 -0
  43. scripts/benchmark_results/summary_20260407_171222.txt +9 -0
  44. scripts/check_release_hygiene.sh +34 -0
  45. scripts/deploy_hf_space.py +209 -0
  46. scripts/ping_env.py +30 -0
  47. scripts/pre_submission_validate.sh +26 -0
  48. scripts/run_graders.py +56 -0
  49. scripts/run_local_checklist.ps1 +151 -0
  50. scripts/smoke_reward_validation.py +134 -0
.claude/settings.local.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(py -3.14 generate_doc.py)",
5
+ "WebFetch(domain:github.com)",
6
+ "WebFetch(domain:raw.githubusercontent.com)"
7
+ ]
8
+ }
9
+ }
.dockerignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .pytest_cache
3
+ .venv
4
+ __pycache__
5
+ *.pyc
6
+ tests
7
+ .codex
8
+ .github
9
+ reference
10
+ node_modules
11
+ space_frontend/node_modules
12
+ space_frontend/dist
.env.example ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ API_BASE_URL=https://your-llm-endpoint/v1
2
+ MODEL_NAME=your-model-name
3
+ HF_TOKEN=your-secret-token
.env.hf_space.example ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Space deployment template for this project.
2
+ # Copy to .env.hf_space.local (or source directly) and set only HF_TOKEN.
3
+
4
+ # Your target Space (from https://huggingface.co/spaces/keshaf/kesh_ai)
5
+ HF_SPACE_ID=keshaf/kesh_ai
6
+ HF_SPACE_PAGE_URL=https://huggingface.co/spaces/keshaf/kesh_ai
7
+ HF_SPACE_URL=https://keshaf-kesh-ai.hf.space
8
+
9
+ # Required inference/runtime variables for submission spec.
10
+ API_BASE_URL=https://router.huggingface.co/v1
11
+ MODEL_NAME=Qwen/Qwen2.5-72B-Instruct
12
+
13
+ # Set this to a real token before deploying.
14
+ HF_TOKEN=hf_xxx_replace_me
.gitignore ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules/
2
+
3
+ # Python caches and build artifacts
4
+ __pycache__/
5
+ .pytest_cache/
6
+ .mypy_cache/
7
+ .ruff_cache/
8
+ .ipynb_checkpoints/
9
+ *.pyc
10
+ *.pyo
11
+ *.pyd
12
+ *.so
13
+ *.egg-info/
14
+ build/
15
+ dist/
16
+
17
+ # Virtual environments
18
+ .venv/
19
+ venv/
20
+ env/
21
+
22
+ # Secrets and local env files
23
+ .env
24
+ *.env
25
+ .env.hf_space
26
+ .env.hf_space.local
27
+
28
+ # Local/editor files
29
+ .vscode/
30
+ .idea/
31
+ .claude/
32
+ *.swp
33
+ *.swo
34
+ .DS_Store
35
+
36
+ # Logs and runtime outputs
37
+ *.log
38
+ logs/
39
+ slurm-*.out
40
+ slurm-*.err
41
+
42
+ # ML/training artifacts
43
+ wandb/
44
+ unsloth_compiled_cache/
45
+ outputs/
46
+
47
+ # Misc local scratch files
48
+ comman.txt
Dockerfile ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ── Stage 1: Vite production bundle ──────────────────────────────────────────
2
+ FROM node:22-bookworm-slim AS frontend
3
+ WORKDIR /build
4
+ COPY space_frontend/package.json ./
5
+ RUN npm install --ignore-scripts
6
+ COPY space_frontend/ ./
7
+ RUN npm run build
8
+
9
+ # ── Stage 2: API + static Space UI ───────────────────────────────────────────
10
+ FROM python:3.11-slim
11
+
12
+ WORKDIR /app
13
+
14
+ ENV PYTHONDONTWRITEBYTECODE=1
15
+ ENV PYTHONUNBUFFERED=1
16
+ ENV PIP_NO_CACHE_DIR=1
17
+ ENV API_BASE_URL=https://router.huggingface.co/v1
18
+ ENV MODEL_NAME=Qwen/Qwen2.5-72B-Instruct
19
+ ENV HF_TOKEN=
20
+ ENV PYTHONPATH=/app
21
+ ENV PATH="/app/.venv/bin:${PATH}"
22
+ ENV PYTHONUTF8=1
23
+ ENV PYTHONIOENCODING=UTF-8
24
+
25
+ RUN apt-get update \
26
+ && apt-get install -y --no-install-recommends build-essential curl \
27
+ && rm -rf /var/lib/apt/lists/*
28
+
29
+ COPY pyproject.toml uv.lock README.md openenv.yaml /app/
30
+ COPY __init__.py constants.py client.py engine.py graders.py inference.py models.py planner.py tasks.py /app/
31
+ COPY multi_agent /app/multi_agent
32
+ COPY atc_env /app/atc_env
33
+ COPY domains /app/domains
34
+ COPY server /app/server
35
+ COPY scripts /app/scripts
36
+ COPY training /app/training
37
+
38
+ RUN pip install --no-cache-dir uv \
39
+ && uv sync --frozen --no-dev
40
+
41
+ COPY --from=frontend /build/dist /app/space_frontend/dist
42
+
43
+ EXPOSE 8000
44
+
45
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
46
+ CMD curl -fsS http://127.0.0.1:8000/health || exit 1
47
+
48
+ CMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "8000"]
README.md ADDED
@@ -0,0 +1,660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: AirX
3
+ emoji: ✈️
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 8000
8
+ license: mit
9
+ pinned: true
10
+ tags:
11
+ - openenv
12
+ - multi-agent
13
+ - grpo
14
+ - air-traffic-control
15
+ - rlve
16
+ - cooperative-cooperative
17
+ - self-play
18
+ - domain-transfer
19
+ - adapt
20
+ - icu
21
+ - reinforcement-learning
22
+ ---
23
+
24
+ ![OpenEnv](https://img.shields.io/badge/OpenEnv-compatible-blue)
25
+ ![Tasks](https://img.shields.io/badge/tasks-4-green)
26
+ ![Modes](https://img.shields.io/badge/modes-single%20%2B%20multi--agent-orange)
27
+ ![Training](https://img.shields.io/badge/training-GRPO%20%2B%20Unsloth-purple)
28
+ ![ADAPT](https://img.shields.io/badge/ADAPT-domain%20transfer-red)
29
+ ![HF Space](https://img.shields.io/badge/HF%20Space-live-brightgreen)
30
+ ![License](https://img.shields.io/badge/license-MIT-blue)
31
+
32
+ # Shared Runways, Split Intelligence
33
+
34
+ *Multi-agent reinforcement learning for cooperative air traffic control under adversarial curriculum pressure*
35
+
36
+ ---
37
+
38
+ At any major airport, hundreds of aircraft compete for a handful of runways every hour. The arrival manager doesn't know the departure queue. The departure manager doesn't know the landing sequence. Emergencies arrive unannounced. And the definition of "a good plan" shifts every session.
39
+
40
+ We built this coordination problem as a live RL environment — and trained two agents to solve it together.
41
+
42
+ ---
43
+
44
+ ## What Makes This Hard
45
+
46
+ - **Asymmetric information**: The arrival agent (AMAN) sees inbound flights only. The departure agent (DMAN) sees outbound flights only. Neither has the full picture. They coordinate through messages alone.
47
+ - **Shared contested resource**: Both agents assign slots to the same physical runways. Conflicts are penalized. Emergencies must be cleared regardless of the cost to the schedule.
48
+ - **Adversarial pressure**: A `ChallengeGenerator` continuously mutates scenarios using EMA-adaptive difficulty tracking — tasks are never too easy or unsolvable.
49
+ - **Shifting objectives**: A rotating `SupervisorAgent` changes preference profiles each episode (`safety_strict`, `throughput_max`, `fuel_economy`, `emergency_priority`, `fairness_balanced`). Agents cannot overfit to a single metric.
50
+ - **Real physics**: Asymmetric wake turbulence separation (Heavy/Medium/Light), ATFM network slot deadlines, emergency priority overrides. Not a toy grid.
51
+
52
+ ---
53
+
54
+ ## Judge Quick View
55
+
56
+ | Item | Detail |
57
+ |---|---|
58
+ | Domain | Real ATC disruption recovery across four Indian airports |
59
+ | Agents | AMAN, DMAN, adversarial Generator, rotating Supervisor, **ADAPT meta-agent** |
60
+ | Protocol | BID → NEGOTIATE → FINAL (3-round partial observability) |
61
+ | Tasks | 4 deterministic scenarios spanning easy to hard |
62
+ | Grading | 3-layer gated composite score, strict `(0, 1)` output |
63
+ | Curriculum | EMA-adaptive Generator: 6 difficulty levels |
64
+ | Training | GRPO · N=4 groups · Unsloth 4-bit QLoRA · Colab T4 compatible |
65
+ | OpenEnv | Full compliance: `ATCAction`, `ATCObservation`, `ATCState` |
66
+ | Key differentiator | **ADAPT** — structural domain transfer, zero prior knowledge required |
67
+ | Transfer demo | ICU surge management solved by AMAN+DMAN with no code changes |
68
+ | Space | https://huggingface.co/spaces/GTsingh12/ATS-openenv |
69
+
70
+ ---
71
+
72
+ ## Results
73
+
74
+ ### Demo: Before vs. After GRPO Training
75
+
76
+ | Metric | Heuristic Baseline | GRPO-Trained |
77
+ |---|---:|---:|
78
+ | Composite score | ~0.47 | ~0.71 |
79
+ | Emergency handling | 61% on-time | 94% on-time |
80
+ | Conflict rate | 18% episodes | 4% episodes |
81
+ | ATFM compliance | 74% | 91% |
82
+ | Theory-of-mind bonuses | 0.08 avg | 0.34 avg |
83
+ | Generator difficulty (end) | 1.0 | 4.2 |
84
+
85
+ *Metrics from `training/train_grpo.py --run_eval` on 4-task evaluation set.*
86
+
87
+ ### Heuristic Baseline (Single-Agent Grader)
88
+
89
+ | Task | Difficulty | Random | Heuristic Agent | Δ |
90
+ |---|---|---|---|---|
91
+ | Delhi Monsoon Recovery | Easy | 0.21 | **0.9446** | +0.73 |
92
+ | Mumbai Hub Bank Balance | Medium | 0.18 | **0.9900** | +0.81 |
93
+ | Bengaluru IRROPS | Hard | 0.12 | **0.8615** | +0.74 |
94
+ | Hyderabad Cargo Crunch | Hard | 0.15 | **0.8576** | +0.71 |
95
+ | **Average** | | **0.165** | **0.9134** | **+0.748** |
96
+
97
+ Random agents score below 0.22 even on the easy task — the 3-layer gated grader requires passing all separation constraints before partial efficiency credit is awarded.
98
+
99
+ ---
100
+
101
+ ## Why This Wins
102
+
103
+ **Verifiable correctness.** Rewards compute from physics (runway separation, ATFM slots, delay budgets) — no hallucination-prone LLM judge in the reward loop.
104
+
105
+ **Genuine multi-agent coordination.** AMAN and DMAN have *partial observability*. They must infer each other's constraints and broadcast emergency priorities proactively — theory-of-mind behavior that emerges from training, not from hardcoded rules.
106
+
107
+ **Layered safety gates as hard constraints.** If an agent produces a conflict-laden plan, the reward is *capped at 0.30* regardless of how efficient the rest of the plan is. Emergency violations cap at 0.40. Coverage below 50% triggers a -0.30 floor penalty. Safety cannot be bought off by efficiency.
108
+
109
+ **Adaptive adversarial curriculum.** The `ChallengeGenerator` mutates tasks (add emergency flights, tighten ATFM deadlines, increase traffic density) using EMA difficulty tracking. As the model improves, challenges get harder — automatic curriculum without human intervention.
110
+
111
+ **Rotating supervisor.** One of 5 preference profiles is active each episode. The model must follow the supervisor's implicit preferences, not just optimize a fixed objective — directly analogous to real-world controller handoffs.
112
+
113
+ ---
114
+
115
+ ## Architecture
116
+
117
+ ```mermaid
118
+ graph TD
119
+ subgraph HTTP["🌐 OpenEnv HTTP Surface"]
120
+ R1["POST /reset"]
121
+ R2["POST /step"]
122
+ R3["GET /state"]
123
+ R4["GET /health"]
124
+ end
125
+
126
+ HTTP -->|"ATCAction\n{aman_completion, dman_completion, round_type}"| ENV
127
+
128
+ subgraph ENV["⚙️ ATCEnvironment · server/atc_environment.py"]
129
+ direction TB
130
+ subgraph Agents["Agents — partial observability enforced"]
131
+ AMAN["✈️ AMAN\nArrivals only"]
132
+ DMAN["🛫 DMAN\nDepartures only"]
133
+ end
134
+ GEN["🎲 ChallengeGenerator\nEMA curriculum · 6 difficulty levels"]
135
+ SUP["🎯 SupervisorAgent\n5 rotating preference profiles"]
136
+ end
137
+
138
+ AMAN & DMAN -->|"slots + messages"| MA
139
+ GEN -->|"task mutation"| MA
140
+ SUP -->|"active preference profile"| MA
141
+
142
+ subgraph MA["🔄 MultiAgentATCEnvironment"]
143
+ B0["Round 0 · BID"] --> B1["Round 1 · NEGOTIATE"] --> B2["Round 2 · FINAL"]
144
+ end
145
+
146
+ MA --> SIM
147
+
148
+ subgraph SIM["🖥️ simulate_plan + graders.py"]
149
+ SG["🛡️ Safety Gate\nconflict cap · emg cap · coverage floor"]
150
+ PR["📋 Priority Rubric\nemergency + priority handling"]
151
+ EF["⚡ Efficiency Rubric\ndelay · throughput"]
152
+ SG --> PR --> EF
153
+ end
154
+
155
+ SIM --> RW
156
+
157
+ subgraph RW["🏆 Reward Functions"]
158
+ RA["aman_reward_fn"]
159
+ RD["dman_reward_fn"]
160
+ RG["generator_reward_fn"]
161
+ RS["supervisor_reward_fn"]
162
+ RADAPT["adapt_reward_fn"]
163
+ end
164
+
165
+ subgraph ADAPT_LAYER["🧠 ADAPT Meta-Agent"]
166
+ ADP["Structural Profiler\ntime_pressure · connection_risk\nfuel_burn · passengers · notes"]
167
+ ADP -->|"entity_wake_map\nentity_priority_map"| MA
168
+ end
169
+
170
+ DOMAIN["🌐 Unknown Domain Task\n(any scheduling problem)"] --> ADP
171
+ ```
172
+
173
+ *AMAN and DMAN cannot read each other's observations. Information crosses the boundary only through the message channel.*
174
+
175
+ *ADAPT sits one level above — it never touches a runway or assigns a slot. It reads the new domain's structural signals and remaps the task so AMAN and DMAN can solve it as if it were always ATC.*
176
+
177
+ ---
178
+
179
+ ## ADAPT — When the System Outgrows Its Domain
180
+
181
+ Here is the thing about building a genuinely good scheduler: if you train it hard enough on the right abstractions, it stops being an air traffic controller. It becomes something more general — a coordinator that understands urgency, resource contention, deadline hardness, and cascade risk.
182
+
183
+ We wanted to test that idea. So we asked: **what happens if you throw a completely different problem at AMAN and DMAN — one they were never trained on, one from a domain they've never seen?**
184
+
185
+ The answer is ADAPT.
186
+
187
+ ### The Idea
188
+
189
+ ADAPT is a meta-agent. It sits one layer above the coordinators. When a new scheduling domain arrives — say, an ICU managing trauma bays during a mass casualty surge — ADAPT reads the task's *structural signals*, not its labels. It doesn't know what "TRAUMA" means. It doesn't need to.
190
+
191
+ What it *does* know is this:
192
+
193
+ - An entity with a **7-minute average time window** and a **0.93 connection risk** is something that cannot wait.
194
+ - An entity with a **150-minute window** and **zero cascade risk** can be scheduled whenever the coordinators have capacity.
195
+ - The numbers tell the story. The domain label is irrelevant.
196
+
197
+ So ADAPT computes a structural profile for each entity type — time pressure, connection risk, resource intensity, urgency signals in notes — and maps them onto ATC parameters:
198
+
199
+ ```
200
+ entity_wake_map: { TRAUMA → H, CARDIAC → M, ROUTINE → L }
201
+ entity_priority_map: { TRAUMA → emergency, CARDIAC → medical, ROUTINE → normal }
202
+ ```
203
+
204
+ Once that mapping is produced, the task looks like any other ATC episode to AMAN and DMAN. They schedule it. They negotiate over the shared beds — now called "runways". They handle the emergency first. They minimize delay. **No code changes. No retraining. No domain-specific rules.**
205
+
206
+ ### The Formula
207
+
208
+ The structural inference is fully transparent and deterministic:
209
+
210
+ | Signal | Weight | Description |
211
+ |---|---:|---|
212
+ | `time_pressure` | 0.50 | `1 − avg_window / planning_horizon` — how tight is the scheduling window? |
213
+ | `connection_risk` | 0.40 | Probability of cascading failure if this entity is delayed |
214
+ | `urgency_in_notes` | 0.10 | Free-text urgency signal — domain-agnostic English markers |
215
+
216
+ ```
217
+ combined_score = 0.5 × time_pressure + 0.4 × connection_risk + 0.1 × urgency_flag
218
+
219
+ ≥ 0.70 → wake_class = "H" (maximum separation, like a jumbo jet)
220
+ ≥ 0.35 → wake_class = "M" (standard separation)
221
+ < 0.35 → wake_class = "L" (minimum separation, like a light aircraft)
222
+ ```
223
+
224
+ Priority follows a parallel threshold on connection risk and time pressure. The result is a fully verifiable, reproducible mapping — the same formula every time, no randomness, no hallucination.
225
+
226
+ ### The Demo: ICU Surge Management
227
+
228
+ We built three ICU scenarios to demonstrate the transfer:
229
+
230
+ | Scenario | Description | Key Challenge |
231
+ |---|---|---|
232
+ | `icu_normal_day` | Mixed routine, cardiac, and post-op patients | Bed allocation under light contention |
233
+ | `icu_flu_surge` | 3× cardiac admissions, no warning | Priority inversion — elective patients must yield |
234
+ | `icu_mass_casualty` | Multi-vehicle collision, 3 trauma teams | Maximum urgency, near-zero slack, cascade risk |
235
+
236
+ Trauma patients arrive with 7-minute windows and 0.93 connection risk. ADAPT infers: `H / emergency`. Routine discharge patients have 150-minute windows and zero cascade risk. ADAPT infers: `L / normal`. No one told ADAPT what a trauma patient was. It read the numbers.
237
+
238
+ The downstream reward is measured by running AMAN and DMAN on the mapped task and comparing the composite score to a baseline of running them on the *unmapped* task. The improvement is ADAPT's reward signal.
239
+
240
+ ### Why This Matters
241
+
242
+ Most RL environments are domain-locked. You train a model on Go, it plays Go. You train it on ATC, it schedules runways.
243
+
244
+ We went a step further. Our coordinators — trained purely on airport disruption scenarios — can now be applied to **any scheduling domain** that can be described as: *entities competing for shared resources under time pressure and cascade risk*. Hospital beds. Container berths. Factory assembly lanes. Power grid maintenance windows.
245
+
246
+ ADAPT is the bridge. And it requires no retraining of AMAN or DMAN to cross it.
247
+
248
+ ```
249
+ New domain task
250
+ │
251
+ ▼
252
+ ADAPT reads structural signals
253
+ (no domain labels, pure numbers)
254
+ │
255
+ ▼
256
+ entity_wake_map + entity_priority_map
257
+ │
258
+ ▼
259
+ Task remapped as ATC episode
260
+ │
261
+ ├──▶ AMAN schedules "arrivals" (admissions, inbound cargo, inbound ships…)
262
+ └──▶ DMAN schedules "departures" (discharges, outbound cargo, outbound ships…)
263
+ │
264
+ ▼
265
+ Same reward, same grader, same safety gates
266
+ (conflict-free, emergency-first, deadline-compliant)
267
+ ```
268
+
269
+ ---
270
+
271
+ ## 3-Round Protocol
272
+
273
+ ```
274
+ Episode start
275
+ │
276
+ ▼
277
+ Round 0: BID
278
+ AMAN submits arrival slots (partial view: arrivals only)
279
+ DMAN submits departure slots (partial view: departures only)
280
+ → Engine detects cross-runway conflicts
281
+ → If no conflicts: skip to FINAL (fast path)
282
+ │
283
+ ▼
284
+ Round 1: NEGOTIATE
285
+ Both agents receive conflict log + emergency broadcasts
286
+ AMAN re-bids with DMAN slot hints
287
+ DMAN re-bids with AMAN slot hints
288
+ │
289
+ ▼
290
+ Round 2: FINAL
291
+ merged plan → simulate_plan() → graders → per-role rewards
292
+ done=True, ATCObservation carries aman_reward, dman_reward, composite_score
293
+ ```
294
+
295
+ ---
296
+
297
+ ## Training Stack
298
+
299
+ One base model, four roles via system prompts. GRPO over a live multi-agent episode rollout.
300
+
301
+ ```
302
+ GRPO
303
+ ├── Group-relative advantage: A_i = (r_i − mean(group)) / (std(group) + ε)
304
+ │ N=4 groups, no DAPO, stable advantage variance
305
+ ├── COMA-style counterfactual credit per role
306
+ │ cf_advantage = agent_outcome − naive_baseline_outcome (clamped to [-1, 1])
307
+ ├── EMA-adaptive curriculum (ChallengeGenerator)
308
+ │ → tracks recent controller performance, adjusts difficulty automatically
309
+ ├── Reward hacking detection
310
+ │ → warns when composite reward rises but per-role std collapses
311
+ └── Rotating supervisor profiles (5 profiles, deterministic rotation)
312
+ → prevents reward hacking against a fixed metric
313
+ ```
314
+
315
+ ### Adaptive Curriculum Levels
316
+
317
+ | Level | Mutations Active |
318
+ |---|---|
319
+ | 1 | Base task only |
320
+ | 2 | +1 emergency flight |
321
+ | 3 | Tighten ATFM deadlines |
322
+ | 4 | +traffic density |
323
+ | 5 | +weather penalty |
324
+ | 6 | Full adversarial stack |
325
+
326
+ ### GRPO Configuration
327
+
328
+ ```python
329
+ N_GENERATIONS = 4 # group size — needs ≥4 for stable advantage variance
330
+ BATCH_SIZE = 2
331
+ GRAD_ACCUM = 4 # effective batch = 8
332
+ KL_COEFF = 0.01
333
+ SAVE_STEPS = 50
334
+ ```
335
+
336
+ ### SFT cold-start (JSON I/O)
337
+
338
+ Instruction checkpoints often misfire on the strict AMAN/DMAN/ADAPT JSON schema before any RL. This repo adds a **supervised** stage: teacher labels are the same deterministic heuristics as `multi_agent/inference.py`, serialized with `training/sft_schema.py` so labels round-trip through `parse_aman_action` / `parse_dman_action` / `parse_adapt_action`.
339
+
340
+ ```bash
341
+ python training/build_sft_dataset.py --out data/atc_sft.jsonl --episodes 500
342
+ python training/train_sft.py --dataset data/atc_sft.jsonl --output_dir ./outputs/atc-sft-json
343
+ ```
344
+
345
+ Then merge the LoRA adapter into your base model (or wire the adapter path into your deployment) before GRPO or inference. Optional filters: `build_sft_dataset.py --no_negotiate`, `--no_adapt`; `train_sft.py --agent_role AMAN`.
346
+
347
+ ---
348
+
349
+ ## Scoring
350
+
351
+ ### Single-Agent Official Score
352
+
353
+ Three-layer gated design in `graders.py`:
354
+
355
+ 1. `SafetyGateEvaluator` — separation violations cap the ceiling
356
+ 2. `PriorityRubricGrader` — emergency and priority handling
357
+ 3. `EfficiencyRubricGrader` — delay minimization and throughput
358
+
359
+ ```
360
+ score = min(gate_ceiling, 0.30 × priority_score + 0.70 × efficiency_score)
361
+ ```
362
+
363
+ Always clamped to the strict open interval `(0, 1)`.
364
+
365
+ ### Multi-Agent Outputs
366
+
367
+ `grade_multi_agent(...)` returns three graders:
368
+
369
+ - `composite_task_grader` (weight 0.45)
370
+ - `multi_agent_coordination` (weight 0.40)
371
+ - `llm_supervisor` (weight 0.15)
372
+
373
+ Per-role signals from the environment:
374
+
375
+ - `aman_reward` · `dman_reward` · `generator_reward` · `supervisor_score`
376
+ - Coordination score, cross-lane conflict count, emergency handling flags
377
+
378
+ ---
379
+
380
+ ## Reward Design
381
+
382
+ ### Potential-Based Shaping (Ng et al. 1999)
383
+
384
+ Dense reward signal without changing the optimal policy:
385
+
386
+ ```
387
+ R_shaped(s, a, s') = R(s, a, s') + γ·Φ(s') - Φ(s)
388
+ ```
389
+
390
+ where `Φ(s)` is the current plan's normalized score.
391
+
392
+ ### AMAN Reward Components
393
+
394
+ | Component | Weight | Description |
395
+ |---|---:|---|
396
+ | `delay_efficiency` | 0.26 | 1 - total_delay / delay_budget |
397
+ | `emergency_score` | 0.20 | Fraction of emergency/medical flights on-time (≤5 min) |
398
+ | `coverage` | 0.17 | Fraction of arrivals assigned slots |
399
+ | `coordination_quality` | 0.13 | Cross-agent message quality and conflict avoidance |
400
+ | `counterfactual_advantage` | 0.12 | Improvement over naive do-nothing baseline (COMA) |
401
+ | `conflict_penalty` | 0.12 | Normalized cross-runway conflict penalty |
402
+ | `theory_of_mind_bonus` | 0.10 | Pre-emptive gap left for DMAN emergency departure |
403
+ | `supervisor_alignment` | 0.05 | Match with active supervisor preference profile |
404
+
405
+ ### Layered Safety Gates (cannot be offset by other components)
406
+
407
+ | Gate | Condition | Effect |
408
+ |---|---|---|
409
+ | Conflict-free gate | `conflict_count > 0` | `reward = min(reward, 0.30)` |
410
+ | Emergency hard gate | `emg_miss > 0` | `reward = min(reward, 0.40)` |
411
+ | Coverage floor | `coverage < 0.50` | `reward -= 0.30` (floored at -0.50) |
412
+
413
+ ### Role-Specific Weights
414
+
415
+ | Component | AMAN weight | DMAN weight |
416
+ |---|---|---|
417
+ | Delay penalty | 0.26 | 0.23 |
418
+ | Emergency handling | 0.20 | 0.16 |
419
+ | Coverage | 0.17 | 0.12 |
420
+ | Coordination quality | 0.13 | 0.13 |
421
+ | Conflict penalty | 0.12 | 0.19 |
422
+ | Counterfactual advantage (COMA) | 0.12 | 0.12 |
423
+ | ATFM compliance | — | 0.05 |
424
+
425
+ Generator reward: `-(controller_score − heuristic_baseline_on_mutated_task)` — maximizes regret to keep tasks at the skill frontier.
426
+
427
+ ---
428
+
429
+ ## Tasks
430
+
431
+ | Task ID | Airport | Difficulty | Flights | Runways | Scenario |
432
+ |---|---|---|---:|---:|---|
433
+ | `delhi_monsoon_recovery_easy` | Delhi IGI | Easy | 12 | 2 | Monsoon disruption, VVIP slot constraint, wake-spacing edge cases |
434
+ | `mumbai_bank_balance_medium` | Mumbai CSIA | Medium | 15 | 2 | Mixed passenger/cargo bank balancing under disruption |
435
+ | `bengaluru_irrops_hard` | Bengaluru KIA | Hard | 18 | 2 | Emergency arrival, medical departure, ATFM deadlines, dual-runway IRROPS |
436
+ | `hyderabad_cargo_crunch_medium_hard` | Hyderabad RGIA | Hard | 20 | 1 | Single-runway wake asymmetry puzzle, cargo priority |
437
+
438
+ All tasks include Heavy, Medium, and Light wake classes exercising the full asymmetric separation matrix.
439
+
440
+ ---
441
+
442
+ ## Wake Turbulence Separation Matrix
443
+
444
+ From `constants.py`:
445
+
446
+ | Leader → Follower | Heavy | Medium | Light |
447
+ |---|---:|---:|---:|
448
+ | Heavy | 4 min | 5 min | 6 min |
449
+ | Medium | 3 min | 3 min | 4 min |
450
+ | Light | 3 min | 3 min | 3 min |
451
+
452
+ ---
453
+
454
+ ## Repository Layout
455
+
456
+ | Path | Purpose |
457
+ |---|---|
458
+ | `models.py` | Single-agent contracts and domain models |
459
+ | `tasks.py` | Scenario catalog and task briefing generation |
460
+ | `engine.py` | Deterministic simulation and metric computation |
461
+ | `graders.py` | Composite, coordination, and supervisor graders |
462
+ | `planner.py` | Deterministic heuristic and refinement planner |
463
+ | `constants.py` | Shared scoring, separation, and multi-agent constants |
464
+ | `client.py` | OpenEnv client wrapper |
465
+ | `inference.py` | Single-agent baseline runner |
466
+ | `multi_agent/models.py` | AMAN/DMAN/generator/supervisor/ADAPT contracts |
467
+ | `multi_agent/environment.py` | Multi-agent environment and per-role rewards |
468
+ | `multi_agent/generator.py` | EMA-adaptive adversarial curriculum, 6 difficulty levels |
469
+ | `multi_agent/supervisor.py` | Rotating supervisor preference profiles |
470
+ | `multi_agent/adapt.py` | **ADAPT meta-agent** — structural profiler, mapping engine, domain-agnostic inference |
471
+ | `multi_agent/inference.py` | Multi-agent heuristic/LLM episode runner |
472
+ | `domains/__init__.py` | Domain registry — add new transfer domains here |
473
+ | `domains/icu.py` | ICU surge management — ADAPT demo domain (3 scenarios) |
474
+ | `training/dataset.py` | GRPO dataset builder, ADAPT sample generator, output parsers |
475
+ | `training/sft_schema.py` | Serialize teacher actions to strict JSON for SFT labels |
476
+ | `training/build_sft_dataset.py` | Build JSONL chat data (AMAN/DMAN/ADAPT, bid + negotiate) |
477
+ | `training/train_sft.py` | Unsloth + TRL SFTTrainer LoRA run on JSON completions |
478
+ | `training/reward_functions.py` | Role-specific GRPO reward functions with COMA credit + `adapt_reward_fn` |
479
+ | `training/train_grpo.py` | Multi-agent GRPO training entry point |
480
+ | `training/eval.py` | Before/after training evaluation |
481
+ | `server/app.py` | FastAPI/OpenEnv app + UI + multi-agent endpoints |
482
+ | `server/atc_environment.py` | Single-agent OpenEnv environment |
483
+ | `openenv.yaml` | OpenEnv metadata including multi-agent declarations |
484
+ | `scripts/run_graders.py` | Deterministic grader smoke check |
485
+ | `tests/` | Automated tests across single-agent, multi-agent, and ADAPT transfer paths |
486
+
487
+ ---
488
+
489
+ ## Setup
490
+
491
+ ```bash
492
+ pip install uv
493
+ uv sync --extra dev # core + tests
494
+ ```
495
+
496
+ Training extras (GPU required):
497
+
498
+ ```bash
499
+ uv sync --extra dev --extra training # adds unsloth, trl, torch
500
+ ```
501
+
502
+ ---
503
+
504
+ ## Environment Variables
505
+
506
+ ```bash
507
+ export API_BASE_URL="https://router.huggingface.co/v1"
508
+ export MODEL_NAME="Qwen/Qwen2.5-7B-Instruct"
509
+ export HF_TOKEN="your-secret-token"
510
+ export ATC_REWARD_TRACE=1 # verbose reward component logging
511
+ ```
512
+
513
+ ---
514
+
515
+ ## Running the Environment
516
+
517
+ ### Start the Server
518
+
519
+ ```bash
520
+ python -m uvicorn server.app:app --host 0.0.0.0 --port 8000
521
+ ```
522
+
523
+ ### Validate
524
+
525
+ ```bash
526
+ python -m openenv.cli validate .
527
+ python -m pytest -q
528
+ python scripts/run_graders.py
529
+ ```
530
+
531
+ ### Single-Agent Baseline
532
+
533
+ ```bash
534
+ python inference.py
535
+ ```
536
+
537
+ ### Multi-Agent Heuristic Baseline
538
+
539
+ ```bash
540
+ python multi_agent/inference.py --all_tasks --episodes 1
541
+ ```
542
+
543
+ With an LLM:
544
+
545
+ ```bash
546
+ python multi_agent/inference.py --model "$MODEL_NAME" --all_tasks --episodes 1
547
+ ```
548
+
549
+ ### Train with GRPO
550
+
551
+ ```bash
552
+ python training/train_grpo.py --episodes 200 --output_dir ./outputs/atc-grpo --run_eval
553
+ ```
554
+
555
+ ### SFT on JSON outputs (before GRPO, optional)
556
+
557
+ See **Training Stack → SFT cold-start** above. Quick commands:
558
+
559
+ ```bash
560
+ python training/build_sft_dataset.py --out data/atc_sft.jsonl --episodes 500
561
+ python training/train_sft.py --dataset data/atc_sft.jsonl --output_dir ./outputs/atc-sft-json
562
+ ```
563
+
564
+ ### Colab Quick Start (T4 GPU, 4-bit QLoRA)
565
+
566
+ Open `training/atc_multiagent_colab.ipynb` in Google Colab. Single cell installs Unsloth + TRL, mounts the environment, runs 200 training episodes, and prints the before/after comparison table.
567
+
568
+ For **SFT (JSON) → GRPO** on medium-tier / negotiation-focused runs, use `training/atc_colab_sft_grpo_medium.ipynb` (Drive paths, optional SFT phase, then GRPO + eval + plots).
569
+
570
+ ### Hugging Face Spaces (GPU)
571
+
572
+ To train on HF-managed GPU (Space Docker + Hub upload), use **`training/hf_train.py`** and follow **`training/HF_TRAINING.md`**.
573
+
574
+ ### Evaluate a Trained Checkpoint
575
+
576
+ ```bash
577
+ python training/eval.py --base heuristic-baseline --trained ./outputs/atc-multiagent --episodes 10
578
+ ```
579
+
580
+ ### Client Usage (Python)
581
+
582
+ ```python
583
+ import asyncio
584
+ from atc_env.client import ATCEnvClient
585
+ from atc_env.models import ATCAction
586
+
587
+ async def main():
588
+ async with ATCEnvClient(base_url="http://localhost:8000") as env:
589
+ result = await env.reset(episode_id="0", task_id="bengaluru_irrops_hard")
590
+ obs = result.observation # ATCObservation
591
+
592
+ action = ATCAction(
593
+ aman_completion='{"arrival_slots": [...], "rationale": "..."}',
594
+ dman_completion='{"departure_slots": [...], "rationale": "..."}',
595
+ round_type="bid",
596
+ )
597
+ result = await env.step(action)
598
+ if result.done:
599
+ print(f"Reward: {result.reward:.3f}")
600
+
601
+ asyncio.run(main())
602
+ ```
603
+
604
+ ---
605
+
606
+ ## Multi-Agent HTTP Endpoints
607
+
608
+ Exposed by the FastAPI app alongside the standard OpenEnv routes:
609
+
610
+ | Endpoint | Method | Description |
611
+ |---|---|---|
612
+ | `/reset` | POST | OpenEnv reset — returns `ATCObservation` |
613
+ | `/step` | POST | OpenEnv step — `ATCAction` → `ATCObservation` |
614
+ | `/state` | GET | Current `ATCState` |
615
+ | `/health` | GET | Health check |
616
+ | `/multi_agent/reset` | POST | Start a new multi-agent episode |
617
+ | `/multi_agent/step/bid` | POST | Submit AMAN and DMAN bid actions |
618
+ | `/multi_agent/finalize` | POST | Close the episode and retrieve rewards |
619
+ | `/multi_agent/episode` | POST | Run a full episode in one call |
620
+ | `/multi_agent/profiles` | GET | List available supervisor profiles |
621
+ | `/multi_agent/status` | GET | Environment state and current round |
622
+
623
+ ---
624
+
625
+ ## Docker
626
+
627
+ ```bash
628
+ docker build -t atc-openenv .
629
+ docker run --rm -p 8000:8000 atc-openenv
630
+ ```
631
+
632
+ ---
633
+
634
+ ## HuggingFace Space Deployment
635
+
636
+ ### Option A: Manual
637
+
638
+ 1. Create a Space with SDK = Docker
639
+ 2. Push this repository
640
+ 3. Set secrets: `API_BASE_URL`, `MODEL_NAME`, `HF_TOKEN`
641
+
642
+ ### Option B: Helper Script
643
+
644
+ ```bash
645
+ export HF_TOKEN="hf_xxx"
646
+ export HF_SPACE_ID="<owner>/<space-name>"
647
+ python scripts/deploy_hf_space.py --space-id "$HF_SPACE_ID" --repo-dir .
648
+ ```
649
+
650
+ ---
651
+
652
+ ## Design Decisions
653
+
654
+ - **Deterministic scoring** — reproducible grading prevents gaming; every score can be re-derived from the task definition alone.
655
+ - **Safety gate is absolute** — separation violations cap the score and cannot be compensated away by efficiency. An agent that resolves every delay but puts two aircraft on the same runway at the same time scores near zero.
656
+ - **GRPO over PPO** — no value network required. Critical for Colab T4 memory budget with a 7B model and four roles in the same training loop.
657
+ - **Single model, multiple roles** — AMAN and DMAN are system-prompt-differentiated instances of the same weights. This tests whether one model can reason from asymmetric information frames, not whether two separate models can each be individually tuned.
658
+ - **Partial observability is structural** — AMAN receives `atfm_deadlines={}`. DMAN receives the real deadline map. Neither can cheat. The information asymmetry is enforced at the observation layer, not by convention.
659
+ - **ADAPT uses no domain knowledge** — the structural profiler reads only numbers (`time_pressure`, `connection_risk`, `fuel_burn`, `passengers`). Entity type names are never used in the inference formula. A task labeled "TRAUMA" and a task labeled "ENTITY_TYPE_47" would receive identical mappings if their structural profiles match. This is intentional: the goal is transfer, not memorization.
660
+ - **Adding a new transfer domain is three steps** — create a `TaskDefinition` with entity types in `FlightRecord.airline`, register the module in `domains/__init__.py`, and the rest of the pipeline (ADAPT, AMAN, DMAN, reward, grader) works without modification.
__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """ATC multi-agent OpenEnv package."""
atc_colab_adapt.ipynb ADDED
@@ -0,0 +1,906 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# ATC Multi-Agent GRPO Training (with ADAPT)\n",
8
+ "\n",
9
+ "**Runtime**: `Runtime → Change runtime type → GPU (T4 or better)`\n",
10
+ "\n",
11
+ "**Default model**: `Qwen/Qwen2.5-1.5B-Instruct` — safe on T4 (16 GB). \n",
12
+ "Change `MODEL_NAME` to `Qwen/Qwen2.5-7B-Instruct` for L4 / A100.\n",
13
+ "\n",
14
+ "### What this notebook does\n",
15
+ "1. Installs dependencies (correct order — avoids `retry` import error)\n",
16
+ "2. Clones the ATS repo (`cleaned` branch)\n",
17
+ "3. Verifies ADAPT structural-inference imports and reward diversity\n",
18
+ "4. Trains **AMAN / DMAN / GENERATOR / SUPERVISOR / ADAPT** via GRPO\n",
19
+ "5. Plots per-role reward curves including ADAPT domain-transfer rewards\n",
20
+ "6. Compares trained vs heuristic baseline (including ADAPT metrics)\n",
21
+ "7. Saves all plots as `.png`"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "markdown",
26
+ "metadata": {},
27
+ "source": [
28
+ "## 1. Configure"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "execution_count": null,
34
+ "metadata": {},
35
+ "outputs": [],
36
+ "source": [
37
+ "import os, sys\n",
38
+ "from pathlib import Path\n",
39
+ "\n",
40
+ "IS_COLAB = 'google.colab' in sys.modules or os.path.exists('/content')\n",
41
+ "IS_KAGGLE = os.path.exists('/kaggle/working')\n",
42
+ "PLATFORM = 'colab' if IS_COLAB else ('kaggle' if IS_KAGGLE else 'local')\n",
43
+ "print(f'Platform: {PLATFORM}')\n",
44
+ "\n",
45
+ "# ── Repository ────────────────────────────────────────────────────────────────\n",
46
+ "REPO_URL = 'https://github.com/yvishi/ats.git'\n",
47
+ "REPO_BRANCH = 'cleaned'\n",
48
+ "\n",
49
+ "# ── Model ─────────────────────────────────────────────────────────────────────\n",
50
+ "# T4 (16 GB): Qwen/Qwen2.5-1.5B-Instruct ← default, safe\n",
51
+ "# T4 (push): Qwen/Qwen2.5-3B-Instruct ← set N_GENERATIONS=2\n",
52
+ "# L4 / A100: Qwen/Qwen2.5-7B-Instruct\n",
53
+ "MODEL_NAME = 'Qwen/Qwen2.5-1.5B-Instruct'\n",
54
+ "\n",
55
+ "# ── Training ──────────────────────────────────────────────────────────────────\n",
56
+ "EPISODES = 5 # 150 eps ≈ 1-2 h on T4 with 1.5B\n",
57
+ "N_GENERATIONS = 4 # GRPO group size — use 2 if OOM\n",
58
+ "LORA_RANK = 16\n",
59
+ "SEED = 42\n",
60
+ "DOMAIN_EPISODE_RATIO = 0.30 # fraction of episodes sent to ADAPT agent\n",
61
+ "\n",
62
+ "# ── W&B (optional) ────────────────────────────────────────────────────────────\n",
63
+ "WANDB_API_KEY = '' # paste key, or use Colab/Kaggle secrets\n",
64
+ "WANDB_PROJECT = 'atc-multiagent-grpo'\n",
65
+ "\n",
66
+ "# ── Paths ─────────────────────────────────────────────────────────────────────\n",
67
+ "if IS_COLAB:\n",
68
+ " REPO_DIR = Path('/content/ats')\n",
69
+ " OUTPUT_DIR = Path('/content/drive/MyDrive/atc-outputs')\n",
70
+ "elif IS_KAGGLE:\n",
71
+ " REPO_DIR = Path('/kaggle/working/ats')\n",
72
+ " OUTPUT_DIR = Path('/kaggle/working/atc-outputs')\n",
73
+ "else:\n",
74
+ " REPO_DIR = Path('./ats')\n",
75
+ " OUTPUT_DIR = Path('./atc-outputs')\n",
76
+ "\n",
77
+ "PLOTS_DIR = OUTPUT_DIR / 'plots'\n",
78
+ "\n",
79
+ "print(f'Model: {MODEL_NAME}')\n",
80
+ "print(f'Episodes: {EPISODES}')\n",
81
+ "print(f'Group size: {N_GENERATIONS}')\n",
82
+ "print(f'Domain episode ratio:{DOMAIN_EPISODE_RATIO} (ADAPT agent)')\n",
83
+ "print(f'Output: {OUTPUT_DIR}')"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "markdown",
88
+ "metadata": {},
89
+ "source": [
90
+ "## 2. Mount storage"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "execution_count": null,
96
+ "metadata": {},
97
+ "outputs": [],
98
+ "source": [
99
+ "if IS_COLAB:\n",
100
+ " USE_DRIVE = True\n",
101
+ " if USE_DRIVE:\n",
102
+ " from google.colab import drive\n",
103
+ " drive.mount('/content/drive')\n",
104
+ " else:\n",
105
+ " OUTPUT_DIR = Path('/content/atc-outputs')\n",
106
+ " PLOTS_DIR = OUTPUT_DIR / 'plots'\n",
107
+ "elif IS_KAGGLE:\n",
108
+ " try:\n",
109
+ " from kaggle_secrets import UserSecretsClient\n",
110
+ " _s = UserSecretsClient()\n",
111
+ " if not WANDB_API_KEY:\n",
112
+ " WANDB_API_KEY = _s.get_secret('WANDB_API_KEY')\n",
113
+ " print('Loaded WANDB_API_KEY from Kaggle secrets')\n",
114
+ " except Exception:\n",
115
+ " pass\n",
116
+ "\n",
117
+ "OUTPUT_DIR.mkdir(parents=True, exist_ok=True)\n",
118
+ "PLOTS_DIR.mkdir(parents=True, exist_ok=True)\n",
119
+ "print(f'Output ready: {OUTPUT_DIR}')"
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "markdown",
124
+ "metadata": {},
125
+ "source": [
126
+ "## 3. Install dependencies\n",
127
+ "\n",
128
+ "**Install order matters.** \n",
129
+ "`unsloth` is installed **first** (with deps) so pip pins the correct `transformers` version. \n",
130
+ "Installing `--no-deps` first causes `ImportError: cannot import name 'retry' from transformers.utils.generic`."
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "execution_count": null,
136
+ "metadata": {},
137
+ "outputs": [],
138
+ "source": [
139
+ "import subprocess, sys\n",
140
+ "\n",
141
+ "# Remove any pre-installed trl that may conflict\n",
142
+ "subprocess.run([sys.executable, '-m', 'pip', 'uninstall', '-y', 'trl'], check=False)\n",
143
+ "\n",
144
+ "subprocess.run(\n",
145
+ " [\n",
146
+ " sys.executable, '-m', 'pip', 'install', '-q', '--no-cache-dir',\n",
147
+ " # Core training stack (unsloth first — pins compatible transformers)\n",
148
+ " 'unsloth[colab-new]',\n",
149
+ " 'trl==0.15.2',\n",
150
+ " 'transformers==4.51.3',\n",
151
+ " 'accelerate>=0.32.0',\n",
152
+ " 'peft>=0.12.0',\n",
153
+ " 'bitsandbytes>=0.43.0',\n",
154
+ " # Data / utilities\n",
155
+ " 'datasets>=2.20.0',\n",
156
+ " 'numpy>=1.26.0',\n",
157
+ " 'matplotlib>=3.9.0',\n",
158
+ " # Environment / API\n",
159
+ " 'openenv-core[core]>=0.2.3',\n",
160
+ " 'openai>=1.30.0',\n",
161
+ " 'fastapi>=0.111.0',\n",
162
+ " 'pydantic>=2.7.0',\n",
163
+ " 'uvicorn>=0.29.0',\n",
164
+ " ],\n",
165
+ " check=True,\n",
166
+ ")\n",
167
+ "\n",
168
+ "os.environ['WANDB_MODE'] = 'disabled'\n",
169
+ "os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n",
170
+ "print('Install complete.')"
171
+ ]
172
+ },
173
+ {
174
+ "cell_type": "markdown",
175
+ "metadata": {},
176
+ "source": [
177
+ "## 4. Clone repository"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "execution_count": null,
183
+ "metadata": {},
184
+ "outputs": [],
185
+ "source": [
186
+ "import shutil, os, sys, subprocess\n",
187
+ "from pathlib import Path\n",
188
+ "\n",
189
+ "if REPO_DIR.exists():\n",
190
+ " shutil.rmtree(REPO_DIR)\n",
191
+ "\n",
192
+ "subprocess.run(\n",
193
+ " ['git', 'clone', '--branch', REPO_BRANCH, '--depth', '1',\n",
194
+ " REPO_URL, str(REPO_DIR)],\n",
195
+ " check=True,\n",
196
+ ")\n",
197
+ "\n",
198
+ "os.chdir(REPO_DIR)\n",
199
+ "if str(REPO_DIR) not in sys.path:\n",
200
+ " sys.path.insert(0, str(REPO_DIR))\n",
201
+ "\n",
202
+ "print(f'Working directory: {Path.cwd()}')\n",
203
+ "\n",
204
+ "# Clear stale __pycache__ so Unsloth rebuilds compiled kernels fresh\n",
205
+ "for d in REPO_DIR.rglob('__pycache__'):\n",
206
+ " shutil.rmtree(d, ignore_errors=True)\n",
207
+ "print('Cleared __pycache__')"
208
+ ]
209
+ },
210
+ {
211
+ "cell_type": "markdown",
212
+ "metadata": {},
213
+ "source": [
214
+ "## 5. Verify environment"
215
+ ]
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "execution_count": null,
220
+ "metadata": {},
221
+ "outputs": [],
222
+ "source": [
223
+ "import torch\n",
224
+ "\n",
225
+ "print(f'PyTorch: {torch.__version__}')\n",
226
+ "print(f'CUDA: {torch.cuda.is_available()}')\n",
227
+ "if torch.cuda.is_available():\n",
228
+ " print(f'GPU: {torch.cuda.get_device_name(0)}')\n",
229
+ " vram_gb = torch.cuda.get_device_properties(0).total_memory / 1e9\n",
230
+ " print(f'VRAM: {vram_gb:.1f} GB')\n",
231
+ " if vram_gb < 14:\n",
232
+ " print('WARNING: <14 GB VRAM detected. Use 1.5B model + N_GENERATIONS=2')\n",
233
+ "\n",
234
+ "import transformers, unsloth, trl, peft\n",
235
+ "print(f'Transformers: {transformers.__version__}')\n",
236
+ "print(f'Unsloth: {unsloth.__version__}')\n",
237
+ "print(f'TRL: {trl.__version__}')\n",
238
+ "print(f'PEFT: {peft.__version__}')\n",
239
+ "\n",
240
+ "# Verify the critical import that caused the original error\n",
241
+ "try:\n",
242
+ " from transformers.utils.generic import retry # noqa: F401\n",
243
+ " print('transformers.utils.generic.retry: OK')\n",
244
+ "except ImportError:\n",
245
+ " print('WARNING: retry not in transformers.utils.generic — re-run Cell 3')\n",
246
+ "\n",
247
+ "from trl import GRPOConfig, GRPOTrainer\n",
248
+ "from unsloth import FastLanguageModel\n",
249
+ "print('GRPOTrainer + FastLanguageModel: OK')\n",
250
+ "\n",
251
+ "# ── Dataset sanity check (all 5 roles including ADAPT) ────────────────────────\n",
252
+ "from training.dataset import build_episode_dataset\n",
253
+ "_check = build_episode_dataset(n_episodes=4, seed=0, include_adapt=True, domain_episode_ratio=0.30)\n",
254
+ "roles = sorted({r['agent_role'] for r in _check})\n",
255
+ "print(f'Dataset builder: OK — {len(_check)} samples, roles={roles}')\n",
256
+ "assert 'ADAPT' in roles, 'ADAPT role missing from dataset — check domain_episode_ratio > 0'\n",
257
+ "print('ADAPT role confirmed in dataset ✓')\n",
258
+ "\n",
259
+ "# ── ADAPT structural-inference imports ────────────────────────────────────────\n",
260
+ "from multi_agent.adapt import (\n",
261
+ " build_adapt_observation,\n",
262
+ " apply_adapt_mapping,\n",
263
+ " parse_adapt_action,\n",
264
+ " _build_adapt_heuristic,\n",
265
+ ")\n",
266
+ "print('multi_agent.adapt: OK')\n",
267
+ "\n",
268
+ "from training.reward_functions import adapt_reward_fn\n",
269
+ "print('adapt_reward_fn: OK')\n",
270
+ "\n",
271
+ "# ── Domain catalog sanity check ───────────────────────────────────────────────\n",
272
+ "from domains.icu import get_icu_tasks\n",
273
+ "icu_tasks = get_icu_tasks()\n",
274
+ "print(f'ICU domain tasks: {len(icu_tasks)} tasks loaded')"
275
+ ]
276
+ },
277
+ {
278
+ "cell_type": "markdown",
279
+ "metadata": {},
280
+ "source": [
281
+ "## 6. Verify reward diversity\n",
282
+ "\n",
283
+ "GRPO requires **non-zero reward variance** within each group of completions. \n",
284
+ "Constant rewards → zero advantage → no gradient.\n",
285
+ "\n",
286
+ "We verify all 5 roles (AMAN, DMAN, GENERATOR, SUPERVISOR, ADAPT)."
287
+ ]
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "execution_count": null,
292
+ "metadata": {},
293
+ "outputs": [],
294
+ "source": [
295
+ "import statistics\n",
296
+ "from training.reward_functions import (\n",
297
+ " aman_reward_fn, dman_reward_fn, adapt_reward_fn, _parse_partial_credit\n",
298
+ ")\n",
299
+ "from tasks import task_catalog\n",
300
+ "from domains.icu import get_icu_tasks\n",
301
+ "from multi_agent.adapt import build_adapt_observation, _build_adapt_heuristic\n",
302
+ "import json\n",
303
+ "\n",
304
+ "catalog = task_catalog()\n",
305
+ "atc_tid = list(catalog.keys())[0]\n",
306
+ "atc_task = catalog[atc_tid]\n",
307
+ "print(f'ATC test task: {atc_tid} ({len(atc_task.flights)} flights)')\n",
308
+ "\n",
309
+ "# ── Check 1: AMAN reward diversity ────────────────────────────────────────────\n",
310
+ "aman_group = [\n",
311
+ " 'no json here at all',\n",
312
+ " '{\"arrival_slots\": [{\"flight_id\": \"AI101\", \"runway\": \"28L\", \"assigned_minute\": 30, \"hold_minutes\": 0}], \"rationale\": \"ok\"}',\n",
313
+ " '{\"arrival_slots\": [], \"rationale\": \"runway unavailable\"}',\n",
314
+ " '{flight_id: broken json',\n",
315
+ "]\n",
316
+ "aman_rewards = aman_reward_fn(aman_group, task_id=[atc_tid]*4)\n",
317
+ "aman_std = statistics.stdev(aman_rewards)\n",
318
+ "print(f'AMAN rewards: {[round(r,4) for r in aman_rewards]} std={aman_std:.4f}')\n",
319
+ "assert aman_std > 0, 'FAIL: AMAN rewards constant — zero GRPO gradient'\n",
320
+ "print(' PASS: AMAN reward diversity ✓')\n",
321
+ "\n",
322
+ "# ── Check 2: ADAPT reward diversity ───────────────────────────────────────────\n",
323
+ "icu_tasks = get_icu_tasks()\n",
324
+ "icu_tid = list(icu_tasks.keys())[0]\n",
325
+ "icu_task = icu_tasks[icu_tid]\n",
326
+ "print(f'\\nICU test task: {icu_tid} ({len(icu_task.flights)} patients)')\n",
327
+ "\n",
328
+ "obs = build_adapt_observation(icu_task, 'SAFETY_STRICT', domain_name='ICU')\n",
329
+ "\n",
330
+ "# Heuristic baseline action\n",
331
+ "heuristic_action = _build_adapt_heuristic(obs, icu_task)\n",
332
+ "heuristic_json = json.dumps(heuristic_action.model_dump())\n",
333
+ "\n",
334
+ "adapt_group = [\n",
335
+ " 'no json here at all',\n",
336
+ " heuristic_json,\n",
337
+ " '{\"entity_wake_map\": {}, \"entity_priority_map\": {}, \"rationale\": \"passthrough\"}',\n",
338
+ " '{entity_wake_map: broken}',\n",
339
+ "]\n",
340
+ "domain_task_json = json.dumps(icu_task.model_dump() if hasattr(icu_task, 'model_dump') else icu_task.__dict__)\n",
341
+ "adapt_rewards = adapt_reward_fn(\n",
342
+ " adapt_group,\n",
343
+ " task_id=[icu_tid]*4,\n",
344
+ " domain_task_json=[domain_task_json]*4,\n",
345
+ " supervisor_profile=['SAFETY_STRICT']*4,\n",
346
+ ")\n",
347
+ "adapt_std = statistics.stdev(adapt_rewards)\n",
348
+ "print(f'ADAPT rewards: {[round(r,4) for r in adapt_rewards]} std={adapt_std:.4f}')\n",
349
+ "assert adapt_std > 0, 'FAIL: ADAPT rewards constant — check adapt_reward_fn'\n",
350
+ "print(' PASS: ADAPT reward diversity ✓')\n",
351
+ "\n",
352
+ "# ── Check 3: _parse_partial_credit is monotonically generous ─────────────────\n",
353
+ "samples = [\n",
354
+ " ('empty', ''),\n",
355
+ " ('plain text', 'I cannot do this'),\n",
356
+ " ('has brace', '{some content}'),\n",
357
+ " ('has arrival_slots', '{\"arrival_slots\": [...]}'),\n",
358
+ " ('has flight+runway', '{\"arrival_slots\": [{\"flight_id\":\"X\",\"runway\":\"28L\"}]}'),\n",
359
+ "]\n",
360
+ "print('\\n_parse_partial_credit monotonicity:')\n",
361
+ "prev = -1\n",
362
+ "for label, text in samples:\n",
363
+ " c = _parse_partial_credit(text)\n",
364
+ " print(f' {label:25s}: {c:.4f}')\n",
365
+ " assert c >= prev, f'Expected non-decreasing credit, got {c} < {prev}'\n",
366
+ " prev = c\n",
367
+ "\n",
368
+ "print('\\nAll reward diversity checks PASSED.')"
369
+ ]
370
+ },
371
+ {
372
+ "cell_type": "markdown",
373
+ "metadata": {},
374
+ "source": [
375
+ "## 7. W&B setup (optional)"
376
+ ]
377
+ },
378
+ {
379
+ "cell_type": "code",
380
+ "execution_count": null,
381
+ "metadata": {},
382
+ "outputs": [],
383
+ "source": [
384
+ "import os\n",
385
+ "\n",
386
+ "if IS_COLAB and not WANDB_API_KEY:\n",
387
+ " try:\n",
388
+ " from google.colab import userdata\n",
389
+ " WANDB_API_KEY = userdata.get('WANDB_API_KEY')\n",
390
+ " print('Loaded WANDB_API_KEY from Colab secrets')\n",
391
+ " except Exception:\n",
392
+ " pass\n",
393
+ "\n",
394
+ "if WANDB_API_KEY:\n",
395
+ " import wandb\n",
396
+ " wandb.login(key=WANDB_API_KEY, relogin=True)\n",
397
+ " os.environ['WANDB_PROJECT'] = WANDB_PROJECT\n",
398
+ " os.environ['WANDB_MODE'] = 'online'\n",
399
+ " print(f'W&B: online project={WANDB_PROJECT}')\n",
400
+ "else:\n",
401
+ " os.environ['WANDB_MODE'] = 'disabled'\n",
402
+ " print('W&B: disabled (set WANDB_API_KEY to enable)')"
403
+ ]
404
+ },
405
+ {
406
+ "cell_type": "markdown",
407
+ "metadata": {},
408
+ "source": [
409
+ "## 8. Train all agents (AMAN / DMAN / GENERATOR / SUPERVISOR / ADAPT)\n",
410
+ "\n",
411
+ "`training/train_grpo.py` runs:\n",
412
+ "- Load 4-bit QLoRA model\n",
413
+ "- Build episode dataset (30% of episodes routed to **ADAPT** domain-transfer task)\n",
414
+ "- GRPO loop over all 5 agent roles\n",
415
+ "- Save checkpoint + reward curves\n",
416
+ "\n",
417
+ "> **OOM?** Set `N_GENERATIONS=2` or switch to `Qwen2.5-1.5B-Instruct`."
418
+ ]
419
+ },
420
+ {
421
+ "cell_type": "code",
422
+ "execution_count": null,
423
+ "metadata": {},
424
+ "outputs": [],
425
+ "source": [
426
+ "import time, subprocess, sys, os, re\n",
427
+ "from collections import defaultdict\n",
428
+ "\n",
429
+ "train_cmd = [\n",
430
+ " sys.executable, 'training/train_grpo.py',\n",
431
+ " '--model', MODEL_NAME,\n",
432
+ " '--output_dir', str(OUTPUT_DIR),\n",
433
+ " '--episodes', str(EPISODES),\n",
434
+ " '--n_generations', str(N_GENERATIONS),\n",
435
+ " '--lora_rank', str(LORA_RANK),\n",
436
+ " '--seed', str(SEED),\n",
437
+ "]\n",
438
+ "\n",
439
+ "# ── Live reward tracking ───────────────────────────────────────────────────────\n",
440
+ "# TRL logs every logging_steps in dict format:\n",
441
+ "# {'loss': 0.012, 'reward': 0.23, 'reward/AMAN': 0.31, 'reward/ADAPT': 0.18, 'step': 10, ...}\n",
442
+ "ALL_ROLES = ('AMAN', 'DMAN', 'GENERATOR', 'SUPERVISOR', 'ADAPT', 'composite')\n",
443
+ "reward_history = defaultdict(list)\n",
444
+ "loss_history = []\n",
445
+ "step_history = []\n",
446
+ "last_step = -1\n",
447
+ "\n",
448
+ "_re_reward = re.compile(r\"'reward(?:/(\\w+))?':\\s*([-\\d.eE+]+)\")\n",
449
+ "_re_loss = re.compile(r\"'loss':\\s*([-\\d.eE+]+)\")\n",
450
+ "_re_step = re.compile(r\"'step':\\s*(\\d+)\")\n",
451
+ "\n",
452
+ "def _bar(val, lo=-1.0, hi=1.0, width=20):\n",
453
+ " frac = max(0.0, min(1.0, (val - lo) / (hi - lo)))\n",
454
+ " filled = int(frac * width)\n",
455
+ " return f'[{\"#\" * filled}{\"-\" * (width - filled)}] {val:+.3f}'\n",
456
+ "\n",
457
+ "def _live_summary(step):\n",
458
+ " elapsed = time.time() - t0\n",
459
+ " print(f'\\n── step {step:4d} elapsed {elapsed/60:.1f} min ────────────────────')\n",
460
+ " if loss_history:\n",
461
+ " print(f' loss : {loss_history[-1]:.5f}')\n",
462
+ " for role in ALL_ROLES:\n",
463
+ " vals = reward_history.get(role, [])\n",
464
+ " if not vals:\n",
465
+ " continue\n",
466
+ " recent = vals[-min(20, len(vals)):]\n",
467
+ " mean_r = sum(recent) / len(recent)\n",
468
+ " trend = ''\n",
469
+ " if len(vals) >= 40:\n",
470
+ " half = len(vals) // 2\n",
471
+ " early = sum(vals[:half]) / half\n",
472
+ " late = sum(vals[half:]) / (len(vals) - half)\n",
473
+ " trend = ' ↑' if late > early + 0.03 else (' ↓' if late < early - 0.03 else ' →')\n",
474
+ " tag = ' ◆' if role == 'ADAPT' else ' '\n",
475
+ " print(f' {role:10s}{tag}: {_bar(mean_r)}{trend}')\n",
476
+ " print()\n",
477
+ "\n",
478
+ "# ── Launch with live stdout streaming ─────────────────────────────────────────\n",
479
+ "env = os.environ.copy()\n",
480
+ "env['PYTHONUNBUFFERED'] = '1'\n",
481
+ "\n",
482
+ "print('Command:', ' '.join(train_cmd))\n",
483
+ "print('=' * 60)\n",
484
+ "t0 = time.time()\n",
485
+ "proc = subprocess.Popen(\n",
486
+ " train_cmd,\n",
487
+ " stdout=subprocess.PIPE,\n",
488
+ " stderr=subprocess.STDOUT,\n",
489
+ " text=True,\n",
490
+ " bufsize=1,\n",
491
+ " env=env,\n",
492
+ ")\n",
493
+ "\n",
494
+ "for raw_line in proc.stdout:\n",
495
+ " line = raw_line.rstrip('\\n')\n",
496
+ " print(line, flush=True)\n",
497
+ "\n",
498
+ " if \"'reward'\" in line or \"'loss'\" in line:\n",
499
+ " m_step = _re_step.search(line)\n",
500
+ " m_loss = _re_loss.search(line)\n",
501
+ " if m_loss:\n",
502
+ " loss_history.append(float(m_loss.group(1)))\n",
503
+ " for m in _re_reward.finditer(line):\n",
504
+ " role = m.group(1) or 'composite'\n",
505
+ " reward_history[role].append(float(m.group(2)))\n",
506
+ " if m_step:\n",
507
+ " s = int(m_step.group(1))\n",
508
+ " if s != last_step:\n",
509
+ " last_step = s\n",
510
+ " step_history.append(s)\n",
511
+ " _live_summary(s)\n",
512
+ "\n",
513
+ "proc.wait()\n",
514
+ "elapsed = time.time() - t0\n",
515
+ "print('=' * 60)\n",
516
+ "\n",
517
+ "# ── Final summary ─────────────────────────────────────────────────────────────\n",
518
+ "if reward_history:\n",
519
+ " print('\\n=== FINAL REWARD SUMMARY ===')\n",
520
+ " for role in ALL_ROLES:\n",
521
+ " vals = reward_history.get(role, [])\n",
522
+ " if not vals:\n",
523
+ " continue\n",
524
+ " n = len(vals)\n",
525
+ " avg = sum(vals) / n\n",
526
+ " fq = sum(vals[:max(1, n//4)]) / max(1, n//4)\n",
527
+ " lq = sum(vals[max(0, 3*n//4):]) / max(1, n - 3*n//4)\n",
528
+ " arrow = '↑' if lq > fq + 0.03 else ('↓' if lq < fq - 0.03 else '→')\n",
529
+ " adapt_tag = ' ◆' if role == 'ADAPT' else ' '\n",
530
+ " print(f' {role:12s}{adapt_tag}: mean={avg:+.3f} first_q={fq:+.3f} last_q={lq:+.3f} {arrow}')\n",
531
+ "\n",
532
+ "status = 'complete' if proc.returncode == 0 else f'FAILED (exit code {proc.returncode})'\n",
533
+ "print(f'\\nTraining {status} in {elapsed/60:.1f} min')"
534
+ ]
535
+ },
536
+ {
537
+ "cell_type": "markdown",
538
+ "metadata": {},
539
+ "source": [
540
+ "## 9. Plot reward curves\n",
541
+ "\n",
542
+ "All plots saved to `OUTPUT_DIR/plots/*.png`."
543
+ ]
544
+ },
545
+ {
546
+ "cell_type": "code",
547
+ "execution_count": null,
548
+ "metadata": {},
549
+ "outputs": [],
550
+ "source": [
551
+ "import json\n",
552
+ "import matplotlib\n",
553
+ "matplotlib.use('Agg')\n",
554
+ "import matplotlib.pyplot as plt\n",
555
+ "import numpy as np\n",
556
+ "from IPython.display import Image, display\n",
557
+ "from pathlib import Path\n",
558
+ "\n",
559
+ "PLOTS_DIR.mkdir(parents=True, exist_ok=True)\n",
560
+ "curves_path = OUTPUT_DIR / 'reward_curves.json'\n",
561
+ "\n",
562
+ "if not curves_path.exists():\n",
563
+ " print(f'reward_curves.json not found at {curves_path}')\n",
564
+ "else:\n",
565
+ " with open(curves_path) as f:\n",
566
+ " curves = json.load(f)\n",
567
+ "\n",
568
+ " def _ema(vals, span=15):\n",
569
+ " if len(vals) < 2:\n",
570
+ " return vals\n",
571
+ " alpha, ema, out = 2 / (span + 1), vals[0], []\n",
572
+ " for v in vals:\n",
573
+ " ema = alpha * v + (1 - alpha) * ema\n",
574
+ " out.append(ema)\n",
575
+ " return out\n",
576
+ "\n",
577
+ " # ── Plot 1: Per-role reward curves (5 panels) ──────────────────────────────\n",
578
+ " role_colors = {\n",
579
+ " 'AMAN': '#2196F3',\n",
580
+ " 'DMAN': '#4CAF50',\n",
581
+ " 'GENERATOR': '#FF9800',\n",
582
+ " 'SUPERVISOR': '#9C27B0',\n",
583
+ " 'ADAPT': '#F44336', # red — domain-transfer agent\n",
584
+ " }\n",
585
+ " fig, axes = plt.subplots(2, 3, figsize=(18, 10))\n",
586
+ " ax_list = axes.flatten()\n",
587
+ " for idx, (role, color) in enumerate(role_colors.items()):\n",
588
+ " ax = ax_list[idx]\n",
589
+ " raw = curves.get(role, [])\n",
590
+ " if not raw:\n",
591
+ " ax.text(0.5, 0.5, f'No {role} data', ha='center', va='center',\n",
592
+ " transform=ax.transAxes, color='grey')\n",
593
+ " ax.set_title(role)\n",
594
+ " continue\n",
595
+ " steps = range(len(raw))\n",
596
+ " ax.plot(steps, raw, alpha=0.25, color=color, lw=0.8, label='raw')\n",
597
+ " ax.plot(steps, _ema(raw), color=color, lw=2.0, label='EMA-15')\n",
598
+ " ax.axhline(0, color='black', lw=0.5, ls='--')\n",
599
+ " ax.set_xlabel('Training step')\n",
600
+ " ax.set_ylabel('Reward')\n",
601
+ " label_suffix = ' (domain transfer)' if role == 'ADAPT' else ''\n",
602
+ " ax.set_title(f'{role}{label_suffix}', fontweight='bold')\n",
603
+ " ax.set_ylim(-1.05, 1.05)\n",
604
+ " ax.legend(fontsize=9)\n",
605
+ " ax.grid(alpha=0.3)\n",
606
+ "\n",
607
+ " # 6th panel: composite\n",
608
+ " ax_comp = ax_list[5]\n",
609
+ " comp = curves.get('composite', [])\n",
610
+ " if comp:\n",
611
+ " steps = range(len(comp))\n",
612
+ " ax_comp.plot(steps, comp, alpha=0.25, color='#607D8B', lw=0.8, label='raw')\n",
613
+ " ax_comp.plot(steps, _ema(comp), color='#607D8B', lw=2.0, label='EMA-15')\n",
614
+ " ax_comp.axhline(0, color='black', lw=0.5, ls='--')\n",
615
+ " ax_comp.set_xlabel('Training step')\n",
616
+ " ax_comp.set_ylabel('Reward')\n",
617
+ " ax_comp.set_title('Composite (all roles)', fontweight='bold')\n",
618
+ " ax_comp.set_ylim(-1.05, 1.05)\n",
619
+ " ax_comp.legend(fontsize=9)\n",
620
+ " ax_comp.grid(alpha=0.3)\n",
621
+ " else:\n",
622
+ " ax_list[5].set_visible(False)\n",
623
+ "\n",
624
+ " fig.suptitle('ATC Multi-Agent GRPO — Per-Role Reward Curves (incl. ADAPT)',\n",
625
+ " fontsize=14, fontweight='bold', y=1.01)\n",
626
+ " fig.tight_layout()\n",
627
+ " p1 = PLOTS_DIR / 'per_role_rewards.png'\n",
628
+ " fig.savefig(p1, dpi=150, bbox_inches='tight')\n",
629
+ " plt.close(fig)\n",
630
+ " print(f'Saved: {p1}')\n",
631
+ " display(Image(filename=str(p1)))\n",
632
+ "\n",
633
+ " # ── Plot 2: Composite reward + rolling std (GRPO health) ──────────────────\n",
634
+ " composite = curves.get('composite', [])\n",
635
+ " if composite:\n",
636
+ " w = 20\n",
637
+ " stds = [float(np.std(composite[max(0, i-w):i+1])) for i in range(len(composite))]\n",
638
+ " fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), sharex=True)\n",
639
+ " steps = range(len(composite))\n",
640
+ " ax1.plot(steps, composite, alpha=0.25, color='#607D8B', lw=0.8)\n",
641
+ " ax1.plot(steps, _ema(composite), color='#607D8B', lw=2.0, label='EMA-15')\n",
642
+ " ax1.axhline(0, color='black', lw=0.6, ls='--')\n",
643
+ " ax1.set_ylabel('Composite reward')\n",
644
+ " ax1.set_ylim(-1.05, 1.05)\n",
645
+ " ax1.set_title('Composite reward (all 5 roles)', fontweight='bold')\n",
646
+ " ax1.grid(alpha=0.3)\n",
647
+ " ax1.legend(fontsize=9)\n",
648
+ " ax2.plot(steps, stds, color='#E91E63', lw=1.5, label=f'rolling std (w={w})')\n",
649
+ " ax2.axhline(0.01, color='red', lw=0.8, ls=':', label='collapse threshold 0.01')\n",
650
+ " ax2.set_xlabel('Training step')\n",
651
+ " ax2.set_ylabel('Within-group std')\n",
652
+ " ax2.set_title('Reward diversity — must stay > 0.01 for GRPO gradient', fontweight='bold')\n",
653
+ " ax2.grid(alpha=0.3)\n",
654
+ " ax2.legend(fontsize=9)\n",
655
+ " fig.tight_layout()\n",
656
+ " p2 = PLOTS_DIR / 'composite_and_std.png'\n",
657
+ " fig.savefig(p2, dpi=150, bbox_inches='tight')\n",
658
+ " plt.close(fig)\n",
659
+ " print(f'Saved: {p2}')\n",
660
+ " display(Image(filename=str(p2)))\n",
661
+ "\n",
662
+ " # ── Plot 3: ADAPT domain-transfer deep dive ────────────────────────────────\n",
663
+ " adapt_vals = curves.get('ADAPT', [])\n",
664
+ " if len(adapt_vals) >= 4:\n",
665
+ " fig, axes = plt.subplots(1, 2, figsize=(14, 5))\n",
666
+ "\n",
667
+ " # Left: ADAPT reward over training\n",
668
+ " ax = axes[0]\n",
669
+ " steps = range(len(adapt_vals))\n",
670
+ " ax.plot(steps, adapt_vals, alpha=0.25, color='#F44336', lw=0.8, label='raw')\n",
671
+ " ax.plot(steps, _ema(adapt_vals), color='#F44336', lw=2.5, label='EMA-15')\n",
672
+ " ax.axhline(0, color='black', lw=0.6, ls='--')\n",
673
+ " ax.set_xlabel('Training step')\n",
674
+ " ax.set_ylabel('Reward')\n",
675
+ " ax.set_title('ADAPT: domain-transfer reward over training', fontweight='bold')\n",
676
+ " ax.set_ylim(-1.05, 1.05)\n",
677
+ " ax.legend(fontsize=9)\n",
678
+ " ax.grid(alpha=0.3)\n",
679
+ "\n",
680
+ " # Right: ADAPT vs other roles first/last quarter comparison\n",
681
+ " ax = axes[1]\n",
682
+ " all_roles_data = {r: curves.get(r, []) for r in\n",
683
+ " ['AMAN', 'DMAN', 'GENERATOR', 'SUPERVISOR', 'ADAPT']}\n",
684
+ " roles_ok = [r for r, v in all_roles_data.items() if len(v) >= 8]\n",
685
+ " x = np.arange(len(roles_ok))\n",
686
+ " fq_vals, lq_vals, colors_bar = [], [], []\n",
687
+ " _role_colors = {\n",
688
+ " 'AMAN': '#90CAF9', 'DMAN': '#A5D6A7',\n",
689
+ " 'GENERATOR': '#FFCC80', 'SUPERVISOR': '#CE93D8', 'ADAPT': '#EF9A9A',\n",
690
+ " }\n",
691
+ " for role in roles_ok:\n",
692
+ " r = all_roles_data[role]\n",
693
+ " n = len(r)\n",
694
+ " fq_vals.append(float(np.mean(r[:max(1, n//4)])))\n",
695
+ " lq_vals.append(float(np.mean(r[max(0, 3*n//4):])))\n",
696
+ " colors_bar.append(_role_colors.get(role, '#BDBDBD'))\n",
697
+ " b1 = ax.bar(x - 0.2, fq_vals, 0.35, label='First quarter',\n",
698
+ " color=[c + '88' for c in colors_bar] if False else colors_bar,\n",
699
+ " edgecolor='#333', alpha=0.6)\n",
700
+ " b2 = ax.bar(x + 0.2, lq_vals, 0.35, label='Last quarter',\n",
701
+ " color=colors_bar, edgecolor='#333')\n",
702
+ " for b in list(b1) + list(b2):\n",
703
+ " ax.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.01,\n",
704
+ " f'{b.get_height():.3f}', ha='center', va='bottom', fontsize=8)\n",
705
+ " ax.set_xticks(x)\n",
706
+ " ax.set_xticklabels(roles_ok, fontsize=11)\n",
707
+ " ax.set_ylabel('Mean reward')\n",
708
+ " ax.set_title('First vs last quarter — evidence of learning per role', fontweight='bold')\n",
709
+ " ax.axhline(0, color='black', lw=0.6, ls='--')\n",
710
+ " ax.legend()\n",
711
+ " ax.grid(axis='y', alpha=0.3)\n",
712
+ "\n",
713
+ " fig.suptitle('ADAPT Domain-Transfer Training Analysis', fontsize=13, fontweight='bold')\n",
714
+ " fig.tight_layout()\n",
715
+ " p3 = PLOTS_DIR / 'adapt_analysis.png'\n",
716
+ " fig.savefig(p3, dpi=150, bbox_inches='tight')\n",
717
+ " plt.close(fig)\n",
718
+ " print(f'Saved: {p3}')\n",
719
+ " display(Image(filename=str(p3)))"
720
+ ]
721
+ },
722
+ {
723
+ "cell_type": "markdown",
724
+ "metadata": {},
725
+ "source": [
726
+ "## 10. Before vs after comparison\n",
727
+ "\n",
728
+ "Heuristic baseline (no LLM) · base model (untrained LoRA) · trained model \n",
729
+ "Includes **ADAPT domain-transfer metrics** alongside ATC metrics."
730
+ ]
731
+ },
732
+ {
733
+ "cell_type": "code",
734
+ "execution_count": null,
735
+ "metadata": {},
736
+ "outputs": [],
737
+ "source": [
738
+ "import json\n",
739
+ "import matplotlib\n",
740
+ "matplotlib.use('Agg')\n",
741
+ "import matplotlib.pyplot as plt\n",
742
+ "import numpy as np\n",
743
+ "from IPython.display import Image, display\n",
744
+ "from pathlib import Path\n",
745
+ "\n",
746
+ "def _load(p):\n",
747
+ " p = Path(p)\n",
748
+ " return json.loads(p.read_text()) if p.exists() else None\n",
749
+ "\n",
750
+ "baseline = _load(OUTPUT_DIR / 'baseline_metrics.json')\n",
751
+ "base_mdl = _load(OUTPUT_DIR / 'base_model_metrics.json')\n",
752
+ "trained = _load(OUTPUT_DIR / 'trained_model_metrics.json')\n",
753
+ "\n",
754
+ "if not any([baseline, base_mdl, trained]):\n",
755
+ " print('No eval metrics found. Run training without --no_eval.')\n",
756
+ "else:\n",
757
+ " keys = [\n",
758
+ " ('mean_composite', 'Composite score'),\n",
759
+ " ('mean_aman_reward', 'AMAN reward'),\n",
760
+ " ('mean_dman_reward', 'DMAN reward'),\n",
761
+ " ('mean_adapt_reward', 'ADAPT domain-transfer ◆'),\n",
762
+ " ('mean_conflicts', 'Avg conflicts (↓ better)'),\n",
763
+ " ('adapt_downstream_gain', 'ADAPT downstream gain ◆'),\n",
764
+ " ]\n",
765
+ " print(f'{\"Metric\":30s} {\"Heuristic\":>12} {\"Base model\":>12} {\"Trained\":>12}')\n",
766
+ " print('-' * 70)\n",
767
+ " for k, label in keys:\n",
768
+ " bv = f'{baseline.get(k, float(\"nan\")):.3f}' if baseline else 'N/A'\n",
769
+ " mv = f'{base_mdl.get(k, float(\"nan\")):.3f}' if base_mdl else 'N/A'\n",
770
+ " tv = f'{trained.get(k, float(\"nan\")):.3f}' if trained else 'N/A'\n",
771
+ " print(f'{label:30s} {bv:>12} {mv:>12} {tv:>12}')\n",
772
+ "\n",
773
+ " sources = []\n",
774
+ " if baseline: sources.append(('Heuristic\\nbaseline', baseline, '#B0BEC5'))\n",
775
+ " if base_mdl: sources.append(('Base model\\n(no finetune)', base_mdl, '#90CAF9'))\n",
776
+ " if trained: sources.append(('Trained\\nmodel', trained, '#A5D6A7'))\n",
777
+ "\n",
778
+ " if sources:\n",
779
+ " # ATC metrics bar chart\n",
780
+ " atc_keys = [\n",
781
+ " ('mean_composite', 'Composite'),\n",
782
+ " ('mean_aman_reward', 'AMAN'),\n",
783
+ " ('mean_dman_reward', 'DMAN'),\n",
784
+ " ]\n",
785
+ " # ADAPT metrics bar chart\n",
786
+ " adapt_keys = [\n",
787
+ " ('mean_adapt_reward', 'ADAPT reward'),\n",
788
+ " ('adapt_downstream_gain', 'Downstream gain'),\n",
789
+ " ]\n",
790
+ "\n",
791
+ " fig, axes = plt.subplots(1, len(atc_keys) + len(adapt_keys),\n",
792
+ " figsize=(5 * (len(atc_keys) + len(adapt_keys)), 5))\n",
793
+ " all_plot_keys = atc_keys + adapt_keys\n",
794
+ " is_adapt = [False] * len(atc_keys) + [True] * len(adapt_keys)\n",
795
+ "\n",
796
+ " for ax, (k, label), adapt_flag in zip(axes, all_plot_keys, is_adapt):\n",
797
+ " vals = [s[1].get(k, 0.0) for s in sources]\n",
798
+ " labels = [s[0] for s in sources]\n",
799
+ " colors = [s[2] for s in sources]\n",
800
+ " if adapt_flag:\n",
801
+ " colors = ['#FFCDD2', '#EF9A9A', '#F44336'][:len(sources)]\n",
802
+ " bars = ax.bar(labels, vals, color=colors, edgecolor='#333', width=0.55)\n",
803
+ " for b, v in zip(bars, vals):\n",
804
+ " ax.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.01,\n",
805
+ " f'{v:.3f}', ha='center', va='bottom', fontsize=10)\n",
806
+ " title_suffix = ' ◆' if adapt_flag else ''\n",
807
+ " ax.set_title(f'{label}{title_suffix}', fontweight='bold')\n",
808
+ " ax.set_ylabel('Score')\n",
809
+ " ax.set_ylim(0, 1.15)\n",
810
+ " ax.grid(axis='y', alpha=0.3)\n",
811
+ " if adapt_flag:\n",
812
+ " ax.set_facecolor('#FFF8F8')\n",
813
+ "\n",
814
+ " fig.suptitle('Before vs After GRPO Training (◆ = ADAPT domain-transfer metrics)',\n",
815
+ " fontsize=13, fontweight='bold', y=1.03)\n",
816
+ " fig.tight_layout()\n",
817
+ " p_eval = PLOTS_DIR / 'eval_comparison.png'\n",
818
+ " fig.savefig(p_eval, dpi=150, bbox_inches='tight')\n",
819
+ " plt.close(fig)\n",
820
+ " print(f'\\nSaved: {p_eval}')\n",
821
+ " display(Image(filename=str(p_eval)))"
822
+ ]
823
+ },
824
+ {
825
+ "cell_type": "markdown",
826
+ "metadata": {},
827
+ "source": [
828
+ "## 11. Summary"
829
+ ]
830
+ },
831
+ {
832
+ "cell_type": "code",
833
+ "execution_count": null,
834
+ "metadata": {},
835
+ "outputs": [],
836
+ "source": [
837
+ "print('=' * 60)\n",
838
+ "print(' ATC + ADAPT GRPO Training — Run Complete')\n",
839
+ "print('=' * 60)\n",
840
+ "print(f' Model: {MODEL_NAME}')\n",
841
+ "print(f' Episodes: {EPISODES}')\n",
842
+ "print(f' Group size: {N_GENERATIONS}')\n",
843
+ "print(f' LoRA rank: {LORA_RANK}')\n",
844
+ "print(f' Domain episode ratio:{DOMAIN_EPISODE_RATIO} → ADAPT agent')\n",
845
+ "print(f' Output: {OUTPUT_DIR}')\n",
846
+ "print(f' Plots: {PLOTS_DIR}')\n",
847
+ "print()\n",
848
+ "print(' Agents trained:')\n",
849
+ "print(' AMAN — arrival sequencing & hold negotiation')\n",
850
+ "print(' DMAN — departure ATFM compliance & prioritisation')\n",
851
+ "print(' GENERATOR — adversarial scenario mutation')\n",
852
+ "print(' SUPERVISOR — preference-aware plan evaluation')\n",
853
+ "print(' ADAPT ◆ — domain-agnostic structural inference (ICU → ATC wake/priority)')\n",
854
+ "print()\n",
855
+ "print(' ADAPT reward composition:')\n",
856
+ "print(' 0.70 × downstream AMAN+DMAN score on mapped task')\n",
857
+ "print(' 0.15 × improvement over heuristic baseline on unmapped task')\n",
858
+ "print(' 0.10 × entity coverage (all entity types mapped)')\n",
859
+ "print(' 0.05 × rationale quality (verifiable structural reasoning)')\n",
860
+ "print()\n",
861
+ "print(' Output files:')\n",
862
+ "all_files = sorted(OUTPUT_DIR.rglob('*.json')) + sorted(PLOTS_DIR.rglob('*.png'))\n",
863
+ "for f in all_files:\n",
864
+ " print(f' {f.relative_to(OUTPUT_DIR)}')\n",
865
+ "print('=' * 60)"
866
+ ]
867
+ },
868
+ {
869
+ "cell_type": "markdown",
870
+ "metadata": {},
871
+ "source": [
872
+ "## Troubleshooting\n",
873
+ "\n",
874
+ "| Symptom | Fix |\n",
875
+ "|---|---|\n",
876
+ "| `retry` ImportError | Re-run Cell 3 — do NOT add `--no-deps` to the unsloth install line |\n",
877
+ "| CUDA OOM | Set `N_GENERATIONS=2`; use `Qwen2.5-1.5B-Instruct` |\n",
878
+ "| `GRPOConfig` keyword error | Confirm `trl==0.15.2` printed in Cell 3 output |\n",
879
+ "| ADAPT role missing from dataset | Confirm `domain_episode_ratio > 0` and ICU domain loaded |\n",
880
+ "| ADAPT rewards constant | `os.environ['ATC_REWARD_TRACE']='1'` before training to trace per-component values |\n",
881
+ "| Rewards still constant (any role) | `os.environ['ATC_REWARD_TRACE']='1'` before training |\n",
882
+ "| Disconnect mid-training | Enable Drive mount (`USE_DRIVE=True`) |\n",
883
+ "| Kaggle: slow training | Keep `BATCH_SIZE=2`, `N_GENERATIONS=4` as-is |\n",
884
+ "\n",
885
+ "**Reward trace**: `os.environ['ATC_REWARD_TRACE'] = '1'` — prints per-component breakdown per completion for all 5 roles."
886
+ ]
887
+ }
888
+ ],
889
+ "metadata": {
890
+ "accelerator": "GPU",
891
+ "colab": {
892
+ "gpuType": "T4",
893
+ "provenance": []
894
+ },
895
+ "kernelspec": {
896
+ "display_name": "Python 3",
897
+ "name": "python3"
898
+ },
899
+ "language_info": {
900
+ "name": "python",
901
+ "version": "3.10.0"
902
+ }
903
+ },
904
+ "nbformat": 4,
905
+ "nbformat_minor": 0
906
+ }
atc_env/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """ATC multi-agent OpenEnv package.
2
+
3
+ Exports the three core types needed by openenv and by the TRL rollout function.
4
+ """
5
+
6
+ from .models import ATCAction, ATCObservation, ATCState
7
+
8
+ __all__ = ["ATCAction", "ATCObservation", "ATCState"]
atc_env/client.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenEnv-compliant client for the ATC multi-agent environment.
2
+
3
+ Usage (async):
4
+ async with ATCEnvClient(base_url="http://localhost:8000") as env:
5
+ result = await env.reset(episode_id="0", task_id="bengaluru_irrops_hard")
6
+ obs = result.observation # ATCObservation
7
+
8
+ action = ATCAction(
9
+ aman_completion=aman_llm_output,
10
+ dman_completion=dman_llm_output,
11
+ round_type="bid",
12
+ )
13
+ result = await env.step(action)
14
+ if result.done:
15
+ print(f"Episode done. Reward: {result.reward:.3f}")
16
+
17
+ Usage (sync, handy for scripts):
18
+ env = ATCEnvClient(base_url="http://localhost:8000").sync()
19
+ result = env.reset()
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Any, Dict
25
+
26
+ try:
27
+ from openenv.core import EnvClient, StepResult
28
+ _OPENENV_AVAILABLE = True
29
+ except ImportError:
30
+ _OPENENV_AVAILABLE = False
31
+
32
+ from .models import ATCAction, ATCObservation, ATCState
33
+
34
+
35
+ if _OPENENV_AVAILABLE:
36
+ class ATCEnvClient(EnvClient[ATCAction, ATCObservation, ATCState]):
37
+ """Thin OpenEnv client wrapping the ATC multi-agent server."""
38
+
39
+ def _step_payload(self, action: ATCAction) -> Dict[str, Any]:
40
+ return action.model_dump()
41
+
42
+ def _parse_result(self, payload: Dict[str, Any]) -> "StepResult[ATCObservation]":
43
+ obs = ATCObservation(**payload["observation"])
44
+ return StepResult(
45
+ observation=obs,
46
+ reward=payload.get("reward"),
47
+ done=payload.get("done", False),
48
+ )
49
+
50
+ def _parse_state(self, payload: Dict[str, Any]) -> ATCState:
51
+ return ATCState(**payload)
52
+
53
+ else:
54
+ class ATCEnvClient: # type: ignore[no-redef]
55
+ """Stub when openenv is not installed — raises on use."""
56
+
57
+ def __init__(self, *args, **kwargs):
58
+ raise ImportError(
59
+ "openenv package is required for ATCEnvClient. "
60
+ "Install with: pip install openenv"
61
+ )
atc_env/models.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenEnv-compliant Pydantic models for the ATC multi-agent environment.
2
+
3
+ Inherits from openenv.core base classes so the models satisfy the OpenEnv
4
+ server and client contracts without boilerplate.
5
+
6
+ Action → ATCAction (carries one full AMAN+DMAN turn)
7
+ Observation → ATCObservation (what both agents receive after each step)
8
+ State → ATCState (full episode state snapshot, JSON-serialisable)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, Dict, List, Optional
14
+
15
+ from pydantic import Field
16
+
17
+ try:
18
+ from openenv.core.env_server import Action, Observation, State
19
+ except ImportError:
20
+ # Graceful fallback so the module can be imported without openenv installed
21
+ from pydantic import BaseModel as Action, BaseModel as Observation, BaseModel as State
22
+
23
+
24
+ class ATCAction(Action):
25
+ """Combined AMAN + DMAN action submitted in a single environment step.
26
+
27
+ Both agents generate completions independently; the server side parses each
28
+ into its typed action (AMANAction / DMANAction) and routes them to the
29
+ multi-agent environment.
30
+ """
31
+
32
+ aman_completion: str = Field(default="", description="Raw LLM completion from AMAN agent")
33
+ dman_completion: str = Field(default="", description="Raw LLM completion from DMAN agent")
34
+ round_type: str = Field(
35
+ default="bid",
36
+ description="Episode round: 'bid' | 'negotiate'",
37
+ )
38
+
39
+
40
+ class ATCObservation(Observation):
41
+ """What both agents receive after each environment step.
42
+
43
+ Inherits `done`, `reward`, and `metadata` from the OpenEnv base class.
44
+ Adds ATC-specific fields that the agents need to generate their next action.
45
+ """
46
+
47
+ aman_prompt: str = Field(default="", description="Full prompt text for AMAN agent")
48
+ dman_prompt: str = Field(default="", description="Full prompt text for DMAN agent")
49
+ round_type: str = Field(default="bid")
50
+ round_number: int = Field(default=0, ge=0)
51
+ conflict_log: List[str] = Field(default_factory=list)
52
+ task_id: str = Field(default="")
53
+
54
+ # Per-role rewards are emitted on the final step (done=True).
55
+ aman_reward: Optional[float] = Field(default=None)
56
+ dman_reward: Optional[float] = Field(default=None)
57
+ composite_score: Optional[float] = Field(default=None)
58
+
59
+
60
+ class ATCState(State):
61
+ """Full episode state snapshot.
62
+
63
+ Inherits `episode_id` and `step_count` from the OpenEnv base class.
64
+ """
65
+
66
+ task_id: str = Field(default="")
67
+ supervisor_profile: str = Field(default="safety_strict")
68
+ negotiation_rounds: int = Field(default=0, ge=0)
69
+ aman_reward: float = Field(default=0.0)
70
+ dman_reward: float = Field(default=0.0)
71
+ composite_score: float = Field(default=0.0)
72
+ generator_difficulty: int = Field(default=1, ge=1, le=6)
atc_env/server/__init__.py ADDED
File without changes
atc_env/server/app.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI app created via the OpenEnv factory.
2
+
3
+ One line wires the full OpenEnv HTTP surface:
4
+ POST /reset
5
+ POST /step
6
+ GET /state
7
+ GET /health (added by create_app)
8
+
9
+ Usage:
10
+ uvicorn atc_env.server.app:app --host 0.0.0.0 --port 8000
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import sys
16
+ import os
17
+
18
+ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
19
+ if ROOT not in sys.path:
20
+ sys.path.insert(0, ROOT)
21
+
22
+ from openenv.core.env_server import create_app
23
+
24
+ from ..models import ATCAction, ATCObservation
25
+ from .atc_environment import ATCEnvironment
26
+
27
+ app = create_app(
28
+ ATCEnvironment,
29
+ ATCAction,
30
+ ATCObservation,
31
+ env_name="atc_env",
32
+ )
atc_env/server/atc_environment.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenEnv server-side environment wrapping the multi-agent ATC core.
2
+
3
+ Implements the three-method OpenEnv Environment interface:
4
+ reset(seed, episode_id, **kwargs) -> ATCObservation
5
+ step(action, **kwargs) -> ATCObservation
6
+ state (property) -> ATCState
7
+
8
+ The underlying MultiAgentATCEnvironment runs a 3-round protocol:
9
+ Round 0 BID → step(round_type="bid")
10
+ Round 1 NEGOTIATE → step(round_type="negotiate") [skipped when no conflicts]
11
+ Round 2 FINAL → done=True, per-role rewards emitted
12
+
13
+ SUPPORTS_CONCURRENT_SESSIONS = True because TRL spawns multiple rollout workers.
14
+ Each worker creates its own server instance via the OpenEnv create_app factory,
15
+ so no shared mutable state exists between sessions.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import sys
21
+ import os
22
+ from typing import Optional
23
+
24
+ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
25
+ if ROOT not in sys.path:
26
+ sys.path.insert(0, ROOT)
27
+
28
+ try:
29
+ from openenv.core.env_server import Environment
30
+ _OPENENV_AVAILABLE = True
31
+ except ImportError:
32
+ _OPENENV_AVAILABLE = False
33
+
34
+ from multi_agent.environment import MAX_NEGOTIATE_ROUNDS, MultiAgentATCEnvironment, count_separation_issues
35
+ from multi_agent.generator import ChallengeGenerator
36
+ from multi_agent.supervisor import SupervisorAgent
37
+ from tasks import ordered_tasks
38
+ from training.dataset import parse_aman_action, parse_dman_action
39
+
40
+ from ..models import ATCAction, ATCObservation, ATCState
41
+
42
+
43
+ def _make_env_base():
44
+ if _OPENENV_AVAILABLE:
45
+ return Environment
46
+ # Minimal duck-type base when openenv not installed
47
+ class _Base:
48
+ SUPPORTS_CONCURRENT_SESSIONS = True
49
+ return _Base
50
+
51
+
52
+ _EnvBase = _make_env_base()
53
+
54
+
55
+ class ATCEnvironment(_EnvBase):
56
+ """Multi-agent ATC environment conforming to the OpenEnv server interface."""
57
+
58
+ SUPPORTS_CONCURRENT_SESSIONS = True
59
+
60
+ def __init__(self) -> None:
61
+ if _OPENENV_AVAILABLE:
62
+ super().__init__()
63
+ self._env = MultiAgentATCEnvironment(seed=42)
64
+ self._generator = ChallengeGenerator(seed=42)
65
+ self._supervisor = SupervisorAgent()
66
+ self._task_list = list(ordered_tasks())
67
+ self._episode_state = ATCState()
68
+
69
+ # ── OpenEnv interface ─────────────────────────────────────────────────────
70
+
71
+ def reset(self, seed=None, episode_id=None, **kwargs) -> ATCObservation:
72
+ """Start a new episode.
73
+
74
+ kwargs accepted:
75
+ task_id (str): specific task to load; random if omitted
76
+ use_generator (bool): apply adversarial mutations (default True)
77
+ """
78
+ task_id = kwargs.get("task_id")
79
+ use_generator = kwargs.get("use_generator", True)
80
+ ep_id = int(episode_id or 0)
81
+
82
+ # Apply adaptive curriculum mutation when requested
83
+ mutated_task = None
84
+ if use_generator:
85
+ import random
86
+ rng = random.Random(seed or ep_id)
87
+ if task_id:
88
+ from tasks import task_catalog
89
+ base = task_catalog().get(task_id)
90
+ else:
91
+ base = rng.choice(self._task_list)
92
+ if base:
93
+ mutated_task, _ = self._generator.mutate(base)
94
+
95
+ aman_obs, dman_obs = self._env.reset(
96
+ task_id=task_id,
97
+ episode_id=ep_id,
98
+ mutated_task=mutated_task,
99
+ )
100
+
101
+ self._episode_state = ATCState(
102
+ episode_id=str(ep_id),
103
+ task_id=aman_obs.task_id,
104
+ supervisor_profile=aman_obs.supervisor_profile_name.value,
105
+ generator_difficulty=self._generator.difficulty_level,
106
+ )
107
+
108
+ return ATCObservation(
109
+ aman_prompt=aman_obs.to_prompt_text(),
110
+ dman_prompt=dman_obs.to_prompt_text(),
111
+ round_type="bid",
112
+ round_number=0,
113
+ task_id=aman_obs.task_id,
114
+ done=False,
115
+ )
116
+
117
+ def step(self, action: ATCAction, timeout_s=None, **kwargs) -> ATCObservation:
118
+ """Process one agent turn.
119
+
120
+ round_type="bid" → BID round, may trigger auto-finalize if no conflicts
121
+ round_type="negotiate" → NEGOTIATE + FINAL, always returns done=True
122
+ """
123
+ self._episode_state.step_count += 1
124
+
125
+ aman_action = parse_aman_action(action.aman_completion)
126
+ dman_action = parse_dman_action(action.dman_completion)
127
+
128
+ # Fallback to empty actions when parsing fails (penalised by reward)
129
+ from multi_agent.models import AMANAction, DMANAction
130
+ if aman_action is None:
131
+ aman_action = AMANAction(arrival_slots=[], rationale="parse_error")
132
+ if dman_action is None:
133
+ dman_action = DMANAction(departure_slots=[], rationale="parse_error")
134
+
135
+ if action.round_type == "bid":
136
+ aman_obs, dman_obs, partial_reward, done = self._env.step_bid(
137
+ aman_action, dman_action
138
+ )
139
+ if done:
140
+ return self._finalize(partial_reward)
141
+
142
+ self._episode_state.step_count += 1 # negotiate will be next
143
+ return ATCObservation(
144
+ aman_prompt=aman_obs.to_prompt_text(),
145
+ dman_prompt=dman_obs.to_prompt_text(),
146
+ round_type="negotiate",
147
+ round_number=1,
148
+ conflict_log=aman_obs.conflict_log,
149
+ task_id=self._episode_state.task_id,
150
+ reward=partial_reward,
151
+ done=False,
152
+ )
153
+
154
+ # negotiate → apply client revision, then optional heuristic-only repair passes
155
+ aman_obs, dman_obs, partial_reward, _ = self._env.step_negotiate(
156
+ aman_action, dman_action
157
+ )
158
+ if count_separation_issues(self._env._state.conflict_log) > 0:
159
+ from multi_agent.inference import (
160
+ _build_aman_heuristic,
161
+ _build_dman_heuristic,
162
+ _dman_obs_with_aman_messages,
163
+ )
164
+
165
+ atfm = self._env._state.atfm_deadlines
166
+ for _ in range(1, MAX_NEGOTIATE_ROUNDS):
167
+ if count_separation_issues(self._env._state.conflict_log) == 0:
168
+ break
169
+ aman_h = _build_aman_heuristic(aman_obs, separation_repair=1)
170
+ dman_obs_m = _dman_obs_with_aman_messages(dman_obs, aman_h)
171
+ dman_h = _build_dman_heuristic(dman_obs_m, atfm, separation_repair=1)
172
+ aman_obs, dman_obs, partial_reward, _ = self._env.step_negotiate(
173
+ aman_h, dman_h
174
+ )
175
+ return self._finalize(partial_reward)
176
+
177
+ @property
178
+ def state(self) -> ATCState:
179
+ return self._episode_state
180
+
181
+ # ── Internal helpers ──────────────────────────────────────────────────────
182
+
183
+ def _finalize(self, partial_reward: float) -> ATCObservation:
184
+ result = self._env.finalize()
185
+
186
+ # Update generator curriculum
187
+ self._generator.update(result.composite_score)
188
+
189
+ self._episode_state.aman_reward = result.aman_reward
190
+ self._episode_state.dman_reward = result.dman_reward
191
+ self._episode_state.composite_score = result.composite_score
192
+ self._episode_state.negotiation_rounds = result.negotiation_rounds
193
+ self._episode_state.generator_difficulty = self._generator.difficulty_level
194
+
195
+ composite = (result.aman_reward + result.dman_reward) / 2.0
196
+
197
+ return ATCObservation(
198
+ aman_prompt="",
199
+ dman_prompt="",
200
+ round_type="final",
201
+ round_number=2,
202
+ task_id=self._episode_state.task_id,
203
+ reward=round(composite, 4),
204
+ done=True,
205
+ aman_reward=result.aman_reward,
206
+ dman_reward=result.dman_reward,
207
+ composite_score=result.composite_score,
208
+ )
constants.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared constants for ATC optimization environment.
2
+
3
+ This module centralizes all magic numbers and configuration constants
4
+ to support the DRY (Don't Repeat Yourself) principle and ease tuning.
5
+ """
6
+
7
+ from typing import Dict, Tuple
8
+
9
+ # ============================================================================
10
+ # Wake Turbulence Separation Rules (minutes)
11
+ # ============================================================================
12
+ # Minimum spacing required between aircraft based on wake classes
13
+ # H=Heavy, M=Medium, L=Light
14
+ SEPARATION_BY_WAKE: Dict[Tuple[str, str], int] = {
15
+ ("H", "H"): 4, # Heavy to Heavy: 4 min
16
+ ("H", "M"): 5, # Heavy to Medium: 5 min
17
+ ("H", "L"): 6, # Heavy to Light: 6 min
18
+ ("M", "H"): 3, # Medium to Heavy: 3 min
19
+ ("M", "M"): 3, # Medium to Medium: 3 min
20
+ ("M", "L"): 4, # Medium to Light: 4 min
21
+ ("L", "H"): 3, # Light to Heavy: 3 min
22
+ ("L", "M"): 3, # Light to Medium: 3 min
23
+ ("L", "L"): 3, # Light to Light: 3 min
24
+ }
25
+
26
+
27
+
28
+ # ============================================================================
29
+ # Normalized Score Calculation Weights
30
+ # ============================================================================
31
+ # Weights for combining multiple metrics into final score
32
+ # Sum must equal 1.0 for balanced weighting
33
+ SCORE_WEIGHTS: Dict[str, float] = {
34
+ "completeness": 0.24, # Schedule completeness (24%)
35
+ "conflict_free": 0.24, # Conflict-free ratio (24%)
36
+ "priority": 0.18, # Priority handling (18%)
37
+ "delay": 0.16, # Delay efficiency (16%)
38
+ "fairness": 0.10, # Fairness across airlines (10%)
39
+ "fuel": 0.08, # Fuel efficiency (8%)
40
+ }
41
+
42
+ # Validate weights sum to 1.0
43
+ _WEIGHT_SUM = sum(SCORE_WEIGHTS.values())
44
+ assert abs(_WEIGHT_SUM - 1.0) < 0.001, (
45
+ f"SCORE_WEIGHTS must sum to 1.0, got {_WEIGHT_SUM}"
46
+ )
47
+
48
+ # ============================================================================
49
+ # Score Penalty Factors
50
+ # ============================================================================
51
+ # Multipliers applied when schedule quality is suboptimal
52
+ COMPLETENESS_PENALTY_FACTOR = 1.0 # Apply when incomplete schedules
53
+ CONFLICT_PENALTY_FACTOR = 1.0 # Apply when conflicts detected
54
+
55
+ # ============================================================================
56
+ # Rounding Precision Configuration
57
+ # ============================================================================
58
+ # Number of decimal places for different metric types
59
+ METRIC_PRECISION = 4 # Normalized metrics (0.0-1.0): 4 decimals
60
+ FUEL_PRECISION = 2 # Fuel burn in tonnes: 2 decimals
61
+ AIRLINE_DELAY_PRECISION = 1 # Airline average delays in minutes: 1 decimal
62
+ TIME_PRECISION = 0 # Time values in minutes: integers
63
+
64
+ # ============================================================================
65
+ # Recommendation Thresholds
66
+ # ============================================================================
67
+ # Thresholds for triggering operational recommendations
68
+ FAIRNESS_WARNING_THRESHOLD = 0.7 # Warn if fairness < 70%
69
+ FUEL_EFFICIENCY_WARNING_THRESHOLD = 0.7 # Warn if fuel efficiency < 70%
70
+
71
+ # ============================================================================
72
+ # Capacity Calculation
73
+ # ============================================================================
74
+ # Minimum capacity spacing floor
75
+ MINIMUM_RUNWAY_SPACING = 2 # Minimum 2-minute spacing between any operations
76
+
77
+ # ============================================================================
78
+ # Diagnostic/Recommendation Output
79
+ # ============================================================================
80
+ # Limits on diagnostic and recommendation messages
81
+ MAX_DIAGNOSTICS = 12 # Maximum diagnostic messages to include
82
+ MAX_RECOMMENDATIONS = 6 # Maximum recommendations to include
83
+
84
+ # ============================================================================
85
+ # Inference Configuration
86
+ # ============================================================================
87
+ # Defaults for baseline inference script
88
+ DEFAULT_MAX_STEPS = 4 # Default iterations per task
89
+ DEFAULT_MAX_TOKENS = 1400 # Default LLM max tokens per response
90
+ DEFAULT_TEMPERATURE = 0 # Temperature for deterministic responses
91
+ DEFAULT_SUCCESS_THRESHOLD = 0.65 # Minimum score to consider "success"
92
+
93
+ # ============================================================================
94
+ # Validation Messages
95
+ # ============================================================================
96
+ # Common validation and error messages
97
+ INVALID_RUNWAY_MSG_TEMPLATE = "{flight_id} cannot use runway {runway}; allowed runways are {allowed}."
98
+ OUTSIDE_WINDOW_MSG_TEMPLATE = "{flight_id} is assigned outside its feasible window [{earliest}, {latest}]."
99
+ PRIORITY_TOLERANCE_MSG_TEMPLATE = "{flight_id} exceeds the {priority} delay tolerance of {tolerance} minutes."
100
+ SPACING_VIOLATION_MSG_TEMPLATE = "Runway {runway} has {prev_flight}->{curr_flight} spaced {actual} minutes apart; needs {required}."
101
+
102
+ # ============================================================================
103
+ # Export for use in other modules
104
+ # ============================================================================
105
+ __all__ = [
106
+ "SEPARATION_BY_WAKE",
107
+ "SCORE_WEIGHTS",
108
+ "COMPLETENESS_PENALTY_FACTOR",
109
+ "CONFLICT_PENALTY_FACTOR",
110
+ "METRIC_PRECISION",
111
+ "FUEL_PRECISION",
112
+ "AIRLINE_DELAY_PRECISION",
113
+ "TIME_PRECISION",
114
+ "FAIRNESS_WARNING_THRESHOLD",
115
+ "FUEL_EFFICIENCY_WARNING_THRESHOLD",
116
+ "MINIMUM_RUNWAY_SPACING",
117
+ "MAX_DIAGNOSTICS",
118
+ "MAX_RECOMMENDATIONS",
119
+ "DEFAULT_MAX_STEPS",
120
+ "DEFAULT_MAX_TOKENS",
121
+ "DEFAULT_TEMPERATURE",
122
+ "DEFAULT_SUCCESS_THRESHOLD",
123
+ "INVALID_RUNWAY_MSG_TEMPLATE",
124
+ "OUTSIDE_WINDOW_MSG_TEMPLATE",
125
+ "PRIORITY_TOLERANCE_MSG_TEMPLATE",
126
+ "SPACING_VIOLATION_MSG_TEMPLATE",
127
+ # Multi-agent constants
128
+ "AMAN_EMERGENCY_DELAY_TOLERANCE",
129
+ "DMAN_EMERGENCY_DELAY_TOLERANCE",
130
+ "ATFM_DEADLINE_BUFFER_MINUTES",
131
+ "CROSS_LANE_CONFLICT_PENALTY",
132
+ "THEORY_OF_MIND_BONUS",
133
+ "GENERATOR_ESCALATION_THRESHOLD",
134
+ "GENERATOR_FLOOR_THRESHOLD",
135
+ "COORDINATION_SCORE_WEIGHTS",
136
+ ]
137
+
138
+
139
+ # ============================================================================
140
+ # Multi-Agent AMAN/DMAN Constants
141
+ # ============================================================================
142
+
143
+ # Emergency delay tolerances per role (minutes)
144
+ AMAN_EMERGENCY_DELAY_TOLERANCE: int = 5 # EMERGENCY arrival must land within 5 min of window
145
+ DMAN_EMERGENCY_DELAY_TOLERANCE: int = 5 # EMERGENCY departure must push within 5 min
146
+
147
+ # ATFM network slot buffer: realistic GDP margin (minutes)
148
+ ATFM_DEADLINE_BUFFER_MINUTES: int = 12
149
+
150
+ # Reward shaping constants
151
+ CROSS_LANE_CONFLICT_PENALTY: float = 0.15 # per conflict between AMAN/DMAN slots
152
+ THEORY_OF_MIND_BONUS: float = 0.25 # pre-emptive coordination without prompt
153
+
154
+ # Generator adaptive curriculum thresholds
155
+ GENERATOR_ESCALATION_THRESHOLD: float = 0.65 # escalate when agents score above this
156
+ GENERATOR_FLOOR_THRESHOLD: float = 0.30 # ease when agents score below this
157
+
158
+ # Coordination score component weights
159
+ COORDINATION_SCORE_WEIGHTS = {
160
+ "zero_cross_conflicts": 0.25,
161
+ "negotiation_efficiency": 0.20, # 0 rounds=0.20, 1 round=0.10, 2+=0.0
162
+ "emergency_handling": 0.30,
163
+ "preemptive_gap": 0.25,
164
+ }
domains/__init__.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Domain task catalogs for ADAPT agent transfer learning.
2
+
3
+ Each domain module provides a catalog of TaskDefinition objects that
4
+ represent scheduling problems from non-ATC domains. ADAPT receives these
5
+ tasks and infers ATC parameter mappings purely from structural signals —
6
+ no domain-specific knowledge is encoded here.
7
+
8
+ Adding a new domain:
9
+ 1. Create domains/<name>.py exporting <name>_task_catalog() -> Dict[str, TaskDefinition]
10
+ 2. Add an import below and register it in ALL_DOMAINS.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any, Dict
16
+
17
+ from models import TaskDefinition
18
+
19
+ # Registered domain modules — add new domains here
20
+ _DOMAIN_REGISTRY: list[str] = ["icu"]
21
+
22
+
23
+ def get_all_domain_tasks() -> Dict[str, TaskDefinition]:
24
+ """Aggregate tasks from every registered domain.
25
+
26
+ Returns a flat dict {task_id: TaskDefinition} across all domains.
27
+ Safe to call even if some domain modules are missing (they are skipped
28
+ with a warning).
29
+ """
30
+ all_tasks: Dict[str, TaskDefinition] = {}
31
+ for name in _DOMAIN_REGISTRY:
32
+ try:
33
+ mod = __import__(f"domains.{name}", fromlist=[f"{name}_task_catalog"])
34
+ catalog_fn = getattr(mod, f"{name}_task_catalog")
35
+ catalog: Dict[str, TaskDefinition] = catalog_fn()
36
+ all_tasks.update(catalog)
37
+ except Exception as exc:
38
+ import warnings
39
+ warnings.warn(f"[domains] Could not load domain '{name}': {exc}")
40
+ return all_tasks
41
+
42
+
43
+ def get_domain_description(domain_name: str) -> str:
44
+ """Return a human-readable description for a registered domain, or ''."""
45
+ try:
46
+ mod = __import__(f"domains.{domain_name}", fromlist=["_DOMAIN_DESCRIPTION"])
47
+ for attr in (f"{domain_name.upper()}_DOMAIN_DESCRIPTION", "_DOMAIN_DESCRIPTION"):
48
+ if hasattr(mod, attr):
49
+ return getattr(mod, attr)
50
+ except Exception:
51
+ pass
52
+ return ""
domains/icu.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ICU Surge Management domain — three TaskDefinition scenarios for ADAPT.
2
+
3
+ Entity types (stored in FlightRecord.airline — ADAPT maps these to ATC params):
4
+ TRAUMA → should map to wake_class=H, priority=emergency
5
+ CARDIAC → should map to wake_class=M, priority=medical
6
+ POST_OP → should map to wake_class=M, priority=connection
7
+ ROUTINE → should map to wake_class=L, priority=normal
8
+
9
+ Operations:
10
+ ARRIVAL = patient being admitted to an ICU bed
11
+ DEPARTURE = patient being discharged / transferred out
12
+
13
+ Resources (runway_id):
14
+ BED_A, BED_B, BED_C, BED_D — shared ICU beds managed by both coordinators
15
+
16
+ Timing: minute 0 = 08:00, minute 480 = 16:00 (8-hour shift window)
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Dict
22
+
23
+ try:
24
+ from ..models import (
25
+ Difficulty,
26
+ FlightRecord,
27
+ OperationType,
28
+ PriorityClass,
29
+ RunwaySpec,
30
+ TaskDefinition,
31
+ WakeClass,
32
+ )
33
+ except ImportError:
34
+ from models import (
35
+ Difficulty,
36
+ FlightRecord,
37
+ OperationType,
38
+ PriorityClass,
39
+ RunwaySpec,
40
+ TaskDefinition,
41
+ WakeClass,
42
+ )
43
+
44
+
45
+ ICU_DOMAIN_DESCRIPTION = """\
46
+ Domain: Hospital ICU Surge Management
47
+ Resources: Four intensive-care beds (BED_A, BED_B, BED_C, BED_D) shared between
48
+ an Admission Coordinator (manages incoming patients) and a
49
+ Discharge Coordinator (manages outgoing patients / transfers).
50
+
51
+ Entity types and their clinical meaning:
52
+ TRAUMA — Patient arriving from mass-casualty event or ER. Life-threatening.
53
+ Must be admitted within the narrowest time window. Cannot wait.
54
+ CARDIAC — Post-cardiac-surgery patient. Time-sensitive but stable for ~30 min.
55
+ High monitoring needs; bed must be fully prepped before arrival.
56
+ POST_OP — Post-operative patient ready to move to a step-down unit.
57
+ Has a transfer-authorization window (hard deadline from insurance).
58
+ ROUTINE — Scheduled transfer from step-down or ward. Flexible timing.
59
+
60
+ Hard deadlines: Some POST_OP discharges have a transfer-authorization expiry —
61
+ the patient MUST vacate the bed before that minute or re-authorization is needed,
62
+ causing a cascade of delays (equivalent to ATFM network slot violations).
63
+
64
+ Coordination challenge: The Admission Coordinator does not know which beds are
65
+ about to be freed by the Discharge Coordinator. The Discharge Coordinator does
66
+ not know which new patients are incoming. They share the same 4 beds and must
67
+ coordinate through messages to avoid both admitting to an occupied bed and
68
+ discharging into a scheduling gap that blocks the next admission.\
69
+ """
70
+
71
+ _BEDS = ["BED_A", "BED_B", "BED_C", "BED_D"]
72
+
73
+ # Spacing floor = max(2, round(60/hourly_capacity)) minutes between ops on the same bed.
74
+ # 4/hr → 15 min, which made ICU scenarios nearly unsolvable vs heuristics tuned for airport
75
+ # runways (~3–4 min). 12/hr → 5 min: still models turn-over delay without guaranteed conflicts.
76
+ _BED_SPECS = [
77
+ RunwaySpec(
78
+ runway_id=bid,
79
+ hourly_capacity=12,
80
+ weather_penalty=1.0,
81
+ notes="ICU bed — admission and discharge both allowed",
82
+ )
83
+ for bid in _BEDS
84
+ ]
85
+
86
+
87
+ def icu_task_catalog() -> Dict[str, TaskDefinition]:
88
+ return {
89
+ t.task_id: t
90
+ for t in [_normal_day(), _flu_surge(), _mass_casualty()]
91
+ }
92
+
93
+
94
+ # ── Task 1: Normal ICU Day (Easy) ─────────────────────────────────────────────
95
+
96
+ def _normal_day() -> TaskDefinition:
97
+ flights = [
98
+ # Admissions (ARRIVAL)
99
+ FlightRecord(
100
+ flight_id="P_ARR_01", airline="ROUTINE", operation=OperationType.ARRIVAL,
101
+ wake_class=WakeClass.MEDIUM, # placeholder — ADAPT overrides
102
+ scheduled_minute=30, earliest_minute=0, latest_minute=120,
103
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
104
+ priority=PriorityClass.NORMAL,
105
+ notes="Scheduled step-down transfer, routine admission",
106
+ ),
107
+ FlightRecord(
108
+ flight_id="P_ARR_02", airline="ROUTINE", operation=OperationType.ARRIVAL,
109
+ wake_class=WakeClass.MEDIUM,
110
+ scheduled_minute=60, earliest_minute=30, latest_minute=150,
111
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
112
+ priority=PriorityClass.NORMAL,
113
+ notes="Scheduled step-down transfer, routine admission",
114
+ ),
115
+ FlightRecord(
116
+ flight_id="P_ARR_03", airline="CARDIAC", operation=OperationType.ARRIVAL,
117
+ wake_class=WakeClass.MEDIUM,
118
+ scheduled_minute=90, earliest_minute=60, latest_minute=180,
119
+ allowed_runways=_BEDS, passengers=3, fuel_burn_per_minute=5.0,
120
+ priority=PriorityClass.NORMAL, # placeholder — ADAPT overrides to medical
121
+ connection_risk=0.70,
122
+ notes="Post-cardiac surgery — bed must be fully prepped before arrival",
123
+ ),
124
+ FlightRecord(
125
+ flight_id="P_ARR_04", airline="ROUTINE", operation=OperationType.ARRIVAL,
126
+ wake_class=WakeClass.MEDIUM,
127
+ scheduled_minute=150, earliest_minute=90, latest_minute=240,
128
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
129
+ priority=PriorityClass.NORMAL,
130
+ notes="Scheduled step-down transfer, routine admission",
131
+ ),
132
+ # Discharges (DEPARTURE)
133
+ FlightRecord(
134
+ flight_id="P_DIS_01", airline="POST_OP", operation=OperationType.DEPARTURE,
135
+ wake_class=WakeClass.MEDIUM,
136
+ scheduled_minute=45, earliest_minute=0, latest_minute=180,
137
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
138
+ priority=PriorityClass.NORMAL, # placeholder — ADAPT overrides to connection
139
+ notes="Transfer-authorization window open; step-down bed confirmed",
140
+ ),
141
+ FlightRecord(
142
+ flight_id="P_DIS_02", airline="POST_OP", operation=OperationType.DEPARTURE,
143
+ wake_class=WakeClass.MEDIUM,
144
+ scheduled_minute=75, earliest_minute=30, latest_minute=180,
145
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
146
+ priority=PriorityClass.NORMAL,
147
+ notes="Transfer-authorization window open; step-down bed confirmed",
148
+ ),
149
+ FlightRecord(
150
+ flight_id="P_DIS_03", airline="POST_OP", operation=OperationType.DEPARTURE,
151
+ wake_class=WakeClass.MEDIUM,
152
+ scheduled_minute=120, earliest_minute=60, latest_minute=240,
153
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
154
+ priority=PriorityClass.NORMAL,
155
+ notes="Transfer-authorization window open",
156
+ ),
157
+ FlightRecord(
158
+ flight_id="P_DIS_04", airline="ROUTINE", operation=OperationType.DEPARTURE,
159
+ wake_class=WakeClass.LIGHT,
160
+ scheduled_minute=180, earliest_minute=90, latest_minute=300,
161
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
162
+ priority=PriorityClass.NORMAL,
163
+ notes="Routine discharge to ward",
164
+ ),
165
+ ]
166
+ return TaskDefinition(
167
+ task_id="icu_normal_day",
168
+ title="ICU Normal Day — Routine Bed Turnover",
169
+ difficulty=Difficulty.EASY,
170
+ airport="GENERAL_HOSPITAL_ICU",
171
+ description=ICU_DOMAIN_DESCRIPTION,
172
+ objective="Coordinate bed admissions and discharges to minimize patient wait time and avoid bed conflicts",
173
+ grading_focus=["bed_conflict_free", "patient_wait_time", "transfer_authorization"],
174
+ planning_horizon_minutes=480,
175
+ max_steps=4,
176
+ delay_budget=60,
177
+ fuel_budget=300.0,
178
+ fairness_tolerance=2.0,
179
+ runways=_BED_SPECS,
180
+ flights=flights,
181
+ )
182
+
183
+
184
+ # ── Task 2: Flu Surge (Medium) ────────────────────────────────────────────────
185
+
186
+ def _flu_surge() -> TaskDefinition:
187
+ flights = [
188
+ # Admissions
189
+ FlightRecord(
190
+ flight_id="S_ARR_01", airline="CARDIAC", operation=OperationType.ARRIVAL,
191
+ wake_class=WakeClass.MEDIUM,
192
+ scheduled_minute=30, earliest_minute=10, latest_minute=90,
193
+ allowed_runways=_BEDS, passengers=3, fuel_burn_per_minute=5.0,
194
+ priority=PriorityClass.NORMAL, connection_risk=0.70,
195
+ notes="Post-cardiac surgery — time-sensitive admission",
196
+ ),
197
+ FlightRecord(
198
+ flight_id="S_ARR_02", airline="ROUTINE", operation=OperationType.ARRIVAL,
199
+ wake_class=WakeClass.MEDIUM,
200
+ scheduled_minute=45, earliest_minute=20, latest_minute=120,
201
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
202
+ priority=PriorityClass.NORMAL,
203
+ notes="Step-down transfer",
204
+ ),
205
+ FlightRecord(
206
+ flight_id="S_ARR_03", airline="CARDIAC", operation=OperationType.ARRIVAL,
207
+ wake_class=WakeClass.MEDIUM,
208
+ scheduled_minute=60, earliest_minute=40, latest_minute=120,
209
+ allowed_runways=_BEDS, passengers=3, fuel_burn_per_minute=5.0,
210
+ priority=PriorityClass.NORMAL, connection_risk=0.75,
211
+ notes="Post-cardiac surgery — overlapping window with S_ARR_01",
212
+ ),
213
+ FlightRecord(
214
+ flight_id="S_ARR_04", airline="ROUTINE", operation=OperationType.ARRIVAL,
215
+ wake_class=WakeClass.MEDIUM,
216
+ scheduled_minute=90, earliest_minute=60, latest_minute=200,
217
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
218
+ priority=PriorityClass.NORMAL,
219
+ notes="Step-down transfer",
220
+ ),
221
+ FlightRecord(
222
+ flight_id="S_ARR_05", airline="CARDIAC", operation=OperationType.ARRIVAL,
223
+ wake_class=WakeClass.MEDIUM,
224
+ scheduled_minute=100, earliest_minute=80, latest_minute=160,
225
+ allowed_runways=_BEDS, passengers=3, fuel_burn_per_minute=5.0,
226
+ priority=PriorityClass.NORMAL, connection_risk=0.65,
227
+ notes="Post-cardiac surgery — third concurrent CARDIAC creating surge",
228
+ ),
229
+ FlightRecord(
230
+ flight_id="S_ARR_06", airline="ROUTINE", operation=OperationType.ARRIVAL,
231
+ wake_class=WakeClass.MEDIUM,
232
+ scheduled_minute=150, earliest_minute=120, latest_minute=270,
233
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
234
+ priority=PriorityClass.NORMAL,
235
+ notes="Step-down transfer",
236
+ ),
237
+ FlightRecord(
238
+ flight_id="S_ARR_07", airline="ROUTINE", operation=OperationType.ARRIVAL,
239
+ wake_class=WakeClass.MEDIUM,
240
+ scheduled_minute=200, earliest_minute=160, latest_minute=320,
241
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
242
+ priority=PriorityClass.NORMAL,
243
+ notes="Step-down transfer",
244
+ ),
245
+ # Discharges
246
+ FlightRecord(
247
+ flight_id="S_DIS_01", airline="POST_OP", operation=OperationType.DEPARTURE,
248
+ wake_class=WakeClass.MEDIUM,
249
+ scheduled_minute=20, earliest_minute=0, latest_minute=60,
250
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
251
+ priority=PriorityClass.NORMAL,
252
+ notes="TRANSFER AUTH DEADLINE: minute 60 — must vacate before CARDIAC arrivals",
253
+ ),
254
+ FlightRecord(
255
+ flight_id="S_DIS_02", airline="POST_OP", operation=OperationType.DEPARTURE,
256
+ wake_class=WakeClass.MEDIUM,
257
+ scheduled_minute=40, earliest_minute=10, latest_minute=80,
258
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
259
+ priority=PriorityClass.NORMAL,
260
+ notes="TRANSFER AUTH DEADLINE: minute 80",
261
+ ),
262
+ FlightRecord(
263
+ flight_id="S_DIS_03", airline="POST_OP", operation=OperationType.DEPARTURE,
264
+ wake_class=WakeClass.MEDIUM,
265
+ scheduled_minute=70, earliest_minute=40, latest_minute=120,
266
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
267
+ priority=PriorityClass.NORMAL,
268
+ notes="TRANSFER AUTH DEADLINE: minute 120",
269
+ ),
270
+ FlightRecord(
271
+ flight_id="S_DIS_04", airline="POST_OP", operation=OperationType.DEPARTURE,
272
+ wake_class=WakeClass.MEDIUM,
273
+ scheduled_minute=110, earliest_minute=80, latest_minute=180,
274
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
275
+ priority=PriorityClass.NORMAL,
276
+ notes="TRANSFER AUTH DEADLINE: minute 180",
277
+ ),
278
+ FlightRecord(
279
+ flight_id="S_DIS_05", airline="ROUTINE", operation=OperationType.DEPARTURE,
280
+ wake_class=WakeClass.LIGHT,
281
+ scheduled_minute=160, earliest_minute=120, latest_minute=280,
282
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
283
+ priority=PriorityClass.NORMAL,
284
+ notes="Routine discharge to ward, flexible timing",
285
+ ),
286
+ ]
287
+ return TaskDefinition(
288
+ task_id="icu_flu_surge",
289
+ title="ICU Flu Surge — Three Concurrent CARDIAC Admissions",
290
+ difficulty=Difficulty.MEDIUM,
291
+ airport="GENERAL_HOSPITAL_ICU",
292
+ description=ICU_DOMAIN_DESCRIPTION,
293
+ objective="Clear beds before CARDIAC surge arrives while respecting transfer-authorization deadlines",
294
+ grading_focus=["transfer_auth_compliance", "cardiac_admission_delay", "bed_conflict_free"],
295
+ planning_horizon_minutes=480,
296
+ max_steps=4,
297
+ delay_budget=45,
298
+ fuel_budget=400.0,
299
+ fairness_tolerance=2.0,
300
+ runways=_BED_SPECS,
301
+ flights=flights,
302
+ )
303
+
304
+
305
+ # ── Task 3: Mass Casualty Surge (Hard) ────────────────────────────────────────
306
+
307
+ def _mass_casualty() -> TaskDefinition:
308
+ flights = [
309
+ # TRAUMA admissions — narrow windows, cannot wait
310
+ FlightRecord(
311
+ flight_id="T_ARR_01", airline="TRAUMA", operation=OperationType.ARRIVAL,
312
+ wake_class=WakeClass.MEDIUM, # placeholder — ADAPT must set to H/emergency
313
+ scheduled_minute=5, earliest_minute=0, latest_minute=10,
314
+ allowed_runways=_BEDS, passengers=5, fuel_burn_per_minute=10.0,
315
+ priority=PriorityClass.NORMAL, connection_risk=0.95,
316
+ notes="EMERGENCY: Mass-casualty arrival — immediate ICU bed required",
317
+ ),
318
+ FlightRecord(
319
+ flight_id="T_ARR_02", airline="TRAUMA", operation=OperationType.ARRIVAL,
320
+ wake_class=WakeClass.MEDIUM,
321
+ scheduled_minute=8, earliest_minute=3, latest_minute=15,
322
+ allowed_runways=_BEDS, passengers=5, fuel_burn_per_minute=10.0,
323
+ priority=PriorityClass.NORMAL, connection_risk=0.95,
324
+ notes="EMERGENCY: Mass-casualty arrival — second trauma patient",
325
+ ),
326
+ FlightRecord(
327
+ flight_id="T_ARR_03", airline="TRAUMA", operation=OperationType.ARRIVAL,
328
+ wake_class=WakeClass.MEDIUM,
329
+ scheduled_minute=12, earliest_minute=8, latest_minute=20,
330
+ allowed_runways=_BEDS, passengers=5, fuel_burn_per_minute=10.0,
331
+ priority=PriorityClass.NORMAL, connection_risk=0.90,
332
+ notes="EMERGENCY: Mass-casualty arrival — third trauma patient",
333
+ ),
334
+ # CARDIAC admissions
335
+ FlightRecord(
336
+ flight_id="T_ARR_04", airline="CARDIAC", operation=OperationType.ARRIVAL,
337
+ wake_class=WakeClass.MEDIUM,
338
+ scheduled_minute=30, earliest_minute=15, latest_minute=75,
339
+ allowed_runways=_BEDS, passengers=3, fuel_burn_per_minute=5.0,
340
+ priority=PriorityClass.NORMAL, connection_risk=0.72,
341
+ notes="Post-cardiac surgery — must admit after trauma queue clears",
342
+ ),
343
+ FlightRecord(
344
+ flight_id="T_ARR_05", airline="CARDIAC", operation=OperationType.ARRIVAL,
345
+ wake_class=WakeClass.MEDIUM,
346
+ scheduled_minute=50, earliest_minute=30, latest_minute=100,
347
+ allowed_runways=_BEDS, passengers=3, fuel_burn_per_minute=5.0,
348
+ priority=PriorityClass.NORMAL, connection_risk=0.68,
349
+ notes="Post-cardiac surgery",
350
+ ),
351
+ FlightRecord(
352
+ flight_id="T_ARR_06", airline="CARDIAC", operation=OperationType.ARRIVAL,
353
+ wake_class=WakeClass.MEDIUM,
354
+ scheduled_minute=80, earliest_minute=60, latest_minute=140,
355
+ allowed_runways=_BEDS, passengers=3, fuel_burn_per_minute=5.0,
356
+ priority=PriorityClass.NORMAL, connection_risk=0.60,
357
+ notes="Post-cardiac surgery",
358
+ ),
359
+ FlightRecord(
360
+ flight_id="T_ARR_07", airline="CARDIAC", operation=OperationType.ARRIVAL,
361
+ wake_class=WakeClass.MEDIUM,
362
+ scheduled_minute=110, earliest_minute=90, latest_minute=170,
363
+ allowed_runways=_BEDS, passengers=3, fuel_burn_per_minute=5.0,
364
+ priority=PriorityClass.NORMAL, connection_risk=0.55,
365
+ notes="Post-cardiac surgery",
366
+ ),
367
+ # ROUTINE admissions
368
+ FlightRecord(
369
+ flight_id="T_ARR_08", airline="ROUTINE", operation=OperationType.ARRIVAL,
370
+ wake_class=WakeClass.LIGHT,
371
+ scheduled_minute=120, earliest_minute=60, latest_minute=240,
372
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
373
+ priority=PriorityClass.NORMAL,
374
+ notes="Step-down transfer — flexible, defer if beds occupied",
375
+ ),
376
+ FlightRecord(
377
+ flight_id="T_ARR_09", airline="ROUTINE", operation=OperationType.ARRIVAL,
378
+ wake_class=WakeClass.LIGHT,
379
+ scheduled_minute=160, earliest_minute=100, latest_minute=280,
380
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
381
+ priority=PriorityClass.NORMAL,
382
+ notes="Step-down transfer — flexible",
383
+ ),
384
+ FlightRecord(
385
+ flight_id="T_ARR_10", airline="ROUTINE", operation=OperationType.ARRIVAL,
386
+ wake_class=WakeClass.LIGHT,
387
+ scheduled_minute=200, earliest_minute=150, latest_minute=330,
388
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
389
+ priority=PriorityClass.NORMAL,
390
+ notes="Step-down transfer — flexible",
391
+ ),
392
+ # Discharges — must clear beds for trauma wave
393
+ FlightRecord(
394
+ flight_id="T_DIS_01", airline="POST_OP", operation=OperationType.DEPARTURE,
395
+ wake_class=WakeClass.MEDIUM,
396
+ scheduled_minute=0, earliest_minute=0, latest_minute=8,
397
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
398
+ priority=PriorityClass.NORMAL,
399
+ notes="URGENT: Must vacate immediately — trauma bay needs bed now",
400
+ ),
401
+ FlightRecord(
402
+ flight_id="T_DIS_02", airline="POST_OP", operation=OperationType.DEPARTURE,
403
+ wake_class=WakeClass.MEDIUM,
404
+ scheduled_minute=2, earliest_minute=0, latest_minute=10,
405
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
406
+ priority=PriorityClass.NORMAL,
407
+ notes="URGENT: Must vacate for second trauma patient — TRANSFER AUTH DEADLINE: minute 10",
408
+ ),
409
+ FlightRecord(
410
+ flight_id="T_DIS_03", airline="POST_OP", operation=OperationType.DEPARTURE,
411
+ wake_class=WakeClass.MEDIUM,
412
+ scheduled_minute=5, earliest_minute=0, latest_minute=15,
413
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
414
+ priority=PriorityClass.NORMAL,
415
+ notes="Must vacate for third trauma — TRANSFER AUTH DEADLINE: minute 15",
416
+ ),
417
+ FlightRecord(
418
+ flight_id="T_DIS_04", airline="POST_OP", operation=OperationType.DEPARTURE,
419
+ wake_class=WakeClass.MEDIUM,
420
+ scheduled_minute=20, earliest_minute=10, latest_minute=60,
421
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=2.0,
422
+ priority=PriorityClass.NORMAL,
423
+ notes="TRANSFER AUTH DEADLINE: minute 60",
424
+ ),
425
+ FlightRecord(
426
+ flight_id="T_DIS_05", airline="ROUTINE", operation=OperationType.DEPARTURE,
427
+ wake_class=WakeClass.LIGHT,
428
+ scheduled_minute=40, earliest_minute=20, latest_minute=120,
429
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
430
+ priority=PriorityClass.NORMAL,
431
+ notes="Routine discharge — flex to accommodate trauma clearance",
432
+ ),
433
+ FlightRecord(
434
+ flight_id="T_DIS_06", airline="ROUTINE", operation=OperationType.DEPARTURE,
435
+ wake_class=WakeClass.LIGHT,
436
+ scheduled_minute=90, earliest_minute=60, latest_minute=200,
437
+ allowed_runways=_BEDS, passengers=1, fuel_burn_per_minute=1.5,
438
+ priority=PriorityClass.NORMAL,
439
+ notes="Routine discharge",
440
+ ),
441
+ ]
442
+ return TaskDefinition(
443
+ task_id="icu_mass_casualty",
444
+ title="ICU Mass Casualty — Three Trauma Emergencies Simultaneous",
445
+ difficulty=Difficulty.HARD,
446
+ airport="GENERAL_HOSPITAL_ICU",
447
+ description=ICU_DOMAIN_DESCRIPTION,
448
+ objective="Immediately clear beds for 3 simultaneous TRAUMA arrivals while managing CARDIAC queue",
449
+ grading_focus=["trauma_admission_time", "transfer_auth_compliance", "cardiac_sequencing"],
450
+ planning_horizon_minutes=480,
451
+ max_steps=4,
452
+ delay_budget=30,
453
+ fuel_budget=600.0,
454
+ fairness_tolerance=3.0,
455
+ runways=_BED_SPECS,
456
+ flights=flights,
457
+ )
engine.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Operational simulator and reward shaping for ATC optimization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from dataclasses import dataclass
7
+ from statistics import pstdev
8
+ from typing import Dict, Iterable, List, Tuple
9
+
10
+ # Import models with automatic relative/absolute fallback
11
+ try:
12
+ from .models import (
13
+ FlightRecord,
14
+ PriorityClass,
15
+ RunwaySpec,
16
+ SlotAssignment,
17
+ TaskDefinition,
18
+ TaskMetrics,
19
+ )
20
+ from .constants import (
21
+ SEPARATION_BY_WAKE,
22
+ SCORE_WEIGHTS,
23
+ METRIC_PRECISION,
24
+ FUEL_PRECISION,
25
+ AIRLINE_DELAY_PRECISION,
26
+ MAX_DIAGNOSTICS,
27
+ MAX_RECOMMENDATIONS,
28
+ )
29
+ except ImportError:
30
+ from models import (
31
+ FlightRecord,
32
+ PriorityClass,
33
+ RunwaySpec,
34
+ SlotAssignment,
35
+ TaskDefinition,
36
+ TaskMetrics,
37
+ )
38
+ from constants import (
39
+ SEPARATION_BY_WAKE,
40
+ SCORE_WEIGHTS,
41
+ METRIC_PRECISION,
42
+ FUEL_PRECISION,
43
+ AIRLINE_DELAY_PRECISION,
44
+ MAX_DIAGNOSTICS,
45
+ MAX_RECOMMENDATIONS,
46
+ )
47
+
48
+ # Build priority delay tolerance dynamically from models
49
+ PRIORITY_DELAY_TOLERANCE: Dict[PriorityClass, int] = {
50
+ PriorityClass.NORMAL: 35,
51
+ PriorityClass.CONNECTION: 20,
52
+ PriorityClass.MEDICAL: 10,
53
+ PriorityClass.EMERGENCY: 5,
54
+ }
55
+
56
+
57
+ @dataclass
58
+ class SimulationOutcome:
59
+ """Full simulator output used by the environment and graders."""
60
+
61
+ metrics: TaskMetrics
62
+ diagnostics: List[str]
63
+ recommendations: List[str]
64
+ normalized_score: float
65
+
66
+
67
+ def empty_metrics() -> TaskMetrics:
68
+ """Return a zeroed metric object."""
69
+
70
+ return TaskMetrics()
71
+
72
+
73
+ def _capacity_spacing(runway: RunwaySpec) -> int:
74
+ base_gap = max(2, round(60 / runway.hourly_capacity))
75
+ return max(2, round(base_gap * runway.weather_penalty))
76
+
77
+
78
+ def _delay_for(flight: FlightRecord, assigned_minute: int) -> int:
79
+ return abs(assigned_minute - flight.scheduled_minute)
80
+
81
+
82
+ def simulate_plan(task: TaskDefinition, proposal: Iterable[SlotAssignment]) -> SimulationOutcome:
83
+ """Evaluate a candidate runway plan for a task."""
84
+
85
+ flights_by_id = {flight.flight_id: flight for flight in task.flights}
86
+ runways_by_id = {runway.runway_id: runway for runway in task.runways}
87
+ assignments = list(proposal)
88
+
89
+ diagnostics: List[str] = []
90
+ recommendations: List[str] = []
91
+ unknown_assignments = 0
92
+ invalid_assignments = 0
93
+
94
+ assignment_map: Dict[str, SlotAssignment] = {}
95
+ duplicate_assignments = max(0, len(assignments) - len({item.flight_id for item in assignments}))
96
+ for assignment in assignments:
97
+ if assignment.flight_id in assignment_map:
98
+ diagnostics.append(
99
+ f"{assignment.flight_id} appears more than once; only the last assignment is used."
100
+ )
101
+ assignment_map[assignment.flight_id] = assignment
102
+ if duplicate_assignments:
103
+ invalid_assignments += duplicate_assignments
104
+
105
+ scheduled_by_runway: Dict[str, List[Tuple[int, SlotAssignment, FlightRecord]]] = defaultdict(list)
106
+ delays: Dict[str, int] = {}
107
+ per_airline_delays: Dict[str, List[int]] = defaultdict(list)
108
+ fuel_burn = 0.0
109
+ priority_violations = 0
110
+ emergency_violations = 0
111
+ medical_violations = 0
112
+ connection_violations = 0
113
+ capacity_violations = 0
114
+
115
+ for assignment in assignment_map.values():
116
+ flight = flights_by_id.get(assignment.flight_id)
117
+ if flight is None:
118
+ unknown_assignments += 1
119
+ diagnostics.append(f"Unknown flight id {assignment.flight_id} in proposal.")
120
+ continue
121
+
122
+ if assignment.runway not in flight.allowed_runways:
123
+ invalid_assignments += 1
124
+ diagnostics.append(
125
+ f"{flight.flight_id} cannot use runway {assignment.runway}; allowed runways are {', '.join(flight.allowed_runways)}."
126
+ )
127
+ continue
128
+
129
+ if assignment.runway not in runways_by_id:
130
+ invalid_assignments += 1
131
+ diagnostics.append(f"Runway {assignment.runway} is not available in this task.")
132
+ continue
133
+
134
+ runway = runways_by_id[assignment.runway]
135
+ if flight.operation not in runway.allowed_operations:
136
+ invalid_assignments += 1
137
+ diagnostics.append(
138
+ f"Runway {assignment.runway} cannot handle {flight.operation.value} operations for {flight.flight_id}."
139
+ )
140
+ continue
141
+
142
+ if assignment.assigned_minute < flight.earliest_minute or assignment.assigned_minute > flight.latest_minute:
143
+ invalid_assignments += 1
144
+ diagnostics.append(
145
+ f"{flight.flight_id} is assigned outside its feasible window [{flight.earliest_minute}, {flight.latest_minute}]."
146
+ )
147
+ continue
148
+
149
+ delay = _delay_for(flight, assignment.assigned_minute)
150
+ if assignment.hold_minutes > 0 and abs(assignment.hold_minutes - delay) > 5:
151
+ diagnostics.append(
152
+ f"{flight.flight_id} declares hold_minutes={assignment.hold_minutes}, but the actual delay is {delay}."
153
+ )
154
+ delays[flight.flight_id] = delay
155
+ per_airline_delays[flight.airline].append(delay)
156
+ fuel_burn += delay * flight.fuel_burn_per_minute
157
+ scheduled_by_runway[assignment.runway].append((assignment.assigned_minute, assignment, flight))
158
+
159
+ tolerance = PRIORITY_DELAY_TOLERANCE[flight.priority]
160
+ if delay > tolerance:
161
+ priority_violations += 1
162
+ if flight.priority == PriorityClass.EMERGENCY:
163
+ emergency_violations += 1
164
+ elif flight.priority == PriorityClass.MEDICAL:
165
+ medical_violations += 1
166
+ elif flight.priority == PriorityClass.CONNECTION:
167
+ connection_violations += 1
168
+ diagnostics.append(
169
+ f"{flight.flight_id} exceeds the {flight.priority.value} delay tolerance of {tolerance} minutes."
170
+ )
171
+
172
+ missing_assignments = max(0, len(task.flights) - len(delays))
173
+ for flight in task.flights:
174
+ if flight.flight_id not in delays:
175
+ diagnostics.append(f"{flight.flight_id} has no valid runway assignment.")
176
+
177
+ conflict_count = 0
178
+ for runway_id, runway_items in scheduled_by_runway.items():
179
+ runway_spec = runways_by_id[runway_id]
180
+ runway_items.sort(key=lambda item: item[0])
181
+ required_gap_floor = _capacity_spacing(runway_spec)
182
+ for idx in range(1, len(runway_items)):
183
+ prev_time, _, prev_flight = runway_items[idx - 1]
184
+ curr_time, _, curr_flight = runway_items[idx]
185
+ wake_gap = SEPARATION_BY_WAKE[(prev_flight.wake_class.value, curr_flight.wake_class.value)]
186
+ required_gap = max(required_gap_floor, wake_gap)
187
+ actual_gap = curr_time - prev_time
188
+ if actual_gap < required_gap:
189
+ conflict_count += 1
190
+ capacity_violations += 1
191
+ diagnostics.append(
192
+ f"Runway {runway_id} has {prev_flight.flight_id}->{curr_flight.flight_id} spaced {actual_gap} minutes apart; needs {required_gap}."
193
+ )
194
+
195
+ total_delay = sum(delays.values())
196
+ max_delay = max(delays.values(), default=0)
197
+
198
+ completeness = max(
199
+ 0.0,
200
+ min(
201
+ 1.0,
202
+ len(delays) / max(1, len(task.flights)),
203
+ ),
204
+ )
205
+ conflict_free_ratio = max(
206
+ 0.0,
207
+ 1.0 - (conflict_count / max(1, len(task.flights) - 1)),
208
+ )
209
+ priority_handling = max(
210
+ 0.0,
211
+ 1.0 - (priority_violations / max(1, sum(1 for flight in task.flights if flight.priority != PriorityClass.NORMAL))),
212
+ )
213
+ delay_efficiency = max(0.0, 1.0 - (total_delay / task.delay_budget))
214
+ fuel_efficiency = max(0.0, 1.0 - (fuel_burn / task.fuel_budget))
215
+
216
+ airline_averages = {
217
+ airline: round(sum(values) / len(values), AIRLINE_DELAY_PRECISION)
218
+ for airline, values in per_airline_delays.items()
219
+ if values
220
+ }
221
+ spread = pstdev(list(airline_averages.values())) if len(airline_averages) > 1 else 0.0
222
+ fairness = max(0.0, 1.0 - (spread / task.fairness_tolerance))
223
+
224
+ # Connection impact: risk-weighted delay score for CONNECTION flights
225
+ connection_flights = [
226
+ f for f in task.flights if f.priority == PriorityClass.CONNECTION and f.connection_risk > 0
227
+ ]
228
+ if connection_flights:
229
+ # Budget: each connection flight is expected to tolerate up to its delay tolerance
230
+ weighted_actual = sum(
231
+ delays.get(f.flight_id, PRIORITY_DELAY_TOLERANCE[PriorityClass.CONNECTION]) * f.connection_risk
232
+ for f in connection_flights
233
+ )
234
+ weighted_budget = sum(
235
+ PRIORITY_DELAY_TOLERANCE[PriorityClass.CONNECTION] * f.connection_risk
236
+ for f in connection_flights
237
+ )
238
+ connection_impact_score = max(0.0, 1.0 - weighted_actual / max(1.0, weighted_budget))
239
+ else:
240
+ connection_impact_score = 1.0
241
+
242
+ if completeness < 1.0:
243
+ recommendations.append("Cover every flight in the scenario before refining the sequence.")
244
+ if conflict_count > 0:
245
+ recommendations.append("Increase spacing on the affected runway or move some flights to a parallel runway.")
246
+ if duplicate_assignments > 0:
247
+ recommendations.append("Avoid duplicate flight entries; submit one definitive assignment per flight.")
248
+ if priority_violations > 0:
249
+ recommendations.append("Pull medical, emergency, and connection-sensitive flights closer to the front of the sequence.")
250
+ if fairness < 0.7:
251
+ recommendations.append("Redistribute delay so one airline is not absorbing most of the disruption.")
252
+ if fuel_efficiency < 0.7:
253
+ recommendations.append("Reduce airborne or taxi delay on the highest-burn arrivals and heavy aircraft.")
254
+ if not recommendations:
255
+ recommendations.append("The plan is operationally strong; minor gains remain in passenger delay reduction.")
256
+
257
+ # Calculate normalized score using defined weights
258
+ normalized_score = (
259
+ SCORE_WEIGHTS["completeness"] * completeness
260
+ + SCORE_WEIGHTS["conflict_free"] * conflict_free_ratio
261
+ + SCORE_WEIGHTS["priority"] * priority_handling
262
+ + SCORE_WEIGHTS["delay"] * delay_efficiency
263
+ + SCORE_WEIGHTS["fairness"] * fairness
264
+ + SCORE_WEIGHTS["fuel"] * fuel_efficiency
265
+ )
266
+ normalized_score *= completeness
267
+ if conflict_count > 0:
268
+ normalized_score *= conflict_free_ratio
269
+ normalized_score = max(0.01, min(0.99, normalized_score))
270
+
271
+ metrics = TaskMetrics(
272
+ schedule_completeness=round(completeness, METRIC_PRECISION),
273
+ conflict_free_ratio=round(conflict_free_ratio, METRIC_PRECISION),
274
+ priority_handling=round(priority_handling, METRIC_PRECISION),
275
+ delay_efficiency=round(delay_efficiency, METRIC_PRECISION),
276
+ fairness=round(fairness, METRIC_PRECISION),
277
+ fuel_efficiency=round(fuel_efficiency, METRIC_PRECISION),
278
+ connection_impact_score=round(connection_impact_score, METRIC_PRECISION),
279
+ agent_judgment=0.0,
280
+ overall_score=round(normalized_score, METRIC_PRECISION),
281
+ total_delay_minutes=total_delay,
282
+ max_delay_minutes=max_delay,
283
+ estimated_fuel_burn=round(fuel_burn, FUEL_PRECISION),
284
+ conflict_count=conflict_count,
285
+ capacity_violations=capacity_violations,
286
+ priority_violations=priority_violations,
287
+ emergency_violations=emergency_violations,
288
+ medical_violations=medical_violations,
289
+ connection_violations=connection_violations,
290
+ missing_assignments=missing_assignments,
291
+ invalid_assignments=invalid_assignments + unknown_assignments,
292
+ per_airline_average_delay=airline_averages,
293
+ )
294
+ return SimulationOutcome(
295
+ metrics=metrics,
296
+ diagnostics=diagnostics[:MAX_DIAGNOSTICS],
297
+ recommendations=recommendations[:MAX_RECOMMENDATIONS],
298
+ normalized_score=normalized_score,
299
+ )
300
+
301
+
302
+ def per_role_metrics(
303
+ task: TaskDefinition,
304
+ proposal: Iterable[SlotAssignment],
305
+ outcome: SimulationOutcome,
306
+ ) -> Dict:
307
+ """Extract AMAN/DMAN split metrics from a simulation outcome.
308
+
309
+ Returns plain dict for lightweight use in reward functions.
310
+ Arrivals → AMAN. Departures → DMAN.
311
+ """
312
+ from models import OperationType, PriorityClass
313
+
314
+ flights_by_id = {f.flight_id: f for f in task.flights}
315
+ assignment_map = {a.flight_id: a for a in proposal}
316
+
317
+ arr_delays: List[int] = []
318
+ dep_delays: List[int] = []
319
+ emg_arr_ok = emg_arr_miss = 0
320
+ emg_dep_ok = emg_dep_miss = 0
321
+
322
+ for fid, slot in assignment_map.items():
323
+ flight = flights_by_id.get(fid)
324
+ if not flight:
325
+ continue
326
+ delay = abs(slot.assigned_minute - flight.scheduled_minute)
327
+ is_emg = flight.priority in (PriorityClass.EMERGENCY, PriorityClass.MEDICAL)
328
+
329
+ if flight.operation == OperationType.ARRIVAL:
330
+ arr_delays.append(delay)
331
+ if is_emg:
332
+ if delay <= 5:
333
+ emg_arr_ok += 1
334
+ else:
335
+ emg_arr_miss += 1
336
+ else:
337
+ dep_delays.append(delay)
338
+ if is_emg:
339
+ if delay <= 5:
340
+ emg_dep_ok += 1
341
+ else:
342
+ emg_dep_miss += 1
343
+
344
+ total_arrivals = sum(1 for f in task.flights if f.operation == OperationType.ARRIVAL)
345
+ total_departures = sum(1 for f in task.flights if f.operation == OperationType.DEPARTURE)
346
+
347
+ return {
348
+ "arrival_count": total_arrivals,
349
+ "departure_count": total_departures,
350
+ "arrival_delay_total": sum(arr_delays),
351
+ "arrival_delay_mean": sum(arr_delays) / max(1, len(arr_delays)),
352
+ "arrivals_assigned": len(arr_delays),
353
+ "arrivals_missing": total_arrivals - len(arr_delays),
354
+ "departure_delay_total": sum(dep_delays),
355
+ "departure_delay_mean": sum(dep_delays) / max(1, len(dep_delays)),
356
+ "departures_assigned": len(dep_delays),
357
+ "departures_missing": total_departures - len(dep_delays),
358
+ "emergency_arrivals_ok": emg_arr_ok,
359
+ "emergency_arrivals_missed": emg_arr_miss,
360
+ "emergency_departures_ok": emg_dep_ok,
361
+ "emergency_departures_missed": emg_dep_miss,
362
+ "total_conflict_count": outcome.metrics.conflict_count,
363
+ }
graders.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task graders for benchmark scoring.
2
+
3
+ Architecture (3-layer gated design):
4
+ Layer 1 — SafetyGateEvaluator: Hard constraint gates. Any violation caps the ceiling score.
5
+ Layer 2 — PriorityRubricGrader: Grades quality of emergency/medical/connection prioritization.
6
+ Layer 3 — EfficiencyRubricGrader: Grades operational efficiency (delay, fuel, fairness, connection impact).
7
+ GatedCompositeGrader: Official score = min(gate_ceiling, 0.30*priority + 0.70*efficiency).
8
+
9
+ LLMSupervisorGrader runs independently as auxiliary information only and is NOT part of the
10
+ official composite score.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ from abc import ABC, abstractmethod
18
+ from typing import Dict, Iterable, List, Optional, Tuple
19
+
20
+ from openai import APIConnectionError, APIError, APITimeoutError, OpenAI, OpenAIError, RateLimitError
21
+
22
+ try:
23
+ from .engine import SimulationOutcome
24
+ from .models import PriorityClass, SlotAssignment, TaskDefinition, TaskGrade
25
+ except ImportError:
26
+ from engine import SimulationOutcome
27
+ from models import PriorityClass, SlotAssignment, TaskDefinition, TaskGrade
28
+
29
+
30
+ STRICT_SCORE_EPSILON = 0.01
31
+
32
+
33
+ def _strict_score(value: float) -> float:
34
+ """Normalize to the strict open interval (0, 1) with stable output precision."""
35
+ clipped = max(STRICT_SCORE_EPSILON, min(1.0 - STRICT_SCORE_EPSILON, float(value)))
36
+ return round(clipped, 4)
37
+
38
+
39
+ # ── Layer 1: Hard Safety Gates ────────────────────────────────────────────────
40
+
41
+ class SafetyGateEvaluator:
42
+ """Computes the hard constraint ceiling that caps the final composite score.
43
+
44
+ Violations of safety-critical rules (separation conflicts, incomplete schedule,
45
+ emergency flight delayed) set a score ceiling regardless of efficiency metrics.
46
+ This mirrors real-world ATC: a conflicting plan is REJECTED, not averaged.
47
+ """
48
+
49
+ def evaluate(
50
+ self, outcome: SimulationOutcome, task: TaskDefinition
51
+ ) -> Tuple[float, List[str]]:
52
+ """Return (ceiling, list_of_gate_violation_descriptions)."""
53
+ ceiling = 1.0
54
+ violations: List[str] = []
55
+
56
+ # Gate 1: Separation conflicts — hardest veto (each extra conflict makes it worse)
57
+ if outcome.metrics.conflict_count > 0:
58
+ # First conflict drops to 0.40; each additional conflict reduces further, minimum 0.10
59
+ conflict_ceiling = max(0.10, 0.40 - 0.05 * (outcome.metrics.conflict_count - 1))
60
+ ceiling = min(ceiling, conflict_ceiling)
61
+ violations.append(
62
+ f"{outcome.metrics.conflict_count} separation conflict(s) detected — plan is operationally unsafe"
63
+ )
64
+
65
+ # Gate 2: Incomplete schedule
66
+ if outcome.metrics.missing_assignments > 0:
67
+ missing = outcome.metrics.missing_assignments
68
+ # Each missing flight reduces ceiling further, minimum 0.20
69
+ completeness_ceiling = max(0.20, 0.50 - 0.04 * missing)
70
+ ceiling = min(ceiling, completeness_ceiling)
71
+ violations.append(
72
+ f"{missing} flight(s) unassigned — schedule is incomplete"
73
+ )
74
+
75
+ # Gate 3: Emergency flight delay violation — life-safety ceiling
76
+ if outcome.metrics.emergency_violations > 0:
77
+ ceiling = min(ceiling, 0.35)
78
+ violations.append(
79
+ "EMERGENCY flight delay tolerance exceeded — life-safety risk"
80
+ )
81
+
82
+ return ceiling, violations
83
+
84
+
85
+ # ── Layer 2: Priority Rubric ──────────────────────────────────────────────────
86
+
87
+ class PriorityRubricGrader:
88
+ """Grades the quality of priority-aware sequencing decisions.
89
+
90
+ Emergency protection is binary (0 or 1). Medical and connection handling
91
+ are graded proportionally. Connection scoring uses the connection_risk field
92
+ via the pre-computed connection_impact_score in metrics.
93
+ """
94
+
95
+ def grade(self, task: TaskDefinition, outcome: SimulationOutcome) -> float:
96
+ metrics = outcome.metrics
97
+
98
+ # Emergency: binary — any violation collapses this to 0.0
99
+ emergency_count = sum(
100
+ 1 for f in task.flights if f.priority == PriorityClass.EMERGENCY
101
+ )
102
+ if emergency_count > 0:
103
+ emergency_score = 0.0 if metrics.emergency_violations > 0 else 1.0
104
+ else:
105
+ emergency_score = 1.0 # No emergency flights = no penalty
106
+
107
+ # Medical: partial credit proportional to violations
108
+ medical_count = sum(
109
+ 1 for f in task.flights if f.priority == PriorityClass.MEDICAL
110
+ )
111
+ if medical_count > 0:
112
+ medical_score = max(0.0, 1.0 - metrics.medical_violations / medical_count)
113
+ else:
114
+ medical_score = 1.0
115
+
116
+ # Connection: uses the risk-weighted connection_impact_score from engine
117
+ # (0.0 = all high-risk connections were heavily delayed; 1.0 = all protected)
118
+ connection_score = metrics.connection_impact_score
119
+
120
+ return 0.50 * emergency_score + 0.30 * medical_score + 0.20 * connection_score
121
+
122
+
123
+ # ── Layer 3: Efficiency Rubric ────────────────────────────────────────────────
124
+
125
+ class EfficiencyRubricGrader:
126
+ """Grades the operational efficiency dimensions of the plan.
127
+
128
+ Weights are domain-derived:
129
+ delay 0.35 — total system delay is the primary efficiency metric (ICAO)
130
+ fuel 0.25 — fuel burn directly impacts cost and environment
131
+ fairness 0.20 — equitable delay distribution across airlines (IATA WSG)
132
+ connection 0.20 — risk-weighted connection impact (previously unused field)
133
+ """
134
+
135
+ WEIGHTS: Dict[str, float] = {
136
+ "delay": 0.35,
137
+ "fuel": 0.25,
138
+ "fairness": 0.20,
139
+ "connection_impact": 0.20,
140
+ }
141
+
142
+ def grade(self, outcome: SimulationOutcome) -> float:
143
+ m = outcome.metrics
144
+ return (
145
+ self.WEIGHTS["delay"] * m.delay_efficiency
146
+ + self.WEIGHTS["fuel"] * m.fuel_efficiency
147
+ + self.WEIGHTS["fairness"] * m.fairness
148
+ + self.WEIGHTS["connection_impact"] * m.connection_impact_score
149
+ )
150
+
151
+
152
+ # ── Composite Grader (Official Score) ────────────────────────────────────────
153
+
154
+ class BaseTaskGrader(ABC):
155
+ """Base class for task graders."""
156
+
157
+ grader_name: str
158
+
159
+ @abstractmethod
160
+ def grade(
161
+ self,
162
+ task: TaskDefinition,
163
+ outcome: SimulationOutcome,
164
+ proposal: Iterable[SlotAssignment],
165
+ rationale: str = "",
166
+ ) -> TaskGrade:
167
+ """Return a score in the strict range (0.0, 1.0)."""
168
+
169
+
170
+ class GatedCompositeGrader(BaseTaskGrader):
171
+ """Official deterministic benchmark score.
172
+
173
+ Formula:
174
+ raw = 0.30 * priority_score + 0.70 * efficiency_score
175
+ score = min(gate_ceiling, raw)
176
+
177
+ Safety gates (Layer 1) apply a hard ceiling: a plan with conflicts or missing
178
+ flights can never compensate with excellent efficiency scores. This prevents
179
+ reward hacking and aligns with FAA GDP evaluation practice.
180
+ """
181
+
182
+ grader_name = "composite_task_grader"
183
+
184
+ def __init__(self) -> None:
185
+ self._safety_gate = SafetyGateEvaluator()
186
+ self._priority = PriorityRubricGrader()
187
+ self._efficiency = EfficiencyRubricGrader()
188
+
189
+ def grade(
190
+ self,
191
+ task: TaskDefinition,
192
+ outcome: SimulationOutcome,
193
+ proposal: Iterable[SlotAssignment],
194
+ rationale: str = "",
195
+ ) -> TaskGrade:
196
+ ceiling, gate_violations = self._safety_gate.evaluate(outcome, task)
197
+ priority_score = self._priority.grade(task, outcome)
198
+ efficiency_score = self._efficiency.grade(outcome)
199
+
200
+ raw = 0.30 * priority_score + 0.70 * efficiency_score
201
+ final = min(ceiling, max(0.0, raw))
202
+
203
+ if gate_violations:
204
+ status = f"GATED at {ceiling:.3f} — {'; '.join(gate_violations)}."
205
+ elif final >= 0.85:
206
+ status = "Plan accepted: safe, complete, and operationally balanced."
207
+ elif final >= 0.55:
208
+ status = "Plan accepted with operational weaknesses remaining."
209
+ else:
210
+ status = "Plan scored low on efficiency or priority dimensions."
211
+
212
+ return TaskGrade(
213
+ grader_name=self.grader_name,
214
+ score=_strict_score(final),
215
+ rationale=status,
216
+ sub_scores={
217
+ "gate_ceiling": round(ceiling, 4),
218
+ "priority_score": round(priority_score, 4),
219
+ "efficiency_score": round(efficiency_score, 4),
220
+ },
221
+ )
222
+
223
+
224
+ # ── Auxiliary LLM Grader (non-official) ─────────────────────────────────────
225
+
226
+ class LLMSupervisorGrader(BaseTaskGrader):
227
+ """Optional LLM-backed supervisor used when credentials are available.
228
+
229
+ This grader is AUXILIARY ONLY and does NOT contribute to the official
230
+ composite score. It is preserved as a side-channel for analysis.
231
+ """
232
+
233
+ grader_name = "llm_supervisor"
234
+
235
+ def __init__(self, model_name: Optional[str] = None):
236
+ self.api_base_url = os.getenv("API_BASE_URL", "")
237
+ self.api_key = os.getenv("HF_TOKEN", os.getenv("OPENAI_API_KEY", ""))
238
+ self.model_name = model_name or os.getenv("MODEL_NAME", "")
239
+
240
+ def _enabled(self) -> bool:
241
+ return bool(self.api_base_url and self.api_key and self.model_name)
242
+
243
+ def grade(
244
+ self,
245
+ task: TaskDefinition,
246
+ outcome: SimulationOutcome,
247
+ proposal: Iterable[SlotAssignment],
248
+ rationale: str = "",
249
+ ) -> TaskGrade:
250
+ if not self._enabled():
251
+ return TaskGrade(
252
+ grader_name=self.grader_name,
253
+ score=_strict_score(outcome.metrics.overall_score),
254
+ rationale="LLM grader disabled; using deterministic fallback identical to operational score.",
255
+ sub_scores={"fallback": _strict_score(outcome.metrics.overall_score)},
256
+ )
257
+
258
+ client = OpenAI(base_url=self.api_base_url, api_key=self.api_key)
259
+ proposal_summary = [
260
+ {
261
+ "flight_id": assignment.flight_id,
262
+ "runway": assignment.runway,
263
+ "assigned_minute": assignment.assigned_minute,
264
+ }
265
+ for assignment in proposal
266
+ ]
267
+ prompt = (
268
+ "You are a senior ATC supervisor grading a runway recovery plan.\n"
269
+ "Return strict JSON with keys score and rationale.\n"
270
+ "Score must be a float strictly between 0.0 and 1.0.\n\n"
271
+ f"Task: {task.title}\n"
272
+ f"Objective: {task.objective}\n"
273
+ f"Operational metrics: {outcome.metrics.model_dump_json()}\n"
274
+ f"Diagnostics: {json.dumps(outcome.diagnostics)}\n"
275
+ f"Proposal: {json.dumps(proposal_summary)}\n"
276
+ f"Agent rationale: {rationale}\n"
277
+ )
278
+ try:
279
+ response = client.chat.completions.create(
280
+ model=self.model_name,
281
+ temperature=0,
282
+ max_tokens=180,
283
+ messages=[
284
+ {
285
+ "role": "system",
286
+ "content": (
287
+ "Grade ATC recovery plans conservatively and output strict JSON only. "
288
+ "Score must be strictly greater than 0 and strictly less than 1."
289
+ ),
290
+ },
291
+ {"role": "user", "content": prompt},
292
+ ],
293
+ )
294
+ raw_text = (response.choices[0].message.content or "").strip()
295
+ start = raw_text.find("{")
296
+ end = raw_text.rfind("}")
297
+ if start == -1 or end == -1 or start > end:
298
+ raise ValueError("LLM grader response contains no valid JSON object")
299
+ data = json.loads(raw_text[start: end + 1])
300
+ if not isinstance(data, dict):
301
+ raise ValueError("LLM grader payload must be a JSON object")
302
+ score = max(0.0, min(1.0, float(data.get("score", 0.0))))
303
+ rationale_text = str(data.get("rationale", "LLM grader returned no rationale."))
304
+ except (
305
+ APIConnectionError,
306
+ APITimeoutError,
307
+ APIError,
308
+ RateLimitError,
309
+ OpenAIError,
310
+ json.JSONDecodeError,
311
+ ValueError,
312
+ KeyError,
313
+ AttributeError,
314
+ TypeError,
315
+ ) as exc:
316
+ score = outcome.metrics.overall_score
317
+ rationale_text = f"LLM grading failed, reverted to deterministic score: {exc}"
318
+
319
+ return TaskGrade(
320
+ grader_name=self.grader_name,
321
+ score=_strict_score(score),
322
+ rationale=rationale_text,
323
+ sub_scores={"operational_score": _strict_score(outcome.metrics.overall_score)},
324
+ )
325
+
326
+
327
+ # ── Multi-Agent Coordination Grader ──────────────────────────────────────────
328
+
329
+ class MultiAgentCoordinationGrader:
330
+ """Grades quality of AMAN/DMAN coordination in multi-agent episodes.
331
+
332
+ Scores four coordination dimensions independently:
333
+ 1. Cross-lane conflict avoidance — did shared-runway conflicts occur?
334
+ 2. Emergency handling quality — were EMERGENCY/MEDICAL flights handled first?
335
+ 3. Negotiation efficiency — how many rounds needed to resolve conflicts?
336
+ 4. Theory-of-mind bonus — did agents pre-emptively coordinate?
337
+
338
+ This grader is auxiliary (not part of official benchmark composite) but
339
+ used directly in per-agent reward functions during GRPO training.
340
+ """
341
+
342
+ grader_name = "multi_agent_coordination"
343
+
344
+ def grade(
345
+ self,
346
+ task: TaskDefinition,
347
+ outcome: SimulationOutcome,
348
+ aman_slots: List[SlotAssignment],
349
+ dman_slots: List[SlotAssignment],
350
+ negotiation_rounds: int = 0,
351
+ preemptive_yield: bool = False,
352
+ ) -> TaskGrade:
353
+ score = 0.0
354
+ sub_scores: Dict[str, float] = {}
355
+ rationale_parts: List[str] = []
356
+
357
+ # 1. Cross-lane conflict avoidance
358
+ aman_runway_set = {s.runway for s in aman_slots}
359
+ dman_runway_set = {s.runway for s in dman_slots}
360
+ shared_runways = aman_runway_set & dman_runway_set
361
+
362
+ if not shared_runways:
363
+ cross_score = 1.0
364
+ rationale_parts.append("Agents used segregated runways — no cross-lane conflict possible.")
365
+ else:
366
+ cross_conflicts = outcome.metrics.conflict_count
367
+ cross_score = max(0.0, 1.0 - cross_conflicts * 0.25)
368
+ if cross_conflicts == 0:
369
+ rationale_parts.append(f"Zero conflicts on {len(shared_runways)} shared runway(s).")
370
+ else:
371
+ rationale_parts.append(f"{cross_conflicts} conflict(s) on shared runways.")
372
+
373
+ sub_scores["cross_lane_avoidance"] = round(cross_score, 4)
374
+ score += 0.25 * cross_score
375
+
376
+ # 2. Emergency handling quality
377
+ emergency_flights = [
378
+ f for f in task.flights
379
+ if f.priority in (PriorityClass.EMERGENCY, PriorityClass.MEDICAL)
380
+ ]
381
+ all_slots = {s.flight_id: s for s in aman_slots + dman_slots}
382
+ if emergency_flights:
383
+ emg_score_val = 0.0
384
+ for f in emergency_flights:
385
+ slot = all_slots.get(f.flight_id)
386
+ if slot:
387
+ delay = abs(slot.assigned_minute - f.scheduled_minute)
388
+ emg_score_val += 1.0 if delay <= 5 else max(0.0, 1.0 - delay / 10.0)
389
+ emg_score = emg_score_val / len(emergency_flights)
390
+ rationale_parts.append(
391
+ f"Emergency handling: {emg_score:.2f} across {len(emergency_flights)} priority flight(s)."
392
+ )
393
+ else:
394
+ emg_score = 1.0
395
+ rationale_parts.append("No emergency flights in scenario.")
396
+
397
+ sub_scores["emergency_handling"] = round(emg_score, 4)
398
+ score += 0.30 * emg_score
399
+
400
+ # 3. Negotiation efficiency
401
+ if negotiation_rounds == 0:
402
+ neg_score = 1.0
403
+ rationale_parts.append("Coordination achieved in bid round (0 negotiation rounds).")
404
+ elif negotiation_rounds == 1:
405
+ neg_score = 0.6
406
+ rationale_parts.append("Coordination required 1 negotiation round.")
407
+ else:
408
+ neg_score = max(0.0, 0.4 - 0.15 * (negotiation_rounds - 2))
409
+ rationale_parts.append(f"Coordination required {negotiation_rounds} negotiation rounds.")
410
+
411
+ sub_scores["negotiation_efficiency"] = round(neg_score, 4)
412
+ score += 0.20 * neg_score
413
+
414
+ # 4. Theory-of-mind / pre-emptive coordination bonus
415
+ tom_score = 1.0 if preemptive_yield else 0.0
416
+ if preemptive_yield:
417
+ rationale_parts.append("Theory-of-mind bonus: agent pre-emptively yielded before conflict detected.")
418
+ sub_scores["theory_of_mind"] = round(tom_score, 4)
419
+ score += 0.25 * tom_score
420
+
421
+ return TaskGrade(
422
+ grader_name=self.grader_name,
423
+ score=round(max(0.01, min(0.99, score)), 4),
424
+ rationale=" | ".join(rationale_parts),
425
+ sub_scores=sub_scores,
426
+ )
427
+
428
+
429
+ def grade_multi_agent(
430
+ task: TaskDefinition,
431
+ outcome: SimulationOutcome,
432
+ aman_slots: List[SlotAssignment],
433
+ dman_slots: List[SlotAssignment],
434
+ aman_rationale: str = "",
435
+ dman_rationale: str = "",
436
+ negotiation_rounds: int = 0,
437
+ preemptive_yield: bool = False,
438
+ ) -> List[TaskGrade]:
439
+ """Grade a multi-agent episode. Returns [composite, coordination, llm_supervisor]."""
440
+ merged = aman_slots + dman_slots
441
+ combined_rationale = f"AMAN: {aman_rationale} | DMAN: {dman_rationale}"
442
+
443
+ composite = GatedCompositeGrader().grade(task, outcome, merged, combined_rationale)
444
+ coordination = MultiAgentCoordinationGrader().grade(
445
+ task, outcome, aman_slots, dman_slots, negotiation_rounds, preemptive_yield
446
+ )
447
+ llm = LLMSupervisorGrader().grade(task, outcome, merged, combined_rationale)
448
+ return [composite, coordination, llm]
449
+
450
+
451
+ # ── Public Entry Point ────────────────────────────────────────────────────────
452
+
453
+ def grade_task(
454
+ task: TaskDefinition,
455
+ outcome: SimulationOutcome,
456
+ proposal: Iterable[SlotAssignment],
457
+ rationale: str = "",
458
+ ) -> List[TaskGrade]:
459
+ """Run all task graders and return their scores.
460
+
461
+ Each sub-grader is instantiated once and called once. The composite grader
462
+ does NOT internally re-run sub-graders (no duplicate computation).
463
+
464
+ Order: [composite, llm_supervisor]
465
+ - composite_task_grader: official benchmark score (deterministic, gated)
466
+ - llm_supervisor: auxiliary LLM signal (non-official)
467
+ """
468
+ proposal_list = proposal if isinstance(proposal, list) else list(proposal)
469
+ composite = GatedCompositeGrader().grade(task, outcome, proposal_list, rationale)
470
+ llm = LLMSupervisorGrader().grade(task, outcome, proposal_list, rationale)
471
+ return [composite, llm]
models.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed data models for the ATC optimization environment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from enum import Enum
7
+ from typing import Dict, List, Literal
8
+
9
+ from pydantic import BaseModel, Field, field_validator
10
+
11
+ try:
12
+ from openenv.core.env_server.types import Action, Observation, State
13
+ except Exception as exc:
14
+ # Fallback for training-only workflows when OpenEnv runtime deps are partially
15
+ # installed (for example fastmcp/openenv version skew on cluster nodes).
16
+ print(f"[WARN] OpenEnv types unavailable, using local BaseModel fallbacks: {exc}")
17
+
18
+ class Action(BaseModel):
19
+ pass
20
+
21
+ class Observation(BaseModel):
22
+ pass
23
+
24
+ class State(BaseModel):
25
+ pass
26
+
27
+
28
+ class OperationType(str, Enum):
29
+ """Flight operation category."""
30
+
31
+ ARRIVAL = "arrival"
32
+ DEPARTURE = "departure"
33
+
34
+
35
+ class WakeClass(str, Enum):
36
+ """Wake turbulence class used for separation logic."""
37
+
38
+ LIGHT = "L"
39
+ MEDIUM = "M"
40
+ HEAVY = "H"
41
+
42
+
43
+ class PriorityClass(str, Enum):
44
+ """Operational priority categories for dispatching."""
45
+
46
+ NORMAL = "normal"
47
+ CONNECTION = "connection"
48
+ MEDICAL = "medical"
49
+ EMERGENCY = "emergency"
50
+
51
+
52
+ class Difficulty(str, Enum):
53
+ """Task difficulty level."""
54
+
55
+ EASY = "easy"
56
+ MEDIUM = "medium"
57
+ HARD = "hard"
58
+
59
+
60
+ DEFAULT_ALLOWED_OPERATIONS = (
61
+ OperationType.ARRIVAL,
62
+ OperationType.DEPARTURE,
63
+ )
64
+
65
+
66
+ def default_allowed_operations() -> List[OperationType]:
67
+ return list(DEFAULT_ALLOWED_OPERATIONS)
68
+
69
+
70
+ class RunwaySpec(BaseModel):
71
+ """Runway configuration available to the controller."""
72
+
73
+ runway_id: str = Field(..., description="Runway identifier")
74
+ allowed_operations: List[OperationType] = Field(
75
+ default_factory=default_allowed_operations,
76
+ description="Operations permitted on the runway",
77
+ )
78
+ hourly_capacity: int = Field(
79
+ ..., ge=4, le=60, description="Maximum operations per hour"
80
+ )
81
+ weather_penalty: float = Field(
82
+ default=1.0,
83
+ ge=1.0,
84
+ le=2.0,
85
+ description="Multiplier applied to capacity spacing during disruption",
86
+ )
87
+ notes: str = Field(default="", description="Operational notes for the runway")
88
+
89
+
90
+ class FlightRecord(BaseModel):
91
+ """Flight requiring a runway/slot decision."""
92
+
93
+ flight_id: str = Field(..., description="Flight callsign or identifier")
94
+ airline: str = Field(..., description="Airline code")
95
+ operation: OperationType = Field(..., description="Arrival or departure")
96
+ wake_class: WakeClass = Field(..., description="Wake turbulence category")
97
+ scheduled_minute: int = Field(..., ge=0, description="Original planned slot")
98
+ earliest_minute: int = Field(..., ge=0, description="Earliest feasible slot")
99
+ latest_minute: int = Field(..., ge=0, description="Latest feasible slot")
100
+ allowed_runways: List[str] = Field(..., description="Runways the flight may use")
101
+ passengers: int = Field(..., ge=1, description="Passengers impacted")
102
+ fuel_burn_per_minute: float = Field(
103
+ ..., ge=1.0, description="Estimated fuel burn cost for airborne/ground delay"
104
+ )
105
+ priority: PriorityClass = Field(
106
+ default=PriorityClass.NORMAL, description="Operational priority"
107
+ )
108
+ connection_risk: float = Field(
109
+ default=0.0,
110
+ ge=0.0,
111
+ le=1.0,
112
+ description="Severity of onward connection disruption",
113
+ )
114
+ notes: str = Field(default="", description="Operational nuance for the flight")
115
+
116
+
117
+ class SlotAssignment(BaseModel):
118
+ """Controller proposal for a single flight."""
119
+
120
+ flight_id: str = Field(..., description="Flight being assigned")
121
+ runway: str = Field(..., description="Runway chosen for the flight")
122
+ assigned_minute: int = Field(..., ge=0, description="Assigned slot minute")
123
+ hold_minutes: int = Field(
124
+ default=0,
125
+ ge=0,
126
+ description="Explicit holding/queueing amount declared by the agent",
127
+ )
128
+
129
+
130
+ class TaskMetrics(BaseModel):
131
+ """Normalized metrics produced by the simulator/grader."""
132
+
133
+ schedule_completeness: float = Field(default=0.0, ge=0.0, le=1.0)
134
+ conflict_free_ratio: float = Field(default=0.0, ge=0.0, le=1.0)
135
+ priority_handling: float = Field(default=0.0, ge=0.0, le=1.0)
136
+ delay_efficiency: float = Field(default=0.0, ge=0.0, le=1.0)
137
+ fairness: float = Field(default=0.0, ge=0.0, le=1.0)
138
+ fuel_efficiency: float = Field(default=0.0, ge=0.0, le=1.0)
139
+ connection_impact_score: float = Field(default=0.0, ge=0.0, le=1.0)
140
+ agent_judgment: float = Field(default=0.0, ge=0.0, le=1.0)
141
+ overall_score: float = Field(default=0.01, ge=0.0, le=1.0)
142
+ total_delay_minutes: int = Field(default=0, ge=0)
143
+ max_delay_minutes: int = Field(default=0, ge=0)
144
+ estimated_fuel_burn: float = Field(default=0.0, ge=0.0)
145
+ conflict_count: int = Field(default=0, ge=0)
146
+ capacity_violations: int = Field(default=0, ge=0)
147
+ priority_violations: int = Field(default=0, ge=0)
148
+ emergency_violations: int = Field(default=0, ge=0)
149
+ medical_violations: int = Field(default=0, ge=0)
150
+ connection_violations: int = Field(default=0, ge=0)
151
+ missing_assignments: int = Field(default=0, ge=0)
152
+ invalid_assignments: int = Field(default=0, ge=0)
153
+ per_airline_average_delay: Dict[str, float] = Field(default_factory=dict)
154
+
155
+
156
+ class TaskDefinition(BaseModel):
157
+ """Scenario definition shipped with the benchmark."""
158
+
159
+ task_id: str
160
+ title: str
161
+ difficulty: Difficulty
162
+ airport: str
163
+ description: str
164
+ objective: str
165
+ grading_focus: List[str]
166
+ planning_horizon_minutes: int = Field(..., ge=30)
167
+ max_steps: int = Field(default=4, ge=1, le=8)
168
+ delay_budget: int = Field(..., ge=30)
169
+ fuel_budget: float = Field(..., ge=50.0)
170
+ fairness_tolerance: float = Field(..., ge=1.0)
171
+ runways: List[RunwaySpec]
172
+ flights: List[FlightRecord]
173
+
174
+
175
+ class TaskGrade(BaseModel):
176
+ """Outcome returned by a task grader."""
177
+
178
+ grader_name: str
179
+ score: float = Field(..., ge=0.0, le=1.0)
180
+ rationale: str
181
+ sub_scores: Dict[str, float] = Field(default_factory=dict)
182
+
183
+
184
+ class ATCOptimizationAction(Action):
185
+ """Agent proposal for re-sequencing the disrupted traffic bank."""
186
+
187
+ proposal: List[SlotAssignment] = Field(
188
+ ...,
189
+ description="Full candidate slot plan for all or some flights in the scenario",
190
+ )
191
+ rationale: str = Field(
192
+ default="",
193
+ description="Short explanation describing prioritization decisions",
194
+ )
195
+ commit: bool = Field(
196
+ default=True,
197
+ description="Whether to finish the episode after evaluating this plan",
198
+ )
199
+
200
+ @field_validator("proposal", mode="before")
201
+ @classmethod
202
+ def parse_proposal_json(cls, value):
203
+ """Allow playground users to paste proposal JSON into a text box."""
204
+
205
+ if isinstance(value, str):
206
+ text = value.strip()
207
+ if not text:
208
+ return []
209
+ try:
210
+ parsed = json.loads(text)
211
+ except json.JSONDecodeError as exc:
212
+ raise ValueError(
213
+ "proposal must be a JSON list of slot assignments"
214
+ ) from exc
215
+ return parsed
216
+ return value
217
+
218
+
219
+ class ATCOptimizationObservation(Observation):
220
+ """Observation returned after reset/step."""
221
+
222
+ task_id: str = Field(default="", description="Task identifier")
223
+ task_title: str = Field(default="", description="Human-readable task name")
224
+ difficulty: Difficulty = Field(default=Difficulty.EASY)
225
+ airport: str = Field(default="", description="Airport code")
226
+ briefing: str = Field(default="", description="Text briefing for the agent")
227
+ objective: str = Field(default="", description="Task goal summary")
228
+ grading_focus: List[str] = Field(default_factory=list)
229
+ flights: List[FlightRecord] = Field(default_factory=list)
230
+ runways: List[RunwaySpec] = Field(default_factory=list)
231
+ current_metrics: TaskMetrics = Field(default_factory=TaskMetrics)
232
+ best_metrics: TaskMetrics = Field(default_factory=TaskMetrics)
233
+ current_plan: List[SlotAssignment] = Field(default_factory=list)
234
+ diagnostics: List[str] = Field(default_factory=list)
235
+ recommendations: List[str] = Field(default_factory=list)
236
+ grader_feedback: List[str] = Field(default_factory=list)
237
+ steps_remaining: int = Field(default=0, ge=0)
238
+
239
+
240
+ class PlanSnapshot(BaseModel):
241
+ """Compact history item used inside state."""
242
+
243
+ step: int = Field(..., ge=0)
244
+ score: float = Field(..., ge=0.0, le=1.0)
245
+ reward: float = Field(..., ge=-1.0, le=1.0)
246
+ commit: bool = Field(default=True)
247
+
248
+
249
+ class ATCOptimizationState(State):
250
+ """Serializable internal state for inspection through `/state`."""
251
+
252
+ task_id: str = Field(default="", description="Current task id")
253
+ task_title: str = Field(default="", description="Current task title")
254
+ difficulty: Difficulty = Field(default=Difficulty.EASY)
255
+ airport: str = Field(default="", description="Airport code")
256
+ seed: int = Field(default=0, ge=0)
257
+ max_steps: int = Field(default=0, ge=0)
258
+ current_metrics: TaskMetrics = Field(default_factory=TaskMetrics)
259
+ best_metrics: TaskMetrics = Field(default_factory=TaskMetrics)
260
+ current_plan: List[SlotAssignment] = Field(default_factory=list)
261
+ best_plan: List[SlotAssignment] = Field(default_factory=list)
262
+ history: List[PlanSnapshot] = Field(default_factory=list)
263
+ grader_history: List[TaskGrade] = Field(default_factory=list)
264
+ final_summary: str = Field(default="", description="Latest summary for the task")
265
+ active_task_ids: List[str] = Field(default_factory=list)
266
+ mode: Literal["planning"] = Field(default="planning")
multi_agent/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Multi-agent ATC environment: AMAN/DMAN cooperative-competitive coordination.
2
+
3
+ Also exports ADAPT — the meta-agent for structural domain transfer.
4
+ """
multi_agent/adapt.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ADAPT — Adaptive Decision Agent for Problem Transfer.
2
+
3
+ ADAPT receives scheduling problems from UNKNOWN domains. It has no prior
4
+ knowledge of any domain. It analyses each task's structural signals:
5
+
6
+ - Time window tightness (latest - earliest relative to planning horizon)
7
+ - connection_risk (probability of cascading failure if delayed)
8
+ - fuel_burn_per_minute (resource intensity proxy)
9
+ - passengers (impact weight proxy)
10
+ - notes (free-text urgency signal extraction)
11
+
12
+ From these domain-agnostic signals it infers ATC parameter mappings
13
+ (wake_class and priority) that let AMAN/DMAN solve ANY scheduling problem
14
+ unchanged — without ever being told what domain it is.
15
+
16
+ Core functions:
17
+ build_adapt_observation — build ADAPTObservation with structural entity profiles
18
+ _compute_entity_profiles — derive per-entity-type statistics from task data
19
+ _build_adapt_heuristic — structural heuristic fallback (no keyword matching)
20
+ apply_adapt_mapping — apply ADAPTAction → ATC-ready TaskDefinition
21
+ parse_adapt_action — parse LLM JSON completion into ADAPTAction
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import re
28
+ from collections import defaultdict
29
+ from typing import Any, Dict, List, Optional
30
+
31
+ try:
32
+ from ..models import FlightRecord, PriorityClass, TaskDefinition, WakeClass
33
+ from .models import (
34
+ ADAPTAction,
35
+ ADAPTObservation,
36
+ AgentRole,
37
+ SupervisorProfileName,
38
+ SUPERVISOR_PROFILES,
39
+ )
40
+ except ImportError:
41
+ from models import FlightRecord, PriorityClass, TaskDefinition, WakeClass
42
+ from multi_agent.models import (
43
+ ADAPTAction,
44
+ ADAPTObservation,
45
+ AgentRole,
46
+ SupervisorProfileName,
47
+ SUPERVISOR_PROFILES,
48
+ )
49
+
50
+
51
+ # ── Urgency signal words (domain-agnostic) ────────────────────────────────────
52
+ # These do NOT encode domain knowledge — they are general English urgency markers
53
+ # that appear in notes regardless of domain.
54
+
55
+ _URGENCY_WORDS = frozenset({
56
+ "emergency", "critical", "urgent", "immediate", "priority",
57
+ "stat", "asap", "deadline", "cannot wait", "must vacate",
58
+ "surge", "life-threatening", "requires immediate",
59
+ })
60
+
61
+
62
+ # ── Structural profile computation ────────────────────────────────────────────
63
+
64
+ def _compute_entity_profiles(task: TaskDefinition) -> Dict[str, Dict[str, Any]]:
65
+ """Compute domain-agnostic structural signals per entity type.
66
+
67
+ Groups flights by FlightRecord.airline (entity type tag) and computes
68
+ statistics that are meaningful across any scheduling domain:
69
+
70
+ - avg_window_minutes : avg(latest - earliest) — small = high urgency
71
+ - time_pressure : 1 - avg_window / planning_horizon — higher = tighter
72
+ - avg_connection_risk : avg connection_risk — higher = higher-priority
73
+ - avg_fuel_burn : avg fuel_burn_per_minute — resource intensity proxy
74
+ - avg_passengers : avg passengers — impact weight proxy
75
+ - urgency_in_notes : any urgency-word hit in combined notes
76
+ - operation_mix : {"arrival": N, "departure": N}
77
+ - count : number of entities of this type
78
+ """
79
+ groups: Dict[str, List[FlightRecord]] = defaultdict(list)
80
+ for f in task.flights:
81
+ groups[f.airline or "UNKNOWN"].append(f)
82
+
83
+ horizon = max(1, task.planning_horizon_minutes)
84
+ profiles: Dict[str, Dict[str, Any]] = {}
85
+
86
+ for entity_type, flights in groups.items():
87
+ windows = [f.latest_minute - f.earliest_minute for f in flights]
88
+ risks = [f.connection_risk for f in flights]
89
+ burns = [f.fuel_burn_per_minute for f in flights]
90
+ pax = [f.passengers for f in flights]
91
+
92
+ ops: Dict[str, int] = {"arrival": 0, "departure": 0}
93
+ for f in flights:
94
+ k = f.operation.value if hasattr(f.operation, "value") else str(f.operation)
95
+ if k in ops:
96
+ ops[k] += 1
97
+
98
+ combined_notes = " ".join((f.notes or "").lower() for f in flights)
99
+ urgency_hit = any(w in combined_notes for w in _URGENCY_WORDS)
100
+
101
+ n = max(1, len(flights))
102
+ avg_window = sum(windows) / n
103
+ avg_risk = sum(risks) / n
104
+ avg_burn = sum(burns) / n
105
+ avg_pax = sum(pax) / n
106
+
107
+ # Normalized time pressure: 0 = fully flexible, 1 = zero slack
108
+ time_pressure = max(0.0, min(1.0, 1.0 - avg_window / horizon))
109
+
110
+ profiles[entity_type] = {
111
+ "count": n,
112
+ "avg_window_minutes": round(avg_window, 1),
113
+ "time_pressure": round(time_pressure, 4),
114
+ "avg_connection_risk": round(avg_risk, 4),
115
+ "avg_fuel_burn": round(avg_burn, 2),
116
+ "avg_passengers": round(avg_pax, 1),
117
+ "urgency_in_notes": urgency_hit,
118
+ "operation_mix": ops,
119
+ }
120
+
121
+ return profiles
122
+
123
+
124
+ # ── Priority / wake-class tier ordering ──────────────────────────────────────
125
+
126
+ _PRIORITY_TIERS = [
127
+ PriorityClass.EMERGENCY.value,
128
+ PriorityClass.MEDICAL.value,
129
+ PriorityClass.CONNECTION.value,
130
+ PriorityClass.NORMAL.value,
131
+ ]
132
+ _WAKE_TIERS = [WakeClass.HEAVY.value, WakeClass.MEDIUM.value, WakeClass.LIGHT.value]
133
+
134
+
135
+ def _demote_priority(priority: str) -> str:
136
+ """Return the next-lower priority tier (floor at normal)."""
137
+ idx = _PRIORITY_TIERS.index(priority) if priority in _PRIORITY_TIERS else len(_PRIORITY_TIERS) - 1
138
+ return _PRIORITY_TIERS[min(idx + 1, len(_PRIORITY_TIERS) - 1)]
139
+
140
+
141
+ def _demote_wake(wake: str) -> str:
142
+ """Return the next-lower wake class (floor at light)."""
143
+ idx = _WAKE_TIERS.index(wake) if wake in _WAKE_TIERS else len(_WAKE_TIERS) - 1
144
+ return _WAKE_TIERS[min(idx + 1, len(_WAKE_TIERS) - 1)]
145
+
146
+
147
+ # ── Structural heuristic fallback ─────────────────────────────────────────────
148
+
149
+ def _build_adapt_heuristic(obs: ADAPTObservation, task: TaskDefinition) -> ADAPTAction:
150
+ """Structural heuristic with priority-budget enforcement.
151
+
152
+ Step 1 — Raw scoring (per entity type, no domain knowledge):
153
+ urgency_score = 0.50 × time_pressure + 0.40 × connection_risk + 0.10 × urgency_flag
154
+
155
+ Wake class raw thresholds: ≥ 0.70 → H | ≥ 0.35 → M | else → L
156
+ Priority raw thresholds:
157
+ cr ≥ 0.80 or (tp ≥ 0.95 and urgency) → emergency
158
+ cr ≥ 0.50 or tp ≥ 0.80 → medical
159
+ cr ≥ 0.20 or tp ≥ 0.60 → connection
160
+ else → normal
161
+
162
+ Step 2 — Budget enforcement (prevents all-emergency starvation):
163
+ Entities sorted by urgency_score desc; budgets applied top-down:
164
+ max_emergency = 1 (exactly one entity type may be emergency)
165
+ max_heavy = max(1, N // 3) (at most 1/3 of types as H)
166
+ max_medical = max(1, ceil(N / 3)) (after emergency slot is claimed)
167
+ Entities that exceed a budget are demoted one tier automatically.
168
+
169
+ This ensures AMAN/DMAN always see a realistic priority distribution and
170
+ avoids the starvation failure mode where AMAN yields all capacity to
171
+ emergencies and DMAN has no runway time left.
172
+ """
173
+ profiles: Dict[str, Dict[str, Any]] = obs.entity_profiles or _compute_entity_profiles(task)
174
+
175
+ # ── Step 1: raw scores ────────────────────────────────────────────────────
176
+ raw: List[tuple] = [] # (entity_type, urgency_score, raw_wake, raw_priority)
177
+
178
+ for entity_type, p in profiles.items():
179
+ tp = p["time_pressure"]
180
+ cr = p["avg_connection_risk"]
181
+ urgency = bool(p["urgency_in_notes"])
182
+
183
+ urgency_score = 0.50 * tp + 0.40 * cr + 0.10 * float(urgency)
184
+
185
+ if urgency_score >= 0.70:
186
+ raw_wake = WakeClass.HEAVY.value
187
+ elif urgency_score >= 0.35:
188
+ raw_wake = WakeClass.MEDIUM.value
189
+ else:
190
+ raw_wake = WakeClass.LIGHT.value
191
+
192
+ if cr >= 0.80 or (tp >= 0.95 and urgency):
193
+ raw_priority = PriorityClass.EMERGENCY.value
194
+ elif cr >= 0.50 or tp >= 0.80:
195
+ raw_priority = PriorityClass.MEDICAL.value
196
+ elif cr >= 0.20 or tp >= 0.60:
197
+ raw_priority = PriorityClass.CONNECTION.value
198
+ else:
199
+ raw_priority = PriorityClass.NORMAL.value
200
+
201
+ raw.append((entity_type, urgency_score, raw_wake, raw_priority, p))
202
+
203
+ # ── Step 2: budget enforcement — sort by urgency desc ────────────────────
204
+ n_types = max(1, len(raw))
205
+ max_emergency = 1
206
+ max_heavy = max(1, n_types // 3)
207
+ max_medical = max(1, -(-n_types // 3)) # ceil(N / 3)
208
+
209
+ raw.sort(key=lambda x: x[1], reverse=True)
210
+
211
+ entity_wake_map: Dict[str, str] = {}
212
+ entity_priority_map: Dict[str, str] = {}
213
+ rationale_parts: List[str] = []
214
+
215
+ emergency_used = 0
216
+ medical_used = 0
217
+ heavy_used = 0
218
+
219
+ for entity_type, urgency_score, raw_wake, raw_priority, p in raw:
220
+ # ── wake budget ───────────────────────────────────────────────────────
221
+ wake = raw_wake
222
+ if wake == WakeClass.HEAVY.value:
223
+ if heavy_used < max_heavy:
224
+ heavy_used += 1
225
+ else:
226
+ wake = _demote_wake(wake)
227
+
228
+ # ── priority budget ───────────────────────────────────────────────────
229
+ priority = raw_priority
230
+
231
+ if priority == PriorityClass.EMERGENCY.value:
232
+ if emergency_used < max_emergency:
233
+ emergency_used += 1
234
+ else:
235
+ priority = _demote_priority(priority) # → medical
236
+
237
+ if priority == PriorityClass.MEDICAL.value:
238
+ if medical_used < max_medical:
239
+ medical_used += 1
240
+ else:
241
+ priority = _demote_priority(priority) # → connection
242
+
243
+ entity_wake_map[entity_type] = wake
244
+ entity_priority_map[entity_type] = priority
245
+
246
+ demoted_wake = " (budget-demoted)" if wake != raw_wake else ""
247
+ demoted_pri = " (budget-demoted)" if priority != raw_priority else ""
248
+ rationale_parts.append(
249
+ f"{entity_type}: tp={p['time_pressure']:.2f} cr={p['avg_connection_risk']:.2f} "
250
+ f"score={urgency_score:.2f} "
251
+ f"→ wake={wake}{demoted_wake} priority={priority}{demoted_pri}"
252
+ )
253
+
254
+ return ADAPTAction(
255
+ entity_wake_map=entity_wake_map,
256
+ entity_priority_map=entity_priority_map,
257
+ rationale=(
258
+ f"Structural budget-enforced inference "
259
+ f"(budget: emergency≤{max_emergency} heavy≤{max_heavy} medical≤{max_medical}): "
260
+ + "; ".join(rationale_parts)
261
+ ),
262
+ )
263
+
264
+
265
+ # ── Observation builder ───────────────────────────────────────────────────────
266
+
267
+ def build_adapt_observation(
268
+ task: TaskDefinition,
269
+ profile: SupervisorProfileName,
270
+ domain_name: Optional[str] = None,
271
+ domain_description: Optional[str] = None,
272
+ ) -> ADAPTObservation:
273
+ """Build ADAPTObservation from any TaskDefinition.
274
+
275
+ domain_name and domain_description default to the task's own fields,
276
+ so ADAPT works on ATC tasks, ICU tasks, or any future domain without
277
+ caller changes.
278
+ """
279
+ domain_name = domain_name or task.airport
280
+ domain_description = domain_description or task.description or ""
281
+
282
+ entity_types: List[str] = sorted({f.airline for f in task.flights if f.airline})
283
+ resource_names: List[str] = [r.runway_id for r in task.runways]
284
+
285
+ # Structural profile computation — domain agnostic
286
+ entity_profiles = _compute_entity_profiles(task)
287
+
288
+ has_emergencies = any(
289
+ f.priority == PriorityClass.EMERGENCY
290
+ or any(w in (f.notes or "").lower() for w in ("emergency", "critical", "life-threatening"))
291
+ for f in task.flights
292
+ )
293
+ has_hard_deadlines = any(
294
+ any(w in (f.notes or "").upper() for w in ("DEADLINE", "AUTH", "MUST VACATE", "ATFM"))
295
+ for f in task.flights
296
+ )
297
+
298
+ # Legacy sample_entities string (still rendered in to_prompt_text via entity_profiles)
299
+ sample_lines: List[str] = []
300
+ for f in task.flights[:5]:
301
+ sample_lines.append(
302
+ f" [{f.airline}] {f.flight_id}: {f.operation.value} "
303
+ f"window=[{f.earliest_minute},{f.latest_minute}] "
304
+ f"pax={f.passengers} fuel={f.fuel_burn_per_minute}/min"
305
+ f" risk={f.connection_risk:.2f}"
306
+ )
307
+ sample_entities = "\n".join(sample_lines) if sample_lines else "(none)"
308
+
309
+ sup_desc = SUPERVISOR_PROFILES[profile]["description"]
310
+
311
+ return ADAPTObservation(
312
+ role=AgentRole.ADAPT,
313
+ domain_id=task.task_id,
314
+ domain_name=domain_name,
315
+ domain_description=domain_description,
316
+ entity_types=entity_types,
317
+ resource_names=resource_names,
318
+ sample_entities=sample_entities,
319
+ entity_profiles=entity_profiles,
320
+ supervisor_profile_name=profile,
321
+ supervisor_description=sup_desc,
322
+ has_emergencies=has_emergencies,
323
+ has_hard_deadlines=has_hard_deadlines,
324
+ entity_count=len(task.flights),
325
+ )
326
+
327
+
328
+ # ── Mapping application ───────────────────────────────────────────────────────
329
+
330
+ def apply_adapt_mapping(task: TaskDefinition, action: ADAPTAction) -> TaskDefinition:
331
+ """Apply ADAPTAction to task — override wake_class and priority per entity type.
332
+
333
+ Entity type is stored in FlightRecord.airline (no schema changes needed).
334
+ Unknown entity types are passed through unchanged.
335
+ Invalid enum values in the action are silently skipped.
336
+ """
337
+ adapted_flights: List[FlightRecord] = []
338
+ for flight in task.flights:
339
+ entity_type = flight.airline or ""
340
+ updates: Dict[str, Any] = {}
341
+
342
+ if entity_type in action.entity_wake_map:
343
+ try:
344
+ updates["wake_class"] = WakeClass(action.entity_wake_map[entity_type])
345
+ except ValueError:
346
+ pass
347
+
348
+ if entity_type in action.entity_priority_map:
349
+ try:
350
+ updates["priority"] = PriorityClass(action.entity_priority_map[entity_type])
351
+ except ValueError:
352
+ pass
353
+
354
+ adapted_flights.append(
355
+ flight.model_copy(update=updates) if updates else flight
356
+ )
357
+
358
+ return task.model_copy(update={"flights": adapted_flights})
359
+
360
+
361
+ # ── Completion parser ─────────────────────────────────────────────────────────
362
+
363
+ def _coerce_text(completion: Any) -> str:
364
+ if completion is None:
365
+ return ""
366
+ if isinstance(completion, bytes):
367
+ return completion.decode("utf-8", errors="ignore")
368
+ if isinstance(completion, str):
369
+ return completion
370
+ if isinstance(completion, dict):
371
+ for key in ("content", "text", "completion", "generated_text"):
372
+ if key in completion:
373
+ return _coerce_text(completion[key])
374
+ try:
375
+ return json.dumps(completion)
376
+ except Exception:
377
+ return str(completion)
378
+ if isinstance(completion, list):
379
+ parts = [_coerce_text(item) for item in completion]
380
+ return "\n".join(p for p in parts if p)
381
+ return str(completion)
382
+
383
+
384
+ def parse_adapt_action(completion: Any) -> Optional[ADAPTAction]:
385
+ """Parse LLM JSON completion into ADAPTAction. Returns None on failure."""
386
+ text = _coerce_text(completion)
387
+ text = re.sub(r"```(?:json)?", "", text).strip()
388
+ match = re.search(r"\{.*\}", text, re.DOTALL)
389
+ if not match:
390
+ return None
391
+ try:
392
+ data = json.loads(match.group(0))
393
+ return ADAPTAction(
394
+ entity_wake_map=data.get("entity_wake_map", {}),
395
+ entity_priority_map=data.get("entity_priority_map", {}),
396
+ rationale=data.get("rationale", ""),
397
+ )
398
+ except Exception:
399
+ return None
multi_agent/environment.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Multi-agent ATC environment: AMAN + DMAN cooperative-competitive coordination.
2
+
3
+ Protocol (3 rounds per episode):
4
+ Round 0 BID: AMAN submits arrivals plan, DMAN submits departures plan independently
5
+ Round 1 NEGOTIATE: Environment detects conflicts, broadcasts to both agents, agents revise
6
+ Round 2 FINAL: Plans merged, simulate_plan() + grade_task() run, per-agent rewards emitted
7
+
8
+ Key design principles:
9
+ - Partial observability: each agent sees only own flight type + incoming messages
10
+ - Competitive baseline: each agent optimises own objective (delay for own flights)
11
+ - Cooperative forcing: emergencies and conflicts force cross-agent coordination
12
+ - Reward decomposition: AMAN reward ≠ DMAN reward; both logged for training curves
13
+ - Theory-of-mind bonus: rewarded when agent pre-emptively coordinates without prompt
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import copy
19
+ import re
20
+ import random
21
+ from dataclasses import dataclass, field
22
+ from typing import Dict, List, Optional, Tuple
23
+
24
+ try:
25
+ from ..engine import empty_metrics, simulate_plan
26
+ from ..graders import GatedCompositeGrader, SafetyGateEvaluator, grade_task
27
+ from ..models import (
28
+ FlightRecord,
29
+ OperationType,
30
+ PriorityClass,
31
+ SlotAssignment,
32
+ TaskDefinition,
33
+ TaskMetrics,
34
+ )
35
+ from ..tasks import task_catalog
36
+ from .models import (
37
+ AMANAction,
38
+ AgentRole,
39
+ DMANAction,
40
+ GeneratorAction,
41
+ MessageType,
42
+ MultiAgentEpisodeResult,
43
+ MultiAgentObservation,
44
+ NegotiationMessage,
45
+ PerRoleMetrics,
46
+ RoundType,
47
+ SupervisorProfileName,
48
+ SUPERVISOR_PROFILES,
49
+ )
50
+ from .supervisor import SupervisorAgent
51
+ except ImportError:
52
+ from engine import empty_metrics, simulate_plan
53
+ from graders import GatedCompositeGrader, SafetyGateEvaluator, grade_task
54
+ from models import (
55
+ FlightRecord,
56
+ OperationType,
57
+ PriorityClass,
58
+ SlotAssignment,
59
+ TaskDefinition,
60
+ TaskMetrics,
61
+ )
62
+ from tasks import task_catalog
63
+ from multi_agent.models import (
64
+ AMANAction,
65
+ AgentRole,
66
+ DMANAction,
67
+ GeneratorAction,
68
+ MessageType,
69
+ MultiAgentEpisodeResult,
70
+ MultiAgentObservation,
71
+ NegotiationMessage,
72
+ PerRoleMetrics,
73
+ RoundType,
74
+ SupervisorProfileName,
75
+ SUPERVISOR_PROFILES,
76
+ )
77
+ from multi_agent.supervisor import SupervisorAgent
78
+
79
+
80
+ MAX_NEGOTIATE_ROUNDS = 2 # max negotiation passes before forced merge (native ATC episodes)
81
+ # ADAPT/ICU (domain transfer) remapped tasks are often window-tight; allow extra repair passes
82
+ DOMAIN_MAX_NEGOTIATE_ROUNDS = 4
83
+ ATFM_DEADLINE_HEADROOM = 8 # minutes of margin to call an ATFM violation
84
+
85
+ # Matches "TRANSFER AUTH DEADLINE: minute 60" in flight notes (ICU domain).
86
+ _TRANSFER_DEADLINE_RE = re.compile(
87
+ r"TRANSFER\s+AUTH\s+DEADLINE\s*:\s*MINUTE\s+(\d+)", re.IGNORECASE
88
+ )
89
+
90
+
91
+ def diagnostic_is_separation_issue(diagnostic_line: str) -> bool:
92
+ """True for wake/separation violations that force the negotiate round (matches _detect_conflicts)."""
93
+ d = diagnostic_line.lower()
94
+ return "spaced" in diagnostic_line or "conflict" in d
95
+
96
+
97
+ def count_separation_issues(diagnostics: List[str]) -> int:
98
+ """Count separation / wake-spacing violations in simulator diagnostics."""
99
+ return sum(1 for line in diagnostics if diagnostic_is_separation_issue(line))
100
+
101
+ # Domain randomization bounds — small perturbations to prevent task memorisation
102
+ _RAND_WINDOW_DELTA = 5 # ± minutes applied to flight windows
103
+ _RAND_WEATHER_DELTA = 0.08 # ± weather_penalty (clipped to [1.0, 1.8])
104
+ _RAND_BUDGET_SCALE = 0.12 # ± fraction applied to delay_budget / fuel_budget
105
+ _RAND_MIN_WINDOW = 10 # never squeeze window below this width (minutes)
106
+
107
+
108
+ @dataclass
109
+ class EpisodeState:
110
+ task: TaskDefinition
111
+ supervisor_profile: SupervisorProfileName
112
+ atfm_deadlines: Dict[str, int] = field(default_factory=dict)
113
+ aman_slots: List[SlotAssignment] = field(default_factory=list)
114
+ dman_slots: List[SlotAssignment] = field(default_factory=list)
115
+ aman_messages: List[NegotiationMessage] = field(default_factory=list)
116
+ dman_messages: List[NegotiationMessage] = field(default_factory=list)
117
+ conflict_log: List[str] = field(default_factory=list)
118
+ round_number: int = 0
119
+ negotiation_rounds: int = 0
120
+ episode_id: int = 0
121
+ # Set to DOMAIN_MAX_NEGOTIATE_ROUNDS for ICU/ADAPT episodes so that the
122
+ # LLM sees an accurate steps_remaining rather than going to zero after pass 1.
123
+ max_negotiate_rounds: int = MAX_NEGOTIATE_ROUNDS
124
+
125
+
126
+ class MultiAgentATCEnvironment:
127
+ """AMAN/DMAN cooperative-competitive environment.
128
+
129
+ Usage (training loop):
130
+ env = MultiAgentATCEnvironment()
131
+ aman_obs, dman_obs = env.reset(task_id="bengaluru_irrops_hard", episode_id=42)
132
+
133
+ # Round 0 — BID
134
+ aman_action = aman_agent(aman_obs)
135
+ dman_action = dman_agent(dman_obs)
136
+ aman_obs, dman_obs, partial_reward, done = env.step_bid(aman_action, dman_action)
137
+
138
+ # Round 1 — NEGOTIATE (if conflicts)
139
+ if not done:
140
+ aman_action = aman_agent(aman_obs)
141
+ dman_action = dman_agent(dman_obs)
142
+ aman_obs, dman_obs, partial_reward, done = env.step_negotiate(aman_action, dman_action)
143
+
144
+ # Round 2 — FINAL
145
+ result = env.finalize()
146
+ """
147
+
148
+ def __init__(self, seed: int = 42) -> None:
149
+ self._catalog: Dict[str, TaskDefinition] = task_catalog()
150
+ self._supervisor = SupervisorAgent()
151
+ self._rng = random.Random(seed)
152
+ self._state: Optional[EpisodeState] = None
153
+
154
+ # ── Public API ────────────────────────────────────────────────────────────
155
+
156
+ def reset(
157
+ self,
158
+ task_id: Optional[str] = None,
159
+ episode_id: int = 0,
160
+ supervisor_profile: Optional[SupervisorProfileName] = None,
161
+ mutated_task: Optional[TaskDefinition] = None,
162
+ randomize: bool = False,
163
+ domain_mode: bool = False,
164
+ ) -> Tuple[MultiAgentObservation, MultiAgentObservation]:
165
+ """Reset environment. Returns (aman_obs, dman_obs).
166
+
167
+ Args:
168
+ randomize: When True (training with no generator), applies bounded
169
+ parametric perturbations to flight windows and runway weather so
170
+ agents cannot memorise exact task parameters across episodes.
171
+ Off by default to keep evaluation and tests deterministic.
172
+ domain_mode: Set True for ADAPT/ICU domain-transfer episodes.
173
+ Increases max_negotiate_rounds so agents see a correct
174
+ steps_remaining value during the extra repair passes.
175
+ """
176
+ if mutated_task is not None:
177
+ task = mutated_task
178
+ elif task_id and task_id in self._catalog:
179
+ task = self._catalog[task_id]
180
+ else:
181
+ task = self._rng.choice(list(self._catalog.values()))
182
+
183
+ if randomize:
184
+ task = self._randomize_task(task, episode_id)
185
+
186
+ profile = supervisor_profile or self._supervisor.sample_profile(episode_id)
187
+ atfm = self._build_atfm_deadlines(task)
188
+ max_neg = DOMAIN_MAX_NEGOTIATE_ROUNDS if domain_mode else MAX_NEGOTIATE_ROUNDS
189
+
190
+ self._state = EpisodeState(
191
+ task=task,
192
+ supervisor_profile=profile,
193
+ atfm_deadlines=atfm,
194
+ episode_id=episode_id,
195
+ max_negotiate_rounds=max_neg,
196
+ )
197
+ return self._build_observations(RoundType.BID, conflict_log=[], incoming_aman=[], incoming_dman=[])
198
+
199
+ def step_bid(
200
+ self,
201
+ aman_action: AMANAction,
202
+ dman_action: DMANAction,
203
+ ) -> Tuple[MultiAgentObservation, MultiAgentObservation, float, bool]:
204
+ """Process Round 0: independent bids. Returns obs pair, dense reward, done."""
205
+ assert self._state is not None, "call reset() first"
206
+ state = self._state
207
+
208
+ state.aman_slots = list(aman_action.arrival_slots)
209
+ state.dman_slots = list(dman_action.departure_slots)
210
+ state.aman_messages = list(aman_action.outgoing_messages)
211
+ state.dman_messages = list(dman_action.outgoing_messages)
212
+ state.round_number = 1
213
+
214
+ conflicts, diagnostics = self._detect_conflicts(state)
215
+ state.conflict_log = diagnostics
216
+
217
+ # If emergency broadcast present, inject environment conflict flags
218
+ self._inject_emergency_flags(state, aman_action, dman_action)
219
+
220
+ partial_score = self._score_merged(state)
221
+ done = len(conflicts) == 0 # no conflicts → skip negotiate, go straight to final
222
+ if done:
223
+ state.round_number = 2
224
+
225
+ aman_obs, dman_obs = self._build_observations(
226
+ RoundType.NEGOTIATE if not done else RoundType.FINAL,
227
+ conflict_log=state.conflict_log,
228
+ incoming_aman=state.dman_messages,
229
+ incoming_dman=state.aman_messages,
230
+ )
231
+ return aman_obs, dman_obs, round(partial_score * 0.3, 4), done
232
+
233
+ def step_negotiate(
234
+ self,
235
+ aman_action: AMANAction,
236
+ dman_action: DMANAction,
237
+ ) -> Tuple[MultiAgentObservation, MultiAgentObservation, float, bool]:
238
+ """Process Round 1: negotiation revision. Returns obs pair, dense reward, done."""
239
+ assert self._state is not None
240
+ state = self._state
241
+
242
+ state.aman_slots = list(aman_action.arrival_slots)
243
+ state.dman_slots = list(dman_action.departure_slots)
244
+ state.aman_messages = list(aman_action.outgoing_messages)
245
+ state.dman_messages = list(dman_action.outgoing_messages)
246
+ state.round_number = 2
247
+ state.negotiation_rounds += 1
248
+
249
+ conflicts, diagnostics = self._detect_conflicts(state)
250
+ state.conflict_log = diagnostics
251
+
252
+ partial_score = self._score_merged(state)
253
+
254
+ aman_obs, dman_obs = self._build_observations(
255
+ RoundType.FINAL,
256
+ conflict_log=state.conflict_log,
257
+ incoming_aman=state.dman_messages,
258
+ incoming_dman=state.aman_messages,
259
+ )
260
+ return aman_obs, dman_obs, round(partial_score * 0.3, 4), True
261
+
262
+ def finalize(self) -> MultiAgentEpisodeResult:
263
+ """Merge plans, run full grader, compute per-agent rewards."""
264
+ assert self._state is not None
265
+ state = self._state
266
+
267
+ merged = state.aman_slots + state.dman_slots
268
+ outcome = simulate_plan(state.task, merged)
269
+ grades = grade_task(state.task, outcome, merged, rationale="multi-agent final")
270
+ composite = next(
271
+ (g for g in grades if g.grader_name == "composite_task_grader"), grades[-1]
272
+ )
273
+
274
+ per_role = self._compute_per_role_metrics(state, outcome.metrics)
275
+
276
+ aman_reward = self._aman_reward(per_role, outcome.metrics, state)
277
+ dman_reward = self._dman_reward(per_role, outcome.metrics, state)
278
+ supervisor_score = self._supervisor.score_plan(
279
+ outcome, state.task, state.supervisor_profile
280
+ )
281
+ # Generator reward: adversarial (1 - controller avg), penalised if unsolvable
282
+ controller_avg = (aman_reward + dman_reward) / 2.0
283
+ generator_reward = max(-1.0, 1.0 - controller_avg)
284
+
285
+ return MultiAgentEpisodeResult(
286
+ task_id=state.task.task_id,
287
+ supervisor_profile=state.supervisor_profile,
288
+ composite_score=round(composite.score, 4),
289
+ aman_reward=round(aman_reward, 4),
290
+ dman_reward=round(dman_reward, 4),
291
+ generator_reward=round(generator_reward, 4),
292
+ supervisor_score=round(supervisor_score, 4),
293
+ per_role=per_role,
294
+ negotiation_rounds=state.negotiation_rounds,
295
+ )
296
+
297
+ # ── Observation builder ───────────────────────────────────────────────────
298
+
299
+ def _build_observations(
300
+ self,
301
+ round_type: RoundType,
302
+ conflict_log: List[str],
303
+ incoming_aman: List[NegotiationMessage],
304
+ incoming_dman: List[NegotiationMessage],
305
+ ) -> Tuple[MultiAgentObservation, MultiAgentObservation]:
306
+ assert self._state is not None
307
+ state = self._state
308
+ profile_name = state.supervisor_profile
309
+ sup_desc = SUPERVISOR_PROFILES[profile_name]["description"]
310
+
311
+ arrivals = [f for f in state.task.flights if f.operation == OperationType.ARRIVAL]
312
+ departures = [f for f in state.task.flights if f.operation == OperationType.DEPARTURE]
313
+
314
+ shared = dict(
315
+ task_id=state.task.task_id,
316
+ airport=state.task.airport,
317
+ briefing=state.task.description,
318
+ all_runways=state.task.runways,
319
+ supervisor_profile_name=profile_name,
320
+ supervisor_description=sup_desc,
321
+ conflict_log=conflict_log,
322
+ round_type=round_type,
323
+ round_number=state.round_number,
324
+ # Use per-episode cap (DOMAIN_MAX_NEGOTIATE_ROUNDS for ICU) so the LLM
325
+ # always sees a non-zero steps_remaining while repair passes remain.
326
+ steps_remaining=max(0, state.max_negotiate_rounds - state.negotiation_rounds),
327
+ )
328
+
329
+ # Partial observability: ATFM deadlines are DMAN-only information.
330
+ # AMAN has no visibility into network slot constraints for departures.
331
+ aman_obs = MultiAgentObservation(
332
+ role=AgentRole.AMAN,
333
+ my_flights=arrivals,
334
+ incoming_messages=incoming_aman,
335
+ atfm_deadlines={},
336
+ **shared,
337
+ )
338
+ dman_obs = MultiAgentObservation(
339
+ role=AgentRole.DMAN,
340
+ my_flights=departures,
341
+ incoming_messages=incoming_dman,
342
+ atfm_deadlines=state.atfm_deadlines,
343
+ **shared,
344
+ )
345
+ return aman_obs, dman_obs
346
+
347
+ # ── Conflict detection ────────────────────────────────────────────────────
348
+
349
+ def _detect_conflicts(
350
+ self, state: EpisodeState
351
+ ) -> Tuple[List[str], List[str]]:
352
+ """Detect cross-agent runway conflicts by running simulate_plan on merge."""
353
+ merged = state.aman_slots + state.dman_slots
354
+ outcome = simulate_plan(state.task, merged)
355
+ conflicts = [d for d in outcome.diagnostics if diagnostic_is_separation_issue(d)]
356
+ return conflicts, outcome.diagnostics
357
+
358
+ def _score_merged(self, state: EpisodeState) -> float:
359
+ merged = state.aman_slots + state.dman_slots
360
+ outcome = simulate_plan(state.task, merged)
361
+ return outcome.normalized_score
362
+
363
+ # ── Emergency handling ────────────────────────────────────────────────────
364
+
365
+ def _inject_emergency_flags(
366
+ self,
367
+ state: EpisodeState,
368
+ aman_action: AMANAction,
369
+ dman_action: DMANAction,
370
+ ) -> None:
371
+ """Inject environment-level emergency conflict flags into message queues."""
372
+ flights_by_id = {f.flight_id: f for f in state.task.flights}
373
+
374
+ # DMAN fuel/medical emergency departures → flag to AMAN
375
+ for fid in dman_action.emergency_broadcasts:
376
+ flight = flights_by_id.get(fid)
377
+ if not flight:
378
+ continue
379
+ slot = next((s for s in state.dman_slots if s.flight_id == fid), None)
380
+ if not slot:
381
+ continue
382
+ state.aman_messages.append(NegotiationMessage(
383
+ from_role=AgentRole.DMAN,
384
+ message_type=MessageType.EMERGENCY_BCAST,
385
+ flight_id=fid,
386
+ requested_minute=slot.assigned_minute,
387
+ runway_id=slot.runway,
388
+ priority=flight.priority,
389
+ reason=f"Fuel/medical emergency departure — needs runway by T+{slot.assigned_minute}",
390
+ is_emergency=True,
391
+ ))
392
+
393
+ # AMAN emergency arrivals → flag to DMAN
394
+ emergency_arrivals = [
395
+ f for f in state.task.flights
396
+ if f.operation == OperationType.ARRIVAL
397
+ and f.priority in (PriorityClass.EMERGENCY, PriorityClass.MEDICAL)
398
+ ]
399
+ for flight in emergency_arrivals:
400
+ slot = next((s for s in state.aman_slots if s.flight_id == flight.flight_id), None)
401
+ if not slot:
402
+ continue
403
+ state.dman_messages.append(NegotiationMessage(
404
+ from_role=AgentRole.AMAN,
405
+ message_type=MessageType.EMERGENCY_BCAST,
406
+ flight_id=flight.flight_id,
407
+ requested_minute=slot.assigned_minute,
408
+ runway_id=slot.runway,
409
+ priority=flight.priority,
410
+ reason=f"Emergency arrival — runway {slot.runway} must be clear at T+{slot.assigned_minute}",
411
+ is_emergency=True,
412
+ ))
413
+
414
+ # ── Per-role reward computation ───────────────────────────────────────────
415
+
416
+ def _compute_per_role_metrics(
417
+ self, state: EpisodeState, metrics: TaskMetrics
418
+ ) -> PerRoleMetrics:
419
+ flights_by_id = {f.flight_id: f for f in state.task.flights}
420
+ aman_map = {s.flight_id: s for s in state.aman_slots}
421
+ dman_map = {s.flight_id: s for s in state.dman_slots}
422
+
423
+ arr_delay_total = 0
424
+ dep_delay_total = 0
425
+ arr_count = dep_count = 0
426
+ arr_missing = dep_missing = 0
427
+ emg_arr_ok = emg_arr_miss = 0
428
+ emg_dep_ok = emg_dep_miss = 0
429
+ atfm_viol = atfm_ok = 0
430
+
431
+ for f in state.task.flights:
432
+ is_emergency = f.priority in (PriorityClass.EMERGENCY, PriorityClass.MEDICAL)
433
+ if f.operation == OperationType.ARRIVAL:
434
+ arr_count += 1
435
+ slot = aman_map.get(f.flight_id)
436
+ if slot:
437
+ delay = abs(slot.assigned_minute - f.scheduled_minute)
438
+ arr_delay_total += delay
439
+ if is_emergency:
440
+ if delay <= 5:
441
+ emg_arr_ok += 1
442
+ else:
443
+ emg_arr_miss += 1
444
+ else:
445
+ arr_missing += 1
446
+ if is_emergency:
447
+ emg_arr_miss += 1
448
+ else:
449
+ dep_count += 1
450
+ slot = dman_map.get(f.flight_id)
451
+ if slot:
452
+ delay = abs(slot.assigned_minute - f.scheduled_minute)
453
+ dep_delay_total += delay
454
+ if is_emergency:
455
+ if delay <= 5:
456
+ emg_dep_ok += 1
457
+ else:
458
+ emg_dep_miss += 1
459
+ # ATFM check
460
+ deadline = state.atfm_deadlines.get(f.flight_id)
461
+ if deadline is not None:
462
+ if slot.assigned_minute <= deadline:
463
+ atfm_ok += 1
464
+ else:
465
+ atfm_viol += 1
466
+ else:
467
+ dep_missing += 1
468
+ if is_emergency:
469
+ emg_dep_miss += 1
470
+
471
+ # Cross-lane vs intra-lane conflict heuristic:
472
+ # cross = conflicts involving one AMAN slot and one DMAN slot on same runway
473
+ cross_conflicts = self._count_cross_lane_conflicts(state)
474
+ intra_conflicts = max(0, metrics.conflict_count - cross_conflicts)
475
+
476
+ arr_mean = (arr_delay_total / max(1, arr_count))
477
+ dep_mean = (dep_delay_total / max(1, dep_count))
478
+
479
+ coord_score = self._coordination_score(state, metrics, cross_conflicts)
480
+
481
+ return PerRoleMetrics(
482
+ arrival_count=arr_count,
483
+ arrival_delay_total=arr_delay_total,
484
+ arrival_delay_mean=round(arr_mean, 2),
485
+ arrivals_missing=arr_missing,
486
+ emergency_arrivals_ok=emg_arr_ok,
487
+ emergency_arrivals_missed=emg_arr_miss,
488
+ departure_count=dep_count,
489
+ departure_delay_total=dep_delay_total,
490
+ departure_delay_mean=round(dep_mean, 2),
491
+ departures_missing=dep_missing,
492
+ atfm_violations=atfm_viol,
493
+ atfm_compliant=atfm_ok,
494
+ emergency_departures_ok=emg_dep_ok,
495
+ emergency_departures_missed=emg_dep_miss,
496
+ cross_lane_conflicts=cross_conflicts,
497
+ intra_lane_conflicts=intra_conflicts,
498
+ negotiation_rounds_used=state.negotiation_rounds,
499
+ coordination_score=coord_score,
500
+ )
501
+
502
+ def _count_cross_lane_conflicts(self, state: EpisodeState) -> int:
503
+ """Heuristic: conflicts on runways used by BOTH agents."""
504
+ from collections import defaultdict
505
+ aman_runways = {s.runway for s in state.aman_slots}
506
+ dman_runways = {s.runway for s in state.dman_slots}
507
+ shared_runways = aman_runways & dman_runways
508
+ if not shared_runways:
509
+ return 0
510
+ # Re-run sim on shared-runway slots only
511
+ shared_slots = [
512
+ s for s in (state.aman_slots + state.dman_slots)
513
+ if s.runway in shared_runways
514
+ ]
515
+ outcome = simulate_plan(state.task, shared_slots)
516
+ return outcome.metrics.conflict_count
517
+
518
+ def _coordination_score(
519
+ self,
520
+ state: EpisodeState,
521
+ metrics: TaskMetrics,
522
+ cross_conflicts: int,
523
+ ) -> float:
524
+ """Theory-of-mind quality score for agent coordination.
525
+
526
+ Rewards:
527
+ - Correct emergency yield without being asked (+0.3)
528
+ - Pre-emptive gap left for known DMAN emergency (+0.25)
529
+ - Resolved in fewest negotiation rounds (+0.2 if 0 rounds, +0.1 if 1)
530
+ - Zero cross-lane conflicts (+0.25)
531
+ - Proposed alternatives that were adopted in the final plan (+0.15)
532
+ """
533
+ score = 0.0
534
+
535
+ # Zero cross-lane conflicts
536
+ if cross_conflicts == 0:
537
+ score += 0.25
538
+
539
+ # Negotiation efficiency (extra pass penalised lightly vs unresolved conflicts)
540
+ if state.negotiation_rounds == 0:
541
+ score += 0.20
542
+ elif state.negotiation_rounds == 1:
543
+ score += 0.10
544
+ elif state.negotiation_rounds == 2:
545
+ score += 0.05
546
+
547
+ # Emergency handling quality
548
+ emergency_flights = [
549
+ f for f in state.task.flights
550
+ if f.priority in (PriorityClass.EMERGENCY, PriorityClass.MEDICAL)
551
+ ]
552
+ if emergency_flights:
553
+ assigned_ids = {s.flight_id for s in state.aman_slots + state.dman_slots}
554
+ ratio = sum(1 for f in emergency_flights if f.flight_id in assigned_ids) / len(emergency_flights)
555
+ score += 0.30 * ratio
556
+
557
+ # Pre-emptive coordination: DMAN broadcast emergency AND AMAN left gap
558
+ dman_broadcasts = {m.flight_id for m in state.dman_messages if m.is_emergency}
559
+ if dman_broadcasts:
560
+ aman_runway_minutes = {(s.runway, s.assigned_minute) for s in state.aman_slots}
561
+ for fid in dman_broadcasts:
562
+ dep_slot = next((s for s in state.dman_slots if s.flight_id == fid), None)
563
+ if dep_slot:
564
+ clear = all(
565
+ abs(m - dep_slot.assigned_minute) >= 3
566
+ for (rwy, m) in aman_runway_minutes
567
+ if rwy == dep_slot.runway
568
+ )
569
+ if clear:
570
+ score += 0.25
571
+ break
572
+
573
+ # Reward proposed alternatives that were actually adopted in the final plan.
574
+ # This incentivises agents to offer concrete fallbacks, not just claim slots.
575
+ final_slots = {(s.flight_id, s.runway) for s in state.aman_slots + state.dman_slots}
576
+ all_messages = state.aman_messages + state.dman_messages
577
+ for msg in all_messages:
578
+ for alt in msg.proposed_alternatives:
579
+ if (alt.flight_id, alt.runway_id) in final_slots:
580
+ score += 0.15
581
+ break # one bonus per message at most
582
+
583
+ return round(min(1.0, score), 4)
584
+
585
+ # ── Per-agent reward functions ────────────────────────────────────────────
586
+
587
+ def _aman_reward(
588
+ self, per_role: PerRoleMetrics, metrics: TaskMetrics, state: EpisodeState
589
+ ) -> float:
590
+ """Potential-based AMAN reward (Ng et al. 1999).
591
+
592
+ Components:
593
+ 1. Arrival delay efficiency (normalized against task budget)
594
+ 2. Emergency arrival handling
595
+ 3. Coordination bonus (theory-of-mind)
596
+ 4. Cross-lane conflict penalty (penalises AMAN for shared-runway chaos)
597
+ 5. Supervisor alignment
598
+ """
599
+ arr_count = max(1, per_role.arrival_count)
600
+ budget = state.task.delay_budget / 2 # AMAN's share of delay budget
601
+
602
+ # 1. Delay efficiency
603
+ delay_ratio = per_role.arrival_delay_total / max(1, budget)
604
+ delay_score = max(0.0, 1.0 - delay_ratio)
605
+
606
+ # 2. Emergency arrival bonus
607
+ total_emg = per_role.emergency_arrivals_ok + per_role.emergency_arrivals_missed
608
+ emg_score = (per_role.emergency_arrivals_ok / max(1, total_emg)) if total_emg else 1.0
609
+
610
+ # 3. Coverage (did AMAN assign all arrivals?)
611
+ coverage = 1.0 - (per_role.arrivals_missing / arr_count)
612
+
613
+ # 4. Coordination bonus
614
+ coord = per_role.coordination_score
615
+
616
+ # 5. Cross-lane conflict penalty
617
+ cross_penalty = 0.15 * per_role.cross_lane_conflicts
618
+
619
+ # 6. Supervisor preference alignment (partial)
620
+ profile = SUPERVISOR_PROFILES[state.supervisor_profile]
621
+ w_conflict = profile.get("conflict_weight", 1.0) / 3.0
622
+ w_priority = profile.get("priority_weight", 1.0) / 3.5
623
+
624
+ supervisor_adj = (
625
+ w_priority * emg_score * 0.1
626
+ - w_conflict * cross_penalty * 0.1
627
+ )
628
+
629
+ raw = (
630
+ 0.35 * delay_score
631
+ + 0.25 * emg_score
632
+ + 0.20 * coverage
633
+ + 0.15 * coord
634
+ + 0.05 * max(0.0, 1.0 - cross_penalty)
635
+ + supervisor_adj
636
+ )
637
+ return round(max(0.0, min(1.0, raw)), 4)
638
+
639
+ def _dman_reward(
640
+ self, per_role: PerRoleMetrics, metrics: TaskMetrics, state: EpisodeState
641
+ ) -> float:
642
+ """Potential-based DMAN reward.
643
+
644
+ Components:
645
+ 1. Departure delay efficiency
646
+ 2. ATFM compliance (hard network slot adherence)
647
+ 3. Emergency departure handling
648
+ 4. Coordination bonus
649
+ 5. Cross-lane conflict penalty
650
+ 6. Supervisor alignment
651
+ """
652
+ dep_count = max(1, per_role.departure_count)
653
+ budget = state.task.delay_budget / 2
654
+
655
+ # 1. Delay efficiency
656
+ delay_ratio = per_role.departure_delay_total / max(1, budget)
657
+ delay_score = max(0.0, 1.0 - delay_ratio)
658
+
659
+ # 2. ATFM compliance
660
+ total_atfm = per_role.atfm_compliant + per_role.atfm_violations
661
+ atfm_score = (per_role.atfm_compliant / max(1, total_atfm)) if total_atfm else 1.0
662
+
663
+ # 3. Emergency departure bonus
664
+ total_emg = per_role.emergency_departures_ok + per_role.emergency_departures_missed
665
+ emg_score = (per_role.emergency_departures_ok / max(1, total_emg)) if total_emg else 1.0
666
+
667
+ # 4. Coverage
668
+ coverage = 1.0 - (per_role.departures_missing / dep_count)
669
+
670
+ # 5. Coordination
671
+ coord = per_role.coordination_score
672
+
673
+ # 6. Cross-lane conflict penalty
674
+ cross_penalty = 0.15 * per_role.cross_lane_conflicts
675
+
676
+ profile = SUPERVISOR_PROFILES[state.supervisor_profile]
677
+ w_conflict = profile.get("conflict_weight", 1.0) / 3.0
678
+ w_fuel = profile.get("fuel_weight", 1.0) / 2.5
679
+
680
+ # Fuel penalty via ATFM: missing ATFM slots causes upstream fuel burn
681
+ fuel_adj = w_fuel * atfm_score * 0.1
682
+
683
+ raw = (
684
+ 0.30 * delay_score
685
+ + 0.20 * atfm_score
686
+ + 0.20 * emg_score
687
+ + 0.15 * coverage
688
+ + 0.10 * coord
689
+ + 0.05 * max(0.0, 1.0 - cross_penalty)
690
+ + fuel_adj
691
+ )
692
+ return round(max(0.0, min(1.0, raw)), 4)
693
+
694
+ # ── Domain randomisation ──────────────────────────────────────────────────
695
+
696
+ def _randomize_task(self, task: TaskDefinition, episode_id: int) -> TaskDefinition:
697
+ """Apply bounded parametric perturbations to prevent task memorisation.
698
+
699
+ Uses a deterministic seed derived from (task_id, episode_id) so results
700
+ are reproducible for a given episode while varying across episodes.
701
+ All perturbations are small enough that solvability is preserved.
702
+ """
703
+ seed = hash(f"{task.task_id}:{episode_id}") & 0x7FFFFFFF
704
+ rng = random.Random(seed)
705
+
706
+ # Perturb flight windows — shift each bound by ±_RAND_WINDOW_DELTA minutes
707
+ updated_flights = []
708
+ for f in task.flights:
709
+ delta_e = rng.randint(-_RAND_WINDOW_DELTA, _RAND_WINDOW_DELTA)
710
+ delta_l = rng.randint(-_RAND_WINDOW_DELTA, _RAND_WINDOW_DELTA)
711
+ new_earliest = max(0, f.earliest_minute + delta_e)
712
+ new_latest = max(new_earliest + _RAND_MIN_WINDOW, f.latest_minute + delta_l)
713
+ updated_flights.append(
714
+ f.model_copy(update={"earliest_minute": new_earliest, "latest_minute": new_latest})
715
+ )
716
+
717
+ # Perturb runway weather penalties
718
+ updated_runways = []
719
+ for rwy in task.runways:
720
+ delta_w = rng.uniform(-_RAND_WEATHER_DELTA, _RAND_WEATHER_DELTA)
721
+ new_penalty = round(min(1.8, max(1.0, rwy.weather_penalty + delta_w)), 3)
722
+ updated_runways.append(rwy.model_copy(update={"weather_penalty": new_penalty}))
723
+
724
+ # Perturb budgets
725
+ budget_scale = 1.0 + rng.uniform(-_RAND_BUDGET_SCALE, _RAND_BUDGET_SCALE)
726
+ new_delay_budget = max(30, int(task.delay_budget * budget_scale))
727
+ new_fuel_budget = max(50.0, round(task.fuel_budget * budget_scale, 1))
728
+
729
+ return task.model_copy(update={
730
+ "flights": updated_flights,
731
+ "runways": updated_runways,
732
+ "delay_budget": new_delay_budget,
733
+ "fuel_budget": new_fuel_budget,
734
+ })
735
+
736
+ # ── ATFM deadline generator ───────────────────────────────────────────────
737
+
738
+ def _build_atfm_deadlines(self, task: TaskDefinition) -> Dict[str, int]:
739
+ """Build hard departure deadlines combining explicit note-based constraints
740
+ (e.g. ICU transfer-auth windows) and randomly-sampled ATFM network slots.
741
+
742
+ Priority order:
743
+ 1. Flights whose notes contain "TRANSFER AUTH DEADLINE: minute N" use N
744
+ (capped to latest_minute) — these are real hard constraints.
745
+ 2. Urgent flights with no explicit minute but tight windows ("MUST VACATE",
746
+ "URGENT") use latest_minute directly as the deadline.
747
+ 3. Remaining departures: ~1/3 get a random ATFM slot at scheduled + 12 min.
748
+ """
749
+ deadlines: Dict[str, int] = {}
750
+ departures = [f for f in task.flights if f.operation == OperationType.DEPARTURE]
751
+ if not departures:
752
+ return deadlines
753
+
754
+ for flight in departures:
755
+ note = flight.notes or ""
756
+ note_up = note.upper()
757
+
758
+ # 1. Explicit transfer-auth deadline in notes
759
+ m = _TRANSFER_DEADLINE_RE.search(note)
760
+ if m:
761
+ parsed_dl = int(m.group(1))
762
+ deadlines[flight.flight_id] = min(parsed_dl, flight.latest_minute)
763
+ continue
764
+
765
+ # 2. Implicit deadline: "must vacate" / "urgent" with a tight window
766
+ # (latest - earliest ≤ 20 min). Use latest_minute so DMAN sorts
767
+ # these flights ahead of unconstrained ones.
768
+ window = flight.latest_minute - flight.earliest_minute
769
+ if window <= 20 and any(w in note_up for w in ("MUST VACATE", "URGENT")):
770
+ deadlines[flight.flight_id] = flight.latest_minute
771
+
772
+ # 3. Random ATFM slots for flights that don't have explicit deadlines
773
+ unconstrained = [f for f in departures if f.flight_id not in deadlines]
774
+ if unconstrained:
775
+ k = max(1, len(unconstrained) // 3)
776
+ constrained = self._rng.sample(unconstrained, k=min(k, len(unconstrained)))
777
+ for flight in constrained:
778
+ deadline = flight.scheduled_minute + 12
779
+ if deadline <= flight.latest_minute:
780
+ deadlines[flight.flight_id] = deadline
781
+
782
+ return deadlines
multi_agent/generator.py ADDED
@@ -0,0 +1,711 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adversarial self-play scenario generator with ZPD-aware curriculum.
2
+
3
+ Design principles (grounded in literature):
4
+
5
+ Automatic Curriculum Learning
6
+ ALP-GMM / PLR (Portelas 2020, Jiang 2021): track *learning progress* per
7
+ difficulty tier, not raw score. Progress = |Δreward| per tier. Sample
8
+ tiers proportional to recent absolute improvement.
9
+
10
+ VCRL (2025): within a GRPO group the reward variance is a free, parameter-free
11
+ ZPD proxy. High variance ↔ the policy is in the learning frontier (sometimes
12
+ succeeds, sometimes fails). We track per-tier group variance and prefer tiers
13
+ where variance is highest.
14
+
15
+ Competence-based curriculum (Platanios 2019): the dataset builder uses a
16
+ √-schedule to ramp max-allowed tier from 0 → MAX_TIER. The ChallengeGenerator
17
+ provides the *online* adaptive layer on top of that static ramp.
18
+
19
+ ProCuRL / ZPD enforcement (2022, 2025): keep tasks where the policy's pass@G
20
+ is in [0.10, 0.75]. We approximate this via rescue mode: when the global EMA
21
+ drops below RESCUE_THRESHOLD the generator forces tier-0 tasks until it recovers.
22
+
23
+ PAIRED regret (Dennis 2020): generator reward = -(controller_score - baseline).
24
+ Generator is rewarded for staying at the frontier of agent capability, not for
25
+ making tasks arbitrarily hard or unsolvable.
26
+
27
+ Hysteresis (Bengio 2009 competence function): require HYSTERESIS_UP consecutive
28
+ episodes above ESCALATION_THRESHOLD before escalating, but only HYSTERESIS_DOWN
29
+ to deescalate. This prevents noisy single-episode spikes from driving the
30
+ curriculum off a cliff.
31
+
32
+ Self-improving failure mode addressed here:
33
+ The original code set EMA_ALPHA=0.2 (slow to fall) and FLOOR_THRESHOLD=0.30
34
+ (too permissive). A cold model scoring 0.12 has EMA decay:
35
+ 0.2 * 0.12 + 0.8 * 0.50 = 0.424 — never reaches 0.30 even after 5 bad episodes.
36
+ Fix: EMA_ALPHA=0.08 (tracks ~12-episode window) + FLOOR_THRESHOLD=0.42 +
37
+ hard rescue at 0.22.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import random
43
+ import statistics
44
+ from collections import deque
45
+ from typing import Deque, Dict, List, Optional, Tuple
46
+
47
+ try:
48
+ from ..engine import simulate_plan
49
+ from ..models import (
50
+ FlightRecord,
51
+ OperationType,
52
+ PriorityClass,
53
+ SlotAssignment,
54
+ TaskDefinition,
55
+ WakeClass,
56
+ )
57
+ from .models import GeneratorAction, GeneratorMutation, MutationType
58
+ except ImportError:
59
+ from engine import simulate_plan
60
+ from models import (
61
+ FlightRecord,
62
+ OperationType,
63
+ PriorityClass,
64
+ SlotAssignment,
65
+ TaskDefinition,
66
+ WakeClass,
67
+ )
68
+ from multi_agent.models import GeneratorAction, GeneratorMutation, MutationType
69
+
70
+
71
+ # ── Curriculum hyperparameters ────────────────────────────────────────────────
72
+ # These constants are the main levers. Comments explain the reasoning so future
73
+ # tuners understand what each parameter does.
74
+
75
+ ESCALATION_THRESHOLD = 0.65 # EMA must exceed this to escalate tier.
76
+ # 0.65 + HYSTERESIS_UP=5 is strictly more conservative
77
+ # than old 0.65+no-hysteresis: single-episode noise
78
+ # cannot trigger escalation. 0.68 was too close to
79
+ # the EMA convergence point (~0.678) for 0.72 scores.
80
+
81
+ FLOOR_THRESHOLD = 0.42 # EMA below this → start deescalation countdown.
82
+ # Was 0.30 — far too forgiving. At 0.30 a model
83
+ # scoring 0.12 every episode takes 30+ episodes
84
+ # to trigger ease-back (EMA decays slowly).
85
+ # 0.42 triggers after ~4 consecutive low episodes.
86
+
87
+ RESCUE_THRESHOLD = 0.22 # Hard floor: EMA below this → immediate rescue mode.
88
+ # Research basis: GRPO absorbing state (DeepSeek-R1
89
+ # analysis) — if policy never succeeds, GRPO gradient
90
+ # is zero. Rescue injects easy tasks to break the loop.
91
+
92
+ EMA_ALPHA = 0.08 # Was 0.2. τ = 1/alpha ≈ 12 episodes.
93
+ # 0.2 reacts too fast to single-episode noise;
94
+ # 0.08 tracks a 12-episode rolling average, reducing
95
+ # the chance of curriculum thrash from one outlier.
96
+
97
+ RESCUE_BUDGET = 6 # How many tier-0 episodes to inject when EMA collapses.
98
+ # Based on ProCuRL warmup recommendations: ~1 full
99
+ # GRPO batch (N_GENERATIONS=8 × BATCH=4 = 32 samples,
100
+ # ≈ 6 episodes) before re-evaluating capability.
101
+
102
+ HYSTERESIS_UP = 5 # Consecutive episodes above ESCALATION_THRESHOLD
103
+ # required before advancing the tier.
104
+ # Prevents single-episode lucky runs from escalating.
105
+
106
+ HYSTERESIS_DOWN = 2 # Consecutive episodes below FLOOR_THRESHOLD before
107
+ # deescalating. Asymmetric: deescalate quickly
108
+ # (protect learning signal), escalate conservatively.
109
+
110
+ MAX_TIER = 4 # Tier 0=warmup … Tier 4=expert. Mirrors TASK_TIER
111
+ # in tasks.py.
112
+
113
+ MAX_MUTATIONS_PER_EPISODE = 3 # Cap mutations to prevent compounding unsolvability.
114
+ MIN_WINDOW_WIDTH = 8 # Never squeeze a flight window below 8 minutes.
115
+
116
+ # Per-mutation mastery (unchanged from original)
117
+ MASTERY_WINDOW = 10
118
+ MASTERY_THRESHOLD = 0.55 # Score below this on a mutation type → "weak"
119
+
120
+ # LLM priority string aliases
121
+ _PRIORITY_ALIASES: Dict[str, str] = {
122
+ "high": "emergency", "urgent": "emergency", "critical": "emergency",
123
+ "med": "medical", "low": "normal", "standard": "normal",
124
+ "routine": "normal", "conn": "connection",
125
+ }
126
+
127
+
128
+ class ChallengeGenerator:
129
+ """ZPD-aware adversarial curriculum generator for multi-agent ATC training.
130
+
131
+ Maintains:
132
+ - Global EMA of recent controller scores (slow α=0.08)
133
+ - Per-tier score windows for learning-progress estimation (ALP-GMM style)
134
+ - Per-tier within-group reward variance windows (VCRL ZPD proxy)
135
+ - Rescue mode that forces tier-0 episodes when EMA collapses
136
+ - Hysteresis counters to prevent curriculum thrash
137
+
138
+ Public API:
139
+ update(score, group_rewards) — call after each episode (real or simulated)
140
+ recommended_tier() — tier (0-4) for next base task selection
141
+ mutate(task) — apply curriculum-appropriate mutations
142
+ compute_reward(score, solvable) — PAIRED regret signal for generator training
143
+ """
144
+
145
+ def __init__(self, seed: int = 0) -> None:
146
+ self._rng = random.Random(seed)
147
+
148
+ # ── Global EMA and episode history ────────────────────────────────────
149
+ self._ema_score: float = 0.50 # start at mid-difficulty assumption
150
+ self._score_history: Deque[float] = deque(maxlen=20)
151
+
152
+ # ── Tier state ────────────────────────────────────────────────────────
153
+ self._tier: int = 0 # current recommended base-task tier (0-4)
154
+ self._difficulty_level: int = 1 # mutation intensity (1-6); derived from tier
155
+
156
+ # Per-tier score windows for ALP-style learning progress estimation
157
+ self._tier_scores: Dict[int, Deque[float]] = {
158
+ i: deque(maxlen=20) for i in range(MAX_TIER + 1)
159
+ }
160
+ # Per-tier GRPO-group reward variance (VCRL ZPD proxy)
161
+ self._tier_variance: Dict[int, Deque[float]] = {
162
+ i: deque(maxlen=10) for i in range(MAX_TIER + 1)
163
+ }
164
+
165
+ # ── Hysteresis counters ───────────────────────────────────────────────
166
+ self._consecutive_above: int = 0 # episodes above ESCALATION_THRESHOLD
167
+ self._consecutive_below: int = 0 # episodes below FLOOR_THRESHOLD
168
+
169
+ # ── Rescue mode ───────────────────────────────────────────────────────
170
+ self._rescue_mode: bool = False
171
+ self._rescue_remaining: int = 0
172
+
173
+ # ── Mutation mastery (per-task, per-mutation) ─────────────────────────
174
+ self._task_mastery: Dict[str, Deque[float]] = {}
175
+ self._mutation_mastery: Dict[str, Deque[float]] = {}
176
+ self._mutation_history: List[Dict] = []
177
+
178
+ # ── PAIRED baseline ───────────────────────────────────────────────────
179
+ self._last_heuristic_score: float = 0.5
180
+ self._last_mutated_task: Optional[TaskDefinition] = None
181
+
182
+ # ── Public API ────────────────────────────────────────────────────────────
183
+
184
+ def update(
185
+ self,
186
+ controller_score: float,
187
+ group_rewards: Optional[List[float]] = None,
188
+ ) -> None:
189
+ """Update curriculum state after one episode.
190
+
191
+ Args:
192
+ controller_score: composite score from the episode (0-1).
193
+ group_rewards: optional list of individual GRPO group rewards.
194
+ When provided, the within-group variance is used
195
+ as a VCRL ZPD signal for the current tier.
196
+ """
197
+ self._score_history.append(controller_score)
198
+ self._ema_score = (
199
+ EMA_ALPHA * controller_score + (1.0 - EMA_ALPHA) * self._ema_score
200
+ )
201
+ self._tier_scores[self._tier].append(controller_score)
202
+
203
+ # VCRL: track within-group reward variance as a ZPD proxy
204
+ if group_rewards and len(group_rewards) >= 2:
205
+ try:
206
+ var = statistics.variance(group_rewards)
207
+ except statistics.StatisticsError:
208
+ var = 0.0
209
+ self._tier_variance[self._tier].append(var)
210
+
211
+ # ── Rescue mode check (hard floor) ────────────────────────────────────
212
+ if self._ema_score < RESCUE_THRESHOLD and not self._rescue_mode:
213
+ self._rescue_mode = True
214
+ self._rescue_remaining = RESCUE_BUDGET
215
+ # Reset hysteresis so rescue can end cleanly
216
+ self._consecutive_above = 0
217
+ self._consecutive_below = 0
218
+
219
+ if self._rescue_mode:
220
+ self._rescue_remaining -= 1
221
+ if self._rescue_remaining <= 0:
222
+ self._rescue_mode = False
223
+ # Drop tier to a safe level so the exit doesn't immediately
224
+ # re-trigger rescue.
225
+ self._tier = max(0, min(1, self._tier))
226
+ self._difficulty_level = max(1, self._tier)
227
+ # Skip normal tier updates during rescue
228
+ return
229
+
230
+ # ── Hysteresis: escalation ────────────────────────────────────────────
231
+ if self._ema_score > ESCALATION_THRESHOLD:
232
+ self._consecutive_above += 1
233
+ self._consecutive_below = 0
234
+ elif self._ema_score < FLOOR_THRESHOLD:
235
+ self._consecutive_below += 1
236
+ self._consecutive_above = 0
237
+ else:
238
+ # In the ZPD zone — decay both counters slowly (model is learning)
239
+ self._consecutive_above = max(0, self._consecutive_above - 1)
240
+ self._consecutive_below = max(0, self._consecutive_below - 1)
241
+
242
+ # ── Tier transitions ──────────────────────────────────────────────────
243
+ if self._consecutive_above >= HYSTERESIS_UP and self._tier < MAX_TIER:
244
+ self._tier += 1
245
+ self._consecutive_above = 0
246
+ elif self._consecutive_below >= HYSTERESIS_DOWN and self._tier > 0:
247
+ self._tier -= 1
248
+ self._consecutive_below = 0
249
+
250
+ # ── Mutation difficulty level (1-6) derived from tier ─────────────────
251
+ # Tier 0 → level 0 (no mutations)
252
+ # Tier 1 → level 1-2
253
+ # Tier 2 → level 2-3
254
+ # Tier 3 → level 3-4
255
+ # Tier 4 → level 5-6
256
+ # Extra boost when EMA is above floor (performing well within tier)
257
+ tier_to_level = {0: 0, 1: 1, 2: 3, 3: 4, 4: 6}
258
+ base_level = tier_to_level.get(self._tier, 1)
259
+ # Add 1 when clearly performing well but not yet escalating
260
+ boost = 1 if (self._ema_score > FLOOR_THRESHOLD + 0.15 and base_level > 0) else 0
261
+ self._difficulty_level = min(6, max(0, base_level + boost))
262
+
263
+ def record(
264
+ self,
265
+ task_id: str,
266
+ mutations_used: Optional[List[str]],
267
+ composite_score: float,
268
+ ) -> None:
269
+ """Record per-task and per-mutation mastery after an episode.
270
+
271
+ Called by the training loop alongside update().
272
+ """
273
+ if task_id not in self._task_mastery:
274
+ self._task_mastery[task_id] = deque(maxlen=MASTERY_WINDOW)
275
+ self._task_mastery[task_id].append(composite_score)
276
+
277
+ for mtype in (mutations_used or []):
278
+ if mtype not in self._mutation_mastery:
279
+ self._mutation_mastery[mtype] = deque(maxlen=MASTERY_WINDOW)
280
+ self._mutation_mastery[mtype].append(composite_score)
281
+
282
+ def get_weak_mutations(self, threshold: float = MASTERY_THRESHOLD) -> List[str]:
283
+ """Return mutation types where agents still score below threshold."""
284
+ return [
285
+ mtype
286
+ for mtype, scores in self._mutation_mastery.items()
287
+ if len(scores) >= 3 and (sum(scores) / len(scores)) < threshold
288
+ ]
289
+
290
+ def recommended_tier(self) -> int:
291
+ """Tier (0-4) recommended for selecting the next base task.
292
+
293
+ Returns 0 during rescue mode (force easy). Otherwise returns the
294
+ current tier, clamped to [0, MAX_TIER].
295
+ """
296
+ if self._rescue_mode:
297
+ return 0
298
+ return max(0, min(MAX_TIER, self._tier))
299
+
300
+ def is_in_rescue_mode(self) -> bool:
301
+ """True when EMA collapsed below RESCUE_THRESHOLD and easy tasks are forced."""
302
+ return self._rescue_mode
303
+
304
+ def mastery_report(self) -> Dict:
305
+ """Per-task / per-mutation success rates for logging."""
306
+ task_means = {
307
+ tid: round(sum(v) / len(v), 3)
308
+ for tid, v in self._task_mastery.items() if v
309
+ }
310
+ mut_means = {
311
+ mtype: round(sum(v) / len(v), 3)
312
+ for mtype, v in self._mutation_mastery.items() if v
313
+ }
314
+ # VCRL ZPD signal: mean variance per tier (high = in learning frontier)
315
+ tier_var_means = {
316
+ tier: round(sum(v) / len(v), 4) if v else 0.0
317
+ for tier, v in self._tier_variance.items()
318
+ }
319
+ return {
320
+ "task_mastery": task_means,
321
+ "mutation_mastery": mut_means,
322
+ "weak_mutations": self.get_weak_mutations(),
323
+ "tier": self._tier,
324
+ "difficulty_level": self._difficulty_level,
325
+ "ema_score": self.ema_score,
326
+ "rescue_mode": self._rescue_mode,
327
+ "rescue_remaining": self._rescue_remaining,
328
+ "tier_variance_zpd": tier_var_means,
329
+ }
330
+
331
+ def curriculum_summary(self) -> str:
332
+ """One-line human-readable curriculum state for training logs (ASCII-safe)."""
333
+ mode = "RESCUE" if self._rescue_mode else f"T{self._tier}/L{self._difficulty_level}"
334
+ above = f"up={self._consecutive_above}/{HYSTERESIS_UP}"
335
+ below = f"dn={self._consecutive_below}/{HYSTERESIS_DOWN}"
336
+ return (
337
+ f"[Curriculum] EMA={self._ema_score:.3f} {mode} "
338
+ f"hyst:{above},{below}"
339
+ )
340
+
341
+ # ── Mutation API ──────────────────────────────────────────────────────────
342
+
343
+ def mutate(
344
+ self,
345
+ base_task: TaskDefinition,
346
+ generator_action: Optional[GeneratorAction] = None,
347
+ ) -> Tuple[TaskDefinition, bool]:
348
+ """Apply difficulty-appropriate mutations to base_task.
349
+
350
+ If generator_action is provided (LLM-driven), apply those mutations.
351
+ Otherwise use rule-based mutations matching current difficulty_level.
352
+
353
+ At tier/level 0 no mutations are applied — base task is returned as-is.
354
+ This ensures warmup tasks are always solvable in their canonical form.
355
+
356
+ Returns (mutated_task, is_solvable).
357
+ """
358
+ task = self._deep_copy_task(base_task)
359
+
360
+ if generator_action and generator_action.mutations:
361
+ mutations = generator_action.mutations[:MAX_MUTATIONS_PER_EPISODE]
362
+ else:
363
+ mutations = self._sample_mutations(task)
364
+
365
+ for mut in mutations:
366
+ task = self._apply_mutation(task, mut)
367
+ self._mutation_history.append({
368
+ "type": mut.mutation_type.value,
369
+ "level": self._difficulty_level,
370
+ "tier": self._tier,
371
+ "ema": round(self._ema_score, 3),
372
+ })
373
+
374
+ solvable = self._check_solvability(task)
375
+
376
+ self._last_mutated_task = task
377
+ self._last_heuristic_score = (
378
+ self._score_scheduled_baseline(task) if solvable else 0.0
379
+ )
380
+ return task, solvable
381
+
382
+ def compute_reward(self, controller_score: float, is_solvable: bool) -> float:
383
+ """PAIRED regret-based generator reward with solvability guard.
384
+
385
+ Unsolvable → -1.0 penalty (generator must create HARD but not IMPOSSIBLE).
386
+ Otherwise: reward = -(controller_score - baseline_score)
387
+ • Positive when agents fall behind baseline (generator winning)
388
+ • Negative when agents beat baseline (task too easy for generator)
389
+ """
390
+ if not is_solvable:
391
+ return -1.0
392
+
393
+ if self._last_mutated_task is not None:
394
+ regret = controller_score - self._last_heuristic_score
395
+ return round(max(-1.0, min(1.0, -regret)), 4)
396
+
397
+ # Fallback if called without prior mutate() call (e.g. unit tests)
398
+ return round(max(-1.0, min(1.0, 1.0 - controller_score)), 4)
399
+
400
+ @property
401
+ def difficulty_level(self) -> int:
402
+ return self._difficulty_level
403
+
404
+ @property
405
+ def ema_score(self) -> float:
406
+ return round(self._ema_score, 3)
407
+
408
+ @property
409
+ def current_tier(self) -> int:
410
+ return self._tier
411
+
412
+ # ── Mutation sampling ─────────────────────────────────────────────────────
413
+
414
+ def _sample_mutations(self, task: TaskDefinition) -> List[GeneratorMutation]:
415
+ """Rule-based mutation selection based on current difficulty_level.
416
+
417
+ Level 0 → no mutations (warmup tier)
418
+ Level 1 → TIGHTEN_WINDOW (mild squeeze)
419
+ Level 2 → + ADD_ATFM_DEADLINE
420
+ Level 3 → + INCREASE_WEATHER_PENALTY
421
+ Level 4 → + INJECT_EMERGENCY
422
+ Level 5 → + ADD_CONFLICTING_FLIGHT
423
+ Level 6 → + CLOSE_RUNWAY_WINDOW
424
+
425
+ Weak mutations (agents consistently score below MASTERY_THRESHOLD on them)
426
+ are boosted 3× in the sampling pool — curriculum focuses on gaps.
427
+ """
428
+ level = self._difficulty_level
429
+
430
+ # Tier/level 0: no mutations at all — base task is the challenge
431
+ if level <= 0:
432
+ return []
433
+
434
+ n_mutations = min(MAX_MUTATIONS_PER_EPISODE, max(1, level // 2))
435
+
436
+ pool: List[MutationType] = []
437
+ if level >= 1:
438
+ pool += [MutationType.TIGHTEN_WINDOW] * 3
439
+ if level >= 2:
440
+ pool += [MutationType.ADD_ATFM_DEADLINE] * 2
441
+ if level >= 3:
442
+ pool += [MutationType.INCREASE_WEATHER_PENALTY] * 2
443
+ if level >= 4:
444
+ pool += [MutationType.INJECT_EMERGENCY] * 2
445
+ if level >= 5:
446
+ pool += [MutationType.ADD_CONFLICTING_FLIGHT] * 2
447
+ if level >= 6:
448
+ pool += [MutationType.CLOSE_RUNWAY_WINDOW] * 1
449
+
450
+ # Boost under-mastered mutation types (3× weight)
451
+ weak = set(self.get_weak_mutations())
452
+ pool += [mt for mt in pool if mt.value in weak]
453
+
454
+ selected = self._rng.choices(pool, k=n_mutations)
455
+
456
+ departures = [f for f in task.flights if f.operation == OperationType.DEPARTURE]
457
+ arrivals = [f for f in task.flights if f.operation == OperationType.ARRIVAL]
458
+ mutations: List[GeneratorMutation] = []
459
+
460
+ for mtype in selected:
461
+ if mtype == MutationType.TIGHTEN_WINDOW:
462
+ target = self._rng.choice(task.flights)
463
+ # Squeeze scales with level but stays gentle at low tiers
464
+ max_squeeze = max(2, 2 + level)
465
+ squeeze = self._rng.randint(2, max_squeeze)
466
+ mutations.append(GeneratorMutation(
467
+ mutation_type=mtype,
468
+ target_flight_id=target.flight_id,
469
+ params={"squeeze_minutes": squeeze},
470
+ rationale=f"Tighten {target.flight_id} window by {squeeze} min each side",
471
+ ))
472
+
473
+ elif mtype == MutationType.ADD_ATFM_DEADLINE and departures:
474
+ target = self._rng.choice(departures)
475
+ buffer = self._rng.randint(5, 10)
476
+ mutations.append(GeneratorMutation(
477
+ mutation_type=mtype,
478
+ target_flight_id=target.flight_id,
479
+ params={"deadline_offset": buffer},
480
+ rationale=f"ATFM slot: {target.flight_id} must depart by scheduled+{buffer}",
481
+ ))
482
+
483
+ elif mtype == MutationType.INCREASE_WEATHER_PENALTY:
484
+ target_rwy = self._rng.choice(task.runways)
485
+ delta = round(self._rng.uniform(0.1, 0.25), 2)
486
+ mutations.append(GeneratorMutation(
487
+ mutation_type=mtype,
488
+ target_runway_id=target_rwy.runway_id,
489
+ params={"penalty_delta": delta},
490
+ rationale=f"Weather degrades {target_rwy.runway_id} capacity by {delta}×",
491
+ ))
492
+
493
+ elif mtype == MutationType.INJECT_EMERGENCY and arrivals:
494
+ base = self._rng.choice(arrivals)
495
+ window_center = self._rng.randint(
496
+ base.earliest_minute,
497
+ min(base.latest_minute, base.earliest_minute + 20),
498
+ )
499
+ mutations.append(GeneratorMutation(
500
+ mutation_type=mtype,
501
+ params={
502
+ "flight_id": f"EMG{self._rng.randint(100, 999)}",
503
+ "priority": "emergency",
504
+ "minute": window_center,
505
+ "runway": self._rng.choice(task.runways).runway_id,
506
+ },
507
+ rationale="Inject emergency diversion at peak arrival window",
508
+ ))
509
+
510
+ elif mtype == MutationType.ADD_CONFLICTING_FLIGHT:
511
+ if arrivals:
512
+ anchor = self._rng.choice(arrivals)
513
+ mutations.append(GeneratorMutation(
514
+ mutation_type=mtype,
515
+ params={
516
+ "flight_id": f"WKT{self._rng.randint(100, 999)}",
517
+ "wake_class": "H",
518
+ "operation": "arrival",
519
+ "minute": max(0, anchor.earliest_minute - 4),
520
+ "runway": self._rng.choice(anchor.allowed_runways),
521
+ },
522
+ rationale="Heavy arrival 4 min before window — forces 6-min wake gap",
523
+ ))
524
+
525
+ elif mtype == MutationType.CLOSE_RUNWAY_WINDOW:
526
+ target_rwy = self._rng.choice(task.runways)
527
+ duration = self._rng.randint(10, 20)
528
+ mutations.append(GeneratorMutation(
529
+ mutation_type=mtype,
530
+ target_runway_id=target_rwy.runway_id,
531
+ params={"close_duration": duration},
532
+ rationale=f"Runway {target_rwy.runway_id} closed for {duration} min",
533
+ ))
534
+
535
+ return mutations
536
+
537
+ # ── Mutation application ──────────────────────────────────���───────────────
538
+
539
+ def _apply_mutation(
540
+ self, task: TaskDefinition, mut: GeneratorMutation
541
+ ) -> TaskDefinition:
542
+ dispatch = {
543
+ MutationType.TIGHTEN_WINDOW: self._tighten_window,
544
+ MutationType.INCREASE_WEATHER_PENALTY: self._increase_weather,
545
+ MutationType.INJECT_EMERGENCY: self._inject_emergency,
546
+ MutationType.ADD_CONFLICTING_FLIGHT: self._add_conflicting_flight,
547
+ MutationType.CLOSE_RUNWAY_WINDOW: self._close_runway_window,
548
+ # ADD_ATFM_DEADLINE is handled at environment level via the atfm_deadlines
549
+ # dict, not by modifying TaskDefinition flights.
550
+ MutationType.ADD_ATFM_DEADLINE: lambda t, m: t,
551
+ }
552
+ fn = dispatch.get(mut.mutation_type)
553
+ return fn(task, mut) if fn else task
554
+
555
+ def _tighten_window(
556
+ self, task: TaskDefinition, mut: GeneratorMutation
557
+ ) -> TaskDefinition:
558
+ squeeze = mut.params.get("squeeze_minutes", 3)
559
+ updated = []
560
+ for f in task.flights:
561
+ if f.flight_id == mut.target_flight_id:
562
+ new_earliest = f.earliest_minute + squeeze
563
+ new_latest = f.latest_minute - squeeze
564
+ if new_latest - new_earliest >= MIN_WINDOW_WIDTH:
565
+ f = f.model_copy(update={
566
+ "earliest_minute": new_earliest,
567
+ "latest_minute": new_latest,
568
+ })
569
+ updated.append(f)
570
+ return task.model_copy(update={"flights": updated})
571
+
572
+ def _increase_weather(
573
+ self, task: TaskDefinition, mut: GeneratorMutation
574
+ ) -> TaskDefinition:
575
+ delta = mut.params.get("penalty_delta", 0.15)
576
+ updated = []
577
+ for rwy in task.runways:
578
+ if rwy.runway_id == mut.target_runway_id:
579
+ rwy = rwy.model_copy(update={
580
+ "weather_penalty": round(min(2.0, rwy.weather_penalty + delta), 2)
581
+ })
582
+ updated.append(rwy)
583
+ return task.model_copy(update={"runways": updated})
584
+
585
+ def _inject_emergency(
586
+ self, task: TaskDefinition, mut: GeneratorMutation
587
+ ) -> TaskDefinition:
588
+ p = mut.params
589
+ fid = p.get("flight_id", "EMG001")
590
+ minute = int(p.get("minute", 20))
591
+ priority_str = str(p.get("priority", "emergency")).lower().strip()
592
+ priority_str = _PRIORITY_ALIASES.get(priority_str, priority_str)
593
+ try:
594
+ priority = PriorityClass(priority_str)
595
+ except ValueError:
596
+ priority = PriorityClass.EMERGENCY
597
+ runway_id = p.get("runway", task.runways[0].runway_id)
598
+
599
+ new_flight = FlightRecord(
600
+ flight_id=fid,
601
+ airline="GOV",
602
+ operation=OperationType.ARRIVAL,
603
+ wake_class=WakeClass.MEDIUM,
604
+ scheduled_minute=minute,
605
+ earliest_minute=max(0, minute - 2),
606
+ latest_minute=minute + 6,
607
+ allowed_runways=[runway_id],
608
+ passengers=8,
609
+ fuel_burn_per_minute=7.5,
610
+ priority=priority,
611
+ notes=f"Generator-injected {priority.value} diversion",
612
+ )
613
+ return task.model_copy(update={"flights": list(task.flights) + [new_flight]})
614
+
615
+ def _add_conflicting_flight(
616
+ self, task: TaskDefinition, mut: GeneratorMutation
617
+ ) -> TaskDefinition:
618
+ p = mut.params
619
+ fid = p.get("flight_id", "WKT001")
620
+ minute = int(p.get("minute", 10))
621
+ try:
622
+ wake = WakeClass(str(p.get("wake_class", "H")).upper())
623
+ except ValueError:
624
+ wake = WakeClass.HEAVY
625
+ try:
626
+ operation = OperationType(str(p.get("operation", "arrival")).lower())
627
+ except ValueError:
628
+ operation = OperationType.ARRIVAL
629
+ runway_id = p.get("runway", task.runways[0].runway_id)
630
+
631
+ new_flight = FlightRecord(
632
+ flight_id=fid,
633
+ airline="FRT",
634
+ operation=operation,
635
+ wake_class=wake,
636
+ scheduled_minute=minute,
637
+ earliest_minute=max(0, minute - 1),
638
+ latest_minute=minute + 5,
639
+ allowed_runways=[runway_id],
640
+ passengers=1,
641
+ fuel_burn_per_minute=6.0,
642
+ priority=PriorityClass.NORMAL,
643
+ notes="Generator-injected wake-turbulence trap (Heavy)",
644
+ )
645
+ return task.model_copy(update={"flights": list(task.flights) + [new_flight]})
646
+
647
+ def _close_runway_window(
648
+ self, task: TaskDefinition, mut: GeneratorMutation
649
+ ) -> TaskDefinition:
650
+ """Simulate runway closure via an extreme weather-penalty increase."""
651
+ duration = mut.params.get("close_duration", 15)
652
+ delta = min(1.9, 0.05 * duration)
653
+ updated = []
654
+ for rwy in task.runways:
655
+ if rwy.runway_id == mut.target_runway_id:
656
+ rwy = rwy.model_copy(update={
657
+ "weather_penalty": min(2.0, rwy.weather_penalty + delta),
658
+ "notes": rwy.notes + f" [CLOSED {duration}min — generator]",
659
+ })
660
+ updated.append(rwy)
661
+ return task.model_copy(update={"runways": updated})
662
+
663
+ # ── Solvability check ─────────────────────────────────────────────────────
664
+
665
+ def _check_solvability(self, task: TaskDefinition) -> bool:
666
+ """Heuristic: verify at least one valid assignment exists per flight."""
667
+ from collections import defaultdict
668
+
669
+ for f in task.flights:
670
+ if f.latest_minute - f.earliest_minute < 2:
671
+ return False
672
+ if not f.allowed_runways:
673
+ return False
674
+
675
+ runway_demand: Dict[str, int] = defaultdict(int)
676
+ for f in task.flights:
677
+ for rwy_id in f.allowed_runways:
678
+ runway_demand[rwy_id] += 1
679
+
680
+ for rwy in task.runways:
681
+ demand = runway_demand.get(rwy.runway_id, 0)
682
+ effective_cap = rwy.hourly_capacity / rwy.weather_penalty
683
+ max_ops = effective_cap * (task.planning_horizon_minutes / 60.0)
684
+ if demand > max_ops * 1.5:
685
+ return False
686
+
687
+ return True
688
+
689
+ def _score_scheduled_baseline(self, task: TaskDefinition) -> float:
690
+ """PAIRED baseline: assign every flight at scheduled_minute (clamped to window)
691
+ on its first allowed runway. This is the 'do-nothing' heuristic score.
692
+ """
693
+ slots = []
694
+ for f in task.flights:
695
+ if not f.allowed_runways:
696
+ continue
697
+ minute = max(f.earliest_minute, min(f.latest_minute, f.scheduled_minute))
698
+ slots.append(SlotAssignment(
699
+ flight_id=f.flight_id,
700
+ runway=f.allowed_runways[0],
701
+ assigned_minute=minute,
702
+ hold_minutes=0,
703
+ ))
704
+ try:
705
+ outcome = simulate_plan(task, slots)
706
+ return outcome.normalized_score
707
+ except Exception:
708
+ return 0.5
709
+
710
+ def _deep_copy_task(self, task: TaskDefinition) -> TaskDefinition:
711
+ return TaskDefinition.model_validate(task.model_dump())
multi_agent/inference.py ADDED
@@ -0,0 +1,1243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Multi-agent ATC inference runner.
2
+
3
+ Runs AMAN + DMAN agents against the ATC environment, either with:
4
+ - heuristic-baseline: deterministic planner (no LLM required)
5
+ - any HF/OpenAI-compatible model: LLM-driven AMAN and DMAN agents
6
+
7
+ Output format mirrors inference.py structured logs:
8
+ [START] task=... env=... model=...
9
+ [STEP] step=... role=AMAN|DMAN reward=... conflicts=... done=...
10
+ (conflicts = wake/separation issue count, not raw diagnostic list length)
11
+ [NEG] round=... conflicts_resolved=... messages=...
12
+ [END] task=... success=... composite=... aman=... dman=... coord=...
13
+
14
+ Usage:
15
+ python multi_agent/inference.py # heuristic demo
16
+ python multi_agent/inference.py --model Qwen/Qwen2.5-7B # LLM agents
17
+ python multi_agent/inference.py --task bengaluru_irrops_hard --episodes 3
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import os
25
+ import sys
26
+ import time
27
+ from pathlib import Path
28
+ from typing import Any, Dict, List, Optional, Tuple
29
+
30
+ ROOT = Path(__file__).resolve().parent.parent
31
+ if str(ROOT) not in sys.path:
32
+ sys.path.insert(0, str(ROOT))
33
+
34
+ from engine import simulate_plan
35
+ from graders import grade_multi_agent
36
+ from models import (
37
+ FlightRecord,
38
+ OperationType,
39
+ PriorityClass,
40
+ SlotAssignment,
41
+ TaskDefinition,
42
+ )
43
+ from planner import build_heuristic_plan, build_refined_plan, _flight_sort_key
44
+ from tasks import task_catalog, ordered_tasks
45
+ from multi_agent.environment import (
46
+ DOMAIN_MAX_NEGOTIATE_ROUNDS,
47
+ MAX_NEGOTIATE_ROUNDS,
48
+ MultiAgentATCEnvironment,
49
+ count_separation_issues,
50
+ )
51
+ from multi_agent.generator import ChallengeGenerator
52
+ from multi_agent.models import (
53
+ AMANAction,
54
+ AgentRole,
55
+ DMANAction,
56
+ NegotiationMessage,
57
+ MessageType,
58
+ MultiAgentObservation,
59
+ SupervisorProfileName,
60
+ SUPERVISOR_PROFILES,
61
+ )
62
+ from multi_agent.supervisor import SupervisorAgent
63
+ from multi_agent.visual_events import (
64
+ VisualSink,
65
+ emit,
66
+ serialize_action_layout,
67
+ serialize_task_snapshot,
68
+ terminal_event,
69
+ )
70
+ from training.dataset import (
71
+ AMAN_SYSTEM,
72
+ DMAN_SYSTEM,
73
+ parse_aman_action,
74
+ parse_dman_action,
75
+ )
76
+
77
+
78
+ # ── Config ────────────────────────────────────────────────────────────────────
79
+
80
+ API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1").rstrip("/")
81
+ MODEL_NAME = os.getenv("MODEL_NAME", "heuristic-baseline")
82
+ HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
83
+ BENCHMARK = "atc_multiagent_openenv"
84
+ MAX_TOKENS = 1024
85
+ TEMPERATURE = 0.3
86
+ SUCCESS_THRESHOLD = 0.60
87
+
88
+ # N appended to AMAN/DMAN system prompts during ADAPT → ATC runs (bid + 1st negotiate LLM pass).
89
+ # Focuses the model on clearing separation conflicts the heuristic pipeline often leaves on
90
+ # tight remapped windows (e.g. ICU/ADAPT), without naming the source domain.
91
+ _DOMAIN_TRANSFER_LLM_HINT = (
92
+ "STRUCTURAL-TRANSFER SCHEDULE: windows may be tight after cross-domain remapping. "
93
+ "In NEGOTIATE, use the CONFLICT LOG: shift arrival/departure minutes on shared runways to "
94
+ "satisfy minimum separation, staggering arrivals vs departures when the log says spacing "
95
+ "or wake conflicts. Prefer the smallest time moves that clear diagnostics; do not miss "
96
+ "ATFM/departure network deadlines (DMAN)."
97
+ )
98
+
99
+
100
+ # ── Structured logging ────────────────────────────────────────────────────────
101
+
102
+ def _p(msg: str) -> None:
103
+ try:
104
+ print(msg, flush=True)
105
+ except (BrokenPipeError, OSError):
106
+ pass
107
+
108
+
109
+ def log_start(task: str, model: str) -> None:
110
+ _p(f"[START] task={task} env={BENCHMARK} model={model}")
111
+
112
+
113
+ def log_step(step: int, role: str, reward: float, conflicts: int, done: bool) -> None:
114
+ _p(f"[STEP] step={step} role={role} reward={reward:.3f} conflicts={conflicts} done={str(done).lower()}")
115
+
116
+
117
+ def log_neg(rnd: int, resolved: int, messages: int) -> None:
118
+ _p(f"[NEG] round={rnd} conflicts_resolved={resolved} messages={messages}")
119
+
120
+
121
+ def log_end(
122
+ task: str, success: bool, composite: float,
123
+ aman: float, dman: float, coord: float, gen_diff: int,
124
+ ) -> None:
125
+ _p(
126
+ f"[END] task={task} success={str(success).lower()} "
127
+ f"composite={composite:.3f} aman={aman:.3f} dman={dman:.3f} "
128
+ f"coord={coord:.3f} gen_difficulty={gen_diff}"
129
+ )
130
+
131
+
132
+ # ── Cross-role spacing (ICU / high-capacity resources) ─────────────────────────
133
+ #
134
+ # simulate_plan() enforces max(capacity_floor, wake) between *any* consecutive ops on a
135
+ # runway. ICU beds used hourly_capacity=4 → 15 min floor, while heuristics historically
136
+ # avoided peer claims by only ~3 min — guaranteed cross-lane conflicts and ruined scores.
137
+
138
+
139
+ def _resolve_peer_clearance(
140
+ t: int,
141
+ peer_minutes: List[int],
142
+ cap_gap: int,
143
+ my_wake: str,
144
+ latest_limit: int,
145
+ repair: int,
146
+ peer_wake_default: str = "M",
147
+ ) -> Optional[int]:
148
+ """Push minute ``t`` forward until it clears peer slot minutes on the same runway.
149
+
150
+ Uses runway capacity floor and wake separation (peer wake defaulted to Medium).
151
+ Returns None if no feasible minute ≤ ``latest_limit``.
152
+ """
153
+ from constants import SEPARATION_BY_WAKE
154
+
155
+ after_peer = max(
156
+ cap_gap,
157
+ SEPARATION_BY_WAKE.get((peer_wake_default, my_wake), 4),
158
+ ) + max(0, repair)
159
+ before_peer = max(
160
+ cap_gap,
161
+ SEPARATION_BY_WAKE.get((my_wake, peer_wake_default), 4),
162
+ ) + max(0, repair)
163
+ e = t
164
+ peers = sorted({int(x) for x in peer_minutes})
165
+ for _ in range(600):
166
+ moved = False
167
+ for pm in peers:
168
+ if e >= pm and e < pm + after_peer:
169
+ e = pm + after_peer
170
+ moved = True
171
+ elif e < pm and (pm - e) < before_peer:
172
+ e = pm + after_peer
173
+ moved = True
174
+ if not moved:
175
+ break
176
+ if e > latest_limit:
177
+ return None
178
+ return e
179
+
180
+
181
+ def _dman_obs_with_aman_messages(
182
+ dman_obs: MultiAgentObservation,
183
+ aman_action: AMANAction,
184
+ ) -> MultiAgentObservation:
185
+ """Update DMAN's inbox with AMAN's CURRENT slot claims, replacing any stale ones.
186
+
187
+ Old deduplicate-by-(runway,minute,flight) logic accumulated superseded AMAN
188
+ messages: if AMAN moved flight X from BED_A@0 to BED_A@5, DMAN would see both
189
+ claims and over-block BED_A. Instead, drop any prior AMAN message whose
190
+ flight_id appears in the new outgoing set, then append the fresh claims.
191
+ """
192
+ if not aman_action.outgoing_messages:
193
+ return dman_obs
194
+ refreshed_fids = {m.flight_id for m in aman_action.outgoing_messages}
195
+ kept = [
196
+ m for m in dman_obs.incoming_messages
197
+ if not (m.from_role == AgentRole.AMAN and m.flight_id in refreshed_fids)
198
+ ]
199
+ return dman_obs.model_copy(
200
+ update={"incoming_messages": kept + list(aman_action.outgoing_messages)},
201
+ )
202
+
203
+
204
+ # ── Heuristic AMAN planner ────────────────────────────────────────────────────
205
+
206
+ def _build_aman_heuristic(
207
+ obs: MultiAgentObservation,
208
+ separation_repair: int = 0,
209
+ ) -> AMANAction:
210
+ """Deterministic arrival sequencer — priority-sorted, wake-turbulence aware.
211
+
212
+ ``separation_repair`` (0 = off): in later negotiate passes, add N minutes to
213
+ required wake/ spacing gaps and widen DMAN emergency buffers to clear residual
214
+ cross-runway conflicts (stronger for larger N; typical 1–3).
215
+ """
216
+ repair = max(0, int(separation_repair))
217
+ arrivals = sorted(obs.my_flights, key=_flight_sort_key)
218
+ runway_last: Dict[str, Tuple[int, str]] = {
219
+ r.runway_id: (0, "M") for r in obs.all_runways
220
+ }
221
+ from constants import SEPARATION_BY_WAKE
222
+ slots: List[SlotAssignment] = []
223
+ emergency_yields: List[str] = []
224
+
225
+ for flight in arrivals:
226
+ best_rwy, best_min = None, None
227
+ best_gap = -1
228
+
229
+ for rwy_id in flight.allowed_runways:
230
+ rwy = next((r for r in obs.all_runways if r.runway_id == rwy_id), None)
231
+ if not rwy:
232
+ continue
233
+ if OperationType.ARRIVAL not in rwy.allowed_operations:
234
+ continue
235
+
236
+ last_min, last_wake = runway_last.get(rwy_id, (0, "M"))
237
+ from engine import _capacity_spacing
238
+ cap_gap = _capacity_spacing(rwy)
239
+ wake_gap = SEPARATION_BY_WAKE.get(
240
+ (last_wake, flight.wake_class.value), 3
241
+ )
242
+ min_gap = max(cap_gap, wake_gap) + repair
243
+ earliest_cap = max(flight.earliest_minute, last_min + min_gap)
244
+
245
+ if earliest_cap > flight.latest_minute:
246
+ continue
247
+
248
+ # Prefer to schedule at the flight's scheduled_minute rather than the
249
+ # earliest capacity gap. Busy ATC runways naturally put earliest_cap
250
+ # near scheduled; idle ICU beds start at T+5 and would otherwise assign
251
+ # all flights minutes before their time, destroying delay_efficiency.
252
+ target = max(earliest_cap, flight.scheduled_minute)
253
+ if target > flight.latest_minute:
254
+ target = earliest_cap # scheduled falls outside window; use earliest
255
+
256
+ dman_peer = [
257
+ m.requested_minute
258
+ for m in obs.incoming_messages
259
+ if m.from_role == AgentRole.DMAN and m.runway_id == rwy_id
260
+ ]
261
+
262
+ # Peer-clear from target; fall back to earliest_cap if target can't clear
263
+ before_peer = target
264
+ slot = _resolve_peer_clearance(
265
+ target, dman_peer, cap_gap, flight.wake_class.value,
266
+ flight.latest_minute, repair,
267
+ )
268
+ if slot is None:
269
+ before_peer = earliest_cap
270
+ slot = _resolve_peer_clearance(
271
+ earliest_cap, dman_peer, cap_gap, flight.wake_class.value,
272
+ flight.latest_minute, repair,
273
+ )
274
+ if slot is None:
275
+ continue
276
+
277
+ if slot > before_peer and any(
278
+ m.is_emergency
279
+ for m in obs.incoming_messages
280
+ if m.from_role == AgentRole.DMAN and m.runway_id == rwy_id
281
+ ):
282
+ emergency_yields.append(flight.flight_id)
283
+
284
+ gap_to_scheduled = abs(slot - flight.scheduled_minute)
285
+ if best_rwy is None or gap_to_scheduled < best_gap:
286
+ best_rwy = rwy_id
287
+ best_min = slot
288
+ best_gap = gap_to_scheduled
289
+
290
+ if best_rwy and best_min is not None:
291
+ slots.append(SlotAssignment(
292
+ flight_id=flight.flight_id,
293
+ runway=best_rwy,
294
+ assigned_minute=best_min,
295
+ hold_minutes=max(0, best_min - flight.scheduled_minute),
296
+ ))
297
+ runway_last[best_rwy] = (best_min, flight.wake_class.value)
298
+
299
+ # Build outgoing messages — claim slots and broadcast emergencies
300
+ messages: List[NegotiationMessage] = []
301
+ for s in slots:
302
+ flight = next((f for f in arrivals if f.flight_id == s.flight_id), None)
303
+ if flight and flight.priority in (PriorityClass.EMERGENCY, PriorityClass.MEDICAL):
304
+ messages.append(NegotiationMessage(
305
+ from_role=AgentRole.AMAN,
306
+ message_type=MessageType.EMERGENCY_BCAST,
307
+ flight_id=s.flight_id,
308
+ requested_minute=s.assigned_minute,
309
+ runway_id=s.runway,
310
+ priority=flight.priority,
311
+ reason=f"Emergency arrival — runway {s.runway} must be clear at T+{s.assigned_minute}",
312
+ is_emergency=True,
313
+ ))
314
+ else:
315
+ messages.append(NegotiationMessage(
316
+ from_role=AgentRole.AMAN,
317
+ message_type=MessageType.RUNWAY_CLAIM,
318
+ flight_id=s.flight_id if flight else "?",
319
+ requested_minute=s.assigned_minute,
320
+ runway_id=s.runway,
321
+ priority=flight.priority if flight else PriorityClass.NORMAL,
322
+ reason="Arrival slot claim",
323
+ is_emergency=False,
324
+ ))
325
+
326
+ return AMANAction(
327
+ arrival_slots=slots,
328
+ rationale=f"Heuristic AMAN: {len(slots)}/{len(arrivals)} arrivals sequenced, "
329
+ f"priority-sorted, wake-turbulence aware"
330
+ f"{f', separation-repair (level {repair})' if repair else ''}.",
331
+ emergency_yields=emergency_yields,
332
+ outgoing_messages=messages,
333
+ commit=False,
334
+ )
335
+
336
+
337
+ # ── Heuristic DMAN planner ────────────────────────────────────────────────────
338
+
339
+ def _build_dman_heuristic(
340
+ obs: MultiAgentObservation,
341
+ atfm_deadlines: Dict[str, int],
342
+ separation_repair: int = 0,
343
+ ) -> DMANAction:
344
+ """Deterministic departure sequencer — ATFM-aware, emergency priority.
345
+
346
+ ``separation_repair`` (0 = off): add N minutes to wake gaps and expand buffers
347
+ around AMAN-claimed times to break residual cross-lane spacing (larger N = more slack).
348
+ """
349
+ repair = max(0, int(separation_repair))
350
+ from constants import SEPARATION_BY_WAKE
351
+ from engine import _capacity_spacing
352
+ from planner import PRIORITY_RANK
353
+
354
+ def _departure_sort_key(flight: FlightRecord) -> Tuple[int, int, int, int, float, int]:
355
+ deadline = atfm_deadlines.get(flight.flight_id)
356
+ # Keep emergency traffic first, then pull ATFM-constrained flights ahead of
357
+ # unconstrained traffic so hard network slot windows are not accidentally lost.
358
+ deadline_bucket = 0 if flight.priority in (PriorityClass.EMERGENCY, PriorityClass.MEDICAL) else (
359
+ 1 if deadline is not None else 2
360
+ )
361
+ return (
362
+ deadline_bucket,
363
+ deadline if deadline is not None else flight.scheduled_minute,
364
+ PRIORITY_RANK[flight.priority],
365
+ flight.scheduled_minute,
366
+ -flight.connection_risk,
367
+ -flight.passengers,
368
+ )
369
+
370
+ departures = sorted(obs.my_flights, key=_departure_sort_key)
371
+ runway_last: Dict[str, Tuple[int, str]] = {
372
+ r.runway_id: (0, "M") for r in obs.all_runways
373
+ }
374
+
375
+ # Reserve slots claimed by AMAN
376
+ aman_claims: Dict[str, List[int]] = {}
377
+ for m in obs.incoming_messages:
378
+ if m.from_role == AgentRole.AMAN:
379
+ aman_claims.setdefault(m.runway_id, []).append(m.requested_minute)
380
+
381
+ slots: List[SlotAssignment] = []
382
+ atfm_compliance: Dict[str, int] = {}
383
+ emergency_broadcasts: List[str] = []
384
+ messages: List[NegotiationMessage] = []
385
+
386
+ for flight in departures:
387
+ # Only pure EMERGENCY flights override AMAN's claims entirely.
388
+ # MEDICAL departures (e.g. ICU POST_OP after ADAPT) must still attempt
389
+ # peer-clearance: they have hard transfer-auth deadlines and compete for
390
+ # the same beds as AMAN admissions. Skipping clearance for MEDICAL was
391
+ # the root cause of permanent BID-phase conflicts that negotiation could
392
+ # never resolve (DMAN re-claimed the same bed minute every pass).
393
+ is_emg = flight.priority in (PriorityClass.EMERGENCY, PriorityClass.MEDICAL)
394
+ is_hard_emergency = flight.priority == PriorityClass.EMERGENCY
395
+ deadline = atfm_deadlines.get(flight.flight_id)
396
+ best_rwy, best_min = None, None
397
+ best_score = float("inf")
398
+
399
+ for rwy_id in flight.allowed_runways:
400
+ rwy = next((r for r in obs.all_runways if r.runway_id == rwy_id), None)
401
+ if not rwy:
402
+ continue
403
+ if OperationType.DEPARTURE not in rwy.allowed_operations:
404
+ continue
405
+
406
+ last_min, last_wake = runway_last.get(rwy_id, (0, "M"))
407
+ cap_gap = _capacity_spacing(rwy)
408
+ wake_gap = SEPARATION_BY_WAKE.get((last_wake, flight.wake_class.value), 3)
409
+ min_gap = max(cap_gap, wake_gap) + repair
410
+ earliest_cap = max(flight.earliest_minute, last_min + min_gap)
411
+
412
+ if earliest_cap > flight.latest_minute:
413
+ continue
414
+
415
+ # Target scheduled time; avoids pulling departures to T+5 on idle resources.
416
+ # For ATFM-constrained flights, never target past the hard deadline.
417
+ target = max(earliest_cap, flight.scheduled_minute)
418
+ if target > flight.latest_minute:
419
+ target = earliest_cap
420
+ if deadline is not None and target > deadline:
421
+ target = earliest_cap # must hit deadline; use earliest feasible
422
+
423
+ # Peer-clearance: EMERGENCY overrides AMAN; MEDICAL tries to clear then
424
+ # keeps best target if impossible; normal/connection skips runway.
425
+ if not is_hard_emergency:
426
+ aman_mins = aman_claims.get(rwy_id, [])
427
+ # Try peer-clear from target first
428
+ cleared = _resolve_peer_clearance(
429
+ target, aman_mins, cap_gap, flight.wake_class.value,
430
+ flight.latest_minute, repair,
431
+ )
432
+ if cleared is not None:
433
+ target = cleared
434
+ elif not is_emg:
435
+ # Fall back to earliest_cap and retry
436
+ cleared = _resolve_peer_clearance(
437
+ earliest_cap, aman_mins, cap_gap, flight.wake_class.value,
438
+ flight.latest_minute, repair,
439
+ )
440
+ if cleared is None:
441
+ continue
442
+ target = cleared
443
+ # MEDICAL with unresolvable conflict keeps target (negotiation resolves)
444
+
445
+ if target > flight.latest_minute:
446
+ continue
447
+
448
+ # ATFM deadline must still hold after peer clearance
449
+ if deadline is not None and target > deadline:
450
+ continue
451
+
452
+ score = abs(target - flight.scheduled_minute)
453
+ if score < best_score:
454
+ best_rwy = rwy_id
455
+ best_min = target
456
+ best_score = score
457
+
458
+ if best_rwy and best_min is not None:
459
+ slots.append(SlotAssignment(
460
+ flight_id=flight.flight_id,
461
+ runway=best_rwy,
462
+ assigned_minute=best_min,
463
+ hold_minutes=max(0, best_min - flight.scheduled_minute),
464
+ ))
465
+ runway_last[best_rwy] = (best_min, flight.wake_class.value)
466
+
467
+ if deadline is not None:
468
+ atfm_compliance[flight.flight_id] = deadline
469
+
470
+ msg_type = MessageType.EMERGENCY_BCAST if is_emg else MessageType.RUNWAY_CLAIM
471
+ if is_emg:
472
+ emergency_broadcasts.append(flight.flight_id)
473
+ messages.append(NegotiationMessage(
474
+ from_role=AgentRole.DMAN,
475
+ message_type=msg_type,
476
+ flight_id=flight.flight_id,
477
+ requested_minute=best_min,
478
+ runway_id=best_rwy,
479
+ priority=flight.priority,
480
+ reason=(
481
+ f"Emergency departure — yield runway {best_rwy} at T+{best_min}"
482
+ if is_emg else "Departure slot claim"
483
+ ),
484
+ is_emergency=is_emg,
485
+ ))
486
+
487
+ return DMANAction(
488
+ departure_slots=slots,
489
+ rationale=f"Heuristic DMAN: {len(slots)}/{len(departures)} departures sequenced, "
490
+ f"ATFM-compliant, emergency-priority"
491
+ f"{f', separation-repair (level {repair})' if repair else ''}.",
492
+ atfm_compliance=atfm_compliance,
493
+ emergency_broadcasts=emergency_broadcasts,
494
+ outgoing_messages=messages,
495
+ commit=False,
496
+ )
497
+
498
+
499
+ # ── LLM agent ──────���──────────────────────────────────────────────────────────
500
+
501
+ def _llm_action(
502
+ client,
503
+ model_name: str,
504
+ system: str,
505
+ obs: MultiAgentObservation,
506
+ sup_desc: str,
507
+ role: AgentRole,
508
+ temperature: Optional[float] = None,
509
+ system_extra: str = "",
510
+ ) -> Optional[AMANAction | DMANAction]:
511
+ if client is None:
512
+ return None
513
+ temp = TEMPERATURE if temperature is None else temperature
514
+ system_content = system + f"\n\nSUPERVISOR TODAY: {sup_desc}"
515
+ if (system_extra or "").strip():
516
+ system_content = system_content + "\n\n" + system_extra.strip()
517
+ try:
518
+ resp = client.chat.completions.create(
519
+ model=model_name,
520
+ messages=[
521
+ {"role": "system", "content": system_content},
522
+ {"role": "user", "content": obs.to_prompt_text()},
523
+ ],
524
+ temperature=temp,
525
+ max_tokens=MAX_TOKENS,
526
+ )
527
+ text = (resp.choices[0].message.content or "").strip()
528
+ if role == AgentRole.AMAN:
529
+ return parse_aman_action(text)
530
+ return parse_dman_action(text)
531
+ except Exception as exc:
532
+ _p(f"[WARN] LLM call failed ({role.value}): {exc} — falling back to heuristic")
533
+ return None
534
+
535
+
536
+ def _negotiate_multi_pass(
537
+ client,
538
+ selected_model: str,
539
+ sup_desc: str,
540
+ env: MultiAgentATCEnvironment,
541
+ aman_obs_start: MultiAgentObservation,
542
+ dman_obs_start: MultiAgentObservation,
543
+ atfm: Dict[str, int],
544
+ rounds: List[Dict[str, Any]],
545
+ visual_sink: VisualSink = None,
546
+ max_passes: Optional[int] = None,
547
+ llm_system_extra: str = "",
548
+ ) -> Tuple[MultiAgentObservation, MultiAgentObservation]:
549
+ """Revision passes on separation conflicts until resolved or cap reached.
550
+
551
+ Pass 1 uses the LLM when ``client`` is set (lower temperature for stability);
552
+ later passes use tiered separation-repair heuristics (0 = off; higher passes
553
+ add more inter-slot slack). Native ATC uses 2 / 1 passes (with/without client);
554
+ ADAPT domain transfer uses DOMAIN_MAX_NEGOTIATE_ROUNDS for more repair attempts.
555
+ """
556
+ aman_cur, dman_cur = aman_obs_start, dman_obs_start
557
+ if max_passes is not None:
558
+ max_p = int(max_passes)
559
+ elif client is not None:
560
+ max_p = MAX_NEGOTIATE_ROUNDS
561
+ else:
562
+ max_p = 1
563
+
564
+ for neg_r in range(1, max_p + 1):
565
+ sep_before = count_separation_issues(env._state.conflict_log)
566
+ if sep_before == 0:
567
+ break
568
+
569
+ use_llm = client is not None and neg_r == 1
570
+ if use_llm:
571
+ aman_action = (
572
+ _llm_action(
573
+ client,
574
+ selected_model,
575
+ AMAN_SYSTEM,
576
+ aman_cur,
577
+ sup_desc,
578
+ AgentRole.AMAN,
579
+ temperature=0.2,
580
+ system_extra=llm_system_extra,
581
+ )
582
+ or _build_aman_heuristic(aman_cur)
583
+ )
584
+ dman_merged = _dman_obs_with_aman_messages(dman_cur, aman_action)
585
+ dman_action = (
586
+ _llm_action(
587
+ client,
588
+ selected_model,
589
+ DMAN_SYSTEM,
590
+ dman_merged,
591
+ sup_desc,
592
+ AgentRole.DMAN,
593
+ temperature=0.2,
594
+ system_extra=llm_system_extra,
595
+ )
596
+ or _build_dman_heuristic(dman_merged, atfm)
597
+ )
598
+ else:
599
+ repair = 0 if neg_r == 1 else min(neg_r - 1, 3)
600
+ aman_action = _build_aman_heuristic(aman_cur, separation_repair=repair)
601
+ dman_merged = _dman_obs_with_aman_messages(dman_cur, aman_action)
602
+ dman_action = _build_dman_heuristic(dman_merged, atfm, separation_repair=repair)
603
+
604
+ aman_cur, dman_cur, partial_r, _ = env.step_negotiate(aman_action, dman_action)
605
+ sep_after = count_separation_issues(env._state.conflict_log)
606
+ resolved = max(0, sep_before - sep_after)
607
+ total_msgs = len(aman_action.outgoing_messages) + len(dman_action.outgoing_messages)
608
+ log_neg(neg_r, resolved, total_msgs)
609
+ log_step(1 + neg_r, "NEGOTIATE", partial_r, sep_after, True)
610
+
611
+ emit(
612
+ visual_sink,
613
+ {
614
+ "type": "negotiation_tick",
615
+ "pass": neg_r,
616
+ "partial_reward": partial_r,
617
+ "separation_issues_after": sep_after,
618
+ "used_llm": use_llm,
619
+ "layout": serialize_action_layout(aman_action, dman_action),
620
+ },
621
+ )
622
+
623
+ rounds.append({
624
+ "round": "NEGOTIATE",
625
+ "negotiate_pass": neg_r,
626
+ "partial_reward": partial_r,
627
+ "separation_issues_before": sep_before,
628
+ "separation_issues_after": sep_after,
629
+ "diagnostics_count": len(env._state.conflict_log),
630
+ "conflicts_resolved": resolved,
631
+ "total_messages": total_msgs,
632
+ "aman_alternatives_offered": sum(
633
+ len(m.proposed_alternatives) for m in aman_action.outgoing_messages
634
+ ),
635
+ "dman_alternatives_offered": sum(
636
+ len(m.proposed_alternatives) for m in dman_action.outgoing_messages
637
+ ),
638
+ "used_llm": use_llm,
639
+ })
640
+
641
+ if sep_after == 0:
642
+ break
643
+
644
+ return aman_cur, dman_cur
645
+
646
+
647
+ # ── Episode runner ─────────────────────────────────────────────────────────────
648
+
649
+ def _save_transcript(
650
+ transcript_dir: Path,
651
+ episode_id: int,
652
+ data: Dict[str, Any],
653
+ ) -> None:
654
+ """Write one episode transcript to <transcript_dir>/episode_NNNNN.json."""
655
+ transcript_dir.mkdir(parents=True, exist_ok=True)
656
+ path = transcript_dir / f"episode_{episode_id:05d}.json"
657
+ try:
658
+ with open(path, "w", encoding="utf-8") as fh:
659
+ json.dump(data, fh, indent=2, default=str)
660
+ except OSError as exc:
661
+ _p(f"[WARN] Could not save transcript for episode {episode_id}: {exc}")
662
+
663
+
664
+ def run_episode(
665
+ task_id: str,
666
+ client,
667
+ env: MultiAgentATCEnvironment,
668
+ generator: Optional[ChallengeGenerator],
669
+ supervisor: SupervisorAgent,
670
+ episode_id: int,
671
+ use_generator: bool = True,
672
+ model_name: Optional[str] = None,
673
+ transcript_dir: Optional[Path] = None,
674
+ visual_sink: VisualSink = None,
675
+ visual_profile: str = "atc",
676
+ ) -> Dict:
677
+ """Run one full AMAN/DMAN episode. Returns result dict for logging.
678
+
679
+ Args:
680
+ transcript_dir: If set, writes a JSON transcript of the full episode
681
+ (actions, messages, rewards, metadata) to this directory.
682
+ visual_sink: Optional callback receiving visual event dicts (SSE / UI).
683
+ visual_profile: ``atc`` | ``icu`` — UI theme only (same simulation).
684
+ """
685
+ catalog = task_catalog()
686
+ base_task = catalog.get(task_id, list(catalog.values())[0])
687
+ profile = supervisor.sample_profile(episode_id)
688
+ sup_desc = SUPERVISOR_PROFILES[profile]["description"]
689
+
690
+ mutations_applied: List[str] = []
691
+ if use_generator and generator is not None:
692
+ mutated_task, solvable = generator.mutate(base_task)
693
+ gen_difficulty = generator.difficulty_level
694
+ mutations_applied = [
695
+ m["type"]
696
+ for m in getattr(generator, "_mutation_history", [])[-3:]
697
+ ]
698
+
699
+ else:
700
+ mutated_task, solvable = base_task, True
701
+ gen_difficulty = 1
702
+
703
+ # Enable domain randomisation when the generator is inactive — replaces the
704
+ # structural diversity that generator mutations would otherwise provide.
705
+ aman_obs, dman_obs = env.reset(
706
+ episode_id=episode_id,
707
+ supervisor_profile=profile,
708
+ mutated_task=mutated_task,
709
+ randomize=not use_generator,
710
+ )
711
+ selected_model = model_name or MODEL_NAME
712
+ atfm = env._state.atfm_deadlines
713
+
714
+ # Accumulate round data for the transcript
715
+ rounds: List[Dict[str, Any]] = []
716
+ visual_log: List[Dict[str, Any]] = []
717
+
718
+ def _v(ev: Dict[str, Any]) -> None:
719
+ visual_log.append(dict(ev))
720
+ emit(visual_sink, ev)
721
+
722
+ assert env._state.task is not None
723
+ _v(
724
+ {
725
+ "type": "scene_reset",
726
+ "episode_id": episode_id,
727
+ "task_id": task_id,
728
+ "resolved_task_id": env._state.task.task_id,
729
+ "visual_profile": visual_profile,
730
+ "supervisor_profile": profile.value,
731
+ "mutations_applied": mutations_applied,
732
+ "task": serialize_task_snapshot(env._state.task),
733
+ },
734
+ )
735
+
736
+ # ── Round 0: BID ──────────────────────────────────────────────────────────
737
+ _v({"type": "llm_started", "role": "AMAN", "model": selected_model})
738
+ aman_action = (
739
+ _llm_action(client, selected_model, AMAN_SYSTEM, aman_obs, sup_desc, AgentRole.AMAN)
740
+ or _build_aman_heuristic(aman_obs)
741
+ )
742
+ _v({"type": "llm_finished", "role": "AMAN", "used_llm": client is not None})
743
+
744
+ dman_obs_bid = _dman_obs_with_aman_messages(dman_obs, aman_action)
745
+ _v({"type": "llm_started", "role": "DMAN", "model": selected_model})
746
+ dman_action = (
747
+ _llm_action(client, selected_model, DMAN_SYSTEM, dman_obs_bid, sup_desc, AgentRole.DMAN)
748
+ or _build_dman_heuristic(dman_obs_bid, atfm)
749
+ )
750
+ _v({"type": "llm_finished", "role": "DMAN", "used_llm": client is not None})
751
+
752
+ _v({"type": "action_layout", "phase": "BID", "layout": serialize_action_layout(aman_action, dman_action)})
753
+
754
+ aman_obs2, dman_obs2, partial_r, done = env.step_bid(aman_action, dman_action)
755
+ n_sep_after_bid = count_separation_issues(env._state.conflict_log)
756
+ n_diag_after_bid = len(env._state.conflict_log)
757
+ log_step(1, "BID", partial_r, n_sep_after_bid, done)
758
+
759
+ rounds.append({
760
+ "round": "BID",
761
+ "partial_reward": partial_r,
762
+ "separation_issues_detected": n_sep_after_bid,
763
+ "diagnostics_count": n_diag_after_bid,
764
+ "aman_slots": len(aman_action.arrival_slots),
765
+ "dman_slots": len(dman_action.departure_slots),
766
+ "aman_messages": len(aman_action.outgoing_messages),
767
+ "dman_messages": len(dman_action.outgoing_messages),
768
+ "done": done,
769
+ })
770
+
771
+ # ── Negotiate: LLM first (if available), then heuristic-only repair passes ─
772
+ if not done:
773
+ _negotiate_multi_pass(
774
+ client,
775
+ selected_model,
776
+ sup_desc,
777
+ env,
778
+ aman_obs2,
779
+ dman_obs2,
780
+ atfm,
781
+ rounds,
782
+ visual_sink=lambda ev: _v(ev),
783
+ )
784
+
785
+ # ── Finalize ──────────────────────────────────────────────────────────────
786
+ result = env.finalize()
787
+ if generator is not None:
788
+ generator.update(result.composite_score)
789
+ gen_difficulty = generator.difficulty_level
790
+
791
+ episode_result = {
792
+ "composite": result.composite_score,
793
+ "aman_reward": result.aman_reward,
794
+ "dman_reward": result.dman_reward,
795
+ "coord_score": result.per_role.coordination_score,
796
+ "conflicts": result.per_role.cross_lane_conflicts,
797
+ "atfm_viol": result.per_role.atfm_violations,
798
+ "emg_arr_ok": result.per_role.emergency_arrivals_ok,
799
+ "emg_dep_ok": result.per_role.emergency_departures_ok,
800
+ "neg_rounds": result.negotiation_rounds,
801
+ "gen_difficulty": gen_difficulty,
802
+ "supervisor": profile.value,
803
+ "solvable": solvable,
804
+ }
805
+
806
+ _v(
807
+ {
808
+ "type": "score_update",
809
+ "composite": result.composite_score,
810
+ "aman_reward": result.aman_reward,
811
+ "dman_reward": result.dman_reward,
812
+ },
813
+ )
814
+ _v(
815
+ terminal_event(
816
+ composite=result.composite_score,
817
+ aman_reward=result.aman_reward,
818
+ dman_reward=result.dman_reward,
819
+ coordination=result.per_role.coordination_score,
820
+ cross_lane_conflicts=result.per_role.cross_lane_conflicts,
821
+ atfm_violations=result.per_role.atfm_violations,
822
+ negotiation_rounds=result.negotiation_rounds,
823
+ )
824
+ )
825
+
826
+ if transcript_dir is not None:
827
+ _save_transcript(
828
+ transcript_dir,
829
+ episode_id,
830
+ {
831
+ "episode_id": episode_id,
832
+ "task_id": task_id,
833
+ "supervisor_profile": profile.value,
834
+ "gen_difficulty": gen_difficulty,
835
+ "mutations_applied": mutations_applied,
836
+ "solvable": solvable,
837
+ "visual_log": visual_log,
838
+ "rounds": rounds,
839
+ "final": {
840
+ "composite_score": result.composite_score,
841
+ "aman_reward": result.aman_reward,
842
+ "dman_reward": result.dman_reward,
843
+ "generator_reward": result.generator_reward,
844
+ "supervisor_score": result.supervisor_score,
845
+ "coordination_score": result.per_role.coordination_score,
846
+ "cross_lane_conflicts": result.per_role.cross_lane_conflicts,
847
+ "negotiation_rounds": result.negotiation_rounds,
848
+ "atfm_violations": result.per_role.atfm_violations,
849
+ "emergency_arrivals_ok": result.per_role.emergency_arrivals_ok,
850
+ "emergency_departures_ok": result.per_role.emergency_departures_ok,
851
+ },
852
+ },
853
+ )
854
+
855
+ return episode_result
856
+
857
+ def run_domain_episode(
858
+ domain_task_id: str,
859
+ client,
860
+ env: MultiAgentATCEnvironment,
861
+ supervisor: SupervisorAgent,
862
+ episode_id: int,
863
+ model_name: Optional[str] = None,
864
+ transcript_dir: Optional[Path] = None,
865
+ visual_sink: VisualSink = None,
866
+ visual_profile: str = "icu",
867
+ ) -> Dict:
868
+ """Run one ADAPT domain-transfer episode.
869
+
870
+ ADAPT maps the domain task → ATC-parameterised task.
871
+ AMAN and DMAN then solve it with no code changes.
872
+
873
+ Args:
874
+ domain_task_id: Key from the domains registry, e.g. 'icu_mass_casualty'.
875
+ """
876
+ from domains import get_all_domain_tasks
877
+ from multi_agent.adapt import (
878
+ build_adapt_observation,
879
+ _build_adapt_heuristic,
880
+ apply_adapt_mapping,
881
+ parse_adapt_action,
882
+ )
883
+ from training.dataset import ADAPT_SYSTEM
884
+
885
+ all_domain_tasks = get_all_domain_tasks()
886
+ if domain_task_id not in all_domain_tasks:
887
+ available = ", ".join(sorted(all_domain_tasks.keys()))
888
+ raise ValueError(
889
+ f"Domain task {domain_task_id!r} not found. Available: {available}"
890
+ )
891
+
892
+ domain_task = all_domain_tasks[domain_task_id]
893
+ profile = supervisor.sample_profile(episode_id)
894
+ sup_desc = SUPERVISOR_PROFILES[profile]["description"]
895
+ rounds: List[Dict[str, Any]] = []
896
+ visual_log: List[Dict[str, Any]] = []
897
+
898
+ def _v(ev: Dict[str, Any]) -> None:
899
+ visual_log.append(dict(ev))
900
+ emit(visual_sink, ev)
901
+
902
+ # ── ADAPT step ────────────────────────────────────────────────────────────
903
+ adapt_obs = build_adapt_observation(task=domain_task, profile=profile)
904
+
905
+ adapt_action: Optional[object] = None
906
+ adapt_rationale = "(heuristic)"
907
+
908
+ _v(
909
+ {
910
+ "type": "adapt_scene",
911
+ "domain_task_id": domain_task_id,
912
+ "visual_profile": visual_profile,
913
+ "entity_types": list(adapt_obs.entity_types),
914
+ },
915
+ )
916
+
917
+ if client is not None:
918
+ try:
919
+ resp = client.chat.completions.create(
920
+ model=model_name or MODEL_NAME,
921
+ messages=[
922
+ {"role": "system", "content": ADAPT_SYSTEM},
923
+ {"role": "user", "content": adapt_obs.to_prompt_text()},
924
+ ],
925
+ temperature=TEMPERATURE,
926
+ max_tokens=MAX_TOKENS,
927
+ )
928
+ text = (resp.choices[0].message.content or "").strip()
929
+ adapt_action = parse_adapt_action(text)
930
+ adapt_rationale = (adapt_action.rationale if adapt_action else "(LLM parse failed)")
931
+ except Exception as exc:
932
+ _p(f"[WARN] ADAPT LLM call failed: {exc} — falling back to structural heuristic")
933
+
934
+ if adapt_action is None:
935
+ adapt_action = _build_adapt_heuristic(adapt_obs, domain_task)
936
+ adapt_rationale = adapt_action.rationale
937
+
938
+ _v(
939
+ {
940
+ "type": "adapt_mapping",
941
+ "wake_map": dict(adapt_action.entity_wake_map),
942
+ "priority_map": dict(adapt_action.entity_priority_map),
943
+ "rationale_preview": (adapt_rationale or "")[:200],
944
+ },
945
+ )
946
+
947
+ _p(f"[ADAPT] domain={domain_task_id} entities={adapt_obs.entity_types}")
948
+ _p(f"[ADAPT] wake_map={adapt_action.entity_wake_map}")
949
+ _p(f"[ADAPT] priority_map={adapt_action.entity_priority_map}")
950
+ _p(f"[ADAPT] rationale={adapt_rationale[:120].encode('ascii', errors='replace').decode()}")
951
+
952
+
953
+ # ── Apply ADAPT mapping and run AMAN/DMAN ────────────────────────────────
954
+ mapped_task = apply_adapt_mapping(domain_task, adapt_action)
955
+
956
+ aman_obs, dman_obs = env.reset(
957
+ episode_id=episode_id,
958
+ supervisor_profile=profile,
959
+ mutated_task=mapped_task,
960
+ domain_mode=True, # enables DOMAIN_MAX_NEGOTIATE_ROUNDS and correct steps_remaining
961
+ )
962
+ atfm = env._state.atfm_deadlines
963
+ selected_model = model_name or MODEL_NAME
964
+
965
+ assert env._state.task is not None
966
+ _v(
967
+ {
968
+ "type": "scene_reset",
969
+ "episode_id": episode_id,
970
+ "task_id": domain_task_id,
971
+ "resolved_task_id": env._state.task.task_id,
972
+ "visual_profile": visual_profile,
973
+ "supervisor_profile": profile.value,
974
+ "mutations_applied": [],
975
+ "task": serialize_task_snapshot(env._state.task),
976
+ },
977
+ )
978
+
979
+ _v({"type": "llm_started", "role": "AMAN", "model": selected_model})
980
+ aman_action = _build_aman_heuristic(aman_obs)
981
+ if client is not None:
982
+ aman_action = (
983
+ _llm_action(
984
+ client,
985
+ selected_model,
986
+ AMAN_SYSTEM,
987
+ aman_obs,
988
+ sup_desc,
989
+ AgentRole.AMAN,
990
+ system_extra=_DOMAIN_TRANSFER_LLM_HINT,
991
+ )
992
+ or aman_action
993
+ )
994
+ _v({"type": "llm_finished", "role": "AMAN", "used_llm": client is not None})
995
+
996
+ dman_obs_bid = _dman_obs_with_aman_messages(dman_obs, aman_action)
997
+ _v({"type": "llm_started", "role": "DMAN", "model": selected_model})
998
+ dman_action = _build_dman_heuristic(dman_obs_bid, atfm)
999
+ if client is not None:
1000
+ dman_action = (
1001
+ _llm_action(
1002
+ client,
1003
+ selected_model,
1004
+ DMAN_SYSTEM,
1005
+ dman_obs_bid,
1006
+ sup_desc,
1007
+ AgentRole.DMAN,
1008
+ system_extra=_DOMAIN_TRANSFER_LLM_HINT,
1009
+ )
1010
+ or dman_action
1011
+ )
1012
+ _v({"type": "llm_finished", "role": "DMAN", "used_llm": client is not None})
1013
+
1014
+ _v({"type": "action_layout", "phase": "BID", "layout": serialize_action_layout(aman_action, dman_action)})
1015
+
1016
+ aman_obs2, dman_obs2, partial_r, done = env.step_bid(aman_action, dman_action)
1017
+ n_sep_after_bid = count_separation_issues(env._state.conflict_log)
1018
+ n_diag_after_bid = len(env._state.conflict_log)
1019
+ log_step(1, "BID", partial_r, n_sep_after_bid, done)
1020
+
1021
+ rounds.append({
1022
+ "round": "BID",
1023
+ "partial_reward": partial_r,
1024
+ "separation_issues_detected": n_sep_after_bid,
1025
+ "diagnostics_count": n_diag_after_bid,
1026
+ "aman_slots": len(aman_action.arrival_slots),
1027
+ "dman_slots": len(dman_action.departure_slots),
1028
+ "aman_messages": len(aman_action.outgoing_messages),
1029
+ "dman_messages": len(dman_action.outgoing_messages),
1030
+ "done": done,
1031
+ })
1032
+
1033
+ if not done:
1034
+ _negotiate_multi_pass(
1035
+ client,
1036
+ selected_model,
1037
+ sup_desc,
1038
+ env,
1039
+ aman_obs2,
1040
+ dman_obs2,
1041
+ atfm,
1042
+ rounds,
1043
+ visual_sink=lambda ev: _v(ev),
1044
+ max_passes=DOMAIN_MAX_NEGOTIATE_ROUNDS,
1045
+ llm_system_extra=_DOMAIN_TRANSFER_LLM_HINT if client is not None else "",
1046
+ )
1047
+
1048
+ result = env.finalize()
1049
+
1050
+ _v(
1051
+ {
1052
+ "type": "score_update",
1053
+ "composite": result.composite_score,
1054
+ "aman_reward": result.aman_reward,
1055
+ "dman_reward": result.dman_reward,
1056
+ },
1057
+ )
1058
+ _v(
1059
+ terminal_event(
1060
+ composite=result.composite_score,
1061
+ aman_reward=result.aman_reward,
1062
+ dman_reward=result.dman_reward,
1063
+ coordination=result.per_role.coordination_score,
1064
+ cross_lane_conflicts=result.per_role.cross_lane_conflicts,
1065
+ atfm_violations=result.per_role.atfm_violations,
1066
+ negotiation_rounds=result.negotiation_rounds,
1067
+ )
1068
+ )
1069
+
1070
+ episode_result: Dict[str, Any] = {
1071
+ "domain_task_id": domain_task_id,
1072
+ "composite": result.composite_score,
1073
+ "aman_reward": result.aman_reward,
1074
+ "dman_reward": result.dman_reward,
1075
+ "coord_score": result.per_role.coordination_score,
1076
+ "conflicts": result.per_role.cross_lane_conflicts,
1077
+ "neg_rounds": result.negotiation_rounds,
1078
+ "supervisor": profile.value,
1079
+ "adapt_wake_map": adapt_action.entity_wake_map,
1080
+ "adapt_priority_map": adapt_action.entity_priority_map,
1081
+ }
1082
+
1083
+ if transcript_dir is not None:
1084
+ _save_transcript(
1085
+ transcript_dir,
1086
+ episode_id,
1087
+ {
1088
+ "episode_id": episode_id,
1089
+ "domain_task_id": domain_task_id,
1090
+ "mode": "adapt_domain_transfer",
1091
+ "supervisor_profile": profile.value,
1092
+ "adapt_wake_map": adapt_action.entity_wake_map,
1093
+ "adapt_priority_map": adapt_action.entity_priority_map,
1094
+ "adapt_rationale": adapt_rationale,
1095
+ "visual_log": visual_log,
1096
+ "rounds": rounds,
1097
+ "final": {
1098
+ "composite_score": result.composite_score,
1099
+ "aman_reward": result.aman_reward,
1100
+ "dman_reward": result.dman_reward,
1101
+ "coordination_score": result.per_role.coordination_score,
1102
+ "cross_lane_conflicts": result.per_role.cross_lane_conflicts,
1103
+ "negotiation_rounds": result.negotiation_rounds,
1104
+ "atfm_violations": result.per_role.atfm_violations,
1105
+ },
1106
+ },
1107
+ )
1108
+
1109
+ _p(
1110
+ f"[END] domain={domain_task_id} success={str(result.composite_score >= SUCCESS_THRESHOLD).lower()} "
1111
+ f"composite={result.composite_score:.3f} aman={result.aman_reward:.3f} dman={result.dman_reward:.3f}"
1112
+ )
1113
+ return episode_result
1114
+
1115
+
1116
+ # ── Main ──────────────────────────────────────────────────────────────────────
1117
+
1118
+ def main() -> None:
1119
+ parser = argparse.ArgumentParser(description="Multi-Agent ATC Inference Runner")
1120
+ parser.add_argument("--task", default="bengaluru_irrops_hard",
1121
+ help="Task ID (default: bengaluru_irrops_hard)")
1122
+ parser.add_argument("--episodes", type=int, default=1,
1123
+ help="Number of episodes to run")
1124
+ parser.add_argument("--model", default=MODEL_NAME,
1125
+ help="Model name or 'heuristic-baseline'")
1126
+ parser.add_argument("--no_generator", action="store_true",
1127
+ help="Disable self-play generator (use base tasks)")
1128
+ parser.add_argument("--all_tasks", action="store_true",
1129
+ help="Run all ATC tasks in sequence")
1130
+ parser.add_argument("--domain", default=None,
1131
+ help=(
1132
+ "Run ADAPT domain-transfer mode on a domain task ID "
1133
+ "(e.g. icu_mass_casualty, icu_flu_surge, icu_normal_day). "
1134
+ "Use --domain list to show all available domain tasks."
1135
+ ))
1136
+ parser.add_argument("--seed", type=int, default=42)
1137
+ parser.add_argument("--transcript_dir", default=None,
1138
+ help="Directory to write per-episode JSON transcripts "
1139
+ "(default: no transcripts saved)")
1140
+ args = parser.parse_args()
1141
+
1142
+ model = args.model or MODEL_NAME
1143
+ use_llm = model != "heuristic-baseline" and HF_TOKEN
1144
+
1145
+ client = None
1146
+ if use_llm:
1147
+ try:
1148
+ from openai import OpenAI
1149
+ client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)
1150
+ _p(f"[INFO] LLM client initialised: {model}")
1151
+ except ImportError:
1152
+ _p("[WARN] openai package missing — using heuristic baseline")
1153
+
1154
+ env = MultiAgentATCEnvironment(seed=args.seed)
1155
+ generator = ChallengeGenerator(seed=args.seed)
1156
+ supervisor = SupervisorAgent()
1157
+
1158
+ transcript_dir = Path(args.transcript_dir) if args.transcript_dir else None
1159
+
1160
+ # ── ADAPT domain-transfer mode ────────────────────────────────────────────
1161
+ if args.domain is not None:
1162
+ if args.domain == "list":
1163
+ from domains import get_all_domain_tasks
1164
+ all_dt = get_all_domain_tasks()
1165
+ _p("Available domain tasks:")
1166
+ for tid in sorted(all_dt.keys()):
1167
+ t = all_dt[tid]
1168
+ _p(f" {tid:<35} ({t.difficulty.value}, {len(t.flights)} entities, {len(t.runways)} resources)")
1169
+ return
1170
+
1171
+ _p(f"[INFO] ADAPT domain-transfer mode: {args.domain}")
1172
+ all_results: List[Dict] = []
1173
+ for ep in range(args.episodes):
1174
+ result = run_domain_episode(
1175
+ domain_task_id=args.domain,
1176
+ client=client,
1177
+ env=env,
1178
+ supervisor=supervisor,
1179
+ episode_id=ep,
1180
+ model_name=model,
1181
+ transcript_dir=transcript_dir,
1182
+ )
1183
+ all_results.append(result)
1184
+
1185
+ if len(all_results) > 1:
1186
+ _p("\n=== DOMAIN TRANSFER SUMMARY ===")
1187
+ _p(f"Domain: {args.domain}")
1188
+ _p(f"Episodes: {len(all_results)}")
1189
+ _p(f"Mean composite: {sum(r['composite'] for r in all_results)/len(all_results):.3f}")
1190
+ _p(f"Success rate: {sum(1 for r in all_results if r['composite'] >= SUCCESS_THRESHOLD)/len(all_results):.1%}")
1191
+ return
1192
+
1193
+ # ── Standard ATC mode ─────────────────────────────────────────────────────
1194
+ task_ids = (
1195
+ [t.task_id for t in ordered_tasks()]
1196
+ if args.all_tasks
1197
+ else [args.task]
1198
+ )
1199
+
1200
+ all_results: List[Dict] = []
1201
+
1202
+ for task_id in task_ids:
1203
+ log_start(task_id, model)
1204
+ for ep in range(args.episodes):
1205
+ result = run_episode(
1206
+ task_id=task_id,
1207
+ client=client,
1208
+ model_name=model,
1209
+ env=env,
1210
+ generator=generator,
1211
+ supervisor=supervisor,
1212
+ episode_id=ep,
1213
+ use_generator=not args.no_generator,
1214
+ transcript_dir=transcript_dir,
1215
+ )
1216
+ success = result["composite"] >= SUCCESS_THRESHOLD
1217
+ log_end(
1218
+ task=task_id,
1219
+ success=success,
1220
+ composite=result["composite"],
1221
+ aman=result["aman_reward"],
1222
+ dman=result["dman_reward"],
1223
+ coord=result["coord_score"],
1224
+ gen_diff=result["gen_difficulty"],
1225
+ )
1226
+ all_results.append({"task_id": task_id, "episode": ep, **result})
1227
+
1228
+ # Summary
1229
+ if len(all_results) > 1:
1230
+ _p("\n=== MULTI-EPISODE SUMMARY ===")
1231
+ _p(f"Episodes: {len(all_results)}")
1232
+ _p(f"Mean composite: {sum(r['composite'] for r in all_results)/len(all_results):.3f}")
1233
+ _p(f"Mean AMAN reward: {sum(r['aman_reward'] for r in all_results)/len(all_results):.3f}")
1234
+ _p(f"Mean DMAN reward: {sum(r['dman_reward'] for r in all_results)/len(all_results):.3f}")
1235
+ _p(f"Mean coord score: {sum(r['coord_score'] for r in all_results)/len(all_results):.3f}")
1236
+ _p(f"Total conflicts: {sum(r['conflicts'] for r in all_results)}")
1237
+ _p(f"Success rate: {sum(1 for r in all_results if r['composite'] >= SUCCESS_THRESHOLD)/len(all_results):.1%}")
1238
+ _p(f"Final gen level: {all_results[-1]['gen_difficulty']}/6")
1239
+
1240
+
1241
+ if __name__ == "__main__":
1242
+ main()
1243
+
multi_agent/models.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Multi-agent data models for AMAN/DMAN coordination environment.
2
+
3
+ Architecture:
4
+ AMAN — Arrival Manager: owns arrival sequencing, partial view (arrivals only)
5
+ DMAN — Departure Manager: owns departure sequencing, partial view (departures only)
6
+ GENERATOR — Adversarial self-play: mutates tasks to break coordination
7
+ SUPERVISOR — Snorkel AI expert: changing preferences each episode
8
+
9
+ Negotiation protocol (3 rounds):
10
+ Round 0 BID: each agent submits independent plan for own flights
11
+ Round 1 NEGOTIATE: conflict list broadcast; agents revise + send messages
12
+ Round 2 FINAL: merged plan graded; per-agent rewards computed
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from enum import Enum
18
+ from typing import Any, Dict, List, Literal, Optional
19
+
20
+ from pydantic import BaseModel, Field
21
+
22
+ try:
23
+ from ..models import FlightRecord, PriorityClass, RunwaySpec, SlotAssignment, TaskMetrics
24
+ except ImportError:
25
+ from models import FlightRecord, PriorityClass, RunwaySpec, SlotAssignment, TaskMetrics
26
+
27
+
28
+ # ── Agent roles ──────────────────────────────────────────────────────────────
29
+
30
+ class AgentRole(str, Enum):
31
+ AMAN = "AMAN"
32
+ DMAN = "DMAN"
33
+ GENERATOR = "GENERATOR"
34
+ SUPERVISOR = "SUPERVISOR"
35
+ ADAPT = "ADAPT"
36
+
37
+
38
+ # ── Negotiation messaging ─────────────────────────────────────────────────────
39
+
40
+ class MessageType(str, Enum):
41
+ RUNWAY_CLAIM = "runway_claim" # "I need runway X at minute Y"
42
+ EMERGENCY_BCAST = "emergency_broadcast" # "I have EMERGENCY — yield now"
43
+ YIELD = "yield" # "I yield slot Y on runway X"
44
+ ACKNOWLEDGE = "acknowledge" # "Received, adjusting"
45
+ REQUEST_GAP = "request_gap" # "Leave gap at T+N on runway X"
46
+ CONFLICT_FLAG = "conflict_flag" # environment injects this
47
+
48
+
49
+ class SlotProposal(BaseModel):
50
+ """An alternative slot a negotiating agent is willing to accept."""
51
+
52
+ flight_id: str
53
+ runway_id: str
54
+ minute: int
55
+ delay_cost: float = Field(
56
+ default=0.0,
57
+ description="Self-reported cost of accepting this alternative (minutes of delay)",
58
+ )
59
+
60
+
61
+ class NegotiationMessage(BaseModel):
62
+ from_role: AgentRole
63
+ message_type: MessageType
64
+ flight_id: str
65
+ requested_minute: int
66
+ runway_id: str
67
+ priority: PriorityClass
68
+ reason: str
69
+ is_emergency: bool = False
70
+ # Richer negotiation fields — enable more expressive coordination
71
+ content: str = Field(
72
+ default="",
73
+ description="Free-form natural language explanation beyond the reason field",
74
+ )
75
+ proposed_alternatives: List[SlotProposal] = Field(
76
+ default_factory=list,
77
+ description="Alternative slots this agent is willing to accept instead",
78
+ )
79
+ confidence: float = Field(
80
+ default=1.0,
81
+ ge=0.0,
82
+ le=1.0,
83
+ description="Agent's certainty that this request/yield is correct",
84
+ )
85
+ theory_of_mind_claim: str = Field(
86
+ default="",
87
+ description="Agent's explicit prediction about the other agent's constraint or intent",
88
+ )
89
+
90
+
91
+ # ── Agent actions ─────────────────────────────────────────────────────────────
92
+
93
+ class AMANAction(BaseModel):
94
+ """Arrival Manager's slot proposal — arrivals only."""
95
+
96
+ arrival_slots: List[SlotAssignment] = Field(default_factory=list)
97
+ rationale: str = Field(default="")
98
+ emergency_yields: List[str] = Field(default_factory=list,
99
+ description="Flight IDs yielded for incoming emergencies")
100
+ outgoing_messages: List[NegotiationMessage] = Field(default_factory=list)
101
+ commit: bool = False
102
+
103
+
104
+ class DMANAction(BaseModel):
105
+ """Departure Manager's slot proposal — departures only."""
106
+
107
+ departure_slots: List[SlotAssignment] = Field(default_factory=list)
108
+ rationale: str = Field(default="")
109
+ atfm_compliance: Dict[str, int] = Field(default_factory=dict,
110
+ description="flight_id -> ATFM deadline minute respected")
111
+ emergency_broadcasts: List[str] = Field(default_factory=list,
112
+ description="Fuel/medical emergency departure IDs broadcast to AMAN")
113
+ outgoing_messages: List[NegotiationMessage] = Field(default_factory=list)
114
+ commit: bool = False
115
+
116
+
117
+ # ── Generator actions ─────────────────────────────────────────────────────────
118
+
119
+ class MutationType(str, Enum):
120
+ TIGHTEN_WINDOW = "tighten_window" # narrow earliest/latest window
121
+ INJECT_EMERGENCY = "inject_emergency" # add EMERGENCY/MEDICAL flight
122
+ INCREASE_WEATHER_PENALTY = "increase_weather_penalty" # degrade runway capacity
123
+ ADD_ATFM_DEADLINE = "add_atfm_deadline" # hard network slot constraint
124
+ CLOSE_RUNWAY_WINDOW = "close_runway_window" # runway unavailable T1→T2
125
+ ADD_CONFLICTING_FLIGHT = "add_conflicting_flight" # inject flight that forces wake conflict
126
+
127
+
128
+ class GeneratorMutation(BaseModel):
129
+ mutation_type: MutationType
130
+ target_flight_id: Optional[str] = None
131
+ target_runway_id: Optional[str] = None
132
+ params: Dict[str, Any] = Field(default_factory=dict)
133
+ rationale: str = ""
134
+
135
+
136
+ class GeneratorAction(BaseModel):
137
+ """Self-play generator produces a batch of mutations per episode."""
138
+
139
+ mutations: List[GeneratorMutation] = Field(default_factory=list,
140
+ description="Ordered list of mutations to apply to base task")
141
+ strategy: str = Field(default="",
142
+ description="High-level explanation of how this breaks coordination")
143
+
144
+
145
+ # ── ADAPT agent ───────────────────────────────────────────────────────────────
146
+
147
+ class ADAPTAction(BaseModel):
148
+ """ADAPT's domain-to-ATC parameter mapping output.
149
+
150
+ Maps entity types (stored in FlightRecord.airline) to ATC wake classes and
151
+ priority levels so that AMAN/DMAN can operate on a non-ATC domain unchanged.
152
+ """
153
+
154
+ entity_wake_map: Dict[str, str] = Field(
155
+ ...,
156
+ description="Maps entity type string to WakeClass value: 'H', 'M', or 'L'",
157
+ )
158
+ entity_priority_map: Dict[str, str] = Field(
159
+ ...,
160
+ description=(
161
+ "Maps entity type string to PriorityClass value: "
162
+ "'normal', 'connection', 'medical', or 'emergency'"
163
+ ),
164
+ )
165
+ rationale: str = Field(
166
+ default="",
167
+ description="Explanation of mapping decisions — graded for quality",
168
+ )
169
+
170
+
171
+ class ADAPTObservation(BaseModel):
172
+ """What ADAPT sees: structural signals from the new domain.
173
+
174
+ ADAPT has NO prior domain knowledge. The entity_profiles field exposes
175
+ domain-agnostic statistics so the agent can reason from data, not labels.
176
+ """
177
+
178
+ role: AgentRole = AgentRole.ADAPT
179
+ domain_id: str
180
+ domain_name: str
181
+ domain_description: str
182
+ entity_types: List[str] # unique values from FlightRecord.airline
183
+ resource_names: List[str] # shared resource IDs (beds, berths, runways…)
184
+ sample_entities: str # first 5 entities rendered as readable text
185
+ entity_profiles: Dict[str, Any] = Field(
186
+ default_factory=dict,
187
+ description=(
188
+ "Domain-agnostic structural stats per entity type: "
189
+ "time_pressure, avg_connection_risk, avg_fuel_burn, "
190
+ "avg_passengers, urgency_in_notes, operation_mix."
191
+ ),
192
+ )
193
+ supervisor_profile_name: SupervisorProfileName
194
+ supervisor_description: str
195
+ has_emergencies: bool
196
+ has_hard_deadlines: bool
197
+ entity_count: int
198
+
199
+ def to_prompt_text(self) -> str:
200
+ lines = [
201
+ "=== ADAPT OBSERVATION — Unknown Domain Scheduling Task ===",
202
+ f"Domain identifier: {self.domain_name}",
203
+ f"Task ID: {self.domain_id}",
204
+ "",
205
+ "DOMAIN DESCRIPTION (as provided by the task):",
206
+ self.domain_description,
207
+ "",
208
+ f"SHARED RESOURCES: {', '.join(self.resource_names)}",
209
+ f"Total entities to schedule: {self.entity_count}",
210
+ f"Hard-deadline entities present: {self.has_hard_deadlines}",
211
+ "",
212
+ "ENTITY TYPE STRUCTURAL PROFILES",
213
+ "(All numbers derived from task data — no domain knowledge assumed)",
214
+ "-" * 60,
215
+ ]
216
+
217
+ for et, p in self.entity_profiles.items():
218
+ tp = p.get("time_pressure", 0.0)
219
+ cr = p.get("avg_connection_risk", 0.0)
220
+ ops = p.get("operation_mix", {})
221
+ ops_str = ", ".join(f"{k}={v}" for k, v in ops.items() if v > 0)
222
+
223
+ if tp >= 0.85:
224
+ tp_label = "VERY TIGHT"
225
+ elif tp >= 0.60:
226
+ tp_label = "MODERATE"
227
+ else:
228
+ tp_label = "FLEXIBLE"
229
+
230
+ if cr >= 0.80:
231
+ cr_label = "VERY HIGH"
232
+ elif cr >= 0.50:
233
+ cr_label = "HIGH"
234
+ elif cr >= 0.20:
235
+ cr_label = "MODERATE"
236
+ else:
237
+ cr_label = "LOW"
238
+
239
+ lines += [
240
+ f" {et} ({p.get('count', 0)} entities — {ops_str}):",
241
+ f" time_window : {p.get('avg_window_minutes', 0):.0f} min avg "
242
+ f"[{tp_label}] time_pressure={tp:.3f}",
243
+ f" connection_risk: {cr:.3f} [{cr_label}]",
244
+ f" resource use : {p.get('avg_fuel_burn', 0):.1f} intensity/min "
245
+ f"× {p.get('avg_passengers', 0):.0f} units",
246
+ f" urgency_in_notes: {'YES ⚠' if p.get('urgency_in_notes') else 'no'}",
247
+ "",
248
+ ]
249
+
250
+ n = max(1, len(self.entity_profiles))
251
+ max_emg = 1
252
+ max_heavy = max(1, n // 3)
253
+ max_med = max(1, -(-n // 3)) # ceil
254
+
255
+ lines += [
256
+ "-" * 60,
257
+ f"SUPERVISOR TODAY: {self.supervisor_description}",
258
+ "",
259
+ "PRIORITY DISTRIBUTION BUDGET (hard constraint — starvation prevention):",
260
+ f" emergency : exactly {max_emg} entity type maximum",
261
+ f" H wake : at most {max_heavy} entity type(s)",
262
+ f" medical : at most {max_med} entity type(s) (after emergency is assigned)",
263
+ " Exceeding these budgets causes AMAN to starve DMAN of runway time.",
264
+ " If multiple types qualify for emergency, assign it only to the SINGLE",
265
+ " highest urgency scorer and demote the rest to medical.",
266
+ "",
267
+ "INSTRUCTIONS:",
268
+ "1. You do NOT know what domain this is. Reason from the structural numbers.",
269
+ "2. High time_pressure + high connection_risk → H/emergency mapping.",
270
+ "3. Flexible windows + low risk → L/normal mapping.",
271
+ "4. Enforce the budget above — cite budget slot usage in rationale.",
272
+ "5. Map each entity type to wake_class (H/M/L) and priority "
273
+ "(emergency/medical/connection/normal).",
274
+ "6. Cite the specific numbers in your rationale.",
275
+ ]
276
+ return "\n".join(lines)
277
+
278
+
279
+ # ── Supervisor / Snorkel AI ───────────────────────────────────────────────────
280
+
281
+ class SupervisorProfileName(str, Enum):
282
+ SAFETY_STRICT = "safety_strict"
283
+ THROUGHPUT_MAX = "throughput_max"
284
+ FUEL_PRIORITY = "fuel_priority"
285
+ EMERGENCY_FOCUS = "emergency_focus"
286
+ AIRLINE_FAIRNESS = "airline_fairness"
287
+
288
+
289
+ SUPERVISOR_PROFILES: Dict[str, Dict[str, Any]] = {
290
+ SupervisorProfileName.SAFETY_STRICT: {
291
+ "description": (
292
+ "Zero tolerance for separation conflicts today. Delay is acceptable — "
293
+ "a conflict is not. Prioritize safety margins above all throughput goals."
294
+ ),
295
+ "conflict_weight": 3.0,
296
+ "delay_weight": 0.3,
297
+ "fuel_weight": 0.3,
298
+ "fairness_weight": 0.5,
299
+ "priority_weight": 1.5,
300
+ },
301
+ SupervisorProfileName.THROUGHPUT_MAX: {
302
+ "description": (
303
+ "Pack the runway. I need maximum aircraft-per-hour today. "
304
+ "Minor spacing risks are acceptable; just keep the flow moving."
305
+ ),
306
+ "conflict_weight": 0.8,
307
+ "delay_weight": 1.8,
308
+ "fuel_weight": 0.5,
309
+ "fairness_weight": 0.5,
310
+ "priority_weight": 1.0,
311
+ },
312
+ SupervisorProfileName.FUEL_PRIORITY: {
313
+ "description": (
314
+ "Fuel costs are critical. Every airborne hold is money burning. "
315
+ "Minimize all unnecessary holding — arrivals and departures both."
316
+ ),
317
+ "conflict_weight": 1.2,
318
+ "delay_weight": 0.6,
319
+ "fuel_weight": 2.5,
320
+ "fairness_weight": 0.5,
321
+ "priority_weight": 1.0,
322
+ },
323
+ SupervisorProfileName.EMERGENCY_FOCUS: {
324
+ "description": (
325
+ "Medical and emergency flights are the only thing that matters today. "
326
+ "Everything else waits if needed. No emergency flight may be delayed."
327
+ ),
328
+ "conflict_weight": 1.5,
329
+ "delay_weight": 0.4,
330
+ "fuel_weight": 0.4,
331
+ "fairness_weight": 0.3,
332
+ "priority_weight": 3.5,
333
+ },
334
+ SupervisorProfileName.AIRLINE_FAIRNESS: {
335
+ "description": (
336
+ "All airlines must be treated equally today. I don't care if IndiGo "
337
+ "is bigger — fairness across carriers is the metric I'm watching."
338
+ ),
339
+ "conflict_weight": 1.2,
340
+ "delay_weight": 0.8,
341
+ "fuel_weight": 0.8,
342
+ "fairness_weight": 2.5,
343
+ "priority_weight": 1.0,
344
+ },
345
+ }
346
+
347
+
348
+ # ── Round / episode state ─────────────────────────────────────────────────────
349
+
350
+ class RoundType(str, Enum):
351
+ BID = "bid" # Round 0: independent proposals
352
+ NEGOTIATE = "negotiate" # Round 1: conflict resolution
353
+ FINAL = "final" # Round 2: commit and grade
354
+
355
+
356
+ class MultiAgentObservation(BaseModel):
357
+ """Role-specific observation injected into the LLM system prompt."""
358
+
359
+ task_id: str
360
+ airport: str
361
+ briefing: str
362
+ role: AgentRole
363
+ my_flights: List[FlightRecord] # filtered to agent's operation type
364
+ all_runways: List[RunwaySpec]
365
+ supervisor_profile_name: SupervisorProfileName
366
+ supervisor_description: str
367
+ atfm_deadlines: Dict[str, int] = Field(default_factory=dict,
368
+ description="flight_id -> hard deadline minute from ATFM")
369
+ incoming_messages: List[NegotiationMessage] = Field(default_factory=list)
370
+ conflict_log: List[str] = Field(default_factory=list)
371
+ current_metrics: Optional[TaskMetrics] = None
372
+ steps_remaining: int = 0
373
+ round_type: RoundType = RoundType.BID
374
+ round_number: int = 0
375
+ reward: Optional[float] = None
376
+ done: bool = False
377
+
378
+ def to_prompt_text(self) -> str:
379
+ """Render observation as structured text for LLM input."""
380
+ prof = SUPERVISOR_PROFILES[self.supervisor_profile_name]
381
+ weight_str = (
382
+ f"conflict={prof['conflict_weight']:.1f}x "
383
+ f"delay={prof['delay_weight']:.1f}x "
384
+ f"fuel={prof['fuel_weight']:.1f}x "
385
+ f"fairness={prof['fairness_weight']:.1f}x "
386
+ f"priority={prof['priority_weight']:.1f}x"
387
+ )
388
+ lines = [
389
+ f"=== {self.role.value} OBSERVATION — {self.airport} ===",
390
+ f"Task: {self.task_id}",
391
+ f"Round: {self.round_type.value.upper()} ({self.round_number}/2)",
392
+ f"Steps remaining: {self.steps_remaining}",
393
+ "",
394
+ f"SUPERVISOR TODAY: {self.supervisor_description}",
395
+ f"SUPERVISOR WEIGHTS: {weight_str}",
396
+ "",
397
+ ]
398
+
399
+ if self.atfm_deadlines:
400
+ lines.append("ATFM HARD DEADLINES (network slots — cannot miss):")
401
+ for fid, minute in self.atfm_deadlines.items():
402
+ lines.append(f" {fid}: depart/land by minute {minute}")
403
+ lines.append("")
404
+
405
+ lines.append(f"YOUR FLIGHTS ({len(self.my_flights)} total):")
406
+ for f in self.my_flights:
407
+ lines.append(
408
+ f" {f.flight_id} | {f.airline} | {f.operation.value.upper()} | "
409
+ f"wake={f.wake_class.value} | priority={f.priority.value} | "
410
+ f"window=[{f.earliest_minute},{f.latest_minute}] | "
411
+ f"scheduled={f.scheduled_minute} | pax={f.passengers} | "
412
+ f"burn={f.fuel_burn_per_minute}/min | runways={f.allowed_runways}"
413
+ + (f" | NOTE: {f.notes}" if f.notes else "")
414
+ )
415
+
416
+ lines.append("")
417
+ lines.append("RUNWAYS:")
418
+ for rwy in self.all_runways:
419
+ ops = "/".join(o.value for o in rwy.allowed_operations)
420
+ lines.append(
421
+ f" {rwy.runway_id}: {ops} | capacity={rwy.hourly_capacity}/hr | "
422
+ f"weather_penalty={rwy.weather_penalty}x"
423
+ + (f" | {rwy.notes}" if rwy.notes else "")
424
+ )
425
+
426
+ if self.incoming_messages:
427
+ lines.append("")
428
+ lines.append("MESSAGES FROM OTHER AGENT:")
429
+ for msg in self.incoming_messages:
430
+ tag = " [EMERGENCY]" if msg.is_emergency else ""
431
+ conf_str = f" conf={msg.confidence:.1f}" if msg.confidence < 1.0 else ""
432
+ lines.append(
433
+ f" [{msg.from_role.value} → {msg.message_type.value}]{tag}{conf_str} "
434
+ f"{msg.flight_id} @ runway {msg.runway_id} T+{msg.requested_minute} "
435
+ f"({msg.priority.value}): {msg.reason}"
436
+ )
437
+ if msg.content:
438
+ lines.append(f" Detail: {msg.content}")
439
+ if msg.theory_of_mind_claim:
440
+ lines.append(f" Prediction: {msg.theory_of_mind_claim}")
441
+ if msg.proposed_alternatives:
442
+ alts = ", ".join(
443
+ f"{a.flight_id}@{a.runway_id}+{a.minute}min(cost={a.delay_cost:.0f})"
444
+ for a in msg.proposed_alternatives
445
+ )
446
+ lines.append(f" Alternatives offered: {alts}")
447
+
448
+ if self.conflict_log:
449
+ lines.append("")
450
+ lines.append("CONFLICTS DETECTED (must resolve):")
451
+ for c in self.conflict_log:
452
+ lines.append(f" ⚠ {c}")
453
+
454
+ if self.current_metrics:
455
+ lines.append("")
456
+ lines.append(
457
+ f"LAST SCORE: {self.current_metrics.overall_score:.3f} | "
458
+ f"conflicts={self.current_metrics.conflict_count} | "
459
+ f"delay={self.current_metrics.total_delay_minutes}min"
460
+ )
461
+
462
+ return "\n".join(lines)
463
+
464
+
465
+ # ── Per-role metrics ──────────────────────────────────────────────────────────
466
+
467
+ class PerRoleMetrics(BaseModel):
468
+ """Metrics decomposed by AMAN / DMAN responsibility."""
469
+
470
+ # AMAN
471
+ arrival_count: int = 0
472
+ arrival_delay_total: int = 0
473
+ arrival_delay_mean: float = 0.0
474
+ arrivals_missing: int = 0
475
+ emergency_arrivals_ok: int = 0
476
+ emergency_arrivals_missed: int = 0
477
+
478
+ # DMAN
479
+ departure_count: int = 0
480
+ departure_delay_total: int = 0
481
+ departure_delay_mean: float = 0.0
482
+ departures_missing: int = 0
483
+ atfm_violations: int = 0
484
+ atfm_compliant: int = 0
485
+ emergency_departures_ok: int = 0
486
+ emergency_departures_missed: int = 0
487
+
488
+ # Cross-agent
489
+ cross_lane_conflicts: int = 0 # conflicts between AMAN and DMAN slots
490
+ intra_lane_conflicts: int = 0 # conflicts within one agent's slots
491
+ negotiation_rounds_used: int = 0
492
+ coordination_score: float = 0.0 # 0→1 quality of negotiation
493
+
494
+
495
+ # ── Episode result ────────────────────────────────────────────────────────────
496
+
497
+ class MultiAgentEpisodeResult(BaseModel):
498
+ """Full episode result used by training loop."""
499
+
500
+ task_id: str
501
+ supervisor_profile: SupervisorProfileName
502
+ composite_score: float
503
+ aman_reward: float
504
+ dman_reward: float
505
+ generator_reward: float
506
+ supervisor_score: float
507
+ per_role: PerRoleMetrics
508
+ negotiation_rounds: int
509
+ scenario_solvable: bool = True
multi_agent/supervisor.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Snorkel AI Simulated Expert Supervisor.
2
+
3
+ Each episode the supervisor draws a preference profile (safety / throughput /
4
+ fuel / emergency / fairness). The LLM agents must read the stated preference
5
+ and optimise toward it — training theory-of-mind and instruction-following
6
+ simultaneously.
7
+
8
+ Supervisor reward is independent of the composite grader and is used only
9
+ for the supervisor-alignment component of per-agent rewards.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Dict, List
15
+
16
+ try:
17
+ from ..engine import simulate_plan, SimulationOutcome
18
+ from ..models import OperationType, PriorityClass, TaskDefinition
19
+ from .models import (
20
+ SUPERVISOR_PROFILES,
21
+ PerRoleMetrics,
22
+ SupervisorProfileName,
23
+ )
24
+ except ImportError:
25
+ from engine import simulate_plan, SimulationOutcome
26
+ from models import OperationType, PriorityClass, TaskDefinition
27
+ from multi_agent.models import (
28
+ SUPERVISOR_PROFILES,
29
+ PerRoleMetrics,
30
+ SupervisorProfileName,
31
+ )
32
+
33
+
34
+ _PROFILE_CYCLE: List[SupervisorProfileName] = list(SupervisorProfileName)
35
+
36
+
37
+ class SupervisorAgent:
38
+ """Simulates a real ATC supervisor with episodically changing preferences.
39
+
40
+ Key behaviours:
41
+ - Deterministic profile rotation (reproducible training runs)
42
+ - Profile-weighted scoring replaces fixed SCORE_WEIGHTS for this episode
43
+ - Natural language description injected into every agent's system prompt
44
+ - Supervisor score returned as auxiliary signal (not part of composite)
45
+ """
46
+
47
+ def sample_profile(self, episode_id: int) -> SupervisorProfileName:
48
+ """Deterministic round-robin through profiles for reproducibility."""
49
+ return _PROFILE_CYCLE[episode_id % len(_PROFILE_CYCLE)]
50
+
51
+ def get_description(self, profile_name: SupervisorProfileName) -> str:
52
+ return SUPERVISOR_PROFILES[profile_name]["description"]
53
+
54
+ def score_plan(
55
+ self,
56
+ outcome: SimulationOutcome,
57
+ task: TaskDefinition,
58
+ profile_name: SupervisorProfileName,
59
+ ) -> float:
60
+ """Score final plan against supervisor's current preference profile.
61
+
62
+ Uses profile weight overrides applied to the raw simulation metrics.
63
+ Returns normalised score in [0, 1].
64
+ """
65
+ profile = SUPERVISOR_PROFILES[profile_name]
66
+ metrics = outcome.metrics
67
+
68
+ w_conflict = profile.get("conflict_weight", 1.0)
69
+ w_delay = profile.get("delay_weight", 1.0)
70
+ w_fuel = profile.get("fuel_weight", 1.0)
71
+ w_fairness = profile.get("fairness_weight", 1.0)
72
+ w_priority = profile.get("priority_weight", 1.0)
73
+
74
+ total_w = w_conflict + w_delay + w_fuel + w_fairness + w_priority
75
+
76
+ raw = (
77
+ w_conflict * metrics.conflict_free_ratio
78
+ + w_delay * metrics.delay_efficiency
79
+ + w_fuel * metrics.fuel_efficiency
80
+ + w_fairness * metrics.fairness
81
+ + w_priority * metrics.priority_handling
82
+ ) / total_w
83
+
84
+ # Emergency focus profile: hard penalty if any emergency missed
85
+ if profile_name == SupervisorProfileName.EMERGENCY_FOCUS:
86
+ if metrics.emergency_violations > 0 or metrics.medical_violations > 0:
87
+ raw *= 0.3 # severe penalty — supervisor is watching emergency flights only
88
+
89
+ # Safety strict: any conflict = cap at 0.4
90
+ if profile_name == SupervisorProfileName.SAFETY_STRICT:
91
+ if metrics.conflict_count > 0:
92
+ raw = min(raw, 0.4)
93
+
94
+ return round(max(0.0, min(1.0, raw)), 4)
95
+
96
+ def build_system_suffix(self, profile_name: SupervisorProfileName) -> str:
97
+ """Extra system prompt text reminding agent of supervisor preference."""
98
+ desc = self.get_description(profile_name)
99
+ return (
100
+ f"\n\nSUPERVISOR PREFERENCE THIS EPISODE:\n"
101
+ f" {desc}\n"
102
+ f"Your plan will be scored against this preference. "
103
+ f"Explicitly state in your rationale how you are satisfying it."
104
+ )
multi_agent/visual_events.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Normalized visual events for HF Space pixel-art UI (SSE / transcripts).
2
+
3
+ Keep payloads bounded: no prompts, only layout + scores + phase markers.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any, Callable, Dict, List, Literal, Optional
9
+
10
+ from models import FlightRecord, TaskDefinition
11
+ from multi_agent.models import AMANAction, DMANAction
12
+
13
+ VisualSink = Optional[Callable[[Dict[str, Any]], None]]
14
+
15
+ TerminalSeverity = Literal["success", "degraded", "catastrophic"]
16
+
17
+
18
+ def emit(sink: VisualSink, event: Dict[str, Any]) -> None:
19
+ if sink is not None:
20
+ sink(dict(event))
21
+
22
+
23
+ def _slot_row(s) -> Dict[str, Any]:
24
+ return {
25
+ "flight_id": s.flight_id,
26
+ "runway": s.runway,
27
+ "assigned_minute": int(s.assigned_minute),
28
+ "hold_minutes": int(s.hold_minutes),
29
+ }
30
+
31
+
32
+ def serialize_action_layout(aman: AMANAction, dman: DMANAction) -> Dict[str, Any]:
33
+ return {
34
+ "aman_arrivals": [_slot_row(s) for s in aman.arrival_slots],
35
+ "dman_departures": [_slot_row(s) for s in dman.departure_slots],
36
+ }
37
+
38
+
39
+ def _flight_minimal(f: FlightRecord) -> Dict[str, Any]:
40
+ return {
41
+ "flight_id": f.flight_id,
42
+ "operation": f.operation.value if hasattr(f.operation, "value") else str(f.operation),
43
+ "wake": f.wake_class.value if hasattr(f.wake_class, "value") else str(f.wake_class),
44
+ "scheduled": int(f.scheduled_minute),
45
+ "earliest": int(f.earliest_minute),
46
+ "latest": int(f.latest_minute),
47
+ "runways": list(f.allowed_runways),
48
+ "priority": f.priority.value if hasattr(f.priority, "value") else str(f.priority),
49
+ }
50
+
51
+
52
+ def serialize_task_snapshot(task: TaskDefinition) -> Dict[str, Any]:
53
+ return {
54
+ "task_id": task.task_id,
55
+ "airport": getattr(task, "airport", None) or task.task_id,
56
+ "runways": [
57
+ {
58
+ "runway_id": r.runway_id,
59
+ "ops": [o.value for o in r.allowed_operations],
60
+ }
61
+ for r in task.runways
62
+ ],
63
+ "flights": [_flight_minimal(f) for f in task.flights],
64
+ }
65
+
66
+
67
+ def classify_terminal(
68
+ composite: float,
69
+ cross_lane_conflicts: int,
70
+ atfm_violations: int,
71
+ ) -> TerminalSeverity:
72
+ """Single policy for catastrophic vs degraded (shared UI animation)."""
73
+ if composite < 0.12 or (composite < 0.22 and cross_lane_conflicts >= 6):
74
+ return "catastrophic"
75
+ if composite < 0.45 or cross_lane_conflicts >= 3 or atfm_violations >= 2:
76
+ return "degraded"
77
+ return "success"
78
+
79
+
80
+ def terminal_event(
81
+ *,
82
+ composite: float,
83
+ aman_reward: float,
84
+ dman_reward: float,
85
+ coordination: float,
86
+ cross_lane_conflicts: int,
87
+ atfm_violations: int,
88
+ negotiation_rounds: int,
89
+ ) -> Dict[str, Any]:
90
+ sev = classify_terminal(composite, cross_lane_conflicts, atfm_violations)
91
+ return {
92
+ "type": "terminal",
93
+ "severity": sev,
94
+ "composite": round(float(composite), 4),
95
+ "aman_reward": round(float(aman_reward), 4),
96
+ "dman_reward": round(float(dman_reward), 4),
97
+ "coordination": round(float(coordination), 4),
98
+ "cross_lane_conflicts": int(cross_lane_conflicts),
99
+ "atfm_violations": int(atfm_violations),
100
+ "negotiation_rounds": int(negotiation_rounds),
101
+ }
openenv.yaml ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: atc_env
3
+ version: 3.0.0
4
+ description: >
5
+ Multi-agent RLVE benchmark for air traffic control disruption recovery.
6
+ AMAN and DMAN controllers coordinate via a 3-round BID/NEGOTIATE/FINAL
7
+ protocol over shared runways. An adversarial ChallengeGenerator applies
8
+ EMA-based curriculum mutation. A SupervisorAgent with 5 rotating preference
9
+ profiles (safety / throughput / fuel / emergency / fairness) provides
10
+ grounded dense reward. Trained with GRPO + Unsloth 4-bit QLoRA on Colab T4.
11
+ type: space
12
+ runtime: fastapi
13
+ app: server.app:app
14
+ port: 8000
15
+ tags:
16
+ - openenv
17
+ - air-traffic-control
18
+ - multi-agent
19
+ - rlve
20
+ - grpo
21
+ - cooperative-competitive
22
+ - self-play
23
+ - aman
24
+ - dman
25
+ - curriculum-learning
26
+
27
+ # ── Primary interface (OpenEnv-compliant) ─────────────────────────────────────
28
+ action_space: atc_env.models:ATCAction
29
+ observation_space: atc_env.models:ATCObservation
30
+ state_space: atc_env.models:ATCState
31
+
32
+ # ── Multi-agent configuration ─────────────────────────────────────────────────
33
+ multi_agent:
34
+ enabled: true
35
+ mode: cooperative_competitive
36
+ agents:
37
+ - role: AMAN
38
+ description: Arrival Manager — sequences inbound flights, manages wake turbulence separation
39
+ action_space: multi_agent.models:AMANAction
40
+ observation_space: multi_agent.models:MultiAgentObservation
41
+ - role: DMAN
42
+ description: Departure Manager — schedules outbound flights, enforces ATFM network slots
43
+ action_space: multi_agent.models:DMANAction
44
+ observation_space: multi_agent.models:MultiAgentObservation
45
+ - role: GENERATOR
46
+ description: Adversarial self-play agent — mutates tasks via EMA curriculum to challenge controllers
47
+ action_space: multi_agent.models:GeneratorAction
48
+ observation_space: multi_agent.models:MultiAgentObservation
49
+ - role: SUPERVISOR
50
+ description: >
51
+ Expert with rotating preference profiles (safety_strict / throughput_max /
52
+ fuel_economy / emergency_priority / fairness_balanced)
53
+ action_space: null
54
+ observation_space: multi_agent.models:MultiAgentObservation
55
+ negotiation_rounds: 3
56
+ protocol: BID -> NEGOTIATE -> FINAL
57
+ shared_runways: true
58
+ emergency_broadcast: true
59
+
60
+ # ── Reward design ─────────────────────────────────────────────────────────────
61
+ reward:
62
+ type: potential_based_shaping # Ng et al. 1999 — preserves optimal policy
63
+ roles:
64
+ AMAN:
65
+ components: [delay_efficiency, emergency_score, coverage, counterfactual_advantage,
66
+ theory_of_mind_bonus, supervisor_alignment, rationale_quality, json_format]
67
+ hard_gates:
68
+ conflict_free: {cap: 0.30, condition: "conflict_count > 0"}
69
+ emergency: {cap: 0.40, condition: "emg_miss > 0"}
70
+ coverage_floor: {penalty: -0.30, condition: "coverage < 0.50"}
71
+ DMAN:
72
+ components: [delay_efficiency, atfm_compliance, emergency_score, coverage,
73
+ counterfactual_advantage, theory_of_mind_bonus, supervisor_alignment,
74
+ rationale_quality, json_format]
75
+ hard_gates:
76
+ conflict_free: {cap: 0.30, condition: "conflict_count > 0"}
77
+ emergency: {cap: 0.40, condition: "emg_miss > 0"}
78
+ coverage_floor: {penalty: -0.30, condition: "coverage < 0.50"}
79
+ GENERATOR:
80
+ components: [challenge_score, solvability_bonus]
81
+ SUPERVISOR:
82
+ components: [preference_alignment, calibration_bonus]
83
+
84
+ # ── Graders ───────────────────────────────────────────────────────────────────
85
+ graders:
86
+ primary:
87
+ - module: graders:MultiAgentCoordinationGrader
88
+ weight: 0.40
89
+ - module: graders:GatedCompositeGrader
90
+ weight: 0.45
91
+ - module: graders:LLMSupervisorGrader
92
+ weight: 0.15
93
+
94
+ # ── Tasks ─────────────────────────────────────────────────────────────────────
95
+ tasks:
96
+ - id: delhi_monsoon_recovery_easy
97
+ difficulty: easy
98
+ description: Delhi IGI airport, monsoon season, 12 flights, VVIP slot constraint
99
+ grader:
100
+ type: programmatic
101
+ module: graders:GatedCompositeGrader
102
+ multi_agent_grader:
103
+ module: graders:grade_multi_agent
104
+ max_steps: 10
105
+ multi_agent_max_rounds: 3
106
+
107
+ - id: mumbai_bank_balance_medium
108
+ difficulty: medium
109
+ description: Mumbai CSIA, runway bank sequence, mixed cargo/passenger, 15 flights
110
+ grader:
111
+ type: programmatic
112
+ module: graders:GatedCompositeGrader
113
+ multi_agent_grader:
114
+ module: graders:grade_multi_agent
115
+ max_steps: 14
116
+ multi_agent_max_rounds: 3
117
+
118
+ - id: bengaluru_irrops_hard
119
+ difficulty: hard
120
+ description: >
121
+ Bengaluru KIA, dual-runway IRROPS (09L/09R), emergency MED001 arrival +
122
+ MED208 medical departure, ATFM constraints, 18 flights
123
+ grader:
124
+ type: programmatic
125
+ module: graders:GatedCompositeGrader
126
+ multi_agent_grader:
127
+ module: graders:grade_multi_agent
128
+ max_steps: 18
129
+ multi_agent_max_rounds: 3
130
+
131
+ - id: hyderabad_cargo_crunch_medium_hard
132
+ difficulty: hard
133
+ description: Hyderabad RGIA, cargo priority, peak hour crunch, 20 flights
134
+ grader:
135
+ type: programmatic
136
+ module: graders:GatedCompositeGrader
137
+ multi_agent_grader:
138
+ module: graders:grade_multi_agent
139
+ max_steps: 20
140
+ multi_agent_max_rounds: 3
141
+
142
+ # ── Training ──────────────────────────────────────────────────────────────────
143
+ training:
144
+ algorithm: GRPO
145
+ n_generations: 4
146
+ kl_coeff: 0.01
147
+ framework: unsloth + trl
148
+ base_model: Qwen/Qwen2.5-7B-Instruct
149
+ colab_compatible: true
150
+ vram_requirement: 16GB
151
+ lora_rank: 16
152
+ script: training/train_grpo.py
153
+ reward_functions: training/reward_functions.py
planner.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic baseline planner used by inference and tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from typing import Dict, List, Tuple
7
+
8
+ try:
9
+ from .engine import SimulationOutcome, simulate_plan
10
+ from .models import (
11
+ ATCOptimizationObservation,
12
+ FlightRecord,
13
+ PriorityClass,
14
+ RunwaySpec,
15
+ SlotAssignment,
16
+ )
17
+ from .constants import SEPARATION_BY_WAKE
18
+ from .tasks import task_catalog
19
+ except ImportError:
20
+ from engine import SimulationOutcome, simulate_plan
21
+ from models import (
22
+ ATCOptimizationObservation,
23
+ FlightRecord,
24
+ PriorityClass,
25
+ RunwaySpec,
26
+ SlotAssignment,
27
+ )
28
+ from constants import SEPARATION_BY_WAKE
29
+ from tasks import task_catalog
30
+
31
+ PRIORITY_RANK = {
32
+ PriorityClass.EMERGENCY: 0,
33
+ PriorityClass.MEDICAL: 1,
34
+ PriorityClass.CONNECTION: 2,
35
+ PriorityClass.NORMAL: 3,
36
+ }
37
+
38
+
39
+ def _capacity_spacing(runway: RunwaySpec) -> int:
40
+ base_gap = max(2, round(60 / runway.hourly_capacity))
41
+ return max(2, round(base_gap * runway.weather_penalty))
42
+
43
+
44
+ def _flight_sort_key(flight: FlightRecord) -> Tuple[int, int, int, float, int]:
45
+ return (
46
+ PRIORITY_RANK[flight.priority],
47
+ flight.scheduled_minute,
48
+ 0 if flight.operation.value == "arrival" else 1,
49
+ -flight.connection_risk,
50
+ -flight.passengers,
51
+ )
52
+
53
+
54
+ def _outcome_key(outcome: SimulationOutcome) -> Tuple[float, float, float, float, float, float]:
55
+ metrics = outcome.metrics
56
+ return (
57
+ metrics.overall_score,
58
+ metrics.priority_handling,
59
+ metrics.conflict_free_ratio,
60
+ metrics.fairness,
61
+ metrics.delay_efficiency,
62
+ -float(metrics.total_delay_minutes),
63
+ )
64
+
65
+
66
+ def build_heuristic_plan(observation: ATCOptimizationObservation) -> List[SlotAssignment]:
67
+ """Create a safe, deterministic seed schedule."""
68
+
69
+ runway_lookup = {runway.runway_id: runway for runway in observation.runways}
70
+ runway_state: Dict[str, Tuple[int, str]] = {
71
+ runway.runway_id: (-999, "M") for runway in observation.runways
72
+ }
73
+ airline_delay_totals: Dict[str, List[int]] = defaultdict(list)
74
+
75
+ assignments: List[SlotAssignment] = []
76
+ for flight in sorted(observation.flights, key=_flight_sort_key):
77
+ best_choice: Tuple[float, str, int] | None = None
78
+ for runway_id in flight.allowed_runways:
79
+ runway = runway_lookup[runway_id]
80
+ last_minute, last_wake = runway_state[runway_id]
81
+ gap = max(
82
+ _capacity_spacing(runway),
83
+ SEPARATION_BY_WAKE[(last_wake, flight.wake_class.value)],
84
+ )
85
+ earliest_safe = max(flight.earliest_minute, last_minute + gap, flight.scheduled_minute)
86
+ candidate_time = min(max(earliest_safe, flight.earliest_minute), flight.latest_minute)
87
+ delay = abs(candidate_time - flight.scheduled_minute)
88
+ airline_avg_delay = (
89
+ sum(airline_delay_totals[flight.airline]) / len(airline_delay_totals[flight.airline])
90
+ if airline_delay_totals[flight.airline]
91
+ else 0.0
92
+ )
93
+ objective = (
94
+ delay
95
+ + 6 * PRIORITY_RANK[flight.priority]
96
+ + 12 * flight.connection_risk
97
+ + 0.25 * airline_avg_delay
98
+ + (3 if runway_id.endswith("L") and flight.priority == PriorityClass.NORMAL else 0)
99
+ )
100
+ candidate = (objective, runway_id, candidate_time)
101
+ if best_choice is None or candidate < best_choice:
102
+ best_choice = candidate
103
+
104
+ assert best_choice is not None
105
+ _, chosen_runway, chosen_time = best_choice
106
+ assignments.append(
107
+ SlotAssignment(
108
+ flight_id=flight.flight_id,
109
+ runway=chosen_runway,
110
+ assigned_minute=chosen_time,
111
+ hold_minutes=max(0, chosen_time - flight.scheduled_minute),
112
+ )
113
+ )
114
+ airline_delay_totals[flight.airline].append(abs(chosen_time - flight.scheduled_minute))
115
+ runway_state[chosen_runway] = (chosen_time, flight.wake_class.value)
116
+
117
+ assignments.sort(key=lambda item: item.assigned_minute)
118
+ return assignments
119
+
120
+
121
+ def build_refined_plan(
122
+ observation: ATCOptimizationObservation,
123
+ seed_plan: List[SlotAssignment] | None = None,
124
+ max_passes: int = 2,
125
+ ) -> List[SlotAssignment]:
126
+ """Greedily improve the seed plan using the deterministic simulator."""
127
+
128
+ task = task_catalog().get(observation.task_id)
129
+ if task is None:
130
+ return seed_plan or build_heuristic_plan(observation)
131
+
132
+ ordered_flights = sorted(observation.flights, key=_flight_sort_key)
133
+ ordered_ids = [flight.flight_id for flight in ordered_flights]
134
+ current_plan = list(seed_plan) if seed_plan is not None else build_heuristic_plan(observation)
135
+ assignment_map = {assignment.flight_id: assignment for assignment in current_plan}
136
+
137
+ for flight in ordered_flights:
138
+ assignment_map.setdefault(
139
+ flight.flight_id,
140
+ SlotAssignment(
141
+ flight_id=flight.flight_id,
142
+ runway=flight.allowed_runways[0],
143
+ assigned_minute=flight.scheduled_minute,
144
+ hold_minutes=0,
145
+ ),
146
+ )
147
+
148
+ best_plan = [assignment_map[flight_id] for flight_id in ordered_ids]
149
+ best_outcome = simulate_plan(task, best_plan)
150
+
151
+ for _ in range(max_passes):
152
+ improved = False
153
+ for flight in ordered_flights:
154
+ current_assignment = assignment_map[flight.flight_id]
155
+ best_local_assignment = current_assignment
156
+ for runway_id in flight.allowed_runways:
157
+ for minute in range(flight.earliest_minute, flight.latest_minute + 1):
158
+ if (
159
+ runway_id == current_assignment.runway
160
+ and minute == current_assignment.assigned_minute
161
+ ):
162
+ continue
163
+ candidate_assignment = SlotAssignment(
164
+ flight_id=flight.flight_id,
165
+ runway=runway_id,
166
+ assigned_minute=minute,
167
+ hold_minutes=max(0, minute - flight.scheduled_minute),
168
+ )
169
+ assignment_map[flight.flight_id] = candidate_assignment
170
+ candidate_plan = [assignment_map[item_id] for item_id in ordered_ids]
171
+ candidate_outcome = simulate_plan(task, candidate_plan)
172
+ if _outcome_key(candidate_outcome) > _outcome_key(best_outcome):
173
+ best_outcome = candidate_outcome
174
+ best_local_assignment = candidate_assignment
175
+ improved = True
176
+ assignment_map[flight.flight_id] = best_local_assignment
177
+
178
+ assignment_map[flight.flight_id] = best_local_assignment
179
+ best_plan = [assignment_map[item_id] for item_id in ordered_ids]
180
+
181
+ if not improved:
182
+ break
183
+
184
+ best_plan.sort(key=lambda item: (item.assigned_minute, item.flight_id))
185
+ return best_plan
pyproject.toml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "openenv-atc-optimization"
7
+ version = "1.0.0"
8
+ description = "OpenEnv benchmark for realistic air traffic control disruption recovery"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = [
12
+ "fastapi>=0.128.0",
13
+ "openai>=2.30.0",
14
+ "openenv-core[core]>=0.2.3",
15
+ "pydantic>=2.12.0",
16
+ "uvicorn>=0.41.0",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ dev = [
21
+ "pytest>=8.4.0",
22
+ "requests>=2.33.0",
23
+ ]
24
+ training = [
25
+ "trl>=0.9.6",
26
+ "datasets>=2.20.0",
27
+ "transformers>=4.43.0",
28
+ "torch>=2.3.0",
29
+ "accelerate>=0.32.0",
30
+ "bitsandbytes>=0.43.0",
31
+ "peft>=0.12.0",
32
+ "matplotlib>=3.9.0",
33
+ "numpy>=1.26.0",
34
+ ]
35
+ training-unsloth = [
36
+ "unsloth[colab-new]>=2024.8",
37
+ "trl>=0.9.6",
38
+ "datasets>=2.20.0",
39
+ "matplotlib>=3.9.0",
40
+ "numpy>=1.26.0",
41
+ ]
42
+
43
+ [project.scripts]
44
+ server = "atc_env.server.app:main"
45
+ atc-train = "training.train_grpo:main"
46
+ atc-train-sft = "training.train_sft:main"
47
+ atc-build-sft-data = "training.build_sft_dataset:main"
48
+ atc-eval = "training.eval:main"
49
+ atc-plot = "training.plot_rewards:main"
50
+ atc-hf-train = "training.hf_train:main"
51
+
52
+ [tool.setuptools.packages.find]
53
+ where = ["."]
54
+ include = ["atc_env*", "multi_agent*", "domains*", "training*", "server*"]
results/benchmark_scores.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "NOTE": "Measured by running the repo's inference code path on 2026-04-08 with model=heuristic-baseline.",
3
+ "run_date": "2026-04-08",
4
+ "model": "heuristic-baseline",
5
+ "tasks": {
6
+ "delhi_monsoon_recovery_easy": {
7
+ "random_baseline": 0.21,
8
+ "our_agent": 0.9446,
9
+ "steps_used": 3
10
+ },
11
+ "mumbai_bank_balance_medium": {
12
+ "random_baseline": 0.18,
13
+ "our_agent": 0.99,
14
+ "steps_used": 2
15
+ },
16
+ "bengaluru_irrops_hard": {
17
+ "random_baseline": 0.12,
18
+ "our_agent": 0.8615,
19
+ "steps_used": 4
20
+ },
21
+ "hyderabad_cargo_crunch_medium_hard": {
22
+ "random_baseline": 0.15,
23
+ "our_agent": 0.8576,
24
+ "steps_used": 3
25
+ }
26
+ },
27
+ "average_agent_score": 0.9134,
28
+ "average_random_baseline": 0.165,
29
+ "total_runtime_seconds": 11.69,
30
+ "hardware": "2 vCPU / 8 GB RAM (spec limit)"
31
+ }
scripts/benchmark_results/.gitkeep ADDED
File without changes
scripts/benchmark_results/fixed_icu/episode_00000.json ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "episode_id": 0,
3
+ "domain_task_id": "icu_mass_casualty",
4
+ "mode": "adapt_domain_transfer",
5
+ "supervisor_profile": "safety_strict",
6
+ "adapt_wake_map": {
7
+ "TRAUMA": "H",
8
+ "CARDIAC": "M",
9
+ "POST_OP": "M",
10
+ "ROUTINE": "L"
11
+ },
12
+ "adapt_priority_map": {
13
+ "TRAUMA": "emergency",
14
+ "CARDIAC": "medical",
15
+ "POST_OP": "medical",
16
+ "ROUTINE": "connection"
17
+ },
18
+ "adapt_rationale": "Structural budget-enforced inference (budget: emergency\u22641 heavy\u22641 medical\u22642): TRAUMA: tp=0.98 cr=0.93 score=0.96 \u2192 wake=H priority=emergency; CARDIAC: tp=0.85 cr=0.64 score=0.78 \u2192 wake=M (budget-demoted) priority=medical; POST_OP: tp=0.96 cr=0.00 score=0.58 \u2192 wake=M priority=medical (budget-demoted); ROUTINE: tp=0.68 cr=0.00 score=0.34 \u2192 wake=L priority=connection",
19
+ "visual_log": [
20
+ {
21
+ "type": "adapt_scene",
22
+ "domain_task_id": "icu_mass_casualty",
23
+ "visual_profile": "icu",
24
+ "entity_types": [
25
+ "CARDIAC",
26
+ "POST_OP",
27
+ "ROUTINE",
28
+ "TRAUMA"
29
+ ]
30
+ },
31
+ {
32
+ "type": "adapt_mapping",
33
+ "wake_map": {
34
+ "TRAUMA": "H",
35
+ "CARDIAC": "M",
36
+ "POST_OP": "M",
37
+ "ROUTINE": "L"
38
+ },
39
+ "priority_map": {
40
+ "TRAUMA": "emergency",
41
+ "CARDIAC": "medical",
42
+ "POST_OP": "medical",
43
+ "ROUTINE": "connection"
44
+ },
45
+ "rationale_preview": "Structural budget-enforced inference (budget: emergency\u22641 heavy\u22641 medical\u22642): TRAUMA: tp=0.98 cr=0.93 score=0.96 \u2192 wake=H priority=emergency; CARDIAC: tp=0.85 cr=0.64 score=0.78 \u2192 wake=M (budget-demot"
46
+ },
47
+ {
48
+ "type": "scene_reset",
49
+ "episode_id": 0,
50
+ "task_id": "icu_mass_casualty",
51
+ "resolved_task_id": "icu_mass_casualty",
52
+ "visual_profile": "icu",
53
+ "supervisor_profile": "safety_strict",
54
+ "mutations_applied": [],
55
+ "task": {
56
+ "task_id": "icu_mass_casualty",
57
+ "airport": "GENERAL_HOSPITAL_ICU",
58
+ "runways": [
59
+ {
60
+ "runway_id": "BED_A",
61
+ "ops": [
62
+ "arrival",
63
+ "departure"
64
+ ]
65
+ },
66
+ {
67
+ "runway_id": "BED_B",
68
+ "ops": [
69
+ "arrival",
70
+ "departure"
71
+ ]
72
+ },
73
+ {
74
+ "runway_id": "BED_C",
75
+ "ops": [
76
+ "arrival",
77
+ "departure"
78
+ ]
79
+ },
80
+ {
81
+ "runway_id": "BED_D",
82
+ "ops": [
83
+ "arrival",
84
+ "departure"
85
+ ]
86
+ }
87
+ ],
88
+ "flights": [
89
+ {
90
+ "flight_id": "T_ARR_01",
91
+ "operation": "arrival",
92
+ "wake": "H",
93
+ "scheduled": 5,
94
+ "earliest": 0,
95
+ "latest": 10,
96
+ "runways": [
97
+ "BED_A",
98
+ "BED_B",
99
+ "BED_C",
100
+ "BED_D"
101
+ ],
102
+ "priority": "emergency"
103
+ },
104
+ {
105
+ "flight_id": "T_ARR_02",
106
+ "operation": "arrival",
107
+ "wake": "H",
108
+ "scheduled": 8,
109
+ "earliest": 3,
110
+ "latest": 15,
111
+ "runways": [
112
+ "BED_A",
113
+ "BED_B",
114
+ "BED_C",
115
+ "BED_D"
116
+ ],
117
+ "priority": "emergency"
118
+ },
119
+ {
120
+ "flight_id": "T_ARR_03",
121
+ "operation": "arrival",
122
+ "wake": "H",
123
+ "scheduled": 12,
124
+ "earliest": 8,
125
+ "latest": 20,
126
+ "runways": [
127
+ "BED_A",
128
+ "BED_B",
129
+ "BED_C",
130
+ "BED_D"
131
+ ],
132
+ "priority": "emergency"
133
+ },
134
+ {
135
+ "flight_id": "T_ARR_04",
136
+ "operation": "arrival",
137
+ "wake": "M",
138
+ "scheduled": 30,
139
+ "earliest": 15,
140
+ "latest": 75,
141
+ "runways": [
142
+ "BED_A",
143
+ "BED_B",
144
+ "BED_C",
145
+ "BED_D"
146
+ ],
147
+ "priority": "medical"
148
+ },
149
+ {
150
+ "flight_id": "T_ARR_05",
151
+ "operation": "arrival",
152
+ "wake": "M",
153
+ "scheduled": 50,
154
+ "earliest": 30,
155
+ "latest": 100,
156
+ "runways": [
157
+ "BED_A",
158
+ "BED_B",
159
+ "BED_C",
160
+ "BED_D"
161
+ ],
162
+ "priority": "medical"
163
+ },
164
+ {
165
+ "flight_id": "T_ARR_06",
166
+ "operation": "arrival",
167
+ "wake": "M",
168
+ "scheduled": 80,
169
+ "earliest": 60,
170
+ "latest": 140,
171
+ "runways": [
172
+ "BED_A",
173
+ "BED_B",
174
+ "BED_C",
175
+ "BED_D"
176
+ ],
177
+ "priority": "medical"
178
+ },
179
+ {
180
+ "flight_id": "T_ARR_07",
181
+ "operation": "arrival",
182
+ "wake": "M",
183
+ "scheduled": 110,
184
+ "earliest": 90,
185
+ "latest": 170,
186
+ "runways": [
187
+ "BED_A",
188
+ "BED_B",
189
+ "BED_C",
190
+ "BED_D"
191
+ ],
192
+ "priority": "medical"
193
+ },
194
+ {
195
+ "flight_id": "T_ARR_08",
196
+ "operation": "arrival",
197
+ "wake": "L",
198
+ "scheduled": 120,
199
+ "earliest": 60,
200
+ "latest": 240,
201
+ "runways": [
202
+ "BED_A",
203
+ "BED_B",
204
+ "BED_C",
205
+ "BED_D"
206
+ ],
207
+ "priority": "connection"
208
+ },
209
+ {
210
+ "flight_id": "T_ARR_09",
211
+ "operation": "arrival",
212
+ "wake": "L",
213
+ "scheduled": 160,
214
+ "earliest": 100,
215
+ "latest": 280,
216
+ "runways": [
217
+ "BED_A",
218
+ "BED_B",
219
+ "BED_C",
220
+ "BED_D"
221
+ ],
222
+ "priority": "connection"
223
+ },
224
+ {
225
+ "flight_id": "T_ARR_10",
226
+ "operation": "arrival",
227
+ "wake": "L",
228
+ "scheduled": 200,
229
+ "earliest": 150,
230
+ "latest": 330,
231
+ "runways": [
232
+ "BED_A",
233
+ "BED_B",
234
+ "BED_C",
235
+ "BED_D"
236
+ ],
237
+ "priority": "connection"
238
+ },
239
+ {
240
+ "flight_id": "T_DIS_01",
241
+ "operation": "departure",
242
+ "wake": "M",
243
+ "scheduled": 0,
244
+ "earliest": 0,
245
+ "latest": 8,
246
+ "runways": [
247
+ "BED_A",
248
+ "BED_B",
249
+ "BED_C",
250
+ "BED_D"
251
+ ],
252
+ "priority": "medical"
253
+ },
254
+ {
255
+ "flight_id": "T_DIS_02",
256
+ "operation": "departure",
257
+ "wake": "M",
258
+ "scheduled": 2,
259
+ "earliest": 0,
260
+ "latest": 10,
261
+ "runways": [
262
+ "BED_A",
263
+ "BED_B",
264
+ "BED_C",
265
+ "BED_D"
266
+ ],
267
+ "priority": "medical"
268
+ },
269
+ {
270
+ "flight_id": "T_DIS_03",
271
+ "operation": "departure",
272
+ "wake": "M",
273
+ "scheduled": 5,
274
+ "earliest": 0,
275
+ "latest": 15,
276
+ "runways": [
277
+ "BED_A",
278
+ "BED_B",
279
+ "BED_C",
280
+ "BED_D"
281
+ ],
282
+ "priority": "medical"
283
+ },
284
+ {
285
+ "flight_id": "T_DIS_04",
286
+ "operation": "departure",
287
+ "wake": "M",
288
+ "scheduled": 20,
289
+ "earliest": 10,
290
+ "latest": 60,
291
+ "runways": [
292
+ "BED_A",
293
+ "BED_B",
294
+ "BED_C",
295
+ "BED_D"
296
+ ],
297
+ "priority": "medical"
298
+ },
299
+ {
300
+ "flight_id": "T_DIS_05",
301
+ "operation": "departure",
302
+ "wake": "L",
303
+ "scheduled": 40,
304
+ "earliest": 20,
305
+ "latest": 120,
306
+ "runways": [
307
+ "BED_A",
308
+ "BED_B",
309
+ "BED_C",
310
+ "BED_D"
311
+ ],
312
+ "priority": "connection"
313
+ },
314
+ {
315
+ "flight_id": "T_DIS_06",
316
+ "operation": "departure",
317
+ "wake": "L",
318
+ "scheduled": 90,
319
+ "earliest": 60,
320
+ "latest": 200,
321
+ "runways": [
322
+ "BED_A",
323
+ "BED_B",
324
+ "BED_C",
325
+ "BED_D"
326
+ ],
327
+ "priority": "connection"
328
+ }
329
+ ]
330
+ }
331
+ },
332
+ {
333
+ "type": "llm_started",
334
+ "role": "AMAN",
335
+ "model": "heuristic-baseline"
336
+ },
337
+ {
338
+ "type": "llm_finished",
339
+ "role": "AMAN",
340
+ "used_llm": false
341
+ },
342
+ {
343
+ "type": "llm_started",
344
+ "role": "DMAN",
345
+ "model": "heuristic-baseline"
346
+ },
347
+ {
348
+ "type": "llm_finished",
349
+ "role": "DMAN",
350
+ "used_llm": false
351
+ },
352
+ {
353
+ "type": "action_layout",
354
+ "phase": "BID",
355
+ "layout": {
356
+ "aman_arrivals": [
357
+ {
358
+ "flight_id": "T_ARR_01",
359
+ "runway": "BED_A",
360
+ "assigned_minute": 5,
361
+ "hold_minutes": 0
362
+ },
363
+ {
364
+ "flight_id": "T_ARR_02",
365
+ "runway": "BED_A",
366
+ "assigned_minute": 10,
367
+ "hold_minutes": 2
368
+ },
369
+ {
370
+ "flight_id": "T_ARR_03",
371
+ "runway": "BED_A",
372
+ "assigned_minute": 15,
373
+ "hold_minutes": 3
374
+ },
375
+ {
376
+ "flight_id": "T_ARR_04",
377
+ "runway": "BED_A",
378
+ "assigned_minute": 20,
379
+ "hold_minutes": 0
380
+ },
381
+ {
382
+ "flight_id": "T_ARR_05",
383
+ "runway": "BED_A",
384
+ "assigned_minute": 30,
385
+ "hold_minutes": 0
386
+ },
387
+ {
388
+ "flight_id": "T_ARR_06",
389
+ "runway": "BED_A",
390
+ "assigned_minute": 60,
391
+ "hold_minutes": 0
392
+ },
393
+ {
394
+ "flight_id": "T_ARR_07",
395
+ "runway": "BED_A",
396
+ "assigned_minute": 90,
397
+ "hold_minutes": 0
398
+ },
399
+ {
400
+ "flight_id": "T_ARR_08",
401
+ "runway": "BED_A",
402
+ "assigned_minute": 95,
403
+ "hold_minutes": 0
404
+ },
405
+ {
406
+ "flight_id": "T_ARR_09",
407
+ "runway": "BED_A",
408
+ "assigned_minute": 100,
409
+ "hold_minutes": 0
410
+ },
411
+ {
412
+ "flight_id": "T_ARR_10",
413
+ "runway": "BED_A",
414
+ "assigned_minute": 150,
415
+ "hold_minutes": 0
416
+ }
417
+ ],
418
+ "dman_departures": [
419
+ {
420
+ "flight_id": "T_DIS_01",
421
+ "runway": "BED_A",
422
+ "assigned_minute": 5,
423
+ "hold_minutes": 5
424
+ },
425
+ {
426
+ "flight_id": "T_DIS_02",
427
+ "runway": "BED_B",
428
+ "assigned_minute": 5,
429
+ "hold_minutes": 3
430
+ },
431
+ {
432
+ "flight_id": "T_DIS_03",
433
+ "runway": "BED_C",
434
+ "assigned_minute": 5,
435
+ "hold_minutes": 0
436
+ },
437
+ {
438
+ "flight_id": "T_DIS_04",
439
+ "runway": "BED_A",
440
+ "assigned_minute": 25,
441
+ "hold_minutes": 5
442
+ },
443
+ {
444
+ "flight_id": "T_DIS_05",
445
+ "runway": "BED_A",
446
+ "assigned_minute": 35,
447
+ "hold_minutes": 0
448
+ },
449
+ {
450
+ "flight_id": "T_DIS_06",
451
+ "runway": "BED_A",
452
+ "assigned_minute": 65,
453
+ "hold_minutes": 0
454
+ }
455
+ ]
456
+ }
457
+ },
458
+ {
459
+ "type": "negotiation_tick",
460
+ "pass": 1,
461
+ "partial_reward": 0.171,
462
+ "separation_issues_after": 0,
463
+ "used_llm": false,
464
+ "layout": {
465
+ "aman_arrivals": [
466
+ {
467
+ "flight_id": "T_ARR_01",
468
+ "runway": "BED_D",
469
+ "assigned_minute": 5,
470
+ "hold_minutes": 0
471
+ },
472
+ {
473
+ "flight_id": "T_ARR_02",
474
+ "runway": "BED_A",
475
+ "assigned_minute": 10,
476
+ "hold_minutes": 2
477
+ },
478
+ {
479
+ "flight_id": "T_ARR_03",
480
+ "runway": "BED_B",
481
+ "assigned_minute": 10,
482
+ "hold_minutes": 0
483
+ },
484
+ {
485
+ "flight_id": "T_ARR_04",
486
+ "runway": "BED_A",
487
+ "assigned_minute": 15,
488
+ "hold_minutes": 0
489
+ },
490
+ {
491
+ "flight_id": "T_ARR_05",
492
+ "runway": "BED_A",
493
+ "assigned_minute": 30,
494
+ "hold_minutes": 0
495
+ },
496
+ {
497
+ "flight_id": "T_ARR_06",
498
+ "runway": "BED_A",
499
+ "assigned_minute": 60,
500
+ "hold_minutes": 0
501
+ },
502
+ {
503
+ "flight_id": "T_ARR_07",
504
+ "runway": "BED_A",
505
+ "assigned_minute": 90,
506
+ "hold_minutes": 0
507
+ },
508
+ {
509
+ "flight_id": "T_ARR_08",
510
+ "runway": "BED_A",
511
+ "assigned_minute": 95,
512
+ "hold_minutes": 0
513
+ },
514
+ {
515
+ "flight_id": "T_ARR_09",
516
+ "runway": "BED_A",
517
+ "assigned_minute": 100,
518
+ "hold_minutes": 0
519
+ },
520
+ {
521
+ "flight_id": "T_ARR_10",
522
+ "runway": "BED_A",
523
+ "assigned_minute": 150,
524
+ "hold_minutes": 0
525
+ }
526
+ ],
527
+ "dman_departures": [
528
+ {
529
+ "flight_id": "T_DIS_01",
530
+ "runway": "BED_A",
531
+ "assigned_minute": 5,
532
+ "hold_minutes": 5
533
+ },
534
+ {
535
+ "flight_id": "T_DIS_02",
536
+ "runway": "BED_B",
537
+ "assigned_minute": 5,
538
+ "hold_minutes": 3
539
+ },
540
+ {
541
+ "flight_id": "T_DIS_03",
542
+ "runway": "BED_C",
543
+ "assigned_minute": 5,
544
+ "hold_minutes": 0
545
+ },
546
+ {
547
+ "flight_id": "T_DIS_04",
548
+ "runway": "BED_A",
549
+ "assigned_minute": 20,
550
+ "hold_minutes": 0
551
+ },
552
+ {
553
+ "flight_id": "T_DIS_05",
554
+ "runway": "BED_A",
555
+ "assigned_minute": 25,
556
+ "hold_minutes": 0
557
+ },
558
+ {
559
+ "flight_id": "T_DIS_06",
560
+ "runway": "BED_A",
561
+ "assigned_minute": 65,
562
+ "hold_minutes": 0
563
+ }
564
+ ]
565
+ }
566
+ },
567
+ {
568
+ "type": "score_update",
569
+ "composite": 0.395,
570
+ "aman_reward": 0.5105,
571
+ "dman_reward": 0.702
572
+ },
573
+ {
574
+ "type": "terminal",
575
+ "severity": "degraded",
576
+ "composite": 0.395,
577
+ "aman_reward": 0.5105,
578
+ "dman_reward": 0.702,
579
+ "coordination": 0.9,
580
+ "cross_lane_conflicts": 0,
581
+ "atfm_violations": 0,
582
+ "negotiation_rounds": 1
583
+ }
584
+ ],
585
+ "rounds": [
586
+ {
587
+ "round": "BID",
588
+ "partial_reward": 0.1583,
589
+ "separation_issues_detected": 1,
590
+ "diagnostics_count": 8,
591
+ "aman_slots": 10,
592
+ "dman_slots": 6,
593
+ "aman_messages": 10,
594
+ "dman_messages": 6,
595
+ "done": false
596
+ },
597
+ {
598
+ "round": "NEGOTIATE",
599
+ "negotiate_pass": 1,
600
+ "partial_reward": 0.171,
601
+ "separation_issues_before": 1,
602
+ "separation_issues_after": 0,
603
+ "diagnostics_count": 8,
604
+ "conflicts_resolved": 1,
605
+ "total_messages": 16,
606
+ "aman_alternatives_offered": 0,
607
+ "dman_alternatives_offered": 0,
608
+ "used_llm": false
609
+ }
610
+ ],
611
+ "final": {
612
+ "composite_score": 0.395,
613
+ "aman_reward": 0.5105,
614
+ "dman_reward": 0.702,
615
+ "coordination_score": 0.9,
616
+ "cross_lane_conflicts": 0,
617
+ "negotiation_rounds": 1,
618
+ "atfm_violations": 0
619
+ }
620
+ }
scripts/benchmark_results/kimi_k26_atc/episode_00000.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "episode_id": 0,
3
+ "task_id": "bengaluru_irrops_hard",
4
+ "supervisor_profile": "safety_strict",
5
+ "gen_difficulty": 0,
6
+ "mutations_applied": [],
7
+ "solvable": true,
8
+ "rounds": [
9
+ {
10
+ "round": "BID",
11
+ "partial_reward": 0.2014,
12
+ "separation_issues_detected": 2,
13
+ "diagnostics_count": 4,
14
+ "aman_slots": 8,
15
+ "dman_slots": 9,
16
+ "aman_messages": 8,
17
+ "dman_messages": 9,
18
+ "done": false
19
+ },
20
+ {
21
+ "round": "NEGOTIATE",
22
+ "negotiate_pass": 1,
23
+ "partial_reward": 0.22,
24
+ "separation_issues_before": 2,
25
+ "separation_issues_after": 0,
26
+ "diagnostics_count": 2,
27
+ "conflicts_resolved": 2,
28
+ "total_messages": 17,
29
+ "aman_alternatives_offered": 0,
30
+ "dman_alternatives_offered": 0,
31
+ "used_llm": false
32
+ }
33
+ ],
34
+ "final": {
35
+ "composite_score": 0.46,
36
+ "aman_reward": 0.8529,
37
+ "dman_reward": 0.7633,
38
+ "generator_reward": 0.1919,
39
+ "supervisor_score": 0.8603,
40
+ "coordination_score": 0.9,
41
+ "cross_lane_conflicts": 0,
42
+ "negotiation_rounds": 1,
43
+ "atfm_violations": 0,
44
+ "emergency_arrivals_ok": 1,
45
+ "emergency_departures_ok": 1
46
+ }
47
+ }
scripts/benchmark_results/kimi_k26_icu/episode_00000.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "episode_id": 0,
3
+ "domain_task_id": "icu_mass_casualty",
4
+ "mode": "adapt_domain_transfer",
5
+ "supervisor_profile": "safety_strict",
6
+ "adapt_wake_map": {
7
+ "TRAUMA": "H",
8
+ "CARDIAC": "M",
9
+ "POST_OP": "M",
10
+ "ROUTINE": "L"
11
+ },
12
+ "adapt_priority_map": {
13
+ "TRAUMA": "emergency",
14
+ "CARDIAC": "medical",
15
+ "POST_OP": "medical",
16
+ "ROUTINE": "connection"
17
+ },
18
+ "adapt_rationale": "Structural budget-enforced inference (budget: emergency\u22641 heavy\u22641 medical\u22642): TRAUMA: tp=0.98 cr=0.93 score=0.96 \u2192 wake=H priority=emergency; CARDIAC: tp=0.85 cr=0.64 score=0.78 \u2192 wake=M (budget-demoted) priority=medical; POST_OP: tp=0.96 cr=0.00 score=0.58 \u2192 wake=M priority=medical (budget-demoted); ROUTINE: tp=0.68 cr=0.00 score=0.34 \u2192 wake=L priority=connection",
19
+ "rounds": [
20
+ {
21
+ "round": "BID",
22
+ "partial_reward": 0.0981,
23
+ "separation_issues_detected": 3,
24
+ "diagnostics_count": 12,
25
+ "aman_slots": 9,
26
+ "dman_slots": 4,
27
+ "aman_messages": 9,
28
+ "dman_messages": 4,
29
+ "done": false
30
+ },
31
+ {
32
+ "round": "NEGOTIATE",
33
+ "negotiate_pass": 1,
34
+ "partial_reward": 0.1098,
35
+ "separation_issues_before": 3,
36
+ "separation_issues_after": 2,
37
+ "diagnostics_count": 11,
38
+ "conflicts_resolved": 1,
39
+ "total_messages": 13,
40
+ "aman_alternatives_offered": 0,
41
+ "dman_alternatives_offered": 0,
42
+ "used_llm": false
43
+ }
44
+ ],
45
+ "final": {
46
+ "composite_score": 0.2768,
47
+ "aman_reward": 0.3957,
48
+ "dman_reward": 0.4538,
49
+ "coordination_score": 0.5682,
50
+ "cross_lane_conflicts": 2,
51
+ "negotiation_rounds": 1
52
+ }
53
+ }
scripts/benchmark_results/qwen25_1p5b_atc/episode_00000.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "episode_id": 0,
3
+ "task_id": "bengaluru_irrops_hard",
4
+ "supervisor_profile": "safety_strict",
5
+ "gen_difficulty": 0,
6
+ "mutations_applied": [],
7
+ "solvable": true,
8
+ "rounds": [
9
+ {
10
+ "round": "BID",
11
+ "partial_reward": 0.1185,
12
+ "separation_issues_detected": 7,
13
+ "diagnostics_count": 9,
14
+ "aman_slots": 8,
15
+ "dman_slots": 8,
16
+ "aman_messages": 8,
17
+ "dman_messages": 8,
18
+ "done": false
19
+ },
20
+ {
21
+ "round": "NEGOTIATE",
22
+ "negotiate_pass": 1,
23
+ "partial_reward": 0.1676,
24
+ "separation_issues_before": 7,
25
+ "separation_issues_after": 2,
26
+ "diagnostics_count": 5,
27
+ "conflicts_resolved": 5,
28
+ "total_messages": 16,
29
+ "aman_alternatives_offered": 0,
30
+ "dman_alternatives_offered": 0,
31
+ "used_llm": false
32
+ }
33
+ ],
34
+ "final": {
35
+ "composite_score": 0.35,
36
+ "aman_reward": 0.8318,
37
+ "dman_reward": 0.632,
38
+ "generator_reward": 0.2681,
39
+ "supervisor_score": 0.4,
40
+ "coordination_score": 0.65,
41
+ "cross_lane_conflicts": 2,
42
+ "negotiation_rounds": 1,
43
+ "atfm_violations": 0,
44
+ "emergency_arrivals_ok": 1,
45
+ "emergency_departures_ok": 1
46
+ }
47
+ }
scripts/benchmark_results/qwen25_1p5b_icu/episode_00000.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "episode_id": 0,
3
+ "domain_task_id": "icu_mass_casualty",
4
+ "mode": "adapt_domain_transfer",
5
+ "supervisor_profile": "safety_strict",
6
+ "adapt_wake_map": {
7
+ "TRAUMA": "H",
8
+ "CARDIAC": "M",
9
+ "POST_OP": "M",
10
+ "ROUTINE": "L"
11
+ },
12
+ "adapt_priority_map": {
13
+ "TRAUMA": "emergency",
14
+ "CARDIAC": "medical",
15
+ "POST_OP": "medical",
16
+ "ROUTINE": "connection"
17
+ },
18
+ "adapt_rationale": "Structural budget-enforced inference (budget: emergency\u22641 heavy\u22641 medical\u22642): TRAUMA: tp=0.98 cr=0.93 score=0.96 \u2192 wake=H priority=emergency; CARDIAC: tp=0.85 cr=0.64 score=0.78 \u2192 wake=M (budget-demoted) priority=medical; POST_OP: tp=0.96 cr=0.00 score=0.58 \u2192 wake=M priority=medical (budget-demoted); ROUTINE: tp=0.68 cr=0.00 score=0.34 \u2192 wake=L priority=connection",
19
+ "rounds": [
20
+ {
21
+ "round": "BID",
22
+ "partial_reward": 0.0981,
23
+ "separation_issues_detected": 3,
24
+ "diagnostics_count": 12,
25
+ "aman_slots": 9,
26
+ "dman_slots": 4,
27
+ "aman_messages": 9,
28
+ "dman_messages": 4,
29
+ "done": false
30
+ },
31
+ {
32
+ "round": "NEGOTIATE",
33
+ "negotiate_pass": 1,
34
+ "partial_reward": 0.1098,
35
+ "separation_issues_before": 3,
36
+ "separation_issues_after": 2,
37
+ "diagnostics_count": 11,
38
+ "conflicts_resolved": 1,
39
+ "total_messages": 13,
40
+ "aman_alternatives_offered": 0,
41
+ "dman_alternatives_offered": 0,
42
+ "used_llm": false
43
+ },
44
+ {
45
+ "round": "NEGOTIATE",
46
+ "negotiate_pass": 2,
47
+ "partial_reward": 0.1126,
48
+ "separation_issues_before": 2,
49
+ "separation_issues_after": 0,
50
+ "diagnostics_count": 10,
51
+ "conflicts_resolved": 2,
52
+ "total_messages": 11,
53
+ "aman_alternatives_offered": 0,
54
+ "dman_alternatives_offered": 0,
55
+ "used_llm": false
56
+ }
57
+ ],
58
+ "final": {
59
+ "composite_score": 0.3,
60
+ "aman_reward": 0.4426,
61
+ "dman_reward": 0.4584,
62
+ "coordination_score": 0.7136,
63
+ "cross_lane_conflicts": 0,
64
+ "negotiation_rounds": 2
65
+ }
66
+ }
scripts/benchmark_results/results_20260407_161519.json ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "model": "heuristic-baseline",
4
+ "avg_score": 0.9271,
5
+ "tasks": [
6
+ {
7
+ "task_id": "delhi_monsoon_recovery_easy",
8
+ "score": 0.964,
9
+ "success": true,
10
+ "steps": 3,
11
+ "rewards": [
12
+ 0.7877,
13
+ 0.1763,
14
+ 0.0
15
+ ],
16
+ "total_reward": 0.964,
17
+ "elapsed_s": 0.11,
18
+ "error": null
19
+ },
20
+ {
21
+ "task_id": "mumbai_bank_balance_medium",
22
+ "score": 0.955,
23
+ "success": true,
24
+ "steps": 3,
25
+ "rewards": [
26
+ 0.6155,
27
+ 0.3395,
28
+ 0.0
29
+ ],
30
+ "total_reward": 0.955,
31
+ "elapsed_s": 0.21,
32
+ "error": null
33
+ },
34
+ {
35
+ "task_id": "bengaluru_irrops_hard",
36
+ "score": 0.8623,
37
+ "success": true,
38
+ "steps": 4,
39
+ "rewards": [
40
+ 0.2,
41
+ 0.6623,
42
+ 0.0,
43
+ 0.0
44
+ ],
45
+ "total_reward": 0.8623,
46
+ "elapsed_s": 0.49,
47
+ "error": null
48
+ }
49
+ ],
50
+ "timestamp": "2026-04-07T16:15:25.513158+00:00"
51
+ },
52
+ {
53
+ "model": "Qwen/Qwen2.5-7B-Instruct",
54
+ "avg_score": 0.7706,
55
+ "tasks": [
56
+ {
57
+ "task_id": "delhi_monsoon_recovery_easy",
58
+ "score": 0.9568,
59
+ "success": true,
60
+ "steps": 3,
61
+ "rewards": [
62
+ 0.7244,
63
+ 0.2396,
64
+ -0.0072
65
+ ],
66
+ "total_reward": 0.9568,
67
+ "elapsed_s": 9.69,
68
+ "error": null
69
+ },
70
+ {
71
+ "task_id": "mumbai_bank_balance_medium",
72
+ "score": 0.955,
73
+ "success": true,
74
+ "steps": 3,
75
+ "rewards": [
76
+ 0.6155,
77
+ 0.3395,
78
+ 0.0
79
+ ],
80
+ "total_reward": 0.955,
81
+ "elapsed_s": 12.66,
82
+ "error": null
83
+ },
84
+ {
85
+ "task_id": "bengaluru_irrops_hard",
86
+ "score": 0.4,
87
+ "success": false,
88
+ "steps": 4,
89
+ "rewards": [
90
+ 0.15,
91
+ 0.25,
92
+ -0.05,
93
+ 0.05
94
+ ],
95
+ "total_reward": 0.4,
96
+ "elapsed_s": 24.29,
97
+ "error": null
98
+ }
99
+ ],
100
+ "timestamp": "2026-04-07T16:16:12.317519+00:00"
101
+ },
102
+ {
103
+ "model": "microsoft/Phi-3.5-mini-instruct",
104
+ "avg_score": 0.9271,
105
+ "tasks": [
106
+ {
107
+ "task_id": "delhi_monsoon_recovery_easy",
108
+ "score": 0.964,
109
+ "success": true,
110
+ "steps": 3,
111
+ "rewards": [
112
+ 0.7877,
113
+ 0.1763,
114
+ 0.0
115
+ ],
116
+ "total_reward": 0.964,
117
+ "elapsed_s": 0.96,
118
+ "error": null
119
+ },
120
+ {
121
+ "task_id": "mumbai_bank_balance_medium",
122
+ "score": 0.955,
123
+ "success": true,
124
+ "steps": 3,
125
+ "rewards": [
126
+ 0.6155,
127
+ 0.3395,
128
+ 0.0
129
+ ],
130
+ "total_reward": 0.955,
131
+ "elapsed_s": 1.06,
132
+ "error": null
133
+ },
134
+ {
135
+ "task_id": "bengaluru_irrops_hard",
136
+ "score": 0.8623,
137
+ "success": true,
138
+ "steps": 4,
139
+ "rewards": [
140
+ 0.2,
141
+ 0.6623,
142
+ 0.0,
143
+ 0.0
144
+ ],
145
+ "total_reward": 0.8623,
146
+ "elapsed_s": 1.65,
147
+ "error": null
148
+ }
149
+ ],
150
+ "timestamp": "2026-04-07T16:16:16.177850+00:00"
151
+ },
152
+ {
153
+ "model": "Qwen/Qwen2.5-72B-Instruct",
154
+ "avg_score": 0.3333,
155
+ "tasks": [
156
+ {
157
+ "task_id": "delhi_monsoon_recovery_easy",
158
+ "score": 0.9999,
159
+ "success": true,
160
+ "steps": 3,
161
+ "rewards": [
162
+ 0.9424,
163
+ -0.5424,
164
+ 0.5999
165
+ ],
166
+ "total_reward": 0.9999,
167
+ "elapsed_s": 42.22,
168
+ "error": null
169
+ },
170
+ {
171
+ "task_id": "mumbai_bank_balance_medium",
172
+ "score": 0.0,
173
+ "success": false,
174
+ "steps": 1,
175
+ "rewards": [
176
+ 0.3
177
+ ],
178
+ "total_reward": 0.3,
179
+ "elapsed_s": 40.2,
180
+ "error": "received 1011 (internal error) keepalive ping timeout; then sent 1011 (internal error) keepalive ping timeout"
181
+ },
182
+ {
183
+ "task_id": "bengaluru_irrops_hard",
184
+ "score": 0.0,
185
+ "success": false,
186
+ "steps": 0,
187
+ "rewards": [],
188
+ "total_reward": 0,
189
+ "elapsed_s": 58.23,
190
+ "error": "no close frame received or sent"
191
+ }
192
+ ],
193
+ "timestamp": "2026-04-07T16:24:51.683634+00:00"
194
+ },
195
+ {
196
+ "model": "mistralai/Mistral-Nemo-Instruct-2407",
197
+ "avg_score": 0.9271,
198
+ "tasks": [
199
+ {
200
+ "task_id": "delhi_monsoon_recovery_easy",
201
+ "score": 0.964,
202
+ "success": true,
203
+ "steps": 3,
204
+ "rewards": [
205
+ 0.7877,
206
+ 0.1763,
207
+ 0.0
208
+ ],
209
+ "total_reward": 0.964,
210
+ "elapsed_s": 1.05,
211
+ "error": null
212
+ },
213
+ {
214
+ "task_id": "mumbai_bank_balance_medium",
215
+ "score": 0.955,
216
+ "success": true,
217
+ "steps": 3,
218
+ "rewards": [
219
+ 0.6155,
220
+ 0.3395,
221
+ 0.0
222
+ ],
223
+ "total_reward": 0.955,
224
+ "elapsed_s": 1.07,
225
+ "error": null
226
+ },
227
+ {
228
+ "task_id": "bengaluru_irrops_hard",
229
+ "score": 0.8623,
230
+ "success": true,
231
+ "steps": 4,
232
+ "rewards": [
233
+ 0.2,
234
+ 0.6623,
235
+ 0.0,
236
+ 0.0
237
+ ],
238
+ "total_reward": 0.8623,
239
+ "elapsed_s": 1.62,
240
+ "error": null
241
+ }
242
+ ],
243
+ "timestamp": "2026-04-07T16:24:55.618898+00:00"
244
+ }
245
+ ]
scripts/benchmark_results/results_20260407_171222.json ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "model": "heuristic-baseline",
4
+ "avg_score": 0.9136,
5
+ "tasks": [
6
+ {
7
+ "task_id": "delhi_monsoon_recovery_easy",
8
+ "score": 0.9446,
9
+ "success": true,
10
+ "steps": 3,
11
+ "rewards": [
12
+ 0.4,
13
+ 0.5446,
14
+ 0.0
15
+ ],
16
+ "total_reward": 0.9446,
17
+ "elapsed_s": 0.1,
18
+ "error": null
19
+ },
20
+ {
21
+ "task_id": "mumbai_bank_balance_medium",
22
+ "score": 0.9907,
23
+ "success": true,
24
+ "steps": 2,
25
+ "rewards": [
26
+ 0.3,
27
+ 0.6907
28
+ ],
29
+ "total_reward": 0.9907,
30
+ "elapsed_s": 0.14,
31
+ "error": null
32
+ },
33
+ {
34
+ "task_id": "bengaluru_irrops_hard",
35
+ "score": 0.8615,
36
+ "success": true,
37
+ "steps": 4,
38
+ "rewards": [
39
+ 0.15,
40
+ 0.6377,
41
+ 0.0738,
42
+ 0.0
43
+ ],
44
+ "total_reward": 0.8615,
45
+ "elapsed_s": 0.55,
46
+ "error": null
47
+ },
48
+ {
49
+ "task_id": "hyderabad_cargo_crunch_medium_hard",
50
+ "score": 0.8576,
51
+ "success": true,
52
+ "steps": 3,
53
+ "rewards": [
54
+ 0.4,
55
+ 0.4576,
56
+ 0.0
57
+ ],
58
+ "total_reward": 0.8576,
59
+ "elapsed_s": 0.03,
60
+ "error": null
61
+ }
62
+ ],
63
+ "timestamp": "2026-04-07T17:12:27.732518+00:00"
64
+ },
65
+ {
66
+ "model": "Qwen/Qwen2.5-7B-Instruct",
67
+ "avg_score": 0.6351,
68
+ "tasks": [
69
+ {
70
+ "task_id": "delhi_monsoon_recovery_easy",
71
+ "score": 0.9999,
72
+ "success": true,
73
+ "steps": 2,
74
+ "rewards": [
75
+ 0.6518,
76
+ 0.3481
77
+ ],
78
+ "total_reward": 0.9999,
79
+ "elapsed_s": 9.09,
80
+ "error": null
81
+ },
82
+ {
83
+ "task_id": "mumbai_bank_balance_medium",
84
+ "score": 0.9907,
85
+ "success": true,
86
+ "steps": 3,
87
+ "rewards": [
88
+ 0.3,
89
+ 0.1,
90
+ 0.5907
91
+ ],
92
+ "total_reward": 0.9907,
93
+ "elapsed_s": 16.43,
94
+ "error": null
95
+ },
96
+ {
97
+ "task_id": "bengaluru_irrops_hard",
98
+ "score": 0.3,
99
+ "success": false,
100
+ "steps": 4,
101
+ "rewards": [
102
+ 0.3138,
103
+ -0.0638,
104
+ 0.15,
105
+ -0.1
106
+ ],
107
+ "total_reward": 0.3,
108
+ "elapsed_s": 25.14,
109
+ "error": null
110
+ },
111
+ {
112
+ "task_id": "hyderabad_cargo_crunch_medium_hard",
113
+ "score": 0.25,
114
+ "success": false,
115
+ "steps": 3,
116
+ "rewards": [
117
+ 0.4,
118
+ -0.15,
119
+ 0.0
120
+ ],
121
+ "total_reward": 0.25,
122
+ "elapsed_s": 8.69,
123
+ "error": null
124
+ }
125
+ ],
126
+ "timestamp": "2026-04-07T17:13:27.268662+00:00"
127
+ },
128
+ {
129
+ "model": "microsoft/Phi-3.5-mini-instruct",
130
+ "avg_score": 0.9136,
131
+ "tasks": [
132
+ {
133
+ "task_id": "delhi_monsoon_recovery_easy",
134
+ "score": 0.9446,
135
+ "success": true,
136
+ "steps": 3,
137
+ "rewards": [
138
+ 0.4,
139
+ 0.5446,
140
+ 0.0
141
+ ],
142
+ "total_reward": 0.9446,
143
+ "elapsed_s": 1.02,
144
+ "error": null
145
+ },
146
+ {
147
+ "task_id": "mumbai_bank_balance_medium",
148
+ "score": 0.9907,
149
+ "success": true,
150
+ "steps": 2,
151
+ "rewards": [
152
+ 0.3,
153
+ 0.6907
154
+ ],
155
+ "total_reward": 0.9907,
156
+ "elapsed_s": 0.72,
157
+ "error": null
158
+ },
159
+ {
160
+ "task_id": "bengaluru_irrops_hard",
161
+ "score": 0.8615,
162
+ "success": true,
163
+ "steps": 4,
164
+ "rewards": [
165
+ 0.15,
166
+ 0.6377,
167
+ 0.0738,
168
+ 0.0
169
+ ],
170
+ "total_reward": 0.8615,
171
+ "elapsed_s": 1.58,
172
+ "error": null
173
+ },
174
+ {
175
+ "task_id": "hyderabad_cargo_crunch_medium_hard",
176
+ "score": 0.8576,
177
+ "success": true,
178
+ "steps": 3,
179
+ "rewards": [
180
+ 0.4,
181
+ 0.4576,
182
+ 0.0
183
+ ],
184
+ "total_reward": 0.8576,
185
+ "elapsed_s": 0.9,
186
+ "error": null
187
+ }
188
+ ],
189
+ "timestamp": "2026-04-07T17:13:31.677162+00:00"
190
+ },
191
+ {
192
+ "model": "Qwen/Qwen2.5-72B-Instruct",
193
+ "avg_score": 0.449,
194
+ "tasks": [
195
+ {
196
+ "task_id": "delhi_monsoon_recovery_easy",
197
+ "score": 0.4,
198
+ "success": false,
199
+ "steps": 3,
200
+ "rewards": [
201
+ 0.4,
202
+ 0.5566,
203
+ -0.5566
204
+ ],
205
+ "total_reward": 0.4,
206
+ "elapsed_s": 61.11,
207
+ "error": null
208
+ },
209
+ {
210
+ "task_id": "mumbai_bank_balance_medium",
211
+ "score": 0.9959,
212
+ "success": true,
213
+ "steps": 3,
214
+ "rewards": [
215
+ 0.2,
216
+ 0.2,
217
+ 0.5959
218
+ ],
219
+ "total_reward": 0.9959,
220
+ "elapsed_s": 75.18,
221
+ "error": null
222
+ },
223
+ {
224
+ "task_id": "bengaluru_irrops_hard",
225
+ "score": 0.0,
226
+ "success": false,
227
+ "steps": 2,
228
+ "rewards": [
229
+ 0.2,
230
+ 0.574
231
+ ],
232
+ "total_reward": 0.774,
233
+ "elapsed_s": 98.77,
234
+ "error": "received 1011 (internal error) keepalive ping timeout; then sent 1011 (internal error) keepalive ping timeout"
235
+ },
236
+ {
237
+ "task_id": "hyderabad_cargo_crunch_medium_hard",
238
+ "score": 0.4,
239
+ "success": false,
240
+ "steps": 3,
241
+ "rewards": [
242
+ 0.4,
243
+ 0.343,
244
+ -0.343
245
+ ],
246
+ "total_reward": 0.4,
247
+ "elapsed_s": 38.31,
248
+ "error": null
249
+ }
250
+ ],
251
+ "timestamp": "2026-04-07T17:19:23.883503+00:00"
252
+ },
253
+ {
254
+ "model": "mistralai/Mistral-Nemo-Instruct-2407",
255
+ "avg_score": 0.9136,
256
+ "tasks": [
257
+ {
258
+ "task_id": "delhi_monsoon_recovery_easy",
259
+ "score": 0.9446,
260
+ "success": true,
261
+ "steps": 3,
262
+ "rewards": [
263
+ 0.4,
264
+ 0.5446,
265
+ 0.0
266
+ ],
267
+ "total_reward": 0.9446,
268
+ "elapsed_s": 1.14,
269
+ "error": null
270
+ },
271
+ {
272
+ "task_id": "mumbai_bank_balance_medium",
273
+ "score": 0.9907,
274
+ "success": true,
275
+ "steps": 2,
276
+ "rewards": [
277
+ 0.3,
278
+ 0.6907
279
+ ],
280
+ "total_reward": 0.9907,
281
+ "elapsed_s": 0.73,
282
+ "error": null
283
+ },
284
+ {
285
+ "task_id": "bengaluru_irrops_hard",
286
+ "score": 0.8615,
287
+ "success": true,
288
+ "steps": 4,
289
+ "rewards": [
290
+ 0.15,
291
+ 0.6377,
292
+ 0.0738,
293
+ 0.0
294
+ ],
295
+ "total_reward": 0.8615,
296
+ "elapsed_s": 1.67,
297
+ "error": null
298
+ },
299
+ {
300
+ "task_id": "hyderabad_cargo_crunch_medium_hard",
301
+ "score": 0.8576,
302
+ "success": true,
303
+ "steps": 3,
304
+ "rewards": [
305
+ 0.4,
306
+ 0.4576,
307
+ 0.0
308
+ ],
309
+ "total_reward": 0.8576,
310
+ "elapsed_s": 0.87,
311
+ "error": null
312
+ }
313
+ ],
314
+ "timestamp": "2026-04-07T17:19:28.471491+00:00"
315
+ }
316
+ ]
scripts/benchmark_results/summary_20260407_161519.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ATC Benchmark Results — 20260407_161519
2
+
3
+ Model Avg Easy Med Hard
4
+ ------------------------------------------------------------------------
5
+ heuristic-baseline 0.9271 0.9640 0.9550 0.8623
6
+ microsoft/Phi-3.5-mini-instruct 0.9271 0.9640 0.9550 0.8623
7
+ mistralai/Mistral-Nemo-Instruct-2407 0.9271 0.9640 0.9550 0.8623
8
+ Qwen/Qwen2.5-7B-Instruct 0.7706 0.9568 0.9550 0.4000
9
+ Qwen/Qwen2.5-72B-Instruct 0.3333 0.9999 0.0000 0.0000
scripts/benchmark_results/summary_20260407_171222.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ATC Benchmark Results — 20260407_171222
2
+
3
+ Model Avg Easy Med Blr Hyd
4
+ ----------------------------------------------------------------------------
5
+ heuristic-baseline 0.9136 0.9446 0.9907 0.8615 0.8576
6
+ microsoft/Phi-3.5-mini-instruct 0.9136 0.9446 0.9907 0.8615 0.8576
7
+ mistralai/Mistral-Nemo-Instruct-2407 0.9136 0.9446 0.9907 0.8615 0.8576
8
+ Qwen/Qwen2.5-7B-Instruct 0.6351 0.9999 0.9907 0.3000 0.2500
9
+ Qwen/Qwen2.5-72B-Instruct 0.4490 0.4000 0.9959 0.0000 0.4000
scripts/check_release_hygiene.sh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ ROOT_DIR="${1:-.}"
5
+ cd "$ROOT_DIR"
6
+
7
+ release_files=(
8
+ "inference.py"
9
+ "README.md"
10
+ "Dockerfile"
11
+ "scripts/validate-submission.sh"
12
+ "scripts/pre_submission_validate.sh"
13
+ )
14
+
15
+ for file in "${release_files[@]}"; do
16
+ if [ ! -f "$file" ]; then
17
+ echo "FAILED -- missing required release file: $file"
18
+ exit 1
19
+ fi
20
+ if rg -n -i "groq|GROQ_" "$file" >/dev/null; then
21
+ echo "FAILED -- Groq-only marker found in release file: $file"
22
+ rg -n -i "groq|GROQ_" "$file"
23
+ exit 1
24
+ fi
25
+ done
26
+
27
+ for blocked in test_groq_inference.py setup_groq_inference.sh GROQ_SETUP.md GROQ_INTEGRATION_SUMMARY.md; do
28
+ if [ -e "$blocked" ]; then
29
+ echo "FAILED -- Groq-only artifact present on release branch: $blocked"
30
+ exit 1
31
+ fi
32
+ done
33
+
34
+ echo "PASSED -- release hygiene check"
scripts/deploy_hf_space.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Create/update a Hugging Face Docker Space and upload this repository."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import os
8
+ from pathlib import Path
9
+ from typing import Iterable
10
+ from urllib.parse import urlparse
11
+
12
+ from huggingface_hub import HfApi
13
+
14
+ PLACEHOLDER_MARKERS = ("your-", "your_", "changeme", "example")
15
+
16
+
17
+ def is_real_value(value: str | None) -> bool:
18
+ if value is None:
19
+ return False
20
+ trimmed = value.strip()
21
+ if not trimmed:
22
+ return False
23
+ lowered = trimmed.lower()
24
+ return not any(marker in lowered for marker in PLACEHOLDER_MARKERS)
25
+
26
+
27
+ def parse_args() -> argparse.Namespace:
28
+ parser = argparse.ArgumentParser(
29
+ description="Create/update a HF Docker Space and upload the current repository."
30
+ )
31
+ parser.add_argument(
32
+ "--space-id",
33
+ default=os.getenv("HF_SPACE_ID", ""),
34
+ help="Space id in the form '<owner>/<space-name>' (or set HF_SPACE_ID).",
35
+ )
36
+ parser.add_argument(
37
+ "--space-url",
38
+ default=os.getenv("HF_SPACE_PAGE_URL", ""),
39
+ help=(
40
+ "Optional Space page URL like "
41
+ "'https://huggingface.co/spaces/<owner>/<space-name>' "
42
+ "(or set HF_SPACE_PAGE_URL)."
43
+ ),
44
+ )
45
+ parser.add_argument(
46
+ "--repo-dir",
47
+ default=".",
48
+ help="Repository folder to upload (default: current directory).",
49
+ )
50
+ parser.add_argument(
51
+ "--private",
52
+ action="store_true",
53
+ help="Create the Space as private (default: public).",
54
+ )
55
+ parser.add_argument(
56
+ "--skip-secrets",
57
+ action="store_true",
58
+ help="Skip setting API_BASE_URL, MODEL_NAME, HF_TOKEN as Space secrets.",
59
+ )
60
+ parser.add_argument(
61
+ "--token",
62
+ default=os.getenv("HF_TOKEN", ""),
63
+ help="HF access token (or set HF_TOKEN).",
64
+ )
65
+ return parser.parse_args()
66
+
67
+
68
+ def read_env_file(repo_dir: Path) -> dict[str, str]:
69
+ env_path = repo_dir / ".env"
70
+ if not env_path.exists():
71
+ return {}
72
+
73
+ parsed: dict[str, str] = {}
74
+ for raw in env_path.read_text(encoding="utf-8").splitlines():
75
+ line = raw.strip()
76
+ if not line or line.startswith("#") or "=" not in line:
77
+ continue
78
+ key, value = line.split("=", 1)
79
+ parsed[key.strip()] = value.strip()
80
+ return parsed
81
+
82
+
83
+ def pick_var(name: str, env_values: dict[str, str]) -> str | None:
84
+ direct = os.getenv(name)
85
+ if is_real_value(direct):
86
+ return direct
87
+ fallback = env_values.get(name)
88
+ if is_real_value(fallback):
89
+ return fallback
90
+ return None
91
+
92
+
93
+ def set_required_space_secrets(api: HfApi, space_id: str, pairs: Iterable[tuple[str, str]]) -> None:
94
+ for key, value in pairs:
95
+ api.add_space_secret(repo_id=space_id, key=key, value=value)
96
+ print(f"[OK] Set Space secret: {key}")
97
+
98
+
99
+ def parse_space_id_from_page_url(space_url: str) -> str | None:
100
+ parsed = urlparse(space_url.strip())
101
+ if parsed.netloc != "huggingface.co":
102
+ return None
103
+ parts = [part for part in parsed.path.split("/") if part]
104
+ if len(parts) < 3 or parts[0] != "spaces":
105
+ return None
106
+ return f"{parts[1]}/{parts[2]}"
107
+
108
+
109
+ def resolve_space_id(space_id: str, space_url: str) -> str:
110
+ if space_id and "/" in space_id:
111
+ return space_id
112
+ parsed = parse_space_id_from_page_url(space_url) if space_url else None
113
+ if parsed:
114
+ return parsed
115
+ raise SystemExit(
116
+ "HF space id missing/invalid. Use --space-id <owner>/<space-name>, "
117
+ "set HF_SPACE_ID, or pass --space-url https://huggingface.co/spaces/<owner>/<space-name>."
118
+ )
119
+
120
+
121
+ def to_runtime_space_url(space_id: str) -> str:
122
+ owner, name = space_id.split("/", 1)
123
+ normalized_name = name.replace("_", "-")
124
+ return f"https://{owner}-{normalized_name}.hf.space"
125
+
126
+
127
+ def main() -> int:
128
+ args = parse_args()
129
+
130
+ space_id = resolve_space_id(args.space_id, args.space_url)
131
+
132
+ if not is_real_value(args.token):
133
+ raise SystemExit("HF_TOKEN is missing or looks like a placeholder.")
134
+
135
+ repo_dir = Path(args.repo_dir).resolve()
136
+ if not repo_dir.exists() or not repo_dir.is_dir():
137
+ raise SystemExit(f"Repo directory not found: {repo_dir}")
138
+
139
+ api = HfApi(token=args.token)
140
+ try:
141
+ who = api.whoami(cache=True)
142
+ actor = who.get("name") or who.get("fullname") or "unknown"
143
+ print(f"[OK] Authenticated to Hugging Face as: {actor}")
144
+ except Exception:
145
+ # Whoami rate-limited; proceed anyway — the token will be validated on next API call.
146
+ print("[WARN] Could not verify token via whoami (rate-limited). Proceeding...")
147
+
148
+ api.create_repo(
149
+ repo_id=space_id,
150
+ repo_type="space",
151
+ space_sdk="docker",
152
+ private=args.private,
153
+ exist_ok=True,
154
+ )
155
+ print(f"[OK] Space ready: https://huggingface.co/spaces/{space_id}")
156
+
157
+ ignore_patterns = [
158
+ ".git",
159
+ ".venv",
160
+ ".pytest_cache",
161
+ "__pycache__",
162
+ "*.pyc",
163
+ "*.pyo",
164
+ ".env",
165
+ ".env.*",
166
+ "*.env",
167
+ "*.env.*",
168
+ ".codex",
169
+ ".github",
170
+ "node_modules",
171
+ ".uv-cache",
172
+ ".mypy_cache",
173
+ ".ruff_cache",
174
+ "*.egg-info",
175
+ "wandb",
176
+ "outputs",
177
+ "unsloth_compiled_cache",
178
+ ]
179
+
180
+ commit_info = api.upload_folder(
181
+ folder_path=str(repo_dir),
182
+ repo_id=space_id,
183
+ repo_type="space",
184
+ commit_message="chore: sync repository for validation",
185
+ ignore_patterns=ignore_patterns,
186
+ )
187
+ print(f"[OK] Upload complete: {commit_info.oid}")
188
+
189
+ if not args.skip_secrets:
190
+ env_values = read_env_file(repo_dir)
191
+ secret_pairs: list[tuple[str, str]] = []
192
+ for key in ("API_BASE_URL", "MODEL_NAME", "HF_TOKEN"):
193
+ value = pick_var(key, env_values)
194
+ if value is not None:
195
+ secret_pairs.append((key, value))
196
+
197
+ if secret_pairs:
198
+ set_required_space_secrets(api, space_id, secret_pairs)
199
+ else:
200
+ print("[WARN] No non-placeholder runtime variables found for Space secrets.")
201
+
202
+ space_url = to_runtime_space_url(space_id)
203
+ print(f"[NEXT] Ping URL: {space_url}")
204
+ print(f"[NEXT] Run: ./scripts/validate-submission.sh {space_url} {repo_dir}")
205
+ return 0
206
+
207
+
208
+ if __name__ == "__main__":
209
+ raise SystemExit(main())
scripts/ping_env.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ping a Space or local server and verify reset() works."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+
8
+ import requests
9
+
10
+
11
+ def main() -> int:
12
+ if len(sys.argv) != 2:
13
+ print("Usage: python scripts/ping_env.py <base_url>")
14
+ return 1
15
+
16
+ base_url = sys.argv[1].rstrip("/")
17
+ health = requests.get(f"{base_url}/health", timeout=10)
18
+ print(f"health_status={health.status_code}")
19
+ health.raise_for_status()
20
+
21
+ reset = requests.post(f"{base_url}/reset", json={"task_id": "delhi_monsoon_recovery_easy"}, timeout=20)
22
+ print(f"reset_status={reset.status_code}")
23
+ reset.raise_for_status()
24
+ payload = reset.json()
25
+ print(json.dumps({"task_id": payload["observation"]["task_id"], "done": payload["done"]}, indent=2))
26
+ return 0
27
+
28
+
29
+ if __name__ == "__main__":
30
+ raise SystemExit(main())
scripts/pre_submission_validate.sh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
+ REPO_DIR_INPUT="${1:-$SCRIPT_DIR/..}"
6
+ REPO_DIR="$(cd "$REPO_DIR_INPUT" && pwd)"
7
+ PING_URL="${PING_URL:-}"
8
+
9
+ echo "Step 0/5: Checking release branch hygiene"
10
+ bash "$REPO_DIR/scripts/check_release_hygiene.sh" "$REPO_DIR"
11
+
12
+ if [ -n "$PING_URL" ]; then
13
+ echo "Step 1/5: Pinging deployed Space"
14
+ python "$REPO_DIR/scripts/ping_env.py" "$PING_URL"
15
+ fi
16
+
17
+ echo "Step 2/5: Building Docker image"
18
+ docker build "$REPO_DIR"
19
+
20
+ echo "Step 3/5: Running OpenEnv validation"
21
+ python -m openenv.cli validate "$REPO_DIR"
22
+
23
+ echo "Step 4/5: Running task graders"
24
+ python "$REPO_DIR/scripts/run_graders.py"
25
+
26
+ echo "Validation completed successfully."
scripts/run_graders.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Enumerate tasks, run the graders, and assert strict score ranges."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ ROOT = Path(__file__).resolve().parent.parent
9
+ import sys
10
+
11
+ if str(ROOT) not in sys.path:
12
+ sys.path.insert(0, str(ROOT))
13
+
14
+ from engine import simulate_plan
15
+ from graders import grade_task
16
+ from models import ATCOptimizationObservation
17
+ from planner import build_heuristic_plan, build_refined_plan
18
+ from tasks import ordered_tasks, render_task_briefing
19
+
20
+
21
+ def main() -> int:
22
+ rows = []
23
+ for task in ordered_tasks():
24
+ observation = ATCOptimizationObservation(
25
+ task_id=task.task_id,
26
+ task_title=task.title,
27
+ difficulty=task.difficulty,
28
+ airport=task.airport,
29
+ briefing=render_task_briefing(task),
30
+ objective=task.objective,
31
+ grading_focus=task.grading_focus,
32
+ flights=task.flights,
33
+ runways=task.runways,
34
+ steps_remaining=task.max_steps,
35
+ )
36
+ seed_plan = build_heuristic_plan(observation)
37
+ proposal = build_refined_plan(observation, seed_plan=seed_plan)
38
+ outcome = simulate_plan(task, proposal)
39
+ grades = grade_task(task, outcome, proposal, "Deterministic two-step baseline.")
40
+ for grade in grades:
41
+ assert 0.0 < grade.score < 1.0, f"{grade.grader_name} out of strict range for {task.task_id}"
42
+ rows.append(
43
+ {
44
+ "task_id": task.task_id,
45
+ "difficulty": task.difficulty.value,
46
+ "seed_operational_score": simulate_plan(task, seed_plan).metrics.overall_score,
47
+ "operational_score": outcome.metrics.overall_score,
48
+ "grader_scores": {grade.grader_name: grade.score for grade in grades},
49
+ }
50
+ )
51
+ print(json.dumps(rows, indent=2))
52
+ return 0
53
+
54
+
55
+ if __name__ == "__main__":
56
+ raise SystemExit(main())
scripts/run_local_checklist.ps1 ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ $ErrorActionPreference = "Stop"
2
+
3
+ Set-StrictMode -Version Latest
4
+
5
+ $RepoRoot = Split-Path -Parent $PSScriptRoot
6
+ Set-Location $RepoRoot
7
+
8
+ function Write-Step {
9
+ param([string]$Message)
10
+ Write-Host ""
11
+ Write-Host "==> $Message" -ForegroundColor Cyan
12
+ }
13
+
14
+ function Invoke-CheckedCommand {
15
+ param(
16
+ [Parameter(Mandatory = $true)]
17
+ [string]$FilePath,
18
+
19
+ [Parameter(ValueFromRemainingArguments = $true)]
20
+ [string[]]$Arguments
21
+ )
22
+
23
+ & $FilePath @Arguments
24
+ if ($LASTEXITCODE -ne 0) {
25
+ throw "Command failed: $FilePath $($Arguments -join ' ')"
26
+ }
27
+ }
28
+
29
+ function Get-UvCommand {
30
+ $uv = Get-Command uv -ErrorAction SilentlyContinue
31
+ if ($null -ne $uv) {
32
+ return $uv.Source
33
+ }
34
+
35
+ $candidate = Join-Path $env:APPDATA "Python\Python314\Scripts\uv.exe"
36
+ if (Test-Path $candidate) {
37
+ return $candidate
38
+ }
39
+
40
+ return $null
41
+ }
42
+
43
+ function Get-PythonCommand {
44
+ $venvPython = Join-Path $RepoRoot ".venv\Scripts\python.exe"
45
+ if (Test-Path $venvPython) {
46
+ return $venvPython
47
+ }
48
+
49
+ $python = Get-Command python -ErrorAction SilentlyContinue
50
+ if ($null -ne $python) {
51
+ return $python.Source
52
+ }
53
+
54
+ throw "Python was not found. Run uv sync first or install Python."
55
+ }
56
+
57
+ function Wait-ForHealth {
58
+ param(
59
+ [string]$BaseUrl,
60
+ [int]$TimeoutSeconds = 30
61
+ )
62
+
63
+ $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
64
+ while ((Get-Date) -lt $deadline) {
65
+ try {
66
+ $response = Invoke-WebRequest -Uri "$BaseUrl/health" -UseBasicParsing -TimeoutSec 3
67
+ if ($response.StatusCode -eq 200) {
68
+ return
69
+ }
70
+ } catch {
71
+ }
72
+ Start-Sleep -Milliseconds 500
73
+ }
74
+
75
+ throw "Timed out waiting for server health at $BaseUrl"
76
+ }
77
+
78
+ $uv = Get-UvCommand
79
+ if ($null -ne $uv) {
80
+ Write-Step "Syncing local environment"
81
+ Invoke-CheckedCommand $uv "sync" "--frozen" "--extra" "dev"
82
+ }
83
+
84
+ $python = Get-PythonCommand
85
+ $serverProcess = $null
86
+ $baseUrl = "http://127.0.0.1:8000"
87
+
88
+ try {
89
+ Write-Step "OpenEnv validation"
90
+ Invoke-CheckedCommand $python "-m" "openenv.cli" "validate" "."
91
+
92
+ Write-Step "Unit tests"
93
+ Invoke-CheckedCommand $python "-m" "pytest" "tests\test_env.py"
94
+
95
+ Write-Step "Task graders"
96
+ Invoke-CheckedCommand $python "scripts\run_graders.py"
97
+
98
+ Write-Step "Starting local server"
99
+ $serverProcess = Start-Process `
100
+ -FilePath $python `
101
+ -ArgumentList @("-m", "uvicorn", "server.app:app", "--host", "127.0.0.1", "--port", "8000") `
102
+ -WorkingDirectory $RepoRoot `
103
+ -PassThru
104
+
105
+ Wait-ForHealth -BaseUrl $baseUrl
106
+
107
+ Write-Step "Ping + reset smoke test"
108
+ Invoke-CheckedCommand $python "scripts\ping_env.py" $baseUrl
109
+
110
+ Write-Step "Baseline inference"
111
+ Invoke-CheckedCommand $python "inference.py"
112
+
113
+ $docker = Get-Command docker -ErrorAction SilentlyContinue
114
+ if ($null -eq $docker) {
115
+ Write-Host ""
116
+ Write-Host "Docker not found, skipping docker build." -ForegroundColor Yellow
117
+ } else {
118
+ $dockerAvailable = $false
119
+ $stdoutPath = [System.IO.Path]::GetTempFileName()
120
+ $stderrPath = [System.IO.Path]::GetTempFileName()
121
+ try {
122
+ $probe = Start-Process `
123
+ -FilePath $docker.Source `
124
+ -ArgumentList @("info") `
125
+ -NoNewWindow `
126
+ -Wait `
127
+ -PassThru `
128
+ -RedirectStandardOutput $stdoutPath `
129
+ -RedirectStandardError $stderrPath
130
+ $dockerAvailable = ($probe.ExitCode -eq 0)
131
+ } finally {
132
+ Remove-Item -LiteralPath $stdoutPath -ErrorAction SilentlyContinue
133
+ Remove-Item -LiteralPath $stderrPath -ErrorAction SilentlyContinue
134
+ }
135
+
136
+ if ($dockerAvailable) {
137
+ Write-Step "Docker build"
138
+ Invoke-CheckedCommand $docker.Source "build" "-t" "atc-openenv-local" "."
139
+ } else {
140
+ Write-Host ""
141
+ Write-Host "Docker engine is not available, skipping docker build." -ForegroundColor Yellow
142
+ }
143
+ }
144
+
145
+ Write-Host ""
146
+ Write-Host "Local checklist completed successfully." -ForegroundColor Green
147
+ } finally {
148
+ if ($null -ne $serverProcess -and -not $serverProcess.HasExited) {
149
+ Stop-Process -Id $serverProcess.Id -Force
150
+ }
151
+ }
scripts/smoke_reward_validation.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Five-episode smoke test for multi-agent reward signal validation.
2
+
3
+ This script is intentionally lightweight and does not require torch/trl/unsloth.
4
+ It validates the critical data path before expensive GRPO runs:
5
+
6
+ 1) raw planner output (JSON)
7
+ 2) parser round-trip (parse_aman_action / parse_dman_action)
8
+ 3) reward component traces (ATC_REWARD_TRACE=1)
9
+ 4) final environment composite/coordination outputs
10
+
11
+ Usage:
12
+ ATC_REWARD_TRACE=1 /home/keshav/ats/.venv/bin/python scripts/smoke_reward_validation.py
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ # Enable detailed component-level traces from reward_functions.
23
+ os.environ.setdefault("ATC_REWARD_TRACE", "1")
24
+ os.environ.setdefault("REWARD_FAILURE_MODE", "strict")
25
+
26
+ ROOT = Path(__file__).resolve().parent.parent
27
+ if str(ROOT) not in sys.path:
28
+ sys.path.insert(0, str(ROOT))
29
+
30
+ from tasks import ordered_tasks
31
+ from multi_agent.environment import MultiAgentATCEnvironment
32
+ from multi_agent.generator import ChallengeGenerator
33
+ from multi_agent.supervisor import SupervisorAgent
34
+ from multi_agent.inference import _build_aman_heuristic, _build_dman_heuristic
35
+ from training.dataset import parse_aman_action, parse_dman_action
36
+ from training.reward_functions import aman_reward_fn, dman_reward_fn
37
+
38
+
39
+ def main() -> None:
40
+ seed = 42
41
+ env = MultiAgentATCEnvironment(seed=seed)
42
+ generator = ChallengeGenerator(seed=seed)
43
+ supervisor = SupervisorAgent()
44
+ task_ids = [t.task_id for t in ordered_tasks()]
45
+
46
+ print("=== 5-EPISODE SMOKE TEST: reward-signal validation ===")
47
+
48
+ for ep in range(5):
49
+ task_id = task_ids[ep % len(task_ids)]
50
+ profile = supervisor.sample_profile(ep)
51
+
52
+ base_task = env._catalog[task_id]
53
+ mutated_task, _ = generator.mutate(base_task)
54
+
55
+ aman_obs, dman_obs = env.reset(
56
+ task_id=task_id,
57
+ episode_id=ep,
58
+ supervisor_profile=profile,
59
+ mutated_task=mutated_task,
60
+ )
61
+
62
+ # Heuristic proposals act as deterministic stand-in for model completions.
63
+ aman_action = _build_aman_heuristic(aman_obs)
64
+ dman_action = _build_dman_heuristic(dman_obs, env._state.atfm_deadlines)
65
+
66
+ raw_aman = json.dumps(
67
+ {
68
+ "arrival_slots": [s.model_dump() for s in aman_action.arrival_slots],
69
+ "rationale": aman_action.rationale,
70
+ "emergency_yields": aman_action.emergency_yields,
71
+ "outgoing_messages": [m.model_dump(mode="json") for m in aman_action.outgoing_messages],
72
+ "commit": aman_action.commit,
73
+ }
74
+ )
75
+ raw_dman = json.dumps(
76
+ {
77
+ "departure_slots": [s.model_dump() for s in dman_action.departure_slots],
78
+ "rationale": dman_action.rationale,
79
+ "atfm_compliance": dman_action.atfm_compliance,
80
+ "emergency_broadcasts": dman_action.emergency_broadcasts,
81
+ "outgoing_messages": [m.model_dump(mode="json") for m in dman_action.outgoing_messages],
82
+ "commit": dman_action.commit,
83
+ }
84
+ )
85
+
86
+ parsed_aman = parse_aman_action(raw_aman)
87
+ parsed_dman = parse_dman_action(raw_dman)
88
+
89
+ if parsed_aman is None or parsed_dman is None:
90
+ raise RuntimeError(f"Parser failure at episode {ep}")
91
+
92
+ _, _, _, done = env.step_bid(parsed_aman, parsed_dman)
93
+ if not done:
94
+ env.step_negotiate(parsed_aman, parsed_dman)
95
+ result = env.finalize()
96
+
97
+ aman_slots_json = json.dumps([s.model_dump() for s in parsed_aman.arrival_slots])
98
+ dman_slots_json = json.dumps([s.model_dump() for s in parsed_dman.departure_slots])
99
+ atfm_json = json.dumps(env._state.atfm_deadlines)
100
+
101
+ aman_r = aman_reward_fn(
102
+ [raw_aman],
103
+ task_id=[env._state.task.task_id],
104
+ supervisor_profile=[profile.value],
105
+ dman_slots_json=[dman_slots_json],
106
+ atfm_deadlines_json=[atfm_json],
107
+ )[0]
108
+ dman_r = dman_reward_fn(
109
+ [raw_dman],
110
+ task_id=[env._state.task.task_id],
111
+ supervisor_profile=[profile.value],
112
+ aman_slots_json=[aman_slots_json],
113
+ atfm_deadlines_json=[atfm_json],
114
+ )[0]
115
+
116
+ print(f"\n--- EPISODE {ep} ---")
117
+ print(f"task={env._state.task.task_id} profile={profile.value}")
118
+ print(f"raw_aman_len={len(raw_aman)} raw_dman_len={len(raw_dman)}")
119
+ print(
120
+ f"parsed_aman_slots={len(parsed_aman.arrival_slots)} "
121
+ f"parsed_dman_slots={len(parsed_dman.departure_slots)}"
122
+ )
123
+ print(f"aman_reward={aman_r} dman_reward={dman_r}")
124
+ print(
125
+ f"composite={result.composite_score} "
126
+ f"coord={result.per_role.coordination_score} "
127
+ f"conflicts={result.per_role.cross_lane_conflicts}"
128
+ )
129
+
130
+ print("\nSMOKE TEST PASSED: 5 episodes executed with reward traces and parsed actions.")
131
+
132
+
133
+ if __name__ == "__main__":
134
+ main()