from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
import time
import zipfile
from pathlib import Path


SOURCE_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(SOURCE_ROOT / "src"))

from reliability_core.process_control import run_supervised_process


def archive_source_hash(archive: zipfile.ZipFile) -> str:
    suffixes={".pyc",".pyo",".db",".sqlite",".sqlite3"}
    rows={name[7:]:hashlib.sha256(archive.read(name)).hexdigest() for name in archive.namelist() if name.startswith("source/") and not name.endswith("/") and Path(name).suffix.lower() not in suffixes}
    payload="".join(f"{digest}  {name}\n" for name,digest in sorted(rows.items()))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def r5_archive_checks(archive: zipfile.ZipFile) -> dict[str, object]:
    required=["prepatch_evidence/integration_evidence_manifest.json","prepatch_evidence/integration_evidence_manifest.sha256.json","postpatch_evidence/raw_runs.jsonl","postpatch_evidence/raw_runs.sha256.json","postpatch_evidence/source_binding.json","rollback/rollback_proof.json"]
    names=set(archive.namelist()); checks={"required_files_present":all(name in names for name in required)}
    if not checks["required_files_present"]:
        return {"passed":False,"checks":checks}
    pre_manifest=json.loads(archive.read(required[0])); pre_side=json.loads(archive.read(required[1])); post_raw=archive.read(required[2]); post_side=json.loads(archive.read(required[3])); post_binding=json.loads(archive.read(required[4])); rollback=json.loads(archive.read(required[5])); source_hash=archive_source_hash(archive)
    checks.update({
        "pre_digest":pre_side.get("sha256")==hashlib.sha256(archive.read(required[0])).hexdigest(),
        "pre_size":pre_side.get("size")==len(archive.read(required[0])),
        "pre_count":pre_side.get("file_count")==pre_manifest.get("file_count") and int(pre_manifest.get("file_count",0))>0,
        "post_digest":post_side.get("sha256")==hashlib.sha256(post_raw).hexdigest() and post_binding.get("sha256")==hashlib.sha256(post_raw).hexdigest(),
        "post_size":post_side.get("size")==len(post_raw) and post_binding.get("size")==len(post_raw),
        "post_rows":post_side.get("row_count")==len(post_raw.decode("utf-8").splitlines()) and post_binding.get("row_count")==post_side.get("row_count"),
        "paths_separate":pre_side.get("path")!=post_side.get("path"),
        "sources_separate":pre_side.get("source_tree_sha256")!=post_side.get("source_tree_sha256"),
        "packaged_source_bound":post_side.get("source_tree_sha256")==source_hash and post_binding.get("source_tree_sha256")==source_hash,
        "rollback_full_tests":"--tests-only" in list(rollback.get("restore_full_test_command") or []) and int(rollback.get("restored_test_count",0))>=143 and int(rollback.get("restored_failures",-1))==0 and int(rollback.get("restored_errors",-1))==0 and int(rollback.get("restored_exit_code",-1))==0 and rollback.get("restore_timed_out") is False and int(rollback.get("restore_orphan_process_count",-1))==0 and rollback.get("original_source_unchanged") is True,
    })
    linux_commands=sorted(name for name in names if name.startswith("postpatch_evidence/platform/linux/") and name.endswith("_command.json"))
    linux=None
    if linux_commands:
        linux_records=[(name,json.loads(archive.read(name))) for name in linux_commands]
        linux_name,linux=max(linux_records,key=lambda item:float(item[1].get("ended_epoch",0.0))); platform_name=linux.get("platform") or (linux.get("container_platform") or {}).get("platform")
        checks["actual_linux_tests"]=int(linux.get("exit_code",-1))==0 and str(linux.get("source_tree_sha256"))==source_hash and str(platform_name).lower().startswith("linux")
    else:
        checks["actual_linux_tests"]=False
    return {"passed":all(checks.values()),"checks":checks,"packaged_source_tree_sha256":source_hash,"linux_command_ref":linux_name if linux_commands else None}


