vinith17 commited on
Commit
56f6a4d
·
1 Parent(s): 8b06b9c

Enable RL training endpoint for Hugging Face Spaces (FastAPI)

Browse files
.vibecheck/provenance/attestations.db CHANGED
Binary files a/.vibecheck/provenance/attestations.db and b/.vibecheck/provenance/attestations.db differ
 
.vibecheck/provenance/edits.jsonl CHANGED
@@ -28,3 +28,4 @@
28
  {"id":"prov-1775452366900-bw6lko-3","file":"..\\..\\.gemini\\antigravity\\brain\\9577d03e-d4d3-4d83-bfc8-bdca02191350\\browser\\scratchpad_n1ok2enr.md","startLine":7,"endLine":24,"timestamp":"2026-04-06T06:37:26.025Z","editSource":"ai-completion","linesAdded":17,"linesRemoved":17,"charsInserted":1288,"editVelocity":0,"aiTool":"none","aiModel":"unknown","confidence":50,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"680afee1f9a8fde2","preview":"- [x] 5. Upload / Paste Code Feature\\n- [x] 6. Auto-Run Feature\\n- [ ] 7. Stats / History (http://localhost:5000/api/history)\\n- [ ] 8. API Comparison (http://localhost:5000/api/comparison)\\n\\n## Findings\\n"}
29
  {"id":"prov-1775597065328-d59yla-1","file":"main.py","startLine":8,"endLine":9,"timestamp":"2026-04-08T11:14:38.761Z","editSource":"human-typing","linesAdded":1,"linesRemoved":1,"charsInserted":32,"editVelocity":0,"aiTool":"none","aiModel":"human","confidence":85,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"0f547befe2909c85","preview":" env_cls=CodeBugEnvironment,\\n"}
30
  {"id":"prov-1775597065328-d59yla-2","file":"main.py","startLine":8,"endLine":12,"timestamp":"2026-04-08T11:16:01.548Z","editSource":"ai-completion","linesAdded":4,"linesRemoved":4,"charsInserted":93,"editVelocity":0,"aiTool":"none","aiModel":"unknown","confidence":50,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"6be0fb36841e90c0","preview":" CodeBugEnvironment,\\n CodeReviewAction,\\n CodeReviewObservation,\\n CodeReviewState\\n"}
 
 
28
  {"id":"prov-1775452366900-bw6lko-3","file":"..\\..\\.gemini\\antigravity\\brain\\9577d03e-d4d3-4d83-bfc8-bdca02191350\\browser\\scratchpad_n1ok2enr.md","startLine":7,"endLine":24,"timestamp":"2026-04-06T06:37:26.025Z","editSource":"ai-completion","linesAdded":17,"linesRemoved":17,"charsInserted":1288,"editVelocity":0,"aiTool":"none","aiModel":"unknown","confidence":50,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"680afee1f9a8fde2","preview":"- [x] 5. Upload / Paste Code Feature\\n- [x] 6. Auto-Run Feature\\n- [ ] 7. Stats / History (http://localhost:5000/api/history)\\n- [ ] 8. API Comparison (http://localhost:5000/api/comparison)\\n\\n## Findings\\n"}
29
  {"id":"prov-1775597065328-d59yla-1","file":"main.py","startLine":8,"endLine":9,"timestamp":"2026-04-08T11:14:38.761Z","editSource":"human-typing","linesAdded":1,"linesRemoved":1,"charsInserted":32,"editVelocity":0,"aiTool":"none","aiModel":"human","confidence":85,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"0f547befe2909c85","preview":" env_cls=CodeBugEnvironment,\\n"}
30
  {"id":"prov-1775597065328-d59yla-2","file":"main.py","startLine":8,"endLine":12,"timestamp":"2026-04-08T11:16:01.548Z","editSource":"ai-completion","linesAdded":4,"linesRemoved":4,"charsInserted":93,"editVelocity":0,"aiTool":"none","aiModel":"unknown","confidence":50,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"6be0fb36841e90c0","preview":" CodeBugEnvironment,\\n CodeReviewAction,\\n CodeReviewObservation,\\n CodeReviewState\\n"}
