forked from Dicklesworthstone/claude_code_agent_farm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude_code_agent_farm.py
More file actions
2990 lines (2539 loc) · 129 KB
/
claude_code_agent_farm.py
File metadata and controls
2990 lines (2539 loc) · 129 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
#!/usr/bin/env python3
"""
Claude Code Agent Farm - Hybrid Orchestrator
Combines simplicity with robust monitoring and automatic agent management
"""
import contextlib
import fcntl
import json
import os
import re
import shlex
import signal
import subprocess
import sys
import tempfile
import textwrap
import time
from datetime import datetime
from pathlib import Path
from random import randint
from typing import Any, Dict, List, Optional, Tuple, Union
import typer
from rich import box
from rich.console import Console
from rich.live import Live
from rich.panel import Panel
from rich.progress import (
BarColumn,
MofNCompleteColumn,
Progress,
SpinnerColumn,
TextColumn,
)
from rich.prompt import Confirm
from rich.table import Table
app = typer.Typer(
rich_markup_mode="rich",
help="Orchestrate multiple Claude Code agents for parallel work using tmux",
context_settings={"help_option_names": ["-h", "--help"]},
)
console = Console(stderr=True) # Use stderr for progress/info so stdout remains clean
# ─────────────────────────────── Configuration ────────────────────────────── #
def interruptible_confirm(message: str, default: bool = False) -> bool:
"""Confirmation prompt that returns default on KeyboardInterrupt"""
try:
return Confirm.ask(message, default=default)
except KeyboardInterrupt:
console.print("\n[yellow]Interrupted - using default response[/yellow]")
return default
# ─────────────────────────────── Constants ────────────────────────────────── #
MONITOR_STATE_FILE = ".claude_agent_farm_state.json"
# ─────────────────────────────── Helper Functions ─────────────────────────── #
def run(cmd: str, *, check: bool = True, quiet: bool = False, capture: bool = False) -> Tuple[int, str, str]:
"""Execute shell command with optional output capture
When capture=False, output is streamed to terminal unless quiet=True
When capture=True, output is captured and returned
"""
if not quiet:
console.log(cmd, style="cyan")
# Parse command for shell safety when possible
cmd_arg: Union[str, List[str]]
try:
# Try to parse as a list of arguments for safer execution
cmd_list = shlex.split(cmd)
use_shell = False
cmd_arg = cmd_list
except ValueError:
# Fall back to shell=True for complex commands with pipes, redirects, etc.
cmd_list = [] # Not used when shell=True
use_shell = True
cmd_arg = cmd
if capture:
result = subprocess.run(cmd_arg, shell=use_shell, capture_output=True, text=True, check=check)
return result.returncode, result.stdout or "", result.stderr or ""
else:
# Stream output to terminal when not capturing
# Preserve stderr even in quiet-mode so that exceptions contain detail
if quiet:
result = subprocess.run(cmd_arg, shell=use_shell, capture_output=True, text=True, check=check)
return result.returncode, result.stdout or "", result.stderr or ""
stdout_pipe = None
stderr_pipe = subprocess.STDOUT
try:
result = subprocess.run(
cmd_arg, shell=use_shell, check=check, stdout=stdout_pipe, stderr=stderr_pipe, text=True
)
return result.returncode, "", ""
except subprocess.CalledProcessError as e:
console.print(f"[red]Command failed with exit code {e.returncode}: {cmd}[/red]")
raise
def line_count(file_path: Path) -> int:
"""Count lines in a file"""
try:
# Try UTF-8 first, then fall back to latin-1
try:
with file_path.open("r", encoding="utf-8") as f:
return sum(1 for _ in f)
except UnicodeDecodeError:
# Try common encodings
for encoding in ["latin-1", "cp1252", "iso-8859-1"]:
try:
with file_path.open("r", encoding=encoding) as f:
return sum(1 for _ in f)
except UnicodeDecodeError:
continue
# Last resort: ignore errors
with file_path.open("r", encoding="utf-8", errors="ignore") as f:
return sum(1 for _ in f)
except Exception as e:
console.print(f"[yellow]Warning: Could not count lines in {file_path}: {e}[/yellow]")
return 0
def tmux_send(target: str, data: str, enter: bool = True, update_heartbeat: bool = True) -> None:
"""Send keystrokes to a tmux pane (binary-safe)"""
max_retries = 3
base_delay = 0.5
for attempt in range(max_retries):
try:
if data:
# Use tmux buffer API for robustness with large payloads
# Create a temporary file with the data to avoid shell-quoting issues
import os
import tempfile
import uuid
with tempfile.NamedTemporaryFile("w", delete=False, encoding="utf-8") as tmp:
tmp.write(data)
tmp_path = tmp.name
buf_name = f"agentfarm_{uuid.uuid4().hex[:8]}"
try:
# Load the data into a tmux buffer
run(f"tmux load-buffer -b {buf_name} {shlex.quote(tmp_path)}", quiet=True)
# Paste the buffer into the target pane and delete the buffer (-d)
run(f"tmux paste-buffer -d -b {buf_name} -t {target}", quiet=True)
finally:
# Clean up temp file
with contextlib.suppress(FileNotFoundError):
os.unlink(tmp_path)
# CRITICAL: Small delay between pasting and Enter for Claude Code
if enter:
time.sleep(0.2)
if enter:
run(f"tmux send-keys -t {target} C-m", quiet=True)
# Update heartbeat if requested (default True)
if update_heartbeat:
# Extract agent ID from target (format: session:window.pane)
try:
pane_id = target.split('.')[-1]
agent_id = int(pane_id)
heartbeat_file = Path(".heartbeats") / f"agent{agent_id:02d}.heartbeat"
if heartbeat_file.parent.exists():
heartbeat_file.write_text(datetime.now().isoformat())
except (ValueError, IndexError, OSError):
# Silently ignore heartbeat errors
pass
break
except subprocess.CalledProcessError:
if attempt < max_retries - 1:
# Exponential backoff: 0.5s, 1s, 2s
time.sleep(base_delay * (2**attempt))
else:
raise
def tmux_capture(target: str) -> str:
"""Capture content from a tmux pane"""
max_retries = 3
for attempt in range(max_retries):
try:
_, stdout, _ = run(f"tmux capture-pane -t {target} -p", quiet=True, capture=True)
return stdout
except subprocess.CalledProcessError:
if attempt < max_retries - 1:
time.sleep(0.2)
else:
# Return empty string on persistent failure
return ""
return ""
# ─────────────────────────────── Agent Monitor ────────────────────────────── #
class AgentMonitor:
"""Monitors Claude Code agents for health and performance"""
def __init__(
self,
session: str,
num_agents: int,
pane_mapping: Dict[int, str],
context_threshold: int = 20,
idle_timeout: int = 60,
max_errors: int = 3,
project_path: Optional[Path] = None,
):
self.session = session
self.num_agents = num_agents
self.pane_mapping = pane_mapping
self.agents: Dict[int, Dict] = {}
self.running = True
self.start_time = datetime.now()
self.context_threshold = context_threshold
self.idle_timeout = idle_timeout
self.base_idle_timeout = idle_timeout # Keep original value as base
self.max_errors = max_errors
self.project_path = project_path
# Cycle time tracking for adaptive timeout
self.cycle_times: List[float] = []
self.max_cycle_history = 20 # Keep last 20 cycle times
# Setup heartbeats directory
self.heartbeats_dir: Optional[Path] = None
if self.project_path:
self.heartbeats_dir = self.project_path / ".heartbeats"
self.heartbeats_dir.mkdir(exist_ok=True)
# Clean up any old heartbeat files
for hb_file in self.heartbeats_dir.glob("agent*.heartbeat"):
hb_file.unlink(missing_ok=True)
# Initialize agent tracking
for i in range(num_agents):
self.agents[i] = {
"status": "starting",
"start_time": datetime.now(),
"cycles": 0,
"last_context": 100,
"errors": 0,
"last_activity": datetime.now(),
"restart_count": 0,
"last_restart": None,
"last_heartbeat": None,
"cycle_start_time": None,
}
def calculate_adaptive_timeout(self) -> int:
"""Calculate adaptive idle timeout based on median cycle time"""
if len(self.cycle_times) < 3:
# Not enough data, use base timeout
return self.base_idle_timeout
# Calculate median cycle time
sorted_times = sorted(self.cycle_times)
median_time = sorted_times[len(sorted_times) // 2]
# Set timeout to 3x median cycle time, but within reasonable bounds
adaptive_timeout = int(median_time * 3)
# Enforce minimum and maximum bounds
min_timeout = 30 # At least 30 seconds
max_timeout = 600 # At most 10 minutes
adaptive_timeout = max(min_timeout, min(adaptive_timeout, max_timeout))
# Only update if significantly different from current (>20% change)
if abs(adaptive_timeout - self.idle_timeout) / self.idle_timeout > 0.2:
console.print(f"[dim]Adjusting idle timeout: {self.idle_timeout}s → {adaptive_timeout}s (median cycle: {median_time:.1f}s)[/dim]")
self.idle_timeout = adaptive_timeout
return self.idle_timeout
def detect_context_percentage(self, content: str) -> Optional[int]:
"""Extract context percentage from pane content"""
# Try multiple patterns for robustness
patterns = [
r"Context left until\s*auto-compact:\s*(\d+)%",
r"Context remaining:\s*(\d+)%",
r"(\d+)%\s*context\s*remaining",
r"Context:\s*(\d+)%",
]
# Safety check for empty content
if not content:
return None
for pattern in patterns:
match = re.search(pattern, content, re.IGNORECASE)
if match:
return int(match.group(1))
return None
def is_claude_ready(self, content: str) -> bool:
"""Check if Claude Code is ready for input"""
# Multiple possible indicators that Claude is ready
ready_indicators = [
"Welcome to Claude Code!" in content, # Welcome message
("│ > Try" in content), # The prompt box with suggestion
("? for shortcuts" in content), # Shortcuts hint at bottom
("╰─" in content and "│ >" in content), # Box structure with prompt
("/help for help" in content), # Help text in welcome message
("cwd:" in content and "Welcome to Claude" in content), # Working directory shown
("Bypassing Permissions" in content and "│ >" in content), # May appear with prompt
("│ >" in content and "─╯" in content), # Prompt box bottom border
]
return any(ready_indicators)
def is_claude_working(self, content: str) -> bool:
"""Check if Claude Code is actively working"""
indicators = ["✻ Pontificating", "● Bash(", "✻ Running", "✻ Thinking", "esc to interrupt"]
return any(indicator in content for indicator in indicators)
def has_welcome_screen(self, content: str) -> bool:
"""Check if Claude Code is showing the welcome/setup screen"""
welcome_indicators = [
# Setup/onboarding screens only
"Choose the text style",
"Choose your language",
"Let's get started",
"run /theme",
"Dark mode✔",
"Light mode",
"colorblind-friendly",
# Remove "Welcome to Claude Code" as it appears when ready
]
return any(indicator in content for indicator in welcome_indicators)
def has_settings_error(self, content: str) -> bool:
"""Check for settings corruption"""
# First check if Claude is actually ready (avoid false positives)
if self.is_claude_ready(content):
return False
error_indicators = [
# Login/auth prompts
"Select login method:",
"Claude account with subscription",
"Sign in to Claude",
"Log in to Claude",
"Enter your API key",
"API key",
# Configuration errors
"Configuration error",
"Settings corrupted",
"Invalid API key",
"Authentication failed",
"Rate limit exceeded",
"Unauthorized",
"Permission denied",
"Failed to load configuration",
"Invalid configuration",
"Error loading settings",
"Settings file is corrupted",
"Failed to parse settings",
"Invalid settings",
"Corrupted settings",
"Config corrupted",
"configuration is corrupted",
"Unable to load settings",
"Error reading settings",
"Settings error",
"config error",
# Parse errors
"TypeError",
"SyntaxError",
"JSONDecodeError",
"ParseError",
# Other login-related text
"Choose your login method",
"Continue with Claude account",
"I have a Claude account",
"Create account",
]
return any(indicator in content for indicator in error_indicators)
def check_agent(self, agent_id: int) -> Dict:
"""Check status of a single agent"""
pane_target = self.pane_mapping.get(agent_id)
if not pane_target:
console.print(f"[red]Error: No pane mapping found for agent {agent_id}[/red]")
return self.agents[agent_id]
content = tmux_capture(pane_target)
agent = self.agents[agent_id]
# Update context percentage
context = self.detect_context_percentage(content)
if context is not None:
agent["last_context"] = context
# Check for errors
if self.has_settings_error(content):
agent["status"] = "error"
agent["errors"] += 1
else:
# Store previous status to detect transitions
prev_status = agent.get("status", "unknown")
# Update status based on activity
if self.is_claude_working(content):
# If transitioning to working, record cycle start time
if prev_status != "working" and agent["cycle_start_time"] is None:
agent["cycle_start_time"] = datetime.now()
agent["status"] = "working"
agent["last_activity"] = datetime.now()
# Update heartbeat when agent is actively working
self._update_heartbeat(agent_id)
elif self.is_claude_ready(content):
# If transitioning from working to ready, record cycle time
if prev_status == "working" and agent["cycle_start_time"] is not None:
cycle_time = (datetime.now() - agent["cycle_start_time"]).total_seconds()
self.cycle_times.append(cycle_time)
# Keep only recent cycle times
if len(self.cycle_times) > self.max_cycle_history:
self.cycle_times.pop(0)
# Update adaptive timeout
self.calculate_adaptive_timeout()
# Reset cycle start time
agent["cycle_start_time"] = None
# Increment cycle count
agent["cycles"] += 1
# Check if idle for too long
idle_time = (datetime.now() - agent["last_activity"]).total_seconds()
if idle_time > self.idle_timeout:
agent["status"] = "idle"
else:
agent["status"] = "ready"
# Update heartbeat when agent is ready (not idle)
self._update_heartbeat(agent_id)
else:
agent["status"] = "unknown"
# Update tmux pane title with context information
self._update_pane_title(agent_id, agent)
return agent
def _update_pane_title(self, agent_id: int, agent: Dict) -> None:
"""Update tmux pane title with agent status and context percentage"""
pane_target = self.pane_mapping.get(agent_id)
if not pane_target:
return
# Build title with context warning
context = agent["last_context"]
status = agent["status"]
# Create context indicator with warning colors
if context <= self.context_threshold:
context_str = f"⚠️ {context}%"
elif context <= 30:
context_str = f"⚡{context}%"
else:
context_str = f"{context}%"
# Status emoji
status_emoji = {
"working": "🔧",
"ready": "✅",
"idle": "💤",
"error": "❌",
"starting": "🚀",
"unknown": "❓"
}.get(status, "")
# Build title
title = f"[{agent_id:02d}] {status_emoji} Context: {context_str}"
# Set pane title
with contextlib.suppress(subprocess.CalledProcessError):
run(f"tmux select-pane -t {pane_target} -T {shlex.quote(title)}", quiet=True)
def _update_heartbeat(self, agent_id: int) -> None:
"""Update heartbeat file for an agent"""
if not self.heartbeats_dir:
return
heartbeat_file = self.heartbeats_dir / f"agent{agent_id:02d}.heartbeat"
try:
# Write current timestamp to heartbeat file
heartbeat_file.write_text(datetime.now().isoformat())
self.agents[agent_id]["last_heartbeat"] = datetime.now()
except Exception:
# Silently ignore heartbeat write errors
pass
def _check_heartbeat_age(self, agent_id: int) -> Optional[float]:
"""Check age of heartbeat file in seconds"""
if not self.heartbeats_dir:
return None
heartbeat_file = self.heartbeats_dir / f"agent{agent_id:02d}.heartbeat"
if not heartbeat_file.exists():
return None
try:
mtime = heartbeat_file.stat().st_mtime
age = time.time() - mtime
return age
except Exception:
return None
def needs_restart(self, agent_id: int) -> Optional[str]:
"""Determine if an agent needs to be restarted and why
Returns:
None - no restart needed
'context' - context nearly exhausted, use /clear
'error' - encountered errors or heartbeat stalled, full restart
'idle' - idle for too long, full restart
"""
agent = self.agents[agent_id]
# Stalled heartbeat indicates the pane is likely hung
heartbeat_age = self._check_heartbeat_age(agent_id)
if heartbeat_age is not None and heartbeat_age > 120:
console.print(f"[yellow]Agent {agent_id} heartbeat is {heartbeat_age:.0f}s old[/yellow]")
return "error"
# Low-context can often be resolved with /clear instead of a full restart
if agent["last_context"] <= self.context_threshold:
return "context"
# Hard failures or repeated errors → full restart
if agent["status"] == "error" or agent["errors"] >= self.max_errors:
return "error"
# Prolonged idleness → full restart so it picks up new work
if agent["status"] == "idle":
return "idle"
return None
def get_status_table(self) -> Table:
"""Generate status table for all agents"""
table = Table(
title=f"Claude Agent Farm - {datetime.now().strftime('%H:%M:%S')}",
box=box.ROUNDED, # Use rounded corners for status tables
)
table.add_column("Agent", style="cyan", width=8)
table.add_column("Status", style="green", width=10)
table.add_column("Cycles", style="yellow", width=6)
table.add_column("Context", style="magenta", width=8)
table.add_column("Runtime", style="blue", width=12)
table.add_column("Heartbeat", style="cyan", width=8)
table.add_column("Errors", style="red", width=6)
for agent_id in sorted(self.agents.keys()):
agent = self.agents[agent_id]
runtime = str(datetime.now() - agent["start_time"]).split(".")[0]
status_style = {
"working": "[green]",
"ready": "[cyan]",
"idle": "[yellow]",
"error": "[red]",
"starting": "[yellow]",
"unknown": "[dim]",
}.get(agent["status"], "")
# Get heartbeat age
heartbeat_age = self._check_heartbeat_age(agent_id)
if heartbeat_age is None:
heartbeat_str = "---"
elif heartbeat_age < 30:
heartbeat_str = f"[green]{heartbeat_age:.0f}s[/green]"
elif heartbeat_age < 60:
heartbeat_str = f"[yellow]{heartbeat_age:.0f}s[/yellow]"
else:
heartbeat_str = f"[red]{heartbeat_age:.0f}s[/red]"
table.add_row(
f"Pane {agent_id:02d}",
f"{status_style}{agent['status']}[/]",
str(agent["cycles"]),
f"{agent['last_context']}%",
runtime,
heartbeat_str,
str(agent["errors"]),
)
return table
# ─────────────────────────────── Main Orchestrator ────────────────────────── #
class ClaudeAgentFarm:
def __init__(
self,
path: str,
agents: int = 6,
session: str = "claude_agents",
stagger: float = 10.0, # Increased from 4.0 to prevent settings clobbering
wait_after_cc: float = 15.0, # Increased from 8.0 to ensure Claude Code is fully ready
check_interval: int = 10,
skip_regenerate: bool = False,
skip_commit: bool = False,
auto_restart: bool = False,
no_monitor: bool = False,
attach: bool = False,
prompt_file: Optional[str] = None,
config: Optional[str] = None,
context_threshold: int = 20,
idle_timeout: int = 60,
max_errors: int = 3,
tmux_kill_on_exit: bool = True,
tmux_mouse: bool = True,
fast_start: bool = False,
full_backup: bool = False,
commit_every: Optional[int] = None,
):
# Store all parameters
self.path = path
self.agents = agents
self.session = session
self.stagger = stagger
self.wait_after_cc = wait_after_cc
self.check_interval = check_interval
self.skip_regenerate = skip_regenerate
self.skip_commit = skip_commit
self.auto_restart = auto_restart
self.no_monitor = no_monitor
self.attach = attach
self.prompt_file = prompt_file
self.config = config
self.context_threshold = context_threshold
self.idle_timeout = idle_timeout
self.max_errors = max_errors
self.tmux_kill_on_exit = tmux_kill_on_exit
self.tmux_mouse = tmux_mouse
self.fast_start = fast_start
self.full_backup = full_backup
self.commit_every = commit_every
# Initialize pane mapping
self.pane_mapping: Dict[int, str] = {}
# Track regeneration cycles for incremental commits
self.regeneration_cycles = 0
# Track run statistics for reporting
self.run_start_time = datetime.now()
self.total_problems_fixed = 0
self.total_commits_made = 0
self.agent_restart_count = 0
# Validate session name (tmux has restrictions)
if not re.match(r"^[a-zA-Z0-9_-]+$", self.session):
raise ValueError(
f"Invalid tmux session name '{self.session}'. Use only letters, numbers, hyphens, and underscores."
)
# Apply config file if provided
if config:
self._load_config(config)
# Validate agent count
if self.agents > getattr(self, "max_agents", 50):
raise ValueError(f"Agent count {self.agents} exceeds maximum {getattr(self, 'max_agents', 50)}")
# Initialize other attributes
self.project_path = Path(self.path).expanduser().resolve()
self.combined_file = self.project_path / "combined_typechecker_and_linter_problems.txt"
self.prompt_text = self._load_prompt()
self.monitor: Optional[AgentMonitor] = None
self.running = True
self.shutting_down = False
# Git settings from config
self.git_branch: Optional[str] = getattr(self, "git_branch", None)
self.git_remote: str = getattr(self, "git_remote", "origin")
self._cleanup_registered = False
self.state_file = self.project_path / MONITOR_STATE_FILE
# Signal handling for double Ctrl-C
self._last_sigint_time: Optional[float] = None
self._force_kill_threshold = 3.0 # seconds
# Setup signal handlers for graceful shutdown
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler)
def _load_config(self, config_path: str) -> None:
"""Load settings from JSON config file"""
config_file = Path(config_path)
if config_file.exists():
with config_file.open() as f:
config_data = json.load(f)
# Accept all config values, not just existing attributes
for key, value in config_data.items():
setattr(self, key, value)
def _signal_handler(self, sig: Any, frame: Any) -> None:
"""Handle shutdown signals gracefully with force-kill on double tap"""
current_time = time.time()
# Check if this is a SIGINT (Ctrl-C)
if sig == signal.SIGINT:
# Check for double tap
if self._last_sigint_time and (current_time - self._last_sigint_time) < self._force_kill_threshold:
# Second Ctrl-C within threshold - force kill
console.print("\n[red]Force killing tmux session...[/red]")
with contextlib.suppress(Exception):
run(f"tmux kill-session -t {self.session}", check=False, quiet=True)
# Clean up state files
try:
if hasattr(self, "state_file") and self.state_file.exists():
self.state_file.unlink()
lock_file = Path.home() / ".claude" / ".agent_farm_launch.lock"
if lock_file.exists():
lock_file.unlink()
except Exception:
pass
# Force exit
os._exit(1)
else:
# First Ctrl-C or outside threshold
self._last_sigint_time = current_time
if not self.shutting_down:
self.shutting_down = True
console.print("\n[yellow]Received interrupt signal. Shutting down gracefully...[/yellow]")
console.print("[dim]Press Ctrl-C again within 3 seconds to force kill[/dim]")
self.running = False
else:
# Other signals (SIGTERM, etc.) - normal graceful shutdown
if not self.shutting_down:
self.shutting_down = True
console.print("\n[yellow]Received termination signal. Shutting down gracefully...[/yellow]")
self.running = False
def _backup_claude_settings(self) -> Optional[str]:
"""Backup essential Claude Code settings (excluding large caches)"""
claude_dir = Path.home() / ".claude"
if not claude_dir.exists():
console.print("[yellow]No Claude Code directory found to backup[/yellow]")
return None
try:
# Create backup directory in project
backup_dir = self.project_path / ".claude_agent_farm_backups"
backup_dir.mkdir(exist_ok=True)
# Create timestamped backup filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_type = "full" if self.full_backup else "essential"
backup_file = backup_dir / f"claude_backup_{backup_type}_{timestamp}.tar.gz"
# Create compressed backup
import tarfile
if self.full_backup:
console.print("[dim]Creating FULL backup of ~/.claude directory (this may take a while)...[/dim]")
with tarfile.open(backup_file, "w:gz") as tar:
# Use filter to preserve all metadata
def reset_ids(tarinfo):
# Preserve all metadata but reset user/group to current user
# This prevents permission issues on restore
tarinfo.uid = os.getuid()
tarinfo.gid = os.getgid()
return tarinfo
tar.add(claude_dir, arcname="claude", filter=reset_ids)
size_mb = backup_file.stat().st_size / (1024 * 1024)
console.print(f"[green]✓ Full backup completed: {backup_file.name} ({size_mb:.1f} MB)[/green]")
else:
console.print("[dim]Creating backup of essential Claude settings...[/dim]")
with tarfile.open(backup_file, "w:gz") as tar:
# Filter to preserve metadata
def reset_ids(tarinfo):
tarinfo.uid = os.getuid()
tarinfo.gid = os.getgid()
return tarinfo
# Add settings.json if it exists
settings_file = claude_dir / "settings.json"
if settings_file.exists():
tar.add(settings_file, arcname="claude/settings.json", filter=reset_ids)
# Add ide directory (usually empty or small)
ide_dir = claude_dir / "ide"
if ide_dir.exists():
tar.add(ide_dir, arcname="claude/ide", filter=reset_ids)
# Add statsig directory (small, contains feature flags)
statsig_dir = claude_dir / "statsig"
if statsig_dir.exists():
tar.add(statsig_dir, arcname="claude/statsig", filter=reset_ids)
# Optionally add todos (usually small)
todos_dir = claude_dir / "todos"
if todos_dir.exists():
# Check size first
todos_size = sum(f.stat().st_size for f in todos_dir.rglob("*") if f.is_file())
if todos_size < 10 * 1024 * 1024: # Less than 10MB
tar.add(todos_dir, arcname="claude/todos", filter=reset_ids)
else:
console.print(f"[dim]Skipping todos directory ({todos_size / 1024 / 1024:.1f} MB)[/dim]")
# Skip projects directory - it's just caches
console.print("[dim]Skipping projects/ directory (caches)[/dim]")
# Get backup size
size_kb = backup_file.stat().st_size / 1024
console.print(f"[green]✓ Backed up Claude settings to {backup_file.name} ({size_kb:.1f} KB)[/green]")
# Clean up old backups (keep last 10)
self._cleanup_old_backups(backup_dir, keep_count=10)
return str(backup_file)
except Exception as e:
console.print(f"[red]Error: Could not backup Claude directory: {e}[/red]")
return None
def _cleanup_old_backups(self, backup_dir: Path, keep_count: int = 10, max_total_mb: int = 200) -> None:
"""Remove old backups, keeping only the most recent ones and enforcing size limit"""
try:
# Find all backup files (both essential and full)
backups = sorted(backup_dir.glob("claude_backup_*.tar.gz"), key=lambda p: p.stat().st_mtime, reverse=True)
# Calculate total size and remove old backups based on both count and size limits
total_size_bytes = 0
max_size_bytes = max_total_mb * 1024 * 1024
backups_to_keep = []
backups_to_remove = []
for i, backup in enumerate(backups):
backup_size = backup.stat().st_size
# Keep backup if we're under both the count limit and size limit
if i < keep_count and total_size_bytes + backup_size <= max_size_bytes:
total_size_bytes += backup_size
backups_to_keep.append(backup)
else:
backups_to_remove.append(backup)
# Always keep at least the most recent backup
if not backups_to_keep and backups:
backups_to_keep.append(backups[0])
backups_to_remove = backups[1:]
# Remove old backups
for old_backup in backups_to_remove:
size_mb = old_backup.stat().st_size / (1024 * 1024)
old_backup.unlink()
console.print(f"[dim]Removed old backup: {old_backup.name} ({size_mb:.1f} MB)[/dim]")
# Report current backup storage status
if backups_to_keep:
total_mb = total_size_bytes / (1024 * 1024)
console.print(f"[dim]Backup storage: {len(backups_to_keep)} files, {total_mb:.1f} MB total[/dim]")
except Exception as e:
console.print(f"[yellow]Warning: Could not clean up old backups: {e}[/yellow]")
def _restore_claude_settings(self, backup_path: Optional[str] = None) -> bool:
"""Restore Claude Code settings from backup"""
try:
# If no backup path provided, use the most recent one
if backup_path is None:
backup_path = self.settings_backup_path
if not backup_path:
console.print("[red]No backup path available[/red]")
return False
backup_file = Path(backup_path)
if not backup_file.exists():
console.print(f"[red]Backup file not found: {backup_path}[/red]")
return False
claude_dir = Path.home() / ".claude"
# For partial backups, we don't need to remove the entire directory
# Just extract over existing files
try:
# Ensure claude directory exists
claude_dir.mkdir(exist_ok=True)
# Save original metadata of existing files
existing_metadata = {}
for item in claude_dir.rglob("*"):
if item.exists():
stat = item.stat()
existing_metadata[str(item)] = {
'mode': stat.st_mode,
'mtime': stat.st_mtime,
'atime': stat.st_atime,
}
# Extract backup
import tarfile
console.print(f"[dim]Restoring from {backup_file.name}...[/dim]")
with tarfile.open(backup_file, "r:gz") as tar:
# Extract with numeric owner to preserve permissions
tar.extractall(path=claude_dir.parent, numeric_owner=True)
# Get list of extracted files to preserve their times
for member in tar.getmembers():
if member.isfile():
extracted_path = claude_dir.parent / member.name
if extracted_path.exists():
# Preserve the modification time from the archive
os.utime(extracted_path, (member.mtime, member.mtime))
# Ensure proper permissions on sensitive files
settings_file = claude_dir / "settings.json"
if settings_file.exists():
# Ensure settings.json has appropriate permissions (readable by user only)
os.chmod(settings_file, 0o600)
# Set ownership to current user for all restored files
uid = os.getuid()
gid = os.getgid()
for root, dirs, files in os.walk(claude_dir):
for d in dirs:
path = Path(root) / d
with contextlib.suppress(Exception):
os.chown(path, uid, gid)
for f in files:
path = Path(root) / f
with contextlib.suppress(Exception):
os.chown(path, uid, gid)
console.print("[green]✓ Restored Claude settings from backup[/green]")
# Check and fix permissions after restore
self._check_claude_permissions()
return True
except Exception as e:
console.print(f"[red]Error during restore: {e}[/red]")
return False
except Exception as e:
console.print(f"[red]Error restoring Claude settings: {e}[/red]")
return False
def _copy_best_practices_guides(self) -> None:
"""Copy best practices guides to the project folder if configured"""
best_practices_files = getattr(self, 'best_practices_files', [])
if not best_practices_files:
return
# Ensure it's a list
if isinstance(best_practices_files, str):
best_practices_files = [best_practices_files]
# Copy to project's best_practices_guides folder
dest_dir = self.project_path / "best_practices_guides"
dest_dir.mkdir(exist_ok=True)
# Copy specified files
copied_files = []
for file_path in best_practices_files:
source_file = Path(file_path).expanduser().resolve()
if not source_file.exists():
console.print(f"[yellow]Best practices file not found: {source_file}[/yellow]")
continue
dest_file = dest_dir / source_file.name
try:
import shutil
shutil.copy2(source_file, dest_file)
copied_files.append(source_file.name)
except Exception as e:
console.print(f"[yellow]Failed to copy {source_file.name}: {e}[/yellow]")