File size: 28,508 Bytes
5f3b513
 
 
 
 
 
 
 
 
 
7277d37
5f3b513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19bb70b
5f3b513
 
 
 
19bb70b
 
 
 
5f3b513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a071c7
 
 
 
 
 
5f3b513
 
 
 
 
 
 
 
 
a68171e
19bb70b
5f3b513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7277d37
19bb70b
5f3b513
 
cae3d69
5f3b513
 
 
 
 
 
 
19bb70b
 
cae3d69
 
7277d37
5f3b513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19bb70b
b91ac29
19bb70b
 
1a0c29d
7277d37
 
5f3b513
92176ae
 
 
 
 
 
5f3b513
9efae57
 
 
 
 
 
 
 
 
 
 
 
5f3b513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cae3d69
5f3b513
 
 
 
 
 
 
 
 
 
7277d37
 
5f3b513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
"""Gradio-independent challenge generation services."""

from __future__ import annotations

import json
import hashlib
import io
import shutil
import stat
import zipfile
from collections.abc import Callable
from datetime import datetime
from pathlib import Path
from pathlib import PurePosixPath
from uuid import UUID, uuid4

from architect.private_artifacts import ensure_private_workspace_dir, private_workspace_dir

_ROUND_PRIVATE_FILES = (
    "challenge_state.json",
    "challenge_run_public.py",
    "challenge_run_secret.py",
    "secret_tests.json",
)
_STUDENT_STATE_FIELDS = {
    "github_url",
    "workspace_path",
    "challenge_created_at",
    "target_file",
    "sabotaged_code",
    "sabotaged_files",
    "nesting_level",
    "refactoring_enabled",
    "debug_mode",
    "challenge_summary",
    "challenge_round_id",
}
_MAX_ROUND_ARCHIVE_BYTES = 45 * 1024 * 1024
_MAX_ROUND_UNPACKED_BYTES = 100 * 1024 * 1024


def _rounds_root() -> Path:
    from architect.repo_cloner import WORKSPACES_DIR

    return Path(WORKSPACES_DIR).resolve() / ".rounds"


def _round_hashes(workspace: Path, private_dir: Path) -> tuple[str, str]:
    artifact_digest = hashlib.sha256()
    for path in sorted(file for file in workspace.rglob("*") if file.is_file()):
        relative = path.relative_to(workspace).as_posix()
        artifact_digest.update(relative.encode("utf-8"))
        artifact_digest.update(b"\0")
        artifact_digest.update(path.read_bytes())
        artifact_digest.update(b"\0")

    tests_digest = hashlib.sha256()
    for name in _ROUND_PRIVATE_FILES:
        path = private_dir / name
        if not path.is_file():
            raise FileNotFoundError(f"Round test artifact is missing: {name}")
        tests_digest.update(name.encode("utf-8"))
        tests_digest.update(b"\0")
        tests_digest.update(path.read_bytes())
        tests_digest.update(b"\0")
    return artifact_digest.hexdigest(), tests_digest.hexdigest()


def _copy_round_private_files(source_workspace: Path, target_workspace: Path) -> None:
    source_dir = private_workspace_dir(source_workspace)
    target_dir = ensure_private_workspace_dir(target_workspace)
    for name in _ROUND_PRIVATE_FILES:
        source = source_dir / name
        if name == "challenge_state.json" and not source.is_file():
            source = source_workspace / name
        if not source.is_file():
            raise FileNotFoundError(f"Round test artifact is missing: {name}")
        target = target_dir / name
        shutil.copyfile(source, target)
        target.chmod(0o600)


def _student_visible_state(state: dict[str, object]) -> dict[str, object]:
    return {key: value for key, value in state.items() if key in _STUDENT_STATE_FIELDS}


def create_challenge_round_archive(round_id: str) -> bytes:
    safe_round_id = str(UUID(round_id))
    round_dir = _rounds_root() / safe_round_id
    template = round_dir / "workspace"
    manifest_path = round_dir / "round.json"
    if not template.is_dir() or not manifest_path.is_file():
        raise FileNotFoundError("Challenge round was not found")

    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
        for path in sorted(template.rglob("*")):
            if not path.is_file():
                continue
            if path.is_symlink():
                raise ValueError("Challenge round contains a symlink")
            archive.write(path, f"workspace/{path.relative_to(template).as_posix()}")
        private_dir = private_workspace_dir(template)
        for name in _ROUND_PRIVATE_FILES:
            path = private_dir / name
            if not path.is_file():
                raise FileNotFoundError(f"Round test artifact is missing: {name}")
            archive.write(path, f"private/{name}")
    bundle = buffer.getvalue()
    if len(bundle) > _MAX_ROUND_ARCHIVE_BYTES:
        raise ValueError("Challenge round archive exceeds the 45 MiB storage limit")
    return bundle


