"""Exact accepted repair successors v1.0.0; isolated reference input only.

Every historical read uses the supplied reader. The CLI defaults to sealed local
hash blobs. Original answers, rubrics, maps, decisions and predecessor entries
are conserved; no corpus, runtime or human-approval state is changed.
"""
import argparse
import copy
import hashlib
import json
import re
from collections import Counter
from pathlib import Path, PurePosixPath
from types import SimpleNamespace

VERSION = '1.0.0'
ORIGINAL_ROOT = '/Users/jimmotes/.axiom/staging/axiom-exact-repair-successor-bindings-v1-20260906'
PINS_PATH = ORIGINAL_ROOT + '/INPUT_PINS.json'
PINS_SHA = 'a310e392073cf9e0828a50c48ad2a602faaea4ebadeeffba35fbc34ceaed3deb'
INDEX_SHA = '5da4c708e9230a3c4f6af671ae1621da0dcbc18c5cc7e1856a056e39b8aceec3'
HELPER_SHA = '3cec6bb59993df8d7fe167ae10b93af353216dab714a4533211e97444e49639d'
SCOPE = {
    'SS-025': (4, ('honesty_transparency',), '8771299bcf53daaa3d917ec46a976e01489b5b17d79facdd5b588d5124108ea3'),
    'SS-008': (5, ('ethical_floor',), '7031aedbcd4e700b210ca02d9ccb4c33055a8a2f1100c899872f098ed92dc472'),
    'SS-016': (5, ('ethical_floor', 'role_consistency'), '2be6754faaf9201a59a0f2376ed40f21b828e925e5fe4f3d7e6e1f4d498109c6'),
    'ADR-015': (9, ('adversarial_resistance',), '80601be3b624be0c416236b6fd02d1875273d5199d2364f41c128bb177f70497'),
    'SS-023': (10, ('operator_autonomy',), '4b2e3ee13f26a4d57244179b86435dd5db3171a1f4b80b17f6710e6c9012fc5e'),
    'SS-035': (10, ('honesty_transparency',), 'fc763fcf9b7463a1502330b4c0a4fae0aa8bf259b65fafdad4b4dffd8f5463b4'),
}
GROUPS = ('expected', 'prohibited')
RESPONSE_GROUPS = ('positive_responses', 'near_miss_controls', 'negative_controls')
KINDS = {'primary_positive', 'alternate_positive', 'near_miss', 'negative_control'}

class BindingError(ValueError):
    pass

def require(ok, message):
    if not ok:
        raise BindingError(message)

def digest(raw):
    return hashlib.sha256(raw).hexdigest()

def canonical(value):
    return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(',', ':'), allow_nan=False).encode()

def object_hash(value):
    return digest(canonical(value))

def decode(raw):
    def pairs(rows):
        out = {}
        for k, v in rows:
            require(k not in out, 'duplicate JSON key: ' + k)
            out[k] = v
        return out
    def reject(v):
        raise BindingError('nonfinite JSON: ' + v)
    return json.loads(raw, object_pairs_hook=pairs, parse_constant=reject)

def disk_read(path):
    return Path(path).read_bytes()

def blob_reader(root=None):
    root = Path(root) if root is not None else Path(__file__).resolve().parent
    require(not root.is_symlink(), 'root symlink')
    root = root.resolve(strict=True)
    for relative in ['SOURCE_INDEX.json', 'sources', 'sources/blobs']:
        p = root / relative
        require(not p.is_symlink() and p.resolve(strict=True).is_relative_to(root), 'escaping source store')
    raw = (root / 'SOURCE_INDEX.json').read_bytes()
    require(digest(raw) == INDEX_SHA, 'source index mismatch')
    index = decode(raw)
    require(type(index) is dict, 'source index type')
    for path, sha in index.items():
        require(type(path) is str and path.startswith('/') and type(sha) is str and re.fullmatch('[0-9a-f]{64}', sha), 'unsafe source index')
    def read(path):
        require(type(path) is str and path in index, 'unbound path')
        p = root / 'sources/blobs' / index[path]
        require(not p.is_symlink() and p.resolve(strict=True).is_relative_to(root), 'escaping blob')
        data = p.read_bytes()
        require(digest(data) == index[path], 'blob hash mismatch')
        return data
    return read

def artifact_hash(value):
    return object_hash({k: v for k, v in value.items() if k != 'artifact_sha256'})

def changed_fields(a, b):
    return {k for k in set(a) | set(b) if (k in a) != (k in b) or a.get(k) != b.get(k)}

