Spaces:
Sleeping
Sleeping
Improve challenge generation and sheet sync
Browse filesFiles changed (4)
200 unmodified lines20120220320420520620720814 unmodified lines22322422522422522622722822923017 unmodified lines248249250249251252253254200 unmodified linesdef map_files(state: ArchitectState) -> ArchitectState: clone_path = state["clone_path"] target_nesting = state["nesting_level"] requested_bugs = max(1, state.get("num_bugs") or 1) min_functions = max(2, min(5, requested_bugs + 1)) suitable_files: list[tuple[int, int, str]] = [] # (func_count, line_count, path)
for root, dirs, files in os.walk(clone_path):14 unmodified lines 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: # Keep smaller files in the fallback pool as long as they can plausibly host bug targets. if func_count >= min_functions: suitable_files.append((func_count, line_count, full)) except: continue # Skip files that can't be parsed17 unmodified lines
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] Found {len(suitable_files)} suitable files ({min_functions}+ 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")832 unmodified lines83383483583683783883984084183683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387416 unmodified lines89189289389489589689789889990090190290390490590690790890991091191291391491591648 unmodified lines9659669679689699709719729739749229759769779781079 unmodified lines20582059206020082009206120622063206420652066201220672068206920704 unmodified lines2075207620772023207820792080208110 unmodified lines209220932094204020952096209720988 unmodified lines21072108210920552056205721102111211221132114211534 unmodified lines2150215121522098215321542100215521562157215846 unmodified lines220522062207220821532209221022112212832 unmodified lines if value == "": return "str:empty" if len(value) == 1: return "str:char" if len(value) <= 5: return "str:short" if len(value) <= 20: return "str:medium" return "str:long" length_bucket = "char" elif len(value) <= 5: length_bucket = "short" elif len(value) <= 20: length_bucket = "medium" else: length_bucket = "long"
if value.islower(): case_bucket = "lower" elif value.isupper(): case_bucket = "upper" elif value[:1].isupper() and any(ch.islower() for ch in value[1:]): case_bucket = "title" elif any(ch.isupper() for ch in value) and any(ch.islower() for ch in value): case_bucket = "mixed" else: case_bucket = "other"
separator_flags = [] if "_" in value: separator_flags.append("underscore") if "-" in value: separator_flags.append("hyphen") if " " in value: separator_flags.append("space") if any(ch.isdigit() for ch in value): separator_flags.append("digit") if value[:1] == "_": separator_flags.append("leading_us") if value[-1:] == "_": separator_flags.append("trailing_us") if not separator_flags: separator_flags.append("plain")
return f"str:{length_bucket}:{case_bucket}:{','.join(separator_flags)}" if isinstance(value, list): elem_types = sorted({type(item).__name__ for item in value}) size = "empty" if not value else "one" if len(value) == 1 else "short" if len(value) <= 4 else "long"16 unmodified lines return f"raw:{_normalize_test_args(args_text)}"
def _single_string_argument_cases(test_cases: list[dict]) -> bool: parsed_cases = 0 for test in test_cases: args_text = test.get("args", "") or test.get("test_args", "") if not args_text: continue try: value = ast.literal_eval(args_text) if not isinstance(value, tuple): value = (value,) except Exception: return False
parsed_cases += 1 if len(value) != 1 or not isinstance(value[0], str): return False
return parsed_cases > 0
def _generate_tests_for_function( func_source: str, func_name: str,48 unmodified lines for test in test_cases if test.get("args", "") or test.get("test_args", "") } required_patterns = min(8, len(unique_args)) if _single_string_argument_cases(test_cases): required_patterns = min(4, len(unique_args)) if ( len(test_cases) >= 20 and len(unique_args) >= max(18, int(len(test_cases) * 0.8)) and len(diversity_signatures) >= min(8, len(unique_args)) and len(diversity_signatures) >= required_patterns ): if debug_mode: print(1079 unmodified lines func_code = "\n".join(source_lines[node.lineno-1:node.end_lineno]) candidates.append((node.name, func_code)) if len(candidates) < n_funcs: return [] # Not enough functions if not candidates: return []
requested_funcs = min(n_funcs, len(candidates)) # Step 2: Use GPT to select best functions for bug injection print(f"[picker] Found {len(candidates)} candidate functions, asking GPT to select best {n_funcs}...") print(f"[picker] Found {len(candidates)} candidate functions, asking GPT to select best {requested_funcs}...") try: # Build prompt with function previews4 unmodified lines prompt = f"""You are an expert code analyst selecting functions for bug injection in a coding challenge.
TASK: Select the {n_funcs} BEST functions from the candidates below for injecting subtle logical bugs.TASK: Select the {requested_funcs} BEST functions from the candidates below for injecting subtle logical bugs.
SELECTION CRITERIA (in priority order):1. TESTABILITY: Functions with clear inputs/outputs and deterministic behavior10 unmodified lines "selected_functions": ["function_name_1", "function_name_2", ...]}}
Return EXACTLY {n_funcs} function names. Choose functions that would make good challenge candidates."""Return EXACTLY {requested_funcs} function names if possible. If fewer candidates are truly suitable, return as many suitable names as you can. Choose functions that would make good challenge candidates."""
response = llm.invoke([HumanMessage(content=prompt)]) response_text = response.content8 unmodified lines valid_names = {name for name, _ in candidates} selected = [name for name in selected if name in valid_names] if len(selected) >= n_funcs: print(f"[picker] GPT selected: {selected[:n_funcs]}") return selected[:n_funcs] if selected: print(f"[picker] GPT selected: {selected[:requested_funcs]}") return selected[:requested_funcs] else: print(f"[picker] GPT returned only {len(selected)} valid functions, falling back to AST scoring...") 34 unmodified lines # Sort by score and take top candidates scored.sort(key=lambda x: x[0], reverse=True) top_candidates = scored[:min(n_funcs * 3, len(scored))] top_candidates = scored[:min(max(requested_funcs * 3, 8), len(scored))] random.shuffle(top_candidates) return [name for _, name in top_candidates[:n_funcs]] return [name for _, name in top_candidates[:requested_funcs]]
def saboteur_init(state: ArchitectState) -> ArchitectState:46 unmodified lines remaining_bugs = n_bugs - len(all_bugs_data) # Pick candidate functions (we may not succeed with all) target_candidates = max(remaining_bugs * 6, 8) candidate_funcs = _pick_simple_functions(source, remaining_bugs * 3, llm) candidate_funcs = _pick_simple_functions(source, target_candidates, llm) if not candidate_funcs: if debug_mode:8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344454647484 unmodified lines535455565758599 unmodified lines6970717273747576777879808182838485863940414243878889909192939495969798454647484950991001011021035610410558596061626364656667686970711061071081098 unmodified lines11811912012112212312412512612712812913013113213313413513613713813914014140 unmodified lines1821831841411421431441451461471481491501511521531541551561571581591601611621631641651661851861871888 unmodified linesfrom datetime import datetimefrom typing import Optional
from dotenv import load_dotenv
load_dotenv()
SUMMARY_HEADERS = [ "תאריך ושעה", "שם סטודנט", "אתגר", "GitHub Repository", "קובץ יעד", "ציון", "הינטים", "טסטים שעברו", "הצליח?", "סוג תוצאה", "נגעה בפונקציית באג?", "תיאור הבאג", "התכתבות עם הצ'אט",]
def _ensure_sheet_headers(sheet) -> None: current_headers = sheet.row_values(1) if current_headers[:len(SUMMARY_HEADERS)] == SUMMARY_HEADERS: return
sheet.update(range_name="A1:M1", values=[SUMMARY_HEADERS]) sheet.format("A1:M1", { "textFormat": {"bold": True}, "backgroundColor": {"red": 0.9, "green": 0.9, "blue": 0.9}, })
def log_to_google_sheets( student_name: str,4 unmodified lines passed_tests: int, all_passed: bool, chat_history: list, submission_record: Optional[dict] = None,) -> bool: """ Log submission to Google Sheets.9 unmodified lines try: import gspread import json from google.oauth2.service_account import Credentials # Try to get service account from environment variable first (for cloud deployment) service_account_json = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON") if service_account_json: # Parse JSON from environment variable service_account_info = json.loads(service_account_json) scopes = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] creds = Credentials.from_service_account_info(service_account_info, scopes=scopes) else: # 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 # Fall back to file (for local development) service_account_file = "google-service-account.json" if not os.path.exists(service_account_file): print("⚠️ Google Sheets: service account not configured (neither env var nor 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) # 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 # Initialize or migrate headers to the current schema. 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}}) _ensure_sheet_headers(sheet) except Exception as e: print(f"⚠️ Could not set headers: {e}") 8 unmodified lines ]) else: chat_text = "לא השתמש בהינטים"
challenge = submission_record.get("challenge", {}) if submission_record else {} scoring = submission_record.get("scoring", {}) if submission_record else {} submission = submission_record.get("submission", {}) if submission_record else {} row = [ timestamp, student_name or "Anonymous", challenge.get("challenge_id", ""), repo_url, challenge.get("target_file", ""), score, hints_used, f"{passed_tests}/{total_tests}", "✅ הצליח" if all_passed else "❌ לא הצליח", scoring.get("submission_outcome", ""), "כן" if submission.get("touched_bug_function") else "לא", challenge.get("bug_description", ""), chat_text, ] 40 unmodified lines 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} }) _ensure_sheet_headers(sheet) print("✅ Headers initialized!") return True 13 unmodified lines141516171718192021292 unmodified lines31431531631731731831932013 unmodified linesfrom typing import TypedDict
from langgraph.graph import StateGraph, ENDfrom langchain_openai import ChatOpenAIfrom langchain_core.messages import HumanMessage, SystemMessage, AIMessagefrom llm_config import get_llm
# Cumulative penalty table — index = number of hints used (mirrors scoring.py)_HINT_PENALTY = [0, 2, 6, 12, 20, 30]292 unmodified lines 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) llm = get_llm(temperature=0.7, request_timeout=60)
# Reconstruct the conversation for the LLM lc_messages: list = [SystemMessage(content=system_prompt)]architect/file_mapper.py+5-3
architect/saboteur.py+74-18
google_sheets_logger.py+71-52
orchestrator/hint_graph.py+2-2