"""Conservative unfinished-operation protection. The approval store must be dedicated to one site. Callers must hold the shared deployment lock. """ import re from core.migration_archive import ( ARCHIVE_SUFFIX, verify_archived_group, ) class OperationBlocked(RuntimeError): """Existing evidence prevents a new operation.""" class OperationGuard: def __init__(self, store): self.store = store def inspect(self): blockers = [] try: self.store.validate_directory() entries = list(self.store.directory.iterdir()) archived_names = set() for path in entries: name = path.name if ( name.endswith(ARCHIVE_SUFFIX) and re.fullmatch( r"[a-f0-9]{32}", name[:-len(ARCHIVE_SUFFIX)], ) is not None ): archived_names.update( verify_archived_group( self.store, name[:32], ) ) for path in entries: name = path.name if name in archived_names: continue if name == ".approval.lock": continue if name == ".deployment.lock": continue if re.fullmatch( r"[a-f0-9]{32}\.approval\.json", name, ): # An unused approval is not an # unfinished migration. self.store.load(name[:32]) continue blockers.append(name) except Exception: raise OperationBlocked( "Approval store cannot be safely inspected" ) from None return { "format_version": 1, "status": "BLOCKED" if blockers else "CLEAR", "blockers": sorted(blockers), "automatic_cleanup": False, } def require_clear(self): report = self.inspect() if report["status"] != "CLEAR": raise OperationBlocked( "Unfinished migration evidence requires review" ) return report