#!/usr/bin/env python3
"""Add compact validation closure records to the frozen candidate ledger."""

from __future__ import annotations

import json
import os
from pathlib import Path


LEDGER = Path(
    "/private/var/folders/kx/8xhl68dn107bzv0r4bc6l7dr0000gn/T/"
    "codex-security-scans-QM6XF1/ai_api/"
    "a782c32b3a1c823e4f803ca07137187fbd2d32cb_20260729T024025Z_zco_cdqv/"
    "artifacts/02_discovery/candidate_ledger.jsonl"
)

DEFERRED = {
    "zhaiker-concurrent-duplicate-import",
    "unknown-host-default-tenant",
    "unknown-platform-client-gate-bypass",
}

MEDIUM_CONFIDENCE = {
    "healthkit-oauth-state-unbound",
    "anonymous-image-upload",
    *DEFERRED,
}

PROOF_GAPS = {
    "baidu-face-empty-allowlist": "Production ingress and the deployed allowlist value were not inspected; a populated allowlist would reduce practical reachability.",
    "zhaiker-forged-exam-callback": "Production ingress and any upstream callback authentication were not inspected.",
    "tracked-environment-and-sql-credentials": "Credential values were deliberately not reproduced or tested, so current validity and privilege are unknown.",
    "bank-bind-user-login-token-mint": "An upstream bank gateway or reverse proxy could authenticate the path, but no such control appears in the repository.",
    "bank-user-id-account-switch": "Bank-user identifier entropy and any upstream caller authentication are unknown.",
    "terminal-face-sync-without-device-auth": "Device-code entropy, network placement, and external gateway controls are unknown.",
    "terminal-role-authorization-disabled": "No external per-route authorization layer is represented; if one exists it could narrow the path.",
    "healthkit-token-logging": "Logger destination, access controls, retention, and token scope are deployment facts not available in the repository.",
    "healthkit-oauth-state-unbound": "A live OAuth/browser reproduction was not run; redirect-code constraints can reduce replay but do not replace state binding.",
    "prepay-concurrent-orphan-orders": "Unrepresented database triggers or constraints could alter the concurrent outcome.",
    "refund-order-goods-horizontal-bypass": "Final payment reversal requires merchant approval; live database reproduction was not attempted.",
    "anonymous-image-upload": "External WAF, rate limits, storage ACLs, and product intent for anonymous uploads are unknown.",
    "zhaiker-concurrent-duplicate-import": "Requires deployed SHOW CREATE TABLE evidence and a concurrent integration test to rule out a unique constraint.",
    "unknown-host-default-tenant": "Requires an authorized runtime request using an unmapped Host or direct IP to prove ingress acceptance.",
    "unknown-platform-client-gate-bypass": "Requires product confirmation that the enable flag is intended as a security or incident-shutdown boundary for all clients.",
}

CONFIDENCE_RATIONALE = {
    "tracked-environment-and-sql-credentials": "Tracked files directly contain non-placeholder credential assignments, but the values were not tested for validity.",
    "healthkit-oauth-state-unbound": "The missing server-side state lifecycle is source-proven; practical login-CSRF delivery remains untested.",
    "anonymous-image-upload": "The default unauthenticated storage path is source-proven, while deployment quotas and intended product behavior are unknown.",
    "zhaiker-concurrent-duplicate-import": "The check-then-insert race is visible in source, but deployed uniqueness constraints are unknown.",
    "unknown-host-default-tenant": "The fallback is source-proven, while alternate-host ingress reachability is unknown.",
    "unknown-platform-client-gate-bypass": "The fail-open branch is source-proven, while the security intent of the client switch is not.",
}


def main() -> None:
    rows = [
        json.loads(line)
        for line in LEDGER.read_text(encoding="utf-8").splitlines()
        if line.strip()
    ]
    for row in rows:
        instance = row["instance"]
        disposition = "deferred" if instance in DEFERRED else "reportable"
        confidence = "medium" if instance in MEDIUM_CONFIDENCE else "high"
        row["validation"] = {
            "disposition": disposition,
            "method": "large internal repository static source-control-sink trace",
            "confidence": confidence,
            "confidence_rationale": CONFIDENCE_RATIONALE.get(
                instance,
                "Direct repository evidence establishes the attacker input, missing or broken control, and security-relevant sink.",
            ),
            "rubric": [
                "Attacker-controlled input or lower-trust boundary identified.",
                "Closest authentication, authorization, authenticity, or safety control inspected.",
                "Security-relevant sink or durable state transition traced.",
                "Repository counterevidence and deployment assumptions checked.",
                "Impact and remaining proof gap stated without claiming a live exploit.",
            ],
            "evidence": [
                row["summary"],
                row["evidence"],
            ],
            "counterevidence_or_proof_gap": PROOF_GAPS[instance],
            "remaining_uncertainty": PROOF_GAPS[instance],
        }

    tmp = LEDGER.with_suffix(".jsonl.tmp")
    with tmp.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
    os.replace(tmp, LEDGER)


if __name__ == "__main__":
    main()