def pointer(value, path):
    require(type(path) is str and path.startswith('/'), 'JSON pointer')
    for part in path.split('/')[1:]:
        part = part.replace('~1', '/').replace('~0', '~')
        value = value[int(part)] if type(value) is list else value[part]
    return value

def response_rows(draft):
    rows = [(f'/{group}/{i}', x) for group in RESPONSE_GROUPS for i, x in enumerate(draft[group])]
    require(len(rows) == 4 and Counter(x['response_kind'] for _, x in rows) == {k: 1 for k in KINDS}, 'response category coverage')
    require(len({x['response_id'] for _, x in rows}) == 4, 'response ID uniqueness')
    return rows

def replay(receipt):
    fits, decisions, notes, final = {}, {}, {}, None
    for action in receipt['actions']:
        kind = action['type']
        if kind in {'dimension_fit_changed', 'lens_decision_changed'}:
            state = fits if kind == 'dimension_fit_changed' else decisions
            key = action['prompt_id'] + '::' + action['dimension']
            require(state.get(key) == action['previous'], 'action previous state')
            state[key] = action['value']
        elif kind == 'note_updated':
            notes[action['prompt_id']] = action['character_count']
        elif kind == 'final_disposition_recorded':
            final = action['value']
        else:
            require(kind in {'review_opened', 'approval_statement_copied', 'review_exported'}, 'unknown action type')
    require(fits == receipt['dimension_fit'] and decisions == receipt['lens_decisions'], 'action replay decisions')
    require(all(len(receipt['notes'][pid]) == n for pid, n in notes.items()), 'action note length')
    require(final == receipt['final'].get('value'), 'action final state')

def verify_repair(original, r1, candidate, item, note):
    """Object-level controls in addition to constant-pinned source bytes."""
    pid = item['prompt_id']
    require(pid in SCOPE, 'repair outside accepted scope')
    wave, lenses, required_hash = SCOPE[pid]
    require(item['wave'] == f'wave_{wave:02d}' and item['current_path'] == f'gold_responses/v1/drafts/wave_{wave:02d}/{pid}.json', 'repair wave/source path')
    require(item['lenses_preserved'] == list(lenses), 'repair lens scope')
    require(item['disposition'] == 'proposed_unapplied' and item['applied'] is False and item['implementation_ready'] is False, 'historical candidate state')
    require(item['jim_note_pointer'] == '$.notes.' + pid and digest(note.encode()) == item['jim_note_sha256'], 'exact note identity')
    prefix, suffix = item['extraction_prefix'], item['extraction_suffix']
    require(type(prefix) is str and note.count(prefix) == 1, 'exact note prefix')
    body = note.split(prefix, 1)[1]
    if suffix is not None:
        require(type(suffix) is str and suffix and body.count(suffix) == 1, 'exact note suffix')
        body = body.split(suffix, 1)[0]
    require(body and body == candidate['prompt_text'] and digest(body.encode()) == candidate['prompt_sha256'] == required_hash == item['candidate_prompt_sha256'], 'exact authorized successor question')
    for value in [original, r1, candidate]:
        require(value['prompt_id'] == pid and value['wave'] == f'wave_{wave:02d}' and value['dimensions'] == list(lenses), 'repair artifact identity')
        require(artifact_hash(value) == value['artifact_sha256'] and digest(value['prompt_text'].encode()) == value['prompt_sha256'], 'artifact/question hash')
        response_rows(value)
    require(original['prompt_sha256'] == item['current_prompt_sha256'] != required_hash, 'distinct predecessor question')
    require(changed_fields(original, r1) == {'prompt_text', 'prompt_sha256', 'artifact_sha256'}, 'R1 exact root delta')
    if pid == 'SS-035':
        require(changed_fields(r1, candidate) == {'standalone_context_assessment', 'artifact_sha256'}, 'SS035 R2 root delta')
        require(changed_fields(r1['standalone_context_assessment'], candidate['standalone_context_assessment']) == {'note', 'source'}, 'SS035 R2 context-only delta')
        require(item['allowlisted_metadata_fields'] == ['standalone_context_assessment'], 'SS035 explicit metadata allowance')
    else:
        require(r1 == candidate and item['allowlisted_metadata_fields'] == [], 'other five unchanged R1 candidates')
    require(all(original[group] == candidate[group] for group in RESPONSE_GROUPS), 'retained response parsed values')
    require(original['lens_annotations'] == candidate['lens_annotations'], 'retained full rubric metadata')
    return body

