#!/usr/bin/env python3
|
"""Transactionally rebuild managed Agent Team paths with ordinary-failure rollback."""
|
|
from __future__ import annotations
|
|
import argparse
|
import hashlib
|
import json
|
import os
|
import re
|
import shutil
|
import subprocess
|
import sys
|
from dataclasses import dataclass, field
|
from pathlib import Path, PurePosixPath
|
|
|
START = "<!-- AI-AGENT-SYSTEM:START -->"
|
END = "<!-- AI-AGENT-SYSTEM:END -->"
|
LEGACY_START = "<!-- AI-AGENT-ROUTING:START -->"
|
LEGACY_END = "<!-- AI-AGENT-ROUTING:END -->"
|
MARKER = ".bootstrap-staging.json"
|
LOCK = ".ai-agent-system-bootstrap.lock"
|
DIGEST = re.compile(r"^[0-9a-f]{64}$")
|
IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
|
|
@dataclass
|
class TransactionState:
|
installed_new_skills: set[str] = field(default_factory=set)
|
moved_old_skills: set[str] = field(default_factory=set)
|
old_ai_moved: bool = False
|
new_ai_installed: bool = False
|
old_agents_moved: bool = False
|
new_agents_installed: bool = False
|
|
|
def configure_stdio() -> None:
|
for stream in (sys.stdout, sys.stderr):
|
if hasattr(stream, "reconfigure"):
|
stream.reconfigure(encoding="utf-8", errors="strict")
|
|
|
def parse_args() -> argparse.Namespace:
|
parser = argparse.ArgumentParser()
|
parser.add_argument("--repository", required=True)
|
parser.add_argument("--staging", required=True)
|
parser.add_argument("--expected-digest", required=True)
|
parser.add_argument("--expected-run-id", required=True)
|
parser.add_argument("--expected-blueprint-id", required=True)
|
parser.add_argument("--allow-warning", action="append", default=[])
|
return parser.parse_args()
|
|
|
def load_json(path: Path) -> dict:
|
value = json.loads(path.read_text(encoding="utf-8-sig"))
|
if not isinstance(value, dict):
|
raise ValueError(f"JSON root must be an object: {path}")
|
return value
|
|
|
def is_reparse(path: Path) -> bool:
|
return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction())
|
|
|
def under(path: Path, root: Path) -> bool:
|
try:
|
path.relative_to(root)
|
return True
|
except ValueError:
|
return False
|
|
|
def ensure_safe_chain(root: Path, relative: str) -> Path:
|
current = root
|
resolved_root = root.resolve(strict=True)
|
for part in PurePosixPath(relative).parts:
|
current /= part
|
if (current.exists() or current.is_symlink()) and is_reparse(current):
|
raise ValueError(f"managed path chain contains a symlink or junction: {relative}")
|
if not under(current.resolve(strict=False), resolved_root):
|
raise ValueError(f"managed path resolves outside the repository: {relative}")
|
return current
|
|
|
def walk_without_reparse(path: Path) -> list[Path]:
|
if not path.exists():
|
return []
|
files: list[Path] = []
|
pending = [path]
|
while pending:
|
current = pending.pop()
|
if is_reparse(current):
|
raise ValueError(f"managed tree contains a symlink or junction: {current}")
|
if current.is_dir():
|
pending.extend(current.iterdir())
|
elif current.is_file():
|
files.append(current)
|
return files
|
|
|
def write_marker(path: Path, marker: dict, status: str, error: str | None = None) -> None:
|
marker["status"] = status
|
if error:
|
marker["error"] = error
|
else:
|
marker.pop("error", None)
|
path.write_text(json.dumps(marker, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
|
def managed_skill_names(manifest: dict) -> set[str]:
|
names: set[str] = set()
|
for value in manifest["managed_paths"]:
|
match = re.fullmatch(r"\.agents/skills/([a-z0-9]+(?:-[a-z0-9]+)*)", value)
|
if match:
|
names.add(match.group(1))
|
return names
|
|
|
def legacy_ai_is_owned(ai_root: Path, agents_path: Path) -> bool:
|
allowed = {"agents", "skills", "workflows", "orchestration", "runs", "bootstrap-manifest.yaml"}
|
if not ai_root.is_dir() or is_reparse(ai_root):
|
return False
|
try:
|
walk_without_reparse(ai_root)
|
except ValueError:
|
return False
|
entries = {path.name for path in ai_root.iterdir()}
|
if (
|
not (ai_root / "agents").is_dir()
|
or not (ai_root / "workflows").is_dir()
|
or not entries <= allowed
|
or not agents_path.is_file()
|
or is_reparse(agents_path)
|
):
|
return False
|
try:
|
text = agents_path.read_bytes().decode("utf-8")
|
except UnicodeDecodeError:
|
return False
|
current = text.count(START) == 1 and text.count(END) == 1 and text.index(START) < text.index(END)
|
legacy = text.count(LEGACY_START) == 1 and text.count(LEGACY_END) == 1 and text.index(LEGACY_START) < text.index(LEGACY_END)
|
return current ^ legacy
|
|
|
def extract_generated_block(path: Path) -> str:
|
text = path.read_bytes().decode("utf-8")
|
if text.count(START) != 1 or text.count(END) != 1:
|
raise ValueError("AGENTS.generated.md must contain exactly one current marker pair")
|
start = text.index(START)
|
end = text.index(END, start) + len(END)
|
return text[start:end]
|
|
|
def merge_agents(existing: Path, generated_block: str) -> str:
|
if not existing.exists():
|
return generated_block + "\n"
|
if is_reparse(existing):
|
raise ValueError("AGENTS.md must not be a symlink or junction")
|
text = existing.read_bytes().decode("utf-8")
|
current = (text.count(START), text.count(END))
|
legacy = (text.count(LEGACY_START), text.count(LEGACY_END))
|
if current == (1, 1) and legacy == (0, 0):
|
start, end_marker = START, END
|
elif current == (0, 0) and legacy == (1, 1):
|
start, end_marker = LEGACY_START, LEGACY_END
|
elif current == (0, 0) and legacy == (0, 0):
|
separator = "" if not text else ("" if text.endswith(("\n", "\r")) else "\n") + "\n"
|
newline = "\r\n" if "\r\n" in text else "\n"
|
return text + separator.replace("\n", newline) + generated_block.replace("\n", newline) + newline
|
else:
|
raise ValueError("AGENTS.md contains conflicting, repeated, or incomplete managed markers")
|
first = text.index(start)
|
last = text.index(end_marker, first) + len(end_marker)
|
newline = "\r\n" if "\r\n" in text else "\n"
|
return text[:first] + generated_block.replace("\n", newline) + text[last:]
|
|
|
def has_managed_marker(path: Path) -> bool:
|
if not path.exists():
|
return False
|
text = path.read_bytes().decode("utf-8")
|
return any(marker in text for marker in (START, END, LEGACY_START, LEGACY_END))
|
|
|
def run_validator(root: Path, allowed_warnings: set[str]) -> dict:
|
validator = Path(__file__).with_name("validate-structure.py")
|
result = subprocess.run(
|
[sys.executable, str(validator), "--root", str(root), "--json"],
|
capture_output=True,
|
text=True,
|
encoding="utf-8",
|
check=False,
|
)
|
if not result.stdout.strip():
|
raise RuntimeError(f"validator produced no report: {result.stderr.strip()}")
|
report = json.loads(result.stdout)
|
warning_codes = {item.get("code") for item in report.get("warnings", [])}
|
unapproved = warning_codes - allowed_warnings
|
accepted = report.get("status") in {"passed", "passed-with-warnings"} and not report.get("errors") and not unapproved
|
if result.returncode != 0 or not accepted:
|
raise ValueError(
|
f"structural validation failed: errors={report.get('errors', [])}, "
|
f"unapproved_warnings={sorted(unapproved)}"
|
)
|
return report
|
|
|
def remove_path(path: Path) -> None:
|
if not path.exists() and not path.is_symlink():
|
return
|
if path.is_dir() and not is_reparse(path):
|
shutil.rmtree(path)
|
else:
|
path.unlink()
|
|
|
def state_digest(repository: Path, paths: list[Path]) -> str:
|
digest = hashlib.sha256()
|
for path in sorted(set(paths), key=lambda value: str(value).casefold()):
|
relative = path.relative_to(repository).as_posix()
|
digest.update(relative.encode("utf-8") + b"\0")
|
if not path.exists() and not path.is_symlink():
|
digest.update(b"missing\0")
|
continue
|
if is_reparse(path):
|
raise ValueError(f"target state contains a symlink or junction: {relative}")
|
if path.is_file():
|
digest.update(b"file\0" + path.read_bytes())
|
continue
|
digest.update(b"directory\0")
|
for child in sorted(walk_without_reparse(path), key=lambda value: value.relative_to(repository).as_posix().casefold()):
|
child_relative = child.relative_to(repository).as_posix()
|
digest.update(child_relative.encode("utf-8") + b"\0" + child.read_bytes())
|
return digest.hexdigest()
|
|
|
def attempt(label: str, action, errors: list[str]) -> None:
|
try:
|
action()
|
except Exception as exc: # continue every remaining compensation
|
errors.append(f"{label}: {exc}")
|
|
|
def rollback(
|
repository: Path,
|
staging: Path,
|
marker_path: Path,
|
marker: dict,
|
state: TransactionState,
|
target_ai: Path,
|
target_agents: Path,
|
target_skills_root: Path,
|
agents_root_existed: bool,
|
skills_root_existed: bool,
|
cause: Exception,
|
) -> list[str]:
|
backup = staging / ".rollback"
|
errors: list[str] = []
|
if state.new_agents_installed:
|
attempt("remove new AGENTS.md", lambda: remove_path(target_agents), errors)
|
if state.old_agents_moved:
|
attempt("restore old AGENTS.md", lambda: os.replace(backup / "AGENTS.md", target_agents), errors)
|
for name in sorted(state.installed_new_skills):
|
attempt(f"remove new Skill {name}", lambda name=name: remove_path(target_skills_root / name), errors)
|
for name in sorted(state.moved_old_skills):
|
source = backup / ".agents" / "skills" / name
|
attempt(f"restore old Skill {name}", lambda source=source, name=name: os.replace(source, target_skills_root / name), errors)
|
|
def remove_empty_backup_skill_parents() -> None:
|
skills = backup / ".agents" / "skills"
|
agents = backup / ".agents"
|
if skills.is_dir() and not any(skills.iterdir()):
|
skills.rmdir()
|
if agents.is_dir() and not any(agents.iterdir()):
|
agents.rmdir()
|
|
attempt("remove empty rollback Skill parents", remove_empty_backup_skill_parents, errors)
|
if state.new_ai_installed:
|
attempt("remove new .ai", lambda: remove_path(target_ai), errors)
|
if state.old_ai_moved:
|
attempt("restore old .ai", lambda: os.replace(backup / ".ai", target_ai), errors)
|
|
def remove_empty_skills_root() -> None:
|
if not skills_root_existed and target_skills_root.is_dir() and not any(target_skills_root.iterdir()):
|
target_skills_root.rmdir()
|
|
def remove_empty_agents_root() -> None:
|
agents_root = repository / ".agents"
|
if not agents_root_existed and agents_root.is_dir() and not any(agents_root.iterdir()):
|
agents_root.rmdir()
|
|
attempt("remove empty .agents/skills", remove_empty_skills_root, errors)
|
attempt("remove empty .agents", remove_empty_agents_root, errors)
|
attempt("write rolled-back marker", lambda: write_marker(marker_path, marker, "rolled-back", str(cause)), errors)
|
return errors
|
|
|
def main() -> int:
|
configure_stdio()
|
args = parse_args()
|
if not DIGEST.fullmatch(args.expected_digest):
|
raise ValueError("expected-digest must be a lowercase SHA-256 digest")
|
if not IDENTIFIER.fullmatch(args.expected_run_id) or not IDENTIFIER.fullmatch(args.expected_blueprint_id):
|
raise ValueError("expected run and blueprint identifiers are invalid")
|
allowed_warnings = set(args.allow_warning)
|
|
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)
|
if not repository.is_dir():
|
raise ValueError("repository must be a directory")
|
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)
|
if staging.parent != repository.parent or not staging.name.startswith(f".{repository.name}.ai-agent-system-"):
|
raise ValueError("staging path is not an owned sibling of the repository")
|
|
marker_path = staging / MARKER
|
if is_reparse(marker_path):
|
raise ValueError("staging marker must not be a symlink or junction")
|
marker = load_json(marker_path)
|
if marker.get("schema_version") != 1 or not isinstance(marker.get("run_id"), str):
|
raise ValueError("staging marker is invalid")
|
if Path(marker.get("repository_root", "")).resolve() != repository:
|
raise ValueError("staging marker repository mismatch")
|
if staging.name != f".{repository.name}.ai-agent-system-{marker['run_id']}":
|
raise ValueError("staging directory name does not match marker run_id")
|
|
pre_report = run_validator(staging, allowed_warnings)
|
if pre_report["candidate_digest"] != args.expected_digest:
|
raise ValueError("validated staging digest differs from expected-digest")
|
if pre_report.get("run_id") != args.expected_run_id or pre_report.get("blueprint_id") != args.expected_blueprint_id:
|
raise ValueError("validated staging identifiers differ from the accepted ValidationReport")
|
new_manifest = load_json(staging / ".ai" / "bootstrap-manifest.json")
|
if new_manifest["run_id"] != marker["run_id"] or args.expected_run_id != marker["run_id"]:
|
raise ValueError("run_id differs across staging marker, manifest, and validation report")
|
if new_manifest["blueprint_id"] != args.expected_blueprint_id:
|
raise ValueError("blueprint_id differs across manifest and validation report")
|
new_skills = managed_skill_names(new_manifest)
|
|
lock_path = repository / LOCK
|
lock_fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
os.close(lock_fd)
|
cleanup_warnings: list[str] = []
|
operation_error: Exception | None = None
|
try:
|
target_ai = ensure_safe_chain(repository, ".ai")
|
target_agents = ensure_safe_chain(repository, "AGENTS.md")
|
ensure_safe_chain(repository, ".agents")
|
target_skills_root = ensure_safe_chain(repository, ".agents/skills")
|
for name in new_skills:
|
ensure_safe_chain(repository, f".agents/skills/{name}")
|
|
old_manifest_path = target_ai / "bootstrap-manifest.json"
|
if target_ai.exists() and old_manifest_path.exists():
|
run_validator(repository, allowed_warnings)
|
old_manifest = load_json(old_manifest_path)
|
elif target_ai.exists():
|
if not legacy_ai_is_owned(target_ai, target_agents):
|
raise ValueError("existing .ai directory is not a recognized managed or legacy Agent Team")
|
old_manifest = {"managed_paths": []}
|
else:
|
old_manifest = {"managed_paths": []}
|
old_skills = managed_skill_names(old_manifest)
|
if not target_ai.exists() and has_managed_marker(target_agents):
|
raise ValueError("AGENTS.md has an orphan managed marker without an owned .ai Agent Team")
|
expected_mode = "rebuild" if target_ai.exists() else "initialize"
|
if new_manifest["generation_mode"] != expected_mode:
|
raise ValueError(f"manifest generation_mode must be {expected_mode} for the current target state")
|
for name in old_skills:
|
ensure_safe_chain(repository, f".agents/skills/{name}")
|
|
agents_root_existed = (repository / ".agents").exists()
|
skills_root_existed = target_skills_root.exists()
|
for name in new_skills:
|
collision = target_skills_root / name
|
if collision.exists() and name not in old_skills:
|
raise ValueError(f"generated Skill would overwrite an unmanaged repository Skill: {name}")
|
|
affected = [target_ai, target_agents]
|
affected.extend(target_skills_root / name for name in old_skills | new_skills)
|
expected_target_state = state_digest(repository, affected)
|
generated_block = extract_generated_block(staging / "AGENTS.generated.md")
|
next_agents = staging / "AGENTS.next.md"
|
next_agents.write_bytes(merge_agents(target_agents, generated_block).encode("utf-8"))
|
if state_digest(repository, affected) != expected_target_state:
|
raise RuntimeError("target state changed while AGENTS.md was being merged")
|
backup = staging / ".rollback"
|
if backup.exists():
|
raise FileExistsError("rollback directory already exists")
|
backup.mkdir()
|
if state_digest(repository, affected) != expected_target_state:
|
raise RuntimeError("target state changed after it was inspected")
|
|
state = TransactionState()
|
try:
|
write_marker(marker_path, marker, "replacing")
|
if target_ai.exists():
|
os.replace(target_ai, backup / ".ai")
|
state.old_ai_moved = True
|
for name in sorted(old_skills):
|
source = target_skills_root / name
|
if source.exists():
|
destination = backup / ".agents" / "skills" / name
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
os.replace(source, destination)
|
state.moved_old_skills.add(name)
|
os.replace(staging / ".ai", target_ai)
|
state.new_ai_installed = True
|
if new_skills:
|
target_skills_root.mkdir(parents=True, exist_ok=True)
|
for name in sorted(new_skills):
|
os.replace(staging / ".agents" / "skills" / name, target_skills_root / name)
|
state.installed_new_skills.add(name)
|
if target_agents.exists():
|
os.replace(target_agents, backup / "AGENTS.md")
|
state.old_agents_moved = True
|
os.replace(next_agents, target_agents)
|
state.new_agents_installed = True
|
|
post_report = run_validator(repository, allowed_warnings)
|
if post_report["candidate_digest"] != args.expected_digest:
|
raise ValueError("installed candidate digest differs from the accepted validation report")
|
except Exception as exc:
|
rollback_errors = rollback(
|
repository,
|
staging,
|
marker_path,
|
marker,
|
state,
|
target_ai,
|
target_agents,
|
target_skills_root,
|
agents_root_existed,
|
skills_root_existed,
|
exc,
|
)
|
if rollback_errors:
|
details = "; ".join(rollback_errors)
|
raise RuntimeError(f"replacement failed: {exc}; rollback requires manual recovery: {details}") from exc
|
raise
|
except Exception as exc:
|
operation_error = exc
|
finally:
|
try:
|
lock_path.unlink(missing_ok=True)
|
except OSError as exc:
|
if operation_error is not None:
|
raise RuntimeError(f"{operation_error}; lock cleanup failed: {exc}") from operation_error
|
cleanup_warnings.append(f"lock cleanup failed: {exc}")
|
|
if operation_error is not None:
|
raise operation_error
|
|
try:
|
write_marker(marker_path, marker, "complete")
|
shutil.rmtree(staging / ".rollback")
|
shutil.rmtree(staging)
|
except OSError as exc:
|
cleanup_warnings.append(f"staging cleanup failed: {exc}")
|
result = {"status": "complete", "repository_root": str(repository), "candidate_digest": args.expected_digest}
|
if cleanup_warnings:
|
result["cleanup_warning"] = "; ".join(cleanup_warnings)
|
result["staging_root"] = str(staging)
|
print(json.dumps(result, 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)
|