"""Real damaged-open / popup recovery / reopened-target comparison. All damage and recovery are confined to a fresh diagnostics fixture. The popup uses the production backend and native verifier without injected substitutes. """ from dataclasses import asdict import argparse import json from pathlib import Path import shutil import subprocess from cbb_refresh_verify.backup_recovery import _manifest from cbb_refresh_verify.verify_runner import VerifyRequest, run_verify, read_library_flag_if_available def write(path, value): path.write_text(json.dumps(value, ensure_ascii=False, default=str, indent=2), encoding='utf-8') def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('phase', choices=('setup', 'open-before', 'restore', 'compare')) args = parser.parse_args() base = Path(__file__).resolve().parents[1] root = base/'diagnostics/icdb-backup-dialog-live-20261028' library = root/'library/mentor_lib.lmc' source = base/'diagnostics/icdb-auto-recovery-20261027/verify-library' project = library.parent/'ReusableBlocksLP/IP101GR/Work/IP101GR.prj' if args.phase == 'setup': root.mkdir(parents=True, exist_ok=False) if any(p.is_symlink() or p.is_junction() for p in source.rglob('*')): raise ValueError('Source contains links') copied = subprocess.run(['robocopy', str(source), str(library.parent), '/E', '/COPY:DAT', '/DCOPY:T', '/MT:8', '/R:1', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS', '/NP'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (root/'copy.log').write_bytes(copied.stdout) if copied.returncode > 7: raise RuntimeError(f'Fixture copy failed: {copied.returncode}') # Remove historical backups only in this new, resolved fixture Work. for path in sorted(project.parent.rglob('*'), reverse=True): if path.is_dir() and path.name in {'ProjectBackup', 'cdbback'}: resolved = path.resolve() if not resolved.is_relative_to((root/'library').resolve()): raise ValueError('History cleanup escaped test fixture') shutil.rmtree(resolved) database = project.parent/'database/icdb.dat' healthy = database.read_bytes() if healthy[:64] == bytes(64): raise ValueError('Fixture baseline is not healthy') database.write_bytes(bytes(64) + healthy[64:]) write(root/'source-before.json', _manifest(source)) write(root/'setup.json', {'project': project, 'database': database, 'damage': 'First 64 bytes zeroed in isolated Work database', 'historical_backups_removed': True}) print('SETUP_DONE', flush=True) return request = VerifyRequest(library, 'IP101GR', root/args.phase, timeout_seconds=300, auto_repair=False) if args.phase == 'open-before': result = run_verify(request, progress=lambda e: print(json.dumps(e, ensure_ascii=True), flush=True), flag_reader=read_library_flag_if_available) write(root/'open-before.json', asdict(result)) log = project.parent/'PCB/LogFiles/PCBLogFile.txt' if log.is_file(): (root/'open-before-PCBLogFile.txt').write_bytes(log.read_bytes()) print(json.dumps(asdict(result), default=str, ensure_ascii=True), flush=True) return if args.phase == 'restore': before = json.loads((root/'open-before.json').read_text('utf-8')) log = (root/'open-before-PCBLogFile.txt').read_text('utf-8', errors='replace') if before['status'] != 'FAIL' or 'Database cannot be loaded' not in log: raise ValueError('Actual damaged target opening failure must be confirmed first') from PySide6.QtCore import QTimer, Qt from PySide6.QtTest import QTest from PySide6.QtWidgets import QApplication from cbb_refresh_verify.application import configure_qt_application from cbb_refresh_verify.ui.main_window import MainWindow app = QApplication([]); configure_qt_application(app) window = MainWindow(data_root=root/'data'); window.resize(1060, 860) window.show(); window.lmc_edit.setText(str(library)) window.libspec_edit.clear(); window.dms_edit.clear() state = {'phase': 'loading'} def tick(): if state['phase'] == 'loading' and not window.busy: if not window.loaded_path: raise RuntimeError(window.status_label.text()) state['phase'] = 'restoring' QTest.mouseClick(window.backup_restore_button, Qt.LeftButton) dialog = window.backup_dialog def progress(event): print(json.dumps(event, ensure_ascii=True, default=str), flush=True) if event.get('stage') == 'validate_source': candidates = list((root/'data/evidence').glob('backup-restore-*/recovery-request.json')) current = max(candidates, key=lambda p: p.stat().st_mtime_ns) config = json.loads(current.read_text('utf-8')) flag = read_library_flag_if_available(Path(config['validation_library']), 'IP101GR') write(current.parent/'source-before-native-flag.json', asdict(flag)) dialog.signals.progress.connect(progress) dialog.source_edit.setText(str(source/'ReusableBlocksLP/IP101GR/Work/IP101GR.prj')) dialog.grab().save(str(root/'dialog-before.png')) def done(name, result): write(root/'restore-ui-result.json', asdict(result)) state['phase'] = 'finishing' QTimer.singleShot(200, finish) dialog.completed.connect(done) QTest.mouseClick(dialog.restore_button, Qt.LeftButton) def finish(): timer.stop() dialog = window.backup_dialog dialog.grab().save(str(root/'dialog-after.png')) window.grab().save(str(root/'window-after.png')) write(root/'ui-state.json', {'status': dialog.status_label.text(), 'target_ready': 'IP101GR' in window.ready_names, 'busy': dialog.busy}) dialog.reject(); window.close(); app.quit() timer=QTimer(); timer.setInterval(100); timer.timeout.connect(tick) window.load_library(); timer.start(); app.exec() print((root/'restore-ui-result.json').read_text('utf-8'), flush=True) return before = json.loads((root/'open-before.json').read_text('utf-8')) restored = json.loads((root/'restore-ui-result.json').read_text('utf-8')) record = json.loads(Path(restored['evidence_path']).read_text('utf-8')) final = record['result'] retained = Path(record.get('retained_work', '')) after_evidence = Path(final['evidence_path']).parent events = [json.loads(line) for line in (after_evidence/'events.jsonl').read_text('utf-8').splitlines()] native_log = project.parent/'PCB/LogFiles/PCBLogFile.txt' text = native_log.read_text('utf-8', errors='replace') checks = { 'real_open_failed_before': before['status'] == 'FAIL' and before['error_category'] == 'MENTOR_DATABASE_LOAD_FAILED', 'source_copy_verified': record['source_validation']['status'] == 'PASS' and record['source_validation']['library_flag'] == 'GREEN', 'same_target_opened_after': any(e.get('stage') == 'identity_verified' and e.get('project') == str(project) for e in events), 'restored_target_passed': final['status'] == 'PASS' and final['library_flag'] == 'GREEN' and final['safe_to_continue'], 'old_damaged_work_retained': (retained/'database/icdb.dat').read_bytes()[:64] == bytes(64), 'original_source_unchanged': _manifest(source) == json.loads((root/'source-before.json').read_text('utf-8')), 'load_error_absent_after': 'Database cannot be loaded' not in text, } write(root/'comparison.json', {'checks': checks, 'passed': all(checks.values())}) print(json.dumps(checks), flush=True) if not all(checks.values()): raise RuntimeError('Real recovery comparison failed') if __name__ == '__main__': main()