31
+ {"id":"prov-1775597065328-d59yla-3","file":"frontend\\codebug (1).html","startLine":547,"endLine":862,"timestamp":"2026-04-08T14:21:06.864Z","editSource":"ai-completion","linesAdded":315,"linesRemoved":302,"charsInserted":14256,"editVelocity":0,"aiTool":"none","aiModel":"unknown","confidence":50,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"b681b8ee26679d7f","preview":" <div id=\"bugNav\" style=\"display:none; margin-bottom:16px;\"></div>\\n <div id=\"bugList\"></div>\\n </div>\\n </div>\\n </div>\\n </div>\\n </div>\\n</section>\\n\\n<!-- ── "}
agent.py CHANGED
@@ -1,58 +1,6 @@
1
- """
2
- agent.py — LLM-powered code reviewer with structured JSON output.
3
-
4
- Key improvements:
5
- - API key validated at import time with a clear startup message
6
- - Exceptions are logged (never silently swallowed)
7
- - System prompt carries persona + schema; user turn carries only the code
8
- - Two few-shot examples are included for reliable JSON compliance
9
- - One automatic retry when the first response is malformed JSON
10
- - Model / token constants come from config.py
11
- """
12
-
13
- import json
14
- import logging
15
- import os
16
- import re
17
- import sys
18
-
19
- from config import (
20
- ANTHROPIC_MODEL,
21
- OPENAI_MODEL,
22
- MAX_TOKENS,
23
- )
24
-
25
- # ---------------------------------------------------------------------------
26
- # Logging
27
- # ---------------------------------------------------------------------------
28
-
29
- logging.basicConfig(
30
- level=logging.INFO,
31
- format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
32
- )
33
- logger = logging.getLogger(__name__)
34
-
35
- # ---------------------------------------------------------------------------
36
- # Startup: API-key validation
37
- # ---------------------------------------------------------------------------
38
-
39
- def _check_api_keys() -> None:
40
- """
41
- Called once at module load. Exits with a clear message if no usable
42
- API key is present, rather than letting the server start and then die
43
- mid-request with a cryptic SDK error.
44
- """
45
- try:
46
- from dotenv import load_dotenv
47
- load_dotenv()
48
- except ImportError:
49
- pass
50
 
