vinith17 commited on
Commit
22f91bc
·
1 Parent(s): f72c418

fix: openenv app IS main app so /reset /step at root — passes automated checker

Browse files
Files changed (1) hide show
  1. main.py +199 -652
main.py CHANGED
@@ -1,12 +1,13 @@
1
  """
2
- CodeBug FastAPI server — Official 30-rule bug detection engine.
3
- Rules: R-N1..R-N5 | R-C1..R-C5 | R-D1..R-D5 | R-S1..R-S5 | R-CF1..R-CF5 | R-L1..R-L5
 
4
  """
5
 
6
- from fastapi import FastAPI, Request, HTTPException
 
7
  from fastapi.responses import HTMLResponse, JSONResponse
8
  from pydantic import BaseModel
9
- import os, re, logging, traceback
10
  from openenv.core.env_server import create_fastapi_app
11
  from environment import CodeBugEnvironment
12
  from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
@@ -18,43 +19,37 @@ try:
18
  except ImportError:
19
  _AGENT_IMPORTED = False
20
 
21
- # Only attempt LLM if at least one API key is actually configured
22
  _HAS_ANTHROPIC = bool(os.environ.get("ANTHROPIC_API_KEY", "").strip())
23
  _HAS_OPENAI = bool(os.environ.get("OPENAI_API_KEY", "").strip())
24
  HAS_LLM = _AGENT_IMPORTED and (_HAS_ANTHROPIC or _HAS_OPENAI)
25
 
26
  logger = logging.getLogger(__name__)
27
 
28
- # Create the OpenEnv app
29
- openenv_app = create_fastapi_app(CodeBugEnvironment, CodeReviewAction, CodeReviewObservation)
 
30
 
31
- # Main FastAPI app
32
- app = FastAPI(title="CodeBug API", version="2.0")
33
 
34
-
35
- # ========================================================================
36
  # POST /api/train
37
- # ========================================================================
38
  class TrainRequest(BaseModel):
39
  episodes: int = 5
40
 
41
  @app.post("/api/train")
42
  async def run_real_training(body: TrainRequest):
43
- """Run the RL training loop for the specified number of episodes."""
44
  try:
45
  stats = run_training(num_episodes=body.episodes, verbose=False)
46
  return {"status": "ok", "stats": stats}
47
  except Exception as e:
48
  logger.error(f"Training failed: {e}\n{traceback.format_exc()}")
49
- return JSONResponse(
50
- status_code=500,
51
- content={"error": f"Training failed: {str(e)}", "details": traceback.format_exc()[:500]}
52
- )
53
 
54
 
55
- # ========================================================================
56
  # POST /api/review
57
- # ========================================================================
58
  class ReviewRequest(BaseModel):
59
  code: str
60
  language: str
@@ -62,35 +57,30 @@ class ReviewRequest(BaseModel):
62
 
63
  @app.post("/api/review")
64
  async def review_code(request: ReviewRequest):
65
- """Analyze code and return ALL bug findings with rule IDs and confidence scores."""
66
  try:
67
  code = request.code.strip()
68
  lang = request.language.lower().strip()
69
 
70
  if not code:
71
  raise HTTPException(status_code=400, detail="Code cannot be empty")
72
- if not lang:
73
- raise HTTPException(status_code=400, detail="Language must be specified")
74
  if len(code) > 5000:
75
  raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
76
 
77
- supported_langs = ['python', 'javascript', 'typescript', 'java', 'go', 'cpp', 'c++']
78
- if lang not in supported_langs:
79
- raise HTTPException(
80
- status_code=400,
81
- detail=f"Language '{lang}' not supported. Supported: {', '.join(supported_langs)}"
82
- )
83
 
84
- logger.info(f"Analyzing {lang} code ({len(code)} chars)...")
85
- if HAS_LLM:
86
- results = _analyze_with_llm(code, lang)
87
- else:
88
- results = analyze_code_comprehensively(code, lang)
89
 
90
  response = {
91
  "bugs_found": len(results),
92
  "bugs": results,
93
- "primary_bug": results[0] if results else None,
 
 
 
 
94
  "analysis_metadata": {
95
  "language": lang,
96
  "code_length": len(code),
@@ -101,36 +91,52 @@ async def review_code(request: ReviewRequest):
101
  ) if results else 1.0
102
  }
103
  }
104
-
105
- if not results:
106
- response["primary_bug"] = {
107
- "type": "approve",
108
- "rule_id": None,
109
- "category": "style",
110
- "severity": 1,
111
- "line_hint": None,
112
- "comment": "No bugs detected by the 30-rule engine.",
113
- "fix": "",
114
- "confidence": 1.0
115
- }
116
-
117
- logger.info(f"Found {len(results)} bugs in {lang} code")
118
  return response
119
 
120
  except HTTPException:
121
  raise
122
  except Exception as e:
123
- error_trace = traceback.format_exc()
124
- logger.error(f"Review endpoint failed: {e}\n{error_trace}")
125
- return JSONResponse(
126
- status_code=500,
127
- content={"error": f"Analysis failed: {str(e)}", "details": error_trace[:500]}
128
- )
129
 
130
 
131
- # ========================================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  # LLM wrapper
133
- # ========================================================================
134
  def _analyze_with_llm(code: str, lang: str) -> list:
135
  if not HAS_LLM:
136
  return analyze_code_comprehensively(code, lang)
@@ -141,625 +147,166 @@ def _analyze_with_llm(code: str, lang: str) -> list:
141
  bugs.sort(key=lambda x: (x.get('severity', 0), x.get('confidence', 0)), reverse=True)
142
  return bugs
143
  except Exception as e:
144
- logger.warning(f"LLM failed ({type(e).__name__}: {e}). Using pattern analysis.")
145
  return analyze_code_comprehensively(code, lang)
146
 
147
 
148
- # ========================================================================
149
  # OFFICIAL 30-RULE BUG ENGINE
150
- # Spec: R-N1..R-N5 | R-C1..R-C5 | R-D1..R-D5 | R-S1..R-S5 | R-CF1..R-CF5 | R-L1..R-L5
151
- # ========================================================================
152
 
153
  def _fl(code: str, pattern: str, flags: int = re.I) -> int | None:
154
- """Return 1-indexed line number of first regex match, or None."""
155
  for i, line in enumerate(code.splitlines(), 1):
156
  if re.search(pattern, line, flags):
157
  return i
158
  return None
159
 
160
-
161
- def _bug(rule_id: str, category: str, severity: int, line_hint, comment: str, fix: str, confidence: float) -> dict:
162
- return {
163
- "type": "bug",
164
- "rule_id": rule_id,
165
- "category": category,
166
- "severity": severity,
167
- "line_hint": line_hint,
168
- "comment": comment,
169
- "fix": fix,
170
- "confidence": confidence,
171
- }
172
-
173
 
