-
Notifications
You must be signed in to change notification settings - Fork 397
Expand file tree
/
Copy pathparallel_orchestrator.py
More file actions
1870 lines (1595 loc) · 78.9 KB
/
parallel_orchestrator.py
File metadata and controls
1870 lines (1595 loc) · 78.9 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 atexit
import logging
import os
import re
import signal
import subprocess
import sys
import threading
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, 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 progress import has_features
from server.utils.process_utils import kill_process_tree
logger = logging.getLogger(__name__)
# Root directory of autoforge (where this script and autonomous_agent_demo.py live)
AUTOFORGE_ROOT = Path(__file__).parent.resolve()
# Debug log file path
DEBUG_LOG_FILE = AUTOFORGE_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(feature_dicts: list[dict], label: str = ""):
"""Helper to dump full database state to debug log.
Args:
feature_dicts: Pre-fetched list of feature dicts.
label: Optional label for the dump entry.
"""
passing = [f for f in feature_dicts if f.get("passes")]
in_progress = [f for f in feature_dicts if f.get("in_progress") and not f.get("passes")]
pending = [f for f in feature_dicts if not f.get("passes") and not f.get("in_progress")]
debug_log.log("DB_DUMP", f"Full database state {label}",
total_features=len(feature_dicts),
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
DEFAULT_TESTING_BATCH_SIZE = 3 # Number of features per testing batch (1-5)
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
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 = None,
yolo_mode: bool = False,
testing_agent_ratio: int = 1,
testing_batch_size: int = DEFAULT_TESTING_BATCH_SIZE,
batch_size: int = 3,
on_output: Callable[[int, str], None] | None = None,
on_status: Callable[[int, str], None] | 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.
testing_batch_size: Number of features to include per testing session (1-5).
Each testing agent receives this many features to regression test.
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.testing_agent_ratio = min(max(testing_agent_ratio, 0), 3) # Clamp 0-3
self.testing_batch_size = min(max(testing_batch_size, 1), 5) # Clamp 1-5
self.batch_size = min(max(batch_size, 1), 3) # Clamp 1-3
self.on_output = on_output
self.on_status = on_status
# Thread-safe state
self._lock = threading.Lock()
# Coding agents: feature_id -> process
# Safe to key by feature_id because start_feature() checks for duplicates before spawning
self.running_coding_agents: dict[int, subprocess.Popen] = {}
# Testing agents: pid -> (feature_id, process)
# Keyed by PID (not feature_id) because multiple agents can test the same feature
self.running_testing_agents: dict[int, tuple[int, subprocess.Popen]] = {}
# Legacy alias for backward compatibility
self.running_agents = self.running_coding_agents
self.abort_events: dict[int, threading.Event] = {}
self._testing_session_counter = 0
self.is_running = False
# Track feature failures to prevent infinite retry loops
self._failure_counts: dict[int, int] = {}
# Track recently tested feature IDs to avoid redundant re-testing.
# Cleared when all passing features have been covered at least once.
self._recently_tested: set[int] = set()
# Batch tracking: primary feature_id -> all feature IDs in batch
self._batch_features: dict[int, list[int]] = {}
# Reverse mapping: any feature_id -> primary feature_id
self._feature_to_primary: dict[int, int] = {}
# Shutdown flag for async-safe signal handling
# Signal handlers only set this flag; cleanup happens in the main loop
self._shutdown_requested = False
# Graceful pause (drain mode) flag
self._drain_requested = False
# Session tracking for logging/debugging
self.session_start_time: datetime | None = None
# Event signaled when any agent completes, allowing the main loop to wake
# immediately instead of waiting for the full POLL_INTERVAL timeout.
# This reduces latency when spawning the next feature after completion.
self._agent_completed_event: asyncio.Event | None = None # Created in run_loop
self._event_loop: asyncio.AbstractEventLoop | None = None # Stored for thread-safe signaling
# Database session for this orchestrator
self._engine, self._session_maker = create_database(project_dir)
def get_session(self):
"""Get a new database session."""
return self._session_maker()
def _get_random_passing_feature(self) -> int | None:
"""Get a random passing feature for regression testing (no claim needed).
Testing agents can test the same feature concurrently - it doesn't matter.
This simplifies the architecture by removing unnecessary coordination.
Returns the feature ID if available, None if no passing features exist.
Note: Prefer _get_test_batch() for batch testing mode. This method is
retained for backward compatibility.
"""
from sqlalchemy.sql.expression import func
session = self.get_session()
try:
# Find a passing feature that's not currently being coded
# Multiple testing agents can test the same feature - that's fine
feature = (
session.query(Feature)
.filter(Feature.passes == True)
.filter(Feature.in_progress == False) # Don't test while coding
.order_by(func.random())
.first()
)
return feature.id if feature else None
finally:
session.close()
def _get_test_batch(self, batch_size: int = 3) -> list[int]:
"""Select a prioritized batch of passing features for regression testing.
Uses weighted scoring to prioritize features that:
1. Haven't been tested recently in this orchestrator session
2. Are depended on by many other features (higher impact if broken)
3. Have more dependencies themselves (complex integration points)
When all passing features have been recently tested, the tracking set
is cleared so the cycle starts fresh.
Args:
batch_size: Maximum number of feature IDs to return (1-5).
Returns:
List of feature IDs to test, may be shorter than batch_size if
fewer passing features are available. Empty list if none available.
"""
session = self.get_session()
try:
session.expire_all()
passing = (
session.query(Feature)
.filter(Feature.passes == True)
.filter(Feature.in_progress == False) # Don't test while coding
.all()
)
# Extract data from ORM objects before closing the session to avoid
# DetachedInstanceError when accessing attributes after session.close().
passing_data: list[dict] = []
for f in passing:
passing_data.append({
'id': f.id,
'dependencies': f.get_dependencies_safe() if hasattr(f, 'get_dependencies_safe') else [],
})
finally:
session.close()
if not passing_data:
return []
# Build a reverse dependency map: feature_id -> count of features that depend on it.
# The Feature model stores dependencies (what I depend ON), so we invert to find
# dependents (what depends ON me).
dependent_counts: dict[int, int] = {}
for fd in passing_data:
for dep_id in fd['dependencies']:
dependent_counts[dep_id] = dependent_counts.get(dep_id, 0) + 1
# Exclude features that are already being tested by running testing agents
# to avoid redundant concurrent testing of the same features.
# running_testing_agents is dict[pid, (primary_feature_id, process)]
with self._lock:
currently_testing_ids: set[int] = set()
for _pid, (feat_id, _proc) in self.running_testing_agents.items():
currently_testing_ids.add(feat_id)
# If all passing features have been recently tested, reset the tracker
# so we cycle through them again rather than returning empty batches.
passing_ids = {fd['id'] for fd in passing_data}
if passing_ids.issubset(self._recently_tested):
self._recently_tested.clear()
# Score each feature by testing priority
scored: list[tuple[int, int]] = []
for fd in passing_data:
f_id = fd['id']
# Skip features already being tested by a running testing agent
if f_id in currently_testing_ids:
continue
score = 0
# Weight 1: Features depended on by many others are higher impact
# if they regress, so test them more often
score += dependent_counts.get(f_id, 0) * 2
# Weight 2: Strongly prefer features not tested recently
if f_id not in self._recently_tested:
score += 5
# Weight 3: Features with more dependencies are integration points
# that are more likely to regress when other code changes
dep_count = len(fd['dependencies'])
score += min(dep_count, 3) # Cap at 3 to avoid over-weighting
scored.append((f_id, score))
# Sort by score descending (highest priority first)
scored.sort(key=lambda x: x[1], reverse=True)
selected = [fid for fid, _ in scored[:batch_size]]
# Track what we've tested to avoid re-testing the same features next batch
self._recently_tested.update(selected)
debug_log.log("TEST_BATCH", f"Selected {len(selected)} features for testing batch",
selected_ids=selected,
recently_tested_count=len(self._recently_tested),
total_passing=len(passing_data))
return selected
def build_feature_batches(
self,
ready: list[dict],
all_features: list[dict],
scheduling_scores: dict[int, float],
) -> list[list[dict]]:
"""Build dependency-aware feature batches for coding agents.
Each batch contains up to `batch_size` features. The algorithm:
1. Start with a ready feature (sorted by scheduling score)
2. Chain extension: find dependents whose deps are satisfied if earlier batch features pass
3. Same-category fill: fill remaining slots with ready features from the same category
Args:
ready: Ready features (sorted by scheduling score)
all_features: All features for dependency checking
scheduling_scores: Pre-computed scheduling scores
Returns:
List of batches, each batch is a list of feature dicts
"""
if self.batch_size <= 1:
# No batching - return each feature as a single-item batch
return [[f] for f in ready]
# Build children adjacency: parent_id -> [child_ids]
children: dict[int, list[int]] = {f["id"]: [] for f in all_features}
feature_map: dict[int, dict] = {f["id"]: f for f in all_features}
for f in all_features:
for dep_id in (f.get("dependencies") or []):
if dep_id in children:
children[dep_id].append(f["id"])
# Pre-compute passing IDs
passing_ids = {f["id"] for f in all_features if f.get("passes")}
used_ids: set[int] = set() # Features already assigned to a batch
batches: list[list[dict]] = []
for feature in ready:
if feature["id"] in used_ids:
continue
batch = [feature]
used_ids.add(feature["id"])
# Simulate passing set = real passing + batch features
simulated_passing = passing_ids | {feature["id"]}
# Phase 1: Chain extension - find dependents whose deps are met
for _ in range(self.batch_size - 1):
best_candidate = None
best_score = -1.0
# Check children of all features currently in the batch
candidate_ids: set[int] = set()
for bf in batch:
for child_id in children.get(bf["id"], []):
if child_id not in used_ids and child_id not in simulated_passing:
candidate_ids.add(child_id)
for cid in candidate_ids:
cf = feature_map.get(cid)
if not cf or cf.get("passes") or cf.get("in_progress"):
continue
# Check if ALL deps are satisfied by simulated passing set
deps = cf.get("dependencies") or []
if all(d in simulated_passing for d in deps):
score = scheduling_scores.get(cid, 0)
if score > best_score:
best_score = score
best_candidate = cf
if best_candidate:
batch.append(best_candidate)
used_ids.add(best_candidate["id"])
simulated_passing.add(best_candidate["id"])
else:
break
# Phase 2: Same-category fill
if len(batch) < self.batch_size:
category = feature.get("category", "")
for rf in ready:
if len(batch) >= self.batch_size:
break
if rf["id"] in used_ids:
continue
if rf.get("category", "") == category:
batch.append(rf)
used_ids.add(rf["id"])
batches.append(batch)
debug_log.log("BATCH", f"Built {len(batches)} batches from {len(ready)} ready features",
batch_sizes=[len(b) for b in batches],
batch_ids=[[f['id'] for f in b] for b in batches[:5]])
return batches
def get_resumable_features(
self,
feature_dicts: list[dict] | None = None,
scheduling_scores: dict[int, float] | None = None,
) -> 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.
Args:
feature_dicts: Pre-fetched list of feature dicts. If None, queries the database.
scheduling_scores: Pre-computed scheduling scores. If None, computed from feature_dicts.
"""
if feature_dicts is None:
session = self.get_session()
try:
session.expire_all()
all_features = session.query(Feature).all()
feature_dicts = [f.to_dict() for f in all_features]
finally:
session.close()
# Snapshot running IDs once (include all batch feature IDs)
with self._lock:
running_ids = set(self.running_coding_agents.keys())
for batch_ids in self._batch_features.values():
running_ids.update(batch_ids)
resumable = []
for fd in feature_dicts:
if not fd.get("in_progress") or fd.get("passes"):
continue
# Skip if blocked for human input
if fd.get("needs_human_input"):
continue
# Skip if already running in this orchestrator instance
if fd["id"] in running_ids:
continue
# Skip if feature has failed too many times
if self._failure_counts.get(fd["id"], 0) >= MAX_FEATURE_RETRIES:
continue
resumable.append(fd)
# Sort by scheduling score (higher = first), then priority, then id
if scheduling_scores is None:
scheduling_scores = compute_scheduling_scores(feature_dicts)
resumable.sort(key=lambda f: (-scheduling_scores.get(f["id"], 0), f["priority"], f["id"]))
return resumable
def get_ready_features(
self,
feature_dicts: list[dict] | None = None,
scheduling_scores: dict[int, float] | None = None,
) -> list[dict]:
"""Get features with satisfied dependencies, not already running.
Args:
feature_dicts: Pre-fetched list of feature dicts. If None, queries the database.
scheduling_scores: Pre-computed scheduling scores. If None, computed from feature_dicts.
"""
if feature_dicts is None:
session = self.get_session()
try:
session.expire_all()
all_features = session.query(Feature).all()
feature_dicts = [f.to_dict() for f in all_features]
finally:
session.close()
# Pre-compute passing_ids once to avoid O(n^2) in the loop
passing_ids = {fd["id"] for fd in feature_dicts if fd.get("passes")}
# Snapshot running IDs once (include all batch feature IDs)
with self._lock:
running_ids = set(self.running_coding_agents.keys())
for batch_ids in self._batch_features.values():
running_ids.update(batch_ids)
ready = []
skipped_reasons = {"passes": 0, "in_progress": 0, "running": 0, "failed": 0, "deps": 0, "needs_human_input": 0}
for fd in feature_dicts:
if fd.get("passes"):
skipped_reasons["passes"] += 1
continue
if fd.get("needs_human_input"):
skipped_reasons["needs_human_input"] += 1
continue
if fd.get("in_progress"):
skipped_reasons["in_progress"] += 1
continue
# Skip if already running in this orchestrator
if fd["id"] in running_ids:
skipped_reasons["running"] += 1
continue
# Skip if feature has failed too many times
if self._failure_counts.get(fd["id"], 0) >= MAX_FEATURE_RETRIES:
skipped_reasons["failed"] += 1
continue
# Check dependencies (pass pre-computed passing_ids)
if are_dependencies_satisfied(fd, feature_dicts, passing_ids):
ready.append(fd)
else:
skipped_reasons["deps"] += 1
# Sort by scheduling score (higher = first), then priority, then id
if scheduling_scores is None:
scheduling_scores = compute_scheduling_scores(feature_dicts)
ready.sort(key=lambda f: (-scheduling_scores.get(f["id"], 0), f["priority"], f["id"]))
# Summary counts for logging
passing = skipped_reasons["passes"]
in_progress = skipped_reasons["in_progress"]
total = len(feature_dicts)
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=total,
skipped=skipped_reasons)
return ready
def get_all_complete(self, feature_dicts: list[dict] | None = None) -> bool:
"""Check if all features are complete or permanently failed.
Returns False if there are no features (initialization needed).
Args:
feature_dicts: Pre-fetched list of feature dicts. If None, queries the database.
"""
if feature_dicts is None:
session = self.get_session()
try:
session.expire_all()
all_features = session.query(Feature).all()
feature_dicts = [f.to_dict() for f in all_features]
finally:
session.close()
# No features = NOT complete, need initialization
if len(feature_dicts) == 0:
return False
passing_count = 0
failed_count = 0
pending_count = 0
for fd in feature_dicts:
if fd.get("passes"):
passing_count += 1
continue # Completed successfully
if self._failure_counts.get(fd["id"], 0) >= MAX_FEATURE_RETRIES:
failed_count += 1
continue # Permanently failed, count as "done"
pending_count += 1
total = len(feature_dicts)
is_complete = pending_count == 0
debug_log.log("COMPLETE_CHECK", f"get_all_complete: {passing_count}/{total} passing, "
f"{failed_count} failed, {pending_count} pending -> {is_complete}")
return is_complete
def get_passing_count(self, feature_dicts: list[dict] | None = None) -> int:
"""Get the number of passing features.
Args:
feature_dicts: Pre-fetched list of feature dicts. If None, queries the database.
"""
if feature_dicts is None:
session = self.get_session()
try:
session.expire_all()
count: int = session.query(Feature).filter(Feature.passes == True).count()
return count
finally:
session.close()
return sum(1 for fd in feature_dicts if fd.get("passes"))
def _maintain_testing_agents(self, feature_dicts: list[dict] | None = None) -> 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.
Multiple testing agents can test the same feature concurrently - this is
intentional and simplifies the architecture by removing claim coordination.
Stops spawning when:
- YOLO mode is enabled
- testing_agent_ratio is 0
- No passing features exist yet
Args:
feature_dicts: Pre-fetched list of feature dicts. If None, queries the database.
"""
# Skip if testing is disabled
if self.yolo_mode or self.testing_agent_ratio == 0:
return
# No testing until there are passing features
passing_count = self.get_passing_count(feature_dicts)
if passing_count == 0:
return
# Don't spawn testing agents if all features are already complete
if self.get_all_complete(feature_dicts):
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)
logger.debug("Spawning testing agent (%d/%d)", spawn_index, desired)
success, msg = self._spawn_testing_agent()
if not success:
debug_log.log("TESTING", f"Spawn failed, stopping: {msg}")
return
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 start_feature_batch(self, feature_ids: list[int], resume: bool = False) -> tuple[bool, str]:
"""Start a coding agent for a batch of features.
Args:
feature_ids: List of feature IDs to implement in batch
resume: If True, resume features already in_progress
Returns:
Tuple of (success, message)
"""
if not feature_ids:
return False, "No features to start"
# Single feature falls back to start_feature
if len(feature_ids) == 1:
return self.start_feature(feature_ids[0], resume=resume)
with self._lock:
# Check if any feature in batch is already running
for fid in feature_ids:
if fid in self.running_coding_agents or fid in self._feature_to_primary:
return False, f"Feature {fid} already running"
if len(self.running_coding_agents) >= self.max_concurrency:
return False, "At max concurrency"
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 all features as in_progress in a single transaction
session = self.get_session()
try:
features_to_mark = []
for fid in feature_ids:
feature = session.query(Feature).filter(Feature.id == fid).first()
if not feature:
return False, f"Feature {fid} not found"
if feature.passes:
return False, f"Feature {fid} already complete"
if not resume:
if feature.in_progress:
return False, f"Feature {fid} already in progress"
features_to_mark.append(feature)
else:
if not feature.in_progress:
return False, f"Feature {fid} not in progress, cannot resume"
for feature in features_to_mark:
feature.in_progress = True
session.commit()
finally:
session.close()
# Spawn batch coding agent
success, message = self._spawn_coding_agent_batch(feature_ids)
if not success:
# Clear in_progress on failure
session = self.get_session()
try:
for fid in feature_ids:
feature = session.query(Feature).filter(Feature.id == fid).first()
if feature and not resume:
feature.in_progress = False
session.commit()
finally:
session.close()
return False, message
return True, f"Started batch [{', '.join(str(fid) for fid in feature_ids)}]"
def _spawn_coding_agent(self, feature_id: int) -> tuple[bool, str]:
"""Spawn a coding agent subprocess for a specific feature."""
# Create abort event
abort_event = threading.Event()
# Start subprocess for this feature
cmd = [
sys.executable,
"-u", # Force unbuffered stdout/stderr
str(AUTOFORGE_ROOT / "autonomous_agent_demo.py"),
"--project-dir", str(self.project_dir),
"--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")
try:
# CREATE_NO_WINDOW on Windows prevents console window pop-ups
# stdin=DEVNULL prevents blocking on stdin reads
# encoding="utf-8" and errors="replace" fix Windows CP1252 issues
popen_kwargs: dict[str, Any] = {
"stdin": subprocess.DEVNULL,
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"text": True,
"encoding": "utf-8",
"errors": "replace",
"cwd": str(self.project_dir), # Run from project dir so CLI creates .claude/ in project
"env": {**os.environ, "PYTHONUNBUFFERED": "1", "NODE_COMPILE_CACHE": "", "PLAYWRIGHT_CLI_SESSION": f"coding-{feature_id}"},
}
if sys.platform == "win32":
popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
proc = subprocess.Popen(cmd, **popen_kwargs)
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 is not None:
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_coding_agent_batch(self, feature_ids: list[int]) -> tuple[bool, str]:
"""Spawn a coding agent subprocess for a batch of features."""
primary_id = feature_ids[0]
abort_event = threading.Event()
cmd = [
sys.executable,
"-u",
str(AUTOFORGE_ROOT / "autonomous_agent_demo.py"),
"--project-dir", str(self.project_dir),
"--max-iterations", "1",
"--agent-type", "coding",
"--feature-ids", ",".join(str(fid) for fid in feature_ids),
]
if self.model:
cmd.extend(["--model", self.model])
if self.yolo_mode:
cmd.append("--yolo")
try:
popen_kwargs: dict[str, Any] = {
"stdin": subprocess.DEVNULL,
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"text": True,
"encoding": "utf-8",
"errors": "replace",
"cwd": str(self.project_dir), # Run from project dir so CLI creates .claude/ in project
"env": {**os.environ, "PYTHONUNBUFFERED": "1", "NODE_COMPILE_CACHE": "", "PLAYWRIGHT_CLI_SESSION": f"coding-{primary_id}"},
}
if sys.platform == "win32":
popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
proc = subprocess.Popen(cmd, **popen_kwargs)
except Exception as e:
# Reset in_progress on failure
session = self.get_session()
try:
for fid in feature_ids:
feature = session.query(Feature).filter(Feature.id == fid).first()
if feature:
feature.in_progress = False
session.commit()
finally:
session.close()
return False, f"Failed to start batch agent: {e}"
with self._lock:
self.running_coding_agents[primary_id] = proc
self.abort_events[primary_id] = abort_event
self._batch_features[primary_id] = list(feature_ids)
for fid in feature_ids:
self._feature_to_primary[fid] = primary_id
# Start output reader thread
threading.Thread(
target=self._read_output,
args=(primary_id, proc, abort_event, "coding"),
daemon=True
).start()
if self.on_status is not None:
for fid in feature_ids:
self.on_status(fid, "running")
ids_str = ", ".join(f"#{fid}" for fid in feature_ids)
print(f"Started coding agent for features {ids_str}", flush=True)
return True, f"Started batch [{ids_str}]"
def _spawn_testing_agent(self) -> tuple[bool, str]:
"""Spawn a testing agent subprocess for batch regression testing.
Selects a prioritized batch of passing features using weighted scoring
(via _get_test_batch) and passes them as --testing-feature-ids to the
subprocess. Falls back to single --testing-feature-id for batches of one.
Multiple testing agents can test the same feature concurrently - this is
intentional and simplifies the architecture by removing claim coordination.
"""
# Check limits first (under lock)
with self._lock:
current_testing_count = len(self.running_testing_agents)
if current_testing_count >= self.max_concurrency:
debug_log.log("TESTING", f"Skipped spawn - at max testing agents ({current_testing_count}/{self.max_concurrency})")
return False, f"At max testing agents ({current_testing_count})"
total_agents = len(self.running_coding_agents) + len(self.running_testing_agents)
if total_agents >= MAX_TOTAL_AGENTS:
debug_log.log("TESTING", f"Skipped spawn - at max total agents ({total_agents}/{MAX_TOTAL_AGENTS})")
return False, f"At max total agents ({total_agents})"
# Select a weighted batch of passing features for regression testing
batch = self._get_test_batch(self.testing_batch_size)
if not batch:
debug_log.log("TESTING", "No features available for testing")
return False, "No features available for testing"
# Use the first feature ID as the representative for logging/tracking
primary_feature_id = batch[0]
batch_str = ",".join(str(fid) for fid in batch)
debug_log.log("TESTING", f"Selected batch for testing: [{batch_str}]")
# Spawn the testing agent
with self._lock:
# Re-check limits in case another thread spawned while we were selecting
current_testing_count = len(self.running_testing_agents)
if current_testing_count >= self.max_concurrency:
return False, f"At max testing agents ({current_testing_count})"