File size: 9,706 Bytes
ff9fcbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
"""
FastAPI application for the Code Review Environment.

Endpoints:
  POST /reset    β€” start new episode
  POST /step     β€” take an action
  GET  /state    β€” get episode state
  GET  /health   β€” health check
  GET  /tasks    β€” list all tasks + action schema
  POST /grader   β€” grade a set of findings (stateless)
  POST /baseline β€” run keyword-heuristic baseline on all tasks
  WS   /ws       β€” persistent WebSocket session
  GET  /docs     β€” Swagger UI (auto-generated)
"""
from __future__ import annotations

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import json
import asyncio
import dataclasses
from typing import Optional, List, Dict, Any

from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

from models import ReviewAction, Issue
from server.environment import CodeReviewEnvironment
from server.graders import grade_episode, run_keyword_baseline
from tasks.data import ALL_TASKS, TASK_IDS



def _serialize(obj) -> dict:
    if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
        d = dataclasses.asdict(obj)
        # asdict handles nested dataclasses and lists recursively
        return d
    if isinstance(obj, dict):
        return obj
    raise TypeError(f"Cannot serialize {type(obj)}")


_env_instance = CodeReviewEnvironment()


def _make_app() -> FastAPI:
    try:
        from openenv.core.env_server import create_fastapi_app
        base = create_fastapi_app(CodeReviewEnvironment)
        return base
    except Exception:
        pass

    _app = FastAPI(
        title="Code Review Environment",
        description=(
            "An OpenEnv environment for training AI agents to perform "
            "code review and security audits."
        ),
        version="1.0.0",
    )

    _app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_methods=["*"],
        allow_headers=["*"],
    )

    @_app.get("/health")
    async def health():
        return {"status": "healthy"}

    @_app.post("/reset")
    async def reset(body: dict = None):
        body = body or {}
        task_id = body.get("task_id")
        seed = body.get("seed")
        episode_id = body.get("episode_id")
        obs = _env_instance.reset(task_id=task_id, seed=seed, episode_id=episode_id)
        return _serialize(obs)

    @_app.post("/step")
    async def step(body: dict):
        action = ReviewAction.from_dict(body)
        obs = _env_instance.step(action)
        return _serialize(obs)

    @_app.get("/state")
    async def state():
        return _serialize(_env_instance.state)

    @_app.websocket("/ws")
    async def websocket_endpoint(websocket: WebSocket):
        await websocket.accept()
        ws_env = CodeReviewEnvironment()
        try:
            while True:
                raw = await websocket.receive_text()
                msg = json.loads(raw)
                msg_type = msg.get("type", "")

                if msg_type == "reset":
                    data = msg.get("data", {})
                    obs = ws_env.reset(
                        task_id=data.get("task_id"),
                        seed=data.get("seed"),
                        episode_id=data.get("episode_id"),
                    )
                    await websocket.send_text(json.dumps({
                        "type": "observation",
                        "data": _serialize(obs),
                    }))

                elif msg_type == "step":
                    action = ReviewAction.from_dict(msg.get("data", {}))
                    obs = ws_env.step(action)
                    await websocket.send_text(json.dumps({
                        "type": "observation",
                        "data": _serialize(obs),
                    }))

                elif msg_type == "state":
                    await websocket.send_text(json.dumps({
                        "type": "state",
                        "data": _serialize(ws_env.state),
                    }))

                elif msg_type == "close":
                    break

                else:
                    await websocket.send_text(json.dumps({
                        "type": "error",
                        "data": f"Unknown message type: {msg_type}",
                    }))

        except WebSocketDisconnect:
            pass
        except Exception as e:
            try:
                await websocket.send_text(json.dumps({"type": "error", "data": str(e)}))
            except Exception:
                pass

    return _app


app = _make_app()


