forked from namefailed/CodeMechanic-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorchestrator.py
More file actions
198 lines (170 loc) · 7.84 KB
/
orchestrator.py
File metadata and controls
198 lines (170 loc) · 7.84 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
"""
Orchestrator
The central brain of CodeMechanic-Bot.
Initializes the EventBus and all Agents. Maps events to their respective agent handlers.
Runs the continuous scanning loop.
"""
import os
import time
import yaml
import logging
import argparse
from typing import Callable, Dict, List
from events import BaseEvent, BountyVerifiedEvent
from utils.database import Database
from agents.bounty_radar import BountyRadar
from agents.scam_detector import ScamDetector
from agents.pr_engineer import PREngineer
from agents.code_reviewer import CodeReviewer
from agents.content_engine import ContentEngine
from agents.devops_monitor import DevOpsMonitor
from agents.earnings_tracker import EarningsTracker
from agents.review_tracker import ReviewTracker
from agents.static_analyzer import StaticAnalyzer
from agents.pr_maintainer import PRMaintainer
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("codemechanic.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class EventBus:
"""
A simple publish-subscribe event bus to decouple agents.
"""
def __init__(self):
self.subscribers: Dict[str, List[Callable]] = {}
def subscribe(self, event_type: str, callback: Callable):
"""Register a callback for a specific event type."""
if event_type not in self.subscribers:
self.subscribers[event_type] = []
self.subscribers[event_type].append(callback)
def publish(self, event: BaseEvent):
"""Emit an event to all registered subscribers."""
logger.info(f"[EventBus] Emitting: {event.event_type}")
if event.event_type in self.subscribers:
for callback in self.subscribers[event.event_type]:
try:
callback(event.payload)
except Exception as e:
logger.error(f"[EventBus] Error in callback {callback.__name__} for event {event.event_type}: {e}")
import threading
class Orchestrator:
"""
Main controller for the CodeMechanic-Bot pipeline.
"""
def __init__(self, config_path: str = "config.yaml", stealth_mode: bool = False):
self.bus = EventBus()
self.stealth_mode = stealth_mode
self.db = Database()
# Synchronization event: True when bounty scan is active
self.bounty_active_event = threading.Event()
self.bounty_active_event.clear()
self.load_config(config_path)
self.init_agents()
self.setup_subscriptions()
self.resume_pending_tasks()
def resume_pending_tasks(self):
"""Resume any issues that were PENDING if the bot crashed mid-execution."""
pending = self.db.get_pending_issues()
if pending:
logger.info(f"Orchestrator: Found {len(pending)} PENDING issues from a previous run. Resuming...")
for issue in pending:
payload = {
"issue_url": issue["issue_url"],
"repo": issue["repo"],
"issue_title": "Resumed Task",
"issue_number": issue["issue_url"].split("/")[-1]
}
self.bus.publish(BountyVerifiedEvent(payload=payload))
def load_config(self, config_path: str):
"""Loads configuration settings from a YAML file and .env variables."""
if os.path.exists(".env"):
with open(".env", "r") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key, val = line.split("=", 1)
os.environ[key.strip()] = val.strip()
try:
with open(config_path, "r") as f:
self.config = yaml.safe_load(f)
if "github_token" in self.config:
os.environ["GITHUB_TOKEN"] = self.config["github_token"]
logger.info("Config loaded successfully.")
except Exception as e:
logger.error(f"Failed to load config: {e}")
self.config = {}
def init_agents(self):
"""Instantiates all agents and injects the publish method."""
self.radar = BountyRadar(self.bus.publish)
self.scam_detector = ScamDetector(self.bus.publish)
self.pr_engineer = PREngineer(self.bus.publish, self.stealth_mode)
self.reviewer = CodeReviewer(self.bus.publish, self.stealth_mode)
self.content_engine = ContentEngine(self.bus.publish)
self.devops_monitor = DevOpsMonitor(self.bus.publish)
self.earnings_tracker = EarningsTracker(self.bus.publish)
self.review_tracker = ReviewTracker(self.bus.publish)
# Pass the event to the StaticAnalyzer so it knows when to pause
self.static_analyzer = StaticAnalyzer(self.bus.publish, self.bounty_active_event)
self.pr_maintainer = PRMaintainer(self.bus.publish)
def setup_subscriptions(self):
"""Wires up the event pipeline between agents."""
self.bus.subscribe("BOUNTY_FOUND", self.scam_detector.evaluate)
self.bus.subscribe("BOUNTY_VERIFIED", self.pr_engineer.solve_issue)
self.bus.subscribe("MAINTAINER_FEEDBACK", self.pr_engineer.solve_issue)
self.bus.subscribe("PR_READY", self.reviewer.review)
self.bus.subscribe("PR_SUBMITTED", self.content_engine.draft_post)
self.bus.subscribe("PR_SUBMITTED", self.devops_monitor.track_ci)
self.bus.subscribe("PR_SUBMITTED", self.earnings_tracker.calculate_roi)
self.bus.subscribe("PR_REVIEWED", self.pr_engineer.solve_issue)
self.bus.subscribe("PR_REJECTED", self.pr_engineer.solve_issue)
def bounty_loop(self):
"""Runs every 30 minutes to scan for bounties."""
while True:
logger.info("--- Starting new Bounty Scan Cycle ---")
self.bounty_active_event.set() # Tell researcher to pause
try:
self.radar.scan()
self.pr_maintainer.check_prs()
self.review_tracker.track()
except Exception as e:
logger.error(f"Error in bounty loop: {e}")
self.bounty_active_event.clear() # Allow researcher to resume
logger.info("--- Bounty Scan Complete. Sleeping for 30 minutes. Researcher unpaused. ---")
time.sleep(1800) # Sleep 30 minutes
def researcher_loop(self):
"""Runs continuously, hunting for Zero-Days. Pauses when bounty_active_event is set."""
while True:
if self.bounty_active_event.is_set():
# Pause while bounty scan is running
time.sleep(10)
continue
try:
self.static_analyzer.scan()
except Exception as e:
logger.error(f"Error in researcher loop: {e}")
# Small sleep between repos to avoid rate limits
time.sleep(60)
def run(self):
"""Starts the orchestrator threads."""
logger.info("Starting dual-mode CodeMechanic-Bot Orchestrator...")
t_bounty = threading.Thread(target=self.bounty_loop, daemon=True)
t_researcher = threading.Thread(target=self.researcher_loop, daemon=True)
t_bounty.start()
t_researcher.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
logger.info("\nShutting down Orchestrator gracefully.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Bug Bot Orchestrator")
parser.add_argument("--stealth", action="store_true", help="Run in stealth mode to mimic a human developer.")
args = parser.parse_args()
orchestrator = Orchestrator(stealth_mode=args.stealth)
orchestrator.run()