Exploit database

GH-786074ac4c791dc9be6cc1a41bc35b4e

royaleybovich/cve-2026-3854-lab

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-3854

2 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files6
royaleybovich/cve-2026-3854-labRevision e8ab9eea2577

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

services/portal/main.py

Suggested starting filePython · 35,210 bytes
# SPDX-FileCopyrightText: 2026 Royal Leybovich
# SPDX-License-Identifier: GPL-3.0-or-later

import hashlib
import json
import os
import re
import time
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
from urllib.parse import quote, unquote

import requests
from fastapi import FastAPI, Form, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from jinja2 import Environment, FileSystemLoader, select_autoescape
from services.portal.curriculum import GUIDED_LEVELS, RESEARCH_CHALLENGES
from shared.tracing.store import connect_redis, get_recent_traces, get_trace_lines

app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379/0")
redis_client = connect_redis(REDIS_URL)

DEFAULT_USER = os.getenv("DEFAULT_USER", "devuser")
DEFAULT_PASSWORD = os.getenv("DEFAULT_PASSWORD", "devpass")
LEARNING_REPOSITORY_NAME = os.getenv("LEARNING_REPOSITORY_NAME", "learn-lab")
LEARN_REPOSITORY = f"{DEFAULT_USER}/{LEARNING_REPOSITORY_NAME}"
REPO_CLONE_COMMAND = f"git clone http://{DEFAULT_USER}:{DEFAULT_PASSWORD}@localhost:3000/{DEFAULT_USER}/YOUR_REPOSITORY.git forgedock-lab"
BASELINE_PUSH_COMMAND = "cd forgedock-lab && git commit --allow-empty -m 'baseline push' && git push origin main"
IDENTITY_COMMAND = 'git config user.name "ForgeDock Learner" && git config user.email "learner@localhost"'
LEARN_REPOSITORY_API = f"http://forgejo:3000/api/v1/repos/{LEARN_REPOSITORY}"
LEARN_REPOSITORIES_API = "http://forgejo:3000/api/v1/user/repos"
RESEARCH_STARTED_COOKIE = "forge_research_v2_started"
RESEARCH_SOLVED_COOKIE = "forge_research_v2_solved"
LEARNING_ATTEMPT_LIMIT = 8

app.mount("/static", StaticFiles(directory="services/portal/static"), name="static")
env = Environment(loader=FileSystemLoader("services/portal/templates"), autoescape=select_autoescape(["html"]))

def progress_get(request: Request, key: str, default: Any) -> Any:
    raw = request.cookies.get(key)
    if raw is None: return default
    try: return json.loads(unquote(raw))
    except (json.JSONDecodeError, TypeError): return raw

def progress_set(request: Request, key: str, value: Any) -> None:
    # Learn progress is deliberately local to this browser and written by the response helpers.
    return None

def render(template: str, **context: Any) -> HTMLResponse:
    return HTMLResponse(env.get_template(template).render(mode=context.pop("mode", None), **context))

def require_learn(request: Request) -> None:
    if request.cookies.get("flagship_learn") != "1":
        raise HTTPException(403, "Learning Lab data is available only inside the Learning Lab")

def cookie_list(request: Request, name: str, default: List[int]) -> List[int]:
    stored = progress_get(request, name, None)
    if stored is not None:
        try: return sorted({int(x) for x in stored})
        except (ValueError, TypeError): return default
    try:
        data = json.loads(unquote(request.cookies.get(name, "")))
        return sorted({int(x) for x in data})
    except (ValueError, TypeError, json.JSONDecodeError):
        return default

def set_list_cookie(response: Any, name: str, values: List[int], request: Optional[Request] = None) -> None:
    response.set_cookie(name, quote(json.dumps(sorted(set(values)))), path="/", samesite="lax")
    if request: progress_set(request, name, sorted(set(values)))

def completed(request: Request) -> List[int]: return cookie_list(request, "forge_completed", [])
def unlocked(request: Request) -> List[int]:
    # Every lesson remains navigable. Completion is still derived from real
    # milestones, but browsing the curriculum never produces a dead end.
    return [1, 2, 3, 4]

