"""Isolated source-bound K2160 preparation; never admits local/guest moves.""" from pathlib import Path import datetime import hashlib import json import os import re import shutil import subprocess import sys import tempfile ROOT=Path.cwd().resolve() out=Path(tempfile.mkdtemp(prefix='K2160-reopen-preparation-',dir='reports/os-implementation')) def art(path): path=Path(path) return dict(path=str(path),sha256=hashlib.sha256(path.read_bytes()).hexdigest()) def frozen(): r=subprocess.run(['node','--input-type=module','-e',"import {frozenSnapshot} from './scripts/os-acceptance/boot-contract-report.mjs';console.log(JSON.stringify(frozenSnapshot(process.cwd())))"],capture_output=True,text=True,check=True) return json.loads(r.stdout) files=[];commands=[];mutants=[] report=dict(status='REOPEN_PREPARATION_RUNNING',guestAccepted=False,productAccepted=False,acceptedMoves=[], physicalTwoGuestReadbackVerified=False,commands=commands,mutants=mutants,files=files) def run(name,args,cwd=ROOT,env=None,expected=0): r=subprocess.run(list(map(str,args)),cwd=cwd,env=env,capture_output=True,text=True,timeout=180) path=out/(name+'.log');path.write_text(r.stdout+r.stderr);a=art(path);files.append(a) commands.append(dict(name=name,argv=list(map(str,args)),exitCode=r.returncode,log=a)) if r.returncode!=expected:raise RuntimeError(name+' unexpected exit; see '+str(path)) return r.stdout+r.stderr def source_paths(): # Only the three known source trees, never reports or Cargo output. paths=[Path('rust-toolchain.toml'),Path('.cargo/config.toml')] for folder in ['kernel','bootinfo','os-shutdown-reopen']: paths.extend(Path(folder)/p for p in ['Cargo.toml','Cargo.lock']) for sub in ['src']+(['tests','host']if folder=='os-shutdown-reopen'else[]): paths.extend(p for p in (Path(folder)/sub).rglob('*')if p.is_file()) paths.extend([Path('os-shutdown-reopen/CONTRACT.md'),Path('tools/reopen_verify/prepare.py'),Path('tools/reopen_verify/process_writer.py')]) assert len(paths)==len(set(paths)) return sorted(paths) try: before=frozen();report['frozenBefore']=before report['previousAttempts']=[] for i,path in enumerate(sys.argv[1:]): prior=json.loads(Path(path).read_bytes());assert prior['status']=='REOPEN_PREPARATION_FAILED' report['previousAttempts'].append(art(path));files.append(art(path)) log=out/('previous-failure-'+str(i)+'.log');log.write_text(prior['error']);files.append(art(log)) report['inputs']=[art(p)for p in source_paths()] source=out/'source' for a in report['inputs']: p=Path(a['path']);assert not p.is_symlink() dst=source/p;dst.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(p,dst) env=dict(os.environ);env.pop('CARGO_ENCODED_RUSTFLAGS',None);env.pop('RUSTFLAGS',None) env.update(CARGO_TARGET_DIR=str((out/'target').resolve()),CARGO_BUILD_JOBS='2',CARGO_INCREMENTAL='0') crate=source/'os-shutdown-reopen';manifest=crate/'Cargo.toml' base=['cargo','test','--manifest-path',manifest,'--locked','--offline','--target','aarch64-apple-darwin','--test','reopen'] log=run('host-tests',base+['--','--test-threads=1'],env=env) assert 'running 14 tests'in log and '14 passed; 0 failed'in log;report['hostTests']=14 run('bare-metal-check',['cargo','check','--manifest-path',manifest,'--locked','--offline','--target','aarch64-unknown-none','--lib'],env=env) text=(crate/'src/lib.rs').read_text() changes=[ ('accept-same-boot','if current.boot == previous.boot','if false','same_boot_even_with_another_process_never_reads_disk'), ('ignore-image','if expected_image == [0; 32] || current_image != expected_image','if false','zero_identity_and_wrong_image_never_read_disk'), ('allow-zero-identity','if !previous.valid() || !current.valid()','if false','zero_identity_and_wrong_image_never_read_disk'), ('allow-retry','if self.attempted','if false','failed_or_successful_attempt_cannot_reuse_prior_readback'), ('accept-wrong-digest','if digest != expected.digest','if false','fresh_verifier_observes_changed_disk_instead_of_previous_cache'), ('hash-sector-padding','hash.update(&block[..bytes]);','hash.update(&block);','tail_padding_and_unrelated_file_are_excluded_but_all_source_bytes_count'), ('skip-final-data-sector','0..size.div_ceil(512)','0..size.div_ceil(512).saturating_sub(1)','exact_logical_bytes_are_read_through_actual_turkfs_metadata'), ('ignore-logical-length','if size != expected.size','if false','wrong_logical_length_cannot_accept_matching_prefix'), ('ignore-duplicate-directory','return Err(Error::AmbiguousDirectory);','/* accept alias */','missing_ambiguous_or_invalid_directory_cannot_select_an_inode'), ('allow-overlapping-files','extents[..index].iter().any(|&(a,b)| a < end && start < b)','false','all_extent_aliases_and_bounds_are_validated_before_any_data_read'), ('allow-metadata-as-file','start <= inode_lba || end > geometry.block_count','end > geometry.block_count','all_extent_aliases_and_bounds_are_validated_before_any_data_read'), ('use-cached-data-address','first_lba + offset as u64','32 + offset as u64','fresh_mount_follows_current_metadata_not_an_expected_lba'), ] for name,before_text,after,test in changes: assert text.count(before_text)==1,(name,text.count(before_text)) directory=out/'mutants'/name;directory.mkdir(parents=True) for folder in ['os-shutdown-reopen','kernel','bootinfo']:shutil.copytree(source/folder,directory/folder) altered=directory/'os-shutdown-reopen/src/lib.rs';altered.write_text(text.replace(before_text,after)) mutated_env=dict(env,CARGO_TARGET_DIR=str((directory/'target').resolve())) log=run(name,['cargo','test','--manifest-path',directory/'os-shutdown-reopen/Cargo.toml','--locked','--offline', '--target','aarch64-apple-darwin','--test','reopen','--',test,'--exact'],env=mutated_env,expected=101) assert 'running 1 test'in log and '0 passed; 1 failed'in log and 'panicked at'in log assert 'could not compile'not in log and not re.search(r'error\[E\d+\]',log) mutants.append(dict(name=name,test=test,rejected=True,source=art(altered),log=commands[-1]['log'])) # Only this preparation's reproducible compiler output is reclaimed. shutil.rmtree(directory/'target') report['sourceMutantsRejected']=len(mutants) run('host-reader-build',['cargo','build','--manifest-path',manifest,'--locked','--offline','--target','aarch64-apple-darwin', '--features','host-reader','--bin','reopen-host-reader'],env=env) binary=out/'reopen-host-reader';shutil.copy2(out/'target/aarch64-apple-darwin/debug/reopen-host-reader',binary) fixtures=out/'process-fixture';fixtures.mkdir() writer=json.loads(run('separate-writer',[sys.executable,source/'tools/reopen_verify/process_writer.py',fixtures])) assert writer['status']=='HOST_WRITER_EXITING';disk=fixtures/'disk.img';raw=disk.read_bytes() args=[binary,disk,fixtures/'source.bin','persisted.txt','21600001','21600002',str(writer['pid']),'21'*32] reader=json.loads(run('separate-reader',args)) assert reader['status']=='HOST_PROCESS_READBACK_PASSED'and reader['pid']!=writer['pid'] assert reader['sha256']==writer['sourceSha256'] and reader['bytes']==writer['bytes']==1537 and reader['reads']==7 assert disk.read_bytes()==raw and hashlib.sha256(raw).hexdigest()==writer['diskSha256'] report['separateProcesses']=dict(writer=writer,reader=reader,diskUnchanged=True,hostOnly=True) cases=[] for name,offset,expected in [('old-data',32*512,'HashMismatch'),('bad-metadata',16*512,'Format')]: copy=fixtures/(name+'.img');data=bytearray(raw);data[offset]^=1;copy.write_bytes(data) call=args.copy();call[1]=copy;log=run(name,call,expected=2);assert expected in log assert copy.read_bytes()==data;cases.append(dict(name=name,rejected=True,expectedError=expected)) call=args.copy();call[5]=call[4];log=run('same-boot-process',call,expected=2);assert 'SameBoot'in log cases.append(dict(name='same-boot-process',rejected=True,expectedError='SameBoot')) assert disk.read_bytes()==raw;report['processNegativeControls']=cases report['frozenAfter']=frozen();assert report['frozenAfter']==report['frozenBefore'] assert report['inputs']==[art(p)for p in source_paths()],'root sources changed during preparation' report['sources']=[] for path in ['os-shutdown-reopen/Cargo.toml','os-shutdown-reopen/Cargo.lock','os-shutdown-reopen/src/lib.rs','os-shutdown-reopen/tests/reopen.rs', 'os-shutdown-reopen/tests/support/mod.rs','os-shutdown-reopen/host/reader.rs','os-shutdown-reopen/CONTRACT.md','kernel/src/turkfs.rs', 'tools/reopen_verify/process_writer.py','tools/reopen_verify/prepare.py']: p=source/path;report['sources'].append(art(p));files.append(art(p)) if p.suffix=='.py': alias=out/(p.name+'.txt');shutil.copyfile(p,alias);files.append(art(alias)) report.update(status='REOPEN_HOST_PREPARATION_PASSED',completedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(), scope='Read-only no_std component using actual existing TurkFS parsers. Fourteen host tests, twelve compiled source mutants and one separate writer/reader process pair. Three subprocess negative controls. ARM64 bare-metal typecheck passed. No QEMU launched, no two-guest shutdown/readback or product acceptance, and no roadmap moves admitted.', pending=['K2155 actual joint admission','source-bound native K2160 candidate','real first-guest writes and shutdown','second independent guest with read-only disk','physical read/identity verification and full 18-profile matrix']) shutil.rmtree(out/'target') except BaseException: import traceback report.update(status='REOPEN_PREPARATION_FAILED',error=traceback.format_exc());raise finally: (out/'report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n') print(json.dumps(dict(status=report['status'],report=str(out/'report.json'))),flush=True)