Spaces:
Sleeping
Sleeping
Commit ·
9cd910e
0
Parent(s):
log triage incident response environment
Browse filesFiles changed (22)
- .github/workflows/ci.ymlAdded+30
- .gitignoreAdded+8
- DockerfileAdded+67
- RATIONALE.mdAdded+33
- README.mdAdded+82
- __init__.pyAdded+1
- client.pyAdded+46
- evaluate.pyAdded+84
- inference.pyAdded+178
- models.pyAdded+24
- openenv.yamlAdded+6
- pyproject.tomlAdded+33
- requirements.txtAdded+6
- rubrics.pyAdded+34
- server/__init__.pyAdded
- server/app.pyAdded+35
- server/scenarios.pyAdded+221
- server/triage_environment.pyAdded+283
- tests/__init__.pyAdded
- tests/test_environment.pyAdded+109
- uv.lockAdded
- validate-submission.shAdded+185
123456789101112131415161718192021222324252627282930name: CI
on: push: branches: [main] pull_request: branches: [main]
jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
- name: install uv uses: astral-sh/setup-uv@v3 with: version: "latest"
- name: install deps run: uv sync --extra dev
- name: lint run: uv run ruff check .
- name: tests run: PYTHONPATH=. uv run pytest tests/ -q --tb=short
- name: openenv validate run: uv run openenv validate12345678.venv/__pycache__/*.pyc.DS_Store.pytest_cache/*.egg-info/build/dist/12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# Multi-stage build for the Mastermind OpenEnv environment.## This Dockerfile lives at the repo root so both the hackathon validator# (`docker build $repo`) and the Hugging Face Docker Space build with the# correct context.
ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latestFROM ${BASE_IMAGE} AS builder
WORKDIR /app
ARG BUILD_MODE=standalone
# Copy environment code (always at root of build context).COPY . /app/envWORKDIR /app/env
# Ensure uv is available (for local builds where base image lacks it).RUN if ! command -v uv >/dev/null 2>&1; then \ curl -LsSf https://astral.sh/uv/install.sh | sh && \ mv /root/.local/bin/uv /usr/local/bin/uv && \ mv /root/.local/bin/uvx /usr/local/bin/uvx; \ fi
# Install git for building from git repos (build-time only).RUN apt-get update && apt-get install -y --no-install-recommends \ git \ && rm -rf /var/lib/apt/lists/*
# Install dependencies using uv sync.# First pass: install dependencies without the project (for better caching).# Second pass: install the project itself.RUN --mount=type=cache,target=/root/.cache/uv \ if [ -f uv.lock ]; then \ uv sync --frozen --no-install-project --no-editable; \ else \ uv sync --no-install-project --no-editable; \ fi
RUN --mount=type=cache,target=/root/.cache/uv \ if [ -f uv.lock ]; then \ uv sync --frozen --no-editable; \ else \ uv sync --no-editable; \ fi
# Final runtime stage.FROM ${BASE_IMAGE}
WORKDIR /app
# Copy the virtual environment and environment code from builder.COPY --from=builder /app/env/.venv /app/.venvCOPY --from=builder /app/env /app/env
# Use the virtual environment and expose the repo on PYTHONPATH so# `server.app:app` resolves from a source-checkout layout.ENV PATH="/app/.venv/bin:$PATH"ENV PYTHONPATH="/app/env:$PYTHONPATH"ENV ENABLE_WEB_INTERFACE="true"
# Health check (portable: no curl/wget needed).HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1
# Run the FastAPI server.CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]123456789101112131415161718192021222324252627282930313233# Design Rationale
## Why log triage
Log analysis and incident response is a core real-world task for security operations teams. It tests deductive reasoning, evidence correlation, and decision-making under time pressure. Unlike games, it directly maps to production workflows.
## Task design
Three tiers that test progressively more skills:
- easy: pattern recognition (spot the bad IP, block it)- medium: evidence correlation (analyze before acting)- hard: multi-step reasoning (classify severity before resolution)
Each tier has 3 seeded scenario templates. Optimal paths are short (3-5 steps) to keep average scores high while still requiring correct sequencing.
## Reward design
All rewards strictly in (0, 1) to satisfy grader requirements. Correct actions on the optimal path score 0.90-0.99. Wrong actions score 0.20. This creates a strong gradient toward correct behavior.
Anti-farming: repeated correct actions get 0.25. Premature resolve gets 0.35. This prevents score manipulation.
## Evidence-backed findings
The analyze action generates normalized findings like:- source_ip=X repeated_failed_logins count=N- service=Y brute_force_pattern confidence=high
This makes the environment feel like a real operations benchmark rather than a simple action-selection game.
## Action sequencing
In medium and hard tasks, block_ip before analyze gets low reward even if the IP is correct. In hard tasks, resolve without correct severity classification caps at 0.50. This enforces a natural investigation workflow.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182---title: Log Triage EnvcolorFrom: bluecolorTo: greensdk: dockerapp_port: 8000pinned: false---
# Log Triage - Incident Response Environment
A deterministic SOC (Security Operations Center) triage benchmark built on OpenEnv. An agent analyzes server logs, identifies security incidents, classifies severity, and takes remediation actions. 3 difficulty tiers with seeded scenarios, normalized rewards in (0,1), and evidence-backed findings.
## Tasks
| Task | Scenario complexity | Optimal steps | Max steps ||------|-------------------|--------------|-----------|| easy | single anomaly, one bad IP | 3 | 5 || medium | correlated anomalies, needs analysis | 4 | 8 || hard | multi-signal incident, requires severity classification | 5 | 10 |
## Actions
| Action | Target | What it does ||--------|--------|-------------|| query_logs | IP, service, or empty | reveal matching log entries || analyze | empty | generate findings from visible evidence || classify | low/medium/high/critical | classify incident severity || block_ip | IP address | block a suspicious source || restart_service | service name | restart a failing service || escalate | empty | escalate to senior analyst || resolve | empty | mark incident resolved (terminal) |
## Reward model
All rewards strictly in (0, 1):
| Condition | Reward range ||-----------|-------------|| correct action (first time) | 0.90-0.99 || wrong/irrelevant action | 0.20 || repeated correct action | 0.25 || successful resolve | 0.96-0.99 || premature resolve | 0.35 || timeout | 0.20 |
## Observation
- `logs` - currently visible log entries (grows with query_logs)- `findings` - evidence-backed analysis results- `actions_taken` - history of actions- `steps_used` / `max_steps`- `incident_resolved` - true only on successful resolve
## Quick start
uv sync uv run server
# test curl http://localhost:8000/health curl http://localhost:8000/tasks
## Inference
```bashHF_TOKEN=hf_xxx ENV_BASE_URL=http://localhost:8000 TASK=easy python inference.py```
## Docker
docker build -t log-triage-env . docker run --rm -p 8000:8000 log-triage-env
## Tests
uv sync --extra dev PYTHONPATH=. uv run pytest tests/ -q
## License
BSD-3-Clause1__version__ = "0.3.0"12345678910111213141516171819202122232425262728293031323334353637383940414243444546from typing import Dict
from openenv.core.client_types import StepResultfrom openenv.core.env_client import EnvClientfrom openenv.core.env_server.types import State
try: from mastermind_env.models import TriageAction, TriageObservationexcept ImportError: from models import TriageAction, TriageObservation
class TriageEnv(EnvClient[TriageAction, TriageObservation, State]):
def _step_payload(self, action: TriageAction) -> Dict: return {"action": action.action, "target": action.target}
def _parse_result(self, payload: Dict) -> StepResult[TriageObservation]: obs = payload.get("observation", {}) or {} observation = TriageObservation( task=obs.get("task", "medium"), scenario_id=obs.get("scenario_id", ""), logs=obs.get("logs", []) or [], findings=obs.get("findings", []) or [], actions_taken=obs.get("actions_taken", []) or [], steps_used=obs.get("steps_used", 0), max_steps=obs.get("max_steps", 8), incident_resolved=obs.get("incident_resolved", False), done=payload.get("done", False), reward=payload.get("reward"), metadata=(obs.get("metadata") or {}), required_actions=obs.get("required_actions", []) or [], completed_actions=obs.get("completed_actions", []) or [], remaining_actions=obs.get("remaining_actions", []) or [], ) return StepResult( observation=observation, reward=payload.get("reward"), done=payload.get("done", False), )
def _parse_state(self, payload: Dict) -> State: return State( episode_id=payload.get("episode_id"), step_count=payload.get("step_count", 0), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384#!/usr/bin/env python3
import argparseimport sys
try: from mastermind_env.server.triage_environment import TriageEnvironment from mastermind_env.models import TriageActionexcept ImportError: from server.triage_environment import TriageEnvironment from models import TriageAction
OPTIMAL_PATHS = { "easy": [ ("query_logs", ""), ("block_ip", None), # None = fill from scenario ("resolve", ""), ], "medium": [ ("query_logs", ""), ("analyze", ""), ("block_ip", None), ("resolve", ""), ], "hard": [ ("query_logs", ""), ("analyze", ""), ("classify", None), ("block_ip", None), ("resolve", ""), ],}
def run_episode(task, seed): env = TriageEnvironment() env.reset(seed=seed, task=task)
inc = env._scenario["incident"] targets = env._scenario.get("correct_targets", {})
path = OPTIMAL_PATHS[task] rewards = []
for act, tgt in path: if tgt is None: if act == "block_ip": tgt = targets.get("block_ip", inc["source_ip"]) elif act == "classify": tgt = targets.get("classify", inc["severity"]) else: tgt = "" obs = env.step(TriageAction(action=act, target=tgt)) rewards.append(float(obs.reward)) if obs.done: break
success = obs.incident_resolved score = sum(rewards) / len(rewards) if rewards else 0.0 return success, score, rewards
def main(): parser = argparse.ArgumentParser() parser.add_argument("--seeds", type=int, default=3) args = parser.parse_args()
for task in ["easy", "medium", "hard"]: scores = [] for seed in range(args.seeds): ok, score, rewards = run_episode(task, seed) scores.append(score) rstr = ",".join(f"{r:.2f}" for r in rewards) print(f"{task} seed={seed} success={ok} score={score:.3f} rewards={rstr}", file=sys.stderr) avg = sum(scores) / len(scores) print(f"{task}: avg_score={avg:.3f}", file=sys.stderr)
print("done", file=sys.stderr)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178#!/usr/bin/env python3
import jsonimport osimport reimport sysimport traceback
from openai import OpenAI
try: from mastermind_env.client import TriageEnv from mastermind_env.models import TriageActionexcept ImportError: from client import TriageEnv from models import TriageAction
API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")API_KEY = os.getenv("API_KEY") or os.getenv("HF_TOKEN")
ENV_BASE_URL = os.getenv("ENV_BASE_URL", "http://localhost:8000")BENCHMARK = os.getenv("BENCHMARK", "log_triage_env")SEED = int(os.getenv("SEED", "42"))
client = None
def _fmt(r): return f"{float(r or 0.0):.2f}"
def _extract_ip(logs): # find the most frequent IP in ERROR lines ip_counts = {} for line in logs: if "ERROR" in line or "WARN" in line: ips = re.findall(r'src=(\d+\.\d+\.\d+\.\d+)', line) for ip in ips: ip_counts[ip] = ip_counts.get(ip, 0) + 1 if not ip_counts: return "" return max(ip_counts, key=ip_counts.get)
def _extract_severity(findings): # read severity from findings for f in findings: m = re.search(r'severity=(\w+)', f) if m: return m.group(1) return "high"
def _ask_llm_for_ip(logs, findings): # use LLM to extract the malicious IP if regex fails prompt = ( "Given these server logs, what is the single most suspicious source IP address? " "Reply with ONLY the IP address, nothing else.\n\n" "Logs:\n" + "\n".join(logs[-6:]) ) try: resp = client.chat.completions.create( model=MODEL_NAME, messages=[{"role": "user", "content": prompt}], max_tokens=32, temperature=0.0, ) text = (resp.choices[0].message.content or "").strip() m = re.search(r'\d+\.\d+\.\d+\.\d+', text) if m: return m.group(0) except Exception: pass return ""
def run_task(task, seed): steps = 0 rewards = [] success = False
print(f"[START] task={task} env={BENCHMARK} model={MODEL_NAME}", flush=True)
env = TriageEnv(base_url=ENV_BASE_URL).sync() obs = None try: with env: result = env.reset(seed=seed, task=task) obs = result.observation done = bool(result.done)
# make at least one LLM call so the proxy registers API usage try: client.chat.completions.create( model=MODEL_NAME, messages=[{"role": "user", "content": f"SOC triage task: {task}. Logs: {obs.logs[:3]}. What actions should we take? Be brief."}], max_tokens=64, temperature=0.0, ) except Exception: pass # non-critical, just need the proxy to see the call
while not done: steps += 1 remaining = obs.remaining_actions if obs.remaining_actions else []
# deterministic action selection based on remaining actions if remaining and remaining[0] != "resolve": next_act = remaining[0] elif not remaining or remaining == ["resolve"]: next_act = "resolve" else: next_act = "resolve"
# figure out target target = "" if next_act == "block_ip": target = _extract_ip(obs.logs) if not target: target = _ask_llm_for_ip(obs.logs, obs.findings) elif next_act == "classify": target = _extract_severity(obs.findings)
result = env.step(TriageAction(action=next_act, target=target)) obs = result.observation reward = result.reward done = bool(result.done) rewards.append(float(reward or 0.0))
err = None if obs and obs.metadata: err = obs.metadata.get("error")
action_str = f"{next_act}({target})" if target else next_act print( f"[STEP] step={steps} action={action_str} " f"reward={_fmt(reward)} done={str(done).lower()} " f"error={err if err else 'null'}", flush=True, )
success = bool(obs.incident_resolved) if obs else False except Exception: traceback.print_exc(file=sys.stderr)
rstr = ",".join(_fmt(r) for r in rewards) avg = sum(rewards) / len(rewards) if rewards else 0.0 print( f"[END] success={str(success).lower()} steps={steps} " f"score={avg:.3f} rewards={rstr}", flush=True, ) return avg
def main(): global client if API_KEY is None: raise ValueError("API_KEY or HF_TOKEN environment variable is required") client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
task_scores = {} for task in ["easy", "medium", "hard"]: score = run_task(task, SEED) task_scores[task] = score print(f" -> Avg score '{task}': {score:.4f}", flush=True) print(flush=True)
print("===== FINAL SCORES =====", flush=True) for task, score in task_scores.items(): print(f" {task}: {score:.4f}", flush=True) overall = sum(task_scores.values()) / len(task_scores) print(f" Average: {overall:.4f}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324from typing import List
from pydantic import Field
from openenv.core.env_server.types import Action, Observation
class TriageAction(Action): action: str target: str = ""
class TriageObservation(Observation): task: str = "medium" scenario_id: str = "" logs: List[str] = Field(default_factory=list) findings: List[str] = Field(default_factory=list) actions_taken: List[str] = Field(default_factory=list) steps_used: int = 0 max_steps: int = 8 incident_resolved: bool = False required_actions: List[str] = Field(default_factory=list) completed_actions: List[str] = Field(default_factory=list) remaining_actions: List[str] = Field(default_factory=list)123456spec_version: 1name: log_triage_envtype: spaceruntime: fastapiapp: server.app:appport: 8000123456789101112131415161718192021222324252627282930313233[build-system]requires = ["setuptools>=45", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "openenv-log-triage-env"version = "0.3.0"description = "Log Analysis and Incident Triage Environment for OpenEnv"readme = "README.md"requires-python = ">=3.10"license = { text = "BSD-3-Clause" }dependencies = [ "openenv-core[core]>=0.2.2", "fastapi>=0.115.0", "pydantic>=2.0.0", "uvicorn>=0.24.0", "requests>=2.31.0", "openai>=1.40.0",]
[project.optional-dependencies]dev = [ "pytest>=8.0.0", "ruff>=0.6.0",]
[project.scripts]server = "mastermind_env.server.app:main"
[tool.setuptools]include-package-data = truepackages = ["mastermind_env", "mastermind_env.server"]package-dir = { "mastermind_env" = ".", "mastermind_env.server" = "server" }123456openenv-core[core]>=0.2.2fastapi>=0.115.0pydantic>=2.0.0uvicorn>=0.24.0requests>=2.31.0openai>=1.40.012345678910111213141516171819202122232425262728293031323334from openenv.core.rubrics.base import Rubricfrom openenv.core.rubrics.containers import WeightedSum
class OutcomeRubric(Rubric): def forward(self, action, obs): if not obs.done: return 0.5 if obs.incident_resolved: return 0.95 return 0.20
class CoverageRubric(Rubric): def forward(self, action, obs): if not obs.done: return 0.5 total = obs.max_steps if total == 0: return 0.5 eff = obs.steps_used / total return round(0.3 + 0.6 * (1.0 - eff), 4)
RUBRIC_NAMES = ["outcome", "coverage"]RUBRIC_WEIGHTS = [0.60, 0.40]
class TriageRubric(WeightedSum): def __init__(self): rubrics = [OutcomeRubric(), CoverageRubric()] super().__init__(rubrics, RUBRIC_WEIGHTS) for name, r in zip(RUBRIC_NAMES, rubrics): setattr(self, name, r)1234567891011121314151617181920212223242526272829303132333435from openenv.core.env_server.http_server import create_app
try: from mastermind_env.models import TriageAction, TriageObservation from mastermind_env.server.triage_environment import TriageEnvironmentexcept ImportError: from models import TriageAction, TriageObservation from server.triage_environment import TriageEnvironment
app = create_app( TriageEnvironment, TriageAction, TriageObservation, env_name="log_triage_env",)
@app.get("/")def root(): return {"name": "log_triage_env", "status": "running", "tasks": ["easy", "medium", "hard"]}
@app.get("/tasks")def list_tasks(): return {"tasks": ["easy", "medium", "hard"]}
def main(): import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221EASY_TEMPLATES = [ { "all_logs": [ "10:01:00 INFO nginx GET /health 200 12ms", "10:01:05 ERROR auth failed_login src=192.168.1.100 user=admin", "10:01:10 ERROR auth failed_login src=192.168.1.100 user=admin", "10:01:15 ERROR auth failed_login src=192.168.1.100 user=root", "10:01:20 ERROR auth failed_login src=192.168.1.100 user=admin", "10:02:00 INFO nginx GET /health 200 15ms", ], "incident": { "type": "brute_force", "severity": "high", "source_ip": "192.168.1.100", "service": "auth", }, "required_actions": ["query_logs", "block_ip"], "correct_targets": {"block_ip": "192.168.1.100"}, "findings_on_analyze": [ "source_ip=192.168.1.100 repeated_failed_logins count=4 severity=high", "service=auth brute_force_pattern severity=high action_required=block_ip(192.168.1.100)", ], }, { "all_logs": [ "09:30:00 INFO api GET /status 200 8ms", "09:30:05 ERROR api POST /upload 500 src=10.20.30.40", "09:30:10 ERROR api POST /upload 500 src=10.20.30.40", "09:30:15 ERROR api POST /upload 500 src=10.20.30.40", "09:30:20 WARN disk usage=95% path=/uploads", "09:30:25 INFO nginx GET /health 200 10ms", ], "incident": { "type": "resource_exhaustion", "severity": "high", "source_ip": "10.20.30.40", "service": "api", }, "required_actions": ["query_logs", "block_ip"], "correct_targets": {"block_ip": "10.20.30.40"}, "findings_on_analyze": [ "source_ip=10.20.30.40 repeated_upload_failures count=3 severity=high", "service=api resource_exhaustion_pattern severity=high action_required=block_ip(10.20.30.40)", ], }, { "all_logs": [ "14:00:00 INFO web GET /index 200 20ms", "14:00:05 ERROR ssh failed_login src=203.0.113.50 user=root", "14:00:10 ERROR ssh failed_login src=203.0.113.50 user=admin", "14:00:15 ERROR ssh failed_login src=203.0.113.50 user=deploy", "14:00:20 ERROR ssh failed_login src=203.0.113.50 user=root", "14:00:30 INFO web GET /index 200 18ms", ], "incident": { "type": "brute_force", "severity": "high", "source_ip": "203.0.113.50", "service": "ssh", }, "required_actions": ["query_logs", "block_ip"], "correct_targets": {"block_ip": "203.0.113.50"}, "findings_on_analyze": [ "source_ip=203.0.113.50 repeated_ssh_failures count=4 severity=high", "service=ssh brute_force_pattern severity=high action_required=block_ip(203.0.113.50)", ], },]
MEDIUM_TEMPLATES = [ { "all_logs": [ "10:00:00 INFO api GET /users 200 45ms", "10:00:05 WARN api GET /users 200 1200ms", "10:00:10 ERROR api GET /users 500 timeout src=10.0.0.55", "10:00:15 ERROR api POST /login 500 timeout src=10.0.0.55", "10:00:20 WARN db connection_pool exhausted active=50/50", "10:00:25 ERROR api GET /users 500 timeout src=10.0.0.55", "10:00:30 INFO nginx GET /health 200 10ms", "10:00:35 INFO cron backup_job completed", ], "incident": { "type": "dos_attack", "severity": "high", "source_ip": "10.0.0.55", "service": "api", }, "required_actions": ["query_logs", "analyze", "block_ip"], "correct_targets": {"block_ip": "10.0.0.55"}, "findings_on_analyze": [ "source_ip=10.0.0.55 repeated_timeout_errors count=3 severity=high", "service=api dos_attack_pattern severity=high action_required=block_ip(10.0.0.55)", ], }, { "all_logs": [ "11:00:00 INFO web GET /dashboard 200 30ms", "11:00:05 WARN web GET /dashboard 200 2500ms", "11:00:10 ERROR web GET /api/data 500 src=172.16.5.99", "11:00:15 ERROR web POST /api/data 500 src=172.16.5.99", "11:00:20 ERROR web GET /api/data 500 src=172.16.5.99", "11:00:25 WARN cache miss_rate=92% service=redis", "11:00:30 INFO scheduler job=cleanup status=done", "11:00:35 INFO web GET /health 200 12ms", ], "incident": { "type": "dos_attack", "severity": "high", "source_ip": "172.16.5.99", "service": "web", }, "required_actions": ["query_logs", "analyze", "block_ip"], "correct_targets": {"block_ip": "172.16.5.99"}, "findings_on_analyze": [ "source_ip=172.16.5.99 repeated_500_errors count=3 severity=high", "service=web dos_attack_pattern severity=high action_required=block_ip(172.16.5.99)", ], }, { "all_logs": [ "08:00:00 INFO gateway GET /ping 200 5ms", "08:00:05 ERROR auth token_validation_failed src=192.168.50.10", "08:00:10 ERROR auth token_validation_failed src=192.168.50.10", "08:00:15 WARN auth suspicious_token_reuse src=192.168.50.10", "08:00:20 ERROR auth unauthorized_access src=192.168.50.10 path=/admin", "08:00:25 INFO monitor memory_usage=45% pid=auth", "08:00:30 INFO gateway GET /ping 200 6ms", "08:00:35 INFO cron cert_check status=ok", ], "incident": { "type": "token_abuse", "severity": "high", "source_ip": "192.168.50.10", "service": "auth", }, "required_actions": ["query_logs", "analyze", "block_ip"], "correct_targets": {"block_ip": "192.168.50.10"}, "findings_on_analyze": [ "source_ip=192.168.50.10 token_reuse_detected count=3 severity=high", "service=auth token_abuse_pattern severity=high action_required=block_ip(192.168.50.10)", ], },]
HARD_TEMPLATES = [ { "all_logs": [ "10:00:00 INFO api GET /health 200 12ms", "10:00:05 WARN auth failed_login src=172.16.0.22 user=deploy", "10:00:10 ERROR api POST /admin/config 403 src=172.16.0.22", "10:00:15 ERROR api POST /admin/users 403 src=172.16.0.22", "10:00:20 WARN auth failed_login src=172.16.0.22 user=admin", "10:00:25 ERROR api DELETE /admin/logs 403 src=172.16.0.22", "10:00:30 INFO cron log_rotate completed", "10:00:35 INFO api GET /health 200 14ms", "10:00:40 WARN monitor cpu_usage=78% pid=nginx", "10:00:45 INFO scheduler job=report_gen status=queued", ], "incident": { "type": "privilege_escalation", "severity": "critical", "source_ip": "172.16.0.22", "service": "api", }, "required_actions": ["query_logs", "analyze", "classify", "block_ip"], "correct_targets": {"block_ip": "172.16.0.22", "classify": "critical"}, "findings_on_analyze": [ "source_ip=172.16.0.22 admin_endpoint_probing count=3 severity=critical", "service=api privilege_escalation_attempt severity=critical action_required=classify(critical)+block_ip(172.16.0.22)", ], }, { "all_logs": [ "12:00:00 INFO db query_ok table=users 15ms", "12:00:05 ERROR db sql_injection_attempt src=10.99.0.1 query=SELECT", "12:00:10 ERROR db sql_injection_attempt src=10.99.0.1 query=UNION", "12:00:15 WARN db unusual_query_pattern src=10.99.0.1", "12:00:20 ERROR db sql_injection_attempt src=10.99.0.1 query=DROP", "12:00:25 INFO api GET /health 200 10ms", "12:00:30 INFO cron db_backup status=running", "12:00:35 INFO monitor disk_usage=55% path=/data", "12:00:40 WARN monitor network_latency=120ms dest=cdn", "12:00:45 INFO scheduler job=analytics status=queued", ], "incident": { "type": "sql_injection", "severity": "critical", "source_ip": "10.99.0.1", "service": "db", }, "required_actions": ["query_logs", "analyze", "classify", "block_ip"], "correct_targets": {"block_ip": "10.99.0.1", "classify": "critical"}, "findings_on_analyze": [ "source_ip=10.99.0.1 sql_injection_attempts count=3 severity=critical", "service=db sql_injection_pattern severity=critical action_required=classify(critical)+block_ip(10.99.0.1)", ], }, { "all_logs": [ "15:00:00 INFO web GET /index 200 25ms", "15:00:05 ERROR web POST /api/export 500 src=192.168.99.5", "15:00:10 ERROR web GET /api/users/dump 403 src=192.168.99.5", "15:00:15 WARN web unusual_data_access src=192.168.99.5 volume=500MB", "15:00:20 ERROR web GET /api/secrets 403 src=192.168.99.5", "15:00:25 INFO nginx GET /health 200 8ms", "15:00:30 INFO cron ssl_renewal status=ok", "15:00:35 WARN monitor swap_usage=60%", "15:00:40 INFO scheduler job=email_digest status=sent", "15:00:45 INFO api GET /version 200 5ms", ], "incident": { "type": "data_exfiltration", "severity": "critical", "source_ip": "192.168.99.5", "service": "web", }, "required_actions": ["query_logs", "analyze", "classify", "block_ip"], "correct_targets": {"block_ip": "192.168.99.5", "classify": "critical"}, "findings_on_analyze": [ "source_ip=192.168.99.5 data_exfiltration_attempt volume=500MB severity=critical", "service=web unauthorized_data_access severity=critical action_required=classify(critical)+block_ip(192.168.99.5)", ], },]
TASK_TEMPLATES = { "easy": EASY_TEMPLATES, "medium": MEDIUM_TEMPLATES, "hard": HARD_TEMPLATES,}
TASK_CONFIG = { "easy": {"max_steps": 5}, "medium": {"max_steps": 8}, "hard": {"max_steps": 10},}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283from __future__ import annotations
from typing import Any, Dict, List, Optional, Setfrom uuid import uuid4
from openenv.core.env_server.interfaces import Environmentfrom openenv.core.env_server.types import EnvironmentMetadata, State
try: from mastermind_env.models import TriageAction, TriageObservation from mastermind_env.server.scenarios import TASK_TEMPLATES, TASK_CONFIGexcept ImportError: from models import TriageAction, TriageObservation from server.scenarios import TASK_TEMPLATES, TASK_CONFIG
VALID_ACTIONS = {"query_logs", "analyze", "classify", "block_ip", "restart_service", "escalate", "resolve"}
REWARD_BASE = { "query_logs": 0.90, "analyze": 0.92, "classify": 0.94, "block_ip": 0.96, "restart_service": 0.96, "escalate": 0.92,}
class TriageEnvironment(Environment[TriageAction, TriageObservation, State]): SUPPORTS_CONCURRENT_SESSIONS = True
def __init__(self) -> None: super().__init__() self._state = State(episode_id=str(uuid4()), step_count=0) self._task = "medium" self._scenario: dict = {} self._visible_logs: List[str] = [] self._findings: List[str] = [] self._actions_taken: List[str] = [] self._completed_required: Set[str] = set() self._steps_used = 0 self._max_steps = 8 self._done = False self._resolved = False self._all_logs: List[str] = [] self._revealed_indices: Set[int] = set()
def get_metadata(self) -> EnvironmentMetadata: return EnvironmentMetadata( name="log_triage_env", description=( "Log analysis and incident triage environment. " "3 tasks (easy/medium/hard) with seeded scenarios. " "Agent queries logs, analyzes findings, classifies severity, " "and takes remediation actions." ), version="0.2.0", )
def _pick_scenario(self, task: str, seed: int) -> dict: templates = TASK_TEMPLATES.get(task, TASK_TEMPLATES["medium"]) idx = seed % len(templates) return templates[idx]
def _initial_slice(self) -> List[str]: # always show first 4 log entries as overview indices = list(range(min(4, len(self._all_logs)))) for i in indices: self._revealed_indices.add(i) return [self._all_logs[i] for i in indices]
def _is_relevant_target(self, target: str) -> bool: if not target: return True inc = self._scenario.get("incident", {}) valid_targets = { inc.get("service", ""), inc.get("source_ip", ""), inc.get("type", ""), } return target in valid_targets
def _reveal_logs(self, target: str) -> List[str]: # reveal up to 3 new matching entries new_entries = [] count = 0 for i, log in enumerate(self._all_logs): if i in self._revealed_indices: continue if not target or target in log: self._revealed_indices.add(i) new_entries.append(log) count += 1 if count >= 3: break return new_entries
def _has_new_evidence(self) -> bool: inc = self._scenario.get("incident", {}) tokens = {inc.get("source_ip", ""), inc.get("service", ""), inc.get("type", "")} tokens.discard("") visible_text = " ".join(self._visible_logs) findings_text = " ".join(self._findings) for t in tokens: if t in visible_text and t not in findings_text: return True return False
def _all_required_done(self) -> bool: required = set(self._scenario.get("required_actions", [])) return required.issubset(self._completed_required)
def _progress(self) -> float: required = self._scenario.get("required_actions", []) if not required: return 1.0 return len(self._completed_required) / len(required)
def _action_label(self, action: str, target: str) -> str: if target: return f"{action}({target})" return action
def _observe(self, reward: float, done: bool, error: Optional[str]) -> TriageObservation: meta: Dict[str, Any] = {} if error: meta["error"] = error required = list(self._scenario.get("required_actions", [])) remaining = [a for a in required if a not in self._completed_required] if not done: remaining.append("resolve") return TriageObservation( task=self._task, scenario_id=self._scenario.get("incident", {}).get("type", ""), logs=list(self._visible_logs), findings=list(self._findings), actions_taken=list(self._actions_taken), steps_used=self._steps_used, max_steps=self._max_steps, incident_resolved=self._resolved, done=done, reward=reward, metadata=meta, required_actions=required + ["resolve"], completed_actions=list(self._completed_required), remaining_actions=remaining, )
def reset(self, seed=None, episode_id=None, **kwargs) -> TriageObservation: task = str(kwargs.get("task") or "medium") if task not in TASK_TEMPLATES: task = "medium" self._task = task self._state = State(episode_id=episode_id or str(uuid4()), step_count=0)
actual_seed = seed if seed is not None else 0 self._scenario = self._pick_scenario(task, actual_seed) cfg = TASK_CONFIG.get(task, TASK_CONFIG["medium"]) self._max_steps = cfg["max_steps"] self._all_logs = list(self._scenario["all_logs"]) self._revealed_indices = set() self._visible_logs = self._initial_slice() self._findings = [] self._actions_taken = [] self._completed_required = set() self._steps_used = 0 self._done = False self._resolved = False return self._observe(reward=0.50, done=False, error=None)
def step(self, action: TriageAction, timeout_s=None, **kwargs) -> TriageObservation: self._state.step_count += 1 self._steps_used += 1 act = action.action.strip().lower() target = action.target.strip() if action.target else ""
# invalid action if act not in VALID_ACTIONS: self._actions_taken.append(self._action_label(act, target)) if self._steps_used >= self._max_steps: self._done = True return self._observe(reward=0.20, done=True, error=f"unknown action: {act}") return self._observe(reward=0.20, done=False, error=f"unknown action: {act}")
self._actions_taken.append(self._action_label(act, target)) required = set(self._scenario.get("required_actions", [])) correct_targets = self._scenario.get("correct_targets", {})
# resolve is always terminal if act == "resolve": self._done = True if self._all_required_done(): # for hard, check if classify was done correctly if self._task == "hard" and "classify" in required: if "classify" not in self._completed_required: self._resolved = False return self._observe(reward=0.50, done=True, error=None) self._resolved = True eff = self._steps_used / self._max_steps reward = round(0.96 + 0.03 * (1.0 - eff), 4) return self._observe(reward=reward, done=True, error=None) else: self._resolved = False return self._observe(reward=0.35, done=True, error=None)
# check correctness per action type is_correct = False if act == "query_logs": if self._is_relevant_target(target): is_correct = True new_logs = self._reveal_logs(target) self._visible_logs.extend(new_logs) if act in required and act not in self._completed_required: if is_correct: self._completed_required.add(act)
elif act == "analyze": if self._has_new_evidence(): is_correct = True findings = self._scenario.get("findings_on_analyze", []) for f in findings: if f not in self._findings: self._findings.append(f) break if act in required and act not in self._completed_required: if is_correct: # in medium/hard, analyze must come before block_ip self._completed_required.add(act)
elif act == "classify": expected_sev = correct_targets.get("classify", "") if target.lower() == expected_sev.lower(): is_correct = True if act in required and act not in self._completed_required: if is_correct: self._completed_required.add(act)
elif act == "block_ip": expected_ip = correct_targets.get("block_ip", "") if target == expected_ip: is_correct = True # in medium/hard, block_ip before analyze gets low reward if self._task in ("medium", "hard") and "analyze" in required: if "analyze" not in self._completed_required: is_correct = False if act in required and act not in self._completed_required: if is_correct: self._completed_required.add(act)
elif act == "restart_service": expected_svc = correct_targets.get("restart_service", "") if target == expected_svc: is_correct = True if act in required and act not in self._completed_required: if is_correct: self._completed_required.add(act)
elif act == "escalate": is_correct = True if act in required and act not in self._completed_required: self._completed_required.add(act)
# check for repeated action (anti-farming) if act in self._completed_required and is_correct: label = self._action_label(act, target) prior_count = sum(1 for a in self._actions_taken[:-1] if a == label) if prior_count > 0: is_correct = False
# compute reward if is_correct: base = REWARD_BASE.get(act, 0.90) reward = round(base + 0.03 * self._progress(), 4) else: reward = 0.20
# check timeout if self._steps_used >= self._max_steps: self._done = True return self._observe(reward=reward, done=True, error=None)
return self._observe(reward=reward, done=False, error=None)
@property def state(self) -> State: return self._state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109from server.triage_environment import TriageEnvironmentfrom server.scenarios import TASK_TEMPLATESfrom models import TriageAction
def make_env(): return TriageEnvironment()
def test_reset_returns_observation(): env = make_env() obs = env.reset(seed=0, task="easy") assert obs.task == "easy" assert obs.done is False assert len(obs.logs) == 4
def test_seed_deterministic(): e1, e2 = make_env(), make_env() o1 = e1.reset(seed=42, task="easy") o2 = e2.reset(seed=42, task="easy") assert o1.logs == o2.logs
def test_invalid_action_low_reward(): env = make_env() env.reset(seed=0, task="easy") obs = env.step(TriageAction(action="garbage")) assert obs.reward == 0.20 assert obs.metadata.get("error") is not None
def test_query_logs_reveals_more(): env = make_env() env.reset(seed=0, task="easy") before = len(env._visible_logs) env.step(TriageAction(action="query_logs", target="")) after = len(env._visible_logs) assert after >= before
def test_resolve_terminal(): env = make_env() env.reset(seed=0, task="easy") obs = env.step(TriageAction(action="resolve")) assert obs.done is True
def test_premature_resolve_low_reward(): env = make_env() env.reset(seed=0, task="easy") obs = env.step(TriageAction(action="resolve")) assert obs.reward == 0.35 assert obs.incident_resolved is False
def test_easy_optimal_path(): env = make_env() env.reset(seed=0, task="easy") ip = env._scenario["incident"]["source_ip"]
r1 = env.step(TriageAction(action="query_logs", target="")) assert 0.0 < r1.reward < 1.0
r2 = env.step(TriageAction(action="block_ip", target=ip)) assert 0.0 < r2.reward < 1.0
r3 = env.step(TriageAction(action="resolve")) assert r3.done is True assert r3.incident_resolved is True assert 0.96 <= r3.reward <= 0.99
def test_all_rewards_in_range(): env = make_env() env.reset(seed=0, task="medium") rewards = [] for i in range(8): obs = env.step(TriageAction(action="query_logs", target="")) rewards.append(obs.reward) if obs.done: break for r in rewards: assert 0.0 < r < 1.0, f"reward {r} out of (0,1)"
def test_anti_farming(): env = make_env() env.reset(seed=0, task="easy") env.step(TriageAction(action="query_logs", target="")) obs2 = env.step(TriageAction(action="query_logs", target="")) assert obs2.reward <= 0.25
def test_each_task_has_templates(): for task in ["easy", "medium", "hard"]: assert len(TASK_TEMPLATES[task]) >= 3
def test_hard_needs_classify(): env = make_env() env.reset(seed=0, task="hard") ip = env._scenario["incident"]["source_ip"] env.step(TriageAction(action="query_logs", target="")) env.step(TriageAction(action="analyze", target="")) env.step(TriageAction(action="block_ip", target=ip)) obs = env.step(TriageAction(action="resolve")) assert obs.done is True assert obs.reward <= 0.50123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185#!/usr/bin/env bash## validate-submission.sh — OpenEnv Submission Validator## Checks that your HF Space is live, Docker image builds, and openenv validate passes.## Prerequisites:# - Docker: https://docs.docker.com/get-docker/# - openenv-core: pip install openenv-core# - curl (usually pre-installed)## Run:# curl -fsSL https://raw.githubusercontent.com/<owner>/<repo>/main/scripts/validate-submission.sh | bash -s -- <ping_url> [repo_dir]## Or download and run locally:# chmod +x validate-submission.sh# ./validate-submission.sh <ping_url> [repo_dir]## Arguments:# ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)# repo_dir Path to your repo (default: current directory)## Examples:# ./validate-submission.sh https://my-team.hf.space# ./validate-submission.sh https://my-team.hf.space ./my-repo#
set -uo pipefail
DOCKER_BUILD_TIMEOUT=600if [ -t 1 ]; then RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BOLD='\033[1m' NC='\033[0m'else RED='' GREEN='' YELLOW='' BOLD='' NC=''fi
run_with_timeout() { local secs="$1"; shift if command -v timeout &>/dev/null; then timeout "$secs" "$@" elif command -v gtimeout &>/dev/null; then gtimeout "$secs" "$@" else "$@" & local pid=$! ( sleep "$secs" && kill "$pid" 2>/dev/null ) & local watcher=$! wait "$pid" 2>/dev/null local rc=$? kill "$watcher" 2>/dev/null wait "$watcher" 2>/dev/null return $rc fi}
portable_mktemp() { local prefix="${1:-validate}" mktemp "${TMPDIR:-/tmp}/${prefix}-XXXXXX" 2>/dev/null || mktemp}
CLEANUP_FILES=()cleanup() { rm -f "${CLEANUP_FILES[@]+"${CLEANUP_FILES[@]}"}"; }trap cleanup EXIT
PING_URL="${1:-}"REPO_DIR="${2:-.}"
if [ -z "$PING_URL" ]; then printf "Usage: %s <ping_url> [repo_dir]\n" "$0" printf "\n" printf " ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)\n" printf " repo_dir Path to your repo (default: current directory)\n" exit 1fi
if ! REPO_DIR="$(cd "$REPO_DIR" 2>/dev/null && pwd)"; then printf "Error: directory '%s' not found\n" "${2:-.}" exit 1fiPING_URL="${PING_URL%/}"export PING_URLPASS=0
log() { printf "[%s] %b\n" "$(date -u +%H:%M:%S)" "$*"; }pass() { log "${GREEN}PASSED${NC} -- $1"; PASS=$((PASS + 1)); }fail() { log "${RED}FAILED${NC} -- $1"; }hint() { printf " ${YELLOW}Hint:${NC} %b\n" "$1"; }stop_at() { printf "\n" printf "${RED}${BOLD}Validation stopped at %s.${NC} Fix the above before continuing.\n" "$1" exit 1}
printf "\n"printf "${BOLD}========================================${NC}\n"printf "${BOLD} OpenEnv Submission Validator${NC}\n"printf "${BOLD}========================================${NC}\n"log "Repo: $REPO_DIR"log "Ping URL: $PING_URL"printf "\n"
log "${BOLD}Step 1/3: Pinging HF Space${NC} ($PING_URL/reset) ..."
CURL_OUTPUT=$(portable_mktemp "validate-curl")CLEANUP_FILES+=("$CURL_OUTPUT")HTTP_CODE=$(curl -s -o "$CURL_OUTPUT" -w "%{http_code}" -X POST \ -H "Content-Type: application/json" -d '{}' \ "$PING_URL/reset" --max-time 30 2>"$CURL_OUTPUT" || printf "000")
if [ "$HTTP_CODE" = "200" ]; then pass "HF Space is live and responds to /reset"elif [ "$HTTP_CODE" = "000" ]; then fail "HF Space not reachable (connection failed or timed out)" hint "Check your network connection and that the Space is running." hint "Try: curl -s -o /dev/null -w '%%{http_code}' -X POST $PING_URL/reset" stop_at "Step 1"else fail "HF Space /reset returned HTTP $HTTP_CODE (expected 200)" hint "Make sure your Space is running and the URL is correct." hint "Try opening $PING_URL in your browser first." stop_at "Step 1"fi
log "${BOLD}Step 2/3: Running docker build${NC} ..."
if ! command -v docker &>/dev/null; then fail "docker command not found" hint "Install Docker: https://docs.docker.com/get-docker/" stop_at "Step 2"fi
if [ -f "$REPO_DIR/Dockerfile" ]; then DOCKER_CONTEXT="$REPO_DIR"elif [ -f "$REPO_DIR/server/Dockerfile" ]; then DOCKER_CONTEXT="$REPO_DIR/server"else fail "No Dockerfile found in repo root or server/ directory" stop_at "Step 2"fi
log " Found Dockerfile in $DOCKER_CONTEXT"
BUILD_OK=falseBUILD_OUTPUT=$(run_with_timeout "$DOCKER_BUILD_TIMEOUT" docker build "$DOCKER_CONTEXT" 2>&1) && BUILD_OK=true
if [ "$BUILD_OK" = true ]; then pass "Docker build succeeded"else fail "Docker build failed (timeout=${DOCKER_BUILD_TIMEOUT}s)" printf "%s\n" "$BUILD_OUTPUT" | tail -20 stop_at "Step 2"fi
log "${BOLD}Step 3/3: Running openenv validate${NC} ..."
if ! command -v openenv &>/dev/null; then fail "openenv command not found" hint "Install it: pip install openenv-core" stop_at "Step 3"fi
VALIDATE_OK=falseVALIDATE_OUTPUT=$(cd "$REPO_DIR" && openenv validate 2>&1) && VALIDATE_OK=true
if [ "$VALIDATE_OK" = true ]; then pass "openenv validate passed" [ -n "$VALIDATE_OUTPUT" ] && log " $VALIDATE_OUTPUT"else fail "openenv validate failed" printf "%s\n" "$VALIDATE_OUTPUT" stop_at "Step 3"fi
printf "\n"printf "${BOLD}========================================${NC}\n"printf "${GREEN}${BOLD} All 3/3 checks passed!${NC}\n"printf "${GREEN}${BOLD} Your submission is ready to submit.${NC}\n"printf "${BOLD}========================================${NC}\n"printf "\n"
exit 0.github/workflows/ci.ymlAdded+30
.gitignoreAdded+8
DockerfileAdded+67
RATIONALE.mdAdded+33
README.mdAdded+82
__init__.pyAdded+1
client.pyAdded+46
evaluate.pyAdded+84
inference.pyAdded+178
models.pyAdded+24
openenv.yamlAdded+6
pyproject.tomlAdded+33
requirements.txtAdded+6
rubrics.pyAdded+34
server/__init__.pyAdded
server/app.pyAdded+35
server/scenarios.pyAdded+221
server/triage_environment.pyAdded+283
tests/__init__.pyAdded
tests/test_environment.pyAdded+109
uv.lockAdded
validate-submission.shAdded+185