import os from pathlib import Path from typing import Optional from linux_updater.core.health import HealthChecker from linux_updater.managers.base import PackageManager from linux_updater.models import CheckResult class RemediationEngine: def __init__(self, manager: PackageManager) -> None: self.manager = manager def can_remediate(self, check: CheckResult) -> bool: if not check.can_remediate: return False return check.remediation_id in {"clean_cache", "remove_stale_lock", "repair_package_db"} def remediate(self, check: CheckResult) -> bool: if not self.can_remediate(check): return False if check.remediation_id == "clean_cache": return self.clean_cache() elif check.remediation_id == "remove_stale_lock": return self.remove_stale_lock(check.message) elif check.remediation_id == "repair_package_db": return self.repair_package_db() return False def repair_package_db(self) -> bool: try: res = self.manager.repair_db() if hasattr(res, "success"): return bool(res.success) return True except Exception: return False def clean_cache(self) -> bool: try: res = self.manager.clean_cache() # If manager returns CommandResult or bool if hasattr(res, "success"): return bool(res.success) return True except Exception: return False def remove_stale_lock(self, lock_path_str: str) -> bool: lock_p = Path(lock_path_str) if not lock_p.exists(): return True # Safety check: if lockfile contains a PID, ensure it is truly dead try: content = lock_p.read_text().strip() if content and content.isdigit(): pid = int(content) if HealthChecker._is_pid_alive(pid): # Process is actually alive! Do not delete! return False except Exception: pass try: lock_p.unlink() return True except Exception: return False