def trace_summary(trace: Dict[str, Any], lines: List[Dict[str, Any]], number: int) -> Dict[str, Any]:
    events = {line.get("event_type"): line.get("message", "") for line in lines}
    final = "Production controls unchanged"
    progress = False
    if "runner.diagnostic_granted" in events: final, progress = "Diagnostics enabled", True
    elif "runner.hook_exit" in events: final, progress = "Hook executed", True
    elif "runner.legacy" in events: final, progress = "Legacy path reached", True
    elif any("Duplicate keys detected:" in x.get("message", "") and not x["message"].endswith("0") for x in lines): final, progress = "Protected fields changed", True
    return {**trace, "number": number, "short_id": trace.get("trace_id", "")[:8], "time": (trace.get("created_at") or "")[:19].replace("T", " "), "final_state": final, "progress": progress, "lines": lines}

def attempts(repository: Optional[str] = None) -> List[Dict[str, Any]]:
    traces = get_recent_traces(redis_client, limit=200)
    if repository:
        traces = [trace for trace in traces if trace.get("repo") == repository]
    total = len(traces)
    result = []
    for i, trace in enumerate(traces):
        lines = get_trace_lines(redis_client, trace.get("trace_id"))
        result.append(trace_summary(trace, lines, total-i))
    return result

CURRICULUM_KEYS = ["baseline_push_seen", "tag_option_seen", "tag_created", "serializer_observed", "delimiter_injection_seen", "duplicate_key_seen", "pipeline_mode_overridden", "execution_fields_identified", "runtime_gate_overridden", "custom_hook_gate_overridden", "hook_manifest_supplied", "hook_path_resolved", "final_proof_received"]

def curriculum_state() -> Dict[str, bool]:
    state = {key: False for key in CURRICULUM_KEYS}
    for attempt in attempts(LEARN_REPOSITORY):
        for line in attempt["lines"]:
            event, message = line.get("event_type", ""), line.get("message", "")
            payload = {}
            if message.startswith("{"):
                try: payload = json.loads(message)
                except json.JSONDecodeError: pass
            if event == "push.directives":
                raw = payload.get("raw_push_options", [])
                if not raw: state["baseline_push_seen"] = True
                for directive in payload.get("recognized_directives", []):
                    if directive.get("name") == "tag":
                        state["tag_option_seen"] = True
                        # "exists" is an idempotent success: the directive
                        # checked the real ref and safely refused to overwrite it.
                        state["tag_created"] |= directive.get("result") in {"created", "exists"}
            if event == "receive-state-serialized": state["serializer_observed"] = True
            if event == "receive-state-parsed":
                winners = payload.get("winning_values", {})
                duplicates = payload.get("duplicate_keys", [])
                state["delimiter_injection_seen"] |= winners.get("lesson_probe") == "str:visible"
                state["duplicate_key_seen"] |= bool(duplicates)
                state["runtime_gate_overridden"] |= winners.get("runtime_mode") == "str:development"
                state["pipeline_mode_overridden"] |= winners.get("pipeline_mode") == "str:diagnostic"
                state["custom_hook_gate_overridden"] |= winners.get("custom_hooks_enabled") == "bool:true"
                state["hook_manifest_supplied"] |= winners.get("hook_manifest", "json:[]") != "json:[]"
                state["execution_fields_identified"] |= (
                    winners.get("runtime_mode") == "str:development"
                    and winners.get("custom_hooks_enabled") == "bool:true"
                    and winners.get("hook_root") != "str:/opt/forgedock/hooks"
                    and winners.get("hook_manifest", "json:[]") != "json:[]"
                )
            if event == "runner.path": state["hook_path_resolved"] = True
        events = {line.get("event_type"): line.get("message", "") for line in attempt["lines"]}
        # The diagnostic tool also emits a proof token. Lesson 4 completes only
        # when the same attempt resolved and executed the escape-hook tool.
        proof_output = events.get("runner.output", "")
        state["final_proof_received"] |= (
            "escape-hook" in events.get("runner.path", "")
            and "FLAG{" in proof_output
            and "runner.hook_exit" in events
        )
    return state

