forked from AutoForgeAI/autoforge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparallel_orchestrator.py
More file actions
1729 lines (1483 loc) · 71.6 KB
/
parallel_orchestrator.py
File metadata and controls
1729 lines (1483 loc) · 71.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
"""
Parallel Orchestrator
=====================
Unified orchestrator that handles all agent lifecycle:
- Initialization: Creates features from app_spec if needed
- Coding agents: Implement features one at a time
- Testing agents: Regression test passing features (optional)
Uses dependency-aware scheduling to ensure features are only started when their
dependencies are satisfied.
Usage:
# Entry point (always uses orchestrator)
python autonomous_agent_demo.py --project-dir my-app --concurrency 3
# Direct orchestrator usage
python parallel_orchestrator.py --project-dir my-app --max-concurrency 3
"""
import asyncio
import os
import subprocess
import sys
import threading
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Callable, Literal
from sqlalchemy import text
from api.database import Feature, create_database
from api.dependency_resolver import are_dependencies_satisfied, compute_scheduling_scores
from git_workflow import (
commit_changes,
create_pr,
generate_branch_name,
get_commit_sha,
is_git_repo,
push_branch,
)
from progress import has_features
from server.services.project_config import get_git_config, get_refinement_config
from server.utils.process_utils import kill_process_tree
from worktree_manager import create_worktree, remove_worktree
# Root directory of autocoder (where this script and autonomous_agent_demo.py live)
AUTOCODER_ROOT = Path(__file__).parent.resolve()
# Debug log file path
DEBUG_LOG_FILE = AUTOCODER_ROOT / "orchestrator_debug.log"
class DebugLogger:
"""Thread-safe debug logger that writes to a file."""
def __init__(self, log_file: Path = DEBUG_LOG_FILE):
self.log_file = log_file
self._lock = threading.Lock()
self._session_started = False
# DON'T clear on import - only mark session start when run_loop begins
def start_session(self):
"""Mark the start of a new orchestrator session. Clears previous logs."""
with self._lock:
self._session_started = True
with open(self.log_file, "w") as f:
f.write(f"=== Orchestrator Debug Log Started: {datetime.now().isoformat()} ===\n")
f.write(f"=== PID: {os.getpid()} ===\n\n")
def log(self, category: str, message: str, **kwargs):
"""Write a timestamped log entry."""
timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
with self._lock:
with open(self.log_file, "a") as f:
f.write(f"[{timestamp}] [{category}] {message}\n")
for key, value in kwargs.items():
f.write(f" {key}: {value}\n")
f.write("\n")
def section(self, title: str):
"""Write a section header."""
with self._lock:
with open(self.log_file, "a") as f:
f.write(f"\n{'='*60}\n")
f.write(f" {title}\n")
f.write(f"{'='*60}\n\n")
# Global debug logger instance
debug_log = DebugLogger()
def _dump_database_state(session, label: str = ""):
"""Helper to dump full database state to debug log."""
from api.database import Feature
all_features = session.query(Feature).all()
passing = [f for f in all_features if f.passes]
in_progress = [f for f in all_features if f.in_progress and not f.passes]
pending = [f for f in all_features if not f.passes and not f.in_progress]
debug_log.log("DB_DUMP", f"Full database state {label}",
total_features=len(all_features),
passing_count=len(passing),
passing_ids=[f.id for f in passing],
in_progress_count=len(in_progress),
in_progress_ids=[f.id for f in in_progress],
pending_count=len(pending),
pending_ids=[f.id for f in pending[:10]]) # First 10 pending only
# =============================================================================
# Process Limits
# =============================================================================
# These constants bound the number of concurrent agent processes to prevent
# resource exhaustion (memory, CPU, API rate limits).
#
# MAX_PARALLEL_AGENTS: Max concurrent coding agents (each is a Claude session)
# MAX_TOTAL_AGENTS: Hard limit on total child processes (coding + testing)
#
# Expected process count during normal operation:
# - 1 orchestrator process (this script)
# - Up to MAX_PARALLEL_AGENTS coding agents
# - Up to max_concurrency testing agents
# - Total never exceeds MAX_TOTAL_AGENTS + 1 (including orchestrator)
#
# Stress test verification:
# 1. Note baseline: tasklist | findstr python | find /c /v ""
# 2. Run: python autonomous_agent_demo.py --project-dir test --parallel --max-concurrency 5
# 3. During run: count should never exceed baseline + 11 (1 orchestrator + 10 agents)
# 4. After stop: should return to baseline
# =============================================================================
MAX_PARALLEL_AGENTS = 5
MAX_TOTAL_AGENTS = 10
DEFAULT_CONCURRENCY = 3
POLL_INTERVAL = 5 # seconds between checking for ready features
MAX_FEATURE_RETRIES = 3 # Maximum times to retry a failed feature
INITIALIZER_TIMEOUT = 1800 # 30 minutes timeout for initializer
STALE_TESTING_LOCK_MINUTES = 30 # Auto-release testing locks older than this
class ParallelOrchestrator:
"""Orchestrates parallel execution of independent features.
Process bounds:
- Up to MAX_PARALLEL_AGENTS (5) coding agents concurrently
- Up to max_concurrency testing agents concurrently
- Hard limit of MAX_TOTAL_AGENTS (10) total child processes
"""
def __init__(
self,
project_dir: Path,
max_concurrency: int = DEFAULT_CONCURRENCY,
model: str = None,
yolo_mode: bool = False,
testing_agent_ratio: int = 1,
brownfield_mode: bool = False,
on_output: Callable[[int, str], None] = None,
on_status: Callable[[int, str], None] = None,
):
"""Initialize the orchestrator.
Args:
project_dir: Path to the project directory
max_concurrency: Maximum number of concurrent coding agents (1-5).
Also caps testing agents at the same limit.
model: Claude model to use (or None for default)
yolo_mode: Whether to run in YOLO mode (skip testing agents entirely)
testing_agent_ratio: Number of regression testing agents to maintain (0-3).
0 = disabled, 1-3 = maintain that many testing agents running independently.
brownfield_mode: Whether to use brownfield prompts (modifying existing codebase)
on_output: Callback for agent output (feature_id, line)
on_status: Callback for agent status changes (feature_id, status)
"""
self.project_dir = project_dir
self.max_concurrency = min(max(max_concurrency, 1), MAX_PARALLEL_AGENTS)
self.model = model
self.yolo_mode = yolo_mode
self.brownfield_mode = brownfield_mode
self.testing_agent_ratio = min(max(testing_agent_ratio, 0), 3) # Clamp 0-3
self.on_output = on_output
self.on_status = on_status
# Thread-safe state
self._lock = threading.Lock()
# Coding agents: feature_id -> process
self.running_coding_agents: dict[int, subprocess.Popen] = {}
# Testing agents: feature_id -> process (feature being tested)
self.running_testing_agents: dict[int, subprocess.Popen] = {}
# Legacy alias for backward compatibility
self.running_agents = self.running_coding_agents
self.abort_events: dict[int, threading.Event] = {}
self.is_running = False
# Track feature failures to prevent infinite retry loops
self._failure_counts: dict[int, int] = {}
# Session tracking for logging/debugging
self.session_start_time: datetime = None
# Database session for this orchestrator
self._engine, self._session_maker = create_database(project_dir)
# Git workflow configuration
try:
self.git_config = get_git_config(project_dir)
except Exception as e:
# If git config loading fails, disable git workflow
debug_log.log("INIT", f"Failed to load git config: {e}")
self.git_config = {
"enabled": False,
"auto_branch": False,
"auto_commit": False,
"auto_pr": False,
"pr_target_branch": "main",
}
# Refinement workflow configuration
try:
self.refinement_config = get_refinement_config(project_dir)
except Exception as e:
# If refinement config loading fails, use defaults
debug_log.log("INIT", f"Failed to load refinement config: {e}")
self.refinement_config = {
"enabled": True,
"auto_transition": True,
"passes": {
"code_quality": True,
"edge_cases": True,
"performance": True,
"security": True,
"ux": True,
},
}
# Current development phase: 'mvp' or 'refinement'
# Determined dynamically based on feature states
self.phase = self._determine_phase()
def get_session(self):
"""Get a new database session."""
return self._session_maker()
def _determine_phase(self) -> str:
"""Determine the current development phase based on feature states.
MVP phase: at least one feature has refinement_state == 'pending'
Refinement phase: all features have refinement_state != 'pending'
(i.e., at least 'draft' or higher)
Returns:
'mvp' or 'refinement'
"""
session = self.get_session()
try:
all_features = session.query(Feature).all()
# No features = MVP phase (will need initialization)
if not all_features:
return "mvp"
# Check if any features are still in 'pending' state
for feature in all_features:
state = feature.refinement_state or "pending"
if state == "pending":
return "mvp"
return "refinement"
finally:
session.close()
def _check_mvp_complete(self) -> bool:
"""Check if MVP phase is complete.
MVP is complete when all features have refinement_state in:
['draft', 'refined_code', 'refined_edge', 'refined_perf', 'refined_security', 'polished']
This means every feature has at least a working implementation (draft).
Returns:
True if MVP is complete, False otherwise.
"""
session = self.get_session()
try:
all_features = session.query(Feature).all()
# No features = MVP not complete
if not all_features:
return False
# MVP-complete states (not 'pending')
mvp_complete_states = {
"draft", "refined_code", "refined_edge",
"refined_perf", "refined_security", "polished"
}
for feature in all_features:
state = feature.refinement_state or "pending"
if state not in mvp_complete_states:
return False
return True
finally:
session.close()
def _auto_transition_to_refinement(self) -> None:
"""Auto-transition from MVP to Refinement phase if conditions are met.
Conditions:
- MVP is complete (all features at least 'draft')
- auto_transition is enabled in refinement config
- Currently in MVP phase
When transitioning:
- Updates self.phase to 'refinement'
- Logs the transition
- Sends WebSocket notification via on_status callback
"""
# Check if auto-transition is enabled
if not self.refinement_config.get("auto_transition", True):
return
# Check if we're currently in MVP phase
if self.phase != "mvp":
return
# Check if MVP is complete
if not self._check_mvp_complete():
return
# Transition to refinement phase
debug_log.log("PHASE", "Auto-transitioning from MVP to Refinement phase")
print("=" * 70, flush=True)
print(" MVP PHASE COMPLETE - TRANSITIONING TO REFINEMENT", flush=True)
print("=" * 70, flush=True)
print("All features have working implementations (draft).", flush=True)
print("Starting refinement passes: code_quality, edge_cases, performance, security, ux", flush=True)
print(flush=True)
self.phase = "refinement"
# Notify via status callback (UI can show phase change)
if self.on_status:
# Use feature_id 0 to indicate orchestrator-level status
self.on_status(0, f"phase_change:refinement")
def _mark_feature_draft(self, feature_id: int) -> bool:
"""Mark a feature as draft (MVP complete) in the database.
This is called when a feature passes during MVP phase to indicate
it has a working implementation and is ready for refinement.
Args:
feature_id: The ID of the feature to mark as draft.
Returns:
True if successfully marked, False otherwise.
"""
session = self.get_session()
try:
feature = session.query(Feature).filter(Feature.id == feature_id).first()
if not feature:
debug_log.log("REFINEMENT", f"Feature #{feature_id} not found for draft marking")
return False
# Only mark as draft if currently pending
current_state = feature.refinement_state or "pending"
if current_state != "pending":
debug_log.log("REFINEMENT", f"Feature #{feature_id} already in state '{current_state}', not marking as draft")
return False
# Update to draft state
feature.refinement_state = "draft"
session.commit()
debug_log.log("REFINEMENT", f"Feature #{feature_id} marked as draft (MVP complete)")
return True
except Exception as e:
session.rollback()
debug_log.log("REFINEMENT", f"Failed to mark feature #{feature_id} as draft: {e}")
return False
finally:
session.close()
def claim_feature_for_testing(self) -> int | None:
"""Claim a random passing feature for regression testing.
Returns the feature ID if successful, None if no features available.
Sets testing_in_progress=True on the claimed feature.
"""
session = self.get_session()
try:
from sqlalchemy.sql.expression import func
# Find a passing feature that's not being worked on
# Exclude features already being tested by this orchestrator
with self._lock:
testing_feature_ids = set(self.running_testing_agents.keys())
candidate = (
session.query(Feature)
.filter(Feature.passes == True)
.filter(Feature.in_progress == False)
.filter(Feature.testing_in_progress == False)
.filter(~Feature.id.in_(testing_feature_ids) if testing_feature_ids else True)
.order_by(func.random())
.first()
)
if not candidate:
return None
# Atomic claim using UPDATE with WHERE clause
result = session.execute(
text("""
UPDATE features
SET testing_in_progress = 1
WHERE id = :feature_id
AND passes = 1
AND in_progress = 0
AND testing_in_progress = 0
"""),
{"feature_id": candidate.id}
)
session.commit()
if result.rowcount == 0:
# Another process claimed it
return None
return candidate.id
except Exception as e:
session.rollback()
debug_log.log("TESTING", f"Failed to claim feature for testing: {e}")
return None
finally:
session.close()
def release_testing_claim(self, feature_id: int):
"""Release a testing claim on a feature (called when testing agent exits)."""
session = self.get_session()
try:
session.execute(
text("UPDATE features SET testing_in_progress = 0 WHERE id = :feature_id"),
{"feature_id": feature_id}
)
session.commit()
except Exception as e:
session.rollback()
debug_log.log("TESTING", f"Failed to release testing claim for feature {feature_id}: {e}")
finally:
session.close()
def get_resumable_features(self) -> list[dict]:
"""Get features that were left in_progress from a previous session.
These are features where in_progress=True but passes=False, and they're
not currently being worked on by this orchestrator. This handles the case
where a previous session was interrupted before completing the feature.
"""
session = self.get_session()
try:
# Force fresh read from database to avoid stale cached data
# This is critical when agent subprocesses have committed changes
session.expire_all()
# Find features that are in_progress but not complete
stale = session.query(Feature).filter(
Feature.in_progress == True,
Feature.passes == False
).all()
resumable = []
for f in stale:
# Skip if already running in this orchestrator instance
with self._lock:
if f.id in self.running_coding_agents:
continue
# Skip if feature has failed too many times
if self._failure_counts.get(f.id, 0) >= MAX_FEATURE_RETRIES:
continue
resumable.append(f.to_dict())
# Sort by scheduling score (higher = first), then priority, then id
all_dicts = [f.to_dict() for f in session.query(Feature).all()]
scores = compute_scheduling_scores(all_dicts)
resumable.sort(key=lambda f: (-scores.get(f["id"], 0), f["priority"], f["id"]))
return resumable
finally:
session.close()
def get_ready_features(self) -> list[dict]:
"""Get features with satisfied dependencies, not already running."""
session = self.get_session()
try:
# Force fresh read from database to avoid stale cached data
# This is critical when agent subprocesses have committed changes
session.expire_all()
all_features = session.query(Feature).all()
all_dicts = [f.to_dict() for f in all_features]
ready = []
skipped_reasons = {"passes": 0, "in_progress": 0, "running": 0, "failed": 0, "deps": 0}
for f in all_features:
if f.passes:
skipped_reasons["passes"] += 1
continue
if f.in_progress:
skipped_reasons["in_progress"] += 1
continue
# Skip if already running in this orchestrator
with self._lock:
if f.id in self.running_coding_agents:
skipped_reasons["running"] += 1
continue
# Skip if feature has failed too many times
if self._failure_counts.get(f.id, 0) >= MAX_FEATURE_RETRIES:
skipped_reasons["failed"] += 1
continue
# Check dependencies
if are_dependencies_satisfied(f.to_dict(), all_dicts):
ready.append(f.to_dict())
else:
skipped_reasons["deps"] += 1
# Sort by scheduling score (higher = first), then priority, then id
scores = compute_scheduling_scores(all_dicts)
ready.sort(key=lambda f: (-scores.get(f["id"], 0), f["priority"], f["id"]))
# Debug logging
passing = sum(1 for f in all_features if f.passes)
in_progress = sum(1 for f in all_features if f.in_progress and not f.passes)
print(
f"[DEBUG] get_ready_features: {len(ready)} ready, "
f"{passing} passing, {in_progress} in_progress, {len(all_features)} total",
flush=True
)
print(
f"[DEBUG] Skipped: {skipped_reasons['passes']} passing, {skipped_reasons['in_progress']} in_progress, "
f"{skipped_reasons['running']} running, {skipped_reasons['failed']} failed, {skipped_reasons['deps']} blocked by deps",
flush=True
)
# Log to debug file (but not every call to avoid spam)
debug_log.log("READY", "get_ready_features() called",
ready_count=len(ready),
ready_ids=[f['id'] for f in ready[:5]], # First 5 only
passing=passing,
in_progress=in_progress,
total=len(all_features),
skipped=skipped_reasons)
return ready
finally:
session.close()
def get_all_complete(self) -> bool:
"""Check if all features are complete or permanently failed.
Returns False if there are no features (initialization needed).
"""
session = self.get_session()
try:
# Force fresh read from database to avoid stale cached data
# This is critical when agent subprocesses have committed changes
session.expire_all()
all_features = session.query(Feature).all()
# No features = NOT complete, need initialization
if len(all_features) == 0:
return False
passing_count = 0
failed_count = 0
pending_count = 0
for f in all_features:
if f.passes:
passing_count += 1
continue # Completed successfully
if self._failure_counts.get(f.id, 0) >= MAX_FEATURE_RETRIES:
failed_count += 1
continue # Permanently failed, count as "done"
pending_count += 1
total = len(all_features)
is_complete = pending_count == 0
print(
f"[DEBUG] get_all_complete: {passing_count}/{total} passing, "
f"{failed_count} failed, {pending_count} pending -> {is_complete}",
flush=True
)
return is_complete
finally:
session.close()
def get_passing_count(self) -> int:
"""Get the number of passing features."""
session = self.get_session()
try:
session.expire_all()
return session.query(Feature).filter(Feature.passes == True).count()
finally:
session.close()
def _update_feature_git_info(
self,
feature_id: int,
branch_name: str | None = None,
worktree_path: str | None = None,
commit_sha: str | None = None,
pr_number: int | None = None,
pr_url: str | None = None,
pr_status: str | None = None,
) -> None:
"""Update git-related fields for a feature in the database.
Args:
feature_id: The ID of the feature to update.
branch_name: Git branch name (e.g., 'feature/42-user-login').
worktree_path: Path to the git worktree directory.
commit_sha: Git commit SHA (40 characters).
pr_number: Pull request number.
pr_url: Pull request URL.
pr_status: Pull request status (e.g., 'open', 'merged').
"""
session = self.get_session()
try:
feature = session.query(Feature).filter(Feature.id == feature_id).first()
if not feature:
debug_log.log("GIT", f"Feature {feature_id} not found for git info update")
return
if branch_name is not None:
feature.branch_name = branch_name
if worktree_path is not None:
feature.worktree_path = worktree_path
if commit_sha is not None:
feature.commit_sha = commit_sha
if pr_number is not None:
feature.pr_number = pr_number
if pr_url is not None:
feature.pr_url = pr_url
if pr_status is not None:
feature.pr_status = pr_status
session.commit()
debug_log.log("GIT", f"Updated git info for feature #{feature_id}",
branch_name=branch_name,
worktree_path=worktree_path,
commit_sha=commit_sha,
pr_number=pr_number)
except Exception as e:
session.rollback()
debug_log.log("GIT", f"Failed to update git info for feature #{feature_id}: {e}")
finally:
session.close()
def _finalize_git_for_feature(self, feature_id: int) -> None:
"""Finalize git operations for a completed feature.
Commits changes, pushes branch, and optionally creates a PR based on
git_config settings. Called when a coding agent successfully completes
a feature.
Args:
feature_id: The ID of the completed feature.
"""
if not self.git_config.get("enabled"):
return
# Get feature details
session = self.get_session()
try:
feature = session.query(Feature).filter(Feature.id == feature_id).first()
if not feature:
debug_log.log("GIT", f"Feature {feature_id} not found for git finalization")
return
# Determine working directory
work_dir = Path(feature.worktree_path) if feature.worktree_path else self.project_dir
branch_name = feature.branch_name
if not branch_name:
debug_log.log("GIT", f"No branch name for feature #{feature_id}, skipping git finalization")
return
debug_log.log("GIT", f"Finalizing git for feature #{feature_id}",
work_dir=str(work_dir),
branch_name=branch_name)
finally:
session.close()
# Auto-commit if enabled
if self.git_config.get("auto_commit"):
commit_message = f"feat: implement feature #{feature_id} - {feature.name if feature else 'unknown'}"
success, output = commit_changes(work_dir, commit_message)
if success:
debug_log.log("GIT", f"Committed changes for feature #{feature_id}")
# Update commit SHA
sha = get_commit_sha(work_dir)
if sha:
self._update_feature_git_info(feature_id, commit_sha=sha)
else:
debug_log.log("GIT", f"Commit failed for feature #{feature_id}: {output}")
# Push branch
success, output = push_branch(work_dir, branch_name)
if success:
debug_log.log("GIT", f"Pushed branch for feature #{feature_id}")
else:
debug_log.log("GIT", f"Push failed for feature #{feature_id}: {output}")
# Auto-PR if enabled
if self.git_config.get("auto_pr"):
target_branch = self.git_config.get("pr_target_branch", "main")
pr_title = f"feat: {feature.name if feature else f'Feature #{feature_id}'}"
pr_body = f"Implements feature #{feature_id}.\n\nGenerated by Autocoder."
pr_number, pr_url_or_error = create_pr(work_dir, pr_title, pr_body, target_branch)
if pr_number:
debug_log.log("GIT", f"Created PR #{pr_number} for feature #{feature_id}")
self._update_feature_git_info(
feature_id,
pr_number=pr_number,
pr_url=pr_url_or_error,
pr_status="open"
)
else:
debug_log.log("GIT", f"PR creation failed for feature #{feature_id}: {pr_url_or_error}")
def _cleanup_stale_testing_locks(self) -> None:
"""Release stale testing locks from crashed testing agents.
A feature is considered stale if:
- testing_in_progress=True AND
- last_tested_at is NOT NULL AND older than STALE_TESTING_LOCK_MINUTES
Note: We do NOT release features with last_tested_at=NULL because that would
incorrectly release features that are legitimately in the middle of their
first test. The last_tested_at is only set when testing completes.
This handles the case where a testing agent crashes mid-test, leaving
the feature locked until orchestrator restart. By checking periodically,
we can release these locks without requiring a restart.
"""
session = self.get_session()
try:
# Use timezone-aware UTC, then strip timezone for SQLite compatibility
# (SQLite stores datetimes as naive strings, but we want consistency with
# datetime.now(timezone.utc) used elsewhere in the codebase)
cutoff_time = (datetime.now(timezone.utc) - timedelta(minutes=STALE_TESTING_LOCK_MINUTES)).replace(tzinfo=None)
# Find stale locks: testing_in_progress=True AND last_tested_at < cutoff
# Excludes NULL last_tested_at to avoid false positives on first-time tests
stale_features = (
session.query(Feature)
.filter(Feature.testing_in_progress == True)
.filter(Feature.last_tested_at.isnot(None))
.filter(Feature.last_tested_at < cutoff_time)
.all()
)
if stale_features:
stale_ids = [f.id for f in stale_features]
# Use ORM update instead of raw SQL for SQLite IN clause compatibility
session.query(Feature).filter(Feature.id.in_(stale_ids)).update(
{"testing_in_progress": False},
synchronize_session=False
)
session.commit()
print(f"[CLEANUP] Released {len(stale_ids)} stale testing locks: {stale_ids}", flush=True)
debug_log.log("CLEANUP", "Released stale testing locks", feature_ids=stale_ids)
except Exception as e:
session.rollback()
print(f"[CLEANUP] Error cleaning stale locks: {e}", flush=True)
debug_log.log("CLEANUP", f"Error cleaning stale locks: {e}")
finally:
session.close()
def _maintain_testing_agents(self) -> None:
"""Maintain the desired count of testing agents independently.
This runs every loop iteration and spawns testing agents as needed to maintain
the configured testing_agent_ratio. Testing agents run independently from
coding agents and continuously re-test passing features to catch regressions.
Also periodically releases stale testing locks (features stuck in
testing_in_progress=True for more than STALE_TESTING_LOCK_MINUTES).
Stops spawning when:
- YOLO mode is enabled
- testing_agent_ratio is 0
- No passing features exist yet
"""
# Skip if testing is disabled
if self.yolo_mode or self.testing_agent_ratio == 0:
return
# Periodically clean up stale testing locks (features stuck mid-test due to crash)
# A feature is considered stale if testing_in_progress=True and last_tested_at
# is either NULL or older than STALE_TESTING_LOCK_MINUTES
self._cleanup_stale_testing_locks()
# No testing until there are passing features
passing_count = self.get_passing_count()
if passing_count == 0:
return
# Spawn testing agents one at a time, re-checking limits each time
# This avoids TOCTOU race by holding lock during the decision
while True:
# Check limits and decide whether to spawn (atomically)
with self._lock:
current_testing = len(self.running_testing_agents)
desired = self.testing_agent_ratio
total_agents = len(self.running_coding_agents) + current_testing
# Check if we need more testing agents
if current_testing >= desired:
return # Already at desired count
# Check hard limit on total agents
if total_agents >= MAX_TOTAL_AGENTS:
return # At max total agents
# We're going to spawn - log while still holding lock
spawn_index = current_testing + 1
debug_log.log("TESTING", f"Spawning testing agent ({spawn_index}/{desired})",
passing_count=passing_count)
# Spawn outside lock (I/O bound operation)
print(f"[DEBUG] Spawning testing agent ({spawn_index}/{desired})", flush=True)
self._spawn_testing_agent()
def start_feature(self, feature_id: int, resume: bool = False) -> tuple[bool, str]:
"""Start a single coding agent for a feature.
Args:
feature_id: ID of the feature to start
resume: If True, resume a feature that's already in_progress from a previous session
Returns:
Tuple of (success, message)
"""
with self._lock:
if feature_id in self.running_coding_agents:
return False, "Feature already running"
if len(self.running_coding_agents) >= self.max_concurrency:
return False, "At max concurrency"
# Enforce hard limit on total agents (coding + testing)
total_agents = len(self.running_coding_agents) + len(self.running_testing_agents)
if total_agents >= MAX_TOTAL_AGENTS:
return False, f"At max total agents ({total_agents}/{MAX_TOTAL_AGENTS})"
# Mark as in_progress in database (or verify it's resumable)
session = self.get_session()
try:
feature = session.query(Feature).filter(Feature.id == feature_id).first()
if not feature:
return False, "Feature not found"
if feature.passes:
return False, "Feature already complete"
if resume:
# Resuming: feature should already be in_progress
if not feature.in_progress:
return False, "Feature not in progress, cannot resume"
else:
# Starting fresh: feature should not be in_progress
if feature.in_progress:
return False, "Feature already in progress"
feature.in_progress = True
session.commit()
finally:
session.close()
# Start coding agent subprocess
success, message = self._spawn_coding_agent(feature_id)
if not success:
return False, message
# NOTE: Testing agents are now maintained independently via _maintain_testing_agents()
# called in the main loop, rather than being spawned when coding agents start.
return True, f"Started feature {feature_id}"
def _spawn_coding_agent(self, feature_id: int) -> tuple[bool, str]:
"""Spawn a coding agent subprocess for a specific feature.
If git workflow is enabled, creates a branch and worktree for the feature
before spawning the agent. The agent subprocess will run in the worktree
directory for isolation.
"""
# Create abort event
abort_event = threading.Event()
# Determine working directory (may be modified by git workflow)
work_dir = self.project_dir
branch_name = None
worktree_path = None
# Git workflow: create branch and worktree if enabled
if self.git_config.get("enabled") and self.git_config.get("auto_branch"):
# Check if project is a git repo
if is_git_repo(self.project_dir):
# Get feature name for branch generation
session = self.get_session()
try:
feature = session.query(Feature).filter(Feature.id == feature_id).first()
feature_name = feature.name if feature else f"feature-{feature_id}"
finally:
session.close()
# Generate branch name
branch_name = generate_branch_name(feature_id, feature_name)
debug_log.log("GIT", f"Creating branch for feature #{feature_id}",
branch_name=branch_name)
# Create worktree for parallel isolation
worktree_result, worktree_msg = create_worktree(
self.project_dir, feature_id, branch_name
)
if worktree_result:
worktree_path = str(worktree_result)
work_dir = worktree_result
debug_log.log("GIT", f"Created worktree for feature #{feature_id}",
worktree_path=worktree_path)
else:
debug_log.log("GIT", f"Worktree creation failed for feature #{feature_id}: {worktree_msg}")
# Update feature with git info
self._update_feature_git_info(
feature_id,
branch_name=branch_name,
worktree_path=worktree_path
)
else:
debug_log.log("GIT", f"Project is not a git repo, skipping git workflow")
# Start subprocess for this feature
cmd = [
sys.executable,
"-u", # Force unbuffered stdout/stderr
str(AUTOCODER_ROOT / "autonomous_agent_demo.py"),
"--project-dir", str(work_dir), # Use worktree path if available
"--max-iterations", "1",
"--agent-type", "coding",
"--feature-id", str(feature_id),
]
if self.model:
cmd.extend(["--model", self.model])
if self.yolo_mode:
cmd.append("--yolo")
if self.brownfield_mode:
cmd.append("--brownfield")
try:
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
cwd=str(work_dir), # Use worktree path as cwd
env={**os.environ, "PYTHONUNBUFFERED": "1"},
)
except Exception as e:
# Reset in_progress on failure
session = self.get_session()
try:
feature = session.query(Feature).filter(Feature.id == feature_id).first()
if feature:
feature.in_progress = False
session.commit()
finally:
session.close()
return False, f"Failed to start agent: {e}"
with self._lock:
self.running_coding_agents[feature_id] = proc
self.abort_events[feature_id] = abort_event
# Start output reader thread
threading.Thread(
target=self._read_output,
args=(feature_id, proc, abort_event, "coding"),
daemon=True
).start()
if self.on_status:
self.on_status(feature_id, "running")
print(f"Started coding agent for feature #{feature_id}", flush=True)
return True, f"Started feature {feature_id}"
def _spawn_testing_agent(self) -> tuple[bool, str]:
"""Spawn a testing agent subprocess for regression testing.