174
  def analyze_code_comprehensively(code: str, lang: str) -> list:
175
- """
176
- Official 30-rule bug detector. Every matching rule fires independently.
177
- Multiple bugs can be returned for the same code snippet.
178
- """
179
  bugs = []
180
  IS_JS = lang in ('javascript', 'typescript')
181
  IS_PY = lang == 'python'
182
 
183
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
184
- # CATEGORY 1 — API & Network
185
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
186
-
187
- # R-N1 · Missing error handling on fetch
188
  if IS_JS and re.search(r'\bfetch\s*\(', code):
189
- has_catch = bool(re.search(r'\.catch\s*\(|try\s*\{', code))
190
- has_status = bool(re.search(r'\.ok\b|\.status\b', code))
191
- if not has_catch or not has_status:
192
- ln = _fl(code, r'\bfetch\s*\(')
193
- bugs.append(_bug(
194
- "R-N1", "api_network", 4, ln,
195
- "R-N1 · Missing error handling on fetch: fetch() does NOT throw on 4xx/5xx. "
196
- "You must check response.ok and wrap in try/catch.",
197
- "const res = await fetch(url);\n"
198
- "if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`);\n"
199
- "const data = await res.json();\n"
200
- "// Always wrap in: try { ... } catch (err) { console.error(err); }",
201
- 0.88
202
- ))
203
-
204
- # R-N2 · No timeout defined
205
- if IS_JS and re.search(r'\bfetch\s*\(', code) \
206
- and not re.search(r'AbortController|signal|timeout', code):
207
- ln = _fl(code, r'\bfetch\s*\(')
208
- bugs.append(_bug(
209
- "R-N2", "api_network", 3, ln,
210
- "R-N2 · No timeout defined: fetch() has no built-in timeout. "
211
- "A hanging request blocks indefinitely and causes silent 500s.",
212
- "const ctrl = new AbortController();\n"
213
- "const tid = setTimeout(() => ctrl.abort(), 5000);\n"
214
- "try {\n"
215
- " const res = await fetch(url, { signal: ctrl.signal });\n"
216
- "} finally { clearTimeout(tid); }",
217
- 0.85
218
- ))
219
-
220
- if IS_PY and re.search(r'requests\.(get|post|put|delete|patch)\s*\(', code) \
221
- and not re.search(r'timeout\s*=', code):
222
- ln = _fl(code, r'requests\.(get|post|put|delete|patch)\s*\(')
223
- bugs.append(_bug(
224
- "R-N2", "api_network", 3, ln,
225
- "R-N2 · No timeout on requests call: without timeout the request can hang indefinitely.",
226
- "response = requests.get(url, timeout=10) # always set timeout",
227
- 0.90
228
- ))
229
-
230
- # R-N3 · Route not registered
231
- if IS_PY and re.search(r'@app\.(get|post|put|delete|patch)', code):
232
- if not re.findall(r'@app\.(get|post|put|delete|patch)\s*\(\s*["\']([^"\']+)["\']', code):
233
- ln = _fl(code, r'@app\.')
234
- bugs.append(_bug(
235
- "R-N3", "api_network", 4, ln,
236
- "R-N3 · Route not registered: @app decorator found but route paths appear missing or malformed. "
237
- "Ensure routes are registered on the exact app instance that uvicorn serves.",
238
- "@app.post('/api/review') # route must be on the served app object\n"
239
- "async def review(body: Body): ...\n"
240
- "# Run: uvicorn main:app # 'app' must be the same object",
241
- 0.72
242
- ))
243
-
244
- # R-N4 · CORS misconfiguration
245
  if re.search(r'allow_origins\s*=\s*\[.*\*.*\]|Access-Control-Allow-Origin.*\*', code):