def event_payload(lines: List[Dict[str, Any]], event_type: str) -> Dict[str, Any]:
    line = next((item for item in lines if item.get("event_type") == event_type), None)
    if not line:
        return {}
    if isinstance(line.get("message"), dict):
        return line["message"]
    try:
        value = json.loads(line.get("message", ""))
        return value if isinstance(value, dict) else {}
    except (TypeError, json.JSONDecodeError):
        return {}

def visible_directive_results(directives: List[Dict[str, Any]]) -> List[str]:
    results = []
    for directive in directives:
        name, result, value = directive.get("name"), directive.get("result"), directive.get("value", "")
        if name == "tag":
            labels = {
                "created": f"Tag {value} created",
                "exists": f"Tag {value} already exists",
                "unauthorized": f"Tag {value} was not authorized",
                "invalid": f"Tag {value} was invalid",
                "no-target": "Tag was not created because no pushed commit was available",
                "failed": "ForgeDock could not create the tag",
            }
            results.append(labels.get(result, "Tag directive processed"))
        elif name == "ci.skip":
            results.append("CI processing skipped")
    return results

def processing_state(attempt: Dict[str, Any], events: Dict[str, str], directives: List[Dict[str, Any]]) -> Dict[str, str]:
    status = attempt.get("status", "started")
    if status == "started":
        return {"state": "processing", "code": status, "label": "ForgeDock is processing this push"}
    if status in {"invalid-manifest", "dispatch-failed"}:
        return {"state": "error", "code": status, "label": "ForgeDock could not finish post-push processing"}
    if status == "failed":
        return {"state": "error", "code": status, "label": "The system tool ran and returned an error"}
    if status == "policy-changed":
        return {"state": "blocked", "code": status, "label": "One protected field changed; execution remained blocked"}
    if status == "no-hooks":
        return {"state": "blocked", "code": status, "label": "Execution remained blocked because no hook manifest was supplied"}
    if status == "executed" and "escape-hook" in events.get("runner.path", ""):
        return {"state": "complete", "code": status, "label": "Code-execution proof received"}
    if status == "executed" and "runner.diagnostic_granted" in events:
        return {"state": "complete", "code": status, "label": "Diagnostic processing completed"}
    results = visible_directive_results(directives)
    return {"state": "complete", "code": status, "label": results[-1] if results else "No protected state changed"}

