File size: 32,495 Bytes
4058302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3648b5
4058302
 
 
 
c3648b5
4058302
 
eb2d131
4058302
 
 
 
 
 
 
 
 
 
 
eb2d131
4058302
 
 
 
 
 
c3648b5
02f3541
c3648b5
 
02f3541
c3648b5
02f3541
 
 
 
3c61da6
02f3541
 
c3648b5
4058302
 
 
 
 
 
c3648b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4058302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423c9d3
4058302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3648b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6883897
 
c3648b5
 
 
6883897
 
 
 
 
 
 
c3648b5
 
6883897
 
 
 
 
 
c3648b5
 
6883897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3648b5
 
 
 
 
 
 
 
6883897
c3648b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02f3541
 
 
c3648b5
 
 
 
 
 
 
 
 
 
 
 
 
 
4058302
423c9d3
 
 
4058302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6883897
4058302
 
 
6883897
4058302
6883897
c3648b5
4058302
 
 
c3648b5
6883897
4058302
 
 
c3648b5
4058302
 
 
c3648b5
6883897
02f3541
 
 
 
 
6883897
 
 
02f3541
6883897
 
 
 
02f3541
c3648b5
 
 
 
 
 
 
02f3541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4058302
423c9d3
 
4058302
 
 
 
 
c3648b5
4058302
 
c3648b5
 
 
02f3541
 
 
4058302
 
 
 
 
 
c3648b5
02f3541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbdbde
02f3541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3648b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4058302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3648b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4058302
 
 
 
 
 
 
 
 
 
 
 
c3648b5
4058302
 
 
 
 
 
c3648b5
 
 
4058302
 
c3648b5
4058302
c3648b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a036134
c3648b5
4058302
 
 
 
 
423c9d3
4058302
 
 
02f3541
 
 
 
 
 
 
 
 
 
 
 
 
4058302
 
 
 
 
 
 
 
 
423c9d3
 
 
 
 
4058302
 
423c9d3
 
4058302
eb2d131
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
ο»Ώ"""FastAPI entry-point for the Incident Command Center environment.

Besides the OpenEnv contract endpoints (`/reset`, `/step`, `/state`, `/close`)
registered by `create_fastapi_app`, this module exposes:

- `GET /` and `GET /web` β€” interactive HTML dashboard.
- `GET /healthz` β€” liveness / readiness probe for orchestrators.
- `GET /version` β€” build metadata.
- `GET /metadata` β€” static environment metadata (action space, reward model).
- `GET /metrics` β€” lightweight in-process counters (best-effort).

The dashboard is written inline so the environment ships as a single
directory and can be embedded in Hugging Face Spaces without extra assets.
"""

from __future__ import annotations

import json
import logging
from pathlib import Path
from typing import Any, Dict

import uvicorn
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
from fastapi.staticfiles import StaticFiles
from openenv.core.env_server import create_fastapi_app

from models import IncidentAction, IncidentObservation
from server.config import EnvConfig
from server.domain import ALL_ACTIONS, ALL_ROLES, build_incident_library
from server.domain.reward import (
    CLOSURE_CORRECT_BASE,
    CLOSURE_WRONG_PENALTY,
    CLUE_REWARD,
    HANDOFF_CORRECT_REWARD,
    MITIGATION_CORRECT_REWARD,
    STEP_COST_INVESTIGATION,
    TIER_MULTIPLIER,
)
from server.environment import IncidentCommandCenterEnvironment
from server.logging_utils import configure_logging

_LOG = logging.getLogger("icc.app")
_CONFIG = EnvConfig.from_env()
configure_logging(level=_CONFIG.log_level, structured=_CONFIG.structured_logging)

# External URLs surfaced on the dashboard so judges can jump straight from
# the HF Space to the GitHub / Colab / docs / training artifacts.
GITHUB_URL = "https://github.com/SwapnilPatil28/Multi-Agent-Incident-Command-Center"
SPACE_PAGE_URL = "https://huggingface.co/spaces/SwapnilPatil28/Multi-Agent-Incident-Command-Center"
SPACE_APP_URL = "https://swapnilpatil28-multi-agent-incident-command-center.hf.space"
COLAB_URL = "https://colab.research.google.com/drive/1vx9E5FrZZrHoRwXs2cvtom3DaI6kZ3LP?usp=sharing"
# Dashboard doc links point at the Hugging Face Space copies of the docs (not
# GitHub) so a judge who opens the Space stays inside the HF ecosystem. The
# README on the Space page is rendered directly, so we point at the Space
# root for it; the other three open the HF file browser.
README_URL = f"{SPACE_PAGE_URL}/blob/main/README.md"
BLOG_POST_URL = f"{SPACE_PAGE_URL}/blob/main/docs/BLOG_POST.md"
SUBMISSION_CHECKLIST_URL = f"{SPACE_PAGE_URL}/blob/main/docs/SUBMISSION_CHECKLIST.md"

