-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoreview.py
More file actions
415 lines (327 loc) · 14.5 KB
/
Copy pathautoreview.py
File metadata and controls
415 lines (327 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
"""
AutoReview — 3-stage AI review pipeline using Claude and Codex CLIs.
Read-only analysis of a target codebase directory.
"""
import asyncio
import json
import re
import shutil
import sys
from datetime import datetime
from pathlib import Path
from rich.console import Console
from rich.panel import Panel
from rich.spinner import Spinner
from rich.live import Live
from rich.text import Text
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
SUBPROCESS_TIMEOUT = 300 # seconds
CROSS_REVIEW_CONTEXT = (
"Here is the report that we received from a company. Review the report generated and compare "
"with your findings to create a more accurate final report. In the report, do not include "
"comparisons, only include findings that are more accurate."
)
ARBITRATION_CONTEXT = (
"Here are 2 reports generated for the issue below. Determine which report is more accurate.\n"
"Return only a single character: 1 or 2.\n"
"Do not include any explanation, words, punctuation, or markdown.\n\n"
"{user_prompt}\n\n"
"--- Report 1 (Claude) ---\n"
"{claude_report_2}\n\n"
"--- Report 2 (Codex) ---\n"
"{codex_report_2}"
)
console = Console()
# ---------------------------------------------------------------------------
# Subprocess helpers
# ---------------------------------------------------------------------------
def _resolve_exe(name: str) -> list[str]:
"""Return the command prefix needed to run a CLI tool on this platform.
On Windows, .cmd/.bat files must be invoked via 'cmd /c'."""
if sys.platform == "win32":
# npm global bins often include multiple shims (e.g. `codex`, `codex.cmd`, `codex.ps1`).
# `shutil.which("codex")` may return the extensionless shim first, which cannot be
# executed directly by CreateProcess and raises WinError 193.
path = None
for candidate in (f"{name}.cmd", f"{name}.bat", f"{name}.exe", name):
path = shutil.which(candidate)
if path:
break
path = path or name
else:
path = shutil.which(name) or name
if sys.platform == "win32" and path.lower().endswith((".cmd", ".bat")):
return ["cmd", "/c", path]
return [path]
async def run_claude(prompt: str, cwd: Path) -> str:
"""Invoke the claude CLI and return the final response text (reasoning-free)."""
cmd = _resolve_exe("claude") + ["--output-format", "json", "-p", prompt]
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=str(cwd),
)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=SUBPROCESS_TIMEOUT)
except asyncio.TimeoutError:
raise RuntimeError(f"Stage timed out after {SUBPROCESS_TIMEOUT}s (claude)")
stdout_text = stdout.decode("utf-8", errors="replace").strip()
stderr_text = stderr.decode("utf-8", errors="replace").strip()
if proc.returncode != 0:
detail = stderr_text or stdout_text or "(no output)"
raise RuntimeError(f"claude exited with code {proc.returncode}: {detail}")
if not stdout_text:
raise RuntimeError("claude returned an empty response")
# Parse JSON and extract the result field
try:
data = json.loads(stdout_text)
result = data.get("result") or data.get("content") or data.get("text")
if result is None:
# Try first item if it's a list
if isinstance(data, list) and data:
first = data[0]
result = first.get("result") or first.get("content") or first.get("text")
if result is not None:
return str(result).strip()
# Fallback: return raw stdout
return stdout_text
except (json.JSONDecodeError, AttributeError):
# Fallback to raw stdout
return stdout_text
async def run_codex(
prompt: str,
cwd: Path,
session_id: str | None = None,
) -> tuple[str, str | None]:
"""
Invoke the codex CLI and return (response_text, session_id_if_found).
If session_id is provided, continues that session.
"""
# codex-cli >=0.104 uses the non-interactive `exec` subcommand and `--full-auto`.
# Pass the prompt over stdin (`-`) to avoid Windows cmd.exe command-line length truncation,
# which can cut off large Stage 2/3 prompts and produce unrelated answers.
base = _resolve_exe("codex") + ["exec", "--full-auto", "--skip-git-repo-check", "-"]
if session_id:
# Newer codex CLI resumes via `exec resume <session_id> <prompt>`.
cmd = _resolve_exe("codex") + [
"exec",
"resume",
"--full-auto",
"--skip-git-repo-check",
session_id,
"-",
]
else:
cmd = base
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=str(cwd),
)
stdout, stderr = await asyncio.wait_for(
proc.communicate(prompt.encode("utf-8")),
timeout=SUBPROCESS_TIMEOUT,
)
except asyncio.TimeoutError:
raise RuntimeError(f"Stage timed out after {SUBPROCESS_TIMEOUT}s (codex)")
stdout_text = stdout.decode("utf-8", errors="replace").strip()
stderr_text = stderr.decode("utf-8", errors="replace").strip()
if proc.returncode != 0:
detail = stderr_text or stdout_text or "(no output)"
raise RuntimeError(f"codex exited with code {proc.returncode}: {detail}")
if not stdout_text:
raise RuntimeError("codex returned an empty response")
# Extract session ID from output if present
found_session_id = _extract_codex_session_id(stdout_text)
# Strip reasoning and get the final response text
response = strip_reasoning_codex(stdout_text)
return response, found_session_id
def _extract_codex_session_id(raw: str) -> str | None:
"""Try to find a session ID in codex output."""
# Common patterns: "session: <id>", "Session ID: <id>", JSON {"session_id": "..."}
patterns = [
r'"session[_\-]?id"\s*:\s*"([^"]+)"',
r'session[_\-]?id[:\s]+([a-zA-Z0-9\-_]+)',
r'Session[:\s]+([a-zA-Z0-9\-_]{8,})',
]
for pattern in patterns:
m = re.search(pattern, raw, re.IGNORECASE)
if m:
return m.group(1)
return None
# ---------------------------------------------------------------------------
# Text processing
# ---------------------------------------------------------------------------
def strip_reasoning_codex(raw: str) -> str:
"""Strip <thinking>…</thinking> blocks and extract the last assistant turn."""
# Remove thinking blocks (dotall)
cleaned = re.sub(r"<thinking>.*?</thinking>", "", raw, flags=re.DOTALL | re.IGNORECASE)
# Try to extract last assistant content block
# Patterns like "Assistant:" or "assistant\n" followed by content
assistant_patterns = [
r"(?:^|\n)(?:assistant|ASSISTANT)\s*[:\-]\s*([\s\S]+?)(?=\n(?:user|human|system|assistant|USER|HUMAN|SYSTEM|ASSISTANT)\s*[:\-]|$)",
r"(?:^|\n)(?:assistant|ASSISTANT)\s*\n([\s\S]+?)(?=\n(?:user|human|system|assistant|USER|HUMAN|SYSTEM|ASSISTANT)\s*\n|$)",
]
last_match = None
for pattern in assistant_patterns:
for m in re.finditer(pattern, cleaned, re.IGNORECASE):
last_match = m.group(1).strip()
if last_match:
return last_match
# If no assistant markers, return cleaned text as-is
return cleaned.strip()
def parse_arbitration_choice(raw: str) -> int:
"""Parse Codex arbitration output and return 1 or 2."""
text = raw.strip()
if text in {"1", "2"}:
return int(text)
# Tolerate minor format drift like "Report 2" or "2." while keeping the contract strict.
match = re.search(r"\b([12])\b", text)
if match:
return int(match.group(1))
raise RuntimeError(f"Stage 3 returned invalid arbitration choice: {text!r}")
# ---------------------------------------------------------------------------
# Prompt builders
# ---------------------------------------------------------------------------
def build_cross_review_prompt(other_report: str) -> str:
"""Build the Stage 2 cross-review prompt."""
return f"{CROSS_REVIEW_CONTEXT}\n\n{other_report}"
def build_arbitration_prompt(
user_prompt: str,
claude_report: str,
codex_report: str,
) -> str:
"""Build the Stage 3 arbitration prompt."""
return ARBITRATION_CONTEXT.format(
user_prompt=user_prompt,
claude_report_2=claude_report,
codex_report_2=codex_report,
)
# ---------------------------------------------------------------------------
# Report saving
# ---------------------------------------------------------------------------
def save_report(cwd: Path, user_prompt: str, supreme_report: str) -> Path:
"""Write review_YYYYMMDD_HHMMSS.md to cwd and return the path."""
timestamp = datetime.now()
filename = f"review_{timestamp.strftime('%Y%m%d_%H%M%S')}.md"
output_path = cwd / filename
content = (
"# AutoReview Report\n\n"
f"**Date:** {timestamp.strftime('%Y-%m-%d %H:%M:%S')}\n"
f"**Query:** {user_prompt}\n\n"
"---\n\n"
"## Supreme Report\n\n"
f"{supreme_report}\n"
)
output_path.write_text(content, encoding="utf-8")
return output_path
# ---------------------------------------------------------------------------
# Pipeline orchestration
# ---------------------------------------------------------------------------
async def run_pipeline(user_prompt: str, cwd: Path) -> None:
"""Orchestrate the full 3-stage review pipeline."""
# --- Stage 1 — Parallel initial analysis ---
with _spinner("Stage 1/3 — Parallel analysis (Claude + Codex)..."):
stage1_results = await asyncio.gather(
run_claude(user_prompt, cwd),
run_codex(user_prompt, cwd),
return_exceptions=True,
)
claude_result_1 = stage1_results[0]
codex_result_1 = stage1_results[1]
if isinstance(claude_result_1, Exception):
raise RuntimeError(f"Stage 1 Claude failed: {claude_result_1}") from claude_result_1
if isinstance(codex_result_1, Exception):
raise RuntimeError(f"Stage 1 Codex failed: {codex_result_1}") from codex_result_1
claude_report_1: str = claude_result_1
codex_response_1, codex_session_id = codex_result_1 # type: ignore[misc]
console.print(f" [dim]Stage 1 complete. Codex session: {codex_session_id or 'none'}[/dim]")
# --- Stage 2 — Parallel cross-review ---
with _spinner("Stage 2/3 — Cross-review (Claude reviews Codex, Codex reviews Claude)..."):
cross_prompt_for_claude = build_cross_review_prompt(codex_response_1)
cross_prompt_for_codex = build_cross_review_prompt(claude_report_1)
stage2_results = await asyncio.gather(
run_claude(cross_prompt_for_claude, cwd),
run_codex(cross_prompt_for_codex, cwd, session_id=codex_session_id),
return_exceptions=True,
)
claude_result_2 = stage2_results[0]
codex_result_2 = stage2_results[1]
if isinstance(claude_result_2, Exception):
raise RuntimeError(f"Stage 2 Claude failed: {claude_result_2}") from claude_result_2
if isinstance(codex_result_2, Exception):
raise RuntimeError(f"Stage 2 Codex failed: {codex_result_2}") from codex_result_2
claude_report_2: str = claude_result_2
codex_report_2_text, _ = codex_result_2 # type: ignore[misc]
# --- Stage 3 — Arbitration ---
with _spinner("Stage 3/3 — Arbitration (Codex synthesises supreme report)..."):
arbitration_prompt = build_arbitration_prompt(
user_prompt=user_prompt,
claude_report=claude_report_2,
codex_report=codex_report_2_text,
)
arb_result = await run_codex(arbitration_prompt, cwd, session_id=None)
arbitration_response, _ = arb_result
winner = parse_arbitration_choice(arbitration_response)
supreme_report = claude_report_2 if winner == 1 else codex_report_2_text
if not supreme_report.strip():
raise RuntimeError("Stage 3 returned an empty supreme report")
# --- Save ---
report_path = save_report(cwd, user_prompt, supreme_report)
console.print(f"\n[bold green]Report saved:[/bold green] {report_path}")
# ---------------------------------------------------------------------------
# Rich spinner context manager
# ---------------------------------------------------------------------------
class _spinner:
"""Simple context manager that shows a rich spinner while work runs."""
def __init__(self, label: str) -> None:
self._label = label
self._live: Live | None = None
def __enter__(self) -> "_spinner":
spinner = Spinner("dots", text=Text(self._label, style="bold cyan"))
self._live = Live(spinner, console=console, transient=True, refresh_per_second=10)
self._live.__enter__()
return self
def __exit__(self, *args: object) -> None:
if self._live:
self._live.__exit__(*args)
console.print(f" [green]✓[/green] {self._label.rstrip('.')}")
# ---------------------------------------------------------------------------
# Main interactive loop
# ---------------------------------------------------------------------------
def main() -> None:
cwd = Path.cwd()
console.print(
Panel(
f"[bold cyan]AutoReview[/bold cyan]\n"
f"3-stage AI review pipeline • Claude Opus 4.6 + Codex 5.3\n\n"
f"[dim]Analysing:[/dim] [yellow]{cwd}[/yellow]",
border_style="cyan",
padding=(1, 2),
)
)
while True:
try:
query = console.input("\n[bold]Enter your query[/bold] (or [dim]quit[/dim] to exit): ").strip()
except (EOFError, KeyboardInterrupt):
console.print("\n[dim]Exiting.[/dim]")
break
if not query:
continue
if query.lower() in ("quit", "exit", "q"):
console.print("[dim]Goodbye.[/dim]")
break
try:
asyncio.run(run_pipeline(query, cwd))
except RuntimeError as exc:
console.print(f"\n[bold red]Error:[/bold red] {exc}")
except Exception as exc: # noqa: BLE001
console.print(f"\n[bold red]Unexpected error:[/bold red] {exc}")
if __name__ == "__main__":
main()