def learning_attempt_card(attempt: Dict[str, Any], lesson: int) -> Dict[str, Any]:
    lines = attempt.get("lines", [])
    event_messages = {line.get("event_type"): line.get("message", "") for line in lines}
    received = event_payload(lines, "push.received")
    directive_payload = event_payload(lines, "push.directives")
    raw_options = directive_payload.get("raw_push_options", [])
    directives = directive_payload.get("recognized_directives", [])
    ref_updates = received.get("ref_updates", [])
    ref_update = next((item for item in ref_updates if str(item.get("ref", "")).startswith("refs/heads/")), ref_updates[0] if ref_updates else {})
    oid = ref_update.get("new_oid", "")
    results = visible_directive_results(directives)
    if not raw_options:
        results.append("No push options were provided")
    proof_output = event_messages.get("runner.output", "")
    confirmation = None
    if "escape-hook" in event_messages.get("runner.path", "") and "runner.hook_exit" in event_messages:
        confirmation = {
            "title": "Payload worked — escape-hook executed",
            "detail": "ForgeDock passed every execution gate and the isolated demonstration tool ran successfully.",
        }
    elif "runner.diagnostic_granted" in event_messages and proof_output:
        confirmation = {
            "title": "Payload worked — diagnostic mode reached",
            "detail": "Your duplicate pipeline_mode value replaced the trusted production setting.",
        }

    card: Dict[str, Any] = {
        "id": attempt.get("trace_id", ""),
        "number": attempt.get("number", 0),
        "occurred_at": received.get("received_at") or attempt.get("created_at", ""),
        "repository": received.get("repository") or attempt.get("repo", LEARN_REPOSITORY),
        "commit": {"oid": oid, "short_oid": oid[:10] if oid else "Unavailable", "ref": ref_update.get("ref", "Unavailable")},
        "git": {"status": "accepted", "label": "Push accepted"},
        "processing": processing_state(attempt, event_messages, directives),
        "push_options": {"raw": raw_options, "recognized_directives": directives},
        "visible_results": results,
        "confirmation": confirmation,
        "serializer": None,
        "parser": None,
        "execution": None,
    }

    serializer = event_payload(lines, "receive-state-serialized")
    if lesson >= 2 and serializer:
        card["serializer"] = {
            "trusted_fields": serializer.get("trusted_fields", {}),
            "push_option_fields": serializer.get("push_option_fields", {}),
            "serialized_value": serializer.get("serialized_value", ""),
            "delimiter": serializer.get("delimiter", ";"),
        }

    parsed = event_payload(lines, "receive-state-parsed")
    winners = parsed.get("winning_values", {})
    if lesson >= 3 and parsed:
        duplicate_rows = []
        for key in parsed.get("duplicate_keys", []):
            history = parsed.get("values_seen", {}).get(key, [])
            duplicate_rows.append({
                "key": key,
                "original": history[0] if history else "Unavailable",
                "injected": history[1:] if len(history) > 1 else [],
                "winning": winners.get(key, history[-1] if history else "Unavailable"),
            })
        card["parser"] = {
            "fields": winners,
            "duplicate_keys": parsed.get("duplicate_keys", []),
            "duplicates": duplicate_rows,
            "winning_values": winners,
        }

    if lesson >= 4 and parsed:
        manifest_raw = winners.get("hook_manifest", "json:[]")
        try:
            manifest = json.loads(str(manifest_raw).removeprefix("json:"))
            manifest_count = len(manifest) if isinstance(manifest, list) else 0
        except json.JSONDecodeError:
            manifest_count = 0
        resolved_message = event_messages.get("runner.path", "")
        resolved_path = resolved_message.split(": ", 1)[-1] if resolved_message else "Not reached"
        runtime = str(winners.get("runtime_mode", "str:production")).removeprefix("str:")
        custom_hooks = winners.get("custom_hooks_enabled") == "bool:true"
        proof_received = "escape-hook" in resolved_path and "FLAG{" in proof_output
        card["execution"] = {
            "gates": [
                {"name": "Runtime mode", "value": runtime, "passed": runtime != "production"},
                {"name": "Custom hooks", "value": "enabled" if custom_hooks else "disabled", "passed": custom_hooks},
                {"name": "Manifest", "value": f"{manifest_count} entr{'y' if manifest_count == 1 else 'ies'}", "passed": manifest_count > 0},
            ],
            "hook_root": str(winners.get("hook_root", "str:/opt/forgedock/hooks")).removeprefix("str:"),
            "hook_manifest": manifest_raw,
            "resolved_path": resolved_path,
            "result": "Code-execution proof received" if proof_received else card["processing"]["label"],
            "proof_received": proof_received,
        }
    return card

def attempt_curriculum_level(attempt: Dict[str, Any]) -> int:
    """Classify a Learning push without returning later-lesson fields early."""
    lines = attempt.get("lines", [])
    raw_options = event_payload(lines, "push.directives").get("raw_push_options", [])
    raw_text = "\n".join(str(option) for option in raw_options)
    winners = event_payload(lines, "receive-state-parsed").get("winning_values", {})
    if (
        any(name in raw_text for name in ("custom_hooks_enabled", "hook_root", "hook_manifest", "flagship="))
        or winners.get("hook_manifest", "json:[]") != "json:[]"
        or winners.get("custom_hooks_enabled") == "bool:true"
    ):
        return 4
    if any(name in raw_text for name in ("runtime_mode", "pipeline_mode", "diagnostics_enabled")):
        return 3
    if ";" in raw_text or "lesson_probe" in winners:
        return 2
    return 1

def attempts_cursor(items: List[Dict[str, Any]]) -> str:
    revision = [
        [item.get("trace_id"), item.get("status"), len(item.get("lines", []))]
        for item in items
    ]
    return hashlib.sha256(json.dumps(revision, separators=(",", ":")).encode()).hexdigest()[:20]

