| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254 |
- """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.
- The tracked configuration lives in `.devin/config.json` and must not contain
- temporary absolute machine paths. Local/session-specific values such as the
- active worktree, expected branch/HEAD, protected roots and owned paths are kept
- in `.devin/config.local.json`, which is gitignored.
- """
- from __future__ import annotations
- import argparse
- import fnmatch
- import json
- import subprocess
- import sys
- from pathlib import Path
- from typing import Any
- DEFAULT_DENIED_COMMANDS = [
- "git reset",
- "git clean",
- "git stash",
- "git checkout -f",
- "git branch -f",
- "git update-ref",
- ]
- DEFAULT_HARDWARE_COMMANDS = [
- "com",
- "jtag",
- "program",
- "prog",
- "programmer",
- "td_commands_prompt",
- ]
- def _run(cmd: list[str], cwd: Path | None, check: bool = False) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- cmd,
- cwd=cwd,
- capture_output=True,
- text=True,
- check=check,
- )
- def _repo_root(cwd: Path) -> Path | None:
- result = _run(["git", "rev-parse", "--show-toplevel"], cwd=cwd)
- if result.returncode != 0 or not result.stdout.strip():
- return None
- return Path(result.stdout.strip()).resolve()
- def _current_branch(repo: Path) -> str | None:
- result = _run(["git", "branch", "--show-current"], cwd=repo)
- if result.returncode != 0:
- return None
- return result.stdout.strip()
- def _current_head(repo: Path) -> str | None:
- result = _run(["git", "rev-parse", "HEAD"], cwd=repo)
- if result.returncode != 0:
- return None
- return result.stdout.strip()
- def _is_worktree_clean(repo: Path) -> bool:
- result = _run(["git", "status", "--porcelain=v2"], cwd=repo)
- return result.returncode == 0 and not result.stdout.strip()
- def _load_json(path: Path) -> dict[str, Any]:
- if path.is_file():
- try:
- return json.loads(path.read_text(encoding="utf-8-sig"))
- except (OSError, json.JSONDecodeError):
- pass
- return {}
- def _load_config(repo: Path) -> dict[str, Any]:
- """Merge tracked `.devin/config.json` with gitignored `.devin/config.local.json`.
- Local values override tracked values so session-specific state never touches
- tracked configuration.
- """
- tracked = _load_json(repo / ".devin" / "config.json")
- local = _load_json(repo / ".devin" / "config.local.json")
- merged = dict(tracked)
- for key, value in local.items():
- if isinstance(value, dict) and isinstance(merged.get(key), dict):
- merged[key] = {**merged[key], **value}
- else:
- merged[key] = value
- return merged
- def _is_under(path: Path, root: Path) -> bool:
- try:
- path.resolve().relative_to(root.resolve())
- return True
- except ValueError:
- return False
- def _matches_owned(path: Path, repo: Path, pattern: str) -> bool:
- """Check whether `path` is under the repo-relative glob `pattern`."""
- rel = path.resolve()
- try:
- repo_rel = rel.relative_to(repo.resolve())
- except ValueError:
- return False
- posix = repo_rel.as_posix()
- return fnmatch.fnmatch(posix, pattern) or fnmatch.fnmatch(posix, pattern.rstrip("/") + "/**")
- def _check_command(command: str, denied: list[str], hardware: list[str]) -> list[str]:
- failures: list[str] = []
- lowered = command.lower()
- for denied_cmd in denied:
- if denied_cmd in lowered:
- failures.append(f"denied_git_command:{denied_cmd}")
- for hw in hardware:
- 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,
- owned_paths: list[str],
- protected_roots: list[str],
- ) -> list[str]:
- failures: list[str] = []
- target_resolved = target.resolve()
- for protected_str in protected_roots:
- protected = Path(protected_str).resolve()
- if _is_under(target_resolved, protected) or target_resolved == protected:
- failures.append(f"protected_path:{protected}")
- if not _is_under(target_resolved, repo):
- failures.append("outside_repo")
- if owned_paths:
- under_owned = any(_matches_owned(target_resolved, repo, p) for p in owned_paths)
- if not under_owned:
- failures.append(f"outside_owned_paths:{target_resolved.relative_to(repo)}")
- return failures
- def _check_event(event: str, args: argparse.Namespace) -> dict[str, Any]:
- cwd = Path(args.cwd or ".").resolve()
- result: dict[str, Any] = {
- "event": event,
- "cwd": str(cwd),
- "repo_root": None,
- "branch": None,
- "head": None,
- "worktree_clean": None,
- "allowed": True,
- "failures": [],
- }
- repo = _repo_root(cwd)
- if repo is None:
- result["allowed"] = False
- result["failures"].append("not_a_git_repository")
- return result
- result["repo_root"] = str(repo)
- result["branch"] = _current_branch(repo)
- result["head"] = _current_head(repo)
- result["worktree_clean"] = _is_worktree_clean(repo)
- config = _load_config(repo)
- result["config_loaded"] = bool(config)
- protected_roots = [str(p) for p in config.get("protected_roots", [])]
- for protected_str in protected_roots:
- protected = Path(protected_str).resolve()
- if _is_under(cwd, protected) or _is_under(repo, protected) or cwd == protected or repo == protected:
- result["allowed"] = False
- result["failures"].append(f"protected_repository:{protected}")
- return result
- active_worktree_str = config.get("active_worktree")
- if active_worktree_str:
- active_worktree = Path(active_worktree_str).resolve()
- if repo != active_worktree:
- result["failures"].append(
- f"worktree_mismatch:expected={active_worktree},actual={repo}"
- )
- expected_branch = config.get("expected_branch")
- if expected_branch and result["branch"] != expected_branch:
- result["failures"].append(
- f"branch_mismatch:expected={expected_branch},actual={result['branch']}"
- )
- expected_head = config.get("expected_head")
- if expected_head and result["head"] != expected_head:
- result["failures"].append(
- f"head_mismatch:expected={expected_head},actual={result['head']}"
- )
- owned_paths = list(config.get("owned_paths", []))
- if not owned_paths and args.agent_role:
- # Derive owned paths from the agent-team contract when a role is supplied.
- contract = _load_json(repo / "agent-team" / "contract.json")
- team = contract.get("teams", {}).get(args.agent_role, {})
- owned_paths = list(team.get("owns", []))
- if args.target_path:
- target = Path(args.target_path).resolve()
- result["failures"].extend(
- _check_path(target, repo, owned_paths, protected_roots)
- )
- if event in ("pre_tool_use", "post_tool_use") and args.command:
- denied = config.get("denied_commands", DEFAULT_DENIED_COMMANDS)
- hardware = DEFAULT_HARDWARE_COMMANDS + list(config.get("hardware_access", {}).keys())
- result["failures"].extend(_check_command(args.command, denied, hardware))
- 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("--tool", default=None)
- parser.add_argument("--target-path", default=None)
- parser.add_argument("--command", default=None)
- parser.add_argument("--agent-role", default=None)
- parser.add_argument("--exit-code", type=int, default=1)
- 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 args.exit_code
- if __name__ == "__main__":
- sys.exit(main())
|