def r6_archive_checks(archive: zipfile.ZipFile) -> dict[str, object]:
    names=set(archive.namelist()); source_hash=archive_source_hash(archive); checks:dict[str,bool]={}
    binding_name="postpatch_evidence/raw_runs.sha256.json"; raw_name="postpatch_evidence/raw_runs.jsonl"
    if binding_name in names and raw_name in names:
        binding=json.loads(archive.read(binding_name)); raw=archive.read(raw_name); producer=" ".join(map(str,binding.get("producer_command") or [])); verifier=" ".join(map(str,binding.get("verification_command") or [])); created=float(binding.get("raw_created_epoch",-1))
        checks["producer_binding"]=all([binding.get("sha256")==hashlib.sha256(raw).hexdigest(),binding.get("size")==len(raw),binding.get("row_count")==len(raw.decode("utf-8").splitlines()),binding.get("source_tree_sha256")==source_hash,binding.get("producer_source_tree_sha256")==source_hash,any(flag in producer for flag in ("--evidence-build","--raw-run-build")),"--tests-only" in verifier,producer!=verifier,float(binding.get("producer_started_epoch",0))<=created<=float(binding.get("producer_ended_epoch",-1)),binding.get("producer_exit_code")==0])
    else: checks["producer_binding"]=False
    linux_root="postpatch_evidence/platform/linux/"; command_names=sorted(name for name in names if name.startswith(linux_root) and name.endswith("_command.json")); versions={"3.11":False,"3.12":False,"3.13":False}
    for name in command_names:
        row=json.loads(archive.read(name)); stdout_name=linux_root+str(row.get("stdout_file","")); stderr_name=linux_root+str(row.get("stderr_file","")); side_name=name+".sha256.json"; stdout=archive.read(stdout_name).decode("utf-8",errors="replace") if stdout_name in names else ""; stderr=archive.read(stderr_name).decode("utf-8",errors="replace") if stderr_name in names else ""; text=stdout+"\n"+stderr; ran=re.findall(r"Ran\s+(\d+)\s+tests?",text); version=str(row.get("python_version") or row.get("python") or ""); side=json.loads(archive.read(side_name)) if side_name in names else {}; valid=all(["run_all.py" in " ".join(map(str,row.get("command",[]))) and "--tests-only" in " ".join(map(str,row.get("command",[]))),row.get("exit_code")==0,row.get("timed_out") is False,int(row.get("orphan_process_count",-1))==0,int(row.get("zombie_process_count",-1))==0,stdout_name in names,stderr_name in names,row.get("stdout_sha256")==hashlib.sha256(archive.read(stdout_name)).hexdigest() if stdout_name in names else False,row.get("stderr_sha256")==hashlib.sha256(archive.read(stderr_name)).hexdigest() if stderr_name in names else False,side.get("sha256")==hashlib.sha256(archive.read(name)).hexdigest(),bool(ran) and int(ran[-1])==int(row.get("test_count",-1)),re.search(r"(?m)^OK(?:\s|$)",text) is not None and "FAILED" not in text,row.get("source_tree_sha256")==source_hash,row.get("resource_warning_error_mode") is True])
        for expected in versions:
            if version.startswith(expected) and valid: versions[expected]=True
    checks["python_311_313_transcripts"]=all(versions.values())
    classification_name="integration_provenance/r6_semantic_classification.json"
    if classification_name in names:
        payload=json.loads(archive.read(classification_name)); rows=list(payload.get("classification") or []); raw_ids={json.loads(line)["test_id"] for line in archive.read(raw_name).decode("utf-8").splitlines()}; signatures={}; valid_rows=True
        for row in rows:
            signature=json.dumps([row.get("origin"),row.get("purpose"),row.get("tests")],sort_keys=True); signatures[signature]=signatures.get(signature,0)+1; source_name="source/"+str(row.get("path","")); source_text=archive.read(source_name).decode("utf-8") if source_name in names else ""; valid_rows=valid_rows and source_name in names and str(row.get("symbol","")) in source_text and set(row.get("tests") or []).issubset(raw_ids) and row.get("after_sha256")==hashlib.sha256(archive.read(source_name)).hexdigest() and not ("r5" in str(row.get("path","")).lower() and "r4" in str(row.get("origin","")).lower())
        checks["semantic_classification"]=bool(rows) and valid_rows and not any(count>=4 for count in signatures.values()) and payload.get("validation",{}).get("passed") is True
    else: checks["semantic_classification"]=False
    verdict=json.loads(archive.read("summary/verdict.json")); r6_gates={key:value for key,value in verdict.get("gates",{}).items() if key.startswith("R6-G")}; checks["r6_gates"]=len(r6_gates)==16 and all(r6_gates.values())
    return {"passed":all(checks.values()),"checks":checks,"python_versions":versions,"packaged_source_tree_sha256":source_hash}


