-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorchestrator.py
More file actions
1335 lines (1098 loc) · 45.6 KB
/
orchestrator.py
File metadata and controls
1335 lines (1098 loc) · 45.6 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
"""
Ansib-eL Core Orchestrator Module
This module implements the central "Repo Manager" for the AI-Native Version Control System.
The Orchestrator acts as a project manager that:
- Breaks down human prompts into executable tasks
- Delegates tasks to sub-agents
- Controls main branch access with human-in-the-loop validation
- Manages repository state and pending approvals
Author: AI Systems Architect
"""
from __future__ import annotations
import uuid
import json
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum, auto
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
Generic,
List,
Optional,
Protocol,
Set,
TypeVar,
Union,
)
from queue import Queue, Empty
from threading import Lock
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# =============================================================================
# Enums and Constants
# =============================================================================
class TaskStatus(Enum):
"""Status states for a task lifecycle."""
PENDING = auto()
ASSIGNED = auto()
IN_PROGRESS = auto()
COMPLETED = auto()
FAILED = auto()
CANCELLED = auto()
class TaskPriority(Enum):
"""Priority levels for task scheduling."""
CRITICAL = 1
HIGH = 2
MEDIUM = 3
LOW = 4
class MergeStatus(Enum):
"""Possible outcomes of a merge operation."""
PENDING_APPROVAL = auto()
APPROVED = auto()
REJECTED = auto()
MERGED = auto()
CONFLICT = auto()
ERROR = auto()
class BranchProtectionLevel(Enum):
"""Protection levels for branches."""
NONE = auto() # No protection
REVIEW_REQUIRED = auto() # Requires review but not necessarily human
HUMAN_APPROVAL = auto() # Requires explicit human approval
LOCKED = auto() # Completely locked
# =============================================================================
# Data Classes
# =============================================================================
@dataclass(frozen=True)
class TaskId:
"""Unique identifier for tasks."""
value: str = field(default_factory=lambda: str(uuid.uuid4()))
def __str__(self) -> str:
return self.value
@dataclass(frozen=True)
class AgentId:
"""Unique identifier for agents."""
value: str = field(default_factory=lambda: str(uuid.uuid4()))
def __str__(self) -> str:
return self.value
@dataclass
class CodeChange:
"""Represents a code change in the repository."""
file_path: str
diff_content: str
description: str
line_start: Optional[int] = None
line_end: Optional[int] = None
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary representation."""
return {
"file_path": self.file_path,
"diff_content": self.diff_content,
"description": self.description,
"line_start": self.line_start,
"line_end": self.line_end,
}
@dataclass
class Task:
"""
Represents an individual task derived from a human prompt.
Attributes:
id: Unique task identifier
description: Human-readable task description
requirements: List of specific requirements to fulfill
acceptance_criteria: Criteria for task completion
priority: Task priority level
estimated_effort: Estimated effort in story points or hours
dependencies: List of task IDs that must complete before this task
metadata: Additional task metadata
status: Current task status
assigned_agent: ID of agent assigned to this task
created_at: Task creation timestamp
completed_at: Task completion timestamp
"""
description: str
requirements: List[str]
acceptance_criteria: List[str]
id: TaskId = field(default_factory=TaskId)
priority: TaskPriority = TaskPriority.MEDIUM
estimated_effort: float = 1.0
dependencies: List[TaskId] = field(default_factory=list)
metadata: Dict[str, Any] = field(default_factory=dict)
status: TaskStatus = TaskStatus.PENDING
assigned_agent: Optional[AgentId] = None
created_at: datetime = field(default_factory=datetime.now)
completed_at: Optional[datetime] = None
def mark_completed(self) -> None:
"""Mark the task as completed."""
self.status = TaskStatus.COMPLETED
self.completed_at = datetime.now()
logger.info(f"Task {self.id} marked as completed")
def mark_failed(self, reason: str) -> None:
"""Mark the task as failed with a reason."""
self.status = TaskStatus.FAILED
self.metadata["failure_reason"] = reason
logger.error(f"Task {self.id} marked as failed: {reason}")
def can_execute(self, completed_tasks: Set[TaskId]) -> bool:
"""Check if all dependencies are satisfied."""
return all(dep in completed_tasks for dep in self.dependencies)
def to_dict(self) -> Dict[str, Any]:
"""Convert task to dictionary representation."""
return {
"id": str(self.id),
"description": self.description,
"requirements": self.requirements,
"acceptance_criteria": self.acceptance_criteria,
"priority": self.priority.name,
"estimated_effort": self.estimated_effort,
"dependencies": [str(dep) for dep in self.dependencies],
"status": self.status.name,
"assigned_agent": str(self.assigned_agent) if self.assigned_agent else None,
"created_at": self.created_at.isoformat(),
"completed_at": self.completed_at.isoformat() if self.completed_at else None,
}
@dataclass
class TaskBreakdown:
"""
Represents the decomposition of a human prompt into executable tasks.
Attributes:
original_prompt: The original human prompt
tasks: List of decomposed tasks
execution_strategy: Recommended execution strategy (sequential/parallel/mixed)
context: Additional context extracted from the prompt
"""
original_prompt: str
tasks: List[Task]
execution_strategy: str = "sequential"
context: Dict[str, Any] = field(default_factory=dict)
created_at: datetime = field(default_factory=datetime.now)
def get_critical_tasks(self) -> List[Task]:
"""Return tasks with CRITICAL priority."""
return [t for t in self.tasks if t.priority == TaskPriority.CRITICAL]
def get_execution_order(self) -> List[Task]:
"""
Return tasks in dependency-respecting execution order.
Uses topological sort for dependency resolution.
"""
# Simple topological sort
completed: Set[TaskId] = set()
ordered: List[Task] = []
remaining = list(self.tasks)
while remaining:
progress = False
for task in remaining[:]:
if task.can_execute(completed):
ordered.append(task)
completed.add(task.id)
remaining.remove(task)
progress = True
if not progress and remaining:
# Circular dependency detected, break with error
raise ValueError(f"Circular dependency detected in tasks: {remaining}")
return ordered
def to_dict(self) -> Dict[str, Any]:
"""Convert breakdown to dictionary representation."""
return {
"original_prompt": self.original_prompt,
"tasks": [task.to_dict() for task in self.tasks],
"execution_strategy": self.execution_strategy,
"context": self.context,
"created_at": self.created_at.isoformat(),
}
@dataclass
class Solution:
"""
Represents a solution produced by an agent.
Attributes:
task_id: ID of the task this solution addresses
agent_id: ID of the agent that produced this solution
changes: List of code changes
explanation: Explanation of the solution approach
tests_included: Whether tests are included
documentation: Any documentation produced
"""
task_id: TaskId
agent_id: AgentId
changes: List[CodeChange]
explanation: str
tests_included: bool = False
documentation: Optional[str] = None
created_at: datetime = field(default_factory=datetime.now)
metadata: Dict[str, Any] = field(default_factory=dict)
def get_affected_files(self) -> Set[str]:
"""Return set of files affected by this solution."""
return {change.file_path for change in self.changes}
def to_dict(self) -> Dict[str, Any]:
"""Convert solution to dictionary representation."""
return {
"task_id": str(self.task_id),
"agent_id": str(self.agent_id),
"changes": [change.to_dict() for change in self.changes],
"explanation": self.explanation,
"tests_included": self.tests_included,
"documentation": self.documentation,
"created_at": self.created_at.isoformat(),
}
@dataclass
class DelegationResult:
"""
Result of delegating a task to an agent.
Attributes:
success: Whether delegation was successful
task_id: ID of the delegated task
assigned_agent: ID of the agent assigned
message: Status message
estimated_completion: Estimated completion time
"""
success: bool
task_id: TaskId
assigned_agent: Optional[AgentId]
message: str
estimated_completion: Optional[datetime] = None
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class MergeResult:
"""
Result of a merge operation.
Attributes:
status: Status of the merge operation
solution: The solution being merged
message: Human-readable result message
commit_hash: Git commit hash if merge was successful
conflicts: List of conflicts if any
approved_by: ID of approver if human approval was required
"""
status: MergeStatus
solution: Solution
message: str
commit_hash: Optional[str] = None
conflicts: List[str] = field(default_factory=list)
approved_by: Optional[str] = None
timestamp: datetime = field(default_factory=datetime.now)
@dataclass
class RepoStatus:
"""
Snapshot of repository state.
Attributes:
current_branch: Current active branch
pending_approvals: Number of solutions awaiting approval
active_tasks: Number of tasks currently in progress
completed_tasks: Number of completed tasks
failed_tasks: Number of failed tasks
branch_protection: Current branch protection level
last_commit: Hash of last commit
working_tree_clean: Whether working tree has uncommitted changes
"""
current_branch: str
pending_approvals: int
active_tasks: int
completed_tasks: int
failed_tasks: int
branch_protection: BranchProtectionLevel
last_commit: Optional[str]
working_tree_clean: bool
timestamp: datetime = field(default_factory=datetime.now)
def is_healthy(self) -> bool:
"""Check if repository is in a healthy state."""
return self.failed_tasks == 0 and self.working_tree_clean
@dataclass
class ApprovalRequest:
"""
Represents a pending approval request for human review.
Attributes:
id: Unique approval request ID
solution: Solution awaiting approval
submitted_at: When the request was submitted
priority: Priority of the approval request
"""
solution: Solution
id: str = field(default_factory=lambda: str(uuid.uuid4()))
submitted_at: datetime = field(default_factory=datetime.now)
priority: TaskPriority = TaskPriority.MEDIUM
reviewed_by: Optional[str] = None
review_comments: Optional[str] = None
def approve(self, reviewer: str, comments: Optional[str] = None) -> None:
"""Mark the approval request as approved."""
self.reviewed_by = reviewer
self.review_comments = comments
logger.info(f"Approval request {self.id} approved by {reviewer}")
def reject(self, reviewer: str, comments: str) -> None:
"""Mark the approval request as rejected."""
self.reviewed_by = reviewer
self.review_comments = comments
logger.info(f"Approval request {self.id} rejected by {reviewer}: {comments}")
# =============================================================================
# Protocols (Interfaces)
# =============================================================================
class GitWrapperInterface(Protocol):
"""Protocol for Git wrapper integration."""
def get_current_branch(self) -> str:
"""Get the name of the current branch."""
...
def create_branch(self, branch_name: str, from_branch: Optional[str] = None) -> bool:
"""Create a new branch."""
...
def checkout_branch(self, branch_name: str) -> bool:
"""Checkout a branch."""
...
def commit_changes(self, message: str, files: Optional[List[str]] = None) -> str:
"""Commit changes and return commit hash."""
...
def merge_branch(self, branch_name: str, strategy: str = "recursive") -> MergeResult:
"""Merge a branch into current branch."""
...
def get_last_commit(self) -> Optional[str]:
"""Get hash of last commit."""
...
def is_working_tree_clean(self) -> bool:
"""Check if working tree is clean."""
...
def get_branch_protection(self, branch_name: str) -> BranchProtectionLevel:
"""Get protection level for a branch."""
...
def set_branch_protection(self, branch_name: str, level: BranchProtectionLevel) -> bool:
"""Set protection level for a branch."""
...
class AgentInterface(Protocol):
"""Protocol for agent integration."""
@property
def id(self) -> AgentId:
"""Unique agent identifier."""
...
@property
def capabilities(self) -> List[str]:
"""List of agent capabilities."""
...
def can_handle(self, task: Task) -> bool:
"""Check if agent can handle the given task."""
...
def execute(self, task: Task) -> Solution:
"""Execute the task and return a solution."""
...
def get_status(self) -> TaskStatus:
"""Get current agent status."""
...
class TournamentInterface(Protocol):
"""Protocol for tournament/parallel execution integration."""
def register_agent(self, agent: AgentInterface) -> None:
"""Register an agent for tournament participation."""
...
def execute_parallel(self, task: Task, agents: List[AgentInterface]) -> List[Solution]:
"""Execute task with multiple agents in parallel."""
...
def select_winner(self, solutions: List[Solution]) -> Solution:
"""Select the best solution from candidates."""
...
class HumanInterface(Protocol):
"""Protocol for human-in-the-loop integration."""
def request_approval(self, request: ApprovalRequest) -> bool:
"""Request human approval for a solution."""
...
def provide_feedback(self, task_id: TaskId, feedback: str) -> None:
"""Provide feedback on a task or solution."""
...
def is_available(self) -> bool:
"""Check if human reviewer is available."""
...
# =============================================================================
# Core Orchestrator Class
# =============================================================================
class Orchestrator:
"""
Central orchestrator for the Ansib-eL AI-Native Version Control System.
The Orchestrator acts as the "Repo Manager" - it doesn't write code but
oversees repository state, manages task delegation, and controls access
to protected branches through human-in-the-loop validation.
Key Responsibilities:
1. Break down human prompts into executable tasks
2. Delegate tasks to appropriate sub-agents
3. Control main branch access with approval gates
4. Manage repository state and health
Example:
>>> orchestrator = Orchestrator("/path/to/repo")
>>> breakdown = orchestrator.process_human_prompt("Add user authentication")
>>> for task in breakdown.tasks:
... result = orchestrator.delegate_task(task, agent_pool)
>>> # Solutions await human approval before merging to main
"""
# Default configuration
DEFAULT_MAIN_BRANCH = "main"
DEFAULT_PROTECTION_LEVEL = BranchProtectionLevel.HUMAN_APPROVAL
def __init__(
self,
repo_path: str,
git_wrapper: Optional[GitWrapperInterface] = None,
human_interface: Optional[HumanInterface] = None,
tournament_system: Optional[TournamentInterface] = None,
):
"""
Initialize the Orchestrator.
Args:
repo_path: Path to the Git repository
git_wrapper: Optional Git wrapper instance (for testing/injection)
human_interface: Optional human interface instance
tournament_system: Optional tournament system for parallel execution
"""
self.repo_path = Path(repo_path).resolve()
self._git = git_wrapper # Will be initialized lazily
self._human = human_interface
self._tournament = tournament_system
# Task management
self._tasks: Dict[TaskId, Task] = {}
self._solutions: Dict[TaskId, Solution] = {}
self._task_lock = Lock()
# Approval queue
self._approval_queue: Queue[ApprovalRequest] = Queue()
self._approved_solutions: List[Solution] = []
self._rejected_solutions: List[Solution] = []
# Branch protection
self._protected_branches: Dict[str, BranchProtectionLevel] = {
self.DEFAULT_MAIN_BRANCH: self.DEFAULT_PROTECTION_LEVEL
}
# Statistics
self._stats = {
"tasks_created": 0,
"tasks_completed": 0,
"tasks_failed": 0,
"merges_approved": 0,
"merges_rejected": 0,
}
logger.info(f"Orchestrator initialized for repository: {self.repo_path}")
# -------------------------------------------------------------------------
# Core Public Methods
# -------------------------------------------------------------------------
def process_human_prompt(self, prompt: str) -> TaskBreakdown:
"""
Break down a human prompt into executable tasks.
This method analyzes the human prompt and decomposes it into
a structured set of tasks with dependencies, priorities, and
acceptance criteria.
Args:
prompt: The natural language prompt from the human
Returns:
TaskBreakdown containing decomposed tasks and execution strategy
Example:
>>> breakdown = orchestrator.process_human_prompt(
... "Add user authentication with login and signup"
... )
>>> print(f"Created {len(breakdown.tasks)} tasks")
"""
logger.info(f"Processing human prompt: {prompt[:50]}...")
# TODO: Integration Point - Connect to LLM for intelligent task breakdown
# This is where an LLM would analyze the prompt and create tasks
# For now, implement a simple rule-based breakdown
tasks = self._breakdown_prompt(prompt)
# Determine execution strategy based on task dependencies
strategy = self._determine_execution_strategy(tasks)
breakdown = TaskBreakdown(
original_prompt=prompt,
tasks=tasks,
execution_strategy=strategy,
context={"prompt_length": len(prompt), "word_count": len(prompt.split())}
)
# Register tasks
with self._task_lock:
for task in tasks:
self._tasks[task.id] = task
self._stats["tasks_created"] += 1
logger.info(f"Prompt breakdown complete: {len(tasks)} tasks created")
return breakdown
def delegate_task(
self,
task: Task,
agent_pool: List[AgentInterface],
use_tournament: bool = False,
) -> DelegationResult:
"""
Delegate a task to an appropriate agent from the pool.
Args:
task: The task to delegate
agent_pool: Available agents to choose from
use_tournament: Whether to use tournament mode (parallel execution)
Returns:
DelegationResult indicating success/failure and assignment details
Raises:
ValueError: If no suitable agent found in pool
Example:
>>> result = orchestrator.delegate_task(task, [agent1, agent2, agent3])
>>> if result.success:
... print(f"Task assigned to {result.assigned_agent}")
"""
logger.info(f"Delegating task {task.id}: {task.description[:40]}...")
if not agent_pool:
return DelegationResult(
success=False,
task_id=task.id,
assigned_agent=None,
message="No agents available in pool"
)
# Find suitable agents
suitable_agents = [a for a in agent_pool if a.can_handle(task)]
if not suitable_agents:
return DelegationResult(
success=False,
task_id=task.id,
assigned_agent=None,
message=f"No agent capable of handling task: {task.description}"
)
# Update task status
task.status = TaskStatus.ASSIGNED
if use_tournament and self._tournament and len(suitable_agents) > 1:
# Tournament mode - execute with multiple agents and select best
return self._delegate_tournament(task, suitable_agents)
else:
# Single agent mode - select best match
return self._delegate_single(task, suitable_agents)
def validate_and_merge(
self,
solution: Solution,
force: bool = False,
reviewer: Optional[str] = None,
) -> MergeResult:
"""
Validate a solution and merge if approved.
This is the human-in-the-loop gateway. Solutions cannot be merged
to protected branches without explicit approval.
Args:
solution: The solution to validate and merge
force: Whether to bypass protection (admin only)
reviewer: ID of the human reviewer
Returns:
MergeResult indicating the outcome
Example:
>>> result = orchestrator.validate_and_merge(solution, reviewer="alice")
>>> if result.status == MergeStatus.MERGED:
... print(f"Successfully merged: {result.commit_hash}")
"""
logger.info(f"Validating solution for task {solution.task_id}")
current_branch = self._get_git_wrapper().get_current_branch()
protection = self._get_branch_protection(current_branch)
# Check if protection can be bypassed
if force:
logger.warning(f"Force merge requested for {solution.task_id}")
protection = BranchProtectionLevel.NONE
# Route based on protection level
if protection == BranchProtectionLevel.HUMAN_APPROVAL:
return self._merge_with_human_approval(solution, reviewer)
elif protection == BranchProtectionLevel.REVIEW_REQUIRED:
return self._merge_with_review(solution, reviewer)
else:
return self._merge_direct(solution)
def get_repo_status(self) -> RepoStatus:
"""
Get current repository status snapshot.
Returns:
RepoStatus containing comprehensive repository state
Example:
>>> status = orchestrator.get_repo_status()
>>> print(f"Pending approvals: {status.pending_approvals}")
>>> print(f"Repository healthy: {status.is_healthy()}")
"""
git = self._get_git_wrapper()
with self._task_lock:
active = sum(1 for t in self._tasks.values()
if t.status == TaskStatus.IN_PROGRESS)
completed = sum(1 for t in self._tasks.values()
if t.status == TaskStatus.COMPLETED)
failed = sum(1 for t in self._tasks.values()
if t.status == TaskStatus.FAILED)
current_branch = git.get_current_branch()
return RepoStatus(
current_branch=current_branch,
pending_approvals=self._approval_queue.qsize(),
active_tasks=active,
completed_tasks=completed,
failed_tasks=failed,
branch_protection=self._get_branch_protection(current_branch),
last_commit=git.get_last_commit(),
working_tree_clean=git.is_working_tree_clean(),
)
# -------------------------------------------------------------------------
# Branch Protection Methods
# -------------------------------------------------------------------------
def set_branch_protection(
self,
branch_name: str,
level: BranchProtectionLevel,
) -> bool:
"""
Set protection level for a branch.
Args:
branch_name: Name of the branch to protect
level: Protection level to apply
Returns:
True if protection was set successfully
"""
self._protected_branches[branch_name] = level
logger.info(f"Set protection level for {branch_name}: {level.name}")
# Also update via Git wrapper if available
git = self._get_git_wrapper()
if hasattr(git, 'set_branch_protection'):
return git.set_branch_protection(branch_name, level)
return True
def get_branch_protection(self, branch_name: str) -> BranchProtectionLevel:
"""Get protection level for a branch."""
return self._get_branch_protection(branch_name)
def lock_branch(self, branch_name: str) -> bool:
"""Completely lock a branch (no commits allowed)."""
return self.set_branch_protection(branch_name, BranchProtectionLevel.LOCKED)
def unlock_branch(self, branch_name: str) -> bool:
"""Remove all protection from a branch."""
return self.set_branch_protection(branch_name, BranchProtectionLevel.NONE)
# -------------------------------------------------------------------------
# Approval Queue Management
# -------------------------------------------------------------------------
def submit_for_approval(self, solution: Solution, priority: TaskPriority = TaskPriority.MEDIUM) -> str:
"""
Submit a solution for human approval.
Args:
solution: Solution to be approved
priority: Priority of the approval request
Returns:
Approval request ID
"""
request = ApprovalRequest(solution=solution, priority=priority)
self._approval_queue.put(request)
logger.info(f"Solution submitted for approval: {request.id}")
return request.id
def get_pending_approvals(self) -> List[ApprovalRequest]:
"""Get list of all pending approval requests."""
# Convert queue to list without consuming
items = list(self._approval_queue.queue)
return sorted(items, key=lambda x: x.priority.value)
def approve_solution(
self,
approval_id: str,
reviewer: str,
comments: Optional[str] = None,
) -> bool:
"""
Approve a pending solution.
Args:
approval_id: ID of the approval request
reviewer: ID of the approving reviewer
comments: Optional review comments
Returns:
True if approval was processed
"""
# Find and remove from queue
temp_queue = Queue()
found = None
while not self._approval_queue.empty():
try:
req = self._approval_queue.get_nowait()
if req.id == approval_id:
found = req
else:
temp_queue.put(req)
except Empty:
break
# Restore queue
while not temp_queue.empty():
self._approval_queue.put(temp_queue.get())
if found:
found.approve(reviewer, comments)
self._approved_solutions.append(found.solution)
self._stats["merges_approved"] += 1
logger.info(f"Solution {approval_id} approved by {reviewer}")
return True
logger.warning(f"Approval request {approval_id} not found")
return False
def reject_solution(
self,
approval_id: str,
reviewer: str,
comments: str,
) -> bool:
"""Reject a pending solution with feedback."""
# Similar to approve but mark as rejected
temp_queue = Queue()
found = None
while not self._approval_queue.empty():
try:
req = self._approval_queue.get_nowait()
if req.id == approval_id:
found = req
else:
temp_queue.put(req)
except Empty:
break
while not temp_queue.empty():
self._approval_queue.put(temp_queue.get())
if found:
found.reject(reviewer, comments)
self._rejected_solutions.append(found.solution)
self._stats["merges_rejected"] += 1
logger.info(f"Solution {approval_id} rejected by {reviewer}")
return True
return False
# -------------------------------------------------------------------------
# Statistics and Reporting
# -------------------------------------------------------------------------
def get_statistics(self) -> Dict[str, Any]:
"""Get orchestrator statistics."""
return {
**self._stats,
"pending_approvals": self._approval_queue.qsize(),
"approved_solutions": len(self._approved_solutions),
"rejected_solutions": len(self._rejected_solutions),
"total_tasks": len(self._tasks),
}
def export_state(self, output_path: Optional[str] = None) -> str:
"""
Export orchestrator state to JSON.
Args:
output_path: Path to save state file (optional)
Returns:
Path to the saved state file
"""
state = {
"repo_path": str(self.repo_path),
"statistics": self._stats,
"protected_branches": {
name: level.name for name, level in self._protected_branches.items()
},
"tasks": {str(tid): task.to_dict() for tid, task in self._tasks.items()},
"pending_approvals": len(self._approval_queue.queue),
"timestamp": datetime.now().isoformat(),
}
if output_path is None:
output_path = self.repo_path / ".ansibel" / "orchestrator_state.json"
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, 'w') as f:
json.dump(state, f, indent=2)
logger.info(f"State exported to {output_path}")
return str(output_path)
# -------------------------------------------------------------------------
# Private Helper Methods
# -------------------------------------------------------------------------
def _breakdown_prompt(self, prompt: str) -> List[Task]:
"""
Break down a prompt into tasks.
TODO: Integration Point - Replace with LLM-based intelligent breakdown
"""
tasks = []
prompt_lower = prompt.lower()
# Simple keyword-based breakdown for demonstration
if "authentication" in prompt_lower or "login" in prompt_lower:
tasks.append(Task(
description="Design authentication system architecture",
requirements=["Define auth flow", "Choose auth mechanism"],
acceptance_criteria=["Architecture document created"],
priority=TaskPriority.HIGH,
))
tasks.append(Task(
description="Implement user login endpoint",
requirements=["Create login API", "Validate credentials"],
acceptance_criteria=["Login works with valid credentials"],
priority=TaskPriority.HIGH,
dependencies=[tasks[-1].id],
))
tasks.append(Task(
description="Implement user signup endpoint",
requirements=["Create signup API", "Validate input"],
acceptance_criteria=["Users can register successfully"],
priority=TaskPriority.HIGH,
dependencies=[tasks[-1].id],
))
elif "test" in prompt_lower:
tasks.append(Task(
description="Write unit tests",
requirements=["Cover core functionality", "Achieve 80% coverage"],
acceptance_criteria=["All tests pass"],
priority=TaskPriority.MEDIUM,
))
else:
# Generic single task
tasks.append(Task(
description=prompt,
requirements=["Implement as specified"],
acceptance_criteria=["Feature works as expected"],
priority=TaskPriority.MEDIUM,
))
return tasks
def _determine_execution_strategy(self, tasks: List[Task]) -> str:
"""Determine the best execution strategy for tasks."""