51
- has_anthropic = bool(os.environ.get("ANTHROPIC_API_KEY", "").strip())
52
- has_openai = bool(os.environ.get("OPENAI_API_KEY", "").strip())
53
-
54
- if not has_anthropic and not has_openai:
55
- print(
56
  "\n"
57
  "╔══════════════════════════════════════════════════════════╗\n"
58
  "║ WARNING: No LLM API key found. ║\n"
@@ -226,59 +174,78 @@ def _parse_json(raw: str) -> dict | None:
226
  # Mock reviewer (last-resort fallback)
227
  # ---------------------------------------------------------------------------
228
 
229
- def mock_review(code: str) -> dict:
 
230
  """
231
  Rule-based fallback used only when both LLM providers are unavailable.
232
- Checks for well-known patterns; deliberately conservative to avoid
233
- false confidence.
234
  """
235
  code_lower = code.lower()
 
236
 
237
- if "hashed = password" in code_lower or (
238
- "password" in code_lower and "hash" not in code_lower and "bcrypt" not in code_lower
239
- ):
240
- return {
241
- "type": "flag",
242
  "category": "security",
243
- "line_hint": "password assignment line",
244
- "comment": "Password assigned without hashing — plain-text storage vulnerability.",
245
  "severity": 5,
246
- }
 
 
 
 
247
 
248
- if 'f"select' in code_lower or "f'select" in code_lower:
249
- return {
250
- "type": "flag",
 
 
 
251
  "category": "security",
252
- "line_hint": "database query line",
253
- "comment": "Vulnerable SQL query: f-string interpolation allows SQL injection.",
254
  "severity": 5,
255
- }
256
-
257
- if "range(len(" in code_lower:
258
- return {
259
- "type": "flag",
 
 
 
 
 
260
  "category": "logic",
261
- "line_hint": "loop range call",
262
- "comment": "range(len(x)) pattern detected — verify for off-by-one errors.",
263
  "severity": 3,
264
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
 
 
266
  if ("> amount" in code_lower or "< amount" in code_lower) and ">=" not in code_lower and "<=" not in code_lower:
267
- return {
268
- "type": "flag",
269
  "category": "logic",
270
- "line_hint": "comparison check",
271
- "comment": "Strict > / < in balance check; may miss the equality edge case.",
272
  "severity": 4,
273
- }
 
 
 
 
274
 
275
- return {
276
- "type": "approve",
277
- "category": "ok",
278
- "line_hint": "",
279
- "comment": "",
280
- "severity": 0,
281
- }
282
 
283
 
284
  # ---------------------------------------------------------------------------
@@ -289,7 +256,7 @@ _REQUIRED_KEYS = {"type", "category", "line_hint", "comment", "severity"}
289
  _DEFAULTS = {"type": "approve", "category": "ok", "line_hint": "", "comment": "", "severity": 0}
290
 
291
 
292
- def review(code: str) -> dict:
293
  """
294
  Review a code snippet.
295
 
@@ -297,26 +264,28 @@ def review(code: str) -> dict:
297
  1. Call LLM with system prompt + user message.
298
  2. If JSON is malformed, retry once with an explicit correction hint.
299
  3. If both attempts fail, fall back to the rule-based mock reviewer.
300
- 4. Fill any missing keys with safe defaults.
 
301
  """
302
  user_msg = build_user_message(code)
303
  raw = call_llm(user_msg, system=_SYSTEM_PROMPT)
304
  result = _parse_json(raw)
305
 
306
- if result is None:
307
  # One retry: tell the model its output was invalid
308
- logger.warning("LLM returned malformed JSON — retrying with correction hint.")
309
  user_msg_retry = build_user_message(code, retry=True)
310
  raw_retry = call_llm(user_msg_retry, system=_SYSTEM_PROMPT)
311
  result = _parse_json(raw_retry)
312
 
313
- if result is None:
314
  logger.warning("Retry also failed — using mock reviewer.")
315
  result = mock_review(code)
316
 
317
- # Fill missing keys with safe defaults
318
- for key, val in _DEFAULTS.items():
319
- result.setdefault(key, val)
 
320
 
321
  return result
322
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ _SYSTEM_PROMPT = """\
3
+ You are an expert security-focused code reviewer.\n\nYour ONLY job is to return a single valid JSON array of bug objects (not markdown, not prose).\n\nJSON array schema (all fields required in each object):\n{\n "type": "bug",\n "category": "security" | "logic" | "style",\n "severity": 1-5,\n "comment": "<brief description of the issue>",\n "fix": "<how to fix it>",\n "confidence": 0.75-0.99,\n "line_hint": "<which line has the issue>"\n}\n\nIf the code is clean, return: []\n\n--- FEW-SHOT EXAMPLES ---\n\nExample 1 — SQL injection and hardcoded password:\nCode:\n def get_user(uid):\n q = f\"SELECT * FROM users WHERE id={uid}\"\n cursor.execute(q)\n password = 'hunter2'\n\nResponse:\n[\n {\n "type": "bug",\n "category": "security",\n "severity": 5,\n "comment": "SQL injection: f-string with variable interpolation in SQL query.",\n "fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",\n "confidence": 0.95,\n "line_hint": "2"\n },\n {\n "type": "bug",\n "category": "security",\n "severity": 5,\n "comment": "Hardcoded password/credential detected.",\n "fix": "Use environment variables: os.getenv('DB_PASSWORD')",\n "confidence": 0.98,\n "line_hint": "4"\n }\n]\n\nExample 2 — clean code:\nCode:\n def add(a: int, b: int) -> int:\n return a + b\n\nResponse:\n[]\n\nExample 3 — off-by-one and division by zero:\nCode:\n for i in range(len(items) - 1):\n process(items[i])\n x = 1 / 0\n\nResponse:\n[\n {\n "type": "bug",\n "category": "logic",\n "severity": 3,\n "comment": "Off-by-one error: range(len(x)-1) skips the last element.",\n "fix": "Use range(len(arr)) or check bounds: if i+1 < len(arr)",\n "confidence": 0.85,\n "line_hint": "1"\n },\n {\n "type": "bug",\n "category": "logic",\n "severity": 3,\n "comment": "Potential division by zero. Check denominator is non-zero.",\n "fix": "Add check: if denominator != 0: result = numerator / denominator",\n "confidence": 0.99,\n "line_hint": "3"\n }\n]\n\n--- END EXAMPLES ---\n\nALWAYS look for:\nSECURITY (severity 4-5):\n - SQL built with f-strings / concatenation\n - Passwords stored/passed without hashing\n - Hardcoded secrets, API keys, or tokens\nLOGIC (severity 2-4):\n - range(len(x) - 1) off-by-one\n - Strict > / < where >= / <= is needed\n - Division without zero-check\n - Missing return in all code paths\n\nIMPORTANT: Return ONLY the JSON array, nothing else.\n"""
 
 
 
4
  "\n"
5
  "╔══════════════════════════════════════════════════════════╗\n"
6
  "║ WARNING: No LLM API key found. ║\n"
 
174
  # Mock reviewer (last-resort fallback)
175
  # ---------------------------------------------------------------------------
176
 
177
+
178
+ def mock_review(code: str) -> list:
179
  """
180
  Rule-based fallback used only when both LLM providers are unavailable.
181
+ Returns a list of bug objects (same schema as LLM output).
 
182
  """
183
  code_lower = code.lower()
184
+ bugs = []
185
 
186
+ # SQL injection
187
+ if 'f"select' in code_lower or "f'select" in code_lower:
188
+ bugs.append({
189
+ "type": "bug",
 
190
  "category": "security",
 
 
191
  "severity": 5,
192
+ "comment": "SQL injection: f-string with variable interpolation in SQL query.",
193
+ "fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
194
+ "confidence": 0.95,
195
+ "line_hint": "database query line"
196
+ })
197
 
198
+ # Hardcoded password
199
+ if "hashed = password" in code_lower or (
200
+ "password" in code_lower and "hash" not in code_lower and "bcrypt" not in code_lower
201
+ ):
202
+ bugs.append({
203
+ "type": "bug",
204
  "category": "security",
 
 
205
  "severity": 5,
206
+ "comment": "Hardcoded password/credential detected.",
207
+ "fix": "Use environment variables: os.getenv('DB_PASSWORD')",
208
+ "confidence": 0.98,
209
+ "line_hint": "password assignment line"
210
+ })
211
+
212
+ # Off-by-one
213
+ if "range(len(" in code_lower and "- 1" in code_lower:
214
+ bugs.append({
215
+ "type": "bug",
216
  "category": "logic",
 
 
217
  "severity": 3,
218
+ "comment": "Off-by-one error: range(len(x)-1) skips the last element.",
219
+ "fix": "Use range(len(arr)) or check bounds: if i+1 < len(arr)",
220
+ "confidence": 0.85,
221
+ "line_hint": "loop range call"
222
+ })
223
+
224
+ # Division by zero
225
+ if "/ 0" in code_lower:
226
+ bugs.append({
227
+ "type": "bug",
228
+ "category": "logic",
229
+ "severity": 3,
230
+ "comment": "Potential division by zero. Check denominator is non-zero.",
231
+ "fix": "Add check: if denominator != 0: result = numerator / denominator",
232
+ "confidence": 0.99,
233
+ "line_hint": "division line"
234
+ })
235
 
236
+ # Strict comparison
237
  if ("> amount" in code_lower or "< amount" in code_lower) and ">=" not in code_lower and "<=" not in code_lower:
238
+ bugs.append({
239
+ "type": "bug",
240
  "category": "logic",
 
 
241
  "severity": 4,
242
+ "comment": "Strict > / < in balance check; may miss the equality edge case.",
243
+ "fix": "Use >= or <= to include equality edge case.",
244
+ "confidence": 0.8,
245
+ "line_hint": "comparison check"
246
+ })
247
 
248
+ return bugs
 
 
 
 
 
 
249
 
250
 
251
  # ---------------------------------------------------------------------------
 
256
  _DEFAULTS = {"type": "approve", "category": "ok", "line_hint": "", "comment": "", "severity": 0}
257
 
258
 
259
+ def review(code: str) -> list:
260
  """
261
  Review a code snippet.
262
 
 
264
  1. Call LLM with system prompt + user message.
265
  2. If JSON is malformed, retry once with an explicit correction hint.
266
  3. If both attempts fail, fall back to the rule-based mock reviewer.
267
+ 4. Fill any missing keys in each bug with safe defaults.
268
+ Returns a list of bug objects (empty if code is clean).
269
  """
270
  user_msg = build_user_message(code)
271
  raw = call_llm(user_msg, system=_SYSTEM_PROMPT)
272
  result = _parse_json(raw)
273
 
274
+ if result is None or not isinstance(result, list):
275
  # One retry: tell the model its output was invalid
276
+ logger.warning("LLM returned malformed JSON or not a list — retrying with correction hint.")
277
  user_msg_retry = build_user_message(code, retry=True)
278
  raw_retry = call_llm(user_msg_retry, system=_SYSTEM_PROMPT)
279
  result = _parse_json(raw_retry)
280
 
281
+ if result is None or not isinstance(result, list):
282
  logger.warning("Retry also failed — using mock reviewer.")
283
  result = mock_review(code)
284
 
285
+ # Fill missing keys in each bug with safe defaults
286
+ for bug in result:
287
+ for key, val in _DEFAULTS.items():
288
+ bug.setdefault(key, val)
289
 
290
  return result
291
 
flask_app.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from training_loop import run_training
3
+
4
+ app = Flask(__name__)
5
+
6
+ @app.route('/train', methods=['POST'])
7
+ def train():
8
+ try:
9
+ episodes = int(request.json.get('episodes', 5))
10
+ except Exception:
11
+ episodes = 5
12
+ stats = run_training(num_episodes=episodes, verbose=False)
13
+ return jsonify({"status": "ok", "stats": stats})
14
+
15
+ if __name__ == '__main__':
16
+ app.run(host='0.0.0.0', port=5000)
frontend/codebug (1).html CHANGED
@@ -544,27 +544,8 @@ def get_user(uid):
544
  <span class="spinner-lbl">Calling Claude API…</span>
545
  </div>
546
  <div class="r-card" id="rCard">
547
- <div id="rBadge" class="r-badge"></div>
548
- <div class="r-field">
549
- <div class="r-field-label">Category</div>
550
- <div class="r-field-value" id="rCat">—</div>
551
- </div>
552
- <div class="r-field">
553
- <div class="r-field-label">Severity</div>
554
- <div class="sev-dots" id="rSev"></div>
555
- </div>
556
- <div class="r-field">
557
- <div class="r-field-label">Line Hint</div>
558
- <div class="r-field-value" id="rLine">—</div>
559
- </div>
560
- <div class="r-field">
561
- <div class="r-field-label">Comment</div>
562
- <div class="r-field-value" id="rComment">—</div>
563
- </div>
564
- <div class="r-field">
565
- <div class="r-field-label">Suggested Fix</div>
566
- <pre class="r-fix" id="rFix"></pre>
567
- </div>
568
  </div>
569
  </div>
570
  </div>
@@ -823,31 +804,63 @@ function mockReview(code) {
823
  comment:'No obvious bugs detected. Code looks clean.', fix:'' };
824
  }
825
 
826
- function renderResult(d) {
827
- const badgeCls = d.category === 'security' ? 'sec'
828
- : d.category === 'logic' ? 'lgc'
829
- : d.type === 'approve' ? 'apr' : 'sty';
830
- const badge = document.getElementById('rBadge');
831
- badge.className = 'r-badge ' + badgeCls;
832
- badge.textContent = d.type === 'approve' ? '✓ Approved' : '⚠ ' + (d.category || d.type);
833
-
834
- document.getElementById('rCat').textContent = d.category || d.type || '—';
835
- document.getElementById('rLine').textContent = d.line_hint ? 'Line ' + d.line_hint : 'Not specified';
836
- document.getElementById('rComment').textContent = d.comment || '—';
837
- document.getElementById('rFix').textContent = d.fix || (d.type === 'approve' ? '(no fix required)' : '—');
838
-
839
- const dotsEl = document.getElementById('rSev');
840
- dotsEl.innerHTML = '';
841
- for (let i = 1; i <= 5; i++) {
842
- const dot = document.createElement('div');
843
- dot.className = 'sd' + (i <= (d.severity || 0) ? ' on' : '');
844
- dotsEl.appendChild(dot);
845
  }
846
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
847
  document.getElementById('rTs').textContent = new Date().toLocaleTimeString();
848
  document.getElementById('rCard').classList.add('on');
849
  }
850
 
 
 
 
 
 
 
 
 
851
  function showFlash(msg) {
852
  const el = document.getElementById('rEmpty');
853
  el.style.display = 'flex';
 
544
  <span class="spinner-lbl">Calling Claude API…</span>
545
  </div>
546
  <div class="r-card" id="rCard">
547
+ <div id="bugNav" style="display:none; margin-bottom:16px;"></div>
548
+ <div id="bugList"></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549
  </div>
550
  </div>
551
  </div>
 
804
  comment:'No obvious bugs detected. Code looks clean.', fix:'' };
805
  }
