"""Assemble fresh model23 evidence only after every exact-runtime scope passes.
Historical model22 gameplay reports cannot supply a gate. Source/build/component
receipts remain separate from production gameplay. Never publishes or packages.
"""
import argparse
import hashlib
import json
from pathlib import Path
import re
import sys

ROOT = Path(__file__).resolve().parents[1]
NATIVE_SHA = 'c936e3d0a15245ae7464eb7688c9511b5119309c15d880cba3aa41261a2304b2'
CLIENT_SHA = '9c7e47b8d5af3f11d4deb27cdfd7503ce79ca1b222016fec805671309e7d3abb'
WORLD_SHA = 'bc09ac0a3a3eff36d99d8d6dc492fbcf40218f82361f56773112b5f173a89d9f'
CATALOG_SHA = '0ac061d64d917ad14a0d0bc141f972f159cbded87994d358dcede62dc688ed7c'
TOOLKIT = 'ac39b39f296b073553ecd4f9c486b9d14beda9eb'
AP_REVISION = '2fb9bdadd4726b404fc0d790887390b66b07df16'
EQUIPMENT_COPIES_SHA = '68418a4b81a9b9dbc6676925b14ae703106c657efdf8d1b1cdfc10ee79874a11'
UNIT_LOG_SHA = '36d6f68db67c65f3845f660b7ae49cce6fb0999983d3e73f84b7c6e6f50a74e0'
RECOVERY_UNIT_LOG_SHA = '653770a31e58580df79c1504c26c26195f6420c20d722d634834211d25b3fc7a'
FINAL_UNIT_LOG_SHA = '408af1445f4b4b765215525a92efabbd8b89c77affee9db2dea587bcc451f893'
DLLS = {
    'libgcc_s_seh-1.dll': 'b37c1770c8ca092700875845b34918803ee6311573eba1c32ff4b1166e4a0e1e',
    'libstdc++-6.dll': '887c21dbe2a211ac4d1a790e4f608b7dee27fae12352856963004e7a715d2e6c',
    'libwinpthread-1.dll': '2e74ef2965ec0d8f7e0543f40293b212d2f5c8680de147643ea6dd4b8b5cb749',
    'SDL2.dll': '47a3b27654832d9f7e5719c88078210a3dbfd6407b559c5a3c4eb8ab7d0ebdb6',
}

def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()

def checked_normal_audit(antecedent_path, card_path):
    assert sha(antecedent_path) == '0fae377c5bc8c7327956002ca407c20879e2c882c064ecc4973daa2f6d961d2f'
    assert sha(card_path) == '862ff41c75cb46387ff5a9d57cfc18a1da695648992c35d438518565b4b0113d'
    base = '2658e2cc77220f3fe516ac121035205f7b37173a0c97afab0d6adfde285f587b'
    wrapper = '4602971ac7ee5f6e4f684cfb022f8a5c22ad42103930eee238ca0e8da8013b65'
    for path in (antecedent_path, card_path):
        pin = json.loads((path.parent / 'base-driver-pin.json').read_text())
        assert pin['sha256'] == base and sha(Path(pin['source'])) == base
        assert sha(path.parent / 'executed-base-driver.py') == base
        assert sha(path.parent / 'executed-driver.py') == wrapper
    dependency_path = antecedent_path.parent / 'normal-observation-dependency.json'
    dependency = json.loads(dependency_path.read_text())
    original_normal = '392db52961c03e1a757c9e97a6d77e8bca47ad4942d5ce5dfb400b54aa995e41'
    assert dependency['format'] == 'pikmin2-normal-observation-dependency-v1'
    assert dependency['source_sha256'] == dependency['snapshot_sha256'] == original_normal
    assert dependency['unchanged'] is True
    assert sha(antecedent_path.parent / 'executed-normal-acceptance.py') == original_normal
    assert sha(Path(dependency['source'])) == original_normal
    onion = '04f1ae67273bc94b5f4d592bdeed4e5bc4110c0817aafa03715dea2d4afb76e6'
    assert sha(card_path.parent / 'executed-onion-guard.py') == onion
    assert sha(ROOT/'tools/test_normal_gameplay_onion.py') == onion
    return card_path.parent / 'final-audit.json'

