File size: 13,241 Bytes
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f05e252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4966a08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f05e252
 
 
 
 
 
 
 
532e19f
 
 
f05e252
532e19f
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import os
import 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)

    sabotaged_files = state.get("sabotaged_files") or {}
    if sabotaged_files:
        for rel_path, content in sabotaged_files.items():
            abs_path = os.path.join(clone_path, rel_path)
            os.makedirs(os.path.dirname(abs_path), exist_ok=True)
            with open(abs_path, "w", encoding="utf-8") as f:
                f.write(content)
            print(f"[deployer] Applied sabotaged file: {abs_path}")
    else:
        sabotaged_code = state.get("sabotaged_code", "")
        if target_file and sabotaged_code:
            with open(target_file, "w", encoding="utf-8") as f:
                f.write(sabotaged_code)
            print(f"[deployer] Applied sabotaged target file: {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
        })

    state["public_tests"] = [
        {
            "function_name": bug["function_name"],
            "bug_description": bug.get("bug_description", ""),
            **test_case,
        }
        for bug in bugs_with_tests
        for test_case in bug.get("public_tests", [])
    ]
    state["secret_tests"] = [
        {
            "function_name": bug["function_name"],
            "bug_description": bug.get("bug_description", ""),
            **test_case,
        }
        for bug in bugs_with_tests
        for test_case in bug.get("secret_tests", [])
    ]
    
    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", "")
    snapshot_sources = sabotaged_files or {}
    if not snapshot_sources and target_file and sabotaged_code:
        rel = os.path.relpath(target_file, clone_path)
        snapshot_sources = {rel: sabotaged_code}

    for rel_path, content in snapshot_sources.items():
        snap_name = rel_path.replace("/", "__").replace("\\", "__")
        snap_path = os.path.join(metadata_dir, snap_name)
        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(content)
        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 state