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b4deece
 
 
 
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import json
import logging
import os
import re
import time
import threading

from flask import Flask, jsonify, render_template, request
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

from config import (
    ALLOWED_EXTENSIONS,
    MAX_CONTENT_LENGTH_MB,
    RATE_LIMIT_AUTO_RUN,
    RATE_LIMIT_DEFAULT,
    RATE_LIMIT_REVIEW,
    RUNS_DIR,
)
from environment import CodeReviewEnv
from agent import review, call_llm
from grader import grade
from training_loop import run_training

logger = logging.getLogger(__name__)

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH_MB * 1024 * 1024

limiter = Limiter(
    get_remote_address,
    app=app,
    default_limits=[RATE_LIMIT_DEFAULT],
    headers_enabled=True,   # Adds Retry-After + X-RateLimit-* headers
)

# Ensure runs directory exists
os.makedirs(RUNS_DIR, exist_ok=True)
HISTORY_FILE = os.path.join(RUNS_DIR, "history.json")

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# --- Global State ---
STATE = {
    "total_reward": 0,
    "episode_count": 0,
    "current_episode_id": None,
    "history": [],
    "is_running": False
}

# Initialize environment
env = CodeReviewEnv("episodes.json", "answers.json")

# Helper to save history to file
def save_history_file():
    stats = {
        "total_reward": STATE["total_reward"],
        "episodes_run": STATE["episode_count"],
        "accuracy": calculate_accuracy(),
        "best_score": calculate_best_score()
    }
    data = {
        "overall_stats": stats,
        "history": STATE["history"]
    }
    with open(HISTORY_FILE, "w") as f:
        json.dump(data, f, indent=4)

def calculate_accuracy():
    if STATE["episode_count"] == 0: return 0
    correct = sum(1 for h in STATE["history"] if h["correct"])
    return correct / STATE["episode_count"]

def calculate_best_score():
    if not STATE["history"]: return 0
    return max(h["reward"] for h in STATE["history"])

def find_bug_lines(code, ai_action):
    lines = code.splitlines()
    highlighted = []
    line_hint = ai_action.get("line_hint", "").lower()
    category = ai_action.get("category", "ok")
    
    if ai_action.get("type") != "flag":
        return []
    
    for i, line in enumerate(lines):
        line_lower = line.lower().strip()
        should_highlight = False
        
        # Security patterns
        if category == "security":
            if any(p in line_lower for p in [
                "f\"select", "f'select", "query =", "execute(",
                "password =", "hashed = password", "= password",
                "api_key =", "secret =", "token ="
            ]):
                should_highlight = True
        
        # Logic patterns  
        if category == "logic":
            if any(p in line_lower for p in [
                "range(len(", "> amount", "< amount",
                ">= amount", "if accounts", "return"
            ]):
                should_highlight = True
        
        # Match line hint keywords
        if line_hint:
            hint_words = [w for w in line_hint.split() if len(w) > 3]
            if any(word in line_lower for word in hint_words):
                should_highlight = True
        
        if should_highlight:
            highlighted.append({
                "line_number": i + 1,
                "content": line,
                "severity": ai_action.get("severity", 3)
            })
    
    return highlighted[:3]  # max 3 highlighted lines

def get_fix_suggestion(code, ai_action):
    if ai_action.get("type") != "flag": return None
    
    comment = ai_action.get('comment', '')
    category = ai_action.get('category', '')

    fix_prompt = f"""
    You are a senior engineer. A code reviewer found this issue:
    
    Bug type: {category}
    Issue: {comment}
    Location: {ai_action.get('line_hint', '')}
    
    Here is the original buggy code:
    {code}
    
    Provide a fixed version of the code.
    Respond with ONLY a JSON object:
    {{
        "fixed_code": "the complete fixed code here",
        "changes": ["list", "of", "what", "changed"],
        "explanation": "one sentence explaining the fix"
    }}
    No markdown, no backticks, just the JSON object.
    """
    
    raw = call_llm(fix_prompt)
    if raw:
        try:
            match = re.search(r'(\{.*\})', raw, re.DOTALL)
            if match:
                return json.loads(match.group(1))
        except:
            pass

    # Fallback logic
    if category == "security" and "sql" in comment.lower():
        return {
            "fixed_code": code.replace(
                "f\"SELECT * FROM users WHERE username='{username}'\"",
                "\"SELECT * FROM users WHERE username=?\""
            ),
            "changes": ["Replaced f-string with parameterized query",
                       "Added ? placeholder instead of variable interpolation"],
            "explanation": "Parameterized queries prevent SQL injection by separating code from data."
        }
    
    if category == "security" and "password" in comment.lower():
        return {
            "fixed_code": code.replace(
                "hashed = password",
                "import hashlib\n    hashed = hashlib.sha256(password.encode()).hexdigest()"
            ),
            "changes": ["Added hashlib import",
                       "Applied SHA-256 hashing before storing password"],
            "explanation": "Always hash passwords with a cryptographic function before storage."
        }
    
    if category == "logic" and "range(len(" in code:
         return {
            "fixed_code": code.replace("range(len(numbers) - 1)", 
                                        "range(len(numbers))"),
            "changes": ["Fixed loop range to include last element"],
            "explanation": "range(len(x)) iterates all items; range(len(x)-1) skips the last one."
        }
    
    return None