246
- ln = _fl(code, r'allow_origins|Access-Control-Allow-Origin')
247
- bugs.append(_bug(
248
- "R-N4", "security", 4, ln,
249
- "R-N4 · Overly permissive CORS: wildcard origin (*) on authenticated endpoints "
250
- "is both a security issue and breaks browser credential policies.",
251
- "app.add_middleware(CORSMiddleware,\n"
252
- " allow_origins=['https://yourapp.com'], # explicit, not ['*']\n"
253
- " allow_credentials=True,\n"
254
- " allow_methods=['GET', 'POST'])",
255
- 0.95
256
- ))
257
-
258
- # R-N5 · Auth token not sent
259
- if IS_JS and re.search(r'\bfetch\s*\(', code) \
260
- and not re.search(r'Authorization|Bearer|headers.*token', code, re.I):
261
- ln = _fl(code, r'\bfetch\s*\(')
262
- bugs.append(_bug(
263
- "R-N5", "security", 3, ln,
264
- "R-N5 · Auth token not sent: fetch() call appears to be missing an Authorization header.",
265
- "fetch(url, {\n"
266
- " headers: {\n"
267
- " 'Authorization': `Bearer ${token}`,\n"
268
- " 'Content-Type': 'application/json'\n"
269
- " }\n"
270
- "});",
271
- 0.70
272
- ))
273
-
274
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
275
- # CATEGORY 2 — Runtime Crashes
276
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
277
-
278
- # R-C1 · Unhandled exception in route handler
279
- if IS_PY and re.search(r'@app\.(get|post|put|delete|patch)', code) \
280
- and not re.search(r'try\s*:', code):
281
- ln = _fl(code, r'@app\.(get|post|put|delete|patch)')
282
- bugs.append(_bug(
283
- "R-C1", "runtime", 4, ln,
284
- "R-C1 · Unhandled exception in route: route handler has no try/except. "
285
- "Any uncaught exception returns a raw 500 with traceback exposed to clients.",
286
- "@app.post('/api/review')\n"
287
- "async def review(body: ReviewRequest):\n"
288
- " try:\n"
289
- " return process(body)\n"
290
- " except Exception as e:\n"
291
- " logger.error('Review failed', exc_info=True)\n"
292
- " raise HTTPException(status_code=500, detail='Internal error')",
293
- 0.85
294
- ))
295
-
296
- # R-C2 · Missing environment variable validation
297
- if IS_PY and re.search(r'os\.environ\.get\(|os\.getenv\(', code) \
298
- and not re.search(r'if not .*(key|token|secret|api)|sys\.exit|raise.*environ', code, re.I):
299
- ln = _fl(code, r'os\.environ\.get|os\.getenv')
300
- bugs.append(_bug(
301
- "R-C2", "runtime", 4, ln,
302
- "R-C2 · Missing env var validation: os.environ.get() returns None silently. "
303
- "Missing required keys will crash mid-request instead of at startup.",
304
- "REQUIRED = ['API_KEY', 'DB_URL']\n"
305
- "for key in REQUIRED:\n"
306
- " if not os.environ.get(key):\n"
307
- " import sys\n"
308
- " sys.exit(f'[FATAL] Missing env var: {key}')",
309
- 0.87
310
- ))
311
-
312
- # R-C3 · Model/resource not loaded at startup
313
- if IS_PY and re.search(r'(model|pipeline|tokenizer|engine)\s*=\s*None', code) \
314
- and not re.search(r'lifespan|on_event|startup|__init__', code, re.I):
315
- ln = _fl(code, r'(model|pipeline|tokenizer|engine)\s*=\s*None')
316
- bugs.append(_bug(
317
- "R-C3", "runtime", 4, ln,
318
- "R-C3 · Model not loaded at startup: resource initialised as None, likely loaded lazily "
319
- "inside a route — causes the first request to hang or crash.",
320
- "from contextlib import asynccontextmanager\n"
321
- "@asynccontextmanager\n"
322
- "async def lifespan(app):\n"
323
- " app.state.model = load_model() # load once at startup\n"
324
- " yield\n"
325
- "app = FastAPI(lifespan=lifespan)",
326
- 0.80
327
- ))
328
-
329
- # R-C4 · NoneType access risk
330
- if re.search(r'\.get\(|request\.|response\.', code) \
331
- and re.search(r'(\w+)\.\w+|\w+\[', code) \
332
- and not re.search(r'is not None|!= None|is None|if \w+', code):
333
- ln = _fl(code, r'\w+\.\w+')
334
- if ln:
335
- bugs.append(_bug(
336
- "R-C4", "runtime", 4, ln,
337
- "R-C4 · NoneType access risk: chained attribute or index access on a value that "
338
- "could be None — the #1 cause of 500 errors.",
339
- "# Guard before access:\n"
340
- "if value is not None:\n"
341
- " result = value.attribute\n"
342
- "# JS optional chaining:\n"
343
- "const name = user?.profile?.name ?? 'default';",
344
- 0.75
345
- ))
346
-
347
- # R-C5 · Type mismatch (no casting)
348
- if IS_PY and re.search(r'request\.(json|form|args|query_params)', code) \
349
- and not re.search(r'int\(|float\(|str\(|BaseModel|pydantic', code):
350
- ln = _fl(code, r'request\.(json|form|args|query_params)')
351
- bugs.append(_bug(
352
- "R-C5", "runtime", 3, ln,
353
- "R-C5 · Type mismatch: request parameters used without type casting or Pydantic validation. "
354
- "A string where int is expected causes a silent crash.",
355
- "class Body(BaseModel):\n"
356
- " code: str\n"
357
- " severity: int # auto-cast & validated\n"
358
- "\n"
359
- "@app.post('/api/review')\n"
360
- "async def review(body: Body): ...",
361
- 0.82
362
- ))
363
-
364
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
365
- # CATEGORY 3 — Data & State
366
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
367
-
368
- # R-D1 · DB connection not closed
369
- if IS_PY and re.search(r'\.(connect|cursor|session|execute)\s*\(', code) \
370
- and not re.search(r'\bwith\b.*(connect|session)|finally\s*:', code):
371
- ln = _fl(code, r'\.(connect|cursor|session|execute)\s*\(')
372
- bugs.append(_bug(
373
- "R-D1", "data_state", 4, ln,
374
- "R-D1 · DB connection not closed: connection opened without context manager. "
375
- "Leaked connections exhaust the pool and cause cascade failures.",
376
- "with db.connect() as conn:\n"
377
- " result = conn.execute(query)\n"
378
- "# SQLAlchemy:\n"
379
- "with SessionLocal() as session:\n"
380
- " session.add(record)\n"
381
- " session.commit()",
382
- 0.88
383
- ))
384
-
385
- # R-D2 · Race condition on shared state
386
- if IS_PY and re.search(r'\bglobal\s+\w+', code) \
387
- and re.search(r'Thread|threading|asyncio|concurrent', code):
388
- ln = _fl(code, r'\bglobal\s+\w+')
389
- bugs.append(_bug(
390
- "R-D2", "data_state", 5, ln,
391
- "R-D2 · Race condition: global variable mutated in threaded/async context without a lock. "
392
- "Concurrent writes will corrupt state.",
393
- "import threading\n"
394
- "_lock = threading.Lock()\n"
395
- "_counter = 0\n"
396
- "\n"
397
- "def increment():\n"
398
- " global _counter\n"
399
- " with _lock:\n"
400
- " _counter += 1",
401
- 0.90
402
- ))
403
-
404
- # R-D3 · Stale cache (no TTL)
405
- if re.search(r'(cache|lru_cache|@cache)', code, re.I) \
406
- and not re.search(r'ttl|expire|maxsize|timeout|invalidate', code, re.I):
407
  ln = _fl(code, r'cache|lru_cache')
408
  if ln:
