#!/usr/bin/env python3 """Remove a staging directory only after its ownership marker is verified.""" from __future__ import annotations import argparse import json import shutil import sys from pathlib import Path MARKER = ".bootstrap-staging.json" REMOVABLE = {"created", "validation-failed", "render-failed", "rolled-back", "complete"} def configure_stdio() -> None: for stream in (sys.stdout, sys.stderr): if hasattr(stream, "reconfigure"): stream.reconfigure(encoding="utf-8", errors="strict") def is_reparse(path: Path) -> bool: return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction()) def reject_reparse_tree(root: Path) -> None: pending = [root] while pending: current = pending.pop() if is_reparse(current): raise ValueError(f"staging tree contains a symlink or junction: {current}") if current.is_dir(): pending.extend(current.iterdir()) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--repository", required=True) parser.add_argument("--staging", required=True) return parser.parse_args() def read_marker(staging: Path) -> dict: marker_path = staging / MARKER return json.loads(marker_path.read_text(encoding="utf-8")) def main() -> int: configure_stdio() args = parse_args() raw_repository = Path(args.repository).absolute() if is_reparse(raw_repository): raise ValueError("repository path must not be a symlink or junction") repository = raw_repository.resolve(strict=True) raw_staging = Path(args.staging).absolute() if is_reparse(raw_staging): raise ValueError("staging path must not be a symlink or junction") staging = raw_staging.resolve(strict=True) expected_prefix = f".{repository.name}.ai-agent-system-" if staging.parent != repository.parent or not staging.name.startswith(expected_prefix): raise ValueError("staging path is not an owned sibling of the repository") marker = read_marker(staging) if Path(marker.get("repository_root", "")).resolve() != repository: raise ValueError("staging marker repository mismatch") if staging.name != f".{repository.name}.ai-agent-system-{marker.get('run_id')}": raise ValueError("staging directory name does not match marker run_id") if marker.get("status") not in REMOVABLE: raise ValueError(f"staging status is not removable: {marker.get('status')}") backup = staging / ".rollback" if backup.exists() and any(backup.iterdir()): raise ValueError("rollback backup is not empty") reject_reparse_tree(staging) shutil.rmtree(staging) print(json.dumps({"status": "removed", "staging_root": str(staging)}, ensure_ascii=False)) return 0 if __name__ == "__main__": try: raise SystemExit(main()) except Exception as exc: configure_stdio() print(json.dumps({"status": "failed", "error": str(exc)}, ensure_ascii=False), file=sys.stderr) raise SystemExit(1)