coderace 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.
coderace/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """coderace - Race coding agents against each other on real tasks."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,23 @@
1
+ """Agent adapters for coderace."""
2
+
3
+ from coderace.adapters.aider import AiderAdapter
4
+ from coderace.adapters.base import BaseAdapter
5
+ from coderace.adapters.claude import ClaudeAdapter
6
+ from coderace.adapters.codex import CodexAdapter
7
+ from coderace.adapters.gemini import GeminiAdapter
8
+
9
+ ADAPTERS: dict[str, type[BaseAdapter]] = {
10
+ "claude": ClaudeAdapter,
11
+ "codex": CodexAdapter,
12
+ "aider": AiderAdapter,
13
+ "gemini": GeminiAdapter,
14
+ }
15
+
16
+ __all__ = [
17
+ "ADAPTERS",
18
+ "BaseAdapter",
19
+ "ClaudeAdapter",
20
+ "CodexAdapter",
21
+ "AiderAdapter",
22
+ "GeminiAdapter",
23
+ ]
@@ -0,0 +1,20 @@
1
+ """Aider adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from coderace.adapters.base import BaseAdapter
6
+
7
+
8
+ class AiderAdapter(BaseAdapter):
9
+ """Adapter for Aider coding assistant."""
10
+
11
+ name = "aider"
12
+
13
+ def build_command(self, task_description: str) -> list[str]:
14
+ return [
15
+ "aider",
16
+ "--message",
17
+ task_description,
18
+ "--yes",
19
+ "--no-auto-commits",
20
+ ]
@@ -0,0 +1,60 @@
1
+ """Base adapter interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ import time
7
+ from abc import ABC, abstractmethod
8
+ from pathlib import Path
9
+
10
+ from coderace.types import AgentResult
11
+
12
+
13
+ class BaseAdapter(ABC):
14
+ """Abstract base class for coding agent adapters."""
15
+
16
+ name: str = "base"
17
+
18
+ @abstractmethod
19
+ def build_command(self, task_description: str) -> list[str]:
20
+ """Build the CLI command to invoke this agent."""
21
+ ...
22
+
23
+ def run(self, task_description: str, workdir: Path, timeout: int) -> AgentResult:
24
+ """Run the agent on a task and capture results."""
25
+ cmd = self.build_command(task_description)
26
+ start = time.monotonic()
27
+ timed_out = False
28
+
29
+ try:
30
+ proc = subprocess.run(
31
+ cmd,
32
+ cwd=workdir,
33
+ capture_output=True,
34
+ text=True,
35
+ timeout=timeout,
36
+ )
37
+ exit_code = proc.returncode
38
+ stdout = proc.stdout
39
+ stderr = proc.stderr
40
+ except subprocess.TimeoutExpired as e:
41
+ timed_out = True
42
+ exit_code = -1
43
+ stdout = (e.stdout or b"").decode("utf-8", errors="replace") if e.stdout else ""
44
+ stderr = (e.stderr or b"").decode("utf-8", errors="replace") if e.stderr else ""
45
+ except FileNotFoundError:
46
+ timed_out = False
47
+ exit_code = 127
48
+ stdout = ""
49
+ stderr = f"Command not found: {cmd[0]}"
50
+
51
+ wall_time = time.monotonic() - start
52
+
53
+ return AgentResult(
54
+ agent=self.name,
55
+ exit_code=exit_code,
56
+ stdout=stdout,
57
+ stderr=stderr,
58
+ wall_time=wall_time,
59
+ timed_out=timed_out,
60
+ )
@@ -0,0 +1,21 @@
1
+ """Claude Code adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from coderace.adapters.base import BaseAdapter
6
+
7
+
8
+ class ClaudeAdapter(BaseAdapter):
9
+ """Adapter for Claude Code CLI."""
10
+
11
+ name = "claude"
12
+
13
+ def build_command(self, task_description: str) -> list[str]:
14
+ return [
15
+ "claude",
16
+ "--print",
17
+ "--output-format",
18
+ "json",
19
+ "-p",
20
+ task_description,
21
+ ]
@@ -0,0 +1,20 @@
1
+ """Codex CLI adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from coderace.adapters.base import BaseAdapter
6
+
7
+
8
+ class CodexAdapter(BaseAdapter):
9
+ """Adapter for OpenAI Codex CLI."""
10
+
11
+ name = "codex"
12
+
13
+ def build_command(self, task_description: str) -> list[str]:
14
+ return [
15
+ "codex",
16
+ "--quiet",
17
+ "--full-auto",
18
+ "-p",
19
+ task_description,
20
+ ]
@@ -0,0 +1,19 @@
1
+ """Gemini CLI adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from coderace.adapters.base import BaseAdapter
6
+
7
+
8
+ class GeminiAdapter(BaseAdapter):
9
+ """Adapter for Google Gemini CLI."""
10
+
11
+ name = "gemini"
12
+
13
+ def build_command(self, task_description: str) -> list[str]:
14
+ return [
15
+ "gemini",
16
+ "--non-interactive",
17
+ "-p",
18
+ task_description,
19
+ ]
coderace/cli.py ADDED
@@ -0,0 +1,306 @@
1
+ """CLI interface for coderace."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import typer
8
+ from rich.console import Console
9
+
10
+ from coderace import __version__
11
+ from coderace.adapters import ADAPTERS
12
+ from coderace.git_ops import (
13
+ add_worktree,
14
+ branch_name_for,
15
+ checkout,
16
+ create_branch,
17
+ get_current_ref,
18
+ get_diff_stat,
19
+ has_uncommitted_changes,
20
+ prune_worktrees,
21
+ remove_worktree,
22
+ )
23
+ from coderace.reporter import print_results, save_results_json
24
+ from coderace.scorer import compute_score
25
+ from coderace.task import create_template, load_task
26
+ from coderace.types import AgentResult, Score
27
+
28
+ app = typer.Typer(
29
+ name="coderace",
30
+ help="Race coding agents against each other on real tasks.",
31
+ no_args_is_help=True,
32
+ )
33
+ console = Console()
34
+
35
+
36
+ @app.command()
37
+ def init(
38
+ name: str = typer.Argument(help="Task name"),
39
+ output_dir: Path = typer.Option(".", "--output", "-o", help="Output directory"),
40
+ ) -> None:
41
+ """Create a task YAML template."""
42
+ path = create_template(name, output_dir)
43
+ console.print(f"[green]Created task template:[/green] {path}")
44
+ console.print("Edit the file to define your task, then run: coderace run " + str(path))
45
+
46
+
47
+ def _run_agent_sequential(
48
+ agent_name: str,
49
+ task_description: str,
50
+ repo: Path,
51
+ branch: str,
52
+ base_ref: str,
53
+ timeout: int,
54
+ ) -> tuple[AgentResult | None, int]:
55
+ """Run a single agent sequentially (on the main repo). Returns (result, lines_changed)."""
56
+ try:
57
+ create_branch(repo, branch, base_ref)
58
+ except Exception:
59
+ return None, 0
60
+
61
+ adapter = ADAPTERS[agent_name]()
62
+ result = adapter.run(task_description, repo, timeout)
63
+
64
+ _, lines = get_diff_stat(repo, base_ref)
65
+ return result, lines
66
+
67
+
68
+ def _run_agent_worktree(
69
+ agent_name: str,
70
+ task_description: str,
71
+ repo: Path,
72
+ branch: str,
73
+ base_ref: str,
74
+ timeout: int,
75
+ ) -> tuple[AgentResult | None, int]:
76
+ """Run a single agent in a git worktree (for parallel execution)."""
77
+ import tempfile
78
+
79
+ worktree_dir = Path(tempfile.mkdtemp(prefix=f"coderace-{agent_name}-"))
80
+
81
+ try:
82
+ # Create branch first (from main repo)
83
+ create_branch(repo, branch, base_ref)
84
+ # Checkout back so worktree can use the branch
85
+ checkout(repo, base_ref)
86
+ # Create worktree
87
+ add_worktree(repo, worktree_dir, branch)
88
+
89
+ adapter = ADAPTERS[agent_name]()
90
+ result = adapter.run(task_description, worktree_dir, timeout)
91
+
92
+ _, lines = get_diff_stat(worktree_dir, base_ref)
93
+ return result, lines
94
+ except Exception:
95
+ return None, 0
96
+ finally:
97
+ remove_worktree(repo, worktree_dir)
98
+ # Clean up temp dir if it still exists
99
+ import shutil
100
+
101
+ if worktree_dir.exists():
102
+ shutil.rmtree(worktree_dir, ignore_errors=True)
103
+
104
+
105
+ @app.command()
106
+ def run(
107
+ task_file: Path = typer.Argument(help="Path to task YAML file"),
108
+ agents: list[str] | None = typer.Option(None, "--agent", "-a", help="Override agent list"),
109
+ parallel: bool = typer.Option(False, "--parallel", "-p", help="Run agents in parallel"),
110
+ ) -> None:
111
+ """Run all agents on a task and score the results."""
112
+ task = load_task(task_file)
113
+
114
+ if agents:
115
+ task.agents = agents
116
+
117
+ repo = task.repo
118
+ if not repo.exists():
119
+ console.print(f"[red]Repo not found:[/red] {repo}")
120
+ raise typer.Exit(1)
121
+
122
+ if has_uncommitted_changes(repo):
123
+ console.print("[red]Repo has uncommitted changes. Commit or stash first.[/red]")
124
+ raise typer.Exit(1)
125
+
126
+ base_ref = get_current_ref(repo)
127
+ mode = "parallel" if parallel else "sequential"
128
+ console.print(f"[dim]Base ref: {base_ref[:8]} | Mode: {mode}[/dim]")
129
+ console.print(f"[dim]Task: {task.name}[/dim]")
130
+ console.print(f"[dim]Agents: {', '.join(task.agents)}[/dim]")
131
+ console.print()
132
+
133
+ # Validate agents
134
+ valid_agents = [a for a in task.agents if a in ADAPTERS]
135
+ invalid = set(task.agents) - set(valid_agents)
136
+ for name in invalid:
137
+ console.print(f"[red]Unknown agent: {name}[/red]")
138
+
139
+ if not valid_agents:
140
+ console.print("[red]No valid agents to run.[/red]")
141
+ raise typer.Exit(1)
142
+
143
+ agent_results: list[AgentResult] = []
144
+ diff_lines_map: dict[str, int] = {}
145
+
146
+ if parallel and len(valid_agents) > 1:
147
+ console.print("[cyan]Racing agents in parallel...[/cyan]")
148
+ from concurrent.futures import ThreadPoolExecutor, as_completed
149
+
150
+ futures = {}
151
+ with ThreadPoolExecutor(max_workers=len(valid_agents)) as executor:
152
+ for agent_name in valid_agents:
153
+ branch = branch_name_for(task.name, agent_name)
154
+ future = executor.submit(
155
+ _run_agent_worktree,
156
+ agent_name,
157
+ task.description,
158
+ repo,
159
+ branch,
160
+ base_ref,
161
+ task.timeout,
162
+ )
163
+ futures[future] = agent_name
164
+
165
+ for future in as_completed(futures):
166
+ agent_name = futures[future]
167
+ result, lines = future.result()
168
+ if result:
169
+ agent_results.append(result)
170
+ diff_lines_map[agent_name] = lines
171
+ if result.timed_out:
172
+ console.print(
173
+ f" [yellow]{agent_name}: timed out after {task.timeout}s[/yellow]"
174
+ )
175
+ elif result.exit_code != 0:
176
+ console.print(
177
+ f" [yellow]{agent_name}: exit code {result.exit_code}[/yellow]"
178
+ )
179
+ else:
180
+ console.print(
181
+ f" [green]{agent_name}: completed in {result.wall_time:.1f}s[/green]"
182
+ )
183
+ else:
184
+ console.print(f" [red]{agent_name}: failed to run[/red]")
185
+
186
+ prune_worktrees(repo)
187
+ else:
188
+ # Sequential mode
189
+ for agent_name in valid_agents:
190
+ branch = branch_name_for(task.name, agent_name)
191
+ console.print(f"[cyan]Running {agent_name}...[/cyan]")
192
+
193
+ result, lines = _run_agent_sequential(
194
+ agent_name, task.description, repo, branch, base_ref, task.timeout
195
+ )
196
+
197
+ if result is None:
198
+ console.print(f" [red]Failed to create branch for {agent_name}[/red]")
199
+ continue
200
+
201
+ agent_results.append(result)
202
+ diff_lines_map[agent_name] = lines
203
+
204
+ if result.timed_out:
205
+ console.print(f" [yellow]Timed out after {task.timeout}s[/yellow]")
206
+ elif result.exit_code != 0:
207
+ console.print(f" [yellow]Exit code: {result.exit_code}[/yellow]")
208
+ else:
209
+ console.print(f" [green]Completed in {result.wall_time:.1f}s[/green]")
210
+
211
+ console.print(f" [dim]Lines changed: {lines}[/dim]")
212
+
213
+ if not agent_results:
214
+ console.print("[red]No agents ran successfully.[/red]")
215
+ raise typer.Exit(1)
216
+
217
+ # Score each agent (checkout each branch for test/lint)
218
+ all_wall_times = [r.wall_time for r in agent_results]
219
+ all_diff_lines = [diff_lines_map.get(r.agent, 0) for r in agent_results]
220
+ scores: list[Score] = []
221
+
222
+ for result in agent_results:
223
+ branch = branch_name_for(task.name, result.agent)
224
+ checkout(repo, branch)
225
+
226
+ score = compute_score(
227
+ result=result,
228
+ test_command=task.test_command,
229
+ lint_command=task.lint_command,
230
+ workdir=repo,
231
+ diff_lines=diff_lines_map.get(result.agent, 0),
232
+ all_wall_times=all_wall_times,
233
+ all_diff_lines=all_diff_lines,
234
+ )
235
+ scores.append(score)
236
+
237
+ # Return to base ref
238
+ checkout(repo, base_ref)
239
+
240
+ # Display and save results
241
+ console.print()
242
+ print_results(scores, console)
243
+
244
+ results_dir = Path(task_file).parent / ".coderace"
245
+ json_path = results_dir / f"{task.name}-results.json"
246
+ save_results_json(scores, json_path)
247
+ console.print(f"\n[dim]Results saved to {json_path}[/dim]")
248
+
249
+
250
+ @app.command()
251
+ def results(
252
+ task_file: Path = typer.Argument(help="Path to task YAML file"),
253
+ ) -> None:
254
+ """Show results from the last run."""
255
+ task = load_task(task_file)
256
+ results_dir = Path(task_file).parent / ".coderace"
257
+ json_path = results_dir / f"{task.name}-results.json"
258
+
259
+ if not json_path.exists():
260
+ console.print(f"[red]No results found. Run the task first:[/red] coderace run {task_file}")
261
+ raise typer.Exit(1)
262
+
263
+ from coderace.reporter import load_results_json
264
+
265
+ data = load_results_json(json_path)
266
+
267
+ from rich.table import Table
268
+
269
+ table = Table(title=f"coderace results: {task.name}", show_lines=True)
270
+ table.add_column("Rank", justify="center", style="bold")
271
+ table.add_column("Agent", style="cyan")
272
+ table.add_column("Score", justify="right", style="bold green")
273
+ table.add_column("Tests", justify="center")
274
+ table.add_column("Exit", justify="center")
275
+ table.add_column("Lint", justify="center")
276
+ table.add_column("Time (s)", justify="right")
277
+ table.add_column("Lines", justify="right")
278
+
279
+ for entry in data:
280
+ b = entry["breakdown"]
281
+ table.add_row(
282
+ str(entry["rank"]),
283
+ entry["agent"],
284
+ f"{entry['composite_score']:.1f}",
285
+ _bool_icon(b["tests_pass"]),
286
+ _bool_icon(b["exit_clean"]),
287
+ _bool_icon(b["lint_clean"]),
288
+ f"{b['wall_time']:.1f}",
289
+ str(b["lines_changed"]),
290
+ )
291
+
292
+ console.print(table)
293
+
294
+
295
+ @app.command()
296
+ def version() -> None:
297
+ """Show coderace version."""
298
+ console.print(f"coderace {__version__}")
299
+
300
+
301
+ def _bool_icon(val: bool) -> str:
302
+ return "[green]PASS[/green]" if val else "[red]FAIL[/red]"
303
+
304
+
305
+ if __name__ == "__main__":
306
+ app()
coderace/git_ops.py ADDED
@@ -0,0 +1,151 @@
1
+ """Git operations for branch isolation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+
9
+ class GitError(Exception):
10
+ """Raised when a git operation fails."""
11
+
12
+
13
+ def get_current_ref(repo: Path) -> str:
14
+ """Get the current HEAD commit hash."""
15
+ result = subprocess.run(
16
+ ["git", "rev-parse", "HEAD"],
17
+ cwd=repo,
18
+ capture_output=True,
19
+ text=True,
20
+ )
21
+ if result.returncode != 0:
22
+ raise GitError(f"Failed to get HEAD: {result.stderr.strip()}")
23
+ return result.stdout.strip()
24
+
25
+
26
+ def create_branch(repo: Path, branch_name: str, base_ref: str) -> None:
27
+ """Create and checkout a new branch from base_ref."""
28
+ result = subprocess.run(
29
+ ["git", "checkout", "-b", branch_name, base_ref],
30
+ cwd=repo,
31
+ capture_output=True,
32
+ text=True,
33
+ )
34
+ if result.returncode != 0:
35
+ raise GitError(f"Failed to create branch {branch_name}: {result.stderr.strip()}")
36
+
37
+
38
+ def checkout(repo: Path, ref: str) -> None:
39
+ """Checkout a ref (branch name or commit hash)."""
40
+ result = subprocess.run(
41
+ ["git", "checkout", ref],
42
+ cwd=repo,
43
+ capture_output=True,
44
+ text=True,
45
+ )
46
+ if result.returncode != 0:
47
+ raise GitError(f"Failed to checkout {ref}: {result.stderr.strip()}")
48
+
49
+
50
+ def get_diff_stat(repo: Path, base_ref: str) -> tuple[str, int]:
51
+ """Get diff stat and total lines changed against base_ref.
52
+
53
+ Returns (diff_stat_text, total_lines_changed).
54
+ """
55
+ stat_result = subprocess.run(
56
+ ["git", "diff", "--stat", base_ref],
57
+ cwd=repo,
58
+ capture_output=True,
59
+ text=True,
60
+ )
61
+
62
+ numstat_result = subprocess.run(
63
+ ["git", "diff", "--numstat", base_ref],
64
+ cwd=repo,
65
+ capture_output=True,
66
+ text=True,
67
+ )
68
+
69
+ total_lines = 0
70
+ for line in numstat_result.stdout.strip().splitlines():
71
+ parts = line.split("\t")
72
+ if len(parts) >= 2:
73
+ try:
74
+ added = int(parts[0]) if parts[0] != "-" else 0
75
+ removed = int(parts[1]) if parts[1] != "-" else 0
76
+ total_lines += added + removed
77
+ except ValueError:
78
+ continue
79
+
80
+ return stat_result.stdout.strip(), total_lines
81
+
82
+
83
+ def branch_name_for(task_name: str, agent_name: str) -> str:
84
+ """Generate a branch name for a task/agent combo."""
85
+ return f"coderace/{agent_name}-{task_name}"
86
+
87
+
88
+ def has_uncommitted_changes(repo: Path) -> bool:
89
+ """Check if the repo has uncommitted changes."""
90
+ result = subprocess.run(
91
+ ["git", "status", "--porcelain"],
92
+ cwd=repo,
93
+ capture_output=True,
94
+ text=True,
95
+ )
96
+ return bool(result.stdout.strip())
97
+
98
+
99
+ def stash_changes(repo: Path) -> bool:
100
+ """Stash uncommitted changes. Returns True if something was stashed."""
101
+ if not has_uncommitted_changes(repo):
102
+ return False
103
+ result = subprocess.run(
104
+ ["git", "stash", "push", "-m", "coderace: auto-stash"],
105
+ cwd=repo,
106
+ capture_output=True,
107
+ text=True,
108
+ )
109
+ return result.returncode == 0
110
+
111
+
112
+ def stash_pop(repo: Path) -> None:
113
+ """Pop the most recent stash."""
114
+ subprocess.run(
115
+ ["git", "stash", "pop"],
116
+ cwd=repo,
117
+ capture_output=True,
118
+ text=True,
119
+ )
120
+
121
+
122
+ def add_worktree(repo: Path, worktree_path: Path, branch: str) -> None:
123
+ """Create a git worktree for a branch."""
124
+ result = subprocess.run(
125
+ ["git", "worktree", "add", str(worktree_path), branch],
126
+ cwd=repo,
127
+ capture_output=True,
128
+ text=True,
129
+ )
130
+ if result.returncode != 0:
131
+ raise GitError(f"Failed to create worktree: {result.stderr.strip()}")
132
+
133
+
134
+ def remove_worktree(repo: Path, worktree_path: Path) -> None:
135
+ """Remove a git worktree."""
136
+ subprocess.run(
137
+ ["git", "worktree", "remove", str(worktree_path), "--force"],
138
+ cwd=repo,
139
+ capture_output=True,
140
+ text=True,
141
+ )
142
+
143
+
144
+ def prune_worktrees(repo: Path) -> None:
145
+ """Prune stale worktree metadata."""
146
+ subprocess.run(
147
+ ["git", "worktree", "prune"],
148
+ cwd=repo,
149
+ capture_output=True,
150
+ text=True,
151
+ )
coderace/reporter.py ADDED
@@ -0,0 +1,92 @@
1
+ """Results reporting (terminal table + JSON)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from rich.console import Console
9
+ from rich.table import Table
10
+
11
+ from coderace.types import Score
12
+
13
+
14
+ def print_results(scores: list[Score], console: Console | None = None) -> str:
15
+ """Print a rich table of results. Returns the table as a string."""
16
+ console = console or Console()
17
+
18
+ # Sort by composite score descending
19
+ ranked = sorted(scores, key=lambda s: s.composite, reverse=True)
20
+
21
+ table = Table(title="coderace results", show_lines=True)
22
+ table.add_column("Rank", justify="center", style="bold")
23
+ table.add_column("Agent", style="cyan")
24
+ table.add_column("Score", justify="right", style="bold green")
25
+ table.add_column("Tests", justify="center")
26
+ table.add_column("Exit", justify="center")
27
+ table.add_column("Lint", justify="center")
28
+ table.add_column("Time (s)", justify="right")
29
+ table.add_column("Lines", justify="right")
30
+
31
+ for i, score in enumerate(ranked, 1):
32
+ b = score.breakdown
33
+ table.add_row(
34
+ str(i),
35
+ score.agent,
36
+ f"{score.composite:.1f}",
37
+ _bool_icon(b.tests_pass),
38
+ _bool_icon(b.exit_clean),
39
+ _bool_icon(b.lint_clean),
40
+ f"{b.wall_time:.1f}",
41
+ str(b.lines_changed),
42
+ )
43
+
44
+ console.print(table)
45
+
46
+ # Return as string for testing
47
+ str_console = Console(file=None, force_terminal=False, width=100)
48
+ with str_console.capture() as capture:
49
+ str_console.print(table)
50
+ return capture.get()
51
+
52
+
53
+ def save_results_json(scores: list[Score], output_path: Path) -> None:
54
+ """Save results as JSON."""
55
+ output_path.parent.mkdir(parents=True, exist_ok=True)
56
+
57
+ data = {
58
+ "results": [
59
+ {
60
+ "rank": i,
61
+ "agent": score.agent,
62
+ "composite_score": score.composite,
63
+ "breakdown": {
64
+ "tests_pass": score.breakdown.tests_pass,
65
+ "exit_clean": score.breakdown.exit_clean,
66
+ "lint_clean": score.breakdown.lint_clean,
67
+ "wall_time": round(score.breakdown.wall_time, 2),
68
+ "lines_changed": score.breakdown.lines_changed,
69
+ },
70
+ "tests_output": score.tests_output,
71
+ "lint_output": score.lint_output,
72
+ "diff_stat": score.diff_stat,
73
+ }
74
+ for i, score in enumerate(
75
+ sorted(scores, key=lambda s: s.composite, reverse=True), 1
76
+ )
77
+ ]
78
+ }
79
+
80
+ output_path.write_text(json.dumps(data, indent=2) + "\n")
81
+
82
+
83
+ def load_results_json(path: Path) -> list[dict]:
84
+ """Load results from a JSON file."""
85
+ if not path.exists():
86
+ raise FileNotFoundError(f"No results found at {path}")
87
+ data = json.loads(path.read_text())
88
+ return data.get("results", [])
89
+
90
+
91
+ def _bool_icon(val: bool) -> str:
92
+ return "[green]PASS[/green]" if val else "[red]FAIL[/red]"
coderace/scorer.py ADDED
@@ -0,0 +1,120 @@
1
+ """Scoring engine for agent results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ from coderace.types import AgentResult, Score, ScoreBreakdown
9
+
10
+ # Weights must sum to 1.0
11
+ WEIGHTS = {
12
+ "tests_pass": 0.40,
13
+ "exit_clean": 0.20,
14
+ "lint_clean": 0.15,
15
+ "wall_time": 0.15,
16
+ "lines_changed": 0.10,
17
+ }
18
+
19
+
20
+ def run_command(cmd: str, cwd: Path, timeout: int = 120) -> tuple[int, str]:
21
+ """Run a shell command, return (exit_code, output)."""
22
+ try:
23
+ proc = subprocess.run(
24
+ cmd,
25
+ shell=True,
26
+ cwd=cwd,
27
+ capture_output=True,
28
+ text=True,
29
+ timeout=timeout,
30
+ )
31
+ output = (proc.stdout + "\n" + proc.stderr).strip()
32
+ return proc.returncode, output
33
+ except subprocess.TimeoutExpired:
34
+ return -1, "Command timed out"
35
+ except Exception as e:
36
+ return -1, str(e)
37
+
38
+
39
+ def compute_score(
40
+ result: AgentResult,
41
+ test_command: str,
42
+ lint_command: str | None,
43
+ workdir: Path,
44
+ diff_lines: int,
45
+ all_wall_times: list[float],
46
+ all_diff_lines: list[int],
47
+ ) -> Score:
48
+ """Compute a composite score for an agent result."""
49
+ breakdown = ScoreBreakdown()
50
+
51
+ # Tests
52
+ test_exit, test_output = run_command(test_command, workdir)
53
+ breakdown.tests_pass = test_exit == 0
54
+
55
+ # Exit clean
56
+ breakdown.exit_clean = result.exit_code == 0 and not result.timed_out
57
+
58
+ # Lint
59
+ lint_output = ""
60
+ if lint_command:
61
+ lint_exit, lint_output = run_command(lint_command, workdir)
62
+ breakdown.lint_clean = lint_exit == 0
63
+ else:
64
+ breakdown.lint_clean = True # No lint command = pass
65
+
66
+ # Raw metrics
67
+ breakdown.wall_time = result.wall_time
68
+ breakdown.lines_changed = diff_lines
69
+
70
+ # Compute composite
71
+ composite = 0.0
72
+
73
+ # Boolean metrics
74
+ composite += WEIGHTS["tests_pass"] * (100.0 if breakdown.tests_pass else 0.0)
75
+ composite += WEIGHTS["exit_clean"] * (100.0 if breakdown.exit_clean else 0.0)
76
+ composite += WEIGHTS["lint_clean"] * (100.0 if breakdown.lint_clean else 0.0)
77
+
78
+ # Wall time: normalize (lower is better)
79
+ composite += WEIGHTS["wall_time"] * _normalize_lower_better(
80
+ result.wall_time, all_wall_times
81
+ )
82
+
83
+ # Lines changed: normalize (fewer is better)
84
+ composite += WEIGHTS["lines_changed"] * _normalize_lower_better(
85
+ float(diff_lines), [float(x) for x in all_diff_lines]
86
+ )
87
+
88
+ return Score(
89
+ agent=result.agent,
90
+ composite=round(composite, 1),
91
+ breakdown=breakdown,
92
+ tests_output=test_output,
93
+ lint_output=lint_output,
94
+ )
95
+
96
+
97
+ def _normalize_lower_better(value: float, all_values: list[float]) -> float:
98
+ """Normalize a metric where lower is better. Returns 0-100 score."""
99
+ if not all_values:
100
+ return 50.0
101
+
102
+ valid = [v for v in all_values if v > 0]
103
+ if not valid:
104
+ return 50.0
105
+
106
+ if len(valid) == 1:
107
+ return 100.0 if value == valid[0] else 50.0
108
+
109
+ min_val = min(valid)
110
+ max_val = max(valid)
111
+
112
+ if max_val == min_val:
113
+ return 100.0
114
+
115
+ if value <= 0:
116
+ return 50.0
117
+
118
+ # Invert: best (min) gets 100, worst (max) gets 0
119
+ normalized = 100.0 * (1.0 - (value - min_val) / (max_val - min_val))
120
+ return max(0.0, min(100.0, normalized))
coderace/task.py ADDED
@@ -0,0 +1,70 @@
1
+ """Task definition loading and validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import yaml
8
+
9
+ from coderace.types import Task
10
+
11
+
12
+ def load_task(path: str | Path) -> Task:
13
+ """Load a task from a YAML file."""
14
+ path = Path(path)
15
+ if not path.exists():
16
+ raise FileNotFoundError(f"Task file not found: {path}")
17
+
18
+ with open(path) as f:
19
+ data = yaml.safe_load(f)
20
+
21
+ if not isinstance(data, dict):
22
+ raise ValueError(f"Task file must contain a YAML mapping, got {type(data).__name__}")
23
+
24
+ required = {"name", "description", "test_command", "agents"}
25
+ missing = required - set(data.keys())
26
+ if missing:
27
+ raise ValueError(f"Missing required fields: {', '.join(sorted(missing))}")
28
+
29
+ repo_str = data.get("repo", ".")
30
+ repo = Path(repo_str)
31
+ if not repo.is_absolute():
32
+ repo = path.parent / repo
33
+
34
+ task = Task(
35
+ name=data["name"],
36
+ description=data["description"],
37
+ repo=repo.resolve(),
38
+ test_command=data["test_command"],
39
+ agents=data["agents"],
40
+ lint_command=data.get("lint_command"),
41
+ timeout=data.get("timeout", 300),
42
+ )
43
+
44
+ errors = task.validate()
45
+ if errors:
46
+ raise ValueError(f"Invalid task: {'; '.join(errors)}")
47
+
48
+ return task
49
+
50
+
51
+ def create_template(name: str, output_dir: Path | None = None) -> Path:
52
+ """Create a task YAML template."""
53
+ output_dir = output_dir or Path.cwd()
54
+ path = output_dir / f"{name}.yaml"
55
+
56
+ template = f"""name: {name}
57
+ description: |
58
+ Describe the task here. What should the agent fix or build?
59
+ Be specific about which files to change and what the expected behavior is.
60
+ repo: .
61
+ test_command: pytest tests/ -x
62
+ lint_command: ruff check .
63
+ timeout: 300
64
+ agents:
65
+ - claude
66
+ - codex
67
+ - aider
68
+ """
69
+ path.write_text(template)
70
+ return path
coderace/types.py ADDED
@@ -0,0 +1,73 @@
1
+ """Shared types for coderace."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+
8
+
9
+ @dataclass
10
+ class Task:
11
+ """A task definition loaded from YAML."""
12
+
13
+ name: str
14
+ description: str
15
+ repo: Path
16
+ test_command: str
17
+ agents: list[str]
18
+ lint_command: str | None = None
19
+ timeout: int = 300
20
+
21
+ def validate(self) -> list[str]:
22
+ """Return list of validation errors, empty if valid."""
23
+ errors: list[str] = []
24
+ if not self.name:
25
+ errors.append("Task name is required")
26
+ if not self.description:
27
+ errors.append("Task description is required")
28
+ if not self.test_command:
29
+ errors.append("test_command is required")
30
+ if not self.agents:
31
+ errors.append("At least one agent is required")
32
+ known = {"claude", "codex", "aider", "gemini"}
33
+ for agent in self.agents:
34
+ if agent not in known:
35
+ errors.append(f"Unknown agent: {agent!r} (known: {', '.join(sorted(known))})")
36
+ if self.timeout < 1:
37
+ errors.append("timeout must be positive")
38
+ return errors
39
+
40
+
41
+ @dataclass
42
+ class AgentResult:
43
+ """Raw result from running an agent on a task."""
44
+
45
+ agent: str
46
+ exit_code: int
47
+ stdout: str
48
+ stderr: str
49
+ wall_time: float
50
+ timed_out: bool = False
51
+
52
+
53
+ @dataclass
54
+ class ScoreBreakdown:
55
+ """Per-metric scores before weighting."""
56
+
57
+ tests_pass: bool = False
58
+ exit_clean: bool = False
59
+ lint_clean: bool = False
60
+ wall_time: float = 0.0
61
+ lines_changed: int = 0
62
+
63
+
64
+ @dataclass
65
+ class Score:
66
+ """Final computed score for an agent run."""
67
+
68
+ agent: str
69
+ composite: float
70
+ breakdown: ScoreBreakdown = field(default_factory=ScoreBreakdown)
71
+ tests_output: str = ""
72
+ lint_output: str = ""
73
+ diff_stat: str = ""
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: coderace
3
+ Version: 0.1.0
4
+ Summary: Race coding agents against each other on real tasks
5
+ Project-URL: Homepage, https://github.com/mikiships/coderace
6
+ Project-URL: Repository, https://github.com/mikiships/coderace
7
+ Author: mikiships
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: ai,aider,benchmark,claude,codex,coding-agents
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Testing
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: pyyaml>=6.0
23
+ Requires-Dist: rich>=13.0
24
+ Requires-Dist: typer>=0.9.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest-mock>=3.0; extra == 'dev'
27
+ Requires-Dist: pytest>=7.0; extra == 'dev'
28
+ Requires-Dist: ruff>=0.4.0; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # coderace
32
+
33
+ Race coding agents against each other on real tasks in your repo.
34
+
35
+ Define a task. Run it against Claude Code, Codex, and Aider. Get a scored comparison table.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install coderace
41
+ ```
42
+
43
+ ## Quick Start
44
+
45
+ ```bash
46
+ # Create a task template
47
+ coderace init fix-auth-bug
48
+
49
+ # Edit the task file (describe the bug, set test command)
50
+ # Then race the agents:
51
+ coderace run fix-auth-bug.yaml
52
+
53
+ # Or race them in parallel (uses git worktrees):
54
+ coderace run fix-auth-bug.yaml --parallel
55
+
56
+ # View results from the last run
57
+ coderace results fix-auth-bug.yaml
58
+ ```
59
+
60
+ ## Task Format
61
+
62
+ ```yaml
63
+ name: fix-auth-bug
64
+ description: |
65
+ The login endpoint returns 500 when email contains a plus sign.
66
+ Fix the email validation in auth/validators.py.
67
+ repo: .
68
+ test_command: pytest tests/test_auth.py -x
69
+ lint_command: ruff check .
70
+ timeout: 300
71
+ agents:
72
+ - claude
73
+ - codex
74
+ - aider
75
+ ```
76
+
77
+ ## What It Does
78
+
79
+ For each agent in the task:
80
+
81
+ 1. Creates a fresh git branch (`coderace/<agent>-<task>`)
82
+ 2. Invokes the agent CLI with the task description
83
+ 3. Runs your test command
84
+ 4. Runs your lint command (optional)
85
+ 5. Computes a composite score
86
+
87
+ ## Scoring
88
+
89
+ | Metric | Weight | Description |
90
+ |--------|--------|-------------|
91
+ | Tests pass | 40% | Did the test command exit 0? |
92
+ | Exit clean | 20% | Did the agent itself exit 0 without timeout? |
93
+ | Lint clean | 15% | Did the lint command exit 0? |
94
+ | Wall time | 15% | Faster is better (normalized across agents) |
95
+ | Lines changed | 10% | Fewer is better (normalized across agents) |
96
+
97
+ ## Output
98
+
99
+ Terminal table with Rich formatting:
100
+
101
+ ```
102
+ ┌──────┬────────┬───────┬───────┬──────┬──────┬──────────┬───────┐
103
+ │ Rank │ Agent │ Score │ Tests │ Exit │ Lint │ Time (s) │ Lines │
104
+ ├──────┼────────┼───────┼───────┼──────┼──────┼──────────┼───────┤
105
+ │ 1 │ claude │ 85.0 │ PASS │ PASS │ PASS │ 10.5 │ 42 │
106
+ │ 2 │ codex │ 70.0 │ PASS │ PASS │ FAIL │ 15.2 │ 98 │
107
+ │ 3 │ aider │ 55.0 │ FAIL │ PASS │ PASS │ 8.1 │ 31 │
108
+ └──────┴────────┴───────┴───────┴──────┴──────┴──────────┴───────┘
109
+ ```
110
+
111
+ Results also saved as JSON in `.coderace/<task>-results.json`.
112
+
113
+ ## Supported Agents
114
+
115
+ | Agent | CLI | Command |
116
+ |-------|-----|---------|
117
+ | Claude Code | `claude` | `claude --print --output-format json -p "<task>"` |
118
+ | Codex | `codex` | `codex --quiet --full-auto -p "<task>"` |
119
+ | Aider | `aider` | `aider --message "<task>" --yes --no-auto-commits` |
120
+ | Gemini CLI | `gemini` | `gemini --non-interactive -p "<task>"` |
121
+
122
+ Each agent must be installed and authenticated separately.
123
+
124
+ ## Parallel Mode
125
+
126
+ Use `--parallel` (or `-p`) to run all agents simultaneously using git worktrees. Each agent gets its own isolated working directory, so they don't interfere with each other.
127
+
128
+ ```bash
129
+ coderace run task.yaml --parallel
130
+ ```
131
+
132
+ Sequential mode (default) runs agents one at a time on the same repo.
133
+
134
+ ## Requirements
135
+
136
+ - Python 3.10+
137
+ - Git
138
+ - At least one coding agent CLI installed
139
+
140
+ ## License
141
+
142
+ MIT
@@ -0,0 +1,18 @@
1
+ coderace/__init__.py,sha256=wSg2jh_3Y65Nfh0k8INcZ8UXs4_tnd5FkzNFUQfld-c,93
2
+ coderace/cli.py,sha256=EhxDadkkewIEPvtu3wQpVh7RP_LR6qI6G4KpPr-JHQ8,9933
3
+ coderace/git_ops.py,sha256=UmCmMdEiI8vvpUQwiJLk9Vy5KRNSKlI3w1FusUVdSdY,4155
4
+ coderace/reporter.py,sha256=FCgeHv3w0_kdqs_75j4iVsMRLbKDlXVICzarf33zao4,3021
5
+ coderace/scorer.py,sha256=UpcpkKpuvcDKy1fOuBZtT9Y9si3-lXGFseUfS1cqP0Y,3284
6
+ coderace/task.py,sha256=CXT0uYT5H_31mSSRl76jF3xpvIWQr23MYqVJ4L3vTPs,1833
7
+ coderace/types.py,sha256=XHiL2mjTv1rQ4PfnIqAlmA-3jwiixVF-5y_5JrpSMPI,1846
8
+ coderace/adapters/__init__.py,sha256=bgXcH-bsJuWALSfx4DjFOy1aHIJX589gn4b2hv4OvCI,573
9
+ coderace/adapters/aider.py,sha256=HQMaZoQO9ruRGKeT4YixATVfDTU28-HMgGBQSPDMC3o,429
10
+ coderace/adapters/base.py,sha256=aFE_FG-cVN5EKmu7p6Mbmz5LtFhMF-IpqiowyHVgSDA,1757
11
+ coderace/adapters/claude.py,sha256=Cb3fgEEyPbNMlUb9QDBcdKEUAT-E-0HrdQdDtM0gf6Y,444
12
+ coderace/adapters/codex.py,sha256=K6EHDlTDyFFozpU52sWjxq9oQlB2l8gEbK4G-QK4SHU,416
13
+ coderace/adapters/gemini.py,sha256=LUG9Pgf0jM3GrlDpra0VLDNFrzJzdVmlhz5-C1rFhgQ,404
14
+ coderace-0.1.0.dist-info/METADATA,sha256=-SDIOSsf9lKjhfjtWH2pUEBDFVhVD9X-ZqB4KMRbhzM,4538
15
+ coderace-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
16
+ coderace-0.1.0.dist-info/entry_points.txt,sha256=2Mg40OC1qw_gQDf51mcIyW5nL323ETJcLYJSsztcUdY,46
17
+ coderace-0.1.0.dist-info/licenses/LICENSE,sha256=_xg5HZ1WlLJEQpwpHZeQrhtyhgKC7ke4BL_qH6U3Jzo,1066
18
+ coderace-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ coderace = coderace.cli:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mikiships
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.