def checked_public_toolkit_dependency(integration):
    path = integration / 'output/public-toolkit-dependency-check/verification.json'
    assert sha(path) == 'b790a6b55f997afb5447826d66954b694b4e4704c613e308b22e6cbe0f60f966'
    review = json.loads(path.read_text())
    assert review['status'] == 'passed-dependency-source-check'
    assert review['canonical_revision'] == 'ac39b39f296b073553ecd4f9c486b9d14beda9eb'
    assert review['public_source_commit'] == 'b38fc7522939dcee07aa7c97b7c448a4ee67a407'
    comparison = review['comparison_to_frozen_client']
    assert comparison['compiled_local_sources'] == 51
    assert comparison['all_match_canonical_sources_after_only_documented_CRLF'] is True
    assert len(comparison['crate_manifests']) == 8 and all(row['equal_after_only_CRLF'] is True for row in comparison['crate_manifests'])
    asset = next(row for row in review['downloads'] if row['name'] == 'Peliarch-Toolkit-2026-10-15.zip')
    assert asset['bytes'] == 419111 and asset['sha256'] == '19b685557b184e8fa99521f9dafc551187f7344a927919658a7f91a406d213a7'
    assert asset['http'] == 200 and asset['matches_publication_receipt'] is True
    return path

def checked_code_manifest(path, expected_hash, expected_files):
    assert sha(path) == expected_hash
    value = json.loads(path.read_text())
    manifest = value if isinstance(value, dict) else {entry['name']: entry['sha256'] for entry in value}
    assert len(value) == len(manifest) == expected_files
    assert set(manifest) == {source.name for source in path.parent.glob('*.py')}
    for name, expected in manifest.items():
        assert Path(name).name == name and Path(name).suffix == '.py'
        assert sha(path.parent / name) == expected, name
    return manifest