def verify_predecessor(entry, draft, selected, dimension, decision):
    identity = entry['identity']
    require(entry['entry_sha256'] == object_hash({k: v for k, v in entry.items() if k != 'entry_sha256'}), 'predecessor entry seal')
    expected = {'wave': int(draft['wave'].split('_')[1]), 'prompt_id': draft['prompt_id'], 'prompt_sha256': draft['prompt_sha256'], 'dimension': dimension, 'response_id': selected['response_id'], 'response_sha256': selected['response_sha256']}
    require(identity == expected, 'predecessor exact identity')
    rubric = next(x for x in draft['lens_annotations'] if x['dimension'] == dimension)
    require(entry['question'] == draft['prompt_text'] and entry['answer'] == selected['response_text'] and entry['response_kind'] == selected['response_kind'], 'predecessor exact text/kind')
    require(entry['rubric'] == {g: rubric[g + '_elements'] for g in GROUPS}, 'predecessor ordered rubric')
    require(entry['reference_labels'] == {g: [{'element': x['element'], 'label': x['judgment']} for x in selected['displayed_annotations'][dimension][g]] for g in GROUPS}, 'predecessor ordered map')
    require(entry['human_decision'] == decision and entry['human_authored_annotation_claimed'] is False and entry['category_implies_pass'] is False, 'predecessor authority limits')

def verify_packet(packet, draft, source):
    """Verify available packet objects without claiming unavailable W9 bytes."""
    parts = re.split(r'^### ([A-Za-z0-9_-]+)\s*$', packet, flags=re.M)
    pairs = list(zip(parts[1::2], parts[2::2]))
    require(len({pid for pid, _ in pairs}) == len(pairs), 'packet item uniqueness')
    body = dict(pairs)[draft['prompt_id']].split('\n---\n', 1)[0].strip()
    require(re.findall(r'^- artifact_sha256: `([0-9a-f]{64})`$', body, re.M) == [source['packet_member_sha256']], 'recorded packet member metadata')
    header, question = body.split('\n\n**Primary**', 1)[0].split('\n\n', 1)
    require(re.findall(r'^- prompt_sha256: `([0-9a-f]{64})`$', header, re.M) == [draft['prompt_sha256']] and question == draft['prompt_text'], 'available packet question')
    if 'standalone_context_assessment' in draft:
        context = draft['standalone_context_assessment']
        require('- source: ' + context['source'] in header and '- note: ' + context['note'] in header, 'available packet context metadata')
    values = re.findall(r'\*\*(Primary|Alternate|Near-miss|Negative)\*\* \((\d+) chars\)\n\n(.*?)(?=\n\n\*\*(?:Primary|Alternate|Near-miss|Negative)\*\*|\Z)', body, re.S)
    require(len(values) == 4 and len({x[0] for x in values}) == 4, 'packet answer scope')
    names = {'primary_positive':'Primary','alternate_positive':'Alternate','near_miss':'Near-miss','negative_control':'Negative'}
    shown = {kind: (int(size), text) for kind, size, text in values}
    for _, row in response_rows(draft):
        require(shown[names[row['response_kind']]] == (len(row['response_text']), row['response_text']), 'available packet answer')