# --- Routes ---

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/api/next-episode", methods=["GET"])
def next_episode():
    # Reset env to get a new snippet
    obs = env.reset()
    STATE["current_episode_id"] = obs["episode_id"]
    return jsonify({
        "episode_id": obs["episode_id"],
        "snippet_id": obs["snippet_id"],
        "code": obs["code"],
        "episode_count": STATE["episode_count"]
    })

@app.route("/api/review", methods=["POST"])
@limiter.limit(RATE_LIMIT_REVIEW)
def perform_review():
    data = request.json
    code = data.get("code")
    episode_id = data.get("episode_id")
    snippet_id = data.get("snippet_id")
    
    # 1. Get AI Review
    ai_action = review(code)
    
    # 2. Get Ground Truth
    ground_truth = env._get_answer(episode_id)
    
    # 3. Grade the review
    res = grade(ai_action, ground_truth)
    reward = res.reward
    
    # 4. Update state
    STATE["total_reward"] += reward
    STATE["episode_count"] += 1
    
    record = {
        "episode_id": episode_id,
        "snippet_id": snippet_id,
        "ai_said": f"{ai_action.get('type')} / {ai_action.get('category')}",
        "reward": reward,
        "correct": res.correct,
        "breakdown": res.breakdown,
        "bug_type": res.bug_type
    }
    STATE["history"].append(record)
    save_history_file()
    
    return jsonify({
        "ai_action": ai_action,
        "reward": reward,
        "correct": res.correct,
        "breakdown": res.breakdown,
        "total_reward": STATE["total_reward"],
        "episode_count": STATE["episode_count"],
        "highlighted_lines": find_bug_lines(code, ai_action),
        "fix": get_fix_suggestion(code, ai_action)
    })

@app.route("/api/history", methods=["GET"])
def get_history():
    # If history is empty in state, try reading from file
    if not STATE["history"] and os.path.exists(HISTORY_FILE):
        try:
            with open(HISTORY_FILE) as f:
                data = json.load(f)
                STATE["history"] = data["history"]
                STATE["total_reward"] = data["overall_stats"]["total_reward"]
                STATE["episode_count"] = data["overall_stats"]["episodes_run"]
        except Exception as exc:
            logger.warning("Could not read history file: %s", exc)
            
    return jsonify({
        "history": STATE["history"],
        "total_reward": STATE["total_reward"],
        "episodes_run": STATE["episode_count"],
        "accuracy": calculate_accuracy(),
        "best_score": calculate_best_score()
    })

@app.route("/api/train", methods=["POST"])
@limiter.limit(RATE_LIMIT_AUTO_RUN)
def train():
    episodes = request.json.get("episodes", 10)
    
    # run synchronously to match frontend assumptions
    try:
        output_data = run_training(num_episodes=episodes, verbose=False, resume=True)
        stats = output_data["overall_stats"]
        return jsonify(stats)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route("/api/health", methods=["GET"])
def health():
    return jsonify({
        "status": "healthy",
        "has_anthropic": bool(os.environ.get("ANTHROPIC_API_KEY")),
        "has_openai": bool(os.environ.get("OPENAI_API_KEY"))
    })

