| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155 |
- """Deterministic guard for cross-tool Agent Team operations.
- This script is designed to be invoked by Devin/Cursor/Codex hooks or directly.
- It validates that the agent is operating in the expected repository, branch,
- worktree, owned paths, and that protected operations are not performed.
- """
- from __future__ import annotations
- import argparse
- import json
- import subprocess
- import sys
- from pathlib import Path
- from typing import Any
- PROTECTED_ROOTS = [
- Path("C:/Users/Administrator/Agentworkspace/CPLD"),
- ]
- DENIED_COMMANDS = [
- "git reset",
- "git clean",
- "git stash",
- "git checkout -f",
- "git branch -f",
- "git update-ref",
- ]
- HARDWARE_COMMANDS = [
- "com",
- "jtag",
- "program",
- "prog",
- "programmer",
- "td_commands_prompt",
- ]
- def _repo_root(cwd: Path) -> Path | None:
- try:
- result = subprocess.run(
- ["git", "rev-parse", "--show-toplevel"],
- cwd=cwd,
- capture_output=True,
- text=True,
- check=True,
- )
- return Path(result.stdout.strip()).resolve()
- except (OSError, subprocess.CalledProcessError):
- return None
- def _current_branch(repo: Path) -> str | None:
- try:
- result = subprocess.run(
- ["git", "branch", "--show-current"],
- cwd=repo,
- capture_output=True,
- text=True,
- check=True,
- )
- return result.stdout.strip()
- except (OSError, subprocess.CalledProcessError):
- return None
- def _load_config(repo: Path) -> dict[str, Any]:
- config_path = repo / ".devin" / "config.json"
- if config_path.is_file():
- try:
- return json.loads(config_path.read_text(encoding="utf-8-sig"))
- except (OSError, json.JSONDecodeError):
- pass
- return {}
- def _is_under(path: Path, root: Path) -> bool:
- try:
- path.resolve().relative_to(root.resolve())
- return True
- except ValueError:
- return False
- def _check_command(command: str) -> list[str]:
- failures: list[str] = []
- lowered = command.lower()
- for denied in DENIED_COMMANDS:
- if denied in lowered:
- failures.append(f"denied_git_command:{denied}")
- for hw in HARDWARE_COMMANDS:
- if hw in lowered and "prompt" not in lowered:
- failures.append(f"potential_hardware_access:{hw}")
- return failures
- def _check_path(target: Path, repo: Path, config: dict[str, Any]) -> list[str]:
- failures: list[str] = []
- denied_paths = config.get("denied_paths", []) + [str(r) for r in PROTECTED_ROOTS]
- for denied_str in denied_paths:
- denied = Path(denied_str).resolve()
- if _is_under(target, denied) or target.resolve() == denied:
- failures.append(f"protected_path:{denied}")
- return failures
- def _check_event(event: str, args: argparse.Namespace) -> dict[str, Any]:
- cwd = Path(args.cwd or ".").resolve()
- repo = _repo_root(cwd)
- result: dict[str, Any] = {
- "event": event,
- "cwd": str(cwd),
- "repo_root": str(repo) if repo else None,
- "branch": _current_branch(repo) if repo else None,
- "allowed": True,
- "failures": [],
- }
- if repo is None:
- result["allowed"] = False
- result["failures"].append("not_a_git_repository")
- return result
- config = _load_config(repo)
- result["config_loaded"] = bool(config)
- if event in ("pre_tool_use", "post_tool_use") and args.command:
- result["failures"].extend(_check_command(args.command))
- if args.target_path:
- target = Path(args.target_path).resolve()
- result["failures"].extend(_check_path(target, repo, config))
- if result["failures"]:
- result["allowed"] = False
- return result
- def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser(description="Agent guard for cross-tool operations")
- parser.add_argument("--event", required=True)
- parser.add_argument("--cwd", default=None)
- parser.add_argument("--repo-root", default=None)
- parser.add_argument("--tool", default=None)
- parser.add_argument("--target-path", default=None)
- parser.add_argument("--command", default=None)
- parser.add_argument("--exit-code", type=int, default=0)
- args = parser.parse_args(argv)
- result = _check_event(args.event, args)
- print(json.dumps(result, indent=2, sort_keys=True))
- return 0 if result["allowed"] else 1
- if __name__ == "__main__":
- sys.exit(main())
|