def canonical_sha(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest()

def payload_kind(value, key=''):
    key = key.lower()
    if isinstance(value, dict) and {'omitted_payload_kind', 'canonical_json_sha256'} <= value.keys() and set(value) <= {
            'omitted_payload_kind', 'canonical_json_sha256', 'record_count', 'check_count', 'receipt_count'}:
        return None
    if key in {'password', 'server_password', 'client_password', 'authorization',
               'credentials', 'credential', 'access_token', 'refresh_token', 'api_key', 'client_secret'} and value:
        return 'credential payload'
    if isinstance(value, dict):
        snapshot = value.get('snapshot', value)
        if isinstance(snapshot, dict) and 'records' in snapshot and ('identity' in snapshot or 'version' in value):
            return 'complete client journal payload'
        if {'checks', 'receipts'} <= value.keys() and {'identity', 'patch', 'save', 'version'} & value.keys():
            return 'complete native journal payload (including any embedded seed patch)'
        if {'contract', 'patch', 'catalog'} <= value.keys():
            return 'raw runtime configuration payload'
        if key in {'patch', 'raw_patch', 'patch_payload'} or ('slot_name' in value and 'caves' in value):
            return 'original seed patch payload'
        if 'location_checks' in value and {'received_items', 'client_game_state'} & value.keys():
            return 'server save payload'
    if isinstance(value, (dict, list)) and key in {
            'patch', 'raw_patch', 'patch_payload', 'raw_config', 'runtime_config',
            'server_save', 'server_save_payload', 'save_payload', 'journal_payload'}:
        return 'raw configuration/save/journal payload'
    if isinstance(value, str) and value:
        if key in {'raw_config', 'server_save_payload', 'save_payload', 'journal_payload', 'patch_payload'}:
            return 'encoded configuration/save/journal payload'
        if key == 'server_save' and len(value) > 256:
            return 'encoded server save payload'
        if value.lstrip().startswith(('{', '[')):
            try:
                decoded = json.loads(value)
            except ValueError:
                pass
            else:
                if isinstance(decoded, (dict, list)) and payload_kind(decoded, key):
                    return 'encoded ' + payload_kind(decoded, key)
    return None

def public_evidence(value, removed, pointer='', key=''):
    kind = payload_kind(value, key)
    if kind:
        removed.append({'pointer': pointer, 'reason': kind})
        summary = {'omitted_payload_kind': kind, 'canonical_json_sha256': canonical_sha(value)}
        if isinstance(value, dict):
            snapshot = value.get('snapshot', value)
            if isinstance(snapshot, dict):
                for field, label in (('records', 'record_count'), ('checks', 'check_count'), ('receipts', 'receipt_count')):
                    if isinstance(snapshot.get(field), (dict, list)):
                        summary[label] = len(snapshot[field])
        return summary
    if isinstance(value, dict):
        return {name: public_evidence(child, removed,
                pointer + '/' + str(name).replace('~', '~0').replace('/', '~1'), str(name))
                for name, child in value.items()}
    if isinstance(value, list):
        return [public_evidence(child, removed, pointer + '/' + str(i)) for i, child in enumerate(value)]
    return value

def status_assertions(value, skipped, pointer=''):
    if pointer in skipped:
        return {}
    result = {}
    if isinstance(value, dict):
        for name, child in value.items():
            path = pointer + '/' + str(name).replace('~', '~0').replace('/', '~1')
            if name in {'status', 'passed', 'server_status'} and path not in skipped:
                result[path] = child
            result.update(status_assertions(child, skipped, path))
    elif isinstance(value, list):
        for i, child in enumerate(value):
            result.update(status_assertions(child, skipped, pointer + '/' + str(i)))
    return result

def assert_no_payloads(value, pointer='', key=''):
    assert payload_kind(value, key) is None, f'raw payload remains at {pointer}'
    if isinstance(value, dict):
        for name, child in value.items():
            assert_no_payloads(child, pointer + '/' + str(name), str(name))
    elif isinstance(value, list):
        for i, child in enumerate(value):
            assert_no_payloads(child, pointer + '/' + str(i))

def assert_no_credential_text(text, source):
    assert not re.search(r'-----BEGIN (?:RSA |OPENSSH |EC )?PRIVATE KEY-----|(?:ghp_|github_pat_|glpat-)[A-Za-z0-9_\-]{16,}', text), f'credential pattern in {source}'

def write_public_evidence(reports, destination):
    assert not destination.exists(), 'choose a new immutable public-evidence directory'
    assert 'public-evidence-provenance.json' not in reports
    destination.mkdir(parents=True)
    result = {}; provenance = {}
    for name, source in reports.items():
        original_hash = sha(source); target = destination / name; removed = []
        if Path(name).suffix == '.json':
            original = json.loads(source.read_text())
            derived = public_evidence(original, removed)
            assert_no_payloads(derived)
            skipped = {entry['pointer'] for entry in removed}
            assert status_assertions(original, skipped) == status_assertions(derived, skipped)
            text = json.dumps(derived, indent=2) + '\n'
            assert_no_credential_text(text, source)
            target.write_text(text)
        else:
            data = source.read_bytes(); text = data.decode('utf-8-sig')
            assert '\0' not in text, f'binary evidence requires content review: {source}'
            assert_no_credential_text(text, source)
            target.write_bytes(data)
        assert sha(source) == original_hash, f'original evidence changed during derivation: {source}'
        result[name] = target
        provenance[name] = {'original_path': str(source.resolve()), 'original_sha256': original_hash,
            'public_path': str(target.resolve()), 'public_sha256': sha(target),
            'removed_json_pointers': removed, 'status_assertions_unchanged': True}
    mapping = destination / 'public-evidence-provenance.json'
    assembly_name = 'assembly-and-public-evidence-code.txt'
    derivation_code = ({'evidence_name': assembly_name,
                        'sha256': provenance[assembly_name]['public_sha256']}
                       if assembly_name in provenance else None)
    mapping_text = json.dumps({'format': 'pikmin2-derived-public-evidence-v1',
        'boundary': 'Public derivatives omit raw seed/configuration/save/journal/credential payloads. Original file hashes and source-report references identify private originals, not these derivative bytes. Gameplay/status assertions outside omitted payloads are unchanged; fixture observations and input paths/hashes remain. This provenance map excludes its own hash; the package manifest binds it.',
        'derivation_code': derivation_code, 'files': provenance}, indent=2) + '\n'
    assert_no_credential_text(mapping_text, mapping)
    mapping.write_text(mapping_text)
    result[mapping.name] = mapping
    return result


def checked_case(path):
    report = json.loads(path.read_text())
    assert report['status'] == 'passed' and not report.get('failure'), path
    assert report['native_sha256'] == NATIVE_SHA, 'historical/different native cannot supply model23 gates'
    assert report['client_sha256'] == CLIENT_SHA and report['native_runtime_sha256'] == DLLS, path
    assert report['apworld_sha256'] == WORLD_SHA and report['catalog_sha256'] == CATALOG_SHA, path
    assert report['toolkit_revision'] == TOOLKIT and report['ap_revision'] == AP_REVISION, path
    unchanged = report['execution_inputs_unchanged']
    assert unchanged and all(value is True for value in unchanged.values()), path
    assert sha(path.parent / 'executed-driver.py') == report['driver_sha256'], path
    return report


def checked_equipment(path, seal_path):
    report = checked_case(path)
    assert sha(path) == '768e70cda624265ad593a0b81eb0ffe3d066378fefc37513779cfef2c1650cfe'
    subgate = report['subgates']['equipment_consumers']
    assert subgate['passed'] is True and set(subgate['consumer_item_ids']) == set(range(501,511)) | {513}
    seal = json.loads(seal_path.read_text())
    assert sha(seal_path) == 'fbcc1b82888d4d6dd52844ea858a840cfa0dede6181c10f062239bc2812e799f'
    assert seal['status'] == 'passed' and seal['gate_source_report_sha256'] == sha(path)
    assert len(seal['segments']) == 6
    assert [segment['role'] for segment in seal['segments']].count('accepted final consumer scope') == 1
    assert seal['segments'][-1]['report_sha256'] == sha(path)
    for segment in seal['segments']:
        source = Path(segment['report_path'])
        assert sha(source) == segment['report_sha256']
        identity = segment['runtime_and_original_patch_identity']
        assert identity['native_sha256'] == NATIVE_SHA and identity['client_sha256'] == CLIENT_SHA
        assert identity['native_runtime_sha256'] == DLLS and identity['patches'] == report['patches']
        assert source.parent.name.startswith('gameplay-equipment-model23-'), 'earlier-runtime checkpoint forbidden'
    copied = path.parent / 'run-inputs'
    manifest_path = copied / 'SHA256.json'
    # The final run preserved the original 66 archival helpers and added 12.
    # The inventory includes earlier snapshots; actual imported helpers are
    # separately pinned by the final audit and executed orchestration.
    manifest = checked_code_manifest(manifest_path, EQUIPMENT_COPIES_SHA, 78)
    original = checked_code_manifest(
        ROOT/'output/gameplay-equipment-model23-1/run-inputs/SHA256.json',
        '334d113e41c069d44facf89263273a8475582ce836b41642ee17d4ee7c41815b', 66)
    assert {name: manifest[name] for name in original} == original
    assert {name: digest for name, digest in manifest.items() if name not in original} == {
        'test_loaded_gameplay_workers.py': '2d42d205189966cc6b8a622e777aa0467d37959a7a188bc9f61143d76d1a44c5',
        'test_normal_card_continuation.py': 'c081d62c6d2bc3b6513800b24136d75f2c2e67754c84a9746946c5dca5f185fe',
        'test_equipment_bk_yellow_carriers.py': '7ef39b14ede82bdee047deb4757c11e1fba62e9e6e820cdcdb22ff5f85283098',
        'test_normal_gameplay_observed.py': '848ccdf2743b878abaf0d1ba1ac381a69be8b915676395579c9958bdc5bb0dd2',
        'test_normal_gameplay_onion.py': '04f1ae67273bc94b5f4d592bdeed4e5bc4110c0817aafa03715dea2d4afb76e6',
        'test_equipment_held_glint_continuation.py': '17ce63a1a0587e8c592107ab63aa3329a9d61ae5241d635f20ed8dc01d1234d6',
        'test_equipment_natural_relift.py': '9cb60818445fbc61505364dac077db6d1012622fd53dcf6ed96704f871b9049d',
        'test_equipment_glint_held.py': '30859c6064506b372b79c2ac4752931341e758c25212b155c13ab8a069d86bd9',
        'test_equipment_sr_combat_setup.py': 'd16b5bf513085b9464df5ec56da3f774ef1207777f02e7449ec9455525deb774',
        'test_normal_gameplay_ground_numbers.py': '02013ee4c048bb61dffd0a441b036a5e80b5536515dcb25e12068106e170577f',
        'test_equipment_resumed_entry.py': 'bd3130fd72d8d24ec42cfc220d653209729139d797437724b36e686324c57363',
        'test_equipment_recall_approach.py': '71c26621c24bf9b18351f3eb096028c50902451acaa663b6181a2f00bd0fc6e3',
    }
    expected = {
        'test_equipment_fresh_original.py': '9886f5a992dca568c1a37d6e8fce1718a6028d9301033b0480a30d4bf10e98ab',
        'test_equipment_original_alternate.py': 'eeec52e315c4d3b1eacce9c8da6e6a622614a853712570534b38a6b49f95bf22',
        'test_equipment_gameplay_real_server.py': 'ccc78e9b3b37cbdc5240760c24f008fc8ce2a061e497193f40468e0b70413d09',
    }
    for name, digest in expected.items():
        assert manifest[name] == digest and sha(ROOT/'tools'/name) == digest
    assert report['driver_sha256'] == '2658e2cc77220f3fe516ac121035205f7b37173a0c97afab0d6adfde285f587b'
    final_audit_path = path.parent / 'final-audit.json'
    assert sha(final_audit_path) == '13c3c585dbd64721f50c51b9354ce65ea78e4120a4401c670a5cb5ba20c5c842'
    final_audit = json.loads(final_audit_path.read_text())
    assert final_audit['status'] == 'passed' and final_audit['report_sha256'] == sha(path)
    assert final_audit['continuation_provenance_sha256'] == sha(seal_path)
    assert final_audit['copied_manifest_sha256'] == EQUIPMENT_COPIES_SHA
    assert final_audit['copied_code_files'] == 78 and final_audit['current_helper_sources_unchanged'] is True
    assert set(final_audit['consumer_item_ids']) == set(range(501, 511)) | {513}
    assert all(final_audit['input_guards'].values())
    assert all(row['absent'] is True for row in final_audit['test_owned_native_processes'])
    independent_path = ROOT/'output/equipment-model23-8-independent-audit-20261016.json'
    assert sha(independent_path) == 'cc621a67ec4a9c1c470c4038389c5e238c175415aad91054c6459ca36f030e29'
    independent = json.loads(independent_path.read_text())
    assert independent['report_sha256'] == sha(path)
    assert independent['continuation_sha256'] == sha(path.parent/'continuation.json') == 'db7aa36ce02793cbf0b7ea1d840ddf47f682d7713810e697d24c36506bee9273'
    assert set(independent['consumer_item_ids']) == set(range(501, 511)) | {513}
    # Baselines and original recipients are retained from actual report events;
    # no old slot2/slot2/slot1 damage/speed/Key assumptions are introduced here.
    return seal, manifest_path, manifest


def checked_source_proofs(native):
    fix = ROOT/'output/native23-yaz0-fix-verification.json'
    assert sha(fix) == '5e08d878e19664e8096e3602f1dd7f7986d82de3ce811915987750acabfb4de8'
    receipt = json.loads(fix.read_text())
    assert receipt['status'] == 'passed' and receipt['native_sha256'] == sha(native) == NATIVE_SHA
    assert sha(ROOT/'output/source-probe-model23-sync.json') == 'a5c14fd35b13c8e72dee6f70ff407fb4d67412d22bf2daefc43d77e26a5ad534'
    sync = json.loads((ROOT/'output/source-probe-model23-sync.json').read_text())
    assert sync['files'] == 3125 and sync['working_source_inputs_unchanged'] is True
    assert sync['native_ship_sha256'] == NATIVE_SHA
    source = Path(sync['source_export'])
    assert {p.relative_to(source).as_posix():sha(p) for p in source.rglob('*') if p.is_file()} == sync['source_hashes']
    assert sha(ROOT/'output/source-closure-model23-probe.json') == 'a31385f6deb89767a7b7912ddf27031e36eb8df87efe983972470a0231ed7b67'
    closure = json.loads((ROOT/'output/source-closure-model23-probe.json').read_text())
    assert closure['source_files'] == 3125 and closure['missing'] == [] and closure['native_source_dependencies'] == 2159
    assert closure['configured'] is True and closure['reused_exported_source_build'] is False
    assert closure['compiled_native_sha256'] == sha(ROOT/'output/source-closure-model23-build/bin/pikmin2-native.exe')
    assert sha(ROOT/'output/native-independent-source23-review.json') == 'db4c2538a09a3db81d99f0df58594b186fd890671a4c3d0acb6cf184a656e0ec'
    independent = json.loads((ROOT/'output/native-independent-source23-review.json').read_text())
    assert independent['status'] == 'passed' and independent['exact_ship_native_sha256'] == NATIVE_SHA
    cold = ROOT/'output/animation-load-native23-validation-2/report.json'
    assert sha(cold) == receipt['private_authored_archive_validation']['report_sha256']
    return fix, cold


def checked_historical_content():
    # Historical source/content provenance only. No model22 gameplay gate enters
    # the fresh23 aggregate. Each asset-bearing source reviewed then is unchanged.
    broad = ROOT/'output/native-model22-broad-content-review.json'
    base = ROOT/'output/native-independent-source22-review.json'
    assert sha(broad) == '098f1e9fa4e2b41400085d36d1e5c9c0edb1e07737f651e9e4e63b262ed0d9b3'
    assert sha(base) == 'cacec13493c39db318d1855fdeee4af27977cb8176815469ef46dfaa2883d6ae'
    review = json.loads(broad.read_text()); prior = json.loads(base.read_text())
    assert review['status'] == prior['status'] == 'passed'
    assert review['native_sha256'] == prior['exact_ship_native_sha256'] == 'ea7787f1d0d27bfb983a0d624bbb3803b60b7ad11be902f470234fe0302a76e8'
    sync = json.loads((ROOT/'output/source-probe-model23-sync.json').read_text())
    assert len(sync['changed']) == 9 and len(sync['added']) == 2 and not sync['removed']
    source = Path(sync['source_export'])
    reviewed = dict(review['reviewed_source_hashes'])
    reviewed.update({row['source']:row['source_sha256'] for row in review['embedded_arrays']})
    assert all(sha(source/name) == digest for name,digest in reviewed.items())
    assert not review['binary_source_files'] and not review['forbidden_resource_or_player_state_suffixes']
    return broad, base


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ('normal_antecedent','normal_card','loaded','water','equipment','ww','louie','poko','count','continuation'):
        parser.add_argument('--'+name,type=Path,required=True)
    parser.add_argument('--unit-log',type=Path,default=ROOT/'output/integration-tests-model23-fresh-equipment-9886f5a9.log')
    args = parser.parse_args()
    native = ROOT.parent/'output/merged-model23-bin/pikmin2-native.exe'
    client = Path('C:/Users/alari/peliarch-integration-20261015/p2-target/release/pikmin2_fusion.exe')
    assert sha(native) == NATIVE_SHA and sha(client) == CLIENT_SHA
    assert {p.name:sha(p) for p in native.parent.glob('*.dll')} == DLLS
    for name in ('normal_card','loaded','water','equipment','ww','louie','poko','count'):
        checked_case(getattr(args,name))
    normal_audit = checked_normal_audit(args.normal_antecedent,args.normal_card)
    sys.path.insert(0,str(ROOT/'tools'))
    from compose_normal_continuation import compose as compose_normal
    normal_bundle = compose_normal(args.normal_antecedent,args.normal_card,native,client)
    normal_composer = ROOT/'tools/compose_normal_continuation.py'
    assert normal_bundle['composer_sha256'] == sha(normal_composer)
    seal, equipment_manifest_path, equipment_manifest = checked_equipment(args.equipment,args.continuation)
    fix, cold = checked_source_proofs(native)
    toolkit = checked_public_toolkit_dependency(ROOT)
    historical_content, historical_source = checked_historical_content()
    function_review = ROOT/'output/release23-assembly-qa-independent-review-recovery-v1.json'
    review = json.loads(function_review.read_text())
    assert review['status'] == 'passed-function-and-source-review'
    assert review['assembly_helper_sha256'] == sha(Path(__file__))
    assert review['zip_qa_helper_sha256'] == sha(ROOT/'output/exact_release23_zip_qa.py')
    assert sha(args.unit_log) == UNIT_LOG_SHA
    assert re.search(r'Ran 102 tests\b',args.unit_log.read_text()) and args.unit_log.read_text().rstrip().endswith('OK')
    recovery_unit_log = ROOT/'output/integration-tests-model23-observed-recovery-inputs.log'
    recovery_review = ROOT/'output/equipment-observed-recovery-input-independent-review.json'
    assert sha(recovery_unit_log) == RECOVERY_UNIT_LOG_SHA
    assert re.search(r'Ran 124 tests\b',recovery_unit_log.read_text()) and recovery_unit_log.read_text().rstrip().endswith('OK')
    assert sha(recovery_review) == 'ffc83fa5371f643416385de7ffc63a01551c5570820651342f67a74e4c0ad435'
    reviewed_recovery = json.loads(recovery_review.read_text())
    assert reviewed_recovery['passed'] is True and reviewed_recovery['full124_owner_log_sha256'] == RECOVERY_UNIT_LOG_SHA
    assert reviewed_recovery['helper_sha256'] == '9cb60818445fbc61505364dac077db6d1012622fd53dcf6ed96704f871b9049d'
    assert reviewed_recovery['independent_focused_units'] == '8 passed'
    final_unit_log = ROOT/'output/integration-tests-model23-purple-ground.log'
    assert sha(final_unit_log) == FINAL_UNIT_LOG_SHA
    assert re.search(r'Ran 140 tests\b',final_unit_log.read_text()) and final_unit_log.read_text().rstrip().endswith('OK')
    normal_review = ROOT/'output/normal-continuation-independent-review.json'
    assert sha(normal_review) == 'a606df1d701e2cb2ccf77f1ef76a4df4a5f969787f2494e64bc7802ba3c31cfb'
    reviewed_normal = json.loads(normal_review.read_text())
    assert reviewed_normal['status'] == 'passed' and reviewed_normal['composer_sha256'] == sha(normal_composer)
    assert reviewed_normal['antecedent_report_sha256'] == sha(args.normal_antecedent)
    assert reviewed_normal['card_report_sha256'] == sha(args.normal_card)
    assert len(reviewed_normal['negative_controls']) == 8 and all(row['rejected'] for row in reviewed_normal['negative_controls'])
    equipment_closure_review = ROOT/'output/equipment-model23-8-seal-closure-audit-20261016.json'
    assert sha(equipment_closure_review) == '266494c5cd2c1d440787c64343a304de74d4f658a0e0007f3ceb9a3367739177'
    reviewed_closure = json.loads(equipment_closure_review.read_text())
    assert reviewed_closure['status'] == 'passed' and reviewed_closure['source_report_sha256'] == sha(args.equipment)
    assert reviewed_closure['official_continuation_seal']['sha256'] == sha(args.continuation)
    assert reviewed_closure['copied_code']['final_78_manifest_sha256'] == EQUIPMENT_COPIES_SHA
    assert reviewed_closure['copied_code']['original_66_changed_digests'] == 0
    assert reviewed_closure['copied_code']['dependency_digest_mismatches_against_final_copy_or_current_source'] == 0
    from compose_gameplay_cases import compose
    from test_gameplay_evidence import aggregate
    goals = ROOT/'output/gameplay-goals-model23.json'
    progression = ROOT/'output/gameplay-progression-model23.json'
    normal = ROOT/'output/gameplay-normal-bundle-model23.json'
    combined = ROOT/'output/gameplay-acceptance-model23.json'
    index = ROOT/'output/release-model23-evidence-index.json'
    destination = ROOT/'output/release-model23-public-evidence'
    assert not any(p.exists() for p in (goals,progression,normal,combined,index,destination))
    normal.write_text(json.dumps(normal_bundle,indent=2)+'\n')
    goals.write_text(json.dumps(compose([args.louie,args.poko,args.count],native,client,'original_goals'),indent=2)+'\n')
    progression.write_text(json.dumps(compose([args.equipment,args.ww],native,client,'progression'),indent=2)+'\n')
    result = aggregate([normal,args.loaded,args.water,goals,progression],native,client)
    assert result['status'] == 'passed' and all(g['passed'] is True for g in result['gates'].values())
    combined.write_text(json.dumps(result,indent=2)+'\n')
    reports = {
        'assembly-and-public-evidence-code.txt':Path(__file__).resolve(),
        'gameplay.json':combined,'normal-gameplay.json':normal,'loaded-gameplay.json':args.loaded,
        'water-gameplay.json':args.water,'original-goals.json':goals,'progression.json':progression,
        'normal-antecedent-failed.json':args.normal_antecedent,
        'normal-card-continuation.json':args.normal_card,
        'normal-card-continuation-provenance.json':args.normal_card.parent/'provenance.json',
        'normal-card-final-audit.json':normal_audit,
        'normal-card-client-1-clean-replay.txt':args.normal_card.parent/'client-1-fresh-server-native-check-replay.jsonl',
        'normal-card-client-2-clean-replay.txt':args.normal_card.parent/'client-2-fresh-server-native-check-replay.jsonl',
        'normal-card-client-1-original-journal-reconnect.txt':args.normal_card.parent/'client-1-original-journal-reconnect.jsonl',
        'normal-card-client-2-original-journal-reconnect.txt':args.normal_card.parent/'client-2-original-journal-reconnect.jsonl',
        'normal-interrupted-bundle-composer-code.txt':normal_composer,
        'normal-continuation-independent-review.json':normal_review,
        'normal-card-attempt3-disqualification.json':args.normal_card.parent.parent/'gameplay-normal-card-continuation-model23-3/reconnect-qualification.json',
        'equipment-consumers.json':args.equipment,'equipment-continuation-provenance.json':args.continuation,
        'equipment-final-audit.json':args.equipment.parent/'final-audit.json',
        'equipment-independent-audit.json':ROOT/'output/equipment-model23-8-independent-audit-20261016.json',
        'equipment-seal-closure-independent-review.json':equipment_closure_review,
        'earned-debt-and-globes.json':args.ww,'original-goal-louie.json':args.louie,
        'original-goal-pokos.json':args.poko,'original-goal-count.json':args.count,
        'normal-antecedent-base-driver-pin.json':args.normal_antecedent.parent/'base-driver-pin.json',
        'normal-card-base-driver-pin.json':args.normal_card.parent/'base-driver-pin.json',
        'normal-observation-dependency.json':args.normal_antecedent.parent/'normal-observation-dependency.json',
        'executed-base-driver-normal-antecedent.txt':args.normal_antecedent.parent/'executed-base-driver.py',
        'executed-base-driver-normal-card.txt':args.normal_card.parent/'executed-base-driver.py',
        'executed-normal-acceptance-code.txt':args.normal_antecedent.parent/'executed-normal-acceptance.py',
        'executed-normal-card-onion-guard-code.txt':args.normal_card.parent/'executed-onion-guard.py',
        'equipment-run-input-code-manifest.json':equipment_manifest_path,
        'native-yaz0-repair-verification.json':fix,'native-yaz0-cold-resource-check.json':cold,
        'source-export-hashes.json':ROOT/'output/source-probe-model23-sync.json',
        'source-build.json':ROOT/'output/source-closure-model23-probe.json',
        'source-build.log':ROOT/'output/source-build-model23-probe.log',
        'source-build-decoder-tests.log':ROOT/'output/source-build-model23-yaz0-selftest.log',
        'native-decoder-source-review.json':ROOT/'output/native23-yaz0-source-independent-review-provisional.json',
        'native-source-review.json':ROOT/'output/native-independent-source23-review.json',
        'native-content-review.json':ROOT/'output/native-content-model23-binary.json',
        'native-resource-delta-review.json':ROOT/'output/native-model23-resource-delta-review.json',
        'historical-model22-broad-content-review.json':historical_content,
        'historical-model22-source-review.json':historical_source,
        'assembly-and-qa-function-review.json':function_review,
        'exact-final-zip-qa-code.txt':ROOT/'output/exact_release23_zip_qa.py',
        'native-callback-tests.log':ROOT/'output/native-callback-model23-final.log',
        'controller-policy-tests.log':ROOT/'output/model23-controller-policy-tests.log',
        'integration-tests.log':args.unit_log,
        'integration-recovery-tests.log':recovery_unit_log,
        'integration-final-140-tests.log':final_unit_log,
        'equipment-observed-recovery-source-review.json':recovery_review,
        'companion-source-client-provenance.json':ROOT/'output/companion-source-client-provenance.json',
        'public-toolkit-dependency-verification.json':toolkit,
    }
    for name in equipment_manifest:
        reports['equipment-run-input-'+name+'.txt'] = equipment_manifest_path.parent/name
    for name in ('normal_antecedent','normal_card','loaded','water','equipment','ww','louie','poko','count'):
        path=getattr(args,name)
        reports['executed-driver-'+name+'.txt'] = path.parent/'executed-driver.py'
        for folder in path.parent.iterdir():
            if folder.is_dir() and folder.name.startswith('executed-'):
                for source in sorted(folder.rglob('*.py')):
                    reports[name+'-'+'-'.join(source.relative_to(path.parent).parts)+'.txt'] = source
    for i,segment in enumerate(seal['segments'],1):
        if Path(segment['report_path']).resolve() != args.equipment.resolve():
            reports[f'equipment-model23-segment-{i}-provenance.json']=Path(segment['report_path'])
    assert all(p.is_file() for p in reports.values())
    reports = write_public_evidence(reports,destination)
    index.write_text(json.dumps({'reports':{n:str(p.resolve()) for n,p in reports.items()}},indent=2)+'\n')
    print(json.dumps({'status':'passed','index':str(index),'evidence_files':len(reports),'native_sha256':NATIVE_SHA}))


if __name__ == '__main__':
    main()
