Spaces:
Sleeping
Sleeping
Commit Β·
532e19f
0
Parent(s):
Initial commit for Hugging Face
Browse filesFiles changed (50)
- .dockerignoreAdded+21
- .env.exampleAdded+18
- .gitignoreAdded+12
- AptfileAdded+1
- DockerfileAdded+22
- GOOGLE_DRIVE_SETUP.mdAdded+113
- GOOGLE_SHEETS_SETUP.mdAdded+107
- LOGIN_GUIDE.mdAdded+185
- PRESET_REPOS.mdAdded+159
- ProcfileAdded+1
- README.mdAdded+35
- REFACTORING_NOTES.mdAdded+278
- RENDER_DEPLOYMENT.mdAdded+85
- RENDER_FIX.mdAdded+106
- RENDER_GOOGLE_SHEETS_SETUP.mdAdded+159
- add_login.mdAdded+242
- app.pyAdded+59
- architect/__init__.pyAdded
- architect/challenge_deployer.pyAdded+257
- architect/file_mapper.pyAdded+257
- architect/graph.pyAdded+75
- architect/nodes.pyAdded+99
- architect/readme_generator.pyAdded+107
- architect/repo_cloner.pyAdded+86
- architect/saboteur.pyAdded
- architect/saboteur_new.txtAdded+197
- architect/state.pyAdded+39
- challenge.pyAdded+136
- debug_output.txtAdded+113
- git_submissions_logger.pyAdded+237
- google_sheets_logger.pyAdded+206
- launch_existing.pyAdded+38
- launch_interface.batAdded+36
- login_patch.pyAdded+118
- main.pyAdded+94
- orchestrator/__init__.pyAdded+1
- orchestrator/graph.pyAdded+31
- orchestrator/hint_graph.pyAdded+424
- orchestrator/nodes.pyAdded+135
- orchestrator/scoring.pyAdded+436
- orchestrator/state.pyAdded+29
- render.yamlAdded+18
- requirements.txtAdded+10
- runtime.txtAdded+1
- session_storage_solution.mdAdded+111
- start.shAdded+15
- start_render.shAdded+4
- student_interface.pyAdded+2091
- test_refactored_saboteur.pyAdded+213
- wsgi.pyAdded+29
123456789101112131415161718192021# Files not to include in Docker image__pycache__/*.pyc*.pyo*.pyd.Python*.so*.egg*.egg-info/dist/build/.env.env.backup.git/.gitignore*.md!README.mdworkspaces/*.log.vscode/.idea/123456789101112131415161718# Legacy Code Simulator - Environment Variables# Add your OpenAI API key below
OPENAI_API_KEY=your_api_key_hereAGENT_MODEL=gpt-4o
# Intel proxy settings (uncomment when on Intel network)# http_proxy=http://proxy-iil.intel.com:912# https_proxy=http://proxy-iil.intel.com:912# no_proxy=localhost,127.0.0.1
# Optional: Google Sheets Integration# Get Sheet ID from URL: https://docs.google.com/spreadsheets/d/{SHEET_ID}/edit# GOOGLE_SHEET_ID=your_google_sheet_id_here
# Optional: Google Drive Backup# Get Folder ID from URL: https://drive.google.com/drive/folders/{FOLDER_ID}# GOOGLE_DRIVE_FOLDER_ID=your_drive_folder_id_here123456789101112**/__pycache__/**.pyc*.pyo.env.env.backupgoogle-service-account.jsonworkspaces/submissions_backup/.claude/***/__pycache__/*.py[cod]*$py.class1git12345678910111213141516171819202122FROM python:3.11-slim
WORKDIR /app
# Install git (needed for cloning repos at runtime)RUN apt-get update && \ apt-get install -y git && \ apt-get clean && \ rm -rf /var/lib/apt/lists/*
# Copy requirements and install Python packagesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY . .
# Expose port (Render provides PORT env var)EXPOSE 10000
# Run the application directly with Python (NOT gunicorn!)CMD ["python", "app.py"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# Google Drive Backup Setup Guide## ================================
Google Drive backup creates detailed submission folders with all files for each student.
## What Gets Saved
Each submission creates a folder in your Drive:```π Legacy Code Submissions/ π 2026-05-19_1430_StudentName_RepoName/ π 1_challenge_prompt.md β The full challenge description π 2_original_code.py β Original code before bugs π 3_buggy_code.py β Code with bugs (what student got) π 4_student_solution.py β What the student submitted π 5_chat_history.txt β Full conversation with AI π 6_summary.json β Scores, tests, metadata```
---
## Setup Instructions
### Step 1: Enable Google Drive API
1. Go to: https://console.cloud.google.com2. Select your project: **"Legacy Code Challenge"**3. Navigate to: **APIs & Services** β **Library**4. Search for: **"Google Drive API"**5. Click on it β Click **"Enable"**
### Step 2: Create Folder in Google Drive
1. Go to: https://drive.google.com2. Create a new folder: **"Legacy Code Submissions"**3. Right-click the folder β **Share**4. Add your service account email: - Open `google-service-account.json` - Find `"client_email"` field - Copy the email (e.g., `legacy-code-logger@...iam.gserviceaccount.com`) - Paste it in the Share dialog5. Give it **Editor** permissions6. Click **Share** (uncheck "Notify people")
### Step 3: Get Folder ID
1. Open the folder you just created2. Look at the URL in your browser: ``` https://drive.google.com/drive/folders/1abc123XYZ456... ^^^^^^^^^^^^^^^ This is the Folder ID ```3. **Copy the Folder ID** (the part after `/folders/`)
### Step 4: Add to Environment Variables
Add to your `.env` file:```envGOOGLE_DRIVE_FOLDER_ID=1abc123XYZ456...```
---
## Testing Locally
1. Make sure `google-service-account.json` is in the project root2. Make sure `GOOGLE_DRIVE_FOLDER_ID` is in `.env`3. Run the test: ```bash python google_drive_logger.py test ```4. Check your Drive folder - you should see a test submission!
---
## For Render Deployment
The same `google-service-account.json` and environment variables work on Render.
**Already done:**- β
`google-service-account.json` uploaded to Render (Secret Files)- β
`GOOGLE_SHEET_ID` in Render Environment Variables
**To add:**- Add `GOOGLE_DRIVE_FOLDER_ID` to Render Environment Variables: 1. Render Dashboard β Settings β Environment 2. Add environment variable: ``` Key: GOOGLE_DRIVE_FOLDER_ID Value: [paste your folder ID here] ``` 3. Save Changes β Redeploy
---
## What You'll See
After each student submits:- β
**Google Sheets** - New row in dashboard (real-time overview)- β
**Google Drive** - New folder with 6 files (detailed backup)
Both update automatically and persist forever!
---
## Security Notes
- The service account can only access: - The specific Sheet you shared with it - The specific Drive folder you shared with it- No access to your other files- Both are already restricted by API scope (Sheets + Drive only)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107# Google Sheets Integration for Submission Logging# ================================================
## Setup Instructions
### 1. Create Google Cloud Project- Go to: https://console.cloud.google.com- Click "Select a project" β "New Project"- Name: "Legacy Code Challenge"- Click "Create"
### 2. Enable Google Sheets API1. In your project, go to: APIs & Services β Library2. Search for "Google Sheets API"3. Click on it β Click "Enable"
### 3. Create Service Account1. APIs & Services β Credentials2. Create Credentials β Service Account3. Service account details: - Name: `legacy-code-logger` - Description: "Logs student submissions to Google Sheets" - Click "Create and Continue"4. Grant access (optional): Skip this step β Click "Continue"5. Click "Done"
### 4. Create Service Account Key1. Click on the service account email you just created2. Go to "Keys" tab3. Add Key β Create new key β JSON format4. Download the JSON file (save as `google-service-account.json`)
**Security Best Practices:**- β
**API Restrictions**: Already done by enabling ONLY Google Sheets API in Step 2- β
**Access Control**: Service account can only access sheets you explicitly share (Step 6)- β **Application Restrictions** (IP/domain): Not available for service account keys - Application restrictions are only for API keys, not service account credentials - Service accounts use OAuth 2.0 authentication via JSON key file- π **Keep JSON file secure**: Never commit to git, never share publicly
### 5. Create Google Sheet1. Go to: https://docs.google.com/spreadsheets2. Create a new spreadsheet3. Name it: "Legacy Code Submissions"4. Copy the Sheet ID from URL: ``` https://docs.google.com/spreadsheets/d/{SHEET_ID}/edit ```
### 6. Share Sheet with Service Account1. Open your Google Sheet2. Click "Share" button (top-right)3. Add the service account email (find it in `google-service-account.json` under `client_email`) - Example: `legacy-code-logger@legacy-code-challenge.iam.gserviceaccount.com`4. Give it "Editor" permissions5. Click "Send"
### 7. Setup Files- Save the downloaded JSON file as `google-service-account.json` in project root- It's already in `.gitignore` - DO NOT commit it to git!
### 8. Environment Variables (.env)```envGOOGLE_SHEET_ID=your_sheet_id_here# Get from sheet URL: https://docs.google.com/spreadsheets/d/{SHEET_ID}/edit```
## OptionalIf you don't want Google Sheets logging:- Don't set `GOOGLE_SHEET_ID` in .env- System will work normally without it- Submissions still saved locally as JSON
## Security Notes- `google-service-account.json` is in `.gitignore` - **DO NOT commit it to git!**- The service account can only access sheets you explicitly share with it- No access to your personal files- **On Render**: Add the entire JSON content as environment variable or upload via dashboard- Never share the JSON file publicly
### Security Restrictions Available:**β
What IS restricted:**1. **API Scope**: Only Google Sheets API is enabled (Step 2)2. **Sheet Access**: Service account can only access sheets you share with it3. **Permissions**: Service account has Editor role only on shared sheets
**β What is NOT available:**- **Application restrictions** (IP addresses, HTTP referrers, etc.) - These apply to API Keys, not Service Account credentials - Service accounts use OAuth 2.0, not API keys - Security is managed through IAM permissions and sheet sharing
### Why Service Accounts are Secure:- Even if the JSON file is exposed, attacker can only: - Access sheets you explicitly shared with this service account email - Use Google Sheets API only (no Gmail, Drive, etc.) - Cannot access your personal Google account or files
## TestingTest locally before deploying:```bashpython google_sheets_logger.py init```This will:1. Check if credentials are configured2. Initialize sheet headers3. Add a test row123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185# Login & Logout System β Usage Guide
## π― Overview
The system now supports two modes:
### 1. **Local Mode** (Development with .env)- API key in `.env` file- **No login page** β goes straight to setup- Logout button **hidden**- For developers/instructors
### 2. **Hosted Mode** (Render/Hugging Face)- No `.env` file (or empty `OPENAI_API_KEY`)- **Login page shown** β users provide name + API key- Logout button **visible** in top-right corner- Each user pays for their own OpenAI usage
---
## π Running Locally
### With API Key (Skip Login):```bash# Make sure .env has OPENAI_API_KEYpython challenge.py# orpython app.py```
### Without API Key (Test Login Page):```bash# Temporarily hide .envmv .env .env.backup
# Run the apppython app.py
# You'll see the login page!# Enter name + API key to continue
# Restore .env when donemv .env.backup .env```
---
## π Deploying to Render
See [RENDER_DEPLOYMENT.md](RENDER_DEPLOYMENT.md) for full guide.
**Quick steps:**1. Push code to GitHub2. Connect Render to your repo3. Render auto-detects `render.yaml`4. Deploy! π
**Don't add `OPENAI_API_KEY` to Render** β let users provide their own!
---
## π How Login Works
### Login Page Components:- **Name field**: Student's name (shown in header)- **API Key field**: OpenAI API key (sk-proj-...)- **Continue button**: Validates key and proceeds
### Validation:- Checks format (must start with `sk-`)- Makes test call to OpenAI API- Shows error if invalid/no quota- Sets key in environment on success
### Logout:- **Button location**: Top-right corner (after login)- **Action**: Clears API key, returns to login page- **Note**: Refresh won't logout β must click button explicitly
---
## π Auto-Detection Logic
```pythonhas_env_key = bool(os.getenv("OPENAI_API_KEY"))
if has_env_key: # Show setup page directly # Hide login page # Hide logout buttonelse: # Show login page # Hide setup page # Show logout button after login```
---
## π Files Modified
- β
`student_interface.py` β Added `validate_openai_key()`, login page, logout button- β
`challenge.py` β Made API key optional for GUI mode- β
`app.py` β New entry point for hosting (uses port from env)- β
`render.yaml` β Render configuration- β
`RENDER_DEPLOYMENT.md` β Deployment guide
---
## β οΈ Important Notes
### For Local Users:- Keep your `.env` file **private** (in `.gitignore`)- Never commit API keys to git!
### For Hosted Users:- Each student needs their own OpenAI API key- Keys are **session-only** (not stored)- Logout clears the key from memory
### Cost Management:- **Hosted mode**: Each user pays for their own usage- **Local mode**: You pay (instructor/developer)- **Recommendation**: Use hosted mode for courses/public access
---
## π§ͺ Testing
### Test Login Flow:```bash# 1. Hide .env to force login pagemv .env .env.backup
# 2. Run apppython app.py
# 3. Try login with:# - Empty fields β error# - Invalid key β error # - Valid key β success!
# 4. Test logout button# - Click logout β returns to login page# - Login again β works!
# 5. Restore .envmv .env.backup .env```
### Test Local Mode:```bash# With .env presentpython challenge.py
# Should skip login page entirely# Go straight to setup page# No logout button visible```
---
## π Troubleshooting
**Q: Login page not showing?** A: Check that `OPENAI_API_KEY` is not in `.env` or environment
**Q: Logout button not visible?** A: It only appears after successful login (hosted mode)
**Q: "API key valid but no quota"?** A: User needs to add billing/credits at platform.openai.com/billing
**Q: Refresh goes back to setup page?** A: Known Gradio limitation β use explicit logout button instead
**Q: Can I force login page even with .env?** A: Yes! Temporarily comment out `OPENAI_API_KEY` in `.env`
---
## π Related Documentation
- [RENDER_DEPLOYMENT.md](RENDER_DEPLOYMENT.md) β How to deploy to Render- [add_login.md](add_login.md) β Detailed implementation notes- [README.md](README.md) β Main project documentation123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159# π¦ Preset GitHub Repositories for Debugging Challenges
This file lists all available preset repositories that are pre-configured and tested for the Legacy Code Challenge system.
---
## β
Currently Integrated (Available in Dropdown)
These repositories are already available in the GUI dropdown menu:
### 1. **boltons** β RECOMMENDED- **URL:** https://github.com/mahmoud/boltons- **Description:** Comprehensive utility library with functions for strings, lists, dicts, math, iterators- **Why it's great:** Clean, well-documented code with many primitive-type functions- **Best for:** All difficulty levels
### 2. **more-itertools**- **URL:** https://github.com/more-itertools/more-itertools- **Description:** Advanced iterator utilities beyond the standard library- **Why it's great:** Pure Python, many simple functions with clear logic- **Best for:** Medium difficulty (nesting-level 3-4)
### 3. **toolz**- **URL:** https://github.com/pytoolz/toolz- **Description:** Functional programming utilities for Python- **Why it's great:** Short, composable functions with minimal dependencies- **Best for:** Low to medium difficulty
### 4. **funcy**- **URL:** https://github.com/Suor/funcy- **Description:** Collection manipulation utilities- **Why it's great:** Simple, readable code with good test coverage- **Best for:** All levels
### 5. **iteration_utilities**- **URL:** https://github.com/MSeifert04/iteration_utilities- **Description:** Fast iterator helpers and utilities- **Why it's great:** Well-structured with helper function chains- **Best for:** Medium to high difficulty (nesting-level 4-5)
### 6. **algorithms** (python-algorithms)- **URL:** https://github.com/keon/algorithms- **Description:** Classic algorithms implemented in Python- **Why it's great:** Educational code, clear implementations- **Best for:** High difficulty (nesting-level 5-6)
### 7. **binaryornot**- **URL:** https://github.com/audreyr/binaryornot- **Description:** Detect if a file is binary or text- **Why it's great:** Small, focused library with file handling- **Best for:** Low difficulty (simple projects)
### 8. **humanize**- **URL:** https://github.com/python-humanize/humanize- **Description:** Human-readable formatting for numbers, dates, file sizes- **Why it's great:** String manipulation with edge cases- **Best for:** Medium difficulty
### 9. **python-dateutil**- **URL:** https://github.com/dateutil/dateutil- **Description:** Powerful date/time manipulation library- **Why it's great:** Complex logic with many edge cases- **Best for:** High difficulty (complex logic)
### 10. **inflection**- **URL:** https://github.com/jpvanhal/inflection- **Description:** String transformations (pluralize, camelize, etc.)- **Why it's great:** Short functions, string manipulation- **Best for:** Low to medium difficulty
---
## π Additional Recommended Repositories (To Add)
These repositories would work well but aren't yet added to the dropdown:
### String/Text Processing- **python-slugify** - https://github.com/un33k/python-slugify- **ftfy** - https://github.com/rspeer/python-ftfy- **arrow** - https://github.com/arrow-py/arrow
### Data Structures- **sortedcontainers** - https://github.com/grantjenks/python-sortedcontainers- **bidict** - https://github.com/jab/bidict- **cachetools** - https://github.com/tkem/cachetools
### Math/Numbers- **num2words** - https://github.com/savoirfairelinux/num2words- **pyparsing** (examples folder) - https://github.com/pyparsing/pyparsing
### File/Path Utilities- **pathlib2** - https://github.com/jazzband/pathlib2- **scandir** - https://github.com/benhoyt/scandir
---
## π« Not Recommended
Avoid these types of repositories:
β **Web frameworks** (Django, Flask) - Too complex, class-heavyβ **ML libraries** (NumPy, TensorFlow) - External dependencies, compiled codeβ **GUI frameworks** (tkinter, PyQt) - Event-driven, hard to testβ **Network libraries** (requests, urllib3) - I/O operations, mocking neededβ **Database ORMs** (SQLAlchemy) - Too many abstractions
---
## π― Selection Criteria
A good repository should have:
β
**Pure Python** - No C extensions or compiled codeβ
**Primitive types** - Functions work with int, str, list, dictβ
**Call chains** - Functions that call other helper functionsβ
**Minimal dependencies** - Stdlib or 1-2 simple depsβ
**Clear logic** - Not overly abstract or metaprogramming-heavyβ
**Good structure** - Organized modules, not one giant file
---
## π How to Use
### In GUI Mode:1. Launch: `python challenge.py`2. Select "Choose from preset list"3. Pick a repository from the dropdown4. Click "Start Challenge"
### In CLI Mode:```bash# List all available repospython challenge.py --list-repos
# Use a preset repopython challenge.py https://github.com/mahmoud/boltons --name "Alice"
# Custom repopython challenge.py https://github.com/YOUR/REPO --name "Alice" --nesting-level 4```
---
## π§ Adding New Presets
To add a new preset repository:
1. Test it first with a custom URL2. Edit `student_interface.py`3. Add to `PRESET_REPOS` dictionary: ```python "Short Name - Description": "https://github.com/user/repo", ```4. Save and restart the application
---
**Last Updated:** May 11, 2026**Total Preset Repos:** 101web: python app.py1234567891011121314151617181920212223242526272829303132333435---title: Legacy Code Challengeemoji: πcolorFrom: redcolorTo: orangesdk: gradiosdk_version: "5.9.1"app_file: app.pypinned: false---
# π Legacy Code Challenge
AI-powered educational tool for debugging legacy code. Students receive buggy code from real GitHub repositories and must fix it with AI assistance.
## Features- π Automated bug injection into real codebases- π€ AI-powered hint system (GPT-4o)- π§ͺ Automated testing and scoring- π Progress tracking via Google Sheets- πΎ Git-based submission backups
## How to Use1. Enter your OpenAI API key2. Choose a GitHub repository (or use default: mahmoud/boltons)3. Select difficulty level4. Debug the injected bugs!
## Environment Variables RequiredSet these in Hugging Face Spaces Settings:- `GOOGLE_SHEET_ID` - For logging submissions- `SUBMISSIONS_REPO_URL` - Git repo for backups- `SUBMISSIONS_GIT_TOKEN` - Git access token
Note: Users provide their own OpenAI API keys via the login page.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278# Two-Phase Bug Injection Refactoring
## SummaryComplete architectural refactor of the bug injection system to guarantee test quality.
**Date**: Current session **Status**: β
Complete - Ready for testing
---
## The Problem (OLD APPROACH)
### What Was WrongSingle GPT call asking it to:1. Inject a bug into a function2. Generate tests that catch the bug
### Why It Failed- GPT created bugs independently of tests- Tests were too generic and passed even with bugs- Result: "detected by 0 tests" repeatedly- No validation that tests actually expose the bug
### Example Failure```Bug: range(n) β range(n-1)Test: func([1,2,3,4,5])- Original: [1,2,3,4,5]- Buggy: [1,2,3,4]BUT: Test expected generic "list" result, so both passed β```
---
## The Solution (NEW APPROACH)
### Revolutionary Idea**Generate tests FIRST on working code, THEN inject bug**
This guarantees:1. Tests are valid (run on working code)2. Tests have concrete expected outputs3. ANY bug changes outputs β guaranteed detection
### Three-Phase Workflow
#### PHASE 1: Generate Tests on Clean Code```pythontests = _generate_tests_for_function(working_code)# Example: 3 public + 3 secret tests```
**Result**: 6 tests with known-good expected outputs
#### PHASE 2: Execute Tests on Original```pythonoriginal_results = _execute_tests_on_source(original_code, tests)# Example: {# "(5,)": (True, "125"),# "(3,)": (True, "27"),# ...# }```
**Result**: Baseline outputs for all 6 tests
#### PHASE 3: Inject Bug β Validate Detection```pythonbuggy_code = _inject_bug_into_function(original_code)buggy_results = _execute_tests_on_source(buggy_code, tests)
differences = count_differences(original_results, buggy_results)if differences >= 4: # At least 4/6 tests must differ SUCCESS! β```
**Result**: Only accept bugs that 4+ tests reliably catch
---
## Technical Changes
### New Functions
#### `_generate_tests_for_function()`- **Purpose**: Generate 3+3 tests for WORKING code- **Input**: Clean function source - **Output**: `{"test_cases_public": [...], "test_cases_secret": [...]}`- **Key**: No bug injection in this phase
#### `_inject_bug_into_function()`- **Purpose**: Inject ONE simple bug- **Input**: Clean function source, list of attempted bugs- **Output**: `{"sabotaged_function_code": "...", "bug_description": "..."}`- **Key**: Avoids repeating failed bugs via `attempted_bugs` list
#### `_execute_tests_on_source()`- **Purpose**: Run all tests on given source- **Input**: Source code, tests dict- **Output**: `{test_args_str: (success, result), ...}`- **Key**: Captures both success status AND result value
### Refactored Functions
#### `_sabotage_one_helper()` - COMPLETE REWRITE**Before**: - Single GPT call: bug + tests together- ~150 lines of validation- No output comparison
**After**:- Phase 1: Generate tests on clean code- Phase 2: Execute β save outputs - Phase 3: Inject bug β execute β compare- Validation: 4+ tests must show different outputs- ~180 lines but much more robust
---
## Validation Strategy
### Acceptance CriteriaFor a bug to be accepted:1. β
Syntax valid (parses without errors)2. β
Function name preserved3. β
No revealing comments4. β
**NEW**: At least 4/6 tests produce DIFFERENT outputs
### What "Different" Means```pythonorig_success, orig_result = original_results[test]buggy_success, buggy_result = buggy_results[test]
different = (orig_success != buggy_success) OR (orig_result != buggy_result)```
Examples of differences:- Original succeeds, buggy crashes β DIFFERENT β- Both succeed, different values β DIFFERENT β- Both succeed, same value β NOT DIFFERENT β
---
## Parameter Simplifications
### Test Count- **Before**: 5 public + 5 secret = 10 tests per bug- **After**: 3 public + 3 secret = 6 tests per bug- **Rationale**: Easier for GPT, still sufficient coverage
### Bug Distribution - **Before**: N bugs β 2 functions β [3,2] split- **After**: N bugs β N functions β 1 bug each- **Rationale**: Simpler validation, clearer test ownership
---
## Expected Benefits
### Cost Savings- Fewer retries needed (tests guaranteed to work)- Fewer GPT calls (separate prompts are clearer)
### Quality Improvement- **Before**: ~30% bugs detected by 0 tests- **After (expected)**: 100% bugs detected by 4+ tests
### Debug VisibilityNew metadata in results:```python{ "_debug_tests_catching_bug": "5/6", ...}```
---
## Migration Notes
### Breaking Changes**None** - `_sabotage_one_helper()` signature unchanged
All existing calls remain compatible:```python_sabotage_one_helper( bug_func_name, current_source, surface_func_name, surface_source, instructions, llm, indirect_mode, call_chain=..., previous_bugs=..., target_nesting=..., debug_mode=...)```
### Unused Parameters- `call_chain`: Not used in new implementation (reserved for future)- `previous_bugs`: Not used (replaced by internal `attempted_bugs` list)- `target_nesting`: Not used in new implementation
These remain in signature for API compatibility.
---
## Testing Plan
### Quick Test```bashpython main.py --repo Ugly_Legacy_code --num-bugs 2 --debug```
**Expected Output**:```[saboteur] PHASE 1: Generating tests for 'func1' (working code)...[saboteur] PHASE 1 SUCCESS: Generated 3 public + 3 secret tests[saboteur] Executing tests on ORIGINAL code...[saboteur] Test (5,) -> OK: 125[saboteur] Test (3,) -> OK: 27...[saboteur] PHASE 2: Bug injection attempt 1/3...[bug_inject] β Bug injected: Changed range(n) to range(n-1)[saboteur] Executing tests on BUGGY code...[saboteur] Test (5,) -> OK: 24[saboteur] DIFFERENCE: (5,)[saboteur] Original: 125[saboteur] Buggy: 24...[saboteur] Bug caught by 5/6 tests[saboteur] SUCCESS! Bug reliably detected by 5/6 tests```
### Metrics to Watch- **Bug acceptance rate**: Should be higher (~80%+ vs ~40% before)- **Tests catching bugs**: Should always be 4+/6 (100% vs ~30% before)- **GPT retries**: Should be lower (clearer prompts)
---
## Files Modified
### architect/saboteur.py- **Lines 595-673**: Added `_generate_tests_for_function()`- **Lines 673-748**: Added `_inject_bug_into_function()`- **Lines 779-803**: Added `_execute_tests_on_source()`- **Lines 821-1000**: Complete rewrite of `_sabotage_one_helper()`
**Total Changes**: ~400 lines added/modified
---
## Rollback Plan
If issues arise, revert commit:```bashgit log --oneline # Find commit before refactorgit revert <commit-hash>```
Old implementation preserved in git history.
---
## Next Steps
1. β
Code refactor complete2. βοΈ Test with `--num-bugs 2 --debug`3. βοΈ Verify "X/6 tests caught bug" in logs4. βοΈ Run full test with 5 bugs5. βοΈ Compare metrics vs old approach
---
## Credits
**Concept**: User's revolutionary insight - "generate tests first, then inject bug" **Implementation**: Complete architectural refactor of saboteur.py **Philosophy**: Guarantee test quality through execution validation, not hope12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# Render Deployment Guide
## Quick Start
1. **Push to GitHub** (if not already): ```bash git add . git commit -m "Add login system and Render support" git push origin main ```
2. **Create Render Account**: - Go to [render.com](https://render.com) - Sign up with GitHub
3. **Deploy**: - Click "New +" β "Web Service" - Connect your GitHub repository - Render will auto-detect `render.yaml` - Click "Create Web Service"
4. **Optional: Add API Key for Local Users**: - Go to Environment tab - Add `OPENAI_API_KEY` if you want local development without login - Leave empty to require all users to login with their own keys
## How It Works
- **With API key in .env**: Login page is skipped (local development)- **Without API key**: Users see login page and provide their own OpenAI API key- **Logout button**: Appears after login, allows switching accounts
## Files for Render
- `app.py` - Main entry point for hosted environment- `render.yaml` - Render configuration (includes git installation)- `Aptfile` - System packages (git required for cloning repos)- `requirements.txt` - Python dependencies- `start.sh` - Alternative startup script
## Important: Git Requirement
This project clones GitHub repositories dynamically at runtime using GitPython. The `Aptfile` ensures git is installed in the Render container.
## Environment Variables
- `PORT` - Automatically set by Render (default: 10000)- `OPENAI_API_KEY` - Optional, only for skipping login page
## Cost Notes
When users provide their own API keys:- Each user pays for their own OpenAI usage- Your hosting cost is only Render's free tier (or paid plan)- No surprise OpenAI bills!
## Testing Locally
Test the hosted mode (with login page):```bash# Temporarily rename .env to disable auto-detectionmv .env .env.backuppython app.py# Restore .env when donemv .env.backup .env```
## Troubleshooting
**Login page not showing?**- Check that `OPENAI_API_KEY` is NOT set in Render environment
**"API key valid but no quota"?**- User needs to add credits to their OpenAI account at platform.openai.com/billing
**"git: command not found" or clone errors?**- Ensure `Aptfile` is committed to your repo- Render should automatically install git from Aptfile- Check build logs to verify git installation
**Timeout errors?**- Render free tier may timeout on long operations (cloning + bug injection can take 1-2 min)- Consider upgrading to paid plan for production use- Free tier has 15-minute request timeout123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106# π Render Deployment Fix
## ΧΧΧ’ΧΧRender ΧΧΧ©ΧΧ ΧΧΧ¨ΧΧ₯ `gunicorn app:app` ΧΧΧ gunicorn ΧΧ ΧΧΧͺΧ§Χ (ΧΧ‘Χ¨Χ Χ ΧΧΧͺΧ).
## β
ΧΧ€ΧͺΧ¨ΧΧ (3 ΧΧ§ΧΧͺ)
### ΧΧΧ€Χ¦ΧΧ 1: Χ’ΧΧΧΧ ΧΧΧ Χ (ΧΧΧΧ¨!)
1. **ΧΧ Χ-Render Dashboard** β ΧΧΧ¨ ΧΧͺ ΧΧ©ΧΧ¨ΧΧͺ Χ©ΧΧ
2. **Settings** β **Build & Deploy**
3. **Start Command** - ΧΧΧΧ£ Χ: ```bash uvicorn app:app --host 0.0.0.0 --port $PORT ```
4. **Save Changes**
5. **Manual Deploy** β **Deploy latest commit**
---
### ΧΧΧ€Χ¦ΧΧ 2: ΧΧΧΧ§Χ ΧΧΧ¦ΧΧ¨Χ ΧΧΧΧ© (Χ Χ§Χ!)
#### Χ©ΧΧ 1: ΧΧΧ§ ΧΧͺ ΧΧ©ΧΧ¨ΧΧͺ ΧΧΧ©Χ- Settings β Danger Zone β **Delete Web Service**
#### Χ©ΧΧ 2: Χ¦ΧΧ¨ Χ©ΧΧ¨ΧΧͺ ΧΧΧ©1. **New** β **Web Service**2. **Repository**: `refaelz1/LegacyInterview`3. **Name**: `legacy-code-challenge`4. **Runtime**: Python 35. **Build Command**: ```bash apt-get update && apt-get install -y git && pip install -r requirements.txt ```6. **Start Command**: ```bash uvicorn app:app --host 0.0.0.0 --port $PORT ```7. **Environment Variables**: - `PORT` = `10000` - `OPENAI_API_KEY` = (leave empty - users will provide)
8. **Create Web Service**
---
## π ΧΧ ΧΧΧΧ¨ ΧΧ§Χ¨ΧΧͺ ΧΧΧ¨Χ ΧΧͺΧΧ§ΧΧ
### Build Logs:```==> Installing dependencies from ./requirements.txtCollecting uvicorn[standard] β Installed uvicorn successfully==> Build successful π```
### Deploy Logs:```==> Deploying...==> Running 'uvicorn app:app --host 0.0.0.0 --port $PORT'π Starting Legacy Code Challenge on port 10000...π No API key found β login page will be shownINFO: Started server process [68]INFO: Waiting for application startup.INFO: Application startup complete.INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit)==> Your service is live π```
---
## π§ͺ ΧΧΧΧ§Χ
1. Χ€ΧͺΧ ΧΧͺ Χ-URL Χ©Render Χ ΧͺΧ ΧΧ2. ΧΧΧΧ¨ ΧΧ¨ΧΧΧͺ **Login Page** Χ’Χ: - Χ©ΧΧ "Your Name" - Χ©ΧΧ "OpenAI API Key" - ΧΧ€ΧͺΧΧ¨ "Continue"
3. ΧΧ ΧΧͺΧ ΧΧ§ΧΧΧ (.env Χ’Χ API key), ΧͺΧ¨ΧΧ ΧΧ©Χ¨ ΧΧͺ **Setup Page**
---
## βοΈ Χ§ΧΧ¦ΧΧ Χ¨ΧΧΧΧ ΧΧΧΧ
- `requirements.txt` - ΧΧΧΧ `uvicorn[standard]`- `app.py` - ΧΧΧ©Χ£ `app = demo.app` Χuvicorn- `Procfile` - `web: uvicorn app:app --host 0.0.0.0 --port $PORT`- `render.yaml` - ΧΧΧΧ¨ΧΧͺ ΧΧΧΧΧΧΧΧΧͺ (ΧΧΧ Render ΧΧͺΧ’ΧΧ ΧΧΧ ΧΧ€Χ’ΧΧΧ)
---
## π Troubleshooting
### Χ©ΧΧΧΧ: `bash: uvicorn: command not found`**Χ€ΧͺΧ¨ΧΧ**: Clear build cache Χ-Settings
### Χ©ΧΧΧΧ: `TypeError: FastAPI.__call__() missing 1 required positional argument`**Χ€ΧͺΧ¨ΧΧ**: ΧΧͺΧ Χ’ΧΧΧΧ ΧΧ¨ΧΧ₯ gunicorn - Χ’ΧΧΧ Start Command!
### Χ©ΧΧΧΧ: `git: command not found`**Χ€ΧͺΧ¨ΧΧ**: ΧΧΧ‘Χ£ `apt-get update && apt-get install -y git` Χ-Build Command123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159# ΧΧΧ¨ΧΧΧͺ ΧΧ’ΧΧΧ ΧΧΧΧ Χ-Render Χ’Χ Google Sheets## =====================================================
## Χ©ΧΧ 1: ΧΧΧ Χͺ Google Cloud (Χ€Χ’Χ ΧΧΧͺ)
### 1.1 ΧΧ¦ΧΧ¨Χͺ Service AccountΧ’Χ§ΧΧ ΧΧΧ¨Χ [GOOGLE_SHEETS_SETUP.md](GOOGLE_SHEETS_SETUP.md) Χ’Χ Χ‘ΧΧ£ Χ©ΧΧ 4:- Χ¦ΧΧ¨ Google Cloud Project- ΧΧ€Χ’Χ Google Sheets API- Χ¦ΧΧ¨ Service Account- ΧΧΧ¨Χ ΧΧͺ `google-service-account.json`
πΎ **Χ©ΧΧΧ¨ ΧΧͺ ΧΧ§ΧΧΧ₯ ΧΧΧΧ©Χ Χ©ΧΧ** (ΧΧ ΧΧ€Χ¨ΧΧΧ§Χ! ΧΧ ΧΧ Χ¦Χ¨ΧΧ ΧΧΧΧΧͺ Χ-git)
### 1.2 ΧΧ¦ΧΧ¨Χͺ Google Sheet1. Χ€ΧͺΧ: https://docs.google.com/spreadsheets2. Χ¦ΧΧ¨ ΧΧΧΧΧΧ ΧΧΧ© ΧΧ©Χ: **"Legacy Code Submissions"**3. **ΧΧ’ΧͺΧ§ ΧΧͺ Χ-Sheet ID** ΧΧ-URL: ``` https://docs.google.com/spreadsheets/d/1abc123...xyz/edit ^^^^^^^^^^^^^^^^ ΧΧ Χ-Sheet ID - ΧͺΧ¦ΧΧ¨Χ ΧΧΧͺΧ! ```
### 1.3 Χ©ΧΧͺΧΧ£ ΧΧΧΧΧΧΧ1. ΧΧΧ₯ **Share** ΧΧΧΧΧΧΧ2. ΧΧΧ‘Χ£ ΧΧͺ Χ-Service Account email ΧΧͺΧΧ `google-service-account.json`: - Χ€ΧͺΧ ΧΧͺ ΧΧ§ΧΧΧ₯ - ΧΧ€Χ© ΧΧͺ `"client_email"` (ΧΧ©ΧΧ ΧΧΧ `xxx@xxx.iam.gserviceaccount.com`) - ΧΧΧΧ§ ΧΧΧͺΧ ΧΧ©ΧΧͺΧΧ£3. ΧͺΧ ΧΧ **Editor** permissions4. Send
---
## Χ©ΧΧ 2: ΧΧ’ΧΧΧͺ ΧΧ§ΧΧ Χ-Git (ΧΧ Χ’ΧΧΧΧ ΧΧ)
```bashgit add -Agit commit -m "Add Google Sheets integration"git push```
β οΈ **ΧΧΧΧ§ Χ©ΧΧ§ΧΧ¦ΧΧ ΧΧΧΧΧ ΧΧ ΧΧΧ’ΧΧ:**- `.env` - `google-service-account.json`- `workspaces/`
(ΧΧ Χ ΧΧ Χ‘Χ - ΧΧΧΧ¨ ΧΧ ΧΧΧ Χ ΧΧ’ΧΧΧ¨ ΧΧΧ‘ΧΧ¨ ΧΧΧͺΧ)
---
## Χ©ΧΧ 3: ΧΧΧΧ¨ΧΧͺ Χ-Render Dashboard
### 3.1 Secret Files (ΧΧ’ΧΧΧͺ google-service-account.json)
1. Χ€ΧͺΧ ΧΧͺ Render Dashboard2. ΧΧΧ¨ ΧΧͺ Χ-Service Χ©ΧΧ (LegacyInterview)3. ΧΧΧ₯ Χ’Χ **Settings** ΧΧͺΧ€Χ¨ΧΧ Χ©ΧΧΧ4. ΧΧΧΧ Χ-**Secret Files**5. ΧΧΧ₯ **Add Secret File**6. ΧΧΧ: ``` Filename: google-service-account.json Contents: [Χ€ΧͺΧ ΧΧͺ ΧΧ§ΧΧΧ₯ ΧΧΧΧ©Χ ΧΧΧ’ΧͺΧ§ ΧΧͺ ΧΧ ΧΧͺΧΧΧ ΧΧΧΧ] ```7. ΧΧΧ₯ **Save Changes**
### 3.2 Environment Variables (ΧΧΧΧ¨Χͺ Sheet ID)
1. ΧΧΧΧͺΧ Settings, ΧΧΧΧ Χ-**Environment Variables**2. ΧΧΧ₯ **Add Environment Variable**3. ΧΧΧ‘Χ£ ΧΧͺ ΧΧ©Χ ΧΧΧ ΧΧΧΧΧ:
```Key: OPENAI_API_KEYValue: sk-proj-... (ΧΧΧ€ΧͺΧ Χ©ΧΧ)
Key: GOOGLE_SHEET_ID Value: 1abc123...xyz (Χ-Sheet ID Χ©ΧΧ’ΧͺΧ§Χͺ ΧΧ©ΧΧ 1.2)```
4. ΧΧΧ₯ **Save Changes**
### 3.3 Deploy
Render ΧΧ’Χ©Χ **Auto-Deploy** ΧΧΧΧΧΧΧ ΧΧΧ¨Χ ΧΧ©ΧΧΧ¨Χ.
ΧΧ ΧΧ - ΧΧΧ₯ **Manual Deploy** β **Deploy latest commit**
---
## Χ©ΧΧ 4: ΧΧΧΧ§Χ Χ©ΧΧΧ Χ’ΧΧΧ
### 4.1 ΧΧΧ Χ-Deploy- Χ’Χ§ΧΧ ΧΧΧ¨Χ Χ-Logs Χ-Render- ΧΧΧ Χ’Χ Χ©ΧͺΧ¨ΧΧ: "Running on public URL..."
### 4.2 Χ€ΧͺΧ ΧΧͺ ΧΧΧͺΧ¨- ΧΧΧ₯ Χ’Χ Χ-URL (ΧΧΧ©Χ: `https://your-app.onrender.com`)- ΧΧͺΧΧΧ¨ Χ’Χ Χ-OpenAI API key Χ©ΧΧ- Χ¦ΧΧ¨ challenge ΧΧ‘ΧΧΧ ΧΧΧͺΧ
### 4.3 ΧΧΧΧ§ ΧΧͺ Google Sheets- Χ€ΧͺΧ ΧΧͺ ΧΧΧΧΧΧΧ Χ©ΧΧ¦Χ¨Χͺ- ΧΧΧ¨Χ Submit - ΧͺΧ¨ΧΧ Χ©ΧΧ¨Χ ΧΧΧ©Χ Χ’Χ: - Χ©Χ ΧΧ‘ΧΧΧΧ Χ - ΧͺΧΧ¨ΧΧ ΧΧ©Χ’Χ - ΧΧΧΧ Χ©ΧΧΧ¨ - Χ¦ΧΧΧ - ΧΧ ΧΧΧͺΧΧͺΧΧΧͺ - ΧΧ§ΧΧ
---
## Χ€ΧͺΧ¨ΧΧ ΧΧ’ΧΧΧͺ
### ΧΧ ΧΧ Χ Χ©ΧΧ¨ ΧΧΧΧΧΧΧ:1. ΧΧΧΧ§ ΧΧͺ Render Logs: - Settings β Logs - ΧΧ€Χ©: "Google Sheets"2. ΧΧ’ΧΧΧͺ Χ Χ€ΧΧ¦ΧΧͺ: - β Sheet ID ΧΧ Χ ΧΧΧ β ΧΧΧΧ§ Χ-Environment Variables - β Service Account ΧΧ Χ©ΧΧͺΧ£ β ΧΧΧΧ§ Share permissions - β JSON file ΧΧ Χ§ΧΧΧ β ΧΧΧΧ§ Secret Files
### ΧΧΧ ΧΧ¨ΧΧΧͺ Logs:```Render Dashboard β Your Service β Logs (ΧͺΧ€Χ¨ΧΧ Χ©ΧΧΧ)```
---
## Χ‘ΧΧΧΧ - ΧΧ Χ¦Χ¨ΧΧ ΧΧΧΧΧͺ ΧΧΧ€Χ:
| ΧΧ | ΧΧΧ€Χ ||-----|------|| ΧΧ§ΧΧ (Python files) | Git β Render ΧΧΧ¨ΧΧ ΧΧΧΧΧΧΧΧͺ || `google-service-account.json` | Render Secret Files (ΧΧ Χ-git!) || `GOOGLE_SHEET_ID` | Render Environment Variables || `OPENAI_API_KEY` | Render Environment Variables || Google Sheet | ΧΧΧ©ΧΧΧ Google Χ©ΧΧ |
---
## ΧΧ Χ§ΧΧ¨Χ ΧΧ€ΧΧ’Χ:
1. Χ‘ΧΧΧΧ Χ Χ ΧΧ Χ‘ Χ-URL Χ©Χ Render2. Χ’ΧΧ©Χ ΧΧͺ ΧΧΧͺΧΧ¨3. ΧΧΧΧ₯ Submit4. **ΧΧ§ΧΧ Χ©ΧΧ Χ Χ©ΧΧΧ¨ ΧΧΧΧΧΧΧΧͺ Χ-Google Sheets**5. **ΧΧͺΧ Χ¨ΧΧΧ ΧΧΧ ΧΧΧΧΧΧΧ ΧΧΧΧ ΧΧΧͺ** π
---
## ΧΧ ΧΧΧ! π
ΧΧΧ¨Χ ΧΧΧΧΧ¨Χ ΧΧΧΧͺ Χ€Χ’Χ ΧΧΧͺ - **ΧΧΧ ΧΧΧΧΧΧΧ**.ΧΧ submission ΧΧ©ΧΧ¨ ΧΧΧΧΧΧΧ ΧΧΧͺΧ ΧͺΧΧΧ ΧΧ’Χ§ΧΧ ΧΧΧ¨Χ ΧΧ ΧΧ‘ΧΧΧΧ ΧΧΧ.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242# ΧΧΧ‘Χ€Χͺ Login Page + Logout Button
## Χ©ΧΧ 1: ΧΧΧ‘Χ£ Χ€ΧΧ Χ§Χ¦ΧΧΧͺ validation
ΧΧΧ‘Χ£ ΧΧͺ ΧΧ§ΧΧ ΧΧΧ **ΧΧͺΧΧΧΧͺ** `student_interface.py`, ΧΧΧ¨Χ Χ-imports:
```pythondef validate_openai_key(api_key: str) -> tuple[bool, str]: """Validate OpenAI API key by making a test call.""" import os if not api_key or not api_key.startswith("sk-"): return False, "β Invalid API key format. Must start with 'sk-'" try: os.environ["OPENAI_API_KEY"] = api_key from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o", temperature=0, request_timeout=10, max_tokens=5) llm.invoke("test") return True, "β
API key validated!" except Exception as e: error = str(e) if "401" in error or "Incorrect API key" in error: return False, "β Invalid API key" elif "quota" in error.lower(): return False, "β οΈ API key valid but no quota" return True, f"β
Key accepted"```
---
## Χ©ΧΧ 2: Χ©Χ Χ ΧΧͺ `create_full_interface()`
**ΧΧΧΧ£ ΧΧͺ ΧΧΧΧΧ¨Χ Χ©Χ ΧΧ€ΧΧ Χ§Χ¦ΧΧ:**
```pythondef create_full_interface() -> gr.Blocks: """ Returns a Gradio app with login page (if needed) + challenge interface. """ import os # Auto-detect: ΧΧ© API key Χ-.env? has_env_key = bool(os.getenv("OPENAI_API_KEY")) css = """ /* ... ΧCSS ΧΧ§ΧΧΧ ... */ /* Logout button in corner */ #logout-btn { position: absolute; top: 20px; right: 20px; z-index: 1000; } """ with gr.Blocks(title="Legacy Code Challenge", css=css) as demo: # State user_api_key_state = gr.State("") user_name_state = gr.State("") workspace_state = gr.State("") hints_used_state = gr.State(0) submission_count_state = gr.State(0) hint_log_state = gr.State([]) confirmation_pending_state = gr.State(False) timer_trigger = gr.Number(value=0, visible=False) # Logout button (hidden until logged in) with gr.Row(): gr.HTML("") # spacer logout_btn = gr.Button("π Logout", visible=False, elem_id="logout-btn", size="sm") # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ # PAGE 0 β Login (hidden if .env exists) # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(visible=not has_env_key, elem_classes=["setup-card"]) as login_page: gr.Markdown( "# π Welcome to Legacy Code Challenge\n" "### Please enter your details to continue" ) login_name = gr.Textbox( label="Your Name", placeholder="e.g. Alice Smith", ) login_api_key = gr.Textbox( label="OpenAI API Key", placeholder="sk-proj-...", type="password", info="Get one at platform.openai.com/api-keys", ) gr.Markdown( "β οΈ **Note:** Your API key is only used for this session and consumes credits from your OpenAI account" ) login_btn = gr.Button("π Continue", variant="primary", size="lg") login_status = gr.Markdown("") # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ # PAGE 1 β Setup (visible if .env exists, else hidden) # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(visible=has_env_key, elem_classes=["setup-card"]) as setup_page: gr.Markdown( "# π Legacy Code Challenge\n" "Fill in the details below, then click **Start Challenge**." ) # ΧΧ©ΧΧ¨ ΧΧͺ ΧΧ Χ-setup page ΧΧΧ Χ©ΧΧΧ... name_box = gr.Textbox(...) url_box = gr.Textbox(...) # ... Χ©ΧΧ¨ ΧΧ©ΧΧΧͺ```
---
## Χ©ΧΧ 3: ΧΧΧ‘Χ£ callbacks
**ΧΧΧ‘Χ£ ΧΧ‘ΧΧ£ ΧΧ€ΧΧ Χ§Χ¦ΧΧ, ΧΧ€Χ Χ `return demo`:**
```python # ββ Login callback ββββββββββββββββββββββββββββββββββββββββββββββββ def on_login(name, api_key): if not name.strip(): return ( gr.update(), # login page stays gr.update(), # setup page hidden gr.update(), # logout hidden "β Please enter your name", "", "" # states empty ) valid, msg = validate_openai_key(api_key) if not valid: return ( gr.update(), gr.update(), gr.update(), msg, "", "" ) # Success! import os os.environ["OPENAI_API_KEY"] = api_key return ( gr.update(visible=False), # hide login gr.update(visible=True), # show setup gr.update(visible=True), # show logout msg, api_key, # save to state name.strip() ) login_btn.click( on_login, inputs=[login_name, login_api_key], outputs=[login_page, setup_page, logout_btn, login_status, user_api_key_state, user_name_state], ) # ββ Logout callback βββββββββββββββββββββββββββββββββββββββββββββββ def on_logout(): import os if "OPENAI_API_KEY" in os.environ: del os.environ["OPENAI_API_KEY"] return ( gr.update(visible=True), # show login gr.update(visible=False), # hide setup gr.update(visible=False), # hide challenge gr.update(visible=False), # hide results gr.update(visible=False), # hide logout "", "", "", 0, 0, [] # clear states ) logout_btn.click( on_logout, outputs=[login_page, setup_page, challenge_page, results_page, logout_btn, user_api_key_state, user_name_state, workspace_state, hints_used_state, submission_count_state, hint_log_state], )```
---
## Χ©ΧΧ 4: Χ’ΧΧΧ ΧΧͺ on_start
**Χ©Χ Χ ΧΧͺ ΧΧ©ΧΧ¨Χ ΧΧ¨ΧΧ©ΧΧ Χ Χ©Χ `on_start`:**
```python# ΧΧ€Χ Χ:def on_start(name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins):
# ΧΧΧ¨Χ:def on_start(saved_name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins, has_env):```
**ΧΧ’ΧΧΧ ΧΧͺ ΧΧ©ΧΧ¨Χ Χ©ΧΧ©ΧͺΧΧ©Χͺ ΧΧ©Χ:**
```python# ΧΧ€Χ Χ:name_str = name.strip()
# ΧΧΧ¨Χ:name_str = saved_name.strip() if saved_name else "Student"```
**ΧΧ’ΧΧΧ ΧΧͺ Χ-click:**
```pythonstart_btn.click( on_start, inputs=[ user_name_state if not has_env_key else name_box, # ΧΧ local - name_box, ΧΧ hosted - state url_box, nesting_slider, bugs_slider, refactoring_check, debug_check, timer_slider, gr.State(has_env_key) # ΧΧΧ ΧΧ local ΧΧ hosted ], outputs=[...],)```
---
## ΧΧͺΧΧ¦ΧΧ:
β
**Local (.env exists):**- ΧΧ Χ¨ΧΧΧ login page- ΧΧ©Χ¨ Χsetup page- ΧΧΧ logout button (ΧΧ Χ¦Χ¨ΧΧ)
β
**Hosted (no .env):**- Χ¨ΧΧΧ login page- Χ¦Χ¨ΧΧ ΧΧΧΧΧ API key- ΧΧ© logout button ΧΧ€ΧΧ Χ- ΧΧΧ¨Χ logout ΧΧΧΧ¨ Χ-login
---
Χ¨ΧΧ¦Χ Χ©ΧΧ’Χ©Χ ΧΧͺ ΧΧ©ΧΧ ΧΧΧΧ ΧΧ’Χ¦ΧΧ ΧΧ§ΧΧ? π1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""app.py β Simplified entry point for hosting platforms (Render, Hugging Face, etc.)
This file launches the full interface with login page support.No API key required β users provide their own via the login page.
IMPORTANT: This is a Gradio application, NOT a WSGI app.Do not use gunicorn! Run directly with: python app.py"""
import osfrom dotenv import load_dotenv
# Load .env if it exists (for local development)load_dotenv()
# Apply proxy settings from .env if definedif os.getenv("http_proxy"): os.environ["http_proxy"] = os.getenv("http_proxy")if os.getenv("https_proxy"): os.environ["https_proxy"] = os.getenv("https_proxy")if os.getenv("no_proxy"): os.environ["no_proxy"] = os.getenv("no_proxy")
import gradio as grimport student_interface
def main() -> None: """Launch the full interface with auto-detected login page.""" port = int(os.getenv("PORT", "7860")) has_key = bool(os.getenv("OPENAI_API_KEY")) print(f"\nπ Starting Legacy Code Challenge on port {port}...") print(f"π Server will listen on 0.0.0.0:{port}") if has_key: print("β
API key detected in environment β skipping login page") else: print("π No API key found β login page will be shown") demo = student_interface.create_full_interface() print(f"π Launching Gradio on 0.0.0.0:{port}...") demo.launch( server_name="0.0.0.0", # Listen on all interfaces for hosting server_port=port, share=False, # Render provides its own URL inbrowser=False, # Don't open browser on server show_error=True, # Show detailed errors in Render logs ) print("β
Gradio server started successfully!")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257import osimport stat
from architect.state import ArchitectState
def _module_import_path(clone_path: str, target_file: str) -> str: """Convert an absolute file path to a dotted module path relative to clone_path.""" rel = os.path.relpath(target_file, clone_path) # e.g. utils/math_utils.py without_ext = os.path.splitext(rel)[0] # e.g. utils/math_utils module_path = without_ext.replace(os.sep, ".") # e.g. utils.math_utils return module_path
def deploy_challenge(state: ArchitectState) -> ArchitectState: clone_path = state["clone_path"] target_file = state["target_file"] module_path = _module_import_path(clone_path, target_file) # Get bug-specific data all_bug_data = state.get("all_bug_data") or [] bug_specific_tests = state.get("bug_specific_tests") or {} # If no per-bug data, fall back to old single-bug behavior if not all_bug_data: all_bug_data = [{ "function_name": state.get("function_name", "target_func"), "bug_description": state.get("bug_description", "Unknown bug") # Changed from bug_variant }] # Use the global tests public_tests = state.get("public_tests") or [] secret_tests = state.get("secret_tests") or [] if not public_tests and not secret_tests: all_tests = state.get("test_cases") or [] if not all_tests: all_tests = [{"args": state["test_args"], "expected": state["expected_output"]}] mid = len(all_tests) // 2 public_tests = all_tests[:mid] if mid > 0 else all_tests secret_tests = all_tests[mid:] if mid > 0 else [] func_name = all_bug_data[0]["function_name"] bug_specific_tests[func_name] = public_tests + secret_tests # Split tests for each bug into public/secret bugs_with_tests = [] for bug in all_bug_data: func_name = bug["function_name"] all_tests = bug_specific_tests.get(func_name) or [] # Skip bugs with no tests (shouldn't happen, but be safe) if not all_tests: continue # All tests now detect the bug (only detecting tests are saved) # Split: first 5 tests to public, rest to secret (max 5 each) public = all_tests[:5] if len(all_tests) >= 5 else all_tests secret = all_tests[5:10] if len(all_tests) > 5 else [] bugs_with_tests.append({ "function_name": func_name, "bug_description": bug.get("bug_description", ""), "public_tests": public, "secret_tests": secret }) def _build_multi_bug_test_file(bugs: list, test_type: str = "public") -> str: """Build a test file with separate sections for each bug.""" # Helper to format test cases def format_tests(tests): case_lines = [] for tc in tests: args_repr = tc.get("args", "()") exp_value = tc.get("expected") if "expected" in tc else tc.get("correct_output") if exp_value is None: exp_repr = "None" elif isinstance(exp_value, str): # Already a string β validate it's a valid Python literal try: eval(exp_value, {"__builtins__": {}}) exp_repr = exp_value except Exception: exp_repr = repr(exp_value) else: # Already a Python object (int, list, tuple, boolβ¦) exp_repr = repr(exp_value) # Handle tuple formatting args_str = args_repr.strip() try: evaluated = eval(args_str) if not isinstance(evaluated, tuple): args_str = f"({args_str},)" except: pass case_lines.append(f" ({args_str}, {exp_repr}),") return "\n".join(case_lines) if case_lines else " # No tests" # Build imports section imports = [] for bug in bugs: func = bug["function_name"] imports.append(f"from {module_path} import {func}") imports_str = "\n".join(imports) # Build test sections for each bug bug_sections = [] test_functions = [] for i, bug in enumerate(bugs, 1): func = bug["function_name"] tests = bug.get(f"{test_type}_tests", []) bug_desc = bug.get("bug_description", "") # Changed from bug_variant # Test cases for this bug cases_literal = format_tests(tests) # Create test function for this bug bug_sections.append( f"# ===== Bug #{i}: {func} =====\n" f"# {bug_desc}\n" f"_BUG{i}_TESTS = [\n{cases_literal}\n]\n" ) test_functions.append( f"def test_bug{i}():\n" f" \"\"\"Test Bug #{i}: {func}\"\"\"\n" f" print(f'\\n===== Testing Bug #{i}: {func} =====')\n" f" passed = crashed = 0\n" f" for j, (args, expected) in enumerate(_BUG{i}_TESTS, 1):\n" f" try:\n" f" result = {func}(*args)\n" f" ok = result == expected\n" f" status = '[PASS]' if ok else '[FAIL]'\n" f" passed += ok\n" f" print(f' Test {{j}}: {{status}}')\n" f" if not ok:\n" f" print(f' args = {{args!r}}')\n" f" print(f' expected = {{expected}}')\n" f" print(f' got = {{result}}')\n" f" except Exception as exc:\n" f" crashed += 1\n" f" print(f' Test {{j}}: [CRASH] - {{type(exc).__name__}}: {{exc}}')\n" f" print(f' args = {{args!r}}')\n" f" \n" f" total = len(_BUG{i}_TESTS)\n" f" return passed, crashed, total\n" ) # Build main runner bug_calls = [] for i in range(1, len(bugs) + 1): bug_calls.append(f" p{i}, c{i}, t{i} = test_bug{i}()") total_calc = " + ".join([f"t{i}" for i in range(1, len(bugs) + 1)]) passed_calc = " + ".join([f"p{i}" for i in range(1, len(bugs) + 1)]) crashed_calc = " + ".join([f"c{i}" for i in range(1, len(bugs) + 1)]) main_runner = ( "def run_all_tests():\n" " \"\"\"Run tests for all bugs.\"\"\"\n" + "\n".join(bug_calls) + "\n" f" \n" f" total = {total_calc}\n" f" passed = {passed_calc}\n" f" crashed = {crashed_calc}\n" f" broken = total - passed\n" f" \n" f" print(f'\\n=========================================')\n" f" if passed == total:\n" f" print(f'=== ALL TESTS PASSED ({{passed}}/{{total}}) ===')\n" f" return True\n" f" elif crashed == total:\n" f" print(f'=== ALL TESTS CRASHED ({{crashed}}/{{total}}) ===')\n" f" return False\n" f" else:\n" f" print(f'=== {{broken}}/{{total}} tests failed ({{crashed}} crash, {{broken-crashed}} wrong) ===')\n" f" return False\n" ) # Combine everything return ( "import sys\n" "import os\n\n" "# Ensure UTF-8 output on Windows\n" "if hasattr(sys.stdout, 'reconfigure'):\n" " sys.stdout.reconfigure(encoding='utf-8')\n\n" "# Make the repo root importable (works from workspace root or .metadata/)\n" "_here = os.path.dirname(os.path.abspath(__file__))\n" "sys.path.insert(0, _here)\n" "sys.path.insert(0, os.path.dirname(_here))\n\n" f"{imports_str}\n\n" f"# {test_type.upper()} TEST CASES\n\n" + "\n".join(bug_sections) + "\n" + "\n".join(test_functions) + "\n" + main_runner + "\n" "if __name__ == '__main__':\n" " run_all_tests()\n" ) # Create public test file challenge_run_path = os.path.join(clone_path, "challenge_run.py") public_content = _build_multi_bug_test_file(bugs_with_tests, "public") with open(challenge_run_path, "w", encoding="utf-8") as f: f.write(public_content) total_public = sum(len(b["public_tests"]) for b in bugs_with_tests) print(f"[deployer] Written: {challenge_run_path} ({total_public} public tests across {len(bugs_with_tests)} bugs)") # Create secret test file secret_run_path = os.path.join(clone_path, "challenge_run_secret.py") secret_content = _build_multi_bug_test_file(bugs_with_tests, "secret") with open(secret_run_path, "w", encoding="utf-8") as f: f.write(secret_content) total_secret = sum(len(b["secret_tests"]) for b in bugs_with_tests) print(f"[deployer] Written: {secret_run_path} ({total_secret} secret tests across {len(bugs_with_tests)} bugs)") # Write detailed explanation for instructor detailed_path = os.path.join(clone_path, "detailed_explanation.txt") with open(detailed_path, "w", encoding="utf-8") as f: f.write(state.get("detailed_explanation", "No detailed explanation available.")) print(f"[deployer] Written: {detailed_path}")
# ββ .metadata/ directory ββββοΏ½οΏ½βββββββββββββββββββββββββββββββββββββββββββββ # Contains the sabotaged-file snapshot AND the secret test file. # Hidden + read-only so students cannot accidentally access or overwrite them. metadata_dir = os.path.join(clone_path, ".metadata") os.makedirs(metadata_dir, exist_ok=True)
# 1. Copy secret test file to hidden .metadata directory secret_metadata_path = os.path.join(metadata_dir, "challenge_run_secret.py") if os.path.exists(secret_metadata_path): os.chmod(secret_metadata_path, stat.S_IWRITE) with open(secret_metadata_path, "w", encoding="utf-8") as f: f.write(secret_content) os.chmod(secret_metadata_path, stat.S_IREAD | stat.S_IRGRP | stat.S_IROTH) print(f"[deployer] Copied to metadata: {secret_metadata_path}")
# 2. Snapshot of every file the saboteur touched target_file = state.get("target_file", "") sabotaged_code = state.get("sabotaged_code", "") if target_file and sabotaged_code: rel = os.path.relpath(target_file, clone_path) # e.g. boltons/strutils.py snap_path = os.path.join(metadata_dir, rel.replace(os.sep, "__")) if os.path.exists(snap_path): os.chmod(snap_path, stat.S_IWRITE) with open(snap_path, "w", encoding="utf-8") as f: f.write(sabotaged_code) os.chmod(snap_path, stat.S_IREAD | stat.S_IRGRP | stat.S_IROTH) print(f"[deployer] Snapshot: {snap_path}")
# Hide the whole .metadata directory on Windows try: import subprocess as _sp _sp.run(["attrib", "+H", "+R", metadata_dir], check=False, capture_output=True) except Exception: pass
return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257import astimport osimport randomfrom typing import Dict, List, Set, Tuple
from architect.state import ArchitectState
SKIP_DIRS = {"__pycache__", ".git", ".tox", "venv", "env", "node_modules", "migrations", "tests", "test", "spec", "specs"}SKIP_FILES = {"setup.py", "conftest.py"}
_UTILITY_HINTS = ("util", "math", "string", "str", "num", "convert", "parse", "calc", "format", "helper", "algo", "numeric", "text", "encode")
# How many top-scoring files to randomly sample from_TOP_N_FILES = 3
def _analyze_call_graph(tree: ast.Module) -> Dict[str, Set[str]]: """ Build a call graph: for each function, which other functions does it call? Returns: {func_name: set_of_called_functions} """ call_graph: Dict[str, Set[str]] = {} # First pass: collect all function names all_functions: Set[str] = set() for node in ast.walk(tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): if not node.name.startswith("_"): # Skip private functions all_functions.add(node.name) # Second pass: for each function, find what it calls for node in tree.body: if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): continue if node.name.startswith("_"): continue called_funcs: Set[str] = set() for child in ast.walk(node): if isinstance(child, ast.Call): # Direct function call if isinstance(child.func, ast.Name) and child.func.id in all_functions: called_funcs.add(child.func.id) # Attribute call (obj.method) - check if method name is a known function elif isinstance(child.func, ast.Attribute) and child.func.attr in all_functions: called_funcs.add(child.func.attr) call_graph[node.name] = called_funcs return call_graph
def _compute_max_depth(func: str, call_graph: Dict[str, Set[str]], visited: Set[str] = None) -> int: """ Compute the maximum call-chain depth from this function. Depth 1 = leaf function (calls no other functions in this file) Depth 2 = calls a leaf function Etc. """ if visited is None: visited = set() if func in visited: # Circular dependency return 1 if func not in call_graph: return 1 called = call_graph[func] if not called: # Leaf function return 1 visited.add(func) max_child_depth = max( (_compute_max_depth(child, call_graph, visited.copy()) for child in called), default=0 ) return max_child_depth + 1
def _get_functions_by_depth(source: str) -> List[Tuple[str, int, List[str]]]: """ Analyze all functions and return: [(func_name, depth, call_chain), ...] Sorted by depth descending. """ try: tree = ast.parse(source) except SyntaxError: return [] call_graph = _analyze_call_graph(tree) results: List[Tuple[str, int, List[str]]] = [] for func_name in call_graph: depth = _compute_max_depth(func_name, call_graph) # Build a sample call chain (simplified - just one path) chain = [func_name] current = func_name for _ in range(depth - 1): called = call_graph.get(current, set()) if not called: break # Pick one called function for the chain next_func = next(iter(called)) chain.append(next_func) current = next_func results.append((func_name, depth, chain)) results.sort(key=lambda x: x[1], reverse=True) return results
def _count_module_level_primitive_functions(tree: ast.Module) -> int: count = 0 for node in tree.body: if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): continue if node.name.startswith("_"): continue if node.end_lineno - node.lineno < 4: continue has_number = any(isinstance(n, ast.Constant) and isinstance(n.value, (int, float)) for n in ast.walk(node)) has_binop = any(isinstance(n, ast.BinOp) for n in ast.walk(node)) has_loop = any(isinstance(n, (ast.For, ast.While)) for n in ast.walk(node)) has_return = any(isinstance(n, ast.Return) and n.value is not None for n in ast.walk(node)) if has_return and (has_number or has_binop or has_loop): count += 1 return count
def _score_file(path: str, target_nesting: int) -> Tuple[int, int]: """ Score a file for sabotage suitability. Returns: (score, max_nesting_depth) """ try: with open(path, encoding="utf-8", errors="ignore") as f: source = f.read() tree = ast.parse(source) except SyntaxError: return -1, 0
if len(source.splitlines()) < 20: return -1000, 0 # too short
# Pure data/config files with no functions can't be sabotaged func_count = sum(1 for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))) if func_count == 0: return -1000, 0
# Analyze nesting depth functions_by_depth = _get_functions_by_depth(source) max_depth = max((depth for _, depth, _ in functions_by_depth), default=0) if functions_by_depth else 0 score = 0 basename = os.path.basename(path).lower() if any(hint in basename for hint in _UTILITY_HINTS): score += 30
class_count = sum(1 for n in tree.body if isinstance(n, ast.ClassDef)) score -= class_count * 20
primitive_funcs = _count_module_level_primitive_functions(tree) score += primitive_funcs * 15 # Bonus for files with good nesting depth if max_depth >= target_nesting: score += 50 # Perfect match or better elif max_depth >= target_nesting - 1: score += 30 # Close enough elif max_depth >= 2: score += 10 # Has some nesting
for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: top = alias.name.split(".")[0] if top not in ("os", "sys", "math", "re", "collections", "itertools", "functools", "typing", "string", "random", "copy"): score -= 10 if isinstance(node, ast.ImportFrom): if node.level > 0: # Relative import (from .something import X) β file depends on package # structure; functions can't be exec-tested in isolation. score -= 25 else: top = (node.module or "").split(".")[0] if top not in ("os", "sys", "math", "re", "collections", "itertools", "functools", "typing", "string", "random", "copy", ""): score -= 5
return score, max_depth
def map_files(state: ArchitectState) -> ArchitectState: clone_path = state["clone_path"] target_nesting = state["nesting_level"] suitable_files: list[tuple[int, int, str]] = [] # (func_count, line_count, path)
for root, dirs, files in os.walk(clone_path): dirs[:] = [d for d in dirs if d not in SKIP_DIRS] for fname in files: if not fname.endswith(".py") or fname in SKIP_FILES: continue if fname.startswith("test_") or fname.endswith("_test.py"): continue full = os.path.join(root, fname) # Count functions and lines in file try: with open(full, encoding="utf-8", errors="ignore") as f: content = f.read() tree = ast.parse(content) func_count = sum(1 for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and not n.name.startswith("_") and not n.name.startswith("test")) line_count = len(content.splitlines()) # Only keep files with enough functions (at least 5 for multi-bug support) if func_count >= 5: suitable_files.append((func_count, line_count, full)) except: continue # Skip files that can't be parsed
if not suitable_files: raise RuntimeError("No suitable Python files found with enough functions in repository.")
# WEIGHTED RANDOM selection: longer files (more lines + more functions) have higher probability # Weight = func_count * line_count (favors large, complex files) weights = [func_count * (line_count / 100) for func_count, line_count, _ in suitable_files] chosen_func_count, chosen_line_count, chosen_path = random.choices(suitable_files, weights=weights, k=1)[0] # Build candidate files list for fallback (sorted by function count and line count) suitable_files.sort(key=lambda x: (x[0], x[1]), reverse=True) all_paths = [p for _, _, p in suitable_files] remaining = [p for p in all_paths if p != chosen_path] candidate_files = [chosen_path] + remaining
with open(chosen_path, encoding="utf-8", errors="ignore") as f: content = f.read()
debug_mode = state.get("debug_mode", False) if debug_mode: print(f"[mapper] Found {len(suitable_files)} suitable files (5+ functions each)") print(f"[mapper] WEIGHTED selection (longer files preferred): {chosen_path}") print(f"[mapper] Selected file: {chosen_func_count} functions, {chosen_line_count} lines") print(f"[mapper] {len(candidate_files)} total candidates available as fallback") state["target_file"] = chosen_path state["original_code"] = content state["candidate_files"] = candidate_files return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475from langgraph.graph import StateGraph, ENDfrom langchain_core.runnables import RunnableLambda
from architect.state import ArchitectStatefrom architect.nodes import ( node_clone_repo, node_map_files, node_sabotage_init, node_inflate_hierarchy, node_obfuscation_level_1, node_obfuscation_level_2, node_verify_sabotage, node_add_misleading_comments, node_overwrite_file, node_deploy, node_done,)
def _route_after_inflation(state: ArchitectState) -> str: """If refactoring enabled, apply obfuscation; otherwise skip to verify.""" if state["refactoring_enabled"]: return "obfuscation_level_1" return "verify_sabotage"
def build_graph() -> StateGraph: builder = StateGraph(ArchitectState)
# Phase 1: Environment & Discovery builder.add_node("clone_repo", RunnableLambda(node_clone_repo)) builder.add_node("map_files", RunnableLambda(node_map_files))
# Phase 2: Sabotage builder.add_node("sabotage_init", RunnableLambda(node_sabotage_init)) builder.add_node("inflate_hierarchy", RunnableLambda(node_inflate_hierarchy))
# Phase 3: Optional Refactoring (if enabled) builder.add_node("obfuscation_level_1", RunnableLambda(node_obfuscation_level_1)) builder.add_node("obfuscation_level_2", RunnableLambda(node_obfuscation_level_2))
# Phase 4: Verification & Deployment builder.add_node("verify_sabotage", RunnableLambda(node_verify_sabotage)) builder.add_node("add_misleading_comments", RunnableLambda(node_add_misleading_comments)) builder.add_node("overwrite_file", RunnableLambda(node_overwrite_file)) builder.add_node("deploy", RunnableLambda(node_deploy)) builder.add_node("done", RunnableLambda(node_done))
# Edges builder.set_entry_point("clone_repo") builder.add_edge("clone_repo", "map_files") builder.add_edge("map_files", "sabotage_init") builder.add_edge("sabotage_init", "inflate_hierarchy")
# After inflation: if refactoring β obfuscate, else β verify builder.add_conditional_edges( "inflate_hierarchy", _route_after_inflation, { "obfuscation_level_1": "obfuscation_level_1", "verify_sabotage": "verify_sabotage", }, )
# Refactoring chain: obfuscate β spaghettify β verify builder.add_edge("obfuscation_level_1", "obfuscation_level_2") builder.add_edge("obfuscation_level_2", "verify_sabotage")
builder.add_edge("verify_sabotage", "add_misleading_comments") builder.add_edge("add_misleading_comments", "overwrite_file") builder.add_edge("overwrite_file", "deploy") builder.add_edge("deploy", "done") builder.add_edge("done", END)
return builder.compile()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import os
from architect.state import ArchitectStatefrom architect.repo_cloner import clone_repofrom architect.file_mapper import map_filesfrom architect.saboteur import ( saboteur_init, inflate_hierarchy, apply_obfuscation_level_1, apply_obfuscation_level_2, verify_sabotage, add_misleading_comments,)from architect.challenge_deployer import deploy_challengefrom architect.readme_generator import create_readme
def node_clone_repo(state: ArchitectState) -> ArchitectState: return clone_repo(state)
def node_map_files(state: ArchitectState) -> ArchitectState: return map_files(state)
def node_sabotage_init(state: ArchitectState) -> ArchitectState: """Target Selection: pick the function and inject the AI-resistant bug.""" return saboteur_init(state)
def node_inflate_hierarchy(state: ArchitectState) -> ArchitectState: """Hierarchy Inflation: inflate all functions in the call chain and add dummy code.""" return inflate_hierarchy(state)
def node_obfuscation_level_1(state: ArchitectState) -> ArchitectState: """Semantic Stripping: rename vars to meaningless identifiers.""" return apply_obfuscation_level_1(state)
def node_obfuscation_level_2(state: ArchitectState) -> ArchitectState: """Deep Nesting: spaghettification with complex control flow.""" return apply_obfuscation_level_2(state)
def node_verify_sabotage(state: ArchitectState) -> ArchitectState: """Integrity Check: confirm bug still manifests, no crashes introduced.""" return verify_sabotage(state)
def node_add_misleading_comments(state: ArchitectState) -> ArchitectState: """Add false bug hints in random locations to confuse AI and students.""" return add_misleading_comments(state)
def node_overwrite_file(state: ArchitectState) -> ArchitectState: with open(state["target_file"], "w", encoding="utf-8") as f: f.write(state["sabotaged_code"]) print(f"[overwrite] Sabotaged code written to: {state['target_file']}") return state
def node_deploy(state: ArchitectState) -> ArchitectState: state = deploy_challenge(state) state = create_readme(state) return state
def node_done(state: ArchitectState) -> ArchitectState: target_rel = os.path.relpath(state["target_file"], state["clone_path"]) refactoring_status = "Enabled (obfuscation + spaghettification)" if state["refactoring_enabled"] else "Disabled (bugs + inflation only)" summary = ( "\n" "=============================================================\n" " LEGACY CHALLENGE ARCHITECT - REPORT \n" "=============================================================\n" f" Repository : {state['github_url']}\n" f" Cloned to : {state['clone_path']}\n" f" Target file : {target_rel}\n" f" Nesting level : {state['nesting_level']} (call-chain depth)\n" f" Refactoring : {refactoring_status}\n" f" Bugs injected : {state['num_bugs']}\n" f" Function : {state['function_name']}{state['test_args']}\n" f" Expected : {state['expected_output']}\n" f" Actual (bug) : {state['actual_output']}\n" f" Description : {state['bug_description']}\n" "\n" " Files created:\n" " - challenge_run.py (5 public tests)\n" " - challenge_run_secret.py (5 secret tests)\n" " - STUDENT_README.md\n" " - detailed_explanation.txt (for instructor)\n" "\n" " Environment is ready. Share the cloned folder with the student.\n" ) print(summary) state["challenge_summary"] = summary return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107import os
from architect.state import ArchitectState
def create_readme(state: ArchitectState) -> ArchitectState: num_bugs = state.get("num_bugs", 1) clone_path = state["clone_path"] repo_name = os.path.basename(clone_path) target_rel = os.path.relpath(state["target_file"], clone_path)
bugs_str = "1 bug" if num_bugs == 1 else f"{num_bugs} bugs"
refactoring_note = "" if state.get("refactoring_enabled", False): refactoring_note = ( "\n\n> **β οΈ Note:** The code has been intentionally obfuscated with " "confusing variable names and structure." )
readme_path = os.path.join(clone_path, "STUDENT_README.md") content = f"""\# Legacy Code Challenge
## Your Mission
You have just joined the team. Your tech lead hands you an urgent ticket:
> **"Something broke in production β the tests are failing and we cannot ship.> Good luck. The original author left the company."**
Your task: find and fix **{bugs_str}** hidden in `{target_rel}` β without breaking anything else.{refactoring_note}
### β οΈ Only modify `{target_rel}`. Do not touch any other file.
---
## How to Work
You can edit the code in two ways:
- **Built-in Code Editor** β use the **π» Code Editor** tab to browse and edit files directly in the challenge UI. Click **πΎ Save** to save your changes.- **Your local IDE** β open the file in VS Code, PyCharm, or any editor you prefer. Your saved changes are picked up automatically when you submit.
To run the tests at any time, either:
- Go to the **π§ͺ Test Results** tab in the challenge UI and click **βΆ Run Tests**.- Or To run the tests at any time, by: ```bashpython {repo_name}\challenge_run.py```
The test cases are also visible in the **π» Code Editor** tab β open `{repo_name}\challenge_run.py`to read them.
---
## Constraints - > ### β οΈ Read carefully β violations will affect your score.
1. **Only fix `{target_rel}`.** Do not change any other file.2. **No renaming variables or parameters.**3. **No splitting or merging functions.** Signatures must stay exactly as-is.4. **No adding external imports.**5. **Minimal fix only.** At most 1β3 lines changed per bug.6. **Do not break existing behaviour.**
---
## AI Assistant
On the right side of the challenge you have an **AI Assistant** you can chat with.It can help you understand the codebase, navigate the challenge UI, explain what a pieceof code does, or point you in the right direction β but it will **not** give you the fix.
> ### **β οΈ Using hints from the AI carries a scoring penalty, so use it wisely.**
---
## Submitting
You can submit at any time using the **π Submit Fix** button.Running the tests first lets you verify whether you have found and fixed all the bugs.
---
## Scoring
Your submission is evaluated automatically by an AI reviewer:
- **Correctness** β did all the tests pass and were all bugs fixed?- **Minimality** β did you change only the lines that needed to change?- **Quality** β does your fix match the expected correct approach?
---
# Good luck.# The codebase is yours now.""" with open(readme_path, "w", encoding="utf-8") as f: f.write(content)
print(f"[readme] Written: {readme_path}") return state1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import osimport shutilimport statimport timeimport git
from architect.state import ArchitectState
WORKSPACES_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "workspaces")
def _force_remove(func, path, _exc_info): """Error handler for shutil.rmtree: clear read-only flag, wait, then retry.""" try: os.chmod(path, stat.S_IWRITE) except OSError: pass time.sleep(0.1) try: func(path) except PermissionError: # Last resort: wait longer and try once more time.sleep(1.0) os.chmod(path, stat.S_IWRITE) func(path)
def _rmtree_with_retry(path: str, retries: int = 3, delay: float = 1.5) -> None: """Remove a directory tree, retrying on Windows file-lock errors.""" for attempt in range(retries): try: shutil.rmtree(path, onexc=_force_remove) return except PermissionError as exc: if attempt == retries - 1: raise RuntimeError( f"Cannot delete '{path}' after {retries} attempts β " "another process (OneDrive, antivirus, or a previous server) " "is holding a file open. Close it and retry." ) from exc print(f"[cloner] File locked, waiting {delay}s before retry ({attempt + 1}/{retries})β¦") time.sleep(delay)
def clone_repo(state: ArchitectState) -> ArchitectState: url = state["github_url"].rstrip("/") repo_name = url.split("/")[-1].removesuffix(".git") dest = os.path.join(WORKSPACES_DIR, repo_name)
os.makedirs(WORKSPACES_DIR, exist_ok=True)
if os.path.exists(dest): print(f"[cloner] Removing existing clone at {dest}") _rmtree_with_retry(dest)
print(f"[cloner] Cloning {url} -> {dest}") git.Repo.clone_from(url, dest) print(f"[cloner] Done.")
# Remove .git directory to prevent students from using git diff/log to find bugs git_dir = os.path.join(dest, ".git") if os.path.exists(git_dir): print(f"[cloner] Removing .git directory to prevent version control analysis...") _rmtree_with_retry(git_dir) print(f"[cloner] .git directory removed successfully.")
# Also remove .github directory (CI/CD configs that might reveal original structure) github_dir = os.path.join(dest, ".github") if os.path.exists(github_dir): print(f"[cloner] Removing .github directory...") _rmtree_with_retry(github_dir) print(f"[cloner] .github directory removed successfully.")
# Also remove git-related files that might reveal history git_files = [".gitignore", ".gitattributes", ".gitmodules"] for git_file in git_files: git_file_path = os.path.join(dest, git_file) if os.path.exists(git_file_path): try: os.remove(git_file_path) print(f"[cloner] Removed {git_file}") except Exception as e: print(f"[cloner] Warning: Could not remove {git_file}: {e}")
state["clone_path"] = dest return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197def saboteur_init(state: ArchitectState) -> ArchitectState: """ NEW SIMPLE WORKFLOW: 1. Pick num_bugs SIMPLE functions (depth 1 - standalone) 2. For each function: a. Generate 6+ tests FOR THAT FUNCTION DIRECTLY b. Inject bug INTO THAT FUNCTION c. Verify at least 3 tests detect the bug 3. Save all buggy functions with their tests 4. Inflation pass (later) will add wrapper layers """ target_nesting = state["nesting_level"] debug_mode = state.get("debug_mode", False) n_bugs = max(1, state.get("num_bugs") or 1)
candidate_files = list(state.get("candidate_files") or [state["target_file"]]) if debug_mode: print(f"\n[saboteur_init] === NEW SIMPLE WORKFLOW ===") print(f"[saboteur_init] Requested bugs: {n_bugs}") print(f"[saboteur_init] Target nesting: {target_nesting}") # Try each candidate file for current_file in candidate_files: with open(current_file, encoding="utf-8", errors="ignore") as f: source = f.read() if debug_mode: print(f"\n[saboteur_init] Trying file: {current_file}") # Pick n_bugs simple functions selected_funcs = _pick_simple_functions(source, n_bugs) if not selected_funcs: if debug_mode: print(f"[saboteur_init] Not enough suitable functions in {current_file}") continue if debug_mode: print(f"[saboteur_init] Selected {len(selected_funcs)} functions: {selected_funcs}") llm = ChatOpenAI(model="gpt-4o", temperature=0.7) current_source = source all_bugs_data = [] bug_specific_tests = {} # {func_name: [test cases that detect this bug]} # Inject bug in each function (DIRECT MODE) for idx, func_name in enumerate(selected_funcs, 1): if debug_mode: print(f"\n[saboteur_init] === BUG {idx}/{len(selected_funcs)}: {func_name} ===") source_before_bug = current_source # Call _sabotage_one_helper in DIRECT mode # (function is its own surface - no call chain) new_source, data = _sabotage_one_helper( bug_func_name=func_name, current_source=current_source, surface_func_name=func_name, # Same function! surface_source="", # Not needed in direct mode instructions=_BUG_INJECTION_SYSTEM_PROMPT, llm=llm, indirect_mode=False, # DIRECT MODE call_chain=[func_name], previous_bugs=[], target_nesting=target_nesting, file_path=current_file, debug_mode=debug_mode ) if new_source is None: if debug_mode: print(f"[saboteur_init] Failed to inject bug in {func_name}, skipping") continue # Get tests from data test_cases = data.get("test_cases", []) # Count how many tests detect THIS bug detecting_tests = [] for tc in test_cases: args = tc.get("args", "()") # Skip invalid tests if "lambda" in args or "range(" in args: continue try: eval(args, {"__builtins__": {}}) except: continue # Run on BEFORE and AFTER before_ok, before_result = _try_exec(source_before_bug, func_name, args, current_file) after_ok, after_result = _try_exec(new_source, func_name, args, current_file) # Test detects bug if results differ if before_ok != after_ok or (before_ok and after_ok and before_result != after_result): detecting_tests.append({ "args": args, "expected": before_result if before_ok else before_result }) num_detecting = len(detecting_tests) if debug_mode: print(f"[saboteur_init] Bug in '{func_name}': {num_detecting}/{len(test_cases)} tests detect it") # Validate: need at least 3 detecting tests if num_detecting < 3: if debug_mode: print(f"[saboteur_init] Not enough detecting tests ({num_detecting} < 3), skipping this bug") continue # Bug is good! current_source = new_source all_bugs_data.append(data) bug_specific_tests[func_name] = detecting_tests if debug_mode: print(f"[saboteur_init] β Bug #{idx} injected successfully") # Check if we got at least one bug if not all_bugs_data: if debug_mode: print(f"[saboteur_init] No bugs successfully injected in {current_file}") continue if debug_mode: print(f"\n[saboteur_init] === SUCCESS: {len(all_bugs_data)}/{n_bugs} bugs injected ===") # Collect all unique tests all_test_cases = [] seen_args = set() for func_name, tests in bug_specific_tests.items(): for tc in tests: args = tc.get("args", "()") if args not in seen_args: seen_args.add(args) all_test_cases.append(tc) # Split into public/secret (50/50) random.shuffle(all_test_cases) mid = len(all_test_cases) // 2 public_tests = all_test_cases[:mid] if mid > 0 else all_test_cases[:1] secret_tests = all_test_cases[mid:] if mid > 0 else all_test_cases[1:] if debug_mode: print(f"[saboteur_init] Total unique tests: {len(all_test_cases)}") print(f"[saboteur_init] Public: {len(public_tests)}, Secret: {len(secret_tests)}") # Get first failing test for display first_fail_args = first_expected = first_actual = None for tc in all_test_cases: args = tc.get("args", "()") expected = tc.get("expected") _, actual = _try_exec(current_source, selected_funcs[0], args, current_file) if expected != actual: first_fail_args, first_expected, first_actual = args, expected, actual break # Build bug description bug_descriptions = [d.get("bug_description", "") for d in all_bugs_data] combined_desc = " | ".join(bug_descriptions) # Save to state state["target_file"] = current_file state["original_code"] = source state["sabotaged_code"] = current_source state["function_name"] = selected_funcs[0] # First function as surface state["test_args"] = first_fail_args or "()" state["expected_output"] = first_expected or "" state["actual_output"] = first_actual or "" state["test_cases"] = all_test_cases state["public_tests"] = public_tests state["secret_tests"] = secret_tests state["bug_description"] = combined_desc state["all_bug_data"] = all_bugs_data state["bug_specific_tests"] = bug_specific_tests # For inflation pass state["sabotaged_functions"] = selected_funcs # List of functions with bugs # Store original buggy function source for inflation if all_bugs_data: state["bug_func_name"] = all_bugs_data[0].get("_debug_func_name", selected_funcs[0]) state["bug_func_source"] = all_bugs_data[0].get("_debug_sabot_func", "") state["original_bug_func_source"] = all_bugs_data[0].get("_debug_func_source", "") if debug_mode: print(f"\n[saboteur_init] === COMPLETE ===") print(f"[saboteur_init] File: {current_file}") print(f"[saboteur_init] Bugs: {selected_funcs}") print(f"[saboteur_init] Description: {combined_desc}") print(f"[saboteur_init] Tests: {len(all_test_cases)} total ({len(public_tests)} public + {len(secret_tests)} secret)") return state # If we get here, no file worked raise RuntimeError(f"Failed to inject bugs in any of {len(candidate_files)} candidate files")123456789101112131415161718192021222324252627282930313233343536373839from typing import TypedDict
class ArchitectState(TypedDict): github_url: str clone_path: str # absolute path of cloned repo on disk target_file: str # absolute path to the chosen Python file original_code: str # file content before sabotage sabotaged_code: str # file content after sabotage nesting_level: int # desired call-chain depth for bug placement refactoring_enabled: bool # whether to apply obfuscation/spaghettification debug_mode: bool # whether to show verbose output and bug location comments num_bugs: int # number of bugs to inject (CLI --num-bugs, default 1) function_name: str # the sabotaged function test_args: str # first failing case args (for README / legacy use) expected_output: str # correct return value for first failing case actual_output: str # buggy return value for first failing case bug_description: str # architect-only description of what was injected detailed_explanation: str # detailed report: where bug is, what it does, how it's hidden challenge_summary: str # final printout for the architect test_cases: list # [{"args": str, "expected": str}, ...] all test cases (LEGACY - for fallback) public_tests: list # [{"args": str, "expected": str}, ...] 5 public tests (LEGACY) secret_tests: list # [{"args": str, "expected": str}, ...] 5 secret tests (LEGACY) candidate_files: list # all scored file paths (sorted best-first) for fallback bug_func_name: str # internal: name of the sabotaged helper function (passed between nodes) bug_func_source: str # internal: exact buggy source of the helper (passed between nodes) call_chain: dict # internal: dict of bug_func_name -> [surface_func, ..., bug_func] call chains # Multi-bug support (NEW) bug_specific_tests: dict # dict of {function_name: [test cases]} for each bug all_bug_data: list # list of bug metadata dicts (one per bug) sabotaged_functions: list # list of function names that have bugs # Per-bug source snapshots (for "Changes & Expected" tab) bug_func_names: list # [func_name, ...] one per bug (POST-INFLATE) bug_func_sources_list: list # [sabotaged_source, ...] one per bug (POST-INFLATE) original_bug_func_sources_list: list # [original_source, ...] one per bug (POST-INFLATE) original_bug_func_source: str # original source of first buggy function (legacy) # PRE-INFLATE versions (for debugging/reference - optional) pre_inflate_bug_sources: list # [sabotaged_source, ...] before wrapper inflation pre_inflate_original_sources: list # [original_source, ...] before wrapper inflation123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""challenge.py β Unified Challenge entry point.
Usage (GUI setup page): python challenge.py [--port 7860] [--share]
Usage (skip setup, run directly): python challenge.py <github_url> --name "Alice" [--nesting-level 3] [--num-bugs N] [--refactoring] [--debug] [--timer N] [--port 7860] [--share]
If github_url is provided the setup page is skipped: the pipeline runsimmediately and the challenge interface opens directly."""
import argparseimport osimport sys
from dotenv import load_dotenv
# ββ Resolve .env (LegacyInterview2/.env first, then parent AiAgent/.env) ββ_base = os.path.dirname(os.path.abspath(__file__))_env_local = os.path.join(_base, ".env")_env_fallback = os.path.join(_base, "..", "First Year", "Advanced Deep Neural Neworks", "Home Exercises", "AiAgent", ".env")if os.path.exists(_env_local): load_dotenv(dotenv_path=_env_local)elif os.path.exists(_env_fallback): load_dotenv(dotenv_path=_env_fallback)else: load_dotenv()
# ββ Apply proxy settings from .env if defined ββif os.getenv("http_proxy"): os.environ["http_proxy"] = os.getenv("http_proxy")if os.getenv("https_proxy"): os.environ["https_proxy"] = os.getenv("https_proxy")if os.getenv("no_proxy"): os.environ["no_proxy"] = os.getenv("no_proxy")
# Note: API key is optional in hosted mode (users provide their own via login page)# Only enforce it when github_url is provided (CLI mode requires API key to run pipeline)
import gradio as gr # noqa: E402import student_interface # noqa: E402
def main() -> None: parser = argparse.ArgumentParser( description="Legacy Challenge β launch the student GUI (with optional CLI shortcuts)." ) # Optional positional β if omitted, the GUI setup page is shown instead parser.add_argument( "github_url", nargs="?", default=None, help="GitHub repo URL. If given, skip the setup page and run immediately.", ) parser.add_argument( "--name", type=str, default="", help="Student name shown in the header. Required when github_url is provided.", ) parser.add_argument( "--nesting-level", type=int, choices=range(1, 7), default=3, metavar="1-6", help="Call-chain depth for bug hiding (default: 3). Only used when github_url is provided.", ) parser.add_argument( "--num-bugs", type=int, default=1, help="Number of bugs to inject (default: 1). Only used when github_url is provided.", ) parser.add_argument( "--refactoring", action="store_true", help="Enable refactoring/obfuscation transforms. Only used when github_url is provided.", ) parser.add_argument( "--debug", action="store_true", help="Debug mode β verbose output, show bug locations. Only used when github_url is provided.", ) parser.add_argument( "--timer", type=int, default=0, help="Countdown timer in minutes (0 = no timer). Only used when github_url is provided.", ) parser.add_argument( "--port", type=int, default=7860, help="Port for the Gradio GUI (default: 7860).", ) parser.add_argument( "--share", action="store_true", help="Create a public Gradio share link.", ) args = parser.parse_args()
base_kwargs = dict( server_name="127.0.0.1", server_port=args.port, share=args.share, inbrowser=True, theme=gr.themes.Base(), css=student_interface._CSS, )
if args.github_url: # ββ Fast path: CLI args supplied β skip setup page ββββββββββββββ # CLI mode requires API key to run the pipeline if not os.getenv("OPENAI_API_KEY"): print("ERROR: OPENAI_API_KEY not set. Add it to .env or export it.") print("(CLI mode requires API key to generate challenges)") sys.exit(1) if not args.name: parser.error("--name is required when providing a GitHub URL (e.g. --name 'Alice Smith')") print( f"\n[challenge] CLI mode β URL: {args.github_url} " f"Nesting: {args.nesting_level} Bugs: {args.num_bugs} " f"Refactoring: {args.refactoring} Debug: {args.debug} Name: {args.name}\n" ) print("[challenge] Running pipelineβ¦") workspace_path = student_interface._run_pipeline( args.github_url.strip(), args.nesting_level, args.num_bugs, refactoring_enabled=args.refactoring, debug_mode=args.debug, ) print(f"[challenge] Workspace ready: {workspace_path}") print(f"[challenge] Opening http://localhost:{args.port}\n") demo = student_interface.create_interface( workspace_path, student_name=args.name, timer_minutes=args.timer ) # JS is embedded in gr.Blocks(js=_make_js(timer)) inside create_interface demo.launch(**base_kwargs)
else: # ββ Normal path: open setup page in the browser ββββββββββββββββββ print(f"\n[challenge] Opening setup page at http://localhost:{args.port}\n") demo = student_interface.create_full_interface() demo.launch(**base_kwargs, js=student_interface._JS)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113ο»Ώpython : C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langchain_core\_api\deprecation.py:26: UserWarning: Core Pydantic V1 functionality isn't compatible with Python 3.14 or greater.At line:1 char:122+ ... nterview2'; python main.py https://github.com/mahmoud/boltons.git --n ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (C:\Users\rzanzu....14 or greater. :String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError from pydantic.v1.fields import FieldInfo as FieldInfoV1
[architect] Starting ΓΉ URL: https://github.com/mahmoud/boltons.git Nesting: 2 Bugs: 1 Refactoring: False Debug: ON
[cloner] Removing existing clone at C:\Users\rzanzuri\OneDrive - Intel Corporation\Desktop\MySecond\Second year\Seminar\Project.final\LegacyInterview2\workspaces\boltonsTraceback (most recent call last): File "C:\Users\rzanzuri\OneDrive - Intel Corporation\Desktop\MySecond\Second year\Seminar\Project.final\LegacyInterview2\main.py", line 91, in <module> main() ~~~~^^ File "C:\Users\rzanzuri\OneDrive - Intel Corporation\Desktop\MySecond\Second year\Seminar\Project.final\LegacyInterview2\main.py", line 87, in main graph.invoke(initial_state) ~~~~~~~~~~~~^^^^^^^^^^^^^^^ File "C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langgraph\pregel\main.py", line 3068, in invoke for chunk in self.stream( ~~~~~~~~~~~^ input, ^^^^^^ ...<10 lines>... **kwargs, ^^^^^^^^^ ): ^ File "C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langgraph\pregel\main.py", line 2643, in stream for _ in runner.tick( ~~~~~~~~~~~^ [t for t in loop.tasks.values() if not t.writes], ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<2 lines>... schedule_task=loop.accept_push, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ): ^ File "C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langgraph\pregel\_runner.py", line 167, in tick run_with_retry( ~~~~~~~~~~~~~~^ t, ^^ ...<10 lines>... }, ^^ ) ^ File "C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langgraph\pregel\_retry.py", line 42, in run_with_retry return task.proc.invoke(task.input, config) ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langgraph\_internal\_runnable.py", line 656, in invoke input = context.run(step.invoke, input, config, **kwargs) File "C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langchain_core\runnables\base.py", line 4880, in invoke return self._call_with_config( ~~~~~~~~~~~~~~~~~~~~~~^ self._invoke, ^^^^^^^^^^^^^ ...<2 lines>... **kwargs, ^^^^^^^^^ ) ^ File "C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langchain_core\runnables\base.py", line 2058, in _call_with_config context.run( ~~~~~~~~~~~^ call_func_with_variable_args, # type: ignore[arg-type] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<4 lines>... **kwargs, ^^^^^^^^^ ), ^ File "C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langchain_core\runnables\config.py", line 433, in call_func_with_variable_args return func(input, **kwargs) # type: ignore[call-arg] File "C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langchain_core\runnables\base.py", line 4737, in _invoke output = call_func_with_variable_args( self.func, input_, config, run_manager, **kwargs ) File "C:\Users\rzanzuri\AppData\Roaming\Python\Python314\site-packages\langchain_core\runnables\config.py", line 433, in call_func_with_variable_args return func(input, **kwargs) # type: ignore[call-arg] File "C:\Users\rzanzuri\OneDrive - Intel Corporation\Desktop\MySecond\Second year\Seminar\Project.final\LegacyInterview2\architect\nodes.py", line 18, in node_clone_repo return clone_repo(state) File "C:\Users\rzanzuri\OneDrive - Intel Corporation\Desktop\MySecond\Second year\Seminar\Project.final\LegacyInterview2\architect\repo_cloner.py", line 56, in clone_repo print(f"[cloner] Cloning {url} \u2192 {dest}") ~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python314\Lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^UnicodeEncodeError: 'charmap' codec can't encode character '\u2192' in position 56: character maps to <undefined>During task with name 'clone_repo' and id 'ba151a2c-146f-7f6b-22af-1979b6335450'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237"""git_submissions_logger.py β Push detailed submission reports to Git repository
Creates a comprehensive backup folder for each submission and commits to Git:- Original prompt/challenge- Original code (before bugs)- Buggy code (what student received)- Student's solution- Full chat history- Summary JSON
Each submission is automatically committed and pushed to a dedicated Git repository."""
import osimport jsonimport subprocessfrom datetime import datetimefrom pathlib import Pathfrom typing import Optional
def push_submission_to_git( student_name: str, repo_url: str, original_code: str, buggy_code: str, student_code: str, chat_history: list, score: int, total_tests: int, passed_tests: int, hints_used: int, challenge_prompt: str, target_file: str,) -> bool: """ Create submission folder and push to Git repository. Structure: submissions/ βββ 2026-05-20_1430_StudentName_RepoName/ βββ 1_challenge_prompt.md βββ 2_original_code.py βββ 3_buggy_code.py βββ 4_student_solution.py βββ 5_chat_history.txt βββ 6_summary.json Returns True if successful, False otherwise. """ # Check if Git submissions repo is configured submissions_repo = os.getenv("SUBMISSIONS_REPO_URL") git_token = os.getenv("SUBMISSIONS_GIT_TOKEN") if not submissions_repo: print("β οΈ Git Submissions: SUBMISSIONS_REPO_URL not configured in .env") return False try: # Create submissions directory if it doesn't exist submissions_dir = Path("submissions_backup") submissions_dir.mkdir(exist_ok=True) # Initialize Git repo if needed git_dir = submissions_dir / ".git" if not git_dir.exists(): print("π Initializing Git repository...") subprocess.run( ["git", "init"], cwd=submissions_dir, check=True, capture_output=True ) # Configure remote with token if available if git_token: # Format: https://TOKEN@github.com/user/repo.git repo_with_token = submissions_repo.replace("https://", f"https://{git_token}@") subprocess.run( ["git", "remote", "add", "origin", repo_with_token], cwd=submissions_dir, check=True, capture_output=True ) else: subprocess.run( ["git", "remote", "add", "origin", submissions_repo], cwd=submissions_dir, check=True, capture_output=True ) # Pull existing commits if repo exists try: subprocess.run( ["git", "pull", "origin", "main"], cwd=submissions_dir, check=True, capture_output=True ) except subprocess.CalledProcessError: # Repo might be empty, that's OK pass print("β
Git repository initialized") # Create submission folder name timestamp = datetime.now().strftime("%Y-%m-%d_%H%M") repo_name = repo_url.split('/')[-1].replace('.git', '') folder_name = f"{timestamp}_{student_name}_{repo_name}" submission_folder = submissions_dir / folder_name submission_folder.mkdir(exist_ok=True) print(f"π Creating submission: {folder_name}") # Prepare files to write files_to_write = [ ("1_challenge_prompt.md", challenge_prompt), ("2_original_code.py", f"# Original code (before bugs)\n# Target file: {target_file}\n\n{original_code}"), ("3_buggy_code.py", f"# Buggy code (what student received)\n# Target file: {target_file}\n\n{buggy_code}"), ("4_student_solution.py", f"# Student's solution\n# Target file: {target_file}\n\n{student_code}"), ("5_chat_history.txt", _format_chat_history(chat_history)), ("6_summary.json", json.dumps({ 'student_name': student_name, 'repository': repo_url, 'timestamp': datetime.now().isoformat(), 'score': score, 'total_tests': total_tests, 'passed_tests': passed_tests, 'success_rate': f"{(passed_tests/total_tests*100):.1f}%" if total_tests > 0 else "0%", 'hints_used': hints_used, 'target_file': target_file, }, ensure_ascii=False, indent=2)), ] # Write all files print(f"π Writing {len(files_to_write)} files...") for filename, content in files_to_write: file_path = submission_folder / filename file_path.write_text(content, encoding='utf-8') print(f" β
{filename}") # Git add, commit, push print("π€ Committing to Git...") subprocess.run( ["git", "add", "."], cwd=submissions_dir, check=True, capture_output=True ) commit_message = f"Add submission: {student_name} - {repo_name} ({score}/{total_tests*10} pts)" subprocess.run( ["git", "commit", "-m", commit_message], cwd=submissions_dir, check=True, capture_output=True ) print("π Pushing to GitHub...") subprocess.run( ["git", "push", "origin", "main"], cwd=submissions_dir, check=True, capture_output=True, timeout=30 ) print(f"β
Pushed to Git: {folder_name}") return True except subprocess.CalledProcessError as e: print(f"β οΈ Git command failed: {e.stderr.decode() if e.stderr else str(e)}") return False except Exception as e: print(f"β οΈ Git submission failed: {type(e).__name__}: {e}") import traceback traceback.print_exc() return False
def _format_chat_history(chat_history: list) -> str: """Format chat history for text file.""" if not chat_history: return "ΧΧ ΧΧ©ΧͺΧΧ© ΧΧΧΧ ΧΧΧ\n" lines = ["ΧΧͺΧΧͺΧΧΧͺ ΧΧΧΧ Χ’Χ ΧΧ¦'ΧΧ\n"] lines.append("=" * 60 + "\n\n") for i, msg in enumerate(chat_history, 1): lines.append(f"ΧΧΧ Χ #{i}\n") lines.append("-" * 40 + "\n") lines.append(f"Χ©ΧΧΧ: {msg.get('summary', 'N/A')}\n\n") lines.append(f"ΧͺΧ©ΧΧΧ:\n{msg.get('response', 'N/A')}\n\n") lines.append("=" * 60 + "\n\n") return "".join(lines)
# CLI testingif __name__ == "__main__": import sys from dotenv import load_dotenv # Load .env file for testing load_dotenv() if len(sys.argv) > 1 and sys.argv[1] == "test": print("Testing Git submissions integration...") submissions_repo = os.getenv("SUBMISSIONS_REPO_URL") if not submissions_repo: print("β SUBMISSIONS_REPO_URL not set in .env") sys.exit(1) success = push_submission_to_git( student_name="Test_Student", repo_url="https://github.com/test/repo", original_code="def hello():\n return 'world'", buggy_code="def hello():\n return 'WORLD'", student_code="def hello():\n return 'world'", chat_history=[{"summary": "How to fix?", "response": "Check the case"}], score=85, total_tests=10, passed_tests=8, hints_used=1, challenge_prompt="# Test Challenge\n\nFix the bug!", target_file="test.py", ) if success: print("β
Test push successful!") else: print("β Test push failed") sys.exit(1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""google_sheets_logger.py β Optional Google Sheets integration for submission logging
This module provides automatic logging of student submissions to Google Sheets.If not configured (no GOOGLE_SHEET_ID), it silently fails and the system continues normally."""
import osfrom datetime import datetimefrom typing import Optional
def log_to_google_sheets( student_name: str, repo_url: str, hints_used: int, score: int, total_tests: int, passed_tests: int, all_passed: bool, chat_history: list,) -> bool: """ Log submission to Google Sheets. Returns True if successful, False otherwise. If Google Sheets is not configured, returns False silently. """ # Check if Google Sheets is configured sheet_id = os.getenv("GOOGLE_SHEET_ID") if not sheet_id: return False # Silently skip if not configured try: import gspread from google.oauth2.service_account import Credentials # Check if service account file exists service_account_file = "google-service-account.json" if not os.path.exists(service_account_file): print("β οΈ Google Sheets: service account file not found") return False # Authenticate scopes = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] creds = Credentials.from_service_account_file(service_account_file, scopes=scopes) client = gspread.authorize(creds) # Open the sheet sheet = client.open_by_key(sheet_id).sheet1 # Initialize headers if this is the first time try: if not sheet.row_values(1): # Empty sheet headers = [ "ΧͺΧΧ¨ΧΧ ΧΧ©Χ’Χ", "Χ©Χ Χ‘ΧΧΧΧ Χ", "GitHub Repository", "Χ¦ΧΧΧ", "ΧΧΧ ΧΧΧ", "ΧΧ‘ΧΧΧ Χ©Χ’ΧΧ¨Χ", "ΧΧ¦ΧΧΧ?", "ΧΧͺΧΧͺΧΧΧͺ Χ’Χ ΧΧ¦'ΧΧ", ] sheet.append_row(headers) # Make headers bold sheet.format('A1:H1', {'textFormat': {'bold': True}}) except Exception as e: print(f"β οΈ Could not set headers: {e}") # Prepare row data timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Format chat history nicely if chat_history: chat_text = "\n\n".join([ f"ΧΧΧ Χ #{i+1}:\nΧ©ΧΧΧ: {msg.get('summary', 'N/A')}\nΧͺΧ©ΧΧΧ: {msg.get('response', 'N/A')}" for i, msg in enumerate(chat_history) ]) else: chat_text = "ΧΧ ΧΧ©ΧͺΧΧ© ΧΧΧΧ ΧΧΧ" row = [ timestamp, student_name or "Anonymous", repo_url, score, hints_used, f"{passed_tests}/{total_tests}", "β
ΧΧ¦ΧΧΧ" if all_passed else "β ΧΧ ΧΧ¦ΧΧΧ", chat_text, ] # Append row sheet.append_row(row) print(f"β
Logged to Google Sheets: {student_name} - Score: {score}") return True except ImportError: print("β οΈ Google Sheets: gspread not installed (pip install gspread google-auth)") return False except Exception as e: print(f"β οΈ Google Sheets logging failed: {e}") return False
def initialize_sheet_headers(sheet_id: Optional[str] = None) -> bool: """ Initialize Google Sheet with headers if it's empty. Call this once to set up the sheet. """ sheet_id = sheet_id or os.getenv("GOOGLE_SHEET_ID") if not sheet_id: print("β GOOGLE_SHEET_ID not set") return False try: import gspread from google.oauth2.service_account import Credentials service_account_file = "google-service-account.json" if not os.path.exists(service_account_file): print(f"β Service account file not found: {service_account_file}") return False scopes = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] creds = Credentials.from_service_account_file(service_account_file, scopes=scopes) client = gspread.authorize(creds) sheet = client.open_by_key(sheet_id).sheet1 # Check if already has headers if sheet.row_count > 0 and sheet.row_values(1): print("β
Sheet already has headers") return True # Add headers headers = [ "Timestamp", "Student Name", "Repository", "Score", "Hints Used", "Tests Passed", "All Passed?", "Code Preview", "Chat Summary" ] sheet.append_row(headers) # Format headers (bold) sheet.format("A1:I1", { "textFormat": {"bold": True}, "backgroundColor": {"red": 0.9, "green": 0.9, "blue": 0.9} }) print("β
Headers initialized!") return True except Exception as e: print(f"β Failed to initialize headers: {e}") return False
# CLI tool for testingif __name__ == "__main__": import sys if len(sys.argv) > 1 and sys.argv[1] == "init": # Initialize headers sheet_id = os.getenv("GOOGLE_SHEET_ID") if not sheet_id: print("Set GOOGLE_SHEET_ID in .env first!") sys.exit(1) success = initialize_sheet_headers(sheet_id) sys.exit(0 if success else 1) else: # Test logging print("Testing Google Sheets logging...") success = log_to_google_sheets( student_name="Test Student", repo_url="https://github.com/test/repo", hints_used=2, score=85, total_tests=10, passed_tests=8, all_passed=False, chat_history=[{"role": "user", "content": "test"}], ) if success: print("β
Test successful!") else: print("β Test failed - check configuration")1234567891011121314151617181920212223242526272829303132333435363738"""Quick launcher for existing workspace - no pipeline run needed!Usage: python launch_existing.py workspaces/inflection"""import argparseimport osimport sysfrom dotenv import load_dotenv
# Load environmentload_dotenv()if not os.getenv("OPENAI_API_KEY"): print("ERROR: OPENAI_API_KEY not set.") sys.exit(1)
from student_interface import create_interface
def main(): parser = argparse.ArgumentParser(description="Launch interface for existing workspace") parser.add_argument("workspace", help="Path to workspace folder (e.g., workspaces/inflection)") parser.add_argument("--name", default="Student", help="Student name") parser.add_argument("--timer", type=int, default=0, help="Timer in minutes (0 = no timer)") parser.add_argument("--port", type=int, default=7860, help="Port (default: 7860)") args = parser.parse_args()
print(f"\nπ Launching interface for workspace: {args.workspace}") print(f" Name: {args.name}") print(f" Port: http://localhost:{args.port}\n")
demo = create_interface(args.workspace, student_name=args.name, timer_minutes=args.timer) # Set share=True to get a public URL (valid for 72 hours) demo.launch(server_port=args.port, share=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536@echo offREM Quick Setup and Launch Script for Legacy Code Challenge System
echo ================================================echo Legacy Code Challenge - Quick Startecho ================================================echo.
REM Check if virtual environment existsif not exist "venv" ( echo Creating virtual environment... python -m venv venv)
echo Activating virtual environment...call venv\Scripts\activate.bat
echo.echo Installing dependencies...pip install -q -r requirements.txt
echo.echo ================================================echo Setup complete!echo ================================================echo.echo You can now:echo 1. Generate a challenge: python main.py https://github.com/user/repo.gitecho 2. Launch student interface: python student_interface.pyecho.echo Starting student interface in 3 seconds...timeout /t 3 /nobreak >nul
python student_interface.py
pause123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Patch to add login page to student_interface.pyThis adds user registration with API key input before the main interface."""
# Add this function at the top of student_interface.py, before create_full_interface():
def validate_openai_key(api_key: str) -> tuple[bool, str]: """Validate that an OpenAI API key is properly formatted and works.""" import os if not api_key or not api_key.startswith("sk-"): return False, "Invalid API key format. Must start with 'sk-'" # Try a simple API call to validate try: os.environ["OPENAI_API_KEY"] = api_key from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o", temperature=0, request_timeout=5, max_tokens=5) llm.invoke("test") return True, "β
API key validated successfully!" except Exception as e: error_msg = str(e) if "401" in error_msg or "Incorrect API key" in error_msg: return False, "β Invalid API key. Please check your key." elif "quota" in error_msg.lower(): return False, "β οΈ API key valid but no quota remaining." else: # Key is probably valid, just another error return True, f"β οΈ API key accepted (error: {error_msg[:50]})"
# Then modify create_full_interface() to add login page:# Add after line "with gr.Blocks..." and before "# Shared state":
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ # PAGE 0 β Login/Registration # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ user_api_key_state = gr.State("") user_name_state = gr.State("") with gr.Column(visible=True, elem_classes=["setup-card"]) as login_page: gr.Markdown( "# π Welcome to Legacy Code Challenge\n" "### Please enter your details to continue" ) login_name = gr.Textbox( label="Your Name", placeholder="e.g. Alice Smith", info="This will appear in your challenge session", ) login_api_key = gr.Textbox( label="OpenAI API Key", placeholder="sk-proj-...", type="password", info="Your API key will be used only for this session", ) gr.Markdown( "π‘ **Don't have an API key?** Get one at [platform.openai.com/api-keys](https://platform.openai.com/api-keys)\n\n" "β οΈ **Note:** Running challenges will consume API credits from your OpenAI account" ) login_btn = gr.Button("π Continue to Challenge Setup", variant="primary", size="lg") login_status = gr.Markdown("")
# Add this callback at the bottom, before "return demo":
def on_login(name, api_key): if not name.strip(): return ( gr.update(visible=True), gr.update(visible=False), "β Please enter your name", "", "" ) valid, msg = validate_openai_key(api_key) if not valid: return ( gr.update(visible=True), gr.update(visible=False), msg, "", "" ) # Success - hide login, show setup import os os.environ["OPENAI_API_KEY"] = api_key return ( gr.update(visible=False), # hide login gr.update(visible=True), # show setup msg, api_key, # save to state name.strip() # save name to state ) login_btn.click( on_login, inputs=[login_name, login_api_key], outputs=[login_page, setup_page, login_status, user_api_key_state, user_name_state], )
# Modify on_start() to use user_name_state instead of name_box:# Change the first line from:# def on_start(name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins):# To:# def on_start(saved_name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins):# And use saved_name instead of name throughout
# Update start_btn.click():# Change inputs from:# inputs=[name_box, url_box, ...]# To:# inputs=[user_name_state, url_box, ...]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import argparseimport osimport sys
from dotenv import load_dotenv
# ββ Resolve .env (LegacyInterview2/.env first, then parent AiAgent/.env) ββ_base = os.path.dirname(os.path.abspath(__file__))_env_local = os.path.join(_base, ".env")_env_fallback = os.path.join(_base, "..", "First Year", "Advanced Deep Neural Neworks", "Home Exercises", "AiAgent", ".env")if os.path.exists(_env_local): load_dotenv(dotenv_path=_env_local)elif os.path.exists(_env_fallback): load_dotenv(dotenv_path=_env_fallback)else: load_dotenv()
# ββ Apply proxy settings from .env if defined ββif os.getenv("http_proxy"): os.environ["http_proxy"] = os.getenv("http_proxy")if os.getenv("https_proxy"): os.environ["https_proxy"] = os.getenv("https_proxy")if os.getenv("no_proxy"): os.environ["no_proxy"] = os.getenv("no_proxy")
if not os.getenv("OPENAI_API_KEY"): print("ERROR: OPENAI_API_KEY not set. Add it to .env or export it.") sys.exit(1)
from architect.graph import build_graph # noqa: E402 (import after env setup)
def main() -> None: parser = argparse.ArgumentParser( description="Legacy Challenge Architect β transform a GitHub repo into a student challenge." ) parser.add_argument("github_url", help="Public GitHub repository URL to clone and sabotage.") parser.add_argument( "--nesting-level", type=int, default=3, help="Desired call-chain depth for bug placement (default: 3)" ) parser.add_argument( "--num-bugs", type=int, default=1, help="Number of bugs to inject (default: 1)" ) parser.add_argument( "--refactoring", action="store_true", help="Apply code obfuscation and spaghettification (default: False, only inject bugs + inflate)" ) parser.add_argument( "--debug", action="store_true", help="Enable debug mode with verbose output and bug location comments (default: False)" ) args = parser.parse_args()
if args.debug: print(f"\n[architect] Starting β URL: {args.github_url} Nesting: {args.nesting_level} Bugs: {args.num_bugs} Refactoring: {args.refactoring} Debug: ON\n") else: print(f"\n[architect] Generating challenge from {args.github_url}...\n")
graph = build_graph() initial_state = { "github_url": args.github_url, "nesting_level": args.nesting_level, "refactoring_enabled": args.refactoring, "debug_mode": args.debug, "num_bugs": args.num_bugs, # remaining fields will be populated by graph nodes "clone_path": "", "target_file": "", "original_code": "", "sabotaged_code": "", "function_name": "", "test_args": "", "expected_output": "", "actual_output": "", "bug_description": "", "detailed_explanation": "", "challenge_summary": "", "test_cases": [], "public_tests": [], "secret_tests": [], "candidate_files": [], "bug_func_name": "", "bug_func_source": "", "call_chain": [], }
graph.invoke(initial_state)
if __name__ == "__main__": main()1# Challenge Orchestrator package12345678910111213141516171819202122232425262728293031"""Challenge Orchestrator β LangGraph pipeline.
Flow: START β node_run_bug_generator β node_save_challenge_state β node_launch_student_gui β END"""
from langgraph.graph import StateGraph, ENDfrom langchain_core.runnables import RunnableLambda
from orchestrator.state import OrchestratorStatefrom orchestrator.nodes import ( node_run_bug_generator, node_save_challenge_state, node_launch_student_gui,)
def build_orchestrator() -> StateGraph: builder = StateGraph(OrchestratorState)
builder.add_node("run_bug_generator", RunnableLambda(node_run_bug_generator)) builder.add_node("save_challenge_state", RunnableLambda(node_save_challenge_state)) builder.add_node("launch_student_gui", RunnableLambda(node_launch_student_gui))
builder.set_entry_point("run_bug_generator") builder.add_edge("run_bug_generator", "save_challenge_state") builder.add_edge("save_challenge_state", "launch_student_gui") builder.add_edge("launch_student_gui", END)
return builder.compile()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424"""Hint Sub-Graph β LangGraph agent for progressive AI hints.
Allow-level policy (based on hints_used): 0 hints β level 0 : no location information, pure methodology guidance 1β2 hints β level 1 : may mention the bug is not in the surface function 3β4 hints β level 2 : may describe the general bug type (e.g. "off-by-one") 5+ hints β level 3 : may name the specific helper function that has the bug
The graph: START β node_check_hint_policy β node_generate_hint β END"""
from typing import TypedDict
from langgraph.graph import StateGraph, ENDfrom langchain_openai import ChatOpenAIfrom langchain_core.messages import HumanMessage, SystemMessage, AIMessage
# Cumulative penalty table β index = number of hints used (mirrors scoring.py)_HINT_PENALTY = [0, 2, 6, 12, 20, 30]MAX_HINTS = 5
# ββ State βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class HintState(TypedDict): messages: list # [{"role": "user"|"assistant", "content": str}, ...] hints_used: int # total AI hints consumed so far this session submission_attempts: int # number of times student has submitted challenge_info: dict # keys: function_name, bug_func_name, target_file, difficulty_level allow_level: int # 0β3, set by node_check_hint_policy response: str # filled by node_generate_hint gave_hint: bool # True if the AI gave substantive debugging guidance hint_summary: str # one-sentence summary of the hint (empty if gave_hint=False)
# ββ Nodes βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def node_check_hint_policy(state: HintState) -> HintState: """Compute the allow_level based on how many hints have already been given.""" h = state["hints_used"] if h == 0: level = 0 elif h <= 2: level = 1 elif h <= 4: level = 2 else: level = 3 return {**state, "allow_level": level}
def node_generate_hint(state: HintState) -> HintState: """Call GPT-4o with a system prompt tuned to the current allow_level.""" hints_used = state["hints_used"]
# Hard limit: no more hints once MAX_HINTS is reached if hints_used >= MAX_HINTS: return {**state, "response": ( f"You've reached the maximum of {MAX_HINTS} hints for this challenge. " "I can no longer provide debugging hints, but I'm still happy to help " "with questions about the UI, how to run tests, or how to navigate the code editor." ), "gave_hint": False}
allow_level = state["allow_level"] info = state["challenge_info"] func_name = info.get("function_name", "the function") target_file = info.get("target_file", "the target file")
bug_func_names: list = info.get("bug_func_names", []) if not bug_func_names: single = info.get("bug_func_name", "") bug_func_names = [single] if single else []
sabot_sources: list = info.get("bug_func_sources_list", []) orig_sources: list = info.get("original_bug_func_sources_list", []) original_code: str = info.get("original_code", "")
# Build a file overview from the original code (module docstring + first ~40 lines) if original_code: overview_lines = original_code.splitlines()[:60] file_overview = ( "\n\nFILE OVERVIEW (original, unmodified file β use this to understand " "what the module does and answer general questions about it):\n" + "\n".join(overview_lines) + ("\n..." if len(original_code.splitlines()) > 60 else "") ) else: file_overview = ""
# Build the internal bug reference block (never shown verbatim to student) bug_blocks: list[str] = [] for i, fn in enumerate(bug_func_names, 1): sabot = sabot_sources[i - 1] if i - 1 < len(sabot_sources) else "" orig = orig_sources[i - 1] if i - 1 < len(orig_sources) else "" block = f"Bug #{i} β function `{fn}`:" if sabot: block += f"\n SABOTAGED (what the student sees):\n{sabot}" if orig: block += f"\n CORRECT (what it should look like):\n{orig}" bug_blocks.append(block)
bug_reference = ( "\n\nBUG REFERENCE (for your eyes only β use this to understand the bug and craft hints):\n" + "\n\n".join(bug_blocks) if bug_blocks else "" )
# Build the hint-policy section of the system prompt. # ALL levels must use the BUG REFERENCE to craft a targeted hint β never give generic advice. primary_bug_func = bug_func_names[0] if bug_func_names else "" if allow_level == 0: policy = ( f"HINT POLICY β LEVEL 0 (1st hint β subtle, behavior-level clue):\n" f" Use the BUG REFERENCE to understand the actual bug. Then craft a hint that:\n" f" β
Focuses on the OBSERVABLE BEHAVIOR that is wrong " f"(e.g. 'think about what the function should return when the input is X').\n" f" β
Asks the student a targeted question about the specific behavior the bug affects " f"β without saying where in the code the problem is.\n" f" β DO NOT mention which function contains the bug.\n" f" β DO NOT name the bug category (no 'off-by-one', 'wrong operator', etc.).\n" f" β NEVER give generic debugging advice like 'trace the flow' or 'check edge cases' " f"β the hint must be specific to THIS code and THIS bug." ) elif allow_level == 1: policy = ( f"HINT POLICY β LEVEL 1 (2nd hint β structural clue):\n" f" Use the BUG REFERENCE to understand the actual bug. Then craft a hint that:\n" f" β
Tells the student the bug is NOT in `{func_name}` itself, but in a " f"helper function that `{func_name}` calls internally.\n" f" β
Points the student toward the specific part of `{func_name}`'s behavior " f"that is broken, so they can trace which helper is responsible.\n" f" β DO NOT name the helper function.\n" f" β DO NOT describe the bug type yet." ) elif allow_level == 2: bug_category_hint = "" if orig_sources and sabot_sources: bug_category_hint = ( f" β
Based on the BUG REFERENCE you can see the difference β describe the " f"general category of the bug " f"(e.g. 'an off-by-one boundary', 'a wrong comparison operator', " f"'a subtle variable mix-up', 'an incorrect arithmetic operation').\n" ) policy = ( f"HINT POLICY β LEVEL 2 (3rd hint β bug category revealed):\n" f" Use the BUG REFERENCE to understand the actual bug. Then craft a hint that:\n" + bug_category_hint + f" β
Confirms the bug is inside a helper called by `{func_name}` " f"(without naming it).\n" f" β Still DO NOT name the exact function." ) else: target = primary_bug_func if primary_bug_func else f"a helper function called by {func_name}" policy = ( f"HINT POLICY β LEVEL 3 (4thβ5th hint β function name revealed):\n" f" The student has used many hints. Now craft a hint that:\n" f" β
Names the specific function: tell the student the bug is in `{target}`.\n" f" β
Describes what to look for inside that function " f"(without showing the fix or naming the exact line).\n" f" β Still DO NOT show corrected code or say exactly what to change." )
hints_remaining = MAX_HINTS - hints_used current_penalty = _HINT_PENALTY[min(hints_used, len(_HINT_PENALTY) - 1)] next_penalty = _HINT_PENALTY[min(hints_used + 1, len(_HINT_PENALTY) - 1)] penalty_schedule = " β ".join(f"β{p}" for p in _HINT_PENALTY[1:])
# ββ Detect confirmation-then-response flow (must run before system_prompt is built) ββ def _msg_text(msg) -> str: c = msg.get("content", "") if isinstance(msg, dict) else "" if isinstance(c, list): c = " ".join(str(p) for p in c if p) return str(c) if c else ""
last_user_msg_raw = _msg_text(state["messages"][-1]).strip() if state["messages"] else "" last_user_msg = last_user_msg_raw.lower()
# Detect the language from the user's message so the LLM can be instructed explicitly. def _detect_language(text: str) -> str: """Return a human-readable language name based on the script used.""" for ch in text: cp = ord(ch) if 0x0590 <= cp <= 0x05FF: # Hebrew block return "Hebrew" if 0x0600 <= cp <= 0x06FF: # Arabic block return "Arabic" if 0x0400 <= cp <= 0x04FF: # Cyrillic block return "Russian" if 0x4E00 <= cp <= 0x9FFF: # CJK block return "Chinese" return "English"
_user_language = _detect_language(last_user_msg_raw)
# Detect explicit DECLINES β multilingual (English + Hebrew + other common). _declines = { # English "no", "nope", "nah", "not now", "nevermind", "never mind", "no thanks", "no thank you", "skip", "cancel", "forget it", "don't", "dont", "no hint", "stop", # Hebrew "ΧΧ", "ΧΧ ΧͺΧΧΧ", "ΧΧ Χ¨ΧΧ¦Χ", "ΧΧ Χ¦Χ¨ΧΧ", "ΧΧ Χ’ΧΧ©ΧΧ", "ΧΧΧ", "Χ’Χ¦ΧΧ¨", # Other common "non", "nein", "Π½Π΅Ρ", "ΩΨ§", } _is_decline = ( last_user_msg in _declines or last_user_msg.startswith("no ") or last_user_msg.startswith("don't") or last_user_msg.startswith("dont") or last_user_msg.startswith("nope") or last_user_msg.startswith("nah ") or last_user_msg.startswith("ΧΧ ") )
_prev_was_confirmation = False for _m in reversed(state["messages"][:-1]): if isinstance(_m, dict) and _m.get("role") == "assistant": if "gave_hint" in _m: _prev_was_confirmation = not _m["gave_hint"] else: _cl = _msg_text(_m).lower() _prev_was_confirmation = any(kw in _cl for kw in ["would you like", "proceed", "penalty to your score"]) break
# When the previous AI message was a confirmation question, the student's current # response IS their answer to it. Give the hint unless they explicitly declined. _student_accepted_hint = _prev_was_confirmation and not _is_decline
_confirmed_hint_instruction = ( "\n\nβ οΈ CONFIRMED HINT: The student has just responded to your confirmation request " "and accepted the hint. Do NOT ask for confirmation again. " "Give the hint now and mark GAVE_HINT:YES." if _student_accepted_hint else "" )
system_prompt = f"""You are a helpful coding mentor for a legacy code debugging challenge.LANGUAGE RULE (mandatory β never violate):The student's most recent message is written in {_user_language}.You MUST respond entirely in {_user_language}. Do not use any other language, even partially.
CHALLENGE CONTEXT:- There may be multiple bugs β use the BUG REFERENCE below to know exactly what they are- The fix for each bug is 1β3 lines (minimal change)- The code may have confusing variable names β that is intentional{file_overview}{bug_reference}
SCORING & PENALTY RULES (share this with the student if they ask):- Hints cause a cumulative point deduction from their final score- Penalty schedule (cumulative): {penalty_schedule} pts for hints 1β{MAX_HINTS}- Current status: {hints_used} hint(s) used β current penalty is β{current_penalty} pts- Hints remaining: {hints_remaining} (maximum is {MAX_HINTS} total)- If they use the next hint, penalty becomes β{next_penalty} pts
CHALLENGE INTERFACE β you know how the UI works and can guide the student:- **π Challenge tab** β shows the challenge README with mission, constraints, and scoring info.- **π» Code Editor tab** β browse and edit any file in the workspace. Use the file dropdown to switch files. Click πΎ Save to save changes. `challenge_run.py` is also visible here.- **π§ͺ Test Results tab** β click βΆ Run Tests to execute the public test suite and see pass/fail output.- **ποΈ My Changes tab** β shows a diff of all edits made since the challenge started.- **π Submit Fix button** β submits the current saved code for final AI evaluation.- The student can also edit files in their local IDE; changes are picked up automatically on submit.- To run tests locally: `python challenge_run.py` from the workspace directory.
You can help the student with any of the above β navigating the UI, running tests, saving files,understanding what a tab shows, or how to submit. These answers are free and do not count as hints.
{policy}
UNIVERSAL RULES (always apply):1. NEVER write or suggest the corrected code β use the BUG REFERENCE only to understand the bug2. NEVER tell the student exactly which value, operator, or variable to change3. Be encouraging and supportive4. Keep responses concise β 2β3 short paragraphs maximum5. Use guiding questions rather than direct answers when possible6. NO REPEATED HINTS β before writing a hint, review every previous assistant message in this conversation. If you already pointed the student in a certain direction (e.g. "trace the call chain", "look at boundary conditions"), do NOT repeat the same advice. Each new hint must add new, progressive information that moves the student one step closer to the bug. If you have nothing new to add within the current allow_level, say so honestly and encourage the student to try what was already suggested before asking for another hint.
HINT CONFIRMATION RULE (critical):- Before giving any substantive debugging hint (GAVE_HINT:YES), you MUST first ask for confirmation β UNLESS the most recent assistant message in the conversation (the last AI turn above) was already a confirmation question for THIS same request.- Confirmation message to use (word for word at the relevant language): "I can give you a hint, but keep in mind it will add β{next_penalty} pts penalty to your score (you've used {hints_used} hint(s) so far, {hints_remaining} remaining). Would you like me to proceed?" Do NOT give the actual hint in that response β mark it GAVE_HINT:NO.- If the last AI message was already asking for confirmation AND the student's current message is an affirmation ("yes", "go ahead", "sure", "proceed", "ok", etc.), then give the hint directly without asking again.- Each new hint request requires a fresh confirmation β the student saying "yes" once does NOT give blanket permission for all future hints.- If the student asks about the UI, navigation, how to run tests, or other non-debugging questions, answer directly β no confirmation needed, these are free.
HINT TRACKING:At the very end of your response, write the following lines (each on its own line):1. Exactly one of: GAVE_HINT:YES β when you provide substantive debugging guidance (including the response where the student confirmed and you are now giving the actual hint). GAVE_HINT:NO β ONLY when you: (a) asked a confirmation question and did NOT yet give the hint, OR (b) answered a UI/navigation/scoring question only, OR (c) gave only encouragement with zero debugging content2. If and only if GAVE_HINT:YES, also write on the next line: HINT_SUMMARY: <one short sentence (max 120 chars) summarising what aspect of the bug you hinted at> Do NOT write HINT_SUMMARY if GAVE_HINT:NO.{_confirmed_hint_instruction}"""
llm = ChatOpenAI(model="gpt-4o", temperature=0.7, request_timeout=60)
# Reconstruct the conversation for the LLM lc_messages: list = [SystemMessage(content=system_prompt)] for msg in state["messages"]: if msg["role"] == "user": lc_messages.append(HumanMessage(content=msg["content"])) elif msg["role"] == "assistant": lc_messages.append(AIMessage(content=msg["content"]))
try: resp = llm.invoke(lc_messages) raw = resp.content # Parse and strip GAVE_HINT and HINT_SUMMARY markers from the tail gave_hint = False hint_summary = "" lines = raw.rstrip().split("\n") # Strip HINT_SUMMARY line (appears after GAVE_HINT) if lines and lines[-1].strip().startswith("HINT_SUMMARY:"): hint_summary = lines[-1].strip()[len("HINT_SUMMARY:"):].strip() lines = lines[:-1] # Strip GAVE_HINT line if lines and lines[-1].strip().startswith("GAVE_HINT:"): gave_hint = lines[-1].strip() == "GAVE_HINT:YES" lines = lines[:-1] raw = "\n".join(lines).rstrip() # Python-level guarantee: if the student accepted the hint (responded to # a confirmation and didn't decline), always count it regardless of LLM. if _student_accepted_hint: gave_hint = True return {**state, "response": raw, "gave_hint": gave_hint, "hint_summary": hint_summary} except Exception as exc: return {**state, "response": f"Sorry, I had trouble generating a hint: {exc}", "gave_hint": False, "hint_summary": ""}
# ββ Graph builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def build_hint_graph(): builder = StateGraph(HintState) builder.add_node("check_policy", node_check_hint_policy) builder.add_node("generate_hint", node_generate_hint) builder.set_entry_point("check_policy") builder.add_edge("check_policy", "generate_hint") builder.add_edge("generate_hint", END) return builder.compile()
# ββ Convenience function for the GUI βββββββββββββββββββββββββββββββββββββββββ
def get_hint( user_message: str, history: list, hints_used: int, submission_attempts: int, challenge_info: dict,) -> dict: """ Get a hint for the student.
Args: user_message: The student's current question. history: List of [user_msg, assistant_msg] pairs (Gradio chatbot format). hints_used: Number of hints used so far (BEFORE this call). submission_attempts: Number of failed submissions. challenge_info: Dict with function_name, bug_func_name, target_file, difficulty_level.
Returns: The assistant's hint as a string. """ # Convert Gradio history to our message list. # Gradio 6 uses dicts {"role": ..., "content": ...}; # older versions used [user, assistant] pairs β handle both. messages: list = [] for entry in history: if isinstance(entry, dict): role = entry.get("role", "") content = entry.get("content", "") if role in ("user", "assistant") and content: msg: dict = {"role": role, "content": content} # Preserve gave_hint metadata so node_generate_hint can detect # whether the previous AI turn was a confirmation question. if "gave_hint" in entry: msg["gave_hint"] = entry["gave_hint"] messages.append(msg) else: human, ai = entry if human: messages.append({"role": "user", "content": human}) if ai: messages.append({"role": "assistant", "content": ai}) messages.append({"role": "user", "content": user_message})
graph = build_hint_graph() result = graph.invoke({ "messages": messages, "hints_used": hints_used, "submission_attempts": submission_attempts, "challenge_info": challenge_info, "allow_level": 0, "response": "", "gave_hint": False, "hint_summary": "", }) return { "response": result["response"], "gave_hint": result["gave_hint"], "hint_summary": result.get("hint_summary", ""), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Challenge Orchestrator nodes: 1. node_run_bug_generator β invoke the existing architect LangGraph pipeline 2. node_save_challenge_state β persist metadata to challenge_state.json 3. node_launch_student_gui β start the Gradio student interface"""
import jsonfrom pathlib import Path
from orchestrator.state import OrchestratorState
# ββ Node 1: call the Bug Generator Agent βββββββββββββββββββββββββββββββββββββ
def node_run_bug_generator(state: OrchestratorState) -> OrchestratorState: """Invoke the existing architect pipeline and collect its output.""" from architect.graph import build_graph as build_architect_graph
print("\n[orchestrator] ββ Step 1/3: Running Bug Generator Agent ββββββββββββββ")
architect_graph = build_architect_graph()
initial_arch_state = { "github_url": state["github_url"], "difficulty_level": state["difficulty_level"], "num_bugs": state["num_bugs"], # remaining fields initialised to empty (architect nodes will populate them) "clone_path": "", "target_file": "", "original_code": "", "sabotaged_code": "", "function_name": "", "test_args": "", "expected_output": "", "actual_output": "", "bug_description": "", "challenge_summary": "", "test_cases": [], "candidate_files": [], "bug_func_name": "", "bug_func_source": "", "bug_func_names": [], "bug_func_sources_list": [], "original_bug_func_sources_list": [], "original_bug_func_source": "", }
result = architect_graph.invoke(initial_arch_state)
print(f"[orchestrator] Bug Generator complete. Workspace: {result.get('clone_path', '?')}")
return { **state, "workspace_path": result.get("clone_path", ""), "target_file": result.get("target_file", ""), "original_code": result.get("original_code", ""), "sabotaged_code": result.get("sabotaged_code", ""), "function_name": result.get("function_name", ""), "bug_func_name": result.get("bug_func_name", ""), "bug_func_source": result.get("bug_func_source", ""), "test_cases": result.get("test_cases", []), "bug_description": result.get("bug_description", ""), "bug_func_names": result.get("bug_func_names", []), "bug_func_sources_list": result.get("bug_func_sources_list", []), "original_bug_func_sources_list": result.get("original_bug_func_sources_list", []), }
# ββ Node 2: save challenge_state.json ββββββββββββββββββββββββββββββββββββββββ
def node_save_challenge_state(state: OrchestratorState) -> OrchestratorState: """Write all architect metadata to <workspace>/challenge_state.json.""" print("\n[orchestrator] ββ Step 2/3: Saving challenge state ββββββββββββββββββ")
workspace = Path(state["workspace_path"]) if not workspace.exists(): print(f"[orchestrator] WARNING: workspace path does not exist: {workspace}")
challenge_state = { "github_url": state["github_url"], "workspace_path": str(workspace), "target_file": state["target_file"], "original_code": state["original_code"], "sabotaged_code": state["sabotaged_code"], "function_name": state["function_name"], "bug_func_name": state["bug_func_name"], "bug_func_source": state["bug_func_source"], "test_cases": state["test_cases"], "difficulty_level": state["difficulty_level"], "bug_description": state["bug_description"], # POST-INFLATE versions (used by comparison system) "bug_func_names": state.get("bug_func_names", []), "bug_func_sources_list": state.get("bug_func_sources_list", []), "original_bug_func_sources_list": state.get("original_bug_func_sources_list", []), # PRE-INFLATE versions (for debugging/reference) "pre_inflate_bug_sources": state.get("pre_inflate_bug_sources", []), "pre_inflate_original_sources": state.get("pre_inflate_original_sources", []), "nesting_level": state.get("nesting_level", 3), "refactoring_enabled": state.get("refactoring_enabled", False), "debug_mode": state.get("debug_mode", False), }
state_path = workspace / "challenge_state.json" with open(state_path, "w", encoding="utf-8") as f: json.dump(challenge_state, f, indent=2, ensure_ascii=False)
print(f"[orchestrator] Challenge state saved β {state_path}") return {**state, "challenge_state_path": str(state_path)}
# ββ Node 3: launch the student Gradio GUI ββββββββββββββββββββββββββββββββββββ
def node_launch_student_gui(state: OrchestratorState) -> OrchestratorState: """Import student_interface and launch Gradio.""" import student_interface
port = state.get("port", 7860) share = state.get("share", False)
print(f"\n[orchestrator] ββ Step 3/3: Launching student GUI βββββββββββββββββ") print(f"[orchestrator] Opening http://localhost:{port} ...")
import gradio as gr interface = student_interface.create_interface(state["workspace_path"]) interface.launch( server_name="127.0.0.1", server_port=port, share=share, inbrowser=True, theme=gr.themes.Soft(), css=student_interface._CSS, )
return {**state, "launch_status": f"Launched on port {port}"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436"""Scoring Engine for the Legacy Code Challenge.
Score breakdown: - LLM score : 0β100 pts (LLM evaluates fix quality, minimality, and test results) - Hint penalty : cumulative deduction per hint used (β2, β6, β12, β20, β30 max) - Total : max(0, llm_score β hint_penalty)"""
import astimport jsonimport subprocessimport sysfrom pathlib import Path
from langchain_openai import ChatOpenAIfrom langchain_core.messages import SystemMessage, HumanMessage
# Cumulative penalty after N hints used (index = number of hints)HINT_PENALTY = [0, 2, 6, 12, 20, 30]
# ββ Test runner βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _run_test_file(workspace_path: str, filename: str) -> dict: """ Execute a test file (challenge_run.py or challenge_run_secret.py) and parse output.
Returns a dict: passed : int β number of passing cases total : int β total cases executed score : int β 0β80 pts output : str β full stdout+stderr text all_passed : bool """ workspace = Path(workspace_path) test_file = workspace / filename
if not test_file.exists(): return { "passed": 0, "total": 0, "score": 0, "output": f"Error: {filename} not found in workspace.", "all_passed": False, }
try: result = subprocess.run( [sys.executable, str(test_file)], cwd=str(workspace), capture_output=True, text=True, encoding="utf-8", timeout=15, ) output = (result.stdout or "") + (result.stderr or "") except subprocess.TimeoutExpired: return { "passed": 0, "total": 0, "score": 0, "output": "Error: Tests timed out (possible infinite loop).", "all_passed": False, } except Exception as exc: return { "passed": 0, "total": 0, "score": 0, "output": f"Error running tests: {exc}", "all_passed": False, }
# Parse "Test N: [PASS] / [FAIL] / [CRASH]" lines passed = total = 0 per_test: list[dict] = [] # [{num, status}] for line in output.split("\n"): stripped = line.strip() if stripped.startswith("Test") and ("PASS" in stripped or "FAIL" in stripped or "CRASH" in stripped): import re as _re m = _re.match(r"Test\s+(\d+):\s+\[?(PASS|FAIL|CRASH)", stripped) if m: num, status = int(m.group(1)), m.group(2) per_test.append({"num": num, "status": status}) total += 1 if status == "PASS": passed += 1
all_passed = passed > 0 and passed == total score = int((passed / total) * 80) if total > 0 else 0
return { "passed": passed, "total": total, "score": score, "output": output.strip(), "all_passed": all_passed, "per_test": per_test, }
def run_tests(workspace_path: str) -> dict: """Run public tests (challenge_run.py) β shown to student during practice.""" return _run_test_file(workspace_path, "challenge_run.py")
def run_secret_tests(workspace_path: str) -> dict: """Run secret tests (challenge_run_secret.py) β used for final submission scoring.""" return _run_test_file(workspace_path, ".metadata/challenge_run_secret.py")
# ββ Function extractor ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _extract_all_funcs(code: str) -> dict[str, str]: """Return {func_name: source_lines} for every top-level or nested function.""" try: tree = ast.parse(code) except SyntaxError: return {} result = {} lines = code.splitlines() for node in ast.walk(tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): result[node.name] = "\n".join(lines[node.lineno - 1: node.end_lineno]) return result
# ββ Hint penalty ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def hint_penalty(hints_used: int) -> int: """Return the cumulative score deduction for the number of hints used.""" return HINT_PENALTY[min(hints_used, len(HINT_PENALTY) - 1)]
# ββ Location check ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def check_fix_location(original_code: str, student_code: str, bug_func_name: str) -> bool: """ Return True if the student's change touched the function that contains the bug (bug_func_name). Used only for feedback; does not affect score. """ if not bug_func_name: return True
try: orig_tree = ast.parse(original_code) student_tree = ast.parse(student_code) except SyntaxError: return False
def func_source(tree: ast.AST, name: str) -> str | None: for node in ast.walk(tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name: return ast.unparse(node) return None
orig_func = func_source(orig_tree, bug_func_name) student_func = func_source(student_tree, bug_func_name)
if orig_func is None or student_func is None: return True
return orig_func != student_func
# ββ LLM scorer ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_LLM_SYSTEM_PROMPT = """\You are an expert code reviewer evaluating a student's fix for a programming challenge.
The student received a Python file with one or more deliberately injected bugs and was askedto fix ALL of them with MINIMAL changes β ideally 1β3 lines per bug, without renamingvariables or restructuring logic.
You will be given:1. Every bug function: the buggy version, the student's version, and the expected fix. Functions marked "NOT FIXED" were not touched by the student at all.2. Test results BEFORE the student's change (run on the buggy code).3. Test results AFTER the student's change (run on their submitted code).
Evaluate the submission on these criteria:- Correctness (0β50 pts): Do the tests pass after the fix? Is ALL the logic correct? Deduct heavily if the student left any bug unfixed (marked "NOT FIXED").- Minimality (0β30 pts): Did the student change only what was necessary? A fix that changes exactly the right token(s) scores 30. Extra rewrites lose points.- Quality (0β20 pts): Does the fix match the expected solution in intent and style? A fix that perfectly matches the expected approach scores 20.
If any bug function is marked "NOT FIXED", the Correctness score must be significantlyreduced (by at least 20 pts per unfixed bug) regardless of test results.
Respond ONLY with a valid JSON object β no markdown, no extra text:{"score": <integer 0-100>, "explanation": "<2-4 sentence explanation>"}"""
def llm_score_submission( changed_funcs: list[dict], test_before_passed: int, test_before_total: int, test_after_passed: int, test_after_total: int, test_output: str, per_test_before: list[dict] | None = None, per_test_after: list[dict] | None = None,) -> dict: """ Ask the LLM to score the submission 0β100 and return an explanation.
changed_funcs: list of {name, buggy, student, expected} Returns: {score: int, explanation: str} """ # Build the function-by-function section func_sections = [] for i, f in enumerate(changed_funcs, 1): if f.get("unfixed"): header = f"### Function {i}: `{f['name']}` β β οΈ NOT FIXED BY STUDENT" student_label = "**Student's version (unchanged β bug still present):**" else: header = f"### Function {i}: `{f['name']}`" student_label = "**Student's fix:**" func_sections.append( f"{header}\n\n" f"**Buggy version (received by student):**\n```python\n{f['buggy']}\n```\n\n" f"{student_label}\n```python\n{f['student']}\n```\n\n" f"**Expected correct version:**\n```python\n{f['expected']}\n```" )
funcs_text = "\n\n".join(func_sections) if func_sections else "(no function changes detected)"
# Build per-test comparison table if we have both before and after breakdowns per_test_section = "" if per_test_before and per_test_after: before_map = {t["num"]: t["status"] for t in per_test_before} after_map = {t["num"]: t["status"] for t in per_test_after} all_nums = sorted(set(before_map) | set(after_map)) rows = [] for n in all_nums: b = before_map.get(n, "β") a = after_map.get(n, "β") change = "" if b != a: change = f" β changed ({b} β {a})" rows.append(f" Test {n:2d}: before={b:<5} after={a}{change}") per_test_section = "\n\n## Per-Test Breakdown\n```\n" + "\n".join(rows) + "\n```"
human_text = ( f"## Changed Functions\n\n{funcs_text}\n\n" f"## Test Results\n" f"- Before student's fix: {test_before_passed}/{test_before_total} tests passed\n" f"- After student's fix: {test_after_passed}/{test_after_total} tests passed" f"{per_test_section}\n\n" f"## Test Output (after fix)\n```\n{test_output[:2000]}\n```" )
try: llm = ChatOpenAI(model="gpt-4o", temperature=0, request_timeout=60) response = llm.invoke([ SystemMessage(content=_LLM_SYSTEM_PROMPT), HumanMessage(content=human_text), ]) raw = response.content.strip() # Strip markdown code fences if the model wraps the JSON if raw.startswith("```"): raw = raw.split("```")[1] if raw.startswith("json"): raw = raw[4:] data = json.loads(raw) score = max(0, min(100, int(data.get("score", 0)))) explanation = str(data.get("explanation", "")) return {"score": score, "explanation": explanation} except Exception as exc: # Fallback: derive a simple score from test results so the UI never crashes if test_after_total > 0: ratio = test_after_passed / test_after_total fallback_score = int(ratio * 100) else: fallback_score = 0 return { "score": fallback_score, "explanation": f"LLM scoring unavailable ({exc}). Score based on test results only.", }
# ββ Baseline test runner (sabotaged code) βββββββββββββββββββββββββββββββββββββ
def _run_tests_on_sabotaged(workspace_path: str, target_file: str, sabotaged_code: str) -> dict: """ Temporarily write sabotaged_code to target_file, run both test files, then restore the original content. Returns {passed, total, per_test: [{num, status}]}. """ target = Path(target_file) try: original_content = target.read_text(encoding="utf-8") except Exception: return {"passed": 0, "total": 0, "per_test": []} try: target.write_text(sabotaged_code, encoding="utf-8") pub = run_tests(workspace_path) sec = run_secret_tests(workspace_path) # Offset secret test numbers so they don't collide with public ones offset = pub["total"] sec_per = [{"num": t["num"] + offset, "status": t["status"]} for t in sec.get("per_test", [])] return { "passed": pub["passed"] + sec["passed"], "total": pub["total"] + sec["total"], "per_test": pub.get("per_test", []) + sec_per, } except Exception: return {"passed": 0, "total": 0, "per_test": []} finally: try: target.write_text(original_content, encoding="utf-8") except Exception: pass
# ββ Master evaluator βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def evaluate_submission( workspace_path: str, student_code: str, original_code: str, bug_func_name: str, hints_used: int, sabotaged_code: str = "", target_file: str = "", bug_func_names: list | None = None,) -> dict: """ Full evaluation of a student submission.
Runs both public and secret tests, then asks an LLM to score the fix quality.
Returns a dict with all score components and diagnostic fields: llm_score : int (0-100, from LLM) llm_explanation : str (LLM's explanation) hint_penalty : int (0-30, subtracted) total_score : int (0-100, clamped to 0) passed : int (combined public + secret) total_tests : int all_passed : bool test_output : str (combined output) public_output : str secret_output : str correct_location : bool (informational only) """ public_result = run_tests(workspace_path) secret_result = run_secret_tests(workspace_path)
combined_passed = public_result["passed"] + secret_result["passed"] combined_total = public_result["total"] + secret_result["total"] all_passed = combined_passed > 0 and combined_passed == combined_total
combined_output = ( "-- Public Tests --\n" + public_result["output"] + "\n\n" "-- Secret Tests --\n" + secret_result["output"] ).strip()
# Identify which functions the student changed vs the sabotaged baseline ref_code = sabotaged_code if sabotaged_code else original_code ref_funcs = _extract_all_funcs(ref_code) stu_funcs = _extract_all_funcs(student_code) orig_funcs = _extract_all_funcs(original_code)
common = set(ref_funcs) & set(stu_funcs) changed_funcs = [] for name in sorted(common): if ref_funcs[name] != stu_funcs[name]: changed_funcs.append({ "name": name, "buggy": ref_funcs[name], "student": stu_funcs[name], "expected": orig_funcs.get(name, "(not found in original)"), })
# For every expected bug function the student did NOT change, add it as # "unfixed" so the LLM sees the full picture and penalises accordingly. all_bug_names = bug_func_names or ([bug_func_name] if bug_func_name else []) changed_names = {f["name"] for f in changed_funcs} for fn in all_bug_names: if fn and fn not in changed_names: buggy_ver = ref_funcs.get(fn, "") student_ver = stu_funcs.get(fn, buggy_ver) expected_ver = orig_funcs.get(fn, "") if buggy_ver: changed_funcs.append({ "name": fn, "buggy": buggy_ver, "student": student_ver, "expected": expected_ver or "(not found in original)", "unfixed": True, })
# Collect per-test results for the "after" state (offset secret test numbers) offset = public_result["total"] sec_per_after = [{"num": t["num"] + offset, "status": t["status"]} for t in secret_result.get("per_test", [])] per_test_after = public_result.get("per_test", []) + sec_per_after
# Run tests on the sabotaged baseline so we can report accurate before/after counts. if target_file and sabotaged_code: before_result = _run_tests_on_sabotaged(workspace_path, target_file, sabotaged_code) before_passed = before_result["passed"] before_total = before_result["total"] per_test_before = before_result["per_test"] else: before_passed, before_total, per_test_before = 0, combined_total, []
# LLM scores the submission 0-100 llm_result = llm_score_submission( changed_funcs=changed_funcs, test_before_passed=before_passed, test_before_total=before_total, test_after_passed=combined_passed, test_after_total=combined_total, test_output=combined_output, per_test_before=per_test_before, per_test_after=per_test_after, )
penalty = hint_penalty(hints_used) total = max(0, llm_result["score"] - penalty) correct_loc = check_fix_location(original_code, student_code, bug_func_name)
return { "llm_score": llm_result["score"], "llm_explanation": llm_result["explanation"], "hint_penalty": penalty, "total_score": total, "passed": combined_passed, "total_tests": combined_total, "all_passed": all_passed, "test_output": combined_output, "public_output": public_result["output"], "secret_output": secret_result["output"], "correct_location": correct_loc, # Keep these for backwards compatibility with any display code "test_score": int((combined_passed / combined_total) * 80) if combined_total > 0 else 0, "diff_score": 0, }1234567891011121314151617181920212223242526272829"""OrchestratorState β shared state for the Challenge Orchestrator LangGraph."""
from typing import TypedDict
class OrchestratorState(TypedDict): # ββ Input (set by challenge.py CLI) βββββββββββββββββββββββββββββββββββββββ github_url: str difficulty_level: int num_bugs: int port: int share: bool
# ββ Filled by node_run_bug_generator ββββββββββββββββββββββββββββββββββββββ workspace_path: str # absolute path to the cloned workspace directory target_file: str # relative path of the sabotaged file (e.g. boltons\formatutils.py) original_code: str # file content BEFORE sabotage (used for diff scoring) sabotaged_code: str # file content AFTER sabotage (what the student receives) function_name: str # public surface function reported as broken bug_func_name: str # internal helper where the bug was actually injected bug_func_source: str # exact source of the buggy helper function test_cases: list # [{"args": str, "expected": str}, ...] verified cases bug_description: str # architect-only description (never shown to student)
# ββ Filled by node_save_challenge_state βββββββββββββββββββββββββββββββββββ challenge_state_path: str # absolute path to the saved challenge_state.json
# ββ Filled by node_launch_student_gui ββββββββββββββββββββββββββββββββββββ launch_status: str # "Launched on port N" or error message123456789101112131415161718services: - type: web name: legacy-code-challenge runtime: python plan: free buildCommand: | apt-get update && apt-get install -y git pip install -r requirements.txt startCommand: bash start_render.sh healthCheckPath: / envVars: - key: OPENAI_API_KEY sync: false - key: PYTHON_VERSION value: 3.11.0 - key: PORT value: 10000 autoDeploy: true12345678910langchain-openailanggraphlangchain-coregitpythonpython-dotenvgradiopywebviewuvicorn[standard]gspreadgoogle-auth1python-3.11.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111# Session Storage Solution for Refresh Problem
## ΧΧΧ’ΧΧ:ΧΧ©Χ’ΧΧ©ΧΧ F5 (refresh) ΧΧΧ€ΧΧ€Χ, ΧΧΧΧ©Χ§ ΧΧΧΧ¨ ΧΧΧ£ ΧΧΧ¨Χ©ΧΧ ΧΧΧΧ©ΧͺΧΧ© Χ¦Χ¨ΧΧ ΧΧΧΧ ΧΧ‘ Χ©ΧΧ ΧΧͺ Χ-API key.
## ΧΧ€ΧͺΧ¨ΧΧ:Χ©ΧΧΧΧ© Χ-**sessionStorage** Χ©Χ ΧΧΧ€ΧΧ€Χ - Χ©ΧΧΧ¨ Χ ΧͺΧΧ ΧΧ Χ’Χ Χ©Χ‘ΧΧΧ¨ΧΧ ΧΧͺ ΧΧΧΧ.
---
## ΧΧΧ©ΧΧ:
### 1. ΧΧΧ‘Χ£ JavaScript ΧΧ©ΧΧΧ¨Χ/ΧΧ’ΧΧ Χ:
```javascript// ΧΧͺΧΧ _make_js() function, ΧΧΧ‘Χ£:
// Save to sessionStorage when user logs inwindow.saveUserSession = function(name, apiKey) { sessionStorage.setItem('userName', name); sessionStorage.setItem('userApiKey', apiKey);};
// Load from sessionStorage on page loadwindow.loadUserSession = function() { const name = sessionStorage.getItem('userName'); const apiKey = sessionStorage.getItem('userApiKey'); return { name: name || '', apiKey: apiKey || '' };};
// Clear session on logoutwindow.clearUserSession = function() { sessionStorage.removeItem('userName'); sessionStorage.removeItem('userApiKey');};
// Auto-restore on page load(function() { const session = window.loadUserSession(); if (session.name && session.apiKey) { // Trigger auto-login document.dispatchEvent(new CustomEvent('autoLogin', { detail: session })); }})();```
### 2. ΧΧ€ΧΧ Χ§Χ¦ΧΧΧͺ on_login():
```pythondef on_login(name, api_key): if not name.strip(): return (...) valid, msg = validate_openai_key(api_key) if not valid: return (...) # Success - save to session storage via JavaScript import os os.environ["OPENAI_API_KEY"] = api_key return ( gr.update(visible=False, js="window.saveUserSession(arguments[0], arguments[1])"), gr.update(visible=True), msg, api_key, name.strip() )```
---
## π ΧΧΧΧΧ:
**sessionStorage** ΧΧΧ‘ΧΧͺ ΧΧΧΧ ΧΧ:- β
ΧΧ Χ Χ©ΧΧ ΧΧ©Χ¨Χͺ (Χ Χ©ΧΧ¨ ΧΧΧ€ΧΧ€Χ)- β
Χ ΧΧΧ§ ΧΧ©Χ‘ΧΧΧ¨ΧΧ ΧΧͺ ΧΧΧΧ- β
ΧΧ Χ ΧΧΧ© ΧΧΧΧΧΧ ΧΧΧ¨ΧΧ- β οΈ Χ’ΧΧΧΧ vulnerable Χ-XSS (ΧΧ ΧΧ© ΧΧΧΧ©Χ ΧΧΧͺΧ¨)
---
## ΧΧΧΧ¨Χ ΧΧΧΧΧͺ:
### 2οΈβ£ **ΧΧ¦Χ’Χ Χ€Χ©ΧΧΧ ΧΧΧͺΧ¨: ΧͺΧ ΧΧΧ©ΧͺΧΧ© ΧΧΧΧ©ΧΧ¨ ΧΧΧΧΧ¨**
ΧΧΧ§ΧΧ ΧΧΧ’ΧΧ ΧΧΧΧ© ΧΧͺ ΧΧ ΧΧΧ£, ΧΧ€Χ©Χ¨:- ΧΧΧΧ‘ΧΧ£ ΧΧ€ΧͺΧΧ¨ "π Logout" ΧΧ€ΧΧ Χ- ΧΧΧ©ΧͺΧΧ© ΧΧΧ©ΧΧ¨ ΧΧΧΧΧ¨ ΧΧ Χ’ΧΧ ΧΧΧ ΧΧ Χ’ΧΧ©Χ logout- ΧΧ ΧΧ‘ΧΧ ΧΧ¨Χ ΧΧ¨ΧΧ ΧΧΧͺΧ¨ΧΧ!
### 3οΈβ£ **Server-side sessions (ΧΧΧ¨ΧΧ ΧΧΧͺΧ¨)**
Χ¦Χ¨ΧΧ:- Database ΧΧ Redis ΧΧ©ΧΧΧ¨ sessions- Authentication middleware- ΧΧΧͺΧ¨ ΧΧͺΧΧΧ Χ-production
---
## ΧΧΧΧ¦Χ:
**ΧΧ€Χ ΧΧ©ΧΧΧΧ© Χ©ΧΧ:**
1. **ΧΧΧ¦ΧΧͺ/ΧΧΧ** β ΧΧ€Χ©Χ¨ refresh = ΧΧΧ¨Χ ΧΧΧͺΧΧΧ¨ΧΧͺ (ΧΧΧ Χ€Χ©ΧΧ)2. **ΧΧ©ΧΧΧΧ© ΧΧΧΧͺΧ** β sessionStorage (ΧΧΧ Χ-99% ΧΧΧΧ§Χ¨ΧΧ)3. **Production Χ¨Χ¦ΧΧ Χ** β Server-side sessions + database
Χ¨ΧΧ¦Χ Χ©ΧΧΧΧ©Χ ΧΧͺ sessionStorage? π123456789101112131415#!/bin/bash
# Start script for hosting platforms (Render, Heroku, etc.)
echo "π Starting Legacy Code Challenge..."
# Install dependencies if neededif [ ! -d "venv" ]; then echo "π¦ Installing dependencies..." pip install -r requirements.txtfi
# Launch the interfaceecho "π Launching Gradio interface..."python main.py1234#!/bin/bash# Render startup script - run Gradio directlyecho "π Starting Gradio application..."exec python app.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091"""Student Interface β Gradio GUI for the Legacy Code Challenge.
Two-page flow: Page 1 (Setup): student name, GitHub URL, nesting level, num-bugs, options β Start Page 2 (Challenge): README, Code Editor, Test runner + AI Assistant sidebar Page 3 (Results): Score breakdown, diffs, test results, hints review"""
from __future__ import annotations
import difflibimport jsonimport osimport sysimport threadingfrom io import StringIOfrom datetime import datetimefrom pathlib import Path
import gradio as gr
from orchestrator.scoring import evaluate_submissionfrom orchestrator.hint_graph import get_hint
# Optional Google Sheets loggingtry: from google_sheets_logger import log_to_google_sheets GOOGLE_SHEETS_AVAILABLE = Trueexcept ImportError: GOOGLE_SHEETS_AVAILABLE = False
# Optional Git submissions backuptry: from git_submissions_logger import push_submission_to_git GIT_SUBMISSIONS_AVAILABLE = Trueexcept ImportError: GIT_SUBMISSIONS_AVAILABLE = False
# Optional Git submissions backuptry: from git_submissions_logger import push_submission_to_git GIT_SUBMISSIONS_AVAILABLE = Trueexcept ImportError: GIT_SUBMISSIONS_AVAILABLE = False
# ββ API Key Validation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def validate_openai_key(api_key: str) -> tuple[bool, str]: """Validate OpenAI API key by making a test call.""" if not api_key or not api_key.startswith("sk-"): return False, "β Invalid API key format. Must start with 'sk-'" try: os.environ["OPENAI_API_KEY"] = api_key from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o", temperature=0, request_timeout=5, max_tokens=5) llm.invoke("test") return True, "β
API key validated!" except Exception as e: error = str(e) if "401" in error or "Incorrect API key" in error: return False, "β Invalid API key" elif "quota" in error.lower(): return False, "β οΈ API key valid but no quota remaining" elif "timeout" in error.lower(): return True, "β
Key accepted (validation timed out - will verify during use)" return True, "β
Key accepted (couldn't fully verify)"
# ββ Challenge state loader ββββββββββββββββββββββββββββββββββββββββββββββββββββ
class ChallengeState: """Loads and exposes data from challenge_state.json."""
def __init__(self, workspace_path: str) -> None: self.workspace = Path(workspace_path) state_file = self.workspace / "challenge_state.json" if not state_file.exists(): raise FileNotFoundError(f"challenge_state.json not found in {workspace_path}") with open(state_file, encoding="utf-8") as f: data = json.load(f)
self.github_url: str = data.get("github_url", "") # Normalise to forward slashes so comparisons work cross-platform raw_target = data.get("target_file", "") try: self.target_file: str = Path(raw_target).resolve().relative_to(self.workspace.resolve()).as_posix() except (ValueError, OSError): self.target_file = Path(raw_target).as_posix() self.original_code: str = data.get("original_code", "") self.sabotaged_code: str = data.get("sabotaged_code", "") self.function_name: str = data.get("function_name", "") self.bug_func_name: str = data.get("bug_func_name", "") self.original_bug_func_source: str = data.get("original_bug_func_source", "") self.bug_func_names: list = data.get("bug_func_names", []) or ( [self.bug_func_name] if self.bug_func_name else [] ) self.bug_func_sources_list: list = data.get("bug_func_sources_list", []) self.original_bug_func_sources_list: list = data.get("original_bug_func_sources_list", []) self.nesting_level: int = data.get("nesting_level", 3) self.refactoring_enabled: bool = data.get("refactoring_enabled", False) self.debug_mode: bool = data.get("debug_mode", False)
# sabotaged_files: {rel_posix_path: content} for every file the # saboteur touched. Primary source: .metadata/ directory # written by the deployer immediately after sabotage (always up-to-date). # Fallback: sabotaged_files dict in JSON, then single sabotaged_code field. snapshot_dir = self.workspace / ".metadata" snap_files: dict[str, str] = {} if snapshot_dir.exists(): # Get the target file path from the data for proper mapping target_rel_from_json = data.get("target_file", "") if target_rel_from_json: try: # Convert to workspace-relative posix path target_abs = Path(target_rel_from_json).resolve() target_rel = target_abs.relative_to(self.workspace.resolve()).as_posix() except (ValueError, OSError): target_rel = Path(target_rel_from_json).as_posix() # Find the corresponding snapshot file # The snapshot filename has separators replaced with __ expected_snapshot_name = target_rel.replace("/", "__") snapshot_path = snapshot_dir / expected_snapshot_name if snapshot_path.exists(): try: snap_files[target_rel] = snapshot_path.read_text(encoding="utf-8") except Exception: pass
if snap_files: self.sabotaged_files: dict[str, str] = snap_files else: # Fall back to JSON fields stored = data.get("sabotaged_files", {}) if not stored and self.sabotaged_code: try: rel = Path(self.target_file).resolve().relative_to( self.workspace.resolve() ).as_posix() except ValueError: rel = Path(self.target_file).name stored = {rel: self.sabotaged_code} self.sabotaged_files = stored
@property def target_path(self) -> Path: return self.workspace / self.target_file
def read_target(self) -> str: if self.target_path.exists(): return self.target_path.read_text(encoding="utf-8") return self.sabotaged_code
def write_target(self, code: str) -> None: self.target_path.write_text(code, encoding="utf-8")
def reset_target(self) -> None: self.write_target(self.sabotaged_code)
def list_py_files(self) -> list[str]: files = sorted(self.workspace.rglob("*.py")) return [ f.relative_to(self.workspace).as_posix() for f in files if ".metadata" not in f.parts ]
def read_py_file(self, rel_path: str) -> str: full = self.workspace / rel_path if full.exists(): return full.read_text(encoding="utf-8") return f"# File not found: {rel_path}"
def readme(self) -> str: readme_path = self.workspace / "STUDENT_README.md" if readme_path.exists(): return readme_path.read_text(encoding="utf-8") return "# Challenge\n\nREADME not found."
def challenge_info(self) -> dict: return { "function_name": self.function_name, "bug_func_name": self.bug_func_name, "target_file": self.target_file, "nesting_level": self.nesting_level, "refactoring_enabled": self.refactoring_enabled, "debug_mode": self.debug_mode, "bug_func_names": self.bug_func_names, "bug_func_sources_list": self.bug_func_sources_list, "original_bug_func_sources_list": self.original_bug_func_sources_list, "original_code": self.original_code, }
# ββ Submission log ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class SubmissionLog: """Persists submissions to <workspace>/submissions/ as JSON files."""
def __init__(self, workspace: Path) -> None: self.log_dir = workspace / "submissions" self.log_dir.mkdir(exist_ok=True)
def save(self, student_code: str, result: dict, hints_used: int) -> None: ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f") entry = { "timestamp": ts, "hints_used": hints_used, "llm_score": result.get("llm_score", result.get("total_score", 0)), "llm_explanation": result.get("llm_explanation", ""), "hint_penalty": result["hint_penalty"], "total_score": result["total_score"], "passed": result["passed"], "total_tests": result["total_tests"], "all_passed": result["all_passed"], "student_code": student_code, } path = self.log_dir / f"{ts}.json" with open(path, "w", encoding="utf-8") as f: json.dump(entry, f, indent=2, ensure_ascii=False)
# ββ Pipeline runner βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _run_pipeline(github_url: str, nesting_level: int, num_bugs: int, refactoring_enabled: bool = False, debug_mode: bool = False) -> str: """Invoke the architect pipeline and return the workspace path.""" from architect.graph import build_graph
graph = build_graph() result = graph.invoke({ "github_url": github_url, "nesting_level": nesting_level, "refactoring_enabled": refactoring_enabled, "debug_mode": debug_mode, "num_bugs": num_bugs, "clone_path": "", "target_file": "", "original_code": "", "sabotaged_code": "", "function_name": "", "test_args": "", "expected_output": "", "actual_output": "", "bug_description": "", "detailed_explanation": "", "challenge_summary": "", "test_cases": [], "public_tests": [], "secret_tests": [], "candidate_files": [], "bug_func_name": "", "bug_func_source": "", "call_chain": {}, })
workspace_path = result["clone_path"]
# Read the actual file on disk (may differ from state if extra transforms ran) target_file_rel = result.get("target_file", "") actual_sabotaged_code = result.get("sabotaged_code", "") workspace_path_obj = Path(workspace_path).resolve() if target_file_rel: target_path = Path(workspace_path) / target_file_rel if target_path.exists(): actual_sabotaged_code = target_path.read_text(encoding="utf-8")
# Build sabotaged_files: {rel_posix_path: content} for every file the # saboteur modified. Currently always one file (target_file). sabotaged_files: dict[str, str] = {} if target_file_rel and actual_sabotaged_code: try: rel_posix = Path(target_file_rel).resolve().relative_to(workspace_path_obj).as_posix() except (ValueError, OSError): rel_posix = Path(target_file_rel).as_posix() sabotaged_files[rel_posix] = actual_sabotaged_code
# Persist challenge_state.json challenge_state = { "github_url": github_url, "workspace_path": workspace_path, "target_file": target_file_rel, "original_code": result.get("original_code", ""), "sabotaged_code": actual_sabotaged_code, "sabotaged_files": sabotaged_files, "function_name": result.get("function_name", ""), "bug_func_name": result.get("bug_func_name", ""), "bug_func_source": result.get("bug_func_source", ""), "original_bug_func_source": result.get("original_bug_func_source", ""), "bug_func_names": result.get("bug_func_names", []), "bug_func_sources_list": result.get("bug_func_sources_list", []), "original_bug_func_sources_list": result.get("original_bug_func_sources_list", []), "test_cases": result.get("test_cases", []), "public_tests": result.get("public_tests", []), "secret_tests": result.get("secret_tests", []), "nesting_level": nesting_level, "refactoring_enabled": refactoring_enabled, "debug_mode": debug_mode, "bug_description": result.get("bug_description", ""), } state_path = Path(workspace_path) / "challenge_state.json" with open(state_path, "w", encoding="utf-8") as f: json.dump(challenge_state, f, indent=2, ensure_ascii=False)
return workspace_path
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
PENALTY_TABLE = [0, 2, 6, 12, 20, 30]
# Sets dark mode as the default on first visit and defines window.startTimer.def _make_js(timer_minutes: int = 0) -> str: auto_start = ( f""" (function tryStartTimer() {{ if (document.getElementById('timer-inner')) {{ window.startTimer({timer_minutes}); }} else {{ setTimeout(tryStartTimer, 150); }} }})();""" if timer_minutes > 0 else "" ) return """() => { if (!localStorage.getItem('gradio-theme')) { localStorage.setItem('gradio-theme', 'dark'); } window.startTimer = function(minutes) { if (!minutes || minutes <= 0) return; if (window._timerInterval) clearInterval(window._timerInterval); const endTime = Date.now() + minutes * 60 * 1000; function tick() { const remaining = Math.max(0, endTime - Date.now()); const m = Math.floor(remaining / 60000); const s = Math.floor((remaining % 60000) / 1000); const el = document.getElementById('timer-inner'); if (!el) return; if (remaining === 0) { el.innerHTML = '<span style="color:#ef4444;font-weight:bold;font-size:1.1em;">β±οΈ TIME\\'S UP!</span>'; clearInterval(window._timerInterval); } else { const color = remaining < 300000 ? '#ef4444' : (remaining < 600000 ? '#f59e0b' : '#22c55e'); el.innerHTML = 'β±οΈ <span style="font-weight:bold;font-size:1.1em;color:' + color + ';">' + String(m).padStart(2,'0') + ':' + String(s).padStart(2,'0') + '</span>'; } } tick(); window._timerInterval = setInterval(tick, 1000); };""" + auto_start + "\n}"
_JS = _make_js(0)
_CSS = """/* Keep footer visible */footer svg { display: inline !important; }.gradio-container { max-width: 100% !important; }
/* Setup page β centred card */.setup-card { max-width: 700px; margin: 40px auto !important; }
/* Code editor β scrollable */#code-editor .cm-scroller { overflow-y: auto !important; max-height: 60vh !important; }#code-editor .cm-editor { max-height: 60vh !important; }
/* Chatbot */#ai-chatbot .wrap { height: 58vh !important; overflow-y: auto !important; }
/* Tab content */.left-tabs .tabitem { overflow-y: auto !important; max-height: 80vh !important; }
/* Results diff blocks */.diff-block { font-family: monospace; font-size: 0.85em; padding: 12px; border-radius: 8px; overflow-y: auto; max-height: 45vh; white-space: pre; background: #1e1e1e; color: #d4d4d4; }
/* Challenge timer β pushed to the right corner of the header */.header-row { display: flex !important; align-items: center !important; width: 100% !important; gap: 8px; }.header-row > * { flex-shrink: 0 !important; }.header-row > *:first-child { flex: 1 1 auto !important; min-width: 0; }#challenge-timer { flex: 0 0 auto !important; font-family: monospace; font-size: 1em; text-align: right; padding: 4px 8px; min-width: 90px; white-space: nowrap; }"""
def _hint_md(hints_used: int, penalty: int) -> str: return ( f"π€ **AI Assistant** | " f"Hints used: **{hints_used}** | Penalty: **{penalty} pts** " f"_(β2 / β6 / β12 / β20 / β30)_" )
_HINT_DECLINES = { "no", "nope", "nah", "not now", "nevermind", "never mind", "no thanks", "no thank you", "skip", "cancel", "forget it", "don't", "dont", "no hint", "stop",}_CONFIRMATION_KWS = ["would you like", "shall i", "want me to", "proceed", "penalty to your score"]
def _is_decline(msg: str) -> bool: m = msg.strip().lower() return ( m in _HINT_DECLINES or m.startswith("no ") or m.startswith("don't") or m.startswith("dont") or m.startswith("nope ") or m.startswith("nah ") )
def _is_confirmation_question(text: str) -> bool: t = text.lower() return any(kw in t for kw in _CONFIRMATION_KWS)
def _colorise_test_output(raw: str) -> str: """Wrap test output lines in coloured HTML spans.""" html_lines = [] for line in raw.split("\n"): if ": PASS" in line or "ALL PASS" in line: html_lines.append(f'<span style="color:#22c55e;font-weight:bold;">{line}</span>') elif ": FAIL" in line or ": CRASH" in line or "FAILED" in line: html_lines.append(f'<span style="color:#ef4444;font-weight:bold;">{line}</span>') else: html_lines.append(f'<span style="color:#d4d4d4;">{line}</span>') return ( '<pre style="font-family:monospace;padding:12px;background:#1e1e1e;' 'color:#d4d4d4;border-radius:8px;overflow-y:auto;max-height:60dvh;' 'white-space:pre-wrap;">' + "<br>".join(html_lines) + "</pre>" )
def _normalize(code: str) -> str: """Strip trailing whitespace per line and normalize line endings.""" return "\n".join(line.rstrip() for line in code.replace("\r\n", "\n").replace("\r", "\n").splitlines())
def _workspace_diff_html(cs: "ChallengeState") -> str: """ Show a unified diff for every file the student changed, compared to the state they received.
For files the saboteur touched (cs.sabotaged_files): compare the locally stored received-state snapshot vs the current disk content. For every other modified file: compare git HEAD vs disk.
This ensures only the student's changes are shown β not the sabotage noise. """ import subprocess
workspace = cs.workspace.resolve() sabotaged_files = cs.sabotaged_files # {rel_posix: received_content} sections: list[str] = []
# ββ 1. Files modified by the saboteur ββββββββββββββββββββββββββββββββββββ for rel_posix, received_content in sabotaged_files.items(): full_path = workspace / rel_posix if not full_path.exists(): continue current = full_path.read_text(encoding="utf-8") if _normalize(current) == _normalize(received_content): continue diff = _diff_html(received_content, current, rel_posix, rel_posix) sections.append( f"<h4 style='color:#94a3b8;margin:10px 0 4px;font-family:monospace;'>" f"π {rel_posix}</h4>" + diff )
# ββ 2. Other modified files via git diff ββββββββββββββββββββββββββββββββββ try: proc = subprocess.run( ["git", "diff", "HEAD", "--name-only"], cwd=str(workspace), capture_output=True, text=True, encoding="utf-8", timeout=10, ) for changed_rel in proc.stdout.splitlines(): changed_posix = changed_rel.replace("\\", "/") if changed_posix in sabotaged_files: continue # already handled above if not changed_rel.endswith(".py"): continue orig_proc = subprocess.run( ["git", "show", f"HEAD:{changed_rel}"], cwd=str(workspace), capture_output=True, text=True, encoding="utf-8", timeout=10, ) if orig_proc.returncode != 0: continue full_path = workspace / changed_rel if not full_path.exists(): continue current = full_path.read_text(encoding="utf-8") if _normalize(current) == _normalize(orig_proc.stdout): continue diff = _diff_html(orig_proc.stdout, current, changed_posix, changed_posix) sections.append( f"<h4 style='color:#94a3b8;margin:10px 0 4px;font-family:monospace;'>" f"π {changed_posix}</h4>" + diff ) except Exception: pass
if not sections: return "<div style='color:#22c55e;padding:12px;'>No changes detected in workspace.</div>"
return "".join(sections)
def _strip_comments_and_docstrings(code: str) -> str: """Remove comment-only lines and docstrings, keeping pure code.""" import ast as _ast docstring_lines: set[int] = set() try: tree = _ast.parse(code) for node in _ast.walk(tree): if isinstance(node, (_ast.FunctionDef, _ast.AsyncFunctionDef, _ast.ClassDef, _ast.Module)): if (node.body and isinstance(node.body[0], _ast.Expr) and isinstance(node.body[0].value, _ast.Constant) and isinstance(node.body[0].value.value, str)): ds = node.body[0] docstring_lines.update(range(ds.lineno, ds.end_lineno + 1)) except Exception: pass result = [] for i, line in enumerate(code.splitlines(), 1): if i in docstring_lines: continue if line.lstrip().startswith("#"): continue result.append(line) return "\n".join(result)
def _diff_html(a: str, b: str, from_label: str, to_label: str, strip_comments: bool = False) -> str: """Generate coloured unified-diff HTML between two code strings.""" if strip_comments: a = _strip_comments_and_docstrings(a) b = _strip_comments_and_docstrings(b) a = _normalize(a) b = _normalize(b) a_lines = a.splitlines(keepends=True) b_lines = b.splitlines(keepends=True) diff = list(difflib.unified_diff(a_lines, b_lines, fromfile=from_label, tofile=to_label, lineterm="")) if not diff: return '<div class="diff-block" style="color:#22c55e;">No changes detected.</div>'
html_lines = [] for line in diff: escaped = line.replace("&", "&").replace("<", "<").replace(">", ">") if line.startswith("+++") or line.startswith("---"): html_lines.append(f'<span style="color:#888;font-style:italic;">{escaped}</span>') elif line.startswith("@@"): html_lines.append(f'<span style="color:#60a5fa;">{escaped}</span>') elif line.startswith("+"): html_lines.append(f'<span style="color:#22c55e;background:#052e16;">{escaped}</span>') elif line.startswith("-"): html_lines.append(f'<span style="color:#ef4444;background:#2d0a0a;">{escaped}</span>') else: html_lines.append(f'<span style="color:#d4d4d4;">{escaped}</span>')
return ( '<div class="diff-block">' + "\n".join(html_lines) + "</div>" )
def _extract_function_source(code: str, func_name: str) -> str: """Extract a named function's source lines from code using ast.""" import ast try: tree = ast.parse(code) for node in ast.walk(tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): if node.name == func_name: lines = code.splitlines() return "\n".join(lines[node.lineno - 1 : node.end_lineno]) except Exception: pass return ""
def _apply_one_bug_fix( current_code: str, func_name: str, orig_pre: str, sabot_pre: str,) -> str | None: """ Apply the fix for a single injected bug by surgically patching func_name inside current_code. Returns the patched file content, or None if the fix could not be determined.
Strategy: character-level diff between orig_pre (correct pre-transform source) and sabot_pre (buggy pre-transform source) surfaces the exact changed tokens. Those tokens survive obfuscation so we can find-and-replace them directly in the fully-obfuscated current_code. """ import difflib
func_in_code = _extract_function_source(current_code, func_name) if not func_in_code: return None
matcher = difflib.SequenceMatcher(None, orig_pre, sabot_pre, autojunk=False) opcodes = matcher.get_opcodes()
fixed_func = func_in_code changed = False
for tag, i1, i2, j1, j2 in opcodes: if tag == "equal": continue
orig_frag = orig_pre[i1:i2] sabot_frag = sabot_pre[j1:j2]
if not orig_frag.strip() and not sabot_frag.strip(): continue
if tag in ("replace", "insert"): if not sabot_frag.strip(): continue
ctx_start_orig = i1 ctx_start_sabot = j1 while ctx_start_orig > 0 and ctx_start_sabot > 0: co = orig_pre[ctx_start_orig - 1] cs_ = sabot_pre[ctx_start_sabot - 1] if co != cs_ or not (co.isalnum() or co == "_"): break ctx_start_orig -= 1 ctx_start_sabot -= 1
search_str = sabot_pre[ctx_start_sabot:j2] replace_str = orig_pre[ctx_start_orig:i2]
if search_str and search_str in fixed_func: fixed_func = fixed_func.replace(search_str, replace_str, 1) changed = True elif sabot_frag and sabot_frag in fixed_func: fixed_func = fixed_func.replace(sabot_frag, orig_frag, 1) changed = True
elif tag == "delete": if not orig_frag.strip(): continue
ctx_left = sabot_pre[max(0, j1 - 30):j1] ctx_right_raw = sabot_pre[j2:j2 + 20] nl = ctx_right_raw.find("\n") ctx_right = ctx_right_raw[:nl] if nl != -1 else ctx_right_raw
for trim in range(len(ctx_left)): search_str = ctx_left[trim:] + ctx_right replace_str = ctx_left[trim:] + orig_frag + ctx_right if search_str and search_str in fixed_func: fixed_func = fixed_func.replace(search_str, replace_str, 1) changed = True break
if not changed or fixed_func == func_in_code: return None
fixed = current_code.replace(func_in_code, fixed_func, 1) return fixed if fixed != current_code else None
def _compute_expected_fixed_code(cs: "ChallengeState") -> str | None: """ Compute the expected correct version of the sabotaged file by applying surgical fixes for every injected bug. Supports num_bugs > 1 by iterating over all (func_name, orig_pre, sabot_pre) triples stored in challenge_state.json. IMPORTANT: After inflate_hierarchy, the sources are POST-INFLATE (include wrappers). This ensures surgical patching works correctly even when wrapper layers exist. Returns None if no fix could be determined. """ import json as _json
try: _data = _json.loads((cs.workspace / "challenge_state.json").read_text(encoding="utf-8")) except Exception: _data = {}
# Multi-bug lists (written by the new pipeline). Fall back to single-bug # fields for workspaces generated before this change. # NOTE: These are POST-INFLATE sources (updated by inflate_hierarchy) bug_func_names = _data.get("bug_func_names") or cs.bug_func_names sabot_sources_list = _data.get("bug_func_sources_list") or [] orig_sources_list = _data.get("original_bug_func_sources_list") or []
# Single-bug fallback: wrap scalar fields in lists if not bug_func_names and cs.bug_func_name: bug_func_names = [cs.bug_func_name] if not sabot_sources_list: sabot_sources_list = [_data.get("bug_func_source", "")] if not orig_sources_list: orig_sources_list = [ cs.original_bug_func_source or _extract_function_source(cs.original_code, cs.bug_func_name) ]
if not bug_func_names: return None
# Use the snapshot as the starting point (matches what the student received). try: target_rel = cs.target_path.resolve().relative_to(cs.workspace.resolve()).as_posix() except ValueError: target_rel = "" current_code = cs.sabotaged_files.get(target_rel) or cs.sabotaged_code
any_changed = False for func_name, orig_pre, sabot_pre in zip(bug_func_names, orig_sources_list, sabot_sources_list): if not (orig_pre and sabot_pre): continue result = _apply_one_bug_fix(current_code, func_name, orig_pre, sabot_pre) if result is not None: current_code = result any_changed = True
return current_code if any_changed else None
def _expected_fix_diff_html(cs: "ChallengeState", submitted_code: str = "") -> str: """ Show two sections: 1. What the expected fix looks like (buggy β expected). 2. How the student's submission compares to the expected fix (expected β submitted): empty if perfect, otherwise shows extra/wrong changes. """ func = cs.bug_func_name
# Resolve the received (snapshot) content for the target file try: target_rel = cs.target_path.resolve().relative_to(cs.workspace.resolve()).as_posix() except ValueError: target_rel = "" received_code = cs.sabotaged_files.get(target_rel) or cs.sabotaged_code
expected_fixed = _compute_expected_fixed_code(cs)
# ββ Fallback: function-level or full-file diff ββββββββββββββββββββββββββββ if expected_fixed is None: approx = received_code for fn in cs.bug_func_names: sabot_func = _extract_function_source(approx, fn) orig_func = _extract_function_source(cs.original_code, fn) if sabot_func and orig_func: candidate = approx.replace(sabot_func, orig_func, 1) if candidate != approx: approx = candidate if approx != received_code: expected_fixed = approx else: return _diff_html(received_code, cs.original_code, target_rel, target_rel, strip_comments=True)
# ββ Section 1: expected fix βββββββββββββββββββββββββββββββββββββββββββββββ section1 = ( "<h4 style='color:#94a3b8;margin:8px 0 4px;'>π― Expected fix</h4>" + _diff_html(received_code, expected_fixed, target_rel, target_rel, strip_comments=True) )
if not submitted_code: return section1
# ββ Section 2: workspace-wide comparison βββββββββββββββββββββββββββββββββ # "Perfect fix" = target file matches expected AND no other files were changed. def _ast_equivalent(a: str, b: str) -> bool: try: import ast as _ast return _ast.dump(_ast.parse(a)) == _ast.dump(_ast.parse(b)) except SyntaxError: return _normalize(a) == _normalize(b)
target_file_ok = _ast_equivalent(expected_fixed, submitted_code)
# Check whether the student touched any files outside the sabotaged set. # Known-modified files = snapshot keys + the challenge target file itself. known_changed = set(cs.sabotaged_files.keys()) | ({target_rel} if target_rel else set()) import subprocess as _sp try: proc = _sp.run( ["git", "diff", "HEAD", "--name-only"], cwd=str(cs.workspace.resolve()), capture_output=True, text=True, encoding="utf-8", timeout=10, ) extra_changed = [ f.replace("\\", "/") for f in proc.stdout.splitlines() if f.replace("\\", "/") not in known_changed ] except Exception: extra_changed = []
is_perfect = target_file_ok and not extra_changed
if is_perfect: verdict = ( "<div style='margin-top:12px;padding:10px 14px;background:#052e16;" "border:1px solid #22c55e;border-radius:6px;color:#22c55e;font-weight:600;'>" "β
Perfect fix β you changed exactly the right lines and nothing more." "</div>" ) else: verdict = ( "<div style='margin-top:12px;padding:10px 14px;background:#2d1a00;" "border:1px solid #f59e0b;border-radius:6px;color:#f59e0b;font-weight:600;'>" "β οΈ Your fix differs from the expected solution β see Your Changes on the left." "</div>" )
return section1 + verdict
def _combined_changes_html(cs: "ChallengeState", submitted_code: str = "") -> str: """ Render the "Changes & Expected" tab as a single HTML block.
For each file in the union of (student-changed files βͺ expected-fix files), a row is rendered with two side-by-side diff panels: - Left: student's diff (vs received sabotaged code) - Right: expected fix diff (vs received sabotaged code) If one side has no changes for a given file, a "No changes" placeholder is shown. A verdict banner spans the full width at the bottom. """ import subprocess as _sp
workspace = cs.workspace.resolve() try: target_rel = cs.target_path.resolve().relative_to(workspace).as_posix() except ValueError: target_rel = ""
sabotaged_files = cs.sabotaged_files received_code = sabotaged_files.get(target_rel) or cs.sabotaged_code
# ββ Collect student-changed files βββββββββββββββββββββββββββββββββββββββββ # student_changes: {rel_posix: (received_content, current_content)} student_changes: dict[str, tuple[str, str]] = {}
for rel_posix, received_content in sabotaged_files.items(): full_path = workspace / rel_posix if not full_path.exists(): continue current = full_path.read_text(encoding="utf-8") if _normalize(current) != _normalize(received_content): student_changes[rel_posix] = (received_content, current)
try: proc = _sp.run( ["git", "diff", "HEAD", "--name-only"], cwd=str(workspace), capture_output=True, text=True, encoding="utf-8", timeout=10, ) for changed_rel in proc.stdout.splitlines(): changed_posix = changed_rel.replace("\\", "/") if changed_posix in sabotaged_files: continue if not changed_rel.endswith(".py"): continue orig_proc = _sp.run( ["git", "show", f"HEAD:{changed_rel}"], cwd=str(workspace), capture_output=True, text=True, encoding="utf-8", timeout=10, ) if orig_proc.returncode != 0: continue full_path = workspace / changed_rel if not full_path.exists(): continue current = full_path.read_text(encoding="utf-8") if _normalize(current) != _normalize(orig_proc.stdout): student_changes[changed_posix] = (orig_proc.stdout, current) except Exception: pass
# ββ Compute expected fix for target file ββββββββββββββββββββββββββββββββββ expected_fixed = _compute_expected_fixed_code(cs) if expected_fixed is None and cs.bug_func_name: sabot_func = _extract_function_source(received_code, cs.bug_func_name) orig_func = _extract_function_source(cs.original_code, cs.bug_func_name) if sabot_func and orig_func: ef = received_code.replace(sabot_func, orig_func, 1) if ef != received_code: expected_fixed = ef
# ββ Build union of files to show ββββββββββββββββββββββββββββββββββββββββββ expected_files = {target_rel} if (target_rel and expected_fixed is not None) else set() all_files = sorted(set(student_changes.keys()) | expected_files)
# ββ Column header row βββββββββββββββββββββββββββββββββββββββββββββββββββββ col_headers = ( "<div style='display:flex;gap:12px;margin-bottom:8px;'>" "<div style='flex:1;min-width:0;font-weight:600;color:#cbd5e1;'>βοΈ Your Changes" " <span style='font-weight:400;color:#64748b;font-size:0.88em;'>" "β your submitted code vs the buggy code you received</span></div>" "<div style='flex:1;min-width:0;font-weight:600;color:#cbd5e1;'>π― Expected Fix" " <span style='font-weight:400;color:#64748b;font-size:0.88em;'>" "β the minimal correct fix</span></div>" "</div>" )
if not all_files: return col_headers + "<div class='diff-block' style='color:#22c55e;'>No changes detected in workspace.</div>"
_no_change_left = "<div class='diff-block' style='color:#22c55e;'>No changes</div>" _no_change_right = "<div class='diff-block' style='color:#64748b;'>No change expected</div>"
# ββ Per-file side-by-side rows ββββββββββββββββββββββββββββββββββββββββββββ rows: list[str] = [] for rel in all_files: file_header = ( f"<h4 style='color:#94a3b8;margin:6px 0 4px;font-family:monospace;'>π {rel}</h4>" )
# Left: student's changes if rel in student_changes: recv, curr = student_changes[rel] left_body = _diff_html(recv, curr, rel, rel) else: left_body = _no_change_left
# Right: expected fix (only for the sabotaged target file) if rel == target_rel and expected_fixed is not None: right_body = _diff_html(received_code, expected_fixed, rel, rel) else: right_body = _no_change_right
rows.append( "<div style='display:flex;gap:12px;margin-bottom:20px;'>" f"<div style='flex:1;min-width:0;'>{file_header}{left_body}</div>" f"<div style='flex:1;min-width:0;'>{file_header}{right_body}</div>" "</div>" )
# ββ Verdict banner (full-width) βββββββββββββββββββββββββββββββββββββββββββ verdict = "" if submitted_code: def _ast_eq(a: str, b: str) -> bool: try: import ast as _ast return _ast.dump(_ast.parse(a)) == _ast.dump(_ast.parse(b)) except SyntaxError: return _normalize(a) == _normalize(b)
target_ok = expected_fixed is not None and _ast_eq(expected_fixed, submitted_code) extra_files = [f for f in student_changes if f != target_rel] is_perfect = target_ok and not extra_files
if is_perfect: verdict = ( "<div style='margin-top:12px;padding:10px 14px;background:#052e16;" "border:1px solid #22c55e;border-radius:6px;color:#22c55e;font-weight:600;'>" "β
Perfect fix β you changed exactly the right lines and nothing more." "</div>" ) else: verdict = ( "<div style='margin-top:12px;padding:10px 14px;background:#2d1a00;" "border:1px solid #f59e0b;border-radius:6px;color:#f59e0b;font-weight:600;'>" "β οΈ Your fix differs from the expected solution." "</div>" )
return col_headers + "".join(rows) + verdict
def _hints_html(hint_log: list) -> str: """Render hint log: list of {"summary": str, "response": str}."""
def _esc(s: str) -> str: return (s.replace("&", "&").replace("<", "<").replace(">", ">"))
entries = [e for e in (hint_log or []) if isinstance(e, dict)]
if not entries: return "<p style='color:#888;font-style:italic;'>No hints were used.</p>"
parts: list[str] = [] for n, entry in enumerate(entries, 1): summary = entry.get("summary", "").strip() if not summary: # Fallback: first sentence of the response first_line = entry.get("response", "").split("\n")[0].strip() dot = first_line.find(". ") summary = first_line[: dot + 1] if dot != -1 else first_line if len(summary) > 160: summary = summary[:157] + "β¦" parts.append( f'<div style="margin:6px 0;padding:8px 14px;border:1px solid #374151;' f'border-radius:8px;background:#1a2e1a;">' f'<span style="color:#93c5fd;font-weight:bold;margin-right:10px;">Hint #{n}</span>' f'<span style="color:#86efac;">{_esc(summary)}</span>' f'</div>' )
header = (f'<p style="color:#888;font-size:0.85em;margin:0 0 8px 0;">' f'{len(entries)} hint(s) used</p>') return ( header + '<div style="max-height:50vh;overflow-y:auto;padding:4px;">' + "".join(parts) + "</div>" )
def _score_summary_html(result: dict) -> str: """Build a prominent score summary block.""" total = result["total_score"] llm_score = result.get("llm_score", total) explanation = result.get("llm_explanation", "") penalty = result["hint_penalty"] passed = result["passed"] ttl = result["total_tests"] all_ok = result["all_passed"]
color = "#22c55e" if all_ok else ("#f59e0b" if total >= 50 else "#ef4444") badge = "π ALL TESTS PASS!" if all_ok else ("β οΈ Partial" if total > 0 else "β Failed")
explanation_html = "" if explanation: import html as _html escaped = _html.escape(explanation) explanation_html = ( f'<div style="margin-top:14px;padding:10px 14px;background:#0f172a;' f'border-left:3px solid #60a5fa;border-radius:4px;color:#cbd5e1;' f'font-size:0.9em;line-height:1.5;">' f'<strong style="color:#60a5fa;">π€ AI Evaluation:</strong><br>{escaped}</div>' )
return f"""<div style="padding:20px;border-radius:12px;background:#1e1e1e;border:2px solid {color};"> <div style="font-size:2.5em;font-weight:bold;color:{color};text-align:center;">{total}/100</div> <div style="text-align:center;color:{color};font-size:1.1em;margin-bottom:16px;">{badge}</div> <table style="width:100%;border-collapse:collapse;font-family:monospace;"> <tr> <td style="padding:6px 12px;color:#d4d4d4;">π€ AI Score</td> <td style="padding:6px 12px;color:#60a5fa;text-align:right;font-weight:bold;">{llm_score}/100</td> <td style="padding:6px 12px;color:#888;">({passed}/{ttl} tests passed)</td> </tr> <tr> <td style="padding:6px 12px;color:#d4d4d4;">π‘ Hint Penalty</td> <td style="padding:6px 12px;color:#f87171;text-align:right;font-weight:bold;">β{penalty}</td> <td style="padding:6px 12px;color:#888;"></td> </tr> </table> {explanation_html}</div>"""
# ββ Full two-page interface βββββββββββββββββββββββββββββββββββββββββββββββββββ
def create_full_interface() -> gr.Blocks: """ Returns a Gradio app with login page (if needed) + challenge interface: Page 0: Login (visible only if OPENAI_API_KEY not in .env) Page 1: Setup form (name / URL / level / bugs) Page 2: Challenge interface (shown after pipeline finishes) Page 3: Results (shown after Submit) """ # Auto-detect: is there an API key in .env? has_env_key = bool(os.getenv("OPENAI_API_KEY"))
css = """ #code-editor { font-size: 14px !important; font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important; background-color: #1e1e1e !important; border-radius: 8px !important; } #code-editor .codemirror-wrapper { background-color: #1e1e1e !important; } #code-editor .cm-editor { background-color: #1e1e1e !important; } /* Logout button styling */ #logout-btn { position: absolute; top: 20px; right: 20px; z-index: 1000; } .setup-card { max-width: 800px; margin: 40px auto; padding: 30px; } """
# Note: CSS parameter moved to launch() in Gradio 6.0, removed for compatibility with gr.Blocks(title="Legacy Code Challenge") as demo:
# Shared state user_api_key_state = gr.State("") user_name_state = gr.State("") workspace_state = gr.State("") hints_used_state = gr.State(0) submission_count_state = gr.State(0) hint_log_state = gr.State([]) confirmation_pending_state = gr.State(False) timer_trigger = gr.Number(value=0, visible=False) # Logout button (hidden until logged in) with gr.Row(): gr.HTML("") # spacer logout_btn = gr.Button("π Logout", visible=False, elem_id="logout-btn", size="sm") # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ # PAGE 0 β Login (visible only if no .env key) # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(visible=not has_env_key, elem_classes=["setup-card"]) as login_page: gr.Markdown( "# π Welcome to Legacy Code Challenge\n" "### Please enter your details to continue" ) login_name = gr.Textbox( label="Your Name", placeholder="e.g. Alice Smith", ) login_api_key = gr.Textbox( label="OpenAI API Key", placeholder="sk-proj-...", type="password", info="Get one at platform.openai.com/api-keys", ) gr.Markdown( "β οΈ **Note:** Your API key is only used for this session and consumes credits from your OpenAI account." ) login_btn = gr.Button("π Continue", variant="primary", size="lg") login_status = gr.Markdown("")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ # PAGE 1 β Setup (visible if .env exists, else hidden) # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(visible=has_env_key, elem_classes=["setup-card"]) as setup_page: gr.Markdown( "# π Legacy Code Challenge\n" "Fill in the details below, then click **Start Challenge**." )
name_box = gr.Textbox( label="Your Name", placeholder="e.g. Alice Smith", ) url_box = gr.Textbox( label="GitHub Repository URL", placeholder="https://github.com/mahmoud/boltons", ) with gr.Row(): nesting_slider = gr.Slider( minimum=1, maximum=6, value=3, step=1, label="π Nesting Level (call-chain depth)", info="Higher = deeper call chains (1=simple, 6=very deep)", ) bugs_slider = gr.Slider( minimum=1, maximum=5, value=1, step=1, label="π Number of Bugs to Inject", ) with gr.Row(): refactoring_check = gr.Checkbox( label="π Enable Refactoring (obfuscation/spaghettification)", value=False, ) debug_check = gr.Checkbox( label="π Debug Mode (verbose output, show bug locations)", value=False, ) timer_slider = gr.Slider( minimum=0, maximum=120, value=0, step=5, label="β±οΈ Challenge Timer (minutes β 0 = no timer)", )
start_btn = gr.Button("π Start Challenge", variant="primary", size="lg") status_box = gr.Textbox( label="Status", interactive=False, visible=False, lines=3, )
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ # PAGE 2 β Challenge (hidden until pipeline finishes) # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(visible=False) as challenge_page:
with gr.Row(elem_classes=["header-row"]): header_md = gr.Markdown("### π Legacy Code Challenge") timer_html = gr.HTML('<span id="timer-inner" style="font-family:monospace"></span>', elem_id="challenge-timer")
with gr.Row(elem_classes=["main-row"]):
# ββ Left column: tabs βββββββββββββββββββββββββββββββββββββ with gr.Column(scale=3, elem_classes=["left-col"]): with gr.Tabs(selected=0, elem_classes=["left-tabs"]) as left_tabs:
with gr.Tab("π Challenge", id=0): challenge_readme = gr.Markdown("")
with gr.Tab("π» Code Editor", id=1): file_dropdown = gr.Dropdown( choices=[], label="File", info="Select a file to view. Submit saves to the target file.", ) with gr.Row(): btn_tests = gr.Button("βΆ Run Tests", variant="secondary") btn_changes = gr.Button("ποΈ View My Changes", variant="secondary") save_btn = gr.Button("πΎ Save", variant="secondary", elem_id="save-btn") save_status = gr.Markdown("") code_editor = gr.Code( value="", language="python", label="", interactive=True, lines=30, elem_id="code-editor", show_label=False, )
with gr.Tab("π§ͺ Test Results", id=2): run_tests_tab_btn = gr.Button("βΆ Run Tests", variant="secondary") test_output = gr.HTML( "<p style='color:#888;font-family:monospace;'>Click 'βΆ Run Tests' to runβ¦</p>" )
with gr.Tab("ποΈ My Changes", id=3): gr.Markdown("_Diff: your saved file vs the original buggy code you received_") with gr.Row(): refresh_btn = gr.Button("π Refresh", variant="secondary") revert_btn = gr.Button("β©οΈ Revert to Original", variant="secondary") changes_diff_html = gr.HTML("")
# ββ Right column: AI assistant + submit βββββββββββββββββββ with gr.Column(scale=2, elem_classes=["right-col"]): hint_counter = gr.Markdown(_hint_md(0, 0)) chatbot = gr.Chatbot( label="AI Assistant", elem_id="ai-chatbot", ) with gr.Row(): chat_input = gr.Textbox( placeholder="Ask the AI assistant for a hintβ¦", show_label=False, scale=5, ) send_btn = gr.Button("Send", variant="secondary", scale=1)
gr.Markdown("---") submit_btn = gr.Button("π Submit Fix", variant="primary") # Live Debug Console (always visible at bottom) gr.Markdown("---") with gr.Accordion("π Live Debug Console", open=False): live_debug_console = gr.Textbox( label="Real-time Execution Logs", lines=10, max_lines=20, interactive=False, placeholder="Debug logs will appear here during submission...", elem_id="live-debug-console" )
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ # PAGE 3 β Results (hidden until Submit clicked) # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(visible=False) as results_page: gr.Markdown("## π Submission Results")
score_summary_html = gr.HTML("")
with gr.Tabs(): with gr.Tab("π§ͺ Test Results"): results_test_html = gr.HTML("")
with gr.Tab("π Changes & Expected"): results_changes_html = gr.HTML("")
with gr.Tab("π‘ Hints Used"): results_hints_html = gr.HTML("") # Debug console (collapsible) with gr.Accordion("π Debug Console", open=False): debug_console = gr.Textbox( label="Execution Logs", lines=15, max_lines=30, interactive=False, placeholder="Debug logs will appear here...", )
# ββ Login callback ββββββββββββββββββββββββββββββββββββββββββββββββ def on_login(name, api_key): if not name.strip(): return ( gr.update(), # login page stays gr.update(), # setup page hidden gr.update(), # logout hidden "β Please enter your name", "", "" # states empty ) valid, msg = validate_openai_key(api_key) if not valid: return ( gr.update(), gr.update(), gr.update(), msg, "", "" ) # Success! os.environ["OPENAI_API_KEY"] = api_key return ( gr.update(visible=False), # hide login gr.update(visible=True), # show setup gr.update(visible=True), # show logout "β
Logged in!", api_key, name.strip() ) def on_logout(): """Clear API key and return to login page.""" if "OPENAI_API_KEY" in os.environ: del os.environ["OPENAI_API_KEY"] return ( gr.update(visible=True), # show login gr.update(visible=False), # hide setup gr.update(visible=False), # hide challenge gr.update(visible=False), # hide results gr.update(visible=False), # hide logout "", "", "", "", # clear textboxes "", "" # clear states )
# ββ Setup callback βββββββββββββββββββββββββββββββββββββββββββββββββ
def on_start(name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins, user_name_from_login, user_api_key): nesting = int(nesting_lvl) # Use login name if available, otherwise name from setup form name_str = user_name_from_login.strip() if user_name_from_login else name.strip() # Ensure API key is set in environment (critical for pipeline) if user_api_key: os.environ["OPENAI_API_KEY"] = user_api_key
yield ( gr.update(visible=True, value="β³ Cloning repository and generating challengeβ¦" " this may take 1β2 minutes."), gr.update(interactive=False), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), )
try: workspace_path = _run_pipeline(url.strip(), nesting, int(num_bugs), refactoring, debug) cs = ChallengeState(workspace_path) py_files = cs.list_py_files() default = cs.target_file if cs.target_file in py_files else (py_files[0] if py_files else "") suffix = f" | {name_str}" if name_str else ""
yield ( gr.update(visible=False), gr.update(interactive=True), gr.update(visible=False), gr.update(visible=True), gr.update(value=f"### π Legacy Code Challenge{suffix}"), gr.update(value=cs.readme()), gr.update(choices=py_files, value=default), gr.update(value=cs.read_target(), label=cs.target_file, interactive=True), workspace_path, int(timer_mins), )
except Exception as exc: error_msg = str(exc) # Provide user-friendly error messages if "verify_sabotage" in error_msg and "crashed" in error_msg: user_message = ( "β Challenge generation failed: The bugs introduced caused all tests to crash.\n\n" "π‘ **Suggestions:**\n" "β’ Try reducing the number of bugs (use 1-2 instead of 3)\n" "β’ Try a different repository with simpler code\n" "β’ Enable 'Debug Mode' to see detailed logs\n\n" f"Technical details: {error_msg}" ) elif "clone" in error_msg.lower(): user_message = ( "β Failed to clone repository.\n\n" "π‘ **Check:**\n" "β’ Is the URL correct?\n" "β’ Is the repository public?\n\n" f"Details: {error_msg}" ) else: user_message = f"β Error: {error_msg}\n\nπ‘ Try enabling 'Debug Mode' for more details." yield ( gr.update(visible=True, value=user_message), gr.update(interactive=True), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), )
# ββ Wiring for login ββββββββββββββββββββββββββββββββββββββββββββββ login_btn.click( on_login, inputs=[login_name, login_api_key], outputs=[ login_page, setup_page, logout_btn, login_status, user_api_key_state, user_name_state ] ) logout_btn.click( on_logout, outputs=[ login_page, setup_page, challenge_page, results_page, logout_btn, login_name, login_api_key, name_box, url_box, user_api_key_state, user_name_state ] ) start_btn.click( on_start, inputs=[name_box, url_box, nesting_slider, bugs_slider, refactoring_check, debug_check, timer_slider, user_name_state, user_api_key_state], outputs=[ status_box, start_btn, setup_page, challenge_page, header_md, challenge_readme, file_dropdown, code_editor, workspace_state, timer_trigger, ], )
timer_trigger.change( fn=None, inputs=[timer_trigger], js="(n) => { window.startTimer && window.startTimer(n); return n; }", outputs=[timer_trigger], )
# ββ Challenge callbacks ββββββββββββββββββββββββββββββββββββββββββββ
def on_file_select(rel_path, workspace_path): if not workspace_path: return gr.update() cs = ChallengeState(workspace_path) content = cs.read_py_file(rel_path) return gr.update(value=content, interactive=True, label=rel_path)
def on_save(code, workspace_path): if not workspace_path: return "β οΈ No challenge loaded." cs = ChallengeState(workspace_path) cs.write_target(code) return "β
Saved"
def on_run_tests(code, workspace_path): loading = '<p style="text-align:center;padding:20px;color:#888;">β³ Running testsβ¦</p>' yield (gr.update(selected=2), loading) if not workspace_path: yield (gr.update(selected=2), "<p style='color:#888'>No challenge loaded.</p>") return # Auto-save before running tests cs_temp = ChallengeState(workspace_path) cs_temp.write_target(code) try: from orchestrator.scoring import run_tests r = run_tests(workspace_path) raw = r["output"] if r["output"] else "No output." yield (gr.update(selected=2), _colorise_test_output(raw)) except Exception as exc: yield (gr.update(selected=2), f"<p style='color:#ef4444;font-family:monospace;'>β Error: {exc}</p>")
def on_show_changes(code, workspace_path): if not workspace_path: diff = "<p style='color:#888'>No challenge loaded.</p>" else: # Save code from editor, then read from disk for comparison # (Gradio code_editor doesn't always pass updated content reliably) cs = ChallengeState(workspace_path) cs.write_target(code) diff = _workspace_diff_html(cs) return (gr.update(selected=3), diff)
def on_revert(workspace_path): if not workspace_path: return gr.update(), gr.update(selected=1) cs = ChallengeState(workspace_path) cs.reset_target() return cs.sabotaged_code, gr.update(selected=1)
def on_submit(hints_used, submit_count, workspace_path, hint_log, user_name): # ULTRA-SIMPLE TEST: Just show SOMETHING immediately test_msg = f""" <div style='padding:20px;background:#1e1e1e;color:#fff;border-radius:8px;'> <h3>π Debug Info</h3> <p><strong>Function called:</strong> YES</p> <p><strong>hints_used:</strong> {hints_used}</p> <p><strong>submit_count:</strong> {submit_count}</p> <p><strong>workspace_path:</strong> {workspace_path}</p> <p><strong>user_name:</strong> {user_name}</p> </div> """ try: # First yield IMMEDIATELY: Show loading state (before any logic that might fail) _loading = '<p style="text-align:center;padding:40px;color:#888;font-size:1.2em;">β³ Running testsβ¦</p>' yield ( gr.update(visible=False), gr.update(visible=True), test_msg, "", "", "", # Show debug info instead of loading submit_count, "", # debug console "β³ Starting submission evaluation...", # live debug ) except Exception as init_exc: # If even the first yield fails, show error err = f"<p style='color:#ef4444;'>β Initialization error: {init_exc}</p>" yield (gr.update(), gr.update(), err, "", "", "", submit_count, str(init_exc), str(init_exc)) return # Capture all print statements for debug console log_capture = StringIO() original_stdout = sys.stdout try: sys.stdout = log_capture if not workspace_path: sys.stdout = original_stdout yield (gr.update(), gr.update(), "No challenge loaded.", "", "", "", submit_count, log_capture.getvalue(), "β No workspace loaded") return print(f"[{datetime.now().strftime('%H:%M:%S')}] π Starting submission evaluation...") cs = ChallengeState(workspace_path) log = SubmissionLog(cs.workspace) print(f"[{datetime.now().strftime('%H:%M:%S')}] π Reading submitted code...") submitted_code = cs.read_target() print(f"[{datetime.now().strftime('%H:%M:%S')}] π§ͺ Running tests...") result = evaluate_submission( workspace_path=workspace_path, student_code=submitted_code, original_code=cs.original_code, bug_func_name=cs.bug_func_name, hints_used=hints_used, sabotaged_code=cs.sabotaged_code, target_file=str(cs.target_path), bug_func_names=cs.bug_func_names, ) print(f"[{datetime.now().strftime('%H:%M:%S')}] πΎ Saving submission...") log.save(submitted_code, result, hints_used) new_count = submit_count + 1
print(f"[{datetime.now().strftime('%H:%M:%S')}] π Generating results...") score_html = _score_summary_html(result) combined_diff = _combined_changes_html(cs, submitted_code) test_html = _colorise_test_output(result["test_output"] or "No test output.") hints_html = _hints_html(hint_log or [])
print(f"[{datetime.now().strftime('%H:%M:%S')}] β
Results ready, returning to user...") # Get all captured logs debug_logs = log_capture.getvalue() sys.stdout = original_stdout # Restore stdout # Return results to user IMMEDIATELY yield ( gr.update(visible=False), gr.update(visible=True), score_html, combined_diff, test_html, hints_html, new_count, debug_logs, debug_logs, # live debug (same) ) # Upload to cloud services in BACKGROUND THREAD (non-blocking) # TEMPORARILY DISABLED - Testing without cloud uploads """ def _background_upload(): student_name = user_name.strip() if user_name else "Anonymous" # Google Sheets (fast summary) if GOOGLE_SHEETS_AVAILABLE: try: print("π Uploading to Google Sheets...") log_to_google_sheets( student_name=student_name, repo_url=cs.github_url, hints_used=hints_used, score=result["total_score"], total_tests=result["total_tests"], passed_tests=result["passed"], all_passed=result["all_passed"], chat_history=hint_log or [], ) print(f"β
Logged to Google Sheets: {student_name}") except Exception as e: print(f"β οΈ Google Sheets logging failed: {e}") # Git Submissions (detailed backup with all code) if GIT_SUBMISSIONS_AVAILABLE: try: print("π Pushing to Git repository...") push_submission_to_git( student_name=student_name, repo_url=cs.github_url, original_code=cs.original_code, buggy_code=cs.sabotaged_code, student_code=submitted_code, chat_history=hint_log or [], score=result["total_score"], total_tests=result["total_tests"], passed_tests=result["passed"], hints_used=hints_used, challenge_prompt=cs.readme(), target_file=cs.target_file, ) print(f"β
Pushed to Git: {student_name}") except Exception as e: print(f"β οΈ Git submission backup failed: {e}") # Start background upload (won't block UI) upload_thread = threading.Thread(target=_background_upload, daemon=True) upload_thread.start() """ except Exception as exc: import traceback error_details = traceback.format_exc() debug_logs = log_capture.getvalue() + f"\n\nβ ERROR:\n{error_details}" sys.stdout = original_stdout # Restore stdout err = f"<p style='color:#ef4444;padding:20px;font-family:monospace;'>β Error during evaluation:<br>{exc}</p>" yield (gr.update(visible=False), gr.update(visible=True), err, "", "", "", submit_count, debug_logs, debug_logs) finally: sys.stdout = original_stdout # Always restore stdout
def on_send(message, history, hints_used, submit_count, workspace_path, hint_log, confirmation_pending): if not message.strip(): penalty = PENALTY_TABLE[min(hints_used, len(PENALTY_TABLE) - 1)] return history, "", hints_used, _hint_md(hints_used, penalty), hint_log, confirmation_pending if not workspace_path: history = list(history or []) + [ {"role": "user", "content": message}, {"role": "assistant", "content": "No challenge loaded yet."}, ] return history, "", hints_used, _hint_md(hints_used, 0), hint_log, False cs = ChallengeState(workspace_path) result = get_hint( user_message=message, history=history, hints_used=hints_used, submission_attempts=submit_count, challenge_info=cs.challenge_info(), ) # Python-level guarantee: if a confirmation was pending and the student # didn't explicitly decline, the hint counts β regardless of LLM marker. accepted_pending = confirmation_pending and not _is_decline(message) gave_hint = result["gave_hint"] or accepted_pending new_confirmation_pending = not gave_hint and _is_confirmation_question(result["response"])
history = list(history or []) + [ {"role": "user", "content": message}, {"role": "assistant", "content": result["response"]}, ] new_hints = hints_used + (1 if gave_hint else 0) penalty = PENALTY_TABLE[min(new_hints, len(PENALTY_TABLE) - 1)] new_log = list(hint_log or []) if gave_hint: new_log.append({"summary": result.get("hint_summary", ""), "response": result["response"]}) return history, "", new_hints, _hint_md(new_hints, penalty), new_log, new_confirmation_pending
# ββ Wiring ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
file_dropdown.change( on_file_select, inputs=[file_dropdown, workspace_state], outputs=[code_editor], ) save_btn.click(on_save, inputs=[code_editor, workspace_state], outputs=[save_status])
btn_tests.click(on_run_tests, inputs=[code_editor, workspace_state], outputs=[left_tabs, test_output]) run_tests_tab_btn.click(on_run_tests, inputs=[code_editor, workspace_state], outputs=[left_tabs, test_output])
btn_changes.click(on_show_changes, inputs=[code_editor, workspace_state], outputs=[left_tabs, changes_diff_html]) refresh_btn.click(on_show_changes, inputs=[code_editor, workspace_state], outputs=[left_tabs, changes_diff_html])
revert_btn.click(on_revert, inputs=[workspace_state], outputs=[code_editor, left_tabs])
submit_btn.click( on_submit, inputs=[hints_used_state, submission_count_state, workspace_state, hint_log_state, user_name_state], outputs=[ challenge_page, results_page, score_summary_html, results_changes_html, results_test_html, results_hints_html, submission_count_state, debug_console, live_debug_console, ], ) send_btn.click( on_send, inputs=[chat_input, chatbot, hints_used_state, submission_count_state, workspace_state, hint_log_state, confirmation_pending_state], outputs=[chatbot, chat_input, hints_used_state, hint_counter, hint_log_state, confirmation_pending_state], ) chat_input.submit( on_send, inputs=[chat_input, chatbot, hints_used_state, submission_count_state, workspace_state, hint_log_state, confirmation_pending_state], outputs=[chatbot, chat_input, hints_used_state, hint_counter, hint_log_state, confirmation_pending_state], )
return demo
# ββ Legacy entry point (used by challenge.py CLI path) βββββββββββββββββββββββ
def create_interface(workspace_path: str, student_name: str = "", timer_minutes: int = 0) -> gr.Blocks: """Build the challenge-only interface for a pre-existing workspace."""
cs = ChallengeState(workspace_path) log = SubmissionLog(cs.workspace)
py_files = cs.list_py_files() default_file = cs.target_file if cs.target_file in py_files else (py_files[0] if py_files else None)
name_suffix = f" | {student_name.strip()}" if student_name.strip() else ""
css = """ #code-editor { font-size: 14px !important; font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important; background-color: #1e1e1e !important; border-radius: 8px !important; } #code-editor .codemirror-wrapper { background-color: #1e1e1e !important; } #code-editor .cm-editor { background-color: #1e1e1e !important; } """
# Note: CSS parameter moved to launch() in Gradio 6.0, removed for compatibility with gr.Blocks(title="Legacy Code Challenge", js=_make_js(timer_minutes)) as demo:
hints_used_state = gr.State(0) submission_count_state = gr.State(0) hint_log_state = gr.State([]) confirmation_pending_state = gr.State(False)
with gr.Row(elem_classes=["header-row"]): gr.Markdown( f"### π Legacy Code Challenge{name_suffix}", elem_classes=["app-header"], ) gr.HTML('<span id="timer-inner"></span>', elem_id="challenge-timer")
# ββ Challenge page ββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(visible=True) as challenge_col: with gr.Row(elem_classes=["main-row"]): with gr.Column(scale=3, elem_classes=["left-col"]): with gr.Tabs(selected=0, elem_classes=["left-tabs"]) as left_tabs:
with gr.Tab("π Challenge", id=0): gr.Markdown(cs.readme())
with gr.Tab("π» Code Editor", id=1): file_dropdown = gr.Dropdown( choices=py_files, value=default_file, label="File", info="Select a file to view. Submit saves to the target file.", ) with gr.Row(): btn_tests = gr.Button("βΆ Run Tests", variant="secondary") btn_changes = gr.Button("ποΈ View My Changes", variant="secondary") save_btn = gr.Button("πΎ Save", variant="secondary", elem_id="save-btn") save_status = gr.Markdown("") code_editor = gr.Code( value=cs.read_target(), language="python", label=cs.target_file, interactive=True, lines=30, elem_id="code-editor", show_label=False, )
with gr.Tab("π§ͺ Test Results", id=2): run_tests_tab_btn = gr.Button("βΆ Run Tests", variant="secondary") test_output = gr.HTML( "<p style='color:#888;font-family:monospace;'>Click 'βΆ Run Tests' to runβ¦</p>" )
with gr.Tab("ποΈ My Changes", id=3): gr.Markdown("_Diff: your saved file vs the original buggy code you received_") with gr.Row(): refresh_btn = gr.Button("π Refresh", variant="secondary") revert_btn = gr.Button("β©οΈ Revert to Original", variant="secondary") changes_diff_html = gr.HTML("")
with gr.Column(scale=2, elem_classes=["right-col"]): hint_counter = gr.Markdown(_hint_md(0, 0)) chatbot = gr.Chatbot( label="AI Assistant", elem_id="ai-chatbot", ) with gr.Row(): chat_input = gr.Textbox( placeholder="Ask the AI assistant for a hintβ¦", show_label=False, scale=5, ) send_btn = gr.Button("Send", variant="secondary", scale=1) gr.Markdown("---") submit_btn = gr.Button("π Submit Fix", variant="primary")
# ββ Results page ββββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(visible=False) as results_col: gr.Markdown("## π Submission Results")
score_summary_html = gr.HTML("")
with gr.Tabs(): with gr.Tab("π§ͺ Test Results"): results_test_html = gr.HTML("")
with gr.Tab("π Changes & Expected"): results_changes_html = gr.HTML("")
with gr.Tab("π‘ Hints Used"): results_hints_html = gr.HTML("") # Debug console (collapsible) with gr.Accordion("π Debug Console", open=False): debug_console_standalone = gr.Textbox( label="Execution Logs", lines=15, max_lines=30, interactive=False, placeholder="Debug logs will appear here...", )
# ββ Callbacks βββββββββββββββββββββββββββββββββββββββββββββββββββββ
def on_file_select(rel_path): content = cs.read_py_file(rel_path) return gr.update(value=content, interactive=True, label=rel_path)
def on_save(code): cs.write_target(code) return "β
Saved"
def on_run_tests(code): loading = '<p style="text-align:center;padding:20px;color:#888;">β³ Running testsβ¦</p>' yield (gr.update(selected=2), loading) # Auto-save before running tests cs.write_target(code) try: from orchestrator.scoring import run_tests r = run_tests(workspace_path) raw = r["output"] if r["output"] else "No output." yield (gr.update(selected=2), _colorise_test_output(raw)) except Exception as exc: yield (gr.update(selected=2), f"<p style='color:#ef4444;font-family:monospace;'>β Error: {exc}</p>")
def on_show_changes(): # Read directly from disk (Gradio code_editor doesn't update its value reliably) diff = _workspace_diff_html(cs) return (gr.update(selected=3), diff)
def on_revert(): cs.reset_target() return cs.sabotaged_code, gr.update(selected=1)
def on_submit(hints_used, submit_count, hint_log): # Capture all print statements for debug console log_capture = StringIO() original_stdout = sys.stdout sys.stdout = log_capture try: _loading = '<p style="text-align:center;padding:40px;color:#888;font-size:1.2em;">β³ Running testsβ¦</p>' sys.stdout = original_stdout # Restore for yield yield ( gr.update(visible=False), gr.update(visible=True), _loading, "", "", "", submit_count, "", # debug console ) sys.stdout = log_capture # Capture again print(f"[{datetime.now().strftime('%H:%M:%S')}] π Starting submission evaluation (standalone mode)...") print(f"[{datetime.now().strftime('%H:%M:%S')}] π Reading submitted code...") submitted_code = cs.read_target() print(f"[{datetime.now().strftime('%H:%M:%S')}] π§ͺ Running tests...") result = evaluate_submission( workspace_path=workspace_path, student_code=submitted_code, original_code=cs.original_code, bug_func_name=cs.bug_func_name, hints_used=hints_used, sabotaged_code=cs.sabotaged_code, target_file=str(cs.target_path), bug_func_names=cs.bug_func_names, ) print(f"[{datetime.now().strftime('%H:%M:%S')}] πΎ Saving submission...") log.save(submitted_code, result, hints_used) new_count = submit_count + 1
print(f"[{datetime.now().strftime('%H:%M:%S')}] π Generating results...") score_html = _score_summary_html(result) combined_diff = _combined_changes_html(cs, submitted_code) test_html = _colorise_test_output(result["test_output"] or "No test output.") hints_html = _hints_html(hint_log or [])
print(f"[{datetime.now().strftime('%H:%M:%S')}] β
Results ready, returning to user...") # Get all captured logs debug_logs = log_capture.getvalue() sys.stdout = original_stdout # Restore stdout # Return results to user IMMEDIATELY yield ( gr.update(visible=False), gr.update(visible=True), score_html, combined_diff, test_html, hints_html, new_count, debug_logs, ) # Upload to cloud services in BACKGROUND THREAD (non-blocking) # TEMPORARILY DISABLED - Testing without cloud uploads """ def _background_upload(): student_name = "Anonymous (standalone mode)" # Google Sheets (fast summary) if GOOGLE_SHEETS_AVAILABLE: try: print("π Uploading to Google Sheets...") log_to_google_sheets( student_name=student_name, repo_url=cs.github_url, hints_used=hints_used, score=result["total_score"], total_tests=result["total_tests"], passed_tests=result["passed"], all_passed=result["all_passed"], chat_history=hint_log or [], ) print(f"β
Logged to Google Sheets: {student_name}") except Exception as e: print(f"β οΈ Google Sheets logging failed: {e}") # Git Submissions (detailed backup with all code) if GIT_SUBMISSIONS_AVAILABLE: try: print("π Pushing to Git repository...") push_submission_to_git( student_name=student_name, repo_url=cs.github_url, original_code=cs.original_code, buggy_code=cs.sabotaged_code, student_code=submitted_code, chat_history=hint_log or [], score=result["total_score"], total_tests=result["total_tests"], passed_tests=result["passed"], hints_used=hints_used, challenge_prompt=cs.readme(), target_file=cs.target_file, ) print(f"β
Pushed to Git: {student_name}") except Exception as e: print(f"β οΈ Git submission backup failed: {e}") # Start background upload (won't block UI) upload_thread = threading.Thread(target=_background_upload, daemon=True) upload_thread.start() """ except Exception as exc: import traceback error_details = traceback.format_exc() debug_logs = log_capture.getvalue() + f"\n\nβ ERROR:\n{error_details}" sys.stdout = original_stdout # Restore stdout err = f"<p style='color:#ef4444;padding:20px;font-family:monospace;'>β Error during evaluation:<br>{exc}</p>" yield (gr.update(visible=False), gr.update(visible=True), err, "", "", "", submit_count, debug_logs) finally: sys.stdout = original_stdout # Always restore stdout
def on_send(message, history, hints_used, submit_count, hint_log, confirmation_pending): if not message.strip(): penalty = PENALTY_TABLE[min(hints_used, len(PENALTY_TABLE) - 1)] return history, "", hints_used, _hint_md(hints_used, penalty), hint_log, confirmation_pending result = get_hint( user_message=message, history=history, hints_used=hints_used, submission_attempts=submit_count, challenge_info=cs.challenge_info(), ) # Python-level guarantee: if a confirmation was pending and the student # didn't explicitly decline, the hint counts β regardless of LLM marker. accepted_pending = confirmation_pending and not _is_decline(message) gave_hint = result["gave_hint"] or accepted_pending new_confirmation_pending = not gave_hint and _is_confirmation_question(result["response"])
history = list(history or []) + [ {"role": "user", "content": message}, {"role": "assistant", "content": result["response"]}, ] new_hints = hints_used + (1 if gave_hint else 0) penalty = PENALTY_TABLE[min(new_hints, len(PENALTY_TABLE) - 1)] new_log = list(hint_log or []) if gave_hint: new_log.append({"summary": result.get("hint_summary", ""), "response": result["response"]}) return history, "", new_hints, _hint_md(new_hints, penalty), new_log, new_confirmation_pending
# ββ Wiring ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
file_dropdown.change(on_file_select, inputs=[file_dropdown], outputs=[code_editor]) save_btn.click(on_save, inputs=[code_editor], outputs=[save_status])
btn_tests.click(on_run_tests, inputs=[code_editor], outputs=[left_tabs, test_output]) run_tests_tab_btn.click(on_run_tests, inputs=[code_editor], outputs=[left_tabs, test_output])
btn_changes.click(on_show_changes, outputs=[left_tabs, changes_diff_html]) refresh_btn.click(on_show_changes, outputs=[left_tabs, changes_diff_html])
revert_btn.click(on_revert, outputs=[code_editor, left_tabs])
submit_btn.click( on_submit, inputs=[hints_used_state, submission_count_state, hint_log_state], outputs=[ challenge_col, results_col, score_summary_html, results_changes_html, results_test_html, results_hints_html, submission_count_state, debug_console_standalone, ], ) send_btn.click( on_send, inputs=[chat_input, chatbot, hints_used_state, submission_count_state, hint_log_state, confirmation_pending_state], outputs=[chatbot, chat_input, hints_used_state, hint_counter, hint_log_state, confirmation_pending_state], ) chat_input.submit( on_send, inputs=[chat_input, chatbot, hints_used_state, submission_count_state, hint_log_state, confirmation_pending_state], outputs=[chatbot, chat_input, hints_used_state, hint_counter, hint_log_state, confirmation_pending_state], )
return demo123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213"""Quick unit test for the refactored two-phase bug injection system.Tests _generate_tests_for_function, _inject_bug_into_function, and _sabotage_one_helper."""
import osos.environ["OPENAI_API_KEY"] = "your-api-key-here" # Replace before running
from langchain_openai import ChatOpenAIfrom architect.saboteur import _generate_tests_for_function, _inject_bug_into_function, _execute_tests_on_source, _sabotage_one_helper
# Simple test functionTEST_FUNCTION = """def power_of_three(n): \"\"\"Return n to the power of 3.\"\"\" result = 1 for i in range(n): result = result * 3 return result"""
TEST_MODULE = """def power_of_three(n): \"\"\"Return n to the power of 3.\"\"\" result = 1 for i in range(n): result = result * 3 return result
def multiply(a, b): return a * b"""
def test_generate_tests(): """Test Phase 1: Generate tests for working code.""" print("\n" + "="*60) print("TEST 1: _generate_tests_for_function()") print("="*60) llm = ChatOpenAI(model="gpt-4o", temperature=0.7) test_data = _generate_tests_for_function( func_source=TEST_FUNCTION, func_name="power_of_three", surface_func_name="power_of_three", surface_source=TEST_FUNCTION, llm=llm, indirect_mode=False, debug_mode=True ) if test_data: print("\nβ
SUCCESS: Generated tests") print(f"Public tests: {test_data.get('test_cases_public', [])}") print(f"Secret tests: {test_data.get('test_cases_secret', [])}") return test_data else: print("\nβ FAILED: Could not generate tests") return None
def test_inject_bug(): """Test Phase 2: Inject bug into function.""" print("\n" + "="*60) print("TEST 2: _inject_bug_into_function()") print("="*60) llm = ChatOpenAI(model="gpt-4o", temperature=0.7) buggy_data = _inject_bug_into_function( func_source=TEST_FUNCTION, func_name="power_of_three", llm=llm, attempted_bugs=[], debug_mode=True ) if buggy_data: print("\nβ
SUCCESS: Injected bug") print(f"Bug description: {buggy_data.get('bug_description', 'N/A')}") print(f"Buggy code:\n{buggy_data.get('sabotaged_function_code', '')}") return buggy_data else: print("\nβ FAILED: Could not inject bug") return None
def test_execute_tests(): """Test Phase 3: Execute tests on source.""" print("\n" + "="*60) print("TEST 3: _execute_tests_on_source()") print("="*60) # First generate tests llm = ChatOpenAI(model="gpt-4o", temperature=0.7) test_data = _generate_tests_for_function( func_source=TEST_FUNCTION, func_name="power_of_three", surface_func_name="power_of_three", surface_source=TEST_FUNCTION, llm=llm, indirect_mode=False, debug_mode=False ) if not test_data: print("β Could not generate tests") return False # Execute on original code print("\nExecuting tests on ORIGINAL code...") original_results = _execute_tests_on_source( TEST_MODULE, "power_of_three", test_data, debug_mode=True ) # Inject bug buggy_data = _inject_bug_into_function( func_source=TEST_FUNCTION, func_name="power_of_three", llm=llm, attempted_bugs=[], debug_mode=False ) if not buggy_data: print("β Could not inject bug") return False # Create buggy module buggy_module = TEST_MODULE.replace(TEST_FUNCTION, buggy_data["sabotaged_function_code"]) # Execute on buggy code print("\nExecuting tests on BUGGY code...") buggy_results = _execute_tests_on_source( buggy_module, "power_of_three", test_data, debug_mode=True ) # Count differences differences = 0 for test_args_str in original_results: if test_args_str not in buggy_results: continue orig_success, orig_result = original_results[test_args_str] buggy_success, buggy_result = buggy_results[test_args_str] if orig_success != buggy_success or orig_result != buggy_result: differences += 1 print(f"\nβ DIFFERENCE: {test_args_str}") print(f" Original: {orig_result}") print(f" Buggy: {buggy_result}") print(f"\n{'β
' if differences >= 4 else 'β'} Result: {differences}/6 tests caught the bug") return differences >= 4
def test_full_pipeline(): """Test the complete _sabotage_one_helper function.""" print("\n" + "="*60) print("TEST 4: _sabotage_one_helper() - FULL PIPELINE") print("="*60) llm = ChatOpenAI(model="gpt-4o", temperature=0.7) buggy_source, data = _sabotage_one_helper( bug_func_name="power_of_three", current_source=TEST_MODULE, surface_func_name="power_of_three", surface_source=TEST_FUNCTION, instructions="Inject a simple bug into the function.", llm=llm, indirect_mode=False, debug_mode=True ) if buggy_source and data: print("\n" + "="*60) print("β
FULL PIPELINE SUCCESS!") print("="*60) print(f"Bug description: {data.get('bug_description', 'N/A')}") print(f"Tests catching bug: {data.get('_debug_tests_catching_bug', 'N/A')}") print(f"\nPublic tests: {len(data.get('test_cases_public', []))}") print(f"Secret tests: {len(data.get('test_cases_secret', []))}") return True else: print("\nβ FULL PIPELINE FAILED") return False
if __name__ == "__main__": print("\n" + "="*60) print("TWO-PHASE BUG INJECTION SYSTEM - UNIT TESTS") print("="*60) # Check API key if "your-api-key-here" in os.environ.get("OPENAI_API_KEY", ""): print("\nβ οΈ WARNING: Please set your OpenAI API key in this file before running!") print("Edit line 7 to add your API key.\n") exit(1) # Run tests test_generate_tests() test_inject_bug() test_execute_tests() test_full_pipeline() print("\n" + "="*60) print("TESTS COMPLETE") print("="*60 + "\n")1234567891011121314151617181920212223242526272829#!/usr/bin/env python3"""wsgi.py β Gunicorn WSGI wrapper for Gradio
This is a workaround for Render's auto-detection.Render insists on running 'gunicorn app:app' but Gradio doesn't support WSGI.
Solution: This file makes gunicorn launch python app.py as a subprocess."""
import osimport sysimport subprocess
# When gunicorn imports this, we launch the real app and exitif __name__ != "__main__": print("π§ Gunicorn detected - launching python app.py instead...") subprocess.run([sys.executable, "app.py"]) sys.exit(0)
# This should never be reached, but just in case:def application(environ, start_response): """Dummy WSGI application that should never be called.""" status = '500 Internal Server Error' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) return [b'Error: Use python app.py directly, not WSGI']
app = application.dockerignoreAdded+21
.env.exampleAdded+18
.gitignoreAdded+12
AptfileAdded+1
DockerfileAdded+22
GOOGLE_DRIVE_SETUP.mdAdded+113
GOOGLE_SHEETS_SETUP.mdAdded+107
LOGIN_GUIDE.mdAdded+185
PRESET_REPOS.mdAdded+159
ProcfileAdded+1
README.mdAdded+35
REFACTORING_NOTES.mdAdded+278
RENDER_DEPLOYMENT.mdAdded+85
RENDER_FIX.mdAdded+106
RENDER_GOOGLE_SHEETS_SETUP.mdAdded+159
add_login.mdAdded+242
app.pyAdded+59
architect/__init__.pyAdded
architect/challenge_deployer.pyAdded+257
architect/file_mapper.pyAdded+257
architect/graph.pyAdded+75
architect/nodes.pyAdded+99
architect/readme_generator.pyAdded+107
architect/repo_cloner.pyAdded+86
architect/saboteur.pyAdded
architect/saboteur_new.txtAdded+197
architect/state.pyAdded+39
challenge.pyAdded+136
debug_output.txtAdded+113
git_submissions_logger.pyAdded+237
google_sheets_logger.pyAdded+206
launch_existing.pyAdded+38
launch_interface.batAdded+36
login_patch.pyAdded+118
main.pyAdded+94
orchestrator/__init__.pyAdded+1
orchestrator/graph.pyAdded+31
orchestrator/hint_graph.pyAdded+424
orchestrator/nodes.pyAdded+135
orchestrator/scoring.pyAdded+436
orchestrator/state.pyAdded+29
render.yamlAdded+18
requirements.txtAdded+10
runtime.txtAdded+1
session_storage_solution.mdAdded+111
start.shAdded+15
start_render.shAdded+4
student_interface.pyAdded+2091
test_refactored_saboteur.pyAdded+213
wsgi.pyAdded+29