806
 
807
+ function renderResult(data) {
808
+ // Support both old and new API (single bug or multiple bugs)
809
+ let bugs = [];
810
+ if (Array.isArray(data.bugs) && data.bugs.length > 0) {
811
+ bugs = data.bugs;
812
+ } else if (data.type || data.category) {
813
+ bugs = [data];
814
+ } else if (data.primary_bug) {
815
+ bugs = [data.primary_bug];
 
 
 
 
 
 
 
 
 
 
816
  }
817
 
818
+ const bugList = document.getElementById('bugList');
819
+ const bugNav = document.getElementById('bugNav');
820
+ bugList.innerHTML = '';
821
+ bugNav.innerHTML = '';
822
+
823
+ if (bugs.length === 0) {
824
+ bugList.innerHTML = `<div class="r-badge apr">✓ Approved</div><div class="r-field-value">No obvious bugs detected. Code looks clean.</div>`;
825
+ bugNav.style.display = 'none';
826
+ } else {
827
+ // Navigation pills for multiple bugs
828
+ if (bugs.length > 1) {
829
+ bugNav.style.display = '';
830
+ bugNav.innerHTML = bugs.map((b, i) => `<button type="button" class="bug-pill" id="bugPill${i}" style="margin-right:6px;padding:4px 10px;border-radius:2px;border:none;background:#222;color:#fff;font-family:var(--mono);font-size:.7rem;cursor:pointer;opacity:${i===0?1:0.6}" onclick="showBug(${i}, this)">Bug ${i+1}</button>`).join('');
831
+ } else {
832
+ bugNav.style.display = 'none';
833
+ }
834
+ // Render all bugs, but only first is visible by default
835
+ bugs.forEach((bug, i) => {
836
+ const badgeCls = bug.category === 'security' ? 'sec'
837
+ : bug.category === 'logic' ? 'lgc'
838
+ : bug.type === 'approve' ? 'apr' : 'sty';
839
+ const sevDots = Array.from({length:5}, (_,j) => `<div class="sd${j < (bug.severity||0) ? ' on' : ''}"></div>`).join('');
840
+ bugList.innerHTML += `
841
+ <div class="bug-detail" id="bugDetail${i}" style="${i===0?'':'display:none;'};margin-bottom:24px;">
842
+ <div class="r-badge ${badgeCls}">${bug.type === 'approve' ? '✓ Approved' : '⚠ ' + (bug.category || bug.type)}</div>
843
+ <div class="r-field"><div class="r-field-label">Category</div><div class="r-field-value">${bug.category || bug.type || '—'}</div></div>
844
+ <div class="r-field"><div class="r-field-label">Severity</div><div class="sev-dots">${sevDots}</div></div>
845
+ <div class="r-field"><div class="r-field-label">Line Hint</div><div class="r-field-value">${bug.line_hint ? 'Line ' + bug.line_hint : 'Not specified'}</div></div>
846
+ <div class="r-field"><div class="r-field-label">Comment</div><div class="r-field-value">${bug.comment || '—'}</div></div>
847
+ <div class="r-field"><div class="r-field-label">Suggested Fix</div><pre class="r-fix">${bug.fix || (bug.type === 'approve' ? '(no fix required)' : '—')}</pre></div>
848
+ </div>
849
+ `;
850
+ });
851
+ }
852
  document.getElementById('rTs').textContent = new Date().toLocaleTimeString();
853
  document.getElementById('rCard').classList.add('on');
854
  }