409
- bugs.append(_bug(
410
- "R-D3", "data_state", 3, ln,
411
- "R-D3 · Stale cache: cache with no TTL, expiry, or invalidation strategy. "
412
- "A never-expiring cache is a latent data-correctness bug.",
413
- "import cachetools\n"
414
- "cache = cachetools.TTLCache(maxsize=256, ttl=300) # expires after 5 min\n"
415
- "# Or: @lru_cache(maxsize=256) for size-bounded (but no TTL)",
416
- 0.78
417
- ))
418
-
419
- # R-D4 · Missing input validation
420
- if IS_PY and re.search(r'@app\.(post|put|patch)', code) \
421
- and not re.search(r'BaseModel|HTTPException|raise.*400|raise.*422|validator', code):
422
- ln = _fl(code, r'@app\.(post|put|patch)')
423
- bugs.append(_bug(
424
- "R-D4", "data_state", 4, ln,
425
- "R-D4 · Missing input validation: POST/PUT route has no Pydantic model or explicit validation. "
426
- "Invalid input causes 500 instead of 422 with field-level errors.",
427
- "from pydantic import BaseModel, validator\n"
428
- "\n"
429
- "class Body(BaseModel):\n"
430
- " code: str\n"
431
- " language: str\n"
432
- "\n"
433
- " @validator('code')\n"
434
- " def not_empty(cls, v):\n"
435
- " if not v.strip(): raise ValueError('code is empty')\n"
436
- " return v",
437
- 0.83
438
- ))
439
-
440
- # R-D5 · Silent data truncation
441
- if IS_PY and re.search(r'(\.save\(|\.add\(|\.insert\(|db\.execute)', code) \
442
- and not re.search(r'len\s*\(|max_length|maxlength', code):
443
- ln = _fl(code, r'\.save\(|\.add\(|db\.execute')
444
- if ln:
445
- bugs.append(_bug(
446
- "R-D5", "data_state", 3, ln,
447
- "R-D5 · Silent data truncation: data written to DB without length validation. "
448
- "Values exceeding column limits are silently truncated or cause insertion errors.",
449
- "MAX_LEN = 255\n"
450
- "if len(value) > MAX_LEN:\n"
451
- " raise HTTPException(400, f'Value too long (max {MAX_LEN})')\n"
452
- "db.save(value)",
453
- 0.72
454
- ))
455
-
456
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
457
- # CATEGORY 4 — Security
458
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
459
-
460
- # R-S1 · Secrets in source code
461
- if re.search(
462
- r'(api_key|apikey|secret|password|passwd|token|auth_token|private_key)\s*[=:]\s*["\'][^"\']{4,}["\']',
463
- code, re.I
464
- ):
465
- ln = _fl(code, r'(api_key|apikey|secret|password|token)\s*[=:]')
466
- bugs.append(_bug(
467
- "R-S1", "security", 5, ln,
468
- "R-S1 · Secrets in source code: API key/token/password hardcoded in source. "
469
- "This secret is now in version control — rotate it immediately.",
470
- "import os\n"
471
- "API_KEY = os.environ.get('API_KEY')\n"
472
- "if not API_KEY:\n"
473
- " raise RuntimeError('API_KEY not set')\n"
474
- "# Scan history: pip install detect-secrets && detect-secrets scan",
475
- 0.97
476
- ))
477
-
478
- # R-S2 · SQL / command injection
479
- if re.search(
480
- r'(f["\'].*?\{.*?(SELECT|INSERT|DELETE|UPDATE|WHERE)|execute\s*\(\s*f["\']|os\.system\s*\(|shell\s*=\s*True)',
481
- code, re.I | re.S
482
- ):
483
- ln = _fl(code, r'SELECT|INSERT|DELETE|os\.system|shell\s*=\s*True')
484
- bugs.append(_bug(
485
- "R-S2", "security", 5, ln,
486
- "R-S2 · SQL/command injection: user input interpolated into SQL or shell command. "
487
- "Attackers can execute arbitrary queries or OS commands.",
488
- "# SQL — parameterized queries:\n"
489
- "cursor.execute('SELECT * FROM t WHERE id = ?', (uid,))\n"
490
- "\n"
491
- "# Shell — list args without shell=True:\n"
492
- "subprocess.run(['ls', path], shell=False, capture_output=True)",
493
- 0.98
494
- ))
495
-
496
- # R-S3 · Overly permissive CORS
497
- if re.search(r'allow_origins\s*=\s*\[.*\*.*\]|Access-Control-Allow-Origin.*\*|cors.*origin.*\*', code, re.I):
498
- ln = _fl(code, r'allow_origins|Access-Control-Allow-Origin')
499
- bugs.append(_bug(
500
- "R-S3", "security", 4, ln,
501
- "R-S3 · Overly permissive CORS: wildcard origin (*) allows any website to call your API. "
502
- "Never use * on authenticated endpoints.",
503
- "app.add_middleware(\n"
504
- " CORSMiddleware,\n"
505
- " allow_origins=['https://yourapp.com'], # no wildcard\n"
506
- " allow_credentials=True,\n"
507
- ")",
508
- 0.95
509
- ))
510
-
511
- # R-S4 · No rate limiting
512
- if IS_PY and re.search(r'@app\.(post|get)\s*\(', code) \
513
- and not re.search(r'limiter|rate_limit|RateLimiter|slowapi|Throttle', code, re.I):
514
- ln = _fl(code, r'@app\.(post|get)\s*\(')
515
- bugs.append(_bug(
516
- "R-S4", "security", 3, ln,
517
- "R-S4 · No rate limiting: public endpoints without throttling can be scraped, abused, or DoS'd.",
518
- "from slowapi import Limiter\n"
519
- "from slowapi.util import get_remote_address\n"
520
- "limiter = Limiter(key_func=get_remote_address)\n"
521
- "\n"
522
- "@app.post('/api/review')\n"
523
- "@limiter.limit('20/minute')\n"
524
- "async def review(request: Request, body: Body): ...",
525
- 0.80
526
- ))
527
-
528
- # R-S5 · Exposed stack traces
529
- if re.search(r'traceback\.format_exc\(\)|format_exception', code) \
530
- and re.search(r'return.*detail|JSONResponse.*trace', code, re.I):
531
- ln = _fl(code, r'traceback\.format_exc|format_exception')
532
- bugs.append(_bug(
533
- "R-S5", "security", 4, ln,
534
- "R-S5 · Exposed stack traces: raw traceback returned to HTTP client. "
535
- "This leaks file paths, library versions, and internal logic.",
536
- "except Exception as e:\n"
537
- " logger.error('Request failed', exc_info=True) # log internally\n"
538
- " raise HTTPException(status_code=500, detail='An error occurred') # generic to client",
539
- 0.92
540
- ))
541
-
542
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
543
- # CATEGORY 5 — Config & Deploy
544
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
545
-
546
- # R-CF1 · Wrong startup command
547
- if re.search(r'\bCMD\b|\bENTRYPOINT\b', code):
548
- cmd = re.search(r'CMD\s+\[?"?([^\]"\n]+)', code)
549
- if cmd and not any(k in cmd.group(1) for k in ('uvicorn', 'gunicorn', 'app', 'python')):
550
- ln = _fl(code, r'\bCMD\b|\bENTRYPOINT\b')
551
- bugs.append(_bug(
552
- "R-CF1", "config_deploy", 5, ln,
553
- "R-CF1 · Wrong startup command: CMD/ENTRYPOINT doesn't reference uvicorn/gunicorn. "
554
- "A typo here causes the container to exit immediately with code 1.",
555
- 'CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]\n'
556
- "# Verify entry module name: main.py -> main:app",
557
- 0.80
558
- ))
559
-
560
- # R-CF2 · Port mismatch (HF Spaces expects 7860)
561
  if re.search(r'port\s*[=:]\s*(?!7860)\d{4,5}|--port\s+(?!7860)\d{4,5}|EXPOSE\s+(?!7860)\d{4,5}', code):
562
- ln = _fl(code, r'port\s*[=:]|--port\s+|EXPOSE\s+')
563
- bugs.append(_bug(
564
- "R-CF2", "config_deploy", 5, ln,
565
- "R-CF2 · Port mismatch: app binds to a port other than 7860. "
566
- "Hugging Face Spaces requires port 7860 — all other ports are unreachable.",
567
- "EXPOSE 7860\n"
568
- 'CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]',
569
- 0.92
570
- ))
571
-
572
- # R-CF3 · Missing dependency in requirements
573
  if IS_PY:
574
  imports = re.findall(r'^(?:import|from)\s+(\w+)', code, re.M)
