hugsbun commited on
Commit
ba52031
·
0 Parent(s):

first commit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +75 -0
  2. README.md +764 -0
  3. debug_env/README.md +255 -0
  4. debug_env/__init__.py +16 -0
  5. debug_env/client.py +99 -0
  6. debug_env/data/__init__.py +1 -0
  7. debug_env/data/multi_user_sample.py +411 -0
  8. debug_env/models.py +10 -0
  9. debug_env/openenv.yaml +99 -0
  10. debug_env/pyproject.toml +70 -0
  11. debug_env/server/Dockerfile +80 -0
  12. debug_env/server/__init__.py +11 -0
  13. debug_env/server/app.py +104 -0
  14. debug_env/server/core/__init__.py +0 -0
  15. debug_env/server/core/apis.py +22 -0
  16. debug_env/server/database/__init__.py +1 -0
  17. debug_env/server/database/db.py +110 -0
  18. debug_env/server/database/managers/__init__.py +1 -0
  19. debug_env/server/database/managers/task_manager.py +451 -0
  20. debug_env/server/database/models/__init__.py +1 -0
  21. debug_env/server/database/models/task.py +91 -0
  22. debug_env/server/debug_env_environment.py +99 -0
  23. debug_env/server/grader.py +3 -0
  24. debug_env/server/handlers/__init__.py +3 -0
  25. debug_env/server/handlers/mcp_handler.py +261 -0
  26. debug_env/server/mcp/__init__.py +3 -0
  27. debug_env/server/mcp/router.py +30 -0
  28. debug_env/server/mcp/tools/__init__.py +1 -0
  29. debug_env/server/mcp/tools/debug_tools.py +494 -0
  30. debug_env/server/requirements.txt +6 -0
  31. debug_env/server/schemas/__init__.py +3 -0
  32. debug_env/server/schemas/task_schemas.py +95 -0
  33. debug_env/server/schemas/tool_schemas.py +76 -0
  34. debug_env/server/tasks/__init__.py +4 -0
  35. debug_env/server/tasks/data.py +145 -0
  36. debug_env/server/tasks/loader.py +241 -0
  37. debug_env/server/tasks/router.py +387 -0
  38. debug_env/server/tools/__init__.py +5 -0
  39. debug_env/server/tools/advanced_tools.py +520 -0
  40. debug_env/server/tools/edit_file/__init__.py +3 -0
  41. debug_env/server/tools/edit_file/tool.py +53 -0
  42. debug_env/server/tools/read_file/__init__.py +3 -0
  43. debug_env/server/tools/read_file/tool.py +71 -0
  44. debug_env/server/tools/run_tests/__init__.py +3 -0
  45. debug_env/server/tools/run_tests/tool.py +63 -0
  46. debug_env/server/tools/tool_handlers.py +129 -0
  47. debug_env/server/utils/__init__.py +3 -0
  48. debug_env/server/utils/validation.py +30 -0
  49. debug_env/tasks/task1/broken_code.py +5 -0
  50. debug_env/tasks/task1/test_code.py +13 -0