def r7_archive_checks(archive: zipfile.ZipFile) -> dict[str, object]:
    names=set(archive.namelist()); source_hash=archive_source_hash(archive); checks:dict[str,bool]={}
    required={
        "source/src/reliability_core/process_control.py",
        "source/src/reliability_core/regressions_r7.py",
        "source/tests/test_r7_rg.py",
        "source/tests/fixtures/process_hazards.py",
        "prepatch_evidence/r7/prepatch_probe_result.json",
        "prepatch_evidence/r7/prepatch_probe_command.json",
        "postpatch_evidence/r7/r7_raw_results.jsonl",
        "postpatch_evidence/r7/r7_raw_results.sha256.json",
        "postpatch_evidence/r7/package_full_suite_command.json",
        "postpatch_evidence/r7/package_full_suite.stdout.txt",
        "postpatch_evidence/r7/package_full_suite.stderr.txt",
        "reports/r7_postpatch_results.json",
        "engine_inheritance/engine_inheritance.json",
    }
    checks["required_files_present"]=required.issubset(names)
    if not checks["required_files_present"]:
        return {"passed":False,"checks":checks,"packaged_source_tree_sha256":source_hash}
    raw_bytes=archive.read("postpatch_evidence/r7/r7_raw_results.jsonl"); binding=json.loads(archive.read("postpatch_evidence/r7/r7_raw_results.sha256.json")); rows=[json.loads(line) for line in raw_bytes.decode("utf-8").splitlines() if line]; inheritance=json.loads(archive.read("engine_inheritance/engine_inheritance.json"))
    ids={str(row.get("test_id")) for row in rows}; report=json.loads(archive.read("reports/r7_postpatch_results.json")); verdict=json.loads(archive.read("summary/verdict.json")); gates={key:value for key,value in verdict.get("gates",{}).items() if key.startswith("R7-G")}
    package=json.loads(archive.read("postpatch_evidence/r7/package_full_suite_command.json")); package_stdout=archive.read("postpatch_evidence/r7/package_full_suite.stdout.txt"); package_stderr=archive.read("postpatch_evidence/r7/package_full_suite.stderr.txt"); transcript=(package_stdout+b"\n"+package_stderr).decode("utf-8",errors="replace"); counts=re.findall(r"Ran\s+(\d+)\s+tests?",transcript)
    checks.update({
        "raw_digest":binding.get("sha256")==hashlib.sha256(raw_bytes).hexdigest() and binding.get("size")==len(raw_bytes) and binding.get("row_count")==len(rows),
        "raw_ids":ids=={f"R7-RG-{number:02d}" for number in range(1,38)} and all(row.get("passed") is True for row in rows),
        "report_dynamic":report.get("row_count")==len(rows)==37 and report.get("pass_count")==sum(row.get("passed") is True for row in rows),
        "r7_gates":len(gates)==16 and all(gates.values()),
        "package_full_suite":package.get("exit_code")==0 and package.get("timed_out") is False and int(package.get("orphan_process_count",-1))==0 and int(package.get("zombie_process_count",-1))==0 and bool(counts) and int(counts[-1])==int(package.get("test_count",-1)) and int(counts[-1])>=197,
        "package_output_hashes":package.get("stdout_sha256")==hashlib.sha256(package_stdout).hexdigest() and package.get("stderr_sha256")==hashlib.sha256(package_stderr).hexdigest(),
        "package_source_binding":package.get("source_tree_sha256")==source_hash,
        "source_is_fresh":source_hash!="d22ef241c7b26e95e73435a0cd8ae0dde0377adeb16494671e6c5ca6668a3294",
        "mandatory_anchors":all(bool(inheritance.get(key)) for key in ("root_goal_anchor","current_work_anchor","capacity_cleanup_anchor","next_handoff_anchor","mandatory_inheritance_contract","tokenmax_runtime_inheritance")),
    })
    return {"passed":all(checks.values()),"checks":checks,"packaged_source_tree_sha256":source_hash,"r7_test_count":len(rows),"r7_gate_count":len(gates)}