def lesson_progress_with(request: Request, active: Optional[int], done: List[int], state: Dict[str, bool]) -> Dict[str, Any]:
    lessons = []
    for level in GUIDED_LEVELS:
        status = "completed" if level["id"] in done else "current" if level["id"] == active else "not-started"
        lessons.append({
            "id": level["id"], "title": level["title"], "status": status,
            "requirements_met": all(state.get(key, False) for key in level["required"]),
            "url": f"/guided/level/{level['id']}",
        })
    next_id = next((level["id"] for level in GUIDED_LEVELS if level["id"] not in done), None)
    return {
        "state": state, "completed": done, "lessons": lessons,
        "all_complete": len(done) == len(GUIDED_LEVELS),
        "next_url": "/guided/complete" if next_id is None else f"/guided/level/{next_id}",
    }

def lesson_progress(request: Request, active: Optional[int] = None) -> Dict[str, Any]:
    return lesson_progress_with(request, active, completed(request), curriculum_state())

EXCERPT_SOURCE = Path("vendor/forgejo/modules/repositoryevents/processor.go")
def code_excerpt(name: str) -> str:
    if name not in {"directives", "serializer", "parser", "execution"}: raise FileNotFoundError(name)
    source = EXCERPT_SOURCE.read_text(encoding="utf-8")
    start, end = f"// curriculum:{name}:start", f"// curriculum:{name}:end"
    if start not in source or end not in source: raise RuntimeError(f"Curriculum excerpt markers missing: {name}")
    return source.split(start, 1)[1].split(end, 1)[0].strip()

def baseline_detected() -> bool:
    for item in attempts(LEARN_REPOSITORY):
        events = [x.get("event_type") for x in item["lines"]]
        if "runner.production" in events and "rpc.duplicates" in events and item["final_state"] == "Production controls unchanged": return True
    return False

def get_service_health() -> List[Dict[str, Any]]:
    services = [
        ("Forgejo", "http://forgejo:3000/api/healthz"),
        ("Hook Executor", "http://hook-executor:8083/healthz"),
        ("Web Terminal", "http://web-terminal:7681"),
    ]
    # Reaching this function through the portal readiness route is itself the
    # portal liveness signal; a blocking HTTP request back into the same worker
    # would deadlock and report a false negative.
    result = [{"name": "Flagship Portal", "state": "ready", "label": "Ready", "detail": "Readiness endpoint is responding"}]
    for name, url in services:
        try:
            response = requests.get(url, timeout=.8)
            result.append({"name": name, "state": "ready" if response.ok else "attention", "label": "Ready" if response.ok else "Needs attention", "detail": "Health check passed" if response.ok else f"HTTP {response.status_code}"})
        except requests.RequestException:
            result.append({"name": name, "state": "unavailable", "label": "Unavailable", "detail": "Service did not answer. Check Docker Compose."})
    redis_ready = not redis_client.__class__.__name__.startswith("Dummy")
    result.append({"name": "Trace Store", "state": "ready" if redis_ready else "unavailable", "label": "Ready" if redis_ready else "Unavailable", "detail": "Trace storage is responding" if redis_ready else "Redis is unavailable"})
    return result

@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
    return render("index.html")

@app.get("/guided", response_class=HTMLResponse)
async def guided_welcome(request: Request):
    response = render("guided/welcome.html", levels=GUIDED_LEVELS, has_progress=bool(completed(request)) or bool(progress_get(request, "forge_onboarding", False)))
    response.set_cookie("flagship_learn", "1", path="/", samesite="lax")
    return response

@app.get("/guided/start", response_class=HTMLResponse)
async def guided_start(): return RedirectResponse("/guided/setup", status_code=307)

@app.get("/guided/setup", response_class=HTMLResponse)
async def guided_setup(request: Request):
    health = get_service_health(); baseline = baseline_detected() or bool(progress_get(request, "forge_baseline", False))
    response = render("guided/setup.html", health=health, baseline=baseline, all_ready=all(x["state"] == "ready" for x in health), commands={"start": "docker compose up -d --build", "clone": REPO_CLONE_COMMAND, "identity": IDENTITY_COMMAND, "baseline": BASELINE_PUSH_COMMAND})
    response.set_cookie("forge_onboarding", "1", path="/"); progress_set(request, "forge_onboarding", True)
    response.set_cookie("flagship_learn", "1", path="/", samesite="lax")
    if baseline: response.set_cookie("forge_baseline", "1", path="/"); progress_set(request, "forge_baseline", True)
    return response

