nyxus_histories.py

verification/tools/nyxus_histories.py

nyxus_histories.py782 lines← SDK documentation
1#!/usr/bin/env python32"""Probe a source-exact, permission-carrying Nyxus history component."""3import native_sdk4from pathlib import Path5import argparse6import datetime7import fcntl8import hashlib9import json10import math11import os12import re13import signal14import subprocess15import sys16import time17import tomllib18import uuid1920import creusot21import creusot_report22import checkpoint_seal23import kani24import kani_obligations25import native_witness26import provider_resource27import run_receipt28import trusted_items2930ROOT = creusot.ROOT31PROOFS = ROOT / 'verification/proofs/nyxus-histories'32PRODUCT = kani.PLATFORM / 'transient.rs'33PIN = Path(__file__).with_suffix('.toml')34EXPECTED = {name + '/proof.json': 'vc_' + name for name in35    ('issue_counter_checked', 'return_counter_checked', 'owning_ledger', 'owning_witness')}36EXPECTED.update({'lists/' + name + '/proof.json': 'vc_' + name for name in37    ('owning_prepend', 'populated_witness', 'empty_witness')})38EXPECTED['lists/impl_AllocatorHeap/link_page_checked/proof.json'] = 'vc_link_page_checked'39ORIGINAL = {}40SCOPE = ('native64 little-endian conditional Perm-based component for isolated live_spans increment/decrement statements, '41    'generic noncopy supplied byte-capability map and issued-identity metadata ledger; '42    'caller count==metadata.len premise, no authoritative all-outstanding-ticket invariant; checked owning two-cell caller; '43    'one actual page-bin prepend with supplied distinct new/header permissions and opaque tail; '44    'NOT complete acquire/release, free forest, populated bins, PageSource/origin, '45    'whole page ownership/final-return or Rust alias/provenance theorem; original raw-target '46    'frontend rejection stays OPEN, uncalled no-contract bodies suppressed for erasure comparison only')47BASE_PATH = '/run/current-system/sw/bin:/usr/bin:/bin'48KANI_SCOPE = ('native64 isolated actual counter statements and actual PageHeader, all valid u16 increments '49    'then decrement, arbitrary bitmap/summaries/band and null links framed; actual stack header origin; '50    'default Kani bounds/safety/unwind checks, not Rust alias validity, physical page/forest or history theorem')51NATIVE_SCOPE = ('finite actual complete SDK transient AllocatorHeap<2,1> and AllocatorHeap<3,2> (Heap/HintedHeap), two byte patterns and '52    'all three hinted priorities; 16 histories of page-list middle/tail unlink/rebin/final return and '53    'full/partial/reused slab slots, exact observed live/free/reserved and slab live/free/bump partitions '54    'and exactly-once active memberships; real noncopy Global page provider, only requested prefixes '55    'initialized/read, no initialization-state oracle; native/compiler/std/allocator/OS TCB, no universal proof')56KANI_SUITES = {'counter': 'counter_native', 'counter-negative': 'counter_negative'}57NEGATIVE = 'NEGATIVE_CONTROL_NYXUS_HISTORY_COUNTER'58SEMANTICS = {59    'count-negative': ('ledger.rs', '    proof_assert!((**header_token).val().live_spans == 2u16);',60        '    proof_assert!((**header_token).val().live_spans == 3u16);', 'owning_ledger'),61    'issued-negative': ('ledger.rs', '    proof_assert!((**header_token).val().live_spans == 1u16 && pool.issued.contains(3usize));',62        '    proof_assert!(pool.issued.is_empty());', 'owning_ledger'),63    'reuse-negative': ('ledger.rs', '    proof_assert!((**header_token).val().live_spans == 2u16 && pool.issued.contains(2usize) && pool.issued.contains(3usize));',64        '    proof_assert!(pool.free.contains(2usize));', 'owning_ledger'),65    'image-negative': ('ledger.rs', '    proof_assert!(image[0]@ == Some(0x51u8));',66        '    proof_assert!(image[0]@ == Some(0xffu8));', 'owning_witness'),67    'prepend-negative': ('lists.rs', '    proof_assert!(metadata(*initial_page, (**page_token).val()));',68        '    proof_assert!(!populated || (**page_token).val().next.is_null_logic());', 'lists/owning_prepend'),69    'tail-negative': ('lists.rs', '    proof_assert!((**head_token).val().next == tail);',70        '    proof_assert!(!populated || (**head_token).val().next != tail);', 'lists/owning_prepend'),71}72ERASURES = {73    'erasure-issue': ('ledger.rs', ').live_spans += 1;', ').live_spans += 2;', 'ledger::issue_counter_checked'),74    'erasure-return': ('ledger.rs', ').live_spans -= 1;', ').live_spans -= 2;', 'ledger::return_counter_checked'),75    'erasure-prepend': ('lists.rs', ').next = self.pages[band][order];', ').next = core::ptr::null_mut();',76        'ledger::lists::<impl AllocatorHeap<2, 1>>::link_page_checked'),77}78FRONTIERS = ('raw-source-open', 'raw-place-open')79PROOF_ACTIONS = ('kernel', *SEMANTICS, *ERASURES, 'ticket-move', *FRONTIERS)80ACTIONS = (*KANI_SUITES, *PROOF_ACTIONS, 'source-control', 'native')81NATIVE64 = '#[cfg(not(all(target_pointer_width="64",target_endian="little")))] compile_error!("native64 little-endian required");\n'828384def pinned(): return tomllib.loads(PIN.read_text())858687def inputs(native=False):88    paths = [PRODUCT, PRODUCT.with_name('allocation.rs'), *sorted(p for p in PROOFS.rglob('*') if p.is_file()),89        *sorted(p for p in (ROOT / 'verification/tools').rglob('*') if p.is_file()90                and p.suffix in ('.py', '.toml', '.patch', '.nix'))]91    if native: paths += [ROOT / 'tools/env.sh', ROOT / 'cdk-rsx/tools/env.sh']92    return paths939495def snapshot(native=False): return {str(p.relative_to(ROOT)): kani.sha(p) for p in inputs(native)}969798def same_json(actual, expected):99    """Canonical declarations keep JSON booleans distinct from numeric flags."""100    try:101        return json.dumps(actual, sort_keys=True, allow_nan=False) == json.dumps(expected, sort_keys=True, allow_nan=False)102    except (TypeError, ValueError):103        return False104105106def constant(raw, signature):107    kani.require(raw.count(signature) == 1, 'Ambiguous history constant')108    start = raw.index(signature)109    item = raw[start:raw.index(';', start) + 1]110    kani.require('\n' not in item and '{' not in item and '}' not in item, 'History constant is no longer a scalar declaration')111    return item112113114def link_projection(raw):115    original = provider_resource.complete_item(raw, '    unsafe fn link_page(')116    old = '                (*self.pages[band][order]).previous = page;'117    new = '                let existing_head = self.pages[band][order];\n                (*existing_head).previous = page;'118    kani.require(original.count(old) == 1 and 'existing_head' not in original, 'Page-link projection anchor changed')119    projected = original.replace(old, new)120    kani.require(projected.count(new) == 1 and projected.replace(new, old) == original,121        'Page-link projection is not exactly reversible')122    return projected123124125def heap_projection(raw):126    original = provider_resource.complete_item(raw, 'pub struct AllocatorHeap<')127    old, new = '    partial:', '    partial_heads:'128    kani.require(original.count(old) == 1 and 'partial_heads' not in original, 'Heap field projection changed')129    projected = original.replace(old, new)130    kani.require(projected.replace(new, old) == original, 'Heap field projection is not reversible')131    return projected132133134def checked_texts(action='kernel'):135    texts = {name: (PROOFS / 'creusot' / name).read_text() for name in ('ledger.rs', 'lists.rs')}136    if action in SEMANTICS:137        name, anchor, statement, _ = SEMANTICS[action]138        kani.require(texts[name].count(anchor) == 1, 'Semantic control anchor changed')139        texts[name] = texts[name].replace(anchor, anchor + '\n' + statement)140    elif action in ERASURES:141        name, old, new, _ = ERASURES[action]142        kani.require(texts[name].count(old) == 1, 'Erasure control anchor changed')143        texts[name] = texts[name].replace(old, new)144    elif action == 'ticket-move':145        anchor = '    let second_ticket = unsafe { issue_counter_checked('146        kani.require(texts['ledger.rs'].count(anchor) == 1, 'Ticket move anchor changed')147        texts['ledger.rs'] = texts['ledger.rs'].replace(anchor,148            '    let moved_once = first_ticket;\n    let moved_twice = first_ticket;\n    let first_ticket = moved_twice;\n' + anchor)149    elif action == 'raw-place-open':150        old = '                let existing_head = self.pages[band][order];\n'151        kani.require(texts['lists.rs'].count(old) == 1, 'Direct-place diagnostic anchor changed')152        texts['lists.rs'] = texts['lists.rs'].replace(old, '').replace(153            'Perm::as_mut(existing_head,', 'Perm::as_mut(self.pages[band][order],')154    else: kani.require(action in ('kernel', 'raw-source-open'), 'Unknown history proof mode')155    return texts156157158def sources(action='kernel'):159    raw = PRODUCT.read_text()160    kani.require(kani.sha(PRODUCT) == pinned()['product_sha256'], 'History source changed')161    header = '#[repr(C)]\n' + provider_resource.complete_item(raw, 'struct PageHeader {')162    constants = '\n'.join(constant(raw, signature) for signature in163        ('pub const PAGE:', 'const MIN_BLOCK:', 'const CELLS:', 'const TREE_BITS:', 'const TREE_WORDS:',164         'const CLASSES:', 'const ORDERS:', 'const SLAB_RESERVED:'))165    bodies = {}166    for name, statement in (('issue_counter', '(*page).live_spans += 1;'), ('return_counter', '(*page).live_spans -= 1;')):167        kani.require(raw.count(statement) == 1, 'Counter statement changed or ambiguous')168        annotation = '' if action == 'raw-source-open' else '#[creusot_std::prelude::trusted]\n'169        bodies[name] = (annotation + 'unsafe fn ' + name170            + '(page: *mut PageHeader) { unsafe { ' + statement + ' } }\n')171    link = provider_resource.complete_item(raw, '    unsafe fn link_page(') if action == 'raw-place-open' else link_projection(raw)172    root = ('#![allow(dead_code,unused_imports)]\n' + NATIVE64 + 'use core::ptr;\n' + constants + '\n' + header + '\n'173        + '#[repr(C, align(16))]\n' + provider_resource.complete_item(raw, 'struct Slab {') + '\n'174        + heap_projection(raw) + '\n'175        + constant(raw, 'pub type Heap =') + '\n' + ''.join(bodies.values())176        + 'impl Heap {\n' + annotation + link + '\n}\nmod ledger;\n')177    texts = checked_texts(action)178    proof = '\n'.join(texts.values())179    kani.require(not trusted_items.trusted_functions(proof) and all(word not in proof for word in180        ('Ghost::conjure', '#[trusted]', '#[ignore]', 'extern_spec!', 'kani::assume', 'requires(false)')),181        'Unregistered history assumption')182    ordinary = re.sub(r'#\[erasure\([^\n]+\)\]', '', proof)183    kani.require(not any(token.text in {*bodies, 'link_page'} for token in kani_obligations.tokens(ordinary)),184        'Checked history called an unproved original target')185    allowed = [] if action == 'raw-source-open' else ['issue_counter', 'return_counter', 'link_page']186    kani.require(trusted_items.trusted_functions(root) == allowed187        and all(word not in root for word in ('#[requires', '#[ensures')), 'Original erasure-only target contract changed')188    result = {'src/lib.rs': root.encode()}189    result.update({'src/' + name: text.encode() for name, text in texts.items()})190    result.update({name: (PROOFS / 'creusot' / name).read_bytes() for name in ('Cargo.toml', 'Cargo.lock', 'why3find.json')})191    return result192193194def declaration(output, action='kernel'):195    identity = creusot.TOOL.resolve().name196    env = {'PATH': str(creusot.TOOL / 'bin') + ':/run/current-system/sw/bin:/usr/bin:/bin',197        'LC_ALL': 'C', 'LANG': 'C', 'TZ': 'UTC', 'RUSTUP_AUTO_INSTALL': '0', 'PYTHONDONTWRITEBYTECODE': '1',198        'CARGO_NET_OFFLINE': 'true', 'CARGO_HOME': str(creusot.INSTALL / 'cargo-home'),199        'CARGO_TARGET_DIR': str(creusot.INSTALL / 'targets' / identity),200        'XDG_CACHE_HOME': str(creusot.INSTALL / 'cache' / identity), 'XDG_CONFIG_HOME': str(creusot.INSTALL / 'config')}201    commands = [[str(creusot.TOOL / 'bin/cargo-creusot'), 'creusot', '--erasure-check=error', '-j', '1',202            'ledger', '--only=coma', '--', '--locked', '--offline'],203        [str(creusot.TOOL / 'bin/cargo-creusot'), 'creusot', '--only=prove', '-j', '1',204            'ledger', '--', '--locked', '--offline']]205    short = action in ERASURES or action in FRONTIERS or action == 'ticket-move'206    if short: commands = commands[:1]207    scope = SCOPE208    if action == 'raw-source-open':209        scope = 'OPEN diagnostic: actual original raw counter body without contracts/body suppression; expected frontend raw-dereference rejection; no semantic export'210    elif action == 'raw-place-open':211        scope = 'OPEN diagnostic: direct original indexed assignment-place comparison; contractless uncalled raw bodies, supplied Perms, field-label-only projection; no semantic export'212    projection = ('DIRECT original indexed LHS; only partial->partial_heads field-label reverse checked'213        if action == 'raw-place-open' else 'one link_page raw LHS local and partial->partial_heads field label; exact reverses checked')214    return {'scope': scope, 'commands': commands, 'cwd': str(output), 'environment': env, 'target': kani.PIN['target'],215        'execution_profile': {'kind': 'history-permission-component', 'action': action, 'why3_seconds': 5.0, 'why3_depth': 6,216            'jobs': 1, 'strict_erasure': True, 'cargo_configuration': 'absent in CARGO_HOME and cwd ancestors',217            'raw_source_bridge': 'OPEN raw frontend and direct indexed-place erasure; no-contract targets uncalled/erasure-only',218            'source_projection': projection,219            'process_seconds': [180] if short else [180, 240], 'process_group': 'private session; kill group on deadline',220            'expected': EXPECTED, 'originals': ORIGINAL}}221222223def validate(output, metadata, action='kernel'):224    validate_component(output, metadata, action)225226227def execute(argv, cwd, environment, seconds, log_path):228    record = {'argv': list(argv), 'cwd': str(Path(cwd).resolve()), 'environment': dict(environment),229        'seconds_limit': seconds, 'timed_out': False}230    started = time.monotonic()231    with log_path.open('w') as log:232        process = subprocess.Popen(argv, cwd=cwd, env=environment, stdin=subprocess.DEVNULL,233            stdout=log, stderr=subprocess.STDOUT, start_new_session=True)234        try:235            process.wait(timeout=seconds)236        except subprocess.TimeoutExpired:237            record['timed_out'] = True238            try: os.killpg(process.pid, signal.SIGKILL)239            except ProcessLookupError: pass240            process.wait()241    record.update(actual_exit=process.returncode, elapsed_seconds=time.monotonic() - started)242    return record243244245def validate_translation_control(output, action, code):246    log = (output / 'translate.log').read_text()247    if action in ERASURES:248        creusot.require_erasure_rejection(log, code, ERASURES[action][3])249    elif action == 'raw-source-open':250        designated_compiler_rejection(log, code, 'error: Dereference of a raw pointer is forbidden in creusot: '251            'use `creusot_std::ghost::perm::Perm<*const T>` instead')252        kani.require('(*page).live_spans += 1;' in log, 'Different original raw-source frontier diagnostic')253    elif action == 'raw-place-open':254        creusot.require_erasure_rejection(log, code, ERASURES['erasure-prepend'][3])255        kani.require('#[erasure] expression (read)' in log and 'target expression (Assign(Plain))' in log,256            'Different indexed-place frontier diagnostic')257    else:258        kani.require(action == 'ticket-move', 'Unknown translation control')259        text = checked_texts(action)['ledger.rs']260        line = next(n for n, row in enumerate(text.splitlines(), 1) if 'let moved_twice = first_ticket;' in row)261        designated_compiler_rejection(log, code, 'error[E0382]: use of moved value: `first_ticket`')262        kani.require('src/ledger.rs:' + str(line) + ':' in log, 'Different noncopy-ticket move diagnostic')263264265def designated_compiler_rejection(log, code, designated):266    log = creusot.diagnostic_text(log)267    errors = [line.strip() for line in log.splitlines() if re.match(r'\s*(?:error(?:\[[^]]+\])?:|Error:)', line)]268    kani.require(type(code) is int and code == 1 and len(errors) == 3 and errors[0] == designated269        and errors[1].startswith('error: could not compile `nyxus-histories` (lib) due to 1 previous error')270        and creusot.one_error_compiler_summary(errors[1]) and errors[2] == 'Error: Compilation failed',271        'Different complete designated compiler diagnostics')272    creusot.require_no_fatal_diagnostics(log, errors)273274275def probe(action='kernel'):276    original, before = run_receipt.checkout(ROOT), snapshot()277    creusot.validate_source()278    tools = creusot.validate_binaries()279    kani.require(original == run_receipt.checkout(ROOT), 'Original history identity changed during authentication')280    output = creusot.TEMP / ('nyxus-histories-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')281        + '-' + action + '-' + uuid.uuid4().hex[:8])282    output.mkdir()283    files = sources(action)284    for name, data in files.items():285        path = output / name286        path.parent.mkdir(parents=True, exist_ok=True)287        path.write_bytes(data)288    profile = declaration(output, action)289    receipt = run_receipt.write(ROOT, output, {**original, 'sources': before, 'suite': action,290        'staged': {name: kani.sha(output / name) for name in files}, 'binaries': tools, **profile})291    def unchanged():292        receipt.verify()293        kani.require(before == snapshot() and tools == creusot.validate_binaries(), 'History probe inputs changed')294        validate(output, json.loads(receipt.original), action)295    unchanged()296    print('Nyxus history', action, output, flush=True)297    translation = execute(profile['commands'][0], profile['cwd'], profile['environment'],298        profile['execution_profile']['process_seconds'][0], output / 'translate.log')299    (output / 'execution.json').write_text(json.dumps({'translation': translation}) + '\n')300    unchanged()301    if action in ERASURES or action in FRONTIERS or action == 'ticket-move':302        kani.require(not translation['timed_out'], 'Translation control timed out')303        validate_translation_control(output, action, translation['actual_exit'])304        result = {'suite': action, 'actual_exit': translation['actual_exit']}305        result.update(frontier='OPEN' if action in FRONTIERS else 'designated rejection')306        return seal(output, result)307    kani.require(translation['actual_exit'] == 0 and not translation['timed_out'], 'History strict translation failed')308    creusot.require_no_fatal_diagnostics((output / 'translate.log').read_text(), ())309    root = output / 'verif/nyxus_histories_rlib'310    inventory = creusot_report.goal_inventory(root / 'ledger', EXPECTED, creusot.TOOL / 'bin/why3',311        translation_root=root, original_source_goals=ORIGINAL,312        load_paths=[creusot.TOOL / 'share/why3find/packages/creusot'], config=creusot.TOOL / 'creusot_why3.conf',313        cwd=output, env=profile['environment'], output_dir=output / 'goal-inventory')314    (output / 'goal-inventory.json').write_text(json.dumps({'goals': {k: sorted(v) for k,v in inventory.goals.items()},315        'inputs': inventory.hashes, 'originals': {k: sorted(v) for k,v in inventory.original_source_goals.items()}}, indent=2) + '\n')316    proof = execute(profile['commands'][1], profile['cwd'], profile['environment'],317        profile['execution_profile']['process_seconds'][1], output / 'prove.log')318    (output / 'execution.json').write_text(json.dumps({'translation': translation, 'proof': proof}) + '\n')319    unchanged(); inventory.verify()320    kani.require(not proof['timed_out'], 'History proof process timed out')321    if action in SEMANTICS:322        expected = SEMANTICS[action][3]323        creusot.require_logical_rejection((output / 'prove.log').read_text(), proof['actual_exit'], 'vc_' + expected.rsplit('/',1)[-1])324        summary = creusot_report.validate_negative_directory(root / 'ledger', inventory, EXPECTED, expected + '/proof.json')325    else:326        kani.require(proof['actual_exit'] == 0, 'History component proof remained open')327        creusot.require_no_fatal_diagnostics((output / 'prove.log').read_text(), ())328        summary = creusot_report.validate_directory(root / 'ledger', inventory, expected=EXPECTED)329    return seal(output, {'suite': action, 'translation_exit': translation['actual_exit'],330        'actual_exit': proof['actual_exit'], 'summary': summary, 'raw_source_bridge': 'OPEN'})331332333def counter_sources():334    raw = PRODUCT.read_text()335    kani.require(kani.sha(PRODUCT) == pinned()['product_sha256'], 'Counter source changed')336    constants = '\n'.join(constant(raw, signature) for signature in337        ('pub const PAGE:', 'const MIN_BLOCK:', 'const CELLS:', 'const TREE_BITS:', 'const TREE_WORDS:'))338    header = '#[repr(C)]\n' + provider_resource.complete_item(raw, 'struct PageHeader {')339    targets = ''340    for name, statement in (('issue_counter', '(*page).live_spans += 1;'), ('return_counter', '(*page).live_spans -= 1;')):341        kani.require(raw.count(statement) == 1, 'Changed counter body')342        targets += 'unsafe fn ' + name + '(page:*mut PageHeader){unsafe{' + statement + '}}\n'343    root = ('#![allow(dead_code,unexpected_cfgs)]\n' + NATIVE64 + 'use core::ptr;\n' + constants + '\n' + header + '\n'344        + targets + 'mod witness { include!(' + json.dumps(str(PROOFS / 'kani.rs')) + '); }\nfn main(){}\n')345    return {'main.rs': root.encode()}346347348def counter_declaration(action, output):349    toolchain = kani.KANI / 'toolchain/bin'350    env = {'PATH': str(toolchain) + ':' + BASE_PATH, 'LC_ALL': 'C', 'LANG': 'C', 'TZ': 'UTC',351        'RUSTUP_AUTO_INSTALL': '0', 'PYTHONDONTWRITEBYTECODE': '1', 'CARGO_NET_OFFLINE': 'true',352        'KANI_HOME': str(kani.TEMP / kani.PIN['home_dir']), 'RUSTUP_HOME': str(kani.TEMP / 'rustup'),353        'RUSTUP_TOOLCHAIN': kani.PIN['rust_toolchain'], 'RUSTC': str(toolchain / 'rustc'), 'CARGO': str(toolchain / 'cargo'),354        'CARGO_HOME': str(kani.TEMP / 'nyxus-histories-cargo-home'), 'CARGO_INCREMENTAL': '0',355        'RUSTFLAGS': '--edition=2024 -A dead_code --check-cfg=cfg(test)', 'TMPDIR': str(output / 'temp')}356    command = [str(kani.LAUNCHER / 'kani'), str(output / 'main.rs'), '--target-dir', str(output / 'target'),357        '-Z', 'unstable-options', '--harness-timeout', '90s', '--export-json', str(output / 'result.json'),358        '--jobs', '1', '--output-format', 'terse', '--exact', '--harness', 'witness::' + KANI_SUITES[action]]359    return {'scope': KANI_SCOPE, 'commands': [command], 'cwd': str(ROOT), 'environment': env, 'target': kani.PIN['target'],360        'execution_profile': {'harness_seconds': 90, 'process_seconds': [90], 'unwind': 4, 'jobs': 1,361            'default_safety_checks': True, 'unwinding_assertions': True, 'process_group': 'private session; kill group on deadline'}}362363364def counter_manifest(action):365    name = KANI_SUITES[action]366    return {'files': pinned()['kani_files'], 'suites': {'nyxus-histories-' + action: {367        'witness::' + name: ['nyxus-histories/kani.rs::counter_pair', 'nyxus-histories/kani.rs::' + name]}}}368369370def native_sources():371    body = PRODUCT.read_bytes()372    kani.require(kani.sha(PRODUCT) == pinned()['product_sha256'], 'Native actual source changed')373    appended = b'\npub mod native_cases { include!("native_fixture.rs"); }\n'374    main = ('#![feature(allocator_ext)]\n#![allow(dead_code)]\n' + NATIVE64 + 'extern crate core;\n'375        'mod allocation;\nmod transient;\nfn main(){transient::native_cases::native_all();}\n')376    return {'main.rs': main.encode(), 'transient.rs': body + appended,377        'allocation.rs': PRODUCT.with_name('allocation.rs').read_bytes(), 'native_fixture.rs': (PROOFS / 'native.rs').read_bytes()}378379380def native_compiler():381    compiler = native_witness.compiler_identity()382    inventory = kani.kani_install.rust_inventory(Path(compiler['path']).parent.parent, kani.PIN['target'])383    return {**compiler, 'native_sysroot_sha256': kani.kani_install.digest(inventory), 'native_sysroot_entries': len(inventory)}384385386def native_declaration(output):387    compiler = native_witness.equality_bridge.production_compiler().resolve()388    env = {'PATH': str(compiler.parent) + ':' + BASE_PATH, 'LC_ALL': 'C', 'LANG': 'C', 'TZ': 'UTC',389        'RUSTUP_AUTO_INSTALL': '0', 'PYTHONDONTWRITEBYTECODE': '1', 'RUSTC': str(compiler),390        'RUSTDOC': str(compiler.parent / 'rustdoc'), 'RUSTUP_HOME': str(compiler.parents[3]),391        'CARGO_HOME': str(kani.TEMP / 'product-cargo-home'), 'CARGO_TARGET_DIR': str(output / 'target'),392        'CARGO_NET_OFFLINE': 'true', 'CARGO_UNSTABLE_CHECKSUM_FRESHNESS': 'true', 'CARGO_BUILD_FINGERPRINT': 'content',393        'RUSTFLAGS': '-Cpanic=unwind', 'TMPDIR': str(output / 'temp')}394    commands = [[str(compiler), '--edition=2024', '--target', kani.PIN['target'], '-Cpanic=unwind',395        str(output / 'main.rs'), '-o', str(output / 'witness')], [str(output / 'witness')]]396    return {'scope': NATIVE_SCOPE, 'commands': commands, 'cwd': str(output), 'environment': env, 'target': kani.PIN['target'],397        'execution_profile': {'kind': 'finite-native-source-complement', 'process_seconds': [180, 30],398            'histories': 16, 'process_group': 'private session; kill group on deadline'}}399400401def write_sources(output, files):402    for name, data in files.items():403        path = output / name404        path.parent.mkdir(parents=True, exist_ok=True)405        path.write_bytes(data)406407408def validate_simple(output, metadata, action):409    validate_component(output, metadata, action)410411412def counter_probe(action):413    original, before = run_receipt.checkout(ROOT), snapshot()414    tool = kani.kani_install.capture(kani.TEMP)415    kani.require(original == run_receipt.checkout(ROOT), 'Counter source identity changed during authentication')416    output = kani.TEMP / ('nyxus-histories-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')417        + '-' + action + '-' + uuid.uuid4().hex[:8])418    output.mkdir(); (output / 'temp').mkdir()419    files, profile, manifest = counter_sources(), counter_declaration(action, output), counter_manifest(action)420    write_sources(output, files)421    receipt = run_receipt.write(ROOT, output, {**original, 'sources': before, 'suite': action,422        'staged': {name: kani.sha(output / name) for name in files}, 'binaries': tool, 'authored_inventory': manifest, **profile})423    def unchanged():424        receipt.verify()425        kani.require(before == snapshot(), 'Counter sources/imports changed')426        validate_simple(output, json.loads(receipt.original), action)427    unchanged(); kani.environment()428    print('Nyxus counter', action, output, flush=True)429    result = execute(profile['commands'][0], profile['cwd'], profile['environment'], 90, output / 'run.log')430    (output / 'execution.json').write_text(json.dumps(result) + '\n')431    unchanged(); kani.kani_install.verify(tool, kani.TEMP)432    kani.require(not result['timed_out'], 'Counter process timed out')433    suite, harness = 'nyxus-histories-' + action, 'witness::' + KANI_SUITES[action]434    kani.EXPECTED_HARNESSES[suite] = {harness}435    if action == 'counter-negative': kani.NEGATIVE_CONTROLS[suite] = NEGATIVE436    summary = kani.validate_run(output, suite, result['actual_exit'], manifest=manifest)437    clauses = kani_obligations.required(suite, {harness}, manifest=manifest)438    return seal(output, {'suite': action, 'actual_exit': result['actual_exit'], 'summary': summary,439        'authored_obligations': len(clauses[harness])})440441442def native_probe():443    original, before = run_receipt.checkout(ROOT), snapshot(native=True)444    compiler = native_compiler()445    kani.require(original == run_receipt.checkout(ROOT), 'Native identity changed during compiler authentication')446    output = kani.TEMP / ('nyxus-histories-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')447        + '-native-' + uuid.uuid4().hex[:8])448    output.mkdir()449    files, profile = native_sources(), native_declaration(output)450    write_sources(output, files)451    supplied, external = native_sdk.native_environment(output, Path(compiler['path']))452    for key in ('RUSTC', 'RUSTDOC', 'RUSTUP_HOME', 'CARGO_HOME', 'CARGO_TARGET_DIR', 'TMPDIR',453            'CARGO_UNSTABLE_CHECKSUM_FRESHNESS', 'CARGO_BUILD_FINGERPRINT', 'RUSTFLAGS'):454        kani.require(supplied[key] == profile['environment'][key], 'Supplied native environment differs')455    binaries = {'compiler': compiler, 'environment_sources': external}456    receipt = run_receipt.write(ROOT, output, {**original, 'sources': before, 'suite': 'native',457        'staged': {name: kani.sha(output / name) for name in files}, 'binaries': binaries, **profile})458    def unchanged():459        receipt.verify()460        kani.require(before == snapshot(native=True) and compiler == native_compiler(), 'Native source/tool closure changed')461        validate_simple(output, json.loads(receipt.original), 'native')462    unchanged()463    print('Nyxus native', output, flush=True)464    results = []465    for index, (command, seconds) in enumerate(zip(profile['commands'], [180, 30])):466        result = execute(command, profile['cwd'], profile['environment'], seconds, output / ('compile.log' if index == 0 else 'run.log'))467        results.append(result)468        (output / 'execution.json').write_text(json.dumps(results, indent=2) + '\n')469        unchanged()470        kani.require(result['actual_exit'] == 0 and not result['timed_out'], 'Actual native phase failed')471        if index == 0: artifact = native_witness.executable_hash(output / 'witness')472    kani.require((output / 'run.log').read_text() == 'NYXUS_HISTORY_ACTUAL_NATIVE_OK\n', 'Wrong actual native witness')473    native_witness.executable_hash(output / 'witness', artifact)474    creusot.require_no_fatal_diagnostics((output / 'compile.log').read_text(), ())475    return seal(output, {'suite': 'native', 'actual_exits': [r['actual_exit'] for r in results],476        'artifact_sha256': artifact, 'histories': 16})477478479def component_declaration(action, output):480    if action in PROOF_ACTIONS: return declaration(output, action)481    if action in KANI_SUITES: return counter_declaration(action, output)482    if action == 'native': return native_declaration(output)483    if action == 'source-control':484        python = str(Path('/run/current-system/sw/bin/python3').resolve())485        return {'scope': 'independent child rejects an altered selected original counter body before compilation',486            'commands': [[python, str(Path(__file__)), '--probe-source', str(output)]], 'cwd': str(ROOT),487            'environment': {'PATH': BASE_PATH, 'LC_ALL': 'C', 'LANG': 'C', 'TZ': 'UTC',488                'PYTHONDONTWRITEBYTECODE': '1', 'RUSTUP_AUTO_INSTALL': '0'}, 'target': kani.PIN['target'],489            'execution_profile': {'kind': 'source-correspondence-child', 'process_seconds': [30],490                'process_group': 'private session; kill group on deadline'}}491    kani.require(action == 'cohort', 'Unknown component declaration')492    return {'scope': 'separate conditional supplied-permission/identity-metadata counter kernel, local prepend, native complements and controls; complete allocator history/raw semantic bridge OPEN',493        'commands': [], 'cwd': str(ROOT), 'environment': {}, 'target': kani.PIN['target'],494        'execution_profile': {'kind': 'artifact-aggregation', 'components': list(ACTIONS)}}495496497def component_sources(action, output):498    if action in PROOF_ACTIONS: return sources(action)499    if action in KANI_SUITES: return counter_sources()500    if action == 'native': return native_sources()501    if action == 'source-control':502        files = sources()503        old, new = b'(*page).live_spans += 1;', b'(*page).live_spans += 2;'504        kani.require(files['src/lib.rs'].count(old) == 1, 'Source control anchor changed')505        files['src/lib.rs'] = files['src/lib.rs'].replace(old, new)506        return files507    kani.require(action == 'cohort', 'Unknown component stage')508    mapping = json.loads((output / 'cohort-map.json').read_text())509    entries = []510    for item in mapping['results']:511        directory = Path(item['output'])512        metadata = json.loads((directory / 'inputs.json').read_text())513        record = checkpoint_seal.verify(directory, item['seal_sha256'], factory=mapping['factory'],514            sdk=mapping['sdk'], tools=metadata['binaries'])515        entries.append({**record['qualification'], 'output': str(directory), 'seal_sha256': item['seal_sha256']})516    value = {'factory': mapping['factory'], 'sdk': mapping['sdk'], 'factory_status': '', 'sdk_status': '', 'results': entries}517    return {'cohort-map.json': (json.dumps(value, indent=2) + '\n').encode()}518519520def cohort_binaries(results, *, factory, sdk):521    kani.require([item['suite'] for item in results] == list(ACTIONS), 'Noncanonical complete cohort actions')522    binaries = {}523    for item in results:524        directory = Path(item['output'])525        metadata = json.loads((directory / 'inputs.json').read_text())526        record = checkpoint_seal.verify(directory, item['seal_sha256'], factory=factory, sdk=sdk, tools=metadata['binaries'])527        kani.require(record['qualification']['suite'] == metadata['suite'] == item['suite'], 'Cohort child action differs')528        binaries[item['suite']] = metadata['binaries']529    return binaries530531532def validate_component(output, metadata, action):533    output = Path(output)534    kani.require(output.is_dir() and all(not parent.is_symlink() for parent in (output, *output.parents)),535        'Symlinked history component directory')536    profile = component_declaration(action, output)537    kani.require(metadata.get('suite') == action, 'Recorded component action differs')538    if action in KANI_SUITES:539        kani.require(same_json(metadata.get('authored_inventory'), counter_manifest(action)),540            'Recorded authored counter inventory differs')541    keys = set(profile)542    kani.require(set(metadata) & (keys | {'command'}) == keys and all(same_json(metadata[k], v) for k,v in profile.items()),543        'Canonical complete history component profile differs')544    files = component_sources(action, output)545    kani.require(metadata['staged'] == {k: hashlib.sha256(v).hexdigest() for k,v in files.items()}546        and all(run_receipt.regular(output / k) and (output / k).read_bytes() == v for k,v in files.items()),547        'Canonical complete history component stage differs')548    if action in PROOF_ACTIONS or action == 'source-control':549        kani.require((output / 'src').is_dir() and not (output / 'src').is_symlink(), 'Symlinked history source directory')550        actual = {p.relative_to(output).as_posix() for p in (output / 'src').rglob('*') if p.is_file()}551        kani.require(actual == {k for k in files if k.startswith('src/')}552            and not any(p.is_symlink() for p in (output / 'src').rglob('*'))553            and not any((output / name).exists() or (output / name).is_symlink()554                for name in ('.cargo', 'build.rs', 'tests', 'examples', 'benches')), 'Unlisted history source input')555        # Source controls invoke Python, not Cargo; retain the same project/config boundary.556        home = creusot.INSTALL / 'cargo-home'557        candidates = [home / name for name in ('config', 'config.toml')]558        candidates += [base / '.cargo' / name for base in (output, *output.parents) for name in ('config', 'config.toml')]559        candidates += [base / name for base in (output, *output.parents) for name in ('rust-toolchain', 'rust-toolchain.toml')]560        kani.require(not any(p.exists() or p.is_symlink() for p in candidates), 'Unlisted effective Cargo configuration')561    elif action != 'cohort':562        kani.require({p.name for p in output.glob('*.rs')} == set(files), 'Unlisted standalone Rust input')563    else:564        mapping = json.loads((output / 'cohort-map.json').read_text())565        kani.require(same_json(metadata['binaries'], cohort_binaries(mapping['results'], factory=mapping['factory'], sdk=mapping['sdk'])),566            'Recorded aggregate tool map differs')567568569def verify_execution(record, profile, index):570    keys = {'argv', 'cwd', 'environment', 'seconds_limit', 'timed_out', 'actual_exit', 'elapsed_seconds'}571    kani.require(set(record) == keys and record['argv'] == profile['commands'][index]572        and record['cwd'] == str(Path(profile['cwd']).resolve()) and record['environment'] == profile['environment']573        and same_json(record['seconds_limit'], profile['execution_profile']['process_seconds'][index])574        and type(record['timed_out']) is bool and not record['timed_out'] and type(record['actual_exit']) is int575        and type(record['elapsed_seconds']) in (int, float) and math.isfinite(record['elapsed_seconds'])576        and record['elapsed_seconds'] >= 0, 'Original actual execution record differs or timed out')577578579def validate_execution_stages(output, profile, action):580    execution = json.loads((output / 'execution.json').read_text())581    if action in PROOF_ACTIONS:582        short = action in ERASURES or action in FRONTIERS or action == 'ticket-move'583        keys = {'translation'} if short else {'translation', 'proof'}584        kani.require(type(execution) is dict and set(execution) == keys, 'Complete original process-stage inventory differs')585        for index, key in enumerate(('translation',) if short else ('translation', 'proof')):586            verify_execution(execution[key], profile, index)587    elif action == 'native':588        kani.require(type(execution) is list and len(execution) == 2, 'Complete original native-stage inventory differs')589        for index, record in enumerate(execution): verify_execution(record, profile, index)590    else: verify_execution(execution, profile, 0)591    return execution592593594def seal(output, result, external=None):595    metadata = json.loads((output / 'inputs.json').read_text())596    validate_component(output, metadata, result['suite'])597    if result['suite'] != 'cohort':598        validate_execution_stages(output, component_declaration(result['suite'], output), result['suite'])599    (output / 'accepted.json').write_text(json.dumps(result, indent=2) + '\n')600    digest = checkpoint_seal.capture(output, kind='nyxus-histories-batch12', qualification=result, external=external)601    record = {**result, 'output': str(output), 'seal_sha256': digest}602    print(json.dumps(record), flush=True)603    return record604605606def source_control():607    original, before = run_receipt.checkout(ROOT), snapshot()608    output = kani.TEMP / ('nyxus-histories-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')609        + '-source-control-' + uuid.uuid4().hex[:8])610    output.mkdir()611    action = 'source-control'612    files, profile = component_sources(action, output), component_declaration(action, output)613    write_sources(output, files)614    python = profile['commands'][0][0]615    tools = {'python': {'path': python, 'sha256': kani.sha(Path(python))}}616    receipt = run_receipt.write(ROOT, output, {**original, 'sources': before, 'suite': action,617        'staged': {k: kani.sha(output / k) for k in files}, 'binaries': tools, **profile})618    receipt.verify(); validate_component(output, json.loads(receipt.original), action)619    result = execute(profile['commands'][0], profile['cwd'], profile['environment'], 30, output / 'run.log')620    (output / 'execution.json').write_text(json.dumps(result) + '\n')621    receipt.verify(); validate_component(output, json.loads(receipt.original), action)622    kani.require(before == snapshot() and kani.sha(Path(python)) == tools['python']['sha256'], 'Source control closure changed')623    verify_execution(result, profile, 0)624    kani.require(result['actual_exit'] == 1 and (output / 'run.log').read_text()625        == 'Nyxus histories refused: Changed original source body\n', 'Different independent source refusal')626    return seal(output, {'suite': action, 'actual_exit': 1})627628629def cohort(results):630    original = run_receipt.checkout(ROOT)631    output = kani.TEMP / ('nyxus-histories-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')632        + '-cohort-' + uuid.uuid4().hex[:8])633    output.mkdir()634    tools = cohort_binaries(results, factory=original['factory'], sdk=original['sdk'])635    external = {str(Path(result['output']) / checkpoint_seal.NAME): result['seal_sha256'] for result in results}636    (output / 'cohort-map.json').write_text(json.dumps({**original, 'results': results}, indent=2) + '\n')637    receipt = run_receipt.write(ROOT, output, {**original, 'suite': 'cohort', 'sources': snapshot(native=True),638        'staged': {'cohort-map.json': kani.sha(output / 'cohort-map.json')}, 'binaries': tools,639        **component_declaration('cohort', output)})640    receipt.verify()641    return seal(output, {'suite': 'cohort', 'components': len(ACTIONS), 'actual_driver_exit': 0,642        'full_allocator_history': 'OPEN', 'raw_source_bridge': 'OPEN'}, external)643644645def reinventory(output):646    saved = json.loads((output / 'goal-inventory.json').read_text())647    root = output / 'verif/nyxus_histories_rlib'648    loads = [creusot.TOOL / 'share/why3find/packages/creusot']649    files = (creusot.TOOL / 'bin/why3', creusot.TOOL / 'creusot_why3.conf')650    before = creusot_report.input_hashes((root, *loads), files)651    kani.require(before == saved['inputs'], 'Original history translation/import closure differs')652    audit_dir = kani.TEMP / ('nyxus-histories-audit-' + uuid.uuid4().hex)653    audit_dir.mkdir()654    goals, originals = {}, {}655    for source in sorted(root.rglob('*.coma')):656        checked = source.is_relative_to(root / 'ledger')657        relative = source.relative_to(root)658        printed = audit_dir / relative.with_suffix('.why')659        printed.parent.mkdir(parents=True, exist_ok=True)660        argv = [str(files[0]), 'prove', '--print-theory', '--config=' + str(files[1]),661            '--warn-off=unused_variable,axiom_abstract,clone_not_abstract']662        for path in loads: argv += ['-L', str(path)]663        argv += [str(source)]664        # A fresh read-only goal print; its original solver reports are untouched.665        profile = declaration(output)666        with printed.open('w') as stdout, printed.with_suffix('.log').open('w') as stderr:667            result = subprocess.run(argv, cwd=output, env=profile['environment'], stdout=stdout, stderr=stderr, timeout=60)668        kani.require(result.returncode == 0, 'Fresh original history goal enumeration failed')669        names = creusot_report.theory_goals(printed.read_text())670        if checked and names:671            goals[(source.relative_to(root / 'ledger').with_suffix('') / 'proof.json').as_posix()] = sorted(names)672        elif not checked: originals[relative.as_posix()] = sorted(names)673    kani.require(goals == saved['goals'] and originals == saved['originals'] == ORIGINAL674        and set(goals) == set(EXPECTED), 'Independent complete history goal inventory differs')675    kani.require(before == creusot_report.input_hashes((root, *loads), files), 'History imports changed during audit')676    return goals677678679def audit(output, digest, *, factory, sdk):680    output = Path(output)681    metadata = json.loads((output / 'inputs.json').read_text())682    record = checkpoint_seal.verify(output, digest, factory=factory, sdk=sdk, tools=metadata['binaries'])683    kani.require(record['kind'] == 'nyxus-histories-batch12' and type(record['format']) is int,684        'Different history checkpoint kind or format')685    action = record['qualification']['suite']686    kani.require(metadata.get('factory_status') == metadata.get('sdk_status') == '', 'Original producer was not clean')687    kani.require(metadata['sources'] == snapshot(native=action in ('native', 'cohort')), 'Original history source/import closure differs')688    validate_component(output, metadata, action)689    kani.require(same_json(json.loads((output / 'accepted.json').read_text()), record['qualification']),690        'Original accepted history result differs')691    profile = component_declaration(action, output)692    if action == 'cohort':693        mapping = json.loads((output / 'cohort-map.json').read_text())694        kani.require(mapping['factory'] == factory and mapping['sdk'] == sdk and len(mapping['results']) == len(ACTIONS)695            and {r['suite'] for r in mapping['results']} == set(ACTIONS), 'Incomplete history cohort population')696        expected = {'suite': 'cohort', 'components': len(ACTIONS), 'actual_driver_exit': 0,697            'full_allocator_history': 'OPEN', 'raw_source_bridge': 'OPEN'}698        kani.require(same_json(record['qualification'], expected), 'Different aggregate history result')699        return [audit(r['output'], r['seal_sha256'], factory=factory, sdk=sdk) for r in mapping['results']]700    execution = validate_execution_stages(output, profile, action)701    if action in PROOF_ACTIONS:702        creusot.validate_source()703        kani.require(metadata['binaries'] == creusot.validate_binaries(), 'Original Creusot tools differ')704        verify_execution(execution['translation'], profile, 0)705        translation = execution['translation']['actual_exit']706        if action in ERASURES or action in FRONTIERS or action == 'ticket-move':707            kani.require(set(execution) == {'translation'}, 'Unexpected control proof stage')708            validate_translation_control(output, action, translation)709            expected = {'suite': action, 'actual_exit': translation,710                'frontier': 'OPEN' if action in FRONTIERS else 'designated rejection'}711        else:712            kani.require(set(execution) == {'translation', 'proof'} and translation == 0, 'Incomplete original history phases')713            creusot.require_no_fatal_diagnostics((output / 'translate.log').read_text(), ())714            verify_execution(execution['proof'], profile, 1)715            code, inventory = execution['proof']['actual_exit'], reinventory(output)716            root = output / 'verif/nyxus_histories_rlib/ledger'717            if action in SEMANTICS:718                name = SEMANTICS[action][3]719                creusot.require_logical_rejection((output / 'prove.log').read_text(), code, 'vc_' + name.rsplit('/',1)[-1])720                summary = creusot_report.validate_negative_directory(root, inventory, EXPECTED, name + '/proof.json')721            else:722                kani.require(code == 0, 'Original history kernel failed')723                creusot.require_no_fatal_diagnostics((output / 'prove.log').read_text(), ())724                summary = creusot_report.validate_directory(root, inventory, expected=EXPECTED)725            expected = {'suite': action, 'translation_exit': translation, 'actual_exit': code,726                'summary': summary, 'raw_source_bridge': 'OPEN'}727    elif action in KANI_SUITES:728        kani.kani_install.verify(metadata['binaries'], kani.TEMP)729        verify_execution(execution, profile, 0)730        code, key = execution['actual_exit'], 'nyxus-histories-' + action731        name, manifest = 'witness::' + KANI_SUITES[action], counter_manifest(action)732        kani.EXPECTED_HARNESSES[key] = {name}733        if action == 'counter-negative': kani.NEGATIVE_CONTROLS[key] = NEGATIVE734        summary = kani.validate_run(output, key, code, manifest=manifest)735        clauses = kani_obligations.required(key, {name}, manifest=manifest)736        expected = {'suite': action, 'actual_exit': code, 'summary': summary, 'authored_obligations': len(clauses[name])}737    elif action == 'native':738        kani.require(metadata['binaries']['compiler'] == native_compiler(), 'Original native compiler/sysroot differs')739        kani.require(all(kani.sha(Path(path)) == sha for path,sha in metadata['binaries']['environment_sources'].items()),740            'Original supplied SDK environment differs')741        kani.require(type(execution) is list and len(execution) == 2, 'Incomplete actual native phases')742        for index, result in enumerate(execution):743            verify_execution(result, profile, index)744            kani.require(result['actual_exit'] == 0, 'Original actual native failure')745        creusot.require_no_fatal_diagnostics((output / 'compile.log').read_text(), ())746        kani.require((output / 'run.log').read_text() == 'NYXUS_HISTORY_ACTUAL_NATIVE_OK\n', 'Wrong original actual native output')747        artifact = native_witness.executable_hash(output / 'witness', record['qualification']['artifact_sha256'])748        expected = {'suite': 'native', 'actual_exits': [0, 0], 'artifact_sha256': artifact, 'histories': 16}749    else:750        kani.require(action == 'source-control', 'Unknown original component')751        verify_execution(execution, profile, 0)752        python = profile['commands'][0][0]753        kani.require(metadata['binaries'] == {'python': {'path': python, 'sha256': kani.sha(Path(python))}}754            and execution['actual_exit'] == 1 and (output / 'run.log').read_text()755            == 'Nyxus histories refused: Changed original source body\n', 'Different original source control')756        expected = {'suite': action, 'actual_exit': 1}757    kani.require(same_json(record['qualification'], expected), 'Original complete history qualification differs')758    return {'suite': action, 'reconsumed': True, 'source': factory, 'seal_sha256': digest}759760761if __name__ == '__main__':762    try:763        with creusot.cache_lease():764            parser = argparse.ArgumentParser(description=__doc__)765            parser.add_argument('action', choices=(*ACTIONS, 'all'), nargs='?', default='all')766            parser.add_argument('--probe-source', type=Path, help=argparse.SUPPRESS)767            args = parser.parse_args()768            if args.probe_source:769                kani.require(all(run_receipt.regular(args.probe_source / name) and (args.probe_source / name).read_bytes() == data770                    for name,data in sources().items()), 'Changed original source body')771                raise RuntimeError('Changed original source was accepted')772            with (creusot.TEMP / '.nyxus-histories.lock').open('w') as lease:773                fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)774                results = []775                for action in ACTIONS if args.action == 'all' else (args.action,):776                    results.append(counter_probe(action) if action in KANI_SUITES else native_probe() if action == 'native'777                        else source_control() if action == 'source-control' else probe(action))778                aggregate = cohort(results) if args.action == 'all' else None779                print(json.dumps({'actual_driver_exit': 0, 'cohort': aggregate}), flush=True)780    except (RuntimeError, subprocess.SubprocessError, BlockingIOError) as error:781        print('Nyxus histories refused:', error, file=sys.stderr)782        sys.exit(1)