def r8_archive_checks(archive: zipfile.ZipFile) -> dict[str, object]:
    names=set(archive.namelist()); source_hash=archive_source_hash(archive); checks:dict[str,bool]={}
    required={"source/src/reliability_core/portable_r8.py","source/src/reliability_core/regressions_r8.py","source/tests/test_r8_rg.py","source/scripts/r8_portable_runner.py","postpatch_evidence/r8/r8_raw_results.jsonl","postpatch_evidence/r8/r8_raw_results.sha256.json","postpatch_evidence/r8/candidate_target_command.json","postpatch_evidence/r8/candidate_target.stdout.txt","postpatch_evidence/r8/candidate_target.stderr.txt","prepatch_evidence/r8/manifest.json","reports/r8_portable_runs.json","reports/r8_postpatch_results.json"}
    checks["required_files_present"]=required.issubset(names)
    if not checks["required_files_present"]: return {"passed":False,"checks":checks,"packaged_source_tree_sha256":source_hash}
    raw=archive.read("postpatch_evidence/r8/r8_raw_results.jsonl"); binding=json.loads(archive.read("postpatch_evidence/r8/r8_raw_results.sha256.json")); rows=[json.loads(line) for line in raw.decode("utf-8").splitlines() if line]
    verdict=json.loads(archive.read("summary/verdict.json")); gates={key:value for key,value in verdict.get("gates",{}).items() if key.startswith("R8-G")}; report=json.loads(archive.read("reports/r8_postpatch_results.json")); portable=json.loads(archive.read("reports/r8_portable_runs.json")); prepatch=json.loads(archive.read("prepatch_evidence/r8/manifest.json")); candidate=json.loads(archive.read("postpatch_evidence/r8/candidate_target_command.json")); candidate_stdout=archive.read("postpatch_evidence/r8/candidate_target.stdout.txt"); candidate_stderr=archive.read("postpatch_evidence/r8/candidate_target.stderr.txt")
    checks.update({
        "raw_digest":binding.get("sha256")==hashlib.sha256(raw).hexdigest() and binding.get("size")==len(raw) and binding.get("row_count")==len(rows)==40,
        "raw_behavior":{row.get("test_id") for row in rows}=={f"R8-RG-{number:02d}" for number in range(1,41)} and all(row.get("passed") is True for row in rows),
        "report_dynamic":report.get("row_count")==len(rows) and report.get("pass_count")==sum(row.get("passed") is True for row in rows),
        "r8_gates":len(gates)==20 and all(gates.values()),
        "prepatch_failure_included":prepatch.get("actual_failure_present") is True and int(prepatch.get("file_count",0))>0,
        "portable_repeats":portable.get("passed") is True and portable.get("candidate_source_tree_sha256")==source_hash and portable.get("final_source_tree_sha256")==source_hash,
        "candidate_target":candidate.get("exit_code")==0 and candidate.get("timed_out") is False and int(candidate.get("orphan_process_count",-1))==0 and int(candidate.get("zombie_process_count",-1))==0 and int(candidate.get("test_count",0))>=81 and candidate.get("source_tree_sha256")==source_hash,
        "candidate_output_hashes":candidate.get("stdout_sha256")==hashlib.sha256(candidate_stdout).hexdigest() and candidate.get("stderr_sha256")==hashlib.sha256(candidate_stderr).hexdigest(),
    })
    return {"passed":all(checks.values()),"checks":checks,"packaged_source_tree_sha256":source_hash,"r8_test_count":len(rows),"r8_gate_count":len(gates),"candidate_source_tree_sha256":portable.get("candidate_source_tree_sha256"),"final_source_tree_sha256":source_hash}


