Spaces:
Sleeping
Sleeping
Daksh Verma commited on
Deploy submission build to my-env
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +18 -0
- .gitignore +9 -0
- Dockerfile +21 -0
- Makefile +39 -0
- README.md +442 -4
- inference.py +1329 -0
- openenv.yaml +20 -0
- pyproject.toml +43 -0
- requirements.txt +1 -0
- run_demo.py +86 -0
- server/Dockerfile +21 -0
- server/__init__.py +1 -0
- server/app.py +14 -0
- server/requirements.txt +8 -0
- unified_incident_env/README.md +10 -0
- unified_incident_env/__init__.py +17 -0
- unified_incident_env/client.py +35 -0
- unified_incident_env/interface.py +17 -0
- unified_incident_env/models.py +306 -0
- unified_incident_env/scripts/__init__.py +1 -0
- unified_incident_env/scripts/baseline_agent.py +97 -0
- unified_incident_env/scripts/walkthrough.py +41 -0
- unified_incident_env/server/__init__.py +1 -0
- unified_incident_env/server/app.py +113 -0
- unified_incident_env/server/challenge.py +882 -0
- unified_incident_env/server/environment.py +947 -0
- unified_incident_env/server/grader.py +193 -0
- unified_incident_env/tests/__init__.py +1 -0
- unified_incident_env/tests/test_environment.py +396 -0
- unified_incident_env/tests/test_submission_inference.py +324 -0
- unified_incident_env/tests/test_trainer.py +339 -0
- unified_incident_env/tests/test_trainer_session.py +545 -0
- unified_incident_env/trainer/__init__.py +24 -0
- unified_incident_env/trainer/action_adapter.py +204 -0
- unified_incident_env/trainer/analyze_failures.py +251 -0
- unified_incident_env/trainer/backend.py +165 -0
- unified_incident_env/trainer/build_datasets.py +258 -0
- unified_incident_env/trainer/build_sft_dataset.py +101 -0
- unified_incident_env/trainer/collect_trajectory.py +53 -0
- unified_incident_env/trainer/eval_models.py +145 -0
- unified_incident_env/trainer/parser.py +5 -0
- unified_incident_env/trainer/policy_adapter.py +64 -0
- unified_incident_env/trainer/prompts.py +434 -0
- unified_incident_env/trainer/reporting.py +227 -0
- unified_incident_env/trainer/run_episode.py +354 -0
- unified_incident_env/trainer/run_session.py +337 -0
- unified_incident_env/trainer/session_config.py +125 -0
- unified_incident_env/trainer/train_external.py +89 -0
- unified_incident_env/trainer/trajectory_memory.py +351 -0
- unified_incident_env/trainer/trajectory_store.py +33 -0
.dockerignore
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
.git/
|
| 5 |
+
.pytest_cache/
|
| 6 |
+
outputs/
|
| 7 |
+
.omx/
|
| 8 |
+
.codex/
|
| 9 |
+
AGENTS.md
|
| 10 |
+
sre_env/
|
| 11 |
+
*.egg-info/
|
| 12 |
+
dist/
|
| 13 |
+
build/
|
| 14 |
+
.gemini/
|
| 15 |
+
madhav_trial/
|
| 16 |
+
*.png
|
| 17 |
+
*.npz
|
| 18 |
+
node_modules/
|
.gitignore
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
.pytest_cache/
|
| 4 |
+
*.pyc
|
| 5 |
+
learning_curve.png
|
| 6 |
+
.omx/
|
| 7 |
+
.codex/
|
| 8 |
+
outputs/
|
| 9 |
+
AGENTS.md
|
Dockerfile
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
+
PYTHONUNBUFFERED=1 \
|
| 7 |
+
ENABLE_WEB_INTERFACE=true
|
| 8 |
+
|
| 9 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 10 |
+
build-essential \
|
| 11 |
+
curl \
|
| 12 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 13 |
+
|
| 14 |
+
COPY . /app
|
| 15 |
+
|
| 16 |
+
RUN pip install --no-cache-dir --upgrade pip && \
|
| 17 |
+
pip install --no-cache-dir .
|
| 18 |
+
|
| 19 |
+
EXPOSE 8000
|
| 20 |
+
|
| 21 |
+
CMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "8000"]
|
Makefile
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.PHONY: install dev test baseline walkthrough trainer-eval trainer-dataset trainer-session docker-build docker-run validate clean
|
| 2 |
+
|
| 3 |
+
install:
|
| 4 |
+
python3 -m pip install -e ".[dev]"
|
| 5 |
+
@echo "Dependencies installed"
|
| 6 |
+
|
| 7 |
+
dev:
|
| 8 |
+
ENABLE_WEB_INTERFACE=true uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
|
| 9 |
+
|
| 10 |
+
test:
|
| 11 |
+
pytest unified_incident_env/tests -v --tb=short
|
| 12 |
+
|
| 13 |
+
baseline:
|
| 14 |
+
python -m unified_incident_env.scripts.baseline_agent
|
| 15 |
+
|
| 16 |
+
walkthrough:
|
| 17 |
+
python -m unified_incident_env.scripts.walkthrough --scenario easy_sqli_db_outage
|
| 18 |
+
|
| 19 |
+
trainer-eval:
|
| 20 |
+
python -m unified_incident_env.trainer.eval_models --models qwen2.5:0.5b gemma2:2b qwen2.5:7b-instruct-q4_K_M --mode strict
|
| 21 |
+
|
| 22 |
+
trainer-dataset:
|
| 23 |
+
python -m unified_incident_env.trainer.build_sft_dataset --source combined --output outputs/trainer/sft_dataset.jsonl
|
| 24 |
+
|
| 25 |
+
trainer-session:
|
| 26 |
+
python -m unified_incident_env.trainer.run_session --model qwen2.5:0.5b --base-url http://127.0.0.1:8000
|
| 27 |
+
|
| 28 |
+
docker-build:
|
| 29 |
+
docker buildx build --platform linux/amd64 -t sre-env:latest .
|
| 30 |
+
|
| 31 |
+
docker-run:
|
| 32 |
+
docker run -p 8000:8000 -e ENABLE_WEB_INTERFACE=true sre-env:latest
|
| 33 |
+
|
| 34 |
+
validate:
|
| 35 |
+
openenv validate .
|
| 36 |
+
|
| 37 |
+
clean:
|
| 38 |
+
rm -rf outputs __pycache__ .pytest_cache
|
| 39 |
+
find . -name "*.pyc" -delete
|
README.md
CHANGED
|
@@ -1,10 +1,448 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: red
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Unified Incident Env
|
| 3 |
+
emoji: 🚨
|
| 4 |
+
colorFrom: blue
|
| 5 |
colorTo: red
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 8000
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# Unified Incident Env
|
| 12 |
+
|
| 13 |
+
A deterministic OpenEnv benchmark where agents resolve production incidents whose true root cause includes a security vulnerability.
|
| 14 |
+
|
| 15 |
+
`unified_incident_env` is one judge-facing environment. It is not a collection of mini-projects and it is not a toy task. Each episode starts as an operational outage, but the correct solution requires the agent to bridge SRE investigation with security remediation, then recover the system in the correct order and submit a postmortem.
|
| 16 |
+
|
| 17 |
+
## Submission Snapshot
|
| 18 |
+
|
| 19 |
+
Hackathon submission targets:
|
| 20 |
+
|
| 21 |
+
- GitHub repository: `https://github.com/dakshdoesdev/my-openenv`
|
| 22 |
+
- Hugging Face Space: `https://huggingface.co/spaces/gylder/my-env`
|
| 23 |
+
|
| 24 |
+
Submission-critical root files:
|
| 25 |
+
|
| 26 |
+
- `inference.py`
|
| 27 |
+
- `requirements.txt`
|
| 28 |
+
- `run_demo.py`
|
| 29 |
+
- `README.md`
|
| 30 |
+
- `Dockerfile`
|
| 31 |
+
- `openenv.yaml`
|
| 32 |
+
|
| 33 |
+
Checklist coverage:
|
| 34 |
+
|
| 35 |
+
- built with OpenEnv
|
| 36 |
+
- root `inference.py` uses the OpenAI client
|
| 37 |
+
- typed models plus `step()` / `reset()` / `state()` are implemented
|
| 38 |
+
- 3 deterministic tasks with easy -> medium -> hard progression
|
| 39 |
+
- Docker-based Hugging Face Space target is configured
|
| 40 |
+
- required inference environment variables are documented below
|
| 41 |
+
|
| 42 |
+
## Why This Benchmark Matters
|
| 43 |
+
|
| 44 |
+
Most agent benchmarks test operations or security in isolation. This benchmark forces both:
|
| 45 |
+
|
| 46 |
+
- operational symptoms appear first
|
| 47 |
+
- the real root cause can be security-rooted
|
| 48 |
+
- patching alone is not enough
|
| 49 |
+
- recovery alone is not enough
|
| 50 |
+
- the final postmortem must reflect the real causal chain
|
| 51 |
+
|
| 52 |
+
This is what makes it useful for evaluating incident-response agents rather than generic tool-using assistants.
|
| 53 |
+
|
| 54 |
+
## Why It Is Non-Trivial
|
| 55 |
+
|
| 56 |
+
The benchmark is intentionally built around causal traps:
|
| 57 |
+
|
| 58 |
+
- restarting the wrong service treats a symptom but does not fix the incident
|
| 59 |
+
- patching the wrong vulnerability or wrong patch family wastes steps and score
|
| 60 |
+
- recovering infrastructure before closing the exploit path can fail or regress
|
| 61 |
+
- weak agents often loop in investigation, security verification, or post-security recovery
|
| 62 |
+
|
| 63 |
+
Bad agent pattern:
|
| 64 |
+
|
| 65 |
+
```text
|
| 66 |
+
database is down
|
| 67 |
+
-> restart database
|
| 68 |
+
-> database crashes again because exploit path is still open
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Good agent pattern:
|
| 72 |
+
|
| 73 |
+
```text
|
| 74 |
+
find root cause
|
| 75 |
+
-> unlock security subquest
|
| 76 |
+
-> patch exploit path
|
| 77 |
+
-> verify fix
|
| 78 |
+
-> recover infrastructure
|
| 79 |
+
-> submit postmortem
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
## Evaluation Gap
|
| 83 |
+
|
| 84 |
+
| Property | Simple ops benchmark | Unified Incident Env |
|
| 85 |
+
| --- | --- | --- |
|
| 86 |
+
| Failure model | broken service only | broken service plus security-rooted cause |
|
| 87 |
+
| Agent role | troubleshooter | incident responder plus security repair assistant |
|
| 88 |
+
| Action pattern | pure recovery | investigate -> unlock security -> patch -> recover |
|
| 89 |
+
| Failure traps | wrong restart | wrong restart plus wrong patch plus wrong order |
|
| 90 |
+
| Success condition | service healthy | service healthy plus exploit path closed plus postmortem |
|
| 91 |
+
|
| 92 |
+
## Benchmark Mechanics
|
| 93 |
+
|
| 94 |
+
Named mechanics that shape behavior:
|
| 95 |
+
|
| 96 |
+
- Causal traps
|
| 97 |
+
- Stage transitions
|
| 98 |
+
- Security unlock
|
| 99 |
+
- Recovery ordering
|
| 100 |
+
- Negative-reward correction pressure
|
| 101 |
+
- Deterministic postmortem scoring
|
| 102 |
+
|
| 103 |
+
These mechanics are explicit in the environment state and reward function. They are not hidden in a black-box grader.
|
| 104 |
+
|
| 105 |
+
## At A Glance
|
| 106 |
+
|
| 107 |
+
| Item | Value |
|
| 108 |
+
| --- | --- |
|
| 109 |
+
| Environment name | `unified_incident_env` |
|
| 110 |
+
| Environment count | 1 |
|
| 111 |
+
| Scenario count | 3 |
|
| 112 |
+
| Difficulty levels | Easy, Medium, Hard |
|
| 113 |
+
| Public actions | 11 |
|
| 114 |
+
| Score range | `0.0` to `1.0` |
|
| 115 |
+
| Score type | deterministic, dense, bounded |
|
| 116 |
+
| Root runner | `inference.py` |
|
| 117 |
+
| OpenEnv validation | passes |
|
| 118 |
+
| Test suite | `51 passed` |
|
| 119 |
+
| Docker build | passes |
|
| 120 |
+
| LLM judge | none |
|
| 121 |
+
|
| 122 |
+
## Scenario Pack
|
| 123 |
+
|
| 124 |
+
| Scenario | Difficulty | Operational failure | Security root cause | Lesson |
|
| 125 |
+
| --- | --- | --- | --- | --- |
|
| 126 |
+
| `database_sqli_outage` | Easy | database crash causes gateway `502`s | SQL injection in login path | close exploit before restarting database |
|
| 127 |
+
| `cache_abuse_broken_access_control` | Medium | cache crash and database degradation cascade | broken access control on internal admin endpoint | follow dependency chain and authorization evidence |
|
| 128 |
+
| `worker_bad_deploy_command_injection` | Hard | worker poisons downstream database and gateway | command injection plus bad deploy | stop investigating once enough evidence exists, then patch and rollback the worker path |
|
| 129 |
+
|
| 130 |
+
Difficulty progression:
|
| 131 |
+
|
| 132 |
+
```text
|
| 133 |
+
Easy -> direct evidence, short recovery chain
|
| 134 |
+
Medium -> dependency reasoning, authorization bug
|
| 135 |
+
Hard -> cross-service causality, exploit plus deploy rollback
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
```mermaid
|
| 139 |
+
flowchart LR
|
| 140 |
+
E["Easy\nDirect evidence"] --> M["Medium\nDependency reasoning"]
|
| 141 |
+
M --> H["Hard\nCross-service causality"]
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
## Public Action Schema
|
| 145 |
+
|
| 146 |
+
Only these `action_type` values are valid:
|
| 147 |
+
|
| 148 |
+
```json
|
| 149 |
+
[
|
| 150 |
+
"query_logs",
|
| 151 |
+
"query_metrics",
|
| 152 |
+
"query_dependencies",
|
| 153 |
+
"restart_service",
|
| 154 |
+
"rollback_deploy",
|
| 155 |
+
"inspect_code",
|
| 156 |
+
"classify_vulnerability",
|
| 157 |
+
"apply_patch",
|
| 158 |
+
"verify_security_fix",
|
| 159 |
+
"submit_security_fix",
|
| 160 |
+
"submit_postmortem"
|
| 161 |
+
]
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
Required fields:
|
| 165 |
+
|
| 166 |
+
| Action | Required fields |
|
| 167 |
+
| --- | --- |
|
| 168 |
+
| `query_logs` | `service` |
|
| 169 |
+
| `query_metrics` | `service`, `metric` |
|
| 170 |
+
| `query_dependencies` | `service` |
|
| 171 |
+
| `restart_service` | `service` |
|
| 172 |
+
| `rollback_deploy` | `service` |
|
| 173 |
+
| `inspect_code` | none |
|
| 174 |
+
| `classify_vulnerability` | `vulnerability_type` |
|
| 175 |
+
| `apply_patch` | `patch_id` |
|
| 176 |
+
| `verify_security_fix` | none |
|
| 177 |
+
| `submit_security_fix` | none |
|
| 178 |
+
| `submit_postmortem` | `postmortem` |
|
| 179 |
+
|
| 180 |
+
## Observation Design
|
| 181 |
+
|
| 182 |
+
Each step returns a typed observation with:
|
| 183 |
+
|
| 184 |
+
- `tick_count`
|
| 185 |
+
- `workflow_stage`
|
| 186 |
+
- `active_alerts`
|
| 187 |
+
- `service_health`
|
| 188 |
+
- `last_action_result`
|
| 189 |
+
- `tool_output`
|
| 190 |
+
- `failure_type`
|
| 191 |
+
- `why_failed`
|
| 192 |
+
- `allowed_actions`
|
| 193 |
+
- `required_fields_by_action`
|
| 194 |
+
- `valid_action_example`
|
| 195 |
+
- `common_trap`
|
| 196 |
+
- `loop_warning`
|
| 197 |
+
- `blocked_until_security_complete`
|
| 198 |
+
- `security_unlock_reason`
|
| 199 |
+
- `best_recovery_action_family`
|
| 200 |
+
- `progress_flags`
|
| 201 |
+
- `security_subquest_status`
|
| 202 |
+
- `security_context`
|
| 203 |
+
- `final_score`
|
| 204 |
+
- `score_breakdown`
|
| 205 |
+
- `incident_resolved`
|
| 206 |
+
- `reward`
|
| 207 |
+
- `done`
|
| 208 |
+
|
| 209 |
+
This keeps the benchmark deterministic while still making failure states explicit and machine-usable.
|
| 210 |
+
|
| 211 |
+
## Scoring
|
| 212 |
+
|
| 213 |
+
The score is deterministic and bounded between `0.0` and `1.0`.
|
| 214 |
+
|
| 215 |
+
```text
|
| 216 |
+
final_score =
|
| 217 |
+
infrastructure_score (0.00 to 0.45) +
|
| 218 |
+
security_score (0.00 to 0.35) +
|
| 219 |
+
efficiency_score (0.00 to 0.10) +
|
| 220 |
+
postmortem_score (0.00 to 0.10)
|
| 221 |
+
```
|
| 222 |
+
|
| 223 |
+
Score weight view:
|
| 224 |
+
|
| 225 |
+
| Component | Weight |
|
| 226 |
+
| --- | ---: |
|
| 227 |
+
| Infrastructure | 0.45 |
|
| 228 |
+
| Security | 0.35 |
|
| 229 |
+
| Efficiency | 0.10 |
|
| 230 |
+
| Postmortem | 0.10 |
|
| 231 |
+
|
| 232 |
+
Deterministic guarantees:
|
| 233 |
+
|
| 234 |
+
- preset authored scenarios
|
| 235 |
+
- deterministic patch outcomes
|
| 236 |
+
- deterministic postmortem scoring
|
| 237 |
+
- no hidden fallback in strict benchmark behavior
|
| 238 |
+
- no LLM grader
|
| 239 |
+
- incomplete security subquest caps the final score at `0.5`
|
| 240 |
+
|
| 241 |
+
## Runtime Flow
|
| 242 |
+
|
| 243 |
+
```text
|
| 244 |
+
model
|
| 245 |
+
-> inference.py
|
| 246 |
+
-> env.step(action)
|
| 247 |
+
-> observation + reward + score
|
| 248 |
+
-> next model decision
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
```mermaid
|
| 252 |
+
flowchart LR
|
| 253 |
+
A["Model"] --> B["inference.py"]
|
| 254 |
+
B --> C["env.step(action)"]
|
| 255 |
+
C --> D["observation + reward + score"]
|
| 256 |
+
D --> A
|
| 257 |
+
```
|
| 258 |
+
|
| 259 |
+
Successful episode flow:
|
| 260 |
+
|
| 261 |
+
```text
|
| 262 |
+
diagnosis
|
| 263 |
+
-> root cause analysis
|
| 264 |
+
-> security subquest
|
| 265 |
+
-> remediation
|
| 266 |
+
-> verification
|
| 267 |
+
-> postmortem
|
| 268 |
+
-> done
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
## Inference Path
|
| 272 |
+
|
| 273 |
+
The root `inference.py` is the submission runner.
|
| 274 |
+
|
| 275 |
+
It:
|
| 276 |
+
|
| 277 |
+
- uses the OpenAI client
|
| 278 |
+
- reads `API_BASE_URL`, `MODEL_NAME`, and `HF_TOKEN`
|
| 279 |
+
- emits validator-compatible `[START]`, `[STEP]`, and `[END]` logs
|
| 280 |
+
- runs all 3 scenarios through the real environment API
|
| 281 |
+
|
| 282 |
+
Inference modes:
|
| 283 |
+
|
| 284 |
+
- `INFERENCE_MODE=judge`
|
| 285 |
+
- default
|
| 286 |
+
- compact, strong-model-friendly prompt
|
| 287 |
+
- structured outputs first
|
| 288 |
+
- no transcript stuffing
|
| 289 |
+
- `INFERENCE_MODE=small`
|
| 290 |
+
- optional local rescue mode for weaker models
|
| 291 |
+
- compact corrective prompt behavior
|
| 292 |
+
|
| 293 |
+
## Model Notes
|
| 294 |
+
|
| 295 |
+
Models used during development and validation:
|
| 296 |
+
|
| 297 |
+
- `qwen2.5:1.5b`
|
| 298 |
+
- `qwen2.5:3b`
|
| 299 |
+
- `qwen2.5:7b-instruct-q4_K_M`
|
| 300 |
+
- `gemma2:2b`
|
| 301 |
+
- `llama-3.3-70b-versatile`
|
| 302 |
+
|
| 303 |
+
The default path is optimized for strong external judge models. The optional `small` mode exists only to support weaker local models without changing the benchmark contract.
|
| 304 |
+
|
| 305 |
+
## Repository Layout
|
| 306 |
+
|
| 307 |
+
```text
|
| 308 |
+
.
|
| 309 |
+
├── README.md
|
| 310 |
+
├── inference.py
|
| 311 |
+
├── requirements.txt
|
| 312 |
+
├── run_demo.py
|
| 313 |
+
├── openenv.yaml
|
| 314 |
+
├── Dockerfile
|
| 315 |
+
├── pyproject.toml
|
| 316 |
+
├── uv.lock
|
| 317 |
+
├── Makefile
|
| 318 |
+
├── server/
|
| 319 |
+
└── unified_incident_env/
|
| 320 |
+
```
|
| 321 |
+
|
| 322 |
+
Important internals:
|
| 323 |
+
|
| 324 |
+
| Path | Purpose |
|
| 325 |
+
| --- | --- |
|
| 326 |
+
| `server/app.py` | top-level app entrypoint |
|
| 327 |
+
| `unified_incident_env/models.py` | typed action, observation, and state models |
|
| 328 |
+
| `unified_incident_env/server/challenge.py` | scenario catalog |
|
| 329 |
+
| `unified_incident_env/server/environment.py` | transition logic |
|
| 330 |
+
| `unified_incident_env/server/grader.py` | deterministic scoring |
|
| 331 |
+
| `unified_incident_env/scripts/baseline_agent.py` | deterministic internal reference baseline |
|
| 332 |
+
| `unified_incident_env/tests/` | regression tests |
|
| 333 |
+
| `unified_incident_env/trainer/` | optional secondary tooling |
|
| 334 |
+
|
| 335 |
+
## Running The Repo
|
| 336 |
+
|
| 337 |
+
Install:
|
| 338 |
+
|
| 339 |
+
```bash
|
| 340 |
+
python3 -m venv .venv
|
| 341 |
+
source .venv/bin/activate
|
| 342 |
+
python -m pip install -r requirements.txt
|
| 343 |
+
```
|
| 344 |
+
|
| 345 |
+
Editable install with dev extras:
|
| 346 |
+
|
| 347 |
+
```bash
|
| 348 |
+
python -m pip install -e ".[dev]"
|
| 349 |
+
```
|
| 350 |
+
|
| 351 |
+
Run tests:
|
| 352 |
+
|
| 353 |
+
```bash
|
| 354 |
+
pytest unified_incident_env/tests -q
|
| 355 |
+
```
|
| 356 |
+
|
| 357 |
+
Validate OpenEnv compliance:
|
| 358 |
+
|
| 359 |
+
```bash
|
| 360 |
+
openenv validate .
|
| 361 |
+
```
|
| 362 |
+
|
| 363 |
+
Run the environment locally:
|
| 364 |
+
|
| 365 |
+
```bash
|
| 366 |
+
uvicorn server.app:app --host 0.0.0.0 --port 8000
|
| 367 |
+
```
|
| 368 |
+
|
| 369 |
+
Run the root inference script:
|
| 370 |
+
|
| 371 |
+
```bash
|
| 372 |
+
python inference.py
|
| 373 |
+
```
|
| 374 |
+
|
| 375 |
+
Run the local demo helper:
|
| 376 |
+
|
| 377 |
+
```bash
|
| 378 |
+
python run_demo.py
|
| 379 |
+
```
|
| 380 |
+
|
| 381 |
+
Build and run with Docker:
|
| 382 |
+
|
| 383 |
+
```bash
|
| 384 |
+
docker build -t unified-incident-env .
|
| 385 |
+
docker run --rm -p 8000:8000 unified-incident-env
|
| 386 |
+
```
|
| 387 |
+
|
| 388 |
+
## Environment Variables
|
| 389 |
+
|
| 390 |
+
Mandatory inference variables:
|
| 391 |
+
|
| 392 |
+
- `API_BASE_URL`
|
| 393 |
+
- `MODEL_NAME`
|
| 394 |
+
- `HF_TOKEN`
|
| 395 |
+
|
| 396 |
+
Additional local overrides:
|
| 397 |
+
|
| 398 |
+
- `ENV_BASE_URL`
|
| 399 |
+
- `INFERENCE_MODE`
|
| 400 |
+
|
| 401 |
+
Example:
|
| 402 |
+
|
| 403 |
+
```bash
|
| 404 |
+
export API_BASE_URL="https://router.huggingface.co/v1"
|
| 405 |
+
export MODEL_NAME="meta-llama/Llama-3.1-70B-Instruct"
|
| 406 |
+
export HF_TOKEN="your_hf_token"
|
| 407 |
+
python inference.py
|
| 408 |
+
```
|
| 409 |
+
|
| 410 |
+
## Validation Status
|
| 411 |
+
|
| 412 |
+
Current repo-level checks:
|
| 413 |
+
|
| 414 |
+
- `pytest unified_incident_env/tests -q` -> `51 passed`
|
| 415 |
+
- `openenv validate .` -> passes
|
| 416 |
+
- `docker build -t unified-incident-env .` -> passes
|
| 417 |
+
|
| 418 |
+
## Hugging Face Space
|
| 419 |
+
|
| 420 |
+
Configured Space URL:
|
| 421 |
+
|
| 422 |
+
- `https://huggingface.co/spaces/gylder/my-env`
|
| 423 |
+
|
| 424 |
+
The repo is structured for a Docker-based Hugging Face Space via `openenv.yaml`.
|
| 425 |
+
|
| 426 |
+
## Optional Trainer Scaffold
|
| 427 |
+
|
| 428 |
+
`unified_incident_env/trainer/` is secondary tooling for:
|
| 429 |
+
|
| 430 |
+
- trajectory collection
|
| 431 |
+
- failure analysis
|
| 432 |
+
- correction dataset generation
|
| 433 |
+
- updater hooks
|
| 434 |
+
|
| 435 |
+
It is not a second environment. The judge-facing benchmark remains `unified_incident_env`.
|
| 436 |
+
|
| 437 |
+
## Reading Order
|
| 438 |
+
|
| 439 |
+
For a new engineer or agent:
|
| 440 |
+
|
| 441 |
+
1. `README.md`
|
| 442 |
+
2. `inference.py`
|
| 443 |
+
3. `openenv.yaml`
|
| 444 |
+
4. `unified_incident_env/models.py`
|
| 445 |
+
5. `unified_incident_env/server/challenge.py`
|
| 446 |
+
6. `unified_incident_env/server/environment.py`
|
| 447 |
+
7. `unified_incident_env/server/grader.py`
|
| 448 |
+
8. `unified_incident_env/tests/`
|
inference.py
ADDED
|
@@ -0,0 +1,1329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Submission inference script with validator-compatible stdout logs."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
from dataclasses import dataclass, field
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
|
| 14 |
+
from unified_incident_env.client import UnifiedIncidentEnv
|
| 15 |
+
from unified_incident_env.models import (
|
| 16 |
+
PostmortemPayload,
|
| 17 |
+
SecurityContext,
|
| 18 |
+
UnifiedIncidentAction,
|
| 19 |
+
UnifiedIncidentObservation,
|
| 20 |
+
)
|
| 21 |
+
from unified_incident_env.server.challenge import SCENARIOS
|
| 22 |
+
|
| 23 |
+
API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
|
| 24 |
+
MODEL_NAME = os.getenv("MODEL_NAME") or "qwen2.5:1.5b"
|
| 25 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 26 |
+
ENV_BASE_URL = os.getenv("ENV_BASE_URL") or UnifiedIncidentEnv.DEFAULT_BASE_URL
|
| 27 |
+
ENV_NAME = "unified-incident-env"
|
| 28 |
+
MAX_TOKENS = 220
|
| 29 |
+
|
| 30 |
+
INFERENCE_MODE = os.getenv("INFERENCE_MODE", "judge").strip().lower()
|
| 31 |
+
POLICY_CARD_WORD_BUDGET_COMPACT = int(os.getenv("POLICY_CARD_WORD_BUDGET_COMPACT", "60"))
|
| 32 |
+
|
| 33 |
+
POLICY_CARD_RULES = [
|
| 34 |
+
"Return JSON only.",
|
| 35 |
+
"Use action_type.",
|
| 36 |
+
"Use only allowed actions.",
|
| 37 |
+
"No explanation text.",
|
| 38 |
+
]
|
| 39 |
+
STAGE_GOALS = {
|
| 40 |
+
"diagnosis": "find the most relevant next investigation step",
|
| 41 |
+
"root_cause_analysis": "confirm the root-cause evidence and avoid unnecessary recovery",
|
| 42 |
+
"security_subquest": "complete the security fix before infrastructure recovery",
|
| 43 |
+
"remediation": "recover services in the correct order",
|
| 44 |
+
"verification": "verify that recovery and security remediation are complete",
|
| 45 |
+
"postmortem": "submit the final incident summary",
|
| 46 |
+
"done": "complete the benchmark",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
ACTION_KEYS = {
|
| 50 |
+
"action_type",
|
| 51 |
+
"service",
|
| 52 |
+
"metric",
|
| 53 |
+
"vulnerability_type",
|
| 54 |
+
"patch_id",
|
| 55 |
+
"postmortem",
|
| 56 |
+
}
|
| 57 |
+
KNOWN_ACTIONS = {
|
| 58 |
+
"query_logs",
|
| 59 |
+
"query_metrics",
|
| 60 |
+
"query_dependencies",
|
| 61 |
+
"restart_service",
|
| 62 |
+
"rollback_deploy",
|
| 63 |
+
"inspect_code",
|
| 64 |
+
"classify_vulnerability",
|
| 65 |
+
"apply_patch",
|
| 66 |
+
"verify_security_fix",
|
| 67 |
+
"submit_security_fix",
|
| 68 |
+
"submit_postmortem",
|
| 69 |
+
}
|
| 70 |
+
LOCAL_ENDPOINT_MARKERS = ("127.0.0.1", "localhost")
|
| 71 |
+
SERVICE_PRIORITY = ("database", "cache", "api-gateway", "worker")
|
| 72 |
+
VULNERABILITY_KEYWORDS = {
|
| 73 |
+
"sql_injection": ("sql injection", "sqli", "query", "parameter", "login"),
|
| 74 |
+
"broken_access_control": ("access control", "authorization", "admin", "role", "permission"),
|
| 75 |
+
"command_injection": ("command injection", "shell", "subprocess", "filename", "worker"),
|
| 76 |
+
}
|
| 77 |
+
PATCH_KEYWORDS = {
|
| 78 |
+
"sql_injection": ("parameter", "prepared", "query"),
|
| 79 |
+
"broken_access_control": ("admin", "role", "authoriz"),
|
| 80 |
+
"command_injection": ("avoid_shell", "argv", "shell", "subprocess"),
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
SYSTEM_PROMPT = """You are solving a deterministic incident-response benchmark.
|
| 84 |
+
|
| 85 |
+
Return exactly one JSON object and nothing else.
|
| 86 |
+
|
| 87 |
+
Rules:
|
| 88 |
+
- Choose only from the allowed action types shown in the user message.
|
| 89 |
+
- Use only the required fields for the chosen action.
|
| 90 |
+
- Do not include explanation text.
|
| 91 |
+
- Do not include markdown.
|
| 92 |
+
- Do not include code fences.
|
| 93 |
+
- Do not repeat an action that already failed or made no progress.
|
| 94 |
+
- If patching is required, use only one of the listed patch IDs.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
USER_PROMPT_TEMPLATE = """Current stage: {stage}
|
| 98 |
+
|
| 99 |
+
Current goal: {goal}
|
| 100 |
+
|
| 101 |
+
Allowed actions:
|
| 102 |
+
{allowed_actions_block}
|
| 103 |
+
|
| 104 |
+
Required fields:
|
| 105 |
+
{required_fields_block}
|
| 106 |
+
|
| 107 |
+
{patch_ids_block}{transition_block}{negative_reward_block}{loop_warning_block}Current environment state:
|
| 108 |
+
{state_block}
|
| 109 |
+
|
| 110 |
+
Valid example:
|
| 111 |
+
{valid_example}
|
| 112 |
+
|
| 113 |
+
Return exactly one JSON object.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@dataclass
|
| 118 |
+
class PolicyNote:
|
| 119 |
+
stage: str
|
| 120 |
+
failure_type: str
|
| 121 |
+
mistake: str
|
| 122 |
+
correction: str
|
| 123 |
+
valid_example: dict[str, Any]
|
| 124 |
+
action_family: str | None = None
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@dataclass
|
| 128 |
+
class PolicyCardState:
|
| 129 |
+
schema_notes: list[PolicyNote] = field(default_factory=list)
|
| 130 |
+
failure_notes: list[PolicyNote] = field(default_factory=list)
|
| 131 |
+
recovery_notes: list[PolicyNote] = field(default_factory=list)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def log_start(task: str, env: str, model: str) -> None:
|
| 135 |
+
print(f"[START] task={task} env={env} model={model}", flush=True)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def log_step(step: int, action: str, reward: float, done: bool, error: str | None) -> None:
|
| 139 |
+
error_val = error if error else "null"
|
| 140 |
+
done_val = str(done).lower()
|
| 141 |
+
print(
|
| 142 |
+
f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}",
|
| 143 |
+
flush=True,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def log_end(success: bool, steps: int, rewards: list[float]) -> None:
|
| 148 |
+
rewards_str = ",".join(f"{reward:.2f}" for reward in rewards)
|
| 149 |
+
print(
|
| 150 |
+
f"[END] success={str(success).lower()} steps={steps} rewards={rewards_str}",
|
| 151 |
+
flush=True,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def action_to_log_string(action: UnifiedIncidentAction) -> str:
|
| 156 |
+
return json.dumps(
|
| 157 |
+
action.model_dump(exclude_none=True, exclude={"metadata"}),
|
| 158 |
+
separators=(",", ":"),
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def create_client() -> OpenAI | None:
|
| 163 |
+
if HF_TOKEN is None:
|
| 164 |
+
raise ValueError("HF_TOKEN environment variable is required")
|
| 165 |
+
try:
|
| 166 |
+
return OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN, timeout=45.0)
|
| 167 |
+
except Exception:
|
| 168 |
+
return None
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _inference_mode() -> str:
|
| 172 |
+
return "small" if os.getenv("INFERENCE_MODE", INFERENCE_MODE).strip().lower() == "small" else "judge"
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _is_local_ollama() -> bool:
|
| 176 |
+
return any(marker in API_BASE_URL for marker in LOCAL_ENDPOINT_MARKERS)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _extract_json_candidate(raw: str) -> str:
|
| 180 |
+
text = raw.strip()
|
| 181 |
+
if "```" in text:
|
| 182 |
+
parts = text.split("```")
|
| 183 |
+
if len(parts) >= 2:
|
| 184 |
+
text = parts[1]
|
| 185 |
+
if text.startswith("json"):
|
| 186 |
+
text = text[4:]
|
| 187 |
+
start = text.find("{")
|
| 188 |
+
end = text.rfind("}")
|
| 189 |
+
if start != -1 and end != -1 and start < end:
|
| 190 |
+
return text[start : end + 1]
|
| 191 |
+
return text
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def parse_action(
|
| 195 |
+
raw: str,
|
| 196 |
+
observation: UnifiedIncidentObservation,
|
| 197 |
+
*,
|
| 198 |
+
scenario_id: str | None = None,
|
| 199 |
+
history: list[dict[str, Any]] | None = None,
|
| 200 |
+
) -> UnifiedIncidentAction | None:
|
| 201 |
+
stage_allowed_actions = _narrow_allowed_actions(
|
| 202 |
+
observation,
|
| 203 |
+
scenario_id=scenario_id,
|
| 204 |
+
history=history or [],
|
| 205 |
+
)
|
| 206 |
+
text = raw.strip()
|
| 207 |
+
if not text:
|
| 208 |
+
return None
|
| 209 |
+
|
| 210 |
+
bare = text.strip().strip('"').strip("'")
|
| 211 |
+
if bare in stage_allowed_actions and bare in KNOWN_ACTIONS:
|
| 212 |
+
fields = observation.required_fields_by_action.get(bare, [])
|
| 213 |
+
if not fields:
|
| 214 |
+
return UnifiedIncidentAction(action_type=bare)
|
| 215 |
+
example = observation.valid_action_example or {}
|
| 216 |
+
if example.get("action_type") == bare:
|
| 217 |
+
try:
|
| 218 |
+
return UnifiedIncidentAction(**example)
|
| 219 |
+
except Exception:
|
| 220 |
+
return None
|
| 221 |
+
return None
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
payload = json.loads(_extract_json_candidate(text))
|
| 225 |
+
except Exception:
|
| 226 |
+
return None
|
| 227 |
+
if not isinstance(payload, dict):
|
| 228 |
+
return None
|
| 229 |
+
|
| 230 |
+
cleaned = {key: value for key, value in payload.items() if key in ACTION_KEYS}
|
| 231 |
+
if "action_type" not in cleaned and isinstance(payload.get("action"), str):
|
| 232 |
+
cleaned["action_type"] = payload["action"]
|
| 233 |
+
if "vulnerability_type" not in cleaned and isinstance(payload.get("vulnerability"), str):
|
| 234 |
+
cleaned["vulnerability_type"] = payload["vulnerability"]
|
| 235 |
+
metrics_value = payload.get("metrics")
|
| 236 |
+
if "metric" not in cleaned and isinstance(metrics_value, list) and len(metrics_value) == 1:
|
| 237 |
+
cleaned["metric"] = metrics_value[0]
|
| 238 |
+
|
| 239 |
+
action_type = cleaned.get("action_type")
|
| 240 |
+
if action_type not in stage_allowed_actions:
|
| 241 |
+
return None
|
| 242 |
+
|
| 243 |
+
try:
|
| 244 |
+
return UnifiedIncidentAction(**cleaned)
|
| 245 |
+
except Exception:
|
| 246 |
+
return None
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def choose_investigation_service(observation: UnifiedIncidentObservation) -> str:
|
| 250 |
+
critical_alerts = [
|
| 251 |
+
alert.service for alert in observation.active_alerts if alert.severity == "critical"
|
| 252 |
+
]
|
| 253 |
+
if critical_alerts:
|
| 254 |
+
return critical_alerts[0]
|
| 255 |
+
for service in SERVICE_PRIORITY:
|
| 256 |
+
health = observation.service_health.get(service)
|
| 257 |
+
if health and health.status == "crashed":
|
| 258 |
+
return service
|
| 259 |
+
for service in SERVICE_PRIORITY:
|
| 260 |
+
health = observation.service_health.get(service)
|
| 261 |
+
if health and health.status == "degraded":
|
| 262 |
+
return service
|
| 263 |
+
return "api-gateway"
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def choose_recovery_service(observation: UnifiedIncidentObservation) -> str:
|
| 267 |
+
for service in SERVICE_PRIORITY:
|
| 268 |
+
health = observation.service_health.get(service)
|
| 269 |
+
if health and health.status == "crashed":
|
| 270 |
+
return service
|
| 271 |
+
for service in SERVICE_PRIORITY:
|
| 272 |
+
health = observation.service_health.get(service)
|
| 273 |
+
if health and health.status == "degraded":
|
| 274 |
+
return service
|
| 275 |
+
return "api-gateway"
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def infer_vulnerability(observation: UnifiedIncidentObservation, history: list[dict[str, Any]]) -> str:
|
| 279 |
+
text_parts = [
|
| 280 |
+
observation.prompt_text,
|
| 281 |
+
observation.tool_output or "",
|
| 282 |
+
observation.security_unlock_reason or "",
|
| 283 |
+
observation.last_action_result,
|
| 284 |
+
observation.why_failed or "",
|
| 285 |
+
]
|
| 286 |
+
text_parts.extend(str(item.get("result", "")) for item in history[-4:])
|
| 287 |
+
haystack = " ".join(text_parts).lower()
|
| 288 |
+
best = "sql_injection"
|
| 289 |
+
best_score = -1
|
| 290 |
+
for vulnerability, keywords in VULNERABILITY_KEYWORDS.items():
|
| 291 |
+
score = sum(1 for keyword in keywords if keyword in haystack)
|
| 292 |
+
if score > best_score:
|
| 293 |
+
best = vulnerability
|
| 294 |
+
best_score = score
|
| 295 |
+
return best
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def extract_patch_options(observation: UnifiedIncidentObservation) -> list[str]:
|
| 299 |
+
sources = [observation.tool_output or "", observation.prompt_text]
|
| 300 |
+
for source in sources:
|
| 301 |
+
match = re.search(r"Patch options:\s*([^\n]+)", source)
|
| 302 |
+
if not match:
|
| 303 |
+
continue
|
| 304 |
+
return [option.strip() for option in match.group(1).split(",") if option.strip()]
|
| 305 |
+
return []
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def _allowed_patch_ids(observation: UnifiedIncidentObservation) -> list[str]:
|
| 309 |
+
options = extract_patch_options(observation)
|
| 310 |
+
if not options:
|
| 311 |
+
options = ["parameterized_query", "enforce_admin_role", "avoid_shell"]
|
| 312 |
+
|
| 313 |
+
# If vulnerability is already classified, filter options to matching family
|
| 314 |
+
vuln = observation.security_context.selected_vulnerability
|
| 315 |
+
if vuln:
|
| 316 |
+
keywords = PATCH_KEYWORDS.get(vuln, [])
|
| 317 |
+
filtered = [
|
| 318 |
+
opt for opt in options
|
| 319 |
+
if any(k in opt.lower() for k in keywords)
|
| 320 |
+
]
|
| 321 |
+
if filtered:
|
| 322 |
+
return filtered
|
| 323 |
+
|
| 324 |
+
return options
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _stage_hint(
|
| 328 |
+
observation: UnifiedIncidentObservation,
|
| 329 |
+
*,
|
| 330 |
+
scenario_id: str | None = None,
|
| 331 |
+
history: list[dict[str, Any]] | None = None,
|
| 332 |
+
) -> str:
|
| 333 |
+
hard = _hard_transition_state(
|
| 334 |
+
scenario_id=scenario_id,
|
| 335 |
+
observation=observation,
|
| 336 |
+
history=history or [],
|
| 337 |
+
)
|
| 338 |
+
if hard["next_required_action"] is not None:
|
| 339 |
+
return hard["next_required_action"]
|
| 340 |
+
if hard["next_required_action_family"] is not None:
|
| 341 |
+
return f"Next required action family: {hard['next_required_action_family']}."
|
| 342 |
+
stage = observation.workflow_stage
|
| 343 |
+
if stage == "diagnosis":
|
| 344 |
+
return "Find the root cause with investigation before moving to security or recovery."
|
| 345 |
+
if stage == "root_cause_analysis":
|
| 346 |
+
return "Confirm the root cause and avoid broad extra queries."
|
| 347 |
+
if stage == "security_subquest":
|
| 348 |
+
return "Solve the security subquest with the next security action."
|
| 349 |
+
if stage == "remediation":
|
| 350 |
+
return "Recover the system with the allowed remediation action."
|
| 351 |
+
if stage == "verification":
|
| 352 |
+
return "Verify the fix before submitting the security fix."
|
| 353 |
+
if stage == "postmortem":
|
| 354 |
+
return "Submit the postmortem after the incident is resolved."
|
| 355 |
+
return "Follow the current stage goal and allowed actions."
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def _stop_investigating_hint(
|
| 359 |
+
observation: UnifiedIncidentObservation,
|
| 360 |
+
*,
|
| 361 |
+
scenario_id: str | None = None,
|
| 362 |
+
history: list[dict[str, Any]] | None = None,
|
| 363 |
+
) -> str | None:
|
| 364 |
+
hard = _hard_transition_state(
|
| 365 |
+
scenario_id=scenario_id,
|
| 366 |
+
observation=observation,
|
| 367 |
+
history=history or [],
|
| 368 |
+
)
|
| 369 |
+
if hard["stop_investigating"]:
|
| 370 |
+
return hard["stop_message"]
|
| 371 |
+
if observation.loop_warning:
|
| 372 |
+
return "Stop repeating the same no-progress action; choose a different allowed action family."
|
| 373 |
+
if observation.workflow_stage == "root_cause_analysis":
|
| 374 |
+
return "Avoid broad investigation; confirm the root cause or move to the next stage."
|
| 375 |
+
if observation.workflow_stage in {"security_subquest", "remediation", "verification", "postmortem"}:
|
| 376 |
+
return "Avoid extra query_* investigation actions unless required by the current stage."
|
| 377 |
+
return None
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def choose_patch_id(observation: UnifiedIncidentObservation, history: list[dict[str, Any]]) -> str:
|
| 381 |
+
options = extract_patch_options(observation)
|
| 382 |
+
vulnerability = infer_vulnerability(observation, history)
|
| 383 |
+
keywords = PATCH_KEYWORDS[vulnerability]
|
| 384 |
+
for option in options:
|
| 385 |
+
lowered = option.lower()
|
| 386 |
+
if any(keyword in lowered for keyword in keywords):
|
| 387 |
+
return option
|
| 388 |
+
if options:
|
| 389 |
+
return options[0]
|
| 390 |
+
defaults = {
|
| 391 |
+
"sql_injection": "parameterized_query",
|
| 392 |
+
"broken_access_control": "enforce_admin_role",
|
| 393 |
+
"command_injection": "avoid_shell",
|
| 394 |
+
}
|
| 395 |
+
return defaults[vulnerability]
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def _timeline_entry(action: UnifiedIncidentAction) -> str:
|
| 399 |
+
if action.action_type in {"query_logs", "query_dependencies"} and action.service:
|
| 400 |
+
return f"{action.action_type} {action.service}"
|
| 401 |
+
if action.action_type == "query_metrics" and action.service and action.metric:
|
| 402 |
+
return f"query_metrics {action.service}.{action.metric}"
|
| 403 |
+
if action.action_type in {"restart_service", "rollback_deploy"} and action.service:
|
| 404 |
+
return f"{action.action_type} {action.service}"
|
| 405 |
+
if action.action_type == "classify_vulnerability" and action.vulnerability_type:
|
| 406 |
+
return f"classify_vulnerability {action.vulnerability_type}"
|
| 407 |
+
if action.action_type == "apply_patch" and action.patch_id:
|
| 408 |
+
return f"apply_patch {action.patch_id}"
|
| 409 |
+
return action.action_type
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def _action_family(action_type: str | None) -> str | None:
|
| 413 |
+
if action_type in {"query_logs", "query_metrics", "query_dependencies"}:
|
| 414 |
+
return "investigate"
|
| 415 |
+
if action_type in {
|
| 416 |
+
"inspect_code",
|
| 417 |
+
"classify_vulnerability",
|
| 418 |
+
"apply_patch",
|
| 419 |
+
"verify_security_fix",
|
| 420 |
+
"submit_security_fix",
|
| 421 |
+
}:
|
| 422 |
+
return "security"
|
| 423 |
+
if action_type in {"restart_service", "rollback_deploy"}:
|
| 424 |
+
return "recovery"
|
| 425 |
+
if action_type == "submit_postmortem":
|
| 426 |
+
return "postmortem"
|
| 427 |
+
return None
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def build_postmortem(
|
| 431 |
+
observation: UnifiedIncidentObservation,
|
| 432 |
+
history: list[dict[str, Any]],
|
| 433 |
+
) -> PostmortemPayload:
|
| 434 |
+
vulnerability = infer_vulnerability(observation, history)
|
| 435 |
+
selected_patch = observation.security_context.selected_patch
|
| 436 |
+
|
| 437 |
+
root_cause_map = {
|
| 438 |
+
"sql_injection": "SQL injection crashed the database and caused gateway errors.",
|
| 439 |
+
"broken_access_control": "Broken access control on an admin path caused cache abuse and database degradation.",
|
| 440 |
+
"command_injection": "Command injection in the worker poisoned downstream services after a bad deploy.",
|
| 441 |
+
}
|
| 442 |
+
attack_vector_map = {
|
| 443 |
+
"sql_injection": "Unsanitized login input abused the SQL query path.",
|
| 444 |
+
"broken_access_control": "Missing admin authorization exposed an internal cache-management route.",
|
| 445 |
+
"command_injection": "Unsafe shell command construction allowed attacker-controlled filenames to execute commands.",
|
| 446 |
+
}
|
| 447 |
+
prevention_map = {
|
| 448 |
+
"sql_injection": ["Parameterized queries", "Database abuse alerting"],
|
| 449 |
+
"broken_access_control": ["Admin role enforcement", "Authorization tests"],
|
| 450 |
+
"command_injection": ["Avoid shell invocation", "Safer deploy validation"],
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
timeline = [_timeline_entry(item["action"]) for item in history if "action" in item]
|
| 454 |
+
remediation_steps = []
|
| 455 |
+
if selected_patch:
|
| 456 |
+
remediation_steps.append(selected_patch.replace("_", " "))
|
| 457 |
+
remediation_steps.extend(
|
| 458 |
+
item["action"].service.replace("-", " ")
|
| 459 |
+
for item in history
|
| 460 |
+
if "action" in item
|
| 461 |
+
and item["action"].action_type in {"restart_service", "rollback_deploy"}
|
| 462 |
+
and item["action"].service
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
return PostmortemPayload(
|
| 466 |
+
root_cause=root_cause_map[vulnerability],
|
| 467 |
+
attack_vector=attack_vector_map[vulnerability],
|
| 468 |
+
timeline=timeline[-6:],
|
| 469 |
+
remediation_steps=remediation_steps[:4],
|
| 470 |
+
prevention_steps=prevention_map[vulnerability],
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def build_fallback_action(
|
| 475 |
+
observation: UnifiedIncidentObservation,
|
| 476 |
+
history: list[dict[str, Any]],
|
| 477 |
+
*,
|
| 478 |
+
scenario_id: str | None = None,
|
| 479 |
+
) -> UnifiedIncidentAction:
|
| 480 |
+
hard = _hard_transition_state(
|
| 481 |
+
scenario_id=scenario_id,
|
| 482 |
+
observation=observation,
|
| 483 |
+
history=history,
|
| 484 |
+
)
|
| 485 |
+
example = observation.valid_action_example or {}
|
| 486 |
+
last_action = (
|
| 487 |
+
history[-1]["action"].model_dump(exclude_none=True, exclude={"metadata"})
|
| 488 |
+
if history and "action" in history[-1]
|
| 489 |
+
else None
|
| 490 |
+
)
|
| 491 |
+
narrowed_allowed_actions = _narrow_allowed_actions(
|
| 492 |
+
observation,
|
| 493 |
+
scenario_id=scenario_id,
|
| 494 |
+
history=history,
|
| 495 |
+
)
|
| 496 |
+
if example.get("action_type") in narrowed_allowed_actions and example != last_action:
|
| 497 |
+
try:
|
| 498 |
+
return UnifiedIncidentAction(**example)
|
| 499 |
+
except Exception:
|
| 500 |
+
pass
|
| 501 |
+
|
| 502 |
+
stage = observation.workflow_stage
|
| 503 |
+
security: SecurityContext = observation.security_context
|
| 504 |
+
|
| 505 |
+
if stage in {"diagnosis", "root_cause_analysis"}:
|
| 506 |
+
if hard["needs_unlock_bridge"]:
|
| 507 |
+
return UnifiedIncidentAction(
|
| 508 |
+
action_type="query_dependencies",
|
| 509 |
+
service="api-gateway",
|
| 510 |
+
)
|
| 511 |
+
if stage == "root_cause_analysis" and "query_dependencies" in observation.allowed_actions:
|
| 512 |
+
return UnifiedIncidentAction(
|
| 513 |
+
action_type="query_dependencies",
|
| 514 |
+
service="api-gateway",
|
| 515 |
+
)
|
| 516 |
+
if "query_logs" in observation.allowed_actions:
|
| 517 |
+
return UnifiedIncidentAction(
|
| 518 |
+
action_type="query_logs",
|
| 519 |
+
service=choose_investigation_service(observation),
|
| 520 |
+
)
|
| 521 |
+
if "query_dependencies" in observation.allowed_actions:
|
| 522 |
+
return UnifiedIncidentAction(
|
| 523 |
+
action_type="query_dependencies",
|
| 524 |
+
service=choose_investigation_service(observation),
|
| 525 |
+
)
|
| 526 |
+
return UnifiedIncidentAction(
|
| 527 |
+
action_type="query_metrics",
|
| 528 |
+
service=choose_investigation_service(observation),
|
| 529 |
+
metric="cpu",
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
if stage == "security_subquest":
|
| 533 |
+
if not security.code_visible:
|
| 534 |
+
return UnifiedIncidentAction(action_type="inspect_code")
|
| 535 |
+
if security.selected_vulnerability is None:
|
| 536 |
+
return UnifiedIncidentAction(
|
| 537 |
+
action_type="classify_vulnerability",
|
| 538 |
+
vulnerability_type=infer_vulnerability(observation, history),
|
| 539 |
+
)
|
| 540 |
+
if security.selected_patch is None:
|
| 541 |
+
return UnifiedIncidentAction(
|
| 542 |
+
action_type="apply_patch",
|
| 543 |
+
patch_id=choose_patch_id(observation, history),
|
| 544 |
+
)
|
| 545 |
+
if security.exploit_blocked is not True or security.functionality_preserved is not True:
|
| 546 |
+
return UnifiedIncidentAction(action_type="verify_security_fix")
|
| 547 |
+
return UnifiedIncidentAction(action_type="submit_security_fix")
|
| 548 |
+
|
| 549 |
+
if stage in {"remediation", "verification"}:
|
| 550 |
+
if hard["force_worker_rollback"]:
|
| 551 |
+
return UnifiedIncidentAction(action_type="rollback_deploy", service="worker")
|
| 552 |
+
worker = observation.service_health.get("worker")
|
| 553 |
+
if (
|
| 554 |
+
"rollback_deploy" in observation.allowed_actions
|
| 555 |
+
and worker is not None
|
| 556 |
+
and worker.status != "healthy"
|
| 557 |
+
):
|
| 558 |
+
return UnifiedIncidentAction(action_type="rollback_deploy", service="worker")
|
| 559 |
+
return UnifiedIncidentAction(
|
| 560 |
+
action_type="restart_service",
|
| 561 |
+
service=choose_recovery_service(observation),
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
return UnifiedIncidentAction(
|
| 565 |
+
action_type="submit_postmortem",
|
| 566 |
+
postmortem=build_postmortem(observation, history),
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def build_compact_policy_card(
|
| 571 |
+
observation: UnifiedIncidentObservation,
|
| 572 |
+
state: PolicyCardState,
|
| 573 |
+
history: list[dict[str, Any]] | None = None,
|
| 574 |
+
*,
|
| 575 |
+
scenario_id: str | None = None,
|
| 576 |
+
) -> str:
|
| 577 |
+
"""Brutally small policy card for weak backends."""
|
| 578 |
+
if history is None:
|
| 579 |
+
history = []
|
| 580 |
+
stage_allowed_actions = _narrow_allowed_actions(
|
| 581 |
+
observation,
|
| 582 |
+
scenario_id=scenario_id,
|
| 583 |
+
history=history,
|
| 584 |
+
)
|
| 585 |
+
lines = [
|
| 586 |
+
f"STAGE: {observation.workflow_stage}",
|
| 587 |
+
f"GOAL: {STAGE_GOALS.get(observation.workflow_stage, 'Pick one valid action.')}",
|
| 588 |
+
f"HINT: {_stage_hint(observation, scenario_id=scenario_id, history=history)}",
|
| 589 |
+
f"ALLOWED: {', '.join(stage_allowed_actions)}",
|
| 590 |
+
]
|
| 591 |
+
stop_hint = _stop_investigating_hint(
|
| 592 |
+
observation,
|
| 593 |
+
scenario_id=scenario_id,
|
| 594 |
+
history=history,
|
| 595 |
+
)
|
| 596 |
+
if stop_hint:
|
| 597 |
+
lines.append(f"STOP_INVESTIGATING: {stop_hint}")
|
| 598 |
+
if observation.loop_warning:
|
| 599 |
+
lines.append("LESSON: Do not repeat the same no-progress action.")
|
| 600 |
+
elif state.failure_notes:
|
| 601 |
+
lines.append(f"LESSON: {state.failure_notes[-1].correction}")
|
| 602 |
+
example = observation.valid_action_example or {"action_type": stage_allowed_actions[0]}
|
| 603 |
+
lines.append(f"EXAMPLE: {json.dumps(example, separators=(',', ':'))}")
|
| 604 |
+
if "apply_patch" in stage_allowed_actions:
|
| 605 |
+
lines.append(f"PATCH_IDS: {', '.join(_allowed_patch_ids(observation))}")
|
| 606 |
+
lines.append("Return exactly one JSON object.")
|
| 607 |
+
return _limit_words("\n".join(lines), max_words=POLICY_CARD_WORD_BUDGET_COMPACT)
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def build_policy_card(
|
| 611 |
+
observation: UnifiedIncidentObservation,
|
| 612 |
+
state: PolicyCardState,
|
| 613 |
+
history: list[dict[str, Any]] | None = None,
|
| 614 |
+
*,
|
| 615 |
+
scenario_id: str | None = None,
|
| 616 |
+
) -> str:
|
| 617 |
+
"""Always use compact mode for small-model inference."""
|
| 618 |
+
return build_compact_policy_card(
|
| 619 |
+
observation,
|
| 620 |
+
state,
|
| 621 |
+
history or [],
|
| 622 |
+
scenario_id=scenario_id,
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def update_policy_card(
|
| 627 |
+
state: PolicyCardState,
|
| 628 |
+
*,
|
| 629 |
+
before: UnifiedIncidentObservation,
|
| 630 |
+
action: UnifiedIncidentAction,
|
| 631 |
+
after: UnifiedIncidentObservation,
|
| 632 |
+
model_error: str | None,
|
| 633 |
+
) -> None:
|
| 634 |
+
if model_error == "invalid_model_output":
|
| 635 |
+
state.schema_notes.append(
|
| 636 |
+
PolicyNote(
|
| 637 |
+
stage=before.workflow_stage,
|
| 638 |
+
failure_type="invalid_model_output",
|
| 639 |
+
mistake="The previous response was not one valid JSON action object.",
|
| 640 |
+
correction="Return exactly one valid JSON action using only allowed actions.",
|
| 641 |
+
valid_example=before.valid_action_example or {"action_type": before.allowed_actions[0]},
|
| 642 |
+
action_family=_action_family((before.valid_action_example or {}).get("action_type")),
|
| 643 |
+
)
|
| 644 |
+
)
|
| 645 |
+
state.schema_notes = state.schema_notes[-4:]
|
| 646 |
+
|
| 647 |
+
if after.failure_type and after.why_failed:
|
| 648 |
+
example = after.valid_action_example or before.valid_action_example or {"action_type": before.allowed_actions[0]}
|
| 649 |
+
family = after.best_recovery_action_family or _action_family(example.get("action_type"))
|
| 650 |
+
correction = (
|
| 651 |
+
f"If this happens again, prefer {family} actions."
|
| 652 |
+
if family
|
| 653 |
+
else "Follow the current stage example and allowed actions."
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
state.failure_notes.append(
|
| 657 |
+
PolicyNote(
|
| 658 |
+
stage=before.workflow_stage,
|
| 659 |
+
failure_type=after.failure_type,
|
| 660 |
+
mistake=after.why_failed,
|
| 661 |
+
correction=correction,
|
| 662 |
+
valid_example=example,
|
| 663 |
+
action_family=family,
|
| 664 |
+
)
|
| 665 |
+
)
|
| 666 |
+
state.failure_notes = state.failure_notes[-4:]
|
| 667 |
+
|
| 668 |
+
if after.reward > 0 and after.failure_type is None:
|
| 669 |
+
state.recovery_notes.append(
|
| 670 |
+
PolicyNote(
|
| 671 |
+
stage=before.workflow_stage,
|
| 672 |
+
failure_type="successful_step",
|
| 673 |
+
mistake="A weaker choice would likely have lost progress.",
|
| 674 |
+
correction=f"This stage can progress with {_timeline_entry(action)}.",
|
| 675 |
+
valid_example=action.model_dump(exclude_none=True, exclude={"metadata"}),
|
| 676 |
+
action_family=_action_family(action.action_type),
|
| 677 |
+
)
|
| 678 |
+
)
|
| 679 |
+
state.recovery_notes = state.recovery_notes[-4:]
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def _build_required_fields_block(
|
| 683 |
+
required_fields_by_action: dict[str, list[str]],
|
| 684 |
+
allowed_actions: list[str],
|
| 685 |
+
) -> str:
|
| 686 |
+
lines = []
|
| 687 |
+
for action in allowed_actions:
|
| 688 |
+
fields = required_fields_by_action.get(action, [])
|
| 689 |
+
if fields:
|
| 690 |
+
lines.append(f"- {action} -> {', '.join(fields)}")
|
| 691 |
+
else:
|
| 692 |
+
lines.append(f"- {action} -> none")
|
| 693 |
+
return "\n".join(lines) or "- none"
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def _build_patch_ids_block(patch_ids: list[str]) -> str:
|
| 697 |
+
if not patch_ids:
|
| 698 |
+
return ""
|
| 699 |
+
lines = ["Available patch IDs:"]
|
| 700 |
+
lines.extend(f"- {patch_id}" for patch_id in patch_ids)
|
| 701 |
+
lines.append("")
|
| 702 |
+
return "\n".join(lines)
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
def _build_transition_block(transition_hint: str | None) -> str:
|
| 706 |
+
if not transition_hint:
|
| 707 |
+
return ""
|
| 708 |
+
return f"Important transition hint:\n- {transition_hint}\n\n"
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
def _build_negative_reward_block(correction_hint: str | None) -> str:
|
| 712 |
+
if not correction_hint:
|
| 713 |
+
return ""
|
| 714 |
+
return f"Previous action correction:\n- {correction_hint}\n\n"
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
def _build_loop_warning_block(loop_warning: str | None) -> str:
|
| 718 |
+
if not loop_warning:
|
| 719 |
+
return ""
|
| 720 |
+
return f"Loop warning:\n- {loop_warning}\n\n"
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def _bool_text(value: bool | None) -> str:
|
| 724 |
+
if value is None:
|
| 725 |
+
return "unknown"
|
| 726 |
+
return str(value).lower()
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def _render_tool_output(observation: UnifiedIncidentObservation) -> str:
|
| 730 |
+
if not observation.tool_output:
|
| 731 |
+
return ""
|
| 732 |
+
|
| 733 |
+
if observation.workflow_stage in {"security_subquest", "verification"}:
|
| 734 |
+
lines = [line.rstrip() for line in observation.tool_output.splitlines() if line.strip()]
|
| 735 |
+
return "\n".join(lines[:6])
|
| 736 |
+
|
| 737 |
+
return observation.tool_output.splitlines()[0]
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def _build_state_block(observation: UnifiedIncidentObservation) -> str:
|
| 741 |
+
lines: list[str] = []
|
| 742 |
+
if observation.active_alerts:
|
| 743 |
+
lines.append("Active alerts:")
|
| 744 |
+
for alert in observation.active_alerts[:3]:
|
| 745 |
+
lines.append(f"- {alert.service}: {alert.severity} - {alert.message}")
|
| 746 |
+
|
| 747 |
+
lines.append(f"Final score: {observation.final_score:.4f}")
|
| 748 |
+
|
| 749 |
+
if observation.last_action_result:
|
| 750 |
+
lines.append(f"Last action result: {observation.last_action_result}")
|
| 751 |
+
|
| 752 |
+
if observation.tool_output:
|
| 753 |
+
rendered_tool_output = _render_tool_output(observation)
|
| 754 |
+
if "\n" in rendered_tool_output:
|
| 755 |
+
lines.append("Tool output:")
|
| 756 |
+
lines.extend(rendered_tool_output.splitlines())
|
| 757 |
+
else:
|
| 758 |
+
lines.append(f"Tool output: {rendered_tool_output}")
|
| 759 |
+
|
| 760 |
+
security = observation.security_context
|
| 761 |
+
if observation.workflow_stage in {"security_subquest", "verification"}:
|
| 762 |
+
lines.append(
|
| 763 |
+
"Security status: "
|
| 764 |
+
f"code visible = {str(security.code_visible).lower()}, "
|
| 765 |
+
f"vulnerability classified = {str(security.selected_vulnerability is not None).lower()}, "
|
| 766 |
+
f"patch applied = {str(security.selected_patch is not None).lower()}, "
|
| 767 |
+
f"exploit blocked = {_bool_text(security.exploit_blocked)}, "
|
| 768 |
+
f"functionality preserved = {_bool_text(security.functionality_preserved)}"
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
if observation.security_unlock_reason:
|
| 772 |
+
lines.append(f"Security unlock reason: {observation.security_unlock_reason}")
|
| 773 |
+
|
| 774 |
+
if observation.blocked_until_security_complete:
|
| 775 |
+
lines.append("Recovery gate: security must be completed before recovery.")
|
| 776 |
+
|
| 777 |
+
return "\n".join(lines) or "- none"
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
def _extract_policy_hint(policy_card: str) -> str | None:
|
| 781 |
+
for prefix in ("LESSON:", "STOP_INVESTIGATING:"):
|
| 782 |
+
for line in policy_card.splitlines():
|
| 783 |
+
if line.startswith(prefix):
|
| 784 |
+
return line.split(":", 1)[1].strip()
|
| 785 |
+
return None
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def _user_prompt_example(
|
| 789 |
+
observation: UnifiedIncidentObservation,
|
| 790 |
+
allowed_actions: list[str],
|
| 791 |
+
*,
|
| 792 |
+
scenario_id: str | None = None,
|
| 793 |
+
history: list[dict[str, Any]] | None = None,
|
| 794 |
+
) -> dict[str, Any]:
|
| 795 |
+
example = observation.valid_action_example or {}
|
| 796 |
+
if example.get("action_type") in allowed_actions:
|
| 797 |
+
return example
|
| 798 |
+
fallback = build_fallback_action(
|
| 799 |
+
observation,
|
| 800 |
+
history or [],
|
| 801 |
+
scenario_id=scenario_id,
|
| 802 |
+
)
|
| 803 |
+
return fallback.model_dump(exclude_none=True, exclude={"metadata"})
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
def build_user_prompt(
|
| 807 |
+
observation: UnifiedIncidentObservation,
|
| 808 |
+
policy_card: str,
|
| 809 |
+
*,
|
| 810 |
+
scenario_id: str | None = None,
|
| 811 |
+
history: list[dict[str, Any]] | None = None,
|
| 812 |
+
) -> str:
|
| 813 |
+
stage_allowed_actions = _narrow_allowed_actions(
|
| 814 |
+
observation,
|
| 815 |
+
scenario_id=scenario_id,
|
| 816 |
+
history=history or [],
|
| 817 |
+
)
|
| 818 |
+
required_fields = observation.required_fields_by_action or {
|
| 819 |
+
action: []
|
| 820 |
+
for action in stage_allowed_actions
|
| 821 |
+
}
|
| 822 |
+
transition_hint = _stop_investigating_hint(
|
| 823 |
+
observation,
|
| 824 |
+
scenario_id=scenario_id,
|
| 825 |
+
history=history or [],
|
| 826 |
+
) or _stage_hint(
|
| 827 |
+
observation,
|
| 828 |
+
scenario_id=scenario_id,
|
| 829 |
+
history=history or [],
|
| 830 |
+
)
|
| 831 |
+
correction_hint = None
|
| 832 |
+
if observation.failure_type and observation.why_failed:
|
| 833 |
+
correction_hint = observation.why_failed
|
| 834 |
+
elif policy_card:
|
| 835 |
+
correction_hint = _extract_policy_hint(policy_card)
|
| 836 |
+
|
| 837 |
+
valid_example = _user_prompt_example(
|
| 838 |
+
observation,
|
| 839 |
+
stage_allowed_actions,
|
| 840 |
+
scenario_id=scenario_id,
|
| 841 |
+
history=history,
|
| 842 |
+
)
|
| 843 |
+
return USER_PROMPT_TEMPLATE.format(
|
| 844 |
+
stage=observation.workflow_stage,
|
| 845 |
+
goal=STAGE_GOALS.get(observation.workflow_stage, "take the best next action"),
|
| 846 |
+
allowed_actions_block="\n".join(f"- {action}" for action in stage_allowed_actions) or "- none",
|
| 847 |
+
required_fields_block=_build_required_fields_block(required_fields, stage_allowed_actions),
|
| 848 |
+
patch_ids_block=_build_patch_ids_block(
|
| 849 |
+
_allowed_patch_ids(observation) if "apply_patch" in stage_allowed_actions else []
|
| 850 |
+
),
|
| 851 |
+
transition_block=_build_transition_block(transition_hint),
|
| 852 |
+
negative_reward_block=_build_negative_reward_block(correction_hint),
|
| 853 |
+
loop_warning_block=_build_loop_warning_block(observation.loop_warning),
|
| 854 |
+
state_block=_build_state_block(observation),
|
| 855 |
+
valid_example=json.dumps(valid_example, separators=(",", ":")),
|
| 856 |
+
)
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def _build_tool_schema(
|
| 860 |
+
observation: UnifiedIncidentObservation,
|
| 861 |
+
*,
|
| 862 |
+
scenario_id: str | None = None,
|
| 863 |
+
history: list[dict[str, Any]] | None = None,
|
| 864 |
+
) -> dict[str, Any]:
|
| 865 |
+
allowed_actions = _narrow_allowed_actions(
|
| 866 |
+
observation,
|
| 867 |
+
scenario_id=scenario_id,
|
| 868 |
+
history=history or [],
|
| 869 |
+
)
|
| 870 |
+
properties: dict[str, Any] = {
|
| 871 |
+
"action_type": {"type": "string", "enum": allowed_actions},
|
| 872 |
+
}
|
| 873 |
+
if any(action in allowed_actions for action in {"query_logs", "query_metrics", "query_dependencies", "restart_service", "rollback_deploy"}):
|
| 874 |
+
properties["service"] = {
|
| 875 |
+
"type": "string",
|
| 876 |
+
"enum": sorted(observation.service_health.keys()),
|
| 877 |
+
}
|
| 878 |
+
if "query_metrics" in allowed_actions:
|
| 879 |
+
properties["metric"] = {
|
| 880 |
+
"type": "string",
|
| 881 |
+
"enum": ["cpu", "memory", "latency", "error_rate", "throughput"],
|
| 882 |
+
}
|
| 883 |
+
if "classify_vulnerability" in allowed_actions:
|
| 884 |
+
properties["vulnerability_type"] = {
|
| 885 |
+
"type": "string",
|
| 886 |
+
"enum": ["sql_injection", "broken_access_control", "command_injection"],
|
| 887 |
+
}
|
| 888 |
+
if "apply_patch" in allowed_actions:
|
| 889 |
+
properties["patch_id"] = {
|
| 890 |
+
"type": "string",
|
| 891 |
+
"enum": _allowed_patch_ids(observation),
|
| 892 |
+
}
|
| 893 |
+
if "submit_postmortem" in allowed_actions:
|
| 894 |
+
properties["postmortem"] = {"type": "object"}
|
| 895 |
+
required = ["action_type"]
|
| 896 |
+
example = observation.valid_action_example or {}
|
| 897 |
+
for field in ("service", "metric", "vulnerability_type", "patch_id", "postmortem"):
|
| 898 |
+
if field in properties and field in example:
|
| 899 |
+
required.append(field)
|
| 900 |
+
return {
|
| 901 |
+
"type": "object",
|
| 902 |
+
"properties": properties,
|
| 903 |
+
"required": required,
|
| 904 |
+
"additionalProperties": False,
|
| 905 |
+
}
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
def _extract_completion_text(completion) -> str:
|
| 909 |
+
message = completion.choices[0].message
|
| 910 |
+
tool_calls = getattr(message, "tool_calls", None) or []
|
| 911 |
+
if tool_calls:
|
| 912 |
+
function = getattr(tool_calls[0], "function", None)
|
| 913 |
+
if function is not None and getattr(function, "arguments", None):
|
| 914 |
+
return function.arguments
|
| 915 |
+
return (message.content or "").strip()
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
def _request_action_completion(
|
| 919 |
+
client: OpenAI,
|
| 920 |
+
observation: UnifiedIncidentObservation,
|
| 921 |
+
user_prompt: str,
|
| 922 |
+
*,
|
| 923 |
+
temperature: float,
|
| 924 |
+
scenario_id: str | None = None,
|
| 925 |
+
history: list[dict[str, Any]] | None = None,
|
| 926 |
+
) -> str:
|
| 927 |
+
import time
|
| 928 |
+
max_retries = 3
|
| 929 |
+
last_exc = None
|
| 930 |
+
|
| 931 |
+
schema = _build_tool_schema(
|
| 932 |
+
observation,
|
| 933 |
+
scenario_id=scenario_id,
|
| 934 |
+
history=history or [],
|
| 935 |
+
)
|
| 936 |
+
|
| 937 |
+
for attempt in range(max_retries):
|
| 938 |
+
try:
|
| 939 |
+
create_kwargs = {
|
| 940 |
+
"model": MODEL_NAME,
|
| 941 |
+
"messages": [
|
| 942 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 943 |
+
{"role": "user", "content": user_prompt},
|
| 944 |
+
],
|
| 945 |
+
"temperature": temperature,
|
| 946 |
+
"max_tokens": MAX_TOKENS,
|
| 947 |
+
"stream": False,
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
if _is_local_ollama():
|
| 951 |
+
create_kwargs["extra_body"] = {"format": schema}
|
| 952 |
+
completion = client.chat.completions.create(**create_kwargs)
|
| 953 |
+
return _extract_completion_text(completion)
|
| 954 |
+
|
| 955 |
+
try:
|
| 956 |
+
# Try tool calling first
|
| 957 |
+
completion = client.chat.completions.create(
|
| 958 |
+
**create_kwargs,
|
| 959 |
+
tools=[
|
| 960 |
+
{
|
| 961 |
+
"type": "function",
|
| 962 |
+
"function": {
|
| 963 |
+
"name": "emit_action",
|
| 964 |
+
"description": "Emit exactly one environment action.",
|
| 965 |
+
"parameters": schema,
|
| 966 |
+
},
|
| 967 |
+
}
|
| 968 |
+
],
|
| 969 |
+
tool_choice={"type": "function", "function": {"name": "emit_action"}},
|
| 970 |
+
)
|
| 971 |
+
return _extract_completion_text(completion)
|
| 972 |
+
except Exception:
|
| 973 |
+
# Fallback to JSON mode
|
| 974 |
+
completion = client.chat.completions.create(
|
| 975 |
+
**create_kwargs,
|
| 976 |
+
response_format={
|
| 977 |
+
"type": "json_schema",
|
| 978 |
+
"json_schema": {
|
| 979 |
+
"name": "unified_incident_action",
|
| 980 |
+
"strict": True,
|
| 981 |
+
"schema": schema,
|
| 982 |
+
},
|
| 983 |
+
},
|
| 984 |
+
)
|
| 985 |
+
return _extract_completion_text(completion)
|
| 986 |
+
except Exception as e:
|
| 987 |
+
last_exc = e
|
| 988 |
+
if attempt < max_retries - 1:
|
| 989 |
+
time.sleep(2.0 * (attempt + 1))
|
| 990 |
+
continue
|
| 991 |
+
raise last_exc
|
| 992 |
+
return ""
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def attempt_repair(
|
| 996 |
+
client: OpenAI,
|
| 997 |
+
observation: UnifiedIncidentObservation,
|
| 998 |
+
raw_output: str,
|
| 999 |
+
*,
|
| 1000 |
+
scenario_id: str | None = None,
|
| 1001 |
+
history: list[dict[str, Any]] | None = None,
|
| 1002 |
+
) -> UnifiedIncidentAction | None:
|
| 1003 |
+
example = observation.valid_action_example or {
|
| 1004 |
+
"action_type": _narrow_allowed_actions(
|
| 1005 |
+
observation,
|
| 1006 |
+
scenario_id=scenario_id,
|
| 1007 |
+
history=history or [],
|
| 1008 |
+
)[0]
|
| 1009 |
+
}
|
| 1010 |
+
repair_prompt = (
|
| 1011 |
+
"Your previous response was invalid.\n"
|
| 1012 |
+
"Return exactly one valid JSON object.\n"
|
| 1013 |
+
"No explanation.\n"
|
| 1014 |
+
f"Example: {json.dumps(example, separators=(',', ':'))}\n"
|
| 1015 |
+
f"Previous response: {raw_output}"
|
| 1016 |
+
)
|
| 1017 |
+
try:
|
| 1018 |
+
repaired = _request_action_completion(
|
| 1019 |
+
client,
|
| 1020 |
+
observation,
|
| 1021 |
+
repair_prompt,
|
| 1022 |
+
temperature=0.0,
|
| 1023 |
+
scenario_id=scenario_id,
|
| 1024 |
+
history=history or [],
|
| 1025 |
+
)
|
| 1026 |
+
except Exception:
|
| 1027 |
+
return None
|
| 1028 |
+
return parse_action(
|
| 1029 |
+
repaired,
|
| 1030 |
+
observation,
|
| 1031 |
+
scenario_id=scenario_id,
|
| 1032 |
+
history=history or [],
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
def get_model_action(
|
| 1037 |
+
client: OpenAI | None,
|
| 1038 |
+
observation: UnifiedIncidentObservation,
|
| 1039 |
+
history: list[dict[str, Any]],
|
| 1040 |
+
policy_state: PolicyCardState,
|
| 1041 |
+
*,
|
| 1042 |
+
scenario_id: str | None = None,
|
| 1043 |
+
) -> tuple[UnifiedIncidentAction, str | None, bool, bool]:
|
| 1044 |
+
fallback = build_fallback_action(observation, history, scenario_id=scenario_id)
|
| 1045 |
+
mode = _inference_mode()
|
| 1046 |
+
if client is None:
|
| 1047 |
+
return fallback, "model_unavailable", False, True
|
| 1048 |
+
|
| 1049 |
+
try:
|
| 1050 |
+
policy_card = (
|
| 1051 |
+
build_policy_card(
|
| 1052 |
+
observation,
|
| 1053 |
+
policy_state,
|
| 1054 |
+
history,
|
| 1055 |
+
scenario_id=scenario_id,
|
| 1056 |
+
)
|
| 1057 |
+
if mode == "small"
|
| 1058 |
+
else ""
|
| 1059 |
+
)
|
| 1060 |
+
raw = _request_action_completion(
|
| 1061 |
+
client,
|
| 1062 |
+
observation,
|
| 1063 |
+
build_user_prompt(
|
| 1064 |
+
observation,
|
| 1065 |
+
policy_card,
|
| 1066 |
+
scenario_id=scenario_id,
|
| 1067 |
+
history=history,
|
| 1068 |
+
),
|
| 1069 |
+
temperature=0.0,
|
| 1070 |
+
scenario_id=scenario_id,
|
| 1071 |
+
history=history,
|
| 1072 |
+
)
|
| 1073 |
+
except Exception:
|
| 1074 |
+
return fallback, "model_request_failed", False, True
|
| 1075 |
+
|
| 1076 |
+
parsed = parse_action(
|
| 1077 |
+
raw,
|
| 1078 |
+
observation,
|
| 1079 |
+
scenario_id=scenario_id,
|
| 1080 |
+
history=history,
|
| 1081 |
+
)
|
| 1082 |
+
if parsed is None:
|
| 1083 |
+
repaired = attempt_repair(
|
| 1084 |
+
client,
|
| 1085 |
+
observation,
|
| 1086 |
+
raw,
|
| 1087 |
+
scenario_id=scenario_id,
|
| 1088 |
+
history=history,
|
| 1089 |
+
)
|
| 1090 |
+
if repaired is not None:
|
| 1091 |
+
return repaired, "repair_retry_used", True, False
|
| 1092 |
+
return fallback, "invalid_model_output", True, True
|
| 1093 |
+
return parsed, None, False, False
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
def run_scenario(client: OpenAI | None, scenario_id: str) -> dict[str, Any]:
|
| 1097 |
+
import time
|
| 1098 |
+
|
| 1099 |
+
started = time.perf_counter()
|
| 1100 |
+
with UnifiedIncidentEnv(base_url=ENV_BASE_URL).sync() as env:
|
| 1101 |
+
observation = env.reset(scenario_id=scenario_id).observation
|
| 1102 |
+
history: list[dict[str, Any]] = []
|
| 1103 |
+
rewards: list[float] = []
|
| 1104 |
+
policy_state = PolicyCardState()
|
| 1105 |
+
repair_retry_count = 0
|
| 1106 |
+
fallback_count = 0
|
| 1107 |
+
log_start(task=scenario_id, env=ENV_NAME, model=MODEL_NAME)
|
| 1108 |
+
|
| 1109 |
+
step = 0
|
| 1110 |
+
while not observation.done:
|
| 1111 |
+
before = observation
|
| 1112 |
+
action, error, used_repair_retry, used_fallback = get_model_action(
|
| 1113 |
+
client,
|
| 1114 |
+
observation,
|
| 1115 |
+
history,
|
| 1116 |
+
policy_state,
|
| 1117 |
+
scenario_id=scenario_id,
|
| 1118 |
+
)
|
| 1119 |
+
if used_repair_retry:
|
| 1120 |
+
repair_retry_count += 1
|
| 1121 |
+
if used_fallback:
|
| 1122 |
+
fallback_count += 1
|
| 1123 |
+
result = env.step(action)
|
| 1124 |
+
observation = result.observation
|
| 1125 |
+
reward = result.reward or 0.0
|
| 1126 |
+
step += 1
|
| 1127 |
+
rewards.append(reward)
|
| 1128 |
+
history.append(
|
| 1129 |
+
{
|
| 1130 |
+
"action": action,
|
| 1131 |
+
"reward": reward,
|
| 1132 |
+
"result": observation.last_action_result,
|
| 1133 |
+
"error": error,
|
| 1134 |
+
}
|
| 1135 |
+
)
|
| 1136 |
+
if _inference_mode() == "small":
|
| 1137 |
+
update_policy_card(
|
| 1138 |
+
policy_state,
|
| 1139 |
+
before=before,
|
| 1140 |
+
action=action,
|
| 1141 |
+
after=observation,
|
| 1142 |
+
model_error=error,
|
| 1143 |
+
)
|
| 1144 |
+
log_step(
|
| 1145 |
+
step=step,
|
| 1146 |
+
action=action_to_log_string(action),
|
| 1147 |
+
reward=reward,
|
| 1148 |
+
done=bool(result.done),
|
| 1149 |
+
error=error,
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
success = bool(
|
| 1153 |
+
observation.done
|
| 1154 |
+
and observation.incident_resolved
|
| 1155 |
+
and observation.security_subquest_status == "completed"
|
| 1156 |
+
)
|
| 1157 |
+
log_end(
|
| 1158 |
+
success=success,
|
| 1159 |
+
steps=step,
|
| 1160 |
+
rewards=rewards,
|
| 1161 |
+
)
|
| 1162 |
+
return {
|
| 1163 |
+
"scenario_id": scenario_id,
|
| 1164 |
+
"score": observation.final_score,
|
| 1165 |
+
"success": success,
|
| 1166 |
+
"steps": step,
|
| 1167 |
+
"repair_retry_triggered": repair_retry_count > 0,
|
| 1168 |
+
"repair_retry_count": repair_retry_count,
|
| 1169 |
+
"fallback_triggered": fallback_count > 0,
|
| 1170 |
+
"fallback_count": fallback_count,
|
| 1171 |
+
"elapsed_s": round(time.perf_counter() - started, 4),
|
| 1172 |
+
}
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
def main() -> None:
|
| 1176 |
+
client = create_client()
|
| 1177 |
+
for scenario_id in SCENARIOS:
|
| 1178 |
+
run_scenario(client, scenario_id)
|
| 1179 |
+
|
| 1180 |
+
|
| 1181 |
+
def _limit_words(text: str, *, max_words: int) -> str:
|
| 1182 |
+
words = text.split()
|
| 1183 |
+
if len(words) <= max_words:
|
| 1184 |
+
return text
|
| 1185 |
+
return " ".join(words[:max_words]).strip() + " ..."
|
| 1186 |
+
|
| 1187 |
+
|
| 1188 |
+
def _narrow_allowed_actions(
|
| 1189 |
+
observation: UnifiedIncidentObservation,
|
| 1190 |
+
*,
|
| 1191 |
+
scenario_id: str | None = None,
|
| 1192 |
+
history: list[dict[str, Any]] | None = None,
|
| 1193 |
+
) -> list[str]:
|
| 1194 |
+
allowed_actions = observation.allowed_actions or sorted(KNOWN_ACTIONS)
|
| 1195 |
+
hard = _hard_transition_state(
|
| 1196 |
+
scenario_id=scenario_id,
|
| 1197 |
+
observation=observation,
|
| 1198 |
+
history=history or [],
|
| 1199 |
+
)
|
| 1200 |
+
if hard["force_worker_rollback"] and "rollback_deploy" in allowed_actions:
|
| 1201 |
+
return ["rollback_deploy"]
|
| 1202 |
+
if hard["needs_unlock_bridge"] and "query_dependencies" in allowed_actions:
|
| 1203 |
+
return ["query_dependencies"]
|
| 1204 |
+
if hard["security_only"]:
|
| 1205 |
+
security_actions = [
|
| 1206 |
+
action for action in allowed_actions
|
| 1207 |
+
if action in {
|
| 1208 |
+
"inspect_code",
|
| 1209 |
+
"classify_vulnerability",
|
| 1210 |
+
"apply_patch",
|
| 1211 |
+
"verify_security_fix",
|
| 1212 |
+
"submit_security_fix",
|
| 1213 |
+
}
|
| 1214 |
+
]
|
| 1215 |
+
if security_actions:
|
| 1216 |
+
allowed_actions = security_actions
|
| 1217 |
+
if observation.workflow_stage not in {"security_subquest", "verification"}:
|
| 1218 |
+
return allowed_actions
|
| 1219 |
+
|
| 1220 |
+
context = observation.security_context
|
| 1221 |
+
if not context.code_visible and "inspect_code" in allowed_actions:
|
| 1222 |
+
return ["inspect_code"]
|
| 1223 |
+
if context.code_visible and context.selected_vulnerability is None and "classify_vulnerability" in allowed_actions:
|
| 1224 |
+
return ["classify_vulnerability"]
|
| 1225 |
+
if context.selected_vulnerability is not None and context.selected_patch is None and "apply_patch" in allowed_actions:
|
| 1226 |
+
return ["apply_patch"]
|
| 1227 |
+
if (
|
| 1228 |
+
context.selected_patch is not None
|
| 1229 |
+
and (context.exploit_blocked is not True or context.functionality_preserved is not True)
|
| 1230 |
+
and "verify_security_fix" in allowed_actions
|
| 1231 |
+
):
|
| 1232 |
+
return ["verify_security_fix"]
|
| 1233 |
+
if (
|
| 1234 |
+
context.exploit_blocked is True
|
| 1235 |
+
and context.functionality_preserved is True
|
| 1236 |
+
and "submit_security_fix" in allowed_actions
|
| 1237 |
+
):
|
| 1238 |
+
return ["submit_security_fix"]
|
| 1239 |
+
return allowed_actions
|
| 1240 |
+
|
| 1241 |
+
|
| 1242 |
+
def _hard_transition_state(
|
| 1243 |
+
*,
|
| 1244 |
+
scenario_id: str | None,
|
| 1245 |
+
observation: UnifiedIncidentObservation,
|
| 1246 |
+
history: list[dict[str, Any]],
|
| 1247 |
+
) -> dict[str, Any]:
|
| 1248 |
+
default = {
|
| 1249 |
+
"investigation_saturated": False,
|
| 1250 |
+
"stop_investigating": False,
|
| 1251 |
+
"stop_message": None,
|
| 1252 |
+
"next_required_action_family": None,
|
| 1253 |
+
"next_required_action": None,
|
| 1254 |
+
"needs_unlock_bridge": False,
|
| 1255 |
+
"security_only": False,
|
| 1256 |
+
"force_worker_rollback": False,
|
| 1257 |
+
}
|
| 1258 |
+
if scenario_id != "worker_bad_deploy_command_injection":
|
| 1259 |
+
return default
|
| 1260 |
+
|
| 1261 |
+
worker_log_queries = sum(
|
| 1262 |
+
1
|
| 1263 |
+
for item in history
|
| 1264 |
+
if item.get("action") is not None
|
| 1265 |
+
and item["action"].action_type == "query_logs"
|
| 1266 |
+
and item["action"].service == "worker"
|
| 1267 |
+
)
|
| 1268 |
+
support_queries = sum(
|
| 1269 |
+
1
|
| 1270 |
+
for item in history
|
| 1271 |
+
if item.get("action") is not None
|
| 1272 |
+
and (
|
| 1273 |
+
(item["action"].action_type == "query_metrics" and item["action"].service in {"worker", "database"})
|
| 1274 |
+
or (item["action"].action_type == "query_dependencies" and item["action"].service == "api-gateway")
|
| 1275 |
+
)
|
| 1276 |
+
)
|
| 1277 |
+
investigation_saturated = worker_log_queries >= 1 and (support_queries >= 1 or observation.workflow_stage != "diagnosis")
|
| 1278 |
+
security_completed = observation.security_subquest_status == "completed"
|
| 1279 |
+
security_unlocked = observation.security_subquest_status != "locked"
|
| 1280 |
+
worker_unhealthy = (
|
| 1281 |
+
observation.service_health.get("worker") is not None
|
| 1282 |
+
and observation.service_health["worker"].status != "healthy"
|
| 1283 |
+
)
|
| 1284 |
+
|
| 1285 |
+
if security_completed and worker_unhealthy:
|
| 1286 |
+
return {
|
| 1287 |
+
**default,
|
| 1288 |
+
"investigation_saturated": True,
|
| 1289 |
+
"stop_investigating": True,
|
| 1290 |
+
"stop_message": "Investigation is complete. The bad worker deploy is still active. Choose rollback_deploy on worker next.",
|
| 1291 |
+
"next_required_action_family": "recovery",
|
| 1292 |
+
"next_required_action": "Next required action: rollback_deploy on worker.",
|
| 1293 |
+
"force_worker_rollback": True,
|
| 1294 |
+
}
|
| 1295 |
+
|
| 1296 |
+
if investigation_saturated and not security_unlocked:
|
| 1297 |
+
return {
|
| 1298 |
+
**default,
|
| 1299 |
+
"investigation_saturated": True,
|
| 1300 |
+
"stop_investigating": True,
|
| 1301 |
+
"stop_message": "You already have enough evidence from worker investigation. Do not query worker logs again. Use query_dependencies on api-gateway to unlock the exploit path.",
|
| 1302 |
+
"next_required_action_family": "security",
|
| 1303 |
+
"next_required_action": "Next bridge action: query_dependencies on api-gateway, then move to security.",
|
| 1304 |
+
"needs_unlock_bridge": True,
|
| 1305 |
+
}
|
| 1306 |
+
|
| 1307 |
+
if investigation_saturated and security_unlocked and not security_completed:
|
| 1308 |
+
return {
|
| 1309 |
+
**default,
|
| 1310 |
+
"investigation_saturated": True,
|
| 1311 |
+
"stop_investigating": True,
|
| 1312 |
+
"stop_message": "Repeated worker investigation is making no progress. Investigation is complete. Choose a security action now.",
|
| 1313 |
+
"next_required_action_family": "security",
|
| 1314 |
+
"next_required_action": "Current goal: inspect and patch the worker exploit path.",
|
| 1315 |
+
"security_only": True,
|
| 1316 |
+
}
|
| 1317 |
+
|
| 1318 |
+
if worker_log_queries >= 2 and not security_completed:
|
| 1319 |
+
return {
|
| 1320 |
+
**default,
|
| 1321 |
+
"stop_investigating": True,
|
| 1322 |
+
"stop_message": "Repeated worker investigation is making no progress. Choose a different allowed action. Investigation is complete.",
|
| 1323 |
+
}
|
| 1324 |
+
|
| 1325 |
+
return default
|
| 1326 |
+
|
| 1327 |
+
|
| 1328 |
+
if __name__ == "__main__":
|
| 1329 |
+
main()
|
openenv.yaml
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: unified-incident-env
|
| 2 |
+
version: 1.0.0
|
| 3 |
+
description: >
|
| 4 |
+
Deterministic unified incident benchmark with one SRE flow, one security
|
| 5 |
+
subquest, and one final score.
|
| 6 |
+
author: Daksh Verma
|
| 7 |
+
license: MIT
|
| 8 |
+
|
| 9 |
+
environment:
|
| 10 |
+
action_type: UnifiedIncidentAction
|
| 11 |
+
observation_type: UnifiedIncidentObservation
|
| 12 |
+
state_type: UnifiedIncidentState
|
| 13 |
+
max_steps: 20
|
| 14 |
+
difficulties: [easy, medium, hard]
|
| 15 |
+
reward_type: dense
|
| 16 |
+
|
| 17 |
+
huggingface:
|
| 18 |
+
space_id: gylder/my-env
|
| 19 |
+
sdk: docker
|
| 20 |
+
hardware: cpu-basic
|
pyproject.toml
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["hatchling"]
|
| 3 |
+
build-backend = "hatchling.build"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "unified-incident-env"
|
| 7 |
+
version = "1.0.0"
|
| 8 |
+
description = "Unified OpenEnv benchmark for incident response with causally linked WebSec remediation"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.10"
|
| 11 |
+
dependencies = [
|
| 12 |
+
"openenv-core>=0.2.1",
|
| 13 |
+
"fastapi>=0.115.0",
|
| 14 |
+
"uvicorn[standard]>=0.30.0",
|
| 15 |
+
"pydantic>=2.8.0",
|
| 16 |
+
"httpx>=0.27.0",
|
| 17 |
+
"openai>=1.0.0",
|
| 18 |
+
"websockets>=12.0",
|
| 19 |
+
"rich>=13.0.0",
|
| 20 |
+
"matplotlib>=3.9.0",
|
| 21 |
+
"numpy>=2.0.0"
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
[project.optional-dependencies]
|
| 25 |
+
dev = [
|
| 26 |
+
"pytest>=8.0.0",
|
| 27 |
+
"pytest-asyncio>=0.23.0"
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
[project.scripts]
|
| 31 |
+
server = "server.app:main"
|
| 32 |
+
baseline = "unified_incident_env.scripts.baseline_agent:main"
|
| 33 |
+
walkthrough = "unified_incident_env.scripts.walkthrough:main"
|
| 34 |
+
trainer-run-episode = "unified_incident_env.trainer.run_episode:main"
|
| 35 |
+
trainer-build-dataset = "unified_incident_env.trainer.build_sft_dataset:main"
|
| 36 |
+
trainer-eval-models = "unified_incident_env.trainer.eval_models:main"
|
| 37 |
+
trainer-build-datasets = "unified_incident_env.trainer.build_datasets:main"
|
| 38 |
+
trainer-update-model = "unified_incident_env.trainer.update_model:main"
|
| 39 |
+
trainer-run-session = "unified_incident_env.trainer.run_session:main"
|
| 40 |
+
trainer-train-external = "unified_incident_env.trainer.train_external:main"
|
| 41 |
+
|
| 42 |
+
[tool.hatch.build.targets.wheel]
|
| 43 |
+
packages = ["unified_incident_env", "server"]
|
requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
-e .
|
run_demo.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run a local end-to-end benchmark demo against the OpenEnv server."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import signal
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import httpx
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
REPO_ROOT = Path(__file__).resolve().parent
|
| 17 |
+
BASE_URL = os.getenv("ENV_BASE_URL", "http://127.0.0.1:8000")
|
| 18 |
+
HEALTH_URL = f"{BASE_URL.rstrip('/')}/health"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def server_is_ready() -> bool:
|
| 22 |
+
try:
|
| 23 |
+
response = httpx.get(HEALTH_URL, timeout=2.0)
|
| 24 |
+
return response.status_code == 200
|
| 25 |
+
except Exception:
|
| 26 |
+
return False
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def start_server() -> subprocess.Popen[str]:
|
| 30 |
+
return subprocess.Popen(
|
| 31 |
+
[
|
| 32 |
+
sys.executable,
|
| 33 |
+
"-m",
|
| 34 |
+
"uvicorn",
|
| 35 |
+
"server.app:app",
|
| 36 |
+
"--host",
|
| 37 |
+
"127.0.0.1",
|
| 38 |
+
"--port",
|
| 39 |
+
"8000",
|
| 40 |
+
],
|
| 41 |
+
cwd=REPO_ROOT,
|
| 42 |
+
text=True,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def wait_for_server(timeout_s: float = 20.0) -> None:
|
| 47 |
+
deadline = time.time() + timeout_s
|
| 48 |
+
while time.time() < deadline:
|
| 49 |
+
if server_is_ready():
|
| 50 |
+
return
|
| 51 |
+
time.sleep(0.5)
|
| 52 |
+
raise RuntimeError(f"Server did not become ready at {HEALTH_URL}")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def stop_server(process: subprocess.Popen[str]) -> None:
|
| 56 |
+
if process.poll() is not None:
|
| 57 |
+
return
|
| 58 |
+
process.send_signal(signal.SIGTERM)
|
| 59 |
+
try:
|
| 60 |
+
process.wait(timeout=10)
|
| 61 |
+
except subprocess.TimeoutExpired:
|
| 62 |
+
process.kill()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def main() -> None:
|
| 66 |
+
server_process: subprocess.Popen[str] | None = None
|
| 67 |
+
try:
|
| 68 |
+
if not server_is_ready():
|
| 69 |
+
server_process = start_server()
|
| 70 |
+
wait_for_server()
|
| 71 |
+
|
| 72 |
+
env = os.environ.copy()
|
| 73 |
+
env.setdefault("ENV_BASE_URL", BASE_URL)
|
| 74 |
+
subprocess.run(
|
| 75 |
+
[sys.executable, "inference.py"],
|
| 76 |
+
cwd=REPO_ROOT,
|
| 77 |
+
env=env,
|
| 78 |
+
check=True,
|
| 79 |
+
)
|
| 80 |
+
finally:
|
| 81 |
+
if server_process is not None:
|
| 82 |
+
stop_server(server_process)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
main()
|
server/Dockerfile
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
+
PYTHONUNBUFFERED=1 \
|
| 7 |
+
ENABLE_WEB_INTERFACE=true
|
| 8 |
+
|
| 9 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 10 |
+
build-essential \
|
| 11 |
+
curl \
|
| 12 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 13 |
+
|
| 14 |
+
COPY . /app
|
| 15 |
+
|
| 16 |
+
RUN pip install --no-cache-dir --upgrade pip && \
|
| 17 |
+
pip install --no-cache-dir .
|
| 18 |
+
|
| 19 |
+
EXPOSE 8000
|
| 20 |
+
|
| 21 |
+
CMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "8000"]
|
server/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""OpenEnv server wrapper package."""
|
server/app.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Top-level OpenEnv entrypoint wrapper."""
|
| 2 |
+
|
| 3 |
+
from unified_incident_env.server.app import app, serve
|
| 4 |
+
from unified_incident_env.server.app import main as _main
|
| 5 |
+
|
| 6 |
+
__all__ = ["app", "main", "serve"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main() -> None:
|
| 10 |
+
_main()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
if __name__ == "__main__":
|
| 14 |
+
main()
|
server/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
openenv-core>=0.2.1
|
| 2 |
+
fastapi>=0.115.0
|
| 3 |
+
uvicorn[standard]>=0.30.0
|
| 4 |
+
pydantic>=2.8.0
|
| 5 |
+
websockets>=12.0
|
| 6 |
+
openai>=1.0.0
|
| 7 |
+
matplotlib>=3.9.0
|
| 8 |
+
numpy>=2.0.0
|
unified_incident_env/README.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Unified Incident Env
|
| 2 |
+
|
| 3 |
+
The runnable submission surface lives at the project root. This package contains the actual environment implementation:
|
| 4 |
+
|
| 5 |
+
- typed models in `models.py`
|
| 6 |
+
- environment logic in `server/environment.py`
|
| 7 |
+
- scoring in `server/grader.py`
|
| 8 |
+
- scenario catalog in `server/challenge.py`
|
| 9 |
+
|
| 10 |
+
Use the root `README.md` for run commands, scoring, and example interaction.
|
unified_incident_env/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unified incident-response OpenEnv package."""
|
| 2 |
+
|
| 3 |
+
from .interface import (
|
| 4 |
+
UnifiedIncidentAction,
|
| 5 |
+
UnifiedIncidentEnv,
|
| 6 |
+
UnifiedIncidentEnvironment,
|
| 7 |
+
UnifiedIncidentObservation,
|
| 8 |
+
UnifiedIncidentState,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"UnifiedIncidentAction",
|
| 13 |
+
"UnifiedIncidentEnv",
|
| 14 |
+
"UnifiedIncidentEnvironment",
|
| 15 |
+
"UnifiedIncidentObservation",
|
| 16 |
+
"UnifiedIncidentState",
|
| 17 |
+
]
|
unified_incident_env/client.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Typed OpenEnv client for the unified incident environment."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from openenv.core import EnvClient
|
| 8 |
+
from openenv.core.client_types import StepResult
|
| 9 |
+
|
| 10 |
+
from .models import UnifiedIncidentAction, UnifiedIncidentObservation, UnifiedIncidentState
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class UnifiedIncidentEnv(
|
| 14 |
+
EnvClient[UnifiedIncidentAction, UnifiedIncidentObservation, UnifiedIncidentState]
|
| 15 |
+
):
|
| 16 |
+
"""Typed client wrapper around the OpenEnv HTTP API."""
|
| 17 |
+
|
| 18 |
+
DEFAULT_BASE_URL = "http://127.0.0.1:8000"
|
| 19 |
+
|
| 20 |
+
def _step_payload(self, action: UnifiedIncidentAction) -> dict[str, Any]:
|
| 21 |
+
return action.model_dump(exclude_none=True)
|
| 22 |
+
|
| 23 |
+
def _parse_result(self, payload: dict[str, Any]) -> StepResult[UnifiedIncidentObservation]:
|
| 24 |
+
observation_data = dict(payload.get("observation", {}))
|
| 25 |
+
observation_data.setdefault("reward", payload.get("reward", 0.0))
|
| 26 |
+
observation_data.setdefault("done", payload.get("done", False))
|
| 27 |
+
observation = UnifiedIncidentObservation.model_validate(observation_data)
|
| 28 |
+
return StepResult(
|
| 29 |
+
observation=observation,
|
| 30 |
+
reward=payload.get("reward", observation.reward),
|
| 31 |
+
done=payload.get("done", observation.done),
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
def _parse_state(self, payload: dict[str, Any]) -> UnifiedIncidentState:
|
| 35 |
+
return UnifiedIncidentState.model_validate(payload)
|
unified_incident_env/interface.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Single public interface surface for the unified incident benchmark."""
|
| 2 |
+
|
| 3 |
+
from .client import UnifiedIncidentEnv
|
| 4 |
+
from .models import (
|
| 5 |
+
UnifiedIncidentAction,
|
| 6 |
+
UnifiedIncidentObservation,
|
| 7 |
+
UnifiedIncidentState,
|
| 8 |
+
)
|
| 9 |
+
from .server.environment import UnifiedIncidentEnvironment
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"UnifiedIncidentAction",
|
| 13 |
+
"UnifiedIncidentEnv",
|
| 14 |
+
"UnifiedIncidentEnvironment",
|
| 15 |
+
"UnifiedIncidentObservation",
|
| 16 |
+
"UnifiedIncidentState",
|
| 17 |
+
]
|
unified_incident_env/models.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Typed models for the final preset-based unified incident environment."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Any, Literal
|
| 6 |
+
|
| 7 |
+
from openenv.core import Action, Observation, State
|
| 8 |
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
| 9 |
+
|
| 10 |
+
ActionType = Literal[
|
| 11 |
+
"query_logs",
|
| 12 |
+
"query_metrics",
|
| 13 |
+
"query_dependencies",
|
| 14 |
+
"restart_service",
|
| 15 |
+
"rollback_deploy",
|
| 16 |
+
"inspect_code",
|
| 17 |
+
"classify_vulnerability",
|
| 18 |
+
"apply_patch",
|
| 19 |
+
"verify_security_fix",
|
| 20 |
+
"submit_security_fix",
|
| 21 |
+
"submit_postmortem",
|
| 22 |
+
]
|
| 23 |
+
Difficulty = Literal["easy", "medium", "hard"]
|
| 24 |
+
MetricName = Literal["cpu", "memory", "latency", "error_rate", "throughput"]
|
| 25 |
+
ServiceName = Literal["api-gateway", "cache", "database", "worker"]
|
| 26 |
+
ServiceStatus = Literal["healthy", "degraded", "crashed"]
|
| 27 |
+
WorkflowStage = Literal[
|
| 28 |
+
"diagnosis",
|
| 29 |
+
"root_cause_analysis",
|
| 30 |
+
"security_subquest",
|
| 31 |
+
"remediation",
|
| 32 |
+
"verification",
|
| 33 |
+
"postmortem",
|
| 34 |
+
"done",
|
| 35 |
+
]
|
| 36 |
+
SecuritySubquestStatus = Literal["locked", "active", "completed"]
|
| 37 |
+
VulnerabilityType = Literal[
|
| 38 |
+
"sql_injection",
|
| 39 |
+
"broken_access_control",
|
| 40 |
+
"command_injection",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class PostmortemPayload(BaseModel):
|
| 45 |
+
"""Structured postmortem payload used by the final action."""
|
| 46 |
+
|
| 47 |
+
model_config = ConfigDict(extra="forbid")
|
| 48 |
+
|
| 49 |
+
root_cause: str = ""
|
| 50 |
+
attack_vector: str = ""
|
| 51 |
+
timeline: list[str] = Field(default_factory=list)
|
| 52 |
+
remediation_steps: list[str] = Field(default_factory=list)
|
| 53 |
+
prevention_steps: list[str] = Field(default_factory=list)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class UnifiedIncidentAction(Action):
|
| 57 |
+
"""One structured environment action."""
|
| 58 |
+
|
| 59 |
+
model_config = ConfigDict(extra="ignore")
|
| 60 |
+
|
| 61 |
+
action_type: ActionType
|
| 62 |
+
service: ServiceName | None = None
|
| 63 |
+
metric: MetricName | None = None
|
| 64 |
+
vulnerability_type: VulnerabilityType | None = None
|
| 65 |
+
patch_id: str | None = None
|
| 66 |
+
postmortem: PostmortemPayload | None = None
|
| 67 |
+
|
| 68 |
+
@model_validator(mode="after")
|
| 69 |
+
def _validate_payload(self) -> "UnifiedIncidentAction":
|
| 70 |
+
if self.action_type in {
|
| 71 |
+
"query_logs",
|
| 72 |
+
"query_dependencies",
|
| 73 |
+
"restart_service",
|
| 74 |
+
"rollback_deploy",
|
| 75 |
+
} and not self.service:
|
| 76 |
+
raise ValueError(f"service is required for {self.action_type}")
|
| 77 |
+
if self.action_type == "query_metrics":
|
| 78 |
+
if not self.service:
|
| 79 |
+
raise ValueError("service is required for query_metrics")
|
| 80 |
+
if not self.metric:
|
| 81 |
+
raise ValueError("metric is required for query_metrics")
|
| 82 |
+
if (
|
| 83 |
+
self.action_type == "classify_vulnerability"
|
| 84 |
+
and self.vulnerability_type is None
|
| 85 |
+
):
|
| 86 |
+
raise ValueError(
|
| 87 |
+
"vulnerability_type is required for classify_vulnerability"
|
| 88 |
+
)
|
| 89 |
+
if self.action_type == "apply_patch" and not self.patch_id:
|
| 90 |
+
raise ValueError("patch_id is required for apply_patch")
|
| 91 |
+
if self.action_type == "submit_postmortem" and self.postmortem is None:
|
| 92 |
+
raise ValueError("postmortem is required for submit_postmortem")
|
| 93 |
+
return self
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class ServiceHealth(BaseModel):
|
| 97 |
+
"""Health snapshot for a service."""
|
| 98 |
+
|
| 99 |
+
model_config = ConfigDict(extra="forbid")
|
| 100 |
+
|
| 101 |
+
name: ServiceName
|
| 102 |
+
status: ServiceStatus
|
| 103 |
+
cpu_pct: float = Field(ge=0.0, le=100.0)
|
| 104 |
+
memory_pct: float = Field(ge=0.0, le=100.0)
|
| 105 |
+
error_rate_pct: float = Field(ge=0.0, le=100.0)
|
| 106 |
+
latency_ms: float = Field(ge=0.0)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class Alert(BaseModel):
|
| 110 |
+
"""Alert exposed to the agent."""
|
| 111 |
+
|
| 112 |
+
model_config = ConfigDict(extra="forbid")
|
| 113 |
+
|
| 114 |
+
service: ServiceName
|
| 115 |
+
severity: Literal["warning", "critical"]
|
| 116 |
+
message: str
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class SecurityContext(BaseModel):
|
| 120 |
+
"""Structured security subquest context."""
|
| 121 |
+
|
| 122 |
+
model_config = ConfigDict(extra="forbid")
|
| 123 |
+
|
| 124 |
+
code_visible: bool = False
|
| 125 |
+
selected_vulnerability: VulnerabilityType | None = None
|
| 126 |
+
selected_patch: str | None = None
|
| 127 |
+
exploit_blocked: bool | None = None
|
| 128 |
+
functionality_preserved: bool | None = None
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class PatchOption(BaseModel):
|
| 132 |
+
"""One security patch option."""
|
| 133 |
+
|
| 134 |
+
model_config = ConfigDict(extra="forbid")
|
| 135 |
+
|
| 136 |
+
id: str
|
| 137 |
+
label: str
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class UnifiedIncidentObservation(Observation):
|
| 141 |
+
"""Observation returned after reset and each step."""
|
| 142 |
+
|
| 143 |
+
model_config = ConfigDict(extra="forbid")
|
| 144 |
+
|
| 145 |
+
prompt_text: str
|
| 146 |
+
tick_count: int
|
| 147 |
+
max_ticks: int
|
| 148 |
+
difficulty: Difficulty
|
| 149 |
+
workflow_stage: WorkflowStage
|
| 150 |
+
active_alerts: list[Alert] = Field(default_factory=list)
|
| 151 |
+
service_health: dict[str, ServiceHealth] = Field(default_factory=dict)
|
| 152 |
+
last_action_result: str = ""
|
| 153 |
+
tool_output: str | None = None
|
| 154 |
+
failure_type: str | None = None
|
| 155 |
+
why_failed: str | None = None
|
| 156 |
+
allowed_actions: list[str] = Field(default_factory=list)
|
| 157 |
+
required_fields_by_action: dict[str, list[str]] = Field(default_factory=dict)
|
| 158 |
+
valid_action_example: dict[str, Any] | None = None
|
| 159 |
+
common_trap: str | None = None
|
| 160 |
+
loop_warning: str | None = None
|
| 161 |
+
blocked_until_security_complete: bool = False
|
| 162 |
+
security_unlock_reason: str | None = None
|
| 163 |
+
best_recovery_action_family: str | None = None
|
| 164 |
+
progress_flags: dict[str, bool] = Field(default_factory=dict)
|
| 165 |
+
security_subquest_status: SecuritySubquestStatus = "locked"
|
| 166 |
+
security_context: SecurityContext = Field(default_factory=SecurityContext)
|
| 167 |
+
final_score: float = 0.0
|
| 168 |
+
score_breakdown: dict[str, float] = Field(default_factory=dict)
|
| 169 |
+
incident_resolved: bool = False
|
| 170 |
+
reward: float = 0.0
|
| 171 |
+
done: bool = False
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class UnifiedIncidentState(State):
|
| 175 |
+
"""Persistent episode state."""
|
| 176 |
+
|
| 177 |
+
model_config = ConfigDict(extra="forbid")
|
| 178 |
+
|
| 179 |
+
episode_id: str
|
| 180 |
+
step_count: int
|
| 181 |
+
scenario_id: str
|
| 182 |
+
difficulty: Difficulty
|
| 183 |
+
current_tick: int
|
| 184 |
+
max_ticks: int
|
| 185 |
+
workflow_stage: WorkflowStage
|
| 186 |
+
active_alerts: list[Alert] = Field(default_factory=list)
|
| 187 |
+
service_health: dict[str, ServiceHealth] = Field(default_factory=dict)
|
| 188 |
+
discovered_evidence: list[str] = Field(default_factory=list)
|
| 189 |
+
identified_root_cause: str | None = None
|
| 190 |
+
failure_type: str | None = None
|
| 191 |
+
why_failed: str | None = None
|
| 192 |
+
allowed_actions: list[str] = Field(default_factory=list)
|
| 193 |
+
required_fields_by_action: dict[str, list[str]] = Field(default_factory=dict)
|
| 194 |
+
valid_action_example: dict[str, Any] | None = None
|
| 195 |
+
common_trap: str | None = None
|
| 196 |
+
loop_warning: str | None = None
|
| 197 |
+
blocked_until_security_complete: bool = False
|
| 198 |
+
security_unlock_reason: str | None = None
|
| 199 |
+
best_recovery_action_family: str | None = None
|
| 200 |
+
progress_flags: dict[str, bool] = Field(default_factory=dict)
|
| 201 |
+
security_subquest_status: SecuritySubquestStatus = "locked"
|
| 202 |
+
security_context: SecurityContext = Field(default_factory=SecurityContext)
|
| 203 |
+
relevant_investigations: int = 0
|
| 204 |
+
correct_infra_steps: int = 0
|
| 205 |
+
infra_restored_in_correct_order: bool = False
|
| 206 |
+
selected_vulnerability: VulnerabilityType | None = None
|
| 207 |
+
selected_patch: str | None = None
|
| 208 |
+
exploit_blocked: bool | None = None
|
| 209 |
+
functionality_preserved: bool | None = None
|
| 210 |
+
security_fix_submitted: bool = False
|
| 211 |
+
incident_resolved: bool = False
|
| 212 |
+
postmortem_submitted: bool = False
|
| 213 |
+
cumulative_reward: float = 0.0
|
| 214 |
+
cumulative_score: float = 0.0
|
| 215 |
+
score_breakdown: dict[str, float] = Field(default_factory=dict)
|
| 216 |
+
wasteful_ticks: int = 0
|
| 217 |
+
last_action_result: str = ""
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class ScenarioSummary(BaseModel):
|
| 221 |
+
"""Public scenario summary."""
|
| 222 |
+
|
| 223 |
+
model_config = ConfigDict(extra="forbid")
|
| 224 |
+
|
| 225 |
+
id: str
|
| 226 |
+
difficulty: Difficulty
|
| 227 |
+
name: str
|
| 228 |
+
description: str
|
| 229 |
+
root_cause: str
|
| 230 |
+
optimal_ticks: int
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class ScenarioCatalog(BaseModel):
|
| 234 |
+
"""Public scenario catalog."""
|
| 235 |
+
|
| 236 |
+
model_config = ConfigDict(extra="forbid")
|
| 237 |
+
|
| 238 |
+
environment: str = "unified_incident_env"
|
| 239 |
+
default_scenario_id: str
|
| 240 |
+
available_difficulties: list[Difficulty]
|
| 241 |
+
filtered_difficulty: Difficulty | None = None
|
| 242 |
+
scenarios: list[ScenarioSummary]
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class BaselineStep(BaseModel):
|
| 246 |
+
"""One baseline action."""
|
| 247 |
+
|
| 248 |
+
model_config = ConfigDict(extra="forbid")
|
| 249 |
+
|
| 250 |
+
action: UnifiedIncidentAction
|
| 251 |
+
rationale: str = ""
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class BaselineDefinition(BaseModel):
|
| 255 |
+
"""One baseline trajectory."""
|
| 256 |
+
|
| 257 |
+
model_config = ConfigDict(extra="forbid")
|
| 258 |
+
|
| 259 |
+
scenario_id: str
|
| 260 |
+
name: str
|
| 261 |
+
description: str
|
| 262 |
+
optimal_ticks: int
|
| 263 |
+
actions: list[BaselineStep] = Field(default_factory=list)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class BaselineCatalog(BaseModel):
|
| 267 |
+
"""Public baseline catalog."""
|
| 268 |
+
|
| 269 |
+
model_config = ConfigDict(extra="forbid")
|
| 270 |
+
|
| 271 |
+
environment: str = "unified_incident_env"
|
| 272 |
+
baselines: list[BaselineDefinition]
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class GraderCheck(BaseModel):
|
| 276 |
+
"""One normalized grader check."""
|
| 277 |
+
|
| 278 |
+
model_config = ConfigDict(extra="forbid")
|
| 279 |
+
|
| 280 |
+
name: str
|
| 281 |
+
passed: bool
|
| 282 |
+
detail: str
|
| 283 |
+
weight: float
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class GraderReport(BaseModel):
|
| 287 |
+
"""Episode-grade report."""
|
| 288 |
+
|
| 289 |
+
model_config = ConfigDict(extra="forbid")
|
| 290 |
+
|
| 291 |
+
scenario_id: str
|
| 292 |
+
passed: bool
|
| 293 |
+
score: float = Field(ge=0.0, le=1.0)
|
| 294 |
+
message: str
|
| 295 |
+
breakdown: dict[str, float] = Field(default_factory=dict)
|
| 296 |
+
checks: list[GraderCheck] = Field(default_factory=list)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class RuntimeStatus(BaseModel):
|
| 300 |
+
"""Runtime status route payload."""
|
| 301 |
+
|
| 302 |
+
model_config = ConfigDict(extra="forbid")
|
| 303 |
+
|
| 304 |
+
environment: str = "unified_incident_env"
|
| 305 |
+
progress: UnifiedIncidentState
|
| 306 |
+
grader: GraderReport
|
unified_incident_env/scripts/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Scripts for the unified incident environment."""
|
unified_incident_env/scripts/baseline_agent.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic scripted baseline for the final preset pack."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
from ..client import UnifiedIncidentEnv
|
| 9 |
+
from ..models import PostmortemPayload, UnifiedIncidentAction
|
| 10 |
+
from ..server.challenge import BASELINES, SCENARIOS
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
POSTMORTEMS = {
|
| 14 |
+
"database_sqli_outage": PostmortemPayload(
|
| 15 |
+
root_cause="SQL injection in login exhausted and crashed the database.",
|
| 16 |
+
attack_vector="Unsanitized SQL input triggered abusive database load.",
|
| 17 |
+
timeline=[
|
| 18 |
+
"Queried database logs",
|
| 19 |
+
"Inspected code",
|
| 20 |
+
"Patched SQL injection",
|
| 21 |
+
"Verified exploit blocked",
|
| 22 |
+
"Restarted database",
|
| 23 |
+
],
|
| 24 |
+
remediation_steps=["Use parameterized query", "Restart database"],
|
| 25 |
+
prevention_steps=["Parameterized queries", "DB abuse alerting"],
|
| 26 |
+
),
|
| 27 |
+
"cache_abuse_broken_access_control": PostmortemPayload(
|
| 28 |
+
root_cause="Broken access control on the internal admin endpoint caused a cache and database cascade.",
|
| 29 |
+
attack_vector="Missing authorization let attackers abuse the internal admin path.",
|
| 30 |
+
timeline=[
|
| 31 |
+
"Queried cache metrics",
|
| 32 |
+
"Queried api-gateway dependencies",
|
| 33 |
+
"Inspected code",
|
| 34 |
+
"Enforced admin role",
|
| 35 |
+
"Verified exploit blocked",
|
| 36 |
+
"Restarted cache",
|
| 37 |
+
"Restarted database",
|
| 38 |
+
],
|
| 39 |
+
remediation_steps=["Enforce admin role", "Restart cache", "Restart database"],
|
| 40 |
+
prevention_steps=["Authorization checks", "Admin role enforcement", "Rate limits"],
|
| 41 |
+
),
|
| 42 |
+
"worker_bad_deploy_command_injection": PostmortemPayload(
|
| 43 |
+
root_cause="A bad worker deploy plus command injection repeatedly poisoned downstream services.",
|
| 44 |
+
attack_vector="Shell-based worker commands accepted unsafe filenames and kept replaying corruption.",
|
| 45 |
+
timeline=[
|
| 46 |
+
"Queried worker logs",
|
| 47 |
+
"Inspected code",
|
| 48 |
+
"Patched command injection",
|
| 49 |
+
"Verified exploit blocked",
|
| 50 |
+
"Rolled back worker",
|
| 51 |
+
"Restarted database",
|
| 52 |
+
],
|
| 53 |
+
remediation_steps=["Avoid shell", "Rollback worker", "Restart database"],
|
| 54 |
+
prevention_steps=["Avoid shell", "Input validation", "Safer deploy checks"],
|
| 55 |
+
),
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def plan_for_scenario(scenario_id: str) -> list[UnifiedIncidentAction]:
|
| 60 |
+
steps = [step.action for step in BASELINES[scenario_id].actions]
|
| 61 |
+
steps.append(
|
| 62 |
+
UnifiedIncidentAction(
|
| 63 |
+
action_type="submit_postmortem",
|
| 64 |
+
postmortem=POSTMORTEMS[scenario_id],
|
| 65 |
+
)
|
| 66 |
+
)
|
| 67 |
+
return steps
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def run_scenario(base_url: str, scenario_id: str) -> dict[str, object]:
|
| 71 |
+
with UnifiedIncidentEnv(base_url=base_url).sync() as env:
|
| 72 |
+
env.reset(scenario_id=scenario_id)
|
| 73 |
+
final = None
|
| 74 |
+
for action in plan_for_scenario(scenario_id):
|
| 75 |
+
final = env.step(action).observation
|
| 76 |
+
assert final is not None
|
| 77 |
+
return {
|
| 78 |
+
"scenario_id": scenario_id,
|
| 79 |
+
"success": bool(final.done and final.incident_resolved),
|
| 80 |
+
"final_score": final.final_score,
|
| 81 |
+
"workflow_stage": final.workflow_stage,
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def main() -> None:
|
| 86 |
+
parser = argparse.ArgumentParser()
|
| 87 |
+
parser.add_argument("--base-url", default=UnifiedIncidentEnv.DEFAULT_BASE_URL)
|
| 88 |
+
parser.add_argument("--scenario", choices=sorted(SCENARIOS))
|
| 89 |
+
args = parser.parse_args()
|
| 90 |
+
|
| 91 |
+
scenario_ids = [args.scenario] if args.scenario else list(SCENARIOS)
|
| 92 |
+
results = [run_scenario(args.base_url, scenario_id) for scenario_id in scenario_ids]
|
| 93 |
+
print(json.dumps(results, indent=2))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
if __name__ == "__main__":
|
| 97 |
+
main()
|
unified_incident_env/scripts/walkthrough.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simple walkthrough that prints a full episode interaction."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
from ..client import UnifiedIncidentEnv
|
| 9 |
+
from .baseline_agent import plan_for_scenario
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def main() -> None:
|
| 13 |
+
parser = argparse.ArgumentParser()
|
| 14 |
+
parser.add_argument(
|
| 15 |
+
"--base-url",
|
| 16 |
+
default=UnifiedIncidentEnv.DEFAULT_BASE_URL,
|
| 17 |
+
)
|
| 18 |
+
parser.add_argument(
|
| 19 |
+
"--scenario",
|
| 20 |
+
default="easy_sqli_db_outage",
|
| 21 |
+
)
|
| 22 |
+
args = parser.parse_args()
|
| 23 |
+
|
| 24 |
+
with UnifiedIncidentEnv(base_url=args.base_url).sync() as env:
|
| 25 |
+
reset = env.reset(scenario_id=args.scenario).observation
|
| 26 |
+
print(json.dumps({"reset": reset.model_dump()}, indent=2))
|
| 27 |
+
for action in plan_for_scenario(args.scenario):
|
| 28 |
+
step = env.step(action).observation
|
| 29 |
+
print(
|
| 30 |
+
json.dumps(
|
| 31 |
+
{
|
| 32 |
+
"action": action.model_dump(exclude_none=True),
|
| 33 |
+
"observation": step.model_dump(),
|
| 34 |
+
},
|
| 35 |
+
indent=2,
|
| 36 |
+
)
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if __name__ == "__main__":
|
| 41 |
+
main()
|
unified_incident_env/server/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Server package for the unified incident environment."""
|
unified_incident_env/server/app.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI app and challenge routes for the unified incident environment."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
|
| 7 |
+
from fastapi import HTTPException
|
| 8 |
+
from openenv.core.env_server import create_app
|
| 9 |
+
|
| 10 |
+
from ..models import (
|
| 11 |
+
BaselineCatalog,
|
| 12 |
+
GraderReport,
|
| 13 |
+
RuntimeStatus,
|
| 14 |
+
ScenarioCatalog,
|
| 15 |
+
UnifiedIncidentAction,
|
| 16 |
+
UnifiedIncidentObservation,
|
| 17 |
+
UnifiedIncidentState,
|
| 18 |
+
)
|
| 19 |
+
from .challenge import (
|
| 20 |
+
current_runtime_progress,
|
| 21 |
+
grade_episode,
|
| 22 |
+
list_baselines,
|
| 23 |
+
list_scenarios,
|
| 24 |
+
set_runtime_progress,
|
| 25 |
+
)
|
| 26 |
+
from .environment import UnifiedIncidentEnvironment
|
| 27 |
+
|
| 28 |
+
_BOOTSTRAP_ENV = UnifiedIncidentEnvironment()
|
| 29 |
+
set_runtime_progress(_BOOTSTRAP_ENV.state.model_dump())
|
| 30 |
+
app = create_app(
|
| 31 |
+
lambda: UnifiedIncidentEnvironment(),
|
| 32 |
+
UnifiedIncidentAction,
|
| 33 |
+
UnifiedIncidentObservation,
|
| 34 |
+
env_name="unified_incident_env",
|
| 35 |
+
max_concurrent_envs=1,
|
| 36 |
+
)
|
| 37 |
+
app.router.routes = [
|
| 38 |
+
route
|
| 39 |
+
for route in app.router.routes
|
| 40 |
+
if not (getattr(route, "path", None) == "/health")
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@app.get("/tasks", response_model=ScenarioCatalog, tags=["challenge"])
|
| 45 |
+
def tasks(difficulty: str | None = None) -> ScenarioCatalog:
|
| 46 |
+
try:
|
| 47 |
+
return list_scenarios(difficulty=difficulty)
|
| 48 |
+
except ValueError as exc:
|
| 49 |
+
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@app.get("/baseline", response_model=BaselineCatalog, tags=["challenge"])
|
| 53 |
+
def baseline(scenario_id: str | None = None) -> BaselineCatalog:
|
| 54 |
+
try:
|
| 55 |
+
return list_baselines(scenario_id=scenario_id)
|
| 56 |
+
except ValueError as exc:
|
| 57 |
+
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@app.get("/grader", response_model=GraderReport, tags=["challenge"])
|
| 61 |
+
def grader(scenario_id: str | None = None) -> GraderReport:
|
| 62 |
+
progress = current_runtime_progress()
|
| 63 |
+
if scenario_id is not None:
|
| 64 |
+
progress["scenario_id"] = scenario_id
|
| 65 |
+
try:
|
| 66 |
+
return grade_episode(progress)
|
| 67 |
+
except ValueError as exc:
|
| 68 |
+
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@app.get("/status", response_model=RuntimeStatus, tags=["challenge"])
|
| 72 |
+
def status() -> RuntimeStatus:
|
| 73 |
+
progress = current_runtime_progress()
|
| 74 |
+
return RuntimeStatus(
|
| 75 |
+
progress=UnifiedIncidentState(**progress),
|
| 76 |
+
grader=grade_episode(progress),
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@app.get("/health", tags=["challenge"])
|
| 81 |
+
def health() -> dict[str, object]:
|
| 82 |
+
return {
|
| 83 |
+
"status": "ok",
|
| 84 |
+
"environment": "unified_incident_env",
|
| 85 |
+
"version": "1.0.0",
|
| 86 |
+
"stages": [
|
| 87 |
+
"diagnosis",
|
| 88 |
+
"root_cause_analysis",
|
| 89 |
+
"security_subquest",
|
| 90 |
+
"remediation",
|
| 91 |
+
"verification",
|
| 92 |
+
"postmortem",
|
| 93 |
+
"done",
|
| 94 |
+
],
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def serve(host: str = "0.0.0.0", port: int = 8000) -> None:
|
| 99 |
+
import uvicorn
|
| 100 |
+
|
| 101 |
+
uvicorn.run(app, host=host, port=port)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def main() -> None:
|
| 105 |
+
parser = argparse.ArgumentParser()
|
| 106 |
+
parser.add_argument("--host", default="0.0.0.0")
|
| 107 |
+
parser.add_argument("--port", type=int, default=8000)
|
| 108 |
+
args = parser.parse_args()
|
| 109 |
+
serve(host=args.host, port=args.port)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if __name__ == "__main__":
|
| 113 |
+
main()
|
unified_incident_env/server/challenge.py
ADDED
|
@@ -0,0 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Final preset scenario catalog, baselines, and runtime helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from copy import deepcopy
|
| 6 |
+
|
| 7 |
+
from ..models import (
|
| 8 |
+
BaselineCatalog,
|
| 9 |
+
BaselineDefinition,
|
| 10 |
+
BaselineStep,
|
| 11 |
+
ScenarioCatalog,
|
| 12 |
+
ScenarioSummary,
|
| 13 |
+
UnifiedIncidentAction,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
DEFAULT_SCENARIO_ID = "database_sqli_outage"
|
| 17 |
+
|
| 18 |
+
SCENARIOS: dict[str, dict] = {
|
| 19 |
+
"database_sqli_outage": {
|
| 20 |
+
"id": "database_sqli_outage",
|
| 21 |
+
"difficulty": "easy",
|
| 22 |
+
"name": "Database SQLi Outage",
|
| 23 |
+
"description": (
|
| 24 |
+
"Login SQL injection abuse overloads and crashes the database, which then drives gateway 502s."
|
| 25 |
+
),
|
| 26 |
+
"common_trap": "Restarting api-gateway only treats the symptom; the database and exploit path are still the root issue.",
|
| 27 |
+
"max_ticks": 8,
|
| 28 |
+
"optimal_ticks": 8,
|
| 29 |
+
"root_cause": "SQL injection in the login endpoint crashed the database.",
|
| 30 |
+
"attack_vector": "Unsanitized SQL input triggered abusive database load.",
|
| 31 |
+
"initial_services": {
|
| 32 |
+
"api-gateway": {
|
| 33 |
+
"status": "degraded",
|
| 34 |
+
"cpu_pct": 71.0,
|
| 35 |
+
"memory_pct": 49.0,
|
| 36 |
+
"error_rate_pct": 24.0,
|
| 37 |
+
"latency_ms": 710.0,
|
| 38 |
+
},
|
| 39 |
+
"cache": {
|
| 40 |
+
"status": "healthy",
|
| 41 |
+
"cpu_pct": 24.0,
|
| 42 |
+
"memory_pct": 29.0,
|
| 43 |
+
"error_rate_pct": 0.0,
|
| 44 |
+
"latency_ms": 18.0,
|
| 45 |
+
},
|
| 46 |
+
"database": {
|
| 47 |
+
"status": "crashed",
|
| 48 |
+
"cpu_pct": 99.0,
|
| 49 |
+
"memory_pct": 98.0,
|
| 50 |
+
"error_rate_pct": 100.0,
|
| 51 |
+
"latency_ms": 0.0,
|
| 52 |
+
},
|
| 53 |
+
"worker": {
|
| 54 |
+
"status": "healthy",
|
| 55 |
+
"cpu_pct": 20.0,
|
| 56 |
+
"memory_pct": 27.0,
|
| 57 |
+
"error_rate_pct": 0.0,
|
| 58 |
+
"latency_ms": 12.0,
|
| 59 |
+
},
|
| 60 |
+
},
|
| 61 |
+
"initial_alerts": [
|
| 62 |
+
{
|
| 63 |
+
"service": "api-gateway",
|
| 64 |
+
"severity": "critical",
|
| 65 |
+
"message": "High 502 rate on login and checkout.",
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"service": "database",
|
| 69 |
+
"severity": "critical",
|
| 70 |
+
"message": "Database process not responding.",
|
| 71 |
+
},
|
| 72 |
+
],
|
| 73 |
+
"logs": {
|
| 74 |
+
"api-gateway": "Gateway retries are failing because the database is down; 502s spiking across auth traffic.",
|
| 75 |
+
"cache": "Cache is healthy; upstream database lookups are failing.",
|
| 76 |
+
"database": (
|
| 77 |
+
"SECURITY_ALERT root cause confirmed: login query used raw string concatenation; "
|
| 78 |
+
"payload `' OR 1=1 --` triggered abusive query load, exhausted the connection pool, "
|
| 79 |
+
"and crashed the database process."
|
| 80 |
+
),
|
| 81 |
+
"worker": "Worker is healthy and unrelated to this outage.",
|
| 82 |
+
},
|
| 83 |
+
"metrics": {
|
| 84 |
+
"database": {
|
| 85 |
+
"cpu": "Database CPU was pinned at 99% before the crash.",
|
| 86 |
+
"memory": "Database memory hit 98% immediately before process exit.",
|
| 87 |
+
},
|
| 88 |
+
"api-gateway": {
|
| 89 |
+
"error_rate": "Gateway error rate is 24%, almost all 502s.",
|
| 90 |
+
},
|
| 91 |
+
},
|
| 92 |
+
"dependencies": {
|
| 93 |
+
"api-gateway": "api-gateway -> cache -> database",
|
| 94 |
+
"database": "database serves login and order state",
|
| 95 |
+
},
|
| 96 |
+
"evidence_rules": [
|
| 97 |
+
{
|
| 98 |
+
"id": "db_logs_root",
|
| 99 |
+
"action_type": "query_logs",
|
| 100 |
+
"service": "database",
|
| 101 |
+
"detail": "Database logs explicitly confirm SQL injection caused the outage.",
|
| 102 |
+
"identifies_root_cause": True,
|
| 103 |
+
"unlocks_security": True,
|
| 104 |
+
"unlock_reason": "Database root-cause logs exposed the vulnerable login path, so the security subquest is now active.",
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"id": "db_metrics_memory",
|
| 108 |
+
"action_type": "query_metrics",
|
| 109 |
+
"service": "database",
|
| 110 |
+
"metric": "memory",
|
| 111 |
+
"detail": "Database memory spike confirmed crash pressure from abusive login traffic.",
|
| 112 |
+
"identifies_root_cause": False,
|
| 113 |
+
"unlocks_security": False,
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"id": "gateway_dependencies",
|
| 117 |
+
"action_type": "query_dependencies",
|
| 118 |
+
"service": "api-gateway",
|
| 119 |
+
"detail": "Gateway depends on the database path.",
|
| 120 |
+
"identifies_root_cause": False,
|
| 121 |
+
"unlocks_security": False,
|
| 122 |
+
},
|
| 123 |
+
],
|
| 124 |
+
"unlock_threshold": 1,
|
| 125 |
+
"security": {
|
| 126 |
+
"hint": "The login handler must bind user input instead of concatenating SQL.",
|
| 127 |
+
"code_context": (
|
| 128 |
+
"def login(username, password):\n"
|
| 129 |
+
" query = \"SELECT id FROM users WHERE username='\" + username + "
|
| 130 |
+
"\"' AND password='\" + password + \"'\"\n"
|
| 131 |
+
" return db.execute(query).fetchone()\n"
|
| 132 |
+
),
|
| 133 |
+
"correct_vulnerability": "sql_injection",
|
| 134 |
+
"correct_patch": "parameterized_query",
|
| 135 |
+
"patch_options": [
|
| 136 |
+
{"id": "parameterized_query", "label": "Use a parameterized query"},
|
| 137 |
+
{"id": "strip_quotes", "label": "Strip quotes from input"},
|
| 138 |
+
{"id": "disable_login", "label": "Disable the login endpoint"},
|
| 139 |
+
],
|
| 140 |
+
"verify_outcomes": {
|
| 141 |
+
"parameterized_query": {
|
| 142 |
+
"exploit_blocked": True,
|
| 143 |
+
"functionality_preserved": True,
|
| 144 |
+
"message": "Exploit blocked and legitimate logins still work.",
|
| 145 |
+
},
|
| 146 |
+
"strip_quotes": {
|
| 147 |
+
"exploit_blocked": False,
|
| 148 |
+
"functionality_preserved": True,
|
| 149 |
+
"message": "Quote stripping is bypassable; exploit still works.",
|
| 150 |
+
},
|
| 151 |
+
"disable_login": {
|
| 152 |
+
"exploit_blocked": True,
|
| 153 |
+
"functionality_preserved": False,
|
| 154 |
+
"message": "Exploit blocked, but legitimate users are locked out.",
|
| 155 |
+
},
|
| 156 |
+
},
|
| 157 |
+
},
|
| 158 |
+
"recovery_sequence": [
|
| 159 |
+
{
|
| 160 |
+
"action_type": "restart_service",
|
| 161 |
+
"service": "database",
|
| 162 |
+
"requires_security_completion": True,
|
| 163 |
+
"message": "Database restarted cleanly after the SQL injection path was closed.",
|
| 164 |
+
"updates": {
|
| 165 |
+
"database": {
|
| 166 |
+
"status": "healthy",
|
| 167 |
+
"cpu_pct": 37.0,
|
| 168 |
+
"memory_pct": 43.0,
|
| 169 |
+
"error_rate_pct": 0.0,
|
| 170 |
+
"latency_ms": 19.0,
|
| 171 |
+
},
|
| 172 |
+
"api-gateway": {
|
| 173 |
+
"status": "healthy",
|
| 174 |
+
"cpu_pct": 33.0,
|
| 175 |
+
"memory_pct": 34.0,
|
| 176 |
+
"error_rate_pct": 0.0,
|
| 177 |
+
"latency_ms": 41.0,
|
| 178 |
+
},
|
| 179 |
+
},
|
| 180 |
+
}
|
| 181 |
+
],
|
| 182 |
+
"trap_actions": [
|
| 183 |
+
{
|
| 184 |
+
"action_type": "restart_service",
|
| 185 |
+
"service": "api-gateway",
|
| 186 |
+
"message": "Restarting api-gateway first does not help while the database is still crashed.",
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"action_type": "restart_service",
|
| 190 |
+
"service": "cache",
|
| 191 |
+
"message": "Restarting cache is a trap; cache is not the failing root cause.",
|
| 192 |
+
},
|
| 193 |
+
],
|
| 194 |
+
"postmortem_keywords": {
|
| 195 |
+
"root_cause": ["sql injection", "database"],
|
| 196 |
+
"attack_vector": ["unsanitized sql", "login", "input"],
|
| 197 |
+
"remediation": ["parameterized query", "restart database"],
|
| 198 |
+
"prevention": ["parameterized queries", "db abuse alerting", "alerting"],
|
| 199 |
+
},
|
| 200 |
+
},
|
| 201 |
+
"cache_abuse_broken_access_control": {
|
| 202 |
+
"id": "cache_abuse_broken_access_control",
|
| 203 |
+
"difficulty": "medium",
|
| 204 |
+
"name": "Cache Abuse Broken Access Control",
|
| 205 |
+
"description": (
|
| 206 |
+
"An internal admin endpoint lacks proper authorization and abuse cascades through cache and database."
|
| 207 |
+
),
|
| 208 |
+
"common_trap": "Restarting database or api-gateway first does not close the abused admin path.",
|
| 209 |
+
"max_ticks": 20,
|
| 210 |
+
"optimal_ticks": 10,
|
| 211 |
+
"root_cause": "Broken access control exposed an internal admin endpoint and caused a cache/database cascade.",
|
| 212 |
+
"attack_vector": "Missing admin authorization let attackers abuse an internal cache-management route.",
|
| 213 |
+
"initial_services": {
|
| 214 |
+
"api-gateway": {
|
| 215 |
+
"status": "degraded",
|
| 216 |
+
"cpu_pct": 63.0,
|
| 217 |
+
"memory_pct": 44.0,
|
| 218 |
+
"error_rate_pct": 11.0,
|
| 219 |
+
"latency_ms": 420.0,
|
| 220 |
+
},
|
| 221 |
+
"cache": {
|
| 222 |
+
"status": "crashed",
|
| 223 |
+
"cpu_pct": 95.0,
|
| 224 |
+
"memory_pct": 93.0,
|
| 225 |
+
"error_rate_pct": 100.0,
|
| 226 |
+
"latency_ms": 0.0,
|
| 227 |
+
},
|
| 228 |
+
"database": {
|
| 229 |
+
"status": "degraded",
|
| 230 |
+
"cpu_pct": 88.0,
|
| 231 |
+
"memory_pct": 74.0,
|
| 232 |
+
"error_rate_pct": 16.0,
|
| 233 |
+
"latency_ms": 240.0,
|
| 234 |
+
},
|
| 235 |
+
"worker": {
|
| 236 |
+
"status": "healthy",
|
| 237 |
+
"cpu_pct": 19.0,
|
| 238 |
+
"memory_pct": 25.0,
|
| 239 |
+
"error_rate_pct": 0.0,
|
| 240 |
+
"latency_ms": 11.0,
|
| 241 |
+
},
|
| 242 |
+
},
|
| 243 |
+
"initial_alerts": [
|
| 244 |
+
{
|
| 245 |
+
"service": "cache",
|
| 246 |
+
"severity": "critical",
|
| 247 |
+
"message": "Cache repeated crash and overload cycle.",
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"service": "database",
|
| 251 |
+
"severity": "critical",
|
| 252 |
+
"message": "Database sustained high CPU after cache failures.",
|
| 253 |
+
},
|
| 254 |
+
{
|
| 255 |
+
"service": "api-gateway",
|
| 256 |
+
"severity": "warning",
|
| 257 |
+
"message": "Gateway latency spiking across cache-backed routes.",
|
| 258 |
+
},
|
| 259 |
+
],
|
| 260 |
+
"logs": {
|
| 261 |
+
"api-gateway": (
|
| 262 |
+
"Repeated calls to /internal/admin/cache-purge are causing downstream churn and latency spikes."
|
| 263 |
+
),
|
| 264 |
+
"cache": (
|
| 265 |
+
"SECURITY_ALERT unauthorized requests hit the internal admin purge endpoint; "
|
| 266 |
+
"rebuild storm repeatedly crashed cache."
|
| 267 |
+
),
|
| 268 |
+
"database": "Database is serving cache-miss flood traffic and remains degraded.",
|
| 269 |
+
"worker": "Worker is healthy and not on the critical path.",
|
| 270 |
+
},
|
| 271 |
+
"metrics": {
|
| 272 |
+
"cache": {
|
| 273 |
+
"cpu": "Cache CPU remains pinned during repeated rebuild cycles.",
|
| 274 |
+
"memory": "Cache memory spiked before each crash.",
|
| 275 |
+
},
|
| 276 |
+
"database": {
|
| 277 |
+
"cpu": "Database CPU is elevated due to cache misses.",
|
| 278 |
+
},
|
| 279 |
+
},
|
| 280 |
+
"dependencies": {
|
| 281 |
+
"api-gateway": "api-gateway -> cache -> database",
|
| 282 |
+
"cache": "cache is flushed by internal admin handlers behind api-gateway",
|
| 283 |
+
},
|
| 284 |
+
"evidence_rules": [
|
| 285 |
+
{
|
| 286 |
+
"id": "cache_metrics_root",
|
| 287 |
+
"action_type": "query_metrics",
|
| 288 |
+
"service": "cache",
|
| 289 |
+
"metric": "cpu",
|
| 290 |
+
"detail": "Cache metrics showed a rebuild storm.",
|
| 291 |
+
"identifies_root_cause": True,
|
| 292 |
+
"unlocks_security": False,
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"id": "gateway_dependencies_unlock",
|
| 296 |
+
"action_type": "query_dependencies",
|
| 297 |
+
"service": "api-gateway",
|
| 298 |
+
"detail": "Dependency analysis pointed to an internal admin chain through api-gateway.",
|
| 299 |
+
"identifies_root_cause": False,
|
| 300 |
+
"unlocks_security": True,
|
| 301 |
+
"unlock_reason": "The dependency chain exposed an internal admin route, so code inspection is now justified.",
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"id": "cache_logs_alt_unlock",
|
| 305 |
+
"action_type": "query_logs",
|
| 306 |
+
"service": "cache",
|
| 307 |
+
"detail": "Cache logs exposed the missing admin authorization issue.",
|
| 308 |
+
"identifies_root_cause": True,
|
| 309 |
+
"unlocks_security": True,
|
| 310 |
+
"unlock_reason": "Cache logs exposed the authorization flaw directly, so the security subquest is now active.",
|
| 311 |
+
},
|
| 312 |
+
],
|
| 313 |
+
"unlock_threshold": 2,
|
| 314 |
+
"security": {
|
| 315 |
+
"hint": "The internal admin endpoint must enforce proper server-side authorization.",
|
| 316 |
+
"code_context": (
|
| 317 |
+
"def purge_cache(request, current_user):\n"
|
| 318 |
+
" if not current_user:\n"
|
| 319 |
+
" raise UnauthorizedError()\n"
|
| 320 |
+
" return cache.purge(request.query_params['key'])\n"
|
| 321 |
+
),
|
| 322 |
+
"correct_vulnerability": "broken_access_control",
|
| 323 |
+
"correct_patch": "enforce_admin_role",
|
| 324 |
+
"patch_options": [
|
| 325 |
+
{"id": "enforce_admin_role", "label": "Enforce admin role server-side"},
|
| 326 |
+
{"id": "hide_admin_link", "label": "Hide the admin link in the UI"},
|
| 327 |
+
{"id": "deny_all_traffic", "label": "Block all traffic to the endpoint"},
|
| 328 |
+
],
|
| 329 |
+
"verify_outcomes": {
|
| 330 |
+
"enforce_admin_role": {
|
| 331 |
+
"exploit_blocked": True,
|
| 332 |
+
"functionality_preserved": True,
|
| 333 |
+
"message": "Abuse path closed and valid admins still work.",
|
| 334 |
+
},
|
| 335 |
+
"hide_admin_link": {
|
| 336 |
+
"exploit_blocked": False,
|
| 337 |
+
"functionality_preserved": True,
|
| 338 |
+
"message": "UI-only hiding fails; direct requests still work.",
|
| 339 |
+
},
|
| 340 |
+
"deny_all_traffic": {
|
| 341 |
+
"exploit_blocked": True,
|
| 342 |
+
"functionality_preserved": False,
|
| 343 |
+
"message": "Abuse closed, but legitimate admin usage is broken.",
|
| 344 |
+
},
|
| 345 |
+
},
|
| 346 |
+
},
|
| 347 |
+
"recovery_sequence": [
|
| 348 |
+
{
|
| 349 |
+
"action_type": "restart_service",
|
| 350 |
+
"service": "cache",
|
| 351 |
+
"requires_security_completion": True,
|
| 352 |
+
"message": "Cache recovered and stayed healthy once the abuse path was closed.",
|
| 353 |
+
"updates": {
|
| 354 |
+
"cache": {
|
| 355 |
+
"status": "healthy",
|
| 356 |
+
"cpu_pct": 36.0,
|
| 357 |
+
"memory_pct": 42.0,
|
| 358 |
+
"error_rate_pct": 0.0,
|
| 359 |
+
"latency_ms": 12.0,
|
| 360 |
+
}
|
| 361 |
+
},
|
| 362 |
+
},
|
| 363 |
+
{
|
| 364 |
+
"action_type": "restart_service",
|
| 365 |
+
"service": "database",
|
| 366 |
+
"requires_security_completion": True,
|
| 367 |
+
"message": "Database stabilized after cache recovered and load normalized.",
|
| 368 |
+
"updates": {
|
| 369 |
+
"database": {
|
| 370 |
+
"status": "healthy",
|
| 371 |
+
"cpu_pct": 35.0,
|
| 372 |
+
"memory_pct": 41.0,
|
| 373 |
+
"error_rate_pct": 0.0,
|
| 374 |
+
"latency_ms": 23.0,
|
| 375 |
+
},
|
| 376 |
+
"api-gateway": {
|
| 377 |
+
"status": "healthy",
|
| 378 |
+
"cpu_pct": 31.0,
|
| 379 |
+
"memory_pct": 33.0,
|
| 380 |
+
"error_rate_pct": 0.0,
|
| 381 |
+
"latency_ms": 39.0,
|
| 382 |
+
},
|
| 383 |
+
},
|
| 384 |
+
},
|
| 385 |
+
],
|
| 386 |
+
"trap_actions": [
|
| 387 |
+
{
|
| 388 |
+
"action_type": "restart_service",
|
| 389 |
+
"service": "database",
|
| 390 |
+
"message": "Restarting database first is a trap; the abuse path will overload it again.",
|
| 391 |
+
},
|
| 392 |
+
{
|
| 393 |
+
"action_type": "restart_service",
|
| 394 |
+
"service": "api-gateway",
|
| 395 |
+
"message": "Restarting api-gateway first treats a symptom, not the root cause.",
|
| 396 |
+
},
|
| 397 |
+
],
|
| 398 |
+
"postmortem_keywords": {
|
| 399 |
+
"root_cause": ["broken access control", "cache", "admin endpoint"],
|
| 400 |
+
"attack_vector": ["authorization", "admin", "internal"],
|
| 401 |
+
"remediation": ["enforce admin role", "restart cache", "restart database"],
|
| 402 |
+
"prevention": ["authorization", "admin role", "rate limits"],
|
| 403 |
+
},
|
| 404 |
+
},
|
| 405 |
+
"worker_bad_deploy_command_injection": {
|
| 406 |
+
"id": "worker_bad_deploy_command_injection",
|
| 407 |
+
"difficulty": "hard",
|
| 408 |
+
"name": "Worker Bad Deploy Command Injection",
|
| 409 |
+
"description": (
|
| 410 |
+
"A bad worker deployment plus command injection repeatedly poisons downstream services."
|
| 411 |
+
),
|
| 412 |
+
"common_trap": "Restarting downstream services first does not help while the worker remains unsafe.",
|
| 413 |
+
"max_ticks": 20,
|
| 414 |
+
"optimal_ticks": 9,
|
| 415 |
+
"root_cause": "A bad worker deploy plus command injection repeatedly poisoned downstream systems.",
|
| 416 |
+
"attack_vector": "Shell command construction in the worker allowed repeated command injection.",
|
| 417 |
+
"initial_services": {
|
| 418 |
+
"api-gateway": {
|
| 419 |
+
"status": "degraded",
|
| 420 |
+
"cpu_pct": 58.0,
|
| 421 |
+
"memory_pct": 41.0,
|
| 422 |
+
"error_rate_pct": 9.0,
|
| 423 |
+
"latency_ms": 370.0,
|
| 424 |
+
},
|
| 425 |
+
"cache": {
|
| 426 |
+
"status": "healthy",
|
| 427 |
+
"cpu_pct": 23.0,
|
| 428 |
+
"memory_pct": 28.0,
|
| 429 |
+
"error_rate_pct": 0.0,
|
| 430 |
+
"latency_ms": 15.0,
|
| 431 |
+
},
|
| 432 |
+
"database": {
|
| 433 |
+
"status": "degraded",
|
| 434 |
+
"cpu_pct": 79.0,
|
| 435 |
+
"memory_pct": 66.0,
|
| 436 |
+
"error_rate_pct": 13.0,
|
| 437 |
+
"latency_ms": 210.0,
|
| 438 |
+
},
|
| 439 |
+
"worker": {
|
| 440 |
+
"status": "degraded",
|
| 441 |
+
"cpu_pct": 94.0,
|
| 442 |
+
"memory_pct": 87.0,
|
| 443 |
+
"error_rate_pct": 31.0,
|
| 444 |
+
"latency_ms": 160.0,
|
| 445 |
+
},
|
| 446 |
+
},
|
| 447 |
+
"initial_alerts": [
|
| 448 |
+
{
|
| 449 |
+
"service": "worker",
|
| 450 |
+
"severity": "critical",
|
| 451 |
+
"message": "Worker abnormal memory growth and process churn.",
|
| 452 |
+
},
|
| 453 |
+
{
|
| 454 |
+
"service": "database",
|
| 455 |
+
"severity": "critical",
|
| 456 |
+
"message": "Database connection instability from worker retries.",
|
| 457 |
+
},
|
| 458 |
+
{
|
| 459 |
+
"service": "api-gateway",
|
| 460 |
+
"severity": "warning",
|
| 461 |
+
"message": "Partial outage across export-backed routes.",
|
| 462 |
+
},
|
| 463 |
+
],
|
| 464 |
+
"logs": {
|
| 465 |
+
"api-gateway": "Gateway requests are stalling on worker-backed exports and reading stale downstream state.",
|
| 466 |
+
"cache": "Cache is healthy; no primary fault present here.",
|
| 467 |
+
"database": "Database connections are unstable because worker retries keep replaying corrupt jobs.",
|
| 468 |
+
"worker": (
|
| 469 |
+
"SECURITY_ALERT export worker shells out with unsanitized user-controlled filenames; "
|
| 470 |
+
"current deploy removed safe command wrapper and corruption repeats."
|
| 471 |
+
),
|
| 472 |
+
},
|
| 473 |
+
"metrics": {
|
| 474 |
+
"database": {
|
| 475 |
+
"cpu": "Database CPU remains elevated from repeated worker retry churn.",
|
| 476 |
+
"latency": "Database latency spikes when corrupt export jobs replay.",
|
| 477 |
+
},
|
| 478 |
+
"worker": {
|
| 479 |
+
"memory": "Worker memory and process churn indicate a bad deploy plus repeated exploit path.",
|
| 480 |
+
},
|
| 481 |
+
},
|
| 482 |
+
"dependencies": {
|
| 483 |
+
"api-gateway": "api-gateway -> worker -> database",
|
| 484 |
+
"worker": "worker writes export state into database and feeds api-gateway completion paths",
|
| 485 |
+
},
|
| 486 |
+
"evidence_rules": [
|
| 487 |
+
{
|
| 488 |
+
"id": "worker_logs_root",
|
| 489 |
+
"action_type": "query_logs",
|
| 490 |
+
"service": "worker",
|
| 491 |
+
"detail": "Worker logs exposed the command injection clue and bad deploy link.",
|
| 492 |
+
"identifies_root_cause": True,
|
| 493 |
+
"unlocks_security": True,
|
| 494 |
+
"unlock_reason": "Worker logs already expose the exploit path, so the security subquest is now active.",
|
| 495 |
+
},
|
| 496 |
+
{
|
| 497 |
+
"id": "db_metrics_support",
|
| 498 |
+
"action_type": "query_metrics",
|
| 499 |
+
"service": "database",
|
| 500 |
+
"metric": "cpu",
|
| 501 |
+
"detail": "Database metrics confirmed downstream instability from worker retries.",
|
| 502 |
+
"identifies_root_cause": False,
|
| 503 |
+
"unlocks_security": False,
|
| 504 |
+
},
|
| 505 |
+
{
|
| 506 |
+
"id": "gateway_dependency_chain",
|
| 507 |
+
"action_type": "query_dependencies",
|
| 508 |
+
"service": "api-gateway",
|
| 509 |
+
"detail": "Dependency analysis exposed the worker-to-database-to-gateway chain.",
|
| 510 |
+
"identifies_root_cause": False,
|
| 511 |
+
"unlocks_security": True,
|
| 512 |
+
"unlock_reason": "The dependency chain points back to the worker exploit path, so the security subquest is now active.",
|
| 513 |
+
},
|
| 514 |
+
],
|
| 515 |
+
"unlock_threshold": 1,
|
| 516 |
+
"security": {
|
| 517 |
+
"hint": "The worker must stop passing filenames into a shell command.",
|
| 518 |
+
"code_context": (
|
| 519 |
+
"def build_export(filename):\n"
|
| 520 |
+
" cmd = '/usr/bin/zip /tmp/out.zip ' + filename\n"
|
| 521 |
+
" return subprocess.check_output(cmd, shell=True)\n"
|
| 522 |
+
),
|
| 523 |
+
"correct_vulnerability": "command_injection",
|
| 524 |
+
"correct_patch": "avoid_shell",
|
| 525 |
+
"patch_options": [
|
| 526 |
+
{"id": "avoid_shell", "label": "Use argv and avoid shell invocation"},
|
| 527 |
+
{"id": "sanitize_quotes_only", "label": "Sanitize quotes only"},
|
| 528 |
+
{"id": "disable_worker_commands", "label": "Disable worker commands"},
|
| 529 |
+
],
|
| 530 |
+
"verify_outcomes": {
|
| 531 |
+
"avoid_shell": {
|
| 532 |
+
"exploit_blocked": True,
|
| 533 |
+
"functionality_preserved": True,
|
| 534 |
+
"message": "Exploit blocked and worker exports still function.",
|
| 535 |
+
},
|
| 536 |
+
"sanitize_quotes_only": {
|
| 537 |
+
"exploit_blocked": False,
|
| 538 |
+
"functionality_preserved": True,
|
| 539 |
+
"message": "Quote-only sanitization is bypassable; exploit path remains.",
|
| 540 |
+
},
|
| 541 |
+
"disable_worker_commands": {
|
| 542 |
+
"exploit_blocked": True,
|
| 543 |
+
"functionality_preserved": False,
|
| 544 |
+
"message": "Exploit blocked, but core worker functionality is disabled.",
|
| 545 |
+
},
|
| 546 |
+
},
|
| 547 |
+
},
|
| 548 |
+
"recovery_sequence": [
|
| 549 |
+
{
|
| 550 |
+
"action_type": "rollback_deploy",
|
| 551 |
+
"service": "worker",
|
| 552 |
+
"requires_security_completion": True,
|
| 553 |
+
"message": "Worker rolled back to the safe version after the exploit path was closed.",
|
| 554 |
+
"updates": {
|
| 555 |
+
"worker": {
|
| 556 |
+
"status": "healthy",
|
| 557 |
+
"cpu_pct": 37.0,
|
| 558 |
+
"memory_pct": 40.0,
|
| 559 |
+
"error_rate_pct": 0.0,
|
| 560 |
+
"latency_ms": 26.0,
|
| 561 |
+
}
|
| 562 |
+
},
|
| 563 |
+
},
|
| 564 |
+
{
|
| 565 |
+
"action_type": "restart_service",
|
| 566 |
+
"service": "database",
|
| 567 |
+
"requires_security_completion": True,
|
| 568 |
+
"message": "Database restarted cleanly after worker poison traffic stopped, and api-gateway stabilized.",
|
| 569 |
+
"updates": {
|
| 570 |
+
"database": {
|
| 571 |
+
"status": "healthy",
|
| 572 |
+
"cpu_pct": 34.0,
|
| 573 |
+
"memory_pct": 38.0,
|
| 574 |
+
"error_rate_pct": 0.0,
|
| 575 |
+
"latency_ms": 24.0,
|
| 576 |
+
},
|
| 577 |
+
"api-gateway": {
|
| 578 |
+
"status": "healthy",
|
| 579 |
+
"cpu_pct": 29.0,
|
| 580 |
+
"memory_pct": 31.0,
|
| 581 |
+
"error_rate_pct": 0.0,
|
| 582 |
+
"latency_ms": 36.0,
|
| 583 |
+
}
|
| 584 |
+
},
|
| 585 |
+
},
|
| 586 |
+
],
|
| 587 |
+
"trap_actions": [
|
| 588 |
+
{
|
| 589 |
+
"action_type": "restart_service",
|
| 590 |
+
"service": "database",
|
| 591 |
+
"message": "Restarting database first is a trap; the bad worker path will re-poison it.",
|
| 592 |
+
},
|
| 593 |
+
{
|
| 594 |
+
"action_type": "restart_service",
|
| 595 |
+
"service": "api-gateway",
|
| 596 |
+
"message": "Restarting api-gateway first treats a symptom while the worker remains unsafe.",
|
| 597 |
+
},
|
| 598 |
+
{
|
| 599 |
+
"action_type": "rollback_deploy",
|
| 600 |
+
"service": "worker",
|
| 601 |
+
"message": "Rolling back before closing the command injection path is a trap; the exploit still persists.",
|
| 602 |
+
"requires_security_incomplete": True,
|
| 603 |
+
},
|
| 604 |
+
],
|
| 605 |
+
"postmortem_keywords": {
|
| 606 |
+
"root_cause": ["bad deploy", "worker", "command injection"],
|
| 607 |
+
"attack_vector": ["shell", "filename", "command injection"],
|
| 608 |
+
"remediation": ["avoid shell", "rollback", "restart database", "restart api-gateway"],
|
| 609 |
+
"prevention": ["avoid shell", "input validation", "deploy"],
|
| 610 |
+
},
|
| 611 |
+
},
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
BASELINES: dict[str, BaselineDefinition] = {
|
| 615 |
+
"database_sqli_outage": BaselineDefinition(
|
| 616 |
+
scenario_id="database_sqli_outage",
|
| 617 |
+
name="Easy baseline",
|
| 618 |
+
description="Deterministic happy path for the easy SQL injection outage.",
|
| 619 |
+
optimal_ticks=8,
|
| 620 |
+
actions=[
|
| 621 |
+
BaselineStep(
|
| 622 |
+
action=UnifiedIncidentAction(
|
| 623 |
+
action_type="query_logs",
|
| 624 |
+
service="database",
|
| 625 |
+
),
|
| 626 |
+
rationale="Find the SQL injection clue in the root-cause logs.",
|
| 627 |
+
),
|
| 628 |
+
BaselineStep(
|
| 629 |
+
action=UnifiedIncidentAction(action_type="inspect_code"),
|
| 630 |
+
rationale="Reveal the vulnerable login code.",
|
| 631 |
+
),
|
| 632 |
+
BaselineStep(
|
| 633 |
+
action=UnifiedIncidentAction(
|
| 634 |
+
action_type="classify_vulnerability",
|
| 635 |
+
vulnerability_type="sql_injection",
|
| 636 |
+
),
|
| 637 |
+
rationale="Classify the vulnerability correctly.",
|
| 638 |
+
),
|
| 639 |
+
BaselineStep(
|
| 640 |
+
action=UnifiedIncidentAction(
|
| 641 |
+
action_type="apply_patch",
|
| 642 |
+
patch_id="parameterized_query",
|
| 643 |
+
),
|
| 644 |
+
rationale="Apply the correct patch.",
|
| 645 |
+
),
|
| 646 |
+
BaselineStep(
|
| 647 |
+
action=UnifiedIncidentAction(action_type="verify_security_fix"),
|
| 648 |
+
rationale="Verify exploit blocking and functionality.",
|
| 649 |
+
),
|
| 650 |
+
BaselineStep(
|
| 651 |
+
action=UnifiedIncidentAction(action_type="submit_security_fix"),
|
| 652 |
+
rationale="Complete the security subquest.",
|
| 653 |
+
),
|
| 654 |
+
BaselineStep(
|
| 655 |
+
action=UnifiedIncidentAction(
|
| 656 |
+
action_type="restart_service",
|
| 657 |
+
service="database",
|
| 658 |
+
),
|
| 659 |
+
rationale="Recover the failed database after the exploit is closed.",
|
| 660 |
+
),
|
| 661 |
+
],
|
| 662 |
+
),
|
| 663 |
+
"cache_abuse_broken_access_control": BaselineDefinition(
|
| 664 |
+
scenario_id="cache_abuse_broken_access_control",
|
| 665 |
+
name="Medium baseline",
|
| 666 |
+
description="Deterministic happy path for the broken-access-control cascade.",
|
| 667 |
+
optimal_ticks=10,
|
| 668 |
+
actions=[
|
| 669 |
+
BaselineStep(
|
| 670 |
+
action=UnifiedIncidentAction(
|
| 671 |
+
action_type="query_metrics",
|
| 672 |
+
service="cache",
|
| 673 |
+
metric="cpu",
|
| 674 |
+
),
|
| 675 |
+
rationale="Confirm the cache rebuild storm.",
|
| 676 |
+
),
|
| 677 |
+
BaselineStep(
|
| 678 |
+
action=UnifiedIncidentAction(
|
| 679 |
+
action_type="query_dependencies",
|
| 680 |
+
service="api-gateway",
|
| 681 |
+
),
|
| 682 |
+
rationale="Expose the suspicious internal admin chain.",
|
| 683 |
+
),
|
| 684 |
+
BaselineStep(
|
| 685 |
+
action=UnifiedIncidentAction(action_type="inspect_code"),
|
| 686 |
+
rationale="Reveal the vulnerable admin endpoint.",
|
| 687 |
+
),
|
| 688 |
+
BaselineStep(
|
| 689 |
+
action=UnifiedIncidentAction(
|
| 690 |
+
action_type="classify_vulnerability",
|
| 691 |
+
vulnerability_type="broken_access_control",
|
| 692 |
+
),
|
| 693 |
+
rationale="Classify the authz flaw.",
|
| 694 |
+
),
|
| 695 |
+
BaselineStep(
|
| 696 |
+
action=UnifiedIncidentAction(
|
| 697 |
+
action_type="apply_patch",
|
| 698 |
+
patch_id="enforce_admin_role",
|
| 699 |
+
),
|
| 700 |
+
rationale="Apply the correct access-control patch.",
|
| 701 |
+
),
|
| 702 |
+
BaselineStep(
|
| 703 |
+
action=UnifiedIncidentAction(action_type="verify_security_fix"),
|
| 704 |
+
rationale="Verify the abuse path is closed.",
|
| 705 |
+
),
|
| 706 |
+
BaselineStep(
|
| 707 |
+
action=UnifiedIncidentAction(action_type="submit_security_fix"),
|
| 708 |
+
rationale="Complete the security subquest.",
|
| 709 |
+
),
|
| 710 |
+
BaselineStep(
|
| 711 |
+
action=UnifiedIncidentAction(
|
| 712 |
+
action_type="restart_service",
|
| 713 |
+
service="cache",
|
| 714 |
+
),
|
| 715 |
+
rationale="Recover cache first.",
|
| 716 |
+
),
|
| 717 |
+
BaselineStep(
|
| 718 |
+
action=UnifiedIncidentAction(
|
| 719 |
+
action_type="restart_service",
|
| 720 |
+
service="database",
|
| 721 |
+
),
|
| 722 |
+
rationale="Recover the database after cache stabilizes.",
|
| 723 |
+
),
|
| 724 |
+
],
|
| 725 |
+
),
|
| 726 |
+
"worker_bad_deploy_command_injection": BaselineDefinition(
|
| 727 |
+
scenario_id="worker_bad_deploy_command_injection",
|
| 728 |
+
name="Hard baseline",
|
| 729 |
+
description="Deterministic happy path for the bad-deploy command-injection incident.",
|
| 730 |
+
optimal_ticks=9,
|
| 731 |
+
actions=[
|
| 732 |
+
BaselineStep(
|
| 733 |
+
action=UnifiedIncidentAction(
|
| 734 |
+
action_type="query_logs",
|
| 735 |
+
service="worker",
|
| 736 |
+
),
|
| 737 |
+
rationale="Find the worker exploit clue.",
|
| 738 |
+
),
|
| 739 |
+
BaselineStep(
|
| 740 |
+
action=UnifiedIncidentAction(action_type="inspect_code"),
|
| 741 |
+
rationale="Reveal the vulnerable worker code.",
|
| 742 |
+
),
|
| 743 |
+
BaselineStep(
|
| 744 |
+
action=UnifiedIncidentAction(
|
| 745 |
+
action_type="classify_vulnerability",
|
| 746 |
+
vulnerability_type="command_injection",
|
| 747 |
+
),
|
| 748 |
+
rationale="Classify the vulnerability correctly.",
|
| 749 |
+
),
|
| 750 |
+
BaselineStep(
|
| 751 |
+
action=UnifiedIncidentAction(
|
| 752 |
+
action_type="apply_patch",
|
| 753 |
+
patch_id="avoid_shell",
|
| 754 |
+
),
|
| 755 |
+
rationale="Apply the correct worker patch.",
|
| 756 |
+
),
|
| 757 |
+
BaselineStep(
|
| 758 |
+
action=UnifiedIncidentAction(action_type="verify_security_fix"),
|
| 759 |
+
rationale="Verify exploit blocking and function retention.",
|
| 760 |
+
),
|
| 761 |
+
BaselineStep(
|
| 762 |
+
action=UnifiedIncidentAction(action_type="submit_security_fix"),
|
| 763 |
+
rationale="Complete the security subquest.",
|
| 764 |
+
),
|
| 765 |
+
BaselineStep(
|
| 766 |
+
action=UnifiedIncidentAction(
|
| 767 |
+
action_type="rollback_deploy",
|
| 768 |
+
service="worker",
|
| 769 |
+
),
|
| 770 |
+
rationale="Rollback the bad deploy after closing the exploit path.",
|
| 771 |
+
),
|
| 772 |
+
BaselineStep(
|
| 773 |
+
action=UnifiedIncidentAction(
|
| 774 |
+
action_type="restart_service",
|
| 775 |
+
service="database",
|
| 776 |
+
),
|
| 777 |
+
rationale="Recover the poisoned database state.",
|
| 778 |
+
),
|
| 779 |
+
],
|
| 780 |
+
),
|
| 781 |
+
}
|
| 782 |
+
|
| 783 |
+
_CURRENT_PROGRESS: dict = {
|
| 784 |
+
"episode_id": "bootstrap",
|
| 785 |
+
"step_count": 0,
|
| 786 |
+
"scenario_id": DEFAULT_SCENARIO_ID,
|
| 787 |
+
"difficulty": "easy",
|
| 788 |
+
"current_tick": 0,
|
| 789 |
+
"max_ticks": SCENARIOS[DEFAULT_SCENARIO_ID]["max_ticks"],
|
| 790 |
+
"workflow_stage": "diagnosis",
|
| 791 |
+
"active_alerts": [],
|
| 792 |
+
"service_health": {},
|
| 793 |
+
"discovered_evidence": [],
|
| 794 |
+
"identified_root_cause": None,
|
| 795 |
+
"security_subquest_status": "locked",
|
| 796 |
+
"security_context": {
|
| 797 |
+
"code_visible": False,
|
| 798 |
+
"selected_vulnerability": None,
|
| 799 |
+
"selected_patch": None,
|
| 800 |
+
"exploit_blocked": None,
|
| 801 |
+
"functionality_preserved": None,
|
| 802 |
+
},
|
| 803 |
+
"security_fix_submitted": False,
|
| 804 |
+
"incident_resolved": False,
|
| 805 |
+
"postmortem_submitted": False,
|
| 806 |
+
"cumulative_reward": 0.0,
|
| 807 |
+
"cumulative_score": 0.0,
|
| 808 |
+
"score_breakdown": {
|
| 809 |
+
"infrastructure_score": 0.0,
|
| 810 |
+
"security_score": 0.0,
|
| 811 |
+
"efficiency_score": 0.10,
|
| 812 |
+
"postmortem_score": 0.0,
|
| 813 |
+
},
|
| 814 |
+
"wasteful_ticks": 0,
|
| 815 |
+
"last_action_result": "",
|
| 816 |
+
}
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
def get_scenario(scenario_id: str) -> dict:
|
| 820 |
+
try:
|
| 821 |
+
return SCENARIOS[scenario_id]
|
| 822 |
+
except KeyError as exc:
|
| 823 |
+
valid = ", ".join(sorted(SCENARIOS))
|
| 824 |
+
raise ValueError(f"Unknown scenario_id {scenario_id!r}. Valid: {valid}") from exc
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
def scenario_for_difficulty(difficulty: str) -> dict:
|
| 828 |
+
for scenario in SCENARIOS.values():
|
| 829 |
+
if scenario["difficulty"] == difficulty:
|
| 830 |
+
return scenario
|
| 831 |
+
valid = ", ".join(sorted({scenario["difficulty"] for scenario in SCENARIOS.values()}))
|
| 832 |
+
raise ValueError(f"Unknown difficulty {difficulty!r}. Valid: {valid}")
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def list_scenarios(difficulty: str | None = None) -> ScenarioCatalog:
|
| 836 |
+
difficulties = sorted(
|
| 837 |
+
{scenario["difficulty"] for scenario in SCENARIOS.values()}
|
| 838 |
+
)
|
| 839 |
+
if difficulty is not None and difficulty not in difficulties:
|
| 840 |
+
valid = ", ".join(difficulties)
|
| 841 |
+
raise ValueError(f"Unknown difficulty {difficulty!r}. Valid: {valid}")
|
| 842 |
+
scenarios = [
|
| 843 |
+
ScenarioSummary(
|
| 844 |
+
id=scenario["id"],
|
| 845 |
+
difficulty=scenario["difficulty"],
|
| 846 |
+
name=scenario["name"],
|
| 847 |
+
description=scenario["description"],
|
| 848 |
+
root_cause=scenario["root_cause"],
|
| 849 |
+
optimal_ticks=scenario["optimal_ticks"],
|
| 850 |
+
)
|
| 851 |
+
for scenario in SCENARIOS.values()
|
| 852 |
+
if difficulty is None or scenario["difficulty"] == difficulty
|
| 853 |
+
]
|
| 854 |
+
return ScenarioCatalog(
|
| 855 |
+
default_scenario_id=DEFAULT_SCENARIO_ID,
|
| 856 |
+
available_difficulties=difficulties,
|
| 857 |
+
filtered_difficulty=difficulty,
|
| 858 |
+
scenarios=scenarios,
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
def list_baselines(scenario_id: str | None = None) -> BaselineCatalog:
|
| 863 |
+
if scenario_id is None:
|
| 864 |
+
return BaselineCatalog(baselines=list(BASELINES.values()))
|
| 865 |
+
get_scenario(scenario_id)
|
| 866 |
+
return BaselineCatalog(baselines=[BASELINES[scenario_id]])
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
def set_runtime_progress(state: dict) -> None:
|
| 870 |
+
global _CURRENT_PROGRESS
|
| 871 |
+
_CURRENT_PROGRESS = deepcopy(state)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def current_runtime_progress() -> dict:
|
| 875 |
+
return deepcopy(_CURRENT_PROGRESS)
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
def grade_episode(state: dict):
|
| 879 |
+
from .grader import UnifiedIncidentGrader
|
| 880 |
+
|
| 881 |
+
scenario_id = state.get("scenario_id", DEFAULT_SC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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Core environment for the final deterministic preset pack."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import uuid
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from openenv.core.env_server import Environment
|
| 10 |
+
from openenv.core.env_server.types import EnvironmentMetadata
|
| 11 |
+
|
| 12 |
+
from ..models import (
|
| 13 |
+
ActionType,
|
| 14 |
+
Alert,
|
| 15 |
+
SecurityContext,
|
| 16 |
+
ServiceHealth,
|
| 17 |
+
UnifiedIncidentAction,
|
| 18 |
+
UnifiedIncidentObservation,
|
| 19 |
+
UnifiedIncidentState,
|
| 20 |
+
)
|
| 21 |
+
from .challenge import DEFAULT_SCENARIO_ID, SCENARIOS, get_scenario, scenario_for_difficulty, set_runtime_progress
|
| 22 |
+
from .grader import UnifiedIncidentGrader
|
| 23 |
+
|
| 24 |
+
SERVICE_ORDER = ("api-gateway", "cache", "database", "worker")
|
| 25 |
+
STAGE_ALLOWED_ACTIONS: dict[str, list[ActionType]] = {
|
| 26 |
+
"diagnosis": ["query_logs", "query_metrics", "query_dependencies"],
|
| 27 |
+
"root_cause_analysis": ["query_logs", "query_metrics", "query_dependencies"],
|
| 28 |
+
"security_subquest": [
|
| 29 |
+
"inspect_code",
|
| 30 |
+
"classify_vulnerability",
|
| 31 |
+
"apply_patch",
|
| 32 |
+
"verify_security_fix",
|
| 33 |
+
"submit_security_fix",
|
| 34 |
+
],
|
| 35 |
+
"remediation": ["restart_service", "rollback_deploy"],
|
| 36 |
+
"verification": ["submit_security_fix", "restart_service", "rollback_deploy"],
|
| 37 |
+
"postmortem": ["submit_postmortem"],
|
| 38 |
+
"done": [],
|
| 39 |
+
}
|
| 40 |
+
REQUIRED_FIELDS_BY_ACTION: dict[str, list[str]] = {
|
| 41 |
+
"query_logs": ["service"],
|
| 42 |
+
"query_metrics": ["service", "metric"],
|
| 43 |
+
"query_dependencies": ["service"],
|
| 44 |
+
"restart_service": ["service"],
|
| 45 |
+
"rollback_deploy": ["service"],
|
| 46 |
+
"inspect_code": [],
|
| 47 |
+
"classify_vulnerability": ["vulnerability_type"],
|
| 48 |
+
"apply_patch": ["patch_id"],
|
| 49 |
+
"verify_security_fix": [],
|
| 50 |
+
"submit_security_fix": [],
|
| 51 |
+
"submit_postmortem": ["postmortem"],
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class UnifiedIncidentEnvironment(
|
| 56 |
+
Environment[UnifiedIncidentAction, UnifiedIncidentObservation, UnifiedIncidentState]
|
| 57 |
+
):
|
| 58 |
+
"""Deterministic unified incident-response environment."""
|
| 59 |
+
|
| 60 |
+
SUPPORTS_CONCURRENT_SESSIONS = False
|
| 61 |
+
|
| 62 |
+
def __init__(self) -> None:
|
| 63 |
+
super().__init__()
|
| 64 |
+
self._grader = UnifiedIncidentGrader()
|
| 65 |
+
self._episode = self._make_episode(get_scenario(DEFAULT_SCENARIO_ID))
|
| 66 |
+
set_runtime_progress(self._state_dict())
|
| 67 |
+
|
| 68 |
+
def get_metadata(self) -> EnvironmentMetadata:
|
| 69 |
+
return EnvironmentMetadata(
|
| 70 |
+
name="unified_incident_env",
|
| 71 |
+
description=(
|
| 72 |
+
"A deterministic unified incident benchmark with one SRE flow, "
|
| 73 |
+
"one security subquest, and one final score."
|
| 74 |
+
),
|
| 75 |
+
version="1.0.0",
|
| 76 |
+
author="Daksh Verma",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
def reset(
|
| 80 |
+
self,
|
| 81 |
+
seed: int | None = None,
|
| 82 |
+
episode_id: str | None = None,
|
| 83 |
+
**kwargs: Any,
|
| 84 |
+
) -> UnifiedIncidentObservation:
|
| 85 |
+
del seed
|
| 86 |
+
scenario_id = kwargs.get("scenario_id")
|
| 87 |
+
difficulty = kwargs.get("difficulty")
|
| 88 |
+
if scenario_id:
|
| 89 |
+
scenario = get_scenario(scenario_id)
|
| 90 |
+
elif difficulty:
|
| 91 |
+
scenario = scenario_for_difficulty(difficulty)
|
| 92 |
+
else:
|
| 93 |
+
scenario = get_scenario(DEFAULT_SCENARIO_ID)
|
| 94 |
+
self._episode = self._make_episode(scenario, episode_id=episode_id)
|
| 95 |
+
set_runtime_progress(self._state_dict())
|
| 96 |
+
return self._build_observation(
|
| 97 |
+
last_action_result="Episode reset.",
|
| 98 |
+
tool_output=None,
|
| 99 |
+
reward=0.0,
|
| 100 |
+
done=False,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def step(
|
| 104 |
+
self,
|
| 105 |
+
action: UnifiedIncidentAction | dict[str, Any],
|
| 106 |
+
timeout_s: float | None = None,
|
| 107 |
+
**kwargs: Any,
|
| 108 |
+
) -> UnifiedIncidentObservation:
|
| 109 |
+
del timeout_s, kwargs
|
| 110 |
+
if isinstance(action, dict):
|
| 111 |
+
action = UnifiedIncidentAction(**action)
|
| 112 |
+
|
| 113 |
+
if self._episode["done"]:
|
| 114 |
+
return self._build_observation(
|
| 115 |
+
last_action_result="Episode complete. Reset to start another run.",
|
| 116 |
+
tool_output=None,
|
| 117 |
+
reward=0.0,
|
| 118 |
+
done=True,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
self._episode["tick"] += 1
|
| 122 |
+
self._episode["step_count"] += 1
|
| 123 |
+
self._clear_teaching_feedback()
|
| 124 |
+
|
| 125 |
+
reward = 0.0
|
| 126 |
+
tool_output: str | None = None
|
| 127 |
+
progressed = False
|
| 128 |
+
|
| 129 |
+
if action.action_type in {"query_logs", "query_metrics", "query_dependencies"}:
|
| 130 |
+
reward, last_action_result, tool_output, progressed = self._handle_investigation(action)
|
| 131 |
+
elif action.action_type in {"inspect_code", "classify_vulnerability", "apply_patch", "verify_security_fix", "submit_security_fix"}:
|
| 132 |
+
reward, last_action_result, tool_output, progressed = self._handle_security(action)
|
| 133 |
+
elif action.action_type in {"restart_service", "rollback_deploy"}:
|
| 134 |
+
reward, last_action_result, progressed = self._handle_infrastructure(action)
|
| 135 |
+
elif action.action_type == "submit_postmortem":
|
| 136 |
+
reward, last_action_result, progressed = self._handle_postmortem(action)
|
| 137 |
+
else:
|
| 138 |
+
last_action_result = f"Unsupported action {action.action_type!r}."
|
| 139 |
+
self._set_failure(
|
| 140 |
+
failure_type="unsupported_action",
|
| 141 |
+
why_failed="The action is not part of the public environment schema.",
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
if not progressed:
|
| 145 |
+
self._episode["wasteful_ticks"] += 1
|
| 146 |
+
self._update_loop_feedback(action, progressed)
|
| 147 |
+
|
| 148 |
+
self._update_workflow_stage()
|
| 149 |
+
self._episode["score_breakdown"] = self._grader.compute_breakdown(
|
| 150 |
+
self._state_dict(),
|
| 151 |
+
self._episode["scenario"],
|
| 152 |
+
)
|
| 153 |
+
self._episode["final_score"] = self._episode["score_breakdown"]["final_score"]
|
| 154 |
+
self._episode["cumulative_reward"] = round(
|
| 155 |
+
self._episode["cumulative_reward"] + reward,
|
| 156 |
+
4,
|
| 157 |
+
)
|
| 158 |
+
self._episode["last_action_result"] = last_action_result
|
| 159 |
+
|
| 160 |
+
done = False
|
| 161 |
+
if self._episode["postmortem_submitted"]:
|
| 162 |
+
self._episode["workflow_stage"] = "done"
|
| 163 |
+
self._episode["done"] = True
|
| 164 |
+
done = True
|
| 165 |
+
elif self._episode["tick"] >= self._episode["max_ticks"]:
|
| 166 |
+
self._episode["done"] = True
|
| 167 |
+
done = True
|
| 168 |
+
last_action_result = f"{last_action_result} Tick budget exhausted.".strip()
|
| 169 |
+
self._episode["last_action_result"] = last_action_result
|
| 170 |
+
|
| 171 |
+
set_runtime_progress(self._state_dict())
|
| 172 |
+
return self._build_observation(
|
| 173 |
+
last_action_result=last_action_result,
|
| 174 |
+
tool_output=tool_output,
|
| 175 |
+
reward=reward,
|
| 176 |
+
done=done,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
@property
|
| 180 |
+
def state(self) -> UnifiedIncidentState:
|
| 181 |
+
return UnifiedIncidentState(**self._state_dict())
|
| 182 |
+
|
| 183 |
+
def _make_episode(self, scenario: dict, episode_id: str | None = None) -> dict[str, Any]:
|
| 184 |
+
services = {
|
| 185 |
+
name: ServiceHealth(name=name, **payload)
|
| 186 |
+
for name, payload in scenario["initial_services"].items()
|
| 187 |
+
}
|
| 188 |
+
alerts = [Alert(**payload) for payload in scenario["initial_alerts"]]
|
| 189 |
+
return {
|
| 190 |
+
"episode_id": episode_id or str(uuid.uuid4()),
|
| 191 |
+
"scenario": scenario,
|
| 192 |
+
"tick": 0,
|
| 193 |
+
"step_count": 0,
|
| 194 |
+
"max_ticks": scenario["max_ticks"],
|
| 195 |
+
"difficulty": scenario["difficulty"],
|
| 196 |
+
"services": services,
|
| 197 |
+
"alerts": alerts,
|
| 198 |
+
"discovered_evidence": [],
|
| 199 |
+
"matched_evidence_ids": set(),
|
| 200 |
+
"relevant_investigations": 0,
|
| 201 |
+
"identified_root_cause": None,
|
| 202 |
+
"failure_type": None,
|
| 203 |
+
"why_failed": None,
|
| 204 |
+
"common_trap": scenario.get("common_trap"),
|
| 205 |
+
"loop_warning": None,
|
| 206 |
+
"blocked_until_security_complete": False,
|
| 207 |
+
"security_unlock_reason": None,
|
| 208 |
+
"best_recovery_action_family": None,
|
| 209 |
+
"last_action_key": None,
|
| 210 |
+
"repeated_no_progress_count": 0,
|
| 211 |
+
"security_subquest_status": "locked",
|
| 212 |
+
"security_context": SecurityContext(
|
| 213 |
+
code_visible=False,
|
| 214 |
+
selected_vulnerability=None,
|
| 215 |
+
selected_patch=None,
|
| 216 |
+
exploit_blocked=None,
|
| 217 |
+
functionality_preserved=None,
|
| 218 |
+
),
|
| 219 |
+
"security_fix_submitted": False,
|
| 220 |
+
"incident_resolved": False,
|
| 221 |
+
"postmortem_submitted": False,
|
| 222 |
+
"postmortem_score": 0.0,
|
| 223 |
+
"infra_progress": 0,
|
| 224 |
+
"correct_infra_steps": 0,
|
| 225 |
+
"infra_restored_in_correct_order": False,
|
| 226 |
+
"workflow_stage": "diagnosis",
|
| 227 |
+
"wasteful_ticks": 0,
|
| 228 |
+
"cumulative_reward": 0.0,
|
| 229 |
+
"final_score": 0.0,
|
| 230 |
+
"score_breakdown": {
|
| 231 |
+
"infrastructure_score": 0.0,
|
| 232 |
+
"security_score": 0.0,
|
| 233 |
+
"efficiency_score": 0.10,
|
| 234 |
+
"postmortem_score": 0.0,
|
| 235 |
+
"final_score": 0.10,
|
| 236 |
+
},
|
| 237 |
+
"last_action_result": "",
|
| 238 |
+
"done": False,
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
def _clear_teaching_feedback(self) -> None:
|
| 242 |
+
self._episode["failure_type"] = None
|
| 243 |
+
self._episode["why_failed"] = None
|
| 244 |
+
self._episode["loop_warning"] = None
|
| 245 |
+
self._episode["blocked_until_security_complete"] = False
|
| 246 |
+
self._episode["best_recovery_action_family"] = None
|
| 247 |
+
|
| 248 |
+
def _set_failure(
|
| 249 |
+
self,
|
| 250 |
+
*,
|
| 251 |
+
failure_type: str,
|
| 252 |
+
why_failed: str,
|
| 253 |
+
blocked_until_security_complete: bool = False,
|
| 254 |
+
best_recovery_action_family: str | None = None,
|
| 255 |
+
) -> None:
|
| 256 |
+
self._episode["failure_type"] = failure_type
|
| 257 |
+
self._episode["why_failed"] = why_failed
|
| 258 |
+
self._episode["blocked_until_security_complete"] = (
|
| 259 |
+
blocked_until_security_complete
|
| 260 |
+
)
|
| 261 |
+
self._episode["best_recovery_action_family"] = best_recovery_action_family
|
| 262 |
+
|
| 263 |
+
def _handle_investigation(
|
| 264 |
+
self, action: UnifiedIncidentAction
|
| 265 |
+
) -> tuple[float, str, str | None, bool]:
|
| 266 |
+
scenario = self._episode["scenario"]
|
| 267 |
+
service = action.service
|
| 268 |
+
assert service is not None
|
| 269 |
+
|
| 270 |
+
if action.action_type == "query_logs":
|
| 271 |
+
output = scenario["logs"].get(service, f"No logs available for {service}.")
|
| 272 |
+
elif action.action_type == "query_metrics":
|
| 273 |
+
output = scenario["metrics"].get(service, {}).get(
|
| 274 |
+
action.metric or "",
|
| 275 |
+
f"No metric {action.metric!r} available for {service}.",
|
| 276 |
+
)
|
| 277 |
+
else:
|
| 278 |
+
output = scenario["dependencies"].get(
|
| 279 |
+
service,
|
| 280 |
+
f"No dependency data available for {service}.",
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
reward = 0.0
|
| 284 |
+
progressed = False
|
| 285 |
+
for rule in scenario["evidence_rules"]:
|
| 286 |
+
if rule["action_type"] != action.action_type:
|
| 287 |
+
continue
|
| 288 |
+
if rule["service"] != service:
|
| 289 |
+
continue
|
| 290 |
+
if action.action_type == "query_metrics" and rule.get("metric") != action.metric:
|
| 291 |
+
continue
|
| 292 |
+
if rule["id"] in self._episode["matched_evidence_ids"]:
|
| 293 |
+
break
|
| 294 |
+
self._episode["matched_evidence_ids"].add(rule["id"])
|
| 295 |
+
self._episode["discovered_evidence"].append(rule["detail"])
|
| 296 |
+
self._episode["relevant_investigations"] += 1
|
| 297 |
+
reward += 0.05
|
| 298 |
+
progressed = True
|
| 299 |
+
if rule.get("identifies_root_cause"):
|
| 300 |
+
self._episode["identified_root_cause"] = scenario["root_cause"]
|
| 301 |
+
if rule.get("unlocks_security"):
|
| 302 |
+
self._episode["security_subquest_status"] = "active"
|
| 303 |
+
self._episode["security_unlock_reason"] = rule.get(
|
| 304 |
+
"unlock_reason",
|
| 305 |
+
"Relevant incident evidence unlocked the security subquest.",
|
| 306 |
+
)
|
| 307 |
+
break
|
| 308 |
+
|
| 309 |
+
if (
|
| 310 |
+
self._episode["security_subquest_status"] == "locked"
|
| 311 |
+
and len(self._episode["matched_evidence_ids"]) >= scenario["unlock_threshold"]
|
| 312 |
+
):
|
| 313 |
+
self._episode["security_subquest_status"] = "active"
|
| 314 |
+
self._episode["security_unlock_reason"] = (
|
| 315 |
+
"Enough incident evidence was collected to justify security investigation."
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
return (
|
| 319 |
+
round(reward, 4),
|
| 320 |
+
f"{action.action_type} returned data for {service}.",
|
| 321 |
+
output,
|
| 322 |
+
progressed,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
def _handle_security(
|
| 326 |
+
self, action: UnifiedIncidentAction
|
| 327 |
+
) -> tuple[float, str, str | None, bool]:
|
| 328 |
+
security = self._episode["security_context"]
|
| 329 |
+
scenario_security = self._episode["scenario"]["security"]
|
| 330 |
+
status = self._episode["security_subquest_status"]
|
| 331 |
+
|
| 332 |
+
if status == "locked":
|
| 333 |
+
self._set_failure(
|
| 334 |
+
failure_type="security_locked",
|
| 335 |
+
why_failed="Security actions are ineffective until the subquest is unlocked by relevant incident evidence.",
|
| 336 |
+
best_recovery_action_family="query_logs",
|
| 337 |
+
)
|
| 338 |
+
return (
|
| 339 |
+
0.0,
|
| 340 |
+
"Security subquest is locked. Investigate the incident first.",
|
| 341 |
+
None,
|
| 342 |
+
False,
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
if action.action_type == "inspect_code":
|
| 346 |
+
if security.code_visible:
|
| 347 |
+
self._set_failure(
|
| 348 |
+
failure_type="code_already_visible",
|
| 349 |
+
why_failed="Inspecting code again does not reveal new information.",
|
| 350 |
+
best_recovery_action_family="classify_vulnerability",
|
| 351 |
+
)
|
| 352 |
+
return 0.0, "Code is already visible.", None, False
|
| 353 |
+
security.code_visible = True
|
| 354 |
+
return (
|
| 355 |
+
0.0,
|
| 356 |
+
"Inspected the vulnerable code path.",
|
| 357 |
+
(
|
| 358 |
+
f"{scenario_security['code_context']}\n"
|
| 359 |
+
f"Patch options: {', '.join(option['id'] for option in scenario_security['patch_options'])}"
|
| 360 |
+
),
|
| 361 |
+
True,
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
if action.action_type == "classify_vulnerability":
|
| 365 |
+
if not security.code_visible:
|
| 366 |
+
self._set_failure(
|
| 367 |
+
failure_type="inspect_required",
|
| 368 |
+
why_failed="Classification is unreliable until the vulnerable code is visible.",
|
| 369 |
+
best_recovery_action_family="inspect_code",
|
| 370 |
+
)
|
| 371 |
+
return 0.0, "Inspect the code before classifying.", None, False
|
| 372 |
+
security.selected_vulnerability = action.vulnerability_type
|
| 373 |
+
if action.vulnerability_type == scenario_security["correct_vulnerability"]:
|
| 374 |
+
return 0.10, "Correct vulnerability classification.", None, True
|
| 375 |
+
self._set_failure(
|
| 376 |
+
failure_type="wrong_vulnerability",
|
| 377 |
+
why_failed="The selected vulnerability does not match the exploit described by the current evidence.",
|
| 378 |
+
best_recovery_action_family="classify_vulnerability",
|
| 379 |
+
)
|
| 380 |
+
return -0.08, "Wrong vulnerability classification.", None, False
|
| 381 |
+
|
| 382 |
+
if action.action_type == "apply_patch":
|
| 383 |
+
if not security.code_visible:
|
| 384 |
+
self._set_failure(
|
| 385 |
+
failure_type="inspect_required",
|
| 386 |
+
why_failed="Patching before inspecting code is unlikely to address the root cause safely.",
|
| 387 |
+
best_recovery_action_family="inspect_code",
|
| 388 |
+
)
|
| 389 |
+
return 0.0, "Inspect the code before patching.", None, False
|
| 390 |
+
security.selected_patch = action.patch_id
|
| 391 |
+
security.exploit_blocked = None
|
| 392 |
+
security.functionality_preserved = None
|
| 393 |
+
if action.patch_id == scenario_security["correct_patch"]:
|
| 394 |
+
return 0.10, "Applied the correct patch.", None, True
|
| 395 |
+
self._set_failure(
|
| 396 |
+
failure_type="wrong_patch",
|
| 397 |
+
why_failed="The selected patch does not safely close the active exploit path.",
|
| 398 |
+
best_recovery_action_family="apply_patch",
|
| 399 |
+
)
|
| 400 |
+
return -0.10, f"Wrong patch applied: {action.patch_id}.", None, False
|
| 401 |
+
|
| 402 |
+
if action.action_type == "verify_security_fix":
|
| 403 |
+
if security.selected_patch is None:
|
| 404 |
+
self._set_failure(
|
| 405 |
+
failure_type="verify_too_early",
|
| 406 |
+
why_failed="Verification needs a selected patch first.",
|
| 407 |
+
best_recovery_action_family="apply_patch",
|
| 408 |
+
)
|
| 409 |
+
return -0.05, "Verify called too early; no patch has been applied.", None, False
|
| 410 |
+
outcome = scenario_security["verify_outcomes"].get(
|
| 411 |
+
security.selected_patch,
|
| 412 |
+
{
|
| 413 |
+
"exploit_blocked": False,
|
| 414 |
+
"functionality_preserved": False,
|
| 415 |
+
"message": f"Verification failed: {security.selected_patch} is an invalid patch for this scenario.",
|
| 416 |
+
},
|
| 417 |
+
)
|
| 418 |
+
security.exploit_blocked = outcome["exploit_blocked"]
|
| 419 |
+
security.functionality_preserved = outcome["functionality_preserved"]
|
| 420 |
+
if outcome["exploit_blocked"] and outcome["functionality_preserved"]:
|
| 421 |
+
return 0.10, outcome["message"], outcome["message"], True
|
| 422 |
+
self._set_failure(
|
| 423 |
+
failure_type="verification_failed",
|
| 424 |
+
why_failed=outcome["message"],
|
| 425 |
+
best_recovery_action_family="apply_patch",
|
| 426 |
+
)
|
| 427 |
+
return 0.0, outcome["message"], outcome["message"], False
|
| 428 |
+
|
| 429 |
+
if action.action_type == "submit_security_fix":
|
| 430 |
+
if not (
|
| 431 |
+
security.selected_vulnerability == scenario_security["correct_vulnerability"]
|
| 432 |
+
and security.selected_patch == scenario_security["correct_patch"]
|
| 433 |
+
and security.exploit_blocked is True
|
| 434 |
+
and security.functionality_preserved is True
|
| 435 |
+
):
|
| 436 |
+
self._set_failure(
|
| 437 |
+
failure_type="submit_too_early",
|
| 438 |
+
why_failed="Security submission only works after correct classification, correct patching, and successful verification.",
|
| 439 |
+
best_recovery_action_family="verify_security_fix",
|
| 440 |
+
)
|
| 441 |
+
return -0.05, "Submit security fix called before a successful verify.", None, False
|
| 442 |
+
self._episode["security_fix_submitted"] = True
|
| 443 |
+
self._episode["security_subquest_status"] = "completed"
|
| 444 |
+
return 0.05, "Security subquest completed.", None, True
|
| 445 |
+
|
| 446 |
+
return 0.0, "Unsupported security action.", None, False
|
| 447 |
+
|
| 448 |
+
def _handle_infrastructure(
|
| 449 |
+
self, action: UnifiedIncidentAction
|
| 450 |
+
) -> tuple[float, str, bool]:
|
| 451 |
+
scenario = self._episode["scenario"]
|
| 452 |
+
service = action.service
|
| 453 |
+
assert service is not None
|
| 454 |
+
|
| 455 |
+
if self._episode["infra_progress"] >= len(scenario["recovery_sequence"]):
|
| 456 |
+
self._set_failure(
|
| 457 |
+
failure_type="infra_already_complete",
|
| 458 |
+
why_failed="No further infrastructure recovery actions are required right now.",
|
| 459 |
+
best_recovery_action_family="submit_postmortem",
|
| 460 |
+
)
|
| 461 |
+
return -0.08, "No infrastructure recovery steps remain.", False
|
| 462 |
+
|
| 463 |
+
expected = scenario["recovery_sequence"][self._episode["infra_progress"]]
|
| 464 |
+
matches_expected = (
|
| 465 |
+
action.action_type == expected["action_type"] and service == expected["service"]
|
| 466 |
+
)
|
| 467 |
+
if matches_expected and expected.get("requires_security_completion") and self._episode["security_subquest_status"] != "completed":
|
| 468 |
+
trap_message = self._trap_message(scenario, action)
|
| 469 |
+
if trap_message is not None:
|
| 470 |
+
self._set_failure(
|
| 471 |
+
failure_type="infra_before_security",
|
| 472 |
+
why_failed=trap_message,
|
| 473 |
+
blocked_until_security_complete=True,
|
| 474 |
+
best_recovery_action_family="submit_security_fix",
|
| 475 |
+
)
|
| 476 |
+
return -0.10, trap_message, False
|
| 477 |
+
self._set_failure(
|
| 478 |
+
failure_type="infra_before_security",
|
| 479 |
+
why_failed="This infrastructure step is blocked until the security subquest is completed.",
|
| 480 |
+
blocked_until_security_complete=True,
|
| 481 |
+
best_recovery_action_family="submit_security_fix",
|
| 482 |
+
)
|
| 483 |
+
return -0.08, "Infrastructure step attempted before security completion.", False
|
| 484 |
+
|
| 485 |
+
if not matches_expected:
|
| 486 |
+
trap_message = self._trap_message(scenario, action)
|
| 487 |
+
if trap_message is not None:
|
| 488 |
+
self._set_failure(
|
| 489 |
+
failure_type="trap_action",
|
| 490 |
+
why_failed=trap_message,
|
| 491 |
+
best_recovery_action_family=expected["action_type"],
|
| 492 |
+
)
|
| 493 |
+
return -0.10, trap_message, False
|
| 494 |
+
self._set_failure(
|
| 495 |
+
failure_type="wrong_infra_action",
|
| 496 |
+
why_failed="This restart or rollback does not address the current bottleneck.",
|
| 497 |
+
best_recovery_action_family=expected["action_type"],
|
| 498 |
+
)
|
| 499 |
+
return -0.08, "Wrong restart or rollback for the current recovery step.", False
|
| 500 |
+
|
| 501 |
+
for service_name, payload in expected["updates"].items():
|
| 502 |
+
self._episode["services"][service_name] = ServiceHealth(
|
| 503 |
+
name=service_name,
|
| 504 |
+
**payload,
|
| 505 |
+
)
|
| 506 |
+
self._refresh_alerts()
|
| 507 |
+
self._episode["infra_progress"] += 1
|
| 508 |
+
self._episode["correct_infra_steps"] += 1
|
| 509 |
+
|
| 510 |
+
reward = 0.10
|
| 511 |
+
if self._episode["infra_progress"] == len(scenario["recovery_sequence"]):
|
| 512 |
+
self._episode["infra_restored_in_correct_order"] = True
|
| 513 |
+
if self._all_required_services_healthy():
|
| 514 |
+
self._episode["incident_resolved"] = True
|
| 515 |
+
reward += 0.30
|
| 516 |
+
return reward, expected["message"], True
|
| 517 |
+
|
| 518 |
+
def _trap_message(
|
| 519 |
+
self,
|
| 520 |
+
scenario: dict[str, Any],
|
| 521 |
+
action: UnifiedIncidentAction,
|
| 522 |
+
) -> str | None:
|
| 523 |
+
for trap in scenario["trap_actions"]:
|
| 524 |
+
if trap["action_type"] != action.action_type or trap["service"] != action.service:
|
| 525 |
+
continue
|
| 526 |
+
if trap.get("requires_security_incomplete") and self._episode["security_subquest_status"] == "completed":
|
| 527 |
+
continue
|
| 528 |
+
return trap["message"]
|
| 529 |
+
return None
|
| 530 |
+
|
| 531 |
+
def _handle_postmortem(
|
| 532 |
+
self, action: UnifiedIncidentAction
|
| 533 |
+
) -> tuple[float, str, bool]:
|
| 534 |
+
if not self._episode["incident_resolved"]:
|
| 535 |
+
self._set_failure(
|
| 536 |
+
failure_type="postmortem_too_early",
|
| 537 |
+
why_failed="Postmortem submission is only valid after services are healthy and recovery is complete.",
|
| 538 |
+
best_recovery_action_family="restart_service",
|
| 539 |
+
)
|
| 540 |
+
return -0.10, "Submit postmortem only after full recovery.", False
|
| 541 |
+
if self._episode["postmortem_submitted"]:
|
| 542 |
+
self._set_failure(
|
| 543 |
+
failure_type="postmortem_already_submitted",
|
| 544 |
+
why_failed="The postmortem is already complete for this episode.",
|
| 545 |
+
)
|
| 546 |
+
return 0.0, "Postmortem already submitted.", False
|
| 547 |
+
assert action.postmortem is not None
|
| 548 |
+
postmortem_score = self._grader.postmortem_score(
|
| 549 |
+
action.postmortem,
|
| 550 |
+
self._episode["scenario"],
|
| 551 |
+
)
|
| 552 |
+
self._episode["postmortem_submitted"] = True
|
| 553 |
+
self._episode["postmortem_score"] = postmortem_score
|
| 554 |
+
return postmortem_score, "Postmortem submitted.", True
|
| 555 |
+
|
| 556 |
+
def _all_required_services_healthy(self) -> bool:
|
| 557 |
+
return all(
|
| 558 |
+
self._episode["services"][name].status == "healthy"
|
| 559 |
+
for name in SERVICE_ORDER
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
def _refresh_alerts(self) -> None:
|
| 563 |
+
self._episode["alerts"] = [
|
| 564 |
+
alert
|
| 565 |
+
for alert in self._episode["alerts"]
|
| 566 |
+
if self._episode["services"][alert.service].status != "healthy"
|
| 567 |
+
]
|
| 568 |
+
|
| 569 |
+
def _update_loop_feedback(
|
| 570 |
+
self,
|
| 571 |
+
action: UnifiedIncidentAction,
|
| 572 |
+
progressed: bool,
|
| 573 |
+
) -> None:
|
| 574 |
+
action_key = repr(action.model_dump(exclude_none=True))
|
| 575 |
+
if progressed:
|
| 576 |
+
self._episode["last_action_key"] = action_key
|
| 577 |
+
self._episode["repeated_no_progress_count"] = 0
|
| 578 |
+
return
|
| 579 |
+
|
| 580 |
+
if self._episode["last_action_key"] == action_key:
|
| 581 |
+
self._episode["repeated_no_progress_count"] += 1
|
| 582 |
+
else:
|
| 583 |
+
self._episode["repeated_no_progress_count"] = 1
|
| 584 |
+
self._episode["last_action_key"] = action_key
|
| 585 |
+
|
| 586 |
+
if self._episode["repeated_no_progress_count"] >= 2:
|
| 587 |
+
repeat_count = self._episode["repeated_no_progress_count"]
|
| 588 |
+
self._episode["loop_warning"] = (
|
| 589 |
+
f"The same no-progress action has repeated {repeat_count} times."
|
| 590 |
+
" Stop repeating it; choose a different allowed action or move to the next workflow stage."
|
| 591 |
+
)
|
| 592 |
+
if self._episode["failure_type"] is None:
|
| 593 |
+
self._set_failure(
|
| 594 |
+
failure_type="repeated_no_progress_action",
|
| 595 |
+
why_failed="The system is not progressing because the same ineffective action keeps repeating.",
|
| 596 |
+
)
|
| 597 |
+
if repeat_count >= 3:
|
| 598 |
+
self._episode["cumulative_reward"] = round(
|
| 599 |
+
self._episode["cumulative_reward"] - 0.02,
|
| 600 |
+
4,
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
def _update_workflow_stage(self) -> None:
|
| 604 |
+
if self._episode["postmortem_submitted"]:
|
| 605 |
+
self._episode["workflow_stage"] = "done"
|
| 606 |
+
return
|
| 607 |
+
if self._episode["incident_resolved"]:
|
| 608 |
+
self._episode["workflow_stage"] = "postmortem"
|
| 609 |
+
return
|
| 610 |
+
if self._episode["security_subquest_status"] == "completed":
|
| 611 |
+
self._episode["workflow_stage"] = "remediation"
|
| 612 |
+
return
|
| 613 |
+
security = self._episode["security_context"]
|
| 614 |
+
if security.exploit_blocked is True and security.functionality_preserved is True:
|
| 615 |
+
self._episode["workflow_stage"] = "verification"
|
| 616 |
+
return
|
| 617 |
+
if self._episode["security_subquest_status"] == "active":
|
| 618 |
+
self._episode["workflow_stage"] = "security_subquest"
|
| 619 |
+
return
|
| 620 |
+
if self._episode["identified_root_cause"]:
|
| 621 |
+
self._episode["workflow_stage"] = "root_cause_analysis"
|
| 622 |
+
return
|
| 623 |
+
self._episode["workflow_stage"] = "diagnosis"
|
| 624 |
+
|
| 625 |
+
def _allowed_actions(self) -> list[str]:
|
| 626 |
+
return list(STAGE_ALLOWED_ACTIONS.get(self._episode["workflow_stage"], []))
|
| 627 |
+
|
| 628 |
+
def _required_fields_by_action(self) -> dict[str, list[str]]:
|
| 629 |
+
return {
|
| 630 |
+
action: REQUIRED_FIELDS_BY_ACTION[action]
|
| 631 |
+
for action in self._allowed_actions()
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
def _valid_action_example(self) -> dict[str, Any]:
|
| 635 |
+
stage = self._episode["workflow_stage"]
|
| 636 |
+
security = self._episode["security_context"]
|
| 637 |
+
scenario = self._episode["scenario"]
|
| 638 |
+
if stage in {"diagnosis", "root_cause_analysis"}:
|
| 639 |
+
if scenario["id"] == "database_sqli_outage":
|
| 640 |
+
return {"action_type": "query_logs", "service": "database"}
|
| 641 |
+
if scenario["id"] == "cache_abuse_broken_access_control":
|
| 642 |
+
return {
|
| 643 |
+
"action_type": "query_metrics",
|
| 644 |
+
"service": "cache",
|
| 645 |
+
"metric": "cpu",
|
| 646 |
+
}
|
| 647 |
+
return {"action_type": "query_logs", "service": "worker"}
|
| 648 |
+
if stage == "security_subquest":
|
| 649 |
+
if not security.code_visible:
|
| 650 |
+
return {"action_type": "inspect_code"}
|
| 651 |
+
if security.selected_vulnerability is None:
|
| 652 |
+
return {
|
| 653 |
+
"action_type": "classify_vulnerability",
|
| 654 |
+
"vulnerability_type": scenario["security"]["correct_vulnerability"],
|
| 655 |
+
}
|
| 656 |
+
if security.selected_patch is None:
|
| 657 |
+
return {
|
| 658 |
+
"action_type": "apply_patch",
|
| 659 |
+
"patch_id": scenario["security"]["correct_patch"],
|
| 660 |
+
}
|
| 661 |
+
if security.exploit_blocked is not True:
|
| 662 |
+
return {"action_type": "verify_security_fix"}
|
| 663 |
+
return {"action_type": "submit_security_fix"}
|
| 664 |
+
if stage in {"remediation", "verification"}:
|
| 665 |
+
if (
|
| 666 |
+
stage == "verification"
|
| 667 |
+
and not self._episode["security_fix_submitted"]
|
| 668 |
+
and security.exploit_blocked is True
|
| 669 |
+
and security.functionality_preserved is True
|
| 670 |
+
):
|
| 671 |
+
return {"action_type": "submit_security_fix"}
|
| 672 |
+
next_index = min(
|
| 673 |
+
self._episode["infra_progress"],
|
| 674 |
+
len(scenario["recovery_sequence"]) - 1,
|
| 675 |
+
)
|
| 676 |
+
expected = scenario["recovery_sequence"][next_index]
|
| 677 |
+
return {
|
| 678 |
+
"action_type": expected["action_type"],
|
| 679 |
+
"service": expected["service"],
|
| 680 |
+
}
|
| 681 |
+
return {
|
| 682 |
+
"action_type": "submit_postmortem",
|
| 683 |
+
"postmortem": {
|
| 684 |
+
"root_cause": scenario["root_cause"],
|
| 685 |
+
"attack_vector": scenario["attack_vector"],
|
| 686 |
+
"timeline": ["Investigated", "Patched", "Recovered"],
|
| 687 |
+
"remediation_steps": ["Patch", "Recover"],
|
| 688 |
+
"prevention_steps": ["Detect", "Harden"],
|
| 689 |
+
},
|
| 690 |
+
}
|
| 691 |
+
|
| 692 |
+
def _progress_flags(self) -> dict[str, bool]:
|
| 693 |
+
return {
|
| 694 |
+
"root_cause_identified": self._episode["identified_root_cause"] is not None,
|
| 695 |
+
"security_subquest_unlocked": self._episode["security_subquest_status"] != "locked",
|
| 696 |
+
"code_visible": self._episode["security_context"].code_visible,
|
| 697 |
+
"security_fix_submitted": self._episode["security_fix_submitted"],
|
| 698 |
+
"incident_resolved": self._episode["incident_resolved"],
|
| 699 |
+
"postmortem_submitted": self._episode["postmortem_submitted"],
|
| 700 |
+
}
|
| 701 |
+
|
| 702 |
+
def _stage_hint(self) -> str:
|
| 703 |
+
stage = self._episode["workflow_stage"]
|
| 704 |
+
if stage == "diagnosis":
|
| 705 |
+
return "Use investigation actions to identify the root cause quickly."
|
| 706 |
+
if stage == "root_cause_analysis":
|
| 707 |
+
return "Confirm the root cause and avoid repeated broad investigation."
|
| 708 |
+
if stage == "security_subquest":
|
| 709 |
+
return "Complete the security subquest with the next security action, then recover the system."
|
| 710 |
+
if stage == "remediation":
|
| 711 |
+
return "Recover the system health using the allowed remediation action."
|
| 712 |
+
if stage == "verification":
|
| 713 |
+
return "Verify the security fix and system recovery before submitting the security fix."
|
| 714 |
+
if stage == "postmortem":
|
| 715 |
+
return "Submit the postmortem now that the incident is resolved."
|
| 716 |
+
return "Follow the current stage goal and allowed actions."
|
| 717 |
+
|
| 718 |
+
def _stop_investigating_reason(self) -> str | None:
|
| 719 |
+
if self._episode["loop_warning"]:
|
| 720 |
+
return "Repeated no-progress actions detected. Stop investigating in the same way."
|
| 721 |
+
if self._episode["workflow_stage"] == "root_cause_analysis":
|
| 722 |
+
return "Confirm the root cause without broad additional queries."
|
| 723 |
+
if self._episode["workflow_stage"] in {"security_subquest", "remediation", "verification", "postmortem"}:
|
| 724 |
+
return "Avoid more query_* investigation actions unless strictly required by the current stage."
|
| 725 |
+
return None
|
| 726 |
+
|
| 727 |
+
def _patch_ids(self) -> list[str]:
|
| 728 |
+
scenario_security = self._episode["scenario"].get("security") or {}
|
| 729 |
+
patch_options = scenario_security.get("patch_options") or []
|
| 730 |
+
return [option["id"] for option in patch_options if "id" in option]
|
| 731 |
+
|
| 732 |
+
def _prompt_text(self, tool_output: str | None) -> str:
|
| 733 |
+
allowed_actions = self._allowed_actions()
|
| 734 |
+
required_fields = self._required_fields_by_action()
|
| 735 |
+
valid_action_example = self._valid_action_example()
|
| 736 |
+
progress_flags = self._progress_flags()
|
| 737 |
+
lines = [
|
| 738 |
+
f"TICK {self._episode['tick']}/{self._episode['max_ticks']}",
|
| 739 |
+
f"WORKFLOW_STAGE: {self._episode['workflow_stage']}",
|
| 740 |
+
"",
|
| 741 |
+
"ACTIVE_ALERTS:",
|
| 742 |
+
]
|
| 743 |
+
if self._episode["alerts"]:
|
| 744 |
+
for alert in self._episode["alerts"]:
|
| 745 |
+
lines.append(f"- [{alert.severity.upper()}] {alert.service}: {alert.message}")
|
| 746 |
+
else:
|
| 747 |
+
lines.append("- none")
|
| 748 |
+
lines.extend(["", "SERVICES:"])
|
| 749 |
+
for service_name in SERVICE_ORDER:
|
| 750 |
+
health = self._episode["services"][service_name]
|
| 751 |
+
lines.append(
|
| 752 |
+
f"- {service_name}: {health.status} cpu={health.cpu_pct:.1f} mem={health.memory_pct:.1f} err={health.error_rate_pct:.1f}"
|
| 753 |
+
)
|
| 754 |
+
lines.extend(
|
| 755 |
+
[
|
| 756 |
+
"",
|
| 757 |
+
"LAST_ACTION_RESULT:",
|
| 758 |
+
self._episode["last_action_result"] or "none",
|
| 759 |
+
"",
|
| 760 |
+
"TOOL_OUTPUT:",
|
| 761 |
+
tool_output or "none",
|
| 762 |
+
"",
|
| 763 |
+
"FAILURE_TYPE:",
|
| 764 |
+
self._episode["failure_type"] or "none",
|
| 765 |
+
"",
|
| 766 |
+
"WHY_FAILED:",
|
| 767 |
+
self._episode["why_failed"] or "none",
|
| 768 |
+
"",
|
| 769 |
+
"SECURITY_SUBQUEST_STATUS:",
|
| 770 |
+
f"- {self._episode['security_subquest_status']}",
|
| 771 |
+
"",
|
| 772 |
+
"SECURITY_CONTEXT:",
|
| 773 |
+
]
|
| 774 |
+
)
|
| 775 |
+
security = self._episode["security_context"]
|
| 776 |
+
lines.extend(
|
| 777 |
+
[
|
| 778 |
+
f"- code_visible: {'true' if security.code_visible else 'false'}",
|
| 779 |
+
f"- selected_vulnerability: {security.selected_vulnerability or 'null'}",
|
| 780 |
+
f"- selected_patch: {security.selected_patch or 'null'}",
|
| 781 |
+
f"- exploit_blocked: {self._bool_or_null(security.exploit_blocked)}",
|
| 782 |
+
f"- functionality_preserved: {self._bool_or_null(security.functionality_preserved)}",
|
| 783 |
+
"",
|
| 784 |
+
"ALLOWED_ACTIONS:",
|
| 785 |
+
]
|
| 786 |
+
)
|
| 787 |
+
lines.extend([f"- {action}" for action in allowed_actions])
|
| 788 |
+
lines.extend(
|
| 789 |
+
[
|
| 790 |
+
"",
|
| 791 |
+
"REQUIRED_FIELDS_BY_ACTION:",
|
| 792 |
+
]
|
| 793 |
+
)
|
| 794 |
+
lines.extend(
|
| 795 |
+
[
|
| 796 |
+
f"- {action}: {', '.join(fields) if fields else '(no extra fields)'}"
|
| 797 |
+
for action, fields in required_fields.items()
|
| 798 |
+
]
|
| 799 |
+
)
|
| 800 |
+
stage_hint = self._stage_hint()
|
| 801 |
+
stop_investigation = self._stop_investigating_reason()
|
| 802 |
+
patch_ids = self._patch_ids()
|
| 803 |
+
lines.extend(
|
| 804 |
+
[
|
| 805 |
+
"",
|
| 806 |
+
"VALID_ACTION_EXAMPLE:",
|
| 807 |
+
json.dumps(valid_action_example, separators=(",", ":")),
|
| 808 |
+
"",
|
| 809 |
+
"COMMON_TRAP:",
|
| 810 |
+
self._episode["common_trap"] or "none",
|
| 811 |
+
"",
|
| 812 |
+
"STAGE_HINT:",
|
| 813 |
+
stage_hint,
|
| 814 |
+
"",
|
| 815 |
+
"STOP_INVESTIGATING:",
|
| 816 |
+
stop_investigation or "none",
|
| 817 |
+
]
|
| 818 |
+
)
|
| 819 |
+
if patch_ids and "apply_patch" in allowed_actions:
|
| 820 |
+
lines.extend([
|
| 821 |
+
"",
|
| 822 |
+
"PATCH_IDS:",
|
| 823 |
+
", ".join(patch_ids),
|
| 824 |
+
])
|
| 825 |
+
lines.extend(
|
| 826 |
+
[
|
| 827 |
+
"",
|
| 828 |
+
"LOOP_WARNING:",
|
| 829 |
+
self._episode["loop_warning"] or "none",
|
| 830 |
+
"",
|
| 831 |
+
"SECURITY_UNLOCK_REASON:",
|
| 832 |
+
self._episode["security_unlock_reason"] or "none",
|
| 833 |
+
"",
|
| 834 |
+
"PROGRESS_FLAGS:",
|
| 835 |
+
]
|
| 836 |
+
)
|
| 837 |
+
lines.extend(
|
| 838 |
+
[
|
| 839 |
+
f"- {name}: {'true' if value else 'false'}"
|
| 840 |
+
for name, value in progress_flags.items()
|
| 841 |
+
]
|
| 842 |
+
)
|
| 843 |
+
lines.extend(
|
| 844 |
+
[
|
| 845 |
+
"",
|
| 846 |
+
"What is the next action? JSON only.",
|
| 847 |
+
]
|
| 848 |
+
)
|
| 849 |
+
return "\n".join(lines)
|
| 850 |
+
|
| 851 |
+
def _bool_or_null(self, value: bool | None) -> str:
|
| 852 |
+
if value is None:
|
| 853 |
+
return "null"
|
| 854 |
+
return "true" if value else "false"
|
| 855 |
+
|
| 856 |
+
def _state_dict(self) -> dict[str, Any]:
|
| 857 |
+
return {
|
| 858 |
+
"episode_id": self._episode["episode_id"],
|
| 859 |
+
"step_count": self._episode["step_count"],
|
| 860 |
+
"scenario_id": self._episode["scenario"]["id"],
|
| 861 |
+
"difficulty": self._episode["difficulty"],
|
| 862 |
+
"current_tick": self._episode["tick"],
|
| 863 |
+
"max_ticks": self._episode["max_ticks"],
|
| 864 |
+
"workflow_stage": self._episode["workflow_stage"],
|
| 865 |
+
"active_alerts": [alert.model_dump() for alert in self._episode["alerts"]],
|
| 866 |
+
"service_health": {
|
| 867 |
+
name: service.model_dump()
|
| 868 |
+
for name, service in self._episode["services"].items()
|
| 869 |
+
},
|
| 870 |
+
"discovered_evidence": list(self._episode["discovered_evidence"]),
|
| 871 |
+
"identified_root_cause": self._episode["identified_root_cause"],
|
| 872 |
+
"failure_type": self._episode["failure_type"],
|
| 873 |
+
"why_failed": self._episode["why_failed"],
|
| 874 |
+
"allowed_actions": self._allowed_actions(),
|
| 875 |
+
"required_fields_by_action": self._required_fields_by_action(),
|
| 876 |
+
"valid_action_example": self._valid_action_example(),
|
| 877 |
+
"common_trap": self._episode["common_trap"],
|
| 878 |
+
"loop_warning": self._episode["loop_warning"],
|
| 879 |
+
"blocked_until_security_complete": self._episode["blocked_until_security_complete"],
|
| 880 |
+
"security_unlock_reason": self._episode["security_unlock_reason"],
|
| 881 |
+
"best_recovery_action_family": self._episode["best_recovery_action_family"],
|
| 882 |
+
"progress_flags": self._progress_flags(),
|
| 883 |
+
"security_subquest_status": self._episode["security_subquest_status"],
|
| 884 |
+
"security_context": self._episode["security_context"].model_dump(),
|
| 885 |
+
"security_fix_submitted": self._episode["security_fix_submitted"],
|
| 886 |
+
"incident_resolved": self._episode["incident_resolved"],
|
| 887 |
+
"postmortem_submitted": self._episode["postmortem_submitted"],
|
| 888 |
+
"cumulative_reward": self._episode["cumulative_reward"],
|
| 889 |
+
"cumulative_score": self._episode["final_score"],
|
| 890 |
+
"score_breakdown": {
|
| 891 |
+
"infrastructure_score": self._episode["score_breakdown"]["infrastructure_score"],
|
| 892 |
+
"security_score": self._episode["score_breakdown"]["security_score"],
|
| 893 |
+
"efficiency_score": self._episode["score_breakdown"]["efficiency_score"],
|
| 894 |
+
"postmortem_score": self._episode["postmortem_score"],
|
| 895 |
+
},
|
| 896 |
+
"relevant_investigations": self._episode["relevant_investigations"],
|
| 897 |
+
"correct_infra_steps": self._episode["correct_infra_steps"],
|
| 898 |
+
"infra_restored_in_correct_order": self._episode["infra_restored_in_correct_order"],
|
| 899 |
+
"selected_vulnerability": self._episode["security_context"].selected_vulnerability,
|
| 900 |
+
"selected_patch": self._episode["security_context"].selected_patch,
|
| 901 |
+
"exploit_blocked": self._episode["security_context"].exploit_blocked,
|
| 902 |
+
"functionality_preserved": self._episode["security_context"].functionality_preserved,
|
| 903 |
+
"wasteful_ticks": self._episode["wasteful_ticks"],
|
| 904 |
+
"last_action_result": self._episode["last_action_result"],
|
| 905 |
+
}
|
| 906 |
+
|
| 907 |
+
def _build_observation(
|
| 908 |
+
self,
|
| 909 |
+
last_action_result: str,
|
| 910 |
+
tool_output: str | None,
|
| 911 |
+
reward: float,
|
| 912 |
+
done: bool,
|
| 913 |
+
) -> UnifiedIncidentObservation:
|
| 914 |
+
return UnifiedIncidentObservation(
|
| 915 |
+
prompt_text=self._prompt_text(tool_output),
|
| 916 |
+
tick_count=self._episode["tick"],
|
| 917 |
+
max_ticks=self._episode["max_ticks"],
|
| 918 |
+
difficulty=self._episode["difficulty"],
|
| 919 |
+
workflow_stage=self._episode["workflow_stage"],
|
| 920 |
+
active_alerts=list(self._episode["alerts"]),
|
| 921 |
+
service_health=dict(self._episode["services"]),
|
| 922 |
+
last_action_result=last_action_result,
|
| 923 |
+
tool_output=tool_output,
|
| 924 |
+
failure_type=self._episode["failure_type"],
|
| 925 |
+
why_failed=self._episode["why_failed"],
|
| 926 |
+
allowed_actions=self._allowed_actions(),
|
| 927 |
+
required_fields_by_action=self._required_fields_by_action(),
|
| 928 |
+
valid_action_example=self._valid_action_example(),
|
| 929 |
+
common_trap=self._episode["common_trap"],
|
| 930 |
+
loop_warning=self._episode["loop_warning"],
|
| 931 |
+
blocked_until_security_complete=self._episode["blocked_until_security_complete"],
|
| 932 |
+
security_unlock_reason=self._episode["security_unlock_reason"],
|
| 933 |
+
best_recovery_action_family=self._episode["best_recovery_action_family"],
|
| 934 |
+
progress_flags=self._progress_flags(),
|
| 935 |
+
security_subquest_status=self._episode["security_subquest_status"],
|
| 936 |
+
security_context=self._episode["security_context"].model_copy(deep=True),
|
| 937 |
+
final_score=self._episode["final_score"],
|
| 938 |
+
score_breakdown={
|
| 939 |
+
"infrastructure_score": self._episode["score_breakdown"]["infrastructure_score"],
|
| 940 |
+
"security_score": self._episode["score_breakdown"]["security_score"],
|
| 941 |
+
"efficiency_score": self._episode["score_breakdown"]["efficiency_score"],
|
| 942 |
+
"postmortem_score": self._episode["postmortem_score"],
|
| 943 |
+
},
|
| 944 |
+
incident_resolved=self._episode["incident_resolved"],
|
| 945 |
+
reward=round(reward, 4),
|
| 946 |
+
done=done,
|
| 947 |
+
)
|
unified_incident_env/server/grader.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fully deterministic grading for the final preset pack."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from ..models import GraderCheck, GraderReport, PostmortemPayload
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _contains_all(text: str, phrases: list[str]) -> bool:
|
| 11 |
+
lowered = text.lower()
|
| 12 |
+
return all(phrase.lower() in lowered for phrase in phrases)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _contains_any(text: str, phrases: list[str]) -> bool:
|
| 16 |
+
lowered = text.lower()
|
| 17 |
+
return any(phrase.lower() in lowered for phrase in phrases)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DeterministicPostmortemScorer:
|
| 21 |
+
"""Deterministic postmortem scorer with the final rubric."""
|
| 22 |
+
|
| 23 |
+
def score(
|
| 24 |
+
self,
|
| 25 |
+
postmortem: PostmortemPayload,
|
| 26 |
+
scenario: dict[str, Any],
|
| 27 |
+
) -> float:
|
| 28 |
+
keywords = scenario["postmortem_keywords"]
|
| 29 |
+
total = 0.0
|
| 30 |
+
root_text = postmortem.root_cause.strip().lower()
|
| 31 |
+
attack_text = postmortem.attack_vector.strip().lower()
|
| 32 |
+
remediation_text = " ".join(
|
| 33 |
+
list(postmortem.timeline) + list(postmortem.remediation_steps)
|
| 34 |
+
).lower()
|
| 35 |
+
prevention_text = " ".join(postmortem.prevention_steps).lower()
|
| 36 |
+
|
| 37 |
+
if root_text and _contains_all(root_text, keywords["root_cause"]):
|
| 38 |
+
total += 0.03
|
| 39 |
+
if attack_text and _contains_any(attack_text, keywords["attack_vector"]):
|
| 40 |
+
total += 0.02
|
| 41 |
+
if remediation_text and _contains_all(remediation_text, keywords["remediation"]):
|
| 42 |
+
total += 0.03
|
| 43 |
+
if prevention_text and _contains_any(prevention_text, keywords["prevention"]):
|
| 44 |
+
total += 0.02
|
| 45 |
+
return round(min(0.10, total), 4)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class UnifiedIncidentGrader:
|
| 49 |
+
"""Deterministic final scorer for the unified preset benchmark."""
|
| 50 |
+
|
| 51 |
+
def __init__(self) -> None:
|
| 52 |
+
self._postmortem = DeterministicPostmortemScorer()
|
| 53 |
+
|
| 54 |
+
def postmortem_score(
|
| 55 |
+
self,
|
| 56 |
+
postmortem: PostmortemPayload,
|
| 57 |
+
scenario: dict[str, Any],
|
| 58 |
+
) -> float:
|
| 59 |
+
return self._postmortem.score(postmortem, scenario)
|
| 60 |
+
|
| 61 |
+
def compute_breakdown(
|
| 62 |
+
self,
|
| 63 |
+
state: dict[str, Any],
|
| 64 |
+
scenario: dict[str, Any],
|
| 65 |
+
) -> dict[str, float]:
|
| 66 |
+
infrastructure_score = min(
|
| 67 |
+
0.45,
|
| 68 |
+
round(
|
| 69 |
+
(0.05 * int(state.get("relevant_investigations", 0)))
|
| 70 |
+
+ (0.10 * int(state.get("correct_infra_steps", 0)))
|
| 71 |
+
+ (0.15 if state.get("infra_restored_in_correct_order", False) else 0.0)
|
| 72 |
+
+ (0.15 if state.get("incident_resolved", False) else 0.0),
|
| 73 |
+
4,
|
| 74 |
+
),
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
security_score = 0.0
|
| 78 |
+
if state.get("selected_vulnerability") == scenario["security"]["correct_vulnerability"]:
|
| 79 |
+
security_score += 0.10
|
| 80 |
+
if state.get("selected_patch") == scenario["security"]["correct_patch"]:
|
| 81 |
+
security_score += 0.10
|
| 82 |
+
if state.get("exploit_blocked") is True:
|
| 83 |
+
security_score += 0.10
|
| 84 |
+
if state.get("security_fix_submitted") is True:
|
| 85 |
+
security_score += 0.05
|
| 86 |
+
security_score = round(min(0.35, security_score), 4)
|
| 87 |
+
|
| 88 |
+
efficiency_score = round(
|
| 89 |
+
max(0.0, 0.10 - (0.01 * int(state.get("wasteful_ticks", 0)))),
|
| 90 |
+
4,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
postmortem_score = round(
|
| 94 |
+
float(state.get("score_breakdown", {}).get("postmortem_score", 0.0)),
|
| 95 |
+
4,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
final_score = round(
|
| 99 |
+
max(
|
| 100 |
+
0.0,
|
| 101 |
+
min(
|
| 102 |
+
1.0,
|
| 103 |
+
infrastructure_score
|
| 104 |
+
+ security_score
|
| 105 |
+
+ efficiency_score
|
| 106 |
+
+ postmortem_score,
|
| 107 |
+
),
|
| 108 |
+
),
|
| 109 |
+
4,
|
| 110 |
+
)
|
| 111 |
+
if state.get("security_subquest_status") != "completed":
|
| 112 |
+
final_score = min(final_score, 0.5)
|
| 113 |
+
|
| 114 |
+
return {
|
| 115 |
+
"infrastructure_score": round(infrastructure_score, 4),
|
| 116 |
+
"security_score": round(security_score, 4),
|
| 117 |
+
"efficiency_score": round(efficiency_score, 4),
|
| 118 |
+
"postmortem_score": round(postmortem_score, 4),
|
| 119 |
+
"final_score": round(final_score, 4),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
def build_report(self, state: dict[str, Any], scenario: dict[str, Any]) -> GraderReport:
|
| 123 |
+
breakdown = self.compute_breakdown(state, scenario)
|
| 124 |
+
checks = [
|
| 125 |
+
GraderCheck(
|
| 126 |
+
name="security_subquest_completed",
|
| 127 |
+
passed=state.get("security_subquest_status") == "completed",
|
| 128 |
+
detail=(
|
| 129 |
+
"Security subquest completed."
|
| 130 |
+
if state.get("security_subquest_status") == "completed"
|
| 131 |
+
else "Security subquest is incomplete."
|
| 132 |
+
),
|
| 133 |
+
weight=0.35,
|
| 134 |
+
),
|
| 135 |
+
GraderCheck(
|
| 136 |
+
name="incident_resolved",
|
| 137 |
+
passed=bool(state.get("incident_resolved")),
|
| 138 |
+
detail=(
|
| 139 |
+
"All required services are healthy."
|
| 140 |
+
if state.get("incident_resolved")
|
| 141 |
+
else "Required services are not fully healthy."
|
| 142 |
+
),
|
| 143 |
+
weight=0.30,
|
| 144 |
+
),
|
| 145 |
+
GraderCheck(
|
| 146 |
+
name="investigation_performed",
|
| 147 |
+
passed=int(state.get("relevant_investigations", 0)) > 0,
|
| 148 |
+
detail=(
|
| 149 |
+
"Relevant investigation was performed."
|
| 150 |
+
if int(state.get("relevant_investigations", 0)) > 0
|
| 151 |
+
else "No relevant investigation evidence was collected."
|
| 152 |
+
),
|
| 153 |
+
weight=0.15,
|
| 154 |
+
),
|
| 155 |
+
GraderCheck(
|
| 156 |
+
name="postmortem_submitted",
|
| 157 |
+
passed=bool(state.get("postmortem_submitted")),
|
| 158 |
+
detail=(
|
| 159 |
+
"Postmortem submitted."
|
| 160 |
+
if state.get("postmortem_submitted")
|
| 161 |
+
else "Postmortem not submitted."
|
| 162 |
+
),
|
| 163 |
+
weight=0.10,
|
| 164 |
+
),
|
| 165 |
+
GraderCheck(
|
| 166 |
+
name="efficiency_positive",
|
| 167 |
+
passed=breakdown["efficiency_score"] > 0.0,
|
| 168 |
+
detail=(
|
| 169 |
+
"Efficiency score remains positive."
|
| 170 |
+
if breakdown["efficiency_score"] > 0.0
|
| 171 |
+
else "Efficiency score fell to zero."
|
| 172 |
+
),
|
| 173 |
+
weight=0.10,
|
| 174 |
+
),
|
| 175 |
+
]
|
| 176 |
+
passed = bool(
|
| 177 |
+
state.get("incident_resolved")
|
| 178 |
+
and state.get("security_subquest_status") == "completed"
|
| 179 |
+
and state.get("postmortem_submitted")
|
| 180 |
+
)
|
| 181 |
+
message = (
|
| 182 |
+
"Unified incident resolved successfully."
|
| 183 |
+
if passed
|
| 184 |
+
else "Unified incident is not fully complete."
|
| 185 |
+
)
|
| 186 |
+
return GraderReport(
|
| 187 |
+
scenario_id=scenario["id"],
|
| 188 |
+
passed=passed,
|
| 189 |
+
score=breakdown["final_score"],
|
| 190 |
+
message=message,
|
| 191 |
+
breakdown=breakdown,
|
| 192 |
+
checks=checks,
|
| 193 |
+
)
|
unified_incident_env/tests/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Tests for the unified incident environment."""
|
unified_incident_env/tests/test_environment.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Behavior and API tests for the final preset-based environment."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing import get_args
|
| 5 |
+
|
| 6 |
+
from unified_incident_env.models import ActionType, PostmortemPayload, UnifiedIncidentAction
|
| 7 |
+
from unified_incident_env.server.app import (
|
| 8 |
+
baseline as baseline_endpoint,
|
| 9 |
+
grader as grader_endpoint,
|
| 10 |
+
health as health_endpoint,
|
| 11 |
+
status as status_endpoint,
|
| 12 |
+
tasks as tasks_endpoint,
|
| 13 |
+
)
|
| 14 |
+
from unified_incident_env.server.environment import UnifiedIncidentEnvironment
|
| 15 |
+
from unified_incident_env.server.grader import UnifiedIncidentGrader
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _postmortem_for(scenario_id: str) -> PostmortemPayload:
|
| 19 |
+
if scenario_id == "database_sqli_outage":
|
| 20 |
+
return PostmortemPayload(
|
| 21 |
+
root_cause="SQL injection in login exhausted and crashed the database.",
|
| 22 |
+
attack_vector="Unsanitized SQL input triggered abusive database load.",
|
| 23 |
+
timeline=[
|
| 24 |
+
"Queried database logs",
|
| 25 |
+
"Inspected code",
|
| 26 |
+
"Patched SQL injection",
|
| 27 |
+
"Verified exploit blocked",
|
| 28 |
+
"Restarted database",
|
| 29 |
+
],
|
| 30 |
+
remediation_steps=["Use parameterized query", "Restart database"],
|
| 31 |
+
prevention_steps=["Parameterized queries", "DB abuse alerting"],
|
| 32 |
+
)
|
| 33 |
+
if scenario_id == "cache_abuse_broken_access_control":
|
| 34 |
+
return PostmortemPayload(
|
| 35 |
+
root_cause="Broken access control on the internal admin endpoint caused a cache and database cascade.",
|
| 36 |
+
attack_vector="Missing authorization let attackers abuse the internal admin path.",
|
| 37 |
+
timeline=[
|
| 38 |
+
"Queried cache metrics",
|
| 39 |
+
"Queried api-gateway dependencies",
|
| 40 |
+
"Inspected code",
|
| 41 |
+
"Enforced admin role",
|
| 42 |
+
"Verified exploit blocked",
|
| 43 |
+
"Restarted cache",
|
| 44 |
+
"Restarted database",
|
| 45 |
+
],
|
| 46 |
+
remediation_steps=["Enforce admin role", "Restart cache", "Restart database"],
|
| 47 |
+
prevention_steps=["Authorization checks", "Admin role enforcement", "Rate limits"],
|
| 48 |
+
)
|
| 49 |
+
return PostmortemPayload(
|
| 50 |
+
root_cause="A bad worker deploy plus command injection repeatedly poisoned downstream services.",
|
| 51 |
+
attack_vector="Shell-based worker commands accepted unsafe filenames and kept replaying corruption.",
|
| 52 |
+
timeline=[
|
| 53 |
+
"Queried worker logs",
|
| 54 |
+
"Queried database metrics",
|
| 55 |
+
"Inspected code",
|
| 56 |
+
"Patched command injection",
|
| 57 |
+
"Verified exploit blocked",
|
| 58 |
+
"Rolled back worker",
|
| 59 |
+
"Restarted database",
|
| 60 |
+
"Restarted api-gateway",
|
| 61 |
+
],
|
| 62 |
+
remediation_steps=["Avoid shell", "Rollback worker", "Restart database", "Restart api-gateway"],
|
| 63 |
+
prevention_steps=["Avoid shell", "Input validation", "Safer deploy checks"],
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _solve_easy(env: UnifiedIncidentEnvironment) -> None:
|
| 68 |
+
env.reset(scenario_id="database_sqli_outage")
|
| 69 |
+
env.step(UnifiedIncidentAction(action_type="query_logs", service="database"))
|
| 70 |
+
env.step(UnifiedIncidentAction(action_type="inspect_code"))
|
| 71 |
+
env.step(
|
| 72 |
+
UnifiedIncidentAction(
|
| 73 |
+
action_type="classify_vulnerability",
|
| 74 |
+
vulnerability_type="sql_injection",
|
| 75 |
+
)
|
| 76 |
+
)
|
| 77 |
+
env.step(
|
| 78 |
+
UnifiedIncidentAction(
|
| 79 |
+
action_type="apply_patch",
|
| 80 |
+
patch_id="parameterized_query",
|
| 81 |
+
)
|
| 82 |
+
)
|
| 83 |
+
env.step(UnifiedIncidentAction(action_type="verify_security_fix"))
|
| 84 |
+
env.step(UnifiedIncidentAction(action_type="submit_security_fix"))
|
| 85 |
+
env.step(UnifiedIncidentAction(action_type="restart_service", service="database"))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _solve_medium(env: UnifiedIncidentEnvironment) -> None:
|
| 89 |
+
env.reset(scenario_id="cache_abuse_broken_access_control")
|
| 90 |
+
env.step(
|
| 91 |
+
UnifiedIncidentAction(
|
| 92 |
+
action_type="query_metrics",
|
| 93 |
+
service="cache",
|
| 94 |
+
metric="cpu",
|
| 95 |
+
)
|
| 96 |
+
)
|
| 97 |
+
env.step(
|
| 98 |
+
UnifiedIncidentAction(
|
| 99 |
+
action_type="query_dependencies",
|
| 100 |
+
service="api-gateway",
|
| 101 |
+
)
|
| 102 |
+
)
|
| 103 |
+
env.step(UnifiedIncidentAction(action_type="inspect_code"))
|
| 104 |
+
env.step(
|
| 105 |
+
UnifiedIncidentAction(
|
| 106 |
+
action_type="classify_vulnerability",
|
| 107 |
+
vulnerability_type="broken_access_control",
|
| 108 |
+
)
|
| 109 |
+
)
|
| 110 |
+
env.step(
|
| 111 |
+
UnifiedIncidentAction(
|
| 112 |
+
action_type="apply_patch",
|
| 113 |
+
patch_id="enforce_admin_role",
|
| 114 |
+
)
|
| 115 |
+
)
|
| 116 |
+
env.step(UnifiedIncidentAction(action_type="verify_security_fix"))
|
| 117 |
+
env.step(UnifiedIncidentAction(action_type="submit_security_fix"))
|
| 118 |
+
env.step(UnifiedIncidentAction(action_type="restart_service", service="cache"))
|
| 119 |
+
env.step(UnifiedIncidentAction(action_type="restart_service", service="database"))
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _solve_hard(env: UnifiedIncidentEnvironment) -> None:
|
| 123 |
+
env.reset(scenario_id="worker_bad_deploy_command_injection")
|
| 124 |
+
env.step(UnifiedIncidentAction(action_type="query_logs", service="worker"))
|
| 125 |
+
env.step(UnifiedIncidentAction(action_type="inspect_code"))
|
| 126 |
+
env.step(
|
| 127 |
+
UnifiedIncidentAction(
|
| 128 |
+
action_type="classify_vulnerability",
|
| 129 |
+
vulnerability_type="command_injection",
|
| 130 |
+
)
|
| 131 |
+
)
|
| 132 |
+
env.step(
|
| 133 |
+
UnifiedIncidentAction(
|
| 134 |
+
action_type="apply_patch",
|
| 135 |
+
patch_id="avoid_shell",
|
| 136 |
+
)
|
| 137 |
+
)
|
| 138 |
+
env.step(UnifiedIncidentAction(action_type="verify_security_fix"))
|
| 139 |
+
env.step(UnifiedIncidentAction(action_type="submit_security_fix"))
|
| 140 |
+
env.step(UnifiedIncidentAction(action_type="rollback_deploy", service="worker"))
|
| 141 |
+
env.step(UnifiedIncidentAction(action_type="restart_service", service="database"))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_happy_path_easy() -> None:
|
| 145 |
+
env = UnifiedIncidentEnvironment()
|
| 146 |
+
_solve_easy(env)
|
| 147 |
+
obs = env.step(
|
| 148 |
+
UnifiedIncidentAction(
|
| 149 |
+
action_type="submit_postmortem",
|
| 150 |
+
postmortem=_postmortem_for("database_sqli_outage"),
|
| 151 |
+
)
|
| 152 |
+
)
|
| 153 |
+
assert obs.done is True
|
| 154 |
+
assert obs.incident_resolved is True
|
| 155 |
+
assert obs.security_subquest_status == "completed"
|
| 156 |
+
assert obs.final_score >= 0.8
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def test_happy_path_medium() -> None:
|
| 160 |
+
env = UnifiedIncidentEnvironment()
|
| 161 |
+
_solve_medium(env)
|
| 162 |
+
obs = env.step(
|
| 163 |
+
UnifiedIncidentAction(
|
| 164 |
+
action_type="submit_postmortem",
|
| 165 |
+
postmortem=_postmortem_for("cache_abuse_broken_access_control"),
|
| 166 |
+
)
|
| 167 |
+
)
|
| 168 |
+
assert obs.done is True
|
| 169 |
+
assert obs.incident_resolved is True
|
| 170 |
+
assert obs.security_subquest_status == "completed"
|
| 171 |
+
assert obs.final_score >= 0.8
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def test_happy_path_hard() -> None:
|
| 175 |
+
env = UnifiedIncidentEnvironment()
|
| 176 |
+
_solve_hard(env)
|
| 177 |
+
obs = env.step(
|
| 178 |
+
UnifiedIncidentAction(
|
| 179 |
+
action_type="submit_postmortem",
|
| 180 |
+
postmortem=_postmortem_for("worker_bad_deploy_command_injection"),
|
| 181 |
+
)
|
| 182 |
+
)
|
| 183 |
+
assert obs.done is True
|
| 184 |
+
assert obs.incident_resolved is True
|
| 185 |
+
assert obs.security_subquest_status == "completed"
|
| 186 |
+
assert obs.final_score >= 0.8
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def test_trap_path_easy() -> None:
|
| 190 |
+
env = UnifiedIncidentEnvironment()
|
| 191 |
+
env.reset(scenario_id="database_sqli_outage")
|
| 192 |
+
obs = env.step(
|
| 193 |
+
UnifiedIncidentAction(action_type="restart_service", service="api-gateway")
|
| 194 |
+
)
|
| 195 |
+
assert "does not help" in obs.last_action_result.lower()
|
| 196 |
+
assert obs.reward == -0.10
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def test_trap_path_medium() -> None:
|
| 200 |
+
env = UnifiedIncidentEnvironment()
|
| 201 |
+
env.reset(scenario_id="cache_abuse_broken_access_control")
|
| 202 |
+
obs = env.step(
|
| 203 |
+
UnifiedIncidentAction(action_type="restart_service", service="database")
|
| 204 |
+
)
|
| 205 |
+
assert "trap" in obs.last_action_result.lower()
|
| 206 |
+
assert obs.reward == -0.10
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def test_trap_path_hard() -> None:
|
| 210 |
+
env = UnifiedIncidentEnvironment()
|
| 211 |
+
env.reset(scenario_id="worker_bad_deploy_command_injection")
|
| 212 |
+
obs = env.step(
|
| 213 |
+
UnifiedIncidentAction(action_type="rollback_deploy", service="worker")
|
| 214 |
+
)
|
| 215 |
+
assert "trap" in obs.last_action_result.lower()
|
| 216 |
+
assert obs.reward == -0.10
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def test_security_subquest_unlock_requires_evidence_chain_on_medium() -> None:
|
| 220 |
+
env = UnifiedIncidentEnvironment()
|
| 221 |
+
obs = env.reset(scenario_id="cache_abuse_broken_access_control")
|
| 222 |
+
assert obs.security_subquest_status == "locked"
|
| 223 |
+
first = env.step(
|
| 224 |
+
UnifiedIncidentAction(
|
| 225 |
+
action_type="query_metrics",
|
| 226 |
+
service="cache",
|
| 227 |
+
metric="cpu",
|
| 228 |
+
)
|
| 229 |
+
)
|
| 230 |
+
assert first.security_subquest_status == "locked"
|
| 231 |
+
assert first.workflow_stage == "root_cause_analysis"
|
| 232 |
+
second = env.step(
|
| 233 |
+
UnifiedIncidentAction(
|
| 234 |
+
action_type="query_dependencies",
|
| 235 |
+
service="api-gateway",
|
| 236 |
+
)
|
| 237 |
+
)
|
| 238 |
+
assert second.security_subquest_status == "active"
|
| 239 |
+
assert second.workflow_stage == "security_subquest"
|
| 240 |
+
assert second.security_unlock_reason is not None
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def test_stage_aware_allowed_actions_and_required_fields() -> None:
|
| 244 |
+
env = UnifiedIncidentEnvironment()
|
| 245 |
+
obs = env.reset(scenario_id="database_sqli_outage")
|
| 246 |
+
assert obs.workflow_stage == "diagnosis"
|
| 247 |
+
assert obs.allowed_actions == [
|
| 248 |
+
"query_logs",
|
| 249 |
+
"query_metrics",
|
| 250 |
+
"query_dependencies",
|
| 251 |
+
]
|
| 252 |
+
assert obs.required_fields_by_action["query_metrics"] == ["service", "metric"]
|
| 253 |
+
assert obs.valid_action_example is not None
|
| 254 |
+
assert obs.valid_action_example["action_type"] in obs.allowed_actions
|
| 255 |
+
|
| 256 |
+
security_obs = env.step(
|
| 257 |
+
UnifiedIncidentAction(action_type="query_logs", service="database")
|
| 258 |
+
)
|
| 259 |
+
assert security_obs.workflow_stage == "security_subquest"
|
| 260 |
+
assert security_obs.allowed_actions == [
|
| 261 |
+
"inspect_code",
|
| 262 |
+
"classify_vulnerability",
|
| 263 |
+
"apply_patch",
|
| 264 |
+
"verify_security_fix",
|
| 265 |
+
"submit_security_fix",
|
| 266 |
+
]
|
| 267 |
+
assert security_obs.required_fields_by_action["apply_patch"] == ["patch_id"]
|
| 268 |
+
|
| 269 |
+
inspect_obs = env.step(UnifiedIncidentAction(action_type="inspect_code"))
|
| 270 |
+
classify_obs = env.step(
|
| 271 |
+
UnifiedIncidentAction(
|
| 272 |
+
action_type="classify_vulnerability",
|
| 273 |
+
vulnerability_type="sql_injection",
|
| 274 |
+
)
|
| 275 |
+
)
|
| 276 |
+
patch_obs = env.step(
|
| 277 |
+
UnifiedIncidentAction(
|
| 278 |
+
action_type="apply_patch",
|
| 279 |
+
patch_id="parameterized_query",
|
| 280 |
+
)
|
| 281 |
+
)
|
| 282 |
+
verify_obs = env.step(UnifiedIncidentAction(action_type="verify_security_fix"))
|
| 283 |
+
assert inspect_obs.workflow_stage == "security_subquest"
|
| 284 |
+
assert classify_obs.workflow_stage == "security_subquest"
|
| 285 |
+
assert patch_obs.workflow_stage == "security_subquest"
|
| 286 |
+
assert verify_obs.workflow_stage == "verification"
|
| 287 |
+
assert "submit_security_fix" in verify_obs.allowed_actions
|
| 288 |
+
assert verify_obs.valid_action_example == {"action_type": "submit_security_fix"}
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def test_loop_warning_emits_after_repeated_no_progress_actions() -> None:
|
| 292 |
+
env = UnifiedIncidentEnvironment()
|
| 293 |
+
env.reset(scenario_id="database_sqli_outage")
|
| 294 |
+
first = env.step(
|
| 295 |
+
UnifiedIncidentAction(action_type="restart_service", service="api-gateway")
|
| 296 |
+
)
|
| 297 |
+
assert first.loop_warning is None
|
| 298 |
+
second = env.step(
|
| 299 |
+
UnifiedIncidentAction(action_type="restart_service", service="api-gateway")
|
| 300 |
+
)
|
| 301 |
+
assert second.loop_warning is not None
|
| 302 |
+
assert second.failure_type in {"trap_action", "repeated_no_progress_action"}
|
| 303 |
+
assert second.why_failed is not None
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def test_observation_exposes_blocked_until_security_complete() -> None:
|
| 307 |
+
env = UnifiedIncidentEnvironment()
|
| 308 |
+
env.reset(scenario_id="database_sqli_outage")
|
| 309 |
+
obs = env.step(
|
| 310 |
+
UnifiedIncidentAction(action_type="restart_service", service="database")
|
| 311 |
+
)
|
| 312 |
+
assert obs.blocked_until_security_complete is True
|
| 313 |
+
assert obs.failure_type == "infra_before_security"
|
| 314 |
+
assert obs.best_recovery_action_family == "submit_security_fix"
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def test_public_action_schema_is_unchanged() -> None:
|
| 318 |
+
assert set(get_args(ActionType)) == {
|
| 319 |
+
"query_logs",
|
| 320 |
+
"query_metrics",
|
| 321 |
+
"query_dependencies",
|
| 322 |
+
"restart_service",
|
| 323 |
+
"rollback_deploy",
|
| 324 |
+
"inspect_code",
|
| 325 |
+
"classify_vulnerability",
|
| 326 |
+
"apply_patch",
|
| 327 |
+
"verify_security_fix",
|
| 328 |
+
"submit_security_fix",
|
| 329 |
+
"submit_postmortem",
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def test_security_incomplete_caps_score_at_point_five() -> None:
|
| 334 |
+
grader = UnifiedIncidentGrader()
|
| 335 |
+
breakdown = grader.compute_breakdown(
|
| 336 |
+
{
|
| 337 |
+
"relevant_investigations": 3,
|
| 338 |
+
"correct_infra_steps": 3,
|
| 339 |
+
"infra_restored_in_correct_order": True,
|
| 340 |
+
"incident_resolved": True,
|
| 341 |
+
"selected_vulnerability": "command_injection",
|
| 342 |
+
"selected_patch": "avoid_shell",
|
| 343 |
+
"exploit_blocked": True,
|
| 344 |
+
"security_fix_submitted": False,
|
| 345 |
+
"security_subquest_status": "active",
|
| 346 |
+
"wasteful_ticks": 0,
|
| 347 |
+
"score_breakdown": {"postmortem_score": 0.10},
|
| 348 |
+
},
|
| 349 |
+
{
|
| 350 |
+
"security": {
|
| 351 |
+
"correct_vulnerability": "command_injection",
|
| 352 |
+
"correct_patch": "avoid_shell",
|
| 353 |
+
}
|
| 354 |
+
},
|
| 355 |
+
)
|
| 356 |
+
assert breakdown["final_score"] == 0.5
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def test_postmortem_scoring_is_deterministic() -> None:
|
| 360 |
+
grader = UnifiedIncidentGrader()
|
| 361 |
+
score = grader.postmortem_score(
|
| 362 |
+
_postmortem_for("database_sqli_outage"),
|
| 363 |
+
{
|
| 364 |
+
"postmortem_keywords": {
|
| 365 |
+
"root_cause": ["sql injection", "database"],
|
| 366 |
+
"attack_vector": ["unsanitized sql", "login", "input"],
|
| 367 |
+
"remediation": ["parameterized query", "restart database"],
|
| 368 |
+
"prevention": ["parameterized queries", "db abuse alerting"],
|
| 369 |
+
}
|
| 370 |
+
},
|
| 371 |
+
)
|
| 372 |
+
assert score == 0.10
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def test_http_routes() -> None:
|
| 376 |
+
payload = tasks_endpoint().model_dump()
|
| 377 |
+
assert payload["environment"] == "unified_incident_env"
|
| 378 |
+
assert {item["id"] for item in payload["scenarios"]} == {
|
| 379 |
+
"database_sqli_outage",
|
| 380 |
+
"cache_abuse_broken_access_control",
|
| 381 |
+
"worker_bad_deploy_command_injection",
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
baseline_payload = baseline_endpoint().model_dump()
|
| 385 |
+
assert len(baseline_payload["baselines"]) == 3
|
| 386 |
+
|
| 387 |
+
grader_payload = grader_endpoint().model_dump()
|
| 388 |
+
assert "score" in grader_payload
|
| 389 |
+
|
| 390 |
+
status_payload = status_endpoint().model_dump()
|
| 391 |
+
assert "progress" in status_payload
|
| 392 |
+
assert "grader" in status_payload
|
| 393 |
+
|
| 394 |
+
health_payload = health_endpoint()
|
| 395 |
+
assert health_payload["status"] == "ok"
|
| 396 |
+
assert health_payload["environment"] == "unified_incident_env"
|
unified_incident_env/tests/test_submission_inference.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
import inference
|
| 6 |
+
from unified_incident_env.models import (
|
| 7 |
+
Alert,
|
| 8 |
+
SecurityContext,
|
| 9 |
+
ServiceHealth,
|
| 10 |
+
UnifiedIncidentObservation,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def make_observation(**overrides: object) -> UnifiedIncidentObservation:
|
| 15 |
+
defaults = {
|
| 16 |
+
"prompt_text": "Test prompt",
|
| 17 |
+
"tick_count": 0,
|
| 18 |
+
"max_ticks": 10,
|
| 19 |
+
"difficulty": "easy",
|
| 20 |
+
"workflow_stage": "diagnosis",
|
| 21 |
+
"active_alerts": [
|
| 22 |
+
Alert(service="database", severity="critical", message="database down")
|
| 23 |
+
],
|
| 24 |
+
"service_health": {
|
| 25 |
+
"api-gateway": ServiceHealth(
|
| 26 |
+
name="api-gateway",
|
| 27 |
+
status="degraded",
|
| 28 |
+
cpu_pct=50.0,
|
| 29 |
+
memory_pct=40.0,
|
| 30 |
+
error_rate_pct=10.0,
|
| 31 |
+
latency_ms=100.0,
|
| 32 |
+
),
|
| 33 |
+
"cache": ServiceHealth(
|
| 34 |
+
name="cache",
|
| 35 |
+
status="healthy",
|
| 36 |
+
cpu_pct=20.0,
|
| 37 |
+
memory_pct=20.0,
|
| 38 |
+
error_rate_pct=0.0,
|
| 39 |
+
latency_ms=10.0,
|
| 40 |
+
),
|
| 41 |
+
"database": ServiceHealth(
|
| 42 |
+
name="database",
|
| 43 |
+
status="crashed",
|
| 44 |
+
cpu_pct=99.0,
|
| 45 |
+
memory_pct=99.0,
|
| 46 |
+
error_rate_pct=100.0,
|
| 47 |
+
latency_ms=0.0,
|
| 48 |
+
),
|
| 49 |
+
"worker": ServiceHealth(
|
| 50 |
+
name="worker",
|
| 51 |
+
status="healthy",
|
| 52 |
+
cpu_pct=15.0,
|
| 53 |
+
memory_pct=20.0,
|
| 54 |
+
error_rate_pct=0.0,
|
| 55 |
+
latency_ms=12.0,
|
| 56 |
+
),
|
| 57 |
+
},
|
| 58 |
+
"last_action_result": "",
|
| 59 |
+
"tool_output": None,
|
| 60 |
+
"failure_type": None,
|
| 61 |
+
"why_failed": None,
|
| 62 |
+
"allowed_actions": ["query_logs", "query_metrics", "query_dependencies"],
|
| 63 |
+
"required_fields_by_action": {
|
| 64 |
+
"query_logs": ["service"],
|
| 65 |
+
"query_metrics": ["service", "metric"],
|
| 66 |
+
"query_dependencies": ["service"],
|
| 67 |
+
},
|
| 68 |
+
"valid_action_example": {"action_type": "query_logs", "service": "database"},
|
| 69 |
+
"common_trap": None,
|
| 70 |
+
"loop_warning": None,
|
| 71 |
+
"blocked_until_security_complete": False,
|
| 72 |
+
"security_unlock_reason": None,
|
| 73 |
+
"best_recovery_action_family": None,
|
| 74 |
+
"progress_flags": {},
|
| 75 |
+
"security_subquest_status": "locked",
|
| 76 |
+
"security_context": SecurityContext(),
|
| 77 |
+
"final_score": 0.0,
|
| 78 |
+
"score_breakdown": {},
|
| 79 |
+
"incident_resolved": False,
|
| 80 |
+
"reward": 0.0,
|
| 81 |
+
"done": False,
|
| 82 |
+
}
|
| 83 |
+
defaults.update(overrides)
|
| 84 |
+
return UnifiedIncidentObservation(**defaults)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_log_helpers_match_required_format(capsys) -> None:
|
| 88 |
+
inference.log_start(task="database_sqli_outage", env="unified-incident-env", model="demo-model")
|
| 89 |
+
inference.log_step(step=2, action='{"action_type":"query_logs","service":"database"}', reward=0.1, done=False, error=None)
|
| 90 |
+
inference.log_end(success=True, steps=2, rewards=[0.1, 0.27])
|
| 91 |
+
captured = capsys.readouterr().out.strip().splitlines()
|
| 92 |
+
assert captured == [
|
| 93 |
+
"[START] task=database_sqli_outage env=unified-incident-env model=demo-model",
|
| 94 |
+
'[STEP] step=2 action={"action_type":"query_logs","service":"database"} reward=0.10 done=false error=null',
|
| 95 |
+
"[END] success=true steps=2 rewards=0.10,0.27",
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_parse_action_strips_extra_keys_and_normalizes_aliases() -> None:
|
| 100 |
+
observation = make_observation(
|
| 101 |
+
workflow_stage="security_subquest",
|
| 102 |
+
allowed_actions=["classify_vulnerability", "apply_patch"],
|
| 103 |
+
required_fields_by_action={
|
| 104 |
+
"classify_vulnerability": ["vulnerability_type"],
|
| 105 |
+
"apply_patch": ["patch_id"],
|
| 106 |
+
},
|
| 107 |
+
valid_action_example={
|
| 108 |
+
"action_type": "classify_vulnerability",
|
| 109 |
+
"vulnerability_type": "sql_injection",
|
| 110 |
+
},
|
| 111 |
+
)
|
| 112 |
+
raw = json.dumps(
|
| 113 |
+
{
|
| 114 |
+
"action": "classify_vulnerability",
|
| 115 |
+
"vulnerability": "sql_injection",
|
| 116 |
+
"details": "ignored",
|
| 117 |
+
}
|
| 118 |
+
)
|
| 119 |
+
action = inference.parse_action(raw, observation)
|
| 120 |
+
assert action == inference.UnifiedIncidentAction(
|
| 121 |
+
action_type="classify_vulnerability",
|
| 122 |
+
vulnerability_type="sql_injection",
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_parse_action_accepts_bare_action_using_stage_example() -> None:
|
| 127 |
+
observation = make_observation(
|
| 128 |
+
workflow_stage="security_subquest",
|
| 129 |
+
allowed_actions=["apply_patch"],
|
| 130 |
+
required_fields_by_action={"apply_patch": ["patch_id"]},
|
| 131 |
+
valid_action_example={"action_type": "apply_patch", "patch_id": "parameterized_query"},
|
| 132 |
+
)
|
| 133 |
+
action = inference.parse_action('"apply_patch"', observation)
|
| 134 |
+
assert action == inference.UnifiedIncidentAction(
|
| 135 |
+
action_type="apply_patch",
|
| 136 |
+
patch_id="parameterized_query",
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_build_fallback_action_uses_public_stage_signals_only() -> None:
|
| 141 |
+
observation = make_observation(
|
| 142 |
+
workflow_stage="security_subquest",
|
| 143 |
+
allowed_actions=[
|
| 144 |
+
"inspect_code",
|
| 145 |
+
"classify_vulnerability",
|
| 146 |
+
"apply_patch",
|
| 147 |
+
"verify_security_fix",
|
| 148 |
+
"submit_security_fix",
|
| 149 |
+
],
|
| 150 |
+
required_fields_by_action={
|
| 151 |
+
"inspect_code": [],
|
| 152 |
+
"classify_vulnerability": ["vulnerability_type"],
|
| 153 |
+
"apply_patch": ["patch_id"],
|
| 154 |
+
"verify_security_fix": [],
|
| 155 |
+
"submit_security_fix": [],
|
| 156 |
+
},
|
| 157 |
+
security_subquest_status="active",
|
| 158 |
+
security_context=SecurityContext(code_visible=True),
|
| 159 |
+
tool_output="Patch options: parameterized_query, strip_quotes, disable_login",
|
| 160 |
+
prompt_text="The login SQL query is vulnerable to SQL injection.",
|
| 161 |
+
)
|
| 162 |
+
action = inference.build_fallback_action(observation, history=[])
|
| 163 |
+
assert action == inference.UnifiedIncidentAction(
|
| 164 |
+
action_type="classify_vulnerability",
|
| 165 |
+
vulnerability_type="sql_injection",
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def test_build_policy_card_is_compact_and_stage_aware() -> None:
|
| 170 |
+
observation = make_observation(
|
| 171 |
+
workflow_stage="diagnosis",
|
| 172 |
+
allowed_actions=["query_logs", "query_metrics", "query_dependencies"],
|
| 173 |
+
valid_action_example={"action_type": "query_logs", "service": "database"},
|
| 174 |
+
)
|
| 175 |
+
state = inference.PolicyCardState(
|
| 176 |
+
schema_notes=[
|
| 177 |
+
inference.PolicyNote(
|
| 178 |
+
stage="diagnosis",
|
| 179 |
+
failure_type="invalid_model_output",
|
| 180 |
+
mistake="Previous output was not valid JSON.",
|
| 181 |
+
correction="Return exactly one JSON object.",
|
| 182 |
+
valid_example={"action_type": "query_logs", "service": "database"},
|
| 183 |
+
)
|
| 184 |
+
]
|
| 185 |
+
)
|
| 186 |
+
card = inference.build_policy_card(observation, state)
|
| 187 |
+
assert "STAGE: diagnosis" in card
|
| 188 |
+
assert "GOAL: find the most relevant next investigation step" in card
|
| 189 |
+
assert '"action_type":"query_logs"' in card
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_build_user_prompt_uses_policy_card_not_recent_history() -> None:
|
| 193 |
+
observation = make_observation()
|
| 194 |
+
prompt = inference.build_user_prompt(observation, "Session policy card:\n- Return JSON only.")
|
| 195 |
+
assert "Session policy card:" not in prompt
|
| 196 |
+
assert "RECENT_HISTORY" not in prompt
|
| 197 |
+
assert "Current stage: diagnosis" in prompt
|
| 198 |
+
assert "Current goal: find the most relevant next investigation step" in prompt
|
| 199 |
+
assert "Allowed actions:" in prompt
|
| 200 |
+
assert "Required fields:" in prompt
|
| 201 |
+
assert "Final score: 0.0000" in prompt
|
| 202 |
+
assert "Valid example:" in prompt
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def test_build_user_prompt_includes_full_security_code_context() -> None:
|
| 206 |
+
observation = make_observation(
|
| 207 |
+
workflow_stage="security_subquest",
|
| 208 |
+
allowed_actions=["classify_vulnerability", "apply_patch"],
|
| 209 |
+
required_fields_by_action={
|
| 210 |
+
"classify_vulnerability": ["vulnerability_type"],
|
| 211 |
+
"apply_patch": ["patch_id"],
|
| 212 |
+
},
|
| 213 |
+
security_context=SecurityContext(code_visible=True),
|
| 214 |
+
tool_output=(
|
| 215 |
+
"def build_export(filename):\n"
|
| 216 |
+
" cmd = '/usr/bin/zip /tmp/out.zip ' + filename\n"
|
| 217 |
+
" return subprocess.check_output(cmd, shell=True)\n"
|
| 218 |
+
"Patch options: avoid_shell, sanitize_quotes_only, disable_worker_commands"
|
| 219 |
+
),
|
| 220 |
+
valid_action_example={
|
| 221 |
+
"action_type": "classify_vulnerability",
|
| 222 |
+
"vulnerability_type": "command_injection",
|
| 223 |
+
},
|
| 224 |
+
)
|
| 225 |
+
prompt = inference.build_user_prompt(observation, "")
|
| 226 |
+
assert "Tool output:" in prompt
|
| 227 |
+
assert "subprocess.check_output" in prompt
|
| 228 |
+
assert "shell=True" in prompt
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def test_build_user_prompt_small_mode_extracts_policy_card_correction(monkeypatch) -> None:
|
| 232 |
+
monkeypatch.setenv("INFERENCE_MODE", "small")
|
| 233 |
+
observation = make_observation()
|
| 234 |
+
prompt = inference.build_user_prompt(
|
| 235 |
+
observation,
|
| 236 |
+
"LESSON: the previous action was wrong; do not repeat it",
|
| 237 |
+
)
|
| 238 |
+
assert "Previous action correction:" in prompt
|
| 239 |
+
assert "the previous action was wrong; do not repeat it" in prompt
|
| 240 |
+
assert "LESSON:" not in prompt
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def test_inference_mode_defaults_to_judge(monkeypatch) -> None:
|
| 244 |
+
monkeypatch.delenv("INFERENCE_MODE", raising=False)
|
| 245 |
+
assert inference._inference_mode() == "judge"
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def test_hard_scenario_switches_to_dependency_bridge_after_worker_evidence() -> None:
|
| 249 |
+
observation = make_observation(
|
| 250 |
+
workflow_stage="root_cause_analysis",
|
| 251 |
+
security_subquest_status="locked",
|
| 252 |
+
allowed_actions=["query_logs", "query_metrics", "query_dependencies"],
|
| 253 |
+
valid_action_example={"action_type": "query_logs", "service": "worker"},
|
| 254 |
+
)
|
| 255 |
+
history = [
|
| 256 |
+
{
|
| 257 |
+
"action": inference.UnifiedIncidentAction(
|
| 258 |
+
action_type="query_logs",
|
| 259 |
+
service="worker",
|
| 260 |
+
)
|
| 261 |
+
}
|
| 262 |
+
]
|
| 263 |
+
narrowed = inference._narrow_allowed_actions(
|
| 264 |
+
observation,
|
| 265 |
+
scenario_id="worker_bad_deploy_command_injection",
|
| 266 |
+
history=history,
|
| 267 |
+
)
|
| 268 |
+
assert narrowed == ["query_dependencies"]
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def test_hard_scenario_forces_worker_rollback_after_security_completion() -> None:
|
| 272 |
+
observation = make_observation(
|
| 273 |
+
workflow_stage="remediation",
|
| 274 |
+
security_subquest_status="completed",
|
| 275 |
+
allowed_actions=["restart_service", "rollback_deploy"],
|
| 276 |
+
service_health={
|
| 277 |
+
"api-gateway": ServiceHealth(
|
| 278 |
+
name="api-gateway",
|
| 279 |
+
status="degraded",
|
| 280 |
+
cpu_pct=50.0,
|
| 281 |
+
memory_pct=40.0,
|
| 282 |
+
error_rate_pct=10.0,
|
| 283 |
+
latency_ms=100.0,
|
| 284 |
+
),
|
| 285 |
+
"cache": ServiceHealth(
|
| 286 |
+
name="cache",
|
| 287 |
+
status="healthy",
|
| 288 |
+
cpu_pct=20.0,
|
| 289 |
+
memory_pct=20.0,
|
| 290 |
+
error_rate_pct=0.0,
|
| 291 |
+
latency_ms=10.0,
|
| 292 |
+
),
|
| 293 |
+
"database": ServiceHealth(
|
| 294 |
+
name="database",
|
| 295 |
+
status="degraded",
|
| 296 |
+
cpu_pct=60.0,
|
| 297 |
+
memory_pct=55.0,
|
| 298 |
+
error_rate_pct=15.0,
|
| 299 |
+
latency_ms=120.0,
|
| 300 |
+
),
|
| 301 |
+
"worker": ServiceHealth(
|
| 302 |
+
name="worker",
|
| 303 |
+
status="degraded",
|
| 304 |
+
cpu_pct=80.0,
|
| 305 |
+
memory_pct=70.0,
|
| 306 |
+
error_rate_pct=20.0,
|
| 307 |
+
latency_ms=200.0,
|
| 308 |
+
),
|
| 309 |
+
},
|
| 310 |
+
)
|
| 311 |
+
narrowed = inference._narrow_allowed_actions(
|
| 312 |
+
observation,
|
| 313 |
+
scenario_id="worker_bad_deploy_command_injection",
|
| 314 |
+
history=[],
|
| 315 |
+
)
|
| 316 |
+
assert narrowed == ["rollback_deploy"]
|
| 317 |
+
prompt = inference.build_user_prompt(
|
| 318 |
+
observation,
|
| 319 |
+
"Session policy card:\n- Return JSON only.",
|
| 320 |
+
scenario_id="worker_bad_deploy_command_injection",
|
| 321 |
+
history=[],
|
| 322 |
+
)
|
| 323 |
+
assert "Important transition hint:" in prompt
|
| 324 |
+
assert "rollback_deploy on worker" in prompt
|
unified_incident_env/tests/test_trainer.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for the model-agnostic trainer scaffold."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from unified_incident_env.scripts.baseline_agent import plan_for_scenario
|
| 9 |
+
from unified_incident_env.server.challenge import get_scenario
|
| 10 |
+
from unified_incident_env.server.environment import UnifiedIncidentEnvironment
|
| 11 |
+
from unified_incident_env.trainer.action_adapter import LenientActionAdapter, StrictActionParser
|
| 12 |
+
from unified_incident_env.trainer.build_sft_dataset import (
|
| 13 |
+
build_baseline_records,
|
| 14 |
+
build_replay_records,
|
| 15 |
+
)
|
| 16 |
+
from unified_incident_env.trainer.eval_models import summarize
|
| 17 |
+
from unified_incident_env.trainer.prompts import build_runtime_request
|
| 18 |
+
from unified_incident_env.trainer.run_episode import EpisodeRunner
|
| 19 |
+
from unified_incident_env.trainer.trajectory_memory import CorrectionMemory, MemoryExample
|
| 20 |
+
from unified_incident_env.trainer.trajectory_store import TrajectoryStore
|
| 21 |
+
from unified_incident_env.trainer.types import EvalScenarioResult, ModelRequest, ModelResponse
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class SequenceBackend:
|
| 25 |
+
"""Test backend that returns pre-seeded outputs in order."""
|
| 26 |
+
|
| 27 |
+
def __init__(self, outputs: list[str]) -> None:
|
| 28 |
+
self.outputs = outputs
|
| 29 |
+
self.index = 0
|
| 30 |
+
|
| 31 |
+
def complete(self, request: ModelRequest) -> ModelResponse:
|
| 32 |
+
del request
|
| 33 |
+
output = self.outputs[self.index]
|
| 34 |
+
self.index += 1
|
| 35 |
+
return ModelResponse(raw_text=output, latency_s=0.01)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _action_jsons(scenario_id: str) -> list[str]:
|
| 39 |
+
return [
|
| 40 |
+
json.dumps(action.model_dump(exclude_none=True))
|
| 41 |
+
for action in plan_for_scenario(scenario_id)
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_strict_parser_rejects_extra_keys_and_missing_fields() -> None:
|
| 46 |
+
parser = StrictActionParser()
|
| 47 |
+
|
| 48 |
+
extra = parser.parse(
|
| 49 |
+
'{"action_type":"query_logs","service":"database","reason":"because"}'
|
| 50 |
+
)
|
| 51 |
+
assert extra.parse_status == "repaired"
|
| 52 |
+
assert extra.cleaned_action == {
|
| 53 |
+
"action_type": "query_logs",
|
| 54 |
+
"service": "database",
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
missing = parser.parse('{"action_type":"query_metrics","service":"database"}')
|
| 58 |
+
assert missing.parse_status == "invalid_action"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_lenient_parser_repairs_small_schema_issues_only() -> None:
|
| 62 |
+
parser = LenientActionAdapter()
|
| 63 |
+
|
| 64 |
+
repaired = parser.parse(
|
| 65 |
+
'{"action_type":"inspect_code","reason":"need context"}'
|
| 66 |
+
)
|
| 67 |
+
assert repaired.parse_status == "repaired"
|
| 68 |
+
assert repaired.cleaned_action == {"action_type": "inspect_code"}
|
| 69 |
+
|
| 70 |
+
metric_repaired = parser.parse(
|
| 71 |
+
'{"action_type":"query_metrics","service":"database","metrics":["cpu"]}'
|
| 72 |
+
)
|
| 73 |
+
assert metric_repaired.parse_status == "repaired"
|
| 74 |
+
assert metric_repaired.cleaned_action == {
|
| 75 |
+
"action_type": "query_metrics",
|
| 76 |
+
"service": "database",
|
| 77 |
+
"metric": "cpu",
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
action_alias = parser.parse('{"action":"inspect_code"}')
|
| 81 |
+
assert action_alias.parse_status == "repaired"
|
| 82 |
+
assert action_alias.cleaned_action == {"action_type": "inspect_code"}
|
| 83 |
+
|
| 84 |
+
vuln_alias = parser.parse(
|
| 85 |
+
'{"action_type":"classify_vulnerability","vulnerability":"sql_injection"}'
|
| 86 |
+
)
|
| 87 |
+
assert vuln_alias.parse_status == "repaired"
|
| 88 |
+
assert vuln_alias.cleaned_action == {
|
| 89 |
+
"action_type": "classify_vulnerability",
|
| 90 |
+
"vulnerability_type": "sql_injection",
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
bare_action = parser.parse("inspect_code")
|
| 94 |
+
assert bare_action.parse_status == "repaired"
|
| 95 |
+
assert bare_action.cleaned_action == {"action_type": "inspect_code"}
|
| 96 |
+
|
| 97 |
+
invalid = parser.parse(
|
| 98 |
+
'{"action_type":"classify_vulnerability","services":["cache"]}'
|
| 99 |
+
)
|
| 100 |
+
assert invalid.parse_status == "invalid_action"
|
| 101 |
+
|
| 102 |
+
ambiguous = parser.parse(
|
| 103 |
+
'{"action_type":"query_metrics","service":"database","metrics":["cpu","memory"]}'
|
| 104 |
+
)
|
| 105 |
+
assert ambiguous.parse_status == "invalid_action"
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_episode_runner_records_successful_strict_episode() -> None:
|
| 109 |
+
runner = EpisodeRunner(
|
| 110 |
+
backend=SequenceBackend(_action_jsons("database_sqli_outage")),
|
| 111 |
+
parser=StrictActionParser(),
|
| 112 |
+
model_name="stub-model",
|
| 113 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
record = runner.run("database_sqli_outage", mode="strict")
|
| 117 |
+
assert record.success is True
|
| 118 |
+
assert record.steps == len(plan_for_scenario("database_sqli_outage"))
|
| 119 |
+
assert record.final_score > 0.5
|
| 120 |
+
assert all(step.parse_status in {"ok", "repaired"} for step in record.step_records)
|
| 121 |
+
assert all(step.structured_mode_used == "backend_adaptive" for step in record.step_records)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def test_episode_runner_stops_on_parse_failure() -> None:
|
| 125 |
+
runner = EpisodeRunner(
|
| 126 |
+
backend=SequenceBackend(["- inspect_code"]),
|
| 127 |
+
parser=StrictActionParser(),
|
| 128 |
+
model_name="stub-model",
|
| 129 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
record = runner.run("database_sqli_outage", mode="strict")
|
| 133 |
+
assert record.success is False
|
| 134 |
+
assert record.failure_reason == "parse_failure:invalid_json"
|
| 135 |
+
assert record.steps == 0
|
| 136 |
+
assert record.step_records[0].parse_status == "invalid_json"
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_lenient_runner_rescues_extra_keys_but_not_logic() -> None:
|
| 140 |
+
outputs = []
|
| 141 |
+
for payload in _action_jsons("database_sqli_outage"):
|
| 142 |
+
data = json.loads(payload)
|
| 143 |
+
data["reason"] = "extra explanation"
|
| 144 |
+
outputs.append(json.dumps(data))
|
| 145 |
+
|
| 146 |
+
runner = EpisodeRunner(
|
| 147 |
+
backend=SequenceBackend(outputs),
|
| 148 |
+
parser=LenientActionAdapter(),
|
| 149 |
+
model_name="stub-model",
|
| 150 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 151 |
+
)
|
| 152 |
+
record = runner.run("database_sqli_outage", mode="lenient")
|
| 153 |
+
assert record.success is True
|
| 154 |
+
assert any(step.parse_status == "repaired" for step in record.step_records)
|
| 155 |
+
|
| 156 |
+
bad_runner = EpisodeRunner(
|
| 157 |
+
backend=SequenceBackend(
|
| 158 |
+
[
|
| 159 |
+
'{"action_type":"classify_vulnerability","services":["cache"]}',
|
| 160 |
+
'{"action_type":"classify_vulnerability","services":["cache"]}',
|
| 161 |
+
*[
|
| 162 |
+
json.dumps(action.model_dump(exclude_none=True))
|
| 163 |
+
for action in plan_for_scenario("database_sqli_outage")[1:]
|
| 164 |
+
],
|
| 165 |
+
]
|
| 166 |
+
),
|
| 167 |
+
parser=LenientActionAdapter(),
|
| 168 |
+
model_name="stub-model",
|
| 169 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 170 |
+
)
|
| 171 |
+
bad_record = bad_runner.run("database_sqli_outage", mode="lenient")
|
| 172 |
+
assert bad_record.success is True
|
| 173 |
+
assert bad_record.teacher_override_count >= 1
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def test_lenient_runner_uses_repair_retry() -> None:
|
| 177 |
+
plan = plan_for_scenario("database_sqli_outage")
|
| 178 |
+
outputs = [
|
| 179 |
+
"- invalid",
|
| 180 |
+
json.dumps(plan[0].model_dump(exclude_none=True)),
|
| 181 |
+
*[
|
| 182 |
+
json.dumps(action.model_dump(exclude_none=True))
|
| 183 |
+
for action in plan[1:]
|
| 184 |
+
],
|
| 185 |
+
]
|
| 186 |
+
runner = EpisodeRunner(
|
| 187 |
+
backend=SequenceBackend(outputs),
|
| 188 |
+
parser=LenientActionAdapter(),
|
| 189 |
+
model_name="stub-model",
|
| 190 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 191 |
+
)
|
| 192 |
+
record = runner.run("database_sqli_outage", mode="lenient")
|
| 193 |
+
assert record.success is True
|
| 194 |
+
assert record.repair_retry_count >= 1
|
| 195 |
+
assert record.step_records[0].repair_retry_used is True
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def test_lenient_runner_uses_teacher_override_after_repeated_no_progress() -> None:
|
| 199 |
+
outputs = [
|
| 200 |
+
json.dumps({"action_type": "restart_service", "service": "database"})
|
| 201 |
+
for _ in range(12)
|
| 202 |
+
]
|
| 203 |
+
runner = EpisodeRunner(
|
| 204 |
+
backend=SequenceBackend(outputs),
|
| 205 |
+
parser=LenientActionAdapter(),
|
| 206 |
+
model_name="stub-model",
|
| 207 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 208 |
+
)
|
| 209 |
+
record = runner.run("database_sqli_outage", mode="lenient")
|
| 210 |
+
assert record.teacher_override_count >= 1
|
| 211 |
+
assert any(step.teacher_override_used for step in record.step_records)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def test_baseline_dataset_builder_emits_all_teacher_steps() -> None:
|
| 215 |
+
records = build_baseline_records()
|
| 216 |
+
assert len(records) == sum(
|
| 217 |
+
len(plan_for_scenario(scenario_id)) for scenario_id in (
|
| 218 |
+
"database_sqli_outage",
|
| 219 |
+
"cache_abuse_broken_access_control",
|
| 220 |
+
"worker_bad_deploy_command_injection",
|
| 221 |
+
)
|
| 222 |
+
)
|
| 223 |
+
assert {record.source for record in records} == {"baseline"}
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def test_prompt_builder_is_stage_specific() -> None:
|
| 227 |
+
env = UnifiedIncidentEnvironment()
|
| 228 |
+
obs = env.reset(scenario_id="database_sqli_outage")
|
| 229 |
+
system_prompt, user_prompt, response_format = build_runtime_request(obs)
|
| 230 |
+
assert "Return exactly one JSON object and nothing else." in system_prompt
|
| 231 |
+
assert "Allowed actions:" not in system_prompt
|
| 232 |
+
assert "Current stage: diagnosis" in user_prompt
|
| 233 |
+
assert "Current goal: find the most relevant next investigation step" in user_prompt
|
| 234 |
+
assert "Allowed actions:" in user_prompt
|
| 235 |
+
assert "- query_logs" in user_prompt
|
| 236 |
+
assert "- inspect_code" not in user_prompt
|
| 237 |
+
assert "Final score: 0.0000" in user_prompt
|
| 238 |
+
assert "Valid example:" in user_prompt
|
| 239 |
+
assert response_format["type"] == "json_schema"
|
| 240 |
+
assert response_format["json_schema"]["strict"] is True
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def test_prompt_builder_keeps_security_code_context() -> None:
|
| 244 |
+
env = UnifiedIncidentEnvironment()
|
| 245 |
+
obs = env.reset(scenario_id="worker_bad_deploy_command_injection")
|
| 246 |
+
obs = env.step({"action_type": "query_logs", "service": "worker"})
|
| 247 |
+
obs = env.step({"action_type": "inspect_code"})
|
| 248 |
+
system_prompt, user_prompt, _response_format = build_runtime_request(obs)
|
| 249 |
+
assert "Return exactly one JSON object and nothing else." in system_prompt
|
| 250 |
+
assert "subprocess.check_output" in user_prompt
|
| 251 |
+
assert "shell=True" in user_prompt
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def test_correction_memory_builds_prompt_addendum() -> None:
|
| 255 |
+
strict_runner = EpisodeRunner(
|
| 256 |
+
backend=SequenceBackend(["- inspect_code"]),
|
| 257 |
+
parser=StrictActionParser(),
|
| 258 |
+
model_name="stub-model",
|
| 259 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 260 |
+
)
|
| 261 |
+
bad_record = strict_runner.run("database_sqli_outage", mode="strict")
|
| 262 |
+
from unified_incident_env.trainer.analyze_failures import analyze_episode
|
| 263 |
+
analysis = analyze_episode(bad_record)
|
| 264 |
+
memory = CorrectionMemory()
|
| 265 |
+
memory.add_episode_examples(bad_record, analysis)
|
| 266 |
+
addendum = memory.build_prompt_addendum("database_sqli_outage", "diagnosis")
|
| 267 |
+
assert "Schema rules:" in addendum
|
| 268 |
+
assert "Episode lessons:" in addendum
|
| 269 |
+
assert "query_logs" in addendum
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def test_correction_memory_prefers_same_scenario_then_falls_back() -> None:
|
| 273 |
+
memory = CorrectionMemory()
|
| 274 |
+
memory.schema_examples["database_sqli_outage"] = []
|
| 275 |
+
|
| 276 |
+
memory.schema_examples["cache_abuse_broken_access_control"] = [
|
| 277 |
+
MemoryExample(
|
| 278 |
+
scenario_id="cache_abuse_broken_access_control",
|
| 279 |
+
stage="diagnosis",
|
| 280 |
+
prompt_text="cache prompt",
|
| 281 |
+
raw_output="bad",
|
| 282 |
+
corrected_action={"action_type": "query_metrics", "service": "cache", "metric": "cpu"},
|
| 283 |
+
failure_type="invalid_json",
|
| 284 |
+
bucket="schema",
|
| 285 |
+
action_family="investigate",
|
| 286 |
+
mistake="Bad JSON.",
|
| 287 |
+
correction="Return JSON only.",
|
| 288 |
+
)
|
| 289 |
+
]
|
| 290 |
+
addendum = memory.build_prompt_addendum("database_sqli_outage", "diagnosis")
|
| 291 |
+
assert "query_metrics" in addendum
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def test_replay_dataset_includes_teacher_and_student_actions(tmp_path: Path) -> None:
|
| 295 |
+
runner = EpisodeRunner(
|
| 296 |
+
backend=SequenceBackend(_action_jsons("database_sqli_outage")),
|
| 297 |
+
parser=StrictActionParser(),
|
| 298 |
+
model_name="stub-model",
|
| 299 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 300 |
+
)
|
| 301 |
+
record = runner.run("database_sqli_outage", mode="strict")
|
| 302 |
+
store = TrajectoryStore(tmp_path / "episodes.jsonl")
|
| 303 |
+
store.append_episode(record)
|
| 304 |
+
|
| 305 |
+
replay_rows = build_replay_records(tmp_path / "episodes.jsonl")
|
| 306 |
+
assert replay_rows
|
| 307 |
+
assert replay_rows[0].target_action is not None
|
| 308 |
+
assert replay_rows[0].student_action is not None
|
| 309 |
+
assert replay_rows[0].parse_status in {"ok", "repaired"}
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def test_eval_summary_reports_success_and_schema_failure_rates() -> None:
|
| 313 |
+
summary = summarize(
|
| 314 |
+
[
|
| 315 |
+
EvalScenarioResult(
|
| 316 |
+
model_name="m1",
|
| 317 |
+
scenario_id="database_sqli_outage",
|
| 318 |
+
success=True,
|
| 319 |
+
final_score=0.9,
|
| 320 |
+
failure_reason=None,
|
| 321 |
+
schema_failure=False,
|
| 322 |
+
elapsed_s=1.0,
|
| 323 |
+
),
|
| 324 |
+
EvalScenarioResult(
|
| 325 |
+
model_name="m1",
|
| 326 |
+
scenario_id="cache_abuse_broken_access_control",
|
| 327 |
+
success=False,
|
| 328 |
+
final_score=0.1,
|
| 329 |
+
failure_reason="parse_failure:invalid_json",
|
| 330 |
+
schema_failure=True,
|
| 331 |
+
elapsed_s=1.0,
|
| 332 |
+
),
|
| 333 |
+
],
|
| 334 |
+
mode="strict",
|
| 335 |
+
)
|
| 336 |
+
assert summary.success_rate == 0.5
|
| 337 |
+
assert summary.avg_score == 0.5
|
| 338 |
+
assert summary.schema_failure_rate == 0.5
|
| 339 |
+
assert summary.by_model["m1"]["success_rate"] == 0.5
|
unified_incident_env/tests/test_trainer_session.py
ADDED
|
@@ -0,0 +1,545 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for the ten-episode session loop."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from unified_incident_env.scripts.baseline_agent import plan_for_scenario
|
| 9 |
+
from unified_incident_env.server.environment import UnifiedIncidentEnvironment
|
| 10 |
+
from unified_incident_env.trainer.action_adapter import StrictActionParser
|
| 11 |
+
from unified_incident_env.trainer.analyze_failures import analyze_episode
|
| 12 |
+
from unified_incident_env.trainer.build_datasets import (
|
| 13 |
+
build_next_action_records,
|
| 14 |
+
build_recovery_records,
|
| 15 |
+
build_schema_repair_records,
|
| 16 |
+
)
|
| 17 |
+
from unified_incident_env.trainer.collect_trajectory import collect_episode
|
| 18 |
+
from unified_incident_env.trainer.run_episode import EpisodeRunner
|
| 19 |
+
from unified_incident_env.trainer.run_session import run_session
|
| 20 |
+
from unified_incident_env.trainer.session_config import default_phases, default_scenario_schedule, make_session_config
|
| 21 |
+
from unified_incident_env.trainer.types import ModelRequest, ModelResponse, UpdateRequest
|
| 22 |
+
from unified_incident_env.trainer.update_model import (
|
| 23 |
+
ExternalCommandUpdater,
|
| 24 |
+
NoOpUpdater,
|
| 25 |
+
OpenAIFineTuneUpdater,
|
| 26 |
+
build_updater,
|
| 27 |
+
)
|
| 28 |
+
from unified_incident_env.trainer.train_external import build_policy_adapter
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class SequenceBackend:
|
| 32 |
+
"""Backend that returns pre-seeded outputs in order."""
|
| 33 |
+
|
| 34 |
+
def __init__(self, outputs: list[str]) -> None:
|
| 35 |
+
self.outputs = outputs
|
| 36 |
+
self.index = 0
|
| 37 |
+
|
| 38 |
+
def complete(self, request: ModelRequest) -> ModelResponse:
|
| 39 |
+
del request
|
| 40 |
+
output = self.outputs[self.index]
|
| 41 |
+
self.index += 1
|
| 42 |
+
return ModelResponse(raw_text=output, latency_s=0.01)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _action_jsons(scenario_id: str) -> list[str]:
|
| 46 |
+
return [
|
| 47 |
+
json.dumps(action.model_dump(exclude_none=True))
|
| 48 |
+
for action in plan_for_scenario(scenario_id)
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_default_session_schedule_and_phases() -> None:
|
| 53 |
+
schedule = default_scenario_schedule()
|
| 54 |
+
assert len(schedule) == 10
|
| 55 |
+
assert schedule[:4] == [
|
| 56 |
+
"database_sqli_outage",
|
| 57 |
+
"cache_abuse_broken_access_control",
|
| 58 |
+
"worker_bad_deploy_command_injection",
|
| 59 |
+
"database_sqli_outage",
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
phases = default_phases()
|
| 63 |
+
assert [phase.episode_ids for phase in phases] == [
|
| 64 |
+
[1, 2],
|
| 65 |
+
[3, 4, 5],
|
| 66 |
+
[6, 7, 8],
|
| 67 |
+
[9, 10],
|
| 68 |
+
]
|
| 69 |
+
assert [phase.update_index for phase in phases] == [1, 2, 3, None]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_session_config_modes_default_correctly() -> None:
|
| 73 |
+
competition = make_session_config(
|
| 74 |
+
model_name="stub-model",
|
| 75 |
+
output_root="/tmp/trainer-tests",
|
| 76 |
+
base_url=None,
|
| 77 |
+
api_base_url="http://stub.local/v1",
|
| 78 |
+
api_key="local",
|
| 79 |
+
)
|
| 80 |
+
assert competition.runtime_mode == "competition"
|
| 81 |
+
assert competition.log_rendered_prompts is False
|
| 82 |
+
assert competition.updater_backend == "external_command"
|
| 83 |
+
|
| 84 |
+
research = make_session_config(
|
| 85 |
+
model_name="stub-model",
|
| 86 |
+
output_root="/tmp/trainer-tests",
|
| 87 |
+
base_url=None,
|
| 88 |
+
api_base_url="http://stub.local/v1",
|
| 89 |
+
api_key="local",
|
| 90 |
+
runtime_mode="research",
|
| 91 |
+
updater_backend="openai_finetune",
|
| 92 |
+
)
|
| 93 |
+
assert research.runtime_mode == "research"
|
| 94 |
+
assert research.log_rendered_prompts is True
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_collect_episode_populates_summary_and_analysis() -> None:
|
| 98 |
+
runner = EpisodeRunner(
|
| 99 |
+
backend=SequenceBackend(_action_jsons("database_sqli_outage")),
|
| 100 |
+
parser=StrictActionParser(),
|
| 101 |
+
model_name="stub-model",
|
| 102 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 103 |
+
)
|
| 104 |
+
record, summary, analysis = collect_episode(
|
| 105 |
+
runner=runner,
|
| 106 |
+
scenario_id="database_sqli_outage",
|
| 107 |
+
episode_id=1,
|
| 108 |
+
mode="strict",
|
| 109 |
+
model_version="stub-model",
|
| 110 |
+
)
|
| 111 |
+
assert record.success is True
|
| 112 |
+
assert summary.success is True
|
| 113 |
+
assert summary.schema_failures == 0
|
| 114 |
+
assert analysis.summary["schema"] == 0
|
| 115 |
+
assert record.episode_id == 1
|
| 116 |
+
assert record.step_records[0].step_index == 1
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_analyze_failures_buckets_schema_policy_and_looping() -> None:
|
| 120 |
+
strict_parser = StrictActionParser()
|
| 121 |
+
bad_runner = EpisodeRunner(
|
| 122 |
+
backend=SequenceBackend(["- inspect_code"]),
|
| 123 |
+
parser=strict_parser,
|
| 124 |
+
model_name="stub-model",
|
| 125 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 126 |
+
)
|
| 127 |
+
bad_record = bad_runner.run(
|
| 128 |
+
"database_sqli_outage",
|
| 129 |
+
mode="strict",
|
| 130 |
+
episode_id=1,
|
| 131 |
+
model_version="stub-model",
|
| 132 |
+
)
|
| 133 |
+
bad_analysis = analyze_episode(bad_record)
|
| 134 |
+
assert "invalid_json" in bad_analysis.schema_failures
|
| 135 |
+
|
| 136 |
+
wrong_outputs = [
|
| 137 |
+
json.dumps({"action_type": "restart_service", "service": "database"})
|
| 138 |
+
for _ in range(10)
|
| 139 |
+
]
|
| 140 |
+
wrong_runner = EpisodeRunner(
|
| 141 |
+
backend=SequenceBackend(wrong_outputs),
|
| 142 |
+
parser=strict_parser,
|
| 143 |
+
model_name="stub-model",
|
| 144 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 145 |
+
)
|
| 146 |
+
wrong_record = wrong_runner.run(
|
| 147 |
+
"database_sqli_outage",
|
| 148 |
+
mode="strict",
|
| 149 |
+
episode_id=2,
|
| 150 |
+
model_version="stub-model",
|
| 151 |
+
)
|
| 152 |
+
wrong_analysis = analyze_episode(wrong_record)
|
| 153 |
+
assert "infra_before_security" in wrong_analysis.policy_failures
|
| 154 |
+
assert "repeated_same_action" in wrong_analysis.looping_failures
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def test_dataset_builders_emit_schema_next_action_and_recovery_rows() -> None:
|
| 158 |
+
strict_parser = StrictActionParser()
|
| 159 |
+
good_runner = EpisodeRunner(
|
| 160 |
+
backend=SequenceBackend(_action_jsons("database_sqli_outage")),
|
| 161 |
+
parser=strict_parser,
|
| 162 |
+
model_name="stub-model",
|
| 163 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 164 |
+
)
|
| 165 |
+
good_record = good_runner.run(
|
| 166 |
+
"database_sqli_outage",
|
| 167 |
+
mode="strict",
|
| 168 |
+
episode_id=1,
|
| 169 |
+
model_version="stub-model",
|
| 170 |
+
)
|
| 171 |
+
good_analysis = analyze_episode(good_record)
|
| 172 |
+
|
| 173 |
+
bad_runner = EpisodeRunner(
|
| 174 |
+
backend=SequenceBackend(["- inspect_code"]),
|
| 175 |
+
parser=strict_parser,
|
| 176 |
+
model_name="stub-model",
|
| 177 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 178 |
+
)
|
| 179 |
+
bad_record = bad_runner.run(
|
| 180 |
+
"database_sqli_outage",
|
| 181 |
+
mode="strict",
|
| 182 |
+
episode_id=2,
|
| 183 |
+
model_version="stub-model",
|
| 184 |
+
)
|
| 185 |
+
bad_analysis = analyze_episode(bad_record)
|
| 186 |
+
|
| 187 |
+
wrong_runner = EpisodeRunner(
|
| 188 |
+
backend=SequenceBackend(
|
| 189 |
+
[json.dumps({"action_type": "restart_service", "service": "database"}) for _ in range(10)]
|
| 190 |
+
),
|
| 191 |
+
parser=strict_parser,
|
| 192 |
+
model_name="stub-model",
|
| 193 |
+
env_factory=UnifiedIncidentEnvironment,
|
| 194 |
+
)
|
| 195 |
+
wrong_record = wrong_runner.run(
|
| 196 |
+
"database_sqli_outage",
|
| 197 |
+
mode="strict",
|
| 198 |
+
episode_id=3,
|
| 199 |
+
model_version="stub-model",
|
| 200 |
+
)
|
| 201 |
+
wrong_analysis = analyze_episode(wrong_record)
|
| 202 |
+
|
| 203 |
+
schema_rows = build_schema_repair_records([bad_record], [bad_analysis])
|
| 204 |
+
next_rows = build_next_action_records([wrong_record], [wrong_analysis])
|
| 205 |
+
recovery_rows = build_recovery_records([wrong_record], [wrong_analysis])
|
| 206 |
+
|
| 207 |
+
assert schema_rows
|
| 208 |
+
assert schema_rows[0].source == "schema_repair"
|
| 209 |
+
assert next_rows
|
| 210 |
+
assert next_rows[0].source == "next_action"
|
| 211 |
+
assert recovery_rows
|
| 212 |
+
assert recovery_rows[0].source == "recovery"
|
| 213 |
+
assert good_analysis.summary["schema"] == 0
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def test_updaters_write_manifests(tmp_path: Path) -> None:
|
| 217 |
+
request = UpdateRequest(
|
| 218 |
+
update_index=1,
|
| 219 |
+
phase_name="probe",
|
| 220 |
+
episodes_used=[1, 2],
|
| 221 |
+
datasets_used=["schema_repair.jsonl"],
|
| 222 |
+
model_before="stub-model",
|
| 223 |
+
output_dir=str(tmp_path / "checkpoints"),
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
noop = NoOpUpdater().update(request)
|
| 227 |
+
assert noop.status == "noop"
|
| 228 |
+
assert Path(noop.artifact_paths[0]).exists()
|
| 229 |
+
assert Path(noop.artifact_paths[1]).exists()
|
| 230 |
+
|
| 231 |
+
command = (
|
| 232 |
+
"python -c \"from pathlib import Path; "
|
| 233 |
+
f"Path(r'{tmp_path / 'checkpoints_ext' / 'marker.txt'}').parent.mkdir(parents=True, exist_ok=True); "
|
| 234 |
+
f"Path(r'{tmp_path / 'checkpoints_ext' / 'marker.txt'}').write_text('ok')\""
|
| 235 |
+
)
|
| 236 |
+
ext_request = request.model_copy(
|
| 237 |
+
update={
|
| 238 |
+
"update_index": 2,
|
| 239 |
+
"output_dir": str(tmp_path / "checkpoints_ext"),
|
| 240 |
+
}
|
| 241 |
+
)
|
| 242 |
+
external = ExternalCommandUpdater(command).update(ext_request)
|
| 243 |
+
assert external.status == "completed"
|
| 244 |
+
assert Path(tmp_path / "checkpoints_ext" / "marker.txt").exists()
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def test_build_policy_adapter_reads_phase_datasets(tmp_path: Path) -> None:
|
| 248 |
+
update_dir = tmp_path / "update_01"
|
| 249 |
+
update_dir.mkdir(parents=True, exist_ok=True)
|
| 250 |
+
schema_row = {
|
| 251 |
+
"scenario_id": "database_sqli_outage",
|
| 252 |
+
"messages": [{"role": "system", "content": "x"}, {"role": "user", "content": "prompt"}],
|
| 253 |
+
"target_action": {"action_type": "query_logs", "service": "database"},
|
| 254 |
+
"metadata": {"workflow_stage": "diagnosis"},
|
| 255 |
+
}
|
| 256 |
+
(update_dir / "schema_repair.jsonl").write_text(json.dumps(schema_row) + "\n", encoding="utf-8")
|
| 257 |
+
(update_dir / "next_action.jsonl").write_text(json.dumps(schema_row) + "\n", encoding="utf-8")
|
| 258 |
+
(update_dir / "recovery.jsonl").write_text(json.dumps(schema_row) + "\n", encoding="utf-8")
|
| 259 |
+
request = UpdateRequest(
|
| 260 |
+
update_index=1,
|
| 261 |
+
phase_name="probe",
|
| 262 |
+
episodes_used=[1, 2],
|
| 263 |
+
datasets_used=[],
|
| 264 |
+
model_before="qwen2.5:3b",
|
| 265 |
+
output_dir=str(update_dir),
|
| 266 |
+
)
|
| 267 |
+
adapter = build_policy_adapter(request)
|
| 268 |
+
assert adapter.base_model == "qwen2.5:3b"
|
| 269 |
+
assert len(adapter.schema_examples) == 1
|
| 270 |
+
assert len(adapter.next_action_examples) == 1
|
| 271 |
+
assert len(adapter.recovery_examples) == 0
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def test_build_updater_rejects_openai_finetune_in_competition_mode() -> None:
|
| 275 |
+
try:
|
| 276 |
+
build_updater(
|
| 277 |
+
"openai_finetune",
|
| 278 |
+
runtime_mode="competition",
|
| 279 |
+
openai_base_url="https://api.openai.com/v1",
|
| 280 |
+
api_key="sk-test",
|
| 281 |
+
)
|
| 282 |
+
except ValueError as exc:
|
| 283 |
+
assert "research mode" in str(exc)
|
| 284 |
+
else:
|
| 285 |
+
raise AssertionError("expected competition-mode rejection")
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def test_openai_finetune_updater_is_mockable_in_research_mode(tmp_path: Path) -> None:
|
| 289 |
+
class FakeFiles:
|
| 290 |
+
def create(self, file, purpose):
|
| 291 |
+
assert purpose == "fine-tune"
|
| 292 |
+
return type("FileObj", (), {"id": "file-123"})()
|
| 293 |
+
|
| 294 |
+
class FakeJobs:
|
| 295 |
+
def __init__(self) -> None:
|
| 296 |
+
self.calls = 0
|
| 297 |
+
|
| 298 |
+
def create(self, training_file, model, suffix=None):
|
| 299 |
+
assert training_file == "file-123"
|
| 300 |
+
assert model == "base-model"
|
| 301 |
+
assert suffix == "probe-01"
|
| 302 |
+
return type("JobObj", (), {"id": "job-123", "status": "queued"})()
|
| 303 |
+
|
| 304 |
+
def retrieve(self, job_id):
|
| 305 |
+
assert job_id == "job-123"
|
| 306 |
+
self.calls += 1
|
| 307 |
+
return type(
|
| 308 |
+
"JobObj",
|
| 309 |
+
(),
|
| 310 |
+
{"id": "job-123", "status": "succeeded", "fine_tuned_model": "ft:model-123"},
|
| 311 |
+
)()
|
| 312 |
+
|
| 313 |
+
class FakeFineTuning:
|
| 314 |
+
def __init__(self) -> None:
|
| 315 |
+
self.jobs = FakeJobs()
|
| 316 |
+
|
| 317 |
+
class FakeClient:
|
| 318 |
+
def __init__(self) -> None:
|
| 319 |
+
self.files = FakeFiles()
|
| 320 |
+
self.fine_tuning = FakeFineTuning()
|
| 321 |
+
|
| 322 |
+
training_file = tmp_path / "train.jsonl"
|
| 323 |
+
training_file.write_text('{"messages":[],"completion":"{}"}\n', encoding="utf-8")
|
| 324 |
+
updater = OpenAIFineTuneUpdater(
|
| 325 |
+
base_url="https://api.openai.com/v1",
|
| 326 |
+
api_key="sk-test",
|
| 327 |
+
client=FakeClient(),
|
| 328 |
+
poll_interval_s=0.0,
|
| 329 |
+
timeout_s=1.0,
|
| 330 |
+
)
|
| 331 |
+
request = UpdateRequest(
|
| 332 |
+
update_index=1,
|
| 333 |
+
phase_name="probe",
|
| 334 |
+
episodes_used=[1, 2],
|
| 335 |
+
datasets_used=[str(training_file)],
|
| 336 |
+
model_before="base-model",
|
| 337 |
+
output_dir=str(tmp_path / "openai_update"),
|
| 338 |
+
runtime_mode="research",
|
| 339 |
+
training_file=str(training_file),
|
| 340 |
+
suffix="probe-01",
|
| 341 |
+
)
|
| 342 |
+
result = updater.update(request)
|
| 343 |
+
assert result.status == "completed"
|
| 344 |
+
assert result.model_after == "ft:model-123"
|
| 345 |
+
assert Path(tmp_path / "openai_update" / "update_01_result.json").exists()
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def test_run_session_executes_ten_episodes_and_three_updates(tmp_path: Path) -> None:
|
| 349 |
+
config = make_session_config(
|
| 350 |
+
model_name="stub-model",
|
| 351 |
+
output_root=tmp_path,
|
| 352 |
+
base_url=None,
|
| 353 |
+
api_base_url="http://stub.local/v1",
|
| 354 |
+
api_key="local",
|
| 355 |
+
updater_backend="noop",
|
| 356 |
+
)
|
| 357 |
+
outputs = []
|
| 358 |
+
for scenario_id in config.scenario_schedule:
|
| 359 |
+
outputs.extend(_action_jsons(scenario_id))
|
| 360 |
+
|
| 361 |
+
report = run_session(
|
| 362 |
+
config,
|
| 363 |
+
backend=SequenceBackend(outputs),
|
| 364 |
+
updater=NoOpUpdater(),
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
assert len(report.episode_summaries) == 10
|
| 368 |
+
assert [update.update_index for update in report.updates] == [1, 2, 3]
|
| 369 |
+
assert [phase.episode_ids for phase in report.phase_reports] == [
|
| 370 |
+
[1, 2],
|
| 371 |
+
[3, 4, 5],
|
| 372 |
+
[6, 7, 8],
|
| 373 |
+
[9, 10],
|
| 374 |
+
]
|
| 375 |
+
|
| 376 |
+
output_dir = Path(report.output_dir)
|
| 377 |
+
assert (output_dir / "episodes.jsonl").exists()
|
| 378 |
+
assert (output_dir / "summaries.json").exists()
|
| 379 |
+
assert (output_dir / "phase_delta.json").exists()
|
| 380 |
+
assert (output_dir / "final_report.json").exists()
|
| 381 |
+
assert (output_dir / "baseline_teacher_dataset.jsonl").exists()
|
| 382 |
+
assert (output_dir / "schema_repair.jsonl").exists()
|
| 383 |
+
assert (output_dir / "next_action.jsonl").exists()
|
| 384 |
+
assert (output_dir / "recovery.jsonl").exists()
|
| 385 |
+
assert (output_dir / "sft_dataset.jsonl").exists()
|
| 386 |
+
assert (output_dir / "checkpoints" / "update_01" / "update_01_result.json").exists()
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def test_run_session_uses_policy_adapter_model_version_on_successful_update(tmp_path: Path) -> None:
|
| 390 |
+
class SuccessfulUpdater:
|
| 391 |
+
def __init__(self) -> None:
|
| 392 |
+
self.calls = 0
|
| 393 |
+
|
| 394 |
+
def update(self, request: UpdateRequest):
|
| 395 |
+
self.calls += 1
|
| 396 |
+
adapter_path = Path(request.output_dir) / "policy_adapter.json"
|
| 397 |
+
adapter_path.write_text(
|
| 398 |
+
json.dumps(
|
| 399 |
+
{
|
| 400 |
+
"base_model": request.model_before,
|
| 401 |
+
"phase_name": request.phase_name,
|
| 402 |
+
"schema_examples": [],
|
| 403 |
+
"next_action_examples": [],
|
| 404 |
+
"recovery_examples": [],
|
| 405 |
+
}
|
| 406 |
+
),
|
| 407 |
+
encoding="utf-8",
|
| 408 |
+
)
|
| 409 |
+
return {
|
| 410 |
+
"update_index": request.update_index,
|
| 411 |
+
"phase_name": request.phase_name,
|
| 412 |
+
"updater_backend": "external_command",
|
| 413 |
+
"model_before": request.model_before,
|
| 414 |
+
"model_after": f"policy_adapter::{request.model_before}::{adapter_path}",
|
| 415 |
+
"status": "completed",
|
| 416 |
+
"episodes_used": request.episodes_used,
|
| 417 |
+
"datasets_used": request.datasets_used,
|
| 418 |
+
"artifact_paths": [str(adapter_path)],
|
| 419 |
+
"notes": "ok",
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
config = make_session_config(
|
| 423 |
+
model_name="stub-model",
|
| 424 |
+
output_root=tmp_path,
|
| 425 |
+
base_url=None,
|
| 426 |
+
api_base_url="http://stub.local/v1",
|
| 427 |
+
api_key="local",
|
| 428 |
+
updater_backend="external_command",
|
| 429 |
+
)
|
| 430 |
+
outputs = []
|
| 431 |
+
for scenario_id in config.scenario_schedule:
|
| 432 |
+
outputs.extend(_action_jsons(scenario_id))
|
| 433 |
+
|
| 434 |
+
report = run_session(
|
| 435 |
+
config,
|
| 436 |
+
backend=SequenceBackend(outputs),
|
| 437 |
+
updater=SuccessfulUpdater(),
|
| 438 |
+
)
|
| 439 |
+
later_versions = {
|
| 440 |
+
summary.episode_id: summary.model_version for summary in report.episode_summaries
|
| 441 |
+
}
|
| 442 |
+
assert later_versions[1] == "stub-model"
|
| 443 |
+
assert later_versions[3].startswith("policy_adapter::")
|
| 444 |
+
assert later_versions[6].startswith("policy_adapter::")
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def test_run_session_falls_back_to_previous_model_on_failed_update(tmp_path: Path) -> None:
|
| 448 |
+
class FailingUpdater:
|
| 449 |
+
def __init__(self) -> None:
|
| 450 |
+
self.calls = 0
|
| 451 |
+
|
| 452 |
+
def update(self, request: UpdateRequest):
|
| 453 |
+
self.calls += 1
|
| 454 |
+
return type(
|
| 455 |
+
"Result",
|
| 456 |
+
(),
|
| 457 |
+
{
|
| 458 |
+
"update_index": request.update_index,
|
| 459 |
+
"phase_name": request.phase_name,
|
| 460 |
+
"updater_backend": "external_command",
|
| 461 |
+
"model_before": request.model_before,
|
| 462 |
+
"model_after": "should-not-be-used",
|
| 463 |
+
"status": "failed",
|
| 464 |
+
"episodes_used": request.episodes_used,
|
| 465 |
+
"datasets_used": request.datasets_used,
|
| 466 |
+
"artifact_paths": [],
|
| 467 |
+
"notes": "intentional failure",
|
| 468 |
+
},
|
| 469 |
+
)()
|
| 470 |
+
|
| 471 |
+
config = make_session_config(
|
| 472 |
+
model_name="stub-model",
|
| 473 |
+
output_root=tmp_path,
|
| 474 |
+
base_url=None,
|
| 475 |
+
api_base_url="http://stub.local/v1",
|
| 476 |
+
api_key="local",
|
| 477 |
+
runtime_mode="competition",
|
| 478 |
+
updater_backend="noop",
|
| 479 |
+
)
|
| 480 |
+
outputs = []
|
| 481 |
+
for scenario_id in config.scenario_schedule:
|
| 482 |
+
outputs.extend(_action_jsons(scenario_id))
|
| 483 |
+
|
| 484 |
+
report = run_session(
|
| 485 |
+
config,
|
| 486 |
+
backend=SequenceBackend(outputs),
|
| 487 |
+
updater=FailingUpdater(),
|
| 488 |
+
)
|
| 489 |
+
final_versions = {
|
| 490 |
+
summary.episode_id: summary.model_version for summary in report.episode_summaries
|
| 491 |
+
}
|
| 492 |
+
assert final_versions[1] == "stub-model"
|
| 493 |
+
assert final_versions[10] == "stub-model"
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def test_competition_mode_redacts_prompts_in_written_episodes(tmp_path: Path) -> None:
|
| 497 |
+
config = make_session_config(
|
| 498 |
+
model_name="stub-model",
|
| 499 |
+
output_root=tmp_path,
|
| 500 |
+
base_url=None,
|
| 501 |
+
api_base_url="http://stub.local/v1",
|
| 502 |
+
api_key="local",
|
| 503 |
+
runtime_mode="competition",
|
| 504 |
+
log_rendered_prompts=False,
|
| 505 |
+
updater_backend="noop",
|
| 506 |
+
)
|
| 507 |
+
outputs = []
|
| 508 |
+
for scenario_id in config.scenario_schedule:
|
| 509 |
+
outputs.extend(_action_jsons(scenario_id))
|
| 510 |
+
|
| 511 |
+
report = run_session(
|
| 512 |
+
config,
|
| 513 |
+
backend=SequenceBackend(outputs),
|
| 514 |
+
updater=NoOpUpdater(),
|
| 515 |
+
)
|
| 516 |
+
output_dir = Path(report.output_dir)
|
| 517 |
+
first_line = (output_dir / "episodes.jsonl").read_text(encoding="utf-8").splitlines()[0]
|
| 518 |
+
stored = json.loads(first_line)
|
| 519 |
+
assert stored["step_records"][0]["prompt_text"] == ""
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def test_research_mode_keeps_prompts_in_written_episodes(tmp_path: Path) -> None:
|
| 523 |
+
config = make_session_config(
|
| 524 |
+
model_name="stub-model",
|
| 525 |
+
output_root=tmp_path,
|
| 526 |
+
base_url=None,
|
| 527 |
+
api_base_url="http://stub.local/v1",
|
| 528 |
+
api_key="local",
|
| 529 |
+
runtime_mode="research",
|
| 530 |
+
log_rendered_prompts=True,
|
| 531 |
+
updater_backend="noop",
|
| 532 |
+
)
|
| 533 |
+
outputs = []
|
| 534 |
+
for scenario_id in config.scenario_schedule:
|
| 535 |
+
outputs.extend(_action_jsons(scenario_id))
|
| 536 |
+
|
| 537 |
+
report = run_session(
|
| 538 |
+
config,
|
| 539 |
+
backend=SequenceBackend(outputs),
|
| 540 |
+
updater=NoOpUpdater(),
|
| 541 |
+
)
|
| 542 |
+
output_dir = Path(report.output_dir)
|
| 543 |
+
first_line = (output_dir / "episodes.jsonl").read_text(encoding="utf-8").splitlines()[0]
|
| 544 |
+
stored = json.loads(first_line)
|
| 545 |
+
assert stored["step_records"][0]["prompt_text"]
|
unified_incident_env/trainer/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training scaffold for unified incident environment."""
|
| 2 |
+
|
| 3 |
+
from .action_adapter import LenientActionAdapter, StrictActionParser
|
| 4 |
+
from .analyze_failures import analyze_block, analyze_episode
|
| 5 |
+
from .backend import OpenAICompatibleBackend
|
| 6 |
+
from .collect_trajectory import collect_episode
|
| 7 |
+
from .policy_adapter import PolicyAdapter
|
| 8 |
+
from .run_session import run_session
|
| 9 |
+
from .run_episode import EpisodeRunner, run_episode
|
| 10 |
+
from .train_external import build_policy_adapter
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"EpisodeRunner",
|
| 14 |
+
"LenientActionAdapter",
|
| 15 |
+
"OpenAICompatibleBackend",
|
| 16 |
+
"PolicyAdapter",
|
| 17 |
+
"StrictActionParser",
|
| 18 |
+
"analyze_block",
|
| 19 |
+
"analyze_episode",
|
| 20 |
+
"build_policy_adapter",
|
| 21 |
+
"collect_episode",
|
| 22 |
+
"run_episode",
|
| 23 |
+
"run_session",
|
| 24 |
+
]
|
unified_incident_env/trainer/action_adapter.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Strict and lenient action parsers for training and eval."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from ..models import ActionType, UnifiedIncidentAction
|
| 9 |
+
from .types import ParseResult
|
| 10 |
+
|
| 11 |
+
_ALLOWED_KEYS = {
|
| 12 |
+
"action_type",
|
| 13 |
+
"service",
|
| 14 |
+
"metric",
|
| 15 |
+
"vulnerability_type",
|
| 16 |
+
"patch_id",
|
| 17 |
+
"postmortem",
|
| 18 |
+
}
|
| 19 |
+
_KNOWN_ACTIONS: set[str] = {
|
| 20 |
+
"query_logs",
|
| 21 |
+
"query_metrics",
|
| 22 |
+
"query_dependencies",
|
| 23 |
+
"restart_service",
|
| 24 |
+
"rollback_deploy",
|
| 25 |
+
"inspect_code",
|
| 26 |
+
"classify_vulnerability",
|
| 27 |
+
"apply_patch",
|
| 28 |
+
"verify_security_fix",
|
| 29 |
+
"submit_security_fix",
|
| 30 |
+
"submit_postmortem",
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _extract_json_text(raw_text: str) -> str:
|
| 35 |
+
text = raw_text.strip()
|
| 36 |
+
if "```" in text:
|
| 37 |
+
parts = text.split("```")
|
| 38 |
+
if len(parts) >= 2:
|
| 39 |
+
text = parts[1]
|
| 40 |
+
if text.startswith("json"):
|
| 41 |
+
text = text[4:]
|
| 42 |
+
start = text.find("{")
|
| 43 |
+
end = text.rfind("}")
|
| 44 |
+
if start != -1 and end != -1 and start < end:
|
| 45 |
+
text = text[start : end + 1]
|
| 46 |
+
return text.strip()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _compact_action(action: UnifiedIncidentAction) -> dict[str, Any]:
|
| 50 |
+
payload = action.model_dump(exclude_none=True)
|
| 51 |
+
if payload.get("metadata") == {}:
|
| 52 |
+
payload.pop("metadata", None)
|
| 53 |
+
return payload
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class StrictActionParser:
|
| 57 |
+
"""Exact parser for judge-style evaluation."""
|
| 58 |
+
|
| 59 |
+
def parse(self, raw_text: str) -> ParseResult:
|
| 60 |
+
bare = raw_text.strip().strip('"').strip("'")
|
| 61 |
+
if bare in {"inspect_code", "verify_security_fix", "submit_security_fix"}:
|
| 62 |
+
action = UnifiedIncidentAction(action_type=bare)
|
| 63 |
+
return ParseResult(
|
| 64 |
+
parse_status="repaired",
|
| 65 |
+
cleaned_action=_compact_action(action),
|
| 66 |
+
repair_labels=["bare_action_wrapped"],
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
data = json.loads(_extract_json_text(raw_text))
|
| 71 |
+
except Exception as exc:
|
| 72 |
+
return ParseResult(parse_status="invalid_json", error=type(exc).__name__)
|
| 73 |
+
|
| 74 |
+
if not isinstance(data, dict):
|
| 75 |
+
return ParseResult(parse_status="invalid_action", error="root must be object")
|
| 76 |
+
|
| 77 |
+
repaired_labels: list[str] = []
|
| 78 |
+
cleaned: dict[str, Any] = {k: v for k, v in data.items() if k in _ALLOWED_KEYS}
|
| 79 |
+
repaired = cleaned != data
|
| 80 |
+
if repaired:
|
| 81 |
+
repaired_labels.append("extra_keys_stripped")
|
| 82 |
+
|
| 83 |
+
if "action_type" not in cleaned and isinstance(data.get("action"), str):
|
| 84 |
+
if data["action"] in _KNOWN_ACTIONS:
|
| 85 |
+
cleaned["action_type"] = data["action"]
|
| 86 |
+
repaired = True
|
| 87 |
+
repaired_labels.append("action_alias_normalized")
|
| 88 |
+
|
| 89 |
+
if (
|
| 90 |
+
"vulnerability_type" not in cleaned
|
| 91 |
+
and isinstance(data.get("vulnerability"), str)
|
| 92 |
+
):
|
| 93 |
+
cleaned["vulnerability_type"] = data["vulnerability"]
|
| 94 |
+
repaired = True
|
| 95 |
+
repaired_labels.append("vulnerability_alias_normalized")
|
| 96 |
+
|
| 97 |
+
metrics_value = data.get("metrics")
|
| 98 |
+
if "metric" not in cleaned and isinstance(metrics_value, list) and len(metrics_value) == 1:
|
| 99 |
+
cleaned["metric"] = metrics_value[0]
|
| 100 |
+
repaired = True
|
| 101 |
+
repaired_labels.append("metric_list_normalized")
|
| 102 |
+
|
| 103 |
+
if "metrics" in data and (
|
| 104 |
+
not isinstance(metrics_value, list) or len(metrics_value) != 1
|
| 105 |
+
):
|
| 106 |
+
return ParseResult(
|
| 107 |
+
parse_status="invalid_action",
|
| 108 |
+
error="metrics alias is ambiguous",
|
| 109 |
+
repair_labels=repaired_labels,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
action = UnifiedIncidentAction(**cleaned)
|
| 114 |
+
except Exception as exc:
|
| 115 |
+
return ParseResult(
|
| 116 |
+
parse_status="invalid_action",
|
| 117 |
+
error=str(exc),
|
| 118 |
+
repair_labels=repaired_labels,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
return ParseResult(
|
| 122 |
+
parse_status="repaired" if repaired else "ok",
|
| 123 |
+
cleaned_action=_compact_action(action),
|
| 124 |
+
repair_labels=repaired_labels,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class LenientActionAdapter:
|
| 129 |
+
"""Training-time parser that repairs small schema mistakes only."""
|
| 130 |
+
|
| 131 |
+
def parse(self, raw_text: str) -> ParseResult:
|
| 132 |
+
bare = raw_text.strip().strip('"').strip("'")
|
| 133 |
+
if bare in _KNOWN_ACTIONS:
|
| 134 |
+
try:
|
| 135 |
+
action = UnifiedIncidentAction(action_type=bare)
|
| 136 |
+
except Exception as exc:
|
| 137 |
+
return ParseResult(
|
| 138 |
+
parse_status="invalid_action",
|
| 139 |
+
error=str(exc),
|
| 140 |
+
repair_labels=["bare_action_wrapped"],
|
| 141 |
+
)
|
| 142 |
+
return ParseResult(
|
| 143 |
+
parse_status="repaired",
|
| 144 |
+
cleaned_action=_compact_action(action),
|
| 145 |
+
repair_labels=["bare_action_wrapped"],
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
try:
|
| 149 |
+
data = json.loads(_extract_json_text(raw_text))
|
| 150 |
+
except Exception as exc:
|
| 151 |
+
return ParseResult(parse_status="invalid_json", error=type(exc).__name__)
|
| 152 |
+
|
| 153 |
+
if not isinstance(data, dict):
|
| 154 |
+
return ParseResult(parse_status="invalid_action", error="root must be object")
|
| 155 |
+
|
| 156 |
+
repaired_labels: list[str] = []
|
| 157 |
+
cleaned: dict[str, Any] = {k: v for k, v in data.items() if k in _ALLOWED_KEYS}
|
| 158 |
+
repaired = cleaned != data
|
| 159 |
+
if repaired:
|
| 160 |
+
repaired_labels.append("extra_keys_stripped")
|
| 161 |
+
|
| 162 |
+
if "action_type" not in cleaned and isinstance(data.get("action"), str):
|
| 163 |
+
if data["action"] in _KNOWN_ACTIONS:
|
| 164 |
+
cleaned["action_type"] = data["action"]
|
| 165 |
+
repaired = True
|
| 166 |
+
repaired_labels.append("action_alias_normalized")
|
| 167 |
+
|
| 168 |
+
if (
|
| 169 |
+
"vulnerability_type" not in cleaned
|
| 170 |
+
and isinstance(data.get("vulnerability"), str)
|
| 171 |
+
):
|
| 172 |
+
cleaned["vulnerability_type"] = data["vulnerability"]
|
| 173 |
+
repaired = True
|
| 174 |
+
repaired_labels.append("vulnerability_alias_normalized")
|
| 175 |
+
|
| 176 |
+
metrics_value = data.get("metrics")
|
| 177 |
+
if "metric" not in cleaned and isinstance(metrics_value, list) and len(metrics_value) == 1:
|
| 178 |
+
cleaned["metric"] = metrics_value[0]
|
| 179 |
+
repaired = True
|
| 180 |
+
repaired_labels.append("metric_list_normalized")
|
| 181 |
+
|
| 182 |
+
if "metrics" in data and (
|
| 183 |
+
not isinstance(metrics_value, list) or len(metrics_value) != 1
|
| 184 |
+
):
|
| 185 |
+
return ParseResult(
|
| 186 |
+
parse_status="invalid_action",
|
| 187 |
+
error="metrics alias is ambiguous",
|
| 188 |
+
repair_labels=repaired_labels,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
action = UnifiedIncidentAction(**cleaned)
|
| 193 |
+
except Exception as exc:
|
| 194 |
+
return ParseResult(
|
| 195 |
+
parse_status="invalid_action",
|
| 196 |
+
error=str(exc),
|
| 197 |
+
repair_labels=repaired_labels,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
return ParseResult(
|
| 201 |
+
parse_status="repaired" if repaired else "ok",
|
| 202 |
+
cleaned_action=_compact_action(action),
|
| 203 |
+
repair_labels=repaired_labels,
|
| 204 |
+
)
|
unified_incident_env/trainer/analyze_failures.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Failure analysis for episode trajectories."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import Counter
|
| 6 |
+
|
| 7 |
+
from .types import EpisodeRecord, FailureAnalysisReport, FailureBucketEntry, StepRecord
|
| 8 |
+
|
| 9 |
+
_INFRA_ACTIONS = {"restart_service", "rollback_deploy"}
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def analyze_episode(record: EpisodeRecord) -> FailureAnalysisReport:
|
| 13 |
+
"""Classify one episode into schema, policy, looping, and reasoning buckets."""
|
| 14 |
+
entries: list[FailureBucketEntry] = []
|
| 15 |
+
|
| 16 |
+
for step in record.step_records:
|
| 17 |
+
entries.extend(_classify_step(record, step))
|
| 18 |
+
|
| 19 |
+
entries.extend(_classify_episode_level(record))
|
| 20 |
+
|
| 21 |
+
schema = sorted({entry.failure_type for entry in entries if entry.bucket == "schema"})
|
| 22 |
+
policy = sorted({entry.failure_type for entry in entries if entry.bucket == "policy"})
|
| 23 |
+
looping = sorted({entry.failure_type for entry in entries if entry.bucket == "looping"})
|
| 24 |
+
reasoning = sorted({entry.failure_type for entry in entries if entry.bucket == "reasoning"})
|
| 25 |
+
summary = Counter(entry.bucket for entry in entries)
|
| 26 |
+
|
| 27 |
+
return FailureAnalysisReport(
|
| 28 |
+
episode_ids=[record.episode_id or 0],
|
| 29 |
+
scenario_ids=[record.scenario_id],
|
| 30 |
+
entries=entries,
|
| 31 |
+
schema_failures=schema,
|
| 32 |
+
policy_failures=policy,
|
| 33 |
+
looping_failures=looping,
|
| 34 |
+
reasoning_failures=reasoning,
|
| 35 |
+
summary={
|
| 36 |
+
"schema": summary.get("schema", 0),
|
| 37 |
+
"policy": summary.get("policy", 0),
|
| 38 |
+
"looping": summary.get("looping", 0),
|
| 39 |
+
"reasoning": summary.get("reasoning", 0),
|
| 40 |
+
},
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def analyze_block(records: list[EpisodeRecord]) -> FailureAnalysisReport:
|
| 45 |
+
"""Combine multiple episode analyses into one block report."""
|
| 46 |
+
analyses = [analyze_episode(record) for record in records]
|
| 47 |
+
entries = [entry for analysis in analyses for entry in analysis.entries]
|
| 48 |
+
summary = Counter(entry.bucket for entry in entries)
|
| 49 |
+
return FailureAnalysisReport(
|
| 50 |
+
episode_ids=[record.episode_id or 0 for record in records],
|
| 51 |
+
scenario_ids=[record.scenario_id for record in records],
|
| 52 |
+
entries=entries,
|
| 53 |
+
schema_failures=sorted({entry.failure_type for entry in entries if entry.bucket == "schema"}),
|
| 54 |
+
policy_failures=sorted({entry.failure_type for entry in entries if entry.bucket == "policy"}),
|
| 55 |
+
looping_failures=sorted({entry.failure_type for entry in entries if entry.bucket == "looping"}),
|
| 56 |
+
reasoning_failures=sorted({entry.failure_type for entry in entries if entry.bucket == "reasoning"}),
|
| 57 |
+
summary={
|
| 58 |
+
"schema": summary.get("schema", 0),
|
| 59 |
+
"policy": summary.get("policy", 0),
|
| 60 |
+
"looping": summary.get("looping", 0),
|
| 61 |
+
"reasoning": summary.get("reasoning", 0),
|
| 62 |
+
},
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _classify_step(record: EpisodeRecord, step: StepRecord) -> list[FailureBucketEntry]:
|
| 67 |
+
entries: list[FailureBucketEntry] = []
|
| 68 |
+
if step.parse_status in {"invalid_json", "invalid_action"}:
|
| 69 |
+
entries.append(
|
| 70 |
+
FailureBucketEntry(
|
| 71 |
+
episode_id=record.episode_id or 0,
|
| 72 |
+
scenario_id=record.scenario_id,
|
| 73 |
+
step_index=step.step_index,
|
| 74 |
+
bucket="schema",
|
| 75 |
+
failure_type=_schema_failure_type(step),
|
| 76 |
+
detail=step.failure_reason or "schema failure",
|
| 77 |
+
)
|
| 78 |
+
)
|
| 79 |
+
return entries
|
| 80 |
+
|
| 81 |
+
student = step.cleaned_action or {}
|
| 82 |
+
teacher = step.teacher_action or {}
|
| 83 |
+
if not teacher or not student or student == teacher:
|
| 84 |
+
return entries
|
| 85 |
+
|
| 86 |
+
student_type = student.get("action_type")
|
| 87 |
+
teacher_type = teacher.get("action_type")
|
| 88 |
+
|
| 89 |
+
if student_type == "classify_vulnerability":
|
| 90 |
+
failure_type = (
|
| 91 |
+
"wrong_vulnerability"
|
| 92 |
+
if teacher_type == "classify_vulnerability"
|
| 93 |
+
else "fails_to_identify_real_vulnerability"
|
| 94 |
+
)
|
| 95 |
+
entries.append(
|
| 96 |
+
FailureBucketEntry(
|
| 97 |
+
episode_id=record.episode_id or 0,
|
| 98 |
+
scenario_id=record.scenario_id,
|
| 99 |
+
step_index=step.step_index,
|
| 100 |
+
bucket="reasoning",
|
| 101 |
+
failure_type=failure_type,
|
| 102 |
+
detail=f"student={student} teacher={teacher}",
|
| 103 |
+
)
|
| 104 |
+
)
|
| 105 |
+
return entries
|
| 106 |
+
|
| 107 |
+
if student_type == "apply_patch" and teacher_type == "apply_patch":
|
| 108 |
+
entries.append(
|
| 109 |
+
FailureBucketEntry(
|
| 110 |
+
episode_id=record.episode_id or 0,
|
| 111 |
+
scenario_id=record.scenario_id,
|
| 112 |
+
step_index=step.step_index,
|
| 113 |
+
bucket="policy",
|
| 114 |
+
failure_type="wrong_patch",
|
| 115 |
+
detail=f"student={student} teacher={teacher}",
|
| 116 |
+
)
|
| 117 |
+
)
|
| 118 |
+
return entries
|
| 119 |
+
|
| 120 |
+
if student_type == "verify_security_fix" and teacher_type != "verify_security_fix":
|
| 121 |
+
entries.append(
|
| 122 |
+
FailureBucketEntry(
|
| 123 |
+
episode_id=record.episode_id or 0,
|
| 124 |
+
scenario_id=record.scenario_id,
|
| 125 |
+
step_index=step.step_index,
|
| 126 |
+
bucket="policy",
|
| 127 |
+
failure_type="verify_too_early",
|
| 128 |
+
detail=f"student={student} teacher={teacher}",
|
| 129 |
+
)
|
| 130 |
+
)
|
| 131 |
+
return entries
|
| 132 |
+
|
| 133 |
+
if student_type == "submit_security_fix" and teacher_type != "submit_security_fix":
|
| 134 |
+
entries.append(
|
| 135 |
+
FailureBucketEntry(
|
| 136 |
+
episode_id=record.episode_id or 0,
|
| 137 |
+
scenario_id=record.scenario_id,
|
| 138 |
+
step_index=step.step_index,
|
| 139 |
+
bucket="policy",
|
| 140 |
+
failure_type="submit_too_early",
|
| 141 |
+
detail=f"student={student} teacher={teacher}",
|
| 142 |
+
)
|
| 143 |
+
)
|
| 144 |
+
return entries
|
| 145 |
+
|
| 146 |
+
if student_type in _INFRA_ACTIONS and teacher_type not in _INFRA_ACTIONS:
|
| 147 |
+
entries.append(
|
| 148 |
+
FailureBucketEntry(
|
| 149 |
+
episode_id=record.episode_id or 0,
|
| 150 |
+
scenario_id=record.scenario_id,
|
| 151 |
+
step_index=step.step_index,
|
| 152 |
+
bucket="policy",
|
| 153 |
+
failure_type="infra_before_security",
|
| 154 |
+
detail=f"student={student} teacher={teacher}",
|
| 155 |
+
)
|
| 156 |
+
)
|
| 157 |
+
return entries
|
| 158 |
+
|
| 159 |
+
if student_type in _INFRA_ACTIONS and teacher_type in _INFRA_ACTIONS:
|
| 160 |
+
failure_type = "wrong_service"
|
| 161 |
+
if student_type == "restart_service":
|
| 162 |
+
failure_type = "wrong_restart"
|
| 163 |
+
elif student_type == "rollback_deploy":
|
| 164 |
+
failure_type = "wrong_rollback"
|
| 165 |
+
entries.append(
|
| 166 |
+
FailureBucketEntry(
|
| 167 |
+
episode_id=record.episode_id or 0,
|
| 168 |
+
scenario_id=record.scenario_id,
|
| 169 |
+
step_index=step.step_index,
|
| 170 |
+
bucket="policy",
|
| 171 |
+
failure_type=failure_type,
|
| 172 |
+
detail=f"student={student} teacher={teacher}",
|
| 173 |
+
)
|
| 174 |
+
)
|
| 175 |
+
return entries
|
| 176 |
+
|
| 177 |
+
entries.append(
|
| 178 |
+
FailureBucketEntry(
|
| 179 |
+
episode_id=record.episode_id or 0,
|
| 180 |
+
scenario_id=record.scenario_id,
|
| 181 |
+
step_index=step.step_index,
|
| 182 |
+
bucket="policy",
|
| 183 |
+
failure_type="wrong_action_choice",
|
| 184 |
+
detail=f"student={student} teacher={teacher}",
|
| 185 |
+
)
|
| 186 |
+
)
|
| 187 |
+
return entries
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _classify_episode_level(record: EpisodeRecord) -> list[FailureBucketEntry]:
|
| 191 |
+
entries: list[FailureBucketEntry] = []
|
| 192 |
+
previous = None
|
| 193 |
+
repeat_count = 0
|
| 194 |
+
for step in record.step_records:
|
| 195 |
+
current = step.cleaned_action
|
| 196 |
+
if current and current == previous:
|
| 197 |
+
repeat_count += 1
|
| 198 |
+
if repeat_count >= 1:
|
| 199 |
+
entries.append(
|
| 200 |
+
FailureBucketEntry(
|
| 201 |
+
episode_id=record.episode_id or 0,
|
| 202 |
+
scenario_id=record.scenario_id,
|
| 203 |
+
step_index=step.step_index,
|
| 204 |
+
bucket="looping",
|
| 205 |
+
failure_type="repeated_same_action",
|
| 206 |
+
detail=f"action={current}",
|
| 207 |
+
)
|
| 208 |
+
)
|
| 209 |
+
else:
|
| 210 |
+
repeat_count = 0
|
| 211 |
+
previous = current
|
| 212 |
+
|
| 213 |
+
stopped = record.stopped_reason or ""
|
| 214 |
+
if stopped in {"diagnosis", "root_cause_analysis"}:
|
| 215 |
+
entries.append(
|
| 216 |
+
FailureBucketEntry(
|
| 217 |
+
episode_id=record.episode_id or 0,
|
| 218 |
+
scenario_id=record.scenario_id,
|
| 219 |
+
step_index=None,
|
| 220 |
+
bucket="looping",
|
| 221 |
+
failure_type="stuck_in_diagnosis",
|
| 222 |
+
detail=f"stopped_reason={stopped}",
|
| 223 |
+
)
|
| 224 |
+
)
|
| 225 |
+
elif stopped == "security_subquest":
|
| 226 |
+
entries.append(
|
| 227 |
+
FailureBucketEntry(
|
| 228 |
+
episode_id=record.episode_id or 0,
|
| 229 |
+
scenario_id=record.scenario_id,
|
| 230 |
+
step_index=None,
|
| 231 |
+
bucket="looping",
|
| 232 |
+
failure_type="stuck_in_security_subquest",
|
| 233 |
+
detail=f"stopped_reason={stopped}",
|
| 234 |
+
)
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
return entries
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _schema_failure_type(step: StepRecord) -> str:
|
| 241 |
+
raw = step.raw_model_output.lower()
|
| 242 |
+
error = (step.failure_reason or "").lower()
|
| 243 |
+
if '"reason"' in raw or '"details"' in raw or "extra_forbidden" in error:
|
| 244 |
+
return "extra_unsupported_fields"
|
| 245 |
+
if '"services"' in raw or '"metrics"' in raw or "field required" in error:
|
| 246 |
+
return "wrong_field_names"
|
| 247 |
+
if "required" in error or "missing" in error:
|
| 248 |
+
return "missing_required_fields"
|
| 249 |
+
if step.parse_status == "invalid_json":
|
| 250 |
+
return "invalid_json"
|
| 251 |
+
return "invalid_action"
|
unified_incident_env/trainer/backend.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Backend interfaces for model calls."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import time
|
| 7 |
+
from typing import Protocol
|
| 8 |
+
from urllib.parse import urlparse
|
| 9 |
+
|
| 10 |
+
from openai import OpenAI
|
| 11 |
+
|
| 12 |
+
from .types import ModelRequest, ModelResponse
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ModelBackend(Protocol):
|
| 16 |
+
"""Minimal backend protocol for trainer use."""
|
| 17 |
+
|
| 18 |
+
def complete(self, request: ModelRequest) -> ModelResponse:
|
| 19 |
+
"""Return raw model text and metadata for one request."""
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class OpenAICompatibleBackend:
|
| 23 |
+
"""OpenAI-compatible backend, suitable for Ollama and similar servers."""
|
| 24 |
+
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
*,
|
| 28 |
+
base_url: str,
|
| 29 |
+
api_key: str,
|
| 30 |
+
timeout_s: float = 90.0,
|
| 31 |
+
) -> None:
|
| 32 |
+
self.base_url = base_url
|
| 33 |
+
self._client = OpenAI(api_key=api_key, base_url=base_url, timeout=timeout_s)
|
| 34 |
+
|
| 35 |
+
def complete(self, request: ModelRequest) -> ModelResponse:
|
| 36 |
+
started = time.perf_counter()
|
| 37 |
+
create_kwargs = {
|
| 38 |
+
"model": request.model_name,
|
| 39 |
+
"temperature": request.temperature,
|
| 40 |
+
"max_tokens": request.max_tokens,
|
| 41 |
+
"messages": [
|
| 42 |
+
{"role": "system", "content": request.system_prompt},
|
| 43 |
+
{"role": "user", "content": request.user_prompt},
|
| 44 |
+
],
|
| 45 |
+
}
|
| 46 |
+
raw_text = ""
|
| 47 |
+
actual_mode = request.structured_mode
|
| 48 |
+
|
| 49 |
+
if request.structured_mode == "backend_adaptive":
|
| 50 |
+
if self._is_ollama():
|
| 51 |
+
actual_mode = "response_format_json"
|
| 52 |
+
else:
|
| 53 |
+
actual_mode = "tool_calling"
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
if actual_mode == "tool_calling":
|
| 57 |
+
tool_choice = request.tool_choice or {
|
| 58 |
+
"type": "function",
|
| 59 |
+
"function": {"name": "emit_action"},
|
| 60 |
+
}
|
| 61 |
+
create_kwargs["tools"] = request.tools or [
|
| 62 |
+
self._tool_from_response_format(request.response_format)
|
| 63 |
+
]
|
| 64 |
+
create_kwargs["tool_choice"] = tool_choice
|
| 65 |
+
response = self._client.chat.completions.create(**create_kwargs)
|
| 66 |
+
raw_text = self._extract_tool_text(response)
|
| 67 |
+
elif actual_mode == "response_format_json":
|
| 68 |
+
if self._is_ollama():
|
| 69 |
+
create_kwargs["extra_body"] = {
|
| 70 |
+
"format": self._ollama_format_payload(request.response_format)
|
| 71 |
+
}
|
| 72 |
+
else:
|
| 73 |
+
create_kwargs["response_format"] = request.response_format or {
|
| 74 |
+
"type": "json_object"
|
| 75 |
+
}
|
| 76 |
+
response = self._client.chat.completions.create(**create_kwargs)
|
| 77 |
+
raw_text = response.choices[0].message.content or ""
|
| 78 |
+
else:
|
| 79 |
+
response = self._client.chat.completions.create(**create_kwargs)
|
| 80 |
+
raw_text = response.choices[0].message.content or ""
|
| 81 |
+
except Exception:
|
| 82 |
+
if request.structured_mode == "backend_adaptive" and actual_mode == "tool_calling":
|
| 83 |
+
fallback_kwargs = dict(create_kwargs)
|
| 84 |
+
if "tools" in fallback_kwargs:
|
| 85 |
+
del fallback_kwargs["tools"]
|
| 86 |
+
if "tool_choice" in fallback_kwargs:
|
| 87 |
+
del fallback_kwargs["tool_choice"]
|
| 88 |
+
if self._is_ollama():
|
| 89 |
+
fallback_kwargs["extra_body"] = {
|
| 90 |
+
"format": self._ollama_format_payload(request.response_format)
|
| 91 |
+
}
|
| 92 |
+
else:
|
| 93 |
+
fallback_kwargs["response_format"] = request.response_format or {
|
| 94 |
+
"type": "json_object"
|
| 95 |
+
}
|
| 96 |
+
response = self._client.chat.completions.create(**fallback_kwargs)
|
| 97 |
+
raw_text = response.choices[0].message.content or ""
|
| 98 |
+
actual_mode = "response_format_json"
|
| 99 |
+
else:
|
| 100 |
+
raise
|
| 101 |
+
|
| 102 |
+
elapsed = time.perf_counter() - started
|
| 103 |
+
return ModelResponse(
|
| 104 |
+
raw_text=raw_text,
|
| 105 |
+
latency_s=round(elapsed, 4),
|
| 106 |
+
metadata={
|
| 107 |
+
"model": request.model_name,
|
| 108 |
+
"structured_mode": actual_mode,
|
| 109 |
+
},
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def _is_ollama(self) -> bool:
|
| 113 |
+
parsed = urlparse(self.base_url)
|
| 114 |
+
host = parsed.netloc.lower()
|
| 115 |
+
return "11434" in host or "ollama" in host or "127.0.0.1" in host or "localhost" in host
|
| 116 |
+
|
| 117 |
+
def _ollama_format_payload(
|
| 118 |
+
self,
|
| 119 |
+
response_format: dict[str, object] | None,
|
| 120 |
+
) -> object:
|
| 121 |
+
if response_format and response_format.get("type") == "json_schema":
|
| 122 |
+
json_schema = response_format.get("json_schema", {})
|
| 123 |
+
if isinstance(json_schema, dict):
|
| 124 |
+
return json_schema.get("schema", "json")
|
| 125 |
+
return "json"
|
| 126 |
+
|
| 127 |
+
def _tool_from_response_format(
|
| 128 |
+
self,
|
| 129 |
+
response_format: dict[str, object] | None,
|
| 130 |
+
) -> dict[str, object]:
|
| 131 |
+
schema = {
|
| 132 |
+
"type": "object",
|
| 133 |
+
"properties": {"action_type": {"type": "string"}},
|
| 134 |
+
"required": ["action_type"],
|
| 135 |
+
"additionalProperties": False,
|
| 136 |
+
}
|
| 137 |
+
if response_format and response_format.get("type") == "json_schema":
|
| 138 |
+
json_schema = response_format.get("json_schema", {})
|
| 139 |
+
schema = json_schema.get("schema", schema) # type: ignore[assignment]
|
| 140 |
+
return {
|
| 141 |
+
"type": "function",
|
| 142 |
+
"function": {
|
| 143 |
+
"name": "emit_action",
|
| 144 |
+
"description": "Emit exactly one structured environment action.",
|
| 145 |
+
"parameters": schema,
|
| 146 |
+
},
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
def _extract_tool_text(self, response) -> str:
|
| 150 |
+
message = response.choices[0].message
|
| 151 |
+
tool_calls = getattr(message, "tool_calls", None) or []
|
| 152 |
+
if tool_calls:
|
| 153 |
+
function = getattr(tool_calls[0], "function", None)
|
| 154 |
+
if function is not None and getattr(function, "arguments", None):
|
| 155 |
+
return function.arguments
|
| 156 |
+
content = message.content or ""
|
| 157 |
+
if isinstance(content, list):
|
| 158 |
+
fragments = []
|
| 159 |
+
for item in content:
|
| 160 |
+
if isinstance(item, dict) and item.get("type") == "text":
|
| 161 |
+
fragments.append(item.get("text", ""))
|
| 162 |
+
return "".join(fragments)
|
| 163 |
+
if isinstance(content, str):
|
| 164 |
+
return content
|
| 165 |
+
return json.dumps(content)
|
unified_incident_env/trainer/build_datasets.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build correction datasets from trajectories and failure analyses."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from .build_sft_dataset import build_baseline_records
|
| 9 |
+
from .trajectory_store import TrajectoryStore
|
| 10 |
+
from .types import EpisodeRecord, FailureAnalysisReport, SFTRecord
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def build_schema_repair_records(
|
| 14 |
+
episodes: list[EpisodeRecord],
|
| 15 |
+
analyses: list[FailureAnalysisReport],
|
| 16 |
+
) -> list[SFTRecord]:
|
| 17 |
+
rows: list[SFTRecord] = []
|
| 18 |
+
analysis_by_episode = {
|
| 19 |
+
analysis.episode_ids[0]: analysis for analysis in analyses if analysis.episode_ids
|
| 20 |
+
}
|
| 21 |
+
for episode in episodes:
|
| 22 |
+
analysis = analysis_by_episode.get(episode.episode_id or 0)
|
| 23 |
+
schema_types = set(analysis.schema_failures if analysis else [])
|
| 24 |
+
for step in episode.step_records:
|
| 25 |
+
if step.parse_status not in {"invalid_json", "invalid_action", "repaired", "teacher_override"}:
|
| 26 |
+
continue
|
| 27 |
+
if step.teacher_action is None:
|
| 28 |
+
continue
|
| 29 |
+
rows.append(
|
| 30 |
+
SFTRecord(
|
| 31 |
+
source="schema_repair",
|
| 32 |
+
scenario_id=episode.scenario_id,
|
| 33 |
+
tick=step.tick,
|
| 34 |
+
messages=[
|
| 35 |
+
{"role": "system", "content": "Repair the action into strict JSON only."},
|
| 36 |
+
{
|
| 37 |
+
"role": "user",
|
| 38 |
+
"content": (
|
| 39 |
+
f"{step.prompt_text}\n\n"
|
| 40 |
+
f"Previous invalid output:\n{step.raw_model_output}"
|
| 41 |
+
),
|
| 42 |
+
},
|
| 43 |
+
],
|
| 44 |
+
target_action=step.teacher_action,
|
| 45 |
+
student_action=step.cleaned_action,
|
| 46 |
+
parse_status=step.parse_status,
|
| 47 |
+
tags=sorted(schema_types) or [step.parse_status],
|
| 48 |
+
metadata={
|
| 49 |
+
"episode_id": episode.episode_id,
|
| 50 |
+
"step_index": step.step_index,
|
| 51 |
+
"repair_retry_used": step.repair_retry_used,
|
| 52 |
+
"teacher_override_used": step.teacher_override_used,
|
| 53 |
+
"normalization_applied": step.normalization_applied,
|
| 54 |
+
"failure_type": step.observation.get("failure_type"),
|
| 55 |
+
"why_failed": step.observation.get("why_failed"),
|
| 56 |
+
"loop_warning": step.observation.get("loop_warning"),
|
| 57 |
+
"blocked_until_security_complete": step.observation.get("blocked_until_security_complete"),
|
| 58 |
+
"security_unlock_reason": step.observation.get("security_unlock_reason"),
|
| 59 |
+
"progress_flags": step.observation.get("progress_flags"),
|
| 60 |
+
},
|
| 61 |
+
)
|
| 62 |
+
)
|
| 63 |
+
return rows
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def build_next_action_records(
|
| 67 |
+
episodes: list[EpisodeRecord],
|
| 68 |
+
analyses: list[FailureAnalysisReport],
|
| 69 |
+
) -> list[SFTRecord]:
|
| 70 |
+
rows: list[SFTRecord] = []
|
| 71 |
+
episode_entries = {
|
| 72 |
+
analysis.episode_ids[0]: analysis.entries
|
| 73 |
+
for analysis in analyses
|
| 74 |
+
if analysis.episode_ids
|
| 75 |
+
}
|
| 76 |
+
allowed = {"policy", "reasoning", "looping"}
|
| 77 |
+
for episode in episodes:
|
| 78 |
+
entries = episode_entries.get(episode.episode_id or 0, [])
|
| 79 |
+
step_indices = {
|
| 80 |
+
entry.step_index
|
| 81 |
+
for entry in entries
|
| 82 |
+
if entry.bucket in allowed and entry.step_index is not None
|
| 83 |
+
}
|
| 84 |
+
for step in episode.step_records:
|
| 85 |
+
if step.step_index not in step_indices:
|
| 86 |
+
continue
|
| 87 |
+
if step.teacher_action is None:
|
| 88 |
+
continue
|
| 89 |
+
tags = [
|
| 90 |
+
entry.failure_type
|
| 91 |
+
for entry in entries
|
| 92 |
+
if entry.step_index == step.step_index and entry.bucket in allowed
|
| 93 |
+
]
|
| 94 |
+
rows.append(
|
| 95 |
+
SFTRecord(
|
| 96 |
+
source="next_action",
|
| 97 |
+
scenario_id=episode.scenario_id,
|
| 98 |
+
tick=step.tick,
|
| 99 |
+
messages=[
|
| 100 |
+
{"role": "system", "content": "Choose the best next action as strict JSON only."},
|
| 101 |
+
{"role": "user", "content": step.prompt_text},
|
| 102 |
+
],
|
| 103 |
+
target_action=step.teacher_action,
|
| 104 |
+
student_action=step.cleaned_action,
|
| 105 |
+
parse_status=step.parse_status,
|
| 106 |
+
tags=sorted(set(tags)) or ["next_action"],
|
| 107 |
+
metadata={
|
| 108 |
+
"episode_id": episode.episode_id,
|
| 109 |
+
"step_index": step.step_index,
|
| 110 |
+
"workflow_stage": step.workflow_stage,
|
| 111 |
+
"teacher_override_used": step.teacher_override_used,
|
| 112 |
+
"failure_type": step.observation.get("failure_type"),
|
| 113 |
+
"why_failed": step.observation.get("why_failed"),
|
| 114 |
+
"loop_warning": step.observation.get("loop_warning"),
|
| 115 |
+
"progress_flags": step.observation.get("progress_flags"),
|
| 116 |
+
},
|
| 117 |
+
)
|
| 118 |
+
)
|
| 119 |
+
return rows
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def build_recovery_records(
|
| 123 |
+
episodes: list[EpisodeRecord],
|
| 124 |
+
analyses: list[FailureAnalysisReport],
|
| 125 |
+
) -> list[SFTRecord]:
|
| 126 |
+
rows: list[SFTRecord] = []
|
| 127 |
+
episode_entries = {
|
| 128 |
+
analysis.episode_ids[0]: analysis.entries
|
| 129 |
+
for analysis in analyses
|
| 130 |
+
if analysis.episode_ids
|
| 131 |
+
}
|
| 132 |
+
recovery_failures = {
|
| 133 |
+
"wrong_restart",
|
| 134 |
+
"wrong_rollback",
|
| 135 |
+
"wrong_service",
|
| 136 |
+
"wrong_patch",
|
| 137 |
+
"wrong_vulnerability",
|
| 138 |
+
"verify_too_early",
|
| 139 |
+
"submit_too_early",
|
| 140 |
+
"infra_before_security",
|
| 141 |
+
"repeated_same_action",
|
| 142 |
+
}
|
| 143 |
+
for episode in episodes:
|
| 144 |
+
entries = episode_entries.get(episode.episode_id or 0, [])
|
| 145 |
+
step_indices = {
|
| 146 |
+
entry.step_index
|
| 147 |
+
for entry in entries
|
| 148 |
+
if entry.failure_type in recovery_failures and entry.step_index is not None
|
| 149 |
+
}
|
| 150 |
+
for step in episode.step_records:
|
| 151 |
+
if step.step_index not in step_indices:
|
| 152 |
+
continue
|
| 153 |
+
if step.teacher_action is None or not step.next_prompt_text:
|
| 154 |
+
continue
|
| 155 |
+
tags = [
|
| 156 |
+
entry.failure_type
|
| 157 |
+
for entry in entries
|
| 158 |
+
if entry.step_index == step.step_index
|
| 159 |
+
and entry.failure_type in recovery_failures
|
| 160 |
+
]
|
| 161 |
+
rows.append(
|
| 162 |
+
SFTRecord(
|
| 163 |
+
source="recovery",
|
| 164 |
+
scenario_id=episode.scenario_id,
|
| 165 |
+
tick=step.tick,
|
| 166 |
+
messages=[
|
| 167 |
+
{"role": "system", "content": "Recover from the previous mistake. Return the best next strict JSON action only."},
|
| 168 |
+
{
|
| 169 |
+
"role": "user",
|
| 170 |
+
"content": (
|
| 171 |
+
f"{step.next_prompt_text}\n\n"
|
| 172 |
+
f"Previous wrong action: {step.cleaned_action}\n"
|
| 173 |
+
f"Penalty or result: reward={step.reward}"
|
| 174 |
+
),
|
| 175 |
+
},
|
| 176 |
+
],
|
| 177 |
+
target_action=step.teacher_action,
|
| 178 |
+
student_action=step.cleaned_action,
|
| 179 |
+
parse_status=step.parse_status,
|
| 180 |
+
tags=sorted(set(tags)) or ["recovery"],
|
| 181 |
+
metadata={
|
| 182 |
+
"episode_id": episode.episode_id,
|
| 183 |
+
"step_index": step.step_index,
|
| 184 |
+
"teacher_override_used": step.teacher_override_used,
|
| 185 |
+
"failure_type": step.observation.get("failure_type"),
|
| 186 |
+
"why_failed": step.observation.get("why_failed"),
|
| 187 |
+
"loop_warning": step.observation.get("loop_warning"),
|
| 188 |
+
"best_recovery_action_family": step.observation.get("best_recovery_action_family"),
|
| 189 |
+
},
|
| 190 |
+
)
|
| 191 |
+
)
|
| 192 |
+
return rows
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def combine_sft_records(
|
| 196 |
+
*,
|
| 197 |
+
baseline_records: list[SFTRecord],
|
| 198 |
+
schema_records: list[SFTRecord],
|
| 199 |
+
next_action_records: list[SFTRecord],
|
| 200 |
+
recovery_records: list[SFTRecord],
|
| 201 |
+
) -> list[SFTRecord]:
|
| 202 |
+
return [
|
| 203 |
+
*baseline_records,
|
| 204 |
+
*schema_records,
|
| 205 |
+
*next_action_records,
|
| 206 |
+
*recovery_records,
|
| 207 |
+
]
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def write_jsonl(records: list[SFTRecord], path: Path) -> None:
|
| 211 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 212 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 213 |
+
for record in records:
|
| 214 |
+
handle.write(record.model_dump_json())
|
| 215 |
+
handle.write("\n")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def load_episodes(path: Path) -> list[EpisodeRecord]:
|
| 219 |
+
return TrajectoryStore(path).load_episodes()
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def main() -> None:
|
| 223 |
+
parser = argparse.ArgumentParser()
|
| 224 |
+
parser.add_argument("--episodes", default="outputs/trainer/episodes.jsonl")
|
| 225 |
+
parser.add_argument("--output-dir", required=True)
|
| 226 |
+
args = parser.parse_args()
|
| 227 |
+
|
| 228 |
+
output_dir = Path(args.output_dir)
|
| 229 |
+
episodes = load_episodes(Path(args.episodes))
|
| 230 |
+
|
| 231 |
+
from .analyze_failures import analyze_episode
|
| 232 |
+
|
| 233 |
+
analyses = [analyze_episode(episode) for episode in episodes]
|
| 234 |
+
baseline_records = build_baseline_records()
|
| 235 |
+
schema_records = build_schema_repair_records(episodes, analyses)
|
| 236 |
+
next_action_records = build_next_action_records(episodes, analyses)
|
| 237 |
+
recovery_records = build_recovery_records(episodes, analyses)
|
| 238 |
+
combined_records = combine_sft_records(
|
| 239 |
+
baseline_records=baseline_records,
|
| 240 |
+
schema_records=schema_records,
|
| 241 |
+
next_action_records=next_action_records,
|
| 242 |
+
recovery_records=recovery_records,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
write_jsonl(baseline_records, output_dir / "baseline_teacher_dataset.jsonl")
|
| 246 |
+
write_jsonl(schema_records, output_dir / "schema_repair.jsonl")
|
| 247 |
+
write_jsonl(next_action_records, output_dir / "next_action.jsonl")
|
| 248 |
+
write_jsonl(recovery_records, output_dir / "recovery.jsonl")
|
| 249 |
+
write_jsonl(combined_records, output_dir / "sft_dataset.jsonl")
|
| 250 |
+
print(
|
| 251 |
+
f"wrote baseline={len(baseline_records)} schema={len(schema_records)} "
|
| 252 |
+
f"next_action={len(next_action_records)} recovery={len(recovery_records)} "
|
| 253 |
+
f"combined={len(combined_records)} to {output_dir}"
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
if __name__ == "__main__":
|
| 258 |
+
main()
|
unified_incident_env/trainer/build_sft_dataset.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build supervised JSONL datasets from baseline and replay trajectories."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from ..scripts.baseline_agent import plan_for_scenario
|
| 9 |
+
from ..server.challenge import SCENARIOS
|
| 10 |
+
from ..server.environment import UnifiedIncidentEnvironment
|
| 11 |
+
from .prompts import TRAINING_SYSTEM_PROMPT
|
| 12 |
+
from .trajectory_store import TrajectoryStore
|
| 13 |
+
from .types import SFTRecord
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def build_baseline_records() -> list[SFTRecord]:
|
| 17 |
+
rows: list[SFTRecord] = []
|
| 18 |
+
for scenario_id in SCENARIOS:
|
| 19 |
+
env = UnifiedIncidentEnvironment()
|
| 20 |
+
obs = env.reset(scenario_id=scenario_id)
|
| 21 |
+
for step_index, action in enumerate(plan_for_scenario(scenario_id), start=1):
|
| 22 |
+
rows.append(
|
| 23 |
+
SFTRecord(
|
| 24 |
+
source="baseline",
|
| 25 |
+
scenario_id=scenario_id,
|
| 26 |
+
tick=obs.tick_count,
|
| 27 |
+
messages=[
|
| 28 |
+
{"role": "system", "content": TRAINING_SYSTEM_PROMPT},
|
| 29 |
+
{"role": "user", "content": obs.prompt_text},
|
| 30 |
+
],
|
| 31 |
+
target_action=action.model_dump(exclude_none=True),
|
| 32 |
+
tags=["teacher", f"step_{step_index}"],
|
| 33 |
+
)
|
| 34 |
+
)
|
| 35 |
+
obs = env.step(action)
|
| 36 |
+
return rows
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def build_replay_records(episodes_path: Path) -> list[SFTRecord]:
|
| 40 |
+
rows: list[SFTRecord] = []
|
| 41 |
+
for episode in TrajectoryStore(episodes_path).load_episodes():
|
| 42 |
+
for step in episode.step_records:
|
| 43 |
+
if step.teacher_action is None:
|
| 44 |
+
continue
|
| 45 |
+
tags = [episode.mode, step.parse_status]
|
| 46 |
+
if step.failure_reason:
|
| 47 |
+
tags.append("failure")
|
| 48 |
+
rows.append(
|
| 49 |
+
SFTRecord(
|
| 50 |
+
source="replay",
|
| 51 |
+
scenario_id=episode.scenario_id,
|
| 52 |
+
tick=step.tick,
|
| 53 |
+
messages=[
|
| 54 |
+
{"role": "system", "content": TRAINING_SYSTEM_PROMPT},
|
| 55 |
+
{"role": "user", "content": step.prompt_text},
|
| 56 |
+
],
|
| 57 |
+
target_action=step.teacher_action,
|
| 58 |
+
student_action=step.cleaned_action,
|
| 59 |
+
parse_status=step.parse_status,
|
| 60 |
+
tags=tags,
|
| 61 |
+
)
|
| 62 |
+
)
|
| 63 |
+
return rows
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def write_jsonl(records: list[SFTRecord], output_path: Path) -> None:
|
| 67 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
with output_path.open("w", encoding="utf-8") as handle:
|
| 69 |
+
for record in records:
|
| 70 |
+
handle.write(record.model_dump_json())
|
| 71 |
+
handle.write("\n")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def main() -> None:
|
| 75 |
+
parser = argparse.ArgumentParser()
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
"--source",
|
| 78 |
+
choices=["baseline", "replay", "combined"],
|
| 79 |
+
default="combined",
|
| 80 |
+
)
|
| 81 |
+
parser.add_argument(
|
| 82 |
+
"--episodes",
|
| 83 |
+
default="outputs/trainer/episodes.jsonl",
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--output",
|
| 87 |
+
required=True,
|
| 88 |
+
)
|
| 89 |
+
args = parser.parse_args()
|
| 90 |
+
|
| 91 |
+
records: list[SFTRecord] = []
|
| 92 |
+
if args.source in {"baseline", "combined"}:
|
| 93 |
+
records.extend(build_baseline_records())
|
| 94 |
+
if args.source in {"replay", "combined"}:
|
| 95 |
+
records.extend(build_replay_records(Path(args.episodes)))
|
| 96 |
+
write_jsonl(records, Path(args.output))
|
| 97 |
+
print(f"wrote {len(records)} rows to {args.output}")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
main()
|
unified_incident_env/trainer/collect_trajectory.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Collection wrapper that turns one episode into trajectory + analysis + summary."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from .analyze_failures import analyze_episode
|
| 6 |
+
from .types import EpisodeRecord, EpisodeSummaryRecord
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def collect_episode(
|
| 10 |
+
*,
|
| 11 |
+
runner,
|
| 12 |
+
scenario_id: str,
|
| 13 |
+
episode_id: int,
|
| 14 |
+
mode: str,
|
| 15 |
+
model_version: str,
|
| 16 |
+
) -> tuple[EpisodeRecord, EpisodeSummaryRecord, object]:
|
| 17 |
+
"""Run, analyze, and summarize one episode."""
|
| 18 |
+
record = runner.run(
|
| 19 |
+
scenario_id=scenario_id,
|
| 20 |
+
mode=mode,
|
| 21 |
+
episode_id=episode_id,
|
| 22 |
+
model_version=model_version,
|
| 23 |
+
)
|
| 24 |
+
analysis = analyze_episode(record)
|
| 25 |
+
record.schema_failures = analysis.summary.get("schema", 0)
|
| 26 |
+
record.policy_failures = analysis.policy_failures
|
| 27 |
+
record.looping_failures = analysis.looping_failures
|
| 28 |
+
record.reasoning_failures = analysis.reasoning_failures
|
| 29 |
+
summary = EpisodeSummaryRecord(
|
| 30 |
+
episode_id=episode_id,
|
| 31 |
+
run_id=record.run_id,
|
| 32 |
+
scenario_id=record.scenario_id,
|
| 33 |
+
difficulty=record.difficulty,
|
| 34 |
+
model_name=record.model_name,
|
| 35 |
+
model_version=record.model_version,
|
| 36 |
+
mode=record.mode,
|
| 37 |
+
steps=record.steps,
|
| 38 |
+
success=record.success,
|
| 39 |
+
final_score=record.final_score,
|
| 40 |
+
schema_failures=analysis.summary.get("schema", 0),
|
| 41 |
+
json_valid_steps=record.json_valid_steps,
|
| 42 |
+
strict_schema_valid_steps=record.strict_schema_valid_steps,
|
| 43 |
+
teacher_override_count=record.teacher_override_count,
|
| 44 |
+
repair_retry_count=record.repair_retry_count,
|
| 45 |
+
policy_failures=analysis.policy_failures,
|
| 46 |
+
looping_failures=analysis.looping_failures,
|
| 47 |
+
reasoning_failures=analysis.reasoning_failures,
|
| 48 |
+
security_subquest_completed=record.security_subquest_completed,
|
| 49 |
+
postmortem_completed=record.postmortem_completed,
|
| 50 |
+
stopped_reason=record.stopped_reason,
|
| 51 |
+
elapsed_s=record.elapsed_s,
|
| 52 |
+
)
|
| 53 |
+
return record, summary, analysis
|
unified_incident_env/trainer/eval_models.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batch evaluation for one or more models."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from ..server.challenge import SCENARIOS
|
| 11 |
+
from .action_adapter import LenientActionAdapter, StrictActionParser
|
| 12 |
+
from .backend import OpenAICompatibleBackend
|
| 13 |
+
from .run_episode import EpisodeRunner
|
| 14 |
+
from .trajectory_store import TrajectoryStore
|
| 15 |
+
from .types import EvalScenarioResult, EvalSummary
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def summarize(results: list[EvalScenarioResult], mode: str) -> EvalSummary:
|
| 19 |
+
success_rate = (
|
| 20 |
+
sum(1 for result in results if result.success) / len(results) if results else 0.0
|
| 21 |
+
)
|
| 22 |
+
avg_score = (
|
| 23 |
+
sum(result.final_score for result in results) / len(results) if results else 0.0
|
| 24 |
+
)
|
| 25 |
+
schema_failure_rate = (
|
| 26 |
+
sum(1 for result in results if result.schema_failure) / len(results)
|
| 27 |
+
if results
|
| 28 |
+
else 0.0
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
by_model: dict[str, dict[str, float]] = {}
|
| 32 |
+
by_scenario: dict[str, dict[str, float]] = {}
|
| 33 |
+
for result in results:
|
| 34 |
+
model_bucket = by_model.setdefault(
|
| 35 |
+
result.model_name,
|
| 36 |
+
{"runs": 0.0, "successes": 0.0, "score_sum": 0.0, "schema_failures": 0.0},
|
| 37 |
+
)
|
| 38 |
+
model_bucket["runs"] += 1
|
| 39 |
+
model_bucket["successes"] += 1.0 if result.success else 0.0
|
| 40 |
+
model_bucket["score_sum"] += result.final_score
|
| 41 |
+
model_bucket["schema_failures"] += 1.0 if result.schema_failure else 0.0
|
| 42 |
+
|
| 43 |
+
scenario_bucket = by_scenario.setdefault(
|
| 44 |
+
result.scenario_id,
|
| 45 |
+
{"runs": 0.0, "successes": 0.0, "score_sum": 0.0},
|
| 46 |
+
)
|
| 47 |
+
scenario_bucket["runs"] += 1
|
| 48 |
+
scenario_bucket["successes"] += 1.0 if result.success else 0.0
|
| 49 |
+
scenario_bucket["score_sum"] += result.final_score
|
| 50 |
+
|
| 51 |
+
for bucket in by_model.values():
|
| 52 |
+
runs = bucket["runs"] or 1.0
|
| 53 |
+
bucket["success_rate"] = round(bucket["successes"] / runs, 4)
|
| 54 |
+
bucket["avg_score"] = round(bucket["score_sum"] / runs, 4)
|
| 55 |
+
bucket["schema_failure_rate"] = round(bucket["schema_failures"] / runs, 4)
|
| 56 |
+
del bucket["score_sum"]
|
| 57 |
+
del bucket["successes"]
|
| 58 |
+
del bucket["schema_failures"]
|
| 59 |
+
|
| 60 |
+
for bucket in by_scenario.values():
|
| 61 |
+
runs = bucket["runs"] or 1.0
|
| 62 |
+
bucket["success_rate"] = round(bucket["successes"] / runs, 4)
|
| 63 |
+
bucket["avg_score"] = round(bucket["score_sum"] / runs, 4)
|
| 64 |
+
del bucket["score_sum"]
|
| 65 |
+
del bucket["successes"]
|
| 66 |
+
|
| 67 |
+
return EvalSummary(
|
| 68 |
+
mode=mode,
|
| 69 |
+
results=results,
|
| 70 |
+
success_rate=round(success_rate, 4),
|
| 71 |
+
avg_score=round(avg_score, 4),
|
| 72 |
+
schema_failure_rate=round(schema_failure_rate, 4),
|
| 73 |
+
by_model=by_model,
|
| 74 |
+
by_scenario=by_scenario,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def main() -> None:
|
| 79 |
+
parser = argparse.ArgumentParser()
|
| 80 |
+
parser.add_argument("--models", nargs="+", required=True)
|
| 81 |
+
parser.add_argument("--mode", choices=["strict", "lenient"], default="strict")
|
| 82 |
+
parser.add_argument("--base-url", default="http://127.0.0.1:8000")
|
| 83 |
+
parser.add_argument(
|
| 84 |
+
"--api-base-url",
|
| 85 |
+
default=os.environ.get("API_BASE_URL", "http://127.0.0.1:11434/v1"),
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--api-key",
|
| 89 |
+
default=os.environ.get("OPENAI_API_KEY") or os.environ.get("HF_TOKEN") or "local",
|
| 90 |
+
)
|
| 91 |
+
parser.add_argument(
|
| 92 |
+
"--output",
|
| 93 |
+
default=None,
|
| 94 |
+
)
|
| 95 |
+
parser.add_argument(
|
| 96 |
+
"--episodes-output",
|
| 97 |
+
default="outputs/trainer/episodes.jsonl",
|
| 98 |
+
)
|
| 99 |
+
args = parser.parse_args()
|
| 100 |
+
|
| 101 |
+
backend = OpenAICompatibleBackend(
|
| 102 |
+
base_url=args.api_base_url,
|
| 103 |
+
api_key=args.api_key,
|
| 104 |
+
)
|
| 105 |
+
parser_impl = StrictActionParser() if args.mode == "strict" else LenientActionAdapter()
|
| 106 |
+
episode_store = TrajectoryStore(Path(args.episodes_output))
|
| 107 |
+
|
| 108 |
+
results: list[EvalScenarioResult] = []
|
| 109 |
+
for model_name in args.models:
|
| 110 |
+
runner = EpisodeRunner(
|
| 111 |
+
backend=backend,
|
| 112 |
+
parser=parser_impl,
|
| 113 |
+
model_name=model_name,
|
| 114 |
+
base_url=args.base_url,
|
| 115 |
+
)
|
| 116 |
+
for scenario_id in SCENARIOS:
|
| 117 |
+
episode = runner.run(scenario_id=scenario_id, mode=args.mode)
|
| 118 |
+
episode_store.append_episode(episode)
|
| 119 |
+
results.append(
|
| 120 |
+
EvalScenarioResult(
|
| 121 |
+
model_name=model_name,
|
| 122 |
+
scenario_id=scenario_id,
|
| 123 |
+
success=episode.success,
|
| 124 |
+
final_score=episode.final_score,
|
| 125 |
+
failure_reason=episode.failure_reason,
|
| 126 |
+
schema_failure=bool(
|
| 127 |
+
episode.failure_reason
|
| 128 |
+
and episode.failure_reason.startswith("parse_failure")
|
| 129 |
+
),
|
| 130 |
+
elapsed_s=episode.elapsed_s,
|
| 131 |
+
)
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
summary = summarize(results, mode=args.mode)
|
| 135 |
+
output_path = Path(
|
| 136 |
+
args.output
|
| 137 |
+
or f"outputs/trainer/{args.mode}_eval_summary.json"
|
| 138 |
+
)
|
| 139 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 140 |
+
output_path.write_text(summary.model_dump_json(indent=2), encoding="utf-8")
|
| 141 |
+
print(summary.model_dump_json(indent=2))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
main()
|
unified_incident_env/trainer/parser.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Parser surface alias for trainer action normalization."""
|
| 2 |
+
|
| 3 |
+
from .action_adapter import LenientActionAdapter, StrictActionParser
|
| 4 |
+
|
| 5 |
+
__all__ = ["LenientActionAdapter", "StrictActionParser"]
|
unified_incident_env/trainer/policy_adapter.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Policy adapter artifacts produced by the external trainer wrapper."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from dataclasses import asdict, dataclass, field
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class PolicyAdapter:
|
| 12 |
+
"""Serializable prompt-side policy adapter for later phases."""
|
| 13 |
+
|
| 14 |
+
base_model: str
|
| 15 |
+
phase_name: str
|
| 16 |
+
schema_examples: list[dict] = field(default_factory=list)
|
| 17 |
+
next_action_examples: list[dict] = field(default_factory=list)
|
| 18 |
+
recovery_examples: list[dict] = field(default_factory=list)
|
| 19 |
+
|
| 20 |
+
def build_prompt_addendum(self, scenario_id: str, stage: str) -> str:
|
| 21 |
+
"""Build an addendum for the given scenario and stage."""
|
| 22 |
+
lines: list[str] = []
|
| 23 |
+
schema = [
|
| 24 |
+
item for item in self.schema_examples
|
| 25 |
+
if item.get("scenario_id") == scenario_id
|
| 26 |
+
][:2]
|
| 27 |
+
next_action = [
|
| 28 |
+
item for item in self.next_action_examples
|
| 29 |
+
if item.get("scenario_id") == scenario_id
|
| 30 |
+
][:2]
|
| 31 |
+
recovery = [
|
| 32 |
+
item for item in self.recovery_examples
|
| 33 |
+
if item.get("scenario_id") == scenario_id
|
| 34 |
+
][:2]
|
| 35 |
+
|
| 36 |
+
if schema:
|
| 37 |
+
lines.append("Adapter schema reminders:")
|
| 38 |
+
for item in schema:
|
| 39 |
+
lines.append(
|
| 40 |
+
f"- invalid -> valid: {json.dumps(item['target_action'], separators=(',', ':'))}"
|
| 41 |
+
)
|
| 42 |
+
if next_action:
|
| 43 |
+
lines.append("Adapter next-action reminders:")
|
| 44 |
+
for item in next_action:
|
| 45 |
+
lines.append(
|
| 46 |
+
f"- stage {item.get('workflow_stage', stage)} -> {json.dumps(item['target_action'], separators=(',', ':'))}"
|
| 47 |
+
)
|
| 48 |
+
if recovery:
|
| 49 |
+
lines.append("Adapter recovery reminders:")
|
| 50 |
+
for item in recovery:
|
| 51 |
+
lines.append(
|
| 52 |
+
f"- recover with {json.dumps(item['target_action'], separators=(',', ':'))}"
|
| 53 |
+
)
|
| 54 |
+
return "\n".join(lines)
|
| 55 |
+
|
| 56 |
+
def save(self, path: Path) -> None:
|
| 57 |
+
"""Write adapter JSON to disk."""
|
| 58 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
path.write_text(json.dumps(asdict(self), indent=2), encoding="utf-8")
|
| 60 |
+
|
| 61 |
+
@classmethod
|
| 62 |
+
def load(cls, path: Path) -> "PolicyAdapter":
|
| 63 |
+
"""Load adapter JSON from disk."""
|
| 64 |
+
return cls(**json.loads(path.read_text(encoding="utf-8")))
|
unified_incident_env/trainer/prompts.py
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prompt builders for training, repair, and strict evaluation."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from ..models import UnifiedIncidentObservation
|
| 9 |
+
|
| 10 |
+
ALL_ACTIONS = [
|
| 11 |
+
"query_logs",
|
| 12 |
+
"query_metrics",
|
| 13 |
+
"query_dependencies",
|
| 14 |
+
"restart_service",
|
| 15 |
+
"rollback_deploy",
|
| 16 |
+
"inspect_code",
|
| 17 |
+
"classify_vulnerability",
|
| 18 |
+
"apply_patch",
|
| 19 |
+
"verify_security_fix",
|
| 20 |
+
"submit_security_fix",
|
| 21 |
+
"submit_postmortem",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
TRAINING_SYSTEM_PROMPT = (
|
| 25 |
+
"You are solving a deterministic incident-response benchmark.\n\n"
|
| 26 |
+
"Return exactly one JSON object and nothing else.\n\n"
|
| 27 |
+
"Rules:\n"
|
| 28 |
+
"- Choose only from the allowed action types shown in the user message.\n"
|
| 29 |
+
"- Use only the required fields for the chosen action.\n"
|
| 30 |
+
"- Do not include explanation text.\n"
|
| 31 |
+
"- Do not include markdown.\n"
|
| 32 |
+
"- Do not include code fences.\n"
|
| 33 |
+
"- Do not repeat an action that already failed or made no progress.\n"
|
| 34 |
+
"- If patching is required, use only one of the listed patch IDs.\n"
|
| 35 |
+
)
|
| 36 |
+
STAGE_GOALS = {
|
| 37 |
+
"diagnosis": "find the most relevant next investigation step",
|
| 38 |
+
"root_cause_analysis": "confirm the root-cause evidence and avoid unnecessary recovery",
|
| 39 |
+
"security_subquest": "complete the security fix before infrastructure recovery",
|
| 40 |
+
"remediation": "recover services in the correct order",
|
| 41 |
+
"verification": "verify that recovery and security remediation are complete",
|
| 42 |
+
"postmortem": "submit the final incident summary",
|
| 43 |
+
"done": "complete the benchmark",
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
STAGE_ACTIONS = {
|
| 47 |
+
"diagnosis": ["query_logs", "query_metrics", "query_dependencies"],
|
| 48 |
+
"root_cause_analysis": ["query_logs", "query_metrics", "query_dependencies"],
|
| 49 |
+
"security_subquest": [
|
| 50 |
+
"inspect_code",
|
| 51 |
+
"classify_vulnerability",
|
| 52 |
+
"apply_patch",
|
| 53 |
+
"verify_security_fix",
|
| 54 |
+
"submit_security_fix",
|
| 55 |
+
],
|
| 56 |
+
"remediation": ["restart_service", "rollback_deploy"],
|
| 57 |
+
"verification": ["restart_service", "rollback_deploy"],
|
| 58 |
+
"postmortem": ["submit_postmortem"],
|
| 59 |
+
"done": [],
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
REQUIRED_FIELDS = {
|
| 63 |
+
"query_logs": ["service"],
|
| 64 |
+
"query_metrics": ["service", "metric"],
|
| 65 |
+
"query_dependencies": ["service"],
|
| 66 |
+
"restart_service": ["service"],
|
| 67 |
+
"rollback_deploy": ["service"],
|
| 68 |
+
"inspect_code": [],
|
| 69 |
+
"classify_vulnerability": ["vulnerability_type"],
|
| 70 |
+
"apply_patch": ["patch_id"],
|
| 71 |
+
"verify_security_fix": [],
|
| 72 |
+
"submit_security_fix": [],
|
| 73 |
+
"submit_postmortem": ["postmortem"],
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
USER_PROMPT_TEMPLATE = """Current stage: {stage}
|
| 77 |
+
|
| 78 |
+
Current goal: {goal}
|
| 79 |
+
|
| 80 |
+
Allowed actions:
|
| 81 |
+
{allowed_actions_block}
|
| 82 |
+
|
| 83 |
+
Required fields:
|
| 84 |
+
{required_fields_block}
|
| 85 |
+
|
| 86 |
+
{patch_ids_block}{transition_block}{negative_reward_block}Current environment state:
|
| 87 |
+
{state_block}
|
| 88 |
+
|
| 89 |
+
Valid example:
|
| 90 |
+
{valid_example}
|
| 91 |
+
|
| 92 |
+
Return exactly one JSON object.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def build_runtime_request(
|
| 97 |
+
observation: UnifiedIncidentObservation,
|
| 98 |
+
*,
|
| 99 |
+
teacher_action: dict[str, Any] | None = None,
|
| 100 |
+
correction_memory_text: str = "",
|
| 101 |
+
strict: bool = False,
|
| 102 |
+
) -> tuple[str, str, dict[str, Any]]:
|
| 103 |
+
"""Build staged prompts and JSON schema guidance for one step."""
|
| 104 |
+
stage = observation.workflow_stage
|
| 105 |
+
allowed_actions = _narrow_allowed_actions(
|
| 106 |
+
observation.allowed_actions or STAGE_ACTIONS.get(stage, ALL_ACTIONS),
|
| 107 |
+
observation,
|
| 108 |
+
)
|
| 109 |
+
required_fields = observation.required_fields_by_action or {
|
| 110 |
+
action: REQUIRED_FIELDS[action] for action in allowed_actions
|
| 111 |
+
}
|
| 112 |
+
example = teacher_action or observation.valid_action_example or _default_example(stage, observation)
|
| 113 |
+
if example.get("action_type") not in allowed_actions:
|
| 114 |
+
example = _default_example(stage, observation)
|
| 115 |
+
user_prompt = _build_user_prompt(
|
| 116 |
+
observation,
|
| 117 |
+
allowed_actions,
|
| 118 |
+
required_fields,
|
| 119 |
+
example=example,
|
| 120 |
+
correction_hint=correction_memory_text.strip() or None,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
response_format = _response_format_for_actions(observation, allowed_actions)
|
| 124 |
+
return TRAINING_SYSTEM_PROMPT, user_prompt, response_format
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def build_repair_request(
|
| 128 |
+
observation: UnifiedIncidentObservation,
|
| 129 |
+
*,
|
| 130 |
+
raw_bad_output: str,
|
| 131 |
+
parse_error: str,
|
| 132 |
+
teacher_action: dict[str, Any] | None = None,
|
| 133 |
+
) -> tuple[str, str]:
|
| 134 |
+
"""Build one-shot repair prompt after a schema failure."""
|
| 135 |
+
stage = observation.workflow_stage
|
| 136 |
+
example = teacher_action or observation.valid_action_example or _default_example(stage, observation)
|
| 137 |
+
system = (
|
| 138 |
+
"Your previous response was invalid.\n"
|
| 139 |
+
"Return exactly one valid JSON object.\n"
|
| 140 |
+
"No explanation. No extra keys."
|
| 141 |
+
)
|
| 142 |
+
user = (
|
| 143 |
+
f"Stage: {stage}\n"
|
| 144 |
+
f"Error: {parse_error}\n"
|
| 145 |
+
f"Bad output: {raw_bad_output}\n"
|
| 146 |
+
f"Example: {json.dumps(example, separators=(',', ':'))}"
|
| 147 |
+
)
|
| 148 |
+
return system, user
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _default_example(
|
| 152 |
+
stage: str,
|
| 153 |
+
observation: UnifiedIncidentObservation,
|
| 154 |
+
) -> dict[str, Any]:
|
| 155 |
+
if stage in {"diagnosis", "root_cause_analysis"}:
|
| 156 |
+
unhealthy = [
|
| 157 |
+
service
|
| 158 |
+
for service, payload in observation.service_health.items()
|
| 159 |
+
if payload.status != "healthy"
|
| 160 |
+
]
|
| 161 |
+
service = unhealthy[0] if unhealthy else "database"
|
| 162 |
+
if stage == "diagnosis":
|
| 163 |
+
if service == "database":
|
| 164 |
+
return {"action_type": "query_logs", "service": "database"}
|
| 165 |
+
return {"action_type": "query_metrics", "service": service, "metric": "cpu"}
|
| 166 |
+
return {"action_type": "query_dependencies", "service": "api-gateway"}
|
| 167 |
+
if stage == "security_subquest":
|
| 168 |
+
context = observation.security_context
|
| 169 |
+
if not context.code_visible:
|
| 170 |
+
return {"action_type": "inspect_code"}
|
| 171 |
+
if context.selected_vulnerability is None:
|
| 172 |
+
return {
|
| 173 |
+
"action_type": "classify_vulnerability",
|
| 174 |
+
"vulnerability_type": "sql_injection",
|
| 175 |
+
}
|
| 176 |
+
if context.selected_patch is None:
|
| 177 |
+
return {"action_type": "apply_patch", "patch_id": "parameterized_query"}
|
| 178 |
+
if context.exploit_blocked is not True:
|
| 179 |
+
return {"action_type": "verify_security_fix"}
|
| 180 |
+
return {"action_type": "submit_security_fix"}
|
| 181 |
+
if stage in {"remediation", "verification"}:
|
| 182 |
+
unhealthy = [
|
| 183 |
+
service
|
| 184 |
+
for service, payload in observation.service_health.items()
|
| 185 |
+
if payload.status != "healthy"
|
| 186 |
+
]
|
| 187 |
+
service = unhealthy[0] if unhealthy else "database"
|
| 188 |
+
return {"action_type": "restart_service", "service": service}
|
| 189 |
+
if stage == "postmortem":
|
| 190 |
+
return {
|
| 191 |
+
"action_type": "submit_postmortem",
|
| 192 |
+
"postmortem": {
|
| 193 |
+
"root_cause": "The security issue caused the outage.",
|
| 194 |
+
"attack_vector": "The vulnerable path was abused.",
|
| 195 |
+
"timeline": ["Investigated", "Patched", "Recovered"],
|
| 196 |
+
"remediation_steps": ["Patch", "Restart"],
|
| 197 |
+
"prevention_steps": ["Detection", "Hardening"],
|
| 198 |
+
},
|
| 199 |
+
}
|
| 200 |
+
return {"action_type": "query_logs", "service": "database"}
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _response_format_for_actions(
|
| 204 |
+
observation: UnifiedIncidentObservation,
|
| 205 |
+
allowed_actions: list[str],
|
| 206 |
+
) -> dict[str, Any]:
|
| 207 |
+
properties: dict[str, Any] = {
|
| 208 |
+
"action_type": {
|
| 209 |
+
"type": "string",
|
| 210 |
+
"enum": allowed_actions,
|
| 211 |
+
}
|
| 212 |
+
}
|
| 213 |
+
if any(action in allowed_actions for action in {"query_logs", "query_metrics", "query_dependencies", "restart_service", "rollback_deploy"}):
|
| 214 |
+
services = sorted(observation.service_health.keys())
|
| 215 |
+
properties["service"] = {"type": "string", "enum": services}
|
| 216 |
+
if "query_metrics" in allowed_actions:
|
| 217 |
+
properties["metric"] = {"type": "string", "enum": ["cpu", "memory", "latency", "error_rate", "throughput"]}
|
| 218 |
+
if "classify_vulnerability" in allowed_actions:
|
| 219 |
+
properties["vulnerability_type"] = {
|
| 220 |
+
"type": "string",
|
| 221 |
+
"enum": ["sql_injection", "broken_access_control", "command_injection"],
|
| 222 |
+
}
|
| 223 |
+
if "apply_patch" in allowed_actions:
|
| 224 |
+
patch_options = _patch_options(observation)
|
| 225 |
+
properties["patch_id"] = {
|
| 226 |
+
"type": "string",
|
| 227 |
+
"enum": patch_options or ["parameterized_query", "enforce_admin_role", "avoid_shell"],
|
| 228 |
+
}
|
| 229 |
+
if "submit_postmortem" in allowed_actions:
|
| 230 |
+
properties["postmortem"] = {"type": "object"}
|
| 231 |
+
|
| 232 |
+
required = ["action_type"]
|
| 233 |
+
example = observation.valid_action_example or {}
|
| 234 |
+
for field in ("service", "metric", "vulnerability_type", "patch_id", "postmortem"):
|
| 235 |
+
if field in properties and field in example:
|
| 236 |
+
required.append(field)
|
| 237 |
+
|
| 238 |
+
schema = {
|
| 239 |
+
"type": "object",
|
| 240 |
+
"properties": properties,
|
| 241 |
+
"required": required,
|
| 242 |
+
"additionalProperties": False,
|
| 243 |
+
}
|
| 244 |
+
return {
|
| 245 |
+
"type": "json_schema",
|
| 246 |
+
"json_schema": {
|
| 247 |
+
"name": "unified_incident_action",
|
| 248 |
+
"strict": True,
|
| 249 |
+
"schema": schema,
|
| 250 |
+
},
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _patch_options(observation: UnifiedIncidentObservation) -> list[str]:
|
| 255 |
+
sources = [observation.tool_output or "", observation.prompt_text]
|
| 256 |
+
for source in sources:
|
| 257 |
+
marker = "Patch options:"
|
| 258 |
+
if marker not in source:
|
| 259 |
+
continue
|
| 260 |
+
suffix = source.split(marker, 1)[1].splitlines()[0]
|
| 261 |
+
return [item.strip() for item in suffix.split(",") if item.strip()]
|
| 262 |
+
return []
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _build_required_fields_block(
|
| 266 |
+
required_fields: dict[str, list[str]],
|
| 267 |
+
allowed_actions: list[str],
|
| 268 |
+
) -> str:
|
| 269 |
+
lines = []
|
| 270 |
+
for action in allowed_actions:
|
| 271 |
+
fields = required_fields.get(action, [])
|
| 272 |
+
if fields:
|
| 273 |
+
lines.append(f"- {action} -> {', '.join(fields)}")
|
| 274 |
+
else:
|
| 275 |
+
lines.append(f"- {action} -> none")
|
| 276 |
+
return "\n".join(lines) or "- none"
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def _build_patch_ids_block(patch_ids: list[str]) -> str:
|
| 280 |
+
if not patch_ids:
|
| 281 |
+
return ""
|
| 282 |
+
lines = ["Available patch IDs:"]
|
| 283 |
+
lines.extend(f"- {patch_id}" for patch_id in patch_ids)
|
| 284 |
+
lines.append("")
|
| 285 |
+
return "\n".join(lines)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def _build_transition_block(observation: UnifiedIncidentObservation) -> str:
|
| 289 |
+
transition_hint = _transition_hint(observation)
|
| 290 |
+
if not transition_hint:
|
| 291 |
+
return ""
|
| 292 |
+
return f"Important transition hint:\n- {transition_hint}\n\n"
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _build_negative_reward_block(correction_hint: str | None) -> str:
|
| 296 |
+
if not correction_hint:
|
| 297 |
+
return ""
|
| 298 |
+
compact = correction_hint.splitlines()[0].strip()
|
| 299 |
+
return f"Previous action correction:\n- {compact}\n\n"
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def _bool_text(value: bool | None) -> str:
|
| 303 |
+
if value is None:
|
| 304 |
+
return "unknown"
|
| 305 |
+
return str(value).lower()
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def _render_tool_output(observation: UnifiedIncidentObservation) -> str:
|
| 309 |
+
if not observation.tool_output:
|
| 310 |
+
return ""
|
| 311 |
+
|
| 312 |
+
if observation.workflow_stage in {"security_subquest", "verification"}:
|
| 313 |
+
lines = [line.rstrip() for line in observation.tool_output.splitlines() if line.strip()]
|
| 314 |
+
return "\n".join(lines[:6])
|
| 315 |
+
|
| 316 |
+
return observation.tool_output.splitlines()[0]
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _build_state_block(observation: UnifiedIncidentObservation) -> str:
|
| 320 |
+
lines: list[str] = []
|
| 321 |
+
if observation.active_alerts:
|
| 322 |
+
lines.append("Active alerts:")
|
| 323 |
+
for alert in observation.active_alerts[:3]:
|
| 324 |
+
lines.append(f"- {alert.service}: {alert.severity} - {alert.message}")
|
| 325 |
+
|
| 326 |
+
lines.append(f"Final score: {observation.final_score:.4f}")
|
| 327 |
+
|
| 328 |
+
if observation.last_action_result:
|
| 329 |
+
lines.append(f"Last action result: {observation.last_action_result}")
|
| 330 |
+
|
| 331 |
+
if observation.tool_output:
|
| 332 |
+
rendered_tool_output = _render_tool_output(observation)
|
| 333 |
+
if "\n" in rendered_tool_output:
|
| 334 |
+
lines.append("Tool output:")
|
| 335 |
+
lines.extend(rendered_tool_output.splitlines())
|
| 336 |
+
else:
|
| 337 |
+
lines.append(f"Tool output: {rendered_tool_output}")
|
| 338 |
+
|
| 339 |
+
security = observation.security_context
|
| 340 |
+
if observation.workflow_stage in {"security_subquest", "verification"}:
|
| 341 |
+
lines.append(
|
| 342 |
+
"Security status: "
|
| 343 |
+
f"code visible = {str(security.code_visible).lower()}, "
|
| 344 |
+
f"vulnerability classified = {str(security.selected_vulnerability is not None).lower()}, "
|
| 345 |
+
f"patch applied = {str(security.selected_patch is not None).lower()}, "
|
| 346 |
+
f"exploit blocked = {_bool_text(security.exploit_blocked)}, "
|
| 347 |
+
f"functionality preserved = {_bool_text(security.functionality_preserved)}"
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
if observation.security_unlock_reason:
|
| 351 |
+
lines.append(f"Security unlock reason: {observation.security_unlock_reason}")
|
| 352 |
+
|
| 353 |
+
if observation.blocked_until_security_complete:
|
| 354 |
+
lines.append("Recovery gate: security must be completed before recovery.")
|
| 355 |
+
|
| 356 |
+
return "\n".join(lines) or "- none"
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def _transition_hint(observation: UnifiedIncidentObservation) -> str | None:
|
| 360 |
+
if observation.blocked_until_security_complete:
|
| 361 |
+
return "security must be completed before recovery"
|
| 362 |
+
stage = observation.workflow_stage
|
| 363 |
+
security = observation.security_context
|
| 364 |
+
if stage == "root_cause_analysis":
|
| 365 |
+
return "confirm the root cause with one more relevant investigation step"
|
| 366 |
+
if stage == "security_subquest":
|
| 367 |
+
if not security.code_visible:
|
| 368 |
+
return "inspection must happen before classification or patching"
|
| 369 |
+
if security.selected_vulnerability is None:
|
| 370 |
+
return "classification is required before patching"
|
| 371 |
+
if security.selected_patch is None:
|
| 372 |
+
return "classification is complete; next required action family is patching"
|
| 373 |
+
if security.exploit_blocked is not True or security.functionality_preserved is not True:
|
| 374 |
+
return "patching is complete; verification is required before submission"
|
| 375 |
+
return "security is fixed; submit the security fix before recovery"
|
| 376 |
+
if stage == "remediation":
|
| 377 |
+
return "recover infrastructure only after security is completed"
|
| 378 |
+
if stage == "verification":
|
| 379 |
+
return "verify both security remediation and infrastructure recovery"
|
| 380 |
+
if stage == "postmortem":
|
| 381 |
+
return "submit the final incident summary"
|
| 382 |
+
return None
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def _build_user_prompt(
|
| 386 |
+
observation: UnifiedIncidentObservation,
|
| 387 |
+
allowed_actions: list[str],
|
| 388 |
+
required_fields: dict[str, list[str]],
|
| 389 |
+
*,
|
| 390 |
+
example: dict[str, Any],
|
| 391 |
+
correction_hint: str | None = None,
|
| 392 |
+
) -> str:
|
| 393 |
+
return USER_PROMPT_TEMPLATE.format(
|
| 394 |
+
stage=observation.workflow_stage,
|
| 395 |
+
goal=STAGE_GOALS.get(observation.workflow_stage, "take the best next action"),
|
| 396 |
+
allowed_actions_block="\n".join(f"- {action}" for action in allowed_actions) or "- none",
|
| 397 |
+
required_fields_block=_build_required_fields_block(required_fields, allowed_actions),
|
| 398 |
+
patch_ids_block=_build_patch_ids_block(
|
| 399 |
+
_patch_options(observation) if "apply_patch" in allowed_actions else []
|
| 400 |
+
),
|
| 401 |
+
transition_block=_build_transition_block(observation),
|
| 402 |
+
negative_reward_block=_build_negative_reward_block(correction_hint),
|
| 403 |
+
state_block=_build_state_block(observation),
|
| 404 |
+
valid_example=json.dumps(example, separators=(",", ":")),
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def _narrow_allowed_actions(
|
| 409 |
+
allowed_actions: list[str],
|
| 410 |
+
observation: UnifiedIncidentObservation,
|
| 411 |
+
) -> list[str]:
|
| 412 |
+
if observation.workflow_stage not in {"security_subquest", "verification"}:
|
| 413 |
+
return allowed_actions
|
| 414 |
+
|
| 415 |
+
context = observation.security_context
|
| 416 |
+
if not context.code_visible and "inspect_code" in allowed_actions:
|
| 417 |
+
return ["inspect_code"]
|
| 418 |
+
if context.code_visible and context.selected_vulnerability is None and "classify_vulnerability" in allowed_actions:
|
| 419 |
+
return ["classify_vulnerability"]
|
| 420 |
+
if context.selected_vulnerability is not None and context.selected_patch is None and "apply_patch" in allowed_actions:
|
| 421 |
+
return ["apply_patch"]
|
| 422 |
+
if (
|
| 423 |
+
context.selected_patch is not None
|
| 424 |
+
and (context.exploit_blocked is not True or context.functionality_preserved is not True)
|
| 425 |
+
and "verify_security_fix" in allowed_actions
|
| 426 |
+
):
|
| 427 |
+
return ["verify_security_fix"]
|
| 428 |
+
if (
|
| 429 |
+
context.exploit_blocked is True
|
| 430 |
+
and context.functionality_preserved is True
|
| 431 |
+
and "submit_security_fix" in allowed_actions
|
| 432 |
+
):
|
| 433 |
+
return ["submit_security_fix"]
|
| 434 |
+
return allowed_actions
|
unified_incident_env/trainer/reporting.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Session reporting and artifact writing helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from .types import EpisodeRecord, PhaseDeltaRecord, SessionPhaseReport, SessionReport
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def build_phase_deltas(phase_reports: list[SessionPhaseReport]) -> list[PhaseDeltaRecord]:
|
| 12 |
+
"""Compute deltas from one phase to the next."""
|
| 13 |
+
deltas: list[PhaseDeltaRecord] = []
|
| 14 |
+
previous = None
|
| 15 |
+
for report in phase_reports:
|
| 16 |
+
if previous is None:
|
| 17 |
+
delta = PhaseDeltaRecord(
|
| 18 |
+
phase_name=report.phase_name,
|
| 19 |
+
score_delta=0.0,
|
| 20 |
+
schema_failure_delta=0.0,
|
| 21 |
+
loop_failure_delta=0.0,
|
| 22 |
+
success_delta=0.0,
|
| 23 |
+
)
|
| 24 |
+
else:
|
| 25 |
+
delta = PhaseDeltaRecord(
|
| 26 |
+
phase_name=report.phase_name,
|
| 27 |
+
score_delta=round(report.avg_score - previous.avg_score, 4),
|
| 28 |
+
schema_failure_delta=round(
|
| 29 |
+
(report.schema_failures / len(report.episode_ids))
|
| 30 |
+
- (previous.schema_failures / len(previous.episode_ids)),
|
| 31 |
+
4,
|
| 32 |
+
),
|
| 33 |
+
loop_failure_delta=round(
|
| 34 |
+
_avg_loop_failures(report) - _avg_loop_failures(previous),
|
| 35 |
+
4,
|
| 36 |
+
),
|
| 37 |
+
success_delta=round(report.success_rate - previous.success_rate, 4),
|
| 38 |
+
)
|
| 39 |
+
deltas.append(delta)
|
| 40 |
+
previous = report
|
| 41 |
+
return deltas
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _avg_loop_failures(report: SessionPhaseReport) -> float:
|
| 45 |
+
if not report.episode_ids:
|
| 46 |
+
return 0.0
|
| 47 |
+
return float(report.loop_failures) / len(report.episode_ids)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def redact_episode_prompts(
|
| 51 |
+
records: list[EpisodeRecord],
|
| 52 |
+
*,
|
| 53 |
+
include_prompts: bool,
|
| 54 |
+
) -> list[EpisodeRecord]:
|
| 55 |
+
"""Redact prompt text fields when compact artifacts are desired."""
|
| 56 |
+
if include_prompts:
|
| 57 |
+
return records
|
| 58 |
+
redacted: list[EpisodeRecord] = []
|
| 59 |
+
for record in records:
|
| 60 |
+
step_records = []
|
| 61 |
+
for step in record.step_records:
|
| 62 |
+
observation = dict(step.observation)
|
| 63 |
+
if "prompt_text" in observation:
|
| 64 |
+
observation["prompt_text"] = ""
|
| 65 |
+
step_records.append(
|
| 66 |
+
step.model_copy(
|
| 67 |
+
update={
|
| 68 |
+
"prompt_text": "",
|
| 69 |
+
"next_prompt_text": None,
|
| 70 |
+
"observation": observation,
|
| 71 |
+
}
|
| 72 |
+
)
|
| 73 |
+
)
|
| 74 |
+
redacted.append(record.model_copy(update={"step_records": step_records}))
|
| 75 |
+
return redacted
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def write_jsonl_episodes(path: Path, records: list[EpisodeRecord]) -> None:
|
| 79 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 80 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 81 |
+
for record in records:
|
| 82 |
+
handle.write(record.model_dump_json())
|
| 83 |
+
handle.write("\n")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def build_final_report(report: SessionReport) -> dict:
|
| 87 |
+
"""Build the high-level report JSON shown at the end of a session."""
|
| 88 |
+
summaries = report.episode_summaries
|
| 89 |
+
final_report = {
|
| 90 |
+
"session_id": report.session_id,
|
| 91 |
+
"model_name": report.model_name,
|
| 92 |
+
"runtime_mode": report.runtime_mode,
|
| 93 |
+
"initial_avg_score": 0.0,
|
| 94 |
+
"final_avg_score": 0.0,
|
| 95 |
+
"success_count": 0,
|
| 96 |
+
"schema_failure_rate": 0.0,
|
| 97 |
+
"json_valid_rate": 0.0,
|
| 98 |
+
"strict_schema_valid_rate": 0.0,
|
| 99 |
+
"average_repeated_action_count": 0.0,
|
| 100 |
+
"teacher_override_rate": 0.0,
|
| 101 |
+
"repair_retry_success_rate": 0.0,
|
| 102 |
+
"schema_to_policy_progression_rate": 0.0,
|
| 103 |
+
"security_unlock_rate": 0.0,
|
| 104 |
+
"security_completion_rate": 0.0,
|
| 105 |
+
"full_task_completion_rate": 0.0,
|
| 106 |
+
"average_steps_to_termination": 0.0,
|
| 107 |
+
"average_score_per_scenario": {},
|
| 108 |
+
"phase_to_phase_score_delta": {
|
| 109 |
+
delta.phase_name: delta.score_delta for delta in report.phase_deltas
|
| 110 |
+
},
|
| 111 |
+
"improvement_metrics": report.improvement_metrics,
|
| 112 |
+
"correction_memory_stats": report.correction_memory_stats,
|
| 113 |
+
}
|
| 114 |
+
if summaries:
|
| 115 |
+
initial = [item for item in summaries if item.episode_id in {1, 2}]
|
| 116 |
+
final = [item for item in summaries if item.episode_id in {9, 10}]
|
| 117 |
+
final_report["initial_avg_score"] = round(
|
| 118 |
+
sum(item.final_score for item in initial) / len(initial), 4
|
| 119 |
+
) if initial else 0.0
|
| 120 |
+
final_report["final_avg_score"] = round(
|
| 121 |
+
sum(item.final_score for item in final) / len(final), 4
|
| 122 |
+
) if final else 0.0
|
| 123 |
+
final_report["success_count"] = sum(1 for item in summaries if item.success)
|
| 124 |
+
final_report["schema_failure_rate"] = round(
|
| 125 |
+
sum(item.schema_failures for item in summaries) / len(summaries),
|
| 126 |
+
4,
|
| 127 |
+
)
|
| 128 |
+
final_report["json_valid_rate"] = round(
|
| 129 |
+
sum(1 for item in summaries if item.schema_failures == 0) / len(summaries),
|
| 130 |
+
4,
|
| 131 |
+
)
|
| 132 |
+
final_report["strict_schema_valid_rate"] = round(
|
| 133 |
+
sum(
|
| 134 |
+
1
|
| 135 |
+
for item in summaries
|
| 136 |
+
if item.mode == "strict" and item.schema_failures == 0
|
| 137 |
+
)
|
| 138 |
+
/ max(1, sum(1 for item in summaries if item.mode == "strict")),
|
| 139 |
+
4,
|
| 140 |
+
)
|
| 141 |
+
final_report["average_repeated_action_count"] = round(
|
| 142 |
+
sum(len(item.looping_failures) for item in summaries) / len(summaries),
|
| 143 |
+
4,
|
| 144 |
+
)
|
| 145 |
+
final_report["teacher_override_rate"] = round(
|
| 146 |
+
sum(item.teacher_override_count for item in summaries)
|
| 147 |
+
/ max(1, sum(item.steps for item in summaries)),
|
| 148 |
+
4,
|
| 149 |
+
)
|
| 150 |
+
retry_steps = sum(item.repair_retry_count for item in summaries)
|
| 151 |
+
repaired_steps = sum(
|
| 152 |
+
1
|
| 153 |
+
for item in summaries
|
| 154 |
+
if item.repair_retry_count > 0 and item.schema_failures == 0
|
| 155 |
+
)
|
| 156 |
+
final_report["repair_retry_success_rate"] = round(
|
| 157 |
+
repaired_steps / max(1, retry_steps),
|
| 158 |
+
4,
|
| 159 |
+
)
|
| 160 |
+
policy_after_schema = sum(
|
| 161 |
+
1
|
| 162 |
+
for item in summaries
|
| 163 |
+
if item.schema_failures == 0 and item.policy_failures
|
| 164 |
+
)
|
| 165 |
+
final_report["schema_to_policy_progression_rate"] = round(
|
| 166 |
+
policy_after_schema / len(summaries),
|
| 167 |
+
4,
|
| 168 |
+
)
|
| 169 |
+
final_report["security_unlock_rate"] = round(
|
| 170 |
+
sum(
|
| 171 |
+
1
|
| 172 |
+
for item in summaries
|
| 173 |
+
if item.stopped_reason not in {"diagnosis", "root_cause_analysis"}
|
| 174 |
+
)
|
| 175 |
+
/ len(summaries),
|
| 176 |
+
4,
|
| 177 |
+
)
|
| 178 |
+
final_report["security_completion_rate"] = round(
|
| 179 |
+
sum(
|
| 180 |
+
1
|
| 181 |
+
for item in summaries
|
| 182 |
+
if "infra_before_security" not in item.policy_failures
|
| 183 |
+
and item.stopped_reason not in {"security_subquest"}
|
| 184 |
+
)
|
| 185 |
+
/ len(summaries),
|
| 186 |
+
4,
|
| 187 |
+
)
|
| 188 |
+
final_report["full_task_completion_rate"] = round(
|
| 189 |
+
sum(1 for item in summaries if item.success) / len(summaries),
|
| 190 |
+
4,
|
| 191 |
+
)
|
| 192 |
+
final_report["average_steps_to_termination"] = round(
|
| 193 |
+
sum(item.steps for item in summaries) / len(summaries),
|
| 194 |
+
4,
|
| 195 |
+
)
|
| 196 |
+
by_scenario: dict[str, list[float]] = {}
|
| 197 |
+
for item in summaries:
|
| 198 |
+
by_scenario.setdefault(item.scenario_id, []).append(item.final_score)
|
| 199 |
+
final_report["average_score_per_scenario"] = {
|
| 200 |
+
scenario_id: round(sum(scores) / len(scores), 4)
|
| 201 |
+
for scenario_id, scores in by_scenario.items()
|
| 202 |
+
}
|
| 203 |
+
return final_report
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def write_session_outputs(
|
| 207 |
+
*,
|
| 208 |
+
output_dir: Path,
|
| 209 |
+
report: SessionReport,
|
| 210 |
+
records: list[EpisodeRecord],
|
| 211 |
+
include_prompts: bool,
|
| 212 |
+
) -> None:
|
| 213 |
+
"""Write all top-level session artifacts."""
|
| 214 |
+
redacted_records = redact_episode_prompts(records, include_prompts=include_prompts)
|
| 215 |
+
write_jsonl_episodes(output_dir / "episodes.jsonl", redacted_records)
|
| 216 |
+
(output_dir / "summaries.json").write_text(
|
| 217 |
+
report.model_dump_json(indent=2),
|
| 218 |
+
encoding="utf-8",
|
| 219 |
+
)
|
| 220 |
+
(output_dir / "phase_delta.json").write_text(
|
| 221 |
+
json.dumps([item.model_dump() for item in report.phase_deltas], indent=2),
|
| 222 |
+
encoding="utf-8",
|
| 223 |
+
)
|
| 224 |
+
(output_dir / "final_report.json").write_text(
|
| 225 |
+
json.dumps(build_final_report(report), indent=2),
|
| 226 |
+
encoding="utf-8",
|
| 227 |
+
)
|
unified_incident_env/trainer/run_episode.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Episode runner for strict and lenient training/eval modes."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
+
import uuid
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
from ..client import UnifiedIncidentEnv
|
| 14 |
+
from ..models import UnifiedIncidentAction
|
| 15 |
+
from ..scripts.baseline_agent import plan_for_scenario
|
| 16 |
+
from ..server.challenge import SCENARIOS
|
| 17 |
+
from ..server.environment import UnifiedIncidentEnvironment
|
| 18 |
+
from .action_adapter import LenientActionAdapter, StrictActionParser
|
| 19 |
+
from .backend import OpenAICompatibleBackend
|
| 20 |
+
from .prompts import build_repair_request, build_runtime_request
|
| 21 |
+
from .trajectory_memory import CorrectionMemory
|
| 22 |
+
from .trajectory_store import TrajectoryStore
|
| 23 |
+
from .types import EpisodeRecord, ModelRequest, StepRecord
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class EpisodeRunner:
|
| 27 |
+
"""Runs one model through one scenario and records a full trajectory."""
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
*,
|
| 32 |
+
backend,
|
| 33 |
+
parser,
|
| 34 |
+
model_name: str,
|
| 35 |
+
base_url: str | None = None,
|
| 36 |
+
env_factory=None,
|
| 37 |
+
correction_memory: CorrectionMemory | None = None,
|
| 38 |
+
) -> None:
|
| 39 |
+
self.backend = backend
|
| 40 |
+
self.parser = parser
|
| 41 |
+
self.model_name = model_name
|
| 42 |
+
self.base_url = base_url
|
| 43 |
+
self.env_factory = env_factory
|
| 44 |
+
self.correction_memory = correction_memory or CorrectionMemory()
|
| 45 |
+
|
| 46 |
+
def run(
|
| 47 |
+
self,
|
| 48 |
+
scenario_id: str,
|
| 49 |
+
mode: str,
|
| 50 |
+
*,
|
| 51 |
+
episode_id: int | None = None,
|
| 52 |
+
model_version: str | None = None,
|
| 53 |
+
) -> EpisodeRecord:
|
| 54 |
+
started = time.perf_counter()
|
| 55 |
+
scenario = SCENARIOS[scenario_id]
|
| 56 |
+
teacher_plan = plan_for_scenario(scenario_id)
|
| 57 |
+
step_records: list[StepRecord] = []
|
| 58 |
+
failure_reason: str | None = None
|
| 59 |
+
final_score = 0.0
|
| 60 |
+
success = False
|
| 61 |
+
steps_taken = 0
|
| 62 |
+
previous_action: dict[str, Any] | None = None
|
| 63 |
+
repeated_no_progress = 0
|
| 64 |
+
|
| 65 |
+
with self._env_context() as env:
|
| 66 |
+
observation = self._unwrap_observation(env.reset(scenario_id=scenario_id))
|
| 67 |
+
while not observation.done:
|
| 68 |
+
teacher_action = (
|
| 69 |
+
teacher_plan[steps_taken].model_dump(exclude_none=True)
|
| 70 |
+
if steps_taken < len(teacher_plan)
|
| 71 |
+
else None
|
| 72 |
+
)
|
| 73 |
+
correction_text = self.correction_memory.build_prompt_addendum(
|
| 74 |
+
scenario_id=scenario_id,
|
| 75 |
+
stage=observation.workflow_stage,
|
| 76 |
+
)
|
| 77 |
+
system_prompt, user_prompt, response_format = build_runtime_request(
|
| 78 |
+
observation,
|
| 79 |
+
teacher_action=teacher_action,
|
| 80 |
+
correction_memory_text=correction_text,
|
| 81 |
+
strict=(mode == "strict"),
|
| 82 |
+
)
|
| 83 |
+
structured_mode = "backend_adaptive"
|
| 84 |
+
raw_model_output = ""
|
| 85 |
+
parse_result = None
|
| 86 |
+
repair_retry_used = False
|
| 87 |
+
teacher_override_used = False
|
| 88 |
+
|
| 89 |
+
if (
|
| 90 |
+
mode == "lenient"
|
| 91 |
+
and repeated_no_progress >= 2
|
| 92 |
+
and teacher_action is not None
|
| 93 |
+
):
|
| 94 |
+
parse_result = self._teacher_override_parse_result(teacher_action)
|
| 95 |
+
raw_model_output = json.dumps(teacher_action)
|
| 96 |
+
teacher_override_used = True
|
| 97 |
+
repeated_no_progress = 0
|
| 98 |
+
else:
|
| 99 |
+
response = self.backend.complete(
|
| 100 |
+
ModelRequest(
|
| 101 |
+
model_name=self.model_name,
|
| 102 |
+
system_prompt=system_prompt,
|
| 103 |
+
user_prompt=user_prompt,
|
| 104 |
+
structured_mode=structured_mode,
|
| 105 |
+
response_format=response_format,
|
| 106 |
+
)
|
| 107 |
+
)
|
| 108 |
+
raw_model_output = response.raw_text
|
| 109 |
+
parse_result = self.parser.parse(response.raw_text)
|
| 110 |
+
|
| 111 |
+
if (
|
| 112 |
+
mode == "lenient"
|
| 113 |
+
and parse_result.cleaned_action is None
|
| 114 |
+
):
|
| 115 |
+
repair_retry_used = True
|
| 116 |
+
repair_system, repair_user = build_repair_request(
|
| 117 |
+
observation,
|
| 118 |
+
raw_bad_output=response.raw_text,
|
| 119 |
+
parse_error=parse_result.error or parse_result.parse_status,
|
| 120 |
+
teacher_action=teacher_action,
|
| 121 |
+
)
|
| 122 |
+
repair_response = self.backend.complete(
|
| 123 |
+
ModelRequest(
|
| 124 |
+
model_name=self.model_name,
|
| 125 |
+
system_prompt=repair_system,
|
| 126 |
+
user_prompt=repair_user,
|
| 127 |
+
structured_mode=structured_mode,
|
| 128 |
+
response_format=response_format,
|
| 129 |
+
temperature=0.0,
|
| 130 |
+
)
|
| 131 |
+
)
|
| 132 |
+
raw_model_output = repair_response.raw_text
|
| 133 |
+
parse_result = self.parser.parse(repair_response.raw_text)
|
| 134 |
+
|
| 135 |
+
if (
|
| 136 |
+
mode == "lenient"
|
| 137 |
+
and parse_result.cleaned_action is None
|
| 138 |
+
and teacher_action is not None
|
| 139 |
+
):
|
| 140 |
+
parse_result = self._teacher_override_parse_result(teacher_action)
|
| 141 |
+
raw_model_output = json.dumps(teacher_action)
|
| 142 |
+
teacher_override_used = True
|
| 143 |
+
|
| 144 |
+
assert parse_result is not None
|
| 145 |
+
if parse_result.cleaned_action is None:
|
| 146 |
+
failure_reason = f"parse_failure:{parse_result.parse_status}"
|
| 147 |
+
observation_payload = observation.model_dump()
|
| 148 |
+
step_records.append(
|
| 149 |
+
StepRecord(
|
| 150 |
+
episode_id=episode_id,
|
| 151 |
+
scenario_id=scenario_id,
|
| 152 |
+
step_index=steps_taken + 1,
|
| 153 |
+
tick=observation.tick_count,
|
| 154 |
+
workflow_stage=observation.workflow_stage,
|
| 155 |
+
observation=observation_payload,
|
| 156 |
+
prompt_text=observation.prompt_text,
|
| 157 |
+
raw_model_output=raw_model_output,
|
| 158 |
+
parse_status=parse_result.parse_status,
|
| 159 |
+
normalization_applied=parse_result.repair_labels,
|
| 160 |
+
cleaned_action=None,
|
| 161 |
+
teacher_action=teacher_action,
|
| 162 |
+
reward=None,
|
| 163 |
+
cumulative_score=observation.final_score,
|
| 164 |
+
final_score_after_step=observation.final_score,
|
| 165 |
+
done=False,
|
| 166 |
+
next_prompt_text=None,
|
| 167 |
+
structured_mode_used=structured_mode,
|
| 168 |
+
repair_retry_used=repair_retry_used,
|
| 169 |
+
teacher_override_used=teacher_override_used,
|
| 170 |
+
failure_reason=parse_result.error,
|
| 171 |
+
failure_type=parse_result.parse_status,
|
| 172 |
+
)
|
| 173 |
+
)
|
| 174 |
+
break
|
| 175 |
+
|
| 176 |
+
action = UnifiedIncidentAction(**parse_result.cleaned_action)
|
| 177 |
+
step = self._unwrap_observation(env.step(action))
|
| 178 |
+
observation_payload = observation.model_dump()
|
| 179 |
+
step_records.append(
|
| 180 |
+
StepRecord(
|
| 181 |
+
episode_id=episode_id,
|
| 182 |
+
scenario_id=scenario_id,
|
| 183 |
+
step_index=steps_taken + 1,
|
| 184 |
+
tick=observation.tick_count,
|
| 185 |
+
workflow_stage=observation.workflow_stage,
|
| 186 |
+
observation=observation_payload,
|
| 187 |
+
prompt_text=observation.prompt_text,
|
| 188 |
+
raw_model_output=raw_model_output,
|
| 189 |
+
parse_status=parse_result.parse_status,
|
| 190 |
+
normalization_applied=parse_result.repair_labels,
|
| 191 |
+
cleaned_action=parse_result.cleaned_action,
|
| 192 |
+
teacher_action=teacher_action,
|
| 193 |
+
reward=step.reward,
|
| 194 |
+
cumulative_score=step.final_score,
|
| 195 |
+
final_score_after_step=step.final_score,
|
| 196 |
+
done=step.done,
|
| 197 |
+
next_prompt_text=step.prompt_text,
|
| 198 |
+
structured_mode_used=structured_mode,
|
| 199 |
+
repair_retry_used=repair_retry_used,
|
| 200 |
+
teacher_override_used=teacher_override_used,
|
| 201 |
+
failure_reason=None,
|
| 202 |
+
failure_type=None,
|
| 203 |
+
)
|
| 204 |
+
)
|
| 205 |
+
if step.reward is not None and step.reward <= 0 and parse_result.cleaned_action == previous_action:
|
| 206 |
+
repeated_no_progress += 1
|
| 207 |
+
else:
|
| 208 |
+
repeated_no_progress = 0
|
| 209 |
+
previous_action = parse_result.cleaned_action
|
| 210 |
+
observation = step
|
| 211 |
+
steps_taken += 1
|
| 212 |
+
|
| 213 |
+
if failure_reason is None:
|
| 214 |
+
success = bool(observation.done and observation.incident_resolved)
|
| 215 |
+
final_score = observation.final_score
|
| 216 |
+
if not success:
|
| 217 |
+
failure_reason = f"stopped:{observation.workflow_stage}"
|
| 218 |
+
else:
|
| 219 |
+
final_score = observation.final_score
|
| 220 |
+
|
| 221 |
+
elapsed_s = round(time.perf_counter() - started, 4)
|
| 222 |
+
return EpisodeRecord(
|
| 223 |
+
run_id=str(uuid.uuid4()),
|
| 224 |
+
episode_id=episode_id,
|
| 225 |
+
scenario_id=scenario_id,
|
| 226 |
+
difficulty=scenario["difficulty"],
|
| 227 |
+
model_name=self.model_name,
|
| 228 |
+
model_version=model_version,
|
| 229 |
+
mode=mode,
|
| 230 |
+
success=success,
|
| 231 |
+
final_score=final_score,
|
| 232 |
+
steps=steps_taken,
|
| 233 |
+
failure_reason=failure_reason,
|
| 234 |
+
elapsed_s=elapsed_s,
|
| 235 |
+
json_valid_steps=sum(
|
| 236 |
+
1 for step in step_records if step.parse_status in {"ok", "repaired", "teacher_override"}
|
| 237 |
+
),
|
| 238 |
+
strict_schema_valid_steps=sum(
|
| 239 |
+
1 for step in step_records if step.parse_status == "ok"
|
| 240 |
+
),
|
| 241 |
+
teacher_override_count=sum(1 for step in step_records if step.teacher_override_used),
|
| 242 |
+
repair_retry_count=sum(1 for step in step_records if step.repair_retry_used),
|
| 243 |
+
security_subquest_completed=bool(
|
| 244 |
+
step_records and any(
|
| 245 |
+
step.cleaned_action and step.cleaned_action.get("action_type") == "submit_security_fix"
|
| 246 |
+
for step in step_records
|
| 247 |
+
)
|
| 248 |
+
),
|
| 249 |
+
postmortem_completed=bool(
|
| 250 |
+
step_records and any(
|
| 251 |
+
step.cleaned_action and step.cleaned_action.get("action_type") == "submit_postmortem"
|
| 252 |
+
for step in step_records
|
| 253 |
+
)
|
| 254 |
+
),
|
| 255 |
+
stopped_reason=(
|
| 256 |
+
failure_reason.split(":", 1)[1]
|
| 257 |
+
if failure_reason and failure_reason.startswith("stopped:")
|
| 258 |
+
else failure_reason
|
| 259 |
+
),
|
| 260 |
+
step_records=step_records,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
def _env_context(self):
|
| 264 |
+
if self.base_url is not None:
|
| 265 |
+
return UnifiedIncidentEnv(base_url=self.base_url).sync()
|
| 266 |
+
return _LocalEnvironmentContext(self.env_factory or UnifiedIncidentEnvironment)
|
| 267 |
+
|
| 268 |
+
def _unwrap_observation(self, value):
|
| 269 |
+
return value.observation if hasattr(value, "observation") else value
|
| 270 |
+
|
| 271 |
+
def _teacher_override_parse_result(self, teacher_action: dict[str, Any]):
|
| 272 |
+
from .types import ParseResult
|
| 273 |
+
|
| 274 |
+
return ParseResult(
|
| 275 |
+
parse_status="teacher_override",
|
| 276 |
+
cleaned_action=teacher_action,
|
| 277 |
+
repair_labels=["teacher_override"],
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class _LocalEnvironmentContext:
|
| 282 |
+
"""Simple context wrapper for direct environment instances."""
|
| 283 |
+
|
| 284 |
+
def __init__(self, factory) -> None:
|
| 285 |
+
self.factory = factory
|
| 286 |
+
self.instance = None
|
| 287 |
+
|
| 288 |
+
def __enter__(self):
|
| 289 |
+
self.instance = self.factory()
|
| 290 |
+
return self.instance
|
| 291 |
+
|
| 292 |
+
def __exit__(self, exc_type, exc, tb):
|
| 293 |
+
self.instance = None
|
| 294 |
+
return False
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def run_episode(
|
| 298 |
+
*,
|
| 299 |
+
model_name: str,
|
| 300 |
+
scenario_id: str,
|
| 301 |
+
mode: str,
|
| 302 |
+
base_url: str | None,
|
| 303 |
+
api_base_url: str,
|
| 304 |
+
api_key: str,
|
| 305 |
+
output_path: Path | None = None,
|
| 306 |
+
) -> EpisodeRecord:
|
| 307 |
+
parser = StrictActionParser() if mode == "strict" else LenientActionAdapter()
|
| 308 |
+
backend = OpenAICompatibleBackend(base_url=api_base_url, api_key=api_key)
|
| 309 |
+
runner = EpisodeRunner(
|
| 310 |
+
backend=backend,
|
| 311 |
+
parser=parser,
|
| 312 |
+
model_name=model_name,
|
| 313 |
+
base_url=base_url,
|
| 314 |
+
)
|
| 315 |
+
record = runner.run(scenario_id=scenario_id, mode=mode)
|
| 316 |
+
if output_path is not None:
|
| 317 |
+
TrajectoryStore(output_path).append_episode(record)
|
| 318 |
+
return record
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def main() -> None:
|
| 322 |
+
parser = argparse.ArgumentParser()
|
| 323 |
+
parser.add_argument("--model", required=True)
|
| 324 |
+
parser.add_argument("--scenario", required=True, choices=sorted(SCENARIOS))
|
| 325 |
+
parser.add_argument("--mode", choices=["strict", "lenient"], default="strict")
|
| 326 |
+
parser.add_argument("--base-url", default=UnifiedIncidentEnv.DEFAULT_BASE_URL)
|
| 327 |
+
parser.add_argument(
|
| 328 |
+
"--api-base-url",
|
| 329 |
+
default=os.environ.get("API_BASE_URL", "http://127.0.0.1:11434/v1"),
|
| 330 |
+
)
|
| 331 |
+
parser.add_argument(
|
| 332 |
+
"--api-key",
|
| 333 |
+
default=os.environ.get("OPENAI_API_KEY") or os.environ.get("HF_TOKEN") or "local",
|
| 334 |
+
)
|
| 335 |
+
parser.add_argument(
|
| 336 |
+
"--output",
|
| 337 |
+
default="outputs/trainer/episodes.jsonl",
|
| 338 |
+
)
|
| 339 |
+
args = parser.parse_args()
|
| 340 |
+
|
| 341 |
+
record = run_episode(
|
| 342 |
+
model_name=args.model,
|
| 343 |
+
scenario_id=args.scenario,
|
| 344 |
+
mode=args.mode,
|
| 345 |
+
base_url=args.base_url,
|
| 346 |
+
api_base_url=args.api_base_url,
|
| 347 |
+
api_key=args.api_key,
|
| 348 |
+
output_path=Path(args.output),
|
| 349 |
+
)
|
| 350 |
+
print(record.model_dump_json(indent=2))
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
if __name__ == "__main__":
|
| 354 |
+
main()
|
unified_incident_env/trainer/run_session.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ten-episode session loop with failure analysis and pluggable updates."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from .action_adapter import LenientActionAdapter, StrictActionParser
|
| 10 |
+
from .backend import OpenAICompatibleBackend
|
| 11 |
+
from .build_datasets import (
|
| 12 |
+
build_baseline_records,
|
| 13 |
+
build_next_action_records,
|
| 14 |
+
build_recovery_records,
|
| 15 |
+
build_schema_repair_records,
|
| 16 |
+
combine_sft_records,
|
| 17 |
+
write_jsonl,
|
| 18 |
+
)
|
| 19 |
+
from .collect_trajectory import collect_episode
|
| 20 |
+
from .reporting import build_phase_deltas, write_session_outputs
|
| 21 |
+
from .run_episode import EpisodeRunner
|
| 22 |
+
from .session_config import make_session_config_from_env
|
| 23 |
+
from .policy_adapter import PolicyAdapter
|
| 24 |
+
from .trajectory_memory import CorrectionMemory
|
| 25 |
+
from .types import SessionPhaseReport, SessionReport, UpdateRequest, UpdateResult
|
| 26 |
+
from .update_model import build_updater
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _extract_policy_adapter_path(model_after: str) -> str | None:
|
| 30 |
+
prefix = "policy_adapter::"
|
| 31 |
+
if not model_after.startswith(prefix):
|
| 32 |
+
return None
|
| 33 |
+
parts = model_after.split("::", 2)
|
| 34 |
+
if len(parts) != 3:
|
| 35 |
+
return None
|
| 36 |
+
return parts[2]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _base_model_from_version(model_version: str) -> str:
|
| 40 |
+
prefix = "policy_adapter::"
|
| 41 |
+
if model_version.startswith(prefix):
|
| 42 |
+
parts = model_version.split("::", 2)
|
| 43 |
+
if len(parts) == 3:
|
| 44 |
+
return parts[1]
|
| 45 |
+
return model_version
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _memory_from_policy_adapter(path: Path) -> CorrectionMemory:
|
| 49 |
+
adapter = PolicyAdapter.load(path)
|
| 50 |
+
memory = CorrectionMemory()
|
| 51 |
+
from .trajectory_memory import MemoryExample
|
| 52 |
+
|
| 53 |
+
for row in adapter.schema_examples:
|
| 54 |
+
memory.schema_examples.setdefault(row["scenario_id"], []).append(
|
| 55 |
+
MemoryExample(
|
| 56 |
+
scenario_id=row["scenario_id"],
|
| 57 |
+
stage=row.get("metadata", {}).get("workflow_stage", "diagnosis"),
|
| 58 |
+
prompt_text=row["messages"][-1]["content"],
|
| 59 |
+
raw_output=json.dumps(row.get("student_action", {}) or {}),
|
| 60 |
+
corrected_action=row["target_action"],
|
| 61 |
+
tags=row.get("tags", []),
|
| 62 |
+
failure_type=(row.get("tags") or [None])[0],
|
| 63 |
+
action_family=None,
|
| 64 |
+
mistake=row.get("metadata", {}).get("failure_reason", ""),
|
| 65 |
+
correction=f"Use {row['target_action'].get('action_type', 'the valid action')} instead.",
|
| 66 |
+
)
|
| 67 |
+
)
|
| 68 |
+
for row in adapter.next_action_examples:
|
| 69 |
+
memory.next_action_examples.setdefault(row["scenario_id"], []).append(
|
| 70 |
+
MemoryExample(
|
| 71 |
+
scenario_id=row["scenario_id"],
|
| 72 |
+
stage=row.get("metadata", {}).get("workflow_stage", "diagnosis"),
|
| 73 |
+
prompt_text=row["messages"][-1]["content"],
|
| 74 |
+
raw_output=json.dumps(row.get("student_action", {}) or {}),
|
| 75 |
+
corrected_action=row["target_action"],
|
| 76 |
+
tags=row.get("tags", []),
|
| 77 |
+
failure_type=(row.get("tags") or [None])[0],
|
| 78 |
+
action_family=None,
|
| 79 |
+
mistake=row.get("metadata", {}).get("failure_reason", ""),
|
| 80 |
+
correction=f"Use {row['target_action'].get('action_type', 'the valid action')} instead.",
|
| 81 |
+
)
|
| 82 |
+
)
|
| 83 |
+
for row in adapter.recovery_examples:
|
| 84 |
+
memory.recovery_examples.setdefault(row["scenario_id"], []).append(
|
| 85 |
+
MemoryExample(
|
| 86 |
+
scenario_id=row["scenario_id"],
|
| 87 |
+
stage=row.get("metadata", {}).get("workflow_stage", "diagnosis"),
|
| 88 |
+
prompt_text=row["messages"][-1]["content"],
|
| 89 |
+
raw_output=json.dumps(row.get("student_action", {}) or {}),
|
| 90 |
+
corrected_action=row["target_action"],
|
| 91 |
+
tags=row.get("tags", []),
|
| 92 |
+
failure_type=(row.get("tags") or [None])[0],
|
| 93 |
+
action_family=None,
|
| 94 |
+
mistake=row.get("metadata", {}).get("failure_reason", ""),
|
| 95 |
+
correction=f"Recover with {row['target_action'].get('action_type', 'the valid action')}.",
|
| 96 |
+
)
|
| 97 |
+
)
|
| 98 |
+
return memory
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def run_session(config, *, backend=None, runner_factory=EpisodeRunner, updater=None):
|
| 102 |
+
output_dir = Path(config.output_root)
|
| 103 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 104 |
+
checkpoints_dir = output_dir / "checkpoints"
|
| 105 |
+
checkpoints_dir.mkdir(parents=True, exist_ok=True)
|
| 106 |
+
|
| 107 |
+
if backend is None:
|
| 108 |
+
backend = OpenAICompatibleBackend(
|
| 109 |
+
base_url=config.api_base_url,
|
| 110 |
+
api_key=config.api_key,
|
| 111 |
+
)
|
| 112 |
+
if updater is None:
|
| 113 |
+
updater = build_updater(
|
| 114 |
+
config.updater_backend,
|
| 115 |
+
runtime_mode=config.runtime_mode,
|
| 116 |
+
command_template=config.updater_command_template,
|
| 117 |
+
openai_base_url=config.api_base_url,
|
| 118 |
+
api_key=config.api_key,
|
| 119 |
+
)
|
| 120 |
+
phase_reports: list[SessionPhaseReport] = []
|
| 121 |
+
|
| 122 |
+
baseline_records = build_baseline_records()
|
| 123 |
+
write_jsonl(baseline_records, output_dir / "baseline_teacher_dataset.jsonl")
|
| 124 |
+
memory_path = output_dir / "correction_memory.json"
|
| 125 |
+
correction_memory = CorrectionMemory.load(memory_path)
|
| 126 |
+
|
| 127 |
+
all_records = []
|
| 128 |
+
all_summaries = []
|
| 129 |
+
all_updates = []
|
| 130 |
+
all_schema_records = []
|
| 131 |
+
all_next_action_records = []
|
| 132 |
+
all_recovery_records = []
|
| 133 |
+
|
| 134 |
+
current_model_version = config.initial_model_version
|
| 135 |
+
|
| 136 |
+
for phase in config.phases:
|
| 137 |
+
mode = (
|
| 138 |
+
config.final_eval_mode
|
| 139 |
+
if phase.phase_name == "final_evaluation"
|
| 140 |
+
else config.collection_mode
|
| 141 |
+
)
|
| 142 |
+
parser_impl = StrictActionParser() if mode == "strict" else LenientActionAdapter()
|
| 143 |
+
runner = runner_factory(
|
| 144 |
+
backend=backend,
|
| 145 |
+
parser=parser_impl,
|
| 146 |
+
model_name=config.model_name,
|
| 147 |
+
base_url=config.base_url,
|
| 148 |
+
correction_memory=correction_memory,
|
| 149 |
+
)
|
| 150 |
+
phase_records = []
|
| 151 |
+
phase_summaries = []
|
| 152 |
+
phase_analyses = []
|
| 153 |
+
|
| 154 |
+
for episode_id in phase.episode_ids:
|
| 155 |
+
scenario_id = config.scenario_schedule[episode_id - 1]
|
| 156 |
+
record, summary, analysis = collect_episode(
|
| 157 |
+
runner=runner,
|
| 158 |
+
scenario_id=scenario_id,
|
| 159 |
+
episode_id=episode_id,
|
| 160 |
+
mode=mode,
|
| 161 |
+
model_version=current_model_version,
|
| 162 |
+
)
|
| 163 |
+
phase_records.append(record)
|
| 164 |
+
phase_summaries.append(summary)
|
| 165 |
+
phase_analyses.append(analysis)
|
| 166 |
+
all_records.append(record)
|
| 167 |
+
all_summaries.append(summary)
|
| 168 |
+
correction_memory.add_episode_examples(record, analysis)
|
| 169 |
+
correction_memory.save(memory_path)
|
| 170 |
+
|
| 171 |
+
update_ids = []
|
| 172 |
+
if phase.update_after and phase.update_index is not None:
|
| 173 |
+
update_dir = checkpoints_dir / f"update_{phase.update_index:02d}"
|
| 174 |
+
schema_records = build_schema_repair_records(phase_records, phase_analyses)
|
| 175 |
+
next_action_records = build_next_action_records(phase_records, phase_analyses)
|
| 176 |
+
recovery_records = build_recovery_records(phase_records, phase_analyses)
|
| 177 |
+
combined_records = combine_sft_records(
|
| 178 |
+
baseline_records=[],
|
| 179 |
+
schema_records=schema_records,
|
| 180 |
+
next_action_records=next_action_records,
|
| 181 |
+
recovery_records=recovery_records,
|
| 182 |
+
)
|
| 183 |
+
write_jsonl(schema_records, update_dir / "schema_repair.jsonl")
|
| 184 |
+
write_jsonl(next_action_records, update_dir / "next_action.jsonl")
|
| 185 |
+
write_jsonl(recovery_records, update_dir / "recovery.jsonl")
|
| 186 |
+
write_jsonl(combined_records, update_dir / "sft_dataset.jsonl")
|
| 187 |
+
|
| 188 |
+
all_schema_records.extend(schema_records)
|
| 189 |
+
all_next_action_records.extend(next_action_records)
|
| 190 |
+
all_recovery_records.extend(recovery_records)
|
| 191 |
+
|
| 192 |
+
update_request = UpdateRequest(
|
| 193 |
+
update_index=phase.update_index,
|
| 194 |
+
phase_name=phase.phase_name,
|
| 195 |
+
episodes_used=phase.episode_ids,
|
| 196 |
+
datasets_used=[
|
| 197 |
+
str(update_dir / "schema_repair.jsonl"),
|
| 198 |
+
str(update_dir / "next_action.jsonl"),
|
| 199 |
+
str(update_dir / "recovery.jsonl"),
|
| 200 |
+
str(update_dir / "sft_dataset.jsonl"),
|
| 201 |
+
],
|
| 202 |
+
model_before=_base_model_from_version(current_model_version),
|
| 203 |
+
output_dir=str(update_dir.resolve()),
|
| 204 |
+
runtime_mode=config.runtime_mode,
|
| 205 |
+
command_template=config.updater_command_template,
|
| 206 |
+
training_file=str((update_dir / "sft_dataset.jsonl").resolve()),
|
| 207 |
+
suffix=f"{phase.phase_name[:10]}-{phase.update_index:02d}",
|
| 208 |
+
)
|
| 209 |
+
update_result = updater.update(update_request)
|
| 210 |
+
if not isinstance(update_result, UpdateResult):
|
| 211 |
+
update_result = UpdateResult.model_validate(
|
| 212 |
+
update_result,
|
| 213 |
+
from_attributes=True,
|
| 214 |
+
)
|
| 215 |
+
all_updates.append(update_result)
|
| 216 |
+
if update_result.status == "completed":
|
| 217 |
+
current_model_version = update_result.model_after
|
| 218 |
+
adapter_path = _extract_policy_adapter_path(update_result.model_after)
|
| 219 |
+
if adapter_path is not None and Path(adapter_path).exists():
|
| 220 |
+
correction_memory.merge(
|
| 221 |
+
_memory_from_policy_adapter(Path(adapter_path))
|
| 222 |
+
)
|
| 223 |
+
correction_memory.save(memory_path)
|
| 224 |
+
update_ids.append(update_result.update_index)
|
| 225 |
+
|
| 226 |
+
phase_report = SessionPhaseReport(
|
| 227 |
+
phase_name=phase.phase_name,
|
| 228 |
+
episode_ids=phase.episode_ids,
|
| 229 |
+
avg_score=round(
|
| 230 |
+
sum(summary.final_score for summary in phase_summaries) / len(phase_summaries),
|
| 231 |
+
4,
|
| 232 |
+
),
|
| 233 |
+
success_rate=round(
|
| 234 |
+
sum(1 for summary in phase_summaries if summary.success) / len(phase_summaries),
|
| 235 |
+
4,
|
| 236 |
+
),
|
| 237 |
+
schema_failures=sum(summary.schema_failures for summary in phase_summaries),
|
| 238 |
+
loop_failures=sum(len(summary.looping_failures) for summary in phase_summaries),
|
| 239 |
+
updates_applied=update_ids,
|
| 240 |
+
)
|
| 241 |
+
phase_reports.append(phase_report)
|
| 242 |
+
|
| 243 |
+
write_jsonl(all_schema_records, output_dir / "schema_repair.jsonl")
|
| 244 |
+
write_jsonl(all_next_action_records, output_dir / "next_action.jsonl")
|
| 245 |
+
write_jsonl(all_recovery_records, output_dir / "recovery.jsonl")
|
| 246 |
+
write_jsonl(
|
| 247 |
+
combine_sft_records(
|
| 248 |
+
baseline_records=baseline_records,
|
| 249 |
+
schema_records=all_schema_records,
|
| 250 |
+
next_action_records=all_next_action_records,
|
| 251 |
+
recovery_records=all_recovery_records,
|
| 252 |
+
),
|
| 253 |
+
output_dir / "sft_dataset.jsonl",
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
initial_phase = [summary for summary in all_summaries if summary.episode_id in {1, 2}]
|
| 257 |
+
final_phase = [summary for summary in all_summaries if summary.episode_id in {9, 10}]
|
| 258 |
+
improvement_metrics = {
|
| 259 |
+
"score_delta_ep1_2_to_ep9_10": round(
|
| 260 |
+
(
|
| 261 |
+
sum(item.final_score for item in final_phase) / len(final_phase)
|
| 262 |
+
if final_phase
|
| 263 |
+
else 0.0
|
| 264 |
+
)
|
| 265 |
+
- (
|
| 266 |
+
sum(item.final_score for item in initial_phase) / len(initial_phase)
|
| 267 |
+
if initial_phase
|
| 268 |
+
else 0.0
|
| 269 |
+
),
|
| 270 |
+
4,
|
| 271 |
+
),
|
| 272 |
+
"schema_failure_delta_ep1_2_to_ep9_10": round(
|
| 273 |
+
(
|
| 274 |
+
sum(item.schema_failures for item in initial_phase) / len(initial_phase)
|
| 275 |
+
if initial_phase
|
| 276 |
+
else 0.0
|
| 277 |
+
)
|
| 278 |
+
- (
|
| 279 |
+
sum(item.schema_failures for item in final_phase) / len(final_phase)
|
| 280 |
+
if final_phase
|
| 281 |
+
else 0.0
|
| 282 |
+
),
|
| 283 |
+
4,
|
| 284 |
+
),
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
report = SessionReport(
|
| 288 |
+
session_id=config.session_id,
|
| 289 |
+
model_name=config.model_name,
|
| 290 |
+
runtime_mode=config.runtime_mode,
|
| 291 |
+
output_dir=str(output_dir),
|
| 292 |
+
episode_summaries=all_summaries,
|
| 293 |
+
updates=all_updates,
|
| 294 |
+
phase_reports=phase_reports,
|
| 295 |
+
phase_deltas=build_phase_deltas(phase_reports),
|
| 296 |
+
improvement_metrics=improvement_metrics,
|
| 297 |
+
correction_memory_stats=correction_memory.stats(),
|
| 298 |
+
)
|
| 299 |
+
write_session_outputs(
|
| 300 |
+
output_dir=output_dir,
|
| 301 |
+
report=report,
|
| 302 |
+
records=all_records,
|
| 303 |
+
include_prompts=config.log_rendered_prompts,
|
| 304 |
+
)
|
| 305 |
+
return report
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def main() -> None:
|
| 309 |
+
parser = argparse.ArgumentParser()
|
| 310 |
+
parser.add_argument("--model", default="qwen2.5:1.5b")
|
| 311 |
+
parser.add_argument("--base-url", default="http://127.0.0.1:8000")
|
| 312 |
+
parser.add_argument("--output-root", default="outputs/trainer")
|
| 313 |
+
parser.add_argument("--runtime-mode", choices=["competition", "research"], default="competition")
|
| 314 |
+
parser.add_argument("--collection-mode", choices=["strict", "lenient"], default="lenient")
|
| 315 |
+
parser.add_argument("--final-eval-mode", choices=["strict", "lenient"], default="strict")
|
| 316 |
+
parser.add_argument("--updater-backend", choices=["noop", "external_command", "openai_finetune"], default="external_command")
|
| 317 |
+
parser.add_argument("--updater-command-template", default=None)
|
| 318 |
+
parser.add_argument("--log-rendered-prompts", action="store_true")
|
| 319 |
+
args = parser.parse_args()
|
| 320 |
+
|
| 321 |
+
config = make_session_config_from_env(
|
| 322 |
+
model_name=args.model,
|
| 323 |
+
output_root=args.output_root,
|
| 324 |
+
base_url=args.base_url,
|
| 325 |
+
runtime_mode=args.runtime_mode,
|
| 326 |
+
collection_mode=args.collection_mode,
|
| 327 |
+
final_eval_mode=args.final_eval_mode,
|
| 328 |
+
updater_backend=args.updater_backend,
|
| 329 |
+
updater_command_template=args.updater_command_template,
|
| 330 |
+
log_rendered_prompts=args.log_rendered_prompts if args.log_rendered_prompts else None,
|
| 331 |
+
)
|
| 332 |
+
report = run_session(config)
|
| 333 |
+
print(report.model_dump_json(indent=2))
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
if __name__ == "__main__":
|
| 337 |
+
main()
|
unified_incident_env/trainer/session_config.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration helpers for the ten-episode session loop."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import uuid
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from ..server.challenge import SCENARIOS
|
| 10 |
+
from .types import RuntimeMode, SessionConfig, SessionPhaseConfig
|
| 11 |
+
|
| 12 |
+
DEFAULT_UPDATE_EPISODES = (2, 5, 8)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def default_scenario_schedule() -> list[str]:
|
| 16 |
+
"""Return a deterministic ten-episode round-robin schedule."""
|
| 17 |
+
ordered = list(SCENARIOS)
|
| 18 |
+
schedule: list[str] = []
|
| 19 |
+
while len(schedule) < 10:
|
| 20 |
+
schedule.extend(ordered)
|
| 21 |
+
return schedule[:10]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def default_phases() -> list[SessionPhaseConfig]:
|
| 25 |
+
"""Return the fixed four-phase ten-episode schedule."""
|
| 26 |
+
return [
|
| 27 |
+
SessionPhaseConfig(
|
| 28 |
+
phase_name="probe",
|
| 29 |
+
episode_ids=[1, 2],
|
| 30 |
+
update_after=True,
|
| 31 |
+
update_index=1,
|
| 32 |
+
),
|
| 33 |
+
SessionPhaseConfig(
|
| 34 |
+
phase_name="first_correction",
|
| 35 |
+
episode_ids=[3, 4, 5],
|
| 36 |
+
update_after=True,
|
| 37 |
+
update_index=2,
|
| 38 |
+
),
|
| 39 |
+
SessionPhaseConfig(
|
| 40 |
+
phase_name="workflow_correction",
|
| 41 |
+
episode_ids=[6, 7, 8],
|
| 42 |
+
update_after=True,
|
| 43 |
+
update_index=3,
|
| 44 |
+
),
|
| 45 |
+
SessionPhaseConfig(
|
| 46 |
+
phase_name="final_evaluation",
|
| 47 |
+
episode_ids=[9, 10],
|
| 48 |
+
update_after=False,
|
| 49 |
+
update_index=None,
|
| 50 |
+
),
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def make_session_config(
|
| 55 |
+
*,
|
| 56 |
+
model_name: str,
|
| 57 |
+
output_root: str | Path,
|
| 58 |
+
base_url: str | None,
|
| 59 |
+
api_base_url: str,
|
| 60 |
+
api_key: str,
|
| 61 |
+
runtime_mode: RuntimeMode = "competition",
|
| 62 |
+
collection_mode: str = "lenient",
|
| 63 |
+
final_eval_mode: str = "strict",
|
| 64 |
+
updater_backend: str = "external_command",
|
| 65 |
+
updater_command_template: str | None = None,
|
| 66 |
+
scenario_schedule: list[str] | None = None,
|
| 67 |
+
phases: list[SessionPhaseConfig] | None = None,
|
| 68 |
+
log_rendered_prompts: bool | None = None,
|
| 69 |
+
) -> SessionConfig:
|
| 70 |
+
"""Create one deterministic session config."""
|
| 71 |
+
session_id = uuid.uuid4().hex[:12]
|
| 72 |
+
output_root_path = Path(output_root)
|
| 73 |
+
output_dir = output_root_path / f"session-{session_id}"
|
| 74 |
+
schedule = scenario_schedule or default_scenario_schedule()
|
| 75 |
+
if log_rendered_prompts is None:
|
| 76 |
+
log_rendered_prompts = runtime_mode == "research"
|
| 77 |
+
return SessionConfig(
|
| 78 |
+
session_id=session_id,
|
| 79 |
+
model_name=model_name,
|
| 80 |
+
initial_model_version=model_name,
|
| 81 |
+
runtime_mode=runtime_mode,
|
| 82 |
+
collection_mode=collection_mode,
|
| 83 |
+
final_eval_mode=final_eval_mode,
|
| 84 |
+
log_rendered_prompts=log_rendered_prompts,
|
| 85 |
+
base_url=base_url,
|
| 86 |
+
api_base_url=api_base_url,
|
| 87 |
+
api_key=api_key,
|
| 88 |
+
output_root=str(output_dir),
|
| 89 |
+
scenario_schedule=schedule,
|
| 90 |
+
phases=phases or default_phases(),
|
| 91 |
+
updater_backend=updater_backend,
|
| 92 |
+
updater_command_template=updater_command_template,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def make_session_config_from_env(
|
| 97 |
+
*,
|
| 98 |
+
model_name: str = "qwen2.5:1.5b",
|
| 99 |
+
output_root: str | Path = "outputs/trainer",
|
| 100 |
+
base_url: str | None = None,
|
| 101 |
+
runtime_mode: RuntimeMode = "competition",
|
| 102 |
+
collection_mode: str = "lenient",
|
| 103 |
+
final_eval_mode: str = "strict",
|
| 104 |
+
updater_backend: str = "external_command",
|
| 105 |
+
updater_command_template: str | None = None,
|
| 106 |
+
phases: list[SessionPhaseConfig] | None = None,
|
| 107 |
+
log_rendered_prompts: bool | None = None,
|
| 108 |
+
) -> SessionConfig:
|
| 109 |
+
"""Create a session config using the common environment variables."""
|
| 110 |
+
return make_session_config(
|
| 111 |
+
model_name=model_name,
|
| 112 |
+
output_root=output_root,
|
| 113 |
+
base_url=base_url,
|
| 114 |
+
runtime_mode=runtime_mode,
|
| 115 |
+
api_base_url=os.environ.get("API_BASE_URL", "http://127.0.0.1:11434/v1"),
|
| 116 |
+
api_key=os.environ.get("OPENAI_API_KEY")
|
| 117 |
+
or os.environ.get("HF_TOKEN")
|
| 118 |
+
or "local",
|
| 119 |
+
collection_mode=collection_mode,
|
| 120 |
+
final_eval_mode=final_eval_mode,
|
| 121 |
+
updater_backend=updater_backend,
|
| 122 |
+
updater_command_template=updater_command_template,
|
| 123 |
+
phases=phases,
|
| 124 |
+
log_rendered_prompts=log_rendered_prompts,
|
| 125 |
+
)
|
unified_incident_env/trainer/train_external.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Default lightweight external trainer wrapper for session updates."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from .policy_adapter import PolicyAdapter
|
| 10 |
+
from .types import UpdateRequest
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _load_jsonl(path: Path) -> list[dict]:
|
| 14 |
+
if not path.exists():
|
| 15 |
+
return []
|
| 16 |
+
rows = []
|
| 17 |
+
with path.open(encoding="utf-8") as handle:
|
| 18 |
+
for line in handle:
|
| 19 |
+
line = line.strip()
|
| 20 |
+
if line:
|
| 21 |
+
rows.append(json.loads(line))
|
| 22 |
+
return rows
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def build_policy_adapter(request: UpdateRequest) -> PolicyAdapter:
|
| 26 |
+
"""Build a lightweight policy adapter from phase datasets."""
|
| 27 |
+
schema_rows = _load_jsonl(Path(request.output_dir) / "schema_repair.jsonl")
|
| 28 |
+
next_action_rows = _load_jsonl(Path(request.output_dir) / "next_action.jsonl")
|
| 29 |
+
recovery_rows = _load_jsonl(Path(request.output_dir) / "recovery.jsonl")
|
| 30 |
+
|
| 31 |
+
if request.phase_name == "probe":
|
| 32 |
+
schema_rows = schema_rows[:12]
|
| 33 |
+
next_action_rows = next_action_rows[:4]
|
| 34 |
+
recovery_rows = []
|
| 35 |
+
elif request.phase_name == "first_correction":
|
| 36 |
+
schema_rows = schema_rows[:12]
|
| 37 |
+
next_action_rows = next_action_rows[:12]
|
| 38 |
+
recovery_rows = []
|
| 39 |
+
else:
|
| 40 |
+
schema_rows = schema_rows[:8]
|
| 41 |
+
next_action_rows = next_action_rows[:8]
|
| 42 |
+
recovery_rows = recovery_rows[:12]
|
| 43 |
+
|
| 44 |
+
return PolicyAdapter(
|
| 45 |
+
base_model=_base_model_from_version(request.model_before),
|
| 46 |
+
phase_name=request.phase_name,
|
| 47 |
+
schema_examples=schema_rows,
|
| 48 |
+
next_action_examples=next_action_rows,
|
| 49 |
+
recovery_examples=recovery_rows,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _base_model_from_version(model_version: str) -> str:
|
| 54 |
+
prefix = "policy_adapter::"
|
| 55 |
+
if model_version.startswith(prefix):
|
| 56 |
+
parts = model_version.split("::", 2)
|
| 57 |
+
if len(parts) == 3:
|
| 58 |
+
return parts[1]
|
| 59 |
+
return model_version
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def main() -> None:
|
| 63 |
+
parser = argparse.ArgumentParser()
|
| 64 |
+
parser.add_argument("--request", required=True)
|
| 65 |
+
args = parser.parse_args()
|
| 66 |
+
|
| 67 |
+
request = UpdateRequest.model_validate_json(Path(args.request).read_text(encoding="utf-8"))
|
| 68 |
+
output_dir = Path(request.output_dir)
|
| 69 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 70 |
+
adapter = build_policy_adapter(request)
|
| 71 |
+
adapter_path = output_dir / "policy_adapter.json"
|
| 72 |
+
adapter.save(adapter_path)
|
| 73 |
+
result = {
|
| 74 |
+
"status": "completed",
|
| 75 |
+
"model_after": f"policy_adapter::{request.model_before}::{adapter_path}",
|
| 76 |
+
"notes": (
|
| 77 |
+
f"built adapter with schema={len(adapter.schema_examples)} "
|
| 78 |
+
f"next_action={len(adapter.next_action_examples)} "
|
| 79 |
+
f"recovery={len(adapter.recovery_examples)}"
|
| 80 |
+
),
|
| 81 |
+
"artifact_paths": [str(adapter_path)],
|
| 82 |
+
}
|
| 83 |
+
result_path = output_dir / f"update_{request.update_index:02d}_external_result.json"
|
| 84 |
+
result_path.write_text(json.dumps(result, indent=2), encoding="utf-8")
|
| 85 |
+
print(json.dumps(result, indent=2))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
main()
|
unified_incident_env/trainer/trajectory_memory.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compact policy-card memory for in-session improvement without weight updates."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from dataclasses import dataclass, field
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from .types import EpisodeRecord, FailureAnalysisReport
|
| 10 |
+
|
| 11 |
+
SCHEMA_RULES = [
|
| 12 |
+
"Return JSON only.",
|
| 13 |
+
"Use action_type.",
|
| 14 |
+
"Use only allowed actions.",
|
| 15 |
+
"Do not add explanation text.",
|
| 16 |
+
]
|
| 17 |
+
MAX_POLICY_WORDS = 300
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class MemoryExample:
|
| 22 |
+
"""One stored correction example."""
|
| 23 |
+
|
| 24 |
+
scenario_id: str
|
| 25 |
+
stage: str
|
| 26 |
+
prompt_text: str
|
| 27 |
+
raw_output: str
|
| 28 |
+
corrected_action: dict
|
| 29 |
+
tags: list[str] = field(default_factory=list)
|
| 30 |
+
bucket: str = "next_action"
|
| 31 |
+
failure_type: str | None = None
|
| 32 |
+
action_family: str | None = None
|
| 33 |
+
mistake: str = ""
|
| 34 |
+
correction: str = ""
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclass
|
| 38 |
+
class CorrectionMemory:
|
| 39 |
+
"""Stores compact policy lessons and examples across episodes."""
|
| 40 |
+
|
| 41 |
+
max_examples_per_bucket: int = 6
|
| 42 |
+
schema_examples: dict[str, list[MemoryExample]] = field(default_factory=dict)
|
| 43 |
+
next_action_examples: dict[str, list[MemoryExample]] = field(default_factory=dict)
|
| 44 |
+
recovery_examples: dict[str, list[MemoryExample]] = field(default_factory=dict)
|
| 45 |
+
|
| 46 |
+
def add_phase_examples(
|
| 47 |
+
self,
|
| 48 |
+
episodes: list[EpisodeRecord],
|
| 49 |
+
analyses: list[FailureAnalysisReport],
|
| 50 |
+
) -> None:
|
| 51 |
+
analysis_map = {
|
| 52 |
+
analysis.episode_ids[0]: analysis for analysis in analyses if analysis.episode_ids
|
| 53 |
+
}
|
| 54 |
+
for episode in episodes:
|
| 55 |
+
analysis = analysis_map.get(episode.episode_id or 0)
|
| 56 |
+
if analysis is not None:
|
| 57 |
+
self.add_episode_examples(episode, analysis)
|
| 58 |
+
|
| 59 |
+
def add_episode_examples(
|
| 60 |
+
self,
|
| 61 |
+
episode: EpisodeRecord,
|
| 62 |
+
analysis: FailureAnalysisReport,
|
| 63 |
+
) -> None:
|
| 64 |
+
"""Update memory immediately after one episode."""
|
| 65 |
+
entries_by_step: dict[int, list] = {}
|
| 66 |
+
for entry in analysis.entries:
|
| 67 |
+
if entry.step_index is None:
|
| 68 |
+
continue
|
| 69 |
+
entries_by_step.setdefault(entry.step_index, []).append(entry)
|
| 70 |
+
|
| 71 |
+
for step in episode.step_records:
|
| 72 |
+
if step.teacher_action is None:
|
| 73 |
+
continue
|
| 74 |
+
step_entries = entries_by_step.get(step.step_index, [])
|
| 75 |
+
if not step_entries and step.parse_status not in {
|
| 76 |
+
"invalid_json",
|
| 77 |
+
"invalid_action",
|
| 78 |
+
"repaired",
|
| 79 |
+
"teacher_override",
|
| 80 |
+
}:
|
| 81 |
+
continue
|
| 82 |
+
|
| 83 |
+
primary = step_entries[0] if step_entries else None
|
| 84 |
+
failure_type = primary.failure_type if primary else _schema_failure_type(step.parse_status)
|
| 85 |
+
bucket = primary.bucket if primary else "schema"
|
| 86 |
+
mistake = _mistake_text(step, primary)
|
| 87 |
+
correction = _correction_text(step)
|
| 88 |
+
example = MemoryExample(
|
| 89 |
+
scenario_id=episode.scenario_id,
|
| 90 |
+
stage=step.workflow_stage,
|
| 91 |
+
prompt_text=step.prompt_text,
|
| 92 |
+
raw_output=step.raw_model_output,
|
| 93 |
+
corrected_action=step.teacher_action,
|
| 94 |
+
tags=list({entry.failure_type for entry in step_entries} or ([failure_type] if failure_type else [])),
|
| 95 |
+
bucket=bucket,
|
| 96 |
+
failure_type=failure_type,
|
| 97 |
+
action_family=_action_family(step.teacher_action),
|
| 98 |
+
mistake=mistake,
|
| 99 |
+
correction=correction,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if bucket == "schema" or step.parse_status in {
|
| 103 |
+
"invalid_json",
|
| 104 |
+
"invalid_action",
|
| 105 |
+
"repaired",
|
| 106 |
+
"teacher_override",
|
| 107 |
+
}:
|
| 108 |
+
self._append(self.schema_examples, episode.scenario_id, example)
|
| 109 |
+
if bucket in {"policy", "reasoning"}:
|
| 110 |
+
self._append(self.next_action_examples, episode.scenario_id, example)
|
| 111 |
+
if bucket == "looping":
|
| 112 |
+
self._append(self.recovery_examples, episode.scenario_id, example)
|
| 113 |
+
|
| 114 |
+
def build_prompt_addendum(self, scenario_id: str, stage: str) -> str:
|
| 115 |
+
"""Return a compact rolling policy card for the current scenario and stage."""
|
| 116 |
+
schema = self._select_examples(self.schema_examples, scenario_id, stage, limit=1)
|
| 117 |
+
failures = self._select_examples(self.next_action_examples, scenario_id, stage, limit=1)
|
| 118 |
+
recoveries = self._select_examples(self.recovery_examples, scenario_id, stage, limit=1)
|
| 119 |
+
examples = self._select_examples(
|
| 120 |
+
{
|
| 121 |
+
**self.schema_examples,
|
| 122 |
+
**{
|
| 123 |
+
key: self.next_action_examples.get(key, []) + self.recovery_examples.get(key, [])
|
| 124 |
+
for key in set(self.next_action_examples) | set(self.recovery_examples)
|
| 125 |
+
},
|
| 126 |
+
},
|
| 127 |
+
scenario_id,
|
| 128 |
+
stage,
|
| 129 |
+
limit=1,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
lines = ["Schema rules:"]
|
| 133 |
+
lines.extend(f"- {rule}" for rule in SCHEMA_RULES)
|
| 134 |
+
|
| 135 |
+
lesson_lines: list[str] = []
|
| 136 |
+
for item in schema + failures + recoveries:
|
| 137 |
+
lesson_lines.append(f"- Mistake: {item.mistake}")
|
| 138 |
+
lesson_lines.append(f"- Correction: {item.correction}")
|
| 139 |
+
|
| 140 |
+
if lesson_lines:
|
| 141 |
+
lines.append("")
|
| 142 |
+
lines.append("Episode lessons:")
|
| 143 |
+
lines.extend(lesson_lines[:6])
|
| 144 |
+
|
| 145 |
+
if failures:
|
| 146 |
+
item = failures[0]
|
| 147 |
+
lines.append("")
|
| 148 |
+
lines.append("Relevant past failure:")
|
| 149 |
+
lines.append(f"- {item.failure_type or 'wrong_action'}: {item.mistake}")
|
| 150 |
+
|
| 151 |
+
if recoveries:
|
| 152 |
+
item = recoveries[0]
|
| 153 |
+
lines.append("")
|
| 154 |
+
lines.append("Relevant recovery:")
|
| 155 |
+
lines.append(
|
| 156 |
+
f"- recover with {json.dumps(item.corrected_action, separators=(',', ':'))}"
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
if examples:
|
| 160 |
+
item = examples[0]
|
| 161 |
+
lines.append("")
|
| 162 |
+
lines.append("Valid example:")
|
| 163 |
+
lines.append(
|
| 164 |
+
f"- {json.dumps(item.corrected_action, separators=(',', ':'))}"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
rendered = "\n".join(lines)
|
| 168 |
+
return _limit_words(rendered, MAX_POLICY_WORDS)
|
| 169 |
+
|
| 170 |
+
def stats(self) -> dict[str, int]:
|
| 171 |
+
"""Return compact memory counts."""
|
| 172 |
+
return {
|
| 173 |
+
"schema_examples": sum(len(v) for v in self.schema_examples.values()),
|
| 174 |
+
"next_action_examples": sum(len(v) for v in self.next_action_examples.values()),
|
| 175 |
+
"recovery_examples": sum(len(v) for v in self.recovery_examples.values()),
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
def merge(self, other: "CorrectionMemory") -> None:
|
| 179 |
+
"""Merge another memory store into this one."""
|
| 180 |
+
for bucket_name in ("schema_examples", "next_action_examples", "recovery_examples"):
|
| 181 |
+
current = getattr(self, bucket_name)
|
| 182 |
+
incoming = getattr(other, bucket_name)
|
| 183 |
+
for key, values in incoming.items():
|
| 184 |
+
current.setdefault(key, [])
|
| 185 |
+
current[key].extend(values)
|
| 186 |
+
current[key] = current[key][-self.max_examples_per_bucket :]
|
| 187 |
+
|
| 188 |
+
def save(self, path: Path) -> None:
|
| 189 |
+
"""Persist memory to disk."""
|
| 190 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 191 |
+
path.write_text(
|
| 192 |
+
json.dumps(
|
| 193 |
+
{
|
| 194 |
+
"schema_examples": self._dump(self.schema_examples),
|
| 195 |
+
"next_action_examples": self._dump(self.next_action_examples),
|
| 196 |
+
"recovery_examples": self._dump(self.recovery_examples),
|
| 197 |
+
},
|
| 198 |
+
indent=2,
|
| 199 |
+
),
|
| 200 |
+
encoding="utf-8",
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
@classmethod
|
| 204 |
+
def load(cls, path: Path) -> "CorrectionMemory":
|
| 205 |
+
"""Load memory from disk."""
|
| 206 |
+
if not path.exists():
|
| 207 |
+
return cls()
|
| 208 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 209 |
+
memory = cls()
|
| 210 |
+
memory.schema_examples = memory._load_bucket(data.get("schema_examples", {}))
|
| 211 |
+
memory.next_action_examples = memory._load_bucket(data.get("next_action_examples", {}))
|
| 212 |
+
memory.recovery_examples = memory._load_bucket(data.get("recovery_examples", {}))
|
| 213 |
+
return memory
|
| 214 |
+
|
| 215 |
+
def _append(self, bucket: dict[str, list[MemoryExample]], key: str, example: MemoryExample) -> None:
|
| 216 |
+
bucket.setdefault(key, []).append(example)
|
| 217 |
+
bucket[key] = bucket[key][-self.max_examples_per_bucket :]
|
| 218 |
+
|
| 219 |
+
def _select_examples(
|
| 220 |
+
self,
|
| 221 |
+
bucket: dict[str, list[MemoryExample]],
|
| 222 |
+
scenario_id: str,
|
| 223 |
+
stage: str,
|
| 224 |
+
*,
|
| 225 |
+
limit: int,
|
| 226 |
+
) -> list[MemoryExample]:
|
| 227 |
+
all_examples = [
|
| 228 |
+
item
|
| 229 |
+
for items in bucket.values()
|
| 230 |
+
for item in items
|
| 231 |
+
]
|
| 232 |
+
ranked = sorted(
|
| 233 |
+
all_examples,
|
| 234 |
+
key=lambda item: self._score(item, scenario_id, stage),
|
| 235 |
+
reverse=True,
|
| 236 |
+
)
|
| 237 |
+
selected: list[MemoryExample] = []
|
| 238 |
+
seen = set()
|
| 239 |
+
for item in ranked:
|
| 240 |
+
key = (
|
| 241 |
+
item.scenario_id,
|
| 242 |
+
item.stage,
|
| 243 |
+
item.failure_type,
|
| 244 |
+
json.dumps(item.corrected_action, sort_keys=True),
|
| 245 |
+
)
|
| 246 |
+
if key in seen:
|
| 247 |
+
continue
|
| 248 |
+
seen.add(key)
|
| 249 |
+
selected.append(item)
|
| 250 |
+
if len(selected) >= limit:
|
| 251 |
+
break
|
| 252 |
+
return selected
|
| 253 |
+
|
| 254 |
+
def _score(self, item: MemoryExample, scenario_id: str, stage: str) -> int:
|
| 255 |
+
score = 0
|
| 256 |
+
if item.scenario_id == scenario_id:
|
| 257 |
+
score += 100
|
| 258 |
+
if item.stage == stage:
|
| 259 |
+
score += 60
|
| 260 |
+
if item.failure_type:
|
| 261 |
+
score += 10
|
| 262 |
+
if item.action_family:
|
| 263 |
+
score += 5
|
| 264 |
+
return score
|
| 265 |
+
|
| 266 |
+
def _dump(self, bucket: dict[str, list[MemoryExample]]) -> dict:
|
| 267 |
+
return {
|
| 268 |
+
key: [
|
| 269 |
+
{
|
| 270 |
+
"scenario_id": item.scenario_id,
|
| 271 |
+
"stage": item.stage,
|
| 272 |
+
"prompt_text": item.prompt_text,
|
| 273 |
+
"raw_output": item.raw_output,
|
| 274 |
+
"corrected_action": item.corrected_action,
|
| 275 |
+
"tags": item.tags,
|
| 276 |
+
"bucket": item.bucket,
|
| 277 |
+
"failure_type": item.failure_type,
|
| 278 |
+
"action_family": item.action_family,
|
| 279 |
+
"mistake": item.mistake,
|
| 280 |
+
"correction": item.correction,
|
| 281 |
+
}
|
| 282 |
+
for item in value
|
| 283 |
+
]
|
| 284 |
+
for key, value in bucket.items()
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
def _load_bucket(self, bucket: dict) -> dict[str, list[MemoryExample]]:
|
| 288 |
+
return {
|
| 289 |
+
key: [MemoryExample(**item) for item in value]
|
| 290 |
+
for key, value in bucket.items()
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _schema_failure_type(parse_status: str) -> str:
|
| 295 |
+
if parse_status == "invalid_json":
|
| 296 |
+
return "invalid_json"
|
| 297 |
+
return "invalid_action"
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _action_family(action: dict | None) -> str | None:
|
| 301 |
+
action_type = (action or {}).get("action_type")
|
| 302 |
+
if action_type in {"query_logs", "query_metrics", "query_dependencies"}:
|
| 303 |
+
return "investigate"
|
| 304 |
+
if action_type in {
|
| 305 |
+
"inspect_code",
|
| 306 |
+
"classify_vulnerability",
|
| 307 |
+
"apply_patch",
|
| 308 |
+
"verify_security_fix",
|
| 309 |
+
"submit_security_fix",
|
| 310 |
+
}:
|
| 311 |
+
return "security"
|
| 312 |
+
if action_type in {"restart_service", "rollback_deploy"}:
|
| 313 |
+
return "recovery"
|
| 314 |
+
if action_type == "submit_postmortem":
|
| 315 |
+
return "postmortem"
|
| 316 |
+
return None
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _mistake_text(step, entry) -> str:
|
| 320 |
+
if step.failure_type and step.observation.get("why_failed"):
|
| 321 |
+
return step.observation["why_failed"]
|
| 322 |
+
if entry is not None:
|
| 323 |
+
return entry.detail
|
| 324 |
+
return "The previous action did not follow the stage rules."
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _correction_text(step) -> str:
|
| 328 |
+
teacher_action = step.teacher_action or {}
|
| 329 |
+
action_type = teacher_action.get("action_type")
|
| 330 |
+
if action_type is None:
|
| 331 |
+
return "Return one valid action object for the current stage."
|
| 332 |
+
if action_type in {"query_logs", "query_metrics", "query_dependencies"}:
|
| 333 |
+
return f"If you are still diagnosing, prefer {action_type} instead of recovery actions."
|
| 334 |
+
if action_type in {
|
| 335 |
+
"inspect_code",
|
| 336 |
+
"classify_vulnerability",
|
| 337 |
+
"apply_patch",
|
| 338 |
+
"verify_security_fix",
|
| 339 |
+
"submit_security_fix",
|
| 340 |
+
}:
|
| 341 |
+
return f"If security is not completed, prefer {action_type} before infrastructure recovery."
|
| 342 |
+
if action_type in {"restart_service", "rollback_deploy"}:
|
| 343 |
+
return f"After security completion, use {action_type} for recovery."
|
| 344 |
+
return f"The next valid move is {action_type}."
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def _limit_words(text: str, limit: int) -> str:
|
| 348 |
+
words = text.split()
|
| 349 |
+
if len(words) <= limit:
|
| 350 |
+
return text
|
| 351 |
+
return " ".join(words[:limit]).strip() + " ..."
|
unified_incident_env/trainer/trajectory_store.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""JSONL trajectory storage and summary helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from .types import EpisodeRecord
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TrajectoryStore:
|
| 12 |
+
"""Append-only JSONL store for episode trajectories."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, path: Path) -> None:
|
| 15 |
+
self.path = path
|
| 16 |
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
def append_episode(self, record: EpisodeRecord) -> None:
|
| 19 |
+
with self.path.open("a", encoding="utf-8") as handle:
|
| 20 |
+
handle.write(record.model_dump_json())
|
| 21 |
+
handle.write("\n")
|
| 22 |
+
|
| 23 |
+
def load_episodes(self) -> list[EpisodeRecord]:
|
| 24 |
+
if not self.path.exists():
|
| 25 |
+
return []
|
| 26 |
+
records: list[EpisodeRecord] = []
|
| 27 |
+
with self.path.open(encoding="utf-8") as handle:
|
| 28 |
+
for line in handle:
|
| 29 |
+
line = line.strip()
|
| 30 |
+
if not line:
|
| 31 |
+
continue
|
| 32 |
+
records.append(EpisodeRecord.model_validate(json.loads(line)))
|
| 33 |
+
return records
|