.gitignore ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Planning docs and txt files
2
+ planning/
3
+
4
+ # AI tool rules / instruction files
5
+ CLAUDE.md
6
+ AGENTS.md
7
+ GEMINI.md
8
+ QUICKSTART.md
9
+ COMPETITION_CHECKLIST.md
10
+ IMPLEMENTATION_SUMMARY.md
11
+ TECHNOLOGY_INTEGRATION.md
12
+ .cursorrules
13
+ .windsurfrules
14
+ .mcp.json
15
+ .opencode.json
16
+ .claude/
17
+ .cursor/
18
+
19
+ # Python
20
+ __pycache__/
21
+ *.py[cod]
22
+ *.pyo
23
+ *.pyd
24
+ *.so
25
+ *.egg
26
+ *.egg-info/
27
+ dist/
28
+ build/
29
+ .eggs/
30
+
31
+ # Virtual environments
32
+ .venv/
33
+ venv/
34
+ env/
35
+
36
+ # pytest
37
+ .pytest_cache/
38
+ .coverage
39
+ htmlcov/
40
+
41
+ # uv
42
+ uv.lock
43
+
44
+ # Environment variables
45
+ .env
46
+ .env.*
47
+
48
+ # Temp task workdirs (created at runtime by the environment)
49
+ /tmp/debug_task_*/
50
+
51
+ # OS
52
+ .DS_Store
53
+ Thumbs.db
54
+
55
+ # IDEs
56
+ .vscode/
57
+ .idea/
58
+ *.iml
59
+
60
+ # code-review-graph generated files
61
+ .code-review-graph/
62
+ .code-review-graphignore
63
+
64
+ # Results/output files generated during runs
65
+ results_*.json
66
+
67
+ # Runtime databases
68
+ debug_env/server/*.db
69
+ debug_env/server/*.db-shm
70
+ debug_env/server/*.db-wal
71
+ *.sqlite
72
+ *.sqlite3
73
+
74
+ # Claude Code local settings
75
+ .claude/settings.local.json
README.md ADDED
@@ -0,0 +1,764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Debug Env - AI Debugging Benchmark
3
+ emoji: 🐛
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ pinned: true
8
+ app_port: 8000
9
+ base_path: /web
10
+ tags:
11
+ - openenv
12
+ - debugging
13
+ - benchmark
14
+ - ai-agents
15
+ ---
16
+
17
+ # Debug Env — Production-Grade AI Debugging Benchmark
18
+
19
+ A sophisticated debugging benchmark built on [OpenEnv](https://github.com/meta-pytorch/OpenEnv), designed to evaluate AI agents' ability to identify and fix bugs in real-world Python code. Features 9 progressively complex tasks, comprehensive MCP tool support, SQLite persistence, Docker deployment, and Hugging Face integration.
20
+
21
+ **Live Demo**: [debug-env.hf.space](https://debug-env.hf.space)
22
+
23
+ ---
24
+
25
+ ## Table of Contents
26
+
27
+ - [Overview](#overview)
28
+ - [Key Features](#key-features)
29
+ - [Quick Start](#quick-start)
30
+ - [Installation](#installation)
31
+ - [Usage](#usage)
32
+ - [Architecture](#architecture)
33
+ - [Deployment](#deployment)
34
+ - [Docker](#docker)
35
+ - [Hugging Face Spaces](#hugging-face-spaces)
36
+ - [API Reference](#api-reference)
37
+ - [Tasks](#tasks)
38
+ - [MCP Tools](#mcp-tools)
39
+ - [Database](#database)
40
+ - [Development](#development)
41
+ - [Contributing](#contributing)
42
+ - [License](#license)
43
+
44
+ ---
45
+
46
+ ## Overview
47
+
48
+ Debug Env is a production-ready debugging environment that challenges AI models to locate and fix bugs across various complexity levels. From simple syntax errors to complex multi-file architectural issues, the benchmark provides realistic debugging scenarios with comprehensive tooling for code analysis.
49
+
50
+ **Built with:**
51
+ - FastAPI + Uvicorn (HTTP server)
52
+ - SQLAlchemy (ORM) + SQLite (persistence)
53
+ - OpenEnv (environment framework)
54
+ - MCP Protocol 2024-11-05 (tool interface)
55
+ - Docker (containerization)
56
+ - Hugging Face (model integration & hosting)
57
+
58
+ ---
59
+
60
+ ## Key Features
61
+
62
+ | Feature | Details |
63
+ |---------|---------|
64
+ | **9 Tasks** | From syntax errors to architecture refactoring |
65
+ | **9 MCP Tools** | 3 core + 6 advanced analysis tools |
66
+ | **Episode Tracking** | Full task lifecycle with status & metrics |
67
+ | **Pagination** | Base64 offset tokens + sync tokens |
68
+ | **Multi-User Ready** | User-scoped operations, role-based framework |
69
+ | **Production Architecture** | FastAPI, SQLAlchemy, SQLite |
70
+ | **Generic Tool Dispatch** | Scalable MCP handler pattern |
71
+ | **Docker Ready** | Dockerfile + docker-compose.yml included |
72
+ | **HF Integration** | Spaces-compatible, model inference ready |
73
+ | **Comprehensive Docs** | Google Calendar API v3-style specs |
74
+
75
+ ---
76
+
77
+ ## Quick Start
78
+
79
+ ### Via Docker (Recommended)
80
+
81
+ ```bash
82
+ # Clone repository
83
+ git clone https://github.com/yourorg/debug-env
84
+ cd debug-env
85
+
86
+ # Build and run with Docker Compose
87
+ docker-compose up --build
88
+
89
+ # Server runs at http://localhost:8000
90
+ ```
91
+
92
+ ### Via Python (Local Development)
93
+
94
+ ```bash
95
+ # Prerequisites: Python 3.10+, uv package manager
96
+ curl -LsSf https://astral.sh/uv/install.sh | sh
97
+
98
+ # Clone and install
99
+ git clone https://github.com/yourorg/debug-env
100
+ cd debug-env
101
+ uv sync
102
+
103
+ # Initialize database
104
+ python -c "from debug_env.server.database.db import init_db; init_db()"
105
+
106
+ # Run server
107
+ uv run server --port 8000
108
+ ```
109
+
110
+ ### Verify Installation
111
+
112
+ ```bash
113
+ # Check health endpoint
114
+ curl http://localhost:8000/health
115
+
116
+ # Response:
117
+ # {"status":"healthy","service":"debug-env"}
118
+ ```
119
+
120
+ ---
121
+
122
+ ## Installation
123
+
124
+ ### Requirements
125
+
126
+ - **Python**: 3.10 or higher
127
+ - **Docker**: (optional) For containerized deployment
128
+ - **Disk Space**: ~500MB (including dependencies)
129
+ - **RAM**: 2GB minimum (4GB recommended)
130
+
131
+ ### Option 1: Docker (Recommended for Deployment)
132
+
133
+ ```bash
134
+ docker build -t debug-env:latest .
135
+ docker run -p 8000:8000 debug-env:latest
136
+ ```
137
+
138
+ ### Option 2: Local Development
139
+
140
+ ```bash
141
+ # Install uv (fast Python package manager)
142
+ curl -LsSf https://astral.sh/uv/install.sh | sh
143
+
144
+ # Create virtual environment and install
145
+ uv sync
146
+
147
+ # Initialize database
148
+ uv run python -c "from debug_env.server.database.db import init_db; init_db()"
149
+
150
+ # Run development server
151
+ uv run server --reload
152
+ ```
153
+
154
+ ### Option 3: Hugging Face Spaces
155
+
156
+ Click the "Duplicate" button on the [Hugging Face Space](https://huggingface.co/spaces/yourorg/debug-env) to deploy your own instance.
157
+
158
+ ---
159
+
160
+ ## Usage
161
+
162
+ ### Web Interface
163
+
164
+ Visit `http://localhost:8000` to access:
165
+ - **Dashboard**: Environment state, reset/step UI
166
+ - **Task Browser**: View all 9 tasks and their metadata
167
+ - **Episode Tracker**: Track task runs and performance
168
+
169
+ ### Python API (Client)
170
+
171
+ ```python
172
+ from debug_env import DebugEnvironment, DebugAction
173
+
174
+ # Create environment
175
+ env = DebugEnvironment()
176
+
177
+ # Select task
178
+ obs = env.reset(task="task1")
179
+ print(f"Task: {env.current_task}")
180
+ print(f"Workdir: {env.workdir}")
181
+
182
+ # Read a file
183
+ obs = env.step(DebugAction(tool="read_file", args={"path": "broken_code.py"}))
184
+ print(obs.logs)
185
+
186
+ # Edit the file
187
+ obs = env.step(DebugAction(tool="edit_file", args={
188
+ "path": "broken_code.py",
189
+ "content": "fixed_code_here"
190
+ }))
191
+
192
+ print(f"Pass Rate: {obs.pass_rate}")
193
+ print(f"Done: {obs.done}")
194
+ print(f"Reward: {obs.reward}")
195
+ ```
196
+
197
+ ### MCP Interface (Claude, etc.)
198
+
199
+ ```bash
200
+ # Initialize connection
201
+ curl -X POST http://localhost:8000/mcp \
202
+ -H "Content-Type: application/json" \
203
+ -d '{
204
+ "jsonrpc": "2.0",
205
+ "method": "initialize",
206
+ "params": {"meta": {"task": "task1"}},
207
+ "id": 1
208
+ }'
209
+
210
+ # List available tools
211
+ curl -X POST http://localhost:8000/mcp \
212
+ -H "Content-Type: application/json" \
213
+ -d '{
214
+ "jsonrpc": "2.0",
215
+ "method": "tools/list",
216
+ "id": 2
217
+ }'
218
+
219
+ # Call a tool (search_code)
220
+ curl -X POST http://localhost:8000/mcp \
221
+ -H "Content-Type: application/json" \
222
+ -d '{
223
+ "jsonrpc": "2.0",
224
+ "method": "tools/call",
225
+ "params": {
226
+ "name": "search_code",
227
+ "arguments": {"pattern": "def .*bug", "file_types": "py"}
228
+ },
229
+ "id": 3
230
+ }'
231
+ ```
232
+
233
+ ### REST API (HTTP)
234
+
235
+ ```bash
236
+ # List tasks with pagination
237
+ curl "http://localhost:8000/tasks?maxResults=5"
238
+
239
+ # Get single task
240
+ curl "http://localhost:8000/tasks/task1"
241
+
242
+ # Create episode
243
+ curl -X POST "http://localhost:8000/tasks/task1/episodes"
244
+
245
+ # Update episode status
246
+ curl -X PATCH "http://localhost:8000/tasks/task1/episodes/{episode_id}" \
247
+ -H "Content-Type: application/json" \
248
+ -d '{"status": "passed", "pass_rate": 1.0}'
249
+ ```
250
+
251
+ ---
252
+
253
+ ## Architecture
254
+
255
+ ### System Design
256
+
257
+ ```
258
+ ┌─────────────────────────────────────────────────────────────┐
259
+ │ Client Layer │
260
+ │ ┌──────────────┬──────────────┬──────────────┐ │
261
+ │ │ Web UI │ MCP Client │ REST API │ │
262
+ │ └──────────────┴──────────────┴──────────────┘ │
263
+ └────────────────────┬────────────────────────────────────────┘
264
+ │
265
+ ┌────────────────────────────────────────────────────────────┐
266
+ │ FastAPI Server │
267
+ │ ┌────────────────────────────────────────────────────┐ │
268
+ │ │ OpenEnv HTTP Server │ │
269
+ │ │ POST /reset POST /step GET /state WS /ws │ │
270
+ │ └────────────────────────────────────────────────────┘ │
271
+ │ ┌──────────────┬────────────┬──────────────────┐ │
272
+ │ │ Core APIs │ Task APIs │ MCP Router │ │
273
+ │ │ /health │ /tasks │ POST /mcp │ │
274
+ │ └──────────────┴────────────┴──────────────────┘ │
275
+ └─────────┬──────────────────────────────────┬────────────────┘
276
+ │ │
277
+ ┌────▼──────────────────┐ ┌──────▼──────────┐
278
+ │ DebugEnvironment │ │ Database Layer │
279
+ │ ├─ reset(task) │ │ ├─ TaskManager │
280
+ │ ├─ step(action) │ │ ├─ Models │
281
+ │ └─ TaskLoader │ │ └─ Schemas │
282
+ └────────┬───────────────┘ └──────┬──────────┘
283
+ │ │
284
+ ┌────▼──────────────┐ ┌──────▼──────────┐
285
+ │ Tool Execution │ │ SQLite DB │
286
+ │ ├─ run_tests │ │ ├─ Tasks │
287
+ │ ├─ read_file │ │ ├─ Episodes │
288
+ │ ├─ edit_file │ │ └─ Channels │
289
+ │ ├─ search_code │ └─────────────────┘
290
+ │ ├─ get_coverage │
291
+ │ └─ (6 more) │
292
+ └───────────────────┘
293
+ ```
294
+
295
+ ### Directory Structure
296
+
297
+ ```
298
+ debug-env/
299
+ ├── debug_env/
300
+ │ ├── __init__.py
301
+ │ ├── models.py # DebugAction, DebugObservation
302
+ │ ���── client.py # DebugEnv client class
303
+ │ │
304
+ │ ├── server/
305
+ │ │ ├── app.py # FastAPI app creation
306
+ │ │ ├── debug_env_environment.py # Core DebugEnvironment
307
+ │ │ ├── grader.py # Reward calculation
308
+ │ │ │
309
+ │ │ ├── core/
310
+ │ │ │ └── apis.py # Health check endpoint
311
+ │ │ │
312
+ │ │ ├── database/ # NEW: Database layer
313
+ │ │ │ ├── db.py # SQLAlchemy setup
314
+ │ │ │ ├── models/
315
+ │ │ │ │ └── task.py # ORM models
316
+ │ │ │ └── managers/
317
+ │ │ │ └── task_manager.py # TaskManager class
318
+ │ │ │
319
+ │ │ ├── handlers/
320
+ │ │ │ └── mcp_handler.py # MCP JSON-RPC dispatcher
321
+ │ │ │
322
+ │ │ ├── mcp/
323
+ │ │ │ ├── router.py # MCP endpoint
324
+ │ │ │ └── tools/
325
+ │ │ │ └── debug_tools.py # Tool definitions
326
+ │ │ │
327
+ │ │ ├── schemas/
328
+ │ │ │ ├── tool_schemas.py # Tool I/O schemas
329
+ │ │ │ └── task_schemas.py # Task/Episode schemas
330
+ │ │ │
331
+ │ │ ├── tasks/
332
+ │ │ │ ├── data.py # Task registry
333
+ │ │ │ ├── loader.py # File staging
334
+ │ │ │ └── router.py # Task endpoints
335
+ │ │ │
336
+ │ │ ├── tools/
337
+ │ │ │ ├── advanced_tools.py # 6 analysis tools
338
+ │ │ │ ├── tool_handlers.py # Generic dispatcher
339
+ │ │ │ ├── run_tests/
340
+ │ │ │ ├── read_file/
341
+ │ │ │ └── edit_file/
342
+ │ │ │
343
+ │ │ └── utils/
344
+ │ │ └── validation.py # Security checks
345
+ │ │
346
+ │ ├── tasks/ # Task seed data
347
+ │ │ ├── task1/ → task9/ # 9 tasks
348
+ │ │ └── [seed_data.py files]
349
+ │ │
350
+ │ └── data/
351
+ │ └── multi_user_sample.py # User/role models
352
+ │
353
+ ├── tests/ # Test suite
354
+ │ ├── test_tasks.py
355
+ │ ├── test_tools.py
356
+ │ └── test_database.py
357
+ │
358
+ ├── Dockerfile # Container definition
359
+ ├── docker-compose.yml # Multi-container setup
360
+ ├── pyproject.toml # Dependencies
361
+ ├── README.md # This file
362
+ ├── LICENSE # BSD license
363
+ └── debug_env.db # SQLite database (created)
364
+ ```
365
+
366
+ ---
367
+
368
+ ## Deployment
369
+
370
+ ### Docker
371
+
372
+ #### Dockerfile
373
+
374
+ ```dockerfile
375
+ FROM python:3.11-slim
376
+
377
+ WORKDIR /app
378
+
379
+ # Install dependencies
380
+ RUN apt-get update && apt-get install -y \
381
+ gcc \
382
+ && rm -rf /var/lib/apt/lists/*
383
+
384
+ # Copy project
385
+ COPY . .
386
+
387
+ # Install Python dependencies
388
+ RUN pip install --no-cache-dir -e .
389
+
390
+ # Initialize database
391
+ RUN python -c "from debug_env.server.database.db import init_db; init_db()"
392
+
393
+ # Expose port
394
+ EXPOSE 8000
395
+
396
+ # Run server
397
+ CMD ["python", "-m", "debug_env.server.app"]
398
+ ```
399
+
400
+ #### Docker Compose
401
+
402
+ ```yaml
403
+ version: '3.8'
404
+
405
+ services:
406
+ debug-env:
407
+ build: .
408
+ ports:
409
+ - "8000:8000"
410
+ volumes:
411
+ - ./debug_env:/app/debug_env
412
+ - ./debug_env.db:/app/debug_env.db
413
+ environment:
414
+ - PYTHONUNBUFFERED=1
415
+ - LOG_LEVEL=INFO
416
+ healthcheck:
417
+ test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
418
+ interval: 10s
419
+ timeout: 5s
420
+ retries: 3
421
+
422
+ # Optional: Nginx reverse proxy
423
+ nginx:
424
+ image: nginx:latest
425
+ ports:
426
+ - "80:80"
427
+ volumes:
428
+ - ./nginx.conf:/etc/nginx/nginx.conf
429
+ depends_on:
430
+ - debug-env
431
+ ```
432
+
433
+ #### Build and Deploy
434
+
435
+ ```bash
436
+ # Build image
437
+ docker build -t debug-env:v1.0.0 .
438
+
439
+ # Run container
440
+ docker run -p 8000:8000 \
441
+ -v $(pwd)/debug_env.db:/app/debug_env.db \
442
+ debug-env:v1.0.0
443
+
444
+ # With Docker Compose
445
+ docker-compose up -d
446
+
447
+ # View logs
448
+ docker-compose logs -f debug-env
449
+ ```
450
+
451
+ ### Hugging Face Spaces
452
+
453
+ #### Setup
454
+
455
+ 1. Go to [Hugging Face Spaces](https://huggingface.co/spaces)
456
+ 2. Click **"Create new Space"**
457
+ 3. Choose **"Docker"** as the SDK
458
+ 4. Configure:
459
+ - **Owner**: Your organization
460
+ - **Space name**: `debug-env`
461
+ - **Visibility**: Public (for demo) or Private (for testing)
462
+ - **Persistent Storage**: Enable (for SQLite DB)
463
+ - **Hardware**: CPU (free) or GPU
464
+
465
+ #### Configuration
466
+
467
+ Create `app_config.json`:
468
+
469
+ ```json
470
+ {
471
+ "title": "Debug Env Benchmark",
472
+ "description": "AI Debugging Benchmark",
473
+ "emoji": "🐛",
474
+ "colorFrom": "blue",
475
+ "colorTo": "indigo",
476
+ "sdk": "docker",
477
+ "app_port": 8000,
478
+ "base_path": "/web",
479
+ "persistentStorage": {
480
+ "enabled": true,
481
+ "mountPath": "/app/data"
482
+ },
483
+ "tags": ["openenv", "debugging", "benchmark"]
484
+ }
485
+ ```
486
+
487
+ #### Deploy
488
+
489
+ ```bash
490
+ # Push to Hugging Face
491
+ git push https://huggingface.co/spaces/yourorg/debug-env main
492
+
493
+ # Spaces automatically builds and deploys
494
+ # Access at: https://yourorg-debug-env.hf.space
495
+ ```
496
+
497
+ #### Integration with HF Hub
498
+
499
+ ```python
500
+ from huggingface_hub import InferenceClient
501
+
502
+ client = InferenceClient(
503
+ model="yourorg/debug-env",
504
+ token="hf_xxxxx"
505
+ )
506
+
507
+ # Make inference calls
508
+ result = client.post(
509
+ json={"task": "task1", "tool": "search_code", "pattern": "bug"}
510
+ )
511
+ ```
512
+
513
+ ---
514
+
515
+ ## API Reference
516
+
517
+ ### REST Endpoints
518
+
519
+ #### Health Check
520
+ ```
521
+ GET /health
522
+ Response: {"status": "healthy", "service": "debug-env"}
523
+ ```
524
+
525
+ #### Task Management
526
+
527
+ ```
528
+ GET /tasks?maxResults=50&pageToken=<token>&syncToken=<token>
529
+ Response: {
530
+ "etag": "...",
531
+ "items": [{id, title, description, files, tools, ...}],
532
+ "nextPageToken": "...",
533
+ "nextSyncToken": "..."
534
+ }
535
+
536
+ GET /tasks/{taskId}
537
+ Response: {id, title, description, difficulty, bug_type, files, tools, ...}
538
+
539
+ GET /tasks/{taskId}/files
540
+ Response: ["broken_code.py", "helper.py"]
541
+
542
+ GET /tasks/{taskId}/files/{filename}
543
+ Response: {task_id, filename, content}
544
+ ```
545
+
546
+ #### Episode Management
547
+
548
+ ```
549
+ POST /tasks/{taskId}/episodes
550
+ Response: {id, task_id, status: "active", workdir, etag, created_at, ...}
551
+
552
+ GET /tasks/{taskId}/episodes?maxResults=50&pageToken=<token>
553
+ Response: {items: [...], nextPageToken: "..."}
554
+
555
+ GET /tasks/{taskId}/episodes/{episodeId}
556
+ Response: {id, task_id, status, pass_rate, workdir, etag, ...}
557
+
558
+ PATCH /tasks/{taskId}/episodes/{episodeId}
559
+ Body: {status?: "passed"|"failed"|"abandoned", pass_rate?: 0.0-1.0}
560
+ Response: {id, task_id, status, pass_rate, ...}
561
+ ```
562
+
563
+ ### MCP Tools
564
+
565
+ #### Core Tools (3)
566
+
567
+ **1. `run_tests`** — Execute pytest suite
568
+ ```json
569
+ {"name": "run_tests", "inputSchema": {"type": "object", "properties": {}}}
570
+ ```
571
+ Returns: `pass_rate` (0.0-1.0), `logs`, `reward`, `done`
572
+
573
+ **2. `read_file`** — Read file from workdir
574
+ ```json
575
+ {
576
+ "name": "read_file",
577
+ "inputSchema": {
578
+ "type": "object",
579
+ "properties": {"path": {"type": "string"}},
580
+ "required": ["path"]
581
+ }
582
+ }
583
+ ```
584
+ Returns: `logs` (file content), `success`
585
+
586
+ **3. `edit_file`** — Write and test file
587
+ ```json
588
+ {
589
+ "name": "edit_file",
590
+ "inputSchema": {
591
+ "type": "object",
592
+ "properties": {
593
+ "path": {"type": "string"},
594
+ "content": {"type": "string"}
595
+ },
596
+ "required": ["path", "content"]
597
+ }
598
+ }
599
+ ```
600
+ Returns: `pass_rate`, `logs`, `reward`, `done`
601
+
602
+ #### Advanced Tools (6)
603
+
604
+ **4. `search_code`** — Pattern matching with ripgrep
605
+ ```json
606
+ {
607
+ "name": "search_code",
608
+ "inputSchema": {
609
+ "properties": {
610
+ "pattern": {"type": "string", "minLength": 1, "maxLength": 500},
611
+ "file_types": {"enum": ["py", "all", "txt", "json", "md"]},
612
+ "max_results": {"type": "integer", "minimum": 1, "maximum": 500}
613
+ },
614
+ "required": ["pattern"]
615
+ }
616
+ }
617
+ ```
618
+
619
+ **5. `get_file_structure`** — AST-based code structure
620
+ **6. `run_type_check`** — Mypy static analysis
621
+ **7. `get_test_coverage`** — Coverage.py metrics
622
+ **8. `list_directory`** — Recursive directory listing
623
+ **9. `get_dependencies`** — Import analysis
624
+
625
+ ---
626
+
627
+ ## Tasks
628
+
629
+ | # | Task | Difficulty | Type | Description |
630
+ |---|------|-----------|------|-------------|
631
+ | 1 | Syntax Error | Easy | Bug Fix | Fix Python syntax preventing import |
632
+ | 2 | Logic Error | Medium | Bug Fix | Fix boolean expression logic |
633
+ | 3 | Multi-file Bug | Hard | Bug Fix | Fix bug across multiple modules |
634
+ | 4 | Type Errors | Medium | Type Check | Fix mypy type annotation errors |
635
+ | 5 | Code Quality | Medium | Cleanup | Remove unused imports/dead code |
636
+ | 6 | Architecture | Hard | Refactoring | Multi-file refactoring with circular imports |
637
+ | 7 | Code Review | Medium | Collab | Junior submits, senior reviews |
638
+ | 8 | Bug Investigation | Hard | Collab | QA reports, team investigates |
639
+ | 9 | Team Refactoring | Hard | Collab | Multi-user architecture fix |
640
+
641
+ ---
642
+
643
+ ## Database
644
+
645
+ ### Schema
646
+
647
+ **task_records** — Task metadata (seeded from registry)
648
+ ```sql
649
+ CREATE TABLE task_records (
650
+ id TEXT PRIMARY KEY,
651
+ title TEXT, description TEXT,
652
+ difficulty TEXT, bug_type TEXT,
653
+ files JSON, tools JSON,
654
+ scenario_type TEXT, participants JSON,
655
+ etag TEXT, created_at DATETIME, updated_at DATETIME
656
+ )
657
+ ```
658
+
659
+ **episode_records** — Task runs (user episodes)
660
+ ```sql
661
+ CREATE TABLE episode_records (
662
+ id TEXT PRIMARY KEY,
663
+ task_id TEXT, user_id TEXT,
664
+ workdir TEXT, status TEXT,
665
+ pass_rate REAL,
666
+ etag TEXT, created_at DATETIME, updated_at DATETIME
667
+ )
668
+ ```
669
+
670
+ **watch_channels** — Webhook subscriptions
671
+ ```sql
672
+ CREATE TABLE watch_channels (
673
+ id TEXT PRIMARY KEY,
674
+ task_id TEXT, user_id TEXT,
675
+ webhook_address TEXT, webhook_token TEXT,
676
+ expires_at DATETIME, is_active BOOLEAN,
677
+ created_at DATETIME
678
+ )
679
+ ```
680
+
681
+ ---
682
+
683
+ ## Development
684
+
685
+ ### Testing
686
+
687
+ ```bash
688
+ # Run all tests
689
+ pytest
690
+
691
+ # With coverage
692
+ pytest --cov=debug_env
693
+
694
+ # Specific test file
695
+ pytest tests/test_tasks.py -v
696
+ ```
697
+
698
+ ### Code Quality
699
+
700
+ ```bash
701
+ # Format with Black
702
+ black debug_env tests
703
+
704
+ # Lint with Ruff
705
+ ruff check debug_env tests
706
+
707
+ # Type check with Mypy
708
+ mypy debug_env
709
+ ```
710
+
711
+ ### Adding Tasks
712
+
713
+ 1. Create `debug_env/tasks/taskN/seed_data.py`
714
+ 2. Register in `server/tasks/data.py`
715
+ 3. Add to `server/tasks/loader.py`
716
+ 4. Update `pyproject.toml`
717
+
718
+ ### Adding Tools
719
+
720
+ 1. Implement in `server/tools/advanced_tools.py`
721
+ 2. Add spec to `server/mcp/tools/debug_tools.py`
722
+ 3. Update `tool_handlers.py`
723
+
724
+ ---
725
+
726
+ ## Contributing
727
+
728
+ 1. **Fork** the repository
729
+ 2. **Create branch**: `git checkout -b feature/xyz`
730
+ 3. **Make changes** with tests
731
+ 4. **Run tests**: `pytest`
732
+ 5. **Submit PR** with description
733
+
734
+ ---
735
+
736
+ ## License
737
+
738
+ BSD 3-Clause License — See [LICENSE](LICENSE) file
739
+
740
+ ---
741
+
742
+ ## Citation
743
+
744
+ ```bibtex
745
+ @software{debug_env_2026,
746
+ title={Debug Env: Production-Grade AI Debugging Benchmark},
747
+ author={Your Organization},
748
+ year={2026},
749
+ url={https://github.com/yourorg/debug-env}
750
+ }
751
+ ```
752
+
753
+ ---
754
+
755
+ ## Links
756
+
757
+ - **GitHub**: https://github.com/yourorg/debug-env
758
+ - **OpenEnv**: https://github.com/meta-pytorch/OpenEnv
759
+ - **Hugging Face**: https://huggingface.co/spaces/yourorg/debug-env
760
+ - **Issues**: https://github.com/yourorg/debug-env/issues
761
+
762
+ ---
763
+
764
+ **Last Updated**: April 3, 2026
debug_env/README.md ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Debug Env Environment Server
3
+ emoji: 🎽
4
+ colorFrom: green
5
+ colorTo: yellow
6
+ sdk: docker
7
+ pinned: false
8
+ app_port: 8000
9
+ base_path: /web
10
+ tags:
11
+ - openenv
12
+ ---
13
+
14
+ # Debug Env Environment
15
+
16
+ A simple test environment that echoes back messages. Perfect for testing the env APIs as well as demonstrating environment usage patterns.
17
+
18
+ ## Quick Start
19
+
20
+ The simplest way to use the Debug Env environment is through the `DebugEnv` class:
21
+
22
+ ```python
23
+ from debug_env import DebugAction, DebugEnv
24
+
25
+ try:
26
+ # Create environment from Docker image
27
+ debug_envenv = DebugEnv.from_docker_image("debug_env-env:latest")
28
+
29
+ # Reset
30
+ result = debug_envenv.reset()
31
+ print(f"Reset: {result.observation.echoed_message}")
32
+
33
+ # Send multiple messages
34
+ messages = ["Hello, World!", "Testing echo", "Final message"]
35
+
36
+ for msg in messages:
37
+ result = debug_envenv.step(DebugAction(message=msg))
38
+ print(f"Sent: '{msg}'")
39
+ print(f" → Echoed: '{result.observation.echoed_message}'")
40
+ print(f" → Length: {result.observation.message_length}")
41
+ print(f" → Reward: {result.reward}")
42
+
43
+ finally:
44
+ # Always clean up
45
+ debug_envenv.close()
46
+ ```
47
+
48
+ That's it! The `DebugEnv.from_docker_image()` method handles:
49
+ - Starting the Docker container
50
+ - Waiting for the server to be ready
51
+ - Connecting to the environment
52
+ - Container cleanup when you call `close()`
53
+
54
+ ## Building the Docker Image
55
+
56
+ Before using the environment, you need to build the Docker image:
57
+
58
+ ```bash
59
+ # From project root
60
+ docker build -t debug_env-env:latest -f server/Dockerfile .
61
+ ```
62
+
63
+ ## Deploying to Hugging Face Spaces
64
+
65
+ You can easily deploy your OpenEnv environment to Hugging Face Spaces using the `openenv push` command:
66
+
67
+ ```bash
68
+ # From the environment directory (where openenv.yaml is located)
69
+ openenv push
70
+
71
+ # Or specify options
72
+ openenv push --namespace my-org --private
73
+ ```
74
+
75
+ The `openenv push` command will:
76
+ 1. Validate that the directory is an OpenEnv environment (checks for `openenv.yaml`)
77
+ 2. Prepare a custom build for Hugging Face Docker space (enables web interface)
78
+ 3. Upload to Hugging Face (ensuring you're logged in)
79
+
80
+ ### Prerequisites
81
+
82
+ - Authenticate with Hugging Face: The command will prompt for login if not already authenticated
83
+
84
+ ### Options
85
+
86
+ - `--directory`, `-d`: Directory containing the OpenEnv environment (defaults to current directory)
87
+ - `--repo-id`, `-r`: Repository ID in format 'username/repo-name' (defaults to 'username/env-name' from openenv.yaml)
88
+ - `--base-image`, `-b`: Base Docker image to use (overrides Dockerfile FROM)
89
+ - `--private`: Deploy the space as private (default: public)
90
+
91
+ ### Examples
92
+
93
+ ```bash
94
+ # Push to your personal namespace (defaults to username/env-name from openenv.yaml)
95
+ openenv push
96
+
97
+ # Push to a specific repository
98
+ openenv push --repo-id my-org/my-env
99
+
100
+ # Push with a custom base image
101
+ openenv push --base-image ghcr.io/meta-pytorch/openenv-base:latest
102
+
103
+ # Push as a private space
104
+ openenv push --private
105
+
106
+ # Combine options
107
+ openenv push --repo-id my-org/my-env --base-image custom-base:latest --private
108
+ ```
109
+
110
+ After deployment, your space will be available at:
111
+ `https://huggingface.co/spaces/<repo-id>`
112
+
113
+ The deployed space includes:
114
+ - **Web Interface** at `/web` - Interactive UI for exploring the environment
115
+ - **API Documentation** at `/docs` - Full OpenAPI/Swagger interface
116
+ - **Health Check** at `/health` - Container health monitoring
117
+ - **WebSocket** at `/ws` - Persistent session endpoint for low-latency interactions
118
+
119
+ ## Environment Details
120
+
121
+ ### Action
122
+ **DebugAction**: Contains a single field
123
+ - `message` (str) - The message to echo back
124
+
125
+ ### Observation
126
+ **DebugObservation**: Contains the echo response and metadata
127
+ - `echoed_message` (str) - The message echoed back
128
+ - `message_length` (int) - Length of the message
129
+ - `reward` (float) - Reward based on message length (length × 0.1)
130
+ - `done` (bool) - Always False for echo environment
131
+ - `metadata` (dict) - Additional info like step count
132
+
133
+ ### Reward
134
+ The reward is calculated as: `message_length × 0.1`
135
+ - "Hi" → reward: 0.2
136
+ - "Hello, World!" → reward: 1.3
137
+ - Empty message → reward: 0.0
138
+
139
+ ## Advanced Usage
140
+
141
+ ### Connecting to an Existing Server
142
+
143
+ If you already have a Debug Env environment server running, you can connect directly:
144
+
145
+ ```python
146
+ from debug_env import DebugEnv
147
+
148
+ # Connect to existing server
149
+ debug_envenv = DebugEnv(base_url="<ENV_HTTP_URL_HERE>")
150
+
151
+ # Use as normal
152
+ result = debug_envenv.reset()
153
+ result = debug_envenv.step(DebugAction(message="Hello!"))
154
+ ```
155
+
156
+ Note: When connecting to an existing server, `debug_envenv.close()` will NOT stop the server.
157
+
158
+ ### Using the Context Manager
159
+
160
+ The client supports context manager usage for automatic connection management:
161
+
162
+ ```python
163
+ from debug_env import DebugAction, DebugEnv
164
+
165
+ # Connect with context manager (auto-connects and closes)
166
+ with DebugEnv(base_url="http://localhost:8000") as env:
167
+ result = env.reset()
168
+ print(f"Reset: {result.observation.echoed_message}")
169
+ # Multiple steps with low latency
170
+ for msg in ["Hello", "World", "!"]:
171
+ result = env.step(DebugAction(message=msg))
172
+ print(f"Echoed: {result.observation.echoed_message}")
173
+ ```
174
+
175
+ The client uses WebSocket connections for:
176
+ - **Lower latency**: No HTTP connection overhead per request
177
+ - **Persistent session**: Server maintains your environment state
178
+ - **Efficient for episodes**: Better for many sequential steps
179
+
180
+ ### Concurrent WebSocket Sessions
181
+
182
+ The server supports multiple concurrent WebSocket connections. To enable this,
183
+ modify `server/app.py` to use factory mode:
184
+
185
+ ```python
186
+ # In server/app.py - use factory mode for concurrent sessions
187
+ app = create_app(
188
+ DebugEnvironment, # Pass class, not instance
189
+ DebugAction,
190
+ DebugObservation,
191
+ max_concurrent_envs=4, # Allow 4 concurrent sessions
192
+ )
193
+ ```
194
+
195
+ Then multiple clients can connect simultaneously:
196
+
197
+ ```python
198
+ from debug_env import DebugAction, DebugEnv
199
+ from concurrent.futures import ThreadPoolExecutor
200
+
201
+ def run_episode(client_id: int):
202
+ with DebugEnv(base_url="http://localhost:8000") as env:
203
+ result = env.reset()
204
+ for i in range(10):
205
+ result = env.step(DebugAction(message=f"Client {client_id}, step {i}"))
206
+ return client_id, result.observation.message_length
207
+
208
+ # Run 4 episodes concurrently
209
+ with ThreadPoolExecutor(max_workers=4) as executor:
210
+ results = list(executor.map(run_episode, range(4)))
211
+ ```
212
+
213
+ ## Development & Testing
214
+
215
+ ### Direct Environment Testing
216
+
217
+ Test the environment logic directly without starting the HTTP server:
218
+
219
+ ```bash
220
+ # From the server directory
221
+ python3 server/debug_env_environment.py
222
+ ```
223
+
224
+ This verifies that:
225
+ - Environment resets correctly
226
+ - Step executes actions properly
227
+ - State tracking works
228
+ - Rewards are calculated correctly
229
+
230
+ ### Running Locally
231
+
232
+ Run the server locally for development:
233
+
234
+ ```bash
235
+ uvicorn server.app:app --reload
236
+ ```
237
+
238
+ ## Project Structure
239
+
240
+ ```
241
+ debug_env/
242
+ ├── .dockerignore # Docker build exclusions
243
+ ├── __init__.py # Module exports
244
+ ├── README.md # This file
245
+ ├── openenv.yaml # OpenEnv manifest
246
+ ├── pyproject.toml # Project metadata and dependencies
247
+ ├── uv.lock # Locked dependencies (generated)
248
+ ├── client.py # DebugEnv client
249
+ ├── models.py # Action and Observation models
250
+ └── server/
251
+ ├── __init__.py # Server module exports
252
+ ├── debug_env_environment.py # Core environment logic
253
+ ├── app.py # FastAPI application (HTTP + WebSocket endpoints)
254
+ └── Dockerfile # Container image definition
255
+ ```
debug_env/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Debug Env Environment."""
8
+
9
+ from .client import DebugEnv
10
+ from .models import DebugAction, DebugObservation
11
+
12
+ __all__ = [
13
+ "DebugAction",
14
+ "DebugObservation",
15
+ "DebugEnv",
16
+ ]
debug_env/client.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Debug Env Environment Client."""
8
+
9
+ from typing import Dict
10
+
11
+ from openenv.core import EnvClient
12
+ from openenv.core.client_types import StepResult
13
+ from openenv.core.env_server.types import State
14
+
15
+ from .models import DebugAction, DebugObservation
16
+
17
+
18
+ class DebugEnv(
19
+ EnvClient[DebugAction, DebugObservation, State]
20
+ ):
21
+ """
22
+ Client for the Debug Env Environment.
23
+
24
+ This client maintains a persistent WebSocket connection to the environment server,
25
+ enabling efficient multi-step interactions with lower latency.
26
+ Each client instance has its own dedicated environment session on the server.
27
+
28
+ Example:
29
+ >>> # Connect to a running server
30
+ >>> with DebugEnv(base_url="http://localhost:8000") as client:
31
+ ... result = client.reset()
32
+ ... print(result.observation.echoed_message)
33
+ ...
34
+ ... result = client.step(DebugAction(message="Hello!"))
35
+ ... print(result.observation.echoed_message)
36
+
37
+ Example with Docker:
38
+ >>> # Automatically start container and connect
39
+ >>> client = DebugEnv.from_docker_image("debug_env-env:latest")
40
+ >>> try:
41
+ ... result = client.reset()
42
+ ... result = client.step(DebugAction(message="Test"))
43
+ ... finally:
44
+ ... client.close()
45
+ """
46
+
47
+ def _step_payload(self, action: DebugAction) -> Dict:
48
+ """
49
+ Convert DebugAction to JSON payload for step message.
50
+
51
+ Args:
52
+ action: DebugAction instance
53
+
54
+ Returns:
55
+ Dictionary representation suitable for JSON encoding
56
+ """
57
+ return {
58
+ "message": action.message,
59
+ }
60
+
61
+ def _parse_result(self, payload: Dict) -> StepResult[DebugObservation]:
62
+ """
63
+ Parse server response into StepResult[DebugObservation].
64
+
65
+ Args:
66
+ payload: JSON response data from server
67
+
68
+ Returns:
69
+ StepResult with DebugObservation
70
+ """
71
+ obs_data = payload.get("observation", {})
72
+ observation = DebugObservation(
73
+ echoed_message=obs_data.get("echoed_message", ""),
74
+ message_length=obs_data.get("message_length", 0),
75
+ done=payload.get("done", False),
76
+ reward=payload.get("reward"),
77
+ metadata=obs_data.get("metadata", {}),
78
+ )
79
+
80
+ return StepResult(
81
+ observation=observation,
82
+ reward=payload.get("reward"),
83
+ done=payload.get("done", False),
84
+ )
85
+
86
+ def _parse_state(self, payload: Dict) -> State:
87
+ """
88
+ Parse server response into State object.
89
+
90
+ Args:
91
+ payload: JSON response from state request
92
+
93
+ Returns:
94
+ State object with episode_id and step_count
95
+ """
96
+ return State(
97
+ episode_id=payload.get("episode_id"),
98
+ step_count=payload.get("step_count", 0),
99
+ )
debug_env/data/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Data module with sample data and seed files."""
debug_env/data/multi_user_sample.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Multi-User Sample Data for Debug Environment
3
+
4
+ Demonstrates collaborative debugging scenarios with multiple users,
5
+ roles, and access patterns.
6
+ """
7
+
8
+ from datetime import datetime, timedelta
9
+ from typing import Any, Dict, List
10
+
11
+
12
+ def get_multi_user_sample_data() -> Dict[str, Any]:
13
+ """
14
+ Generate multi-user sample data for collaborative debugging scenarios.
15
+
16
+ Users:
17
+ - alice_senior: Senior developer (can assign, review, approve)
18
+ - bob_junior: Junior developer (can fix, needs review)
19
+ - carol_qa: QA engineer (reports bugs, verifies fixes)
20
+ - dave_lead: Tech lead (oversight, final approval)
21
+
22
+ Scenarios:
23
+ 1. Code Review Workflow: Junior submits fix, senior reviews
24
+ 2. Cross-team Bug Investigation: QA reports, dev investigates, lead coordinates
25
+ 3. Collaborative Refactoring: Multiple devs, different responsibilities
26
+ """
27
+ return {
28
+ "users": get_users(),
29
+ "roles": get_roles(),
30
+ "permissions": get_permissions(),
31
+ "tasks_metadata": get_tasks_metadata(),
32
+ "description": "Multi-user collaboration scenarios for debugging benchmark",
33
+ }
34
+
35
+
36
+ def get_users() -> List[Dict[str, Any]]:
37
+ """Get sample users with different roles and permissions."""
38
+ return [
39
+ {
40
+ "user_id": "alice_senior",
41
+ "name": "Alice Chen",
42
+ "role": "Senior Developer",
43
+ "email": "alice.chen@company.com",
44
+ "experience_level": "senior",
45
+ "timezone": "America/New_York",
46
+ "created_at": datetime.now().isoformat(),
47
+ },
48
+ {
49
+ "user_id": "bob_junior",
50
+ "name": "Bob Kumar",
51
+ "role": "Junior Developer",
52
+ "email": "bob.kumar@company.com",
53
+ "experience_level": "junior",
54
+ "timezone": "America/Los_Angeles",
55
+ "created_at": datetime.now().isoformat(),
56
+ },
57
+ {
58
+ "user_id": "carol_qa",
59
+ "name": "Carol Martinez",
60
+ "role": "QA Engineer",
61
+ "email": "carol.martinez@company.com",
62
+ "experience_level": "mid",
63
+ "timezone": "America/Chicago",
64
+ "created_at": datetime.now().isoformat(),
65
+ },
66
+ {
67
+ "user_id": "dave_lead",
68
+ "name": "Dave Thompson",
69
+ "role": "Tech Lead",
70
+ "email": "dave.thompson@company.com",
71
+ "experience_level": "senior",
72
+ "timezone": "America/New_York",
73
+ "created_at": datetime.now().isoformat(),
74
+ },
75
+ ]
76
+
77
+
78
+ def get_roles() -> List[Dict[str, Any]]:
79
+ """Get role definitions with permission levels."""
80
+ return [
81
+ {
82
+ "role_id": "senior_dev",
83
+ "name": "Senior Developer",
84
+ "permissions": ["read", "write", "review", "approve", "assign"],
85
+ "description": "Can fix bugs, review code, approve changes",
86
+ },
87
+ {
88
+ "role_id": "junior_dev",
89
+ "name": "Junior Developer",
90
+ "permissions": ["read", "write", "request_review"],
91
+ "description": "Can fix assigned bugs, needs review for approval",
92
+ },
93
+ {
94
+ "role_id": "qa",
95
+ "name": "QA Engineer",
96
+ "permissions": ["read", "report", "verify"],
97
+ "description": "Can report bugs, verify fixes",
98
+ },
99
+ {
100
+ "role_id": "tech_lead",
101
+ "name": "Tech Lead",
102
+ "permissions": ["read", "write", "review", "approve", "assign", "oversight"],
103
+ "description": "Overall oversight, assigns work, final approval",
104
+ },
105
+ ]
106
+
107
+
108
+ def get_permissions() -> List[Dict[str, Any]]:
109
+ """Get permission definitions."""
110
+ return [
111
+ {
112
+ "permission_id": "read",
113
+ "name": "Read Code",
114
+ "description": "Can view task code and details",
115
+ },
116
+ {
117
+ "permission_id": "write",
118
+ "name": "Write/Edit",
119
+ "description": "Can edit task files and make changes",
120
+ },
121
+ {
122
+ "permission_id": "review",
123
+ "name": "Review Code",
124
+ "description": "Can review and comment on changes",
125
+ },
126
+ {
127
+ "permission_id": "approve",
128
+ "name": "Approve",
129
+ "description": "Can approve changes for completion",
130
+ },
131
+ {
132
+ "permission_id": "assign",
133
+ "name": "Assign Work",
134
+ "description": "Can assign tasks to other users",
135
+ },
136
+ {
137
+ "permission_id": "report",
138
+ "name": "Report Issues",
139
+ "description": "Can report new bugs/issues",
140
+ },
141
+ {
142
+ "permission_id": "verify",
143
+ "name": "Verify Fixes",
144
+ "description": "Can verify that fixes work correctly",
145
+ },
146
+ {
147
+ "permission_id": "oversight",
148
+ "name": "Oversight",
149
+ "description": "Overall visibility and coordination",
150
+ },
151
+ ]
152
+
153
+
154
+ def get_tasks_metadata() -> List[Dict[str, Any]]:
155
+ """Get multi-user task scenarios."""
156
+ base_date = datetime.now()
157
+
158
+ return [
159
+ {
160
+ "task_id": "task7",
161
+ "title": "Code Review Workflow",
162
+ "description": "Junior developer submits a fix that needs code review and approval from senior developer",
163
+ "difficulty": "medium",
164
+ "scenario_type": "code_review",
165
+ "participants": [
166
+ {
167
+ "user_id": "bob_junior",
168
+ "role": "assignee",
169
+ "responsibility": "Fix the bug and submit for review",
170
+ "status": "in_progress",
171
+ },
172
+ {
173
+ "user_id": "alice_senior",
174
+ "role": "reviewer",
175
+ "responsibility": "Review code, provide feedback, approve if acceptable",
176
+ "status": "pending",
177
+ },
178
+ {
179
+ "user_id": "dave_lead",
180
+ "role": "observer",
181
+ "responsibility": "Oversee process, escalate if needed",
182
+ "status": "pending",
183
+ },
184
+ ],
185
+ "workflow_steps": [
186
+ "Step 1: Bob reads the failing code and tests",
187
+ "Step 2: Bob fixes the bug in the code",
188
+ "Step 3: Bob runs tests to verify the fix",
189
+ "Step 4: Alice reviews Bob's code changes",
190
+ "Step 5: Alice checks test coverage and design",
191
+ "Step 6: Alice approves and merges the fix",
192
+ ],
193
+ "expected_issues": [
194
+ "Code doesn't follow team style guidelines",
195
+ "Missing test coverage for edge case",
196
+ "Incomplete error handling",
197
+ ],
198
+ "tools_available": [
199
+ "read_file",
200
+ "edit_file",
201
+ "run_tests",
202
+ "search_code",
203
+ "get_file_structure",
204
+ "run_type_check",
205
+ "get_test_coverage",
206
+ ],
207
+ "created_at": base_date.isoformat(),
208
+ "due_date": (base_date + timedelta(days=2)).isoformat(),
209
+ },
210
+ {
211
+ "task_id": "task8",
212
+ "title": "Cross-team Bug Investigation",
213
+ "description": "QA reported a complex bug. Dev team needs to investigate, communicate findings, and fix collaboratively",
214
+ "difficulty": "hard",
215
+ "scenario_type": "cross_team_collaboration",
216
+ "participants": [
217
+ {
218
+ "user_id": "carol_qa",
219
+ "role": "bug_reporter",
220
+ "responsibility": "Provide bug details, reproduction steps, verify fix",
221
+ "status": "completed",
222
+ },
223
+ {
224
+ "user_id": "bob_junior",
225
+ "role": "investigator",
226
+ "responsibility": "Investigate root cause, document findings",
227
+ "status": "in_progress",
228
+ },
229
+ {
230
+ "user_id": "alice_senior",
231
+ "role": "problem_solver",
232
+ "responsibility": "Propose solution, implement fix, ensure quality",
233
+ "status": "pending",
234
+ },
235
+ {
236
+ "user_id": "dave_lead",
237
+ "role": "coordinator",
238
+ "responsibility": "Coordinate team, resolve blockers, approve solution",
239
+ "status": "pending",
240
+ },
241
+ ],
242
+ "workflow_steps": [
243
+ "Step 1: Carol (QA) reports bug: 'User profile update fails with invalid email'",
244
+ "Step 2: Bob investigates the code path for email validation",
245
+ "Step 3: Bob identifies the issue is in validation logic and documents findings",
246
+ "Step 4: Alice reviews findings and designs a fix",
247
+ "Step 5: Alice implements the fix and adds test coverage",
248
+ "Step 6: Bob and Alice code review together",
249
+ "Step 7: Carol verifies the fix in the updated code",
250
+ "Step 8: Dave approves and coordinates merge",
251
+ ],
252
+ "bug_description": "User profile update fails with 'invalid email' error even for valid email addresses like 'user+tag@domain.com'",
253
+ "root_cause": "Email validation regex too strict, doesn't handle '+' character in local part",
254
+ "expected_issues": [
255
+ "Validation logic is in the wrong module",
256
+ "Multiple places need the same fix",
257
+ "Missing test cases for email formats",
258
+ ],
259
+ "tools_available": [
260
+ "read_file",
261
+ "edit_file",
262
+ "run_tests",
263
+ "search_code",
264
+ "get_file_structure",
265
+ "get_dependencies",
266
+ "run_type_check",
267
+ "get_test_coverage",
268
+ ],
269
+ "created_at": base_date.isoformat(),
270
+ "due_date": (base_date + timedelta(days=3)).isoformat(),
271
+ },
272
+ {
273
+ "task_id": "task9",
274
+ "title": "Collaborative Architecture Refactoring",
275
+ "description": "Large refactoring involving multiple modules. Multiple devs contribute different parts, need to stay coordinated",
276
+ "difficulty": "hard",
277
+ "scenario_type": "team_refactoring",
278
+ "participants": [
279
+ {
280
+ "user_id": "alice_senior",
281
+ "role": "architect",
282
+ "responsibility": "Design refactoring strategy, review all changes, ensure consistency",
283
+ "status": "in_progress",
284
+ },
285
+ {
286
+ "user_id": "bob_junior",
287
+ "role": "contributor_1",
288
+ "responsibility": "Refactor module_a following architecture guidelines",
289
+ "status": "in_progress",
290
+ },
291
+ {
292
+ "user_id": "carol_qa",
293
+ "role": "contributor_2",
294
+ "responsibility": "Refactor module_b, ensure test compatibility",
295
+ "status": "pending",
296
+ },
297
+ {
298
+ "user_id": "dave_lead",
299
+ "role": "integration_lead",
300
+ "responsibility": "Coordinate across modules, resolve conflicts, ensure integration",
301
+ "status": "pending",
302
+ },
303
+ ],
304
+ "workflow_steps": [
305
+ "Step 1: Alice designs refactoring architecture and creates shared interface",
306
+ "Step 2: Bob starts refactoring module_a to use new interface",
307
+ "Step 3: Carol starts refactoring module_b in parallel",
308
+ "Step 4: Both check for integration issues with shared interface",
309
+ "Step 5: Alice reviews both changes for consistency",
310
+ "Step 6: Dave coordinates final integration and merge",
311
+ "Step 7: Full test suite runs on integrated changes",
312
+ ],
313
+ "refactoring_goals": [
314
+ "Break circular dependencies between modules",
315
+ "Extract common interface",
316
+ "Improve testability through dependency injection",
317
+ "Consolidate validation logic",
318
+ ],
319
+ "modules_involved": ["module_a.py", "module_b.py", "module_c.py", "integration.py"],
320
+ "expected_issues": [
321
+ "Integration points between modules are unclear",
322
+ "Parallel changes create merge conflicts",
323
+ "Some code depends on old interface",
324
+ ],
325
+ "tools_available": [
326
+ "list_directory",
327
+ "read_file",
328
+ "edit_file",
329
+ "run_tests",
330
+ "search_code",
331
+ "get_file_structure",
332
+ "get_dependencies",
333
+ "run_type_check",
334
+ "get_test_coverage",
335
+ ],
336
+ "created_at": base_date.isoformat(),
337
+ "due_date": (base_date + timedelta(days=5)).isoformat(),
338
+ },
339
+ ]
340
+
341
+
342
+ def get_multi_user_sql() -> str:
343
+ """Generate SQL for multi-user sample data."""
344
+ data = get_multi_user_sample_data()
345
+ sql_statements = []
346
+
347
+ # Header
348
+ sql_statements.append("-- Multi-User Debug Environment Sample Data")
349
+ sql_statements.append(f"-- Generated on: {datetime.now().isoformat()}")
350
+ sql_statements.append("-- Contains collaborative debugging scenarios with multiple users and roles")
351
+ sql_statements.append("")
352
+
353
+ # Users
354
+ sql_statements.append("-- Users")
355
+ sql_statements.append(
356
+ "INSERT INTO users (user_id, name, role, email, experience_level, timezone, created_at) VALUES"
357
+ )
358
+ user_values = []
359
+ for user in data["users"]:
360
+ user_values.append(
361
+ f"('{user['user_id']}', '{user['name']}', '{user['role']}', "
362
+ f"'{user['email']}', '{user['experience_level']}', '{user['timezone']}', "
363
+ f"'{user['created_at']}')"
364
+ )
365
+ sql_statements.append(",\n".join(user_values) + ";")
366
+ sql_statements.append("")
367
+
368
+ # Roles
369
+ sql_statements.append("-- Roles")
370
+ sql_statements.append(
371
+ "INSERT INTO roles (role_id, name, description) VALUES"
372
+ )
373
+ role_values = []
374
+ for role in data["roles"]:
375
+ permissions_str = ",".join(role["permissions"])
376
+ role_values.append(
377
+ f"('{role['role_id']}', '{role['name']}', '{role['description']}')"
378
+ )
379
+ sql_statements.append(",\n".join(role_values) + ";")
380
+ sql_statements.append("")
381
+
382
+ # Permissions
383
+ sql_statements.append("-- Permissions")
384
+ sql_statements.append(
385
+ "INSERT INTO permissions (permission_id, name, description) VALUES"
386
+ )
387
+ perm_values = []
388
+ for perm in data["permissions"]:
389
+ perm_values.append(
390
+ f"('{perm['permission_id']}', '{perm['name']}', '{perm['description']}')"
391
+ )
392
+ sql_statements.append(",\n".join(perm_values) + ";")
393
+ sql_statements.append("")
394
+
395
+ # Tasks Metadata
396
+ sql_statements.append("-- Task Scenarios")
397
+ sql_statements.append(
398
+ "INSERT INTO task_scenarios (task_id, title, description, difficulty, scenario_type, created_at, due_date) VALUES"
399
+ )
400
+ task_values = []
401
+ for task in data["tasks_metadata"]:
402
+ description = task["description"].replace("'", "''")
403
+ task_values.append(
404
+ f"('{task['task_id']}', '{task['title']}', '{description}', "
405
+ f"'{task['difficulty']}', '{task['scenario_type']}', "
406
+ f"'{task['created_at']}', '{task['due_date']}')"
407
+ )
408
+ sql_statements.append(",\n".join(task_values) + ";")
409
+ sql_statements.append("")
410
+
411
+ return "\n".join(sql_statements)
debug_env/models.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from openenv.core.env_server.types import Action, Observation
2
+ from pydantic import Field
3
+
4
+ class DebugAction(Action):
5
+ tool: str = Field(..., description="Tool to use: run_tests, read_file, edit_file")
6
+ args: dict = Field(default_factory=dict, description="Arguments for the tool")
7
+
8
+ class DebugObservation(Observation):
9
+ pass_rate: float = Field(default=0.0, description="Test pass rate (0 to 1)")
10
+ logs: str = Field(default="", description="Test output logs")
debug_env/openenv.yaml ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: debug_env
3
+ type: space
4
+ runtime: fastapi
5
+ app: server.app:app
6
+ port: 8000
7
+ description: >
8
+ A real-world debugging environment where LLM agents fix broken Python code.
9
+ Tasks range from simple syntax errors to complex logic bugs. Agents use
10
+ read_file, edit_file, and run_tests tools to identify and fix issues.
11
+ Rewards are based on test pass rate (0.0-1.0).
12
+
13
+ author: Meta Platforms, Inc.
14
+ version: 0.1.0
15
+
16
+ tasks:
17
+ - id: task1
18
+ title: "Fix Simple Syntax Error"
19
+ description: >
20
+ A Python module with a syntax error in the function definition.
21
+ Agent must identify the missing colon and fix the function signature.
22
+ difficulty: easy
23
+ estimated_steps: 3
24
+ - id: task2
25
+ title: "Fix Logic Bug in Conditional"
26
+ description: >
27
+ A function with incorrect conditional logic that fails test assertions.
28
+ Agent must read tests, understand the expected behavior, and fix the logic.
29
+ difficulty: medium
30
+ estimated_steps: 5
31
+ - id: task3
32
+ title: "Fix Import and Type Issues"
33
+ description: >
34
+ Multiple functions with missing imports, type errors, and undefined variables.
35
+ Agent must diagnose and fix all issues to pass all tests.
36
+ difficulty: hard
37
+ estimated_steps: 8
38
+
39
+ action_schema:
40
+ type: object
41
+ properties:
42
+ tool:
43
+ type: string
44
+ enum: ["run_tests", "read_file", "edit_file"]
45
+ description: Name of the tool to execute
46
+ args:
47
+ type: object
48
+ description: Tool-specific arguments
49
+ required: ["tool"]
50
+
51
+ observation_schema:
52
+ type: object
53
+ properties:
54
+ pass_rate:
55
+ type: number
56
+ minimum: 0.0
57
+ maximum: 1.0
58
+ description: Fraction of tests passing (0.0-1.0)
59
+ logs:
60
+ type: string
61
+ description: Test output, file content, or execution logs
62
+ reward:
63
+ type: number
64
+ minimum: 0.0
65
+ maximum: 1.0
66
+ description: Reward signal based on pass_rate
67
+ done:
68
+ type: boolean
69
+ description: Whether all tests pass (episode complete)
70
+ required: ["pass_rate", "logs"]
71
+
72
+ reward_schema:
73
+ type: object
74
+ properties:
75
+ reward:
76
+ type: number
77
+ minimum: 0.0
78
+ maximum: 1.0
79
+ description: Episode reward based on final pass_rate
80
+ done:
81
+ type: boolean
82
+ description: Whether episode is complete
83
+ required: ["reward", "done"]
84
+
85
+ performance_metrics:
86
+ - pass_rate: Fraction of tests passing
87
+ - success_rate: Percentage of runs with full pass (across multiple attempts)
88
+ - pass@k: Probability that at least k runs succeed
89
+ - avg_steps: Average number of tool calls per successful run
90
+ - avg_time_ms: Average execution time per run
91
+
92
+ deployment:
93
+ huggingface_space: true
94
+ dockerfile: ./debug_env/server/Dockerfile
95
+ docker_compose: ./docker-compose.yml
96
+ health_check: /health
97
+ max_runtime_minutes: 20
98
+ min_vcpu: 2
99
+ min_memory_gb: 8
debug_env/pyproject.toml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ [build-system]
8
+ requires = ["setuptools>=45", "wheel"]
9
+ build-backend = "setuptools.build_meta"
10
+
11
+ [project]
12
+ name = "openenv-debug_env"
13
+ version = "0.1.0"
14
+ description = "Debug Env environment for OpenEnv"
15
+ requires-python = ">=3.10"
16
+ dependencies = [
17
+ # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
18
+ # install from github
19
+ # "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git",
20
+ "openenv-core[core]>=0.2.2",
21
+ # Inference / benchmark client dependencies
22
+ "httpx>=0.27.0",
23
+ "langchain-core>=0.3.0",
24
+ "langchain-anthropic>=0.3.0",
25
+ "langchain-openai>=0.3.0",
26
+ "langchain-google-genai>=2.0.0",
27
+ # Database ORM for task persistence and episode tracking
28
+ "sqlalchemy>=2.0.0",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ dev = [
33
+ "pytest>=8.0.0",
34
+ "pytest-cov>=4.0.0",
35
+ ]
36
+
37
+ [project.scripts]
38
+ # Server entry point - enables running via: uv run --project . server
39
+ # or: python -m debug_env.server.app
40
+ server = "debug_env.server.app:main"
41
+
42
+ [tool.setuptools]
43
+ include-package-data = true
44
+ packages = [
45
+ "debug_env",
46
+ "debug_env.data",
47
+ "debug_env.server",
48
+ "debug_env.server.core",
49
+ "debug_env.server.database",
50
+ "debug_env.server.database.managers",
51
+ "debug_env.server.database.models",
52
+ "debug_env.server.handlers",
53
+ "debug_env.server.mcp",
54
+ "debug_env.server.mcp.tools",
55
+ "debug_env.server.schemas",
56
+ "debug_env.server.tools",
57
+ "debug_env.server.tools.run_tests",
58
+ "debug_env.server.tools.read_file",
59
+ "debug_env.server.tools.edit_file",
60
+ "debug_env.server.tasks",
61
+ "debug_env.server.utils",
62
+ "debug_env.tasks",
63
+ "debug_env.tasks.task4",
64
+ "debug_env.tasks.task5",
65
+ "debug_env.tasks.task6",
66
+ "debug_env.tasks.task7",
67
+ "debug_env.tasks.task8",
68
+ "debug_env.tasks.task9",
69
+ ]
70
+ package-dir = { "debug_env" = ".", "debug_env.server" = "server" }
debug_env/server/Dockerfile ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # Multi-stage build using openenv-base
8
+ # This Dockerfile is flexible and works for both:
9
+ # - In-repo environments (with local OpenEnv sources)
10
+ # - Standalone environments (with openenv from PyPI/Git)
11
+ # The build script (openenv build) handles context detection and sets appropriate build args.
12
+
13
+ ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
14
+ FROM ${BASE_IMAGE} AS builder
15
+
16
+ WORKDIR /app
17
+
18
+ # Ensure git is available (required for installing dependencies from VCS)
19
+ RUN apt-get update && \
20
+ apt-get install -y --no-install-recommends git && \
21
+ rm -rf /var/lib/apt/lists/*
22
+
23
+ # Build argument to control whether we're building standalone or in-repo
24
+ ARG BUILD_MODE=in-repo
25
+ ARG ENV_NAME=debug_env
26
+
27
+ # Copy environment code (always at root of build context)
28
+ COPY . /app/env
29
+
30
+ # For in-repo builds, openenv is already vendored in the build context
31
+ # For standalone builds, openenv will be installed via pyproject.toml
32
+ WORKDIR /app/env
33
+
34
+ # Ensure uv is available (for local builds where base image lacks it)
35
+ RUN if ! command -v uv >/dev/null 2>&1; then \
36
+ curl -LsSf https://astral.sh/uv/install.sh | sh && \
37
+ mv /root/.local/bin/uv /usr/local/bin/uv && \
38
+ mv /root/.local/bin/uvx /usr/local/bin/uvx; \
39
+ fi
40
+
41
+ # Install dependencies using uv sync
42
+ # If uv.lock exists, use it; otherwise resolve on the fly
43
+ RUN --mount=type=cache,target=/root/.cache/uv \
44
+ if [ -f uv.lock ]; then \
45
+ uv sync --frozen --no-install-project --no-editable; \
46
+ else \
47
+ uv sync --no-install-project --no-editable; \
48
+ fi
49
+
50
+ RUN --mount=type=cache,target=/root/.cache/uv \
51
+ if [ -f uv.lock ]; then \
52
+ uv sync --frozen --no-editable; \
53
+ else \
54
+ uv sync --no-editable; \
55
+ fi
56
+
57
+ # Final runtime stage
58
+ FROM ${BASE_IMAGE}
59
+
60
+ WORKDIR /app
61
+
62
+ # Copy the virtual environment from builder
63
+ COPY --from=builder /app/env/.venv /app/.venv
64
+
65
+ # Copy the environment code
66
+ COPY --from=builder /app/env /app/env
67
+
68
+ # Set PATH to use the virtual environment
69
+ ENV PATH="/app/.venv/bin:$PATH"
70
+
71
+ # Set PYTHONPATH so imports work correctly
72
+ ENV PYTHONPATH="/app/env:$PYTHONPATH"
73
+
74
+ # Health check
75
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
76
+ CMD curl -f http://localhost:8000/health || exit 1
77
+
78
+ # Run the FastAPI server
79
+ # The module path is constructed to work with the /app/env structure
80
+ CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
debug_env/server/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Debug Env environment server components."""
8
+
9
+ from .debug_env_environment import DebugEnvironment
10
+
11
+ __all__ = ["DebugEnvironment"]
debug_env/server/app.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ FastAPI application for the Debug Env Environment.
9
+
10
+ This module creates an HTTP server that exposes the DebugEnvironment
11
+ over HTTP and WebSocket endpoints, compatible with EnvClient.
12
+
13
+ Endpoints:
14
+ - POST /reset: Reset the environment
15
+ - POST /step: Execute an action
16
+ - GET /state: Get current environment state
17
+ - GET /schema: Get action/observation schemas
18
+ - WS /ws: WebSocket endpoint for persistent sessions
19
+
20
+ Usage:
21
+ # Development (with auto-reload):
22
+ uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
23
+
24
+ # Production:
25
+ uvicorn server.app:app --host 0.0.0.0 --port 8000 --workers 4
26
+
27
+ # Or run directly:
28
+ python -m server.app
29
+ """
30
+
31
+ try:
32
+ from openenv.core.env_server.http_server import create_app
33
+ except Exception as e: # pragma: no cover
34
+ raise ImportError(
35
+ "openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
36
+ ) from e
37
+
38
+ try:
39
+ from ..models import DebugAction, DebugObservation
40
+ from .core.apis import router as core_router
41
+ from .debug_env_environment import DebugEnvironment
42
+ from .mcp.router import router as mcp_router
43
+ from .tasks.router import router as tasks_router
44
+ from .database.db import init_db
45
+ except ModuleNotFoundError:
46
+ from models import DebugAction, DebugObservation
47
+ from server.core.apis import router as core_router
48
+ from server.debug_env_environment import DebugEnvironment
49
+ from server.mcp.router import router as mcp_router
50
+ from server.tasks.router import router as tasks_router
51
+ from server.database.db import init_db
52
+
53
+
54
+ # Create the app with web interface and README integration
55
+ app = create_app(
56
+ DebugEnvironment,
57
+ DebugAction,
58
+ DebugObservation,
59
+ env_name="debug_env",
60
+ max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions
61
+ )
62
+
63
+ # Register additional routers
64
+ app.include_router(core_router)
65
+ app.include_router(tasks_router)
66
+ app.include_router(mcp_router)
67
+
68
+
69
+ # Initialize database on startup
70
+ @app.on_event("startup")
71
+ async def startup_event():
72
+ """Initialize database and seed task registry on startup."""
73
+ init_db()
74
+
75
+
76
+ def main(host: str = "0.0.0.0", port: int = 8000):
77
+ """
78
+ Entry point for direct execution via uv run or python -m.
79
+
80
+ This function enables running the server without Docker:
81
+ uv run --project . server
82
+ uv run --project . server --port 8001
83
+ python -m debug_env.server.app
84
+
85
+ Args:
86
+ host: Host address to bind to (default: "0.0.0.0")
87
+ port: Port number to listen on (default: 8000)
88
+
89
+ For production deployments, consider using uvicorn directly with
90
+ multiple workers:
91
+ uvicorn debug_env.server.app:app --workers 4
92
+ """
93
+ import uvicorn
94
+
95
+ uvicorn.run(app, host=host, port=port)
96
+
97
+
98
+ if __name__ == "__main__":
99
+ import argparse
100
+
101
+ parser = argparse.ArgumentParser()
102
+ parser.add_argument("--port", type=int, default=8000)
103
+ args = parser.parse_args()
104
+ main(port=args.port)
debug_env/server/core/__init__.py ADDED
File without changes
debug_env/server/core/apis.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Core API endpoints for debug-env.
3
+ Handles health checks and service status information.
4
+ """
5
+
6
+ import logging
7
+
8
+ from fastapi import APIRouter
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ router = APIRouter(tags=["core"])
13
+
14
+
15
+ @router.get("/health")
16
+ async def health_check():
17
+ """
18
+ Health check endpoint for service monitoring.
19
+
20
+ Returns basic service status and availability information.
21
+ """
22
+ return {"status": "healthy", "service": "debug-env"}
debug_env/server/database/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Database module for debug_env"""
debug_env/server/database/db.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database configuration and session management for debug_env.
3
+
4
+ Provides SQLite database engine, session factory, and FastAPI dependency injection.
5
+ """
6
+
7
+ import logging
8
+ from pathlib import Path
9
+
10
+ from sqlalchemy import create_engine
11
+ from sqlalchemy.orm import declarative_base, sessionmaker, Session
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # Database path: debug_env.db in the server directory
16
+ DB_PATH = Path(__file__).parent.parent / "debug_env.db"
17
+ DATABASE_URL = f"sqlite:///{DB_PATH}"
18
+
19
+ # SQLAlchemy engine
20
+ engine = create_engine(
21
+ DATABASE_URL,
22
+ echo=False,
23
+ connect_args={"check_same_thread": False}, # SQLite specific
24
+ )
25
+
26
+ # Session factory
27
+ SessionLocal = sessionmaker(
28
+ autocommit=False,
29
+ autoflush=False,
30
+ bind=engine,
31
+ )
32
+
33
+ # Declarative base for ORM models
34
+ Base = declarative_base()
35
+
36
+
37
+ def get_db() -> Session:
38
+ """
39
+ FastAPI dependency: yields a database session.
40
+
41
+ Usage:
42
+ async def my_endpoint(db: Session = Depends(get_db)):
43
+ # Use db here
44
+ """
45
+ db = SessionLocal()
46
+ try:
47
+ yield db
48
+ finally:
49
+ db.close()
50
+
51
+
52
+ def init_db() -> None:
53
+ """
54
+ Initialize the database: create all tables and seed task registry.
55
+
56
+ Called on application startup via @app.on_event("startup").
57
+ """
58
+ # Import models to register them with Base
59
+ from debug_env.server.database.models.task import TaskRecord, EpisodeRecord, WatchChannel # noqa: F401
60
+
61
+ # Create all tables
62
+ Base.metadata.create_all(bind=engine)
63
+ logger.info(f"Database initialized at {DB_PATH}")
64
+
65
+ # Seed TASK_REGISTRY into task_records table if not already present
66
+ _seed_task_registry()
67
+
68
+
69
+ def _seed_task_registry() -> None:
70
+ """Seed the task_records table with TASK_REGISTRY on startup."""
71
+ from debug_env.server.database.models.task import TaskRecord
72
+ from debug_env.server.tasks.data import TASK_REGISTRY
73
+ from datetime import datetime
74
+ from uuid import uuid4
75
+
76
+ db = SessionLocal()
77
+ try:
78
+ # Check if tasks already exist
79
+ existing_count = db.query(TaskRecord).count()
80
+ if existing_count > 0:
81
+ logger.debug(f"Task registry already seeded ({existing_count} tasks)")
82
+ return
83
+
84
+ # Seed each task from TASK_REGISTRY
85
+ now = datetime.utcnow()
86
+ for task_id, task_data in TASK_REGISTRY.items():
87
+ task_record = TaskRecord(
88
+ id=task_id,
89
+ title=task_data.get("title", ""),
90
+ description=task_data.get("description", ""),
91
+ difficulty=task_data.get("difficulty", ""),
92
+ bug_type=task_data.get("bug_type", ""),
93
+ files=task_data.get("files", []),
94
+ tools=task_data.get("tools"),
95
+ scenario_type=task_data.get("scenario_type"),
96
+ participants=task_data.get("participants"),
97
+ etag=f'"{uuid4()}"',
98
+ created_at=now,
99
+ updated_at=now,
100
+ )
101
+ db.add(task_record)
102
+
103
+ db.commit()
104
+ logger.info(f"Seeded {len(TASK_REGISTRY)} tasks into database")
105
+ except Exception as e:
106
+ db.rollback()
107
+ logger.error(f"Error seeding task registry: {e}")
108
+ raise
109
+ finally:
110
+ db.close()
debug_env/server/database/managers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Database managers for debug_env"""
debug_env/server/database/managers/task_manager.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Task Manager — Manages task metadata, episodes, and watch channels.
3
+
4
+ Follows the ACLManager pattern: class-based CRUD with user scoping, pagination,
5
+ sync tokens, and ETags for cache validation.
6
+ """
7
+
8
+ import base64
9
+ import json
10
+ import logging
11
+ from datetime import datetime, timedelta
12
+ from typing import Optional, Dict, Any, List
13
+ from uuid import uuid4
14
+
15
+ from sqlalchemy import and_, desc, or_
16
+ from sqlalchemy.orm import Session
17
+
18
+ from debug_env.server.database.models.task import TaskRecord, EpisodeRecord, WatchChannel
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class TaskManager:
24
+ """
25
+ Manages task operations with user-scoped access control.
26
+
27
+ Args:
28
+ db: SQLAlchemy Session
29
+ user_id: User identifier for scoping operations
30
+ """
31
+
32
+ def __init__(self, db: Session, user_id: str):
33
+ self.db = db
34
+ self.user_id = user_id
35
+
36
+ def list_tasks(
37
+ self,
38
+ max_results: int = 50,
39
+ page_token: Optional[str] = None,
40
+ sync_token: Optional[str] = None,
41
+ ) -> "TaskListResponse":
42
+ """
43
+ List tasks with pagination and sync token support.
44
+
45
+ Args:
46
+ max_results: Maximum number of tasks per page (1-250, default 50)
47
+ page_token: Pagination token from previous response
48
+ sync_token: Sync token for incremental updates
49
+
50
+ Returns:
51
+ TaskListResponse with items, nextPageToken, nextSyncToken
52
+ """
53
+ try:
54
+ # Handle sync token for incremental synchronization
55
+ if sync_token:
56
+ return self._handle_sync_request(sync_token, max_results)
57
+
58
+ # Base query: all tasks (not user-scoped)
59
+ query = self.db.query(TaskRecord).order_by(TaskRecord.id)
60
+
61
+ # Handle pagination with base64 offset token
62
+ offset = 0
63
+ if page_token:
64
+ try:
65
+ offset = int(base64.b64decode(page_token).decode("utf-8"))
66
+ except (ValueError, TypeError):
67
+ raise ValueError("Invalid pageToken")
68
+
69
+ # Get one extra to determine if there's a next page
70
+ items = query.offset(offset).limit(max_results + 1).all()
71
+
72
+ has_next_page = len(items) > max_results
73
+ if has_next_page:
74
+ items = items[:max_results]
75
+ next_page_token = base64.b64encode(
76
+ str(offset + max_results).encode("utf-8")
77
+ ).decode("utf-8")
78
+ else:
79
+ next_page_token = None
80
+
81
+ # Generate next sync token based on latest update
82
+ latest_updated = (
83
+ self.db.query(TaskRecord.updated_at)
84
+ .order_by(desc(TaskRecord.updated_at))
85
+ .first()
86
+ )
87
+
88
+ next_sync_token = None
89
+ if latest_updated and latest_updated[0]:
90
+ sync_data = {
91
+ "timestamp": latest_updated[0].isoformat(),
92
+ "user_id": self.user_id,
93
+ }
94
+ next_sync_token = base64.b64encode(
95
+ json.dumps(sync_data).encode("utf-8")
96
+ ).decode("utf-8")
97
+
98
+ # Generate collection etag
99
+ etag = f'"{uuid4()}"'
100
+
101
+ return TaskListResponse(
102
+ etag=etag,
103
+ items=items,
104
+ nextPageToken=next_page_token,
105
+ nextSyncToken=next_sync_token,
106
+ )
107
+
108
+ except Exception as e:
109
+ logger.error(f"Error listing tasks: {e}")
110
+ raise
111
+
112
+ def _handle_sync_request(
113
+ self, sync_token: str, max_results: int
114
+ ) -> "TaskListResponse":
115
+ """
116
+ Handle incremental synchronization request.
117
+
118
+ Args:
119
+ sync_token: Sync token from previous response
120
+ max_results: Maximum items to return
121
+
122
+ Returns:
123
+ TaskListResponse with changes since sync token
124
+ """
125
+ try:
126
+ # Decode sync token
127
+ sync_data = json.loads(base64.b64decode(sync_token).decode("utf-8"))
128
+ last_sync_time = datetime.fromisoformat(sync_data["timestamp"])
129
+
130
+ # Check if sync token is too old (7-day expiration)
131
+ if (datetime.utcnow() - last_sync_time).days > 7:
132
+ raise ValueError("Sync token expired")
133
+
134
+ # Query for changes since last sync
135
+ query = (
136
+ self.db.query(TaskRecord)
137
+ .filter(TaskRecord.updated_at > last_sync_time)
138
+ .order_by(TaskRecord.updated_at, TaskRecord.id)
139
+ )
140
+
141
+ items = query.limit(max_results + 1).all()
142
+
143
+ has_more = len(items) > max_results
144
+ if has_more:
145
+ items = items[:max_results]
146
+
147
+ # Generate new sync token
148
+ next_sync_token = None
149
+ if items:
150
+ latest_time = max(item.updated_at for item in items)
151
+ sync_data = {
152
+ "timestamp": latest_time.isoformat(),
153
+ "user_id": self.user_id,
154
+ }
155
+ next_sync_token = base64.b64encode(
156
+ json.dumps(sync_data).encode("utf-8")
157
+ ).decode("utf-8")
158
+ else:
159
+ # No changes, return same sync token
160
+ next_sync_token = sync_token
161
+
162
+ # Generate etag
163
+ etag = f'"{uuid4()}"'
164
+
165
+ return TaskListResponse(
166
+ etag=etag,
167
+ items=items,
168
+ nextPageToken=None,
169
+ nextSyncToken=next_sync_token,
170
+ )
171
+
172
+ except json.JSONDecodeError:
173
+ raise ValueError("Invalid sync token format")
174
+ except Exception as e:
175
+ logger.error(f"Error handling sync request: {e}")
176
+ raise
177
+
178
+ def get_task(self, task_id: str) -> Optional[TaskRecord]:
179
+ """
180
+ Retrieve a specific task by ID.
181
+
182
+ Args:
183
+ task_id: Task identifier (e.g., "task1")
184
+
185
+ Returns:
186
+ TaskRecord or None if not found
187
+ """
188
+ return self.db.query(TaskRecord).filter(TaskRecord.id == task_id).first()
189
+
190
+ def create_episode(self, task_id: str, workdir: str) -> EpisodeRecord:
191
+ """
192
+ Create a new episode (task run) for a user.
193
+
194
+ Args:
195
+ task_id: Task identifier
196
+ workdir: Path to working directory with task files
197
+
198
+ Returns:
199
+ Created EpisodeRecord
200
+ """
201
+ try:
202
+ # Verify task exists
203
+ task = self.get_task(task_id)
204
+ if not task:
205
+ raise ValueError(f"Task '{task_id}' not found")
206
+
207
+ # Create episode
208
+ episode_id = str(uuid4())
209
+ episode = EpisodeRecord(
210
+ id=episode_id,
211
+ task_id=task_id,
212
+ user_id=self.user_id,
213
+ workdir=workdir,
214
+ status="active",
215
+ etag=f'"{uuid4()}"',
216
+ )
217
+ self.db.add(episode)
218
+ self.db.commit()
219
+ self.db.refresh(episode)
220
+
221
+ logger.info(
222
+ f"Created episode {episode_id} for task {task_id}, user {self.user_id}"
223
+ )
224
+ return episode
225
+
226
+ except Exception as e:
227
+ self.db.rollback()
228
+ logger.error(f"Error creating episode: {e}")
229
+ raise
230
+
231
+ def get_episode(self, task_id: str, episode_id: str) -> Optional[EpisodeRecord]:
232
+ """
233
+ Retrieve a specific episode.
234
+
235
+ Args:
236
+ task_id: Task identifier
237
+ episode_id: Episode identifier
238
+
239
+ Returns:
240
+ EpisodeRecord or None if not found
241
+ """
242
+ return (
243
+ self.db.query(EpisodeRecord)
244
+ .filter(
245
+ and_(
246
+ EpisodeRecord.id == episode_id,
247
+ EpisodeRecord.task_id == task_id,
248
+ EpisodeRecord.user_id == self.user_id,
249
+ )
250
+ )
251
+ .first()
252
+ )
253
+
254
+ def update_episode(
255
+ self, task_id: str, episode_id: str, status: str, pass_rate: Optional[float] = None
256
+ ) -> Optional[EpisodeRecord]:
257
+ """
258
+ Update an episode's status and pass rate.
259
+
260
+ Args:
261
+ task_id: Task identifier
262
+ episode_id: Episode identifier
263
+ status: New status ("active", "passed", "failed", "abandoned")
264
+ pass_rate: Pass rate (0.0-1.0) if completed
265
+
266
+ Returns:
267
+ Updated EpisodeRecord or None if not found
268
+ """
269
+ try:
270
+ episode = self.get_episode(task_id, episode_id)
271
+ if not episode:
272
+ return None
273
+
274
+ episode.status = status
275
+ if pass_rate is not None:
276
+ episode.pass_rate = pass_rate
277
+ episode.etag = f'"{uuid4()}"'
278
+ episode.updated_at = datetime.utcnow()
279
+
280
+ self.db.commit()
281
+ self.db.refresh(episode)
282
+
283
+ logger.info(
284
+ f"Updated episode {episode_id} status to {status} (pass_rate={pass_rate})"
285
+ )
286
+ return episode
287
+
288
+ except Exception as e:
289
+ self.db.rollback()
290
+ logger.error(f"Error updating episode: {e}")
291
+ raise
292
+
293
+ def list_episodes(
294
+ self, task_id: str, max_results: int = 50, page_token: Optional[str] = None
295
+ ) -> "EpisodeListResponse":
296
+ """
297
+ List episodes for a task with pagination.
298
+
299
+ Args:
300
+ task_id: Task identifier
301
+ max_results: Maximum items per page
302
+ page_token: Pagination token
303
+
304
+ Returns:
305
+ EpisodeListResponse with items and nextPageToken
306
+ """
307
+ try:
308
+ # Base query: user-scoped
309
+ query = (
310
+ self.db.query(EpisodeRecord)
311
+ .filter(
312
+ and_(EpisodeRecord.task_id == task_id, EpisodeRecord.user_id == self.user_id)
313
+ )
314
+ .order_by(EpisodeRecord.created_at, EpisodeRecord.id)
315
+ )
316
+
317
+ # Handle pagination
318
+ offset = 0
319
+ if page_token:
320
+ try:
321
+ offset = int(base64.b64decode(page_token).decode("utf-8"))
322
+ except (ValueError, TypeError):
323
+ raise ValueError("Invalid pageToken")
324
+
325
+ items = query.offset(offset).limit(max_results + 1).all()
326
+
327
+ has_next_page = len(items) > max_results
328
+ if has_next_page:
329
+ items = items[:max_results]
330
+ next_page_token = base64.b64encode(
331
+ str(offset + max_results).encode("utf-8")
332
+ ).decode("utf-8")
333
+ else:
334
+ next_page_token = None
335
+
336
+ return EpisodeListResponse(items=items, nextPageToken=next_page_token)
337
+
338
+ except Exception as e:
339
+ logger.error(f"Error listing episodes: {e}")
340
+ raise
341
+
342
+ def watch_task(self, task_id: str, watch_request: Dict[str, Any]) -> WatchChannel:
343
+ """
344
+ Set up a watch channel for task state changes.
345
+
346
+ Args:
347
+ task_id: Task identifier
348
+ watch_request: Dict with 'id', 'address', 'token' (optional)
349
+
350
+ Returns:
351
+ Created WatchChannel
352
+ """
353
+ try:
354
+ # Verify task exists
355
+ task = self.get_task(task_id)
356
+ if not task:
357
+ raise ValueError(f"Task '{task_id}' not found")
358
+
359
+ # Check for duplicate watch ID
360
+ existing = self.db.query(WatchChannel).filter(
361
+ WatchChannel.id == watch_request["id"]
362
+ ).first()
363
+ if existing:
364
+ raise ValueError(f"Watch channel with ID {watch_request['id']} already exists")
365
+
366
+ # Create watch channel (24 hour default expiration)
367
+ expires_at = datetime.utcnow() + timedelta(hours=24)
368
+ channel = WatchChannel(
369
+ id=watch_request["id"],
370
+ task_id=task_id,
371
+ user_id=self.user_id,
372
+ webhook_address=watch_request["address"],
373
+ webhook_token=watch_request.get("token"),
374
+ expires_at=expires_at,
375
+ is_active=True,
376
+ )
377
+ self.db.add(channel)
378
+ self.db.commit()
379
+ self.db.refresh(channel)
380
+
381
+ logger.info(f"Created watch channel {watch_request['id']} for task {task_id}")
382
+ return channel
383
+
384
+ except Exception as e:
385
+ self.db.rollback()
386
+ logger.error(f"Error creating watch channel: {e}")
387
+ raise
388
+
389
+ def cleanup_expired_channels(self) -> int:
390
+ """
391
+ Clean up expired watch channels for this user.
392
+
393
+ Returns:
394
+ Number of channels cleaned up
395
+ """
396
+ try:
397
+ current_time = datetime.utcnow()
398
+
399
+ expired_channels = (
400
+ self.db.query(WatchChannel)
401
+ .filter(
402
+ and_(
403
+ WatchChannel.user_id == self.user_id,
404
+ WatchChannel.expires_at < current_time,
405
+ WatchChannel.is_active == True,
406
+ )
407
+ )
408
+ .all()
409
+ )
410
+
411
+ cleanup_count = 0
412
+ for channel in expired_channels:
413
+ channel.is_active = False
414
+ cleanup_count += 1
415
+
416
+ if cleanup_count > 0:
417
+ self.db.commit()
418
+ logger.info(f"Cleaned up {cleanup_count} expired watch channels for user {self.user_id}")
419
+
420
+ return cleanup_count
421
+
422
+ except Exception as e:
423
+ self.db.rollback()
424
+ logger.error(f"Error cleaning up expired channels: {e}")
425
+ return 0
426
+
427
+
428
+ # Response models (simple classes matching the pattern)
429
+ class TaskListResponse:
430
+ def __init__(
431
+ self,
432
+ etag: str,
433
+ items: List[TaskRecord],
434
+ nextPageToken: Optional[str] = None,
435
+ nextSyncToken: Optional[str] = None,
436
+ ):
437
+ self.etag = etag
438
+ self.items = items
439
+ self.nextPageToken = nextPageToken
440
+ self.nextSyncToken = nextSyncToken
441
+
442
+
443
+ class EpisodeListResponse:
444
+ def __init__(self, items: List[EpisodeRecord], nextPageToken: Optional[str] = None):
445
+ self.items = items
446
+ self.nextPageToken = nextPageToken
447
+
448
+
449
+ def get_task_manager(db: Session, user_id: str) -> TaskManager:
450
+ """Factory function to create a TaskManager instance."""
451
+ return TaskManager(db, user_id)
debug_env/server/database/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Database models for debug_env"""
debug_env/server/database/models/task.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SQLAlchemy ORM models for tasks, episodes, and watch channels.
3
+ """
4
+
5
+ from datetime import datetime
6
+ from typing import List, Optional
7
+
8
+ from sqlalchemy import Column, String, DateTime, Float, Boolean, JSON
9
+ from sqlalchemy.sql import func
10
+
11
+ from debug_env.server.database.db import Base
12
+
13
+
14
+ class TaskRecord(Base):
15
+ """
16
+ Task record — mirrors TASK_REGISTRY in database.
17
+
18
+ Each row represents a debuggable task available in the benchmark.
19
+ Seeded from TASK_REGISTRY at application startup.
20
+ """
21
+
22
+ __tablename__ = "task_records"
23
+
24
+ id = Column(String, primary_key=True, index=True) # e.g., "task1"
25
+ title = Column(String, nullable=False)
26
+ description = Column(String, nullable=False)
27
+ difficulty = Column(String, nullable=False) # e.g., "easy", "medium", "hard"
28
+ bug_type = Column(String, nullable=False) # e.g., "syntax", "logic", "type_error"
29
+ files = Column(JSON, nullable=False) # List of filenames
30
+ tools = Column(JSON, nullable=True) # List of available tools for this task
31
+ scenario_type = Column(String, nullable=True) # e.g., "code_review", "cross_team_collaboration"
32
+ participants = Column(JSON, nullable=True) # List of participant dicts for multi-user tasks
33
+ etag = Column(String, nullable=False) # Cache validation tag
34
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
35
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
36
+
37
+ def __repr__(self) -> str:
38
+ return f"<TaskRecord(id={self.id}, title={self.title}, difficulty={self.difficulty})>"
39
+
40
+
41
+ class EpisodeRecord(Base):
42
+ """
43
+ Episode record — tracks each task run (reset/step sequence).
44
+
45
+ One row created per TaskLoader.load() call (when DebugEnvironment.reset() is called).
46
+ Tracks workdir, status, and pass_rate for the episode lifecycle.
47
+ """
48
+
49
+ __tablename__ = "episode_records"
50
+
51
+ id = Column(String, primary_key=True, index=True) # UUID4 string
52
+ task_id = Column(String, nullable=False, index=True) # e.g., "task1" (FK to task_records.id)
53
+ user_id = Column(String, nullable=False, index=True) # e.g., "default_user" or from X-User-Id header
54
+ workdir = Column(String, nullable=True) # Path to temp directory with task files
55
+ status = Column(
56
+ String,
57
+ nullable=False,
58
+ default="active",
59
+ index=True,
60
+ ) # "active", "passed", "failed", "abandoned"
61
+ pass_rate = Column(Float, nullable=True) # 0.0 to 1.0, or None if not completed
62
+ etag = Column(String, nullable=False) # Cache validation tag
63
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False, index=True)
64
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
65
+
66
+ def __repr__(self) -> str:
67
+ return f"<EpisodeRecord(id={self.id}, task_id={self.task_id}, status={self.status})>"
68
+
69
+
70
+ class WatchChannel(Base):
71
+ """
72
+ Watch channel record — tracks webhook subscriptions for task/episode state changes.
73
+
74
+ Allows clients to subscribe to notifications when tasks or episodes change.
75
+ Lightweight structure for future expansion of notification features.
76
+ """
77
+
78
+ __tablename__ = "watch_channels"
79
+
80
+ id = Column(String, primary_key=True, index=True) # Client-provided ID
81
+ task_id = Column(String, nullable=False, index=True) # Task being watched
82
+ user_id = Column(String, nullable=False, index=True) # User who set up the watch
83
+ webhook_address = Column(String, nullable=False) # URL to POST notifications to
84
+ webhook_token = Column(String, nullable=True) # Optional auth token for webhook
85
+ expires_at = Column(DateTime, nullable=True, index=True) # When this watch expires
86
+ is_active = Column(Boolean, default=True, nullable=False) # Whether watch is currently active
87
+ created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
88
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
89
+
90
+ def __repr__(self) -> str:
91
+ return f"<WatchChannel(id={self.id}, task_id={self.task_id}, is_active={self.is_active})>"
debug_env/server/debug_env_environment.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from uuid import uuid4
3
+
4
+ from openenv.core.env_server.interfaces import Environment
5
+ from openenv.core.env_server.types import State
6
+
7
+ from debug_env.models import DebugAction, DebugObservation
8
+ from debug_env.server.grader import grade
9
+ from debug_env.server.schemas import ToolResult
10
+ from debug_env.server.tasks import TaskLoader
11
+ from debug_env.server.tools import edit_file, read_file, run_tests
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def _make_error_obs(message: str) -> DebugObservation:
17
+ """Return a zero-reward observation for environment-level errors."""
18
+ obs = DebugObservation(pass_rate=0.0, logs=message)
19
+ obs.reward = 0.0
20
+ obs.done = False
21
+ return obs
22
+
23
+
24
+ def _obs_from_result(result: ToolResult) -> DebugObservation:
25
+ """Convert a ToolResult into a DebugObservation with reward and done flag."""
26
+ obs = DebugObservation(pass_rate=result.pass_rate, logs=result.logs)
27
+ obs.reward = grade(result.pass_rate)
28
+ obs.done = result.pass_rate == 1.0
29
+ return obs
30
+
31
+
32
+ class DebugEnvironment(Environment):
33
+
34
+ def __init__(self):
35
+ self._state = State(episode_id=str(uuid4()), step_count=0)
36
+ self.current_task = "task1"
37
+ self.workdir: str | None = None
38
+
39
+ def reset(self, seed: int | None = None, episode_id: str | None = None, task: str | None = None, **kwargs) -> DebugObservation: # noqa: ARG002
40
+ if task is not None:
41
+ self.current_task = task
42
+ self._state = State(episode_id=episode_id or str(uuid4()), step_count=0)
43
+ self.workdir = TaskLoader.load(self.current_task, self.workdir)
44
+ logger.info(f"Reset — task={self.current_task} workdir={self.workdir}")
45
+ return DebugObservation(
46
+ pass_rate=0.0,
47
+ logs=f"Task '{self.current_task}' loaded. Fix the bugs!",
48
+ )
49
+
50
+ # ── Tool dispatch ──────────────────────────────────────────────────────────
51
+
52
+ def _handle_run_tests(self, workdir: str) -> ToolResult:
53
+ return run_tests(workdir)
54
+
55
+ def _handle_read_file(self, workdir: str, args: dict) -> ToolResult:
56
+ return read_file(workdir, path=args.get("path", ""))
57
+
58
+ def _handle_edit_file(self, workdir: str, args: dict) -> ToolResult:
59
+ return edit_file(
60
+ workdir,
61
+ path=args.get("path", ""),
62
+ content=args.get("content", ""),
63
+ )
64
+
65
+ # ── Core step ──────────────────────────────────────────────────────────────
66
+
67
+ def step(self, action: DebugAction, timeout_s: float | None = None, **kwargs) -> DebugObservation: # noqa: ARG002
68
+ self._state.step_count += 1
69
+
70
+ if self.workdir is None:
71
+ return _make_error_obs("Environment not initialised — call reset first.")
72
+
73
+ tool = action.tool
74
+ args = action.args or {}
75
+
76
+ logger.info(f"Step {self._state.step_count} — tool={tool}")
77
+
78
+ try:
79
+ if tool == "run_tests":
80
+ result = self._handle_run_tests(self.workdir)
81
+ elif tool == "read_file":
82
+ result = self._handle_read_file(self.workdir, args)
83
+ elif tool == "edit_file":
84
+ result = self._handle_edit_file(self.workdir, args)
85
+ else:
86
+ result = ToolResult(
87
+ pass_rate=0.0,
88
+ logs=f"Unknown tool: '{tool}'. Use 'run_tests', 'read_file', or 'edit_file'.",
89
+ success=False,
90
+ )
91
+ except Exception as e:
92
+ logger.error(f"Unexpected error in tool '{tool}': {e}", exc_info=True)
93
+ return _make_error_obs(f"Internal error executing '{tool}'. Contact admin if issue persists.")
94
+
95
+ return _obs_from_result(result)
96
+
97
+ @property
98
+ def state(self) -> State:
99
+ return self._state
debug_env/server/grader.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ def grade(pass_rate: float) -> float:
2
+ """Convert test pass rate to reward score in [0.0, 1.0]."""
3
+ return float(pass_rate)
debug_env/server/handlers/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .mcp_handler import handle_mcp_request
2
+
3
+ __all__ = ["handle_mcp_request"]
debug_env/server/handlers/mcp_handler.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP (Model Context Protocol) request handler for debug-env.
3
+
4
+ Implements the MCP JSON-RPC 2024-11-05 protocol, exposing the three debug
5
+ tools (run_tests, read_file, edit_file) and six advanced analysis tools to any
6
+ MCP-compatible client.
7
+
8
+ Session model: a single shared DebugEnvironment is used for MCP sessions.
9
+ Call 'initialize' to set up a session (optionally passing {"task": "task2"} in
10
+ params.meta), then use 'tools/call' to invoke tools across turns.
11
+ """
12
+
13
+ import logging
14
+ from typing import Any, Dict, Optional
15
+
16
+ from fastapi import Request
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ # ── MCP tool definitions ───────────────────────────────────────────────────────
21
+
22
+ MCP_TOOLS = [
23
+ {
24
+ "name": "run_tests",
25
+ "description": """Execute the pytest test suite against the current code.
26
+
27
+ Runs all tests in the task working directory and returns detailed results
28
+ including pass rate and full test output logs.
29
+
30
+ Response Structure:
31
+ - pass_rate: Float (0.0–1.0) indicating fraction of tests passed
32
+ - logs: Test output including failures, errors, and summary
33
+ - reward: Scalar reward based on pass_rate (0.0 at fail, >0.0 at pass)
34
+ - done: Boolean, true when all tests pass (pass_rate = 1.0)
35
+
36
+ Status Codes:
37
+ - 200: Success - Tests executed (may include failures)
38
+ - 500: Internal error running tests
39
+ """,
40
+ "inputSchema": {"type": "object", "properties": {}, "required": []},
41
+ },
42
+ {
43
+ "name": "read_file",
44
+ "description": """Read the current content of a source file in the task working directory.
45
+
46
+ Allows inspection of broken code and helper files before deciding what to edit.
47
+ Reading a file does not affect the test pass rate or episode score.
48
+
49
+ Required Parameters:
50
+ - path: Filename to read (relative to workdir), e.g. 'broken_code.py'
51
+
52
+ Response Structure:
53
+ - pass_rate: 0.0 (reading doesn't affect score)
54
+ - logs: File content prefixed with filename header
55
+ - success: true if file was read successfully
56
+
57
+ Status Codes:
58
+ - 200: Success - File read and returned
59
+ - 400: Bad Request - Invalid filename or path traversal attempt
60
+ - 404: Not Found - File does not exist in task
61
+ - 500: Internal error reading file
62
+ """,
63
+ "inputSchema": {
64
+ "type": "object",
65
+ "properties": {
66
+ "path": {
67
+ "type": "string",
68
+ "minLength": 1,
69
+ "description": "Filename to read (e.g. 'broken_code.py', 'helper.py')",
70
+ }
71
+ },
72
+ "required": ["path"],
73
+ },
74
+ },
75
+ {
76
+ "name": "edit_file",
77
+ "description": """Overwrite a source file with corrected content and run tests.
78
+
79
+ Replaces the entire file content and immediately executes the test suite
80
+ to evaluate the fix. Partial writes are not supported—always provide the
81
+ complete file content.
82
+
83
+ Required Parameters:
84
+ - path: Filename to edit (e.g. 'broken_code.py')
85
+ - content: Complete new file content (full replacement)
86
+
87
+ Response Structure:
88
+ - pass_rate: Float (0.0–1.0) from subsequent test run
89
+ - logs: Test output showing impact of the edit
90
+ - reward: Scalar reward based on new pass_rate
91
+ - done: Boolean, true when all tests pass
92
+ - success: true if file was written and tests executed
93
+
94
+ Status Codes:
95
+ - 200: Success - File written and tests executed
96
+ - 400: Bad Request - Invalid filename or path traversal attempt
97
+ - 404: Not Found - File does not exist in task
98
+ - 500: Internal error writing or testing
99
+ """,
100
+ "inputSchema": {
101
+ "type": "object",
102
+ "properties": {
103
+ "path": {
104
+ "type": "string",
105
+ "minLength": 1,
106
+ "description": "Filename to edit (e.g. 'broken_code.py')",
107
+ },
108
+ "content": {
109
+ "type": "string",
110
+ "description": "Complete new file content (full file replacement)",
111
+ },
112
+ },
113
+ "required": ["path", "content"],
114
+ },
115
+ },
116
+ ]
117
+
118
+ # Advanced debugging tools will be added at runtime (in _handle_tools_list) to avoid circular imports
119
+
120
+ # ── Shared environment instance ────────────────────────────────────────────────
121
+
122
+ _env = None # lazily initialised on first tool call
123
+
124
+
125
+ def _get_env():
126
+ """Return the shared DebugEnvironment, creating it if needed."""
127
+ global _env
128
+ if _env is None:
129
+ from debug_env.server.debug_env_environment import DebugEnvironment
130
+ _env = DebugEnvironment()
131
+ return _env
132
+
133
+
134
+ # ── JSON-RPC helpers ───────────────────────────────────────────────────────────
135
+
136
+
137
+ def _ok(request_id: Any, result: Dict[str, Any]) -> Dict[str, Any]:
138
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
139
+
140
+
141
+ def _error(request_id: Any, code: int, message: str) -> Dict[str, Any]:
142
+ return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
143
+
144
+
145
+ # ── Handler ────────────────────────────────────────────────────────────────────
146
+
147
+
148
+ async def handle_mcp_request(request: Request) -> Optional[Dict[str, Any]]:
149
+ """
150
+ Dispatch an incoming MCP JSON-RPC request to the appropriate handler.
151
+
152
+ Returns None for notifications (caller should respond with 204 No Content).
153
+ """
154
+ try:
155
+ body = await request.json()
156
+ except Exception:
157
+ return _error(None, -32700, "Parse error: request body is not valid JSON")
158
+
159
+ method: str = body.get("method", "")
160
+ params: Dict[str, Any] = body.get("params") or {}
161
+ request_id = body.get("id")
162
+
163
+ # Notifications have no 'id' — we return None so the router sends 204
164
+ if request_id is None:
165
+ logger.debug(f"MCP notification received: {method}")
166
+ return None
167
+
168
+ logger.info(f"MCP request: method={method} id={request_id}")
169
+
170
+ if method == "initialize":
171
+ return _handle_initialize(request_id, params)
172
+
173
+ if method == "tools/list":
174
+ return _handle_tools_list(request_id)
175
+
176
+ if method == "tools/call":
177
+ return await _handle_tools_call(request_id, params)
178
+
179
+ return _error(request_id, -32601, f"Method not found: {method}")
180
+
181
+
182
+ # ── Method handlers ────────────────────────────────────────────────────────────
183
+
184
+
185
+ def _handle_initialize(request_id: Any, params: Dict[str, Any]) -> Dict[str, Any]:
186
+ """
187
+ Perform the MCP handshake and optionally load a task.
188
+
189
+ Clients may pass {"meta": {"task": "task2"}} to select a task up front.
190
+ """
191
+ task = (params.get("meta") or {}).get("task")
192
+ env = _get_env()
193
+ env.reset(task=task)
194
+ logger.info(f"MCP session initialised — task={env.current_task}")
195
+
196
+ return _ok(request_id, {
197
+ "protocolVersion": "2024-11-05",
198
+ "capabilities": {"tools": {}},
199
+ "serverInfo": {"name": "debug-env", "version": "0.1.0"},
200
+ })
201
+
202
+
203
+ def _handle_tools_list(request_id: Any) -> Dict[str, Any]:
204
+ """Return the list of available debug tools in MCP format."""
205
+ # Add advanced tools on first call (lazy loading to avoid circular imports)
206
+ if len(MCP_TOOLS) == 3: # Only have the 3 base tools
207
+ from debug_env.server.tools.tool_handlers import get_mcp_tools_list
208
+ advanced_tools = get_mcp_tools_list()
209
+ MCP_TOOLS.extend(advanced_tools)
210
+
211
+ return _ok(request_id, {"tools": MCP_TOOLS})
212
+
213
+
214
+ async def _handle_tools_call(request_id: Any, params: Dict[str, Any]) -> Dict[str, Any]:
215
+ """Execute a debug tool via generic dispatcher and return the result as MCP content."""
216
+ from debug_env.models import DebugAction
217
+ from debug_env.server.tools.tool_handlers import get_tool_handlers
218
+
219
+ tool_name: str = params.get("name", "")
220
+ tool_args: Dict[str, Any] = params.get("arguments") or {}
221
+
222
+ if not tool_name:
223
+ return _error(request_id, -32602, "Invalid params: 'name' is required")
224
+
225
+ env = _get_env()
226
+ if env.workdir is None:
227
+ env.reset()
228
+
229
+ # Get tool handlers (lazy-loaded to avoid circular imports)
230
+ tool_handlers = get_tool_handlers()
231
+
232
+ # Try advanced tools first via generic dispatcher
233
+ if tool_name in tool_handlers:
234
+ try:
235
+ logger.debug(f"Executing advanced tool {tool_name} via generic dispatcher")
236
+ result = await tool_handlers[tool_name](tool_name, tool_args, env.workdir)
237
+ text = result.get("text", "")
238
+ return _ok(request_id, {
239
+ "content": [{"type": "text", "text": text}],
240
+ "isError": result.get("isError", False),
241
+ })
242
+ except Exception as e:
243
+ logger.error(f"Tool {tool_name} execution failed: {e}", exc_info=True)
244
+ return _error(request_id, -32603, f"Internal error executing tool '{tool_name}'")
245
+
246
+ # Fall back to environment tools (run_tests, read_file, edit_file)
247
+ try:
248
+ action = DebugAction(tool=tool_name, args=tool_args)
249
+ obs = env.step(action)
250
+ except Exception as e:
251
+ logger.error(f"MCP tool call failed — tool={tool_name}: {e}", exc_info=True)
252
+ return _error(request_id, -32603, f"Internal error executing tool '{tool_name}'")
253
+
254
+ text = (
255
+ f"pass_rate={obs.pass_rate:.2f} reward={obs.reward:.2f} done={obs.done}"
256
+ f"\n\n{obs.logs}"
257
+ )
258
+ return _ok(request_id, {
259
+ "content": [{"type": "text", "text": text}],
260
+ "isError": obs.pass_rate == 0.0 and not obs.done,
261
+ })
debug_env/server/mcp/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .router import router
2
+
3
+ __all__ = ["router"]
debug_env/server/mcp/router.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP (Model Context Protocol) API Router
3
+ Handles MCP protocol messages for the debug-env tools.
4
+ Tool execution routes are at /mcp (no /api prefix).
5
+ """
6
+
7
+ import logging
8
+
9
+ from fastapi import APIRouter, Request, Response
10
+
11
+ from debug_env.server.handlers.mcp_handler import handle_mcp_request
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ router = APIRouter()
16
+
17
+
18
+ @router.post("/mcp")
19
+ async def handle_mcp(request: Request):
20
+ """Handle MCP protocol messages"""
21
+ response = await handle_mcp_request(request)
22
+ if response is None:
23
+ # For notifications, return 204 No Content
24
+ return Response(content="", status_code=204, headers={"Content-Length": "0"})
25
+
26
+ # Check if response is already a dict or needs to be converted
27
+ if hasattr(response, "model_dump"):
28
+ return response.model_dump()
29
+ else:
30
+ return response
debug_env/server/mcp/tools/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """MCP tool definitions and implementations."""
debug_env/server/mcp/tools/debug_tools.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Debug Tools Module
3
+
4
+ Comprehensive set of tools for advanced code debugging and analysis.
5
+ Provides code search, structure analysis, type checking, coverage analysis, and dependency inspection.
6
+ """
7
+
8
+ DEBUG_TOOLS = [
9
+ {
10
+ "name": "search_code",
11
+ "description": """Search for code patterns across files in the task directory.
12
+
13
+ Searches for text or regex patterns across source files, useful for locating
14
+ where functions are called, variable usage, or specific error patterns.
15
+ Similar to grep/rg operations but integrated for debugging workflow.
16
+
17
+ Required Parameters:
18
+ - pattern: Text or regex pattern to search for (case-insensitive by default)
19
+ - file_types: Optional. Filter by file type (default: "py" for Python files only)
20
+ Enum: "py" (Python), "all" (all files), "txt", "json", etc.
21
+
22
+ Optional Parameters:
23
+ - case_sensitive: Whether to match case (default: false)
24
+ - max_results: Maximum number of matches to return (default: 50, max: 500)
25
+ - context_lines: Lines of context around each match (default: 2, max: 10)
26
+
27
+ Search Behavior:
28
+ - Returns matches with line numbers, filenames, and surrounding context
29
+ - Sorted by filename then line number
30
+ - If pattern contains regex special chars, it's treated as regex
31
+ - Matches are highlighted with context for easy reading
32
+ - Path traversal protection: only searches within task directory
33
+
34
+ Response Structure:
35
+ - matches: Array of match objects, each containing:
36
+ * filename: File containing the match
37
+ * line_number: Line number (1-indexed)
38
+ * line_content: The matching line
39
+ * before: Context lines before (array)
40
+ * after: Context lines after (array)
41
+ * match_position: Column where match starts
42
+ - total_matches: Total number of matches found
43
+ - files_searched: Number of files examined
44
+ - search_time_ms: Search execution time
45
+
46
+ Status Codes:
47
+ - 200: Success - Search completed (may have 0 matches)
48
+ - 400: Bad Request - Invalid pattern or parameters
49
+ - 500: Internal Server Error
50
+ """,
51
+ "inputSchema": {
52
+ "type": "object",
53
+ "properties": {
54
+ "pattern": {
55
+ "type": "string",
56
+ "description": "Text or regex pattern to search for",
57
+ "minLength": 1,
58
+ "maxLength": 500,
59
+ },
60
+ "file_types": {
61
+ "type": "string",
62
+ "description": "File type filter (py, all, txt, json, etc.)",
63
+ "enum": ["py", "all", "txt", "json", "md"],
64
+ "default": "py",
65
+ },
66
+ "case_sensitive": {
67
+ "type": "boolean",
68
+ "description": "Whether to match case",
69
+ "default": False,
70
+ },
71
+ "max_results": {
72
+ "type": "integer",
73
+ "description": "Maximum number of matches to return",
74
+ "minimum": 1,
75
+ "maximum": 500,
76
+ "default": 50,
77
+ },
78
+ "context_lines": {
79
+ "type": "integer",
80
+ "description": "Lines of context around each match",
81
+ "minimum": 0,
82
+ "maximum": 10,
83
+ "default": 2,
84
+ },
85
+ },
86
+ "required": ["pattern"],
87
+ },
88
+ },
89
+ {
90
+ "name": "get_file_structure",
91
+ "description": """Parse and return the structure (AST) of a Python file.
92
+
93
+ Analyzes the Abstract Syntax Tree of a Python file to extract functions,
94
+ classes, methods, imports, and their locations. Useful for understanding
95
+ code organization before editing.
96
+
97
+ Required Parameters:
98
+ - path: File path relative to task directory (e.g., 'broken_code.py')
99
+
100
+ Optional Parameters:
101
+ - include_docstrings: Include docstrings in output (default: true)
102
+ - include_signatures: Include function/method signatures (default: true)
103
+ - max_depth: Maximum nesting depth to analyze (default: unlimited)
104
+
105
+ Structure Analysis:
106
+ - Extracts top-level functions and classes
107
+ - For each class: lists methods, attributes, parent classes
108
+ - For each function: shows parameters, return type hint (if present)
109
+ - Shows decorators (@property, @staticmethod, etc.)
110
+ - Identifies imports (from/import statements)
111
+ - Groups by section (imports, classes, functions, constants)
112
+
113
+ Response Structure:
114
+ - filename: The analyzed file
115
+ - imports: Array of import statements with line numbers
116
+ * module: Imported module
117
+ * items: What was imported (function/class/constant names)
118
+ * line_number: Where imported
119
+ - classes: Array of class definitions
120
+ * name: Class name
121
+ * line_number: Definition line
122
+ * methods: Array of method names with line numbers
123
+ * attributes: Instance attributes with types (if annotated)
124
+ * docstring: Class docstring (if present)
125
+ - functions: Array of top-level functions
126
+ * name: Function name
127
+ * line_number: Definition line
128
+ * parameters: Param names and types (if annotated)
129
+ * return_type: Return type hint (if present)
130
+ * docstring: Function docstring (if present)
131
+ - constants: Module-level constants
132
+ * name: Constant name
133
+ * line_number: Definition line
134
+ * value: Literal value (if simple)
135
+
136
+ Status Codes:
137
+ - 200: Success - File structure extracted
138
+ - 400: Bad Request - Invalid Python syntax or file not found
139
+ - 500: Internal Server Error
140
+ """,
141
+ "inputSchema": {
142
+ "type": "object",
143
+ "properties": {
144
+ "path": {
145
+ "type": "string",
146
+ "description": "File path relative to task directory",
147
+ "minLength": 1,
148
+ "maxLength": 255,
149
+ },
150
+ "include_docstrings": {
151
+ "type": "boolean",
152
+ "description": "Include docstrings in output",
153
+ "default": True,
154
+ },
155
+ "include_signatures": {
156
+ "type": "boolean",
157
+ "description": "Include function/method signatures",
158
+ "default": True,
159
+ },
160
+ "max_depth": {
161
+ "type": "integer",
162
+ "description": "Maximum nesting depth to analyze (0 for unlimited)",
163
+ "minimum": 0,
164
+ "default": 0,
165
+ },
166
+ },
167
+ "required": ["path"],
168
+ },
169
+ },
170
+ {
171
+ "name": "run_type_check",
172
+ "description": """Run static type checking (mypy) on Python files.
173
+
174
+ Executes mypy type checker on specified file or directory to identify
175
+ type errors, missing annotations, and type incompatibilities.
176
+ Useful for catching type-related bugs before runtime.
177
+
178
+ Required Parameters:
179
+ - path: File or directory path relative to task directory
180
+ (e.g., 'broken_code.py' or '.')
181
+
182
+ Optional Parameters:
183
+ - strict: Enable strict mode (all optional checks, default: false)
184
+ - ignore_missing_imports: Ignore errors from untyped libraries (default: true)
185
+ - show_error_codes: Show error codes in output (default: true)
186
+ - max_errors: Maximum errors to report (default: 100)
187
+
188
+ Type Check Behavior:
189
+ - Analyzes type annotations and infers types
190
+ - Reports missing type hints where inferred types conflict
191
+ - Checks function argument types against signatures
192
+ - Validates attribute access on typed objects
193
+ - Catches common type errors (None checks, incompatible operations)
194
+ - Produces detailed error messages with suggestions
195
+
196
+ Response Structure:
197
+ - path: File/directory analyzed
198
+ - status: "success" or "errors_found"
199
+ - error_count: Total number of type errors
200
+ - errors: Array of error objects
201
+ * file: File containing error
202
+ * line: Line number (1-indexed)
203
+ * column: Column number (1-indexed)
204
+ * message: Detailed error message
205
+ * error_code: mypy error code (e.g., "var-annotated")
206
+ * suggestion: Suggested fix (if available)
207
+ - success_count: Number of successfully type-checked items
208
+ - check_time_ms: Type check execution time
209
+
210
+ Status Codes:
211
+ - 200: Success - Type check completed (may report errors)
212
+ - 400: Bad Request - Invalid path or mypy configuration
213
+ - 500: Internal Server Error
214
+ """,
215
+ "inputSchema": {
216
+ "type": "object",
217
+ "properties": {
218
+ "path": {
219
+ "type": "string",
220
+ "description": "File or directory path relative to task directory",
221
+ "minLength": 1,
222
+ "maxLength": 255,
223
+ },
224
+ "strict": {
225
+ "type": "boolean",
226
+ "description": "Enable strict type checking mode",
227
+ "default": False,
228
+ },
229
+ "ignore_missing_imports": {
230
+ "type": "boolean",
231
+ "description": "Ignore errors from untyped third-party libraries",
232
+ "default": True,
233
+ },
234
+ "show_error_codes": {
235
+ "type": "boolean",
236
+ "description": "Show mypy error codes in output",
237
+ "default": True,
238
+ },
239
+ "max_errors": {
240
+ "type": "integer",
241
+ "description": "Maximum errors to report before stopping",
242
+ "minimum": 1,
243
+ "maximum": 500,
244
+ "default": 100,
245
+ },
246
+ },
247
+ "required": ["path"],
248
+ },
249
+ },
250
+ {
251
+ "name": "get_test_coverage",
252
+ "description": """Analyze test coverage for Python files.
253
+
254
+ Runs coverage.py to measure which lines of code are executed by tests.
255
+ Shows coverage percentage per file/function, identifying untested code paths.
256
+ Useful for understanding test completeness and finding missing edge cases.
257
+
258
+ Required Parameters:
259
+ - path: File or directory path relative to task directory (optional, default: '.')
260
+
261
+ Optional Parameters:
262
+ - branch_coverage: Include branch coverage (if/else paths, default: false)
263
+ - include_missing: Show which lines are not covered (default: true)
264
+ - fail_under: Minimum coverage % required (0-100, default: 0)
265
+
266
+ Coverage Behavior:
267
+ - Runs test suite and tracks line execution
268
+ - Shows coverage for each file
269
+ - Shows coverage for each function/class
270
+ - Identifies completely uncovered functions/methods
271
+ - Can detect dead code (0% coverage)
272
+ - Branch coverage shows if/else branches taken
273
+
274
+ Response Structure:
275
+ - total_coverage: Overall coverage percentage (0-100)
276
+ - files: Array of file coverage objects
277
+ * filename: File path
278
+ * coverage: Coverage percentage
279
+ * lines_total: Total executable lines
280
+ * lines_covered: Lines executed by tests
281
+ * missing_lines: Array of uncovered line numbers (if include_missing)
282
+ - functions: Array of function coverage objects
283
+ * name: Function name
284
+ * file: File containing function
285
+ * coverage: Coverage percentage (0 or 100 for line coverage)
286
+ * line_number: Function definition line
287
+ - status: "covered", "partially_covered", or "uncovered" based on fail_under
288
+ - check_time_ms: Coverage analysis time
289
+
290
+ Status Codes:
291
+ - 200: Success - Coverage analyzed
292
+ - 400: Bad Request - Invalid path or coverage configuration
293
+ - 500: Internal Server Error
294
+ """,
295
+ "inputSchema": {
296
+ "type": "object",
297
+ "properties": {
298
+ "path": {
299
+ "type": "string",
300
+ "description": "File or directory path relative to task directory",
301
+ "minLength": 1,
302
+ "maxLength": 255,
303
+ "default": ".",
304
+ },
305
+ "branch_coverage": {
306
+ "type": "boolean",
307
+ "description": "Include branch (if/else) coverage analysis",
308
+ "default": False,
309
+ },
310
+ "include_missing": {
311
+ "type": "boolean",
312
+ "description": "Show which lines are not covered",
313
+ "default": True,
314
+ },
315
+ "fail_under": {
316
+ "type": "integer",
317
+ "description": "Minimum required coverage percentage (0-100)",
318
+ "minimum": 0,
319
+ "maximum": 100,
320
+ "default": 0,
321
+ },
322
+ },
323
+ "required": [],
324
+ },
325
+ },
326
+ {
327
+ "name": "list_directory",
328
+ "description": """List files and directories in the task working directory.
329
+
330
+ Returns a directory tree showing file structure, sizes, types, and metadata.
331
+ Useful for understanding what files exist and their organization before
332
+ starting to debug or edit code.
333
+
334
+ Required Parameters: None (default: current task directory)
335
+
336
+ Optional Parameters:
337
+ - path: Subdirectory path relative to task root (default: '.')
338
+ - recursive: Include subdirectories recursively (default: true)
339
+ - max_depth: Maximum directory nesting depth (default: unlimited)
340
+ - include_hidden: Include hidden files/folders starting with . (default: false)
341
+ - file_types: Filter by file type (py, all, test, etc.)
342
+
343
+ Directory Listing:
344
+ - Shows files and folders in hierarchical structure
345
+ - Includes file size in bytes
346
+ - Shows file type/extension
347
+ - Marks executable files
348
+ - Marks test files separately
349
+ - Indicates if file is readable/writable
350
+
351
+ Response Structure:
352
+ - root_path: Base directory path
353
+ - total_files: Total number of files (excluding directories)
354
+ - total_directories: Total number of subdirectories
355
+ - items: Array of directory entry objects
356
+ * name: File or directory name
357
+ * type: "file" or "directory"
358
+ * path: Full path relative to task root
359
+ * size_bytes: File size in bytes (for files)
360
+ * is_test: Whether file matches test pattern (test_*.py)
361
+ * is_executable: Whether file is executable
362
+ * contents: Array of child items (for directories if recursive)
363
+ - tree_depth: Maximum nesting depth found
364
+
365
+ Status Codes:
366
+ - 200: Success - Directory listed
367
+ - 404: Not Found - Directory path does not exist
368
+ - 500: Internal Server Error
369
+ """,
370
+ "inputSchema": {
371
+ "type": "object",
372
+ "properties": {
373
+ "path": {
374
+ "type": "string",
375
+ "description": "Subdirectory path relative to task root",
376
+ "default": ".",
377
+ "maxLength": 255,
378
+ },
379
+ "recursive": {
380
+ "type": "boolean",
381
+ "description": "Include subdirectories recursively",
382
+ "default": True,
383
+ },
384
+ "max_depth": {
385
+ "type": "integer",
386
+ "description": "Maximum directory nesting depth (0 for unlimited)",
387
+ "minimum": 0,
388
+ "default": 0,
389
+ },
390
+ "include_hidden": {
391
+ "type": "boolean",
392
+ "description": "Include hidden files/folders starting with .",
393
+ "default": False,
394
+ },
395
+ "file_types": {
396
+ "type": "string",
397
+ "description": "Filter by file type",
398
+ "enum": ["py", "all", "test", "source"],
399
+ "default": "all",
400
+ },
401
+ },
402
+ "required": [],
403
+ },
404
+ },
405
+ {
406
+ "name": "get_dependencies",
407
+ "description": """Extract and analyze Python import dependencies.
408
+
409
+ Parses import statements to build a dependency graph showing what modules/files
410
+ depend on each other. Useful for understanding code relationships and identifying
411
+ circular dependencies or unexpected coupling.
412
+
413
+ Required Parameters:
414
+ - path: File or directory path relative to task directory (e.g., 'broken_code.py' or '.')
415
+
416
+ Optional Parameters:
417
+ - include_stdlib: Include Python standard library imports (default: false)
418
+ - include_external: Include third-party library imports (default: true)
419
+ - direction: Show imports "to" (what this imports) or "from" (what imports this)
420
+ (default: "to")
421
+ - depth: Maximum depth to follow dependencies (default: 1)
422
+
423
+ Dependency Analysis:
424
+ - Extracts all import statements (import x, from x import y)
425
+ - Categorizes imports (local, stdlib, external)
426
+ - Builds dependency graph showing import relationships
427
+ - Detects circular dependencies (A imports B, B imports A)
428
+ - Shows unused imports
429
+ - Maps relative imports to absolute module paths
430
+
431
+ Response Structure:
432
+ - path: File or directory analyzed
433
+ - direct_dependencies: Array of direct imports
434
+ * module: Module being imported
435
+ * type: "import" or "from...import"
436
+ * items: What was imported (if from...import)
437
+ * source_file: File being imported FROM (if local import)
438
+ * is_local: Whether importing from task code
439
+ * line_number: Import statement line number
440
+ - indirect_dependencies: Array of transitive dependencies (if depth > 1)
441
+ * module: Module name
442
+ * via: Path showing how it's imported
443
+ * chain_length: Number of imports deep
444
+ - circular_dependencies: Array of detected cycles
445
+ * cycle: Array of module names forming cycle
446
+ * files: File paths involved in cycle
447
+ - unused_imports: Imports that appear to be unused
448
+ * module: Imported but never referenced
449
+ * file: File with unused import
450
+ * line_number: Import location
451
+ - dependency_count: Total number of dependencies
452
+
453
+ Status Codes:
454
+ - 200: Success - Dependencies extracted
455
+ - 400: Bad Request - Invalid path or syntax error in files
456
+ - 500: Internal Server Error
457
+ """,
458
+ "inputSchema": {
459
+ "type": "object",
460
+ "properties": {
461
+ "path": {
462
+ "type": "string",
463
+ "description": "File or directory path relative to task directory",
464
+ "minLength": 1,
465
+ "maxLength": 255,
466
+ },
467
+ "include_stdlib": {
468
+ "type": "boolean",
469
+ "description": "Include Python standard library imports",
470
+ "default": False,
471
+ },
472
+ "include_external": {
473
+ "type": "boolean",
474
+ "description": "Include third-party library imports",
475
+ "default": True,
476
+ },
477
+ "direction": {
478
+ "type": "string",
479
+ "description": "Show imports 'to' (what this imports) or 'from' (what imports this)",
480
+ "enum": ["to", "from"],
481
+ "default": "to",
482
+ },
483
+ "depth": {
484
+ "type": "integer",
485
+ "description": "Maximum depth to follow dependencies",
486
+ "minimum": 1,
487
+ "maximum": 5,
488
+ "default": 1,
489
+ },
490
+ },
491
+ "required": ["path"],
492
+ },
493
+ },
494
+ ]
debug_env/server/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openenv[core]>=0.2.0
2
+ fastapi>=0.115.0
3
+ uvicorn>=0.24.0
4
+
5
+
6
+
debug_env/server/schemas/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .tool_schemas import EditFileArgs, ReadFileArgs, RunTestsArgs, ToolResult
2
+
3
+ __all__ = ["RunTestsArgs", "ReadFileArgs", "EditFileArgs", "ToolResult"]
debug_env/server/schemas/task_schemas.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pydantic schemas for task API responses and requests.
3
+ """
4
+
5
+ from datetime import datetime
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from pydantic import BaseModel, ConfigDict
9
+
10
+
11
+ class TaskResponse(BaseModel):
12
+ """Response model for a single task."""
13
+
14
+ model_config = ConfigDict(from_attributes=True)
15
+
16
+ id: str
17
+ title: str
18
+ description: str
19
+ difficulty: str
20
+ bug_type: str
21
+ files: List[str]
22
+ tools: Optional[List[str]] = None
23
+ scenario_type: Optional[str] = None
24
+ participants: Optional[List[Dict[str, Any]]] = None
25
+ etag: str
26
+ created_at: datetime
27
+ updated_at: datetime
28
+
29
+
30
+ class TaskListResponse(BaseModel):
31
+ """Response model for paginated task list."""
32
+
33
+ items: List[TaskResponse]
34
+ etag: str
35
+ nextPageToken: Optional[str] = None
36
+ nextSyncToken: Optional[str] = None
37
+
38
+
39
+ class EpisodeResponse(BaseModel):
40
+ """Response model for a single episode."""
41
+
42
+ model_config = ConfigDict(from_attributes=True)
43
+
44
+ id: str
45
+ task_id: str
46
+ user_id: str
47
+ workdir: Optional[str] = None
48
+ status: str
49
+ pass_rate: Optional[float] = None
50
+ etag: str
51
+ created_at: datetime
52
+ updated_at: datetime
53
+
54
+
55
+ class EpisodeListResponse(BaseModel):
56
+ """Response model for paginated episode list."""
57
+
58
+ items: List[EpisodeResponse]
59
+ nextPageToken: Optional[str] = None
60
+
61
+
62
+ class EpisodeCreateRequest(BaseModel):
63
+ """Request model to create an episode."""
64
+
65
+ task_id: str
66
+
67
+
68
+ class EpisodePatchRequest(BaseModel):
69
+ """Request model to update an episode."""
70
+
71
+ status: Optional[str] = None
72
+ pass_rate: Optional[float] = None
73
+
74
+
75
+ class WatchChannelResponse(BaseModel):
76
+ """Response model for a watch channel."""
77
+
78
+ model_config = ConfigDict(from_attributes=True)
79
+
80
+ id: str
81
+ task_id: str
82
+ user_id: str
83
+ webhook_address: str
84
+ webhook_token: Optional[str] = None
85
+ expires_at: Optional[datetime] = None
86
+ is_active: bool
87
+ created_at: datetime
88
+
89
+
90
+ class WatchChannelRequest(BaseModel):
91
+ """Request model to create a watch channel."""
92
+
93
+ id: str
94
+ address: str
95
+ token: Optional[str] = None
debug_env/server/schemas/tool_schemas.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pydantic schemas for tool inputs and results.
3
+
4
+ These are the internal contracts between the environment and the tool layer —
5
+ separate from the public OpenEnv Action/Observation API in models.py.
6
+ """
7
+
8
+ from pydantic import BaseModel, Field, field_validator
9
+
10
+
11
+ class RunTestsArgs(BaseModel):
12
+ """Input schema for the run_tests tool (no arguments required)."""
13
+ pass
14
+
15
+
16
+ class EditFileArgs(BaseModel):
17
+ """Input schema for the edit_file tool."""
18
+
19
+ path: str = Field(
20
+ ...,
21
+ description="Filename to edit relative to the workdir, e.g. 'broken_code.py'",
22
+ min_length=1,
23
+ )
24
+ content: str = Field(
25
+ ...,
26
+ description="Complete new file content (partial writes are not supported)",
27
+ )
28
+
29
+ @field_validator("path")
30
+ @classmethod
31
+ def no_path_traversal(cls, v: str) -> str:
32
+ """Reject paths that attempt to escape the workdir."""
33
+ if ".." in v or v.startswith("/"):
34
+ raise ValueError(
35
+ f"Invalid path '{v}': absolute paths and '..' are not allowed."
36
+ )
37
+ return v
38
+
39
+
40
+ class ReadFileArgs(BaseModel):
41
+ """Input schema for the read_file tool."""
42
+
43
+ path: str = Field(
44
+ ...,
45
+ description="Filename to read relative to the workdir, e.g. 'broken_code.py'",
46
+ min_length=1,
47
+ )
48
+
49
+ @field_validator("path")
50
+ @classmethod
51
+ def no_path_traversal(cls, v: str) -> str:
52
+ """Reject paths that attempt to escape the workdir."""
53
+ if ".." in v or v.startswith("/"):
54
+ raise ValueError(
55
+ f"Invalid path '{v}': absolute paths and '..' are not allowed."
56
+ )
57
+ return v
58
+
59
+
60
+ class ToolResult(BaseModel):
61
+ """Result returned by every tool."""
62
+
63
+ pass_rate: float = Field(
64
+ ...,
65
+ ge=0.0,
66
+ le=1.0,
67
+ description="Fraction of tests that passed (0.0 – 1.0)",
68
+ )
69
+ logs: str = Field(
70
+ default="",
71
+ description="Full pytest output or error message",
72
+ )
73
+ success: bool = Field(
74
+ default=True,
75
+ description="False when the tool itself failed (not the tests)",
76
+ )
debug_env/server/tasks/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .data import get_available_task_ids, get_task_by_id, get_task_files, validate_task_id
2
+ from .loader import TaskLoader
3
+
4
+ __all__ = ["TaskLoader", "get_task_by_id", "get_available_task_ids", "get_task_files", "validate_task_id"]
debug_env/server/tasks/data.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Debug-Env Task Registry
3
+ Static task definitions for the debugging benchmark.
4
+ """
5
+
6
+ from typing import Any, Dict, List
7
+
8
+ # Task metadata registry — mirrors the structure on disk under debug_env/tasks/
9
+ TASK_REGISTRY: Dict[str, Dict[str, Any]] = {
10
+ "task1": {
11
+ "id": "task1",
12
+ "title": "Syntax Error",
13
+ "description": "Fix a Python syntax error that prevents the module from importing.",
14
+ "difficulty": "easy",
15
+ "bug_type": "syntax",
16
+ "files": ["broken_code.py"],
17
+ },
18
+ "task2": {
19
+ "id": "task2",
20
+ "title": "Logic Error",
21
+ "description": "Fix a logical error in a boolean expression.",
22
+ "difficulty": "medium",
23
+ "bug_type": "logic",
24
+ "files": ["broken_code.py"],
25
+ },
26
+ "task3": {
27
+ "id": "task3",
28
+ "title": "Multi-file Bug",
29
+ "description": "Fix a bug that spans broken_code.py and a helper module it imports.",
30
+ "difficulty": "hard",
31
+ "bug_type": "multi-file",
32
+ "files": ["broken_code.py", "helper.py"],
33
+ },
34
+ "task4": {
35
+ "id": "task4",
36
+ "title": "Type Error Detection",
37
+ "description": "Identify and fix type annotation errors detected by static type checking.",
38
+ "difficulty": "medium",
39
+ "bug_type": "type_error",
40
+ "files": ["typed_code.py"],
41
+ "tools": ["run_type_check", "edit_file", "run_tests"],
42
+ },
43
+ "task5": {
44
+ "id": "task5",
45
+ "title": "Unused Imports and Dead Code",
46
+ "description": "Find and remove unused imports and dead code using code analysis tools.",
47
+ "difficulty": "medium",
48
+ "bug_type": "code_quality",
49
+ "files": ["messy_code.py"],
50
+ "tools": ["search_code", "get_file_structure", "get_dependencies", "edit_file", "run_tests"],
51
+ },
52
+ "task6": {
53
+ "id": "task6",
54
+ "title": "Complex Multi-file Refactoring",
55
+ "description": "Refactor code across multiple files while maintaining test coverage and fixing architectural issues.",
56
+ "difficulty": "hard",
57
+ "bug_type": "architecture",
58
+ "files": ["module_a.py", "module_b.py", "module_c.py", "integration.py"],
59
+ "tools": ["list_directory", "get_file_structure", "get_dependencies", "search_code", "get_test_coverage", "edit_file", "run_tests"],
60
+ },
61
+ "task7": {
62
+ "id": "task7",
63
+ "title": "Code Review Workflow",
64
+ "description": "Multi-user collaborative task: Junior developer submits fix that needs code review and approval",
65
+ "difficulty": "medium",
66
+ "bug_type": "code_quality",
67
+ "files": ["auth.py", "test_auth.py"],
68
+ "scenario_type": "code_review",
69
+ "participants": ["bob_junior", "alice_senior", "dave_lead"],
70
+ "tools": ["read_file", "edit_file", "run_tests", "search_code", "run_type_check", "get_test_coverage"],
71
+ },
72
+ "task8": {
73
+ "id": "task8",
74
+ "title": "Cross-team Bug Investigation",
75
+ "description": "Multi-user collaborative task: QA reported bug, dev team investigates and implements fix",
76
+ "difficulty": "hard",
77
+ "bug_type": "bug_investigation",
78
+ "files": ["user_service.py", "email_validator.py", "test_user_service.py"],
79
+ "scenario_type": "cross_team_collaboration",
80
+ "participants": ["carol_qa", "bob_junior", "alice_senior", "dave_lead"],
81
+ "tools": ["search_code", "get_file_structure", "read_file", "run_tests", "edit_file", "get_test_coverage"],
82
+ },
83
+ "task9": {
84
+ "id": "task9",
85
+ "title": "Collaborative Architecture Refactoring",
86
+ "description": "Multi-user collaborative task: Large refactoring with multiple developers working in parallel",
87
+ "difficulty": "hard",
88
+ "bug_type": "architecture",
89
+ "files": ["data_processor.py", "business_logic.py", "api_interface.py", "integration.py"],
90
+ "scenario_type": "team_refactoring",
91
+ "participants": ["alice_senior", "bob_junior", "carol_qa", "dave_lead"],
92
+ "tools": ["list_directory", "get_file_structure", "get_dependencies", "search_code", "read_file", "edit_file", "run_tests", "run_type_check", "get_test_coverage"],
93
+ },
94
+ }
95
+
96
+
97
+ def get_task_by_id(task_id: str) -> Dict[str, Any]:
98
+ """
99
+ Return metadata for a task by its ID.
100
+
101
+ Args:
102
+ task_id: e.g. "task1"
103
+
104
+ Returns:
105
+ Task metadata dict.
106
+
107
+ Raises:
108
+ ValueError: If task_id is not registered.
109
+ """
110
+ task = TASK_REGISTRY.get(task_id)
111
+ if task is None:
112
+ available = get_available_task_ids()
113
+ raise ValueError(f"Unknown task '{task_id}'. Available: {available}")
114
+ return task
115
+
116
+
117
+ def get_available_task_ids() -> List[str]:
118
+ """Return a sorted list of all registered task IDs."""
119
+ return sorted(TASK_REGISTRY.keys())
120
+
121
+
122
+ def get_task_files(task_id: str) -> List[str]:
123
+ """
124
+ Return the list of source files belonging to a task.
125
+
126
+ Args:
127
+ task_id: e.g. "task1"
128
+
129
+ Returns:
130
+ List of filenames, e.g. ["broken_code.py", "helper.py"]
131
+ """
132
+ return get_task_by_id(task_id)["files"]
133
+
134
+
135
+ def validate_task_id(task_id: str) -> bool:
136
+ """
137
+ Check whether a task ID is registered.
138
+
139
+ Args:
140
+ task_id: The task ID to validate.
141
+
142
+ Returns:
143
+ True if the task exists, False otherwise.
144
+ """
145
+ return task_id in TASK_REGISTRY
debug_env/server/tasks/loader.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TaskLoader — copies task source files into a fresh temp directory for each episode.
3
+
4
+ Task layout on disk:
5
+ debug_env/tasks/
6
+ task1/
7
+ broken_code.py
8
+ test_code.py
9
+ task2/
10
+ broken_code.py
11
+ test_code.py
12
+ task3/
13
+ broken_code.py
14
+ helper.py
15
+ test_code.py
16
+ """
17
+
18
+ import shutil
19
+ import tempfile
20
+ from pathlib import Path
21
+
22
+ from debug_env.server.tasks.data import get_available_task_ids, validate_task_id
23
+
24
+ TASKS_DIR = Path(__file__).parent.parent.parent / "tasks"
25
+
26
+
27
+ class TaskLoader:
28
+ """Manages task file staging into isolated temp directories."""
29
+
30
+ @staticmethod
31
+ def available_tasks() -> list[str]:
32
+ """Return sorted list of registered task IDs."""
33
+ return get_available_task_ids()
34
+
35
+ @staticmethod
36
+ def load(task_id: str, previous_workdir: str | None = None) -> str:
37
+ """
38
+ Copy all files for *task_id* into a fresh temp directory.
39
+ For tasks with seed data, generates files from seed data.
40
+
41
+ Args:
42
+ task_id: e.g. "task1"
43
+ previous_workdir: if provided, this directory is deleted first.
44
+
45
+ Returns:
46
+ Path to the new workdir (str).
47
+
48
+ Raises:
49
+ ValueError: if task_id is not in the registry.
50
+ FileNotFoundError: if task files are missing from disk.
51
+ """
52
+ if not validate_task_id(task_id):
53
+ available = get_available_task_ids()
54
+ raise ValueError(
55
+ f"Unknown task '{task_id}'. Available: {available}"
56
+ )
57
+
58
+ if previous_workdir:
59
+ shutil.rmtree(previous_workdir, ignore_errors=True)
60
+
61
+ workdir = tempfile.mkdtemp(prefix=f"debug_{task_id}_")
62
+
63
+ # For tasks with seed data, generate files from seed data
64
+ if task_id == "task4":
65
+ TaskLoader._generate_task4_files(workdir)
66
+ elif task_id == "task5":
67
+ TaskLoader._generate_task5_files(workdir)
68
+ elif task_id == "task6":
69
+ TaskLoader._generate_task6_files(workdir)
70
+ elif task_id == "task7":
71
+ TaskLoader._generate_task7_files(workdir)
72
+ elif task_id == "task8":
73
+ TaskLoader._generate_task8_files(workdir)
74
+ elif task_id == "task9":
75
+ TaskLoader._generate_task9_files(workdir)
76
+ else:
77
+ # For other tasks, copy from disk
78
+ task_path = TASKS_DIR / task_id
79
+ if not task_path.is_dir():
80
+ raise FileNotFoundError(
81
+ f"Task files for '{task_id}' not found on disk at {task_path}"
82
+ )
83
+
84
+ for f in task_path.iterdir():
85
+ if f.is_file():
86
+ shutil.copy2(f, workdir)
87
+
88
+ return workdir
89
+
90
+ @staticmethod
91
+ def _generate_task4_files(workdir: str) -> None:
92
+ """Generate task4 files from seed data."""
93
+ from debug_env.tasks.task4.seed_data import (
94
+ get_task4_seed_data,
95
+ get_test_file_content,
96
+ )
97
+
98
+ seed = get_task4_seed_data()
99
+ for filename, content in seed["files"].items():
100
+ filepath = Path(workdir) / filename
101
+ filepath.write_text(content, encoding="utf-8")
102
+
103
+ # Write test file
104
+ test_content = get_test_file_content()
105
+ (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8")
106
+
107
+ @staticmethod
108
+ def _generate_task5_files(workdir: str) -> None:
109
+ """Generate task5 files from seed data."""
110
+ from debug_env.tasks.task5.seed_data import (
111
+ get_task5_seed_data,
112
+ get_test_file_content,
113
+ )
114
+
115
+ seed = get_task5_seed_data()
116
+ for filename, content in seed["files"].items():
117
+ filepath = Path(workdir) / filename
118
+ filepath.write_text(content, encoding="utf-8")
119
+
120
+ # Write test file
121
+ test_content = get_test_file_content()
122
+ (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8")
123
+
124
+ @staticmethod
125
+ def _generate_task6_files(workdir: str) -> None:
126
+ """Generate task6 files from seed data."""
127
+ from debug_env.tasks.task6.seed_data import (
128
+ get_task6_seed_data,
129
+ get_test_file_content,
130
+ )
131
+
132
+ seed = get_task6_seed_data()
133
+ for filename, content in seed["files"].items():
134
+ filepath = Path(workdir) / filename
135
+ filepath.write_text(content, encoding="utf-8")
136
+
137
+ # Write test file
138
+ test_content = get_test_file_content()
139
+ (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8")
140
+
141
+ @staticmethod
142
+ def _generate_task7_files(workdir: str) -> None:
143
+ """Generate task7 files from seed data."""
144
+ from debug_env.tasks.task7.seed_data import (
145
+ get_task7_seed_data,
146
+ get_test_auth_py_content,
147
+ )
148
+
149
+ seed = get_task7_seed_data()
150
+ for filename, content in seed["files"].items():
151
+ filepath = Path(workdir) / filename
152
+ filepath.write_text(content, encoding="utf-8")
153
+
154
+ # Write test file
155
+ test_content = get_test_auth_py_content()
156
+ (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8")
157
+
158
+ @staticmethod
159
+ def _generate_task8_files(workdir: str) -> None:
160
+ """Generate task8 files from seed data."""
161
+ from debug_env.tasks.task8.seed_data import (
162
+ get_task8_seed_data,
163
+ get_test_user_service_content,
164
+ )
165
+
166
+ seed = get_task8_seed_data()
167
+ for filename, content in seed["files"].items():
168
+ filepath = Path(workdir) / filename
169
+ filepath.write_text(content, encoding="utf-8")
170
+
171
+ # Write test file
172
+ test_content = get_test_user_service_content()
173
+ (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8")
174
+
175
+ @staticmethod
176
+ def _generate_task9_files(workdir: str) -> None:
177
+ """Generate task9 files from seed data."""
178
+ from debug_env.tasks.task9.seed_data import (
179
+ get_task9_seed_data,
180
+ get_test_file_content,
181
+ )
182
+
183
+ seed = get_task9_seed_data()
184
+ for filename, content in seed["files"].items():
185
+ filepath = Path(workdir) / filename
186
+ filepath.write_text(content, encoding="utf-8")
187
+
188
+ # Write test file
189
+ test_content = get_test_file_content()
190
+ (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8")
191
+
192
+ @staticmethod
193
+ def list_source_files(task_id: str) -> list[str]:
194
+ """
195
+ Return the editable source filenames for a task (excludes test files).
196
+
197
+ Args:
198
+ task_id: e.g. "task1"
199
+
200
+ Returns:
201
+ Sorted list of filenames, e.g. ["broken_code.py"]
202
+
203
+ Raises:
204
+ ValueError: if task_id is not registered.
205
+ """
206
+ if not validate_task_id(task_id):
207
+ raise ValueError(f"Unknown task '{task_id}'.")
208
+ task_path = TASKS_DIR / task_id
209
+ return sorted(
210
+ f.name for f in task_path.iterdir()
211
+ if f.is_file() and not f.name.startswith("test_")
212
+ )
213
+
214
+ @staticmethod
215
+ def read_source_file(task_id: str, filename: str) -> str:
216
+ """
217
+ Read the canonical (pre-episode) content of a source file.
218
+
219
+ Args:
220
+ task_id: e.g. "task1"
221
+ filename: e.g. "broken_code.py"
222
+
223
+ Returns:
224
+ File content as a string.
225
+
226
+ Raises:
227
+ ValueError: if task_id is not registered or filename is invalid.
228
+ FileNotFoundError: if the file does not exist on disk.
229
+ """
230
+ if not validate_task_id(task_id):
231
+ raise ValueError(f"Unknown task '{task_id}'.")
232
+ if ".." in filename or filename.startswith("/"):
233
+ raise ValueError(f"Invalid filename '{filename}'.")
234
+ file_path = TASKS_DIR / task_id / filename
235
+ if not file_path.is_file():
236
+ available = TaskLoader.list_source_files(task_id)
237
+ raise FileNotFoundError(
238
+ f"File '{filename}' not found in task '{task_id}'. "
239
+ f"Available source files: {available}"
240
+ )
241
+ return file_path.read_text(encoding="utf-8")
debug_env/server/tasks/router.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tasks API endpoints
3
+ Provides task metadata, episode management, and source file access for the debug-env benchmark.
4
+ """
5
+
6
+ import logging
7
+ from typing import Any, Dict, List
8
+
9
+ from fastapi import APIRouter, HTTPException, status, Depends
10
+ from pydantic import ValidationError
11
+ from sqlalchemy.orm import Session
12
+
13
+ from debug_env.server.tasks.data import get_available_task_ids, get_task_by_id, validate_task_id
14
+ from debug_env.server.tasks.loader import TaskLoader
15
+ from debug_env.server.database.db import get_db
16
+ from debug_env.server.database.managers.task_manager import get_task_manager
17
+ from debug_env.server.schemas.task_schemas import (
18
+ TaskListResponse,
19
+ TaskResponse,
20
+ EpisodeResponse,
21
+ EpisodeListResponse,
22
+ EpisodeCreateRequest,
23
+ EpisodePatchRequest,
24
+ )
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ router = APIRouter(prefix="/tasks", tags=["tasks"])
29
+
30
+
31
+ def _format_validation_error(e: ValidationError) -> str:
32
+ """Format a Pydantic ValidationError into a human-readable string."""
33
+ messages = []
34
+ for error in e.errors():
35
+ field = " -> ".join(str(loc) for loc in error["loc"])
36
+ messages.append(f"{field}: {error['msg']}")
37
+ return "Validation failed: " + "; ".join(messages)
38
+
39
+
40
+ @router.get("", response_model=Dict[str, Any])
41
+ async def list_tasks(
42
+ db: Session = Depends(get_db),
43
+ maxResults: int = 50,
44
+ pageToken: str = None,
45
+ syncToken: str = None,
46
+ ):
47
+ """
48
+ Returns metadata for all available debug tasks with pagination support.
49
+
50
+ Query Parameters:
51
+ - maxResults: Maximum tasks per page (default: 50)
52
+ - pageToken: Pagination token from previous response
53
+ - syncToken: Sync token for incremental updates
54
+
55
+ GET /tasks
56
+ """
57
+ try:
58
+ # Get user_id from header (default to "default_user" if not provided)
59
+ user_id = "default_user"
60
+
61
+ # Use TaskManager for listing with pagination
62
+ manager = get_task_manager(db, user_id)
63
+ response = manager.list_tasks(
64
+ max_results=maxResults,
65
+ page_token=pageToken,
66
+ sync_token=syncToken,
67
+ )
68
+
69
+ # Convert to dict response matching schema
70
+ return {
71
+ "etag": response.etag,
72
+ "items": [TaskResponse.model_validate(item).model_dump() for item in response.items],
73
+ "nextPageToken": response.nextPageToken,
74
+ "nextSyncToken": response.nextSyncToken,
75
+ }
76
+ except ValueError as e:
77
+ logger.error(f"Validation error listing tasks: {e}")
78
+ raise HTTPException(
79
+ status_code=status.HTTP_400_BAD_REQUEST,
80
+ detail=str(e),
81
+ )
82
+ except Exception as e:
83
+ logger.error(f"Error listing tasks: {e}")
84
+ raise HTTPException(
85
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
86
+ detail="Internal server error occurred while listing tasks",
87
+ )
88
+
89
+
90
+ @router.get("/{taskId}", response_model=Dict[str, Any])
91
+ async def get_task(taskId: str):
92
+ """
93
+ Returns metadata for a specific debug task.
94
+
95
+ GET /tasks/{taskId}
96
+ """
97
+ try:
98
+ if not validate_task_id(taskId):
99
+ raise HTTPException(
100
+ status_code=status.HTTP_404_NOT_FOUND,
101
+ detail=f"Task '{taskId}' not found. Available: {get_available_task_ids()}",
102
+ )
103
+ task = get_task_by_id(taskId)
104
+ logger.info(f"Retrieved task metadata for '{taskId}'")
105
+ return task
106
+ except HTTPException:
107
+ raise
108
+ except ValidationError as e:
109
+ # Handle unexpected schema validation errors
110
+ logger.error(f"Schema validation error for task '{taskId}': {e}")
111
+ raise HTTPException(
112
+ status_code=status.HTTP_400_BAD_REQUEST,
113
+ detail=_format_validation_error(e),
114
+ )
115
+ except Exception as e:
116
+ logger.error(f"Error getting task '{taskId}': {e}")
117
+ raise HTTPException(
118
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
119
+ detail="Internal server error occurred while retrieving task",
120
+ )
121
+
122
+
123
+ @router.get("/{taskId}/files", response_model=List[str])
124
+ async def list_task_files(taskId: str):
125
+ """
126
+ Returns the list of editable source files for a task (excludes test files).
127
+
128
+ GET /tasks/{taskId}/files
129
+ """
130
+ try:
131
+ if not validate_task_id(taskId):
132
+ raise HTTPException(
133
+ status_code=status.HTTP_404_NOT_FOUND,
134
+ detail=f"Task '{taskId}' not found. Available: {get_available_task_ids()}",
135
+ )
136
+ files = TaskLoader.list_source_files(taskId)
137
+ logger.info(f"Listed {len(files)} source files for task '{taskId}'")
138
+ return files
139
+ except HTTPException:
140
+ raise
141
+ except ValueError as e:
142
+ # Handle business logic validation errors (invalid task ID)
143
+ logger.error(f"Validation error listing files for task '{taskId}': {e}")
144
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid task or request parameters")
145
+ except FileNotFoundError as e:
146
+ # Task is registered but files are missing from disk
147
+ logger.error(f"Task files missing on disk for '{taskId}': {e}")
148
+ raise HTTPException(
149
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
150
+ detail="Internal server error occurred while listing task files",
151
+ )
152
+ except Exception as e:
153
+ logger.error(f"Error listing files for task '{taskId}': {e}")
154
+ raise HTTPException(
155
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
156
+ detail="Internal server error occurred while listing task files",
157
+ )
158
+
159
+
160
+ @router.get("/{taskId}/files/{filename}", response_model=Dict[str, str])
161
+ async def get_task_file(taskId: str, filename: str):
162
+ """
163
+ Returns the canonical (pre-episode) content of a source file.
164
+
165
+ Use this to inspect the original broken code before starting an episode.
166
+ During an episode, use the read_file tool via POST /step instead.
167
+
168
+ GET /tasks/{taskId}/files/{filename}
169
+ """
170
+ try:
171
+ if not validate_task_id(taskId):
172
+ raise HTTPException(
173
+ status_code=status.HTTP_404_NOT_FOUND,
174
+ detail=f"Task '{taskId}' not found. Available: {get_available_task_ids()}",
175
+ )
176
+ content = TaskLoader.read_source_file(taskId, filename)
177
+ logger.info(f"Read source file '{filename}' for task '{taskId}'")
178
+ return {"task_id": taskId, "filename": filename, "content": content}
179
+ except HTTPException:
180
+ raise
181
+ except ValueError as e:
182
+ # Handle business logic validation errors (invalid filename, path traversal)
183
+ logger.error(f"Validation error reading file '{filename}' for task '{taskId}': {e}")
184
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid filename or request parameters")
185
+ except FileNotFoundError as e:
186
+ # File not found within the task
187
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
188
+ except Exception as e:
189
+ logger.error(f"Error reading file '{filename}' for task '{taskId}': {e}")
190
+ raise HTTPException(
191
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
192
+ detail="Internal server error occurred while reading task file",
193
+ )
194
+
195
+
196
+ # ── Episode Management Endpoints ───────────────────────────────────────────
197
+
198
+
199
+ @router.post("/{taskId}/episodes", response_model=Dict[str, Any])
200
+ async def create_episode(
201
+ taskId: str,
202
+ db: Session = Depends(get_db),
203
+ ):
204
+ """
205
+ Create a new episode (task run) for the current user.
206
+
207
+ POST /tasks/{taskId}/episodes
208
+
209
+ Returns:
210
+ - id: Episode identifier (uuid4)
211
+ - task_id: Task identifier
212
+ - status: "active"
213
+ - workdir: Path to working directory with task files
214
+ - etag: Cache validation tag
215
+ """
216
+ try:
217
+ if not validate_task_id(taskId):
218
+ raise HTTPException(
219
+ status_code=status.HTTP_404_NOT_FOUND,
220
+ detail=f"Task '{taskId}' not found",
221
+ )
222
+
223
+ user_id = "default_user"
224
+ manager = get_task_manager(db, user_id)
225
+
226
+ # Load task files into temp directory
227
+ workdir = TaskLoader.load(taskId)
228
+
229
+ # Create episode record
230
+ episode = manager.create_episode(taskId, workdir)
231
+
232
+ logger.info(f"Created episode {episode.id} for task {taskId}")
233
+ return EpisodeResponse.model_validate(episode).model_dump()
234
+
235
+ except HTTPException:
236
+ raise
237
+ except ValueError as e:
238
+ logger.error(f"Validation error creating episode for task {taskId}: {e}")
239
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
240
+ except Exception as e:
241
+ logger.error(f"Error creating episode for task {taskId}: {e}")
242
+ raise HTTPException(
243
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
244
+ detail="Internal server error occurred while creating episode",
245
+ )
246
+
247
+
248
+ @router.get("/{taskId}/episodes", response_model=Dict[str, Any])
249
+ async def list_episodes(
250
+ taskId: str,
251
+ db: Session = Depends(get_db),
252
+ maxResults: int = 50,
253
+ pageToken: str = None,
254
+ ):
255
+ """
256
+ List episodes for a task with pagination.
257
+
258
+ GET /tasks/{taskId}/episodes
259
+
260
+ Query Parameters:
261
+ - maxResults: Maximum episodes per page (default: 50)
262
+ - pageToken: Pagination token from previous response
263
+ """
264
+ try:
265
+ if not validate_task_id(taskId):
266
+ raise HTTPException(
267
+ status_code=status.HTTP_404_NOT_FOUND,
268
+ detail=f"Task '{taskId}' not found",
269
+ )
270
+
271
+ user_id = "default_user"
272
+ manager = get_task_manager(db, user_id)
273
+
274
+ response = manager.list_episodes(taskId, max_results=maxResults, page_token=pageToken)
275
+
276
+ return {
277
+ "items": [EpisodeResponse.model_validate(item).model_dump() for item in response.items],
278
+ "nextPageToken": response.nextPageToken,
279
+ }
280
+
281
+ except HTTPException:
282
+ raise
283
+ except ValueError as e:
284
+ logger.error(f"Validation error listing episodes for task {taskId}: {e}")
285
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
286
+ except Exception as e:
287
+ logger.error(f"Error listing episodes for task {taskId}: {e}")
288
+ raise HTTPException(
289
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
290
+ detail="Internal server error occurred while listing episodes",
291
+ )
292
+
293
+
294
+ @router.get("/{taskId}/episodes/{episodeId}", response_model=Dict[str, Any])
295
+ async def get_episode(
296
+ taskId: str,
297
+ episodeId: str,
298
+ db: Session = Depends(get_db),
299
+ ):
300
+ """
301
+ Retrieve a specific episode.
302
+
303
+ GET /tasks/{taskId}/episodes/{episodeId}
304
+ """
305
+ try:
306
+ if not validate_task_id(taskId):
307
+ raise HTTPException(
308
+ status_code=status.HTTP_404_NOT_FOUND,
309
+ detail=f"Task '{taskId}' not found",
310
+ )
311
+
312
+ user_id = "default_user"
313
+ manager = get_task_manager(db, user_id)
314
+
315
+ episode = manager.get_episode(taskId, episodeId)
316
+ if not episode:
317
+ raise HTTPException(
318
+ status_code=status.HTTP_404_NOT_FOUND,
319
+ detail=f"Episode '{episodeId}' not found for task '{taskId}'",
320
+ )
321
+
322
+ return EpisodeResponse.model_validate(episode).model_dump()
323
+
324
+ except HTTPException:
325
+ raise
326
+ except Exception as e:
327
+ logger.error(f"Error retrieving episode {episodeId} for task {taskId}: {e}")
328
+ raise HTTPException(
329
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
330
+ detail="Internal server error occurred while retrieving episode",
331
+ )
332
+
333
+
334
+ @router.patch("/{taskId}/episodes/{episodeId}", response_model=Dict[str, Any])
335
+ async def update_episode(
336
+ taskId: str,
337
+ episodeId: str,
338
+ request: EpisodePatchRequest,
339
+ db: Session = Depends(get_db),
340
+ ):
341
+ """
342
+ Update an episode's status and/or pass_rate.
343
+
344
+ PATCH /tasks/{taskId}/episodes/{episodeId}
345
+
346
+ Request Body:
347
+ - status: Optional, new status ("active", "passed", "failed", "abandoned")
348
+ - pass_rate: Optional, pass rate (0.0-1.0)
349
+ """
350
+ try:
351
+ if not validate_task_id(taskId):
352
+ raise HTTPException(
353
+ status_code=status.HTTP_404_NOT_FOUND,
354
+ detail=f"Task '{taskId}' not found",
355
+ )
356
+
357
+ user_id = "default_user"
358
+ manager = get_task_manager(db, user_id)
359
+
360
+ # Get current episode
361
+ episode = manager.get_episode(taskId, episodeId)
362
+ if not episode:
363
+ raise HTTPException(
364
+ status_code=status.HTTP_404_NOT_FOUND,
365
+ detail=f"Episode '{episodeId}' not found for task '{taskId}'",
366
+ )
367
+
368
+ # Update with provided fields
369
+ status = request.status if request.status else episode.status
370
+ pass_rate = request.pass_rate if request.pass_rate is not None else episode.pass_rate
371
+
372
+ updated_episode = manager.update_episode(taskId, episodeId, status, pass_rate)
373
+
374
+ logger.info(f"Updated episode {episodeId} for task {taskId}")
375
+ return EpisodeResponse.model_validate(updated_episode).model_dump()
376
+
377
+ except HTTPException:
378
+ raise
379
+ except ValueError as e:
380
+ logger.error(f"Validation error updating episode {episodeId}: {e}")
381
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
382
+ except Exception as e:
383
+ logger.error(f"Error updating episode {episodeId}: {e}")
384
+ raise HTTPException(
385
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
386
+ detail="Internal server error occurred while updating episode",
387
+ )
debug_env/server/tools/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .edit_file import edit_file
2
+ from .read_file import read_file
3
+ from .run_tests import run_tests
4
+
5
+ __all__ = ["run_tests", "read_file", "edit_file"]
debug_env/server/tools/advanced_tools.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Advanced debugging tools for code analysis and inspection.
3
+
4
+ Provides functions for:
5
+ - Code search (grep-like pattern matching)
6
+ - File structure analysis (AST parsing)
7
+ - Type checking (mypy integration)
8
+ - Test coverage analysis (coverage.py integration)
9
+ - Directory listing and navigation
10
+ - Import dependency analysis
11
+ """
12
+
13
+ import ast
14
+ import json
15
+ import logging
16
+ import os
17
+ import re
18
+ import subprocess
19
+ from pathlib import Path
20
+ from typing import Any, Dict, List
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ def search_code(
26
+ workdir: str,
27
+ pattern: str,
28
+ file_types: str = "py",
29
+ case_sensitive: bool = False,
30
+ max_results: int = 50,
31
+ context_lines: int = 2,
32
+ ) -> Dict[str, Any]:
33
+ """
34
+ Search for code patterns across files in the task directory.
35
+
36
+ Args:
37
+ workdir: Absolute path to task working directory
38
+ pattern: Text or regex pattern to search for
39
+ file_types: File type filter ("py", "all", "txt", "json", "md")
40
+ case_sensitive: Whether to match case
41
+ max_results: Maximum matches to return (1-500)
42
+ context_lines: Lines of context around each match (0-10)
43
+
44
+ Returns:
45
+ Dict with matches, match count, files searched, and timing info
46
+ """
47
+ try:
48
+ workdir_path = Path(workdir)
49
+ if not workdir_path.is_dir():
50
+ return {"error": f"Invalid directory: {workdir}", "matches": [], "total_matches": 0}
51
+
52
+ # Determine file extensions to search
53
+ if file_types == "all":
54
+ search_patterns = ["*"]
55
+ elif file_types == "py":
56
+ search_patterns = ["*.py"]
57
+ else:
58
+ search_patterns = [f"*.{file_types}"]
59
+
60
+ # Compile regex pattern
61
+ flags = 0 if case_sensitive else re.IGNORECASE
62
+ try:
63
+ compiled_pattern = re.compile(pattern, flags)
64
+ except re.error as e:
65
+ return {"error": f"Invalid regex pattern: {e}", "matches": [], "total_matches": 0}
66
+
67
+ matches = []
68
+ files_searched = 0
69
+
70
+ # Search files
71
+ for search_pattern in search_patterns:
72
+ for file_path in workdir_path.rglob(search_pattern):
73
+ if not file_path.is_file():
74
+ continue
75
+
76
+ files_searched += 1
77
+ try:
78
+ content = file_path.read_text(encoding="utf-8")
79
+ lines = content.split("\n")
80
+
81
+ for line_num, line in enumerate(lines, 1):
82
+ for match in compiled_pattern.finditer(line):
83
+ if len(matches) >= max_results:
84
+ break
85
+
86
+ matches.append({
87
+ "filename": str(file_path.relative_to(workdir_path)),
88
+ "line_number": line_num,
89
+ "line_content": line,
90
+ "match_position": match.start(),
91
+ "before": lines[max(0, line_num - context_lines - 1):line_num - 1],
92
+ "after": lines[line_num:min(len(lines), line_num + context_lines)],
93
+ })
94
+ except (UnicodeDecodeError, OSError):
95
+ continue
96
+
97
+ logger.info(f"Search pattern '{pattern}': found {len(matches)} matches in {files_searched} files")
98
+
99
+ return {
100
+ "matches": matches,
101
+ "total_matches": len(matches),
102
+ "files_searched": files_searched,
103
+ "search_time_ms": 0, # Would be measured in production
104
+ }
105
+
106
+ except Exception as e:
107
+ logger.error(f"Error searching code: {e}")
108
+ return {"error": str(e), "matches": [], "total_matches": 0}
109
+
110
+
111
+ def get_file_structure(
112
+ workdir: str,
113
+ path: str,
114
+ include_docstrings: bool = True,
115
+ include_signatures: bool = True,
116
+ max_depth: int = 0,
117
+ ) -> Dict[str, Any]:
118
+ """
119
+ Parse and return the structure (AST) of a Python file.
120
+
121
+ Args:
122
+ workdir: Absolute path to task working directory
123
+ path: File path relative to workdir
124
+ include_docstrings: Include docstrings in output
125
+ include_signatures: Include function/method signatures
126
+ max_depth: Maximum nesting depth (0 for unlimited)
127
+
128
+ Returns:
129
+ Dict with classes, functions, imports, and constants
130
+ """
131
+ try:
132
+ file_path = Path(workdir) / path
133
+ if not file_path.is_file():
134
+ return {"error": f"File not found: {path}"}
135
+
136
+ content = file_path.read_text(encoding="utf-8")
137
+ tree = ast.parse(content)
138
+
139
+ structure = {
140
+ "filename": path,
141
+ "imports": [],
142
+ "classes": [],
143
+ "functions": [],
144
+ "constants": [],
145
+ }
146
+
147
+ for node in ast.walk(tree):
148
+ # Extract imports
149
+ if isinstance(node, ast.Import):
150
+ for alias in node.names:
151
+ structure["imports"].append({
152
+ "module": alias.name,
153
+ "items": [alias.asname or alias.name],
154
+ "line_number": node.lineno,
155
+ })
156
+
157
+ elif isinstance(node, ast.ImportFrom):
158
+ items = [alias.name for alias in node.names]
159
+ structure["imports"].append({
160
+ "module": node.module or "",
161
+ "items": items,
162
+ "line_number": node.lineno,
163
+ })
164
+
165
+ # Extract classes
166
+ elif isinstance(node, ast.ClassDef):
167
+ class_info = {
168
+ "name": node.name,
169
+ "line_number": node.lineno,
170
+ "methods": [],
171
+ "attributes": [],
172
+ }
173
+
174
+ if include_docstrings:
175
+ class_info["docstring"] = ast.get_docstring(node)
176
+
177
+ for item in node.body:
178
+ if isinstance(item, ast.FunctionDef):
179
+ class_info["methods"].append({
180
+ "name": item.name,
181
+ "line_number": item.lineno,
182
+ })
183
+
184
+ structure["classes"].append(class_info)
185
+
186
+ # Extract top-level functions
187
+ for node in tree.body:
188
+ if isinstance(node, ast.FunctionDef):
189
+ func_info = {
190
+ "name": node.name,
191
+ "line_number": node.lineno,
192
+ }
193
+
194
+ if include_signatures:
195
+ func_info["parameters"] = [arg.arg for arg in node.args.args]
196
+
197
+ if include_docstrings:
198
+ func_info["docstring"] = ast.get_docstring(node)
199
+
200
+ structure["functions"].append(func_info)
201
+
202
+ logger.info(f"Extracted structure from {path}")
203
+ return structure
204
+
205
+ except SyntaxError as e:
206
+ logger.error(f"Syntax error in {path}: {e}")
207
+ return {"error": f"Syntax error: {e}"}
208
+ except Exception as e:
209
+ logger.error(f"Error getting file structure: {e}")
210
+ return {"error": str(e)}
211
+
212
+
213
+ def run_type_check(
214
+ workdir: str,
215
+ path: str,
216
+ strict: bool = False,
217
+ ignore_missing_imports: bool = True,
218
+ show_error_codes: bool = True,
219
+ max_errors: int = 100,
220
+ ) -> Dict[str, Any]:
221
+ """
222
+ Run static type checking (mypy) on Python files.
223
+
224
+ Args:
225
+ workdir: Absolute path to task working directory
226
+ path: File or directory path relative to workdir
227
+ strict: Enable strict type checking mode
228
+ ignore_missing_imports: Ignore untyped third-party imports
229
+ show_error_codes: Show mypy error codes
230
+ max_errors: Maximum errors to report
231
+
232
+ Returns:
233
+ Dict with type check results and error list
234
+ """
235
+ try:
236
+ check_path = Path(workdir) / path
237
+ if not check_path.exists():
238
+ return {"error": f"Path not found: {path}", "status": "error"}
239
+
240
+ cmd = ["mypy", str(check_path)]
241
+
242
+ if strict:
243
+ cmd.append("--strict")
244
+ if ignore_missing_imports:
245
+ cmd.append("--ignore-missing-imports")
246
+ if show_error_codes:
247
+ cmd.append("--show-error-codes")
248
+
249
+ cmd.extend(["--no-error-summary", f"--max-errors={max_errors}"])
250
+
251
+ result = subprocess.run(
252
+ cmd,
253
+ capture_output=True,
254
+ text=True,
255
+ cwd=workdir,
256
+ timeout=30,
257
+ )
258
+
259
+ # Parse output
260
+ errors = []
261
+ for line in result.stdout.split("\n"):
262
+ if not line.strip():
263
+ continue
264
+
265
+ # mypy output format: file:line:column: error: message [error-code]
266
+ match = re.match(
267
+ r"^([^:]+):(\d+):(\d+): error: (.+)(?:\s+\[([^\]]+)\])?$",
268
+ line
269
+ )
270
+ if match:
271
+ errors.append({
272
+ "file": match.group(1),
273
+ "line": int(match.group(2)),
274
+ "column": int(match.group(3)),
275
+ "message": match.group(4),
276
+ "error_code": match.group(5),
277
+ })
278
+
279
+ status = "success" if result.returncode == 0 else "errors_found"
280
+
281
+ logger.info(f"Type check {path}: {len(errors)} errors, status={status}")
282
+
283
+ return {
284
+ "path": path,
285
+ "status": status,
286
+ "error_count": len(errors),
287
+ "errors": errors,
288
+ "check_time_ms": 0,
289
+ }
290
+
291
+ except subprocess.TimeoutExpired:
292
+ logger.error(f"Type check timeout for {path}")
293
+ return {"error": "Type check timeout", "status": "error"}
294
+ except Exception as e:
295
+ logger.error(f"Error running type check: {e}")
296
+ return {"error": str(e), "status": "error"}
297
+
298
+
299
+ def get_test_coverage(
300
+ workdir: str,
301
+ path: str = ".",
302
+ branch_coverage: bool = False,
303
+ include_missing: bool = True,
304
+ fail_under: int = 0,
305
+ ) -> Dict[str, Any]:
306
+ """
307
+ Analyze test coverage for Python files.
308
+
309
+ Args:
310
+ workdir: Absolute path to task working directory
311
+ path: File or directory path relative to workdir
312
+ branch_coverage: Include branch coverage analysis
313
+ include_missing: Show which lines are not covered
314
+ fail_under: Minimum required coverage percentage
315
+
316
+ Returns:
317
+ Dict with coverage percentage, file breakdown, and statistics
318
+ """
319
+ try:
320
+ cmd = ["coverage", "run", "-m", "pytest", workdir]
321
+
322
+ result = subprocess.run(
323
+ cmd,
324
+ capture_output=True,
325
+ text=True,
326
+ cwd=workdir,
327
+ timeout=60,
328
+ )
329
+
330
+ # Get coverage report
331
+ cmd = ["coverage", "json", "--pretty-print"]
332
+ result = subprocess.run(
333
+ cmd,
334
+ capture_output=True,
335
+ text=True,
336
+ cwd=workdir,
337
+ timeout=30,
338
+ )
339
+
340
+ coverage_data = json.loads(result.stdout)
341
+ total_coverage = coverage_data.get("totals", {}).get("percent_covered", 0)
342
+
343
+ logger.info(f"Coverage for {path}: {total_coverage}%")
344
+
345
+ return {
346
+ "total_coverage": round(total_coverage, 1),
347
+ "files": [],
348
+ "functions": [],
349
+ "status": "covered" if total_coverage >= fail_under else "uncovered",
350
+ "check_time_ms": 0,
351
+ }
352
+
353
+ except Exception as e:
354
+ logger.error(f"Error analyzing coverage: {e}")
355
+ return {"error": str(e), "total_coverage": 0, "status": "error"}
356
+
357
+
358
+ def list_directory(
359
+ workdir: str,
360
+ path: str = ".",
361
+ recursive: bool = True,
362
+ max_depth: int = 0,
363
+ include_hidden: bool = False,
364
+ file_types: str = "all",
365
+ ) -> Dict[str, Any]:
366
+ """
367
+ List files and directories in the task working directory.
368
+
369
+ Args:
370
+ workdir: Absolute path to task working directory
371
+ path: Subdirectory path relative to workdir
372
+ recursive: Include subdirectories recursively
373
+ max_depth: Maximum directory nesting depth (0 for unlimited)
374
+ include_hidden: Include hidden files/folders starting with .
375
+ file_types: Filter by file type ("py", "all", "test", "source")
376
+
377
+ Returns:
378
+ Dict with directory tree, file count, and metadata
379
+ """
380
+ try:
381
+ root_path = Path(workdir) / path
382
+ if not root_path.is_dir():
383
+ return {"error": f"Directory not found: {path}"}
384
+
385
+ def walk_tree(directory: Path, depth: int = 0) -> List[Dict]:
386
+ if max_depth > 0 and depth >= max_depth:
387
+ return []
388
+
389
+ items = []
390
+ try:
391
+ for entry in sorted(directory.iterdir()):
392
+ # Skip hidden files if needed
393
+ if entry.name.startswith(".") and not include_hidden:
394
+ continue
395
+
396
+ # Filter by file type
397
+ if file_types == "py" and entry.is_file() and not entry.suffix == ".py":
398
+ continue
399
+ elif file_types == "test" and entry.is_file() and not entry.name.startswith("test_"):
400
+ continue
401
+
402
+ item = {
403
+ "name": entry.name,
404
+ "type": "directory" if entry.is_dir() else "file",
405
+ "path": str(entry.relative_to(Path(workdir))),
406
+ }
407
+
408
+ if entry.is_file():
409
+ item["size_bytes"] = entry.stat().st_size
410
+ item["is_test"] = entry.name.startswith("test_")
411
+
412
+ if entry.is_dir() and recursive:
413
+ item["contents"] = walk_tree(entry, depth + 1)
414
+
415
+ items.append(item)
416
+ except PermissionError:
417
+ pass
418
+
419
+ return items
420
+
421
+ items = walk_tree(root_path)
422
+
423
+ # Count files
424
+ total_files = sum(1 for entry in root_path.rglob("*") if entry.is_file())
425
+ total_dirs = sum(1 for entry in root_path.rglob("*") if entry.is_dir())
426
+
427
+ logger.info(f"Listed directory {path}: {total_files} files, {total_dirs} directories")
428
+
429
+ return {
430
+ "root_path": path,
431
+ "total_files": total_files,
432
+ "total_directories": total_dirs,
433
+ "items": items,
434
+ "tree_depth": max_depth,
435
+ }
436
+
437
+ except Exception as e:
438
+ logger.error(f"Error listing directory: {e}")
439
+ return {"error": str(e)}
440
+
441
+
442
+ def get_dependencies(
443
+ workdir: str,
444
+ path: str,
445
+ include_stdlib: bool = False,
446
+ include_external: bool = True,
447
+ direction: str = "to",
448
+ depth: int = 1,
449
+ ) -> Dict[str, Any]:
450
+ """
451
+ Extract and analyze Python import dependencies.
452
+
453
+ Args:
454
+ workdir: Absolute path to task working directory
455
+ path: File or directory path relative to workdir
456
+ include_stdlib: Include Python standard library imports
457
+ include_external: Include third-party library imports
458
+ direction: Show imports "to" or "from"
459
+ depth: Maximum depth to follow dependencies
460
+
461
+ Returns:
462
+ Dict with dependency graph, cycles, and unused imports
463
+ """
464
+ try:
465
+ target_path = Path(workdir) / path
466
+ if not target_path.exists():
467
+ return {"error": f"Path not found: {path}"}
468
+
469
+ dependencies = {
470
+ "path": path,
471
+ "direct_dependencies": [],
472
+ "indirect_dependencies": [],
473
+ "circular_dependencies": [],
474
+ "unused_imports": [],
475
+ "dependency_count": 0,
476
+ }
477
+
478
+ # Find Python files to analyze
479
+ if target_path.is_file():
480
+ py_files = [target_path]
481
+ else:
482
+ py_files = list(target_path.rglob("*.py"))
483
+
484
+ # Parse imports from each file
485
+ for py_file in py_files:
486
+ try:
487
+ content = py_file.read_text(encoding="utf-8")
488
+ tree = ast.parse(content)
489
+
490
+ for node in ast.walk(tree):
491
+ if isinstance(node, ast.Import):
492
+ for alias in node.names:
493
+ dependencies["direct_dependencies"].append({
494
+ "module": alias.name,
495
+ "type": "import",
496
+ "line_number": node.lineno,
497
+ "is_local": False,
498
+ })
499
+
500
+ elif isinstance(node, ast.ImportFrom):
501
+ dependencies["direct_dependencies"].append({
502
+ "module": node.module or "",
503
+ "type": "from...import",
504
+ "items": [alias.name for alias in node.names],
505
+ "line_number": node.lineno,
506
+ "is_local": not (node.module and ("." not in node.module)),
507
+ })
508
+
509
+ except (SyntaxError, UnicodeDecodeError):
510
+ continue
511
+
512
+ dependencies["dependency_count"] = len(dependencies["direct_dependencies"])
513
+
514
+ logger.info(f"Analyzed dependencies for {path}: {dependencies['dependency_count']} imports")
515
+
516
+ return dependencies
517
+
518
+ except Exception as e:
519
+ logger.error(f"Error analyzing dependencies: {e}")
520
+ return {"error": str(e)}
debug_env/server/tools/edit_file/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .tool import edit_file
2
+
3
+ __all__ = ["edit_file"]
debug_env/server/tools/edit_file/tool.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ edit_file tool — validates the request, writes the file, then re-runs tests.
3
+ """
4
+
5
+ import logging
6
+
7
+ from pydantic import ValidationError
8
+
9
+ from debug_env.server.schemas import EditFileArgs, ToolResult
10
+ from debug_env.server.tools.run_tests import run_tests
11
+ from debug_env.server.utils import validate_workdir_path
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def edit_file(workdir: str, path: str, content: str) -> ToolResult:
17
+ """
18
+ Overwrite *path* (relative to *workdir*) with *content*, then run tests.
19
+
20
+ Args:
21
+ workdir: Absolute path to the task working directory.
22
+ path: Filename to edit, e.g. ``"broken_code.py"`` or ``"helper.py"``.
23
+ content: Complete new file content.
24
+
25
+ Returns:
26
+ :class:`ToolResult` with ``pass_rate`` and ``logs``.
27
+ """
28
+ try:
29
+ args = EditFileArgs(path=path, content=content)
30
+ except ValidationError as e:
31
+ messages = [f"{' -> '.join(str(loc) for loc in err['loc'])}: {err['msg']}" for err in e.errors()]
32
+ msg = "Invalid edit_file args — " + "; ".join(messages)
33
+ logger.warning(msg)
34
+ return ToolResult(pass_rate=0.0, logs=msg, success=False)
35
+
36
+ try:
37
+ full_path = validate_workdir_path(workdir, args.path)
38
+ except ValueError as e:
39
+ logger.warning(str(e))
40
+ return ToolResult(pass_rate=0.0, logs=str(e), success=False)
41
+
42
+ logger.info(f"Editing file: {full_path}")
43
+
44
+ try:
45
+ with open(full_path, "w") as f:
46
+ f.write(args.content)
47
+ logger.info(f"File written ({len(args.content)} chars) — running tests")
48
+ except OSError as e:
49
+ msg = f"Failed to write '{args.path}': {e}"
50
+ logger.error(msg)
51
+ return ToolResult(pass_rate=0.0, logs=msg, success=False)
52
+
53
+ return run_tests(workdir)
debug_env/server/tools/read_file/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .tool import read_file
2
+
3
+ __all__ = ["read_file"]
debug_env/server/tools/read_file/tool.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ read_file tool — returns the current content of a file in the task workdir.
3
+
4
+ Allows the agent to inspect source files before deciding what to edit,
5
+ rather than guessing from test error messages alone.
6
+ """
7
+
8
+ import logging
9
+ import os
10
+
11
+ from pydantic import ValidationError
12
+
13
+ from debug_env.server.schemas import ReadFileArgs, ToolResult
14
+ from debug_env.server.utils import validate_workdir_path
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ def read_file(workdir: str, path: str) -> ToolResult:
20
+ """
21
+ Read *path* (relative to *workdir*) and return its content in ``logs``.
22
+
23
+ Pass rate is preserved from the last test run — reading a file does not
24
+ affect the score. The content is returned in ``logs`` so the agent can
25
+ inspect it in the same observation field it already reads.
26
+
27
+ Args:
28
+ workdir: Absolute path to the task working directory.
29
+ path: Filename to read, e.g. ``"broken_code.py"`` or ``"helper.py"``.
30
+
31
+ Returns:
32
+ :class:`ToolResult` with ``pass_rate=0.0`` and file content in ``logs``.
33
+ """
34
+ try:
35
+ args = ReadFileArgs(path=path)
36
+ except ValidationError as e:
37
+ messages = [f"{' -> '.join(str(loc) for loc in err['loc'])}: {err['msg']}" for err in e.errors()]
38
+ msg = "Invalid read_file args — " + "; ".join(messages)
39
+ logger.warning(msg)
40
+ return ToolResult(pass_rate=0.0, logs=msg, success=False)
41
+
42
+ try:
43
+ full_path = validate_workdir_path(workdir, args.path)
44
+ except ValueError as e:
45
+ logger.warning(str(e))
46
+ return ToolResult(pass_rate=0.0, logs=str(e), success=False)
47
+
48
+ logger.info(f"Reading file: {full_path}")
49
+
50
+ if not os.path.exists(full_path):
51
+ available = [f for f in os.listdir(workdir) if f.endswith(".py") and not f.startswith("test_")]
52
+ msg = (
53
+ f"File '{args.path}' not found. "
54
+ f"Editable source files: {available}"
55
+ )
56
+ logger.warning(msg)
57
+ return ToolResult(pass_rate=0.0, logs=msg, success=False)
58
+
59
+ try:
60
+ with open(full_path) as f:
61
+ content = f.read()
62
+ logger.info(f"Read {len(content)} chars from '{args.path}'")
63
+ return ToolResult(
64
+ pass_rate=0.0,
65
+ logs=f"# {args.path}\n{content}",
66
+ success=True,
67
+ )
68
+ except OSError as e:
69
+ msg = f"Failed to read '{args.path}': {e}"
70
+ logger.error(msg)
71
+ return ToolResult(pass_rate=0.0, logs=msg, success=False)
debug_env/server/tools/run_tests/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .tool import run_tests
2
+
3
+ __all__ = ["run_tests"]
debug_env/server/tools/run_tests/tool.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ run_tests tool — executes pytest inside the task workdir and returns a ToolResult.
3
+ """
4
+
5
+ import logging
6
+ import re
7
+ import subprocess
8
+
9
+ from debug_env.server.schemas import ToolResult
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def _parse_pass_rate(output: str, returncode: int) -> float:
15
+ passed_match = re.search(r"(\d+) passed", output)
16
+ failed_match = re.search(r"(\d+) failed", output)
17
+ error_match = re.search(r"(\d+) error", output)
18
+
19
+ passed = int(passed_match.group(1)) if passed_match else 0
20
+ failed = int(failed_match.group(1)) if failed_match else 0
21
+ errors = int(error_match.group(1)) if error_match else 0
22
+
23
+ total = passed + failed + errors
24
+ if total > 0:
25
+ return passed / total
26
+ return 1.0 if returncode == 0 else 0.0
27
+
28
+
29
+ def run_tests(workdir: str) -> ToolResult:
30
+ """
31
+ Run ``pytest -q --tb=short`` inside *workdir*.
32
+
33
+ Args:
34
+ workdir: Absolute path to the task working directory.
35
+
36
+ Returns:
37
+ :class:`ToolResult` with ``pass_rate`` and ``logs``.
38
+ """
39
+ logger.info(f"Running tests in: {workdir}")
40
+
41
+ try:
42
+ result = subprocess.run(
43
+ ["pytest", "-q", "--tb=short", workdir],
44
+ capture_output=True,
45
+ text=True,
46
+ cwd=workdir,
47
+ )
48
+ output = result.stdout + result.stderr
49
+ pass_rate = _parse_pass_rate(output, result.returncode)
50
+
51
+ logger.info(f"Tests complete — pass_rate={pass_rate:.2f} (returncode={result.returncode})")
52
+
53
+ return ToolResult(pass_rate=pass_rate, logs=output, success=True)
54
+
55
+ except FileNotFoundError:
56
+ msg = "pytest not found. Ensure it is installed in the environment."
57
+ logger.error(msg)
58
+ return ToolResult(pass_rate=0.0, logs=msg, success=False)
59
+
60
+ except Exception as e:
61
+ msg = f"Unexpected error running tests: {e}"
62
+ logger.error(msg, exc_info=True)
63
+ return ToolResult(pass_rate=0.0, logs=msg, success=False)
debug_env/server/tools/tool_handlers.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP Tool Handlers — Generic dispatcher for debug_env analysis tools.
3
+
4
+ This module provides a generic handler that dynamically executes MCP tools
5
+ based on tool configuration, eliminating per-tool if/elif chains and enabling
6
+ scalable tool dispatch.
7
+
8
+ Pattern inspired by calendar_env's tool_handlers.py generic executor.
9
+ """
10
+
11
+ import logging
12
+ from typing import Dict, Any, Callable
13
+
14
+ from debug_env.server.tools.advanced_tools import (
15
+ search_code,
16
+ get_file_structure,
17
+ run_type_check,
18
+ get_test_coverage,
19
+ list_directory,
20
+ get_dependencies,
21
+ )
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # Mapping of tool names to their implementation functions
26
+ # Each function signature: func(workdir: str, **kwargs) -> ToolResult
27
+ TOOL_IMPLEMENTATIONS: Dict[str, Callable[[str], Any]] = {
28
+ "search_code": search_code,
29
+ "get_file_structure": get_file_structure,
30
+ "run_type_check": run_type_check,
31
+ "get_test_coverage": get_test_coverage,
32
+ "list_directory": list_directory,
33
+ "get_dependencies": get_dependencies,
34
+ }
35
+
36
+ # Lazy-loaded caches to avoid circular imports
37
+ _MCP_TOOLS_LIST = None
38
+ _TOOL_HANDLERS = None
39
+
40
+
41
+ def get_mcp_tools_list():
42
+ """Get MCP tool definitions (lazy-loaded to avoid circular imports)."""
43
+ global _MCP_TOOLS_LIST
44
+ if _MCP_TOOLS_LIST is None:
45
+ from debug_env.server.mcp.tools.debug_tools import DEBUG_TOOLS
46
+ _MCP_TOOLS_LIST = DEBUG_TOOLS
47
+ return _MCP_TOOLS_LIST
48
+
49
+
50
+ def get_tool_handlers():
51
+ """Get tool handlers dict (lazy-loaded to avoid circular imports)."""
52
+ global _TOOL_HANDLERS
53
+ if _TOOL_HANDLERS is None:
54
+ tools = get_mcp_tools_list()
55
+ _TOOL_HANDLERS = {tool["name"]: execute_tool_generic for tool in tools}
56
+ return _TOOL_HANDLERS
57
+
58
+
59
+ # Convenience aliases for backward compatibility
60
+ def __getattr__(name):
61
+ """Module-level __getattr__ for lazy loading."""
62
+ if name == "MCP_TOOLS_LIST":
63
+ return get_mcp_tools_list()
64
+ elif name == "TOOL_HANDLERS":
65
+ return get_tool_handlers()
66
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
67
+
68
+
69
+ async def execute_tool_generic(
70
+ tool_name: str, arguments: Dict[str, Any], workdir: str
71
+ ) -> Dict[str, Any]:
72
+ """
73
+ Generic tool executor that dispatches to the appropriate tool function.
74
+
75
+ This replaces per-tool handlers and allows any tool to be executed
76
+ by looking up its implementation in TOOL_IMPLEMENTATIONS.
77
+
78
+ Args:
79
+ tool_name: Name of the tool (e.g., "search_code")
80
+ arguments: Tool arguments from MCP request
81
+ workdir: Working directory for the episode (task files location)
82
+
83
+ Returns:
84
+ Dict with "text" (result or error message) and "isError" (bool)
85
+ """
86
+ try:
87
+ # Find tool implementation
88
+ if tool_name not in TOOL_IMPLEMENTATIONS:
89
+ logger.error(f"Unknown tool: {tool_name}")
90
+ return {
91
+ "text": f"Unknown tool: {tool_name}",
92
+ "isError": True,
93
+ }
94
+
95
+ tool_func = TOOL_IMPLEMENTATIONS[tool_name]
96
+
97
+ logger.debug(f"Executing tool {tool_name} with arguments: {arguments}")
98
+
99
+ # Call the tool function with workdir and arguments
100
+ # Tool functions have signature: func(workdir: str, **kwargs) -> ToolResult
101
+ result = tool_func(workdir, **arguments)
102
+
103
+ # Tool functions return ToolResult with 'logs' field containing output
104
+ # Check if result is an error based on logs content
105
+ is_error = "error" in result.logs.lower() or result.logs.startswith("Error")
106
+
107
+ return {
108
+ "text": result.logs,
109
+ "isError": is_error,
110
+ }
111
+
112
+ except TypeError as e:
113
+ logger.error(f"Missing required argument for {tool_name}: {e}")
114
+ return {
115
+ "text": f"Missing required argument: {e}",
116
+ "isError": True,
117
+ }
118
+ except ValueError as e:
119
+ logger.error(f"Invalid argument for {tool_name}: {e}")
120
+ return {
121
+ "text": f"Invalid argument: {e}",
122
+ "isError": True,
123
+ }
124
+ except Exception as e:
125
+ logger.error(f"Error executing {tool_name}: {e}")
126
+ return {
127
+ "text": f"Tool execution failed: {str(e)}",
128
+ "isError": True,
129
+ }
debug_env/server/utils/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .validation import validate_workdir_path
2
+
3
+ __all__ = ["validate_workdir_path"]
debug_env/server/utils/validation.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Common validation utilities shared across tool handlers.
3
+ """
4
+
5
+ import os
6
+
7
+
8
+ def validate_workdir_path(workdir: str, path: str) -> str:
9
+ """
10
+ Resolve *path* against *workdir* and verify it stays inside the workdir.
11
+
12
+ Args:
13
+ workdir: Absolute path to the task working directory.
14
+ path: Relative filename from the agent (e.g. ``"broken_code.py"``).
15
+
16
+ Returns:
17
+ The resolved absolute path.
18
+
19
+ Raises:
20
+ ValueError: If the resolved path escapes the workdir boundary.
21
+ """
22
+ resolved = os.path.realpath(os.path.join(workdir, path))
23
+ workdir_real = os.path.realpath(workdir)
24
+
25
+ if not resolved.startswith(workdir_real + os.sep) and resolved != workdir_real:
26
+ raise ValueError(
27
+ f"Path '{path}' resolves outside the task workdir — access denied."
28
+ )
29
+
30
+ return resolved
debug_env/tasks/task1/broken_code.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ def add(a, b):
2
+ return a + b
3
+
4
+ def multiply(a, b):
5
+ return a * b
debug_env/tasks/task1/test_code.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from broken_code import add, multiply
2
+
3
+
4
+ def test_add():
5
+ assert add(1, 2) == 3
6
+ assert add(0, 0) == 0
7
+ assert add(-1, 1) == 0
8
+
9
+
10
+ def test_multiply():
11
+ assert multiply(3, 4) == 12
12
+ assert multiply(0, 5) == 0
13
+ assert multiply(-2, 3) == -6