-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtournament.py
More file actions
1549 lines (1261 loc) · 55.4 KB
/
tournament.py
File metadata and controls
1549 lines (1261 loc) · 55.4 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Tournament/Parallel Execution System for Ansib-eL (AI-Native Version Control)
This module implements the Tournament Logic where multiple agents attempt the same
task and the best solution is selected through parallel execution and evaluation.
Key Components:
- TournamentOrchestrator: Main orchestrator for spawning and managing agents
- Parallel execution with asyncio for concurrent agent runs
- Diff presentation for human review
- Pluggable evaluation strategies
- Solution archival for training data
"""
import asyncio
import uuid
import time
import difflib
import json
from datetime import datetime
from enum import Enum, auto
from typing import Dict, List, Optional, Callable, Any, Protocol, Set, Tuple
from dataclasses import dataclass, field, asdict
from abc import ABC, abstractmethod
from concurrent.futures import TimeoutError as FutureTimeoutError
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# =============================================================================
# Enums and Constants
# =============================================================================
class SelectionMode(Enum):
"""Mode for selecting the winning solution from a tournament."""
HUMAN_CHOICE = auto() # Human reviews and selects winner
AUTO_BEST = auto() # Automatically select highest scoring solution
THRESHOLD = auto() # Select first solution meeting threshold score
class SolutionStatus(Enum):
"""Status of a solution in the tournament."""
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
TIMEOUT = "timeout"
CANCELLED = "cancelled"
class TournamentStatus(Enum):
"""Status of a tournament."""
CREATED = "created"
RUNNING = "running"
COMPLETED = "completed"
CANCELLED = "cancelled"
ERROR = "error"
# =============================================================================
# Data Classes
# =============================================================================
@dataclass
class AgentConfig:
"""Configuration for spawning an agent in a tournament.
Attributes:
agent_id: Unique identifier for this agent configuration
agent_type: Type/class of agent to spawn (e.g., "gpt-5.2", "claude-opus-4.5", "custom")
model_config: Model-specific configuration (temperature, max_tokens, etc.)
system_prompt: Optional system prompt override
timeout_seconds: Maximum time allowed for this agent to complete
priority: Execution priority (higher = executed earlier)
metadata: Additional agent-specific metadata
"""
agent_id: str
agent_type: str
model_config: Dict[str, Any] = field(default_factory=dict)
system_prompt: Optional[str] = None
timeout_seconds: float = 300.0
priority: int = 0
metadata: Dict[str, Any] = field(default_factory=dict)
def __post_init__(self):
if not self.agent_id:
self.agent_id = str(uuid.uuid4())
@dataclass
class Task:
"""Represents a task to be solved by agents in a tournament.
Attributes:
task_id: Unique identifier for this task
description: Human-readable task description
context_files: List of file paths providing context
requirements: Specific requirements or constraints
test_commands: Commands to validate the solution
expected_output: Expected output patterns for validation
metadata: Additional task metadata
"""
task_id: str
description: str
context_files: List[str] = field(default_factory=list)
requirements: List[str] = field(default_factory=list)
test_commands: List[str] = field(default_factory=list)
expected_output: Optional[str] = None
metadata: Dict[str, Any] = field(default_factory=dict)
def __post_init__(self):
if not self.task_id:
self.task_id = str(uuid.uuid4())
@dataclass
class Solution:
"""Represents a solution produced by an agent.
Attributes:
solution_id: Unique identifier for this solution
agent_id: ID of the agent that produced this solution
task_id: ID of the task this solution addresses
files_changed: Dictionary mapping file paths to their new content
diff: Unified diff representation of changes
explanation: Agent's explanation of the solution
metrics: Solution quality metrics
status: Current status of the solution
created_at: Timestamp when solution was created
completed_at: Timestamp when solution was completed
execution_time_ms: Time taken to generate solution
test_results: Results from running test commands
"""
solution_id: str
agent_id: str
task_id: str
files_changed: Dict[str, str] = field(default_factory=dict)
diff: str = ""
explanation: str = ""
metrics: Dict[str, float] = field(default_factory=dict)
status: SolutionStatus = SolutionStatus.PENDING
created_at: datetime = field(default_factory=datetime.utcnow)
completed_at: Optional[datetime] = None
execution_time_ms: float = 0.0
test_results: Dict[str, Any] = field(default_factory=dict)
def __post_init__(self):
if not self.solution_id:
self.solution_id = str(uuid.uuid4())
def to_dict(self) -> Dict[str, Any]:
"""Convert solution to dictionary for serialization."""
return {
"solution_id": self.solution_id,
"agent_id": self.agent_id,
"task_id": self.task_id,
"files_changed": self.files_changed,
"diff": self.diff,
"explanation": self.explanation,
"metrics": self.metrics,
"status": self.status.value,
"created_at": self.created_at.isoformat(),
"completed_at": self.completed_at.isoformat() if self.completed_at else None,
"execution_time_ms": self.execution_time_ms,
"test_results": self.test_results,
}
@dataclass
class Tournament:
"""Represents a tournament instance with multiple competing agents.
Attributes:
tournament_id: Unique identifier for this tournament
task: The task being solved
agent_configs: List of agent configurations
selection_mode: How the winner will be selected
solutions: Map of agent_id to their solution
status: Current tournament status
created_at: Timestamp when tournament was created
started_at: Timestamp when tournament started
completed_at: Timestamp when tournament completed
winner_id: ID of the winning solution (if selected)
evaluation_scores: Scores from evaluation strategies
"""
tournament_id: str
task: Task
agent_configs: List[AgentConfig]
selection_mode: SelectionMode
solutions: Dict[str, Solution] = field(default_factory=dict)
status: TournamentStatus = TournamentStatus.CREATED
created_at: datetime = field(default_factory=datetime.utcnow)
started_at: Optional[datetime] = None
completed_at: Optional[datetime] = None
winner_id: Optional[str] = None
evaluation_scores: Dict[str, Dict[str, float]] = field(default_factory=dict)
def __post_init__(self):
if not self.tournament_id:
self.tournament_id = str(uuid.uuid4())
def get_completed_solutions(self) -> List[Solution]:
"""Get all successfully completed solutions."""
return [
s for s in self.solutions.values()
if s.status == SolutionStatus.COMPLETED
]
def get_failed_solutions(self) -> List[Solution]:
"""Get all failed/timed out solutions."""
return [
s for s in self.solutions.values()
if s.status in (SolutionStatus.FAILED, SolutionStatus.TIMEOUT)
]
def get_leaderboard(self) -> List[Tuple[str, float]]:
"""Get solutions ranked by their composite score."""
scored_solutions = []
for agent_id, scores in self.evaluation_scores.items():
if scores:
composite = sum(scores.values()) / len(scores)
scored_solutions.append((agent_id, composite))
return sorted(scored_solutions, key=lambda x: x[1], reverse=True)
@dataclass
class TournamentResult:
"""Results from running a tournament.
Attributes:
tournament_id: ID of the tournament
solutions: All solutions produced
winner: The winning solution (if selected)
execution_summary: Summary of execution statistics
evaluation_summary: Summary of evaluation results
"""
tournament_id: str
solutions: List[Solution]
winner: Optional[Solution] = None
execution_summary: Dict[str, Any] = field(default_factory=dict)
evaluation_summary: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert result to dictionary for serialization."""
return {
"tournament_id": self.tournament_id,
"solutions": [s.to_dict() for s in self.solutions],
"winner": self.winner.to_dict() if self.winner else None,
"execution_summary": self.execution_summary,
"evaluation_summary": self.evaluation_summary,
}
@dataclass
class ReviewPresentation:
"""Formatted presentation of solutions for human review.
Attributes:
tournament_id: ID of the tournament
task_description: Description of the task
solution_comparisons: Side-by-side comparisons
diffs: Formatted diffs for each solution
agent_metadata: Metadata about each agent
recommendations: Auto-generated recommendations
"""
tournament_id: str
task_description: str
solution_comparisons: List[Dict[str, Any]]
diffs: Dict[str, str]
agent_metadata: Dict[str, Dict[str, Any]]
recommendations: List[str] = field(default_factory=list)
def to_markdown(self) -> str:
"""Generate markdown representation for review."""
lines = [
f"# Tournament Review: {self.tournament_id}",
"",
f"## Task: {self.task_description}",
"",
"## Solutions Overview",
"",
]
for comp in self.solution_comparisons:
lines.extend([
f"### Solution: {comp.get('agent_id', 'Unknown')}",
f"- **Status**: {comp.get('status', 'Unknown')}",
f"- **Score**: {comp.get('score', 'N/A')}",
f"- **Execution Time**: {comp.get('execution_time', 'N/A')}ms",
"",
])
if self.recommendations:
lines.extend([
"## Recommendations",
"",
])
for rec in self.recommendations:
lines.append(f"- {rec}")
lines.append("")
lines.extend([
"## Detailed Diffs",
"",
])
for agent_id, diff in self.diffs.items():
lines.extend([
f"### {agent_id}",
"```diff",
diff,
"```",
"",
])
return "\n".join(lines)
@dataclass
class ArchivedSolution:
"""Archived solution with metadata for training.
Attributes:
archive_id: Unique identifier for this archive entry
solution: The solution being archived
tournament_id: ID of the tournament
rejection_reason: Why this solution was not selected
winner_comparison: Comparison with winning solution
training_metadata: Metadata for training use
archived_at: Timestamp of archival
"""
archive_id: str
solution: Solution
tournament_id: str
rejection_reason: Optional[str] = None
winner_comparison: Dict[str, Any] = field(default_factory=dict)
training_metadata: Dict[str, Any] = field(default_factory=dict)
archived_at: datetime = field(default_factory=datetime.utcnow)
def __post_init__(self):
if not self.archive_id:
self.archive_id = str(uuid.uuid4())
def to_dict(self) -> Dict[str, Any]:
"""Convert archive to dictionary for storage."""
return {
"archive_id": self.archive_id,
"solution": self.solution.to_dict(),
"tournament_id": self.tournament_id,
"rejection_reason": self.rejection_reason,
"winner_comparison": self.winner_comparison,
"training_metadata": self.training_metadata,
"archived_at": self.archived_at.isoformat(),
}
# =============================================================================
# Protocols and Abstract Classes
# =============================================================================
class AgentManager(Protocol):
"""Protocol for agent management - to be implemented by the system."""
async def spawn_agent(self, config: AgentConfig) -> str:
"""Spawn an agent with the given configuration. Returns agent ID."""
...
async def execute_task(self, agent_id: str, task: Task) -> Solution:
"""Execute a task with the given agent. Returns the solution."""
...
async def terminate_agent(self, agent_id: str) -> None:
"""Terminate an agent."""
...
class GitWrapper(Protocol):
"""Protocol for Git operations - to be implemented by the system."""
async def get_file_content(self, path: str) -> str:
"""Get content of a file at the given path."""
...
async def apply_diff(self, diff: str) -> bool:
"""Apply a diff to the working directory."""
...
async def get_diff(self, source: str, target: str) -> str:
"""Get diff between two states."""
...
class EvaluationStrategy(ABC):
"""Abstract base class for solution evaluation strategies."""
@property
@abstractmethod
def name(self) -> str:
"""Name of this evaluation strategy."""
pass
@abstractmethod
async def evaluate(self, solution: Solution, task: Task) -> float:
"""Evaluate a solution and return a score (0.0 to 1.0)."""
pass
# =============================================================================
# Evaluation Strategy Implementations
# =============================================================================
class ComplexityEvaluator(EvaluationStrategy):
"""Evaluates solution based on code complexity metrics."""
@property
def name(self) -> str:
return "complexity"
async def evaluate(self, solution: Solution, task: Task) -> float:
"""Score based on cyclomatic complexity and lines of code."""
total_lines = 0
complexity_score = 1.0
for filepath, content in solution.files_changed.items():
lines = content.split('\n')
total_lines += len(lines)
# Simple complexity heuristic: count control structures
control_structures = sum(
content.count(keyword)
for keyword in ['if ', 'for ', 'while ', 'switch', 'try:', 'except']
)
# Penalize high complexity
if len(lines) > 0:
complexity_ratio = control_structures / len(lines)
complexity_score *= max(0.5, 1.0 - complexity_ratio)
# Prefer moderate line counts (not too short, not too long)
length_score = 1.0
if total_lines < 5:
length_score = 0.7 # Too short might be incomplete
elif total_lines > 500:
length_score = 0.8 # Very long solutions
return complexity_score * length_score
class TestPassEvaluator(EvaluationStrategy):
"""Evaluates solution based on test pass rate."""
@property
def name(self) -> str:
return "test_pass"
async def evaluate(self, solution: Solution, task: Task) -> float:
"""Score based on test results."""
if not solution.test_results:
return 0.5 # Neutral if no tests run
passed = solution.test_results.get('passed', 0)
total = solution.test_results.get('total', 0)
if total == 0:
return 0.5
pass_rate = passed / total
# Bonus for 100% pass rate
if pass_rate == 1.0:
return 1.0
return pass_rate * 0.9 # Slight penalty for not passing all
class RequirementMatchEvaluator(EvaluationStrategy):
"""Evaluates solution based on requirement fulfillment."""
@property
def name(self) -> str:
return "requirement_match"
async def evaluate(self, solution: Solution, task: Task) -> float:
"""Score based on how well requirements are met."""
if not task.requirements:
return 1.0 # No requirements means perfect match
# Simple keyword matching in explanation and diff
explanation_lower = solution.explanation.lower()
diff_lower = solution.diff.lower()
matches = 0
for req in task.requirements:
req_lower = req.lower()
# Check if requirement keywords appear in solution
req_keywords = set(req_lower.split()) - {'the', 'a', 'an', 'to', 'of', 'in', 'and'}
if req_keywords:
match_count = sum(
1 for kw in req_keywords
if kw in explanation_lower or kw in diff_lower
)
matches += match_count / len(req_keywords)
return min(1.0, matches / len(task.requirements))
class CompositeEvaluator(EvaluationStrategy):
"""Combines multiple evaluation strategies with weights."""
def __init__(self, strategies: List[tuple[EvaluationStrategy, float]]):
"""
Args:
strategies: List of (strategy, weight) tuples
"""
self.strategies = strategies
self._name = "composite"
@property
def name(self) -> str:
return self._name
async def evaluate(self, solution: Solution, task: Task) -> float:
"""Combine scores from all strategies."""
if not self.strategies:
return 0.5
total_score = 0.0
total_weight = 0.0
for strategy, weight in self.strategies:
try:
score = await strategy.evaluate(solution, task)
total_score += score * weight
total_weight += weight
except Exception as e:
logger.warning(f"Evaluation failed for {strategy.name}: {e}")
if total_weight == 0:
return 0.5
return total_score / total_weight
# =============================================================================
# Diff Presentation
# =============================================================================
class DiffPresenter:
"""Formats and presents diffs for human review.
This class provides multiple diff visualization formats including
unified diff, side-by-side comparison, and highlighted differences.
"""
def __init__(self, context_lines: int = 3):
self.context_lines = context_lines
def format_unified_diff(
self,
original: Dict[str, str],
modified: Dict[str, str],
from_label: str = "original",
to_label: str = "modified"
) -> str:
"""Generate unified diff between original and modified files.
Args:
original: Dictionary mapping file paths to original content
modified: Dictionary mapping file paths to modified content
from_label: Label for original state
to_label: Label for modified state
Returns:
Unified diff string
"""
all_files = set(original.keys()) | set(modified.keys())
diffs = []
for filepath in sorted(all_files):
original_content = original.get(filepath, "")
modified_content = modified.get(filepath, "")
if original_content != modified_content:
diff = difflib.unified_diff(
original_content.splitlines(keepends=True),
modified_content.splitlines(keepends=True),
fromfile=f"{from_label}/{filepath}",
tofile=f"{to_label}/{filepath}",
n=self.context_lines
)
diffs.append(''.join(diff))
return '\n'.join(diffs) if diffs else "No changes"
def format_side_by_side(
self,
original: Dict[str, str],
modified: Dict[str, str],
width: int = 80
) -> str:
"""Generate side-by-side comparison.
Args:
original: Dictionary mapping file paths to original content
modified: Dictionary mapping file paths to modified content
width: Width of each column
Returns:
Side-by-side comparison string
"""
all_files = set(original.keys()) | set(modified.keys())
output = []
for filepath in sorted(all_files):
output.append(f"\n{'=' * (width * 2 + 5)}")
output.append(f"File: {filepath}")
output.append(f"{'=' * (width * 2 + 5)}\n")
orig_lines = original.get(filepath, "").splitlines()
mod_lines = modified.get(filepath, "").splitlines()
max_lines = max(len(orig_lines), len(mod_lines))
for i in range(max_lines):
orig = orig_lines[i] if i < len(orig_lines) else ""
mod = mod_lines[i] if i < len(mod_lines) else ""
# Truncate to width
orig_display = orig[:width-1].ljust(width)
mod_display = mod[:width-1].ljust(width)
# Mark differences
marker = " "
if orig != mod:
marker = "*"
output.append(f"{marker} {orig_display} | {mod_display}")
return '\n'.join(output)
def format_solution_summary(self, solution: Solution) -> str:
"""Generate a summary of a solution's changes.
Args:
solution: The solution to summarize
Returns:
Formatted summary string
"""
lines = [
f"Solution: {solution.solution_id}",
f"Agent: {solution.agent_id}",
f"Status: {solution.status.value}",
f"Files Changed: {len(solution.files_changed)}",
f"Execution Time: {solution.execution_time_ms:.2f}ms",
"",
"Metrics:",
]
for metric, value in solution.metrics.items():
lines.append(f" {metric}: {value}")
if solution.explanation:
lines.extend([
"",
"Explanation:",
solution.explanation[:500] + "..." if len(solution.explanation) > 500 else solution.explanation
])
return '\n'.join(lines)
def highlight_differences(
self,
solutions: List[Solution],
focus_files: Optional[List[str]] = None
) -> Dict[str, List[Dict[str, Any]]]:
"""Highlight key differences between solutions.
Args:
solutions: List of solutions to compare
focus_files: Specific files to focus on (None = all files)
Returns:
Dictionary mapping file paths to difference analysis
"""
if not solutions:
return {}
# Collect all files
all_files = set()
for sol in solutions:
all_files.update(sol.files_changed.keys())
if focus_files:
all_files = all_files & set(focus_files)
differences = {}
for filepath in all_files:
file_versions = []
for sol in solutions:
content = sol.files_changed.get(filepath, "")
file_versions.append({
"solution_id": sol.solution_id,
"agent_id": sol.agent_id,
"content": content,
"content_hash": hash(content) & 0xFFFFFFFF
})
# Find unique versions
content_groups = {}
for fv in file_versions:
h = fv["content_hash"]
if h not in content_groups:
content_groups[h] = []
content_groups[h].append(fv)
differences[filepath] = {
"num_unique_versions": len(content_groups),
"versions": list(content_groups.values()),
"agents_per_version": [len(v) for v in content_groups.values()]
}
return differences
# =============================================================================
# Tournament Orchestrator
# =============================================================================
class TournamentOrchestrator:
"""Main orchestrator for tournament-based parallel agent execution.
This class manages the complete tournament lifecycle:
1. Creating tournaments with multiple agent configurations
2. Executing agents in parallel with timeout handling
3. Evaluating solutions using pluggable strategies
4. Presenting results for human review
5. Archiving rejected solutions for training
Example:
orchestrator = TournamentOrchestrator(agent_manager, git_wrapper)
tournament = orchestrator.create_tournament(
task=task,
agent_configs=[config1, config2, config3],
selection_mode=SelectionMode.HUMAN_CHOICE
)
result = await orchestrator.run_tournament(tournament.tournament_id)
review = await orchestrator.present_for_review(tournament.tournament_id)
winner = await orchestrator.select_winner(tournament.tournament_id, winner_id)
"""
def __init__(
self,
agent_manager: AgentManager,
git_wrapper: Optional[GitWrapper] = None,
default_evaluators: Optional[List[EvaluationStrategy]] = None,
max_concurrent_agents: int = 5
):
"""Initialize the tournament orchestrator.
Args:
agent_manager: Manager for spawning and controlling agents
git_wrapper: Optional Git wrapper for file operations
default_evaluators: Default evaluation strategies
max_concurrent_agents: Maximum agents to run concurrently
"""
self.agent_manager = agent_manager
self.git_wrapper = git_wrapper
self.max_concurrent_agents = max_concurrent_agents
# Default evaluators
if default_evaluators is None:
self.default_evaluators = [
ComplexityEvaluator(),
TestPassEvaluator(),
RequirementMatchEvaluator()
]
else:
self.default_evaluators = default_evaluators
# Tournament storage
self._tournaments: Dict[str, Tournament] = {}
# Progress tracking
self._progress_callbacks: List[Callable[[str, Dict[str, Any]], None]] = []
# Cancellation tokens
self._cancellation_tokens: Dict[str, asyncio.Event] = {}
# Diff presenter
self._diff_presenter = DiffPresenter()
def create_tournament(
self,
task: Task,
agent_configs: List[AgentConfig],
selection_mode: SelectionMode = SelectionMode.HUMAN_CHOICE
) -> Tournament:
"""Create a new tournament with the given task and agent configurations.
Args:
task: The task to be solved
agent_configs: List of agent configurations to compete
selection_mode: How the winner will be selected
Returns:
The created Tournament instance
"""
# Sort agent configs by priority (higher first)
sorted_configs = sorted(agent_configs, key=lambda c: -c.priority)
tournament = Tournament(
tournament_id=str(uuid.uuid4()),
task=task,
agent_configs=sorted_configs,
selection_mode=selection_mode
)
self._tournaments[tournament.tournament_id] = tournament
self._cancellation_tokens[tournament.tournament_id] = asyncio.Event()
logger.info(f"Created tournament {tournament.tournament_id} with {len(agent_configs)} agents")
return tournament
async def run_tournament(self, tournament_id: str) -> TournamentResult:
"""Execute all agents in the tournament and return results.
This method runs all agent configurations in parallel (up to max_concurrent_agents),
with individual timeout handling for each agent. Failures are isolated so one
agent's failure doesn't affect others.
Args:
tournament_id: ID of the tournament to run
Returns:
TournamentResult with all solutions and execution summary
"""
tournament = self._get_tournament(tournament_id)
cancel_token = self._cancellation_tokens.get(tournament_id)
if tournament is None:
raise ValueError(f"Tournament {tournament_id} not found")
tournament.status = TournamentStatus.RUNNING
tournament.started_at = datetime.utcnow()
self._notify_progress(tournament_id, {
"status": "started",
"total_agents": len(tournament.agent_configs)
})
# Create semaphore for limiting concurrent execution
semaphore = asyncio.Semaphore(self.max_concurrent_agents)
# Execute all agents
tasks = []
for config in tournament.agent_configs:
task = self._execute_agent_with_semaphore(
tournament_id, config, tournament.task, semaphore, cancel_token
)
tasks.append(task)
# Wait for all to complete
results = await asyncio.gather(*tasks, return_exceptions=True)
# Process results
success_count = 0
failure_count = 0
timeout_count = 0
for i, result in enumerate(results):
config = tournament.agent_configs[i]
if isinstance(result, Exception):
# Create failed solution
solution = Solution(
solution_id=str(uuid.uuid4()),
agent_id=config.agent_id,
task_id=tournament.task.task_id,
status=SolutionStatus.FAILED,
explanation=f"Execution failed: {str(result)}"
)
failure_count += 1
logger.error(f"Agent {config.agent_id} failed: {result}")
else:
solution = result
if solution.status == SolutionStatus.COMPLETED:
success_count += 1
elif solution.status == SolutionStatus.TIMEOUT:
timeout_count += 1
failure_count += 1
tournament.solutions[config.agent_id] = solution
# Evaluate solutions
await self._evaluate_solutions(tournament)
tournament.status = TournamentStatus.COMPLETED
tournament.completed_at = datetime.utcnow()
# Build execution summary
execution_summary = {
"total_agents": len(tournament.agent_configs),
"successful": success_count,
"failed": failure_count,
"timeouts": timeout_count,
"total_execution_time_ms": sum(
s.execution_time_ms for s in tournament.solutions.values()
)
}
self._notify_progress(tournament_id, {
"status": "completed",
"execution_summary": execution_summary
})
# Auto-select winner if mode is AUTO_BEST or THRESHOLD
winner = None
if tournament.selection_mode == SelectionMode.AUTO_BEST:
winner = await self._auto_select_winner(tournament)
elif tournament.selection_mode == SelectionMode.THRESHOLD:
winner = await self._threshold_select_winner(tournament, threshold=0.8)
return TournamentResult(
tournament_id=tournament_id,
solutions=list(tournament.solutions.values()),
winner=winner,
execution_summary=execution_summary,
evaluation_summary=tournament.evaluation_scores
)
async def present_for_review(self, tournament_id: str) -> ReviewPresentation:
"""Format tournament results for human review.
Creates a comprehensive review presentation including:
- Side-by-side solution comparisons
- Formatted diffs for each solution
- Agent metadata and performance metrics
- Auto-generated recommendations
Args:
tournament_id: ID of the tournament to present
Returns:
ReviewPresentation formatted for human review
"""
tournament = self._get_tournament(tournament_id)
if tournament is None:
raise ValueError(f"Tournament {tournament_id} not found")
# Build solution comparisons
comparisons = []
for agent_id, solution in tournament.solutions.items():
scores = tournament.evaluation_scores.get(agent_id, {})
composite_score = sum(scores.values()) / len(scores) if scores else 0.0
comparisons.append({
"agent_id": agent_id,
"solution_id": solution.solution_id,
"status": solution.status.value,
"score": round(composite_score, 3),
"execution_time": solution.execution_time_ms,
"files_changed": len(solution.files_changed),
"metrics": solution.metrics
})
# Sort by score descending
comparisons.sort(key=lambda x: x["score"], reverse=True)
# Build diffs
diffs = {}
for agent_id, solution in tournament.solutions.items():
if solution.diff:
diffs[agent_id] = solution.diff
else:
diffs[agent_id] = self._diff_presenter.format_solution_summary(solution)
# Build agent metadata
agent_metadata = {}
for config in tournament.agent_configs:
solution = tournament.solutions.get(config.agent_id)
agent_metadata[config.agent_id] = {
"agent_type": config.agent_type,
"timeout_seconds": config.timeout_seconds,
"priority": config.priority,
"model_config": config.model_config,
"solution_status": solution.status.value if solution else "unknown",
"execution_time_ms": solution.execution_time_ms if solution else 0
}
# Generate recommendations
recommendations = self._generate_recommendations(tournament)
return ReviewPresentation(