agent_guard.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. The tracked configuration lives in `.devin/config.json` and must not contain
  6. temporary absolute machine paths. Local/session-specific values such as the
  7. active worktree, expected branch/HEAD, protected roots and owned paths are kept
  8. in `.devin/config.local.json`, which is gitignored.
  9. """
  10. from __future__ import annotations
  11. import argparse
  12. import fnmatch
  13. import json
  14. import subprocess
  15. import sys
  16. from pathlib import Path
  17. from typing import Any
  18. DEFAULT_DENIED_COMMANDS = [
  19. "git reset",
  20. "git clean",
  21. "git stash",
  22. "git checkout -f",
  23. "git branch -f",
  24. "git update-ref",
  25. ]
  26. DEFAULT_HARDWARE_COMMANDS = [
  27. "com",
  28. "jtag",
  29. "program",
  30. "prog",
  31. "programmer",
  32. "td_commands_prompt",
  33. ]
  34. def _run(cmd: list[str], cwd: Path | None, check: bool = False) -> subprocess.CompletedProcess[str]:
  35. return subprocess.run(
  36. cmd,
  37. cwd=cwd,
  38. capture_output=True,
  39. text=True,
  40. check=check,
  41. )
  42. def _repo_root(cwd: Path) -> Path | None:
  43. result = _run(["git", "rev-parse", "--show-toplevel"], cwd=cwd)
  44. if result.returncode != 0 or not result.stdout.strip():
  45. return None
  46. return Path(result.stdout.strip()).resolve()
  47. def _current_branch(repo: Path) -> str | None:
  48. result = _run(["git", "branch", "--show-current"], cwd=repo)
  49. if result.returncode != 0:
  50. return None
  51. return result.stdout.strip()
  52. def _current_head(repo: Path) -> str | None:
  53. result = _run(["git", "rev-parse", "HEAD"], cwd=repo)
  54. if result.returncode != 0:
  55. return None
  56. return result.stdout.strip()
  57. def _is_worktree_clean(repo: Path) -> bool:
  58. result = _run(["git", "status", "--porcelain=v2"], cwd=repo)
  59. return result.returncode == 0 and not result.stdout.strip()
  60. def _load_json(path: Path) -> dict[str, Any]:
  61. if path.is_file():
  62. try:
  63. return json.loads(path.read_text(encoding="utf-8-sig"))
  64. except (OSError, json.JSONDecodeError):
  65. pass
  66. return {}
  67. def _load_config(repo: Path) -> dict[str, Any]:
  68. """Merge tracked `.devin/config.json` with gitignored `.devin/config.local.json`.
  69. Local values override tracked values so session-specific state never touches
  70. tracked configuration.
  71. """
  72. tracked = _load_json(repo / ".devin" / "config.json")
  73. local = _load_json(repo / ".devin" / "config.local.json")
  74. merged = dict(tracked)
  75. for key, value in local.items():
  76. if isinstance(value, dict) and isinstance(merged.get(key), dict):
  77. merged[key] = {**merged[key], **value}
  78. else:
  79. merged[key] = value
  80. return merged
  81. def _is_under(path: Path, root: Path) -> bool:
  82. try:
  83. path.resolve().relative_to(root.resolve())
  84. return True
  85. except ValueError:
  86. return False
  87. def _matches_owned(path: Path, repo: Path, pattern: str) -> bool:
  88. """Check whether `path` is under the repo-relative glob `pattern`."""
  89. rel = path.resolve()
  90. try:
  91. repo_rel = rel.relative_to(repo.resolve())
  92. except ValueError:
  93. return False
  94. posix = repo_rel.as_posix()
  95. return fnmatch.fnmatch(posix, pattern) or fnmatch.fnmatch(posix, pattern.rstrip("/") + "/**")
  96. def _check_command(command: str, denied: list[str], hardware: list[str]) -> list[str]:
  97. failures: list[str] = []
  98. lowered = command.lower()
  99. for denied_cmd in denied:
  100. if denied_cmd in lowered:
  101. failures.append(f"denied_git_command:{denied_cmd}")
  102. for hw in hardware:
  103. if hw in lowered and "prompt" not in lowered:
  104. failures.append(f"potential_hardware_access:{hw}")
  105. return failures
  106. def _check_path(
  107. target: Path,
  108. repo: Path,
  109. owned_paths: list[str],
  110. protected_roots: list[str],
  111. ) -> list[str]:
  112. failures: list[str] = []
  113. target_resolved = target.resolve()
  114. for protected_str in protected_roots:
  115. protected = Path(protected_str).resolve()
  116. if _is_under(target_resolved, protected) or target_resolved == protected:
  117. failures.append(f"protected_path:{protected}")
  118. if not _is_under(target_resolved, repo):
  119. failures.append("outside_repo")
  120. if owned_paths:
  121. under_owned = any(_matches_owned(target_resolved, repo, p) for p in owned_paths)
  122. if not under_owned:
  123. failures.append(f"outside_owned_paths:{target_resolved.relative_to(repo)}")
  124. return failures
  125. def _check_event(event: str, args: argparse.Namespace) -> dict[str, Any]:
  126. cwd = Path(args.cwd or ".").resolve()
  127. result: dict[str, Any] = {
  128. "event": event,
  129. "cwd": str(cwd),
  130. "repo_root": None,
  131. "branch": None,
  132. "head": None,
  133. "worktree_clean": None,
  134. "allowed": True,
  135. "failures": [],
  136. }
  137. repo = _repo_root(cwd)
  138. if repo is None:
  139. result["allowed"] = False
  140. result["failures"].append("not_a_git_repository")
  141. return result
  142. result["repo_root"] = str(repo)
  143. result["branch"] = _current_branch(repo)
  144. result["head"] = _current_head(repo)
  145. result["worktree_clean"] = _is_worktree_clean(repo)
  146. config = _load_config(repo)
  147. result["config_loaded"] = bool(config)
  148. protected_roots = [str(p) for p in config.get("protected_roots", [])]
  149. for protected_str in protected_roots:
  150. protected = Path(protected_str).resolve()
  151. if _is_under(cwd, protected) or _is_under(repo, protected) or cwd == protected or repo == protected:
  152. result["allowed"] = False
  153. result["failures"].append(f"protected_repository:{protected}")
  154. return result
  155. active_worktree_str = config.get("active_worktree")
  156. if active_worktree_str:
  157. active_worktree = Path(active_worktree_str).resolve()
  158. if repo != active_worktree:
  159. result["failures"].append(
  160. f"worktree_mismatch:expected={active_worktree},actual={repo}"
  161. )
  162. expected_branch = config.get("expected_branch")
  163. if expected_branch and result["branch"] != expected_branch:
  164. result["failures"].append(
  165. f"branch_mismatch:expected={expected_branch},actual={result['branch']}"
  166. )
  167. expected_head = config.get("expected_head")
  168. if expected_head and result["head"] != expected_head:
  169. result["failures"].append(
  170. f"head_mismatch:expected={expected_head},actual={result['head']}"
  171. )
  172. owned_paths = list(config.get("owned_paths", []))
  173. if not owned_paths and args.agent_role:
  174. # Derive owned paths from the agent-team contract when a role is supplied.
  175. contract = _load_json(repo / "agent-team" / "contract.json")
  176. team = contract.get("teams", {}).get(args.agent_role, {})
  177. owned_paths = list(team.get("owns", []))
  178. if args.target_path:
  179. target = Path(args.target_path).resolve()
  180. result["failures"].extend(
  181. _check_path(target, repo, owned_paths, protected_roots)
  182. )
  183. if event in ("pre_tool_use", "post_tool_use") and args.command:
  184. denied = config.get("denied_commands", DEFAULT_DENIED_COMMANDS)
  185. hardware = DEFAULT_HARDWARE_COMMANDS + list(config.get("hardware_access", {}).keys())
  186. result["failures"].extend(_check_command(args.command, denied, hardware))
  187. if result["failures"]:
  188. result["allowed"] = False
  189. return result
  190. def main(argv: list[str] | None = None) -> int:
  191. parser = argparse.ArgumentParser(description="Agent guard for cross-tool operations")
  192. parser.add_argument("--event", required=True)
  193. parser.add_argument("--cwd", default=None)
  194. parser.add_argument("--tool", default=None)
  195. parser.add_argument("--target-path", default=None)
  196. parser.add_argument("--command", default=None)
  197. parser.add_argument("--agent-role", default=None)
  198. parser.add_argument("--exit-code", type=int, default=1)
  199. args = parser.parse_args(argv)
  200. result = _check_event(args.event, args)
  201. print(json.dumps(result, indent=2, sort_keys=True))
  202. return 0 if result["allowed"] else args.exit_code
  203. if __name__ == "__main__":
  204. sys.exit(main())