def r9_archive_checks(archive: zipfile.ZipFile) -> dict[str, object]:
    names=set(archive.namelist()); source_hash=archive_source_hash(archive); checks:dict[str,bool]={}
    required={"source/test_execution_manifest.json","source/src/reliability_core/suite_isolation.py","source/src/reliability_core/regressions_r9.py","source/tests/test_r9_rg.py","prepatch_evidence/r9/prepatch_load_reproduction.json","postpatch_evidence/r9/r9_raw_results.jsonl","postpatch_evidence/r9/r9_raw_results.sha256.json","reports/r9_order_load_matrix.json","reports/r9_postpatch_results.json","postpatch_evidence/r9/candidate_package_matrix.json"}
    checks["required_files_present"]=required.issubset(names)
    if not checks["required_files_present"]:
        return {"passed":False,"checks":checks,"packaged_source_tree_sha256":source_hash}
    raw=archive.read("postpatch_evidence/r9/r9_raw_results.jsonl"); binding=json.loads(archive.read("postpatch_evidence/r9/r9_raw_results.sha256.json")); rows=[json.loads(line) for line in raw.decode("utf-8").splitlines() if line]
    report=json.loads(archive.read("reports/r9_postpatch_results.json")); matrix=json.loads(archive.read("reports/r9_order_load_matrix.json")); candidate_matrix=json.loads(archive.read("postpatch_evidence/r9/candidate_package_matrix.json")); prepatch=json.loads(archive.read("prepatch_evidence/r9/prepatch_load_reproduction.json")); verdict=json.loads(archive.read("summary/verdict.json")); gates={key:value for key,value in verdict.get("gates",{}).items() if key.startswith("R9-G")}
    checks.update({
        "raw_digest":binding.get("sha256")==hashlib.sha256(raw).hexdigest() and binding.get("size")==len(raw) and binding.get("row_count")==len(rows)==40,
        "raw_behavior":{row.get("test_id") for row in rows}=={f"R9-RG-{number:02d}" for number in range(1,41)} and all(row.get("passed") is True for row in rows),
        "report_dynamic":report.get("row_count")==len(rows) and report.get("pass_count")==sum(row.get("passed") is True for row in rows),
        "prepatch_difference":prepatch.get("individual_pass") is True and prepatch.get("full_suite_fail") is True and prepatch.get("reproduced") is True,
        "order_load_matrix":matrix.get("passed") is True and int(matrix.get("record_count",0))>0 and matrix.get("source_tree_sha256")==source_hash,
        "candidate_package_matrix":candidate_matrix.get("passed") is True and candidate_matrix.get("source_tree_sha256")==source_hash,
        "r9_gates":len(gates)==20 and all(gates.values()),
    })
    return {"passed":all(checks.values()),"checks":checks,"packaged_source_tree_sha256":source_hash,"r9_test_count":len(rows),"r9_gate_count":len(gates),"r9_order_load_matrix_passed":checks["order_load_matrix"],"r9_policy_coverage_passed":checks["raw_behavior"],"r9_candidate_package_matrix_passed":checks["candidate_package_matrix"]}


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("zip_path", type=Path)
    parser.add_argument("sidecar_path", type=Path)
    args = parser.parse_args()
    sidecar = json.loads(args.sidecar_path.read_text(encoding="utf-8"))
    actual_hash = hashlib.sha256(args.zip_path.read_bytes()).hexdigest()
    checksum_mismatches = json_failures = utf8_failures = 0
    with zipfile.ZipFile(args.zip_path) as archive:
        bad = archive.testzip()
        names = archive.namelist()
        for line in archive.read("checksums/files.sha256").decode("utf-8").splitlines():
            expected, name = line.split("  ", 1)
            checksum_mismatches += int(hashlib.sha256(archive.read(name)).hexdigest() != expected)
        for name in names:
            if name.endswith((".json", ".jsonl", ".md", ".txt", ".py", ".toml", ".ps1")):
                try: text = archive.read(name).decode("utf-8")
                except UnicodeDecodeError: utf8_failures += 1; continue
                if name.endswith(".json"):
                    try: json.loads(text)
                    except Exception: json_failures += 1
        raw = archive.read("tests/raw_runs.jsonl").decode("utf-8")
        raw_hash = hashlib.sha256(raw.encode("utf-8")).hexdigest()
        declared_raw_hash = json.loads(archive.read("tests/raw_runs.sha256.json"))["sha256"]
        verdict = json.loads(archive.read("summary/verdict.json"))["overall_verdict"]
        r5_checks = r5_archive_checks(archive)
        r6_checks = r6_archive_checks(archive)
        r7_checks = r7_archive_checks(archive)
        r8_checks = r8_archive_checks(archive)
        r9_checks = r9_archive_checks(archive)
        with tempfile.TemporaryDirectory(prefix="wrlab-functional-selfcheck-") as directory:
            root = Path(directory) / "source"
            for name in names:
                if not name.startswith("source/") or name.endswith("/"): continue
                relative = Path(name).relative_to("source")
                if ".." in relative.parts: raise ValueError("unsafe source member")
                target=root/relative; target.parent.mkdir(parents=True,exist_ok=True); target.write_bytes(archive.read(name))
            extracted_source_hash=archive_source_hash(archive)
            functional=run_supervised_process([sys.executable,"run_all.py","--functional-smoke"],root,environment={**os.environ,"PYTHONDONTWRITEBYTECODE":"1"},total_timeout_seconds=45,max_output_bytes=1024*1024)
            independent_targets=["tests.test_r5_rg.R5RegressionTests.test_r5_rg_03","tests.test_r5_rg.R5RegressionTests.test_r5_rg_04","tests.test_r4_rg.R4RegressionTests.test_r4_rg_05","tests.test_r6_rg.R6RegressionTests.test_r6_rg_01","tests.test_r7_rg","tests.test_r8_rg","tests.test_r9_rg"]
            target_matrix=run_supervised_process([sys.executable,"-m","unittest","-v",*independent_targets],root,environment={**os.environ,"PYTHONDONTWRITEBYTECODE":"1"},total_timeout_seconds=600,max_output_bytes=8*1024*1024)
            matrix_output=Path(directory)/"r9-final-matrix"; matrix_output.mkdir()
            matrix_specs=[("default",None),("reverse",None),("random",909),("sensitive-first",None),("sensitive-last",None)]; final_matrix_rows=[]; matrix_processes=[]
            for ordinal,(order,seed) in enumerate(matrix_specs,1):
                run_id=f"final-{order.replace('-','')}-{ordinal:02d}"; command=[sys.executable,"scripts/r9_matrix_runner.py","--output-dir",str(matrix_output),"--run-id",run_id,"--run-ordinal",str(ordinal),"--source-origin","final","--order",order,"--load-profile","normal","--timeout-seconds","1200"]
                if seed is not None: command.extend(["--seed",str(seed)])
                process=run_supervised_process(command,root,environment={**os.environ,"PYTHONDONTWRITEBYTECODE":"1","EVIDENCE_NESTING_LEVEL":"1"},total_timeout_seconds=1260,max_output_bytes=1024*1024); matrix_processes.append({"order_name":order,"exit_code":process["exit_code"],"timed_out":process["timed_out"],"orphan_process_count":process["orphan_process_count"],"zombie_process_count":process["zombie_process_count"],"stdout_sha256":hashlib.sha256(process["stdout"].encode("utf-8")).hexdigest(),"stderr_sha256":hashlib.sha256(process["stderr"].encode("utf-8")).hexdigest()})
                record_path=matrix_output/f"{run_id}.json"
                if record_path.is_file(): final_matrix_rows.append(json.loads(record_path.read_text(encoding="utf-8")))
            default_record=next((row for row in final_matrix_rows if row.get("order_name")=="default"),{})
            default_stdout=matrix_output/str(default_record.get("stdout_file","")); default_stderr=matrix_output/str(default_record.get("stderr_file",""))
            full_suite={"exit_code":default_record.get("exit_code",-1),"timed_out":default_record.get("timed_out",True),"orphan_process_count":default_record.get("orphan_process_count",-1),"zombie_process_count":default_record.get("zombie_process_count",-1),"elapsed_ms":float(default_record.get("elapsed_seconds",0))*1000,"stdout":default_stdout.read_text(encoding="utf-8",errors="replace") if default_stdout.is_file() else "","stderr":default_stderr.read_text(encoding="utf-8",errors="replace") if default_stderr.is_file() else ""}
            full_text=full_suite["stdout"]+"\n"+full_suite["stderr"]; full_counts=re.findall(r"Ran\s+(\d+)\s+tests?",full_text); full_test_count=int(full_counts[-1]) if full_counts else 0
            r9_final_package_matrix_passed=len(final_matrix_rows)==5 and all(row.get("passed") is True and row.get("source_origin")=="final" and row.get("source_tree_sha256")==extracted_source_hash and row.get("test_count")==full_test_count for row in final_matrix_rows) and all(row["exit_code"]==0 and row["timed_out"] is False and row["orphan_process_count"]==0 and row["zombie_process_count"]==0 for row in matrix_processes)
    result = {
        "hash_match": actual_hash == sidecar["sha256"], "size_match": args.zip_path.stat().st_size == sidecar["size"],
        "zip_bad_file": bad, "entry_count": len(names), "checksum_mismatches": checksum_mismatches,
        "json_failures": json_failures, "utf8_failures": utf8_failures, "raw_digest_match": raw_hash == declared_raw_hash,
        "verdict": verdict,
        "functional_rerun_passed": functional["exit_code"] == 0 and not functional["timed_out"],
        "functional_rerun_exit_code": functional["exit_code"],
        "functional_rerun_timed_out": functional["timed_out"],
        "functional_rerun_elapsed_ms": functional["elapsed_ms"],
        "functional_rerun_orphan_process_count": functional["orphan_process_count"],
        "functional_rerun_zombie_process_count": functional["zombie_process_count"],
        "independent_target_matrix_passed":target_matrix["exit_code"]==0 and not target_matrix["timed_out"] and target_matrix["orphan_process_count"]==0 and target_matrix["zombie_process_count"]==0,
        "independent_target_matrix_exit_code":target_matrix["exit_code"],"independent_target_matrix_timed_out":target_matrix["timed_out"],"independent_target_matrix_orphan_process_count":target_matrix["orphan_process_count"],"independent_target_matrix_zombie_process_count":target_matrix["zombie_process_count"],"independent_target_matrix_stdout_sha256":hashlib.sha256(target_matrix["stdout"].encode("utf-8")).hexdigest(),"independent_target_matrix_stderr_sha256":hashlib.sha256(target_matrix["stderr"].encode("utf-8")).hexdigest(),
        "independent_full_suite_passed": full_suite["exit_code"] == 0 and not full_suite["timed_out"] and full_suite["orphan_process_count"] == 0 and full_suite["zombie_process_count"] == 0 and full_test_count >= 314,
        "full_suite_rerun_passed": full_suite["exit_code"] == 0 and not full_suite["timed_out"] and full_suite["orphan_process_count"] == 0 and full_suite["zombie_process_count"] == 0 and full_test_count >= 314,
        "full_suite_rerun_exit_code": full_suite["exit_code"],
        "full_suite_rerun_timed_out": full_suite["timed_out"],
        "full_suite_rerun_test_count": full_test_count,
        "full_suite_rerun_orphan_process_count": full_suite["orphan_process_count"],
        "full_suite_rerun_zombie_process_count": full_suite["zombie_process_count"],
        "full_suite_rerun_source_tree_sha256": extracted_source_hash,
        "full_suite_rerun_command": [sys.executable,"run_all.py","--tests-only"],
        "full_suite_rerun_stdout_sha256": hashlib.sha256(full_suite["stdout"].encode("utf-8")).hexdigest(),
        "full_suite_rerun_stderr_sha256": hashlib.sha256(full_suite["stderr"].encode("utf-8")).hexdigest(),
        "full_suite_rerun_elapsed_ms": full_suite["elapsed_ms"],
        "r5_evidence_and_rollback_checks": r5_checks,
        "r6_final_correction_checks":r6_checks,
        "r7_execution_enforcement_checks":r7_checks,
        "r8_portable_reproducibility_checks":r8_checks,
        "r9_suite_isolation_checks":r9_checks,
        "r9_order_load_matrix_passed":r9_checks.get("r9_order_load_matrix_passed") is True,
        "r9_policy_coverage_passed":r9_checks.get("r9_policy_coverage_passed") is True,
        "r9_candidate_package_matrix_passed":r9_checks.get("r9_candidate_package_matrix_passed") is True,
        "r9_final_package_matrix_passed":r9_final_package_matrix_passed,
        "r9_final_package_matrix":{"record_count":len(final_matrix_rows),"orders":[row.get("order_name") for row in final_matrix_rows],"records":[{"run_id":row.get("run_id"),"order_name":row.get("order_name"),"random_seed":row.get("random_seed"),"test_count":row.get("test_count"),"exit_code":row.get("exit_code"),"timed_out":row.get("timed_out"),"orphan_process_count":row.get("orphan_process_count"),"zombie_process_count":row.get("zombie_process_count"),"source_tree_sha256":row.get("source_tree_sha256"),"stdout_sha256":row.get("stdout_sha256"),"stderr_sha256":row.get("stderr_sha256"),"passed":row.get("passed")} for row in final_matrix_rows],"controller_processes":matrix_processes},
        "candidate_source_tree_sha256":r8_checks.get("candidate_source_tree_sha256"),
        "final_source_tree_sha256":extracted_source_hash,
        "root_goal_anchor_present":r7_checks.get("checks",{}).get("mandatory_anchors") is True,
        "current_work_anchor_present":r7_checks.get("checks",{}).get("mandatory_anchors") is True,
        "capacity_cleanup_anchor_present":r7_checks.get("checks",{}).get("mandatory_anchors") is True,
        "next_handoff_anchor_present":r7_checks.get("checks",{}).get("mandatory_anchors") is True,
        "mandatory_inheritance_contract_present":r7_checks.get("checks",{}).get("mandatory_anchors") is True,
        "tokenmax_runtime_inheritance_present":r7_checks.get("checks",{}).get("mandatory_anchors") is True,
    }
    result["passed"] = all([result["hash_match"], result["size_match"], bad is None, checksum_mismatches == 0, json_failures == 0, utf8_failures == 0, result["raw_digest_match"], verdict == "PASS", result["functional_rerun_passed"], result["functional_rerun_orphan_process_count"] == 0, result["functional_rerun_zombie_process_count"] == 0, result["independent_target_matrix_passed"],result["independent_full_suite_passed"],result["full_suite_rerun_passed"],result["candidate_source_tree_sha256"]==result["final_source_tree_sha256"],result["r9_final_package_matrix_passed"],r5_checks["passed"],r6_checks["passed"],r7_checks["passed"],r8_checks["passed"],r9_checks["passed"]])
    print(json.dumps(result, sort_keys=True))
    return 0 if result["passed"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
