reviewloop-ai 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. reviewloop/__init__.py +3 -0
  2. reviewloop/agents/__init__.py +0 -0
  3. reviewloop/agents/base.py +28 -0
  4. reviewloop/agents/claude_code.py +160 -0
  5. reviewloop/agents/codex.py +108 -0
  6. reviewloop/agents/cursor.py +96 -0
  7. reviewloop/agents/git_guard.py +214 -0
  8. reviewloop/agents/isolation.py +319 -0
  9. reviewloop/agents/registry.py +32 -0
  10. reviewloop/agents/runner.py +152 -0
  11. reviewloop/anchor.py +154 -0
  12. reviewloop/cli.py +226 -0
  13. reviewloop/cli_snippets.py +197 -0
  14. reviewloop/config.py +83 -0
  15. reviewloop/diff.py +182 -0
  16. reviewloop/errors.py +10 -0
  17. reviewloop/models.py +134 -0
  18. reviewloop/output/__init__.py +0 -0
  19. reviewloop/output/json_out.py +13 -0
  20. reviewloop/output/redact.py +43 -0
  21. reviewloop/output/sarif.py +46 -0
  22. reviewloop/output/summary.py +101 -0
  23. reviewloop/pipeline/__init__.py +0 -0
  24. reviewloop/pipeline/agent.py +124 -0
  25. reviewloop/pipeline/context.py +98 -0
  26. reviewloop/pipeline/engine.py +135 -0
  27. reviewloop/pipeline/failures.py +19 -0
  28. reviewloop/pipeline/findings.py +14 -0
  29. reviewloop/pipeline/flows.py +86 -0
  30. reviewloop/pipeline/git.py +17 -0
  31. reviewloop/pipeline/prompts.py +107 -0
  32. reviewloop/pipeline/review.py +45 -0
  33. reviewloop/pipeline/split.py +58 -0
  34. reviewloop/pipeline/steps/__init__.py +0 -0
  35. reviewloop/pipeline/steps/follow_up/__init__.py +1 -0
  36. reviewloop/pipeline/steps/follow_up/build_follow_up_context.py +12 -0
  37. reviewloop/pipeline/steps/follow_up/follow_up_review.py +27 -0
  38. reviewloop/pipeline/steps/follow_up/follow_up_summary.py +29 -0
  39. reviewloop/pipeline/steps/follow_up/force_push_and_lineage.py +42 -0
  40. reviewloop/pipeline/steps/follow_up/in_progress_comment.py +13 -0
  41. reviewloop/pipeline/steps/follow_up/load_thread_inputs.py +80 -0
  42. reviewloop/pipeline/steps/follow_up/post_follow_up_comments.py +29 -0
  43. reviewloop/pipeline/steps/follow_up/resolve_target_turn.py +26 -0
  44. reviewloop/pipeline/steps/follow_up/security_rescan.py +44 -0
  45. reviewloop/pipeline/steps/initial/__init__.py +1 -0
  46. reviewloop/pipeline/steps/initial/build_context.py +91 -0
  47. reviewloop/pipeline/steps/initial/clean.py +20 -0
  48. reviewloop/pipeline/steps/initial/detect_stack.py +33 -0
  49. reviewloop/pipeline/steps/initial/fetch_previous_comments.py +11 -0
  50. reviewloop/pipeline/steps/initial/get_diff.py +129 -0
  51. reviewloop/pipeline/steps/initial/get_pr_info.py +18 -0
  52. reviewloop/pipeline/steps/initial/init_context.py +14 -0
  53. reviewloop/pipeline/steps/initial/initial_review.py +18 -0
  54. reviewloop/pipeline/steps/initial/large_diff_review.py +83 -0
  55. reviewloop/pipeline/steps/initial/load_config.py +49 -0
  56. reviewloop/pipeline/steps/initial/post_comment.py +92 -0
  57. reviewloop/pipeline/steps/initial/pr_overview.py +21 -0
  58. reviewloop/pipeline/steps/initial/pre_review_comment.py +23 -0
  59. reviewloop/pipeline/steps/initial/quality_gate.py +35 -0
  60. reviewloop/pipeline/steps/initial/resolve_review_context.py +21 -0
  61. reviewloop/pipeline/steps/initial/security_branch.py +83 -0
  62. reviewloop/pipeline/steps/initial/security_merge.py +17 -0
  63. reviewloop/pipeline/steps/initial/summarize_context.py +52 -0
  64. reviewloop/pipeline/steps/initial/summary.py +21 -0
  65. reviewloop/platform.py +73 -0
  66. reviewloop/py.typed +0 -0
  67. reviewloop/rules/common.md +47 -0
  68. reviewloop/rules/csharp.md +52 -0
  69. reviewloop/rules/django.md +44 -0
  70. reviewloop/rules/go.md +53 -0
  71. reviewloop/rules/java.md +48 -0
  72. reviewloop/rules/laravel.md +52 -0
  73. reviewloop/rules/nestjs.md +43 -0
  74. reviewloop/rules/php.md +43 -0
  75. reviewloop/rules/python.md +45 -0
  76. reviewloop/rules/react.md +41 -0
  77. reviewloop/rules/typescript.md +37 -0
  78. reviewloop/security/__init__.py +0 -0
  79. reviewloop/security/scanners.py +163 -0
  80. reviewloop/skills/__init__.py +0 -0
  81. reviewloop/skills/code-review/SKILL.md +63 -0
  82. reviewloop/skills/follow-up/SKILL.md +44 -0
  83. reviewloop/skills/output-contract/SKILL.md +61 -0
  84. reviewloop/skills/pr-overview/SKILL.md +32 -0
  85. reviewloop/skills/quality-gate/SKILL.md +60 -0
  86. reviewloop/skills/schemas.py +98 -0
  87. reviewloop/skills/security-review/SKILL.md +43 -0
  88. reviewloop/skills/security-verify/SKILL.md +32 -0
  89. reviewloop/skills/summarize-context/SKILL.md +33 -0
  90. reviewloop/stacks.py +95 -0
  91. reviewloop/state.py +53 -0
  92. reviewloop/trackers/__init__.py +0 -0
  93. reviewloop/trackers/_text.py +5 -0
  94. reviewloop/trackers/base.py +14 -0
  95. reviewloop/trackers/github_issues.py +33 -0
  96. reviewloop/trackers/gitlab_issues.py +36 -0
  97. reviewloop/trackers/jira.py +61 -0
  98. reviewloop/trackers/registry.py +37 -0
  99. reviewloop/vcs/__init__.py +0 -0
  100. reviewloop/vcs/base.py +33 -0
  101. reviewloop/vcs/bitbucket_cloud.py +309 -0
  102. reviewloop/vcs/bitbucket_dc.py +314 -0
  103. reviewloop/vcs/bitbucket_http.py +16 -0
  104. reviewloop/vcs/common.py +43 -0
  105. reviewloop/vcs/github.py +390 -0
  106. reviewloop/vcs/gitlab.py +274 -0
  107. reviewloop_ai-0.1.0.dist-info/METADATA +230 -0
  108. reviewloop_ai-0.1.0.dist-info/RECORD +111 -0
  109. reviewloop_ai-0.1.0.dist-info/WHEEL +4 -0
  110. reviewloop_ai-0.1.0.dist-info/entry_points.txt +2 -0
  111. reviewloop_ai-0.1.0.dist-info/licenses/LICENSE +661 -0
