import json from pathlib import Path import pytest def target_fixture(tmp_path): from dataclasses import replace from test_verify_runner import fixture, request from cbb_refresh_verify.native_repair import select_repair_target work = fixture(tmp_path) database = work/'database' database.mkdir() (database/'icdb.dat').write_bytes(b'original damaged database') diagnosis = {'error_code': 'ICDB_REPAIR_REQUIRED', 'machine': 'OLD-PC', 'database_path': str(database), 'session': '2026-10-24 08.22.29-10308', 'scope': 'project'} req = replace(request(tmp_path), auto_repair=True) return req, diagnosis, select_repair_target(req, diagnosis) def complete_native_success(target): """A complete successful worker result, with no contradictory native state.""" return {'status': 'REPAIRED', 'project': str(target.project), 'database': str(target.database), 'native_pid': 777, 'release': {'native_exited': True, 'safe_to_continue': True, 'addresses': []}, 'evidence': {'confirmed': True, 'native_backup': True, 'outcome': 'UNCONFIRMED', 'failure_complete': False, 'restore_complete': False, 'restored_from_backup': '', 'diagnostic_tail': 'Diagnostic: START\nDiagnostic: FINISH', 'database_tail': f'{target.database}\niCDBProjectBackupRepair\nIC: Closing project', 'restore_tail': '', 'output_tail': '', 'backup_log_tail': '', 'log_paths': []}} def test_repair_target_matches_actual_database_not_guessed_cbb_name(tmp_path): request, record, target = target_fixture(tmp_path) assert target.project.name == 'CBB1.prj' assert target.database == target.project.parent/'database' @pytest.mark.parametrize('change', ['foreign', 'shared', 'missing_session', 'unknown_scope']) def test_repair_target_rejects_unresolved_or_shared_database(tmp_path, change): from cbb_refresh_verify.native_repair import select_repair_target request, record, target = target_fixture(tmp_path) if change == 'foreign': record['database_path'] = str(tmp_path/'foreign/database') if change == 'shared': record.update(scope='central_library', database_path=str(tmp_path/'SymbolLibs/__ReusableBlocksSymb')) if change == 'missing_session': record['session'] = '' if change == 'unknown_scope': record['scope'] = 'unknown' with pytest.raises(ValueError): select_repair_target(request, record) def test_repair_backup_contains_database_locks_backups_and_original_files(tmp_path): from cbb_refresh_verify.native_repair import backup_project request, record, target = target_fixture(tmp_path) for relative in ('database/cdbsvr/sAddress.adr', 'ProjectBackup/backups/old.zip', 'PCB/copy.lock', 'Log Files/ProjectBackupLog.txt'): path = target.project.parent/relative path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(b'original '+relative.encode()) destination = tmp_path/'repair-backup' manifest = backup_project(target, destination) assert manifest['complete'] is True assert (destination/'database/icdb.dat').read_bytes() == b'original damaged database' assert (destination/'database/cdbsvr/sAddress.adr').read_bytes().startswith(b'original') assert (destination/'ProjectBackup/backups/old.zip').is_file() assert (destination/'PCB/copy.lock').is_file() def test_repair_backup_refuses_database_open_by_another_client(tmp_path): import win32file, win32con from cbb_refresh_verify.native_repair import backup_project request, record, target = target_fixture(tmp_path) handle = win32file.CreateFile(str(target.database/'icdb.dat'), win32con.GENERIC_READ, win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None) try: with pytest.raises(OSError): backup_project(target, tmp_path/'backup') finally: handle.Close() assert not (tmp_path/'backup/backup-manifest.json').exists() def test_repair_backup_rejects_reparse_directory(tmp_path): import _winapi from cbb_refresh_verify.native_repair import backup_project request, record, target = target_fixture(tmp_path) outside = tmp_path/'outside' outside.mkdir() _winapi.CreateJunction(str(outside), str(target.project.parent/'linked')) with pytest.raises(ValueError): backup_project(target, tmp_path/'backup') def test_native_confirmation_requires_exact_target_and_known_repair_prompt(): from cbb_refresh_verify.native_repair_ui import confirmation_allowed assert confirmation_allowed('iCDB Project Backup - C:\\exact.prj', r'C:\exact.prj', 'The project content will be validated and repaired if necessary.\n' 'A project backup will be created before any action take place.\n' 'You will be able to revert all changes using that backup.') assert not confirmation_allowed('iCDB Project Backup - C:\\OTHER.prj', r'C:\exact.prj', 'The project content will be validated and repaired if necessary.') assert not confirmation_allowed('iCDB Project Backup - C:\\exact.prj', r'C:\exact.prj', 'Confirm no other clients are connected. Continue anyway?') def test_native_diagnostics_finish_alone_does_not_prove_repair_success(): from cbb_refresh_verify.native_repair_ui import repair_completed assert not repair_completed('Diagnostic: FINISH', 'IC: Closing project', native_backup=False) assert not repair_completed('ERROR: invalid database\nDiagnostic: FINISH', 'iCDBProjectBackupRepair\nIC: Closing project', native_backup=True) assert repair_completed('Diagnostic: START\nDiagnostic: FINISH', 'iCDBProjectBackupRepair\nIC: Closing project', native_backup=True) def test_native_restore_of_old_backup_requires_review_even_when_diagnostics_finish(tmp_path): from cbb_refresh_verify.native_repair_ui import _native_evidence from cbb_refresh_verify.icdb_recovery import snapshot_log project = tmp_path/'project.prj' database = tmp_path/'database' project.touch() log = tmp_path/'Log Files/ProjectBackupLog.txt' log.parent.mkdir() baseline = snapshot_log(log) for folder, text in ( ('dbcheck', 'Diagnostic: START\nDiagnostic: FINISH'), ('dbrestore', f'iCDB database restored from backup: {tmp_path}/old.zip\n[0] DONE')): path = database/'cdbsvr'/folder/'new-1234/log.txt' path.parent.mkdir(parents=True) path.write_text(text) evidence = _native_evidence(project, database, 1234, 0, baseline) assert evidence['restored_from_backup'] == f'{tmp_path}/old.zip' assert evidence['restore_complete'] is True assert evidence['confirmed'] is False def test_automatic_repair_retries_only_once_and_preserves_original_failure(tmp_path, monkeypatch): from dataclasses import replace from cbb_refresh_verify import verify_runner as runner from cbb_refresh_verify import native_repair request, record, target = target_fixture(tmp_path) evidence = tmp_path/'first/result.json' evidence.parent.mkdir() (evidence.parent/'diagnostics').mkdir() (evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record)) original = runner.VerifyResult('FAIL', stderr='native lost session', safe_to_continue=False, error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence) calls = [] def verify(req, **kwargs): calls.append(req) return original monkeypatch.setattr(runner, '_run_verify_serialized', verify) monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: complete_native_success(target)) outcome = runner.run_verify(request) assert len(calls) == 2 assert outcome.status == 'FAIL' assert outcome.stderr == 'native lost session' assert outcome.recovery_attempts[0]['original_error'] == 'native lost session' assert outcome.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED' assert outcome.recovery_attempts[0]['native_status'] == 'REPAIRED' @pytest.mark.parametrize('text,expected,terminal', [ ('There is no backup of iCDB.\nRepair project error [Cannot repair the project - there is no backup of missing iCDB].', 'MISSING_HEALTHY_BACKUP', True), ('Repair project error [Database validation failed].', 'NATIVE_REPAIR_FAILED', True), ('Project is in use. Full functionality is unavailable.', 'DATABASE_BUSY', False), ('Repairing the project. Diagnostic: START', 'UNCONFIRMED', False), ]) def test_current_native_output_classifies_failure_and_terminal_evidence(text, expected, terminal): from cbb_refresh_verify.native_repair_ui import classify_repair_evidence result = classify_repair_evidence('', '', '', text) assert result['outcome'] == expected assert result['failure_complete'] is terminal def test_historical_no_backup_output_replay_is_conclusive_failure(): from cbb_refresh_verify.native_repair_ui import classify_repair_evidence # Sanitized actual native Output from the 2026-10-28 no-history fixture. text = ('Repairing the project [/CBB.prj].\n' 'Repair backup [repair.zip] created successfully.\n' 'The iCDB database is corrupted.\nThere is no backup of iCDB.\n' 'Repair project error [Cannot repair the project - there is no backup of missing iCDB].\n' 'The project is probably in inconsistent state. Please restore the project from one of previous backups.') result = classify_repair_evidence('', '', '', text) assert result == {'outcome': 'MISSING_HEALTHY_BACKUP', 'failure_complete': True} @pytest.mark.parametrize('repair_status', ['BLOCKED', 'RESTORED_REVIEW_REQUIRED']) def test_automatic_repair_does_not_retry_busy_or_unsupported_target(tmp_path, monkeypatch, repair_status): from cbb_refresh_verify import verify_runner as runner from cbb_refresh_verify import native_repair request, record, target = target_fixture(tmp_path) evidence = tmp_path/'first/result.json' evidence.parent.mkdir() (evidence.parent/'diagnostics').mkdir() (evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record)) calls = [] def verify(req, **kwargs): calls.append(req) return runner.VerifyResult('FAIL', stderr='native lost session', error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=False, evidence_path=evidence) monkeypatch.setattr(runner, '_run_verify_serialized', verify) monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status':repair_status}) outcome = runner.run_verify(request) assert len(calls) == 1 assert outcome.safe_to_continue is False assert outcome.recovery_attempts[0]['status'] == repair_status def test_timeout_never_enters_automatic_repair(tmp_path, monkeypatch): from cbb_refresh_verify import verify_runner as runner, native_repair request, record, target = target_fixture(tmp_path) evidence = tmp_path/'first/result.json' evidence.parent.mkdir() (evidence.parent/'diagnostics').mkdir() (evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record)) monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw: runner.VerifyResult('TIMEOUT', error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=False, evidence_path=evidence)) monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: pytest.fail('A timed-out native owner must not be repaired')) assert runner.run_verify(request).status == 'TIMEOUT' def test_retained_importer_blocks_repair_even_without_an_open_database_handle(tmp_path, monkeypatch): from cbb_refresh_verify import native_repair request, record, target = target_fixture(tmp_path) evidence = tmp_path/'original' evidence.mkdir() (evidence/'content-check-process.json').write_text(json.dumps({'status':'RETAINED','pid':123})) monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw: pytest.fail('Do not repair between importer transactions')) outcome = native_repair.attempt_recovery(request, record, evidence) assert outcome['status'] == 'BLOCKED' assert 'IMPORTER_RELEASE_UNCONFIRMED' in outcome['detail'] def test_repair_cancellation_during_access_check_prevents_native_launch(tmp_path, monkeypatch): from cbb_refresh_verify import native_repair_ui as ui, native_repair, mentor_adapter request, record, target = target_fixture(tmp_path) root = tmp_path/'worker' root.mkdir() cancel = root/'cancel.signal' job = root/'request.json' job.write_text(json.dumps({'project':str(target.project),'database':str(target.database), 'root':str(root),'cancel_signal':str(cancel),'timeout':1, 'supervisor_pid':123,'desktop':'CbbRepair_test'})) calls = [] monkeypatch.setattr('cbb_refresh_verify.desktop_worker.start_supervisor_watchdog', lambda *a, **kw: calls.append('watchdog')) monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'CbbRepair_test', raising=False) monkeypatch.setattr(ui, '_repair_command', lambda *_: 32924) monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: []) monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: []) def check(*a): assert calls == ['watchdog'], 'Watch supervisor before filesystem checks' cancel.touch() calls.append('check') monkeypatch.setattr(native_repair, 'check_repair_access', check) monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('Repair must not start')) assert ui.repair_worker_main(job) == 1 outcome = json.loads((root/'repair-result.json').read_text('utf-8')) assert 'REPAIR_CANCELLED_BEFORE_LAUNCH' in outcome['detail'] def test_repair_worker_refuses_the_input_desktop_before_backup(tmp_path, monkeypatch): from cbb_refresh_verify import native_repair_ui as ui, native_repair request, record, target = target_fixture(tmp_path) root = tmp_path/'worker' root.mkdir() job = root/'request.json' job.write_text(json.dumps({'project':str(target.project),'database':str(target.database), 'root':str(root),'cancel_signal':str(root/'cancel.signal'),'timeout':1, 'supervisor_pid':123,'desktop':'CbbRepair_test'})) monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'Default', raising=False) monkeypatch.setattr(native_repair, 'backup_project', lambda *a: pytest.fail('Input desktop repair forbidden')) assert ui.repair_worker_main(job) == 1 assert 'REPAIR_PRIVATE_DESKTOP_REQUIRED' in json.loads((root/'repair-result.json').read_text('utf-8'))['detail'] def test_repair_worker_job_binds_supervisor_and_private_desktop(tmp_path, monkeypatch): from cbb_refresh_verify.native_repair import run_native_repair request, record, target = target_fixture(tmp_path) class Worker: returncode = 0 def __init__(self, command, desktop): job = json.loads(Path(command[-1]).read_text('utf-8')) assert job['supervisor_pid'] > 0 assert job['desktop'] == desktop assert desktop.startswith('CbbRepair_') (Path(job['root'])/'repair-result.json').write_text('{"status":"BLOCKED"}') def poll(self): return 0 def bind_cancellation(self, path): pass def close(self): pass monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker) assert run_native_repair(target, tmp_path/'native')['status'] == 'BLOCKED' def test_backup_detects_a_file_added_during_the_copy(tmp_path, monkeypatch): from cbb_refresh_verify import native_repair request, record, target = target_fixture(tmp_path) original = native_repair.shutil.copy2 def changed(source, destination): result = original(source, destination) (target.project.parent/'new-file.txt').write_bytes(b'concurrent writer') return result monkeypatch.setattr(native_repair.shutil, 'copy2', changed) with pytest.raises(OSError, match='REPAIR_BACKUP_CHANGED'): native_repair.backup_project(target, tmp_path/'backup') def repair_worker_fixture(tmp_path, monkeypatch, scenario): """Replay native window/log transitions without launching a native client.""" from types import SimpleNamespace import win32con, win32gui from cbb_refresh_verify import native_repair_ui as ui, native_repair, mentor_adapter request, diagnosis, target = target_fixture(tmp_path) root = tmp_path/'worker' root.mkdir() job = root/'request.json' job.write_text(json.dumps({'project': str(target.project), 'database': str(target.database), 'root': str(root), 'cancel_signal': str(root/'cancel.signal'), 'timeout': 1, 'supervisor_pid': 123, 'desktop': 'CbbRepair_test'})) ticks = [0.0] state = {'requested': False, 'confirmed': False, 'closed': False} actions = [] monkeypatch.setattr(ui, 'time', SimpleNamespace(monotonic=lambda: ticks[0], time_ns=lambda: 0, sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds))) monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'CbbRepair_test') monkeypatch.setattr(ui, '_repair_command', lambda *_: 32924) monkeypatch.setattr(ui, 'discover_sdd_home', lambda *_: tmp_path, raising=False) monkeypatch.setattr('cbb_refresh_verify.mentor_paths.discover_sdd_home', lambda *_: tmp_path) monkeypatch.setattr('cbb_refresh_verify.desktop_worker.start_supervisor_watchdog', lambda *a, **kw: None) monkeypatch.setattr(native_repair, 'backup_project', lambda *a: {}) monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: []) monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: []) monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: SimpleNamespace( pid=777, poll=lambda: 0 if state['closed'] and ticks[0] >= .6 else None)) terminal = 'Repair project error [Cannot repair the project - there is no backup of missing iCDB].' def output(_): if scenario == 'busy_before': return 'Project is in use. Full functionality is unavailable.' if scenario == 'stale': return terminal if not state['confirmed']: return '' if scenario == 'busy': return 'Repair project error [Project is in use].' if scenario == 'active': return 'Repairing the project. Please wait.' if scenario in {'success', 'restore'}: return 'Repair project finished.' return terminal monkeypatch.setattr(ui, '_native_output', output, raising=False) def windows(_): main = {'hwnd': 100, 'class': 'Afx:main', 'title': 'iCDB Project Backup - '+str(target.project), 'enabled': True, 'children': []} if state['confirmed'] and scenario in {'unknown', 'custom_prompt'}: return [main, {'hwnd': 300, 'class': 'CustomDialog' if scenario == 'custom_prompt' else '#32770', 'title': 'Unexpected', 'enabled': True, 'children': [{'text': 'Overwrite design?', 'class': 'Button', 'id': 1, 'hwnd': 301, 'enabled': True}]}] if state['requested'] and not state['confirmed']: return [main, {'hwnd': 200, 'class': '#32770', 'title': '', 'enabled': True, 'children': [{'hwnd': 201, 'class': 'Button', 'id': 1, 'enabled': True, 'text': 'The project content will be validated and repaired if necessary.\n' 'A project backup will be created before any action take place.\n' 'You will be able to revert all changes using that backup.'}]}] return [main] monkeypatch.setattr(ui, '_windows', windows) def post(hwnd, message, *args): actions.append((hwnd, message)) if message == win32con.WM_COMMAND: state['requested'] = True if message == win32con.BM_CLICK: state['confirmed'] = True if scenario in {'success', 'restore'}: import zipfile log = target.project.parent/'Log Files/ProjectBackupLog.txt' log.parent.mkdir(parents=True) log.write_text('Successfully created [Project Repair] backup [repair.zip]') archive = target.project.parent/'ProjectBackup/backups/repair.zip' archive.parent.mkdir(parents=True) with zipfile.ZipFile(archive, 'w') as zipped: zipped.writestr('database/icdb.dat', b'backup') logs = {'dbcheck': 'Diagnostic: START\nDiagnostic: FINISH', 'log': f'{target.database}\niCDBProjectBackupRepair\nIC: Closing project'} if scenario == 'restore': logs['dbrestore'] = 'iCDB database restored from backup: old.zip\n[0] DONE' for folder, text in logs.items(): path = target.database/'cdbsvr'/folder/'new-777/log.txt' path.parent.mkdir(parents=True) path.write_text(text) if scenario == 'address': address = target.database/'cdbsvr/sAddress.adr' address.parent.mkdir(parents=True) address.write_text('owner') if message == win32con.WM_CLOSE: state['closed'] = True monkeypatch.setattr(win32gui, 'PostMessage', post) return ui, root, job, actions @pytest.mark.parametrize('scenario,expected,closed', [ ('failed', 'MISSING_HEALTHY_BACKUP', True), ('busy', 'DATABASE_BUSY', False), ('unknown', 'UNKNOWN_DIALOG', False), ('custom_prompt', 'UNKNOWN_DIALOG', False), ('active', 'TIMEOUT_UNRELEASED', False), ('stale', 'TIMEOUT_UNRELEASED', False), ('address', 'MISSING_HEALTHY_BACKUP', False), ]) def test_native_worker_closes_only_conclusively_failed_idle_tool(tmp_path, monkeypatch, scenario, expected, closed): import win32con ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario) assert ui.repair_worker_main(job) == 1 result = json.loads((root/'repair-result.json').read_text('utf-8')) assert result['status'] == expected assert result['release']['safe_to_continue'] is closed assert ((100, win32con.WM_CLOSE) in actions) is closed assert actions[:2] == [(100, win32con.WM_COMMAND), (201, win32con.BM_CLICK)] assert bool(result['evidence']['output_tail']) is (scenario != 'stale') if scenario == 'unknown': assert result['unknown_dialogs'][0]['title'] == 'Unexpected' @pytest.mark.parametrize('scenario,expected', [('success', 'REPAIRED'), ('restore', 'RESTORED_REVIEW_REQUIRED')]) def test_native_worker_preserves_success_and_historical_restore_distinction(tmp_path, monkeypatch, scenario, expected): from cbb_refresh_verify.native_repair import RepairTarget, native_success_confirmed ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario) assert ui.repair_worker_main(job) == (0 if scenario == 'success' else 1) result = json.loads((root/'repair-result.json').read_text('utf-8')) assert result['status'] == expected assert result['release']['safe_to_continue'] is True assert result['evidence']['native_backup'] is True assert result['evidence']['confirmed'] is (scenario == 'success') assert (root/'native-logs/dbcheck/new-777/log.txt').exists() request = json.loads(job.read_text('utf-8')) target = RepairTarget(Path(request['project']), Path(request['database'])) assert native_success_confirmed(target, result) is (scenario == 'success') def test_repair_skips_application_backup_but_keeps_native_repair_backup(tmp_path, monkeypatch): ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'success') monkeypatch.setattr('cbb_refresh_verify.native_repair.backup_project', lambda *a: pytest.fail('application project backup must not run')) assert ui.repair_worker_main(job) == 0 result = json.loads((root/'repair-result.json').read_text('utf-8')) assert result['evidence']['native_backup'] is True assert not (root/'complete-backup').exists() def test_repair_without_application_backup_still_rejects_busy_database(tmp_path, monkeypatch): import win32con, win32file ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'success') database = Path(json.loads(job.read_text())['database'])/'icdb.dat' handle = win32file.CreateFile(str(database), win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) try: monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('busy database launched')) assert ui.repair_worker_main(job) == 1 assert 'REPAIR_DATABASE_IN_USE' in json.loads((root/'repair-result.json').read_text(encoding='utf-8'))['detail'] finally: handle.Close() def test_native_busy_project_on_load_never_invokes_repair(tmp_path, monkeypatch): ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'busy_before') assert ui.repair_worker_main(job) == 1 result = json.loads((root/'repair-result.json').read_text('utf-8')) assert result['status'] == 'DATABASE_BUSY' assert actions == [] assert not result['release']['safe_to_continue'] @pytest.mark.parametrize('readback', ['missing', 'timeout', 'truncated']) def test_unavailable_initial_output_never_requests_or_confirms_repair(tmp_path, monkeypatch, readback): from types import SimpleNamespace from cbb_refresh_verify import native_repair_ui as module actual_read = module._native_output ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') windows = ui._windows def observe(pid): result = windows(pid) if readback != 'missing': result[0]['children'].append({'hwnd': 400, 'class': 'RichEdit20A'}) return result monkeypatch.setattr(ui, '_windows', observe) class Readback: def __call__(self, hwnd, message, length, buffer, flags, timeout, copied): if readback == 'timeout': return 0 copied._obj.value = length-1 return 1 monkeypatch.setattr(ui.ctypes, 'WinDLL', lambda *a, **kw: SimpleNamespace(SendMessageTimeoutW=Readback())) monkeypatch.setattr(ui, '_native_output', actual_read) assert ui.repair_worker_main(job) == 1 result = json.loads((root/'repair-result.json').read_text('utf-8')) assert actions == [] assert result['status'] == 'TIMEOUT_UNRELEASED' assert result['release']['safe_to_continue'] is False assert json.loads((root/'native-output.json').read_text('utf-8'))['baseline'] is None def test_initial_output_waits_until_readable_and_accepts_empty_baseline(tmp_path, monkeypatch): import win32con ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') reads = [] def output(_): reads.append(len(reads)) if len(reads) <= 2: assert not actions return None return '' monkeypatch.setattr(ui, '_native_output', output) assert ui.repair_worker_main(job) == 1 assert actions == [(100, win32con.WM_COMMAND), (201, win32con.BM_CLICK)] assert json.loads((root/'native-output.json').read_text('utf-8'))['baseline'] == '' def test_invoked_busy_native_result_never_reopens_or_continues_queue(tmp_path, monkeypatch): import win32con from test_verify_runner import request from cbb_refresh_verify import verify_runner as runner, native_repair ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'busy') assert ui.repair_worker_main(job) == 1 busy = json.loads((root/'repair-result.json').read_text('utf-8')) assert (100, win32con.WM_CLOSE) not in actions assert busy['status'] == 'DATABASE_BUSY' and busy['release']['native_exited'] is False from dataclasses import replace req = replace(request(tmp_path), auto_repair=True) target = json.loads(job.read_text('utf-8')) evidence = tmp_path/'first/result.json' evidence.parent.mkdir() (evidence.parent/'diagnostics').mkdir() (evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps({ 'error_code': 'ICDB_REPAIR_REQUIRED', 'scope': 'project', 'session': 'original-session', 'database_path': target['database']})) opens = [] def verify(*a, **kw): opens.append('open') return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=False, evidence_path=evidence) monkeypatch.setattr(runner, '_run_verify_serialized', verify) monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: busy) results = runner.run_batch([req, req], verifier=runner.run_verify) assert opens == ['open'] assert results[0].recovery_attempts[0]['status'] == 'DATABASE_BUSY' assert results[0].safe_to_continue is False and results[1].status == 'SKIPPED' @pytest.mark.parametrize('status,released,scope,expected', [ ('MISSING_HEALTHY_BACKUP', True, 'project', True), ('NATIVE_REPAIR_FAILED', True, 'project', True), ('MISSING_HEALTHY_BACKUP', False, 'project', False), ('MISSING_HEALTHY_BACKUP', True, 'central_library', False), ('MISSING_HEALTHY_BACKUP', True, 'unknown', False), ('UNKNOWN_DIALOG', True, 'project', False), ('TIMEOUT_UNRELEASED', True, 'project', False), ('DATABASE_BUSY', True, 'project', False), ]) def test_failed_repair_continues_only_released_project_local_items( tmp_path, monkeypatch, status, released, scope, expected): from cbb_refresh_verify import verify_runner as runner, native_repair request, diagnosis, target = target_fixture(tmp_path) diagnosis['scope'] = scope evidence = tmp_path/'first/result.json' evidence.parent.mkdir() (evidence.parent/'diagnostics').mkdir() (evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis)) original = runner.VerifyResult('FAIL', stderr='original session lost', safe_to_continue=False, error_category='ICDB_REPAIR_REQUIRED', error_stage='PCB_STARTING', evidence_path=evidence) monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw: original) monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: { 'status': status, 'release': {'safe_to_continue': released}, 'evidence': {'failure_complete': True}, 'project': str(target.project), 'database': str(target.database)}) result = runner.run_verify(request) assert result.safe_to_continue is expected assert result.status == 'FAIL' assert result.error_stage == 'PCB_STARTING' assert result.stderr.startswith('original session lost') assert status in result.stderr assert result.recovery_attempts[0]['original_stage'] == 'PCB_STARTING' @pytest.mark.parametrize('validation_status,flag,expected', [ ('PASS', 'GREEN', True), ('PASS', 'UNKNOWN', False), ('FAIL', 'GREEN', False), ]) def test_maintenance_counts_require_native_success_then_verify_green( tmp_path, monkeypatch, validation_status, flag, expected): from cbb_refresh_verify import verify_runner as runner, native_repair from cbb_refresh_verify.icdb_maintenance import maintenance_counts request, diagnosis, target = target_fixture(tmp_path) evidence = tmp_path/'first/result.json' evidence.parent.mkdir() (evidence.parent/'diagnostics').mkdir() (evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis)) original = runner.VerifyResult('FAIL', stderr='original lost session', safe_to_continue=False, error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence) evidence.write_text(json.dumps({'stderr': original.stderr})) validated = runner.VerifyResult(validation_status, library_flag=flag, evidence_path=tmp_path/'second.json', safe_to_continue=True) calls = [] def verify(req, **kwargs): calls.append(req) return original if len(calls) == 1 else validated monkeypatch.setattr(runner, '_run_verify_serialized', verify) monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: complete_native_success(target)) result = runner.run_verify(request) assert len(calls) == 2 and calls[1].auto_repair is False assert result.recovery_attempts[0]['validation_passed'] is expected assert maintenance_counts([result])['repaired'] == int(expected) assert original.evidence_path.exists(), 'Original result evidence must remain available' assert json.loads(original.evidence_path.read_text('utf-8'))['stderr'] == 'original lost session' def test_native_success_without_release_does_not_reopen(tmp_path, monkeypatch): from cbb_refresh_verify import verify_runner as runner, native_repair request, diagnosis, target = target_fixture(tmp_path) evidence = tmp_path/'first/result.json' evidence.parent.mkdir() (evidence.parent/'diagnostics').mkdir() (evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis)) calls = [] def verify(*args, **kwargs): calls.append('open') return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=False, evidence_path=evidence) monkeypatch.setattr(runner, '_run_verify_serialized', verify) monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status': 'REPAIRED'}) result = runner.run_verify(request) assert calls == ['open'] assert not result.safe_to_continue assert result.recovery_attempts[0]['status'] == 'UNCONFIRMED' @pytest.mark.parametrize('obstacle', ['none', 'launcher', 'repair_tool', 'importer', 'address', 'handle', 'shared_handle', 'probe']) def test_repair_release_requires_process_address_and_database_handle_release(tmp_path, monkeypatch, obstacle): import win32con, win32file from cbb_refresh_verify import native_repair, mentor_adapter request, diagnosis, target = target_fixture(tmp_path) monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [(123, 'ExpeditionPCB.exe', 'launcher')] if obstacle == 'launcher' else []) def processes(name): if obstacle == 'probe': raise OSError('process observation unavailable') if ((obstacle == 'repair_tool' and name == 'iCDBProjectBackup.exe') or (obstacle == 'importer' and name == 'ReuseBlockImporter.exe')): return [(456, name, 'unconfirmed owner', 0)] return [] monkeypatch.setattr(mentor_adapter, '_process_details', processes) if obstacle == 'address': address = target.database/'cdbsvr/sAddress.adr' address.parent.mkdir(parents=True) address.touch() handle = None try: if obstacle in {'handle', 'shared_handle'}: database_file = target.database/'icdb.dat' if obstacle == 'shared_handle': database_file = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/icdb.dat' database_file.parent.mkdir(parents=True) database_file.touch() handle = win32file.CreateFile(str(database_file), win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None) result = native_repair.repair_release_state(request, target, complete_native_success(target)) assert result['safe_to_continue'] is (obstacle == 'none') finally: if handle: handle.Close() def test_attempt_persists_distinct_native_failure_and_release_result(tmp_path, monkeypatch): from cbb_refresh_verify import native_repair, mentor_adapter request, diagnosis, target = target_fixture(tmp_path) evidence = tmp_path/'evidence' evidence.mkdir() monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: []) monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: []) monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw: { 'status': 'MISSING_HEALTHY_BACKUP', 'project': str(target.project), 'database': str(target.database), 'native_pid': 777, 'release': {'safe_to_continue': True, 'native_exited': True, 'addresses': []}, 'evidence': {'failure_complete': True, 'output_tail': 'no backup'}}) result = native_repair.attempt_recovery(request, diagnosis, evidence) assert result['status'] == 'MISSING_HEALTHY_BACKUP' assert result['release']['database_exclusive'] is True assert result['release']['safe_to_continue'] is True assert isinstance(result['evidence'], dict) assert result['evidence_path'] == str(evidence/'native-repair') assert json.loads((evidence/'native-repair/attempt.json').read_text('utf-8')) == result def test_retry_exception_keeps_original_error_and_native_repair_evidence(tmp_path, monkeypatch): from cbb_refresh_verify import verify_runner as runner, native_repair request, diagnosis, target = target_fixture(tmp_path) evidence = tmp_path/'first/result.json' evidence.parent.mkdir() (evidence.parent/'diagnostics').mkdir() (evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis)) calls = [] def verify(*a, **kw): calls.append('open') if len(calls) > 1: raise OSError('retry infrastructure failure') return runner.VerifyResult('FAIL', stderr='original native error', safe_to_continue=False, error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence) monkeypatch.setattr(runner, '_run_verify_serialized', verify) native_result = complete_native_success(target) native_result['evidence']['diagnostic_tail'] += '\noriginal repair evidence' monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: native_result) result = runner.run_verify(request) assert not result.safe_to_continue assert 'original native error' in result.stderr assert 'retry infrastructure failure' in result.stderr assert 'original repair evidence' in result.recovery_attempts[0]['evidence']['diagnostic_tail'] assert result.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED' assert json.loads(evidence.read_text('utf-8'))['recovery_attempts'] def test_sanitized_field_open_failure_replay_closes_launcher_then_repairs_once(tmp_path, monkeypatch): from types import SimpleNamespace from dataclasses import replace from test_failed_startup import startup_fixture from cbb_refresh_verify import verify_runner as runner, native_repair, failed_session, mentor_adapter from cbb_refresh_verify.pcb_bridge import wait_for_target_document, PcbBridgeError replay = json.loads((Path(__file__).parent/'fixtures/issue2-lost-session-sanitized.json').read_text('utf-8')) request, diagnosis, target = target_fixture(tmp_path) # Retain a different PRJ name: the field CBB name never authorizes guessing it. block_root = target.project.parent.parent block_root.rename(block_root.with_name(replay['block'])) request = replace(request, block_name=replay['block']) project, pcb = runner.preflight(request) diagnosis['database_path'] = str(project.parent/'database') target = native_repair.select_repair_target(request, diagnosis) job, records, messages = startup_fixture(tmp_path, monkeypatch) job.update(project=str(project), pcb=str(pcb), lmc_file=str(request.lmc_file)) records[0] = (12, records[0][1], f'ExpeditionPCB.exe "{pcb}" -ReusableCircuit', 11) diagnosis.update(session=replay['diagnosis']['session'], machine='FIELD-PC') (tmp_path/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis)) (tmp_path/'dialogs.jsonl').write_text(json.dumps(replay['dialog'])+'\n') ticks = [0.0] monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds))) launcher = SimpleNamespace(pid=11, poll=lambda: 0 if ticks[0] >= .4 else None) monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: []) trace = [] evidence = tmp_path/'result.json' original = runner.VerifyResult('FAIL', stderr=replay['native_error'], safe_to_continue=False, error_category=replay['original_result']['error_category'], error_stage=replay['original_result']['error_stage'], evidence_path=evidence) assert runner.classify_failure_category(original.stderr) == original.error_category assert runner.phase_for_event(replay['observed_events'][2]).value == original.error_stage opens = [] def verify(req, **kwargs): opens.append(req) trace.append('open') if len(opens) == 1: errors = iter(('', replay['native_error'])) with pytest.raises(PcbBridgeError, match='Repair project'): wait_for_target_document(job, lambda: SimpleNamespace(ActiveDocument=None), process_alive=lambda: True, error_reader=lambda: next(errors), emit=lambda **e: trace.append(e['stage']), sleep=lambda _: None) closed = failed_session.close_failed_startup(job, 12, launcher_process=launcher, emit=lambda **e: trace.append(e['stage']), timeout_seconds=1) assert closed['status'] == 'CLOSED' trace.append('launcher_exited') return original # Repeated field error after one repair must not loop. def repair(actual, root, **kwargs): assert actual == target assert trace[-1] == 'launcher_exited' assert not records and launcher.poll() == 0 trace.append('native_repair') return complete_native_success(actual) monkeypatch.setattr(runner, '_run_verify_serialized', verify) monkeypatch.setattr(native_repair, 'run_native_repair', repair) result = runner.run_verify(request) assert trace == ['open', 'pcb_document_wait', 'startup_close_requested', 'startup_close_result', 'launcher_exited', 'native_repair', 'open'] assert len(opens) == 2 and opens[1].auto_repair is False assert result.error_stage == 'PCB_STARTING' assert result.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED' assert result.recovery_attempts[0]['original_error'] == replay['native_error'] assert json.loads((tmp_path/'pre-repair-result.json').read_text('utf-8'))['stderr'] == replay['native_error'] MALFORMED_SUCCESS = [ ('minimal', None), ('native_pid', None), ('native_pid', True), ('project', None), ('project', '/CBB.prj'), ('project', []), ('database', None), ('database', '/database'), ('release', []), ('release', 'released'), ('release.native_exited', None), ('release.native_exited', False), ('release.native_exited', 1), ('release.native_exited', 'true'), ('release.safe_to_continue', 1), ('release.addresses', ['owner']), ('release.addresses', ''), ('evidence', None), ('evidence', []), ('evidence', 'confirmed'), ('evidence.confirmed', None), ('evidence.confirmed', False), ('evidence.confirmed', 1), ('evidence.confirmed', 'true'), ('evidence.native_backup', False), ('evidence.failure_complete', True), ('evidence.outcome', 'DATABASE_BUSY'), ('evidence.restore_complete', True), ('evidence.restored_from_backup', 'old.zip'), ('unknown_dialogs', [{'title': 'Unknown'}]), ] def malformed_native_success(target, key, value): result = complete_native_success(target) if key == 'minimal': return {'status': 'REPAIRED', 'release': {'safe_to_continue': True}} if key in {'project', 'database'} and isinstance(value, str) and value.startswith(''): other = target.project.parent.parent.parent/'other-target' other.mkdir(exist_ok=True) if key == 'project': other = other/'other.prj' other.touch() value = str(other.resolve()) if '.' in key: parent, field = key.split('.') result[parent][field] = value else: result[key] = value return result @pytest.mark.parametrize('key,value', MALFORMED_SUCCESS) def test_malformed_native_success_never_authorizes_release(tmp_path, monkeypatch, key, value): from cbb_refresh_verify import native_repair, mentor_adapter request, diagnosis, target = target_fixture(tmp_path) monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: []) monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: []) result = native_repair.repair_release_state(request, target, malformed_native_success(target, key, value)) assert result['safe_to_continue'] is False @pytest.mark.parametrize('key,value', MALFORMED_SUCCESS) def test_malformed_native_success_never_reopens_or_counts_repaired(tmp_path, monkeypatch, key, value): from cbb_refresh_verify import verify_runner as runner, native_repair from cbb_refresh_verify.icdb_maintenance import maintenance_counts request, diagnosis, target = target_fixture(tmp_path) evidence = tmp_path/'first/result.json' evidence.parent.mkdir() (evidence.parent/'diagnostics').mkdir() (evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis)) calls = [] def verify(*a, **kw): calls.append('open') if len(calls) == 1: return runner.VerifyResult('FAIL', stderr='original error', error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=False, evidence_path=evidence) return runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=evidence) monkeypatch.setattr(runner, '_run_verify_serialized', verify) monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: malformed_native_success(target, key, value)) result = runner.run_verify(request) assert calls == ['open'] assert result.status == 'FAIL' and result.safe_to_continue is False assert result.recovery_attempts[0]['status'] == 'UNCONFIRMED' assert result.recovery_attempts[0]['release']['safe_to_continue'] is False assert maintenance_counts([result])['repaired'] == 0 @pytest.mark.parametrize('owner', [None, 'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe']) def test_repair_release_uses_real_process_query_contract(tmp_path, monkeypatch, owner): from types import SimpleNamespace import win32com.client from cbb_refresh_verify.native_repair import repair_release_state request, diagnosis, target = target_fixture(tmp_path) queried = [] names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'cscript.exe') queries = {"SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId " f"FROM Win32_Process WHERE Name='{name}'": name for name in names} def query(wql): name = queries[wql] queried.append(name) return ([SimpleNamespace(ProcessId='456', ParentProcessId='1', Name=name, ExecutablePath=f'C:\\Mentor\\{name}', CommandLine=f'{name} target')] if name == owner else []) def service(moniker): assert moniker == 'winmgmts:' return SimpleNamespace(ExecQuery=query) monkeypatch.setattr(win32com.client, 'GetObject', service) from cbb_refresh_verify import owner_probe import subprocess monkeypatch.setattr(owner_probe.subprocess, 'run', lambda command, **kw: subprocess.CompletedProcess(command, owner_probe.owner_probe_main(command[-1]))) # Keep pcb_processes, _processes, _process_details and release validation real. state = repair_release_state(request, target, complete_native_success(target)) assert 'error' not in state assert queried == list(names) assert state['safe_to_continue'] is (owner is None) assert state['remaining_pids'] == ([] if owner is None else [456]) assert state['database_exclusive'] is (owner is None) @pytest.mark.parametrize('name', [ 'other.exe', 'icdbprojectbackup.exe', "iCDBProjectBackup.exe' OR Name='other.exe", "ReuseBlockImporter.exe' OR Name='other.exe", ]) def test_repair_process_queries_still_reject_arbitrary_input(monkeypatch, name): import win32com.client from cbb_refresh_verify.mentor_adapter import _process_details monkeypatch.setattr(win32com.client, 'GetObject', lambda *a: pytest.fail('Unsupported name reached WMI')) with pytest.raises(ValueError, match='Unsupported process query'): _process_details(name) def real_shape_repair_fixture(tmp_path, monkeypatch, scenario, window_state='loads'): """Replay recorded UI structures through the real bounded Output reader.""" from copy import deepcopy from types import SimpleNamespace from cbb_refresh_verify import native_repair_ui actual_output_reader = native_repair_ui._native_output ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario) capture = json.loads((Path(__file__).parent/'fixtures/icdb-repair-startup-windows-sanitized.json').read_text('utf-8')) project = json.loads(job.read_text('utf-8'))['project'] original_windows, operation_output = ui._windows, ui._native_output polls = [] current = {'loading': True} def windows(pid): polls.append(ui.time.monotonic()) loading = len(polls) <= 2 or window_state == 'shell_stuck' if loading: assert not actions, 'Startup shell must never receive a command' original = original_windows(pid) main = deepcopy(capture['startup_shell']) current['loading'] = loading if not loading: main['title'] = capture['loaded_title_prefix']+project if window_state == 'wrong_target': main['title'] = capture['loaded_title_prefix']+'C:\\Other\\other.prj' if window_state == 'shell_after_invoke' and actions: main['title'] = 'iCDB Project Backup' auxiliary = deepcopy(capture['auxiliary_windows']) if window_state == 'named_aux': auxiliary[0]['title'] = 'Unrecognized prompt' if window_state == 'lookalike_aux': auxiliary[0]['class'] += '.Other' if window_state == 'duplicate_shell' and loading: auxiliary.append({**deepcopy(main), 'hwnd': 101}) if window_state == 'duplicate_target' and not loading: auxiliary.append({**deepcopy(main), 'hwnd': 101}) return [main, *original[1:], *auxiliary] class Readback: def __call__(self, hwnd, message, length, buffer, flags, timeout, copied): assert hwnd == 400 if window_state == 'missing_output': return 0 text = '' if current['loading'] else capture['loaded_output']+operation_output([]) if window_state == 'busy_loading': text = 'Project is in use. Full functionality is unavailable.' ui.ctypes.cast(buffer, ui.ctypes.POINTER(ui.ctypes.c_wchar * length)).contents.value = text copied._obj.value = len(text) return 1 monkeypatch.setattr(ui, '_windows', windows) monkeypatch.setattr(ui.ctypes, 'WinDLL', lambda *a, **kw: SimpleNamespace(SendMessageTimeoutW=Readback())) monkeypatch.setattr(ui, '_native_output', actual_output_reader) return ui, root, job, actions, polls @pytest.mark.parametrize('scenario,expected,closed', [ ('failed', 'MISSING_HEALTHY_BACKUP', True), ('success', 'REPAIRED', True), ('restore', 'RESTORED_REVIEW_REQUIRED', True), ('busy', 'DATABASE_BUSY', False), ('unknown', 'UNKNOWN_DIALOG', False), ]) def test_recorded_startup_shell_loads_target_with_input_indicator_windows( tmp_path, monkeypatch, scenario, expected, closed): import win32con ui, root, job, actions, polls = real_shape_repair_fixture(tmp_path, monkeypatch, scenario) assert ui.repair_worker_main(job) == (0 if scenario == 'success' else 1) result = json.loads((root/'repair-result.json').read_text('utf-8')) assert len(polls) >= 4 and polls[2] >= .4 assert result['status'] == expected assert actions[:2] == [(100, win32con.WM_COMMAND), (201, win32con.BM_CLICK)] assert ((100, win32con.WM_CLOSE) in actions) is closed assert result['release']['safe_to_continue'] is closed assert 'Project is not in use' in json.loads((root/'native-output.json').read_text('utf-8'))['baseline'] @pytest.mark.parametrize('state,expected', [ ('shell_stuck', 'TIMEOUT_UNRELEASED'), ('wrong_target', 'UNKNOWN_DIALOG'), ('duplicate_shell', 'UNKNOWN_DIALOG'), ('duplicate_target', 'UNKNOWN_DIALOG'), ('named_aux', 'UNKNOWN_DIALOG'), ('lookalike_aux', 'UNKNOWN_DIALOG'), ('missing_output', 'TIMEOUT_UNRELEASED'), ('busy_loading', 'DATABASE_BUSY'), ]) def test_recorded_startup_shape_retains_unconfirmed_or_unknown_state(tmp_path, monkeypatch, state, expected): ui, root, job, actions, polls = real_shape_repair_fixture(tmp_path, monkeypatch, 'failed', state) assert ui.repair_worker_main(job) == 1 result = json.loads((root/'repair-result.json').read_text('utf-8')) assert result['status'] == expected assert actions == [] assert result['release']['safe_to_continue'] is False def test_generic_shell_after_invocation_is_not_a_startup_exception(tmp_path, monkeypatch): import win32con ui, root, job, actions, polls = real_shape_repair_fixture(tmp_path, monkeypatch, 'failed', 'shell_after_invoke') assert ui.repair_worker_main(job) == 1 result = json.loads((root/'repair-result.json').read_text('utf-8')) assert result['status'] == 'UNKNOWN_DIALOG' assert actions == [(100, win32con.WM_COMMAND)] assert result['release']['safe_to_continue'] is False @pytest.mark.parametrize('verdict,expected', [ ('', 'UNCONFIRMED'), ("Project is not in use. Full iCDB Project Backup's functionality is available.", 'UNCONFIRMED'), ('Project is in use. Full functionality is unavailable.', 'DATABASE_BUSY'), ]) def test_native_usage_check_progress_waits_for_actual_busy_verdict(verdict, expected): from cbb_refresh_verify.native_repair_ui import classify_repair_evidence output = '[2026-11-02 12:00:00] Checking if project is in use.\r\n' output += '[2026-11-02 12:00:00] '+verdict assert classify_repair_evidence('', '', '', output)['outcome'] == expected