app = create_fastapi_app(
    IncidentCommandCenterEnvironment,
    IncidentAction,
    IncidentObservation,
)

# Serve the committed training-evidence artifacts (reward_curve.png,
# training_curve.png, reward_components.png, summary_metrics.json, ...)
# so the dashboard can embed them without depending on external hosts.
_ARTIFACTS_DIR = Path(__file__).resolve().parent.parent / "artifacts"
if _ARTIFACTS_DIR.exists():
    app.mount(
        "/artifacts",
        StaticFiles(directory=str(_ARTIFACTS_DIR)),
        name="artifacts",
    )


def _load_summary_metrics() -> Dict[str, Any]:
    """Best-effort load of the committed training results for the dashboard."""
    path = _ARTIFACTS_DIR / "summary_metrics.json"
    if not path.exists():
        return {}
    try:
        with path.open("r", encoding="utf-8") as fh:
            return json.load(fh)
    except (OSError, json.JSONDecodeError):
        return {}


# ---------------------------------------------------------------------------
# Introspection helpers
# ---------------------------------------------------------------------------


def _resolve_environment() -> IncidentCommandCenterEnvironment | None:
    """Best-effort retrieval of the running environment instance.

    OpenEnv versions differ in where they stash the environment, so we try a
    few well-known attribute names before giving up.
    """
    for attr in ("environment", "env", "_environment"):
        env = getattr(app.state, attr, None)
        if env is not None:
            return env  # type: ignore[return-value]
    return None


def _metadata_payload() -> Dict[str, Any]:
    library = build_incident_library()
    return {
        "name": _CONFIG.name,
        "version": _CONFIG.version,
        "tasks": library.tasks(),
        "incidents_per_task": {
            task: len(library.templates_for(task)) for task in library.tasks()
        },
        "actions": list(ALL_ACTIONS),
        "roles": list(ALL_ROLES),
        "reward_model": {
            "step_cost_investigation": STEP_COST_INVESTIGATION,
            "clue_reward": CLUE_REWARD,
            "handoff_correct": HANDOFF_CORRECT_REWARD,
            "mitigation_correct": MITIGATION_CORRECT_REWARD,
            "closure_correct_base": CLOSURE_CORRECT_BASE,
            "closure_wrong": CLOSURE_WRONG_PENALTY,
            "tier_multiplier": TIER_MULTIPLIER,
        },
        "budgets": {
            "easy": _CONFIG.easy_budget,
            "medium": _CONFIG.medium_budget,
            "hard": _CONFIG.hard_budget,
        },
        "sla_minutes": {
            "easy": _CONFIG.easy_sla_minutes,
            "medium": _CONFIG.medium_sla_minutes,
            "hard": _CONFIG.hard_sla_minutes,
        },
    }


# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------


@app.get("/healthz", response_class=JSONResponse)
async def healthz() -> JSONResponse:
    return JSONResponse(
        {
            "status": "ok",
            "name": _CONFIG.name,
            "version": _CONFIG.version,
        }
    )


@app.get("/version", response_class=JSONResponse)
async def version() -> JSONResponse:
    return JSONResponse(
        {
            "name": _CONFIG.name,
            "version": _CONFIG.version,
            "default_seed": _CONFIG.default_seed,
        }
    )


@app.get("/env-info", response_class=JSONResponse)
async def env_info() -> JSONResponse:
    """Rich metadata about the environment (rubric, budgets, taxonomy)."""
    return JSONResponse(_metadata_payload())


@app.get("/metrics", response_class=PlainTextResponse)
async def metrics() -> PlainTextResponse:
    env = _resolve_environment()
    lines = [
        f'icc_info{{name="{_CONFIG.name}",version="{_CONFIG.version}"}} 1',
    ]
    if env is not None and env.state is not None:
        s = env.state
        lines += [
            f'icc_episode_step_total {s.step_count}',
            f'icc_cumulative_reward {s.cumulative_reward}',
            f'icc_incidents_resolved_total {s.incidents_resolved}',
            f'icc_incidents_failed_total {s.incidents_failed}',
            f'icc_budget_remaining {s.budget_remaining}',
            f'icc_sla_minutes_remaining {s.sla_minutes_remaining}',
            f'icc_current_incident_index {s.current_incident_index}',
        ]
    return PlainTextResponse("\n".join(lines) + "\n")