@app.get("/api/readiness")
async def readiness(request: Request):
    require_learn(request)
    health = get_service_health(); return {"services": health, "all_ready": all(x["state"] == "ready" for x in health), "baseline": baseline_detected(), "repository_ready": learn_repository_exists()}

def learn_repository_exists() -> bool:
    try: return requests.get(LEARN_REPOSITORY_API, auth=(DEFAULT_USER, DEFAULT_PASSWORD), timeout=2).status_code == 200
    except requests.RequestException: return False

@app.get("/api/learn-repository")
async def learn_repository_status(request: Request):
    require_learn(request)
    return {"ready": learn_repository_exists(), "full_name": LEARN_REPOSITORY}

@app.post("/api/learn-repository")
async def create_learn_repository(request: Request):
    require_learn(request)
    if learn_repository_exists(): return {"ready": True, "created": False, "full_name": LEARN_REPOSITORY}
    try:
        response = requests.post(LEARN_REPOSITORIES_API, auth=(DEFAULT_USER, DEFAULT_PASSWORD), json={"name": LEARNING_REPOSITORY_NAME, "auto_init": True, "default_branch": "main"}, timeout=5)
    except requests.RequestException as exc:
        raise HTTPException(503, f"ForgeDock did not answer: {exc}") from exc
    if response.status_code != 201: raise HTTPException(502, "ForgeDock could not create the learning repository")
    return {"ready": True, "created": True, "full_name": LEARN_REPOSITORY}

@app.get("/api/traces")
async def traces_api(request: Request, trace_id: Optional[str] = None):
    require_learn(request)
    raise HTTPException(410, "The raw trace viewer was replaced by lesson-aware Learning Lab push cards")

@app.get("/api/learning/attempts")
async def learning_attempts(request: Request, lesson: int = 1, after: Optional[str] = None):
    require_learn(request)
    if lesson not in range(1, 5):
        raise HTTPException(404, "Lesson not found")
    items = [item for item in attempts(LEARN_REPOSITORY) if attempt_curriculum_level(item) <= lesson]
    cursor = attempts_cursor(items)
    if after and after == cursor:
        return {"cursor": cursor, "unchanged": True, "attempts": []}
    visible_items = items[:LEARNING_ATTEMPT_LIMIT]
    return {
        "cursor": cursor,
        "unchanged": False,
        "total": len(items),
        "attempts": [learning_attempt_card(item, lesson) for item in visible_items],
    }

@app.get("/api/learning/progress")
async def learning_progress(request: Request, active: Optional[int] = None):
    require_learn(request)
    if active is not None and active not in range(1, 5):
        raise HTTPException(404, "Lesson not found")
    return lesson_progress(request, active)

@app.post("/api/learning/lessons/{level_id}/complete")
async def complete_learning_lesson(request: Request, level_id: int):
    require_learn(request)
    if level_id not in range(1, 5):
        raise HTTPException(404, "Lesson not found")
    level = GUIDED_LEVELS[level_id - 1]
    state = curriculum_state()
    missing = [key for key in level["required"] if not state.get(key)]
    if missing:
        return JSONResponse({"complete": False, "missing": missing, **lesson_progress(request, level_id)}, status_code=409)
    done = completed(request)
    if level_id not in done:
        done.append(level_id)
    response = JSONResponse({"complete": True, **lesson_progress_with(request, level_id, done, state)})
    set_list_cookie(response, "forge_completed", done, request)
    return response

@app.get("/api/lessons/state")
async def lessons_state(request: Request):
    require_learn(request)
    return curriculum_state()

@app.get("/api/lessons/excerpt/{name}")
async def lesson_excerpt(request: Request, name: str):
    require_learn(request)
    try: return {"name": name, "source": code_excerpt(name)}
    except FileNotFoundError: raise HTTPException(404)

@app.get("/guided/level/{level_id}", response_class=HTMLResponse)
async def guided_level(request: Request, level_id: int, trace_id: Optional[str] = None, feedback: Optional[str] = None):
    if level_id not in range(1, 5): raise HTTPException(404)
    level = GUIDED_LEVELS[level_id-1]
    response = render(
        "guided/level.html", level=level, levels=GUIDED_LEVELS,
        completed=completed(request), unlocked=unlocked(request),
        lesson_state=curriculum_state(), progress=lesson_progress(request, level_id),
        feedback=feedback,
    )
    response.set_cookie("flagship_learn", "1", path="/", samesite="lax")
    return response