def delete_challenge_round(round_id: str) -> None:
    safe_round_id = str(UUID(round_id))
    round_dir = _rounds_root() / safe_round_id
    template = round_dir / "workspace"
    shutil.rmtree(round_dir, ignore_errors=True)
    shutil.rmtree(private_workspace_dir(template), ignore_errors=True)


def _restore_challenge_round_archive(
    round_id: str,
    manifest: dict[str, str | int],
    archive_bytes: bytes,
) -> Path:
    from architect.repo_cloner import WORKSPACES_DIR

    safe_round_id = str(UUID(round_id))
    if manifest.get("round_id") != safe_round_id or len(archive_bytes) > _MAX_ROUND_ARCHIVE_BYTES:
        raise ValueError("Challenge round metadata or archive is invalid")
    rounds_root = _rounds_root()
    rounds_root.mkdir(parents=True, exist_ok=True)
    round_dir = rounds_root / safe_round_id
    if round_dir.exists():
        cached_template = round_dir / "workspace"
        if cached_template.is_dir() and (round_dir / "round.json").is_file():
            return cached_template
        shutil.rmtree(round_dir, ignore_errors=True)

    staging_dir = rounds_root / f".restore-{uuid4()}"
    template = staging_dir / "workspace"
    staged_private_dir: Path | None = None
    try:
        staging_dir.mkdir(mode=0o700)
        total_size = 0
        seen_names: set[str] = set()
        with zipfile.ZipFile(io.BytesIO(archive_bytes), "r") as bundle:
            for entry in bundle.infolist():
                member = PurePosixPath(entry.filename)
                if member.is_absolute() or ".." in member.parts or not member.parts:
                    raise ValueError("Challenge round archive contains an unsafe path")
                if entry.is_dir():
                    continue
                if entry.filename in seen_names:
                    raise ValueError("Challenge round archive contains duplicate paths")
                seen_names.add(entry.filename)
                total_size += entry.file_size
                if total_size > _MAX_ROUND_UNPACKED_BYTES:
                    raise ValueError("Challenge round archive expands beyond the 100 MiB limit")
                mode = (entry.external_attr >> 16) & 0o170000
                if mode == stat.S_IFLNK:
                    raise ValueError("Challenge round archive contains a symlink")

                if member.parts[0] == "workspace" and len(member.parts) > 1:
                    if any(part in {".private", ".rounds"} for part in member.parts[1:]):
                        raise ValueError("Challenge round archive contains a reserved path")
                    destination = template.joinpath(*member.parts[1:])
                elif member.parts[0] == "private" and len(member.parts) == 2 and member.parts[1] in _ROUND_PRIVATE_FILES:
                    if staged_private_dir is None:
                        staged_private_dir = ensure_private_workspace_dir(template)
                    destination = staged_private_dir / member.parts[1]
                else:
                    raise ValueError("Challenge round archive contains an unsupported path")
                destination.parent.mkdir(parents=True, exist_ok=True)
                with bundle.open(entry, "r") as source, destination.open("wb") as target:
                    shutil.copyfileobj(source, target)
                destination.chmod(0o600)

        if staged_private_dir is None:
            raise ValueError("Challenge round archive is missing private test artifacts")
        archive_hash, tests_hash = _round_hashes(template, staged_private_dir)
        if archive_hash != manifest.get("artifact_hash") or tests_hash != manifest.get("tests_hash"):
            raise ValueError("Challenge round integrity check failed")
        (staging_dir / "round.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
        staging_dir.chmod(0o700)
        staging_dir.rename(round_dir)

        restored_template = round_dir / "workspace"
        restored_private = ensure_private_workspace_dir(restored_template)
        for name in _ROUND_PRIVATE_FILES:
            shutil.copyfile(staged_private_dir / name, restored_private / name)
            (restored_private / name).chmod(0o600)
        restored_hashes = _round_hashes(restored_template, restored_private)
        if restored_hashes != (manifest.get("artifact_hash"), manifest.get("tests_hash")):
            raise ValueError("Restored challenge round failed integrity verification")
        shutil.rmtree(private_workspace_dir(template), ignore_errors=True)
        return restored_template
    except Exception:
        shutil.rmtree(round_dir, ignore_errors=True)
        shutil.rmtree(staging_dir, ignore_errors=True)
        if staged_private_dir:
            shutil.rmtree(staged_private_dir, ignore_errors=True)
        raise


def create_challenge_round(
    workspace_path: str | Path,
    timer_minutes: int = 0,
    chat_messages_per_student: int = 5,
) -> dict[str, str | int]:
    """Publish the current challenge and private tests as an immutable local round."""
    from architect.repo_cloner import WORKSPACES_DIR

    if isinstance(chat_messages_per_student, bool) or not isinstance(chat_messages_per_student, int):
        raise ValueError("Round chat message limit must be an integer")
    if not 0 <= chat_messages_per_student <= 100:
        raise ValueError("Round chat message limit must be between 0 and 100 per student")

    source_workspace = Path(workspace_path).resolve()
    challenge = ChallengeWorkspace(source_workspace)
    round_id = str(uuid4())
    round_dir = _rounds_root() / round_id
    template = round_dir / "workspace"
    round_dir.mkdir(parents=True, mode=0o700)
    round_dir.chmod(0o700)
    shutil.copytree(source_workspace, template)
    state_path = template / "challenge_state.json"
    state = json.loads(state_path.read_text(encoding="utf-8"))
    target_file = Path(state.get("target_file", ""))
    if target_file.is_absolute():
        try:
            target_file = target_file.resolve().relative_to(source_workspace)
        except ValueError as exc:
            shutil.rmtree(round_dir, ignore_errors=True)
            raise ValueError("Challenge target is outside the source workspace") from exc
    state["target_file"] = target_file.as_posix()
    state["workspace_path"] = str(template.resolve())
    state_path.write_text(json.dumps(state, indent=2, ensure_ascii=False), encoding="utf-8")
    _copy_round_private_files(source_workspace, template)
    private_state_path = private_workspace_dir(template) / "challenge_state.json"
    private_state = json.loads(private_state_path.read_text(encoding="utf-8"))
    private_state["target_file"] = target_file.as_posix()
    private_state["workspace_path"] = str(template.resolve())
    private_state_path.write_text(json.dumps(private_state, indent=2, ensure_ascii=False), encoding="utf-8")
    private_state_path.chmod(0o600)
    state_path.write_text(json.dumps(_student_visible_state(private_state), indent=2, ensure_ascii=False), encoding="utf-8")
    round_workspace = ChallengeWorkspace(template)
    if challenge.sabotaged_files:
        for relative_path, received_code in challenge.sabotaged_files.items():
            round_workspace.write_file(relative_path, received_code)
    else:
        round_workspace.reset_target()
    (template / "detailed_explanation.txt").unlink(missing_ok=True)
    artifact_hash, tests_hash = _round_hashes(template, private_workspace_dir(template))
    manifest: dict[str, str | int] = {
        "round_id": round_id,
        "github_url": challenge.github_url,
        "target_file": challenge.target_file,
        "artifact_hash": artifact_hash,
        "tests_hash": tests_hash,
        "timer_minutes": max(0, min(int(timer_minutes), 120)),
        "quota_units_per_student": chat_messages_per_student + 2,
        "chat_messages_per_student": chat_messages_per_student,
    }
    (round_dir / "round.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
    return manifest


def create_challenge_from_round(
    round_id: str, workspace_id: str, course_id: str = "local"
) -> tuple[str, dict[str, str | int]]:
    """Create an isolated participant workspace from a verified round snapshot."""
    from architect.repo_cloner import WORKSPACES_DIR

    safe_round_id = str(UUID(round_id))
    safe_workspace_id = str(UUID(workspace_id))
    round_dir = _rounds_root() / safe_round_id
    manifest_path = round_dir / "round.json"
    template = round_dir / "workspace"
    if not manifest_path.is_file() or not template.is_dir():
        from supabase_challenge_rounds import ChallengeRoundStoreError, load_challenge_round

        try:
            stored_round = load_challenge_round(safe_round_id, course_id)
        except ChallengeRoundStoreError as exc:
            raise FileNotFoundError(f"Could not load this shared round from persistent storage: {exc}") from exc
        if stored_round is None:
            raise FileNotFoundError("Challenge round was not found")
        stored_manifest, archive_bytes = stored_round
        template = _restore_challenge_round_archive(safe_round_id, stored_manifest, archive_bytes)
        round_dir = template.parent
        manifest_path = round_dir / "round.json"
    try:
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise FileNotFoundError("Challenge round was not found") from exc
    if manifest.get("round_id") != safe_round_id or not template.is_dir():
        raise FileNotFoundError("Challenge round was not found")

    actual_hashes = _round_hashes(template, private_workspace_dir(template))
    if actual_hashes != (manifest.get("artifact_hash"), manifest.get("tests_hash")):
        raise ValueError("Challenge round integrity check failed")

    workspace_path = Path(WORKSPACES_DIR).resolve() / safe_workspace_id
    if workspace_path.exists():
        raise FileExistsError("Challenge workspace already exists")
    shutil.copytree(template, workspace_path)
    try:
        _copy_round_private_files(template, workspace_path)
        state_path = workspace_path / "challenge_state.json"
        private_state_path = private_workspace_dir(workspace_path) / "challenge_state.json"
        state = json.loads(private_state_path.read_text(encoding="utf-8"))
        state["workspace_path"] = str(workspace_path)
        state["challenge_round_id"] = safe_round_id
        private_state_path.write_text(json.dumps(state, indent=2, ensure_ascii=False), encoding="utf-8")
        private_state_path.chmod(0o600)
        state_path.write_text(json.dumps(_student_visible_state(state), indent=2, ensure_ascii=False), encoding="utf-8")
        (workspace_path / "detailed_explanation.txt").unlink(missing_ok=True)
    except Exception:
        shutil.rmtree(workspace_path, ignore_errors=True)
        shutil.rmtree(private_workspace_dir(workspace_path), ignore_errors=True)
        raise
    return str(workspace_path), manifest


def create_challenge(
    github_url: str,
    nesting_level: int,
    num_bugs: int,
    refactoring_enabled: bool = False,
    debug_mode: bool = False,
    workspace_id: str | None = None,
    progress_callback: Callable[[int, str], None] | None = None,
    generation_id: str | None = None,
) -> str:
    """Run the architect graph and persist its result into a challenge workspace."""
    from architect.bug_first_pipeline import build_selected_graph, get_challenge_pipeline_variant
    from architect.repo_cloner import WORKSPACES_DIR

    clone_path = ""
    if workspace_id:
        safe_workspace_id = str(UUID(workspace_id))
        clone_path = str(Path(WORKSPACES_DIR) / safe_workspace_id)

    from supabase_generation_prompts import load_generation_prompt_supplements

    pipeline_variant = get_challenge_pipeline_variant()
    graph = build_selected_graph(progress_callback=progress_callback)
    initial_state = {
        "github_url": github_url,
        "nesting_level": nesting_level,
        "refactoring_enabled": refactoring_enabled,
        "debug_mode": debug_mode,
        "num_bugs": num_bugs,
        "clone_path": 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": {},
        "generation_id": generation_id or str(uuid4()),
        "generation_progress_callback": progress_callback,
        "prompt_supplements": load_generation_prompt_supplements(),
        "generation_failures": [],
        "generation_usage": {},
    }
    result = graph.invoke(initial_state)

    try:
        from supabase_generation_prompts import record_generation_event
        record_generation_event(generation_id or "", "generation_benchmark", "node_timings", payload=result.get("node_timings") or {})
    except Exception:
        pass

    workspace_path = result["clone_path"]
    workspace_root = Path(workspace_path).resolve()
    target_file_rel = ""
    target_file_value = str(result.get("target_file") or "")
    if target_file_value:
        target_path = Path(target_file_value)
        if not target_path.is_absolute():
            target_path = workspace_root / target_path
        try:
            target_path = target_path.resolve(strict=True)
            target_file_rel = target_path.relative_to(workspace_root).as_posix()
        except (FileNotFoundError, OSError, ValueError) as exc:
            raise ValueError("Generated challenge target file is outside the workspace or unavailable") from exc
    actual_sabotaged_code = result.get("sabotaged_code", "")
    workspace_root = 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")

    sabotaged_files: dict[str, str] = {}
    if target_file_rel and actual_sabotaged_code:
        try:
            relative_path = Path(target_file_rel).resolve().relative_to(workspace_root).as_posix()
        except (ValueError, OSError):
            relative_path = Path(target_file_rel).as_posix()
        sabotaged_files[relative_path] = actual_sabotaged_code

    challenge_state = {
        "github_url": github_url,
        "workspace_path": workspace_path,
        "challenge_created_at": datetime.now().isoformat(),
        "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", []),
        "nesting_level": nesting_level,
        "refactoring_enabled": refactoring_enabled,
        "debug_mode": debug_mode,
        "pipeline_variant": pipeline_variant,
        "bug_description": result.get("bug_description", ""),
        "detailed_explanation": result.get("detailed_explanation", ""),
        "challenge_summary": result.get("challenge_summary", ""),
    }
    state_path = Path(workspace_path) / "challenge_state.json"
    private_state_path = ensure_private_workspace_dir(workspace_path) / "challenge_state.json"
    private_state_path.write_text(json.dumps(challenge_state, indent=2, ensure_ascii=False), encoding="utf-8")
    private_state_path.chmod(0o600)
    state_path.write_text(json.dumps(_student_visible_state(challenge_state), indent=2, ensure_ascii=False), encoding="utf-8")
    (Path(workspace_path) / "detailed_explanation.txt").unlink(missing_ok=True)
    if progress_callback:
        progress_callback(99, "Finalizing challenge workspace")
    return workspace_path


class ChallengeWorkspace:
    """Read and edit only student-visible Python files in a challenge workspace."""

    _HIDDEN_NAMES = {"challenge_run.py", "challenge_run_secret.py"}

    def __init__(self, workspace_path: str | Path) -> None:
        from architect.repo_cloner import WORKSPACES_DIR

        self.workspace = Path(workspace_path).resolve()
        workspaces_root = Path(WORKSPACES_DIR).resolve()
        try:
            self.workspace.relative_to(workspaces_root)
        except ValueError as exc:
            raise ValueError("Workspace must be inside the workspaces directory") from exc

        state_path = self.workspace / "challenge_state.json"
        if not state_path.is_file():
            raise FileNotFoundError("Challenge state was not found")
        private_dir = ensure_private_workspace_dir(self.workspace)
        private_state_path = private_dir / "challenge_state.json"
        visible_data = json.loads(state_path.read_text(encoding="utf-8"))
        if private_state_path.is_file():
            self.data = json.loads(private_state_path.read_text(encoding="utf-8"))
        else:
            self.data = visible_data
            private_state_path.write_text(json.dumps(self.data, ensure_ascii=False), encoding="utf-8")
            private_state_path.chmod(0o600)
        legacy_secret_tests = self.data.pop("secret_tests", None)
        secret_data_path = private_dir / "secret_tests.json"
        if legacy_secret_tests is not None and not secret_data_path.is_file():
            secret_data_path.write_text(
                json.dumps({"secret_tests": legacy_secret_tests}, ensure_ascii=False),
                encoding="utf-8",
            )
            secret_data_path.chmod(0o600)

        private_runners = {
            "challenge_run.py": private_dir / "challenge_run_public.py",
            "challenge_run_secret.py": private_dir / "challenge_run_secret.py",
        }
        legacy_runners = tuple(
            (self.workspace / runner_name, private_runner)
            for runner_name, private_runner in private_runners.items()
        ) + (
            (self.workspace / ".metadata" / "challenge_run_secret.py", private_runners["challenge_run_secret.py"]),
        )
        for legacy_runner, private_runner in legacy_runners:
            if not private_runner.is_file() and legacy_runner.is_file():
                shutil.copyfile(legacy_runner, private_runner)
                private_runner.chmod(0o600)

        migrated = legacy_secret_tests is not None
        for legacy_runner, _private_runner in legacy_runners:
            if legacy_runner.is_file():
                try:
                    legacy_runner.chmod(stat.S_IRUSR | stat.S_IWUSR)
                    legacy_runner.unlink()
                    migrated = True
                except OSError:
                    pass
        if migrated or visible_data != _student_visible_state(self.data):
            state_path.write_text(json.dumps(_student_visible_state(self.data), indent=2, ensure_ascii=False), encoding="utf-8")
        if migrated:
            private_state_path.write_text(json.dumps(self.data, indent=2, ensure_ascii=False), encoding="utf-8")
            private_state_path.chmod(0o600)

        target = Path(self.data.get("target_file", ""))
        if target.is_absolute():
            try:
                target = target.resolve().relative_to(self.workspace)
            except ValueError as exc:
                raise ValueError("Challenge target is outside its workspace") from exc
        self.target_file = target.as_posix()
        self.github_url = str(self.data.get("github_url", ""))
        self.original_code = str(self.data.get("original_code", ""))
        self.sabotaged_code = str(self.data.get("sabotaged_code", ""))
        self.bug_func_source = str(self.data.get("bug_func_source", ""))
        self.original_bug_func_source = str(self.data.get("original_bug_func_source", ""))
        self.sabotaged_files = dict(self.data.get("sabotaged_files", {}))
        self.bug_description = str(self.data.get("bug_description", ""))
        self.challenge_summary = str(self.data.get("challenge_summary", ""))
        self.function_name = str(self.data.get("function_name", ""))
        self.bug_func_name = str(self.data.get("bug_func_name", ""))
        self.bug_func_names = list(self.data.get("bug_func_names", []))
        self.bug_func_sources_list = list(self.data.get("bug_func_sources_list", []))
        self.original_bug_func_sources_list = list(self.data.get("original_bug_func_sources_list", []))
        self.public_tests = list(self.data.get("public_tests", []))
        try:
            secret_path = private_dir / "secret_tests.json"
            private_data = json.loads(secret_path.read_text(encoding="utf-8"))
            self.secret_tests = list(private_data.get("secret_tests", []))
        except (OSError, ValueError, json.JSONDecodeError):
            self.secret_tests = []
        self.nesting_level = int(self.data.get("nesting_level", 3))
        self.refactoring_enabled = bool(self.data.get("refactoring_enabled", False))
        self.debug_mode = bool(self.data.get("debug_mode", False))

    @property
    def target_path(self) -> Path:
        return self._resolve_python_file(self.target_file)

    def _resolve_python_file(self, rel_path: str) -> Path:
        if not isinstance(rel_path, str) or not rel_path.strip():
            raise ValueError("A relative Python file path is required")
        normalized = rel_path.replace("\\", "/")
        pure_path = PurePosixPath(normalized)
        if pure_path.is_absolute() or ".." in pure_path.parts or ".metadata" in pure_path.parts:
            raise ValueError("File path is not available")
        if pure_path.name in self._HIDDEN_NAMES or pure_path.suffix != ".py":
            raise ValueError("File path is not available")
        full_path = (self.workspace / Path(*pure_path.parts)).resolve()
        try:
            full_path.relative_to(self.workspace)
        except ValueError as exc:
            raise ValueError("File path is outside the challenge workspace") from exc
        return full_path

    def list_python_files(self) -> list[str]:
        files = sorted(self.workspace.rglob("*.py"))
        return [
            file.relative_to(self.workspace).as_posix()
            for file in files
            if file.is_file()
            and ".metadata" not in file.relative_to(self.workspace).parts
            and file.name not in self._HIDDEN_NAMES
        ]

    def read_file(self, rel_path: str) -> str:
        file_path = self._resolve_python_file(rel_path)
        if not file_path.is_file():
            raise FileNotFoundError("Python file was not found")
        return file_path.read_text(encoding="utf-8")

    def write_file(self, rel_path: str, content: str) -> None:
        if not isinstance(content, str):
            raise ValueError("File contents must be text")
        file_path = self._resolve_python_file(rel_path)
        if not file_path.is_file():
            raise FileNotFoundError("Python file was not found")
        file_path.write_text(content, encoding="utf-8")

    def reset_target(self) -> str:
        self.write_file(self.target_file, self.sabotaged_code)
        return self.sabotaged_code

    def readme(self) -> str:
        readme_path = self.workspace / "STUDENT_README.md"
        return readme_path.read_text(encoding="utf-8") if readme_path.is_file() else ""

    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,
        }