chunhualin1
2026-07-15 1a1ec5d071834d7720039ca94fc0c357d05d67c9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/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)