@app.post("/guided/level/{level_id}/complete")
async def complete_milestone_level(request: Request, level_id: int):
    require_learn(request)
    if level_id not in range(1, 5): raise HTTPException(404)
    level = GUIDED_LEVELS[level_id-1]
    state = curriculum_state(); missing = [key for key in level["required"] if not state.get(key)]
    if missing: return await guided_level(request, level_id, feedback="Run the required real experiments first: " + ", ".join(missing))
    done = completed(request)
    if level_id not in done: done.append(level_id)
    destination = "/guided/complete" if level_id == 4 else f"/guided/level/{level_id + 1}"
    response = RedirectResponse(destination, status_code=303); set_list_cookie(response, "forge_completed", done, request); return response

@app.get("/guided/level/{level_id}/review", response_class=HTMLResponse)
async def level_review(request: Request, level_id: int):
    if level_id not in completed(request): raise HTTPException(403, "Complete this level before opening its review")
    return RedirectResponse("/guided/complete" if level_id == 4 else f"/guided/level/{level_id + 1}", status_code=302)

@app.get("/guided/complete", response_class=HTMLResponse)
async def guided_complete(request: Request):
    if not all(x in completed(request) for x in (1,2,3,4)): raise HTTPException(403, "Complete all lessons first")
    return render("guided/complete.html", levels=GUIDED_LEVELS, completed=completed(request))

@app.post("/guided/reset/{level_id}")
async def reset_level(request: Request, level_id: int):
    done = [x for x in completed(request) if x != level_id]
    response = RedirectResponse(f"/guided/level/{level_id}", status_code=303); set_list_cookie(response, "forge_completed", done, request); progress_set(request, f"forge_hints_{level_id}", []); response.delete_cookie(f"forge_hints_{level_id}", path="/"); return response

@app.get("/guided/reset/{level_id}")
@app.get("/guided/reset-all")
async def destructive_get_rejected(level_id: Optional[int] = None): raise HTTPException(405, "Reset actions require POST")

@app.post("/guided/reset-all")
async def reset_all(request: Request):
    response = RedirectResponse("/guided", status_code=303)
    for name in ["forge_completed", "forge_onboarding", "forge_baseline", "forge_unlocked_levels"]: response.delete_cookie(name, path="/"); progress_set(request, name, [])
    return response

def research_start_epoch(request: Request) -> Optional[float]:
    try:
        return float(request.cookies.get(RESEARCH_STARTED_COOKIE, ""))
    except (TypeError, ValueError):
        return None

def attempt_epoch(attempt: Dict[str, Any]) -> float:
    value = attempt.get("created_at", "")
    try:
        return datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp()
    except (TypeError, ValueError):
        return 0.0

def research_attempts_since(started: float) -> List[Dict[str, Any]]:
    return [
        attempt for attempt in attempts()
        if attempt_epoch(attempt) >= started
    ]

def research_flag(value: str) -> bool:
    return bool(re.fullmatch(r"FLAG\{[A-Za-z0-9_-]{3,96}\}", value))

def configured_research_flag(variable: str) -> str:
    value = os.getenv(variable, "").strip()
    return value if research_flag(value) else ""

def research_proof_observed(challenge_id: int, submitted: str, started: float) -> bool:
    proof_variables = {1: "FLAG", 2: "DIAGNOSTIC_FLAG", 3: "HOOK_ESCAPE_FLAG"}
    configured = configured_research_flag(proof_variables.get(challenge_id, ""))
    if not configured or submitted != configured:
        return False
    for attempt in research_attempts_since(started):
        lines = attempt.get("lines", [])
        if challenge_id == 1:
            directives = event_payload(lines, "push.directives").get("recognized_directives", [])
            if any(
                item.get("name") == "tag"
                and item.get("result") == "created"
                and item.get("proof_embedded") is True
                for item in directives
            ):
                return True
        elif challenge_id == 2:
            directive_payload = event_payload(lines, "push.directives")
            parsed = event_payload(lines, "receive-state-parsed")
            raw = directive_payload.get("raw_push_options", [])
            events = {line.get("event_type"): line.get("message", "") for line in lines}
            if (
                parsed.get("winning_values", {}).get("pipeline_mode") == "str:diagnostic"
                and "pipeline_mode" in parsed.get("duplicate_keys", [])
                and any(";pipeline_mode=str:diagnostic" in str(option) for option in raw)
                and "runner.diagnostic_granted" in events
                and configured in events.get("runner.output", "")
            ):
                return True
        elif challenge_id == 3:
            events = {line.get("event_type"): line.get("message", "") for line in lines}
            if "escape-hook" in events.get("runner.path", "") and configured in events.get("runner.output", ""):
                return True
    return False