855
 
856
+ // Navigation for multiple bugs
857
+ function showBug(idx, btn) {
858
+ const bugs = document.querySelectorAll('.bug-detail');
859
+ bugs.forEach((el, i) => { el.style.display = (i === idx) ? '' : 'none'; });
860
+ const pills = document.querySelectorAll('.bug-pill');
861
+ pills.forEach((el, i) => { el.style.opacity = (i === idx) ? 1 : 0.6; });
862
+ }
863
+
864
  function showFlash(msg) {
865
  const el = document.getElementById('rEmpty');
866
  el.style.display = 'flex';
main.py CHANGED
@@ -1,3 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from openenv.core.env_server import create_fastapi_app
2
  from environment import CodeBugEnvironment
3
  from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
@@ -10,8 +23,9 @@ import re
10
  import logging
11
 
12
  # Import LLM capabilities
 
13
  try:
14
- from agent import call_llm, build_user_message, _SYSTEM_PROMPT
15
  HAS_LLM = True
16
  except ImportError:
17
  HAS_LLM = False
@@ -110,79 +124,24 @@ async def review_code(request: ReviewRequest):
110
  )
111
 
112
 
 
113
  def analyze_code_with_llm(code: str, lang: str) -> list:
114
  """
115
- Use LLM (Claude/GPT) to analyze code comprehensively.
116
- Returns list of bugs with confidence scores.
117
- Falls back to pattern-based if LLM fails.
118
  """
