"""Safe, scoped quarantine for worker-created untracked scratch artifacts.""" from __future__ import annotations import hashlib import shutil import subprocess from dataclasses import dataclass from pathlib import Path from typing import Callable from afk_developer.event_store import DurableEventStore @dataclass(frozen=True) class QuarantinedArtifact: project_path: str sha256: str byte_count: int quarantine_path: Path @dataclass(frozen=True) class QuarantineResult: moved: list[QuarantinedArtifact] blocked_paths: list[str] @property def passed(self) -> bool: return bool(self.moved) and not self.blocked_paths def quarantine_unreported_untracked( project_dir: Path | str, reported_files: list[str], quarantine_dir: Path, *, before_move: Callable[[QuarantinedArtifact], None] | None = None, after_move: Callable[[QuarantinedArtifact], None] | None = None, ) -> QuarantineResult: """Copy-verify-remove only safe, unreported Git-untracked regular files. The original is not discarded until a byte-identical copy exists outside the project. Paths that are reported, unsafe, missing, directories, or symlinks remain in place and are returned as blocked rather than guessed at. """ root = Path(project_dir).resolve() reported = {_normalized_project_path(root, path) for path in reported_files} reported.discard("") candidates = _untracked_paths(root) moved: list[QuarantinedArtifact] = [] blocked: list[str] = [] for raw_path in candidates: if raw_path in reported: continue source = (root / raw_path).resolve() if not source.is_relative_to(root) or not source.is_file() or source.is_symlink(): blocked.append(raw_path) continue content = source.read_bytes() digest = hashlib.sha256(content).hexdigest() artifact = QuarantinedArtifact( project_path=raw_path, sha256=digest, byte_count=len(content), quarantine_path=quarantine_dir / f"{digest}-{Path(raw_path).name}", ) if before_move: before_move(artifact) artifact.quarantine_path.parent.mkdir(parents=True, exist_ok=True) if artifact.quarantine_path.exists(): if ( not artifact.quarantine_path.is_file() or _sha256_file(artifact.quarantine_path) != digest ): blocked.append(raw_path) continue else: shutil.copy2(source, artifact.quarantine_path) if _sha256_file(artifact.quarantine_path) != digest: blocked.append(raw_path) continue try: source.unlink() except OSError: blocked.append(raw_path) continue moved.append(artifact) if after_move: after_move(artifact) return QuarantineResult(moved=moved, blocked_paths=sorted(blocked)) def reconcile_completed_quarantine_effects(store: DurableEventStore) -> list[str]: """Return pending quarantine effects proven complete without changing files. An intent can survive a crash after the source was removed but before the result event was appended. Reconciliation only recognizes the one unambiguous state: source absent and a byte-identical quarantined copy present. All other states remain pending for inspection; it never retries a copy or removal. """ pending: dict[str, dict[str, object]] = {} for event in store.read_events(): payload = event.payload if event.kind == "effect_intended" and payload.get("operation") == "quarantine": pending[str(payload["effect_id"])] = payload elif event.kind == "effect_completed": pending.pop(str(payload["effect_id"]), None) completed: list[str] = [] for effect_id, payload in pending.items(): source = Path(str(payload.get("source_path", ""))) destination = Path(str(payload.get("quarantine_path", ""))) expected_hash = str(payload.get("sha256", "")) if ( expected_hash and not source.exists() and destination.is_file() and _sha256_file(destination) == expected_hash ): completed.append(effect_id) return completed def _untracked_paths(project_root: Path) -> list[str]: try: result = subprocess.run( ["git", "ls-files", "--others", "--exclude-standard"], cwd=str(project_root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30, check=False, ) except (OSError, subprocess.TimeoutExpired): return [] if result.returncode != 0: return [] return sorted( path for path in result.stdout.splitlines() if path and _is_safe_relative_path(path) ) def _normalized_project_path(project_root: Path, raw_path: str) -> str: candidate = (project_root / raw_path).resolve() if not candidate.is_relative_to(project_root): return "" return candidate.relative_to(project_root).as_posix() def _is_safe_relative_path(path: str) -> bool: candidate = Path(path) return not candidate.is_absolute() and ".." not in candidate.parts and bool(path) def _sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()