coderMayank69 commited on
Commit
2db0a88
·
0 Parent(s):

created script

Browse files
.dockerignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ *.log
6
+ .venv/
7
+ .env
8
+ .git/
9
+ .gitignore
.github/copilot-instructions.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Project Guidelines
2
+
3
+ ## Code Style
4
+ - Use Python 3.11 and type hints for all public functions.
5
+ - Keep request/response schemas in Pydantic models under app/models.py.
6
+ - Keep grading deterministic; avoid non-deterministic scoring logic.
7
+
8
+ ## Architecture
9
+ - FastAPI entrypoint is app/main.py.
10
+ - Core environment logic is app/env.py with reset, step, and state methods.
11
+ - Task definitions live in app/tasks.py.
12
+ - Deterministic reward logic lives in app/grader.py.
13
+
14
+ ## Build and Test
15
+ - Install dependencies: pip install -r requirements.txt
16
+ - Run API server: uvicorn app.main:app --host 0.0.0.0 --port 8000
17
+ - Validate OpenEnv manifest: openenv validate
18
+ - Run baseline script: python app/inference.py
19
+ - Build and run container:
20
+ - docker build -t synapse-code-auditor .
21
+ - docker run --rm -p 8000:8000 synapse-code-auditor
22
+
23
+ ## Conventions
24
+ - Environment episodes are single-step for scoring consistency.
25
+ - Reward must remain within 0.0 to 1.0 with partial credit support.
26
+ - API schema compatibility for endpoints /reset, /step, and /state is required.
Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ ENV PYTHONDONTWRITEBYTECODE=1
4
+ ENV PYTHONUNBUFFERED=1
5
+
6
+ WORKDIR /app
7
+
8
+ COPY requirements.txt ./
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ COPY . .
12
+
13
+ EXPOSE 8000
14
+
15
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
README.md ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Synapse Code Auditor (OpenEnv Environment)
2
+
3
+ Synapse Code Auditor is a production-ready OpenEnv environment for evaluating AI code-review behavior across deterministic tasks.
4
+
5
+ ## Real-World Use Case
6
+
7
+ Software teams use code review to catch bugs, improve quality, and enforce maintainability. This environment simulates that workflow so agent performance can be trained and measured with reproducible rewards.
8
+
9
+ ## Project Structure
10
+
11
+ ```text
12
+ .
13
+ ├── app/
14
+ │ ├── __init__.py
15
+ │ ├── env.py
16
+ │ ├── grader.py
17
+ │ ├── inference.py
18
+ │ ├── main.py
19
+ │ ├── models.py
20
+ │ └── tasks.py
21
+ ├── .dockerignore
22
+ ├── Dockerfile
23
+ ├── openenv.yaml
24
+ ├── README.md
25
+ └── requirements.txt
26
+ ```
27
+
28
+ ## OpenEnv Interface
29
+
30
+ This environment implements the required interface methods in the core environment class:
31
+
32
+ - reset(task_id=None, seed=42)
33
+ - step(action)
34
+ - state()
35
+
36
+ FastAPI endpoints expose the same functionality:
37
+
38
+ - POST /reset
39
+ - POST /step
40
+ - GET /state
41
+
42
+ ## Action and Observation Schemas
43
+
44
+ Observation:
45
+
46
+ ```json
47
+ {
48
+ "task_id": "easy",
49
+ "task_type": "easy",
50
+ "code": "def add_numbers(a, b)\n result = a + b\n return result\n",
51
+ "instructions": "Identify the exact syntax error in the code and propose a valid fix.",
52
+ "previous_feedback": null
53
+ }
54
+ ```
55
+
56
+ Action:
57
+
58
+ ```json
59
+ {
60
+ "review": "The function definition is missing a colon. Change it to def add_numbers(a, b):"
61
+ }
62
+ ```
63
+
64
+ Reward:
65
+
66
+ ```json
67
+ {
68
+ "score": 1.0,
69
+ "matched_criteria": ["syntax error", "missing colon", "def add_numbers(a, b):"],
70
+ "missed_criteria": [],
71
+ "penalties": {},
72
+ "rationale": "Coverage=1.00; Penalty=0.00; Matched=3/3"
73
+ }
74
+ ```
75
+
76
+ ## Tasks
77
+
78
+ 1. Easy: Detect syntax errors
79
+ 2. Medium: Suggest optimization
80
+ 3. Hard: Full code review with scoring
81
+
82
+ Each task has deterministic grading criteria and a score range of 0.0 to 1.0.
83
+
84
+ ## Deterministic Grader and Reward Design
85
+
86
+ - Deterministic keyword/criterion matching for each task.
87
+ - Partial reward from criterion coverage.
88
+ - Penalties for short, irrelevant, or incorrect responses.
89
+ - Hard task penalizes missing overall score/rating in the review.
90
+
91
+ Reward formula:
92
+
93
+ ```text
94
+ score = clamp(criterion_coverage - penalties, 0.0, 1.0)
95
+ ```
96
+
97
+ ## Local Setup
98
+
99
+ ### 1. Create environment and install dependencies
100
+
101
+ ```bash
102
+ python -m venv .venv
103
+ . .venv/Scripts/activate
104
+ pip install -r requirements.txt
105
+ ```
106
+
107
+ ### 2. Run FastAPI server
108
+
109
+ ```bash
110
+ uvicorn app.main:app --host 0.0.0.0 --port 8000
111
+ ```
112
+
113
+ ### 3. Validate OpenEnv manifest
114
+
115
+ ```bash
116
+ openenv validate
117
+ ```
118
+
119
+ ## Docker Run
120
+
121
+ ```bash
122
+ docker build -t synapse-code-auditor .
123
+ docker run --rm -p 8000:8000 synapse-code-auditor
124
+ ```
125
+
126
+ Then test:
127
+
128
+ ```bash
129
+ curl http://localhost:8000/health
130
+ curl -X POST http://localhost:8000/reset -H "Content-Type: application/json" -d "{\"task_id\":\"easy\",\"seed\":42}"
131
+ ```
132
+
133
+ ## Baseline Inference Script
134
+
135
+ The baseline runner uses an OpenAI-compatible client and executes all 3 tasks.
136
+
137
+ Required environment variables:
138
+
139
+ - OPENAI_API_KEY: API key for model inference
140
+ - API_BASE_URL: OpenAI-compatible API URL (default https://api.openai.com/v1)
141
+ - MODEL_NAME: model identifier (default gpt-4o-mini)
142
+
143
+ Optional:
144
+
145
+ - ENV_BASE_URL: environment API base URL (default http://localhost:8000)
146
+
147
+ Run:
148
+
149
+ ```bash
150
+ python app/inference.py
151
+ ```
152
+
153
+ ## Example Baseline Output
154
+
155
+ ```text
156
+ Synapse Code Auditor baseline run
157
+ Environment URL: http://localhost:8000
158
+ Model endpoint: https://api.openai.com/v1
159
+ Model: gpt-4o-mini
160
+ - easy: score=1.0000 | Coverage=1.00; Penalty=0.00; Matched=3/3
161
+ - medium: score=1.0000 | Coverage=1.00; Penalty=0.00; Matched=3/3
162
+ - hard: score=0.8000 | Coverage=1.00; Penalty=0.20; Matched=5/5
163
+ Average score: 0.9333
164
+ ```
165
+
166
+ ## Hugging Face Spaces Deployment
167
+
168
+ This project is container-ready and compatible with Hugging Face Docker Spaces.
169
+
170
+ 1. Push repository to Hugging Face Space configured for Docker.
171
+ 2. Ensure port 8000 is exposed (already set in Dockerfile and openenv.yaml).
172
+ 3. Build and run automatically in Space.
173
+
174
+ OpenEnv deployment command:
175
+
176
+ ```bash
177
+ openenv push
178
+ ```
179
+
180
+ ## API Reference
181
+
182
+ - GET /health
183
+ - POST /reset with payload {"task_id": "easy|medium|hard", "seed": 42}
184
+ - POST /step with payload {"action": {"review": "..."}}
185
+ - GET /state
186
+
187
+ This environment is ready for end-to-end local execution, Docker execution, and OpenEnv workflow validation.
app/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Synapse Code Auditor application package."""
app/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (231 Bytes). View file
 
app/__pycache__/env.cpython-313.pyc ADDED
Binary file (4.72 kB). View file
 
app/__pycache__/grader.cpython-313.pyc ADDED
Binary file (3.51 kB). View file
 
app/__pycache__/main.cpython-313.pyc ADDED
Binary file (2.38 kB). View file
 
app/__pycache__/models.cpython-313.pyc ADDED
Binary file (4.28 kB). View file
 
app/__pycache__/tasks.cpython-313.pyc ADDED
Binary file (2.64 kB). View file
 
app/env.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.grader import grade_review
2
+ from app.models import Action, EnvState, Observation, Reward, StepResult, TaskType
3
+ from app.tasks import ORDERED_TASK_IDS, get_task
4
+
5
+
6
+ class AICodeReviewEnvironment:
7
+ def __init__(self) -> None:
8
+ self.episode_id = 0
9
+ self.total_steps = 0
10
+ self._task_pointer = 0
11
+ self._last_reward: float | None = None
12
+ self._history: list[dict] = []
13
+ self._current_task_id: str | None = None
14
+ self._current_observation: Observation | None = None
15
+ self._done = False
16
+
17
+ def reset(self, task_id: str | None = None, seed: int = 42) -> Observation:
18
+ self.episode_id += 1
19
+ self._done = False
20
+
21
+ if task_id is None:
22
+ # Deterministic task sequence controlled by seed for reproducibility.
23
+ self._task_pointer = (seed + self.episode_id - 1) % len(ORDERED_TASK_IDS)
24
+ chosen_task_id = ORDERED_TASK_IDS[self._task_pointer]
25
+ else:
26
+ chosen_task_id = task_id
27
+
28
+ task = get_task(chosen_task_id)
29
+
30
+ observation = Observation(
31
+ task_id=task.id,
32
+ task_type=TaskType(task.task_type),
33
+ code=task.code,
34
+ instructions=task.instructions,
35
+ previous_feedback=None,
36
+ )
37
+
38
+ self._current_task_id = task.id
39
+ self._current_observation = observation
40
+ return observation
41
+
42
+ def step(self, action: Action) -> StepResult:
43
+ if self._current_task_id is None or self._current_observation is None:
44
+ raise ValueError("Environment not initialized. Call reset() first.")
45
+
46
+ if self._done:
47
+ raise ValueError("Episode already completed. Call reset() for a new task.")
48
+
49
+ task = get_task(self._current_task_id)
50
+ grade = grade_review(task=task, review=action.review)
51
+
52
+ reward = Reward(
53
+ score=grade.score,
54
+ matched_criteria=grade.matched_criteria,
55
+ missed_criteria=grade.missed_criteria,
56
+ penalties=grade.penalties,
57
+ rationale=grade.rationale,
58
+ )
59
+
60
+ self.total_steps += 1
61
+ self._done = True
62
+ self._last_reward = reward.score
63
+
64
+ self._history.append(
65
+ {
66
+ "episode_id": self.episode_id,
67
+ "task_id": task.id,
68
+ "task_type": task.task_type,
69
+ "reward": reward.score,
70
+ }
71
+ )
72
+
73
+ next_observation = Observation(
74
+ task_id=self._current_observation.task_id,
75
+ task_type=self._current_observation.task_type,
76
+ code=self._current_observation.code,
77
+ instructions=self._current_observation.instructions,
78
+ previous_feedback=f"Scored {reward.score:.2f}. {reward.rationale}",
79
+ )
80
+
81
+ return StepResult(
82
+ observation=next_observation,
83
+ reward=reward,
84
+ done=True,
85
+ info={
86
+ "task_title": task.title,
87
+ "episode_id": self.episode_id,
88
+ },
89
+ )
90
+
91
+ def state(self) -> EnvState:
92
+ status = "idle" if self._current_task_id is None else ("done" if self._done else "awaiting_action")
93
+ current_type = None
94
+ if self._current_task_id is not None:
95
+ current_type = get_task(self._current_task_id).task_type
96
+
97
+ return EnvState(
98
+ episode_id=self.episode_id,
99
+ current_task_id=self._current_task_id,
100
+ current_task_type=current_type,
101
+ status=status,
102
+ total_steps=self.total_steps,
103
+ last_reward=self._last_reward,
104
+ history=self._history[-20:],
105
+ )
app/grader.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ from app.models import GradeResult, TaskDefinition
4
+
5
+
6
+ _IRRELEVANT_MARKERS = {
7
+ "weather",
8
+ "recipe",
9
+ "movie",
10
+ "travel",
11
+ "football",
12
+ "politics",
13
+ }
14
+
15
+
16
+ def _normalize(text: str) -> str:
17
+ return " ".join(re.findall(r"[a-z0-9_+.#-]+", text.lower()))
18
+
19
+
20
+ def _contains_phrase(text: str, phrase: str) -> bool:
21
+ return phrase.lower() in text
22
+
23
+
24
+ def grade_review(task: TaskDefinition, review: str) -> GradeResult:
25
+ normalized_review = _normalize(review)
26
+
27
+ matched_criteria: list[str] = []
28
+ missed_criteria: list[str] = []
29
+
30
+ for criterion_group in task.criteria:
31
+ matched = any(_contains_phrase(normalized_review, _normalize(phrase)) for phrase in criterion_group)
32
+ canonical = criterion_group[0]
33
+ if matched:
34
+ matched_criteria.append(canonical)
35
+ else:
36
+ missed_criteria.append(canonical)
37
+
38
+ coverage_score = len(matched_criteria) / len(task.criteria)
39
+
40
+ penalties: dict[str, float] = {}
41
+
42
+ if len(review.split()) < 12:
43
+ penalties["too_short"] = 0.15
44
+
45
+ if len(matched_criteria) == 0:
46
+ penalties["no_relevant_content"] = 0.35
47
+
48
+ if re.search(r"\b(no issues|looks good|perfect as is)\b", review.lower()):
49
+ penalties["incorrect_no_issues_claim"] = 0.30
50
+
51
+ irrelevant_hits = sum(1 for marker in _IRRELEVANT_MARKERS if marker in normalized_review)
52
+ if irrelevant_hits >= 2:
53
+ penalties["irrelevant_content"] = min(0.10 * irrelevant_hits, 0.30)
54
+
55
+ if task.id == "hard" and not re.search(r"\b(score|rating|overall)\b", review.lower()):
56
+ penalties["missing_overall_score"] = 0.10
57
+
58
+ total_penalty = sum(penalties.values())
59
+ final_score = max(0.0, min(1.0, coverage_score - total_penalty))
60
+
61
+ rationale = (
62
+ f"Coverage={coverage_score:.2f}; Penalty={total_penalty:.2f}; "
63
+ f"Matched={len(matched_criteria)}/{len(task.criteria)}"
64
+ )
65
+
66
+ return GradeResult(
67
+ score=round(final_score, 4),
68
+ matched_criteria=matched_criteria,
69
+ missed_criteria=missed_criteria,
70
+ penalties=penalties,
71
+ rationale=rationale,
72
+ )
app/inference.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dataclasses import dataclass
3
+
4
+ import requests
5
+ from openai import OpenAI
6
+
7
+
8
+ @dataclass
9
+ class BaselineResult:
10
+ task_id: str
11
+ score: float
12
+ rationale: str
13
+
14
+
15
+ def _build_prompt(task_id: str, instructions: str, code: str) -> str:
16
+ return (
17
+ "You are a code reviewer. Complete exactly the requested review task.\n"
18
+ f"Task ID: {task_id}\n"
19
+ f"Instructions: {instructions}\n"
20
+ "Code:\n"
21
+ f"{code}\n\n"
22
+ "Return concise, actionable review feedback."
23
+ )
24
+
25
+
26
+ def _run_task(
27
+ env_base_url: str,
28
+ client: OpenAI,
29
+ model_name: str,
30
+ task_id: str,
31
+ ) -> BaselineResult:
32
+ reset_response = requests.post(
33
+ f"{env_base_url}/reset",
34
+ json={"task_id": task_id, "seed": 42},
35
+ timeout=30,
36
+ )
37
+ reset_response.raise_for_status()
38
+ reset_payload = reset_response.json()
39
+
40
+ observation = reset_payload["observation"]
41
+ prompt = _build_prompt(
42
+ task_id=observation["task_id"],
43
+ instructions=observation["instructions"],
44
+ code=observation["code"],
45
+ )
46
+
47
+ completion = client.chat.completions.create(
48
+ model=model_name,
49
+ temperature=0,
50
+ seed=42,
51
+ messages=[
52
+ {
53
+ "role": "system",
54
+ "content": "You are an expert software engineer specializing in code review.",
55
+ },
56
+ {"role": "user", "content": prompt},
57
+ ],
58
+ )
59
+
60
+ review = completion.choices[0].message.content or ""
61
+
62
+ step_response = requests.post(
63
+ f"{env_base_url}/step",
64
+ json={"action": {"review": review}},
65
+ timeout=30,
66
+ )
67
+ step_response.raise_for_status()
68
+ step_payload = step_response.json()
69
+
70
+ return BaselineResult(
71
+ task_id=task_id,
72
+ score=float(step_payload["reward"]["score"]),
73
+ rationale=step_payload["reward"]["rationale"],
74
+ )
75
+
76
+
77
+ def main() -> None:
78
+ env_base_url = os.getenv("ENV_BASE_URL", "http://localhost:8000")
79
+ api_base_url = os.getenv("API_BASE_URL", "https://api.openai.com/v1")
80
+ model_name = os.getenv("MODEL_NAME", "gpt-4o-mini")
81
+ api_key = os.getenv("OPENAI_API_KEY")
82
+
83
+ if not api_key:
84
+ raise RuntimeError("OPENAI_API_KEY must be set to run inference.py")
85
+
86
+ client = OpenAI(base_url=api_base_url, api_key=api_key)
87
+
88
+ task_ids = ["easy", "medium", "hard"]
89
+ results = [_run_task(env_base_url, client, model_name, task_id) for task_id in task_ids]
90
+
91
+ print("Synapse Code Auditor baseline run")
92
+ print(f"Environment URL: {env_base_url}")
93
+ print(f"Model endpoint: {api_base_url}")
94
+ print(f"Model: {model_name}")
95
+
96
+ total = 0.0
97
+ for result in results:
98
+ total += result.score
99
+ print(f"- {result.task_id}: score={result.score:.4f} | {result.rationale}")
100
+
101
+ avg_score = total / len(results)
102
+ print(f"Average score: {avg_score:.4f}")
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()
app/main.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+
3
+ from app.env import AICodeReviewEnvironment
4
+ from app.models import ResetRequest, ResetResponse, StateResponse, StepRequest, StepResult
5
+
6
+ app = FastAPI(
7
+ title="Synapse Code Auditor",
8
+ description="OpenEnv-compatible environment for deterministic AI code review evaluation.",
9
+ version="1.0.0",
10
+ )
11
+
12
+ env = AICodeReviewEnvironment()
13
+
14
+
15
+ @app.get("/health")
16
+ def health() -> dict[str, str]:
17
+ return {"status": "healthy", "service": "synapse-code-auditor"}
18
+
19
+
20
+ @app.post("/reset", response_model=ResetResponse)
21
+ def reset(request: ResetRequest) -> ResetResponse:
22
+ try:
23
+ observation = env.reset(task_id=request.task_id, seed=request.seed)
24
+ except KeyError as exc:
25
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
26
+
27
+ return ResetResponse(observation=observation, state=env.state())
28
+
29
+
30
+ @app.post("/step", response_model=StepResult)
31
+ def step(request: StepRequest) -> StepResult:
32
+ try:
33
+ return env.step(request.action)
34
+ except ValueError as exc:
35
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
36
+
37
+
38
+ @app.get("/state", response_model=StateResponse)
39
+ def state() -> StateResponse:
40
+ return StateResponse(state=env.state())
app/models.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+ from typing import Any
3
+
4
+ from pydantic import BaseModel, Field
5
+
6
+
7
+ class TaskType(str, Enum):
8
+ EASY = "easy"
9
+ MEDIUM = "medium"
10
+ HARD = "hard"
11
+
12
+
13
+ class Observation(BaseModel):
14
+ task_id: str
15
+ task_type: TaskType
16
+ code: str
17
+ instructions: str
18
+ previous_feedback: str | None = None
19
+
20
+
21
+ class Action(BaseModel):
22
+ review: str = Field(min_length=1)
23
+
24
+
25
+ class Reward(BaseModel):
26
+ score: float = Field(ge=0.0, le=1.0)
27
+ matched_criteria: list[str]
28
+ missed_criteria: list[str]
29
+ penalties: dict[str, float]
30
+ rationale: str
31
+
32
+
33
+ class StepResult(BaseModel):
34
+ observation: Observation
35
+ reward: Reward
36
+ done: bool
37
+ info: dict[str, Any]
38
+
39
+
40
+ class EnvState(BaseModel):
41
+ episode_id: int
42
+ current_task_id: str | None
43
+ current_task_type: TaskType | None
44
+ status: str
45
+ total_steps: int
46
+ last_reward: float | None
47
+ history: list[dict[str, Any]]
48
+
49
+
50
+ class ResetRequest(BaseModel):
51
+ task_id: str | None = Field(default=None, description="Task id: easy, medium, hard")
52
+ seed: int = 42
53
+
54
+
55
+ class StepRequest(BaseModel):
56
+ action: Action
57
+
58
+
59
+ class StateResponse(BaseModel):
60
+ state: EnvState
61
+
62
+
63
+ class ResetResponse(BaseModel):
64
+ observation: Observation
65
+ state: EnvState
66
+
67
+
68
+ class TaskDefinition(BaseModel):
69
+ id: str
70
+ task_type: TaskType
71
+ title: str
72
+ code: str
73
+ instructions: str
74
+ criteria: list[list[str]]
75
+
76
+
77
+ class GradeResult(BaseModel):
78
+ score: float
79
+ matched_criteria: list[str]
80
+ missed_criteria: list[str]
81
+ penalties: dict[str, float]
82
+ rationale: str
app/tasks.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.models import TaskDefinition, TaskType
2
+
3
+
4
+ TASKS: dict[str, TaskDefinition] = {
5
+ "easy": TaskDefinition(
6
+ id="easy",
7
+ task_type=TaskType.EASY,
8
+ title="Detect syntax errors",
9
+ code=(
10
+ "def add_numbers(a, b)\n"
11
+ " result = a + b\n"
12
+ " return result\n"
13
+ ),
14
+ instructions=(
15
+ "Identify the exact syntax error in the code and propose a valid fix. "
16
+ "The response should mention the specific line-level issue and corrected syntax."
17
+ ),
18
+ criteria=[
19
+ ["syntax error", "invalid syntax"],
20
+ ["missing colon", "colon after function definition", "def line needs colon"],
21
+ ["def add_numbers(a, b):", "add a colon at end of function definition"],
22
+ ],
23
+ ),
24
+ "medium": TaskDefinition(
25
+ id="medium",
26
+ task_type=TaskType.MEDIUM,
27
+ title="Suggest optimization",
28
+ code=(
29
+ "def squared_evens(numbers):\n"
30
+ " result = []\n"
31
+ " for n in numbers:\n"
32
+ " if n % 2 == 0:\n"
33
+ " result.append(n * n)\n"
34
+ " return result\n"
35
+ ),
36
+ instructions=(
37
+ "Suggest performance or readability optimizations while preserving behavior. "
38
+ "Mention at least one concrete optimization strategy and why it helps."
39
+ ),
40
+ criteria=[
41
+ ["list comprehension", "comprehension"],
42
+ ["same behavior", "preserve behavior", "without changing output"],
43
+ ["readability", "cleaner", "more concise"],
44
+ ],
45
+ ),
46
+ "hard": TaskDefinition(
47
+ id="hard",
48
+ task_type=TaskType.HARD,
49
+ title="Full code review with scoring",
50
+ code=(
51
+ "def average(values):\n"
52
+ " total = 0\n"
53
+ " for i in range(len(values)):\n"
54
+ " total += values[i]\n"
55
+ " return total / len(values)\n\n"
56
+ "def process(data):\n"
57
+ " try:\n"
58
+ " return [average(x) for x in data]\n"
59
+ " except Exception:\n"
60
+ " return []\n"
61
+ ),
62
+ instructions=(
63
+ "Perform a full code review covering correctness, robustness, efficiency, and maintainability. "
64
+ "Include an explicit overall score in the review."
65
+ ),
66
+ criteria=[
67
+ ["division by zero", "empty list", "len(values) == 0"],
68
+ ["broad exception", "except Exception", "too broad catch"],
69
+ ["iterate directly", "avoid range(len", "pythonic loop"],
70
+ ["type hints", "docstring", "tests"],
71
+ ["overall score", "score", "rating"],
72
+ ],
73
+ ),
74
+ }
75
+
76
+
77
+ ORDERED_TASK_IDS: list[str] = ["easy", "medium", "hard"]
78
+
79
+
80
+ def get_task(task_id: str) -> TaskDefinition:
81
+ if task_id not in TASKS:
82
+ raise KeyError(f"Unknown task_id: {task_id}")
83
+ return TASKS[task_id]
openenv.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: synapse_code_auditor
3
+ type: space
4
+ runtime: fastapi
5
+ app: app.main:app
6
+ port: 8000
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi==0.115.12
2
+ uvicorn[standard]==0.34.0
3
+ pydantic==2.11.3
4
+ openai==1.75.0
5
+ requests==2.32.3
6
+ openenv-core==0.2.3