575
- stdlib = {
576
- 'os', 'sys', 're', 'json', 'time', 'math', 'io', 'abc', 'copy', 'enum',
577
- 'typing', 'pathlib', 'datetime', 'collections', 'functools', 'itertools',
578
- 'logging', 'threading', 'asyncio', 'contextlib', 'inspect', 'traceback',
579
- 'hashlib', 'hmac', 'base64', 'urllib', 'http', 'socket', 'struct',
580
- 'random', 'string', 'shutil', 'glob', 'tempfile', 'subprocess', 'signal',
581
- }
582
- third_party = sorted(set(m for m in imports if m not in stdlib and not m.startswith('_')))
583
- if third_party:
584
- bugs.append(_bug(
585
- "R-CF3", "config_deploy", 3, 1,
586
- f"R-CF3 · Missing dependency check: third-party imports detected "
587
- f"({', '.join(third_party)}) — verify all are in requirements.txt / Dockerfile.",
588
- "pip freeze > requirements.txt\n"
589
- "# In Dockerfile:\n"
590
- "COPY requirements.txt .\n"
591
- "RUN pip install --no-cache-dir -r requirements.txt",
592
- 0.75
593
- ))
594
-
595
- # R-CF4 · Wrong working directory (relative paths without __file__)
596
- if IS_PY and re.search(r'open\s*\(\s*["\'](?!/)', code) \
597
- and not re.search(r'__file__|os\.path\.dirname|pathlib\.Path', code):
598
- ln = _fl(code, r'open\s*\(\s*["\']')
599
- bugs.append(_bug(
600
- "R-CF4", "config_deploy", 4, ln,
601
- "R-CF4 · Wrong working directory: relative file path without __file__ anchor. "
602
- "Works locally but breaks in Docker containers where CWD differs.",
603
- "import os\n"
604
- "BASE = os.path.dirname(os.path.abspath(__file__))\n"
605
- "path = os.path.join(BASE, 'templates', 'index.html')\n"
606
- "with open(path) as f: ...",
607
- 0.88
608
- ))
609
-
610
- # R-CF5 · Build vs runtime confusion (heavy deps at module level)
611
- if IS_PY and re.search(r'^import (torch|transformers|tensorflow|keras)', code, re.M):
612
- ln = _fl(code, r'^import (torch|transformers|tensorflow|keras)')
613
- if ln:
614
- bugs.append(_bug(
615
- "R-CF5", "config_deploy", 3, ln,
616
- "R-CF5 · Build vs runtime confusion: heavy ML library imported at module level. "
617
- "If the Docker layer is cached without GPU, the import fails at runtime.",
618
- "def get_model():\n"
619
- " import torch # lazy import — only when needed\n"
620
- " return torch.load('model.pt')",
621
- 0.72
622
- ))
623
-
624
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
625
- # CATEGORY 6 — Logic & Testing
626
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
627
-
628
- # R-L1 · No test for the happy path
629
- if IS_PY and re.search(r'def \w+\s*\(', code) \
630
- and not re.search(r'def test_|import pytest|import unittest|assert\b', code):
631
- bugs.append(_bug(
632
- "R-L1", "logic_testing", 2, 1,
633
- "R-L1 · No test for the happy path: no pytest/unittest tests found. "
634
- "Every endpoint and function needs at least one integration test.",
635
- "from fastapi.testclient import TestClient\n"
636
- "client = TestClient(app)\n"
637
- "\n"
638
- "def test_review_happy_path():\n"
639
- " r = client.post('/api/review', json={'code': 'x=1', 'language': 'python'})\n"
640
- " assert r.status_code == 200\n"
641
- " assert 'bugs' in r.json()",
642
- 0.75
643
- ))
644
-
645
- # R-L2 · Edge cases not covered
646
- if IS_PY and re.search(r'def test_', code) \
647
- and not re.search(r'empty|null|none|zero|boundary|edge|invalid|negative|max|min', code, re.I):
648
- ln = _fl(code, r'def test_')
649
- bugs.append(_bug(
650
- "R-L2", "logic_testing", 2, ln,
651
- "R-L2 · Edge cases not covered: tests found but none test empty, null, zero, max, or boundary values.",
652
- "def test_empty_code_returns_400():\n"
653
- " r = client.post('/api/review', json={'code': '', 'language': 'python'})\n"
654
- " assert r.status_code == 400\n"
655
- "\n"
656
- "def test_oversized_code_returns_400():\n"
657
- " r = client.post('/api/review', json={'code': 'x' * 6000, 'language': 'python'})\n"
658
- " assert r.status_code == 400",
659
- 0.70
660
- ))
661
-
662
- # R-L3 · Off-by-one errors
663
- if re.search(r'range\s*\(\s*len\s*\([^)]+\)\s*-\s*1\s*\)|for.+in.+\[\s*:-1\s*\]', code):
664
- ln = _fl(code, r'range\s*\(\s*len|:\s*-1\s*\]')
665
- bugs.append(_bug(
666
- "R-L3", "logic_testing", 3, ln,
667
- "R-L3 · Off-by-one error: range(len(x)-1) or x[:-1] skips the last element. "
668
- "Review every loop bound, slice, and pagination offset.",
669
- "for i in range(len(numbers)): # not len(numbers)-1\n"
670
- "for item in numbers: # preferred\n"
671
- "for i, item in enumerate(numbers): # with index\n"
672
- "x[:] # full slice",
673
- 0.90
674
- ))
675
-
676
- # R-L4 · Wrong default values (mutable defaults)
677
- if IS_PY and re.search(r'def\s+\w+\s*\([^)]*=\s*(\[\]|\{\}|set\(\)|list\(\)|dict\(\))', code):
678
- ln = _fl(code, r'def\s+\w+\s*\([^)]*=\s*(\[\]|\{\}|set\(\))')
679
- bugs.append(_bug(
680
- "R-L4", "logic_testing", 4, ln,
681
- "R-L4 · Wrong default value: mutable default ([], {}, set()) is shared across ALL calls. "
682
- "State from one call leaks into the next — a classic Python bug.",
683
- "def process(items=None, config=None):\n"
684
- " if items is None: items = []\n"
685
- " if config is None: config = {}\n"
686
- " # Each call now gets a fresh object",
687
- 0.98
688
- ))
689
-
690
- # R-L5 · Async/await misuse
691
- if re.search(r'async\s+(def|function)', code) \
692
- and not re.search(r'\bawait\b', code):
693
- ln = _fl(code, r'async\s+(def|function)')
694
- bugs.append(_bug(
695
- "R-L5", "logic_testing", 4, ln,
696
- "R-L5 · Async/await misuse: async function with no await returns a coroutine object, not the result. "
697
- "Enable async linting to catch this automatically.",
698
- "async def get_data():\n"
699
- " result = await fetch_from_db() # not fetch_from_db()\n"
700
- " return result\n"
701
- "\n"
702
- "# Enable warnings:\n"
703
- "# python -W error::RuntimeWarning",
704
- 0.88
705
- ))
706
-
707
- # Sort by severity DESC, then confidence DESC
708
  bugs.sort(key=lambda b: (b["severity"], b["confidence"]), reverse=True)
