diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e41b4d54c7fb45aeab0c7de0fe2e27440acfd284 --- /dev/null +++ b/.gitignore @@ -0,0 +1,75 @@ +# Planning docs and txt files +planning/ + +# AI tool rules / instruction files +CLAUDE.md +AGENTS.md +GEMINI.md +QUICKSTART.md +COMPETITION_CHECKLIST.md +IMPLEMENTATION_SUMMARY.md +TECHNOLOGY_INTEGRATION.md +.cursorrules +.windsurfrules +.mcp.json +.opencode.json +.claude/ +.cursor/ + +# Python +__pycache__/ +*.py[cod] +*.pyo +*.pyd +*.so +*.egg +*.egg-info/ +dist/ +build/ +.eggs/ + +# Virtual environments +.venv/ +venv/ +env/ + +# pytest +.pytest_cache/ +.coverage +htmlcov/ + +# uv +uv.lock + +# Environment variables +.env +.env.* + +# Temp task workdirs (created at runtime by the environment) +/tmp/debug_task_*/ + +# OS +.DS_Store +Thumbs.db + +# IDEs +.vscode/ +.idea/ +*.iml + +# code-review-graph generated files +.code-review-graph/ +.code-review-graphignore + +# Results/output files generated during runs +results_*.json + +# Runtime databases +debug_env/server/*.db +debug_env/server/*.db-shm +debug_env/server/*.db-wal +*.sqlite +*.sqlite3 + +# Claude Code local settings +.claude/settings.local.json diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..53bf04ddc4ee17e8ee8d2b62e63841c788598826 --- /dev/null +++ b/README.md @@ -0,0 +1,764 @@ +--- +title: Debug Env - AI Debugging Benchmark +emoji: 🐛 +colorFrom: blue +colorTo: indigo +sdk: docker +pinned: true +app_port: 8000 +base_path: /web +tags: + - openenv + - debugging + - benchmark + - ai-agents +--- + +# Debug Env — Production-Grade AI Debugging Benchmark + +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. + +**Live Demo**: [debug-env.hf.space](https://debug-env.hf.space) + +--- + +## Table of Contents + +- [Overview](#overview) +- [Key Features](#key-features) +- [Quick Start](#quick-start) +- [Installation](#installation) +- [Usage](#usage) +- [Architecture](#architecture) +- [Deployment](#deployment) + - [Docker](#docker) + - [Hugging Face Spaces](#hugging-face-spaces) +- [API Reference](#api-reference) +- [Tasks](#tasks) +- [MCP Tools](#mcp-tools) +- [Database](#database) +- [Development](#development) +- [Contributing](#contributing) +- [License](#license) + +--- + +## Overview + +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. + +**Built with:** +- FastAPI + Uvicorn (HTTP server) +- SQLAlchemy (ORM) + SQLite (persistence) +- OpenEnv (environment framework) +- MCP Protocol 2024-11-05 (tool interface) +- Docker (containerization) +- Hugging Face (model integration & hosting) + +--- + +## Key Features + +| Feature | Details | +|---------|---------| +| **9 Tasks** | From syntax errors to architecture refactoring | +| **9 MCP Tools** | 3 core + 6 advanced analysis tools | +| **Episode Tracking** | Full task lifecycle with status & metrics | +| **Pagination** | Base64 offset tokens + sync tokens | +| **Multi-User Ready** | User-scoped operations, role-based framework | +| **Production Architecture** | FastAPI, SQLAlchemy, SQLite | +| **Generic Tool Dispatch** | Scalable MCP handler pattern | +| **Docker Ready** | Dockerfile + docker-compose.yml included | +| **HF Integration** | Spaces-compatible, model inference ready | +| **Comprehensive Docs** | Google Calendar API v3-style specs | + +--- + +## Quick Start + +### Via Docker (Recommended) + +```bash +# Clone repository +git clone https://github.com/yourorg/debug-env +cd debug-env + +# Build and run with Docker Compose +docker-compose up --build + +# Server runs at http://localhost:8000 +``` + +### Via Python (Local Development) + +```bash +# Prerequisites: Python 3.10+, uv package manager +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Clone and install +git clone https://github.com/yourorg/debug-env +cd debug-env +uv sync + +# Initialize database +python -c "from debug_env.server.database.db import init_db; init_db()" + +# Run server +uv run server --port 8000 +``` + +### Verify Installation + +```bash +# Check health endpoint +curl http://localhost:8000/health + +# Response: +# {"status":"healthy","service":"debug-env"} +``` + +--- + +## Installation + +### Requirements + +- **Python**: 3.10 or higher +- **Docker**: (optional) For containerized deployment +- **Disk Space**: ~500MB (including dependencies) +- **RAM**: 2GB minimum (4GB recommended) + +### Option 1: Docker (Recommended for Deployment) + +```bash +docker build -t debug-env:latest . +docker run -p 8000:8000 debug-env:latest +``` + +### Option 2: Local Development + +```bash +# Install uv (fast Python package manager) +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Create virtual environment and install +uv sync + +# Initialize database +uv run python -c "from debug_env.server.database.db import init_db; init_db()" + +# Run development server +uv run server --reload +``` + +### Option 3: Hugging Face Spaces + +Click the "Duplicate" button on the [Hugging Face Space](https://huggingface.co/spaces/yourorg/debug-env) to deploy your own instance. + +--- + +## Usage + +### Web Interface + +Visit `http://localhost:8000` to access: +- **Dashboard**: Environment state, reset/step UI +- **Task Browser**: View all 9 tasks and their metadata +- **Episode Tracker**: Track task runs and performance + +### Python API (Client) + +```python +from debug_env import DebugEnvironment, DebugAction + +# Create environment +env = DebugEnvironment() + +# Select task +obs = env.reset(task="task1") +print(f"Task: {env.current_task}") +print(f"Workdir: {env.workdir}") + +# Read a file +obs = env.step(DebugAction(tool="read_file", args={"path": "broken_code.py"})) +print(obs.logs) + +# Edit the file +obs = env.step(DebugAction(tool="edit_file", args={ + "path": "broken_code.py", + "content": "fixed_code_here" +})) + +print(f"Pass Rate: {obs.pass_rate}") +print(f"Done: {obs.done}") +print(f"Reward: {obs.reward}") +``` + +### MCP Interface (Claude, etc.) + +```bash +# Initialize connection +curl -X POST http://localhost:8000/mcp \ + -H "Content-Type: application/json" \ + -d '{ + "jsonrpc": "2.0", + "method": "initialize", + "params": {"meta": {"task": "task1"}}, + "id": 1 + }' + +# List available tools +curl -X POST http://localhost:8000/mcp \ + -H "Content-Type: application/json" \ + -d '{ + "jsonrpc": "2.0", + "method": "tools/list", + "id": 2 + }' + +# Call a tool (search_code) +curl -X POST http://localhost:8000/mcp \ + -H "Content-Type: application/json" \ + -d '{ + "jsonrpc": "2.0", + "method": "tools/call", + "params": { + "name": "search_code", + "arguments": {"pattern": "def .*bug", "file_types": "py"} + }, + "id": 3 + }' +``` + +### REST API (HTTP) + +```bash +# List tasks with pagination +curl "http://localhost:8000/tasks?maxResults=5" + +# Get single task +curl "http://localhost:8000/tasks/task1" + +# Create episode +curl -X POST "http://localhost:8000/tasks/task1/episodes" + +# Update episode status +curl -X PATCH "http://localhost:8000/tasks/task1/episodes/{episode_id}" \ + -H "Content-Type: application/json" \ + -d '{"status": "passed", "pass_rate": 1.0}' +``` + +--- + +## Architecture + +### System Design + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Client Layer │ +│ ┌──────────────┬──────────────┬──────────────┐ │ +│ │ Web UI │ MCP Client │ REST API │ │ +│ └──────────────┴──────────────┴──────────────┘ │ +└────────────────────┬────────────────────────────────────────┘ + │ +┌────────────────────────────────────────────────────────────┐ +│ FastAPI Server │ +│ ┌────────────────────────────────────────────────────┐ │ +│ │ OpenEnv HTTP Server │ │ +│ │ POST /reset POST /step GET /state WS /ws │ │ +│ └────────────────────────────────────────────────────┘ │ +│ ┌──────────────┬────────────┬──────────────────┐ │ +│ │ Core APIs │ Task APIs │ MCP Router │ │ +│ │ /health │ /tasks │ POST /mcp │ │ +│ └──────────────┴────────────┴──────────────────┘ │ +└─────────┬──────────────────────────────────┬────────────────┘ + │ │ + ┌────▼──────────────────┐ ┌──────▼──────────┐ + │ DebugEnvironment │ │ Database Layer │ + │ ├─ reset(task) │ │ ├─ TaskManager │ + │ ├─ step(action) │ │ ├─ Models │ + │ └─ TaskLoader │ │ └─ Schemas │ + └────────┬───────────────┘ └──────┬──────────┘ + │ │ + ┌────▼──────────────┐ ┌──────▼──────────┐ + │ Tool Execution │ │ SQLite DB │ + │ ├─ run_tests │ │ ├─ Tasks │ + │ ├─ read_file │ │ ├─ Episodes │ + │ ├─ edit_file │ │ └─ Channels │ + │ ├─ search_code │ └─────────────────┘ + │ ├─ get_coverage │ + │ └─ (6 more) │ + └───────────────────┘ +``` + +### Directory Structure + +``` +debug-env/ +├── debug_env/ +│ ├── __init__.py +│ ├── models.py # DebugAction, DebugObservation +│ ├── client.py # DebugEnv client class +│ │ +│ ├── server/ +│ │ ├── app.py # FastAPI app creation +│ │ ├── debug_env_environment.py # Core DebugEnvironment +│ │ ├── grader.py # Reward calculation +│ │ │ +│ │ ├── core/ +│ │ │ └── apis.py # Health check endpoint +│ │ │ +│ │ ├── database/ # NEW: Database layer +│ │ │ ├── db.py # SQLAlchemy setup +│ │ │ ├── models/ +│ │ │ │ └── task.py # ORM models +│ │ │ └── managers/ +│ │ │ └── task_manager.py # TaskManager class +│ │ │ +│ │ ├── handlers/ +│ │ │ └── mcp_handler.py # MCP JSON-RPC dispatcher +│ │ │ +│ │ ├── mcp/ +│ │ │ ├── router.py # MCP endpoint +│ │ │ └── tools/ +│ │ │ └── debug_tools.py # Tool definitions +│ │ │ +│ │ ├── schemas/ +│ │ │ ├── tool_schemas.py # Tool I/O schemas +│ │ │ └── task_schemas.py # Task/Episode schemas +│ │ │ +│ │ ├── tasks/ +│ │ │ ├── data.py # Task registry +│ │ │ ├── loader.py # File staging +│ │ │ └── router.py # Task endpoints +│ │ │ +│ │ ├── tools/ +│ │ │ ├── advanced_tools.py # 6 analysis tools +│ │ │ ├── tool_handlers.py # Generic dispatcher +│ │ │ ├── run_tests/ +│ │ │ ├── read_file/ +│ │ │ └── edit_file/ +│ │ │ +│ │ └── utils/ +│ │ └── validation.py # Security checks +│ │ +│ ├── tasks/ # Task seed data +│ │ ├── task1/ → task9/ # 9 tasks +│ │ └── [seed_data.py files] +│ │ +│ └── data/ +│ └── multi_user_sample.py # User/role models +│ +├── tests/ # Test suite +│ ├── test_tasks.py +│ ├── test_tools.py +│ └── test_database.py +│ +├── Dockerfile # Container definition +├── docker-compose.yml # Multi-container setup +├── pyproject.toml # Dependencies +├── README.md # This file +├── LICENSE # BSD license +└── debug_env.db # SQLite database (created) +``` + +--- + +## Deployment + +### Docker + +#### Dockerfile + +```dockerfile +FROM python:3.11-slim + +WORKDIR /app + +# Install dependencies +RUN apt-get update && apt-get install -y \ + gcc \ + && rm -rf /var/lib/apt/lists/* + +# Copy project +COPY . . + +# Install Python dependencies +RUN pip install --no-cache-dir -e . + +# Initialize database +RUN python -c "from debug_env.server.database.db import init_db; init_db()" + +# Expose port +EXPOSE 8000 + +# Run server +CMD ["python", "-m", "debug_env.server.app"] +``` + +#### Docker Compose + +```yaml +version: '3.8' + +services: + debug-env: + build: . + ports: + - "8000:8000" + volumes: + - ./debug_env:/app/debug_env + - ./debug_env.db:/app/debug_env.db + environment: + - PYTHONUNBUFFERED=1 + - LOG_LEVEL=INFO + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8000/health"] + interval: 10s + timeout: 5s + retries: 3 + + # Optional: Nginx reverse proxy + nginx: + image: nginx:latest + ports: + - "80:80" + volumes: + - ./nginx.conf:/etc/nginx/nginx.conf + depends_on: + - debug-env +``` + +#### Build and Deploy + +```bash +# Build image +docker build -t debug-env:v1.0.0 . + +# Run container +docker run -p 8000:8000 \ + -v $(pwd)/debug_env.db:/app/debug_env.db \ + debug-env:v1.0.0 + +# With Docker Compose +docker-compose up -d + +# View logs +docker-compose logs -f debug-env +``` + +### Hugging Face Spaces + +#### Setup + +1. Go to [Hugging Face Spaces](https://huggingface.co/spaces) +2. Click **"Create new Space"** +3. Choose **"Docker"** as the SDK +4. Configure: + - **Owner**: Your organization + - **Space name**: `debug-env` + - **Visibility**: Public (for demo) or Private (for testing) + - **Persistent Storage**: Enable (for SQLite DB) + - **Hardware**: CPU (free) or GPU + +#### Configuration + +Create `app_config.json`: + +```json +{ + "title": "Debug Env Benchmark", + "description": "AI Debugging Benchmark", + "emoji": "🐛", + "colorFrom": "blue", + "colorTo": "indigo", + "sdk": "docker", + "app_port": 8000, + "base_path": "/web", + "persistentStorage": { + "enabled": true, + "mountPath": "/app/data" + }, + "tags": ["openenv", "debugging", "benchmark"] +} +``` + +#### Deploy + +```bash +# Push to Hugging Face +git push https://huggingface.co/spaces/yourorg/debug-env main + +# Spaces automatically builds and deploys +# Access at: https://yourorg-debug-env.hf.space +``` + +#### Integration with HF Hub + +```python +from huggingface_hub import InferenceClient + +client = InferenceClient( + model="yourorg/debug-env", + token="hf_xxxxx" +) + +# Make inference calls +result = client.post( + json={"task": "task1", "tool": "search_code", "pattern": "bug"} +) +``` + +--- + +## API Reference + +### REST Endpoints + +#### Health Check +``` +GET /health +Response: {"status": "healthy", "service": "debug-env"} +``` + +#### Task Management + +``` +GET /tasks?maxResults=50&pageToken=&syncToken= +Response: { + "etag": "...", + "items": [{id, title, description, files, tools, ...}], + "nextPageToken": "...", + "nextSyncToken": "..." +} + +GET /tasks/{taskId} +Response: {id, title, description, difficulty, bug_type, files, tools, ...} + +GET /tasks/{taskId}/files +Response: ["broken_code.py", "helper.py"] + +GET /tasks/{taskId}/files/{filename} +Response: {task_id, filename, content} +``` + +#### Episode Management + +``` +POST /tasks/{taskId}/episodes +Response: {id, task_id, status: "active", workdir, etag, created_at, ...} + +GET /tasks/{taskId}/episodes?maxResults=50&pageToken= +Response: {items: [...], nextPageToken: "..."} + +GET /tasks/{taskId}/episodes/{episodeId} +Response: {id, task_id, status, pass_rate, workdir, etag, ...} + +PATCH /tasks/{taskId}/episodes/{episodeId} +Body: {status?: "passed"|"failed"|"abandoned", pass_rate?: 0.0-1.0} +Response: {id, task_id, status, pass_rate, ...} +``` + +### MCP Tools + +#### Core Tools (3) + +**1. `run_tests`** — Execute pytest suite +```json +{"name": "run_tests", "inputSchema": {"type": "object", "properties": {}}} +``` +Returns: `pass_rate` (0.0-1.0), `logs`, `reward`, `done` + +**2. `read_file`** — Read file from workdir +```json +{ + "name": "read_file", + "inputSchema": { + "type": "object", + "properties": {"path": {"type": "string"}}, + "required": ["path"] + } +} +``` +Returns: `logs` (file content), `success` + +**3. `edit_file`** — Write and test file +```json +{ + "name": "edit_file", + "inputSchema": { + "type": "object", + "properties": { + "path": {"type": "string"}, + "content": {"type": "string"} + }, + "required": ["path", "content"] + } +} +``` +Returns: `pass_rate`, `logs`, `reward`, `done` + +#### Advanced Tools (6) + +**4. `search_code`** — Pattern matching with ripgrep +```json +{ + "name": "search_code", + "inputSchema": { + "properties": { + "pattern": {"type": "string", "minLength": 1, "maxLength": 500}, + "file_types": {"enum": ["py", "all", "txt", "json", "md"]}, + "max_results": {"type": "integer", "minimum": 1, "maximum": 500} + }, + "required": ["pattern"] + } +} +``` + +**5. `get_file_structure`** — AST-based code structure +**6. `run_type_check`** — Mypy static analysis +**7. `get_test_coverage`** — Coverage.py metrics +**8. `list_directory`** — Recursive directory listing +**9. `get_dependencies`** — Import analysis + +--- + +## Tasks + +| # | Task | Difficulty | Type | Description | +|---|------|-----------|------|-------------| +| 1 | Syntax Error | Easy | Bug Fix | Fix Python syntax preventing import | +| 2 | Logic Error | Medium | Bug Fix | Fix boolean expression logic | +| 3 | Multi-file Bug | Hard | Bug Fix | Fix bug across multiple modules | +| 4 | Type Errors | Medium | Type Check | Fix mypy type annotation errors | +| 5 | Code Quality | Medium | Cleanup | Remove unused imports/dead code | +| 6 | Architecture | Hard | Refactoring | Multi-file refactoring with circular imports | +| 7 | Code Review | Medium | Collab | Junior submits, senior reviews | +| 8 | Bug Investigation | Hard | Collab | QA reports, team investigates | +| 9 | Team Refactoring | Hard | Collab | Multi-user architecture fix | + +--- + +## Database + +### Schema + +**task_records** — Task metadata (seeded from registry) +```sql +CREATE TABLE task_records ( + id TEXT PRIMARY KEY, + title TEXT, description TEXT, + difficulty TEXT, bug_type TEXT, + files JSON, tools JSON, + scenario_type TEXT, participants JSON, + etag TEXT, created_at DATETIME, updated_at DATETIME +) +``` + +**episode_records** — Task runs (user episodes) +```sql +CREATE TABLE episode_records ( + id TEXT PRIMARY KEY, + task_id TEXT, user_id TEXT, + workdir TEXT, status TEXT, + pass_rate REAL, + etag TEXT, created_at DATETIME, updated_at DATETIME +) +``` + +**watch_channels** — Webhook subscriptions +```sql +CREATE TABLE watch_channels ( + id TEXT PRIMARY KEY, + task_id TEXT, user_id TEXT, + webhook_address TEXT, webhook_token TEXT, + expires_at DATETIME, is_active BOOLEAN, + created_at DATETIME +) +``` + +--- + +## Development + +### Testing + +```bash +# Run all tests +pytest + +# With coverage +pytest --cov=debug_env + +# Specific test file +pytest tests/test_tasks.py -v +``` + +### Code Quality + +```bash +# Format with Black +black debug_env tests + +# Lint with Ruff +ruff check debug_env tests + +# Type check with Mypy +mypy debug_env +``` + +### Adding Tasks + +1. Create `debug_env/tasks/taskN/seed_data.py` +2. Register in `server/tasks/data.py` +3. Add to `server/tasks/loader.py` +4. Update `pyproject.toml` + +### Adding Tools + +1. Implement in `server/tools/advanced_tools.py` +2. Add spec to `server/mcp/tools/debug_tools.py` +3. Update `tool_handlers.py` + +--- + +## Contributing + +1. **Fork** the repository +2. **Create branch**: `git checkout -b feature/xyz` +3. **Make changes** with tests +4. **Run tests**: `pytest` +5. **Submit PR** with description + +--- + +## License + +BSD 3-Clause License — See [LICENSE](LICENSE) file + +--- + +## Citation + +```bibtex +@software{debug_env_2026, + title={Debug Env: Production-Grade AI Debugging Benchmark}, + author={Your Organization}, + year={2026}, + url={https://github.com/yourorg/debug-env} +} +``` + +--- + +## Links + +- **GitHub**: https://github.com/yourorg/debug-env +- **OpenEnv**: https://github.com/meta-pytorch/OpenEnv +- **Hugging Face**: https://huggingface.co/spaces/yourorg/debug-env +- **Issues**: https://github.com/yourorg/debug-env/issues + +--- + +**Last Updated**: April 3, 2026 diff --git a/debug_env/README.md b/debug_env/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bdfc5864b34d7ae7679d81ca2676fe6596c6436e --- /dev/null +++ b/debug_env/README.md @@ -0,0 +1,255 @@ +--- +title: Debug Env Environment Server +emoji: 🎽 +colorFrom: green +colorTo: yellow +sdk: docker +pinned: false +app_port: 8000 +base_path: /web +tags: + - openenv +--- + +# Debug Env Environment + +A simple test environment that echoes back messages. Perfect for testing the env APIs as well as demonstrating environment usage patterns. + +## Quick Start + +The simplest way to use the Debug Env environment is through the `DebugEnv` class: + +```python +from debug_env import DebugAction, DebugEnv + +try: + # Create environment from Docker image + debug_envenv = DebugEnv.from_docker_image("debug_env-env:latest") + + # Reset + result = debug_envenv.reset() + print(f"Reset: {result.observation.echoed_message}") + + # Send multiple messages + messages = ["Hello, World!", "Testing echo", "Final message"] + + for msg in messages: + result = debug_envenv.step(DebugAction(message=msg)) + print(f"Sent: '{msg}'") + print(f" → Echoed: '{result.observation.echoed_message}'") + print(f" → Length: {result.observation.message_length}") + print(f" → Reward: {result.reward}") + +finally: + # Always clean up + debug_envenv.close() +``` + +That's it! The `DebugEnv.from_docker_image()` method handles: +- Starting the Docker container +- Waiting for the server to be ready +- Connecting to the environment +- Container cleanup when you call `close()` + +## Building the Docker Image + +Before using the environment, you need to build the Docker image: + +```bash +# From project root +docker build -t debug_env-env:latest -f server/Dockerfile . +``` + +## Deploying to Hugging Face Spaces + +You can easily deploy your OpenEnv environment to Hugging Face Spaces using the `openenv push` command: + +```bash +# From the environment directory (where openenv.yaml is located) +openenv push + +# Or specify options +openenv push --namespace my-org --private +``` + +The `openenv push` command will: +1. Validate that the directory is an OpenEnv environment (checks for `openenv.yaml`) +2. Prepare a custom build for Hugging Face Docker space (enables web interface) +3. Upload to Hugging Face (ensuring you're logged in) + +### Prerequisites + +- Authenticate with Hugging Face: The command will prompt for login if not already authenticated + +### Options + +- `--directory`, `-d`: Directory containing the OpenEnv environment (defaults to current directory) +- `--repo-id`, `-r`: Repository ID in format 'username/repo-name' (defaults to 'username/env-name' from openenv.yaml) +- `--base-image`, `-b`: Base Docker image to use (overrides Dockerfile FROM) +- `--private`: Deploy the space as private (default: public) + +### Examples + +```bash +# Push to your personal namespace (defaults to username/env-name from openenv.yaml) +openenv push + +# Push to a specific repository +openenv push --repo-id my-org/my-env + +# Push with a custom base image +openenv push --base-image ghcr.io/meta-pytorch/openenv-base:latest + +# Push as a private space +openenv push --private + +# Combine options +openenv push --repo-id my-org/my-env --base-image custom-base:latest --private +``` + +After deployment, your space will be available at: +`https://huggingface.co/spaces/` + +The deployed space includes: +- **Web Interface** at `/web` - Interactive UI for exploring the environment +- **API Documentation** at `/docs` - Full OpenAPI/Swagger interface +- **Health Check** at `/health` - Container health monitoring +- **WebSocket** at `/ws` - Persistent session endpoint for low-latency interactions + +## Environment Details + +### Action +**DebugAction**: Contains a single field +- `message` (str) - The message to echo back + +### Observation +**DebugObservation**: Contains the echo response and metadata +- `echoed_message` (str) - The message echoed back +- `message_length` (int) - Length of the message +- `reward` (float) - Reward based on message length (length × 0.1) +- `done` (bool) - Always False for echo environment +- `metadata` (dict) - Additional info like step count + +### Reward +The reward is calculated as: `message_length × 0.1` +- "Hi" → reward: 0.2 +- "Hello, World!" → reward: 1.3 +- Empty message → reward: 0.0 + +## Advanced Usage + +### Connecting to an Existing Server + +If you already have a Debug Env environment server running, you can connect directly: + +```python +from debug_env import DebugEnv + +# Connect to existing server +debug_envenv = DebugEnv(base_url="") + +# Use as normal +result = debug_envenv.reset() +result = debug_envenv.step(DebugAction(message="Hello!")) +``` + +Note: When connecting to an existing server, `debug_envenv.close()` will NOT stop the server. + +### Using the Context Manager + +The client supports context manager usage for automatic connection management: + +```python +from debug_env import DebugAction, DebugEnv + +# Connect with context manager (auto-connects and closes) +with DebugEnv(base_url="http://localhost:8000") as env: + result = env.reset() + print(f"Reset: {result.observation.echoed_message}") + # Multiple steps with low latency + for msg in ["Hello", "World", "!"]: + result = env.step(DebugAction(message=msg)) + print(f"Echoed: {result.observation.echoed_message}") +``` + +The client uses WebSocket connections for: +- **Lower latency**: No HTTP connection overhead per request +- **Persistent session**: Server maintains your environment state +- **Efficient for episodes**: Better for many sequential steps + +### Concurrent WebSocket Sessions + +The server supports multiple concurrent WebSocket connections. To enable this, +modify `server/app.py` to use factory mode: + +```python +# In server/app.py - use factory mode for concurrent sessions +app = create_app( + DebugEnvironment, # Pass class, not instance + DebugAction, + DebugObservation, + max_concurrent_envs=4, # Allow 4 concurrent sessions +) +``` + +Then multiple clients can connect simultaneously: + +```python +from debug_env import DebugAction, DebugEnv +from concurrent.futures import ThreadPoolExecutor + +def run_episode(client_id: int): + with DebugEnv(base_url="http://localhost:8000") as env: + result = env.reset() + for i in range(10): + result = env.step(DebugAction(message=f"Client {client_id}, step {i}")) + return client_id, result.observation.message_length + +# Run 4 episodes concurrently +with ThreadPoolExecutor(max_workers=4) as executor: + results = list(executor.map(run_episode, range(4))) +``` + +## Development & Testing + +### Direct Environment Testing + +Test the environment logic directly without starting the HTTP server: + +```bash +# From the server directory +python3 server/debug_env_environment.py +``` + +This verifies that: +- Environment resets correctly +- Step executes actions properly +- State tracking works +- Rewards are calculated correctly + +### Running Locally + +Run the server locally for development: + +```bash +uvicorn server.app:app --reload +``` + +## Project Structure + +``` +debug_env/ +├── .dockerignore # Docker build exclusions +├── __init__.py # Module exports +├── README.md # This file +├── openenv.yaml # OpenEnv manifest +├── pyproject.toml # Project metadata and dependencies +├── uv.lock # Locked dependencies (generated) +├── client.py # DebugEnv client +├── models.py # Action and Observation models +└── server/ + ├── __init__.py # Server module exports + ├── debug_env_environment.py # Core environment logic + ├── app.py # FastAPI application (HTTP + WebSocket endpoints) + └── Dockerfile # Container image definition +``` diff --git a/debug_env/__init__.py b/debug_env/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b50a036780f42c427dd9c3497225286048b1bba --- /dev/null +++ b/debug_env/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Debug Env Environment.""" + +from .client import DebugEnv +from .models import DebugAction, DebugObservation + +__all__ = [ + "DebugAction", + "DebugObservation", + "DebugEnv", +] diff --git a/debug_env/client.py b/debug_env/client.py new file mode 100644 index 0000000000000000000000000000000000000000..f51fcef8f8df878fd8481d1d940575b0beeb6313 --- /dev/null +++ b/debug_env/client.py @@ -0,0 +1,99 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Debug Env Environment Client.""" + +from typing import Dict + +from openenv.core import EnvClient +from openenv.core.client_types import StepResult +from openenv.core.env_server.types import State + +from .models import DebugAction, DebugObservation + + +class DebugEnv( + EnvClient[DebugAction, DebugObservation, State] +): + """ + Client for the Debug Env Environment. + + This client maintains a persistent WebSocket connection to the environment server, + enabling efficient multi-step interactions with lower latency. + Each client instance has its own dedicated environment session on the server. + + Example: + >>> # Connect to a running server + >>> with DebugEnv(base_url="http://localhost:8000") as client: + ... result = client.reset() + ... print(result.observation.echoed_message) + ... + ... result = client.step(DebugAction(message="Hello!")) + ... print(result.observation.echoed_message) + + Example with Docker: + >>> # Automatically start container and connect + >>> client = DebugEnv.from_docker_image("debug_env-env:latest") + >>> try: + ... result = client.reset() + ... result = client.step(DebugAction(message="Test")) + ... finally: + ... client.close() + """ + + def _step_payload(self, action: DebugAction) -> Dict: + """ + Convert DebugAction to JSON payload for step message. + + Args: + action: DebugAction instance + + Returns: + Dictionary representation suitable for JSON encoding + """ + return { + "message": action.message, + } + + def _parse_result(self, payload: Dict) -> StepResult[DebugObservation]: + """ + Parse server response into StepResult[DebugObservation]. + + Args: + payload: JSON response data from server + + Returns: + StepResult with DebugObservation + """ + obs_data = payload.get("observation", {}) + observation = DebugObservation( + echoed_message=obs_data.get("echoed_message", ""), + message_length=obs_data.get("message_length", 0), + done=payload.get("done", False), + reward=payload.get("reward"), + metadata=obs_data.get("metadata", {}), + ) + + return StepResult( + observation=observation, + reward=payload.get("reward"), + done=payload.get("done", False), + ) + + def _parse_state(self, payload: Dict) -> State: + """ + Parse server response into State object. + + Args: + payload: JSON response from state request + + Returns: + State object with episode_id and step_count + """ + return State( + episode_id=payload.get("episode_id"), + step_count=payload.get("step_count", 0), + ) diff --git a/debug_env/data/__init__.py b/debug_env/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..02eba9b2506ea59b1299f2cb6dbc4d2674632eae --- /dev/null +++ b/debug_env/data/__init__.py @@ -0,0 +1 @@ +"""Data module with sample data and seed files.""" \ No newline at end of file diff --git a/debug_env/data/multi_user_sample.py b/debug_env/data/multi_user_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..4a704de195bcaa096283eb58baa0833671caf26d --- /dev/null +++ b/debug_env/data/multi_user_sample.py @@ -0,0 +1,411 @@ +""" +Multi-User Sample Data for Debug Environment + +Demonstrates collaborative debugging scenarios with multiple users, +roles, and access patterns. +""" + +from datetime import datetime, timedelta +from typing import Any, Dict, List + + +def get_multi_user_sample_data() -> Dict[str, Any]: + """ + Generate multi-user sample data for collaborative debugging scenarios. + + Users: + - alice_senior: Senior developer (can assign, review, approve) + - bob_junior: Junior developer (can fix, needs review) + - carol_qa: QA engineer (reports bugs, verifies fixes) + - dave_lead: Tech lead (oversight, final approval) + + Scenarios: + 1. Code Review Workflow: Junior submits fix, senior reviews + 2. Cross-team Bug Investigation: QA reports, dev investigates, lead coordinates + 3. Collaborative Refactoring: Multiple devs, different responsibilities + """ + return { + "users": get_users(), + "roles": get_roles(), + "permissions": get_permissions(), + "tasks_metadata": get_tasks_metadata(), + "description": "Multi-user collaboration scenarios for debugging benchmark", + } + + +def get_users() -> List[Dict[str, Any]]: + """Get sample users with different roles and permissions.""" + return [ + { + "user_id": "alice_senior", + "name": "Alice Chen", + "role": "Senior Developer", + "email": "alice.chen@company.com", + "experience_level": "senior", + "timezone": "America/New_York", + "created_at": datetime.now().isoformat(), + }, + { + "user_id": "bob_junior", + "name": "Bob Kumar", + "role": "Junior Developer", + "email": "bob.kumar@company.com", + "experience_level": "junior", + "timezone": "America/Los_Angeles", + "created_at": datetime.now().isoformat(), + }, + { + "user_id": "carol_qa", + "name": "Carol Martinez", + "role": "QA Engineer", + "email": "carol.martinez@company.com", + "experience_level": "mid", + "timezone": "America/Chicago", + "created_at": datetime.now().isoformat(), + }, + { + "user_id": "dave_lead", + "name": "Dave Thompson", + "role": "Tech Lead", + "email": "dave.thompson@company.com", + "experience_level": "senior", + "timezone": "America/New_York", + "created_at": datetime.now().isoformat(), + }, + ] + + +def get_roles() -> List[Dict[str, Any]]: + """Get role definitions with permission levels.""" + return [ + { + "role_id": "senior_dev", + "name": "Senior Developer", + "permissions": ["read", "write", "review", "approve", "assign"], + "description": "Can fix bugs, review code, approve changes", + }, + { + "role_id": "junior_dev", + "name": "Junior Developer", + "permissions": ["read", "write", "request_review"], + "description": "Can fix assigned bugs, needs review for approval", + }, + { + "role_id": "qa", + "name": "QA Engineer", + "permissions": ["read", "report", "verify"], + "description": "Can report bugs, verify fixes", + }, + { + "role_id": "tech_lead", + "name": "Tech Lead", + "permissions": ["read", "write", "review", "approve", "assign", "oversight"], + "description": "Overall oversight, assigns work, final approval", + }, + ] + + +def get_permissions() -> List[Dict[str, Any]]: + """Get permission definitions.""" + return [ + { + "permission_id": "read", + "name": "Read Code", + "description": "Can view task code and details", + }, + { + "permission_id": "write", + "name": "Write/Edit", + "description": "Can edit task files and make changes", + }, + { + "permission_id": "review", + "name": "Review Code", + "description": "Can review and comment on changes", + }, + { + "permission_id": "approve", + "name": "Approve", + "description": "Can approve changes for completion", + }, + { + "permission_id": "assign", + "name": "Assign Work", + "description": "Can assign tasks to other users", + }, + { + "permission_id": "report", + "name": "Report Issues", + "description": "Can report new bugs/issues", + }, + { + "permission_id": "verify", + "name": "Verify Fixes", + "description": "Can verify that fixes work correctly", + }, + { + "permission_id": "oversight", + "name": "Oversight", + "description": "Overall visibility and coordination", + }, + ] + + +def get_tasks_metadata() -> List[Dict[str, Any]]: + """Get multi-user task scenarios.""" + base_date = datetime.now() + + return [ + { + "task_id": "task7", + "title": "Code Review Workflow", + "description": "Junior developer submits a fix that needs code review and approval from senior developer", + "difficulty": "medium", + "scenario_type": "code_review", + "participants": [ + { + "user_id": "bob_junior", + "role": "assignee", + "responsibility": "Fix the bug and submit for review", + "status": "in_progress", + }, + { + "user_id": "alice_senior", + "role": "reviewer", + "responsibility": "Review code, provide feedback, approve if acceptable", + "status": "pending", + }, + { + "user_id": "dave_lead", + "role": "observer", + "responsibility": "Oversee process, escalate if needed", + "status": "pending", + }, + ], + "workflow_steps": [ + "Step 1: Bob reads the failing code and tests", + "Step 2: Bob fixes the bug in the code", + "Step 3: Bob runs tests to verify the fix", + "Step 4: Alice reviews Bob's code changes", + "Step 5: Alice checks test coverage and design", + "Step 6: Alice approves and merges the fix", + ], + "expected_issues": [ + "Code doesn't follow team style guidelines", + "Missing test coverage for edge case", + "Incomplete error handling", + ], + "tools_available": [ + "read_file", + "edit_file", + "run_tests", + "search_code", + "get_file_structure", + "run_type_check", + "get_test_coverage", + ], + "created_at": base_date.isoformat(), + "due_date": (base_date + timedelta(days=2)).isoformat(), + }, + { + "task_id": "task8", + "title": "Cross-team Bug Investigation", + "description": "QA reported a complex bug. Dev team needs to investigate, communicate findings, and fix collaboratively", + "difficulty": "hard", + "scenario_type": "cross_team_collaboration", + "participants": [ + { + "user_id": "carol_qa", + "role": "bug_reporter", + "responsibility": "Provide bug details, reproduction steps, verify fix", + "status": "completed", + }, + { + "user_id": "bob_junior", + "role": "investigator", + "responsibility": "Investigate root cause, document findings", + "status": "in_progress", + }, + { + "user_id": "alice_senior", + "role": "problem_solver", + "responsibility": "Propose solution, implement fix, ensure quality", + "status": "pending", + }, + { + "user_id": "dave_lead", + "role": "coordinator", + "responsibility": "Coordinate team, resolve blockers, approve solution", + "status": "pending", + }, + ], + "workflow_steps": [ + "Step 1: Carol (QA) reports bug: 'User profile update fails with invalid email'", + "Step 2: Bob investigates the code path for email validation", + "Step 3: Bob identifies the issue is in validation logic and documents findings", + "Step 4: Alice reviews findings and designs a fix", + "Step 5: Alice implements the fix and adds test coverage", + "Step 6: Bob and Alice code review together", + "Step 7: Carol verifies the fix in the updated code", + "Step 8: Dave approves and coordinates merge", + ], + "bug_description": "User profile update fails with 'invalid email' error even for valid email addresses like 'user+tag@domain.com'", + "root_cause": "Email validation regex too strict, doesn't handle '+' character in local part", + "expected_issues": [ + "Validation logic is in the wrong module", + "Multiple places need the same fix", + "Missing test cases for email formats", + ], + "tools_available": [ + "read_file", + "edit_file", + "run_tests", + "search_code", + "get_file_structure", + "get_dependencies", + "run_type_check", + "get_test_coverage", + ], + "created_at": base_date.isoformat(), + "due_date": (base_date + timedelta(days=3)).isoformat(), + }, + { + "task_id": "task9", + "title": "Collaborative Architecture Refactoring", + "description": "Large refactoring involving multiple modules. Multiple devs contribute different parts, need to stay coordinated", + "difficulty": "hard", + "scenario_type": "team_refactoring", + "participants": [ + { + "user_id": "alice_senior", + "role": "architect", + "responsibility": "Design refactoring strategy, review all changes, ensure consistency", + "status": "in_progress", + }, + { + "user_id": "bob_junior", + "role": "contributor_1", + "responsibility": "Refactor module_a following architecture guidelines", + "status": "in_progress", + }, + { + "user_id": "carol_qa", + "role": "contributor_2", + "responsibility": "Refactor module_b, ensure test compatibility", + "status": "pending", + }, + { + "user_id": "dave_lead", + "role": "integration_lead", + "responsibility": "Coordinate across modules, resolve conflicts, ensure integration", + "status": "pending", + }, + ], + "workflow_steps": [ + "Step 1: Alice designs refactoring architecture and creates shared interface", + "Step 2: Bob starts refactoring module_a to use new interface", + "Step 3: Carol starts refactoring module_b in parallel", + "Step 4: Both check for integration issues with shared interface", + "Step 5: Alice reviews both changes for consistency", + "Step 6: Dave coordinates final integration and merge", + "Step 7: Full test suite runs on integrated changes", + ], + "refactoring_goals": [ + "Break circular dependencies between modules", + "Extract common interface", + "Improve testability through dependency injection", + "Consolidate validation logic", + ], + "modules_involved": ["module_a.py", "module_b.py", "module_c.py", "integration.py"], + "expected_issues": [ + "Integration points between modules are unclear", + "Parallel changes create merge conflicts", + "Some code depends on old interface", + ], + "tools_available": [ + "list_directory", + "read_file", + "edit_file", + "run_tests", + "search_code", + "get_file_structure", + "get_dependencies", + "run_type_check", + "get_test_coverage", + ], + "created_at": base_date.isoformat(), + "due_date": (base_date + timedelta(days=5)).isoformat(), + }, + ] + + +def get_multi_user_sql() -> str: + """Generate SQL for multi-user sample data.""" + data = get_multi_user_sample_data() + sql_statements = [] + + # Header + sql_statements.append("-- Multi-User Debug Environment Sample Data") + sql_statements.append(f"-- Generated on: {datetime.now().isoformat()}") + sql_statements.append("-- Contains collaborative debugging scenarios with multiple users and roles") + sql_statements.append("") + + # Users + sql_statements.append("-- Users") + sql_statements.append( + "INSERT INTO users (user_id, name, role, email, experience_level, timezone, created_at) VALUES" + ) + user_values = [] + for user in data["users"]: + user_values.append( + f"('{user['user_id']}', '{user['name']}', '{user['role']}', " + f"'{user['email']}', '{user['experience_level']}', '{user['timezone']}', " + f"'{user['created_at']}')" + ) + sql_statements.append(",\n".join(user_values) + ";") + sql_statements.append("") + + # Roles + sql_statements.append("-- Roles") + sql_statements.append( + "INSERT INTO roles (role_id, name, description) VALUES" + ) + role_values = [] + for role in data["roles"]: + permissions_str = ",".join(role["permissions"]) + role_values.append( + f"('{role['role_id']}', '{role['name']}', '{role['description']}')" + ) + sql_statements.append(",\n".join(role_values) + ";") + sql_statements.append("") + + # Permissions + sql_statements.append("-- Permissions") + sql_statements.append( + "INSERT INTO permissions (permission_id, name, description) VALUES" + ) + perm_values = [] + for perm in data["permissions"]: + perm_values.append( + f"('{perm['permission_id']}', '{perm['name']}', '{perm['description']}')" + ) + sql_statements.append(",\n".join(perm_values) + ";") + sql_statements.append("") + + # Tasks Metadata + sql_statements.append("-- Task Scenarios") + sql_statements.append( + "INSERT INTO task_scenarios (task_id, title, description, difficulty, scenario_type, created_at, due_date) VALUES" + ) + task_values = [] + for task in data["tasks_metadata"]: + description = task["description"].replace("'", "''") + task_values.append( + f"('{task['task_id']}', '{task['title']}', '{description}', " + f"'{task['difficulty']}', '{task['scenario_type']}', " + f"'{task['created_at']}', '{task['due_date']}')" + ) + sql_statements.append(",\n".join(task_values) + ";") + sql_statements.append("") + + return "\n".join(sql_statements) \ No newline at end of file diff --git a/debug_env/models.py b/debug_env/models.py new file mode 100644 index 0000000000000000000000000000000000000000..4f9282d80a7a47413765a9fd9b757c9cbc9aea17 --- /dev/null +++ b/debug_env/models.py @@ -0,0 +1,10 @@ +from openenv.core.env_server.types import Action, Observation +from pydantic import Field + +class DebugAction(Action): + tool: str = Field(..., description="Tool to use: run_tests, read_file, edit_file") + args: dict = Field(default_factory=dict, description="Arguments for the tool") + +class DebugObservation(Observation): + pass_rate: float = Field(default=0.0, description="Test pass rate (0 to 1)") + logs: str = Field(default="", description="Test output logs") \ No newline at end of file diff --git a/debug_env/openenv.yaml b/debug_env/openenv.yaml new file mode 100644 index 0000000000000000000000000000000000000000..186ce32252ff7f6b77ab3ffc6c27b20ffe325656 --- /dev/null +++ b/debug_env/openenv.yaml @@ -0,0 +1,99 @@ +spec_version: 1 +name: debug_env +type: space +runtime: fastapi +app: server.app:app +port: 8000 +description: > + A real-world debugging environment where LLM agents fix broken Python code. + Tasks range from simple syntax errors to complex logic bugs. Agents use + read_file, edit_file, and run_tests tools to identify and fix issues. + Rewards are based on test pass rate (0.0-1.0). + +author: Meta Platforms, Inc. +version: 0.1.0 + +tasks: + - id: task1 + title: "Fix Simple Syntax Error" + description: > + A Python module with a syntax error in the function definition. + Agent must identify the missing colon and fix the function signature. + difficulty: easy + estimated_steps: 3 + - id: task2 + title: "Fix Logic Bug in Conditional" + description: > + A function with incorrect conditional logic that fails test assertions. + Agent must read tests, understand the expected behavior, and fix the logic. + difficulty: medium + estimated_steps: 5 + - id: task3 + title: "Fix Import and Type Issues" + description: > + Multiple functions with missing imports, type errors, and undefined variables. + Agent must diagnose and fix all issues to pass all tests. + difficulty: hard + estimated_steps: 8 + +action_schema: + type: object + properties: + tool: + type: string + enum: ["run_tests", "read_file", "edit_file"] + description: Name of the tool to execute + args: + type: object + description: Tool-specific arguments + required: ["tool"] + +observation_schema: + type: object + properties: + pass_rate: + type: number + minimum: 0.0 + maximum: 1.0 + description: Fraction of tests passing (0.0-1.0) + logs: + type: string + description: Test output, file content, or execution logs + reward: + type: number + minimum: 0.0 + maximum: 1.0 + description: Reward signal based on pass_rate + done: + type: boolean + description: Whether all tests pass (episode complete) + required: ["pass_rate", "logs"] + +reward_schema: + type: object + properties: + reward: + type: number + minimum: 0.0 + maximum: 1.0 + description: Episode reward based on final pass_rate + done: + type: boolean + description: Whether episode is complete + required: ["reward", "done"] + +performance_metrics: + - pass_rate: Fraction of tests passing + - success_rate: Percentage of runs with full pass (across multiple attempts) + - pass@k: Probability that at least k runs succeed + - avg_steps: Average number of tool calls per successful run + - avg_time_ms: Average execution time per run + +deployment: + huggingface_space: true + dockerfile: ./debug_env/server/Dockerfile + docker_compose: ./docker-compose.yml + health_check: /health + max_runtime_minutes: 20 + min_vcpu: 2 + min_memory_gb: 8 diff --git a/debug_env/pyproject.toml b/debug_env/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..029cf9d7a0c43ca05a53b98d2d63ae20f0cf7c1f --- /dev/null +++ b/debug_env/pyproject.toml @@ -0,0 +1,70 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +[build-system] +requires = ["setuptools>=45", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "openenv-debug_env" +version = "0.1.0" +description = "Debug Env environment for OpenEnv" +requires-python = ">=3.10" +dependencies = [ + # Core OpenEnv runtime (provides FastAPI server + HTTP client types) + # install from github + # "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git", + "openenv-core[core]>=0.2.2", + # Inference / benchmark client dependencies + "httpx>=0.27.0", + "langchain-core>=0.3.0", + "langchain-anthropic>=0.3.0", + "langchain-openai>=0.3.0", + "langchain-google-genai>=2.0.0", + # Database ORM for task persistence and episode tracking + "sqlalchemy>=2.0.0", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.0.0", + "pytest-cov>=4.0.0", +] + +[project.scripts] +# Server entry point - enables running via: uv run --project . server +# or: python -m debug_env.server.app +server = "debug_env.server.app:main" + +[tool.setuptools] +include-package-data = true +packages = [ + "debug_env", + "debug_env.data", + "debug_env.server", + "debug_env.server.core", + "debug_env.server.database", + "debug_env.server.database.managers", + "debug_env.server.database.models", + "debug_env.server.handlers", + "debug_env.server.mcp", + "debug_env.server.mcp.tools", + "debug_env.server.schemas", + "debug_env.server.tools", + "debug_env.server.tools.run_tests", + "debug_env.server.tools.read_file", + "debug_env.server.tools.edit_file", + "debug_env.server.tasks", + "debug_env.server.utils", + "debug_env.tasks", + "debug_env.tasks.task4", + "debug_env.tasks.task5", + "debug_env.tasks.task6", + "debug_env.tasks.task7", + "debug_env.tasks.task8", + "debug_env.tasks.task9", +] +package-dir = { "debug_env" = ".", "debug_env.server" = "server" } \ No newline at end of file diff --git a/debug_env/server/Dockerfile b/debug_env/server/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..693d6c78f678d8831d1cfa7e69b7b2a6e19ab565 --- /dev/null +++ b/debug_env/server/Dockerfile @@ -0,0 +1,80 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# Multi-stage build using openenv-base +# This Dockerfile is flexible and works for both: +# - In-repo environments (with local OpenEnv sources) +# - Standalone environments (with openenv from PyPI/Git) +# The build script (openenv build) handles context detection and sets appropriate build args. + +ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest +FROM ${BASE_IMAGE} AS builder + +WORKDIR /app + +# Ensure git is available (required for installing dependencies from VCS) +RUN apt-get update && \ + apt-get install -y --no-install-recommends git && \ + rm -rf /var/lib/apt/lists/* + +# Build argument to control whether we're building standalone or in-repo +ARG BUILD_MODE=in-repo +ARG ENV_NAME=debug_env + +# Copy environment code (always at root of build context) +COPY . /app/env + +# For in-repo builds, openenv is already vendored in the build context +# For standalone builds, openenv will be installed via pyproject.toml +WORKDIR /app/env + +# Ensure uv is available (for local builds where base image lacks it) +RUN if ! command -v uv >/dev/null 2>&1; then \ + curl -LsSf https://astral.sh/uv/install.sh | sh && \ + mv /root/.local/bin/uv /usr/local/bin/uv && \ + mv /root/.local/bin/uvx /usr/local/bin/uvx; \ + fi + +# Install dependencies using uv sync +# If uv.lock exists, use it; otherwise resolve on the fly +RUN --mount=type=cache,target=/root/.cache/uv \ + if [ -f uv.lock ]; then \ + uv sync --frozen --no-install-project --no-editable; \ + else \ + uv sync --no-install-project --no-editable; \ + fi + +RUN --mount=type=cache,target=/root/.cache/uv \ + if [ -f uv.lock ]; then \ + uv sync --frozen --no-editable; \ + else \ + uv sync --no-editable; \ + fi + +# Final runtime stage +FROM ${BASE_IMAGE} + +WORKDIR /app + +# Copy the virtual environment from builder +COPY --from=builder /app/env/.venv /app/.venv + +# Copy the environment code +COPY --from=builder /app/env /app/env + +# Set PATH to use the virtual environment +ENV PATH="/app/.venv/bin:$PATH" + +# Set PYTHONPATH so imports work correctly +ENV PYTHONPATH="/app/env:$PYTHONPATH" + +# Health check +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD curl -f http://localhost:8000/health || exit 1 + +# Run the FastAPI server +# The module path is constructed to work with the /app/env structure +CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"] diff --git a/debug_env/server/__init__.py b/debug_env/server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b4545ee6ccabf91ef9d8ded7339ce45d9a127bd6 --- /dev/null +++ b/debug_env/server/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Debug Env environment server components.""" + +from .debug_env_environment import DebugEnvironment + +__all__ = ["DebugEnvironment"] diff --git a/debug_env/server/app.py b/debug_env/server/app.py new file mode 100644 index 0000000000000000000000000000000000000000..60e3f4ace3a83f09e957a46348144521b3aed44d --- /dev/null +++ b/debug_env/server/app.py @@ -0,0 +1,104 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +""" +FastAPI application for the Debug Env Environment. + +This module creates an HTTP server that exposes the DebugEnvironment +over HTTP and WebSocket endpoints, compatible with EnvClient. + +Endpoints: + - POST /reset: Reset the environment + - POST /step: Execute an action + - GET /state: Get current environment state + - GET /schema: Get action/observation schemas + - WS /ws: WebSocket endpoint for persistent sessions + +Usage: + # Development (with auto-reload): + uvicorn server.app:app --reload --host 0.0.0.0 --port 8000 + + # Production: + uvicorn server.app:app --host 0.0.0.0 --port 8000 --workers 4 + + # Or run directly: + python -m server.app +""" + +try: + from openenv.core.env_server.http_server import create_app +except Exception as e: # pragma: no cover + raise ImportError( + "openenv is required for the web interface. Install dependencies with '\n uv sync\n'" + ) from e + +try: + from ..models import DebugAction, DebugObservation + from .core.apis import router as core_router + from .debug_env_environment import DebugEnvironment + from .mcp.router import router as mcp_router + from .tasks.router import router as tasks_router + from .database.db import init_db +except ModuleNotFoundError: + from models import DebugAction, DebugObservation + from server.core.apis import router as core_router + from server.debug_env_environment import DebugEnvironment + from server.mcp.router import router as mcp_router + from server.tasks.router import router as tasks_router + from server.database.db import init_db + + +# Create the app with web interface and README integration +app = create_app( + DebugEnvironment, + DebugAction, + DebugObservation, + env_name="debug_env", + max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions +) + +# Register additional routers +app.include_router(core_router) +app.include_router(tasks_router) +app.include_router(mcp_router) + + +# Initialize database on startup +@app.on_event("startup") +async def startup_event(): + """Initialize database and seed task registry on startup.""" + init_db() + + +def main(host: str = "0.0.0.0", port: int = 8000): + """ + Entry point for direct execution via uv run or python -m. + + This function enables running the server without Docker: + uv run --project . server + uv run --project . server --port 8001 + python -m debug_env.server.app + + Args: + host: Host address to bind to (default: "0.0.0.0") + port: Port number to listen on (default: 8000) + + For production deployments, consider using uvicorn directly with + multiple workers: + uvicorn debug_env.server.app:app --workers 4 + """ + import uvicorn + + uvicorn.run(app, host=host, port=port) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--port", type=int, default=8000) + args = parser.parse_args() + main(port=args.port) diff --git a/debug_env/server/core/__init__.py b/debug_env/server/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/debug_env/server/core/apis.py b/debug_env/server/core/apis.py new file mode 100644 index 0000000000000000000000000000000000000000..41a21fb5ae28b04a1d4ed475cd22fa76d439f7c7 --- /dev/null +++ b/debug_env/server/core/apis.py @@ -0,0 +1,22 @@ +""" +Core API endpoints for debug-env. +Handles health checks and service status information. +""" + +import logging + +from fastapi import APIRouter + +logger = logging.getLogger(__name__) + +router = APIRouter(tags=["core"]) + + +@router.get("/health") +async def health_check(): + """ + Health check endpoint for service monitoring. + + Returns basic service status and availability information. + """ + return {"status": "healthy", "service": "debug-env"} \ No newline at end of file diff --git a/debug_env/server/database/__init__.py b/debug_env/server/database/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5a43bc1ae9d0940d5c4c56bec4853c16fceca1ce --- /dev/null +++ b/debug_env/server/database/__init__.py @@ -0,0 +1 @@ +"""Database module for debug_env""" diff --git a/debug_env/server/database/db.py b/debug_env/server/database/db.py new file mode 100644 index 0000000000000000000000000000000000000000..db1eef44b0007720a00a1efbe55477039ba228cd --- /dev/null +++ b/debug_env/server/database/db.py @@ -0,0 +1,110 @@ +""" +Database configuration and session management for debug_env. + +Provides SQLite database engine, session factory, and FastAPI dependency injection. +""" + +import logging +from pathlib import Path + +from sqlalchemy import create_engine +from sqlalchemy.orm import declarative_base, sessionmaker, Session + +logger = logging.getLogger(__name__) + +# Database path: debug_env.db in the server directory +DB_PATH = Path(__file__).parent.parent / "debug_env.db" +DATABASE_URL = f"sqlite:///{DB_PATH}" + +# SQLAlchemy engine +engine = create_engine( + DATABASE_URL, + echo=False, + connect_args={"check_same_thread": False}, # SQLite specific +) + +# Session factory +SessionLocal = sessionmaker( + autocommit=False, + autoflush=False, + bind=engine, +) + +# Declarative base for ORM models +Base = declarative_base() + + +def get_db() -> Session: + """ + FastAPI dependency: yields a database session. + + Usage: + async def my_endpoint(db: Session = Depends(get_db)): + # Use db here + """ + db = SessionLocal() + try: + yield db + finally: + db.close() + + +def init_db() -> None: + """ + Initialize the database: create all tables and seed task registry. + + Called on application startup via @app.on_event("startup"). + """ + # Import models to register them with Base + from debug_env.server.database.models.task import TaskRecord, EpisodeRecord, WatchChannel # noqa: F401 + + # Create all tables + Base.metadata.create_all(bind=engine) + logger.info(f"Database initialized at {DB_PATH}") + + # Seed TASK_REGISTRY into task_records table if not already present + _seed_task_registry() + + +def _seed_task_registry() -> None: + """Seed the task_records table with TASK_REGISTRY on startup.""" + from debug_env.server.database.models.task import TaskRecord + from debug_env.server.tasks.data import TASK_REGISTRY + from datetime import datetime + from uuid import uuid4 + + db = SessionLocal() + try: + # Check if tasks already exist + existing_count = db.query(TaskRecord).count() + if existing_count > 0: + logger.debug(f"Task registry already seeded ({existing_count} tasks)") + return + + # Seed each task from TASK_REGISTRY + now = datetime.utcnow() + for task_id, task_data in TASK_REGISTRY.items(): + task_record = TaskRecord( + id=task_id, + title=task_data.get("title", ""), + description=task_data.get("description", ""), + difficulty=task_data.get("difficulty", ""), + bug_type=task_data.get("bug_type", ""), + files=task_data.get("files", []), + tools=task_data.get("tools"), + scenario_type=task_data.get("scenario_type"), + participants=task_data.get("participants"), + etag=f'"{uuid4()}"', + created_at=now, + updated_at=now, + ) + db.add(task_record) + + db.commit() + logger.info(f"Seeded {len(TASK_REGISTRY)} tasks into database") + except Exception as e: + db.rollback() + logger.error(f"Error seeding task registry: {e}") + raise + finally: + db.close() diff --git a/debug_env/server/database/managers/__init__.py b/debug_env/server/database/managers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fde76cff170426f3dde626d21b3ade57bf754bae --- /dev/null +++ b/debug_env/server/database/managers/__init__.py @@ -0,0 +1 @@ +"""Database managers for debug_env""" diff --git a/debug_env/server/database/managers/task_manager.py b/debug_env/server/database/managers/task_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..06d81f428ffaad30d00c2075e7687c607ed0a656 --- /dev/null +++ b/debug_env/server/database/managers/task_manager.py @@ -0,0 +1,451 @@ +""" +Task Manager — Manages task metadata, episodes, and watch channels. + +Follows the ACLManager pattern: class-based CRUD with user scoping, pagination, +sync tokens, and ETags for cache validation. +""" + +import base64 +import json +import logging +from datetime import datetime, timedelta +from typing import Optional, Dict, Any, List +from uuid import uuid4 + +from sqlalchemy import and_, desc, or_ +from sqlalchemy.orm import Session + +from debug_env.server.database.models.task import TaskRecord, EpisodeRecord, WatchChannel + +logger = logging.getLogger(__name__) + + +class TaskManager: + """ + Manages task operations with user-scoped access control. + + Args: + db: SQLAlchemy Session + user_id: User identifier for scoping operations + """ + + def __init__(self, db: Session, user_id: str): + self.db = db + self.user_id = user_id + + def list_tasks( + self, + max_results: int = 50, + page_token: Optional[str] = None, + sync_token: Optional[str] = None, + ) -> "TaskListResponse": + """ + List tasks with pagination and sync token support. + + Args: + max_results: Maximum number of tasks per page (1-250, default 50) + page_token: Pagination token from previous response + sync_token: Sync token for incremental updates + + Returns: + TaskListResponse with items, nextPageToken, nextSyncToken + """ + try: + # Handle sync token for incremental synchronization + if sync_token: + return self._handle_sync_request(sync_token, max_results) + + # Base query: all tasks (not user-scoped) + query = self.db.query(TaskRecord).order_by(TaskRecord.id) + + # Handle pagination with base64 offset token + offset = 0 + if page_token: + try: + offset = int(base64.b64decode(page_token).decode("utf-8")) + except (ValueError, TypeError): + raise ValueError("Invalid pageToken") + + # Get one extra to determine if there's a next page + items = query.offset(offset).limit(max_results + 1).all() + + has_next_page = len(items) > max_results + if has_next_page: + items = items[:max_results] + next_page_token = base64.b64encode( + str(offset + max_results).encode("utf-8") + ).decode("utf-8") + else: + next_page_token = None + + # Generate next sync token based on latest update + latest_updated = ( + self.db.query(TaskRecord.updated_at) + .order_by(desc(TaskRecord.updated_at)) + .first() + ) + + next_sync_token = None + if latest_updated and latest_updated[0]: + sync_data = { + "timestamp": latest_updated[0].isoformat(), + "user_id": self.user_id, + } + next_sync_token = base64.b64encode( + json.dumps(sync_data).encode("utf-8") + ).decode("utf-8") + + # Generate collection etag + etag = f'"{uuid4()}"' + + return TaskListResponse( + etag=etag, + items=items, + nextPageToken=next_page_token, + nextSyncToken=next_sync_token, + ) + + except Exception as e: + logger.error(f"Error listing tasks: {e}") + raise + + def _handle_sync_request( + self, sync_token: str, max_results: int + ) -> "TaskListResponse": + """ + Handle incremental synchronization request. + + Args: + sync_token: Sync token from previous response + max_results: Maximum items to return + + Returns: + TaskListResponse with changes since sync token + """ + try: + # Decode sync token + sync_data = json.loads(base64.b64decode(sync_token).decode("utf-8")) + last_sync_time = datetime.fromisoformat(sync_data["timestamp"]) + + # Check if sync token is too old (7-day expiration) + if (datetime.utcnow() - last_sync_time).days > 7: + raise ValueError("Sync token expired") + + # Query for changes since last sync + query = ( + self.db.query(TaskRecord) + .filter(TaskRecord.updated_at > last_sync_time) + .order_by(TaskRecord.updated_at, TaskRecord.id) + ) + + items = query.limit(max_results + 1).all() + + has_more = len(items) > max_results + if has_more: + items = items[:max_results] + + # Generate new sync token + next_sync_token = None + if items: + latest_time = max(item.updated_at for item in items) + sync_data = { + "timestamp": latest_time.isoformat(), + "user_id": self.user_id, + } + next_sync_token = base64.b64encode( + json.dumps(sync_data).encode("utf-8") + ).decode("utf-8") + else: + # No changes, return same sync token + next_sync_token = sync_token + + # Generate etag + etag = f'"{uuid4()}"' + + return TaskListResponse( + etag=etag, + items=items, + nextPageToken=None, + nextSyncToken=next_sync_token, + ) + + except json.JSONDecodeError: + raise ValueError("Invalid sync token format") + except Exception as e: + logger.error(f"Error handling sync request: {e}") + raise + + def get_task(self, task_id: str) -> Optional[TaskRecord]: + """ + Retrieve a specific task by ID. + + Args: + task_id: Task identifier (e.g., "task1") + + Returns: + TaskRecord or None if not found + """ + return self.db.query(TaskRecord).filter(TaskRecord.id == task_id).first() + + def create_episode(self, task_id: str, workdir: str) -> EpisodeRecord: + """ + Create a new episode (task run) for a user. + + Args: + task_id: Task identifier + workdir: Path to working directory with task files + + Returns: + Created EpisodeRecord + """ + try: + # Verify task exists + task = self.get_task(task_id) + if not task: + raise ValueError(f"Task '{task_id}' not found") + + # Create episode + episode_id = str(uuid4()) + episode = EpisodeRecord( + id=episode_id, + task_id=task_id, + user_id=self.user_id, + workdir=workdir, + status="active", + etag=f'"{uuid4()}"', + ) + self.db.add(episode) + self.db.commit() + self.db.refresh(episode) + + logger.info( + f"Created episode {episode_id} for task {task_id}, user {self.user_id}" + ) + return episode + + except Exception as e: + self.db.rollback() + logger.error(f"Error creating episode: {e}") + raise + + def get_episode(self, task_id: str, episode_id: str) -> Optional[EpisodeRecord]: + """ + Retrieve a specific episode. + + Args: + task_id: Task identifier + episode_id: Episode identifier + + Returns: + EpisodeRecord or None if not found + """ + return ( + self.db.query(EpisodeRecord) + .filter( + and_( + EpisodeRecord.id == episode_id, + EpisodeRecord.task_id == task_id, + EpisodeRecord.user_id == self.user_id, + ) + ) + .first() + ) + + def update_episode( + self, task_id: str, episode_id: str, status: str, pass_rate: Optional[float] = None + ) -> Optional[EpisodeRecord]: + """ + Update an episode's status and pass rate. + + Args: + task_id: Task identifier + episode_id: Episode identifier + status: New status ("active", "passed", "failed", "abandoned") + pass_rate: Pass rate (0.0-1.0) if completed + + Returns: + Updated EpisodeRecord or None if not found + """ + try: + episode = self.get_episode(task_id, episode_id) + if not episode: + return None + + episode.status = status + if pass_rate is not None: + episode.pass_rate = pass_rate + episode.etag = f'"{uuid4()}"' + episode.updated_at = datetime.utcnow() + + self.db.commit() + self.db.refresh(episode) + + logger.info( + f"Updated episode {episode_id} status to {status} (pass_rate={pass_rate})" + ) + return episode + + except Exception as e: + self.db.rollback() + logger.error(f"Error updating episode: {e}") + raise + + def list_episodes( + self, task_id: str, max_results: int = 50, page_token: Optional[str] = None + ) -> "EpisodeListResponse": + """ + List episodes for a task with pagination. + + Args: + task_id: Task identifier + max_results: Maximum items per page + page_token: Pagination token + + Returns: + EpisodeListResponse with items and nextPageToken + """ + try: + # Base query: user-scoped + query = ( + self.db.query(EpisodeRecord) + .filter( + and_(EpisodeRecord.task_id == task_id, EpisodeRecord.user_id == self.user_id) + ) + .order_by(EpisodeRecord.created_at, EpisodeRecord.id) + ) + + # Handle pagination + offset = 0 + if page_token: + try: + offset = int(base64.b64decode(page_token).decode("utf-8")) + except (ValueError, TypeError): + raise ValueError("Invalid pageToken") + + items = query.offset(offset).limit(max_results + 1).all() + + has_next_page = len(items) > max_results + if has_next_page: + items = items[:max_results] + next_page_token = base64.b64encode( + str(offset + max_results).encode("utf-8") + ).decode("utf-8") + else: + next_page_token = None + + return EpisodeListResponse(items=items, nextPageToken=next_page_token) + + except Exception as e: + logger.error(f"Error listing episodes: {e}") + raise + + def watch_task(self, task_id: str, watch_request: Dict[str, Any]) -> WatchChannel: + """ + Set up a watch channel for task state changes. + + Args: + task_id: Task identifier + watch_request: Dict with 'id', 'address', 'token' (optional) + + Returns: + Created WatchChannel + """ + try: + # Verify task exists + task = self.get_task(task_id) + if not task: + raise ValueError(f"Task '{task_id}' not found") + + # Check for duplicate watch ID + existing = self.db.query(WatchChannel).filter( + WatchChannel.id == watch_request["id"] + ).first() + if existing: + raise ValueError(f"Watch channel with ID {watch_request['id']} already exists") + + # Create watch channel (24 hour default expiration) + expires_at = datetime.utcnow() + timedelta(hours=24) + channel = WatchChannel( + id=watch_request["id"], + task_id=task_id, + user_id=self.user_id, + webhook_address=watch_request["address"], + webhook_token=watch_request.get("token"), + expires_at=expires_at, + is_active=True, + ) + self.db.add(channel) + self.db.commit() + self.db.refresh(channel) + + logger.info(f"Created watch channel {watch_request['id']} for task {task_id}") + return channel + + except Exception as e: + self.db.rollback() + logger.error(f"Error creating watch channel: {e}") + raise + + def cleanup_expired_channels(self) -> int: + """ + Clean up expired watch channels for this user. + + Returns: + Number of channels cleaned up + """ + try: + current_time = datetime.utcnow() + + expired_channels = ( + self.db.query(WatchChannel) + .filter( + and_( + WatchChannel.user_id == self.user_id, + WatchChannel.expires_at < current_time, + WatchChannel.is_active == True, + ) + ) + .all() + ) + + cleanup_count = 0 + for channel in expired_channels: + channel.is_active = False + cleanup_count += 1 + + if cleanup_count > 0: + self.db.commit() + logger.info(f"Cleaned up {cleanup_count} expired watch channels for user {self.user_id}") + + return cleanup_count + + except Exception as e: + self.db.rollback() + logger.error(f"Error cleaning up expired channels: {e}") + return 0 + + +# Response models (simple classes matching the pattern) +class TaskListResponse: + def __init__( + self, + etag: str, + items: List[TaskRecord], + nextPageToken: Optional[str] = None, + nextSyncToken: Optional[str] = None, + ): + self.etag = etag + self.items = items + self.nextPageToken = nextPageToken + self.nextSyncToken = nextSyncToken + + +class EpisodeListResponse: + def __init__(self, items: List[EpisodeRecord], nextPageToken: Optional[str] = None): + self.items = items + self.nextPageToken = nextPageToken + + +def get_task_manager(db: Session, user_id: str) -> TaskManager: + """Factory function to create a TaskManager instance.""" + return TaskManager(db, user_id) diff --git a/debug_env/server/database/models/__init__.py b/debug_env/server/database/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aeafc359d85fb1f8c80dd0fbbe1d6383ac1b0b45 --- /dev/null +++ b/debug_env/server/database/models/__init__.py @@ -0,0 +1 @@ +"""Database models for debug_env""" diff --git a/debug_env/server/database/models/task.py b/debug_env/server/database/models/task.py new file mode 100644 index 0000000000000000000000000000000000000000..13ed73170cb65cd4c342f509df7fc51ec22ba492 --- /dev/null +++ b/debug_env/server/database/models/task.py @@ -0,0 +1,91 @@ +""" +SQLAlchemy ORM models for tasks, episodes, and watch channels. +""" + +from datetime import datetime +from typing import List, Optional + +from sqlalchemy import Column, String, DateTime, Float, Boolean, JSON +from sqlalchemy.sql import func + +from debug_env.server.database.db import Base + + +class TaskRecord(Base): + """ + Task record — mirrors TASK_REGISTRY in database. + + Each row represents a debuggable task available in the benchmark. + Seeded from TASK_REGISTRY at application startup. + """ + + __tablename__ = "task_records" + + id = Column(String, primary_key=True, index=True) # e.g., "task1" + title = Column(String, nullable=False) + description = Column(String, nullable=False) + difficulty = Column(String, nullable=False) # e.g., "easy", "medium", "hard" + bug_type = Column(String, nullable=False) # e.g., "syntax", "logic", "type_error" + files = Column(JSON, nullable=False) # List of filenames + tools = Column(JSON, nullable=True) # List of available tools for this task + scenario_type = Column(String, nullable=True) # e.g., "code_review", "cross_team_collaboration" + participants = Column(JSON, nullable=True) # List of participant dicts for multi-user tasks + etag = Column(String, nullable=False) # Cache validation tag + created_at = Column(DateTime, default=datetime.utcnow, nullable=False) + updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + def __repr__(self) -> str: + return f"" + + +class EpisodeRecord(Base): + """ + Episode record — tracks each task run (reset/step sequence). + + One row created per TaskLoader.load() call (when DebugEnvironment.reset() is called). + Tracks workdir, status, and pass_rate for the episode lifecycle. + """ + + __tablename__ = "episode_records" + + id = Column(String, primary_key=True, index=True) # UUID4 string + task_id = Column(String, nullable=False, index=True) # e.g., "task1" (FK to task_records.id) + user_id = Column(String, nullable=False, index=True) # e.g., "default_user" or from X-User-Id header + workdir = Column(String, nullable=True) # Path to temp directory with task files + status = Column( + String, + nullable=False, + default="active", + index=True, + ) # "active", "passed", "failed", "abandoned" + pass_rate = Column(Float, nullable=True) # 0.0 to 1.0, or None if not completed + etag = Column(String, nullable=False) # Cache validation tag + created_at = Column(DateTime, default=datetime.utcnow, nullable=False, index=True) + updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + def __repr__(self) -> str: + return f"" + + +class WatchChannel(Base): + """ + Watch channel record — tracks webhook subscriptions for task/episode state changes. + + Allows clients to subscribe to notifications when tasks or episodes change. + Lightweight structure for future expansion of notification features. + """ + + __tablename__ = "watch_channels" + + id = Column(String, primary_key=True, index=True) # Client-provided ID + task_id = Column(String, nullable=False, index=True) # Task being watched + user_id = Column(String, nullable=False, index=True) # User who set up the watch + webhook_address = Column(String, nullable=False) # URL to POST notifications to + webhook_token = Column(String, nullable=True) # Optional auth token for webhook + expires_at = Column(DateTime, nullable=True, index=True) # When this watch expires + is_active = Column(Boolean, default=True, nullable=False) # Whether watch is currently active + created_at = Column(DateTime, default=datetime.utcnow, nullable=False) + updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + def __repr__(self) -> str: + return f"" diff --git a/debug_env/server/debug_env_environment.py b/debug_env/server/debug_env_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..7b4bb8578e6bd32422f39438ff7a6384fbe690f0 --- /dev/null +++ b/debug_env/server/debug_env_environment.py @@ -0,0 +1,99 @@ +import logging +from uuid import uuid4 + +from openenv.core.env_server.interfaces import Environment +from openenv.core.env_server.types import State + +from debug_env.models import DebugAction, DebugObservation +from debug_env.server.grader import grade +from debug_env.server.schemas import ToolResult +from debug_env.server.tasks import TaskLoader +from debug_env.server.tools import edit_file, read_file, run_tests + +logger = logging.getLogger(__name__) + + +def _make_error_obs(message: str) -> DebugObservation: + """Return a zero-reward observation for environment-level errors.""" + obs = DebugObservation(pass_rate=0.0, logs=message) + obs.reward = 0.0 + obs.done = False + return obs + + +def _obs_from_result(result: ToolResult) -> DebugObservation: + """Convert a ToolResult into a DebugObservation with reward and done flag.""" + obs = DebugObservation(pass_rate=result.pass_rate, logs=result.logs) + obs.reward = grade(result.pass_rate) + obs.done = result.pass_rate == 1.0 + return obs + + +class DebugEnvironment(Environment): + + def __init__(self): + self._state = State(episode_id=str(uuid4()), step_count=0) + self.current_task = "task1" + self.workdir: str | None = None + + def reset(self, seed: int | None = None, episode_id: str | None = None, task: str | None = None, **kwargs) -> DebugObservation: # noqa: ARG002 + if task is not None: + self.current_task = task + self._state = State(episode_id=episode_id or str(uuid4()), step_count=0) + self.workdir = TaskLoader.load(self.current_task, self.workdir) + logger.info(f"Reset — task={self.current_task} workdir={self.workdir}") + return DebugObservation( + pass_rate=0.0, + logs=f"Task '{self.current_task}' loaded. Fix the bugs!", + ) + + # ── Tool dispatch ────────────────────────────────────────────────────────── + + def _handle_run_tests(self, workdir: str) -> ToolResult: + return run_tests(workdir) + + def _handle_read_file(self, workdir: str, args: dict) -> ToolResult: + return read_file(workdir, path=args.get("path", "")) + + def _handle_edit_file(self, workdir: str, args: dict) -> ToolResult: + return edit_file( + workdir, + path=args.get("path", ""), + content=args.get("content", ""), + ) + + # ── Core step ────────────────────────────────────────────────────────────── + + def step(self, action: DebugAction, timeout_s: float | None = None, **kwargs) -> DebugObservation: # noqa: ARG002 + self._state.step_count += 1 + + if self.workdir is None: + return _make_error_obs("Environment not initialised — call reset first.") + + tool = action.tool + args = action.args or {} + + logger.info(f"Step {self._state.step_count} — tool={tool}") + + try: + if tool == "run_tests": + result = self._handle_run_tests(self.workdir) + elif tool == "read_file": + result = self._handle_read_file(self.workdir, args) + elif tool == "edit_file": + result = self._handle_edit_file(self.workdir, args) + else: + result = ToolResult( + pass_rate=0.0, + logs=f"Unknown tool: '{tool}'. Use 'run_tests', 'read_file', or 'edit_file'.", + success=False, + ) + except Exception as e: + logger.error(f"Unexpected error in tool '{tool}': {e}", exc_info=True) + return _make_error_obs(f"Internal error executing '{tool}'. Contact admin if issue persists.") + + return _obs_from_result(result) + + @property + def state(self) -> State: + return self._state diff --git a/debug_env/server/grader.py b/debug_env/server/grader.py new file mode 100644 index 0000000000000000000000000000000000000000..2110785da8463ce0679296c885fd578cbc6a679d --- /dev/null +++ b/debug_env/server/grader.py @@ -0,0 +1,3 @@ +def grade(pass_rate: float) -> float: + """Convert test pass rate to reward score in [0.0, 1.0].""" + return float(pass_rate) diff --git a/debug_env/server/handlers/__init__.py b/debug_env/server/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..44439bdbb1b64833856b6dfa5be826f48a7b5d2c --- /dev/null +++ b/debug_env/server/handlers/__init__.py @@ -0,0 +1,3 @@ +from .mcp_handler import handle_mcp_request + +__all__ = ["handle_mcp_request"] diff --git a/debug_env/server/handlers/mcp_handler.py b/debug_env/server/handlers/mcp_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..42a506a4ef0482532d9d9a375e9a97bf8dc6b32b --- /dev/null +++ b/debug_env/server/handlers/mcp_handler.py @@ -0,0 +1,261 @@ +""" +MCP (Model Context Protocol) request handler for debug-env. + +Implements the MCP JSON-RPC 2024-11-05 protocol, exposing the three debug +tools (run_tests, read_file, edit_file) and six advanced analysis tools to any +MCP-compatible client. + +Session model: a single shared DebugEnvironment is used for MCP sessions. +Call 'initialize' to set up a session (optionally passing {"task": "task2"} in +params.meta), then use 'tools/call' to invoke tools across turns. +""" + +import logging +from typing import Any, Dict, Optional + +from fastapi import Request + +logger = logging.getLogger(__name__) + +# ── MCP tool definitions ─────────────────────────────────────────────────────── + +MCP_TOOLS = [ + { + "name": "run_tests", + "description": """Execute the pytest test suite against the current code. + + Runs all tests in the task working directory and returns detailed results + including pass rate and full test output logs. + + Response Structure: + - pass_rate: Float (0.0–1.0) indicating fraction of tests passed + - logs: Test output including failures, errors, and summary + - reward: Scalar reward based on pass_rate (0.0 at fail, >0.0 at pass) + - done: Boolean, true when all tests pass (pass_rate = 1.0) + + Status Codes: + - 200: Success - Tests executed (may include failures) + - 500: Internal error running tests + """, + "inputSchema": {"type": "object", "properties": {}, "required": []}, + }, + { + "name": "read_file", + "description": """Read the current content of a source file in the task working directory. + + Allows inspection of broken code and helper files before deciding what to edit. + Reading a file does not affect the test pass rate or episode score. + + Required Parameters: + - path: Filename to read (relative to workdir), e.g. 'broken_code.py' + + Response Structure: + - pass_rate: 0.0 (reading doesn't affect score) + - logs: File content prefixed with filename header + - success: true if file was read successfully + + Status Codes: + - 200: Success - File read and returned + - 400: Bad Request - Invalid filename or path traversal attempt + - 404: Not Found - File does not exist in task + - 500: Internal error reading file + """, + "inputSchema": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "description": "Filename to read (e.g. 'broken_code.py', 'helper.py')", + } + }, + "required": ["path"], + }, + }, + { + "name": "edit_file", + "description": """Overwrite a source file with corrected content and run tests. + + Replaces the entire file content and immediately executes the test suite + to evaluate the fix. Partial writes are not supported—always provide the + complete file content. + + Required Parameters: + - path: Filename to edit (e.g. 'broken_code.py') + - content: Complete new file content (full replacement) + + Response Structure: + - pass_rate: Float (0.0–1.0) from subsequent test run + - logs: Test output showing impact of the edit + - reward: Scalar reward based on new pass_rate + - done: Boolean, true when all tests pass + - success: true if file was written and tests executed + + Status Codes: + - 200: Success - File written and tests executed + - 400: Bad Request - Invalid filename or path traversal attempt + - 404: Not Found - File does not exist in task + - 500: Internal error writing or testing + """, + "inputSchema": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "description": "Filename to edit (e.g. 'broken_code.py')", + }, + "content": { + "type": "string", + "description": "Complete new file content (full file replacement)", + }, + }, + "required": ["path", "content"], + }, + }, +] + +# Advanced debugging tools will be added at runtime (in _handle_tools_list) to avoid circular imports + +# ── Shared environment instance ──────────────────────────────────────────────── + +_env = None # lazily initialised on first tool call + + +def _get_env(): + """Return the shared DebugEnvironment, creating it if needed.""" + global _env + if _env is None: + from debug_env.server.debug_env_environment import DebugEnvironment + _env = DebugEnvironment() + return _env + + +# ── JSON-RPC helpers ─────────────────────────────────────────────────────────── + + +def _ok(request_id: Any, result: Dict[str, Any]) -> Dict[str, Any]: + return {"jsonrpc": "2.0", "id": request_id, "result": result} + + +def _error(request_id: Any, code: int, message: str) -> Dict[str, Any]: + return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}} + + +# ── Handler ──────────────────────────────────────────────────────────────────── + + +async def handle_mcp_request(request: Request) -> Optional[Dict[str, Any]]: + """ + Dispatch an incoming MCP JSON-RPC request to the appropriate handler. + + Returns None for notifications (caller should respond with 204 No Content). + """ + try: + body = await request.json() + except Exception: + return _error(None, -32700, "Parse error: request body is not valid JSON") + + method: str = body.get("method", "") + params: Dict[str, Any] = body.get("params") or {} + request_id = body.get("id") + + # Notifications have no 'id' — we return None so the router sends 204 + if request_id is None: + logger.debug(f"MCP notification received: {method}") + return None + + logger.info(f"MCP request: method={method} id={request_id}") + + if method == "initialize": + return _handle_initialize(request_id, params) + + if method == "tools/list": + return _handle_tools_list(request_id) + + if method == "tools/call": + return await _handle_tools_call(request_id, params) + + return _error(request_id, -32601, f"Method not found: {method}") + + +# ── Method handlers ──────────────────────────────────────────────────────────── + + +def _handle_initialize(request_id: Any, params: Dict[str, Any]) -> Dict[str, Any]: + """ + Perform the MCP handshake and optionally load a task. + + Clients may pass {"meta": {"task": "task2"}} to select a task up front. + """ + task = (params.get("meta") or {}).get("task") + env = _get_env() + env.reset(task=task) + logger.info(f"MCP session initialised — task={env.current_task}") + + return _ok(request_id, { + "protocolVersion": "2024-11-05", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "debug-env", "version": "0.1.0"}, + }) + + +def _handle_tools_list(request_id: Any) -> Dict[str, Any]: + """Return the list of available debug tools in MCP format.""" + # Add advanced tools on first call (lazy loading to avoid circular imports) + if len(MCP_TOOLS) == 3: # Only have the 3 base tools + from debug_env.server.tools.tool_handlers import get_mcp_tools_list + advanced_tools = get_mcp_tools_list() + MCP_TOOLS.extend(advanced_tools) + + return _ok(request_id, {"tools": MCP_TOOLS}) + + +async def _handle_tools_call(request_id: Any, params: Dict[str, Any]) -> Dict[str, Any]: + """Execute a debug tool via generic dispatcher and return the result as MCP content.""" + from debug_env.models import DebugAction + from debug_env.server.tools.tool_handlers import get_tool_handlers + + tool_name: str = params.get("name", "") + tool_args: Dict[str, Any] = params.get("arguments") or {} + + if not tool_name: + return _error(request_id, -32602, "Invalid params: 'name' is required") + + env = _get_env() + if env.workdir is None: + env.reset() + + # Get tool handlers (lazy-loaded to avoid circular imports) + tool_handlers = get_tool_handlers() + + # Try advanced tools first via generic dispatcher + if tool_name in tool_handlers: + try: + logger.debug(f"Executing advanced tool {tool_name} via generic dispatcher") + result = await tool_handlers[tool_name](tool_name, tool_args, env.workdir) + text = result.get("text", "") + return _ok(request_id, { + "content": [{"type": "text", "text": text}], + "isError": result.get("isError", False), + }) + except Exception as e: + logger.error(f"Tool {tool_name} execution failed: {e}", exc_info=True) + return _error(request_id, -32603, f"Internal error executing tool '{tool_name}'") + + # Fall back to environment tools (run_tests, read_file, edit_file) + try: + action = DebugAction(tool=tool_name, args=tool_args) + obs = env.step(action) + except Exception as e: + logger.error(f"MCP tool call failed — tool={tool_name}: {e}", exc_info=True) + return _error(request_id, -32603, f"Internal error executing tool '{tool_name}'") + + text = ( + f"pass_rate={obs.pass_rate:.2f} reward={obs.reward:.2f} done={obs.done}" + f"\n\n{obs.logs}" + ) + return _ok(request_id, { + "content": [{"type": "text", "text": text}], + "isError": obs.pass_rate == 0.0 and not obs.done, + }) diff --git a/debug_env/server/mcp/__init__.py b/debug_env/server/mcp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5bc0c2e6d2a80e722fadb85839ca1fe3083e3a6d --- /dev/null +++ b/debug_env/server/mcp/__init__.py @@ -0,0 +1,3 @@ +from .router import router + +__all__ = ["router"] diff --git a/debug_env/server/mcp/router.py b/debug_env/server/mcp/router.py new file mode 100644 index 0000000000000000000000000000000000000000..f108e31832b18f1c022d0c18e32dc810089f49d0 --- /dev/null +++ b/debug_env/server/mcp/router.py @@ -0,0 +1,30 @@ +""" +MCP (Model Context Protocol) API Router +Handles MCP protocol messages for the debug-env tools. +Tool execution routes are at /mcp (no /api prefix). +""" + +import logging + +from fastapi import APIRouter, Request, Response + +from debug_env.server.handlers.mcp_handler import handle_mcp_request + +logger = logging.getLogger(__name__) + +router = APIRouter() + + +@router.post("/mcp") +async def handle_mcp(request: Request): + """Handle MCP protocol messages""" + response = await handle_mcp_request(request) + if response is None: + # For notifications, return 204 No Content + return Response(content="", status_code=204, headers={"Content-Length": "0"}) + + # Check if response is already a dict or needs to be converted + if hasattr(response, "model_dump"): + return response.model_dump() + else: + return response diff --git a/debug_env/server/mcp/tools/__init__.py b/debug_env/server/mcp/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..95344ccee8b27bf04f5cfd6ed4edc8f2e0cecefe --- /dev/null +++ b/debug_env/server/mcp/tools/__init__.py @@ -0,0 +1 @@ +"""MCP tool definitions and implementations.""" \ No newline at end of file diff --git a/debug_env/server/mcp/tools/debug_tools.py b/debug_env/server/mcp/tools/debug_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..1e9de396cfb6e44215eaaa7540632489457ce076 --- /dev/null +++ b/debug_env/server/mcp/tools/debug_tools.py @@ -0,0 +1,494 @@ +""" +Debug Tools Module + +Comprehensive set of tools for advanced code debugging and analysis. +Provides code search, structure analysis, type checking, coverage analysis, and dependency inspection. +""" + +DEBUG_TOOLS = [ + { + "name": "search_code", + "description": """Search for code patterns across files in the task directory. + + Searches for text or regex patterns across source files, useful for locating + where functions are called, variable usage, or specific error patterns. + Similar to grep/rg operations but integrated for debugging workflow. + + Required Parameters: + - pattern: Text or regex pattern to search for (case-insensitive by default) + - file_types: Optional. Filter by file type (default: "py" for Python files only) + Enum: "py" (Python), "all" (all files), "txt", "json", etc. + + Optional Parameters: + - case_sensitive: Whether to match case (default: false) + - max_results: Maximum number of matches to return (default: 50, max: 500) + - context_lines: Lines of context around each match (default: 2, max: 10) + + Search Behavior: + - Returns matches with line numbers, filenames, and surrounding context + - Sorted by filename then line number + - If pattern contains regex special chars, it's treated as regex + - Matches are highlighted with context for easy reading + - Path traversal protection: only searches within task directory + + Response Structure: + - matches: Array of match objects, each containing: + * filename: File containing the match + * line_number: Line number (1-indexed) + * line_content: The matching line + * before: Context lines before (array) + * after: Context lines after (array) + * match_position: Column where match starts + - total_matches: Total number of matches found + - files_searched: Number of files examined + - search_time_ms: Search execution time + + Status Codes: + - 200: Success - Search completed (may have 0 matches) + - 400: Bad Request - Invalid pattern or parameters + - 500: Internal Server Error + """, + "inputSchema": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Text or regex pattern to search for", + "minLength": 1, + "maxLength": 500, + }, + "file_types": { + "type": "string", + "description": "File type filter (py, all, txt, json, etc.)", + "enum": ["py", "all", "txt", "json", "md"], + "default": "py", + }, + "case_sensitive": { + "type": "boolean", + "description": "Whether to match case", + "default": False, + }, + "max_results": { + "type": "integer", + "description": "Maximum number of matches to return", + "minimum": 1, + "maximum": 500, + "default": 50, + }, + "context_lines": { + "type": "integer", + "description": "Lines of context around each match", + "minimum": 0, + "maximum": 10, + "default": 2, + }, + }, + "required": ["pattern"], + }, + }, + { + "name": "get_file_structure", + "description": """Parse and return the structure (AST) of a Python file. + + Analyzes the Abstract Syntax Tree of a Python file to extract functions, + classes, methods, imports, and their locations. Useful for understanding + code organization before editing. + + Required Parameters: + - path: File path relative to task directory (e.g., 'broken_code.py') + + Optional Parameters: + - include_docstrings: Include docstrings in output (default: true) + - include_signatures: Include function/method signatures (default: true) + - max_depth: Maximum nesting depth to analyze (default: unlimited) + + Structure Analysis: + - Extracts top-level functions and classes + - For each class: lists methods, attributes, parent classes + - For each function: shows parameters, return type hint (if present) + - Shows decorators (@property, @staticmethod, etc.) + - Identifies imports (from/import statements) + - Groups by section (imports, classes, functions, constants) + + Response Structure: + - filename: The analyzed file + - imports: Array of import statements with line numbers + * module: Imported module + * items: What was imported (function/class/constant names) + * line_number: Where imported + - classes: Array of class definitions + * name: Class name + * line_number: Definition line + * methods: Array of method names with line numbers + * attributes: Instance attributes with types (if annotated) + * docstring: Class docstring (if present) + - functions: Array of top-level functions + * name: Function name + * line_number: Definition line + * parameters: Param names and types (if annotated) + * return_type: Return type hint (if present) + * docstring: Function docstring (if present) + - constants: Module-level constants + * name: Constant name + * line_number: Definition line + * value: Literal value (if simple) + + Status Codes: + - 200: Success - File structure extracted + - 400: Bad Request - Invalid Python syntax or file not found + - 500: Internal Server Error + """, + "inputSchema": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "File path relative to task directory", + "minLength": 1, + "maxLength": 255, + }, + "include_docstrings": { + "type": "boolean", + "description": "Include docstrings in output", + "default": True, + }, + "include_signatures": { + "type": "boolean", + "description": "Include function/method signatures", + "default": True, + }, + "max_depth": { + "type": "integer", + "description": "Maximum nesting depth to analyze (0 for unlimited)", + "minimum": 0, + "default": 0, + }, + }, + "required": ["path"], + }, + }, + { + "name": "run_type_check", + "description": """Run static type checking (mypy) on Python files. + + Executes mypy type checker on specified file or directory to identify + type errors, missing annotations, and type incompatibilities. + Useful for catching type-related bugs before runtime. + + Required Parameters: + - path: File or directory path relative to task directory + (e.g., 'broken_code.py' or '.') + + Optional Parameters: + - strict: Enable strict mode (all optional checks, default: false) + - ignore_missing_imports: Ignore errors from untyped libraries (default: true) + - show_error_codes: Show error codes in output (default: true) + - max_errors: Maximum errors to report (default: 100) + + Type Check Behavior: + - Analyzes type annotations and infers types + - Reports missing type hints where inferred types conflict + - Checks function argument types against signatures + - Validates attribute access on typed objects + - Catches common type errors (None checks, incompatible operations) + - Produces detailed error messages with suggestions + + Response Structure: + - path: File/directory analyzed + - status: "success" or "errors_found" + - error_count: Total number of type errors + - errors: Array of error objects + * file: File containing error + * line: Line number (1-indexed) + * column: Column number (1-indexed) + * message: Detailed error message + * error_code: mypy error code (e.g., "var-annotated") + * suggestion: Suggested fix (if available) + - success_count: Number of successfully type-checked items + - check_time_ms: Type check execution time + + Status Codes: + - 200: Success - Type check completed (may report errors) + - 400: Bad Request - Invalid path or mypy configuration + - 500: Internal Server Error + """, + "inputSchema": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "File or directory path relative to task directory", + "minLength": 1, + "maxLength": 255, + }, + "strict": { + "type": "boolean", + "description": "Enable strict type checking mode", + "default": False, + }, + "ignore_missing_imports": { + "type": "boolean", + "description": "Ignore errors from untyped third-party libraries", + "default": True, + }, + "show_error_codes": { + "type": "boolean", + "description": "Show mypy error codes in output", + "default": True, + }, + "max_errors": { + "type": "integer", + "description": "Maximum errors to report before stopping", + "minimum": 1, + "maximum": 500, + "default": 100, + }, + }, + "required": ["path"], + }, + }, + { + "name": "get_test_coverage", + "description": """Analyze test coverage for Python files. + + Runs coverage.py to measure which lines of code are executed by tests. + Shows coverage percentage per file/function, identifying untested code paths. + Useful for understanding test completeness and finding missing edge cases. + + Required Parameters: + - path: File or directory path relative to task directory (optional, default: '.') + + Optional Parameters: + - branch_coverage: Include branch coverage (if/else paths, default: false) + - include_missing: Show which lines are not covered (default: true) + - fail_under: Minimum coverage % required (0-100, default: 0) + + Coverage Behavior: + - Runs test suite and tracks line execution + - Shows coverage for each file + - Shows coverage for each function/class + - Identifies completely uncovered functions/methods + - Can detect dead code (0% coverage) + - Branch coverage shows if/else branches taken + + Response Structure: + - total_coverage: Overall coverage percentage (0-100) + - files: Array of file coverage objects + * filename: File path + * coverage: Coverage percentage + * lines_total: Total executable lines + * lines_covered: Lines executed by tests + * missing_lines: Array of uncovered line numbers (if include_missing) + - functions: Array of function coverage objects + * name: Function name + * file: File containing function + * coverage: Coverage percentage (0 or 100 for line coverage) + * line_number: Function definition line + - status: "covered", "partially_covered", or "uncovered" based on fail_under + - check_time_ms: Coverage analysis time + + Status Codes: + - 200: Success - Coverage analyzed + - 400: Bad Request - Invalid path or coverage configuration + - 500: Internal Server Error + """, + "inputSchema": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "File or directory path relative to task directory", + "minLength": 1, + "maxLength": 255, + "default": ".", + }, + "branch_coverage": { + "type": "boolean", + "description": "Include branch (if/else) coverage analysis", + "default": False, + }, + "include_missing": { + "type": "boolean", + "description": "Show which lines are not covered", + "default": True, + }, + "fail_under": { + "type": "integer", + "description": "Minimum required coverage percentage (0-100)", + "minimum": 0, + "maximum": 100, + "default": 0, + }, + }, + "required": [], + }, + }, + { + "name": "list_directory", + "description": """List files and directories in the task working directory. + + Returns a directory tree showing file structure, sizes, types, and metadata. + Useful for understanding what files exist and their organization before + starting to debug or edit code. + + Required Parameters: None (default: current task directory) + + Optional Parameters: + - path: Subdirectory path relative to task root (default: '.') + - recursive: Include subdirectories recursively (default: true) + - max_depth: Maximum directory nesting depth (default: unlimited) + - include_hidden: Include hidden files/folders starting with . (default: false) + - file_types: Filter by file type (py, all, test, etc.) + + Directory Listing: + - Shows files and folders in hierarchical structure + - Includes file size in bytes + - Shows file type/extension + - Marks executable files + - Marks test files separately + - Indicates if file is readable/writable + + Response Structure: + - root_path: Base directory path + - total_files: Total number of files (excluding directories) + - total_directories: Total number of subdirectories + - items: Array of directory entry objects + * name: File or directory name + * type: "file" or "directory" + * path: Full path relative to task root + * size_bytes: File size in bytes (for files) + * is_test: Whether file matches test pattern (test_*.py) + * is_executable: Whether file is executable + * contents: Array of child items (for directories if recursive) + - tree_depth: Maximum nesting depth found + + Status Codes: + - 200: Success - Directory listed + - 404: Not Found - Directory path does not exist + - 500: Internal Server Error + """, + "inputSchema": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Subdirectory path relative to task root", + "default": ".", + "maxLength": 255, + }, + "recursive": { + "type": "boolean", + "description": "Include subdirectories recursively", + "default": True, + }, + "max_depth": { + "type": "integer", + "description": "Maximum directory nesting depth (0 for unlimited)", + "minimum": 0, + "default": 0, + }, + "include_hidden": { + "type": "boolean", + "description": "Include hidden files/folders starting with .", + "default": False, + }, + "file_types": { + "type": "string", + "description": "Filter by file type", + "enum": ["py", "all", "test", "source"], + "default": "all", + }, + }, + "required": [], + }, + }, + { + "name": "get_dependencies", + "description": """Extract and analyze Python import dependencies. + + Parses import statements to build a dependency graph showing what modules/files + depend on each other. Useful for understanding code relationships and identifying + circular dependencies or unexpected coupling. + + Required Parameters: + - path: File or directory path relative to task directory (e.g., 'broken_code.py' or '.') + + Optional Parameters: + - include_stdlib: Include Python standard library imports (default: false) + - include_external: Include third-party library imports (default: true) + - direction: Show imports "to" (what this imports) or "from" (what imports this) + (default: "to") + - depth: Maximum depth to follow dependencies (default: 1) + + Dependency Analysis: + - Extracts all import statements (import x, from x import y) + - Categorizes imports (local, stdlib, external) + - Builds dependency graph showing import relationships + - Detects circular dependencies (A imports B, B imports A) + - Shows unused imports + - Maps relative imports to absolute module paths + + Response Structure: + - path: File or directory analyzed + - direct_dependencies: Array of direct imports + * module: Module being imported + * type: "import" or "from...import" + * items: What was imported (if from...import) + * source_file: File being imported FROM (if local import) + * is_local: Whether importing from task code + * line_number: Import statement line number + - indirect_dependencies: Array of transitive dependencies (if depth > 1) + * module: Module name + * via: Path showing how it's imported + * chain_length: Number of imports deep + - circular_dependencies: Array of detected cycles + * cycle: Array of module names forming cycle + * files: File paths involved in cycle + - unused_imports: Imports that appear to be unused + * module: Imported but never referenced + * file: File with unused import + * line_number: Import location + - dependency_count: Total number of dependencies + + Status Codes: + - 200: Success - Dependencies extracted + - 400: Bad Request - Invalid path or syntax error in files + - 500: Internal Server Error + """, + "inputSchema": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "File or directory path relative to task directory", + "minLength": 1, + "maxLength": 255, + }, + "include_stdlib": { + "type": "boolean", + "description": "Include Python standard library imports", + "default": False, + }, + "include_external": { + "type": "boolean", + "description": "Include third-party library imports", + "default": True, + }, + "direction": { + "type": "string", + "description": "Show imports 'to' (what this imports) or 'from' (what imports this)", + "enum": ["to", "from"], + "default": "to", + }, + "depth": { + "type": "integer", + "description": "Maximum depth to follow dependencies", + "minimum": 1, + "maximum": 5, + "default": 1, + }, + }, + "required": ["path"], + }, + }, +] \ No newline at end of file diff --git a/debug_env/server/requirements.txt b/debug_env/server/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..65b1c22b3db715ed9d63b9ad06cd4afb0d9412c5 --- /dev/null +++ b/debug_env/server/requirements.txt @@ -0,0 +1,6 @@ +openenv[core]>=0.2.0 +fastapi>=0.115.0 +uvicorn>=0.24.0 + + + diff --git a/debug_env/server/schemas/__init__.py b/debug_env/server/schemas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75ea0017065d35ae37beeed9c5c43179539e4679 --- /dev/null +++ b/debug_env/server/schemas/__init__.py @@ -0,0 +1,3 @@ +from .tool_schemas import EditFileArgs, ReadFileArgs, RunTestsArgs, ToolResult + +__all__ = ["RunTestsArgs", "ReadFileArgs", "EditFileArgs", "ToolResult"] diff --git a/debug_env/server/schemas/task_schemas.py b/debug_env/server/schemas/task_schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..ee651a2b30891d879a2b86bbb85a09c983e5d0e6 --- /dev/null +++ b/debug_env/server/schemas/task_schemas.py @@ -0,0 +1,95 @@ +""" +Pydantic schemas for task API responses and requests. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional + +from pydantic import BaseModel, ConfigDict + + +class TaskResponse(BaseModel): + """Response model for a single task.""" + + model_config = ConfigDict(from_attributes=True) + + id: str + title: str + description: str + difficulty: str + bug_type: str + files: List[str] + tools: Optional[List[str]] = None + scenario_type: Optional[str] = None + participants: Optional[List[Dict[str, Any]]] = None + etag: str + created_at: datetime + updated_at: datetime + + +class TaskListResponse(BaseModel): + """Response model for paginated task list.""" + + items: List[TaskResponse] + etag: str + nextPageToken: Optional[str] = None + nextSyncToken: Optional[str] = None + + +class EpisodeResponse(BaseModel): + """Response model for a single episode.""" + + model_config = ConfigDict(from_attributes=True) + + id: str + task_id: str + user_id: str + workdir: Optional[str] = None + status: str + pass_rate: Optional[float] = None + etag: str + created_at: datetime + updated_at: datetime + + +class EpisodeListResponse(BaseModel): + """Response model for paginated episode list.""" + + items: List[EpisodeResponse] + nextPageToken: Optional[str] = None + + +class EpisodeCreateRequest(BaseModel): + """Request model to create an episode.""" + + task_id: str + + +class EpisodePatchRequest(BaseModel): + """Request model to update an episode.""" + + status: Optional[str] = None + pass_rate: Optional[float] = None + + +class WatchChannelResponse(BaseModel): + """Response model for a watch channel.""" + + model_config = ConfigDict(from_attributes=True) + + id: str + task_id: str + user_id: str + webhook_address: str + webhook_token: Optional[str] = None + expires_at: Optional[datetime] = None + is_active: bool + created_at: datetime + + +class WatchChannelRequest(BaseModel): + """Request model to create a watch channel.""" + + id: str + address: str + token: Optional[str] = None diff --git a/debug_env/server/schemas/tool_schemas.py b/debug_env/server/schemas/tool_schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..adcae7425c1962dde4fc828ee39492af60c15719 --- /dev/null +++ b/debug_env/server/schemas/tool_schemas.py @@ -0,0 +1,76 @@ +""" +Pydantic schemas for tool inputs and results. + +These are the internal contracts between the environment and the tool layer — +separate from the public OpenEnv Action/Observation API in models.py. +""" + +from pydantic import BaseModel, Field, field_validator + + +class RunTestsArgs(BaseModel): + """Input schema for the run_tests tool (no arguments required).""" + pass + + +class EditFileArgs(BaseModel): + """Input schema for the edit_file tool.""" + + path: str = Field( + ..., + description="Filename to edit relative to the workdir, e.g. 'broken_code.py'", + min_length=1, + ) + content: str = Field( + ..., + description="Complete new file content (partial writes are not supported)", + ) + + @field_validator("path") + @classmethod + def no_path_traversal(cls, v: str) -> str: + """Reject paths that attempt to escape the workdir.""" + if ".." in v or v.startswith("/"): + raise ValueError( + f"Invalid path '{v}': absolute paths and '..' are not allowed." + ) + return v + + +class ReadFileArgs(BaseModel): + """Input schema for the read_file tool.""" + + path: str = Field( + ..., + description="Filename to read relative to the workdir, e.g. 'broken_code.py'", + min_length=1, + ) + + @field_validator("path") + @classmethod + def no_path_traversal(cls, v: str) -> str: + """Reject paths that attempt to escape the workdir.""" + if ".." in v or v.startswith("/"): + raise ValueError( + f"Invalid path '{v}': absolute paths and '..' are not allowed." + ) + return v + + +class ToolResult(BaseModel): + """Result returned by every tool.""" + + pass_rate: float = Field( + ..., + ge=0.0, + le=1.0, + description="Fraction of tests that passed (0.0 – 1.0)", + ) + logs: str = Field( + default="", + description="Full pytest output or error message", + ) + success: bool = Field( + default=True, + description="False when the tool itself failed (not the tests)", + ) diff --git a/debug_env/server/tasks/__init__.py b/debug_env/server/tasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc3e06dbb60991c85bef7f4c59932127d13d8a2 --- /dev/null +++ b/debug_env/server/tasks/__init__.py @@ -0,0 +1,4 @@ +from .data import get_available_task_ids, get_task_by_id, get_task_files, validate_task_id +from .loader import TaskLoader + +__all__ = ["TaskLoader", "get_task_by_id", "get_available_task_ids", "get_task_files", "validate_task_id"] diff --git a/debug_env/server/tasks/data.py b/debug_env/server/tasks/data.py new file mode 100644 index 0000000000000000000000000000000000000000..20650406f30be10ba8ecd7e7f0354a191e98a453 --- /dev/null +++ b/debug_env/server/tasks/data.py @@ -0,0 +1,145 @@ +""" +Debug-Env Task Registry +Static task definitions for the debugging benchmark. +""" + +from typing import Any, Dict, List + +# Task metadata registry — mirrors the structure on disk under debug_env/tasks/ +TASK_REGISTRY: Dict[str, Dict[str, Any]] = { + "task1": { + "id": "task1", + "title": "Syntax Error", + "description": "Fix a Python syntax error that prevents the module from importing.", + "difficulty": "easy", + "bug_type": "syntax", + "files": ["broken_code.py"], + }, + "task2": { + "id": "task2", + "title": "Logic Error", + "description": "Fix a logical error in a boolean expression.", + "difficulty": "medium", + "bug_type": "logic", + "files": ["broken_code.py"], + }, + "task3": { + "id": "task3", + "title": "Multi-file Bug", + "description": "Fix a bug that spans broken_code.py and a helper module it imports.", + "difficulty": "hard", + "bug_type": "multi-file", + "files": ["broken_code.py", "helper.py"], + }, + "task4": { + "id": "task4", + "title": "Type Error Detection", + "description": "Identify and fix type annotation errors detected by static type checking.", + "difficulty": "medium", + "bug_type": "type_error", + "files": ["typed_code.py"], + "tools": ["run_type_check", "edit_file", "run_tests"], + }, + "task5": { + "id": "task5", + "title": "Unused Imports and Dead Code", + "description": "Find and remove unused imports and dead code using code analysis tools.", + "difficulty": "medium", + "bug_type": "code_quality", + "files": ["messy_code.py"], + "tools": ["search_code", "get_file_structure", "get_dependencies", "edit_file", "run_tests"], + }, + "task6": { + "id": "task6", + "title": "Complex Multi-file Refactoring", + "description": "Refactor code across multiple files while maintaining test coverage and fixing architectural issues.", + "difficulty": "hard", + "bug_type": "architecture", + "files": ["module_a.py", "module_b.py", "module_c.py", "integration.py"], + "tools": ["list_directory", "get_file_structure", "get_dependencies", "search_code", "get_test_coverage", "edit_file", "run_tests"], + }, + "task7": { + "id": "task7", + "title": "Code Review Workflow", + "description": "Multi-user collaborative task: Junior developer submits fix that needs code review and approval", + "difficulty": "medium", + "bug_type": "code_quality", + "files": ["auth.py", "test_auth.py"], + "scenario_type": "code_review", + "participants": ["bob_junior", "alice_senior", "dave_lead"], + "tools": ["read_file", "edit_file", "run_tests", "search_code", "run_type_check", "get_test_coverage"], + }, + "task8": { + "id": "task8", + "title": "Cross-team Bug Investigation", + "description": "Multi-user collaborative task: QA reported bug, dev team investigates and implements fix", + "difficulty": "hard", + "bug_type": "bug_investigation", + "files": ["user_service.py", "email_validator.py", "test_user_service.py"], + "scenario_type": "cross_team_collaboration", + "participants": ["carol_qa", "bob_junior", "alice_senior", "dave_lead"], + "tools": ["search_code", "get_file_structure", "read_file", "run_tests", "edit_file", "get_test_coverage"], + }, + "task9": { + "id": "task9", + "title": "Collaborative Architecture Refactoring", + "description": "Multi-user collaborative task: Large refactoring with multiple developers working in parallel", + "difficulty": "hard", + "bug_type": "architecture", + "files": ["data_processor.py", "business_logic.py", "api_interface.py", "integration.py"], + "scenario_type": "team_refactoring", + "participants": ["alice_senior", "bob_junior", "carol_qa", "dave_lead"], + "tools": ["list_directory", "get_file_structure", "get_dependencies", "search_code", "read_file", "edit_file", "run_tests", "run_type_check", "get_test_coverage"], + }, +} + + +def get_task_by_id(task_id: str) -> Dict[str, Any]: + """ + Return metadata for a task by its ID. + + Args: + task_id: e.g. "task1" + + Returns: + Task metadata dict. + + Raises: + ValueError: If task_id is not registered. + """ + task = TASK_REGISTRY.get(task_id) + if task is None: + available = get_available_task_ids() + raise ValueError(f"Unknown task '{task_id}'. Available: {available}") + return task + + +def get_available_task_ids() -> List[str]: + """Return a sorted list of all registered task IDs.""" + return sorted(TASK_REGISTRY.keys()) + + +def get_task_files(task_id: str) -> List[str]: + """ + Return the list of source files belonging to a task. + + Args: + task_id: e.g. "task1" + + Returns: + List of filenames, e.g. ["broken_code.py", "helper.py"] + """ + return get_task_by_id(task_id)["files"] + + +def validate_task_id(task_id: str) -> bool: + """ + Check whether a task ID is registered. + + Args: + task_id: The task ID to validate. + + Returns: + True if the task exists, False otherwise. + """ + return task_id in TASK_REGISTRY diff --git a/debug_env/server/tasks/loader.py b/debug_env/server/tasks/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..1c920368f1da972d043e7245d1ab9f75054e38fd --- /dev/null +++ b/debug_env/server/tasks/loader.py @@ -0,0 +1,241 @@ +""" +TaskLoader — copies task source files into a fresh temp directory for each episode. + +Task layout on disk: + debug_env/tasks/ + task1/ + broken_code.py + test_code.py + task2/ + broken_code.py + test_code.py + task3/ + broken_code.py + helper.py + test_code.py +""" + +import shutil +import tempfile +from pathlib import Path + +from debug_env.server.tasks.data import get_available_task_ids, validate_task_id + +TASKS_DIR = Path(__file__).parent.parent.parent / "tasks" + + +class TaskLoader: + """Manages task file staging into isolated temp directories.""" + + @staticmethod + def available_tasks() -> list[str]: + """Return sorted list of registered task IDs.""" + return get_available_task_ids() + + @staticmethod + def load(task_id: str, previous_workdir: str | None = None) -> str: + """ + Copy all files for *task_id* into a fresh temp directory. + For tasks with seed data, generates files from seed data. + + Args: + task_id: e.g. "task1" + previous_workdir: if provided, this directory is deleted first. + + Returns: + Path to the new workdir (str). + + Raises: + ValueError: if task_id is not in the registry. + FileNotFoundError: if task files are missing from disk. + """ + if not validate_task_id(task_id): + available = get_available_task_ids() + raise ValueError( + f"Unknown task '{task_id}'. Available: {available}" + ) + + if previous_workdir: + shutil.rmtree(previous_workdir, ignore_errors=True) + + workdir = tempfile.mkdtemp(prefix=f"debug_{task_id}_") + + # For tasks with seed data, generate files from seed data + if task_id == "task4": + TaskLoader._generate_task4_files(workdir) + elif task_id == "task5": + TaskLoader._generate_task5_files(workdir) + elif task_id == "task6": + TaskLoader._generate_task6_files(workdir) + elif task_id == "task7": + TaskLoader._generate_task7_files(workdir) + elif task_id == "task8": + TaskLoader._generate_task8_files(workdir) + elif task_id == "task9": + TaskLoader._generate_task9_files(workdir) + else: + # For other tasks, copy from disk + task_path = TASKS_DIR / task_id + if not task_path.is_dir(): + raise FileNotFoundError( + f"Task files for '{task_id}' not found on disk at {task_path}" + ) + + for f in task_path.iterdir(): + if f.is_file(): + shutil.copy2(f, workdir) + + return workdir + + @staticmethod + def _generate_task4_files(workdir: str) -> None: + """Generate task4 files from seed data.""" + from debug_env.tasks.task4.seed_data import ( + get_task4_seed_data, + get_test_file_content, + ) + + seed = get_task4_seed_data() + for filename, content in seed["files"].items(): + filepath = Path(workdir) / filename + filepath.write_text(content, encoding="utf-8") + + # Write test file + test_content = get_test_file_content() + (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8") + + @staticmethod + def _generate_task5_files(workdir: str) -> None: + """Generate task5 files from seed data.""" + from debug_env.tasks.task5.seed_data import ( + get_task5_seed_data, + get_test_file_content, + ) + + seed = get_task5_seed_data() + for filename, content in seed["files"].items(): + filepath = Path(workdir) / filename + filepath.write_text(content, encoding="utf-8") + + # Write test file + test_content = get_test_file_content() + (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8") + + @staticmethod + def _generate_task6_files(workdir: str) -> None: + """Generate task6 files from seed data.""" + from debug_env.tasks.task6.seed_data import ( + get_task6_seed_data, + get_test_file_content, + ) + + seed = get_task6_seed_data() + for filename, content in seed["files"].items(): + filepath = Path(workdir) / filename + filepath.write_text(content, encoding="utf-8") + + # Write test file + test_content = get_test_file_content() + (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8") + + @staticmethod + def _generate_task7_files(workdir: str) -> None: + """Generate task7 files from seed data.""" + from debug_env.tasks.task7.seed_data import ( + get_task7_seed_data, + get_test_auth_py_content, + ) + + seed = get_task7_seed_data() + for filename, content in seed["files"].items(): + filepath = Path(workdir) / filename + filepath.write_text(content, encoding="utf-8") + + # Write test file + test_content = get_test_auth_py_content() + (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8") + + @staticmethod + def _generate_task8_files(workdir: str) -> None: + """Generate task8 files from seed data.""" + from debug_env.tasks.task8.seed_data import ( + get_task8_seed_data, + get_test_user_service_content, + ) + + seed = get_task8_seed_data() + for filename, content in seed["files"].items(): + filepath = Path(workdir) / filename + filepath.write_text(content, encoding="utf-8") + + # Write test file + test_content = get_test_user_service_content() + (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8") + + @staticmethod + def _generate_task9_files(workdir: str) -> None: + """Generate task9 files from seed data.""" + from debug_env.tasks.task9.seed_data import ( + get_task9_seed_data, + get_test_file_content, + ) + + seed = get_task9_seed_data() + for filename, content in seed["files"].items(): + filepath = Path(workdir) / filename + filepath.write_text(content, encoding="utf-8") + + # Write test file + test_content = get_test_file_content() + (Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8") + + @staticmethod + def list_source_files(task_id: str) -> list[str]: + """ + Return the editable source filenames for a task (excludes test files). + + Args: + task_id: e.g. "task1" + + Returns: + Sorted list of filenames, e.g. ["broken_code.py"] + + Raises: + ValueError: if task_id is not registered. + """ + if not validate_task_id(task_id): + raise ValueError(f"Unknown task '{task_id}'.") + task_path = TASKS_DIR / task_id + return sorted( + f.name for f in task_path.iterdir() + if f.is_file() and not f.name.startswith("test_") + ) + + @staticmethod + def read_source_file(task_id: str, filename: str) -> str: + """ + Read the canonical (pre-episode) content of a source file. + + Args: + task_id: e.g. "task1" + filename: e.g. "broken_code.py" + + Returns: + File content as a string. + + Raises: + ValueError: if task_id is not registered or filename is invalid. + FileNotFoundError: if the file does not exist on disk. + """ + if not validate_task_id(task_id): + raise ValueError(f"Unknown task '{task_id}'.") + if ".." in filename or filename.startswith("/"): + raise ValueError(f"Invalid filename '{filename}'.") + file_path = TASKS_DIR / task_id / filename + if not file_path.is_file(): + available = TaskLoader.list_source_files(task_id) + raise FileNotFoundError( + f"File '{filename}' not found in task '{task_id}'. " + f"Available source files: {available}" + ) + return file_path.read_text(encoding="utf-8") diff --git a/debug_env/server/tasks/router.py b/debug_env/server/tasks/router.py new file mode 100644 index 0000000000000000000000000000000000000000..2199bf094d5bb831be3aff10251d9086984cac29 --- /dev/null +++ b/debug_env/server/tasks/router.py @@ -0,0 +1,387 @@ +""" +Tasks API endpoints +Provides task metadata, episode management, and source file access for the debug-env benchmark. +""" + +import logging +from typing import Any, Dict, List + +from fastapi import APIRouter, HTTPException, status, Depends +from pydantic import ValidationError +from sqlalchemy.orm import Session + +from debug_env.server.tasks.data import get_available_task_ids, get_task_by_id, validate_task_id +from debug_env.server.tasks.loader import TaskLoader +from debug_env.server.database.db import get_db +from debug_env.server.database.managers.task_manager import get_task_manager +from debug_env.server.schemas.task_schemas import ( + TaskListResponse, + TaskResponse, + EpisodeResponse, + EpisodeListResponse, + EpisodeCreateRequest, + EpisodePatchRequest, +) + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/tasks", tags=["tasks"]) + + +def _format_validation_error(e: ValidationError) -> str: + """Format a Pydantic ValidationError into a human-readable string.""" + messages = [] + for error in e.errors(): + field = " -> ".join(str(loc) for loc in error["loc"]) + messages.append(f"{field}: {error['msg']}") + return "Validation failed: " + "; ".join(messages) + + +@router.get("", response_model=Dict[str, Any]) +async def list_tasks( + db: Session = Depends(get_db), + maxResults: int = 50, + pageToken: str = None, + syncToken: str = None, +): + """ + Returns metadata for all available debug tasks with pagination support. + + Query Parameters: + - maxResults: Maximum tasks per page (default: 50) + - pageToken: Pagination token from previous response + - syncToken: Sync token for incremental updates + + GET /tasks + """ + try: + # Get user_id from header (default to "default_user" if not provided) + user_id = "default_user" + + # Use TaskManager for listing with pagination + manager = get_task_manager(db, user_id) + response = manager.list_tasks( + max_results=maxResults, + page_token=pageToken, + sync_token=syncToken, + ) + + # Convert to dict response matching schema + return { + "etag": response.etag, + "items": [TaskResponse.model_validate(item).model_dump() for item in response.items], + "nextPageToken": response.nextPageToken, + "nextSyncToken": response.nextSyncToken, + } + except ValueError as e: + logger.error(f"Validation error listing tasks: {e}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=str(e), + ) + except Exception as e: + logger.error(f"Error listing tasks: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Internal server error occurred while listing tasks", + ) + + +@router.get("/{taskId}", response_model=Dict[str, Any]) +async def get_task(taskId: str): + """ + Returns metadata for a specific debug task. + + GET /tasks/{taskId} + """ + try: + if not validate_task_id(taskId): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Task '{taskId}' not found. Available: {get_available_task_ids()}", + ) + task = get_task_by_id(taskId) + logger.info(f"Retrieved task metadata for '{taskId}'") + return task + except HTTPException: + raise + except ValidationError as e: + # Handle unexpected schema validation errors + logger.error(f"Schema validation error for task '{taskId}': {e}") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=_format_validation_error(e), + ) + except Exception as e: + logger.error(f"Error getting task '{taskId}': {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Internal server error occurred while retrieving task", + ) + + +@router.get("/{taskId}/files", response_model=List[str]) +async def list_task_files(taskId: str): + """ + Returns the list of editable source files for a task (excludes test files). + + GET /tasks/{taskId}/files + """ + try: + if not validate_task_id(taskId): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Task '{taskId}' not found. Available: {get_available_task_ids()}", + ) + files = TaskLoader.list_source_files(taskId) + logger.info(f"Listed {len(files)} source files for task '{taskId}'") + return files + except HTTPException: + raise + except ValueError as e: + # Handle business logic validation errors (invalid task ID) + logger.error(f"Validation error listing files for task '{taskId}': {e}") + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid task or request parameters") + except FileNotFoundError as e: + # Task is registered but files are missing from disk + logger.error(f"Task files missing on disk for '{taskId}': {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Internal server error occurred while listing task files", + ) + except Exception as e: + logger.error(f"Error listing files for task '{taskId}': {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Internal server error occurred while listing task files", + ) + + +@router.get("/{taskId}/files/{filename}", response_model=Dict[str, str]) +async def get_task_file(taskId: str, filename: str): + """ + Returns the canonical (pre-episode) content of a source file. + + Use this to inspect the original broken code before starting an episode. + During an episode, use the read_file tool via POST /step instead. + + GET /tasks/{taskId}/files/{filename} + """ + try: + if not validate_task_id(taskId): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Task '{taskId}' not found. Available: {get_available_task_ids()}", + ) + content = TaskLoader.read_source_file(taskId, filename) + logger.info(f"Read source file '{filename}' for task '{taskId}'") + return {"task_id": taskId, "filename": filename, "content": content} + except HTTPException: + raise + except ValueError as e: + # Handle business logic validation errors (invalid filename, path traversal) + logger.error(f"Validation error reading file '{filename}' for task '{taskId}': {e}") + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid filename or request parameters") + except FileNotFoundError as e: + # File not found within the task + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) + except Exception as e: + logger.error(f"Error reading file '{filename}' for task '{taskId}': {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Internal server error occurred while reading task file", + ) + + +# ── Episode Management Endpoints ─────────────────────────────────────────── + + +@router.post("/{taskId}/episodes", response_model=Dict[str, Any]) +async def create_episode( + taskId: str, + db: Session = Depends(get_db), +): + """ + Create a new episode (task run) for the current user. + + POST /tasks/{taskId}/episodes + + Returns: + - id: Episode identifier (uuid4) + - task_id: Task identifier + - status: "active" + - workdir: Path to working directory with task files + - etag: Cache validation tag + """ + try: + if not validate_task_id(taskId): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Task '{taskId}' not found", + ) + + user_id = "default_user" + manager = get_task_manager(db, user_id) + + # Load task files into temp directory + workdir = TaskLoader.load(taskId) + + # Create episode record + episode = manager.create_episode(taskId, workdir) + + logger.info(f"Created episode {episode.id} for task {taskId}") + return EpisodeResponse.model_validate(episode).model_dump() + + except HTTPException: + raise + except ValueError as e: + logger.error(f"Validation error creating episode for task {taskId}: {e}") + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + except Exception as e: + logger.error(f"Error creating episode for task {taskId}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Internal server error occurred while creating episode", + ) + + +@router.get("/{taskId}/episodes", response_model=Dict[str, Any]) +async def list_episodes( + taskId: str, + db: Session = Depends(get_db), + maxResults: int = 50, + pageToken: str = None, +): + """ + List episodes for a task with pagination. + + GET /tasks/{taskId}/episodes + + Query Parameters: + - maxResults: Maximum episodes per page (default: 50) + - pageToken: Pagination token from previous response + """ + try: + if not validate_task_id(taskId): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Task '{taskId}' not found", + ) + + user_id = "default_user" + manager = get_task_manager(db, user_id) + + response = manager.list_episodes(taskId, max_results=maxResults, page_token=pageToken) + + return { + "items": [EpisodeResponse.model_validate(item).model_dump() for item in response.items], + "nextPageToken": response.nextPageToken, + } + + except HTTPException: + raise + except ValueError as e: + logger.error(f"Validation error listing episodes for task {taskId}: {e}") + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + except Exception as e: + logger.error(f"Error listing episodes for task {taskId}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Internal server error occurred while listing episodes", + ) + + +@router.get("/{taskId}/episodes/{episodeId}", response_model=Dict[str, Any]) +async def get_episode( + taskId: str, + episodeId: str, + db: Session = Depends(get_db), +): + """ + Retrieve a specific episode. + + GET /tasks/{taskId}/episodes/{episodeId} + """ + try: + if not validate_task_id(taskId): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Task '{taskId}' not found", + ) + + user_id = "default_user" + manager = get_task_manager(db, user_id) + + episode = manager.get_episode(taskId, episodeId) + if not episode: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Episode '{episodeId}' not found for task '{taskId}'", + ) + + return EpisodeResponse.model_validate(episode).model_dump() + + except HTTPException: + raise + except Exception as e: + logger.error(f"Error retrieving episode {episodeId} for task {taskId}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Internal server error occurred while retrieving episode", + ) + + +@router.patch("/{taskId}/episodes/{episodeId}", response_model=Dict[str, Any]) +async def update_episode( + taskId: str, + episodeId: str, + request: EpisodePatchRequest, + db: Session = Depends(get_db), +): + """ + Update an episode's status and/or pass_rate. + + PATCH /tasks/{taskId}/episodes/{episodeId} + + Request Body: + - status: Optional, new status ("active", "passed", "failed", "abandoned") + - pass_rate: Optional, pass rate (0.0-1.0) + """ + try: + if not validate_task_id(taskId): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Task '{taskId}' not found", + ) + + user_id = "default_user" + manager = get_task_manager(db, user_id) + + # Get current episode + episode = manager.get_episode(taskId, episodeId) + if not episode: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Episode '{episodeId}' not found for task '{taskId}'", + ) + + # Update with provided fields + status = request.status if request.status else episode.status + pass_rate = request.pass_rate if request.pass_rate is not None else episode.pass_rate + + updated_episode = manager.update_episode(taskId, episodeId, status, pass_rate) + + logger.info(f"Updated episode {episodeId} for task {taskId}") + return EpisodeResponse.model_validate(updated_episode).model_dump() + + except HTTPException: + raise + except ValueError as e: + logger.error(f"Validation error updating episode {episodeId}: {e}") + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + except Exception as e: + logger.error(f"Error updating episode {episodeId}: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Internal server error occurred while updating episode", + ) diff --git a/debug_env/server/tools/__init__.py b/debug_env/server/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ebe2881189170dabbda28e2d377744d88fbfa081 --- /dev/null +++ b/debug_env/server/tools/__init__.py @@ -0,0 +1,5 @@ +from .edit_file import edit_file +from .read_file import read_file +from .run_tests import run_tests + +__all__ = ["run_tests", "read_file", "edit_file"] diff --git a/debug_env/server/tools/advanced_tools.py b/debug_env/server/tools/advanced_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..6a318e7d871a52cac040791304a2ed56ef26d524 --- /dev/null +++ b/debug_env/server/tools/advanced_tools.py @@ -0,0 +1,520 @@ +""" +Advanced debugging tools for code analysis and inspection. + +Provides functions for: +- Code search (grep-like pattern matching) +- File structure analysis (AST parsing) +- Type checking (mypy integration) +- Test coverage analysis (coverage.py integration) +- Directory listing and navigation +- Import dependency analysis +""" + +import ast +import json +import logging +import os +import re +import subprocess +from pathlib import Path +from typing import Any, Dict, List + +logger = logging.getLogger(__name__) + + +def search_code( + workdir: str, + pattern: str, + file_types: str = "py", + case_sensitive: bool = False, + max_results: int = 50, + context_lines: int = 2, +) -> Dict[str, Any]: + """ + Search for code patterns across files in the task directory. + + Args: + workdir: Absolute path to task working directory + pattern: Text or regex pattern to search for + file_types: File type filter ("py", "all", "txt", "json", "md") + case_sensitive: Whether to match case + max_results: Maximum matches to return (1-500) + context_lines: Lines of context around each match (0-10) + + Returns: + Dict with matches, match count, files searched, and timing info + """ + try: + workdir_path = Path(workdir) + if not workdir_path.is_dir(): + return {"error": f"Invalid directory: {workdir}", "matches": [], "total_matches": 0} + + # Determine file extensions to search + if file_types == "all": + search_patterns = ["*"] + elif file_types == "py": + search_patterns = ["*.py"] + else: + search_patterns = [f"*.{file_types}"] + + # Compile regex pattern + flags = 0 if case_sensitive else re.IGNORECASE + try: + compiled_pattern = re.compile(pattern, flags) + except re.error as e: + return {"error": f"Invalid regex pattern: {e}", "matches": [], "total_matches": 0} + + matches = [] + files_searched = 0 + + # Search files + for search_pattern in search_patterns: + for file_path in workdir_path.rglob(search_pattern): + if not file_path.is_file(): + continue + + files_searched += 1 + try: + content = file_path.read_text(encoding="utf-8") + lines = content.split("\n") + + for line_num, line in enumerate(lines, 1): + for match in compiled_pattern.finditer(line): + if len(matches) >= max_results: + break + + matches.append({ + "filename": str(file_path.relative_to(workdir_path)), + "line_number": line_num, + "line_content": line, + "match_position": match.start(), + "before": lines[max(0, line_num - context_lines - 1):line_num - 1], + "after": lines[line_num:min(len(lines), line_num + context_lines)], + }) + except (UnicodeDecodeError, OSError): + continue + + logger.info(f"Search pattern '{pattern}': found {len(matches)} matches in {files_searched} files") + + return { + "matches": matches, + "total_matches": len(matches), + "files_searched": files_searched, + "search_time_ms": 0, # Would be measured in production + } + + except Exception as e: + logger.error(f"Error searching code: {e}") + return {"error": str(e), "matches": [], "total_matches": 0} + + +def get_file_structure( + workdir: str, + path: str, + include_docstrings: bool = True, + include_signatures: bool = True, + max_depth: int = 0, +) -> Dict[str, Any]: + """ + Parse and return the structure (AST) of a Python file. + + Args: + workdir: Absolute path to task working directory + path: File path relative to workdir + include_docstrings: Include docstrings in output + include_signatures: Include function/method signatures + max_depth: Maximum nesting depth (0 for unlimited) + + Returns: + Dict with classes, functions, imports, and constants + """ + try: + file_path = Path(workdir) / path + if not file_path.is_file(): + return {"error": f"File not found: {path}"} + + content = file_path.read_text(encoding="utf-8") + tree = ast.parse(content) + + structure = { + "filename": path, + "imports": [], + "classes": [], + "functions": [], + "constants": [], + } + + for node in ast.walk(tree): + # Extract imports + if isinstance(node, ast.Import): + for alias in node.names: + structure["imports"].append({ + "module": alias.name, + "items": [alias.asname or alias.name], + "line_number": node.lineno, + }) + + elif isinstance(node, ast.ImportFrom): + items = [alias.name for alias in node.names] + structure["imports"].append({ + "module": node.module or "", + "items": items, + "line_number": node.lineno, + }) + + # Extract classes + elif isinstance(node, ast.ClassDef): + class_info = { + "name": node.name, + "line_number": node.lineno, + "methods": [], + "attributes": [], + } + + if include_docstrings: + class_info["docstring"] = ast.get_docstring(node) + + for item in node.body: + if isinstance(item, ast.FunctionDef): + class_info["methods"].append({ + "name": item.name, + "line_number": item.lineno, + }) + + structure["classes"].append(class_info) + + # Extract top-level functions + for node in tree.body: + if isinstance(node, ast.FunctionDef): + func_info = { + "name": node.name, + "line_number": node.lineno, + } + + if include_signatures: + func_info["parameters"] = [arg.arg for arg in node.args.args] + + if include_docstrings: + func_info["docstring"] = ast.get_docstring(node) + + structure["functions"].append(func_info) + + logger.info(f"Extracted structure from {path}") + return structure + + except SyntaxError as e: + logger.error(f"Syntax error in {path}: {e}") + return {"error": f"Syntax error: {e}"} + except Exception as e: + logger.error(f"Error getting file structure: {e}") + return {"error": str(e)} + + +def run_type_check( + workdir: str, + path: str, + strict: bool = False, + ignore_missing_imports: bool = True, + show_error_codes: bool = True, + max_errors: int = 100, +) -> Dict[str, Any]: + """ + Run static type checking (mypy) on Python files. + + Args: + workdir: Absolute path to task working directory + path: File or directory path relative to workdir + strict: Enable strict type checking mode + ignore_missing_imports: Ignore untyped third-party imports + show_error_codes: Show mypy error codes + max_errors: Maximum errors to report + + Returns: + Dict with type check results and error list + """ + try: + check_path = Path(workdir) / path + if not check_path.exists(): + return {"error": f"Path not found: {path}", "status": "error"} + + cmd = ["mypy", str(check_path)] + + if strict: + cmd.append("--strict") + if ignore_missing_imports: + cmd.append("--ignore-missing-imports") + if show_error_codes: + cmd.append("--show-error-codes") + + cmd.extend(["--no-error-summary", f"--max-errors={max_errors}"]) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + cwd=workdir, + timeout=30, + ) + + # Parse output + errors = [] + for line in result.stdout.split("\n"): + if not line.strip(): + continue + + # mypy output format: file:line:column: error: message [error-code] + match = re.match( + r"^([^:]+):(\d+):(\d+): error: (.+)(?:\s+\[([^\]]+)\])?$", + line + ) + if match: + errors.append({ + "file": match.group(1), + "line": int(match.group(2)), + "column": int(match.group(3)), + "message": match.group(4), + "error_code": match.group(5), + }) + + status = "success" if result.returncode == 0 else "errors_found" + + logger.info(f"Type check {path}: {len(errors)} errors, status={status}") + + return { + "path": path, + "status": status, + "error_count": len(errors), + "errors": errors, + "check_time_ms": 0, + } + + except subprocess.TimeoutExpired: + logger.error(f"Type check timeout for {path}") + return {"error": "Type check timeout", "status": "error"} + except Exception as e: + logger.error(f"Error running type check: {e}") + return {"error": str(e), "status": "error"} + + +def get_test_coverage( + workdir: str, + path: str = ".", + branch_coverage: bool = False, + include_missing: bool = True, + fail_under: int = 0, +) -> Dict[str, Any]: + """ + Analyze test coverage for Python files. + + Args: + workdir: Absolute path to task working directory + path: File or directory path relative to workdir + branch_coverage: Include branch coverage analysis + include_missing: Show which lines are not covered + fail_under: Minimum required coverage percentage + + Returns: + Dict with coverage percentage, file breakdown, and statistics + """ + try: + cmd = ["coverage", "run", "-m", "pytest", workdir] + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + cwd=workdir, + timeout=60, + ) + + # Get coverage report + cmd = ["coverage", "json", "--pretty-print"] + result = subprocess.run( + cmd, + capture_output=True, + text=True, + cwd=workdir, + timeout=30, + ) + + coverage_data = json.loads(result.stdout) + total_coverage = coverage_data.get("totals", {}).get("percent_covered", 0) + + logger.info(f"Coverage for {path}: {total_coverage}%") + + return { + "total_coverage": round(total_coverage, 1), + "files": [], + "functions": [], + "status": "covered" if total_coverage >= fail_under else "uncovered", + "check_time_ms": 0, + } + + except Exception as e: + logger.error(f"Error analyzing coverage: {e}") + return {"error": str(e), "total_coverage": 0, "status": "error"} + + +def list_directory( + workdir: str, + path: str = ".", + recursive: bool = True, + max_depth: int = 0, + include_hidden: bool = False, + file_types: str = "all", +) -> Dict[str, Any]: + """ + List files and directories in the task working directory. + + Args: + workdir: Absolute path to task working directory + path: Subdirectory path relative to workdir + recursive: Include subdirectories recursively + max_depth: Maximum directory nesting depth (0 for unlimited) + include_hidden: Include hidden files/folders starting with . + file_types: Filter by file type ("py", "all", "test", "source") + + Returns: + Dict with directory tree, file count, and metadata + """ + try: + root_path = Path(workdir) / path + if not root_path.is_dir(): + return {"error": f"Directory not found: {path}"} + + def walk_tree(directory: Path, depth: int = 0) -> List[Dict]: + if max_depth > 0 and depth >= max_depth: + return [] + + items = [] + try: + for entry in sorted(directory.iterdir()): + # Skip hidden files if needed + if entry.name.startswith(".") and not include_hidden: + continue + + # Filter by file type + if file_types == "py" and entry.is_file() and not entry.suffix == ".py": + continue + elif file_types == "test" and entry.is_file() and not entry.name.startswith("test_"): + continue + + item = { + "name": entry.name, + "type": "directory" if entry.is_dir() else "file", + "path": str(entry.relative_to(Path(workdir))), + } + + if entry.is_file(): + item["size_bytes"] = entry.stat().st_size + item["is_test"] = entry.name.startswith("test_") + + if entry.is_dir() and recursive: + item["contents"] = walk_tree(entry, depth + 1) + + items.append(item) + except PermissionError: + pass + + return items + + items = walk_tree(root_path) + + # Count files + total_files = sum(1 for entry in root_path.rglob("*") if entry.is_file()) + total_dirs = sum(1 for entry in root_path.rglob("*") if entry.is_dir()) + + logger.info(f"Listed directory {path}: {total_files} files, {total_dirs} directories") + + return { + "root_path": path, + "total_files": total_files, + "total_directories": total_dirs, + "items": items, + "tree_depth": max_depth, + } + + except Exception as e: + logger.error(f"Error listing directory: {e}") + return {"error": str(e)} + + +def get_dependencies( + workdir: str, + path: str, + include_stdlib: bool = False, + include_external: bool = True, + direction: str = "to", + depth: int = 1, +) -> Dict[str, Any]: + """ + Extract and analyze Python import dependencies. + + Args: + workdir: Absolute path to task working directory + path: File or directory path relative to workdir + include_stdlib: Include Python standard library imports + include_external: Include third-party library imports + direction: Show imports "to" or "from" + depth: Maximum depth to follow dependencies + + Returns: + Dict with dependency graph, cycles, and unused imports + """ + try: + target_path = Path(workdir) / path + if not target_path.exists(): + return {"error": f"Path not found: {path}"} + + dependencies = { + "path": path, + "direct_dependencies": [], + "indirect_dependencies": [], + "circular_dependencies": [], + "unused_imports": [], + "dependency_count": 0, + } + + # Find Python files to analyze + if target_path.is_file(): + py_files = [target_path] + else: + py_files = list(target_path.rglob("*.py")) + + # Parse imports from each file + for py_file in py_files: + try: + content = py_file.read_text(encoding="utf-8") + tree = ast.parse(content) + + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + dependencies["direct_dependencies"].append({ + "module": alias.name, + "type": "import", + "line_number": node.lineno, + "is_local": False, + }) + + elif isinstance(node, ast.ImportFrom): + dependencies["direct_dependencies"].append({ + "module": node.module or "", + "type": "from...import", + "items": [alias.name for alias in node.names], + "line_number": node.lineno, + "is_local": not (node.module and ("." not in node.module)), + }) + + except (SyntaxError, UnicodeDecodeError): + continue + + dependencies["dependency_count"] = len(dependencies["direct_dependencies"]) + + logger.info(f"Analyzed dependencies for {path}: {dependencies['dependency_count']} imports") + + return dependencies + + except Exception as e: + logger.error(f"Error analyzing dependencies: {e}") + return {"error": str(e)} \ No newline at end of file diff --git a/debug_env/server/tools/edit_file/__init__.py b/debug_env/server/tools/edit_file/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb4e4044d6b665deab6267096db8a1e6d0a89a8 --- /dev/null +++ b/debug_env/server/tools/edit_file/__init__.py @@ -0,0 +1,3 @@ +from .tool import edit_file + +__all__ = ["edit_file"] diff --git a/debug_env/server/tools/edit_file/tool.py b/debug_env/server/tools/edit_file/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..ffe3f86b36eed2cca4aebfba61f304c7d6d0e84e --- /dev/null +++ b/debug_env/server/tools/edit_file/tool.py @@ -0,0 +1,53 @@ +""" +edit_file tool — validates the request, writes the file, then re-runs tests. +""" + +import logging + +from pydantic import ValidationError + +from debug_env.server.schemas import EditFileArgs, ToolResult +from debug_env.server.tools.run_tests import run_tests +from debug_env.server.utils import validate_workdir_path + +logger = logging.getLogger(__name__) + + +def edit_file(workdir: str, path: str, content: str) -> ToolResult: + """ + Overwrite *path* (relative to *workdir*) with *content*, then run tests. + + Args: + workdir: Absolute path to the task working directory. + path: Filename to edit, e.g. ``"broken_code.py"`` or ``"helper.py"``. + content: Complete new file content. + + Returns: + :class:`ToolResult` with ``pass_rate`` and ``logs``. + """ + try: + args = EditFileArgs(path=path, content=content) + except ValidationError as e: + messages = [f"{' -> '.join(str(loc) for loc in err['loc'])}: {err['msg']}" for err in e.errors()] + msg = "Invalid edit_file args — " + "; ".join(messages) + logger.warning(msg) + return ToolResult(pass_rate=0.0, logs=msg, success=False) + + try: + full_path = validate_workdir_path(workdir, args.path) + except ValueError as e: + logger.warning(str(e)) + return ToolResult(pass_rate=0.0, logs=str(e), success=False) + + logger.info(f"Editing file: {full_path}") + + try: + with open(full_path, "w") as f: + f.write(args.content) + logger.info(f"File written ({len(args.content)} chars) — running tests") + except OSError as e: + msg = f"Failed to write '{args.path}': {e}" + logger.error(msg) + return ToolResult(pass_rate=0.0, logs=msg, success=False) + + return run_tests(workdir) diff --git a/debug_env/server/tools/read_file/__init__.py b/debug_env/server/tools/read_file/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..30c9a36cdf8d4a86f34e37e2a3c3cbfc83a102bc --- /dev/null +++ b/debug_env/server/tools/read_file/__init__.py @@ -0,0 +1,3 @@ +from .tool import read_file + +__all__ = ["read_file"] diff --git a/debug_env/server/tools/read_file/tool.py b/debug_env/server/tools/read_file/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..dd7674828bd54cf06ec99bdd75f90b30cf6d5d47 --- /dev/null +++ b/debug_env/server/tools/read_file/tool.py @@ -0,0 +1,71 @@ +""" +read_file tool — returns the current content of a file in the task workdir. + +Allows the agent to inspect source files before deciding what to edit, +rather than guessing from test error messages alone. +""" + +import logging +import os + +from pydantic import ValidationError + +from debug_env.server.schemas import ReadFileArgs, ToolResult +from debug_env.server.utils import validate_workdir_path + +logger = logging.getLogger(__name__) + + +def read_file(workdir: str, path: str) -> ToolResult: + """ + Read *path* (relative to *workdir*) and return its content in ``logs``. + + Pass rate is preserved from the last test run — reading a file does not + affect the score. The content is returned in ``logs`` so the agent can + inspect it in the same observation field it already reads. + + Args: + workdir: Absolute path to the task working directory. + path: Filename to read, e.g. ``"broken_code.py"`` or ``"helper.py"``. + + Returns: + :class:`ToolResult` with ``pass_rate=0.0`` and file content in ``logs``. + """ + try: + args = ReadFileArgs(path=path) + except ValidationError as e: + messages = [f"{' -> '.join(str(loc) for loc in err['loc'])}: {err['msg']}" for err in e.errors()] + msg = "Invalid read_file args — " + "; ".join(messages) + logger.warning(msg) + return ToolResult(pass_rate=0.0, logs=msg, success=False) + + try: + full_path = validate_workdir_path(workdir, args.path) + except ValueError as e: + logger.warning(str(e)) + return ToolResult(pass_rate=0.0, logs=str(e), success=False) + + logger.info(f"Reading file: {full_path}") + + if not os.path.exists(full_path): + available = [f for f in os.listdir(workdir) if f.endswith(".py") and not f.startswith("test_")] + msg = ( + f"File '{args.path}' not found. " + f"Editable source files: {available}" + ) + logger.warning(msg) + return ToolResult(pass_rate=0.0, logs=msg, success=False) + + try: + with open(full_path) as f: + content = f.read() + logger.info(f"Read {len(content)} chars from '{args.path}'") + return ToolResult( + pass_rate=0.0, + logs=f"# {args.path}\n{content}", + success=True, + ) + except OSError as e: + msg = f"Failed to read '{args.path}': {e}" + logger.error(msg) + return ToolResult(pass_rate=0.0, logs=msg, success=False) diff --git a/debug_env/server/tools/run_tests/__init__.py b/debug_env/server/tools/run_tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05ec86c76c2d2a34da55fe5604fc2ea78ef87fc9 --- /dev/null +++ b/debug_env/server/tools/run_tests/__init__.py @@ -0,0 +1,3 @@ +from .tool import run_tests + +__all__ = ["run_tests"] diff --git a/debug_env/server/tools/run_tests/tool.py b/debug_env/server/tools/run_tests/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dc098f52b7b8fa74a2426578aac48ae72368b8 --- /dev/null +++ b/debug_env/server/tools/run_tests/tool.py @@ -0,0 +1,63 @@ +""" +run_tests tool — executes pytest inside the task workdir and returns a ToolResult. +""" + +import logging +import re +import subprocess + +from debug_env.server.schemas import ToolResult + +logger = logging.getLogger(__name__) + + +def _parse_pass_rate(output: str, returncode: int) -> float: + passed_match = re.search(r"(\d+) passed", output) + failed_match = re.search(r"(\d+) failed", output) + error_match = re.search(r"(\d+) error", output) + + passed = int(passed_match.group(1)) if passed_match else 0 + failed = int(failed_match.group(1)) if failed_match else 0 + errors = int(error_match.group(1)) if error_match else 0 + + total = passed + failed + errors + if total > 0: + return passed / total + return 1.0 if returncode == 0 else 0.0 + + +def run_tests(workdir: str) -> ToolResult: + """ + Run ``pytest -q --tb=short`` inside *workdir*. + + Args: + workdir: Absolute path to the task working directory. + + Returns: + :class:`ToolResult` with ``pass_rate`` and ``logs``. + """ + logger.info(f"Running tests in: {workdir}") + + try: + result = subprocess.run( + ["pytest", "-q", "--tb=short", workdir], + capture_output=True, + text=True, + cwd=workdir, + ) + output = result.stdout + result.stderr + pass_rate = _parse_pass_rate(output, result.returncode) + + logger.info(f"Tests complete — pass_rate={pass_rate:.2f} (returncode={result.returncode})") + + return ToolResult(pass_rate=pass_rate, logs=output, success=True) + + except FileNotFoundError: + msg = "pytest not found. Ensure it is installed in the environment." + logger.error(msg) + return ToolResult(pass_rate=0.0, logs=msg, success=False) + + except Exception as e: + msg = f"Unexpected error running tests: {e}" + logger.error(msg, exc_info=True) + return ToolResult(pass_rate=0.0, logs=msg, success=False) diff --git a/debug_env/server/tools/tool_handlers.py b/debug_env/server/tools/tool_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..3590d2e2192d0e0151673e2eb8b79ff32d455f21 --- /dev/null +++ b/debug_env/server/tools/tool_handlers.py @@ -0,0 +1,129 @@ +""" +MCP Tool Handlers — Generic dispatcher for debug_env analysis tools. + +This module provides a generic handler that dynamically executes MCP tools +based on tool configuration, eliminating per-tool if/elif chains and enabling +scalable tool dispatch. + +Pattern inspired by calendar_env's tool_handlers.py generic executor. +""" + +import logging +from typing import Dict, Any, Callable + +from debug_env.server.tools.advanced_tools import ( + search_code, + get_file_structure, + run_type_check, + get_test_coverage, + list_directory, + get_dependencies, +) + +logger = logging.getLogger(__name__) + +# Mapping of tool names to their implementation functions +# Each function signature: func(workdir: str, **kwargs) -> ToolResult +TOOL_IMPLEMENTATIONS: Dict[str, Callable[[str], Any]] = { + "search_code": search_code, + "get_file_structure": get_file_structure, + "run_type_check": run_type_check, + "get_test_coverage": get_test_coverage, + "list_directory": list_directory, + "get_dependencies": get_dependencies, +} + +# Lazy-loaded caches to avoid circular imports +_MCP_TOOLS_LIST = None +_TOOL_HANDLERS = None + + +def get_mcp_tools_list(): + """Get MCP tool definitions (lazy-loaded to avoid circular imports).""" + global _MCP_TOOLS_LIST + if _MCP_TOOLS_LIST is None: + from debug_env.server.mcp.tools.debug_tools import DEBUG_TOOLS + _MCP_TOOLS_LIST = DEBUG_TOOLS + return _MCP_TOOLS_LIST + + +def get_tool_handlers(): + """Get tool handlers dict (lazy-loaded to avoid circular imports).""" + global _TOOL_HANDLERS + if _TOOL_HANDLERS is None: + tools = get_mcp_tools_list() + _TOOL_HANDLERS = {tool["name"]: execute_tool_generic for tool in tools} + return _TOOL_HANDLERS + + +# Convenience aliases for backward compatibility +def __getattr__(name): + """Module-level __getattr__ for lazy loading.""" + if name == "MCP_TOOLS_LIST": + return get_mcp_tools_list() + elif name == "TOOL_HANDLERS": + return get_tool_handlers() + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") + + +async def execute_tool_generic( + tool_name: str, arguments: Dict[str, Any], workdir: str +) -> Dict[str, Any]: + """ + Generic tool executor that dispatches to the appropriate tool function. + + This replaces per-tool handlers and allows any tool to be executed + by looking up its implementation in TOOL_IMPLEMENTATIONS. + + Args: + tool_name: Name of the tool (e.g., "search_code") + arguments: Tool arguments from MCP request + workdir: Working directory for the episode (task files location) + + Returns: + Dict with "text" (result or error message) and "isError" (bool) + """ + try: + # Find tool implementation + if tool_name not in TOOL_IMPLEMENTATIONS: + logger.error(f"Unknown tool: {tool_name}") + return { + "text": f"Unknown tool: {tool_name}", + "isError": True, + } + + tool_func = TOOL_IMPLEMENTATIONS[tool_name] + + logger.debug(f"Executing tool {tool_name} with arguments: {arguments}") + + # Call the tool function with workdir and arguments + # Tool functions have signature: func(workdir: str, **kwargs) -> ToolResult + result = tool_func(workdir, **arguments) + + # Tool functions return ToolResult with 'logs' field containing output + # Check if result is an error based on logs content + is_error = "error" in result.logs.lower() or result.logs.startswith("Error") + + return { + "text": result.logs, + "isError": is_error, + } + + except TypeError as e: + logger.error(f"Missing required argument for {tool_name}: {e}") + return { + "text": f"Missing required argument: {e}", + "isError": True, + } + except ValueError as e: + logger.error(f"Invalid argument for {tool_name}: {e}") + return { + "text": f"Invalid argument: {e}", + "isError": True, + } + except Exception as e: + logger.error(f"Error executing {tool_name}: {e}") + return { + "text": f"Tool execution failed: {str(e)}", + "isError": True, + } diff --git a/debug_env/server/utils/__init__.py b/debug_env/server/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4acabaa9241abf6c3cfb21cd29d8cfd23839f0e2 --- /dev/null +++ b/debug_env/server/utils/__init__.py @@ -0,0 +1,3 @@ +from .validation import validate_workdir_path + +__all__ = ["validate_workdir_path"] diff --git a/debug_env/server/utils/validation.py b/debug_env/server/utils/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..722c50cce65126d466a86019c0af8a080128c609 --- /dev/null +++ b/debug_env/server/utils/validation.py @@ -0,0 +1,30 @@ +""" +Common validation utilities shared across tool handlers. +""" + +import os + + +def validate_workdir_path(workdir: str, path: str) -> str: + """ + Resolve *path* against *workdir* and verify it stays inside the workdir. + + Args: + workdir: Absolute path to the task working directory. + path: Relative filename from the agent (e.g. ``"broken_code.py"``). + + Returns: + The resolved absolute path. + + Raises: + ValueError: If the resolved path escapes the workdir boundary. + """ + resolved = os.path.realpath(os.path.join(workdir, path)) + workdir_real = os.path.realpath(workdir) + + if not resolved.startswith(workdir_real + os.sep) and resolved != workdir_real: + raise ValueError( + f"Path '{path}' resolves outside the task workdir — access denied." + ) + + return resolved diff --git a/debug_env/tasks/task1/broken_code.py b/debug_env/tasks/task1/broken_code.py new file mode 100644 index 0000000000000000000000000000000000000000..8666aa5c22013cb1d5e125c7b9ad9385be74dec7 --- /dev/null +++ b/debug_env/tasks/task1/broken_code.py @@ -0,0 +1,5 @@ +def add(a, b): + return a + b + +def multiply(a, b): + return a * b diff --git a/debug_env/tasks/task1/test_code.py b/debug_env/tasks/task1/test_code.py new file mode 100644 index 0000000000000000000000000000000000000000..6df75849fa7f0aae8539ec696cdf1b48919b84d2 --- /dev/null +++ b/debug_env/tasks/task1/test_code.py @@ -0,0 +1,13 @@ +from broken_code import add, multiply + + +def test_add(): + assert add(1, 2) == 3 + assert add(0, 0) == 0 + assert add(-1, 1) == 0 + + +def test_multiply(): + assert multiply(3, 4) == 12 + assert multiply(0, 5) == 0 + assert multiply(-2, 3) == -6 diff --git a/debug_env/tasks/task2/broken_code.py b/debug_env/tasks/task2/broken_code.py new file mode 100644 index 0000000000000000000000000000000000000000..64b6a902cf93ec2bf4f39304d842fc96fa5701f2 --- /dev/null +++ b/debug_env/tasks/task2/broken_code.py @@ -0,0 +1,10 @@ +def is_even(n): + return n % 2 == 1 # Bug: should be == 0 + + +def get_evens(numbers): + return [n for n in numbers if is_even(n)] + + +def sum_of_evens(numbers): + return sum(get_evens(numbers)) diff --git a/debug_env/tasks/task2/test_code.py b/debug_env/tasks/task2/test_code.py new file mode 100644 index 0000000000000000000000000000000000000000..34799396c8c9ae212d776e90c316fb58678c5e7a --- /dev/null +++ b/debug_env/tasks/task2/test_code.py @@ -0,0 +1,20 @@ +from broken_code import is_even, get_evens, sum_of_evens + + +def test_is_even(): + assert is_even(2) == True + assert is_even(3) == False + assert is_even(0) == True + assert is_even(7) == False + + +def test_get_evens(): + assert get_evens([1, 2, 3, 4]) == [2, 4] + assert get_evens([1, 3, 5]) == [] + assert get_evens([2, 4, 6]) == [2, 4, 6] + + +def test_sum_of_evens(): + assert sum_of_evens([1, 2, 3, 4, 5, 6]) == 12 + assert sum_of_evens([1, 3, 5]) == 0 + assert sum_of_evens([]) == 0 diff --git a/debug_env/tasks/task3/broken_code.py b/debug_env/tasks/task3/broken_code.py new file mode 100644 index 0000000000000000000000000000000000000000..ed6d3ae48706d365fb7d50ac39512bb80faeb611 --- /dev/null +++ b/debug_env/tasks/task3/broken_code.py @@ -0,0 +1,27 @@ +from helper import clamp + + +def normalize_grade(score): + """Clamp score to valid 0-100 range.""" + return clamp(score, 0, 100) + + +def letter_grade(score): + """Convert numeric score to letter grade.""" + score = normalize_grade(score) + if score >= 90: + return 'A' + elif score >= 80: + return 'B' + elif score >= 70: + return 'C' + elif score >= 60: + return 'D' + else: + return 'F' + + +def class_average(scores): + if not scores: + return 0.0 + return sum(scores) / len(scores) diff --git a/debug_env/tasks/task3/helper.py b/debug_env/tasks/task3/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..6f56308982046229cc244039a1c88f0d4eb0c8aa --- /dev/null +++ b/debug_env/tasks/task3/helper.py @@ -0,0 +1,6 @@ +def clamp(value, min_val, max_val): + if value < min_val: + return max_val # Bug: should return min_val + if value > max_val: + return min_val # Bug: should return max_val + return value diff --git a/debug_env/tasks/task3/test_code.py b/debug_env/tasks/task3/test_code.py new file mode 100644 index 0000000000000000000000000000000000000000..4abf50127b0cfdabbc46cb79d4c67fc0afad5077 --- /dev/null +++ b/debug_env/tasks/task3/test_code.py @@ -0,0 +1,21 @@ +from broken_code import normalize_grade, letter_grade, class_average + + +def test_normalize_grade(): + assert normalize_grade(85) == 85 + assert normalize_grade(-10) == 0 + assert normalize_grade(110) == 100 + + +def test_letter_grade(): + assert letter_grade(95) == 'A' + assert letter_grade(85) == 'B' + assert letter_grade(75) == 'C' + assert letter_grade(65) == 'D' + assert letter_grade(50) == 'F' + + +def test_class_average(): + assert class_average([80, 90, 70]) == 80.0 + assert class_average([]) == 0.0 + assert class_average([100]) == 100.0 diff --git a/debug_env/tasks/task4/__init__.py b/debug_env/tasks/task4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a9747a702a0a1405199aae564137f1675cc60b --- /dev/null +++ b/debug_env/tasks/task4/__init__.py @@ -0,0 +1 @@ +"""Task 4: Type Error Detection""" \ No newline at end of file diff --git a/debug_env/tasks/task4/seed_data.py b/debug_env/tasks/task4/seed_data.py new file mode 100644 index 0000000000000000000000000000000000000000..67253a324e57d0e98e792c9c6c6c8b392685275d --- /dev/null +++ b/debug_env/tasks/task4/seed_data.py @@ -0,0 +1,223 @@ +""" +Task 4: Type Error Detection Seed Data + +Comprehensive seed data for type error detection task. +Contains Python code with type hint mismatches and type incompatibilities +that can be found using mypy static type checking. +""" + +from typing import Any, Dict, List + + +def get_task4_seed_data() -> Dict[str, Any]: + """ + Generate seed data for task4 (Type Error Detection). + + Files: + - typed_code.py: Main module with type annotations and errors + - helper.py: Helper module with incompatible return types + + Type Errors Present: + 1. Function parameter type mismatch (passing str instead of int) + 2. Return type doesn't match annotation (returning None instead of str) + 3. Attribute access on potentially None type + 4. Incompatible type in assignment + 5. Missing argument in function call + 6. Wrong argument type in method call + """ + return { + "files": { + "typed_code.py": get_typed_code_content(), + "helper.py": get_helper_content(), + }, + "test_file": "test_typed_code.py", + "expected_issues": [ + "Line 15: Argument 1 to 'process_number' has incompatible type 'str'; expected 'int'", + "Line 28: Incompatible return value type (got 'None', expected 'str')", + "Line 37: Item 'None' has no attribute 'upper'", + "Line 42: Incompatible types in assignment (expression has type 'int', variable has type 'str')", + "Line 50: Missing positional argument 'required_param' in call to 'validate_input'", + "Line 61: Argument 1 to 'calculate_average' has incompatible type 'list[str]'; expected 'list[int]'", + ], + "tools_to_use": [ + "run_type_check", + "get_file_structure", + "edit_file", + "run_tests", + ], + "difficulty": "medium", + } + + +def get_typed_code_content() -> str: + """Get the broken typed_code.py file content.""" + return '''""" +Typed module with intentional type errors for debugging. +""" + +from typing import Optional, List +from helper import safe_divide, validate_input + + +def process_number(value: int) -> int: + """Process a number and return the result.""" + return value * 2 + + +def calculate_stats(numbers: List[int]) -> str: + """Calculate statistics and return formatted string.""" + if not numbers: + return # Type error: no return value when return type is str + + total = sum(numbers) + average = total / len(numbers) + return f"Average: {average}" + + +def format_name(name: Optional[str]) -> str: + """Format and return a person's name.""" + if name: + # Type error: name could be None, can't call .upper() on Optional[str] + return name.upper() + return "UNKNOWN" + + +def main(): + """Main function with multiple type errors.""" + # Type error: passing string instead of int + result1 = process_number("42") + + # Type error: assigning int to str variable + formatted_string: str = 100 + + # Type error: missing required parameter + validated = validate_input() + + # Type error: passing list of strings instead of list of ints + stats = calculate_stats(["1", "2", "3"]) + + # Correct usage for reference + correct_result = process_number(42) + correct_stats = calculate_stats([1, 2, 3]) + + return { + "result1": result1, + "formatted_string": formatted_string, + "validated": validated, + "stats": stats, + "correct_result": correct_result, + } + + +if __name__ == "__main__": + main() +''' + + +def get_helper_content() -> str: + """Get the helper.py file content.""" + return '''""" +Helper module with type-hinted functions. +""" + +from typing import List, Optional + + +def safe_divide(a: float, b: float) -> Optional[float]: + """ + Safely divide two numbers, returning None if division by zero. + + Args: + a: Numerator + b: Denominator + + Returns: + The result of a/b, or None if b is 0 + """ + if b == 0: + return None + return a / b + + +def validate_input(required_param: str, optional_param: Optional[str] = None) -> bool: + """ + Validate input parameters. + + Args: + required_param: A required string parameter + optional_param: An optional string parameter + + Returns: + True if input is valid, False otherwise + """ + if not required_param: + return False + if optional_param is not None and len(optional_param) == 0: + return False + return True + + +def calculate_average(numbers: List[int]) -> float: + """ + Calculate the average of a list of integers. + + Args: + numbers: List of integers + + Returns: + The average as a float + + Raises: + ValueError: If the list is empty + """ + if not numbers: + raise ValueError("Cannot calculate average of empty list") + return sum(numbers) / len(numbers) +''' + + +def get_test_file_content() -> str: + """Get the test_typed_code.py file content.""" + return '''""" +Tests for typed_code module. +""" + +import pytest +from typed_code import process_number, calculate_stats, format_name, main + + +def test_process_number(): + """Test process_number with valid input.""" + assert process_number(5) == 10 + assert process_number(0) == 0 + assert process_number(-3) == -6 + + +def test_calculate_stats(): + """Test calculate_stats with various inputs.""" + assert "Average: 2.0" in calculate_stats([1, 2, 3]) + assert "Average: 5.5" in calculate_stats([5, 6]) + + # Edge case: empty list + assert calculate_stats([]) == "" + + +def test_format_name(): + """Test format_name with various inputs.""" + assert format_name("alice") == "ALICE" + assert format_name("bob") == "BOB" + assert format_name(None) == "UNKNOWN" + + +def test_main(): + """Test main function.""" + result = main() + assert result is not None + assert "result1" in result + assert "formatted_string" in result + assert "validated" in result + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) +''' \ No newline at end of file diff --git a/debug_env/tasks/task5/__init__.py b/debug_env/tasks/task5/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88a5f1eb67f16300fc07f49379b4b65b1d276904 --- /dev/null +++ b/debug_env/tasks/task5/__init__.py @@ -0,0 +1 @@ +"""Task 5: Unused Imports and Dead Code""" \ No newline at end of file diff --git a/debug_env/tasks/task5/seed_data.py b/debug_env/tasks/task5/seed_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e74da17359b01020bd936f143c7c31254f514829 --- /dev/null +++ b/debug_env/tasks/task5/seed_data.py @@ -0,0 +1,265 @@ +""" +Task 5: Unused Imports and Dead Code Seed Data + +Comprehensive seed data for code quality task. +Contains Python code with unused imports, unused variables, and dead code paths +that can be found using search, dependency analysis, and code structure inspection. +""" + +from typing import Any, Dict, List + + +def get_task5_seed_data() -> Dict[str, Any]: + """ + Generate seed data for task5 (Unused Imports & Dead Code). + + Files: + - messy_code.py: Module with unused imports and dead code + + Issues Present: + 1. Unused imports (json, urllib, sys) + 2. Unused imports from typing (Tuple, Callable, Dict) + 3. Unused variable assignments + 4. Dead code paths (unreachable due to early returns) + 5. Commented-out code blocks + 6. Unused function parameters + 7. Unused class attributes + """ + return { + "files": { + "messy_code.py": get_messy_code_content(), + }, + "test_file": "test_messy_code.py", + "issues_to_fix": [ + "Remove unused import: json (line 3)", + "Remove unused import: urllib (line 4)", + "Remove unused import from typing: Tuple, Callable, Dict (line 6)", + "Remove unused variable: config_data (line 20)", + "Remove unused variable: temp_result (line 28)", + "Remove dead code: parse_legacy_format function (lines 35-42)", + "Remove dead code: return statement in process_data (line 59-60)", + "Remove unused parameter: debug_mode in analyze_data (line 68)", + "Remove unused class attribute: _cache in DataProcessor (line 77)", + "Remove commented-out code blocks (lines 82-85, 95-98)", + ], + "tools_to_use": [ + "search_code", + "get_file_structure", + "get_dependencies", + "edit_file", + "run_tests", + ], + "difficulty": "medium", + } + + +def get_messy_code_content() -> str: + """Get the broken messy_code.py file content.""" + return '''""" +Messy module with unused imports, variables, and dead code. +Needs cleanup and refactoring. +""" + +import json # UNUSED +import urllib # UNUSED +from typing import List, Optional +from typing import Tuple, Callable, Dict # UNUSED: Tuple, Callable, Dict + + +def load_data(filename: str) -> List[str]: + """Load data from file.""" + try: + with open(filename, "r") as f: + return f.readlines() + except FileNotFoundError: + # Unused variable assignment + config_data = {"default": "path", "timeout": 30} + return [] + + +def process_data(items: List[str]) -> List[str]: + """Process items.""" + # Unused variable + temp_result = [] + + results = [] + for item in items: + results.append(item.strip().upper()) + + # Dead code: unreachable due to early return + return results + unused_value = 999 # Unreachable + processed = [x.lower() for x in results] # Unreachable + + +def parse_legacy_format(data: str) -> Optional[str]: + """ + Dead code function - never called. + Parse data in legacy format. + """ + # This entire function is dead code + parts = data.split("|") + if len(parts) != 3: + return None + return parts[1] + + +def analyze_data( + items: List[str], + debug_mode: bool = False, # UNUSED parameter +) -> dict: + """Analyze items and return summary.""" + # debug_mode is never used + count = len(items) + non_empty = len([x for x in items if x.strip()]) + + return { + "total": count, + "non_empty": non_empty, + "empty": count - non_empty, + } + + +class DataProcessor: + """Process data with potential for cleanup.""" + + def __init__(self): + """Initialize processor.""" + self.data = [] + self._cache = {} # UNUSED: never read or written + + def process(self, items: List[str]) -> List[str]: + """Process items.""" + # Commented-out code blocks + # self._cache["processed"] = items + # processed_items = self._preprocess(items) + # results = self._apply_transformations(processed_items) + + results = [] + for item in items: + results.append(item.strip().upper()) + + # More commented code + # self._cache["results"] = results + # logger.debug(f"Processed {len(results)} items") + + return results + + def validate(self, items: List[str]) -> bool: + """Validate items.""" + return len(items) > 0 + + +def main(): + """Main entry point.""" + data = load_data("data.txt") + processed = process_data(data) + analysis = analyze_data(processed, debug_mode=True) + + processor = DataProcessor() + result = processor.process(data) + + return { + "processed": processed, + "analysis": analysis, + "result": result, + } + + +if __name__ == "__main__": + main() +''' + + +def get_test_file_content() -> str: + """Get the test_messy_code.py file content.""" + return '''""" +Tests for messy_code module. +""" + +import pytest +from messy_code import ( + load_data, + process_data, + analyze_data, + DataProcessor, + main, +) + + +def test_process_data(): + """Test process_data function.""" + input_data = ["hello", "world", "test"] + result = process_data(input_data) + + assert len(result) == 3 + assert result[0] == "HELLO" + assert result[1] == "WORLD" + assert result[2] == "TEST" + + +def test_process_data_with_whitespace(): + """Test process_data with whitespace.""" + input_data = [" hello ", "\\tworld\\t", "\\n test "] + result = process_data(input_data) + + assert result[0] == "HELLO" + assert result[1] == "WORLD" + assert result[2] == "TEST" + + +def test_analyze_data(): + """Test analyze_data function.""" + items = ["hello", "", "world", "", ""] + result = analyze_data(items) + + assert result["total"] == 5 + assert result["non_empty"] == 2 + assert result["empty"] == 3 + + +def test_analyze_data_all_non_empty(): + """Test analyze_data with all non-empty items.""" + items = ["a", "b", "c"] + result = analyze_data(items) + + assert result["total"] == 3 + assert result["non_empty"] == 3 + assert result["empty"] == 0 + + +def test_data_processor(): + """Test DataProcessor class.""" + processor = DataProcessor() + data = ["test", "data", "items"] + + result = processor.process(data) + assert len(result) == 3 + assert result[0] == "TEST" + + +def test_data_processor_validate(): + """Test DataProcessor validation.""" + processor = DataProcessor() + + assert processor.validate(["item"]) is True + assert processor.validate([]) is False + + +def test_main(): + """Test main function.""" + # Note: This test will fail if data.txt doesn't exist + # It's included to show the expected behavior + try: + result = main() + assert result is not None + assert "processed" in result + assert "analysis" in result + except FileNotFoundError: + # Expected if data.txt doesn't exist + pass + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) +''' \ No newline at end of file diff --git a/debug_env/tasks/task6/__init__.py b/debug_env/tasks/task6/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b39ccb3215c86f505ea6ffec45f0a149b61f722 --- /dev/null +++ b/debug_env/tasks/task6/__init__.py @@ -0,0 +1 @@ +"""Task 6: Complex Multi-file Refactoring""" \ No newline at end of file diff --git a/debug_env/tasks/task6/seed_data.py b/debug_env/tasks/task6/seed_data.py new file mode 100644 index 0000000000000000000000000000000000000000..454e83607e1fdc253e9bf5b263cf09efe960af32 --- /dev/null +++ b/debug_env/tasks/task6/seed_data.py @@ -0,0 +1,388 @@ +""" +Task 6: Complex Multi-file Refactoring Seed Data + +Comprehensive seed data for architectural refactoring task. +Contains multiple Python modules with architectural issues including: +- Circular dependencies +- Tight coupling between modules +- Broken abstraction layers +- Missing integration points +- Data flow inconsistencies +""" + +from typing import Any, Dict, List + + +def get_task6_seed_data() -> Dict[str, Any]: + """ + Generate seed data for task6 (Complex Multi-file Refactoring). + + Files: + - module_a.py: Data processing module + - module_b.py: Business logic module (depends on A) + - module_c.py: API interface module + - integration.py: Integration layer (coordination) + + Architectural Issues: + 1. Circular dependency: A ↔ B ↔ C + 2. Tight coupling: Direct object instantiation instead of DI + 3. Broken abstraction: B accesses A's internal state directly + 4. Inconsistent error handling across modules + 5. Missing interface definitions + 6. Data validation scattered across modules + 7. Integration logic mixed with business logic + 8. Test coverage gaps due to tight coupling + + Goal: + Refactor to: + - Break circular dependencies via dependency injection + - Extract common interfaces + - Consolidate validation logic + - Improve separation of concerns + - Make integration layer explicit + """ + return { + "files": { + "module_a.py": get_module_a_content(), + "module_b.py": get_module_b_content(), + "module_c.py": get_module_c_content(), + "integration.py": get_integration_content(), + }, + "test_file": "test_integration.py", + "architectural_issues": [ + "Circular import: module_a imports from module_b, module_b imports from module_a", + "Tight coupling: ProcessorB directly instantiates ProcessorA", + "Broken abstraction: ProcessorB accesses _raw_data (internal) from ProcessorA", + "Inconsistent validation: validate() in A, validate() in B, no validation in C", + "Missing interface: No abstract base for processors", + "Data flow unclear: Integration happens in multiple places", + "Error handling: Different exception patterns in each module", + "Integration logic: BusinessLogic.execute() does too much", + ], + "refactoring_goals": [ + "Extract common processor interface (Processor ABC)", + "Use dependency injection instead of instantiation", + "Move validation to a dedicated Validator class", + "Consolidate error handling with custom exceptions", + "Make integration explicit via Integration class", + "Break circular dependency via interface abstraction", + "Separate concerns: each module has single responsibility", + ], + "tools_to_use": [ + "list_directory", + "get_file_structure", + "get_dependencies", + "search_code", + "get_test_coverage", + "edit_file", + "run_tests", + ], + "difficulty": "hard", + } + + +def get_module_a_content() -> str: + """Get module_a.py content.""" + return '''""" +Module A: Data Processing + +Responsible for low-level data processing. +Currently has tight coupling to Module B. +""" + + +class ProcessorA: + """Process raw data.""" + + def __init__(self): + """Initialize processor A.""" + self._raw_data = [] + self._processed = False + + def load(self, data: list) -> None: + """Load raw data.""" + self._raw_data = data + self._processed = False + + def validate(self) -> bool: + """Validate raw data.""" + if not self._raw_data: + return False + # Basic validation + return all(isinstance(x, (int, str)) for x in self._raw_data) + + def process(self) -> list: + """Process the data.""" + if not self.validate(): + raise ValueError("Invalid data in ProcessorA") + + result = [str(x).upper() for x in self._raw_data] + self._processed = True + return result + + +def create_processor_a() -> ProcessorA: + """Factory function for ProcessorA.""" + return ProcessorA() +''' + + +def get_module_b_content() -> str: + """Get module_b.py content.""" + return '''""" +Module B: Business Logic + +Contains business logic that depends on Module A. +Has circular dependency with Module A. +Tightly coupled to ProcessorA implementation. +""" + +from module_a import ProcessorA, create_processor_a + + +class BusinessLogic: + """Business logic processor.""" + + def __init__(self): + """Initialize business logic.""" + # Tight coupling: directly instantiates ProcessorA + self.processor_a = create_processor_a() + self._cache = {} + + def validate(self) -> bool: + """Validate business logic state.""" + # Inconsistent validation logic + if not hasattr(self.processor_a, "_raw_data"): + return False + return len(self.processor_a._raw_data) > 0 # Broken abstraction! + + def execute(self, data: list) -> dict: + """ + Execute business logic. + This method does too much (violates SRP). + """ + # Load data + self.processor_a.load(data) + + # Validate using ProcessorA + if not self.processor_a.validate(): + raise ValueError("Data validation failed") + + # Process + processed = self.processor_a.process() + + # Additional business logic + enriched = [f"processed_{item}" for item in processed] + + # Direct access to internal state (broken abstraction) + result = { + "original_count": len(self.processor_a._raw_data), + "processed_count": len(enriched), + "processed_data": enriched, + } + + # Cache management (integration concern mixed in) + self._cache["last_result"] = result + + return result + + def get_last_result(self) -> dict: + """Get cached result.""" + return self._cache.get("last_result", {}) + + +def create_business_logic() -> BusinessLogic: + """Factory function for BusinessLogic.""" + return BusinessLogic() +''' + + +def get_module_c_content() -> str: + """Get module_c.py content.""" + return '''""" +Module C: API Interface + +Provides API interface to the system. +Currently doesn't validate input (relies on downstream modules). +Has tight coupling to BusinessLogic. +""" + +from module_b import create_business_logic + + +class APIEndpoint: + """API endpoint interface.""" + + def __init__(self): + """Initialize API endpoint.""" + # Tight coupling: directly instantiates BusinessLogic + self.business_logic = create_business_logic() + + def process_request(self, data: list) -> dict: + """ + Process incoming request. + No validation at API boundary! + """ + # Should validate here, but doesn't + result = self.business_logic.execute(data) + return { + "status": "success", + "data": result, + } + + def get_status(self) -> dict: + """Get current status.""" + # Inconsistent error handling + try: + last_result = self.business_logic.get_last_result() + return { + "status": "ok", + "last_result_size": len(last_result.get("processed_data", [])), + } + except Exception as e: + return {"status": "error", "message": str(e)} + + +def create_api_endpoint() -> APIEndpoint: + """Factory function for APIEndpoint.""" + return APIEndpoint() +''' + + +def get_integration_content() -> str: + """Get integration.py content.""" + return '''""" +Integration Module + +Currently mixes integration logic with business logic. +No explicit integration layer. +""" + +from module_c import create_api_endpoint + + +def main(): + """ + Main integration point. + This is the only place orchestration happens, + but orchestration logic is scattered across modules. + """ + # Create API endpoint (which creates BusinessLogic, which creates ProcessorA) + api = create_api_endpoint() + + # Process some data + raw_data = ["apple", "banana", "cherry", 123] + + try: + response = api.process_request(raw_data) + print("Success:", response) + except ValueError as e: + print("Validation error:", e) + except Exception as e: + print("Unexpected error:", e) + + # Get status + status = api.get_status() + print("Status:", status) + + return response + + +if __name__ == "__main__": + main() +''' + + +def get_test_file_content() -> str: + """Get test_integration.py file content.""" + return '''""" +Integration tests for multi-module system. + +These tests are difficult to write due to tight coupling. +They need to instantiate many objects at once. +""" + +import pytest +from module_a import ProcessorA +from module_b import BusinessLogic +from module_c import APIEndpoint + + +def test_processor_a_basic(): + """Test ProcessorA basic functionality.""" + processor = ProcessorA() + processor.load(["hello", "world"]) + + assert processor.validate() + assert processor.process() == ["HELLO", "WORLD"] + + +def test_processor_a_invalid_data(): + """Test ProcessorA with invalid data.""" + processor = ProcessorA() + processor.load([None, {}]) # Invalid types + + assert not processor.validate() + + +def test_processor_a_empty_data(): + """Test ProcessorA with empty data.""" + processor = ProcessorA() + processor.load([]) + + assert not processor.validate() + + +def test_business_logic(): + """Test BusinessLogic execution.""" + bl = BusinessLogic() + result = bl.execute(["test", "data"]) + + assert result["processed_count"] == 2 + assert "processed_test" in result["processed_data"] + + +def test_business_logic_caching(): + """Test BusinessLogic result caching.""" + bl = BusinessLogic() + + result1 = bl.execute(["first"]) + cached = bl.get_last_result() + + assert cached == result1 + assert len(cached["processed_data"]) == 1 + + +def test_api_endpoint(): + """Test APIEndpoint.""" + api = APIEndpoint() + response = api.process_request(["api", "test"]) + + assert response["status"] == "success" + assert "data" in response + + +def test_api_status(): + """Test APIEndpoint status.""" + api = APIEndpoint() + api.process_request(["test"]) + + status = api.get_status() + assert status["status"] == "ok" + assert status["last_result_size"] == 1 + + +def test_full_integration(): + """Test full system integration.""" + api = APIEndpoint() + + # Process data through full stack + response = api.process_request(["integration", "test", "data"]) + + assert response["status"] == "success" + assert len(response["data"]["processed_data"]) == 3 + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) +''' \ No newline at end of file diff --git a/debug_env/tasks/task7/__init__.py b/debug_env/tasks/task7/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..238c7680c9377599cade9cd0be823f7597264697 --- /dev/null +++ b/debug_env/tasks/task7/__init__.py @@ -0,0 +1 @@ +"""Task 7: Code Review Workflow""" \ No newline at end of file diff --git a/debug_env/tasks/task7/seed_data.py b/debug_env/tasks/task7/seed_data.py new file mode 100644 index 0000000000000000000000000000000000000000..2ab8e350b16177711924e0722c8985e82a1d1233 --- /dev/null +++ b/debug_env/tasks/task7/seed_data.py @@ -0,0 +1,259 @@ +""" +Task 7: Code Review Workflow Seed Data + +Collaborative scenario: Junior developer submits fix that needs code review. +Demonstrates multi-user workflow with approval gates. +""" + +from typing import Any, Dict + + +def get_task7_seed_data() -> Dict[str, Any]: + """ + Generate seed data for task7 (Code Review Workflow). + + Scenario: + Bob (Junior Dev) found and fixed a bug in authentication logic. + Alice (Senior Dev) needs to review the fix. + Dave (Tech Lead) oversees the process. + + Workflow: + 1. Bob reads failing test and understands the bug + 2. Bob edits the authentication code to fix the issue + 3. Bob runs tests to verify the fix works + 4. Alice reviews the code changes + 5. Alice checks test coverage and style + 6. Alice approves the fix + + Issues to address: + 1. Code style doesn't match team standards + 2. Missing edge case test coverage + 3. Missing docstring on modified function + 4. Incomplete error handling + """ + return { + "files": { + "auth.py": get_auth_py_content(), + "test_auth.py": get_test_auth_py_content(), + }, + "test_file": "test_auth.py", + "participants": [ + { + "user_id": "bob_junior", + "role": "assignee", + "responsibility": "Fix the bug, ensure tests pass", + "status": "in_progress", + }, + { + "user_id": "alice_senior", + "role": "reviewer", + "responsibility": "Review code, check quality, approve", + "status": "pending", + }, + { + "user_id": "dave_lead", + "role": "observer", + "responsibility": "Oversee, escalate if needed", + "status": "pending", + }, + ], + "initial_state": "Bug reported: authenticate() returns True for invalid tokens", + "expected_issues": [ + "Code style inconsistency (spacing, naming)", + "Missing docstring on authenticate_token()", + "Missing test for None token", + "Incomplete error message in exception", + "Missing type hints on helper function", + ], + "review_checklist": [ + "✗ Code style matches team guidelines", + "✗ Test coverage is adequate", + "✗ Docstrings present and clear", + "✗ Error handling is complete", + "✗ No security vulnerabilities introduced", + ], + "tools_to_use": [ + "read_file", + "edit_file", + "run_tests", + "search_code", + "run_type_check", + "get_test_coverage", + ], + "difficulty": "medium", + } + + +def get_auth_py_content() -> str: + """Get the auth.py file with the bug to fix.""" + return '''""" +Authentication module with token validation. +""" + +import re +from typing import Optional + + +def validate_token_format(token: str) -> bool: + """Validate token format (basic pattern check).""" + if not token or not isinstance(token, str): + return False + # Simple pattern: alphanumeric, at least 20 chars + return bool(re.match(r"^[a-zA-Z0-9]{20,}$", token)) + + +def check_token_expiry(token: str) -> bool: + """Check if token is expired.""" + # Simplified: tokens with "expired" in them are expired + return "expired" not in token.lower() + + +# Bug: This function has incorrect logic +def authenticate_token(token: str) -> bool: + """ + Authenticate a user token. + + Args: + token: The authentication token to validate + + Returns: + True if token is valid, False otherwise + """ + # BUG: Returns True for None/empty tokens + if not validate_token_format(token): + return True # WRONG: Should return False + + # BUG: Doesn't check expiry + return True # WRONG: Should check expiry too + + +def authenticate(username: str, password: str) -> bool: + """ + Authenticate a user with username and password. + + Args: + username: The username + password: The password (should be hashed) + + Returns: + True if authenticated, False otherwise + """ + # For this exercise, accept specific credentials + if username == "admin" and password == "secret123": + return True + return False + + +def authenticate_with_token(token: str) -> bool: + """Authenticate using a token.""" + # Uses the buggy function + return authenticate_token(token) + + +def get_user_info(token: Optional[str]) -> dict: + """Get user info if token is valid.""" + if token and authenticate_with_token(token): + return {"user_id": "123", "username": "admin"} + return {} +''' + + +def get_test_auth_py_content() -> str: + """Get the test_auth.py file.""" + return '''""" +Tests for authentication module. +""" + +import pytest +from auth import ( + validate_token_format, + check_token_expiry, + authenticate_token, + authenticate, + authenticate_with_token, + get_user_info, +) + + +def test_validate_token_format_valid(): + """Test validate_token_format with valid tokens.""" + assert validate_token_format("abcd1234567890abcdef") + assert validate_token_format("ABCDEF1234567890WXYZ") + assert validate_token_format("a" * 50) # Very long token + + +def test_validate_token_format_invalid(): + """Test validate_token_format with invalid tokens.""" + assert not validate_token_format("short") + assert not validate_token_format("") + assert not validate_token_format("token-with-dashes") + assert not validate_token_format("token_with_underscores") + + +def test_validate_token_format_none(): + """Test validate_token_format with None.""" + assert not validate_token_format(None) + + +def test_check_token_expiry(): + """Test check_token_expiry function.""" + assert check_token_expiry("valid_token_abc123") + assert not check_token_expiry("expired_token_xyz") + assert not check_token_expiry("EXPIRED") + + +def test_authenticate_token_valid(): + """Test authenticate_token with valid token.""" + assert authenticate_token("validtoken12345678901") + + +def test_authenticate_token_invalid_format(): + """Test authenticate_token rejects invalid format.""" + assert not authenticate_token("short") + assert not authenticate_token("") + + +def test_authenticate_token_expired(): + """Test authenticate_token rejects expired tokens.""" + assert not authenticate_token("expiredtoken12345678901") + + +def test_authenticate_token_none(): + """Test authenticate_token with None token.""" + assert not authenticate_token(None) + + +def test_authenticate_valid_credentials(): + """Test authenticate with valid credentials.""" + assert authenticate("admin", "secret123") + + +def test_authenticate_invalid_credentials(): + """Test authenticate with invalid credentials.""" + assert not authenticate("admin", "wrongpassword") + assert not authenticate("unknownuser", "secret123") + + +def test_authenticate_with_token(): + """Test authenticate_with_token.""" + assert authenticate_with_token("validtoken12345678901") + assert not authenticate_with_token("invalidtoken") + assert not authenticate_with_token("expiredtoken12345678901") + + +def test_get_user_info_valid_token(): + """Test get_user_info with valid token.""" + info = get_user_info("validtoken12345678901") + assert info.get("user_id") == "123" + assert info.get("username") == "admin" + + +def test_get_user_info_invalid_token(): + """Test get_user_info with invalid token.""" + assert get_user_info("invalid") == {} + assert get_user_info(None) == {} + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) +''' \ No newline at end of file diff --git a/debug_env/tasks/task8/__init__.py b/debug_env/tasks/task8/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..76a79761a6f2aa808103c32b9e41df9ee93dd000 --- /dev/null +++ b/debug_env/tasks/task8/__init__.py @@ -0,0 +1 @@ +"""Task 8: Cross-team Bug Investigation""" \ No newline at end of file diff --git a/debug_env/tasks/task8/seed_data.py b/debug_env/tasks/task8/seed_data.py new file mode 100644 index 0000000000000000000000000000000000000000..89a4e57368310023f44f59e5124456398bab398d --- /dev/null +++ b/debug_env/tasks/task8/seed_data.py @@ -0,0 +1,340 @@ +""" +Task 8: Cross-team Bug Investigation Seed Data + +Collaborative scenario: QA reported a bug, dev team must investigate and fix. +Demonstrates multi-user workflow with investigation and coordination. +""" + +from typing import Any, Dict + + +def get_task8_seed_data() -> Dict[str, Any]: + """ + Generate seed data for task8 (Cross-team Bug Investigation). + + Scenario: + Carol (QA) reported: "User profile update fails with 'invalid email' error" + Bug details: Valid emails like "user+tag@domain.com" are rejected + + Bob (Junior Dev) investigates and documents findings + Alice (Senior Dev) designs and implements the fix + Dave (Tech Lead) coordinates and approves + + Root cause: Email validation regex is too strict + + Workflow: + 1. Understand the bug from Carol's report + 2. Investigate the code to find where validation happens + 3. Identify the regex pattern that's too restrictive + 4. Search for all places email is validated + 5. Design a fix that handles edge cases + 6. Fix validation and add comprehensive tests + 7. Verify fix works for reported and edge cases + 8. Get approval from senior dev and tech lead + """ + return { + "files": { + "user_service.py": get_user_service_content(), + "email_validator.py": get_email_validator_content(), + "test_user_service.py": get_test_user_service_content(), + }, + "test_file": "test_user_service.py", + "bug_report": { + "reporter": "carol_qa", + "title": "User profile update fails with invalid email", + "description": "Users cannot update their profile with valid email addresses containing '+' character", + "reproduction_steps": [ + "1. Go to user profile settings", + "2. Change email to 'user+tag@example.com'", + "3. Click save/update", + "4. Error: 'Invalid email format'", + ], + "expected_behavior": "Email should be accepted as it's valid per RFC 5322", + "actual_behavior": "Email is rejected with validation error", + "severity": "high", + "affected_users": "Any user with '+' in their email (common for filtering/organizing)", + }, + "participants": [ + { + "user_id": "carol_qa", + "role": "bug_reporter", + "responsibility": "Provide details, verify fix", + "status": "completed", + }, + { + "user_id": "bob_junior", + "role": "investigator", + "responsibility": "Investigate root cause", + "status": "in_progress", + }, + { + "user_id": "alice_senior", + "role": "problem_solver", + "responsibility": "Design and implement fix", + "status": "pending", + }, + { + "user_id": "dave_lead", + "role": "coordinator", + "responsibility": "Coordinate, approve solution", + "status": "pending", + }, + ], + "investigation_questions": [ + "Where is email validation happening?", + "What regex pattern is being used?", + "Are there multiple places email is validated?", + "What email formats should be supported?", + "What test cases are missing?", + ], + "expected_issues": [ + "Regex pattern uses [a-zA-Z0-9] instead of allowing special chars", + "Validation logic is duplicated in user_service.py", + "Missing test cases for emails with '+' character", + "Missing test cases for other valid formats (dots, hyphens)", + "Error messages could be more helpful", + ], + "tools_to_use": [ + "search_code", + "get_file_structure", + "read_file", + "run_tests", + "edit_file", + "get_test_coverage", + ], + "difficulty": "hard", + } + + +def get_user_service_content() -> str: + """Get user_service.py with the email validation bug.""" + return '''""" +User service module for user profile management. +Contains email validation logic. +""" + +import re +from typing import Optional, Dict, Any +from email_validator import validate_email as external_validate_email + + +def validate_email_local(email: str) -> bool: + """ + Validate email format using regex (BUGGY - too strict). + + BUG: This regex doesn't allow '+', '.', or '-' in the local part + Common in real-world emails but not supported here. + """ + if not email: + return False + # BUG: This pattern is too restrictive + pattern = r"^[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z]{2,}$" + return bool(re.match(pattern, email)) + + +def update_user_profile(user_id: str, profile_data: Dict[str, Any]) -> Dict[str, Any]: + """ + Update user profile with new data. + + Args: + user_id: User ID + profile_data: Dict with fields to update (email, name, etc) + + Returns: + Updated profile data + + Raises: + ValueError: If validation fails + """ + updated_profile = {"user_id": user_id} + + # Email validation using the buggy function + if "email" in profile_data: + email = profile_data["email"] + # BUG: Uses the restrictive local validation + if not validate_email_local(email): + raise ValueError(f"Invalid email format: {email}") + updated_profile["email"] = email + + if "name" in profile_data: + updated_profile["name"] = profile_data["name"] + + if "phone" in profile_data: + updated_profile["phone"] = profile_data["phone"] + + return updated_profile + + +def validate_user_data(user_data: Dict[str, Any]) -> bool: + """ + Validate all user data before saving. + + BUG: Also uses the restrictive email validation + """ + if "email" in user_data: + # Duplicated validation logic + if not validate_email_local(user_data["email"]): + return False + + if "name" in user_data: + if not user_data.get("name") or len(user_data["name"]) < 2: + return False + + return True + + +def get_user_profile(user_id: str) -> Dict[str, Any]: + """Get user profile data.""" + # Mock data + return { + "user_id": user_id, + "name": "Test User", + "email": "testuser@example.com", + "phone": "555-1234", + } +''' + + +def get_email_validator_content() -> str: + """Get email_validator.py helper module.""" + return '''""" +Email validation utilities. +""" + +import re + + +def validate_email(email: str, strict: bool = False) -> bool: + """ + Validate email format. + + Args: + email: Email address to validate + strict: If True, use strict validation rules + + Returns: + True if valid, False otherwise + """ + if not email or not isinstance(email, str): + return False + + # Basic structure check + if "@" not in email or "." not in email: + return False + + local, domain = email.rsplit("@", 1) + + if not local or not domain: + return False + + if strict: + # Strict: only alphanumeric + underscore + local_pattern = r"^[a-zA-Z0-9_]+$" + else: + # More permissive: allow common special chars + local_pattern = r"^[a-zA-Z0-9.+\\-_]+$" + + domain_pattern = r"^[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9]\\.[a-zA-Z]{2,}$" + + return bool(re.match(local_pattern, local)) and bool(re.match(domain_pattern, domain)) +''' + + +def get_test_user_service_content() -> str: + """Get test_user_service.py file.""" + return '''""" +Tests for user service module. +""" + +import pytest +from user_service import ( + validate_email_local, + update_user_profile, + validate_user_data, + get_user_profile, +) + + +def test_validate_email_local_valid(): + """Test email validation with standard emails.""" + assert validate_email_local("user@example.com") + assert validate_email_local("john@company.org") + + +def test_validate_email_local_plus_sign(): + """Test email validation with plus sign (CURRENTLY FAILS).""" + # This is valid per RFC 5322 but our regex rejects it + assert validate_email_local("user+tag@example.com") + + +def test_validate_email_local_dot_in_local(): + """Test email validation with dots (CURRENTLY FAILS).""" + assert validate_email_local("first.last@example.com") + + +def test_validate_email_local_hyphen(): + """Test email validation with hyphen (CURRENTLY FAILS).""" + assert validate_email_local("user-name@example.com") + + +def test_validate_email_local_invalid(): + """Test email validation with invalid formats.""" + assert not validate_email_local("invalid") + assert not validate_email_local("@example.com") + assert not validate_email_local("user@") + assert not validate_email_local("") + assert not validate_email_local(None) + + +def test_update_user_profile_basic(): + """Test updating user profile with valid email.""" + result = update_user_profile("user1", {"email": "user@example.com"}) + assert result["email"] == "user@example.com" + + +def test_update_user_profile_plus_email(): + """Test updating with plus-sign email (CURRENTLY FAILS).""" + result = update_user_profile("user1", {"email": "user+tag@example.com"}) + assert result["email"] == "user+tag@example.com" + + +def test_update_user_profile_with_name(): + """Test updating profile with name.""" + result = update_user_profile("user1", { + "email": "user@example.com", + "name": "John Doe" + }) + assert result["name"] == "John Doe" + + +def test_update_user_profile_invalid_email(): + """Test updating with invalid email raises error.""" + with pytest.raises(ValueError, match="Invalid email"): + update_user_profile("user1", {"email": "invalid"}) + + +def test_validate_user_data_valid(): + """Test user data validation.""" + assert validate_user_data({"email": "user@example.com", "name": "John"}) + + +def test_validate_user_data_plus_email(): + """Test user data validation with plus-sign email (CURRENTLY FAILS).""" + assert validate_user_data({"email": "user+tag@example.com"}) + + +def test_validate_user_data_short_name(): + """Test user data validation with short name.""" + assert not validate_user_data({"name": "J"}) + + +def test_get_user_profile(): + """Test getting user profile.""" + profile = get_user_profile("test_user") + assert profile["user_id"] == "test_user" + assert "email" in profile + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) +''' \ No newline at end of file diff --git a/debug_env/tasks/task9/__init__.py b/debug_env/tasks/task9/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed159f85adbd402dc4dda4760f95f6aff97a3314 --- /dev/null +++ b/debug_env/tasks/task9/__init__.py @@ -0,0 +1 @@ +"""Task 9: Collaborative Architecture Refactoring""" \ No newline at end of file diff --git a/debug_env/tasks/task9/seed_data.py b/debug_env/tasks/task9/seed_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e28e34d0b652f954646cd3f06760e8e77ae91249 --- /dev/null +++ b/debug_env/tasks/task9/seed_data.py @@ -0,0 +1,325 @@ +""" +Task 9: Collaborative Architecture Refactoring Seed Data + +Complex collaborative scenario: Multiple developers refactor architecture +in parallel while maintaining integration and consistency. +""" + +from typing import Any, Dict + + +def get_task9_seed_data() -> Dict[str, Any]: + """ + Generate seed data for task9 (Collaborative Architecture Refactoring). + + Scenario: + Large refactoring to break circular dependencies and improve testability. + Multiple developers work on different modules in parallel. + + Alice (Senior) designs architecture, reviews all changes + Bob (Junior) refactors data processing layer + Carol (QA) refactors business logic, ensures test compatibility + Dave (Lead) coordinates integration, resolves conflicts + + Current problems: + - Circular imports: module_a imports module_b, module_b imports module_a + - Tight coupling: Direct instantiation instead of dependency injection + - Missing abstractions: No interfaces/base classes + - Scattered validation: Same logic duplicated across modules + - Difficult to test: Can't instantiate modules independently + + Refactoring goals: + 1. Extract common Processor abstract base class + 2. Use dependency injection instead of direct instantiation + 3. Create Validator class to consolidate validation + 4. Remove circular dependencies via interface abstraction + 5. Make each module independently testable + 6. Improve error handling with custom exceptions + """ + return { + "files": { + "data_processor.py": get_data_processor_content(), + "business_logic.py": get_business_logic_content(), + "api_interface.py": get_api_interface_content(), + "integration.py": get_integration_content(), + }, + "test_file": "test_refactoring.py", + "participants": [ + { + "user_id": "alice_senior", + "role": "architect", + "responsibility": "Design refactoring, review changes, ensure consistency", + "status": "in_progress", + }, + { + "user_id": "bob_junior", + "role": "contributor", + "responsibility": "Refactor data_processor.py following architecture", + "status": "in_progress", + }, + { + "user_id": "carol_qa", + "role": "contributor", + "responsibility": "Refactor business_logic.py, ensure test compatibility", + "status": "pending", + }, + { + "user_id": "dave_lead", + "role": "integration_lead", + "responsibility": "Coordinate integration, resolve conflicts, final merge", + "status": "pending", + }, + ], + "current_issues": [ + "Circular import: data_processor ↔ business_logic ↔ api_interface", + "Tight coupling: Direct instantiation of dependencies", + "Broken abstraction: Direct access to private attributes", + "Duplicated validation logic across modules", + "Tests require full integration (can't unit test modules)", + "Error handling inconsistent across modules", + ], + "refactoring_steps": [ + "Step 1: Design shared Processor interface (Alice)", + "Step 2: Create Validator class (Alice)", + "Step 3: Create custom exceptions (Alice)", + "Step 4: Refactor data_processor.py (Bob)", + "Step 5: Refactor business_logic.py (Carol)", + "Step 6: Update api_interface.py (Carol or Bob)", + "Step 7: Update integration.py for dependency injection (Alice)", + "Step 8: Verify all modules integrate correctly (Dave)", + "Step 9: Run full test suite (All)", + ], + "shared_artifacts_to_create": [ + "base_processor.py (abstract Processor class)", + "validators.py (consolidated Validator class)", + "exceptions.py (custom exception classes)", + ], + "expected_challenges": [ + "Parallel changes to shared interfaces cause conflicts", + "Some code still depends on old circular import structure", + "Test suite needs updating for new module structure", + "Circular import detection not obvious at first", + ], + "tools_to_use": [ + "list_directory", + "get_file_structure", + "get_dependencies", + "search_code", + "read_file", + "edit_file", + "run_tests", + "run_type_check", + "get_test_coverage", + ], + "difficulty": "hard", + } + + +def get_data_processor_content() -> str: + """Get data_processor.py with circular dependency and tight coupling.""" + return '''""" +Data Processing Module + +BUG: Has circular import with business_logic.py +BUG: Directly instantiates BusinessLogic (tight coupling) +BUG: Validation logic duplicated elsewhere +""" + +# BUG: Circular import (business_logic imports this too) +from business_logic import BusinessLogic + + +class DataProcessor: + """Process data - currently tightly coupled and hard to test.""" + + def __init__(self): + """Initialize processor.""" + self._data = [] + # BUG: Direct instantiation creates circular dependency + self._logic = BusinessLogic() + + def load(self, data): + """Load data.""" + # BUG: Validation logic - also exists in BusinessLogic + if not data or not isinstance(data, list): + raise ValueError("Data must be non-empty list") + self._data = data + + def process(self): + """Process data through business logic.""" + # BUG: Direct access to private attribute + self._logic._validate() + return self._logic._execute(self._data) + + def validate(self): + """Validate data - DUPLICATED from BusinessLogic.""" + if not self._data: + return False + return all(isinstance(x, (int, str)) for x in self._data) +''' + + +def get_business_logic_content() -> str: + """Get business_logic.py with circular dependency.""" + return '''""" +Business Logic Module + +BUG: Has circular import with data_processor.py +BUG: Directly instantiates DataProcessor (tight coupling) +BUG: Validation duplicated +""" + +# BUG: Circular import (data_processor imports this too) +from data_processor import DataProcessor + + +class BusinessLogic: + """Business logic - currently has circular dependency.""" + + def __init__(self): + """Initialize.""" + self._cache = {} + # BUG: Direct instantiation + self._processor = DataProcessor() + + def _validate(self): + """Validate - DUPLICATED validation logic.""" + if not hasattr(self._processor, "_data"): + return False + return len(self._processor._data) > 0 + + def _execute(self, data): + """Execute business logic.""" + # BUG: Inconsistent error handling + try: + result = [f"processed_{item}" for item in data] + return result + except Exception as e: + # BUG: Generic error handling + return [] + + def run(self, data): + """Run with data.""" + self._processor.load(data) + if not self._processor.validate(): + # BUG: Inconsistent error handling + raise RuntimeError("Invalid data") + return self._execute(data) +''' + + +def get_api_interface_content() -> str: + """Get api_interface.py.""" + return '''""" +API Interface Module + +BUG: Direct instantiation of BusinessLogic +""" + +from business_logic import BusinessLogic + + +class APIInterface: + """API interface - tight coupling to BusinessLogic.""" + + def __init__(self): + """Initialize.""" + # BUG: Direct instantiation + self._logic = BusinessLogic() + + def process_request(self, data): + """Process request.""" + # BUG: No input validation at API boundary + result = self._logic.run(data) + return {"status": "success", "data": result} + + def validate_request(self, data): + """Validate request - should be here, not scattered.""" + # BUG: Validation scattered across modules + if not data: + return False + return isinstance(data, list) +''' + + +def get_integration_content() -> str: + """Get integration.py.""" + return '''""" +Integration Module + +Currently mixes orchestration with business logic. +After refactoring, should use dependency injection. +""" + +from api_interface import APIInterface + + +def main(): + """Main integration - currently creates tight coupling.""" + # BUG: Integration logic mixes with instantiation + api = APIInterface() + + # BUG: No way to swap implementations for testing + data = ["apple", "banana", "cherry"] + + try: + response = api.process_request(data) + print("Success:", response) + except Exception as e: + print("Error:", e) + + return response + + +if __name__ == "__main__": + main() +''' + + +def get_test_file_content() -> str: + """Get test_refactoring.py.""" + return '''""" +Integration tests for refactoring validation. + +Current structure makes unit testing difficult. +After refactoring, should be easier to test modules independently. +""" + +import pytest + + +# NOTE: Current tests are difficult because modules are tightly coupled +# After refactoring with dependency injection, tests should be cleaner + + +def test_data_processor_load(): + """Test DataProcessor load - currently requires full setup.""" + # BUG: Can't test DataProcessor alone due to circular import + # After refactoring: Should work independently + pass + + +def test_business_logic_execute(): + """Test BusinessLogic execute - currently requires DataProcessor.""" + # BUG: Can't test BusinessLogic independently + # After refactoring: Should inject mocked DataProcessor + pass + + +def test_api_interface_request(): + """Test APIInterface request - currently full stack.""" + # BUG: Tests full stack, not individual components + # After refactoring: Should test API layer independently + pass + + +def test_validation_consistency(): + """Test that validation logic is consistent across modules.""" + # BUG: Validation is duplicated - hard to test consistently + # After refactoring: Should have single Validator + pass + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) +''' \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..08a68037d0927fdc479e8245d3d3e60b9f4471e8 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,31 @@ +version: '3.8' + +services: + debug-env: + build: + context: ./debug_env + dockerfile: ./server/Dockerfile + args: + BUILD_MODE: standalone + ENV_NAME: debug_env + ports: + - "8000:8000" + environment: + - PYTHONUNBUFFERED=1 + - LOG_LEVEL=info + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8000/health"] + interval: 30s + timeout: 3s + retries: 3 + start_period: 5s + restart: unless-stopped + volumes: + # Optional: mount code for development + - ./debug_env:/app/env:ro + networks: + - debug_env_network + +networks: + debug_env_network: + driver: bridge diff --git a/inference.py b/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..1c77c65bdad5ea9151b01587f0ef783a6eebea9a --- /dev/null +++ b/inference.py @@ -0,0 +1,535 @@ +""" +Debug-Env Benchmark Executor (Competition Version) + +Evaluates LLM agents on code debugging tasks via the OpenEnv server. +Fully compliant with OpenEnv competition requirements. + +Usage: + python inference.py # uses env vars + TASK=task2 NUMBER_OF_RUNS=3 python inference.py + +Required Environment Variables: + API_BASE_URL LLM API endpoint (e.g., https://api.openai.com/v1) + MODEL_NAME Model identifier (e.g., gpt-4o-mini) + OPENAI_API_KEY OpenAI API key + +Optional Environment Variables: + ENV_URL OpenEnv server URL (default: http://127.0.0.1:8000) + TASK task1 | task2 | task3 (default: task1) + NUMBER_OF_RUNS how many runs for Pass@k (default: 3) + MAX_STEPS max steps per run (default: 40) + TEMPERATURE LLM temperature (default: 0.0) + MAX_TOKENS max tokens per response (default: 4096) + REQUEST_DELAY_MS delay between requests in ms (default: 500) + +Output: + - Structured [START]/[STEP]/[END] logs to stdout + - Results JSON file: results_{task}_{timestamp}.json +""" + +import asyncio +import json +import logging +import os +import sys +import time +from datetime import datetime, timezone +from math import comb +from typing import Any, Dict, List, Optional + +from dotenv import load_dotenv + +load_dotenv() + +import httpx +from openai import AsyncOpenAI, APIError, RateLimitError + +logging.basicConfig( + level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger(__name__) + +# ── Tool definitions for function calling ────────────────────────────────────── + +TOOLS = [ + { + "type": "function", + "function": { + "name": "run_tests", + "description": ( + "Execute the pytest test suite against the current code. " + "Returns pass rate and full test output logs." + ), + "parameters": {"type": "object", "properties": {}, "required": []}, + }, + }, + { + "type": "function", + "function": { + "name": "read_file", + "description": ( + "Read the current content of a source file in the task working directory. " + "Use this to inspect broken code and helper files." + ), + "parameters": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Filename to read (e.g. 'broken_code.py')", + } + }, + "required": ["path"], + }, + }, + }, + { + "type": "function", + "function": { + "name": "edit_file", + "description": ( + "Overwrite a source file with corrected content and run tests. " + "Always provide the complete file content (full replacement)." + ), + "parameters": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Filename to edit (e.g. 'broken_code.py')", + }, + "content": { + "type": "string", + "description": "Complete new file content (full file replacement)", + }, + }, + "required": ["path", "content"], + }, + }, + }, +] + +SYSTEM_PROMPT = ( + "Fix broken Python code.\n\n" + "Steps:\n" + "1. run_tests - see errors\n" + "2. read_file('broken_code.py') - see buggy code\n" + "3. edit_file('broken_code.py') - fix it\n" + "4. run_tests - verify\n\n" + "Rules:\n" + "- MUST call edit_file to fix (reading only = reward 0)\n" + "- Always provide COMPLETE file in edit_file\n" + "- Stop when all tests pass (reward = 1.0)" +) + +# ── Configuration ─────────────────────────────────────────────────────────────── + +CONFIG = { + "env_url": os.getenv("ENV_URL", "http://127.0.0.1:8000"), + "api_base_url": os.getenv("API_BASE_URL", "https://api.openai.com/v1"), + "model_name": os.getenv("MODEL_NAME", "gpt-4o-mini"), + "openai_api_key": os.getenv("OPENAI_API_KEY", ""), + "task": os.getenv("TASK", "task1"), + "number_of_runs": int(os.getenv("NUMBER_OF_RUNS", "1")), # Testing: 1 run + "max_steps_per_run": int(os.getenv("MAX_STEPS", "10")), # Testing: 10 steps max + "temperature": float(os.getenv("TEMPERATURE", "0.0")), + "max_tokens": int(os.getenv("MAX_TOKENS", "1024")), # Testing: 1K tokens max + "request_delay_ms": int(os.getenv("REQUEST_DELAY_MS", "500")), +} + + +def _validate_config(config: Dict[str, Any]) -> None: + """Validate required environment variables.""" + if not config["openai_api_key"]: + raise ValueError( + "OPENAI_API_KEY environment variable is required. " + "Set it via: export OPENAI_API_KEY=sk-..." + ) + if not config["model_name"]: + raise ValueError( + "MODEL_NAME environment variable is required. " + "Set it via: export MODEL_NAME=gpt-4o-mini" + ) + if not config["api_base_url"]: + raise ValueError( + "API_BASE_URL environment variable is required. " + "Set it via: export API_BASE_URL=https://api.openai.com/v1" + ) + + +# ── OpenAI Client Setup ───────────────────────────────────────────────────────── + + +async def _init_openai_client(config: Dict[str, Any]) -> AsyncOpenAI: + """Initialize AsyncOpenAI client with proper configuration.""" + return AsyncOpenAI( + api_key=config["openai_api_key"], + base_url=config["api_base_url"], + ) + + +# ── OpenEnv Environment Client ────────────────────────────────────────────────── + + +async def env_reset(env_url: str, task: str) -> Dict[str, Any]: + """Reset the environment to the initial state for a task.""" + async with httpx.AsyncClient(timeout=30) as client: + r = await client.post(f"{env_url}/reset", json={"task": task}) + r.raise_for_status() + return r.json() + + +async def env_step( + env_url: str, tool: str, args: Dict[str, Any], delay_ms: int = 500 +) -> Dict[str, Any]: + """Execute a tool step with retry logic and rate limiting.""" + action = {"tool": tool, "args": args} + + # Rate limiting delay + await asyncio.sleep(delay_ms / 1000.0) + + # Retry logic for transient errors + max_retries = 3 + for attempt in range(max_retries): + try: + async with httpx.AsyncClient(timeout=60) as client: + r = await client.post(f"{env_url}/step", json={"action": action}) + r.raise_for_status() + return r.json() + except httpx.HTTPStatusError as e: + if e.response.status_code == 429: # Rate limited + wait_time = 2**attempt # Exponential backoff: 1s, 2s, 4s + logger.warning( + f"Rate limited. Retrying in {wait_time}s (attempt {attempt+1}/{max_retries})" + ) + await asyncio.sleep(wait_time) + else: + raise + except Exception as e: + if attempt == max_retries - 1: + raise + logger.warning( + f"Request failed: {e}. Retrying (attempt {attempt+1}/{max_retries})" + ) + await asyncio.sleep(1) + + raise RuntimeError(f"Failed to execute {tool} after {max_retries} retries") + + +# ── Single Run Execution ──────────────────────────────────────────────────────── + + +async def execute_run( + run_number: int, + client: AsyncOpenAI, + config: Dict[str, Any], +) -> Dict[str, Any]: + """Execute a single run of the debugging task.""" + from copy import deepcopy + + env_url = config["env_url"] + task = config["task"] + max_steps = config["max_steps_per_run"] + model = config["model_name"] + + # Structured logging: [START] + print(f"[START] run={run_number} task={task} model={model}") + + # Reset environment + reset_data = await env_reset(env_url, task) + initial_logs = (reset_data.get("observation") or {}).get("logs", "") + + # Initialize message history + messages = [ + { + "role": "system", + "content": SYSTEM_PROMPT, + }, + { + "role": "user", + "content": ( + f"Task: {task}\n\n" + f"Tests:\n{initial_logs}\n\n" + f"Fix broken_code.py. Start with run_tests." + ), + }, + ] + + rewards: List[float] = [] + tools_used: List[str] = [] + steps_detail: List[Dict] = [] + success = False + start_ts = datetime.now(timezone.utc) + + for step in range(1, max_steps + 1): + try: + # LLM call with function calling + response = await client.chat.completions.create( + model=model, + messages=messages, + tools=TOOLS, + tool_choice="auto", + temperature=config["temperature"], + max_tokens=config["max_tokens"], + ) + + # Check if LLM finished without tool calls + assistant_message = response.choices[0].message + has_tool_calls = hasattr(assistant_message, 'tool_calls') and assistant_message.tool_calls + + # Debug: Log what tools the model is trying to call + if has_tool_calls: + tool_names = [tc.function.name for tc in assistant_message.tool_calls] + logger.debug(f"Model trying to call: {tool_names}") + + if not has_tool_calls: + logger.info("LLM finished reasoning without tool calls") + break + + # Process tool calls + messages.append({ + "role": "assistant", + "content": assistant_message.content or "", + "tool_calls": [ + { + "id": tc.id, + "type": "function", + "function": { + "name": tc.function.name, + "arguments": tc.function.arguments, + } + } + for tc in assistant_message.tool_calls + ] if assistant_message.tool_calls else None + }) + + tool_results = [] + for tc in assistant_message.tool_calls: + tool_name = tc.function.name + tool_args = json.loads(tc.function.arguments) + + # Execute tool in environment + res = await env_step( + env_url, + tool_name, + tool_args, + delay_ms=config["request_delay_ms"], + ) + reward = res.get("reward", 0.0) + done = res.get("done", False) + logs = (res.get("observation") or {}).get("logs", "") + + rewards.append(reward) + if tool_name not in tools_used: + tools_used.append(tool_name) + + steps_detail.append( + { + "step": step, + "tool": tool_name, + "args": { + k: v[:120] + "…" + if isinstance(v, str) and len(v) > 120 + else v + for k, v in tool_args.items() + }, + "reward": reward, + "done": done, + } + ) + + # Structured logging: [STEP] + print( + f"[STEP] run={run_number} step={step} " + f"tool={tool_name} reward={reward:.2f} done={done}" + ) + + # Add tool result to messages + tool_results.append( + { + "role": "tool", + "tool_call_id": tc.id, + "content": f"reward={reward}, done={done}\n\n{logs}", + } + ) + + if done: + success = True + break + + # Add all tool results to messages + messages.extend(tool_results) + + if success: + break + + except (RateLimitError, APIError) as e: + logger.error(f"OpenAI API error at step {step}: {e}") + if step < max_steps: + await asyncio.sleep(2) + else: + break + except Exception as e: + logger.error(f"Unexpected error at step {step}: {e}", exc_info=True) + break + + elapsed_ms = int( + (datetime.now(timezone.utc) - start_ts).total_seconds() * 1000 + ) + final_reward = rewards[-1] if rewards else 0.0 + + # Structured logging: [END] + print( + f"[END] run={run_number} success={success} " + f"steps={len(rewards)} final_reward={final_reward:.2f} elapsed_ms={elapsed_ms}" + ) + + return { + "run_number": run_number, + "success": success, + "final_reward": final_reward, + "rewards": rewards, + "steps": steps_detail, + "tools_used": tools_used, + "elapsed_ms": elapsed_ms, + } + + +# ── Statistics Calculation ────────────────────────────────────────────────────── + + +def calculate_statistics(runs: List[Dict[str, Any]]) -> Dict[str, Any]: + """Calculate Pass@k and other metrics from run results.""" + total = len(runs) + successes = [r for r in runs if r["success"]] + n_success = len(successes) + + # Pass@k: probability that at least one of k runs succeeds + pass_at = {} + for k in range(1, total + 1): + if total - n_success < k: + pass_at[f"pass@{k}"] = 1.0 + else: + pass_at[f"pass@{k}"] = ( + 1.0 - comb(total - n_success, k) / comb(total, k) + ) + + avg_steps = sum(len(r["rewards"]) for r in runs) / total if total else 0 + avg_final_reward = sum(r["final_reward"] for r in runs) / total if total else 0 + mean_time_ms = sum(r["elapsed_ms"] for r in runs) / total if total else 0 + + # Tool usage across all runs + tool_counts: Dict[str, int] = {} + for r in runs: + for t in r["tools_used"]: + tool_counts[t] = tool_counts.get(t, 0) + 1 + + return { + "total_runs": total, + "successful_runs": n_success, + "success_rate": n_success / total if total else 0.0, + **pass_at, + "avg_steps_per_run": round(avg_steps, 2), + "avg_final_reward": round(avg_final_reward, 4), + "mean_elapsed_ms": round(mean_time_ms, 0), + "tool_usage": tool_counts, + } + + +# ── Main ──────────────────────────────────────────────────────────────────────── + + +async def main(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """Main benchmark execution.""" + if config is None: + config = CONFIG + + # Validate configuration + try: + _validate_config(config) + except ValueError as e: + logger.error(f"Configuration error: {e}") + sys.exit(1) + + task = config["task"] + n_runs = config["number_of_runs"] + + logger.info("=" * 70) + logger.info(f"DEBUG-ENV BENCHMARK - OPENAI COMPETITION VERSION") + logger.info( + f"task={task} model={config['model_name']} " + f"runs={n_runs} max_steps={config['max_steps_per_run']}" + ) + logger.info("=" * 70) + + # Initialize OpenAI client + client = await _init_openai_client(config) + all_runs: List[Dict[str, Any]] = [] + + # Execute runs + for run_number in range(1, n_runs + 1): + try: + result = await execute_run(run_number, client, config) + all_runs.append(result) + except Exception as e: + logger.error(f"Run {run_number} failed: {e}", exc_info=True) + all_runs.append( + { + "run_number": run_number, + "success": False, + "final_reward": 0.0, + "rewards": [], + "steps": [], + "tools_used": [], + "elapsed_ms": 0, + "error": str(e), + } + ) + + # Calculate statistics + stats = calculate_statistics(all_runs) + + output = { + "benchmark_config": { + "task": task, + "model": config["model_name"], + "api_base_url": config["api_base_url"], + "number_of_runs": n_runs, + "max_steps_per_run": config["max_steps_per_run"], + "temperature": config["temperature"], + }, + "runs": all_runs, + "statistics": stats, + } + + # Save results to JSON file + ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") + out_file = f"results_{task}_{ts}.json" + with open(out_file, "w") as f: + json.dump(output, f, indent=2, default=str) + + # Print summary + print() + print("=" * 70) + print("BENCHMARK SUMMARY") + print("=" * 70) + print(f"Task: {task}") + print(f"Model: {config['model_name']}") + print(f"Runs: {stats['total_runs']}") + print(f"Success rate: {stats['success_rate']:.1%} ({stats['successful_runs']}/{stats['total_runs']})") + for k in range(1, n_runs + 1): + key = f"pass@{k}" + if key in stats: + print(f"{key:15} {stats[key]:.1%}") + print(f"Avg steps: {stats['avg_steps_per_run']}") + print(f"Avg reward: {stats['avg_final_reward']:.4f}") + print(f"Mean time: {stats['mean_elapsed_ms']:.0f} ms") + print(f"Tool usage: {stats['tool_usage']}") + print(f"Results file: {out_file}") + print("=" * 70) + + return output + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8aaf8dd5bc019a9928fde56868ce698855413384 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,138 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +[build-system] +requires = ["setuptools>=45", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "openenv-debug-env" +version = "0.1.0" +description = "Debug Env - An OpenEnv benchmark for evaluating LLM agents on code debugging tasks" +readme = "README.md" +requires-python = ">=3.10" +authors = [ + {name = "Meta Platforms, Inc.", email = "pytorch@meta.com"}, +] +keywords = [ + "openenv", + "benchmark", + "llm", + "agents", + "debugging", + "code", +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: BSD License", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Scientific/Engineering :: Artificial Intelligence", +] + +dependencies = [ + # OpenEnv runtime + "openenv-core[core]>=0.2.2", + + # Web & HTTP + "fastapi>=0.104.0", + "uvicorn[standard]>=0.24.0", + "httpx>=0.27.0", + + # LLM Inference (OpenAI primary, with support for others) + "openai>=1.29.0", # Official OpenAI client + "langchain-core>=0.3.0", + "langchain-openai>=0.3.0", + "langchain-anthropic>=0.3.0", + "langchain-google-genai>=2.0.0", + + # Database persistence + "sqlalchemy>=2.0.0", + + # Utilities + "python-dotenv>=1.0.0", + "pydantic>=2.0.0", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.0.0", + "pytest-cov>=4.0.0", + "pytest-asyncio>=0.23.0", + "black>=24.0.0", + "ruff>=0.3.0", +] + +[project.scripts] +# Server entry point - enables running via: python -m debug_env.server.app +server = "debug_env.server.app:main" + +# Inference entry point +inference = "inference:main" + +[tool.setuptools] +include-package-data = true + +[tool.setuptools.packages.find] +where = ["debug_env"] +include = ["debug_env*"] + +[tool.black] +line-length = 100 +target-version = ["py310"] +include = '\.pyi?$' +exclude = ''' +/( + \.git + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | _build + | buck-out + | build + | dist + | __pycache__ +)/ +''' + +[tool.ruff] +line-length = 100 +target-version = "py310" +exclude = [ + ".git", + ".venv", + "__pycache__", + "build", + "dist", +] + +[tool.ruff.lint] +select = [ + "E", # pycodestyle errors + "W", # pycodestyle warnings + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "SIM", # flake8-simplify +] +ignore = [ + "E501", # line-too-long + "E203", # whitespace-before-punctuation + "W503", # line-break-before-binary-operator +] + +[tool.pytest.ini_options] +minversion = "7.0" +addopts = "-v --strict-markers --tb=short" +testpaths = ["tests"] +asyncio_mode = "auto" diff --git a/verify_setup.py b/verify_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8783d7cc7536b92af1f50262ffa0ee1f97469a18 --- /dev/null +++ b/verify_setup.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python +""" +Verification script for OpenEnv Competition Setup + +Checks all required components and validates the setup is ready for submission. +""" + +import os +import sys +import json +import subprocess +from pathlib import Path +from typing import Tuple +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + +def check_file_exists(path: str, description: str) -> Tuple[bool, str]: + """Check if a required file exists.""" + p = Path(path) + if p.exists(): + return True, f"[OK] {description}: {path}" + return False, f"[FAIL] {description}: MISSING - {path}" + +def check_python_module(module_name: str) -> Tuple[bool, str]: + """Check if a Python module is installed.""" + try: + __import__(module_name) + return True, f"[OK] {module_name} installed" + except ImportError: + return False, f"[FAIL] {module_name} NOT installed" + +def check_env_var(var_name: str) -> Tuple[bool, str]: + """Check if an environment variable is set.""" + value = os.getenv(var_name) + if value: + masked = value[:10] + "***" if len(value) > 10 else "***" + return True, f"[OK] {var_name} is set ({masked})" + return False, f"[FAIL] {var_name} NOT set" + +def check_syntax(file_path: str) -> Tuple[bool, str]: + """Check Python file syntax.""" + try: + compile(open(file_path).read(), file_path, 'exec') + return True, f"[OK] {file_path} syntax OK" + except SyntaxError as e: + return False, f"[FAIL] {file_path} has syntax error: {e}" + +def check_task_files() -> Tuple[bool, str]: + """Check that all tasks have required files.""" + for task_num in [1, 2, 3]: + task_dir = f"debug_env/tasks/task{task_num}" + broken_code = f"{task_dir}/broken_code.py" + test_code = f"{task_dir}/test_code.py" + + if not Path(broken_code).exists(): + return False, f"[FAIL] {broken_code} missing" + if not Path(test_code).exists(): + return False, f"[FAIL] {test_code} missing" + + return True, "[OK] All 3 tasks have required files" + +def check_docker_file() -> Tuple[bool, str]: + """Check Dockerfile exists and is readable.""" + dockerfile = "debug_env/server/Dockerfile" + if Path(dockerfile).exists(): + try: + with open(dockerfile) as f: + content = f.read() + if "FROM" in content and "CMD" in content: + return True, f"[OK] Dockerfile is valid" + except Exception as e: + return False, f"[FAIL] Dockerfile error: {e}" + return False, f"[FAIL] Dockerfile missing" + +def main(): + print("\n" + "=" * 70) + print("OpenEnv Competition Setup Verification") + print("=" * 70 + "\n") + + checks = [] + + # 1. File structure + print("1. Checking file structure...") + checks.append(check_file_exists("debug_env/openenv.yaml", "openenv.yaml")) + checks.append(check_file_exists("inference.py", "inference.py (competition entry point)")) + checks.append(check_file_exists(".env", ".env configuration")) + checks.append(check_file_exists(".env.example", ".env.example template")) + checks.append(check_file_exists("README.md", "README.md")) + checks.append(check_file_exists("QUICKSTART.md", "QUICKSTART.md")) + checks.append(check_file_exists("COMPETITION_CHECKLIST.md", "COMPETITION_CHECKLIST.md")) + checks.append(check_file_exists("pyproject.toml", "pyproject.toml (root)")) + checks.append(check_file_exists("docker-compose.yml", "docker-compose.yml")) + checks.append(check_docker_file()) + + # 2. Task files + print("\n2. Checking task files...") + checks.append(check_task_files()) + + # 3. Python syntax + print("\n3. Checking Python syntax...") + checks.append(check_syntax("inference.py")) + + # 4. Required Python modules + print("\n4. Checking Python dependencies...") + checks.append(check_python_module("openai")) + checks.append(check_python_module("httpx")) + checks.append(check_python_module("openenv")) + checks.append(check_python_module("fastapi")) + + # 5. Environment variables + print("\n5. Checking environment configuration...") + checks.append(check_env_var("OPENAI_API_KEY")) + checks.append(check_env_var("API_BASE_URL")) + checks.append(check_env_var("MODEL_NAME")) + + # Print results + print("\n" + "=" * 70) + print("Verification Results") + print("=" * 70 + "\n") + + passed = 0 + failed = 0 + + for success, message in checks: + print(message) + if success: + passed += 1 + else: + failed += 1 + + print("\n" + "=" * 70) + print(f"Summary: {passed} passed, {failed} failed") + print("=" * 70 + "\n") + + if failed == 0: + print("[SUCCESS] All checks passed! Your setup is ready for competition.\n") + print("Next steps:") + print(" 1. Set OPENAI_API_KEY in .env with your actual API key") + print(" 2. Run: python inference.py") + print(" 3. Check results in results_task1_*.json") + print(" 4. Deploy to Hugging Face Spaces") + return 0 + else: + print(f"[ERROR] {failed} checks failed. Please fix the issues above.\n") + if failed >= 2: + print("Start with:") + print(" 1. pip install -e .") + print(" 2. cp .env.example .env") + print(" 3. Edit .env with your OPENAI_API_KEY") + return 1 + +if __name__ == "__main__": + sys.exit(main())