reviewloop/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """reviewloop: AI code review in your own CI with your own agent CLI."""
2
+
3
+ __version__ = "0.1.0" # x-release-please-version
File without changes
@@ -0,0 +1,28 @@
1
+ from pathlib import Path
2
+ from typing import Protocol
3
+
4
+ from pydantic import BaseModel
5
+
6
+
7
+ class AgentTask(BaseModel):
8
+ step: str
9
+ prompt: str
10
+ skills: list[str]
11
+ workdir: Path
12
+ output_schema: type[BaseModel]
13
+ timeout_s: int
14
+ model: str | None = None
15
+
16
+
17
+ class AgentResult(BaseModel):
18
+ output: BaseModel
19
+
20
+
21
+ class AgentAdapter(Protocol):
22
+ name: str
23
+
24
+ def check_auth(self) -> None: ...
25
+
26
+ def run(self, task: AgentTask) -> AgentResult:
27
+ """One CLI invocation; the repair loop lives in agents/runner.py."""
28
+ ...
@@ -0,0 +1,160 @@
1
+ """Claude Code adapter: `claude -p` restricted to read tools, four git commands and one output file.
2
+
3
+ Credentials come from environment variables only. HOME is a fresh temporary directory per run, so file-based auth
4
+ does not work: no `~/.claude` login, no AWS profile or `~/.aws` files, no Google application-default credentials
5
+ file under HOME. Use ANTHROPIC_API_KEY, CLAUDE_CODE_OAUTH_TOKEN, Bedrock keys in env, or Vertex with
6
+ GOOGLE_APPLICATION_CREDENTIALS pointing at a key file outside HOME.
7
+
8
+ Besides the allow rules below, Claude Code runs its built-in read-only shell commands (ls, cat, grep, find, read-only
9
+ git, ...) without a prompt in every permission mode. They read inside the sandbox, which has no symlinks, and
10
+ `blockReadsOutsideWorkingDirectories` plus the post-run snapshot check bound the rest.
11
+
12
+ The real-CLI smoke run must confirm that `/usr/bin/git diff a /abs/x` is refused (git by path skips the guard).
13
+ """
14
+
15
+ import json
16
+ import os
17
+ import shlex
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+ from reviewloop.agents.base import AgentResult, AgentTask
22
+ from reviewloop.agents.isolation import install_git_wrapper, install_skills, scrub_env
23
+ from reviewloop.agents.runner import output_path, run_cli
24
+ from reviewloop.errors import AgentStepError
25
+
26
+ # Model credentials only. `ANTHROPIC_*` also covers gateway settings such as ANTHROPIC_BASE_URL and
27
+ # ANTHROPIC_VERTEX_PROJECT_ID. Cloud credentials pass only when their provider is selected, so a runner's AWS or
28
+ # Google credentials for other jobs never reach an agent that uses an API key.
29
+ BASE_CREDENTIALS = ("ANTHROPIC_*", "CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX")
30
+ BEDROCK_CREDENTIALS = (
31
+ "AWS_REGION",
32
+ "AWS_DEFAULT_REGION",
33
+ "AWS_ACCESS_KEY_ID",
34
+ "AWS_SECRET_ACCESS_KEY",
35
+ "AWS_SESSION_TOKEN",
36
+ "AWS_BEARER_TOKEN_BEDROCK",
37
+ )
38
+ VERTEX_CREDENTIALS = ("CLOUD_ML_REGION", "VERTEX_REGION_*", "GOOGLE_APPLICATION_CREDENTIALS")
39
+ _TOKEN_VARS = ("ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_AUTH_TOKEN")
40
+ _TRUTHY = ("1", "true", "yes", "on")
41
+
42
+
43
+ def _flag(name: str) -> bool:
44
+ return os.environ.get(name, "").strip().lower() in _TRUTHY
45
+
46
+
47
+ # Built-in tools the session has at all; everything else (Edit, NotebookEdit, WebFetch, Agent, ...) is absent.
48
+ TOOLS = "Read,Grep,Glob,Skill,Bash,Write"
49
+ GIT_COMMANDS = ("git log", "git blame", "git show", "git diff")
50
+ # Deny wins over allow. A bare `Edit` deny is not used: it also blocks Write, which the output file needs.
51
+ # These denies are an outer layer only; the git guard installed by `install_git_wrapper` is what enforces the git
52
+ # allowlist (ruling R17), because git accepts abbreviated and grouped options that patterns cannot enumerate.
53
+ # `--output` makes git log/show/diff write a file. `--no-index`, a `/dev/null` operand (implicit no-index),
54
+ # `--contents` (and its abbreviations), `-S` and `--ignore-revs-file` make git diff/blame read a named file. `$`
55
+ # expansion or /proc could print the model credential into the transcript.
56
+ DISALLOWED = (
57
+ "NotebookEdit",
58
+ "WebFetch",
59
+ "WebSearch",
60
+ "Bash(*--output*)",
61
+ "Bash(*--no-index*)",
62
+ "Bash(*--contents*)",
63
+ "Bash(*$*)",
64
+ "Bash(*/proc/*)",
65
+ "Bash(git blame*-S*)",
66
+ "Bash(git blame*--conte*)",
67
+ "Bash(git blame*--con*)",
68
+ "Bash(git blame*--ignore-rev*)",
69
+ "Bash(git diff*/dev/null*)",
70
+ # git by path, through a launcher, or as a git-<sub> binary would skip the git guard first on PATH.
71
+ "Bash(*/git *)",
72
+ "Bash(*/git)",
73
+ "Bash(env *)",
74
+ "Bash(command *)",
75
+ "Bash(exec *)",
76
+ "Bash(*git-*)",
77
+ "Read(//proc/**)",
78
+ )
79
+ # User settings in the throwaway HOME. Project and local settings of the checkout are never loaded, because the
80
+ # checkout is untrusted and its `.claude/settings.json` could add hooks or allow rules.
81
+ SETTINGS = {
82
+ "disableAllHooks": True,
83
+ # CLAUDE.md files and rules in the checkout are instructions the PR author controls; AGENTS.md stays, as data.
84
+ "claudeMdExcludes": ["**/CLAUDE.md", "**/CLAUDE.local.md", "**/.claude/rules/**"],
85
+ "permissions": {
86
+ "blockReadsOutsideWorkingDirectories": True,
87
+ "blockWritesOutsideWorkingDirectories": True,
88
+ "disableBypassPermissionsMode": "disable",
89
+ },
90
+ }
91
+
92
+
93
+ class ClaudeCodeAdapter:
94
+ name = "claude-code"
95
+
96
+ def __init__(self, binary: str = "claude") -> None:
97
+ self.binary = binary
98
+
99
+ def check_auth(self) -> None:
100
+ if any(os.environ.get(var) for var in _TOKEN_VARS):
101
+ return
102
+ if _flag("CLAUDE_CODE_USE_BEDROCK") or _flag("CLAUDE_CODE_USE_VERTEX"):
103
+ return
104
+ raise AgentStepError(
105
+ "Claude Code has no credential: set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN, "
106
+ "or CLAUDE_CODE_USE_BEDROCK / CLAUDE_CODE_USE_VERTEX with that provider's credentials"
107
+ )
108
+
109
+ def environment(self, home: str) -> dict[str, str]:
110
+ names: list[str] = list(BASE_CREDENTIALS)
111
+ if _flag("CLAUDE_CODE_USE_BEDROCK"):
112
+ names.extend(BEDROCK_CREDENTIALS)
113
+ if _flag("CLAUDE_CODE_USE_VERTEX"):
114
+ names.extend(VERTEX_CREDENTIALS)
115
+ env = scrub_env(names)
116
+ env["HOME"] = home
117
+ return env
118
+
119
+ def command(self, task: AgentTask) -> list[str]:
120
+ allowed = ["Read", "Grep", "Glob", "Skill", *(f"Bash({cmd}:*)" for cmd in GIT_COMMANDS)]
121
+ allowed.append(f"Edit({output_path(task).as_posix()})")
122
+ argv = [
123
+ self.binary,
124
+ "-p",
125
+ "--output-format",
126
+ "stream-json",
127
+ "--verbose",
128
+ "--tools",
129
+ TOOLS,
130
+ "--allowedTools",
131
+ ",".join(allowed),
132
+ "--disallowedTools",
133
+ ",".join(DISALLOWED),
134
+ "--permission-mode",
135
+ "dontAsk",
136
+ "--setting-sources",
137
+ "user",
138
+ "--strict-mcp-config",
139
+ "--no-session-persistence",
140
+ ]
141
+ if task.model:
142
+ argv += ["--model", task.model]
143
+ return argv
144
+
145
+ def run(self, task: AgentTask) -> AgentResult:
146
+ argv = self.command(task)
147
+ with tempfile.TemporaryDirectory(prefix="reviewloop-home-") as home:
148
+ config = Path(home) / ".claude"
149
+ install_skills(task.step, task.skills, config / "skills")
150
+ config.mkdir(exist_ok=True)
151
+ (config / "settings.json").write_text(json.dumps(SETTINGS))
152
+ bin_dir = install_git_wrapper(Path(home), task.workdir)
153
+ # Claude Code runs CLAUDE_ENV_FILE before every Bash command in the same shell, so the guard stays first
154
+ # on PATH even if a login shell's /etc/profile resets PATH.
155
+ env_file = Path(home) / "agent-env.sh"
156
+ env_file.write_text(f'export PATH={shlex.quote(str(bin_dir))}:"$PATH"\n')
157
+ env = self.environment(home)
158
+ env["PATH"] = os.pathsep.join([str(bin_dir), env.get("PATH", os.defpath)])
159
+ env["CLAUDE_ENV_FILE"] = str(env_file)
160
+ return run_cli(task, argv, env)
@@ -0,0 +1,108 @@
1
+ """Codex adapter (experimental): `codex exec` in a read-only sandbox, never asking for approval.
2
+
3
+ Experimental because Codex cannot restrict shell commands to the spec 8.2 allowlist: in the read-only sandbox every
4
+ command runs without approval (`cat`, `ls`, `rg`, ...), and execpolicy rules only decide what may run outside the
5
+ sandbox. Its reads are not limited to the copy either. Writes are blocked by the sandbox, network is off, and the
6
+ post-run snapshot check still fails any change. See docs/adr/0002-agent-tool-restriction.md.
7
+
8
+ Codex writes the output file itself (`--output-last-message`), so the model's final message is the JSON output and the
9
+ sandbox stays read-only. Credentials: OPENAI_API_KEY (handed to `codex exec` as CODEX_API_KEY, the only API key variable
10
+ it reads) or CODEX_AUTH_JSON, written to `$HOME/.codex/auth.json` in the throwaway HOME. A refreshed token is not saved
11
+ back, so an auth.json login must be re-saved by the user when its refresh token rotates.
12
+ """
13
+
14
+ import json
15
+ import os
16
+ import tempfile
17
+ from collections.abc import Mapping
18
+ from pathlib import Path
19
+
20
+ from reviewloop.agents.base import AgentResult, AgentTask
21
+ from reviewloop.agents.isolation import install_git_wrapper, install_skills, scrub_env
22
+ from reviewloop.agents.runner import output_path, run_cli
23
+ from reviewloop.errors import AgentStepError
24
+
25
+ AUTH_JSON_VAR = "CODEX_AUTH_JSON"
26
+ API_KEY_VAR = "OPENAI_API_KEY"
27
+ # Off: connectors, subagents, and the shell snapshot that would copy a login shell's environment into commands.
28
+ DISABLED_FEATURES = ("apps", "multi_agent", "shell_snapshot")
29
+
30
+
31
+ def _toml(value: str) -> str:
32
+ # A JSON string is a valid TOML basic string.
33
+ return json.dumps(value)
34
+
35
+
36
+ class CodexAdapter:
37
+ name = "codex"
38
+ experimental = True
39
+
40
+ def __init__(self, binary: str = "codex") -> None:
41
+ self.binary = binary
42
+
43
+ def check_auth(self) -> None:
44
+ if os.environ.get(API_KEY_VAR) or os.environ.get(AUTH_JSON_VAR):
45
+ return
46
+ raise AgentStepError(f"Codex has no credential: set {API_KEY_VAR} or {AUTH_JSON_VAR}")
47
+
48
+ def environment(self, home: str) -> dict[str, str]:
49
+ env = scrub_env([])
50
+ env["HOME"] = home
51
+ key = os.environ.get(API_KEY_VAR)
52
+ if key:
53
+ env["CODEX_API_KEY"] = key
54
+ return env
55
+
56
+ def command(self, task: AgentTask, env: Mapping[str, str]) -> list[str]:
57
+ shell_env = f"{{PATH = {_toml(env['PATH'])}, HOME = {_toml(env['HOME'])}}}"
58
+ overrides = {
59
+ "approval_policy": _toml("never"),
60
+ # A login shell would run /etc/profile, which can put the real git ahead of the guard on PATH.
61
+ "allow_login_shell": "false",
62
+ # AGENTS.md stays in the copy as data, but is not loaded as instructions the PR author controls.
63
+ "project_doc_max_bytes": "0",
64
+ "web_search": _toml("disabled"),
65
+ "cli_auth_credentials_store": _toml("file"),
66
+ # Shell commands get PATH and HOME only, never the model credential.
67
+ "shell_environment_policy.inherit": _toml("none"),
68
+ "shell_environment_policy.set": shell_env,
69
+ **{f"features.{feature}": "false" for feature in DISABLED_FEATURES},
70
+ }
71
+ argv = [
72
+ self.binary,
73
+ "exec",
74
+ "--sandbox",
75
+ "read-only",
76
+ "--json",
77
+ "--ephemeral",
78
+ "--ignore-user-config",
79
+ "--ignore-rules",
80
+ "--output-last-message",
81
+ output_path(task).as_posix(),
82
+ ]
83
+ for key, value in overrides.items():
84
+ argv += ["-c", f"{key}={value}"]
85
+ if task.model:
86
+ argv += ["--model", task.model]
87
+ return [*argv, "-"]
88
+
89
+ def run(self, task: AgentTask) -> AgentResult:
90
+ rel = output_path(task).as_posix()
91
+ prompt = (
92
+ f"{task.prompt}\n\nYour final message is saved as {rel}: make it only that JSON document, with no other "
93
+ "text and no code fence. Do not try to write any file; the workspace is read-only."
94
+ )
95
+ task = task.model_copy(update={"prompt": prompt})
96
+ with tempfile.TemporaryDirectory(prefix="reviewloop-home-") as home:
97
+ install_skills(task.step, task.skills, Path(home) / ".agents" / "skills")
98
+ auth = os.environ.get(AUTH_JSON_VAR)
99
+ if auth:
100
+ config = Path(home) / ".codex"
101
+ config.mkdir(mode=0o700)
102
+ fd = os.open(config / "auth.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
103
+ with os.fdopen(fd, "w") as handle:
104
+ handle.write(auth)
105
+ bin_dir = install_git_wrapper(Path(home), task.workdir)
106
+ env = self.environment(home)
107
+ env["PATH"] = os.pathsep.join([str(bin_dir), env.get("PATH", os.defpath)])
108
+ return run_cli(task, self.command(task, env), env)
@@ -0,0 +1,96 @@
1
+ """Cursor adapter (experimental): `cursor-agent -p` in allowlist mode, allowlist of four git commands.
2
+
3
+ Experimental because Cursor cannot hold shell commands to the allowlist. Its matcher drops `VAR=value` prefixes and
4
+ standalone assignments, so `PATH=/usr/bin git diff --no-index ...` or `GIT_EXTERNAL_DIFF=... git log -p --ext-diff`
5
+ matches `Shell(git log)`/`Shell(git diff)` and runs past the git guard; and it replays a login-shell state, which can
6
+ reset PATH ahead of the guard. In print mode it still rejects shell commands, MCP tools and web fetches the allowlist
7
+ does not cover. Its own sandbox stays off: with it on, any command that fits the sandbox would run without being on
8
+ the allowlist. Cursor cannot limit edits to one file, so the post-run snapshot check is what enforces writes.
9
+
10
+ Credentials: CURSOR_API_KEY only. HOME is a fresh temporary directory per run, so a `cursor-agent login` session is not
11
+ used. Cursor loads AGENTS.md and CLAUDE.md from the copy as rules; they stay, as data the review may read, and the
12
+ output contract tells the agent to treat repository text as data. See docs/adr/0002-agent-tool-restriction.md.
13
+ """
14
+
15
+ import json
16
+ import os
17
+ import tempfile
18
+ from pathlib import Path
19
+
20
+ from reviewloop.agents.base import AgentResult, AgentTask
21
+ from reviewloop.agents.isolation import install_git_wrapper, install_skills, scrub_env
22
+ from reviewloop.agents.runner import run_cli
23
+ from reviewloop.errors import AgentStepError
24
+
25
+ API_KEY_VAR = "CURSOR_API_KEY"
26
+ GIT_COMMANDS = ("git log", "git blame", "git show", "git diff")
27
+ # Deny wins over allow. These are an outer layer only (see the module docstring). git by path or through a launcher
28
+ # would skip the git guard; `$` or backtick expansion and /proc could print the model credential. With Cursor's sandbox
29
+ # off its Read tool is not held to the workspace (`readBoundary` applies to sandboxed commands only), so the Read denies
30
+ # name runner files that hold VCS or registry credentials outside the copy. They match the path as written, so they
31
+ # are best effort; see the ADR.
32
+ DENY = (
33
+ "Shell(*/git)",
34
+ "Shell(env)",
35
+ "Shell(command)",
36
+ "Shell(exec)",
37
+ "Shell(*$*)",
38
+ "Shell(*`*)",
39
+ "Shell(*/proc/*)",
40
+ "Read(/proc/*)",
41
+ "Read(*/.git/config)",
42
+ "Read(*/.git/modules/*)",
43
+ "Read(*/.git-credentials)",
44
+ "Read(*/.config/gh/*)",
45
+ "Read(*/.config/glab-cli/*)",
46
+ "Read(*/.netrc)",
47
+ "Read(*/.ssh/*)",
48
+ "Read(*/.docker/config.json)",
49
+ "WebFetch(*)",
50
+ "Mcp(*:*)",
51
+ )
52
+ # User config in the throwaway HOME. The copy's `.cursor/cli.json` is removed by `prepare_sandbox`.
53
+ CONFIG = {
54
+ "version": 1,
55
+ "editor": {"vimMode": False},
56
+ "approvalMode": "allowlist",
57
+ "autoAcceptWebSearch": False,
58
+ "sandbox": {"mode": "disabled", "readBoundary": "workspace"},
59
+ "permissions": {"allow": [f"Shell({cmd})" for cmd in GIT_COMMANDS], "deny": list(DENY)},
60
+ }
61
+
62
+
63
+ class CursorAdapter:
64
+ name = "cursor"
65
+ experimental = True
66
+
67
+ def __init__(self, binary: str = "cursor-agent") -> None:
68
+ self.binary = binary
69
+
70
+ def check_auth(self) -> None:
71
+ if not os.environ.get(API_KEY_VAR):
72
+ raise AgentStepError(f"Cursor has no credential: set {API_KEY_VAR}")
73
+
74
+ def environment(self, home: str) -> dict[str, str]:
75
+ env = scrub_env([API_KEY_VAR])
76
+ env["HOME"] = home
77
+ return env
78
+
79
+ def command(self, task: AgentTask) -> list[str]:
80
+ # `--trust` stores the trust mark under the throwaway HOME; without it print mode refuses an unknown workspace.
81
+ argv = [self.binary, "-p", "--output-format", "stream-json", "--trust", "--sandbox", "disabled"]
82
+ if task.model:
83
+ argv += ["--model", task.model]
84
+ return argv
85
+
86
+ def run(self, task: AgentTask) -> AgentResult:
87
+ argv = self.command(task)
88
+ with tempfile.TemporaryDirectory(prefix="reviewloop-home-") as home:
89
+ config = Path(home) / ".cursor"
90
+ install_skills(task.step, task.skills, config / "skills")
91
+ config.mkdir(exist_ok=True)
92
+ (config / "cli-config.json").write_text(json.dumps(CONFIG))
93
+ bin_dir = install_git_wrapper(Path(home), task.workdir)
94
+ env = self.environment(home)
95
+ env["PATH"] = os.pathsep.join([str(bin_dir), env.get("PATH", os.defpath)])
96
+ return run_cli(task, argv, env)
@@ -0,0 +1,214 @@
1
+ """Allowlist guard that stands in for `git` during an agent run (ruling R17).
2
+
3
+ An installed copy of this file is the agent's `git`, first on its PATH. It runs under `python -I` with only the
4
+ standard library. It allows `git log|blame|show|diff` with a fixed set of exact options per subcommand, requires every
5
+ argument that can name a file to resolve inside the sandbox, then execs the real git with the pager, external diff
6
+ and textconv turned off. CLI deny patterns cannot do this: git accepts abbreviated long options and grouped short
7
+ options, and `git diff` silently switches to no-index mode for a path outside the repository.
8
+ """
9
+
10
+ import os
11
+ import re
12
+ import sys
13
+ from collections.abc import Callable, Sequence
14
+
15
+
16
+ class GitDenied(Exception):
17
+ """An argument outside the allowlist; the wrapper prints it after `reviewloop: ` and exits 2."""
18
+
19
+
20
+ # FLAG takes no value. REQUIRED takes `--name=value`, or a short option's attached value or next argument.
21
+ # OPTIONAL takes `--name=value` or an attached short value, never the next argument.
22
+ FLAG, REQUIRED, OPTIONAL = "flag", "required", "optional"
23
+ Check = Callable[[str], list[str]]
24
+ Options = dict[str, tuple[str, Check]]
25
+
26
+
27
+ def _matching(pattern: str, path_group: int | None = None) -> Check:
28
+ compiled = re.compile(pattern)
29
+
30
+ def check(value: str) -> list[str]:
31
+ match = compiled.fullmatch(value)
32
+ if match is None:
33
+ raise ValueError(value)
34
+ return [match.group(path_group)] if path_group else []
35
+
36
+ return check
37
+
38
+
39
+ _NONE = _matching(r"")
40
+ _ANY = _matching(r".*")
41
+ _NUM = _matching(r"\d+")
42
+ _SCORE = _matching(r"\d+%?")
43
+ _WORD_DIFF = _matching(r"plain|color|porcelain|none")
44
+ # -L <start>[,<end>] where each bound is a line number or /regex/ (end may be +n/-n), or :<funcname>.
45
+ _RANGE_SPEC = r"(?:\d+|/[^/]*/)(?:,(?:[+-]?\d+|/[^/]*/))?|:[^:]+"
46
+ _BLAME_RANGE = _matching(_RANGE_SPEC)
47
+ _LOG_RANGE = _matching(rf"(?:{_RANGE_SPEC}):(.+)", 1)
48
+
49
+
50
+ def _flags(*names: str) -> Options:
51
+ return dict.fromkeys(names, (FLAG, _NONE))
52
+
53
+
54
+ SUBCOMMANDS: dict[str, Options] = {
55
+ "log": {
56
+ **_flags("-p", "--oneline", "--stat", "--name-only", "--name-status", "--follow", "--no-merges"),
57
+ **_flags("--first-parent", "--reverse", "--graph", "--decorate"),
58
+ "-n": (REQUIRED, _NUM),
59
+ "-L": (REQUIRED, _LOG_RANGE),
60
+ "--max-count": (REQUIRED, _NUM),
61
+ **{name: (REQUIRED, _ANY) for name in ("--format", "--pretty", "--since", "--until", "--author", "--grep")},
62
+ },
63
+ "blame": {
64
+ **_flags("-w", "--porcelain", "--line-porcelain", "-s", "-e"),
65
+ "-L": (REQUIRED, _BLAME_RANGE),
66
+ "-M": (OPTIONAL, _SCORE),
67
+ "-C": (OPTIONAL, _SCORE),
68
+ "--date": (REQUIRED, _ANY),
69
+ },
70
+ "show": {
71
+ **_flags("-p", "--stat", "--name-only", "--name-status"),
72
+ "--format": (REQUIRED, _ANY),
73
+ "--pretty": (REQUIRED, _ANY),
74
+ "-U": (REQUIRED, _NUM),
75
+ },
76
+ "diff": {
77
+ **_flags("--stat", "--name-only", "--name-status", "--cached", "--staged", "-w", "--ignore-space-change"),
78
+ **_flags("--function-context"),
79
+ "-U": (REQUIRED, _NUM),
80
+ "--word-diff": (OPTIONAL, _WORD_DIFF),
81
+ },
82
+ }
83
+ SAFE_FLAGS = {"blame": ["--no-textconv"]}
84
+ DIFF_SAFE_FLAGS = ["--no-ext-diff", "--no-textconv"]
85
+
86
+ _RANGE = re.compile(r"(.*?)(\.\.\.?)(.*)")
87
+ # A revision side of `a..b`: starts like a ref (never `/`, `~` or `.`), never contains `..` or a `/.` segment.
88
+ _REV = re.compile(r"[\w@{}^+-][\w@{}^~+/.-]*")
89
+
90
+
91
+ def _is_rev(side: str) -> bool:
92
+ if not side:
93
+ return True
94
+ unsafe = ".." in side or "/." in side or "//" in side or side.endswith(("/", "."))
95
+ return bool(_REV.fullmatch(side)) and not unsafe
96
+
97
+
98
+ def _is_range(arg: str) -> bool:
99
+ match = _RANGE.fullmatch(arg)
100
+ return bool(match and (match[1] or match[3]) and _is_rev(match[1]) and _is_rev(match[3]))
101
+
102
+
103
+ class _Checker:
104
+ def __init__(self, root: str, cwd: str) -> None:
105
+ self.root = os.path.realpath(root)
106
+ self.cwd = os.path.realpath(cwd)
107
+ if not self._inside(self.cwd):
108
+ raise GitDenied("git must run inside the sandbox")
109
+
110
+ def _inside(self, real: str) -> bool:
111
+ return real == self.root or real.startswith(self.root + os.sep)
112
+
113
+ def path(self, value: str, base: str | None = None) -> None:
114
+ if value.startswith("~") or os.path.isabs(value):
115
+ raise GitDenied(f"git path outside the sandbox: {value}")
116
+ if not self._inside(os.path.realpath(os.path.join(base or self.cwd, value))):
117
+ raise GitDenied(f"git path outside the sandbox: {value}")
118
+
119
+ def positional(self, arg: str) -> None:
120
+ if _is_range(arg):
121
+ return
122
+ # The whole argument may be read as a file (diff falls back to no-index for paths outside the repository),
123
+ # so check it as a path first, even when it also looks like `<rev>:<path>`.
124
+ if "/" in arg or ":" in arg or arg.startswith("~") or self.on_disk(arg):
125
+ self.path(arg)
126
+ if ":" in arg:
127
+ # <rev>:<path> and :<stage>:<path> name a path from the repository root, ./ and ../ from the cwd.
128
+ rest = re.sub(r"^\d:", "", arg[1:]) if arg.startswith(":") else arg.split(":", 1)[1]
129
+ self.path(rest, None if rest.startswith(("./", "../")) else self.root)
130
+
131
+ def on_disk(self, arg: str) -> bool:
132
+ return os.path.lexists(os.path.join(self.cwd, arg))
133
+
134
+ def value(self, check: Check, value: str, shown: str) -> None:
135
+ try:
136
+ paths = check(value)
137
+ except ValueError:
138
+ raise GitDenied(f"git option value not allowed: {shown}") from None
139
+ for path in paths:
140
+ self.path(path)
141
+
142
+
143
+ def _short_group(arg: str, options: Options, rest: list[str], checker: _Checker) -> None:
144
+ for j in range(1, len(arg)):
145
+ name = "-" + arg[j]
146
+ if name not in options:
147
+ raise GitDenied(f"git option not allowed: {name}")
148
+ kind, check = options[name]
149
+ if kind == FLAG:
150
+ continue
151
+ value = arg[j + 1 :]
152
+ if kind == REQUIRED and not value:
153
+ if not rest:
154
+ raise GitDenied(f"git option needs a value: {name}")
155
+ value = rest.pop(0)
156
+ if value:
157
+ checker.value(check, value, name + value)
158
+ return
159
+
160
+
161
+ def git_command(args: Sequence[str], *, real_git: str, root: str, cwd: str) -> list[str]:
162
+ """Validate an agent's git arguments and return the real git argv, or raise `GitDenied`."""
163
+ checker = _Checker(root, cwd)
164
+ if not args:
165
+ raise GitDenied("git subcommand not allowed: (none)")
166
+ sub, rest = args[0], list(args[1:])
167
+ if sub.startswith("-"):
168
+ raise GitDenied(f"git option not allowed: {sub}")
169
+ if sub not in SUBCOMMANDS:
170
+ raise GitDenied(f"git subcommand not allowed: {sub}")
171
+ options = SUBCOMMANDS[sub]
172
+ pending = list(rest)
173
+ while pending:
174
+ arg = pending.pop(0)
175
+ if arg == "--":
176
+ for path in pending:
177
+ checker.path(path)
178
+ break
179
+ if arg.startswith("--"):
180
+ name, eq, value = arg.partition("=")
181
+ if name not in options:
182
+ raise GitDenied(f"git option not allowed: {name}")
183
+ kind, check = options[name]
184
+ if kind == FLAG and eq:
185
+ raise GitDenied(f"git option takes no value: {arg}")
186
+ if kind == REQUIRED and not eq:
187
+ raise GitDenied(f"git option needs =<value>: {name}")
188
+ if eq:
189
+ checker.value(check, value, arg)
190
+ elif arg == "-":
191
+ raise GitDenied("git option not allowed: -")
192
+ elif arg.startswith("-"):
193
+ _short_group(arg, options, pending, checker)
194
+ else:
195
+ checker.positional(arg)
196
+ # Without `--`, git diff treats two paths as a no-index diff of arbitrary files. Revisions never name a
197
+ # file in the working tree, so a diff argument that exists on disk must come after `--`.
198
+ if sub == "diff" and checker.on_disk(arg):
199
+ raise GitDenied(f"git diff paths must follow --: {arg}")
200
+ # --literal-pathspecs turns off pathspec magic such as `:(top)` and `:(glob)`, so a path means what it says.
201
+ return [real_git, "--no-pager", "--literal-pathspecs", sub, *SAFE_FLAGS.get(sub, DIFF_SAFE_FLAGS), *rest]
202
+
203
+
204
+ def git_wrapper_main(argv: Sequence[str], *, real_git: str, root: str) -> int:
205
+ try:
206
+ command = git_command(argv, real_git=real_git, root=root, cwd=os.getcwd())
207
+ except GitDenied as exc:
208
+ print(f"reviewloop: {exc}", file=sys.stderr)
209
+ return 2
210
+ # Any GIT_* variable (GIT_DIR, GIT_EXTERNAL_DIFF, GIT_CONFIG_PARAMETERS, ...) could redirect or extend git.
211
+ env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")}
212
+ env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_PAGER="cat")
213
+ os.execve(real_git, command, env) # noqa: S606
214
+ return 0