-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadversarial_coding.py
More file actions
302 lines (238 loc) Β· 9.1 KB
/
adversarial_coding.py
File metadata and controls
302 lines (238 loc) Β· 9.1 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
"""
Adversarial Coding - Apply adversarial protocol to actual code generation with validation gates
"""
from coding_agent_wrapper import CodingAgentWrapper, validate_component, ValidationResult
from typing import Optional
import json
import time
def adversarial_build(
task: str,
workdir: str,
max_rounds: int = 3,
agent_type: str = "codex",
verbose: bool = False
) -> dict:
"""
Build a component using adversarial protocol with validation gates.
Process:
1. Proposer builds the component
2. Validate (run tests, health checks)
3. If validation fails, Attacker reviews and finds issues
4. Proposer fixes issues
5. Repeat until validation passes or max_rounds reached
Args:
task: Description of what to build
workdir: Working directory for the build
max_rounds: Maximum attack/defend rounds
agent_type: Type of coding agent (claude, codex)
verbose: Print detailed output
Returns:
{
"success": bool,
"rounds": int,
"validation": ValidationResult.to_dict(),
"workdir": str,
"conversation": [...],
"final_critique": str
}
"""
print(f"\n{'='*70}")
print(f"ποΈ ADVERSARIAL BUILD")
print(f"{'='*70}")
print(f"Task: {task}")
print(f"Workdir: {workdir}")
print(f"Max rounds: {max_rounds}")
print(f"{'='*70}\n")
# Create proposer and attacker agents
proposer = CodingAgentWrapper(workdir=workdir, agent_type=agent_type)
conversation = []
validation_result = None
for round_num in range(1, max_rounds + 1):
print(f"\n{'='*70}")
print(f"π ROUND {round_num}/{max_rounds}")
print(f"{'='*70}\n")
if round_num == 1:
# Initial build
proposer_prompt = f"""Build this component:
{task}
REQUIREMENTS:
1. Create all necessary code files
2. Write comprehensive tests (unit + edge cases)
3. Create a health check script that validates the component works
4. Add a README with setup instructions
Make it production-ready for 1M users scale."""
else:
# Fix issues from previous round
proposer_prompt = f"""Previous attempt had issues:
{attacker_critique}
Fix ALL the issues mentioned. Update code, add missing tests, handle edge cases."""
print("π· PROPOSER: Building...")
if verbose:
print(f"\nPrompt: {proposer_prompt}\n")
start = time.time()
proposer_response = proposer.run(proposer_prompt, timeout=300)
elapsed = time.time() - start
print(f"β Proposer completed in {elapsed:.1f}s")
if verbose:
print(f"\nProposer output:\n{proposer_response[:500]}...\n")
conversation.append({
"round": round_num,
"role": "proposer",
"prompt": proposer_prompt,
"response": proposer_response,
"elapsed": elapsed
})
# VALIDATION GATE
print("\nπ VALIDATING...")
validation_result = validate_component(proposer)
print(validation_result.summary())
if validation_result.is_complete():
print(f"\nβ
COMPONENT COMPLETE after {round_num} round(s)")
break
# Validation failed - get attacker critique
print("\nβοΈ ATTACKER: Reviewing failures...")
# Build context for attacker
context = proposer.get_context()
attacker_prompt = f"""Review this code that FAILED validation:
{context}
VALIDATION RESULTS:
{validation_result.summary()}
TEST OUTPUT:
{validation_result.test_output[:500] if validation_result.test_output else 'No tests run'}
Your job: Find ALL the issues. Be thorough and specific.
Focus on:
1. Why tests are failing (or missing)
2. Edge cases not handled
3. Security vulnerabilities
4. Performance issues for 1M users scale
5. Missing error handling
List at least 3-5 concrete issues with file names and line references."""
if verbose:
print(f"\nAttacker prompt: {attacker_prompt[:300]}...\n")
# Use a fresh agent for attacker (different perspective)
attacker = CodingAgentWrapper(workdir=workdir, agent_type=agent_type)
start = time.time()
attacker_critique = attacker.run(attacker_prompt, timeout=180)
elapsed = time.time() - start
print(f"β Attacker completed in {elapsed:.1f}s")
if verbose:
print(f"\nAttacker critique:\n{attacker_critique[:500]}...\n")
conversation.append({
"round": round_num,
"role": "attacker",
"prompt": attacker_prompt,
"response": attacker_critique,
"elapsed": elapsed,
"validation": validation_result.to_dict()
})
# Continue to next round with fixes
print(f"\nβ οΈ Issues found. Moving to round {round_num + 1}...")
# Final result
success = validation_result is not None and validation_result.is_complete()
result = {
"success": success,
"rounds": round_num,
"validation": validation_result.to_dict() if validation_result else {},
"workdir": str(proposer.workdir),
"conversation": conversation,
"files_created": proposer.list_files(),
"final_critique": attacker_critique if not success else "All validation checks passed"
}
# Save state
state_file = f"{workdir}/adversarial_build_state.json"
with open(state_file, 'w') as f:
json.dump(result, f, indent=2)
print(f"\nπ Build state saved to: {state_file}")
return result
def build_with_baseline(
task: str,
workdir: str,
agent_type: str = "codex",
verbose: bool = False
) -> dict:
"""
Build component with single agent (baseline for comparison).
Returns same format as adversarial_build for comparison.
"""
print(f"\n{'='*70}")
print(f"π¦ BASELINE BUILD (Single Agent)")
print(f"{'='*70}")
print(f"Task: {task}")
print(f"Workdir: {workdir}")
print(f"{'='*70}\n")
agent = CodingAgentWrapper(workdir=workdir, agent_type=agent_type)
prompt = f"""Build this component:
{task}
REQUIREMENTS:
1. Create all necessary code files
2. Write comprehensive tests (unit + edge cases)
3. Create a health check script that validates the component works
4. Add a README with setup instructions
Make it production-ready for 1M users scale."""
print("π· AGENT: Building...")
if verbose:
print(f"\nPrompt: {prompt}\n")
start = time.time()
response = agent.run(prompt, timeout=300)
elapsed = time.time() - start
print(f"β Agent completed in {elapsed:.1f}s")
if verbose:
print(f"\nAgent output:\n{response[:500]}...\n")
# Validate
print("\nπ VALIDATING...")
validation_result = validate_component(agent)
print(validation_result.summary())
result = {
"success": validation_result.is_complete(),
"rounds": 1,
"validation": validation_result.to_dict(),
"workdir": str(agent.workdir),
"conversation": [{
"round": 1,
"role": "agent",
"prompt": prompt,
"response": response,
"elapsed": elapsed
}],
"files_created": agent.list_files()
}
# Save state
state_file = f"{workdir}/baseline_build_state.json"
with open(state_file, 'w') as f:
json.dump(result, f, indent=2)
print(f"\nπ Build state saved to: {state_file}")
return result
if __name__ == "__main__":
import sys
import argparse
parser = argparse.ArgumentParser(description="Build code with adversarial validation")
parser.add_argument("task", help="What to build")
parser.add_argument("--workdir", required=True, help="Working directory")
parser.add_argument("--rounds", type=int, default=3, help="Max validation rounds")
parser.add_argument("--baseline", action="store_true", help="Run baseline (single agent)")
parser.add_argument("--agent", default="codex", choices=["claude", "codex"],
help="Agent type (default: codex)")
parser.add_argument("--verbose", "-v", action="store_true", help="Verbose output")
args = parser.parse_args()
if args.baseline:
result = build_with_baseline(
args.task,
args.workdir,
agent_type=args.agent,
verbose=args.verbose
)
else:
result = adversarial_build(
args.task,
args.workdir,
max_rounds=args.rounds,
agent_type=args.agent,
verbose=args.verbose
)
print(f"\n{'='*70}")
print(f"π― FINAL RESULT: {'β
SUCCESS' if result['success'] else 'β INCOMPLETE'}")
print(f"{'='*70}")
print(f"Rounds: {result['rounds']}")
print(f"Files created: {len(result['files_created'])}")
print(f"Workdir: {result['workdir']}")
sys.exit(0 if result['success'] else 1)