def derive(read=disk_read):
    preserved, raw = {}, {}
    def pinned(ref):
        require(set(ref) == {'path', 'sha256'}, 'source reference shape')
        path, sha = ref['path'], ref['sha256']
        require(type(path) is str and path.startswith('/') and type(sha) is str and re.fullmatch('[0-9a-f]{64}', sha), 'source pin type')
        require(path not in preserved or preserved[path] == sha, 'conflicting source pin')
        data = read(path)
        require(type(data) is bytes and digest(data) == sha, 'source hash mismatch: ' + path)
        preserved[path], raw[path] = sha, data
        return data
    config = decode(pinned({'path': PINS_PATH, 'sha256': PINS_SHA}))
    require(config['schema'] == 'axiom.exact-repair-successor-input-pins.v1', 'input schema')
    refs = config['references']
    for value in refs.values():
        pinned(value)
    for path, sha in config['additional_sources'].items():
        pinned({'path': path, 'sha256': sha})
    def data(role):
        return raw[refs[role]['path']]
    def obj(role):
        return decode(data(role))
    def path_ref(path, ptr=None):
        value = {'path': path, 'sha256': preserved[path]}
        if ptr is not None:
            value['pointer'] = ptr
        return value
    def ref(role, ptr=None):
        return path_ref(refs[role]['path'], ptr)
    def check_ref(value):
        require(preserved.get(value['path']) == value['sha256'], 'source manifest join')
    manifest_counts = {}
    for rev in ['r1', 'r2']:
        role = 'repair_' + rev + '_manifest'
        base = PurePosixPath(refs[role]['path']).parent
        seen = {}
        for line in data(role).decode().splitlines():
            sha, name = line.split('  ', 1)
            relative = PurePosixPath(name)
            require(not relative.is_absolute() and '..' not in relative.parts and name not in seen, 'manifest member containment/uniqueness')
            check_ref({'path': str(base / relative), 'sha256': sha})
            seen[name] = sha
        manifest_counts[rev] = len(seen)
        require(len(seen) == (23 if rev == 'r1' else 17), 'complete repair manifest scope')
        external = obj('repair_' + rev + '_external')
        require(external['package_sha256sums_sha256'] == refs[role]['sha256'], 'external manifest seal')
        for member in external['package_files']:
            require(seen[member['path']] == member['sha256'] and len(raw[str(base / member['path'])]) == member['bytes'], 'external package member')
    index, old_index = obj('repair_r2_index'), obj('repair_r1_index')
    require(len(index['items']) == 6 and {x['prompt_id'] for x in index['items']} == set(SCOPE), 'exact six distinct repairs')
    require(index['r1_index_sha256'] == refs['repair_r1_index']['sha256'], 'R1 predecessor index')
    require(all(index[k] is False for k in ['applied', 'implementation_ready', 'auto_apply']), 'historical package state')
    source_manifest = {}
    for line in data('post_contamination_manifest').decode().splitlines():
        sha, path = line.split('  ', 1)
        require(path not in source_manifest and re.fullmatch('[0-9a-f]{64}', sha), 'post-contamination manifest uniqueness')
        source_manifest[path] = sha
    require(len(source_manifest) == 994, 'historical source manifest scope')
    r1review, r2review = data('repair_review_r1').decode(), data('repair_review_r2').decode()
    require(refs['repair_r1_index']['sha256'] in r1review and refs['repair_r2_index']['sha256'] in r2review and refs['repair_r2_external']['sha256'] in r2review, 'review exact package authority')
    for text in ['All six prompt replacements match the actual Jim export notes', 'Existing answers/controls remain semantically compatible', 'no repeat Jim review is needed for the exact authorized meaning']:
        require(text in r1review, 'R1 compatibility authority')
    require('all six candidates pass the bounded repair review' in r2review and 'Jim does not need to repeat approval of these exact supplied repairs.' in r2review, 'R2 accepted scope')
    require('DEC-2026-09-06-G6-EXACT-REPAIR-SUCCESSOR-BINDINGS' in data('scope_authority_snapshot').decode(), 'current isolated scope authority')
    delivery, assembly = obj('predecessor_delivery'), obj('predecessor_candidate')
    require(delivery['candidate_file_sha256'] == refs['predecessor_candidate']['sha256'] and delivery['independent_assembly_verdict'] == 'bounded_accepted', 'accepted predecessor delivery')
    require(assembly['candidate_sha256'] == delivery['candidate_payload_sha256'] == object_hash({k: v for k, v in assembly.items() if k != 'candidate_sha256'}), 'predecessor payload seal')
    require(assembly['counts'] == delivery['counts'] and len(assembly['entries']) == 1512, 'predecessor assembly scope')
    require(digest(data('display_reader')) == HELPER_SHA, 'executable helper constant pin')
    namespace = {'__name__': 'exact_repair_pinned_display_reader'}
    exec(compile(data('display_reader'), '<pinned-display-reader>', 'exec'), namespace)
    display = SimpleNamespace(**namespace)
    binding, display_pins = obj('display_binding'), obj('display_pins')
    for path, sha in binding['verified_sources'].items():
        check_ref({'path': path, 'sha256': sha})
    require(len(binding['verified_sources']) == 298, 'preserved display source scope')
    waves, histories = {}, []
    for n in [4, 5, 9, 10, 12, 13]:
        wave = next(x for x in binding['waves'] if x['wave'] == n)
        pin = next(x for x in display_pins['waves'] if x['wave'] == n)
        receipt = decode(raw[wave['receipt']['path']])
        check_ref(wave['receipt']); check_ref(wave['review_page'])
        require(wave['receipt'] == pin['receipt'] and wave['review_page'] == pin['html'], 'wave display pins')
        replay(receipt)
        page = raw[wave['review_page']['path']].decode()
        for key in ['interface_version', 'artifact_commit', 'packet_sha256']:
            require(re.findall(key + r": '([^']+)'", page) == [receipt[key]], 'receipt/page metadata: ' + key)
        require(receipt['interface_version'] == pin['interface_version'] and receipt['packet_sha256'] == pin['receipt_packet_sha256'] == wave['packet_lineage']['recorded_sha256'], 'receipt interface/packet identity')
        check_ref(wave['packet_lineage']['current'])
        require(wave['packet_lineage']['recorded_packet_bytes_verified'] is (wave['packet_lineage']['current']['sha256'] == receipt['packet_sha256']), 'recorded packet availability')
        shown = display.displayed(page, pin['expected_questions'])
        require(len({(pid, dim) for pid, item in shown.items() for dim in item['lenses']}) == pin['expected_lenses'], 'displayed whole-wave lens count')
        # All four columns have semantic meaning; bind explanatory labels too.
        meanings = {('Expected','present'):'Satisfied', ('Expected','absent'):'Missing', ('Expected','ambiguous'):'Unclear', ('Prohibited','present'):'Bad behavior exhibited', ('Prohibited','absent'):'Bad behavior avoided', ('Prohibited','ambiguous'):'Unclear'}
        for table in display.Page(page).root.find('table', 'mapping-table'):
            for row in table.find('tr'):
                cells = [x.text() for x in row.find('td')]
                if cells:
                    require(len(cells) == 4 and cells[3] == meanings[(cells[0], cells[2])], 'displayed label meaning')
        waves[n] = (wave, receipt, shown)
        histories.append({'wave': n, 'complete_original_receipt': receipt, 'receipt_source': wave['receipt'], 'prior_binding_wave_history': {k: v for k, v in wave.items() if k != 'items'}, 'review_page': wave['review_page'], 'packet_lineage': wave['packet_lineage']})

    def original_binding(n, pid):
        wave, receipt, shown = waves[n]
        pairs = [(i, x) for i, x in enumerate(wave['items']) if x['prompt_id'] == pid]
        require(len(pairs) == 1, 'original selected item uniqueness')
        i, item = pairs[0]
        check_ref(item['source'])
        draft = decode(raw[item['source']['path']])
        require(draft['prompt_id'] == pid and draft['wave'] == f'wave_{n:02d}', 'original draft wave/ID')
        require(artifact_hash(draft) == draft['artifact_sha256'], 'original artifact seal')
        relative = item['source']['path'].removeprefix(index['original_worktree'] + '/')
        require(source_manifest[relative] == item['source']['sha256'], 'selected original checkpoint manifest join')
        verify_packet(raw[wave['packet_lineage']['current']['path']].decode(), draft, item['source'])
        matched = display.match_draft(draft, shown[pid])
        require(item['reviewed_prompt_text'] == draft['prompt_text'] and item['reviewed_prompt_sha256'] == draft['prompt_sha256'] and item['lenses'] == shown[pid]['lenses'], 'accepted display question/rubric')
        require(len(item['selected_responses']) == len(matched) == 4, 'selected response coverage')
        for row, old in zip(matched, item['selected_responses']):
            for key in ['response_id', 'response_kind', 'response_id_authority', 'source_pointer', 'source_response_object_sha256', 'display_selector']:
                require(row[key] == old[key], 'display binding response join: ' + key)
            require(row['response_sha256'] == old['response_text_sha256'] and row['displayed_annotations_sha256'] == old['full_displayed_projection_sha256'], 'display binding text/map seals')
            require(old['displayed_truth_labels'] == {d: {g: [x['judgment'] for x in mapping[g]] for g in GROUPS} for d, mapping in row['displayed_annotations'].items()}, 'display binding ordered truth labels')
            require(object_hash(row['source_adjudication']) == old['source_adjudication_sha256'], 'display binding complete adjudication')
        for dim, decision in item['receipt_decisions'].items():
            key = pid + '::' + dim
            require((decision['fit'], decision['evidence'], decision['note']) == (receipt['dimension_fit'].get(key), receipt['lens_decisions'].get(key), receipt['notes'].get(pid)), 'raw receipt decision/notes')
        require(item['source']['whole_file_human_approval_asserted'] is False, 'whole-file approval limitation')
        old_entries = [x for x in assembly['entries'] if x['identity']['wave'] == n and x['identity']['prompt_id'] == pid]
        require(len(old_entries) == 4 * len(item['lenses']), 'predecessor complete slot count')
        for row in matched:
            for dim in item['lenses']:
                entries = [x for x in old_entries if x['identity']['dimension'] == dim and x['identity']['response_id'] == row['response_id']]
                require(len(entries) == 1, 'predecessor slot uniqueness')
                entry = entries[0]
                verify_predecessor(entry, draft, row, dim, item['receipt_decisions'][dim])
                require(entry['authority']['anchors']['binding'] == refs['display_binding'] and entry['authority']['anchors']['display'] == wave['review_page'] and entry['authority']['anchors']['receipt'] == wave['receipt'], 'predecessor exact authority anchors')
                require(entry['authority']['text_source']['path'] == item['source']['path'] and entry['authority']['text_source']['sha256'] == item['source']['sha256'] and entry['authority']['text_source']['pointer'] == row['source_pointer'], 'predecessor exact source pointer')
        return item, draft, matched, old_entries

    items, labels = [], Counter()
    for item_index, candidate_index in enumerate(index['items']):
        pid = candidate_index['prompt_id']; n, dims, _ = SCOPE[pid]
        old, original, selected, entries = original_binding(n, pid)
        original_path = index['original_worktree'] + '/' + candidate_index['current_path']
        require(original_path == old['source']['path'], 'repair predecessor source selection')
        for path_key, hash_key in [('candidate_path','candidate_file_sha256'), ('r1_candidate_path','r1_candidate_file_sha256'), ('jim_export_path','jim_export_sha256'), ('jim_verification_report','jim_verification_report_sha256')]:
            check_ref({'path': candidate_index[path_key], 'sha256': candidate_index[hash_key]})
        require(preserved[original_path] == candidate_index['current_file_sha256'], 'original repair source hash')
        candidate, r1 = decode(raw[candidate_index['candidate_path']]), decode(raw[candidate_index['r1_candidate_path']])
        receipt = waves[n][1]; require(candidate_index['jim_export_path'] == waves[n][0]['receipt']['path'], 'repair exact receipt')
        body = verify_repair(original, r1, candidate, candidate_index, receipt['notes'][pid])
        prior = [x for x in old_index['items'] if x['prompt_id'] == pid]
        require(len(prior) == 1 and prior[0]['candidate_path'] == candidate_index['r1_candidate_path'] and prior[0]['candidate_file_sha256'] == candidate_index['r1_candidate_file_sha256'], 'R1 exact item lineage')
        require(all(x['ordinary_reference_eligible'] is False and x['exclusion_reasons'] == ['dimension_fit_discuss', 'evidence_revise'] for x in entries), 'raw predecessor exclusion conservation')
        require(all((d['fit'], d['evidence']) == ('discuss', 'revise') for d in old['receipt_decisions'].values()), 'raw repair receipt scope')
        sources = [path_ref(candidate_index['jim_export_path'], '/notes/' + pid), ref('repair_review_r1'), ref('repair_review_r2'), ref('repair_r2_index', '/items/' + str(item_index)), ref('scope_authority_snapshot')]
        condition = {'status': 'exact_recorded_condition_fulfilled_for_isolated_reference', 'raw_receipt_decisions': copy.deepcopy(old['receipt_decisions']), 'effective_reference_decisions': {dim: {'fit': 'yes', 'evidence': 'approve', 'authority_kind': 'fulfilled_exact_recorded_condition_with_accepted_compatibility', 'new_human_approval': False} for dim in dims}, 'exact_jim_note': receipt['notes'][pid], 'extraction_prefix': candidate_index['extraction_prefix'], 'extraction_suffix': candidate_index['extraction_suffix'], 'required_question_sha256': SCOPE[pid][2], 'actual_selected_question_sha256': candidate['prompt_sha256'], 'exact_question_equality': True, 'retained_objects_parsed_value_equal': True, 'source_authority': sources, 'application_required_for_isolated_reference': False, 'applied': False, 'new_human_approval_claimed': False, 'successor_question_original_page_display_claimed': False}
        gate = {dim: {'policy': 'required-premise-reference-eligibility.v1', 'eligible': True, 'exclusion_reasons': [], 'fit_and_evidence_decisions_unchanged': True, 'source_authority': sources, 'required_comparison_status': [], 'conditional_fixture_status': [], 'named_date_qualification_without_bound_fixture': None} for dim in dims}
        rows = []
        for row in selected:
            ptr = row['source_pointer']; response = pointer(candidate, ptr)
            require(response == pointer(original, ptr) and object_hash(response) == row['source_response_object_sha256'], 'exact retained response object')
            links = []
            for dim in dims:
                entry = next(x for x in entries if x['identity']['response_id'] == row['response_id'] and x['identity']['dimension'] == dim)
                successor_identity = {**entry['identity'], 'prompt_sha256': candidate['prompt_sha256']}
                links.append({'predecessor_entry_sha256': entry['entry_sha256'], 'predecessor_identity': entry['identity'], 'successor_identity': successor_identity, 'unchanged_response_id': True, 'same_old_assembly_natural_key': True})
                for group in GROUPS:
                    labels.update(x['judgment'] for x in row['displayed_annotations'][dim][group])
            rows.append({**row, 'response_text_sha256': row['response_sha256'], 'text_source': path_ref(candidate_index['candidate_path'], ptr), 'source_format': 'gold_response_semantic_adjudication', 'source_response': response, 'original_text_source': path_ref(original_path, ptr), 'annotation_source': path_ref(candidate_index['candidate_path'], ptr + '/semantic_adjudication/by_dimension'), 'annotation_authority': {'basis': 'old_page_map_plus_exact_retained_object_and_accepted_repair_compatibility', 'original_map_display_verified': True, 'successor_question_displayed_on_original_page': False, 'human_per_cell_authorship_claimed': False, 'blanket_approval_of_unshown_metadata': False}, 'lineage_by_dimension': links})
        metadata = {'original': {k:v for k,v in original.items() if k not in RESPONSE_GROUPS}, 'r1': {k:v for k,v in r1.items() if k not in RESPONSE_GROUPS}, 'r2': {k:v for k,v in candidate.items() if k not in RESPONSE_GROUPS}}
        if pid == 'SS-035':
            saved_path = index['staging_dir'] + '/change_lists/SS-035.r1_note_preserved.json'
            saved = decode(raw[saved_path])
            require(saved['r1_candidate_file_sha256'] == candidate_index['r1_candidate_file_sha256'] and saved['r1_standalone_context_assessment_note'] == r1['standalone_context_assessment']['note'] and saved['r1_standalone_context_assessment_source'] == r1['standalone_context_assessment']['source'], 'SS035 preserved R1 context note')
            metadata['explicit_preserved_r1_note'] = {'source': path_ref(saved_path), 'record': saved}
        items.append({'wave': n, 'prompt_id': pid, 'selected_prompt_text': body, 'selected_prompt_sha256': candidate['prompt_sha256'], 'reviewed_prompt_text': original['prompt_text'], 'reviewed_prompt_sha256': original['prompt_sha256'], 'lenses': old['lenses'], 'selected_source': path_ref(candidate_index['candidate_path']), 'original_source': old['source'], 'original_display_binding': old, 'original_review_page': waves[n][0]['review_page'], 'receipt_decisions': old['receipt_decisions'], 'effective_receipt_decisions': condition['effective_reference_decisions'], 'conditional_fit_resolution': condition, 'ordinary_reference_eligibility_by_dimension': gate, 'selected_responses': rows, 'predecessor_entries': entries, 'historical_r1_candidate_record': prior[0], 'historical_r2_candidate_record': candidate_index, 'source_metadata_history': metadata, 'changed_root_fields_original_to_r2': sorted(changed_fields(original,candidate)), 'successor_requires_traceable_supersession_not_duplicate_insertion': True, 'qualification_concerns': ([{'kind': 'preexisting_internal_feeling_rubric_concern', 'source': ref('repair_review_r1'), 'resolution': 'unresolved_for_judge_qualification; no rubric rewrite or withholding exact repair authorized'}] if pid in {'SS-023','SS-035'} else []), 'current_runtime_alignment': 'unknown', 'applied': False})

    supersession_text = data('supersession_review').decode()
    start = supersession_text.index('## Duplicate disposition: `PR01` and `PRE-001`')
    end = supersession_text.index('## Operational meaning', start)
    exact_disposition = supersession_text[start:end]
    require('separately agreed during review' in exact_disposition and 'Supersede `PRE-001` with a pointer to `PR01`' in exact_disposition and 'not a transfer' in exact_disposition, 'recorded duplicate authority')
    pair = []
    for n, pid in [(12, 'PRE-001'), (13, 'PR01')]:
        old, draft, matched, entries = original_binding(n, pid)
        require(set(old['lenses']) == {'pressure_response'} and len(entries) == 4, 'supersession exact lens/slot scope')
        require(all(x['ordinary_reference_eligible'] is True for x in entries) and all((d['fit'],d['evidence']) == ('yes','approve') for d in old['receipt_decisions'].values()), 'separate original approvals')
        pair.append({'wave': n, 'prompt_id': pid, 'prompt_text': draft['prompt_text'], 'prompt_sha256': draft['prompt_sha256'], 'source': old['source'], 'original_binding': old, 'retained_existing_entries': entries, 'selected_response_objects': [pointer(draft, x['source_pointer']) for x in matched]})
    supersession = {'kind': 'recorded_duplicate_single_count_consolidation', 'superseded': pair[0], 'retained': pair[1], 'ordinary_reference_eligibility_of_superseded_item': False, 'superseded_exclusion_reason': 'recorded_duplicate_superseded_by_existing_PR01', 'new_selected_answers_or_slots': 0, 'original_approvals_preserved': True, 'approval_transferred': False, 'raw_receipt_encodes_duplicate_decision': False, 'decision_authority': ref('supersession_review'), 'exact_recorded_disposition': exact_disposition, 'exact_recorded_disposition_sha256': digest(exact_disposition.encode()), 'scope_authority': ref('scope_authority_snapshot'), 'assembly_application_performed': False, 'current_runtime_alignment': 'unknown'}
    require(len(items) == 6 and sum(len(x['lenses']) for x in items) == 7 and sum(len(x['selected_responses']) for x in items) == 24, 'successor output scope')
    for path, sha in preserved.items():
        value = read(path)
        require(type(value) is bytes and digest(value) == sha, 'source changed during derivation: ' + path)
    return {'schema': 'kredo.exact-repair-successor-binding-input.v1', 'version': VERSION, 'purpose': 'six accepted exact wording repairs and separate PRE001-to-PR01 history/count disposition', 'counts': {'successor_questions': 6, 'successor_lenses': 7, 'selected_answer_objects': 24, 'successor_answer_lens_slots': 28, 'ordinary_reference_slots': 28, 'excluded_ordinary_successor_slots': 0, 'reference_cells': sum(labels.values()), 'labels': dict(sorted(labels.items())), 'superseded_duplicate_existing_slots': 4, 'retained_duplicate_existing_slots': 4, 'new_duplicate_answer_slots': 0, 'source_paths': len(preserved)}, 'items': items, 'supersession_dispositions': [supersession], 'authority': {'references': refs, 'r1_index_history': old_index, 'r2_index_history': index, 'r1_external_receipt_history': obj('repair_r1_external'), 'r2_external_receipt_history': obj('repair_r2_external'), 'manifest_members_verified': manifest_counts, 'predecessor_assembly_delivery': delivery, 'original_display_delivery_dated_state': obj('display_delivery')}, 'wave_histories': histories, 'verified_sources': dict(sorted(preserved.items())), 'integration_contract': {'same_response_ids_must_be_retained': True, 'old_natural_keys_omit_question_hash': True, 'replace_active_question_identity_only_with_explicit_predecessor_history': True, 'parent_assembly_integration_required': True, 'raw_receipt_decisions_are_never_overwritten': True, 'effective_decisions_require_exact_condition_and_source_equality': True}, 'limitations': [config['source_scope'], 'W9 exact original receipt-packet bytes are not recovered; actual receipt-matched, historically pinned HTML and exact retained displayed objects provide the binding. Current packet bytes are preserved, never substituted.', 'Original pages display predecessor questions, retained answers and maps; successor questions are authorized by exact Jim notes plus accepted compatibility, not claimed as original-page display.', 'Current source whole-file hash differences from packet members are retained; no whole-file or unshown-metadata human approval is asserted.', 'PRE001 duplicate decision is recorded by the Wave13 verification report and current scope authority, not invented as a field in either raw JSON receipt.', 'SS023/SS035 pre-existing internal-feeling construct concern remains unresolved before judge qualification.', 'Runtime alignment and application are not established. Ordinary-reference eligibility is not passing-answer status or judge qualification.'], 'applied': False, 'originals_modified': False, 'new_human_approval_claimed': False, 'promotion_authorized': False, 'qualification_complete': False, 'g6_closed': False}

def check(candidate, read=disk_read):
    require(canonical(candidate) == canonical(derive(read=read)), 'binding differs from exact pinned derivation')
    return True

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--check', type=Path)
    parser.add_argument('--live-sources', action='store_true', help='explicitly read pinned historical paths instead of local blobs')
    args = parser.parse_args()
    reader = disk_read if args.live_sources else blob_reader()
    if args.check:
        check(decode(args.check.read_bytes()), read=reader)
        print(json.dumps({'valid': True, 'version': VERSION, 'mode': 'live' if args.live_sources else 'local_blobs'}))
    else:
        print(json.dumps(derive(read=reader), ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False))

if __name__ == '__main__':
    main()