@app.get("/tasks")
async def list_tasks():
    tasks_list = []
    for task in ALL_TASKS.values():
        tasks_list.append({
            "task_id": task["task_id"],
            "difficulty": task["difficulty"],
            "description": task["description"],
            "language": task.get("language", "python"),
            "max_steps": task["max_steps"],
            "num_issues": len(task["ground_truth_issues"]),
            "files": list(task["code_files"].keys()),
        })

    action_schema = {
        "type": "object",
        "description": "ReviewAction β€” one action per /step call",
        "required": ["action_type"],
        "properties": {
            "action_type": {
                "type": "string",
                "enum": ["flag_issue", "clear_flag", "request_hint", "submit_review"],
                "description": (
                    "flag_issue: mark a line as problematic. "
                    "clear_flag: remove a previous flag. "
                    "request_hint: get a hint (-0.01 reward). "
                    "submit_review: end episode and receive final grade."
                ),
            },
            "line_number": {
                "type": "integer",
                "description": "Line number of the issue (required for flag_issue / clear_flag)",
            },
            "filename": {
                "type": "string",
                "description": "File where the issue is (required for flag_issue / clear_flag)",
            },
            "issue_type": {
                "type": "string",
                "enum": ["bug", "security", "performance", "logic"],
                "description": "Category of issue (required for flag_issue)",
            },
            "severity": {
                "type": "string",
                "enum": ["low", "medium", "high", "critical"],
                "description": "Severity level (required for flag_issue)",
            },
            "description": {
                "type": "string",
                "description": "Human-readable description of the issue",
            },
            "fix_suggestion": {
                "type": "string",
                "description": "Optional suggested fix",
            },
        },
        "examples": [
            {
                "action_type": "flag_issue",
                "line_number": 6,
                "filename": "utils.py",
                "issue_type": "bug",
                "severity": "high",
                "description": "Off-by-one error in range()",
                "fix_suggestion": "Change range(len(numbers) + 1) to range(len(numbers))",
            },
            {"action_type": "submit_review"},
        ],
    }

    return {
        "tasks": tasks_list,
        "action_schema": action_schema,
        "total_tasks": len(tasks_list),
    }


class GraderRequest(BaseModel):
    task_id: str
    flagged_issues: List[Dict[str, Any]]

@app.post("/grader")
async def run_grader(request: GraderRequest):
    task = ALL_TASKS.get(request.task_id)
    if not task:
        raise HTTPException(
            status_code=404,
            detail=f"Unknown task_id '{request.task_id}'. Valid: {TASK_IDS}",
        )

    flagged = [Issue.from_dict(i) for i in request.flagged_issues]
    ground_truth = [Issue.from_dict(gt) for gt in task["ground_truth_issues"]]
    score = grade_episode(flagged, ground_truth)

    tp = sum(
        1 for f in flagged
        if any(
            True for gt in ground_truth
            if abs(f.line_number - gt.line_number) <= 2
            and f.filename == gt.filename
        )
    )

    return {
        "task_id": request.task_id,
        "difficulty": task["difficulty"],
        "score": score,
        "max_score": 1.0,
        "details": {
            "total_flagged": len(flagged),
            "true_positives": tp,
            "false_positives": len(flagged) - tp,
            "total_ground_truth": len(ground_truth),
        },
    }


@app.post("/baseline")
async def run_baseline():
    results = {}
    for task_id, task in ALL_TASKS.items():
        findings = run_keyword_baseline(task)
        ground_truth = [Issue.from_dict(gt) for gt in task["ground_truth_issues"]]
        score = grade_episode(findings, ground_truth)
        results[task_id] = {
            "difficulty": task["difficulty"],
            "score": score,
            "findings_count": len(findings),
            "ground_truth_count": len(ground_truth),
        }

    overall = sum(r["score"] for r in results.values()) / len(results)
    return {
        "baseline_scores": results,
        "overall_average": round(overall, 4),
        "method": "keyword_heuristic",
        "note": (
            "Run 'python baseline.py' with OPENAI_API_KEY for the LLM-based baseline. "
            "This endpoint uses a deterministic regex heuristic."
        ),
    }


def main():
    import uvicorn
    port = int(os.environ.get("PORT", 7860))
    uvicorn.run("server.app:app", host="0.0.0.0", port=port)


if __name__ == "__main__":
    main()