|
@@ -3,21 +3,23 @@
|
|
|
This script is designed to be invoked by Devin/Cursor/Codex hooks or directly.
|
|
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,
|
|
It validates that the agent is operating in the expected repository, branch,
|
|
|
worktree, owned paths, and that protected operations are not performed.
|
|
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
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
import argparse
|
|
import argparse
|
|
|
|
|
+import fnmatch
|
|
|
import json
|
|
import json
|
|
|
import subprocess
|
|
import subprocess
|
|
|
import sys
|
|
import sys
|
|
|
from pathlib import Path
|
|
from pathlib import Path
|
|
|
from typing import Any
|
|
from typing import Any
|
|
|
|
|
|
|
|
-PROTECTED_ROOTS = [
|
|
|
|
|
- Path("C:/Users/Administrator/Agentworkspace/CPLD"),
|
|
|
|
|
-]
|
|
|
|
|
-
|
|
|
|
|
-DENIED_COMMANDS = [
|
|
|
|
|
|
|
+DEFAULT_DENIED_COMMANDS = [
|
|
|
"git reset",
|
|
"git reset",
|
|
|
"git clean",
|
|
"git clean",
|
|
|
"git stash",
|
|
"git stash",
|
|
@@ -26,7 +28,7 @@ DENIED_COMMANDS = [
|
|
|
"git update-ref",
|
|
"git update-ref",
|
|
|
]
|
|
]
|
|
|
|
|
|
|
|
-HARDWARE_COMMANDS = [
|
|
|
|
|
|
|
+DEFAULT_HARDWARE_COMMANDS = [
|
|
|
"com",
|
|
"com",
|
|
|
"jtag",
|
|
"jtag",
|
|
|
"program",
|
|
"program",
|
|
@@ -36,44 +38,68 @@ HARDWARE_COMMANDS = [
|
|
|
]
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+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:
|
|
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):
|
|
|
|
|
|
|
+ result = _run(["git", "rev-parse", "--show-toplevel"], cwd=cwd)
|
|
|
|
|
+ if result.returncode != 0 or not result.stdout.strip():
|
|
|
return None
|
|
return None
|
|
|
|
|
+ return Path(result.stdout.strip()).resolve()
|
|
|
|
|
|
|
|
|
|
|
|
|
def _current_branch(repo: Path) -> str | 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):
|
|
|
|
|
|
|
+ result = _run(["git", "branch", "--show-current"], cwd=repo)
|
|
|
|
|
+ if result.returncode != 0:
|
|
|
return None
|
|
return None
|
|
|
|
|
+ return result.stdout.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
-def _load_config(repo: Path) -> dict[str, Any]:
|
|
|
|
|
- config_path = repo / ".devin" / "config.json"
|
|
|
|
|
- if config_path.is_file():
|
|
|
|
|
|
|
+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:
|
|
try:
|
|
|
- return json.loads(config_path.read_text(encoding="utf-8-sig"))
|
|
|
|
|
|
|
+ return json.loads(path.read_text(encoding="utf-8-sig"))
|
|
|
except (OSError, json.JSONDecodeError):
|
|
except (OSError, json.JSONDecodeError):
|
|
|
pass
|
|
pass
|
|
|
return {}
|
|
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:
|
|
def _is_under(path: Path, root: Path) -> bool:
|
|
|
try:
|
|
try:
|
|
|
path.resolve().relative_to(root.resolve())
|
|
path.resolve().relative_to(root.resolve())
|
|
@@ -82,53 +108,126 @@ def _is_under(path: Path, root: Path) -> bool:
|
|
|
return False
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
-def _check_command(command: str) -> list[str]:
|
|
|
|
|
|
|
+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] = []
|
|
failures: list[str] = []
|
|
|
lowered = command.lower()
|
|
lowered = command.lower()
|
|
|
- for denied in DENIED_COMMANDS:
|
|
|
|
|
- if denied in lowered:
|
|
|
|
|
- failures.append(f"denied_git_command:{denied}")
|
|
|
|
|
- for hw in HARDWARE_COMMANDS:
|
|
|
|
|
|
|
+ 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:
|
|
if hw in lowered and "prompt" not in lowered:
|
|
|
failures.append(f"potential_hardware_access:{hw}")
|
|
failures.append(f"potential_hardware_access:{hw}")
|
|
|
return failures
|
|
return failures
|
|
|
|
|
|
|
|
|
|
|
|
|
-def _check_path(target: Path, repo: Path, config: dict[str, Any]) -> list[str]:
|
|
|
|
|
|
|
+def _check_path(
|
|
|
|
|
+ target: Path,
|
|
|
|
|
+ repo: Path,
|
|
|
|
|
+ owned_paths: list[str],
|
|
|
|
|
+ protected_roots: list[str],
|
|
|
|
|
+) -> list[str]:
|
|
|
failures: 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}")
|
|
|
|
|
|
|
+ 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
|
|
return failures
|
|
|
|
|
|
|
|
|
|
|
|
|
def _check_event(event: str, args: argparse.Namespace) -> dict[str, Any]:
|
|
def _check_event(event: str, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
cwd = Path(args.cwd or ".").resolve()
|
|
cwd = Path(args.cwd or ".").resolve()
|
|
|
- repo = _repo_root(cwd)
|
|
|
|
|
result: dict[str, Any] = {
|
|
result: dict[str, Any] = {
|
|
|
"event": event,
|
|
"event": event,
|
|
|
"cwd": str(cwd),
|
|
"cwd": str(cwd),
|
|
|
- "repo_root": str(repo) if repo else None,
|
|
|
|
|
- "branch": _current_branch(repo) if repo else None,
|
|
|
|
|
|
|
+ "repo_root": None,
|
|
|
|
|
+ "branch": None,
|
|
|
|
|
+ "head": None,
|
|
|
|
|
+ "worktree_clean": None,
|
|
|
"allowed": True,
|
|
"allowed": True,
|
|
|
"failures": [],
|
|
"failures": [],
|
|
|
}
|
|
}
|
|
|
|
|
+
|
|
|
|
|
+ repo = _repo_root(cwd)
|
|
|
if repo is None:
|
|
if repo is None:
|
|
|
result["allowed"] = False
|
|
result["allowed"] = False
|
|
|
result["failures"].append("not_a_git_repository")
|
|
result["failures"].append("not_a_git_repository")
|
|
|
return result
|
|
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)
|
|
config = _load_config(repo)
|
|
|
result["config_loaded"] = bool(config)
|
|
result["config_loaded"] = bool(config)
|
|
|
|
|
|
|
|
- if event in ("pre_tool_use", "post_tool_use") and args.command:
|
|
|
|
|
- result["failures"].extend(_check_command(args.command))
|
|
|
|
|
|
|
+ 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:
|
|
if args.target_path:
|
|
|
target = Path(args.target_path).resolve()
|
|
target = Path(args.target_path).resolve()
|
|
|
- result["failures"].extend(_check_path(target, repo, config))
|
|
|
|
|
|
|
+ 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"]:
|
|
if result["failures"]:
|
|
|
result["allowed"] = False
|
|
result["allowed"] = False
|
|
@@ -139,16 +238,16 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
parser = argparse.ArgumentParser(description="Agent guard for cross-tool operations")
|
|
parser = argparse.ArgumentParser(description="Agent guard for cross-tool operations")
|
|
|
parser.add_argument("--event", required=True)
|
|
parser.add_argument("--event", required=True)
|
|
|
parser.add_argument("--cwd", default=None)
|
|
parser.add_argument("--cwd", default=None)
|
|
|
- parser.add_argument("--repo-root", default=None)
|
|
|
|
|
parser.add_argument("--tool", default=None)
|
|
parser.add_argument("--tool", default=None)
|
|
|
parser.add_argument("--target-path", default=None)
|
|
parser.add_argument("--target-path", default=None)
|
|
|
parser.add_argument("--command", default=None)
|
|
parser.add_argument("--command", default=None)
|
|
|
- parser.add_argument("--exit-code", type=int, default=0)
|
|
|
|
|
|
|
+ parser.add_argument("--agent-role", default=None)
|
|
|
|
|
+ parser.add_argument("--exit-code", type=int, default=1)
|
|
|
args = parser.parse_args(argv)
|
|
args = parser.parse_args(argv)
|
|
|
|
|
|
|
|
result = _check_event(args.event, args)
|
|
result = _check_event(args.event, args)
|
|
|
print(json.dumps(result, indent=2, sort_keys=True))
|
|
print(json.dumps(result, indent=2, sort_keys=True))
|
|
|
- return 0 if result["allowed"] else 1
|
|
|
|
|
|
|
+ return 0 if result["allowed"] else args.exit_code
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if __name__ == "__main__":
|