agent_guard.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """Deterministic guard for cross-tool Agent Team operations.
  2. This script is designed to be invoked by Devin/Cursor/Codex hooks or directly.
  3. It validates that the agent is operating in the expected repository, branch,
  4. worktree, owned paths, and that protected operations are not performed.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import json
  9. import subprocess
  10. import sys
  11. from pathlib import Path
  12. from typing import Any
  13. PROTECTED_ROOTS = [
  14. Path("C:/Users/Administrator/Agentworkspace/CPLD"),
  15. ]
  16. DENIED_COMMANDS = [
  17. "git reset",
  18. "git clean",
  19. "git stash",
  20. "git checkout -f",
  21. "git branch -f",
  22. "git update-ref",
  23. ]
  24. HARDWARE_COMMANDS = [
  25. "com",
  26. "jtag",
  27. "program",
  28. "prog",
  29. "programmer",
  30. "td_commands_prompt",
  31. ]
  32. def _repo_root(cwd: Path) -> Path | None:
  33. try:
  34. result = subprocess.run(
  35. ["git", "rev-parse", "--show-toplevel"],
  36. cwd=cwd,
  37. capture_output=True,
  38. text=True,
  39. check=True,
  40. )
  41. return Path(result.stdout.strip()).resolve()
  42. except (OSError, subprocess.CalledProcessError):
  43. return None
  44. def _current_branch(repo: Path) -> str | None:
  45. try:
  46. result = subprocess.run(
  47. ["git", "branch", "--show-current"],
  48. cwd=repo,
  49. capture_output=True,
  50. text=True,
  51. check=True,
  52. )
  53. return result.stdout.strip()
  54. except (OSError, subprocess.CalledProcessError):
  55. return None
  56. def _load_config(repo: Path) -> dict[str, Any]:
  57. config_path = repo / ".devin" / "config.json"
  58. if config_path.is_file():
  59. try:
  60. return json.loads(config_path.read_text(encoding="utf-8-sig"))
  61. except (OSError, json.JSONDecodeError):
  62. pass
  63. return {}
  64. def _is_under(path: Path, root: Path) -> bool:
  65. try:
  66. path.resolve().relative_to(root.resolve())
  67. return True
  68. except ValueError:
  69. return False
  70. def _check_command(command: str) -> list[str]:
  71. failures: list[str] = []
  72. lowered = command.lower()
  73. for denied in DENIED_COMMANDS:
  74. if denied in lowered:
  75. failures.append(f"denied_git_command:{denied}")
  76. for hw in HARDWARE_COMMANDS:
  77. if hw in lowered and "prompt" not in lowered:
  78. failures.append(f"potential_hardware_access:{hw}")
  79. return failures
  80. def _check_path(target: Path, repo: Path, config: dict[str, Any]) -> list[str]:
  81. failures: list[str] = []
  82. denied_paths = config.get("denied_paths", []) + [str(r) for r in PROTECTED_ROOTS]
  83. for denied_str in denied_paths:
  84. denied = Path(denied_str).resolve()
  85. if _is_under(target, denied) or target.resolve() == denied:
  86. failures.append(f"protected_path:{denied}")
  87. return failures
  88. def _check_event(event: str, args: argparse.Namespace) -> dict[str, Any]:
  89. cwd = Path(args.cwd or ".").resolve()
  90. repo = _repo_root(cwd)
  91. result: dict[str, Any] = {
  92. "event": event,
  93. "cwd": str(cwd),
  94. "repo_root": str(repo) if repo else None,
  95. "branch": _current_branch(repo) if repo else None,
  96. "allowed": True,
  97. "failures": [],
  98. }
  99. if repo is None:
  100. result["allowed"] = False
  101. result["failures"].append("not_a_git_repository")
  102. return result
  103. config = _load_config(repo)
  104. result["config_loaded"] = bool(config)
  105. if event in ("pre_tool_use", "post_tool_use") and args.command:
  106. result["failures"].extend(_check_command(args.command))
  107. if args.target_path:
  108. target = Path(args.target_path).resolve()
  109. result["failures"].extend(_check_path(target, repo, config))
  110. if result["failures"]:
  111. result["allowed"] = False
  112. return result
  113. def main(argv: list[str] | None = None) -> int:
  114. parser = argparse.ArgumentParser(description="Agent guard for cross-tool operations")
  115. parser.add_argument("--event", required=True)
  116. parser.add_argument("--cwd", default=None)
  117. parser.add_argument("--repo-root", default=None)
  118. parser.add_argument("--tool", default=None)
  119. parser.add_argument("--target-path", default=None)
  120. parser.add_argument("--command", default=None)
  121. parser.add_argument("--exit-code", type=int, default=0)
  122. args = parser.parse_args(argv)
  123. result = _check_event(args.event, args)
  124. print(json.dumps(result, indent=2, sort_keys=True))
  125. return 0 if result["allowed"] else 1
  126. if __name__ == "__main__":
  127. sys.exit(main())