def research_cards(
    request: Request,
    feedback_id: Optional[int] = None,
    feedback: Optional[str] = None,
    submitted: str = "",
    solved_override: Optional[set] = None,
    active_id: Optional[int] = None,
) -> List[Dict[str, Any]]:
    valid_ids = {item["id"] for item in RESEARCH_CHALLENGES}
    stored = cookie_list(request, RESEARCH_SOLVED_COOKIE, [])
    solved = set(stored if solved_override is None else solved_override) & valid_ids
    cards = []
    for definition in RESEARCH_CHALLENGES:
        card = dict(definition)
        challenge_id = definition["id"]
        prerequisites = set(range(1, challenge_id))
        card["solved"] = challenge_id in solved
        card["available"] = prerequisites.issubset(solved)
        card["locked"] = not card["available"]
        card["state"] = "solved" if card["solved"] else "available" if card["available"] else "locked"
        card["active"] = active_id == challenge_id and card["available"]
        card["unlock_text"] = f"Solve Challenge {challenge_id - 1} to unlock" if card["locked"] else ""
        card["feedback"] = feedback if definition["id"] == feedback_id else None
        card["evidence_flag"] = submitted if definition["id"] == feedback_id and feedback == "Incorrect" else ""
        card["next_id"] = challenge_id + 1 if card["solved"] and challenge_id < len(RESEARCH_CHALLENGES) else None
        cards.append(card)
    return cards

@app.get("/research", response_class=HTMLResponse)
async def research_ticket(request: Request):
    cards = research_cards(request)
    response = render(
        "research.html",
        challenges=cards,
        solved_count=sum(1 for card in cards if card["solved"]),
    )
    response.delete_cookie("flagship_learn", path="/")
    if research_start_epoch(request) is None:
        response.set_cookie(RESEARCH_STARTED_COOKIE, str(time.time()), path="/", samesite="lax", httponly=True)
    response.delete_cookie("forge_research_started", path="/")
    response.delete_cookie("forge_research_solved", path="/")
    return response

@app.post("/research/challenge/{challenge_id}/submit", response_class=HTMLResponse)
async def submit_research_challenge(request: Request, challenge_id: int, flag: str = Form(...)):
    if challenge_id not in range(1, len(RESEARCH_CHALLENGES) + 1):
        raise HTTPException(404, "Challenge not found")
    started = research_start_epoch(request)
    if started is None:
        started = time.time()
    solved = set(cookie_list(request, RESEARCH_SOLVED_COOKIE, []))
    if not set(range(1, challenge_id)).issubset(solved):
        raise HTTPException(403, "Solve the previous challenge first")
    submitted = flag.strip()
    correct = research_proof_observed(challenge_id, submitted, started)
    if correct:
        solved.add(challenge_id)
    feedback = "Correct" if correct else "Incorrect"
    # Build the response against the updated solved set without exposing why a
    # proof did or did not match any private event.
    cards = research_cards(request, challenge_id, feedback, submitted, solved, active_id=challenge_id)
    response = render(
        "research.html",
        challenges=cards,
        solved_count=sum(1 for card in cards if card["solved"]),
    )
    response.set_cookie(RESEARCH_STARTED_COOKIE, str(started), path="/", samesite="lax", httponly=True)
    response.set_cookie(RESEARCH_SOLVED_COOKIE, quote(json.dumps(sorted(solved))), path="/", samesite="lax", httponly=True)
    response.delete_cookie("flagship_learn", path="/")
    return response

@app.get("/healthz")
async def healthz(): return {"status": "ok"}