@app.get("/", response_class=HTMLResponse)
@app.get("/web", response_class=HTMLResponse)
async def root() -> HTMLResponse:
    return HTMLResponse(_dashboard_html())


def _dashboard_html() -> str:
    metadata_json = json.dumps(_metadata_payload(), indent=2)
    metrics = _load_summary_metrics()
    artifacts_available = _ARTIFACTS_DIR.exists() and (
        _ARTIFACTS_DIR / "reward_curve.png"
    ).exists()

    # --- Headline training numbers (1.5B SFT vs base, hard task) -------------
    base_rewards = metrics.get("base_model_rewards") or [0.0, 0.0, 0.0]
    sft_rewards = metrics.get("sft_model_rewards") or [0.0, 0.0, 0.0]
    improvement = metrics.get("improvement_sft_over_base") or [0.0, 0.0, 0.0]
    headline_delta = improvement[2] if len(improvement) >= 3 else 0.0

    def _fmt(val: Any) -> str:
        try:
            return f"{float(val):+.2f}"
        except (TypeError, ValueError):
            return "β€”"

    training_rows = "".join(
        f"<tr><td>{tier}</td><td>{_fmt(base_rewards[idx])}</td>"
        f"<td>{_fmt(sft_rewards[idx])}</td>"
        f"<td class='delta'>{_fmt(improvement[idx])}</td></tr>"
        for idx, tier in enumerate(("easy", "medium", "hard"))
        if idx < len(base_rewards)
    )

    # --- Training-evidence block (plots + caption) ---------------------------
    if artifacts_available:
        plots_html = """
    <h2>Training evidence</h2>
    <p class='sub'>
      Committed artifacts from the reference training run
      (Qwen2.5-1.5B-Instruct, 8 episodes/task, 3 epochs) plus the
      Qwen2.5-0.5B-Instruct ablation. Click any plot to open it full-size.
    </p>
    <div class='plots'>
      <figure>
        <a href='/artifacts/reward_curve.png' target='_blank' rel='noopener'>
          <img src='/artifacts/reward_curve.png' alt='Reward curve by policy (1.5B)' loading='lazy' />
        </a>
        <figcaption><strong>1.5B reward curve.</strong> Mean episodic reward per task tier
        across Random / Heuristic / Base-LLM / SFT-LLM. SFT matches the heuristic
        demonstrator across every tier and outperforms the untuned base by
        <strong>+{hard}</strong> on hard incidents.</figcaption>
      </figure>
      <figure>
        <a href='/artifacts/training_curve.png' target='_blank' rel='noopener'>
          <img src='/artifacts/training_curve.png' alt='SFT training loss and token accuracy (1.5B)' loading='lazy' />
        </a>
        <figcaption><strong>1.5B training curve.</strong> Supervised loss collapses from
        <code>~2.84 β†’ ~0.02</code> and next-token accuracy climbs from
        <code>~0.49 β†’ ~0.99</code> over three epochs on 680 rollout tokens.</figcaption>
      </figure>
      <figure>
        <a href='/artifacts/reward_components.png' target='_blank' rel='noopener'>
          <img src='/artifacts/reward_components.png' alt='Reward component decomposition (1.5B)' loading='lazy' />
        </a>
        <figcaption><strong>1.5B reward-component breakdown.</strong> SFT reproduces the
        heuristic's positive components (<code>clue_bonus</code>,
        <code>mitigation_correct</code>, <code>closure_correct</code>,
        <code>speed_bonus</code>) while the base model stalls on
        <code>step_cost</code> and SLA penalties.</figcaption>
      </figure>
      <figure>
        <a href='/artifacts/reward_curve_qwen0p5b.png' target='_blank' rel='noopener'>
          <img src='/artifacts/reward_curve_qwen0p5b.png' alt='Reward curve by policy (0.5B ablation)' loading='lazy' />
        </a>
        <figcaption><strong>0.5B ablation reward curve.</strong> Same pipeline, smaller
        backbone. SFT improves by only <strong>+0.43 / +0.14 / +0.00</strong> over base β€”
        the 0.5B model is too small to absorb the multi-step, role-gated policy.
        Scale is the story.</figcaption>
      </figure>
    </div>
    <p class='sub' style='margin-top:0.75rem'>
      Raw files:
      <a href='/artifacts/summary_metrics.json'>summary_metrics.json</a>
      Β·
      <a href='/artifacts/training_log.json'>training_log.json</a>
      Β·
      <a href='/artifacts/summary_metrics_qwen0p5b.json'>summary_metrics_qwen0p5b.json</a>
    </p>
""".format(hard=_fmt(headline_delta))
    else:
        plots_html = (
            "<h2>Training evidence</h2>"
            "<div class='card'><p class='sub'>Plots not bundled in this image. "
            "See the <a href='" + GITHUB_URL + "/tree/main/artifacts'>GitHub artifacts folder</a>.</p></div>"
        )

    # --- 0.5B ablation summary ----------------------------------------------
    ablation_html = """
    <h2>Ablation: model scale matters for imitation learning</h2>
    <div class='card'>
      <p class='sub'>
        Same pipeline, same data schema β€” only the base-model size differs. The 0.5B
        model cannot absorb the expert policy; 1.5B matches it exactly.
      </p>
      <div class='table-wrap'>
        <table>
          <thead>
            <tr>
              <th>Model</th><th>Easy Ξ”</th><th>Medium Ξ”</th><th>Hard Ξ”</th>
              <th>Heuristic match?</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Qwen2.5-0.5B-Instruct</td>
              <td>+0.43</td><td>+0.14</td><td class='delta'>+0.00</td>
              <td>No (stuck on step-cost)</td>
            </tr>
            <tr>
              <td><strong>Qwen2.5-1.5B-Instruct</strong></td>
              <td>-1.80</td><td>+3.13</td><td class='delta good'>+10.17</td>
              <td><strong>Yes (exact match)</strong></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
"""

    # Theme mapping now lives in the top story block β€” keep this var empty
    # so the existing `{themes_html}` slot renders to nothing (no duplication).
    themes_html = ""

    # --- Reward-rubric details ----------------------------------------------
    reward_rubric_rows = "".join(
        f"<tr><td><code>{name}</code></td><td>{value}</td></tr>"
        for name, value in (
            ("step_cost", f"{STEP_COST_INVESTIGATION} per investigation step"),
            ("clue_reward", f"+{CLUE_REWARD} per new fact"),
            ("handoff_correct", f"+{HANDOFF_CORRECT_REWARD}"),
            ("mitigation_correct", f"+{MITIGATION_CORRECT_REWARD}"),
            ("closure_correct_base", f"+{CLOSURE_CORRECT_BASE} Γ— tier multiplier"),
            ("closure_wrong", f"{CLOSURE_WRONG_PENALTY} Γ— tier multiplier"),
        )
    )

    return f"""
<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Incident Command Center | OpenEnv Dashboard</title>
  <style>
    :root {{
      --primary:#3b82f6; --accent:#22d3ee; --bg:#0f172a;
      --card:#111c31; --card-2:#152238; --text:#e2e8f0; --muted:#94a3b8;
      --good:#22c55e; --bad:#ef4444; --warn:#f59e0b;
    }}
    * {{ box-sizing: border-box; }}
    body {{
      font-family: -apple-system, 'Segoe UI', sans-serif;
      background: radial-gradient(1000px 600px at 10% -10%, #1e293b, var(--bg));
      color: var(--text); padding: 2rem; margin: 0; min-height: 100vh;
    }}
    header {{ display:flex; align-items:center; justify-content:space-between; max-width:1200px; margin:0 auto 1.5rem; flex-wrap:wrap; gap:1rem; }}
    .brand {{ display:flex; align-items:center; gap:0.75rem; }}
    .logo {{ width:44px; height:44px; border-radius:10px; background:linear-gradient(135deg,var(--primary),var(--accent)); }}
    h1 {{ font-size:1.6rem; margin:0; }}
    h2 {{ font-size:1.25rem; margin:1.8rem 0 0.6rem; color:#cbd5e1; }}
    .sub {{ color: var(--muted); }}
    .grid {{ display:grid; grid-template-columns: repeat(auto-fit,minmax(240px,1fr)); gap:1rem; max-width:1200px; margin:0 auto; }}
    .grid-3 {{ grid-template-columns: repeat(auto-fit,minmax(280px,1fr)); }}
    .card {{ background: var(--card); border: 1px solid #1f2a44; padding: 1.25rem; border-radius: 14px; }}
    .card h3 {{ margin:0 0 0.5rem; font-size:1rem; color:#f1f5f9; }}
    .pill {{ display:inline-block; padding:2px 8px; margin:2px; border-radius:999px; background:#1e293b; border:1px solid #334155; color:#cbd5e1; font-size:0.78rem; }}
    .pill.cta {{ background:linear-gradient(135deg,var(--primary),var(--accent)); color:#0b1225; border-color:transparent; font-weight:600; }}
    .container {{ max-width: 1200px; margin: 0 auto; }}
    code {{ background:#0b1225; border:1px solid #1f2a44; padding:2px 6px; border-radius:6px; color:#67e8f9; font-family:'JetBrains Mono', monospace; }}
    pre {{ background:#0b1225; border:1px solid #1f2a44; padding: 1rem; border-radius: 10px; color:#cbd5e1; overflow-x:auto; font-size:0.85rem; }}
    a {{ color: var(--accent); text-decoration: none; }}
    a:hover {{ text-decoration: underline; }}
    .kpi {{ display:flex; flex-direction:column; gap:0.25rem; }}
    .kpi .num {{ font-size:1.6rem; font-weight:700; color:#f8fafc; }}
    .kpi .lbl {{ color: var(--muted); font-size:0.8rem; }}
    .kpi .num.good {{ color: var(--good); }}
    footer {{ max-width:1200px; margin:2rem auto 0; color:var(--muted); font-size:0.85rem; }}
    /* Training-evidence plots: one plot per row, centred, with a tighter
       max-width so the charts read as compact figures rather than banners.
       Click the image to open the full-resolution PNG in a new tab. */
    .plots {{ display:flex; flex-direction:column; gap:1.25rem; max-width:1200px; margin:0 auto; }}
    .plots figure {{ background: var(--card); border:1px solid #1f2a44; border-radius: 14px; padding: 1rem 1.25rem; margin:0; }}
    .plots figure a {{ display:block; }}
    .plots img {{
      width:100%; height:auto; display:block;
      max-width:720px; margin:0 auto;
      border-radius:10px; background:#0b1225;
      transition: transform 0.2s ease;
    }}
    .plots img:hover {{ transform: scale(1.01); }}
    .plots figcaption {{ color: var(--muted); font-size:0.9rem; margin-top:0.6rem; line-height:1.55; text-align:center; max-width:720px; margin-left:auto; margin-right:auto; }}
    .table-wrap {{ overflow-x:auto; }}
    table {{ width:100%; border-collapse: collapse; margin-top:0.5rem; font-size:0.9rem; }}
    th, td {{ padding:0.5rem 0.75rem; text-align:left; border-bottom:1px solid #1f2a44; }}
    th {{ color:#cbd5e1; font-weight:600; }}
    td.delta {{ font-weight:600; color:#f8fafc; }}
    td.delta.good {{ color: var(--good); }}
    .links {{ display:flex; flex-wrap:wrap; gap:0.5rem; }}

    /* "Story in 2 minutes" hero panel β€” plain-English summary for judges. */
    .hero-card {{
      background: linear-gradient(135deg, #0f2647 0%, #172a4a 60%, #1f2a44 100%);
      border: 1px solid #1f2a44; border-radius: 16px;
      padding: 1.75rem 1.75rem 1.5rem; margin: 0 auto 1.5rem;
      max-width: 1200px; box-shadow: 0 6px 30px rgba(34,211,238,0.08);
    }}
    .hero-card h2 {{ font-size:1.35rem; margin:0 0 0.4rem; color:#f1f5f9; }}
    .hero-card h3 {{ font-size:1rem; color:#e2e8f0; margin:0 0 0.3rem; }}
    .hero-card .lede {{
      font-size:1.02rem; line-height:1.6; color:#e2e8f0;
      background:#0b1225; border-left: 3px solid var(--accent);
      padding: 0.9rem 1.1rem; border-radius: 6px; margin: 0.3rem 0 0;
    }}
    .hero-card .lede strong {{ color:#f8fafc; }}
    .hero-card table {{ font-size:0.92rem; }}
    .hero-card .card {{ background: #0e1a30; }}

    /* "Resources & documentation" click-through cards. */
    .res-card {{
      display:block; color: var(--text); text-decoration:none;
      background: var(--card); border:1px solid #1f2a44; border-radius:12px;
      padding: 1rem 1.1rem;
      transition: transform 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease;
    }}
    .res-card:hover {{
      border-color: var(--accent); transform: translateY(-2px);
      box-shadow: 0 8px 24px rgba(34,211,238,0.12);
      text-decoration:none;
    }}
    .res-icon {{ font-size:1.6rem; line-height:1; margin-bottom:0.5rem; }}
    .res-title {{ font-weight:600; color:#f1f5f9; margin-bottom:0.2rem; }}
  </style>
</head>
<body>
  <header>
    <div class='brand'>
      <div class='logo'></div>
      <div>
        <h1>Incident Command Center</h1>
        <div class='sub'>OpenEnv Β· Multi-Agent Β· Long-Horizon Β· Professional-Task Simulation</div>
      </div>
    </div>
    <div class='links'>
      <a class='pill cta' href='{GITHUB_URL}' target='_blank' rel='noopener'>GitHub</a>
      <a class='pill cta' href='{COLAB_URL}' target='_blank' rel='noopener'>Open in Colab</a>
      <a class='pill cta' href='{README_URL}' target='_blank' rel='noopener'>README</a>
      <a class='pill cta' href='{BLOG_POST_URL}' target='_blank' rel='noopener'>Blog post</a>
      <a class='pill' href='{SPACE_PAGE_URL}' target='_blank' rel='noopener'>HF Space page</a>
      <span class='pill'>v{_CONFIG.version}</span>
      <span class='pill'>task: easy / medium / hard</span>
    </div>
  </header>

  <div class='container'>

    <!-- ============================================================ -->
    <!-- PART 1 β€” Plain-English story for non-technical judges        -->
    <!-- ============================================================ -->
    <div class='hero-card'>
      <h2 style='margin-top:0'>🚨 The story in 2 minutes</h2>
      <p class='lede'>
        When a real tech company has an outage, <strong>three people's phones
        buzz at once</strong> β€” a Triage engineer, an Investigator, and an Ops
        Manager. They have to cooperate under a ticking <strong>SLA clock</strong>,
        every action costs <strong>budget</strong>, and every wrong call costs
        <strong>real money</strong> (enterprise outages hurt ~3Γ— more than free-tier).
        <br /><br />
        We built a simulator of that war room β€” and we fine-tuned an LLM to run it
        <strong>as well as the human expert</strong>.
      </p>

      <h3 style='margin-top:1.25rem'>What is the environment?</h3>
      <p class='sub' style='margin:0 0 0.75rem'>
        Three specialist agents with <strong>different permissions</strong> resolve
        a live queue of 13 realistic tech incidents across 3 difficulty tiers.
      </p>
      <div class='table-wrap'>
        <table>
          <thead>
            <tr><th>Role</th><th>Can do</th><th>Cannot do</th></tr>
          </thead>
          <tbody>
            <tr>
              <td>πŸ” <strong>Triage</strong></td>
              <td>Pull logs Β· check metrics Β· consult KB</td>
              <td>Close a ticket</td>
            </tr>
            <tr>
              <td>πŸ§ͺ <strong>Investigator</strong></td>
              <td>Apply a fix Β· roll back a deploy</td>
              <td>Escalate or file a post-mortem</td>
            </tr>
            <tr>
              <td>πŸ‘· <strong>Ops Manager</strong></td>
              <td>Escalate Β· file post-mortem Β· <strong>close the ticket</strong></td>
              <td>Apply a code fix</td>
            </tr>
          </tbody>
        </table>
      </div>

      <h3 style='margin-top:1.25rem'>What did the agent learn?</h3>
      <p class='sub' style='margin:0'>
        Not "pick the right label." It learned a whole workflow β€” dig up clues,
        hand off to the right specialist, apply the correct fix, respect the SLA,
        file the post-mortem, close the ticket. The rubric makes every piece of
        that workflow <em>visible</em> as a named reward component, so you can
        see <em>why</em> the agent earned (or lost) points at every step.
      </p>

      <h3 style='margin-top:1.25rem'>Why it matters for the 3 hackathon themes</h3>
      <div class='grid grid-3'>
        <div class='card'>
          <h3>🀝 Theme #1 β€” Multi-Agent</h3>
          <p class='sub'>
            Three distinct roles with <strong>non-overlapping permissions</strong>.
            Wrong-actor calls β†’ <code>-0.08</code>. Correct handoff β†’ <code>+0.15</code>.
            Cooperation is <em>trained</em>, not hard-coded.
          </p>
        </div>
        <div class='card'>
          <h3>⏱️ Theme #2 β€” Long-Horizon</h3>
          <p class='sub'>
            Each episode runs <strong>3–5 sequential incidents</strong> over 20–60
            steps with a single ticking SLA clock. Big rewards (+0.80 Γ— tier) only
            fire after clues β†’ fix β†’ post-mortem. Sparse and delayed by design.
          </p>
        </div>
        <div class='card'>
          <h3>🏒 Theme #3 β€” Professional World-Model</h3>
          <p class='sub'>
            Real logs, metrics, KB articles, red-herring signals, customer tiers,
            SLA timers, revenue impact. Close an enterprise ticket wrong and it
            hurts ~3Γ— what a free-tier one does.
          </p>
        </div>
      </div>

      <p class='sub' style='margin-top:1rem;font-style:italic'>
        ↓ Keep scrolling for the headline numbers, training plots, ablation, and
        the full rubric. Or jump straight to the
        <a href='{README_URL}' target='_blank' rel='noopener'>README</a> or the
        <a href='{BLOG_POST_URL}' target='_blank' rel='noopener'>blog post</a>.
      </p>
    </div>

    <!-- ============================================================ -->
    <!-- Resources & documentation β€” every link the judges need       -->
    <!-- ============================================================ -->
    <h2>Resources &amp; documentation</h2>
    <div class='grid grid-3'>
      <a class='res-card' href='{GITHUB_URL}' target='_blank' rel='noopener'>
        <div class='res-icon'>πŸ’»</div>
        <div class='res-title'>GitHub repository</div>
        <div class='sub'>Full source, tests, Dockerfile, CI-ready</div>
      </a>
      <a class='res-card' href='{SPACE_PAGE_URL}' target='_blank' rel='noopener'>
        <div class='res-icon'>πŸ€—</div>
        <div class='res-title'>Hugging Face Space page</div>
        <div class='sub'>Repo view, build logs, discussions</div>
      </a>
      <a class='res-card' href='{SPACE_APP_URL}' target='_blank' rel='noopener'>
        <div class='res-icon'>🟒</div>
        <div class='res-title'>Live environment</div>
        <div class='sub'>You are here β€” OpenEnv endpoints live</div>
      </a>
      <a class='res-card' href='{COLAB_URL}' target='_blank' rel='noopener'>
        <div class='res-icon'>πŸŽ“</div>
        <div class='res-title'>Reproduce training (Colab T4)</div>
        <div class='sub'>One-click notebook, ~1 h wall clock</div>
      </a>
      <a class='res-card' href='{README_URL}' target='_blank' rel='noopener'>
        <div class='res-icon'>πŸ“–</div>
        <div class='res-title'>README (Part 1 + Part 2)</div>
        <div class='sub'>Story overview + full technical deep-dive</div>
      </a>
      <a class='res-card' href='{BLOG_POST_URL}' target='_blank' rel='noopener'>
        <div class='res-icon'>πŸ“</div>
        <div class='res-title'>Mini blog post</div>
        <div class='sub'>The short writeup β€” MD file on the HF Space + GitHub</div>
      </a>
      <a class='res-card' href='{SUBMISSION_CHECKLIST_URL}' target='_blank' rel='noopener'>
        <div class='res-icon'>βœ…</div>
        <div class='res-title'>Submission checklist</div>
        <div class='sub'>Every judging rule β†’ where to find the evidence</div>
      </a>
    </div>

    <h2>Headline results</h2>
    <div class='grid'>
      <div class='card'>
        <div class='kpi'>
          <span class='lbl'>SFT reward lift on hard tasks</span>
          <span class='num good'>{_fmt(headline_delta)}</span>
          <span class='sub'>vs Qwen2.5-1.5B-Instruct base</span>
        </div>
      </div>
      <div class='card'>
        <div class='kpi'>
          <span class='lbl'>Heuristic-policy match</span>
          <span class='num'>Exact</span>
          <span class='sub'>SFT clones the demonstrator across every tier</span>
        </div>
      </div>
      <div class='card'>
        <div class='kpi'>
          <span class='lbl'>Scale ablation (hard Ξ”)</span>
          <span class='num'>0.5B β†’ 1.5B</span>
          <span class='sub'>+0.00 β†’ +10.17: capacity matters</span>
        </div>
      </div>
      <div class='card'>
        <div class='kpi'>
          <span class='lbl'>Training data</span>
          <span class='num'>680 rows</span>
          <span class='sub'>24 heuristic rollouts Β· 3 epochs</span>
        </div>
      </div>
    </div>

    <h2>Environment at a glance</h2>
    <div class='grid'>
      <div class='card'>
        <div class='kpi'>
          <span class='lbl'>Incidents in library</span>
          <span class='num' id='kpi-inc'>β€”</span>
        </div>
      </div>
      <div class='card'>
        <div class='kpi'>
          <span class='lbl'>Specialist roles</span>
          <span class='num'>3</span>
          <span class='sub'>triage Β· investigator Β· ops manager</span>
        </div>
      </div>
      <div class='card'>
        <div class='kpi'>
          <span class='lbl'>Reward components</span>
          <span class='num'>14+</span>
          <span class='sub'>rubric-based, transparent</span>
        </div>
      </div>
      <div class='card'>
        <div class='kpi'>
          <span class='lbl'>Seeded reproducibility</span>
          <span class='num'>Yes</span>
          <span class='sub'>default seed {_CONFIG.default_seed}</span>
        </div>
      </div>
    </div>

    <h2>1.5B SFT vs base (reference run)</h2>
    <div class='card'>
      <div class='table-wrap'>
        <table>
          <thead>
            <tr>
              <th>Task tier</th><th>Base reward</th><th>SFT reward</th><th>Ξ”</th>
            </tr>
          </thead>
          <tbody>
            {training_rows}
          </tbody>
        </table>
      </div>
      <p class='sub' style='margin-top:0.75rem'>
        Numbers loaded live from
        <a href='/artifacts/summary_metrics.json'>summary_metrics.json</a>
        committed alongside this Space.
      </p>
    </div>

    {plots_html}

    {ablation_html}

    {themes_html}

    <h2>Endpoints</h2>
    <div class='card'>
      <p class='sub'>Standard OpenEnv contract plus operational endpoints.</p>
      <ul>
        <li><code>POST /reset</code> β€” start a new episode (task_name, seed).</li>
        <li><code>POST /step</code> β€” submit an IncidentAction.</li>
        <li><code>GET /state</code> β€” full environment state.</li>
        <li><code>GET /healthz</code> β€” liveness probe.</li>
        <li><code>GET /version</code> β€” build information.</li>
        <li><code>GET /env-info</code> β€” action space, reward model, budgets.</li>
        <li><code>GET /metrics</code> β€” Prometheus-style counters.</li>
        <li><code>GET /docs</code> β€” interactive OpenAPI documentation.</li>
        <li><code>GET /artifacts/…</code> β€” committed training plots &amp; metrics.</li>
      </ul>
    </div>

    <h2>Action space</h2>
    <div class='card'>
      {"".join(f"<span class='pill'>{a}</span>" for a in ALL_ACTIONS)}
      <p class='sub' style='margin-top:0.5rem'>
        Each action is gated by the acting role; wrong-actor calls are penalised.
      </p>
    </div>

    <h2>Reward model</h2>
    <div class='card'>
      <p>
        Composable rubric with anti-gaming safeguards. Every step returns a
        <code>reward_components</code> dictionary so training curves are
        interpretable. Closure rewards and SLA penalties are scaled by
        customer-tier multipliers:
      </p>
      <p>
        {"".join(f"<span class='pill'>{tier}: x{mult}</span>" for tier, mult in TIER_MULTIPLIER.items())}
      </p>
      <div class='table-wrap'>
        <table>
          <thead><tr><th>Component</th><th>Signal</th></tr></thead>
          <tbody>{reward_rubric_rows}</tbody>
        </table>
      </div>
      <p class='sub' style='margin-top:0.75rem'>
        Full rubric (invalid-action, repeated-lookup, rollback-effective,
        post-mortem-logged, etc.) is documented in the
        <a href='https://huggingface.co/spaces/SwapnilPatil28/Multi-Agent-Incident-Command-Center/blob/main/README.md' target='_blank' rel='noopener'>README</a>.
      </p>
    </div>

    <h2>Metadata</h2>
    <div class='card'>
      <pre id='metadata-json'>{metadata_json}</pre>
    </div>
  </div>

  <footer>
    <div>
      <strong>Incident Command Center v{_CONFIG.version}</strong> Β· Built on
      <a href='https://github.com/meta-pytorch/openenv' target='_blank' rel='noopener'>OpenEnv</a>
      for the OpenEnv India 2026 Round 2 hackathon.
    </div>
    <div style='margin-top:0.4rem'>
      <a href='{GITHUB_URL}' target='_blank' rel='noopener'>GitHub</a> Β·
      <a href='{SPACE_PAGE_URL}' target='_blank' rel='noopener'>HF Space page</a> Β·
      <a href='{COLAB_URL}' target='_blank' rel='noopener'>Colab</a> Β·
      <a href='{README_URL}' target='_blank' rel='noopener'>README</a> Β·
      <a href='{BLOG_POST_URL}' target='_blank' rel='noopener'>Blog post</a> Β·
      <a href='{SUBMISSION_CHECKLIST_URL}' target='_blank' rel='noopener'>Submission checklist</a>
    </div>
  </footer>

  <script>
    try {{
      const data = {metadata_json};
      const total = Object.values(data.incidents_per_task || {{}}).reduce((a,b)=>a+b,0);
      document.getElementById('kpi-inc').textContent = total;
    }} catch (e) {{}}
  </script>
</body>
</html>
"""


def main() -> None:
    uvicorn.run(app, host="0.0.0.0", port=8000)


if __name__ == "__main__":
    main()