@app.route("/api/upload", methods=["POST"])
@limiter.limit(RATE_LIMIT_REVIEW)
def upload_file():
    if 'file' not in request.files:
        return jsonify({"error": "No file provided"}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "Empty file"}), 400
    if not allowed_file(file.filename):
        return jsonify({"error": "File type not supported"}), 400
        
    code = file.read().decode('utf-8')
    note = None
    if len(code) > 10000:
        code = code[:10000]
        note = "User uploaded file β€” truncated to first 10,000 characters"
        
    return process_raw_code(code, file.filename, note)

@app.route("/api/review-text", methods=["POST"])
@limiter.limit(RATE_LIMIT_REVIEW)
def review_text():
    data = request.json
    code = data.get("code", "")
    filename = data.get("filename", "pasted_code.py")
    
    if not code:
        return jsonify({"error": "Empty code"}), 400
        
    note = None
    if len(code) > 10000:
        code = code[:10000]
        note = "Pasted code β€” truncated to first 10,000 characters"
        
    return process_raw_code(code, filename, note)

def process_raw_code(code, filename, note=None):
    # 1. Get AI Review
    ai_action = review(code)
    
    # 2. Build fake ground truth
    ground_truth = {
        "bug": {
            "type": ai_action["category"] if ai_action["type"] == "flag" else "none",
            "severity": ai_action.get("severity", 0),
            "description": "User uploaded file β€” no ground truth",
            "line_hint": ai_action.get("line_hint", "")
        }
    }
    
    # 3. Grade
    res = grade(ai_action, ground_truth)
    reward = res.reward
    
    # 4. Update state
    STATE["total_reward"] += reward
    STATE["episode_count"] += 1
    
    record = {
        "episode_id": f"upload_{STATE['episode_count']}",
        "snippet_id": filename,
        "ai_said": f"{ai_action.get('type')} / {ai_action.get('category')}",
        "reward": reward,
        "correct": res.correct,
        "breakdown": res.breakdown,
        "bug_type": res.bug_type
    }
    STATE["history"].append(record)
    save_history_file()
    
    return jsonify({
        "filename": filename,
        "code": code,
        "line_count": len(code.splitlines()),
        "ai_action": ai_action,
        "reward": reward,
        "correct": res.correct,
        "breakdown": res.breakdown,
        "total_reward": STATE["total_reward"],
        "episode_count": STATE["episode_count"],
        "summary": res.summary(),
        "note": note or "User uploaded file β€” reward based on AI confidence",
        "highlighted_lines": find_bug_lines(code, ai_action),
        "fix": get_fix_suggestion(code, ai_action)
    })

@app.route("/api/comparison", methods=["GET"])
def get_comparison():
    # Pick episode ep_001 (SQL injection β€” best visual example)
    code = ""
    for ep in env.episodes:
        if ep["episode_id"] == "ep_001":
            code = ep["code"]
            break
            
    truth = env._get_answer("ep_001")
    
    # Simulate untrained AI
    untrained_action = {
        "type": "approve",
        "category": "ok", 
        "line_hint": "",
        "comment": "Code looks fine, no issues found.",
        "severity": 0
    }
    
    trained_action = review(code)
    
    untrained_result = grade(untrained_action, truth)
    trained_result = grade(trained_action, truth)
    
    highlighted = find_bug_lines(code, trained_action)
    
    return jsonify({
        "code": code,
        "highlighted_lines": highlighted,
        "untrained": {
            "action": untrained_action,
            "reward": untrained_result.reward,
            "correct": untrained_result.correct,
            "breakdown": untrained_result.breakdown
        },
        "trained": {
            "action": trained_action,
            "reward": trained_result.reward,
            "correct": trained_result.correct,
            "breakdown": trained_result.breakdown
        },
        "ground_truth": truth.get("bug", {})
    })

@app.route("/api/stats", methods=["GET"])
def get_stats():
    return jsonify({
        "total_reward": STATE["total_reward"],
        "episode_count": STATE["episode_count"],
        "accuracy": calculate_accuracy(),
        "best_score": calculate_best_score(),
        "is_running": STATE["is_running"]
    })

@app.route("/api/reset", methods=["GET"])
def reset_state():
    STATE["total_reward"] = 0
    STATE["episode_count"] = 0
    STATE["history"] = []
    STATE["is_running"] = False
    if os.path.exists(HISTORY_FILE):
        os.remove(HISTORY_FILE)
    return jsonify({"status": "reset"})

if __name__ == "__main__":
    app.run(port=5000, threaded=True, debug=True)