709
  return bugs
710
-
711
-
712
- # ========================================================================
713
- # GET / - Serve frontend
714
- # ========================================================================
715
- @app.get("/")
716
- def serve_frontend():
717
- """Serve the CodeBug frontend UI"""
718
- html_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates", "index.html")
719
- try:
720
- with open(html_path, "r", encoding="utf-8") as f:
721
- return HTMLResponse(f.read())
722
- except Exception:
723
- return HTMLResponse("<h1>CodeBug API Running.</h1><p>Visit /docs for API documentation.</p>")
724
-
725
-
726
- # ========================================================================
727
- # GET /api/health
728
- # ========================================================================
729
- @app.get("/api/health")
730
- async def health_check():
731
- return {
732
- "status": "ok",
733
- "version": "2.0",
734
- "rules_engine": "30-rule official spec",
735
- "rule_categories": [
736
- "API & Network (R-N1..R-N5)",
737
- "Runtime Crashes (R-C1..R-C5)",
738
- "Data & State (R-D1..R-D5)",
739
- "Security (R-S1..R-S5)",
740
- "Config & Deploy (R-CF1..R-CF5)",
741
- "Logic & Testing (R-L1..R-L5)",
742
- ],
743
- "supported_languages": ["python", "javascript", "typescript", "java", "go", "cpp"],
744
- "llm_active": HAS_LLM,
745
- }
746
-
747
-
748
- # ========================================================================
749
- # GET /api/stats
750
- # ========================================================================
751
- @app.get("/api/stats")
752
- async def get_stats():
753
- return {
754
- "rules_total": 30,
755
- "categories": 6,
756
- "rules_per_category": 5,
757
- "languages_supported": 6,
758
- "llm_active": HAS_LLM,
759
- }
760
-
761
-
762
- # ========================================================================
763
- # Mount OpenEnv app at /openenv
764
- # ========================================================================
765
- app.mount("/openenv", openenv_app)
 
1
  """
2
+ CodeBug — OpenEnv-compliant FastAPI server.
3
+ The openenv app IS the main app so /reset /step /state are at root level.
4
+ Custom routes /api/review /api/train / are added on top.
5
  """
6
 
7
+ import os, re, logging, traceback, uuid
8
+ from fastapi import FastAPI, HTTPException
9
  from fastapi.responses import HTMLResponse, JSONResponse
10
  from pydantic import BaseModel
 
11
  from openenv.core.env_server import create_fastapi_app
12
  from environment import CodeBugEnvironment
13
  from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
 
19
  except ImportError:
20
  _AGENT_IMPORTED = False
21
 
 
22
  _HAS_ANTHROPIC = bool(os.environ.get("ANTHROPIC_API_KEY", "").strip())
23
  _HAS_OPENAI = bool(os.environ.get("OPENAI_API_KEY", "").strip())
24
  HAS_LLM = _AGENT_IMPORTED and (_HAS_ANTHROPIC or _HAS_OPENAI)
25
 
26
  logger = logging.getLogger(__name__)
27
 
28
+ # ── The openenv app IS the main app ──────────────────────────────────────
29
+ # This puts /reset /step /state /ws at the ROOT so the checker finds them.
30
+ app = create_fastapi_app(CodeBugEnvironment, CodeReviewAction, CodeReviewObservation)
31
 
 
 
32
 
33
+ # =========================================================================
 
34
  # POST /api/train
35
+ # =========================================================================
36
  class TrainRequest(BaseModel):
37
  episodes: int = 5
38
 
39
  @app.post("/api/train")
40
  async def run_real_training(body: TrainRequest):
 
41
  try:
42
  stats = run_training(num_episodes=body.episodes, verbose=False)
43
  return {"status": "ok", "stats": stats}
44
  except Exception as e:
45
  logger.error(f"Training failed: {e}\n{traceback.format_exc()}")
46
+ return JSONResponse(status_code=500,
47
+ content={"error": str(e), "details": traceback.format_exc()[:500]})
 
 
48
 
49
 
50
+ # =========================================================================
51
  # POST /api/review
52
+ # =========================================================================
53
  class ReviewRequest(BaseModel):
54
  code: str
55
  language: str
 
57
 
58
  @app.post("/api/review")
59
  async def review_code(request: ReviewRequest):
 
60
  try:
61
  code = request.code.strip()
62
  lang = request.language.lower().strip()
63
 
64
  if not code:
65
  raise HTTPException(status_code=400, detail="Code cannot be empty")
 
 
66
  if len(code) > 5000:
67
  raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
68
 
69
+ supported = ['python', 'javascript', 'typescript', 'java', 'go', 'cpp', 'c++']
70
+ if lang not in supported:
71
+ raise HTTPException(status_code=400,
72
+ detail=f"Language '{lang}' not supported. Use: {', '.join(supported)}")
 
 
73
 
74
+ results = _analyze_with_llm(code, lang) if HAS_LLM else analyze_code_comprehensively(code, lang)
 
 
 
 
75
 
76
  response = {
77
  "bugs_found": len(results),
78
  "bugs": results,
79
+ "primary_bug": results[0] if results else {
80
+ "type": "approve", "rule_id": None, "category": "style",
81
+ "severity": 1, "line_hint": None,
82
+ "comment": "No bugs detected.", "fix": "", "confidence": 1.0
83
+ },
84
  "analysis_metadata": {
85
  "language": lang,
86
  "code_length": len(code),
 
91
  ) if results else 1.0
92
  }
93
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  return response
95
 
96
  except HTTPException:
97
  raise
98
  except Exception as e:
99
+ logger.error(traceback.format_exc())
100
+ return JSONResponse(status_code=500, content={"error": str(e)})
 
 
 
 
101
 
102
 
103
+ # =========================================================================
104
+ # GET / — Serve frontend
105
+ # =========================================================================
106
+ @app.get("/")
107
+ def serve_frontend():
108
+ html_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates", "index.html")
109
+ try:
110
+ with open(html_path, encoding="utf-8") as f:
111
+ return HTMLResponse(f.read())
112
+ except Exception:
113
+ return HTMLResponse("<h1>CodeBug API</h1><p>Visit /docs for API docs. POST /reset to start.</p>")
114
+
115
+
116
+ # =========================================================================
117
+ # GET /api/health
118
+ # =========================================================================
119
+ @app.get("/api/health")
120
+ async def health_check():
121
+ return {
122
+ "status": "ok", "version": "2.0",
123
+ "openenv_routes": ["/reset", "/step", "/state"],
124
+ "custom_routes": ["/api/review", "/api/train"],
125
+ "llm_active": HAS_LLM,
126
+ }
127
+
128
+
129
+ # =========================================================================
130
+ # GET /api/stats
131
+ # =========================================================================
132
+ @app.get("/api/stats")
133
+ async def get_stats():
134
+ return {"rules_total": 30, "categories": 6, "languages": 6, "llm_active": HAS_LLM}
135
+
136
+
137
+ # =========================================================================
138
  # LLM wrapper