119
  try:
120
- # Improved prompt that gets LLM to return clean JSON
121
- analysis_prompt = f"""You are an expert code security reviewer. Analyze this {lang} code for ALL bugs, vulnerabilities, and issues.
122
-
123
- CODE:
124
- {code}
125
-
126
- Return ONLY a valid JSON array (no markdown, no explanation). Each bug object must have these exact fields:
127
- - type: "bug"
128
- - category: "security" | "logic" | "style"
129
- - severity: 1-5 (1=minor, 5=critical)
130
- - comment: brief description of the issue
131
- - fix: how to fix it
132
- - confidence: 0.75-0.99
133
- - line_hint: which line has the issue
134
-
135
- If code is clean, return: []
136
-
137
- Examples of bugs to look for:
138
- - SQL injection (f-strings in queries)
139
- - Hardcoded secrets/passwords
140
- - Command injection
141
- - XSS vulnerabilities
142
- - Infinite recursion without base case
143
- - Off-by-one errors in loops
144
- - Race conditions
145
- - Mutable default arguments (Python)
146
- - Resource leaks
147
- - Exception handling issues
148
- - Type mismatches
149
-
150
- IMPORTANT: Return ONLY the JSON array, nothing else."""
151
-
152
- response = call_llm(analysis_prompt, system=_SYSTEM_PROMPT)
153
-
154
- if response:
155
- # Parse JSON response
156
- try:
157
- # Extract JSON array from response
158
- json_match = re.search(r'\[\s*(?:\{[^}]*\}[,\s]*)*\]', response, re.DOTALL)
159
- if json_match:
160
- bugs = json.loads(json_match.group())
161
-
162
- # Ensure all required fields exist
163
- for bug in bugs:
164
- if isinstance(bug, dict):
165
- bug.setdefault("type", "bug")
166
- bug.setdefault("category", "logic")
167
- bug.setdefault("severity", 3)
168
- bug.setdefault("confidence", 0.85)
169
- bug.setdefault("comment", "")
170
- bug.setdefault("fix", "")
171
- bug.setdefault("line_hint", "")
172
- bug.setdefault("languages", [lang])
173
-
174
- # Sort by severity (highest first), then by confidence
175
- bugs.sort(key=lambda x: (x.get('severity', 0), x.get('confidence', 0)), reverse=True)
176
-
177
- logger.info(f"LLM found {len(bugs)} bugs in {lang} code")
178
- return bugs
179
- except (json.JSONDecodeError, AttributeError) as e:
180
- logger.debug(f"Failed to parse LLM JSON: {e}. Response was: {response[:200]}")
181
- # Fall through to pattern-based fallback
182
-
183
- # Fallback to pattern-based if LLM response is empty or invalid
184
- return analyze_code_comprehensively(code, lang)
185
-
186
  except Exception as e:
187
  logger.warning(f"LLM analysis failed ({type(e).__name__}: {e}). Using fallback pattern-based analysis.")
188
  return analyze_code_comprehensively(code, lang)
 
1
+ from training_loop import run_training
2
+
3
+ # Endpoint to trigger RL training
4
+ from fastapi import Query
5
+
6
+ @app.post("/api/train")
7
+ async def run_real_training(episodes: int = Query(5, description="Number of training episodes to run")):
8
+ """
9
+ Run the RL training loop for the specified number of episodes.
10
+ Returns training stats and summary.
11
+ """
12
+ stats = run_training(num_episodes=episodes, verbose=False)
13
+ return {"status": "ok", "stats": stats}
14
  from openenv.core.env_server import create_fastapi_app
15
  from environment import CodeBugEnvironment
16
  from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
 
23
  import logging
24
 
25
  # Import LLM capabilities
26
+
27
  try:
28
+ from agent import review as agent_review
29
  HAS_LLM = True
30
  except ImportError:
31
  HAS_LLM = False
 
124
  )
125
 
126
 
127
+
128
  def analyze_code_with_llm(code: str, lang: str) -> list:
129
  """
130
+ Use LLM-powered agent.review() to analyze code for ALL bugs. Returns a list of bug objects. Falls back to pattern-based if LLM fails.
 
 
131
  """
132
  try:
133
+ bugs = agent_review(code)
134
+ # Optionally filter by language if needed
135
+ if not isinstance(bugs, list):
136
+ bugs = []
137
+ # Add language info if missing
138
+ for bug in bugs:
139
+ if "languages" not in bug:
140
+ bug["languages"] = [lang]
141
+ # Sort by severity (highest first), then by confidence
142
+ bugs.sort(key=lambda x: (x.get('severity', 0), x.get('confidence', 0)), reverse=True)
143
+ logger.info(f"LLM found {len(bugs)} bugs in {lang} code")
144
+ return bugs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  except Exception as e:
146
  logger.warning(f"LLM analysis failed ({type(e).__name__}: {e}). Using fallback pattern-based analysis.")
147
  return analyze_code_comprehensively(code, lang)