-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoding_agent_wrapper.py
More file actions
310 lines (260 loc) · 10.8 KB
/
coding_agent_wrapper.py
File metadata and controls
310 lines (260 loc) · 10.8 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
"""
Coding Agent Wrapper - Integrates Claude Code with adversarial validation
"""
import os
import subprocess
import tempfile
from pathlib import Path
from typing import Optional, Dict, Any
import json
class CodingAgentWrapper:
"""Wraps a coding agent (Claude Code) for use in adversarial protocol"""
def __init__(self, workdir: Optional[str] = None, agent_type: str = "claude"):
"""
Args:
workdir: Working directory for the agent. If None, creates temp dir.
agent_type: Type of coding agent (claude, codex, etc.)
"""
if workdir:
self.workdir = Path(workdir)
self.workdir.mkdir(parents=True, exist_ok=True)
else:
self.workdir = Path(tempfile.mkdtemp(prefix="adversarial_coding_"))
self.agent_type = agent_type
self.conversation_log = []
# Initialize git repo if needed (Codex requires it)
if agent_type == "codex" and not (self.workdir / ".git").exists():
subprocess.run(["git", "init"], cwd=self.workdir, capture_output=True)
subprocess.run(["git", "config", "user.name", "Adversarial Builder"],
cwd=self.workdir, capture_output=True)
subprocess.run(["git", "config", "user.email", "builder@adversarial.ai"],
cwd=self.workdir, capture_output=True)
def run(self, prompt: str, timeout: int = 300) -> str:
"""
Run coding agent with prompt and return response.
Args:
prompt: The task/question for the agent
timeout: Maximum execution time in seconds
Returns:
Agent's response text
"""
self.conversation_log.append({"role": "user", "content": prompt})
# Build command based on agent type
if self.agent_type == "claude":
cmd = ["claude", prompt]
elif self.agent_type == "codex":
cmd = ["codex", "exec", prompt]
else:
raise ValueError(f"Unknown agent type: {self.agent_type}")
try:
result = subprocess.run(
cmd,
cwd=self.workdir,
capture_output=True,
text=True,
timeout=timeout
)
output = result.stdout
if result.stderr:
output += f"\n[stderr]: {result.stderr}"
self.conversation_log.append({"role": "assistant", "content": output})
return output
except subprocess.TimeoutExpired:
error_msg = f"Agent timed out after {timeout}s"
self.conversation_log.append({"role": "error", "content": error_msg})
return error_msg
except Exception as e:
error_msg = f"Agent execution failed: {str(e)}"
self.conversation_log.append({"role": "error", "content": error_msg})
return error_msg
def list_files(self, pattern: str = "*") -> list[str]:
"""List files in working directory matching pattern"""
return [str(p.relative_to(self.workdir))
for p in self.workdir.rglob(pattern)
if p.is_file() and ".git" not in str(p)]
def read_file(self, filepath: str) -> str:
"""Read file content"""
full_path = self.workdir / filepath
if not full_path.exists():
return f"[File not found: {filepath}]"
try:
return full_path.read_text()
except Exception as e:
return f"[Error reading {filepath}: {str(e)}]"
def write_file(self, filepath: str, content: str):
"""Write content to file"""
full_path = self.workdir / filepath
full_path.parent.mkdir(parents=True, exist_ok=True)
full_path.write_text(content)
def run_command(self, command: str, timeout: int = 60) -> Dict[str, Any]:
"""
Run a shell command in the working directory.
Used for running tests, health checks, etc.
Returns:
{"success": bool, "stdout": str, "stderr": str, "exit_code": int}
"""
try:
result = subprocess.run(
command,
cwd=self.workdir,
shell=True,
capture_output=True,
text=True,
timeout=timeout
)
return {
"success": result.returncode == 0,
"stdout": result.stdout,
"stderr": result.stderr,
"exit_code": result.returncode
}
except subprocess.TimeoutExpired:
return {
"success": False,
"stdout": "",
"stderr": f"Command timed out after {timeout}s",
"exit_code": -1
}
except Exception as e:
return {
"success": False,
"stdout": "",
"stderr": str(e),
"exit_code": -1
}
def get_context(self) -> str:
"""
Get current state context for the attacker.
Returns file tree and key file contents.
"""
files = self.list_files()
context = f"Working directory: {self.workdir}\n\n"
context += f"Files created ({len(files)}):\n"
for f in files[:20]: # Limit to first 20 files
context += f" - {f}\n"
if len(files) > 20:
context += f" ... and {len(files) - 20} more files\n"
# Include key files content
key_patterns = ["*.md", "package.json", "*.test.*", "test/*", "tests/*"]
key_files = []
for pattern in key_patterns:
key_files.extend(self.list_files(pattern))
if key_files:
context += "\n=== Key Files ===\n"
for f in key_files[:5]: # Limit to 5 key files
context += f"\n--- {f} ---\n"
context += self.read_file(f)[:500] # First 500 chars
if len(self.read_file(f)) > 500:
context += "\n... (truncated)"
context += "\n"
return context
def save_state(self, filepath: str = "agent_state.json"):
"""Save agent state for debugging/analysis"""
state = {
"workdir": str(self.workdir),
"agent_type": self.agent_type,
"files": self.list_files(),
"conversation_log": self.conversation_log
}
with open(filepath, 'w') as f:
json.dump(state, f, indent=2)
def cleanup(self):
"""Clean up temporary directory if it was auto-created"""
if self.workdir.exists() and "adversarial_coding_" in str(self.workdir):
import shutil
shutil.rmtree(self.workdir)
class ValidationResult:
"""Result of validation checks"""
def __init__(self):
self.tests_exist = False
self.tests_pass = False
self.health_check_exists = False
self.health_check_pass = False
self.files_created = []
self.issues = []
self.test_output = ""
self.health_output = ""
def is_complete(self) -> bool:
"""Check if component meets completion criteria"""
return (
self.tests_exist and
self.tests_pass and
len(self.files_created) > 0 and
len(self.issues) == 0
)
def to_dict(self) -> dict:
return {
"tests_exist": self.tests_exist,
"tests_pass": self.tests_pass,
"health_check_exists": self.health_check_exists,
"health_check_pass": self.health_check_pass,
"files_created": self.files_created,
"issues": self.issues,
"is_complete": self.is_complete()
}
def summary(self) -> str:
"""Human-readable summary"""
status = "✅ COMPLETE" if self.is_complete() else "❌ INCOMPLETE"
summary = f"{status}\n\n"
summary += f"Files created: {len(self.files_created)}\n"
summary += f"Tests exist: {'✅' if self.tests_exist else '❌'}\n"
summary += f"Tests pass: {'✅' if self.tests_pass else '❌'}\n"
if self.health_check_exists:
summary += f"Health check: {'✅' if self.health_check_pass else '❌'}\n"
if self.issues:
summary += f"\n⚠️ Issues found: {len(self.issues)}\n"
for i, issue in enumerate(self.issues[:5], 1):
summary += f" {i}. {issue}\n"
if len(self.issues) > 5:
summary += f" ... and {len(self.issues) - 5} more\n"
return summary
def validate_component(agent: CodingAgentWrapper) -> ValidationResult:
"""
Validate that a component meets completion criteria.
Checks:
- Files were created
- Tests exist
- Tests pass
- Health check exists and passes (if applicable)
"""
result = ValidationResult()
# Check files created
result.files_created = agent.list_files()
# Check for test files
test_files = agent.list_files("*.test.*") + agent.list_files("test*/*")
result.tests_exist = len(test_files) > 0
# Run tests if they exist
if result.tests_exist:
# Try common test commands
for test_cmd in ["npm test", "yarn test", "pytest", "python -m pytest", "go test"]:
test_result = agent.run_command(test_cmd, timeout=120)
if test_result["exit_code"] != 127: # Command exists
result.test_output = test_result["stdout"] + test_result["stderr"]
result.tests_pass = test_result["success"]
break
# Check for health check script
health_check_files = [f for f in result.files_created
if "health" in f.lower() and f.endswith((".sh", ".js", ".py"))]
result.health_check_exists = len(health_check_files) > 0
if result.health_check_exists:
health_file = health_check_files[0]
if health_file.endswith(".sh"):
cmd = f"bash {health_file}"
elif health_file.endswith(".py"):
cmd = f"python {health_file}"
elif health_file.endswith(".js"):
cmd = f"node {health_file}"
else:
cmd = None
if cmd:
health_result = agent.run_command(cmd, timeout=30)
result.health_output = health_result["stdout"] + health_result["stderr"]
result.health_check_pass = health_result["success"]
# Identify issues
if not result.tests_exist:
result.issues.append("No tests found")
elif not result.tests_pass:
result.issues.append(f"Tests failed: {result.test_output[:200]}")
if len(result.files_created) == 0:
result.issues.append("No files created")
return result