139
+ # =========================================================================
140
  def _analyze_with_llm(code: str, lang: str) -> list:
141
  if not HAS_LLM:
142
  return analyze_code_comprehensively(code, lang)
 
147
  bugs.sort(key=lambda x: (x.get('severity', 0), x.get('confidence', 0)), reverse=True)
148
  return bugs
149
  except Exception as e:
150
+ logger.warning(f"LLM failed: {e}. Using pattern analysis.")
151
  return analyze_code_comprehensively(code, lang)
152
 
153
 
154
+ # =========================================================================
155
  # OFFICIAL 30-RULE BUG ENGINE
156
+ # R-N1..R-N5 | R-C1..R-C5 | R-D1..R-D5 | R-S1..R-S5 | R-CF1..R-CF5 | R-L1..R-L5
157
+ # =========================================================================
158
 
159
  def _fl(code: str, pattern: str, flags: int = re.I) -> int | None:
 
160
  for i, line in enumerate(code.splitlines(), 1):
161
  if re.search(pattern, line, flags):
162
  return i
163
  return None
164
 
165
+ def _bug(rule_id, category, severity, line_hint, comment, fix, confidence):
166
+ return {"type": "bug", "rule_id": rule_id, "category": category,
167
+ "severity": severity, "line_hint": line_hint,
168
+ "comment": comment, "fix": fix, "confidence": confidence}
 
 
 
 
 
 
 
 
 
169
 
170
  def analyze_code_comprehensively(code: str, lang: str) -> list:
 
 
 
 
171
  bugs = []
172
  IS_JS = lang in ('javascript', 'typescript')
173
  IS_PY = lang == 'python'
174
 
175
+ # ── API & Network ─────────────────────────────────────────────────
 
 
 
 
176
  if IS_JS and re.search(r'\bfetch\s*\(', code):
177
+ if not re.search(r'\.catch\s*\(|try\s*\{', code) or not re.search(r'\.ok\b|\.status\b', code):
178
+ bugs.append(_bug("R-N1","api_network",4,_fl(code,r'\bfetch\s*\('),
179
+ "R-N1 · Missing error handling on fetch: fetch() does not throw on 4xx/5xx.",
180
+ "if (!res.ok) throw new Error(`HTTP ${res.status}`);\n// Wrap in try/catch",0.88))
181
+
182
+ if IS_JS and re.search(r'\bfetch\s*\(', code) and not re.search(r'AbortController|signal|timeout', code):
183
+ bugs.append(_bug("R-N2","api_network",3,_fl(code,r'\bfetch\s*\('),
184
+ "R-N2 · No timeout: fetch() can hang indefinitely.",
185
+ "const ctrl = new AbortController();\nsetTimeout(()=>ctrl.abort(),5000);\nfetch(url,{signal:ctrl.signal})",0.85))
186
+
187
+ if IS_PY and re.search(r'requests\.(get|post|put|delete)\s*\(', code) and not re.search(r'timeout\s*=', code):
188
+ bugs.append(_bug("R-N2","api_network",3,_fl(code,r'requests\.(get|post)'),
189
+ "R-N2 · No timeout on requests call.",
190
+ "requests.get(url, timeout=10)",0.90))
191
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  if re.search(r'allow_origins\s*=\s*\[.*\*.*\]|Access-Control-Allow-Origin.*\*', code):
193
+ bugs.append(_bug("R-N4","security",4,_fl(code,r'allow_origins|Access-Control'),
194
+ "R-N4 · CORS wildcard (*) on authenticated endpoints is a security issue.",
195
+ "allow_origins=['https://yourapp.com'] # not ['*']",0.95))
196
+
197
+ if IS_JS and re.search(r'\bfetch\s*\(', code) and not re.search(r'Authorization|Bearer', code, re.I):
198
+ bugs.append(_bug("R-N5","security",3,_fl(code,r'\bfetch\s*\('),
199
+ "R-N5 · Auth token not sent in fetch request.",
200
+ "headers: {'Authorization': `Bearer ${token}`}",0.70))
201
+
202
+ # ── Runtime Crashes ────────────────────────────────────────────────
203
+ if IS_PY and re.search(r'@app\.(get|post|put|delete|patch)', code) and not re.search(r'try\s*:', code):
204
+ bugs.append(_bug("R-C1","runtime",4,_fl(code,r'@app\.(get|post)'),
205
+ "R-C1 · Unhandled exception in route: any error will expose a raw 500 with traceback.",
206
+ "try:\n return process(body)\nexcept Exception as e:\n logger.error(e,exc_info=True)\n raise HTTPException(500,'Internal error')",0.85))
207
+
208
+ if IS_PY and re.search(r'os\.environ\.get\(|os\.getenv\(', code) and not re.search(r'sys\.exit|raise.*environ|if not', code, re.I):
209
+ bugs.append(_bug("R-C2","runtime",4,_fl(code,r'os\.environ'),
210
+ "R-C2 · Missing env var validation: None returned silently if key missing.",
211
+ "if not os.environ.get('KEY'):\n sys.exit('[FATAL] KEY not set')",0.87))
212
+
213
+ if IS_PY and re.search(r'(model|pipeline|tokenizer)\s*=\s*None', code) and not re.search(r'lifespan|on_event|startup', code, re.I):
214
+ bugs.append(_bug("R-C3","runtime",4,_fl(code,r'(model|pipeline)\s*=\s*None'),
215
+ "R-C3 · Model not loaded at startup — first request hangs or crashes.",
216
+ "@asynccontextmanager\nasync def lifespan(app):\n app.state.model = load_model()\n yield",0.80))
217
+
218
+ if IS_PY and re.search(r'request\.(json|form|args|query_params)', code) and not re.search(r'BaseModel|int\(|float\(', code):
219
+ bugs.append(_bug("R-C5","runtime",3,_fl(code,r'request\.(json|form)'),
220
+ "R-C5 · Type mismatch: no Pydantic validation on request params.",
221
+ "class Body(BaseModel):\n value: int # auto-cast",0.82))
222
+
223
+ # ── Data & State ───────────────────────────────────────────────────
224
+ if IS_PY and re.search(r'\.(connect|cursor|session|execute)\s*\(', code) and not re.search(r'\bwith\b', code):
225
+ bugs.append(_bug("R-D1","data_state",4,_fl(code,r'\.(connect|cursor)'),
226
+ "R-D1 · DB connection not closed — use context manager.",
227
+ "with db.connect() as conn:\n conn.execute(query)",0.88))
228
+
229
+ if IS_PY and re.search(r'\bglobal\s+\w+', code) and re.search(r'Thread|threading|asyncio', code):
230
+ bugs.append(_bug("R-D2","data_state",5,_fl(code,r'\bglobal\s+'),
231
+ "R-D2 · Race condition: global mutation in threaded context.",
232
+ "_lock = threading.Lock()\nwith _lock:\n counter += 1",0.90))
233
+
234
+ if re.search(r'(cache|lru_cache)', code, re.I) and not re.search(r'ttl|expire|maxsize|timeout', code, re.I):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  ln = _fl(code, r'cache|lru_cache')
236
  if ln:
237
+ bugs.append(_bug("R-D3","data_state",3,ln,
238
+ "R-D3 · Stale cache: no TTL or expiry defined.",
239
+ "cachetools.TTLCache(maxsize=256, ttl=300)",0.78))
240
+
241
+ if IS_PY and re.search(r'@app\.(post|put|patch)', code) and not re.search(r'BaseModel|HTTPException|validator', code):
242
+ bugs.append(_bug("R-D4","data_state",4,_fl(code,r'@app\.(post|put)'),
243
+ "R-D4 · Missing input validation: no Pydantic model on POST route.",
244
+ "class Body(BaseModel):\n code: str\n language: str",0.83))
245
+
246
+ # ── Security ───────────────────────────────────────────────────────
247
+ if re.search(r'(api_key|secret|password|token)\s*[=:]\s*["\'][^"\']{4,}["\']', code, re.I):
248
+ bugs.append(_bug("R-S1","security",5,_fl(code,r'(api_key|secret|password|token)\s*[=:]'),
249
+ "R-S1 · Hardcoded secret in source code. Rotate immediately.",
250
+ "API_KEY = os.environ.get('API_KEY')\nif not API_KEY: raise RuntimeError('not set')",0.97))
251
+
252
+ if re.search(r'(f["\'].*?\{.*?(SELECT|INSERT|DELETE|UPDATE)|os\.system\s*\(|shell\s*=\s*True)', code, re.I|re.S):
253
+ bugs.append(_bug("R-S2","security",5,_fl(code,r'SELECT|INSERT|os\.system|shell\s*=\s*True'),
254
+ "R-S2 · SQL/command injection: user input in query or shell.",
255
+ "cursor.execute('SELECT * FROM t WHERE id=?',(uid,))",0.98))
256
+
257
+ if re.search(r'allow_origins\s*=\s*\[.*\*|cors.*\*', code, re.I):
258
+ bugs.append(_bug("R-S3","security",4,_fl(code,r'allow_origins|cors'),
259
+ "R-S3 · Overly permissive CORS wildcard.",
260
+ "allow_origins=['https://yourapp.com']",0.95))
261
+
262
+ if IS_PY and re.search(r'@app\.(post|get)\s*\(', code) and not re.search(r'limiter|rate_limit|slowapi', code, re.I):
263
+ bugs.append(_bug("R-S4","security",3,_fl(code,r'@app\.(post|get)'),
264
+ "R-S4 · No rate limiting on public endpoint.",
265
+ "@limiter.limit('20/minute')",0.80))
266
+
267
+ # ── Config & Deploy ────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  if re.search(r'port\s*[=:]\s*(?!7860)\d{4,5}|--port\s+(?!7860)\d{4,5}|EXPOSE\s+(?!7860)\d{4,5}', code):
269
+ bugs.append(_bug("R-CF2","config_deploy",5,_fl(code,r'port\s*[=:]|EXPOSE'),
270
+ "R-CF2 · Port mismatch: HF Spaces requires port 7860.",
271
+ 'CMD ["uvicorn","main:app","--host","0.0.0.0","--port","7860"]',0.92))
272
+
273
+ if IS_PY and re.search(r'open\s*\(\s*["\'](?!/)', code) and not re.search(r'__file__|os\.path\.dirname', code):
274
+ bugs.append(_bug("R-CF4","config_deploy",4,_fl(code,r'open\s*\(\s*["\']'),
275
+ "R-CF4 · Relative path breaks in Docker — anchor to __file__.",
276
+ "BASE=os.path.dirname(os.path.abspath(__file__))\nopen(os.path.join(BASE,'file.txt'))",0.88))
277
+
 
 
278
  if IS_PY:
279
  imports = re.findall(r'^(?:import|from)\s+(\w+)', code, re.M)
280
+ stdlib = {'os','sys','re','json','time','math','io','abc','copy','enum','typing','pathlib',
281
+ 'datetime','collections','functools','itertools','logging','threading','asyncio',
282
+ 'contextlib','inspect','traceback','hashlib','hmac','base64','urllib','http',
283
+ 'socket','struct','random','string','shutil','glob','tempfile','subprocess'}
284
+ third = sorted(set(m for m in imports if m not in stdlib and not m.startswith('_')))
285
+ if third:
286
+ bugs.append(_bug("R-CF3","config_deploy",3,1,
287
+ f"R-CF3 · Verify these are in requirements.txt: {', '.join(third)}",
288
+ "pip freeze > requirements.txt",0.75))
289
+
290
+ # ── Logic & Testing ────────────────────────────────────────────────
291
+ if IS_PY and re.search(r'def \w+\s*\(', code) and not re.search(r'def test_|pytest|unittest|assert\b', code):
292
+ bugs.append(_bug("R-L1","logic_testing",2,1,
293
+ "R-L1 · No tests found for this code.",
294
+ "def test_happy_path():\n assert func(input) == expected",0.75))
295
+
296
+ if re.search(r'range\s*\(\s*len\s*\([^)]+\)\s*-\s*1\s*\)|for.+\[:-1\]', code):
297
+ bugs.append(_bug("R-L3","logic_testing",3,_fl(code,r'range\s*\(\s*len|:-1'),
298
+ "R-L3 · Off-by-one: range(len(x)-1) skips the last element.",
299
+ "for i in range(len(numbers)): # not -1",0.90))
300
+
301
+ if IS_PY and re.search(r'def\s+\w+\s*\([^)]*=\s*(\[\]|\{\}|set\(\))', code):
302
+ bugs.append(_bug("R-L4","logic_testing",4,_fl(code,r'def\s+\w+\s*\([^)]*=\s*(\[\]|\{\})'),
303
+ "R-L4 · Mutable default argument — shared across all calls.",
304
+ "def func(items=None):\n if items is None: items = []",0.98))
305
+
306
+ if re.search(r'async\s+(def|function)', code) and not re.search(r'\bawait\b', code):
307
+ bugs.append(_bug("R-L5","logic_testing",4,_fl(code,r'async\s+(def|function)'),
308
+ "R-L5 · async function with no await — returns coroutine, not result.",
309
+ "result = await fetch_from_db() # not fetch_from_db()",0.88))
310
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  bugs.sort(key=lambda b: (b["severity"], b["confidence"]), reverse=True)
312
  return bugs