FerrellSyntheticIntelligence commited on
Commit
b22f2de
·
verified ·
1 Parent(s): 4f15617

Upload jedi/swarm/coordinator.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. jedi/swarm/coordinator.py +249 -0
jedi/swarm/coordinator.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ JEDI Swarm Coordinator — Multi-agent orchestration.
3
+
4
+ Manages nanobot swarms with:
5
+ - Distributed consensus protocols
6
+ - Emergent behavior management
7
+ - Stigmergy-based coordination
8
+ - Swarm-level memory
9
+ - Collective decision making
10
+
11
+ Inspired by: FSI_FELON Chimera + Natural swarm intelligence
12
+ """
13
+
14
+ import json
15
+ import time
16
+ import random
17
+ import threading
18
+ from typing import Dict, List, Optional, Any
19
+ from collections import Counter
20
+
21
+
22
+ class SwarmCoordinator:
23
+ """
24
+ Coordinates multiple nanobots as a unified swarm.
25
+ Uses decentralized consensus for decisions.
26
+ """
27
+
28
+ def __init__(self, swarm_id: str, config: Optional[Dict] = None):
29
+ self.swarm_id = swarm_id
30
+ self.config = config or self._default_config()
31
+ self.members = {} # bot_id -> Nanobot
32
+ self.shared_wisdom = SharedWisdom()
33
+ self.consensus = ConsensusProtocol(threshold=self.config.get("consensus_threshold", 0.7))
34
+ self.role_assignments = {}
35
+ self.swarm_state = "idle"
36
+ self._lock = threading.Lock()
37
+ self._task_queue = []
38
+
39
+ def _default_config(self) -> Dict:
40
+ return {
41
+ "consensus_threshold": 0.7,
42
+ "max_members": 100,
43
+ "min_members_for_quorum": 3,
44
+ "emergency_response": True,
45
+ "task_redundancy": 2, # Each task assigned to at least N bots
46
+ }
47
+
48
+ def add_member(self, bot_id: str, bot_type: str) -> Dict:
49
+ """Add a nanobot to the swarm."""
50
+ with self._lock:
51
+ if len(self.members) >= self.config["max_members"]:
52
+ return {"error": "Swarm at capacity"}
53
+ self.members[bot_id] = {
54
+ "id": bot_id,
55
+ "type": bot_type,
56
+ "joined": time.time(),
57
+ "last_contact": time.time(),
58
+ "alive": True,
59
+ }
60
+ return {"success": True, "swarm_size": len(self.members)}
61
+
62
+ def assign_role(self, bot_id: str, role: str) -> Dict:
63
+ """Assign a specific role to a nanobot in the swarm."""
64
+ if bot_id not in self.members:
65
+ return {"error": "Bot not in swarm"}
66
+
67
+ self.role_assignments[bot_id] = role
68
+ return {"success": True, "bot_id": bot_id, "role": role}
69
+
70
+ def queue_task(self, task: Dict) -> Dict:
71
+ """Add a task to the swarm's queue for execution."""
72
+ task_id = f"TASK-{int(time.time())}-{random.randint(1000,9999)}"
73
+ task["task_id"] = task_id
74
+ task["status"] = "queued"
75
+ task["created_at"] = time.time()
76
+
77
+ with self._lock:
78
+ self._task_queue.append(task)
79
+
80
+ # Assign to available bots
81
+ assignment = self._assign_task(task)
82
+ return {"task_id": task_id, "assignment": assignment, "queue_position": len(self._task_queue)}
83
+
84
+ def _assign_task(self, task: Dict) -> Dict:
85
+ """Intelligently assign a task to the best nanobot(s)."""
86
+ task_type = task.get("type", "unknown")
87
+ bots_by_type = {}
88
+
89
+ for bid, info in self.members.items():
90
+ if not info["alive"]:
91
+ continue
92
+ role = self.role_assignments.get(bid, info["type"])
93
+ if role not in bots_by_type:
94
+ bots_by_type[role] = []
95
+ bots_by_type[role].append(bid)
96
+
97
+ # Map task types to required roles
98
+ role_map = {
99
+ "recon": ["scout", "recon", "ghost"],
100
+ "defense": ["guardian", "sentinel", "medic"],
101
+ "offense": ["striker", "shadow", "ghost"],
102
+ "audit": ["auditor"],
103
+ "secure_dev": ["architect", "weaver"],
104
+ "coordination": ["synapse"],
105
+ "forensics": ["medic", "guardian"],
106
+ }
107
+
108
+ required_roles = role_map.get(task_type, ["scout"])
109
+ assigned = []
110
+
111
+ for role in required_roles:
112
+ if role in bots_by_type:
113
+ selected = bots_by_type[role][:self.config["task_redundancy"]]
114
+ assigned.extend(selected)
115
+
116
+ return {
117
+ "task_id": task["task_id"],
118
+ "assigned_bots": assigned,
119
+ "redundancy": self.config["task_redundancy"],
120
+ "not_enough": len(assigned) == 0,
121
+ }
122
+
123
+ def collect_intel(self, bot_id: str, intel: Dict):
124
+ """Collect intelligence from a nanobot into shared wisdom."""
125
+ self.shared_wisdom.add_intel(bot_id, intel)
126
+ with self._lock:
127
+ if bot_id in self.members:
128
+ self.members[bot_id]["last_contact"] = time.time()
129
+
130
+ def swarm_decision(self, proposals: List[Dict]) -> Optional[Dict]:
131
+ """Make a swarm-level decision using consensus protocol."""
132
+ return self.consensus.reach_consensus(proposals, min_voters=self.config["min_members_for_quorum"])
133
+
134
+ def get_swarm_status(self) -> Dict:
135
+ """Get comprehensive swarm status."""
136
+ active_bots = sum(1 for info in self.members.values() if info["alive"])
137
+ return {
138
+ "swarm_id": self.swarm_id,
139
+ "total_members": len(self.members),
140
+ "active_members": active_bots,
141
+ "state": self.swarm_state,
142
+ "tasks_queued": len(self._task_queue),
143
+ "wisdom_size": self.shared_wisdom.size(),
144
+ "consensus_reached": self.consensus.total_decisions,
145
+ "role_distribution": dict(Counter(self.role_assignments.values())),
146
+ }
147
+
148
+
149
+ class SharedWisdom:
150
+ """
151
+ Collective swarm memory — stigmergy-based.
152
+ Nanobots leave traces that others follow.
153
+ """
154
+
155
+ def __init__(self):
156
+ self._intel = []
157
+ self._pheromone_trails = {}
158
+ self._lock = threading.Lock()
159
+
160
+ def add_intel(self, bot_id: str, intel: Dict):
161
+ with self._lock:
162
+ self._intel.append({
163
+ "bot_id": bot_id,
164
+ "data": intel,
165
+ "timestamp": time.time()
166
+ })
167
+
168
+ def add_pheromone(self, trail_id: str, strength: float):
169
+ """Add to a pheromone trail. Higher strength = more bots recommend this path."""
170
+ with self._lock:
171
+ current = self._pheromone_trails.get(trail_id, {"strength": 0, "voters": set()})
172
+ current["strength"] += strength
173
+ current["last_updated"] = time.time()
174
+ self._pheromone_trails[trail_id] = current
175
+
176
+ def get_strongest_trails(self, limit: int = 5) -> List[tuple]:
177
+ """Get the pheromone trails with highest strength."""
178
+ with self._lock:
179
+ sorted_trails = sorted(
180
+ self._pheromone_trails.items(),
181
+ key=lambda x: x[1]["strength"],
182
+ reverse=True
183
+ )
184
+ return sorted_trails[:limit]
185
+
186
+ def size(self) -> Dict:
187
+ with self._lock:
188
+ return {
189
+ "intel_entries": len(self._intel),
190
+ "pheromone_trails": len(self._pheromone_trails),
191
+ }
192
+
193
+
194
+ class ConsensusProtocol:
195
+ """
196
+ Distributed consensus for swarm decision-making.
197
+ Used for critical operations like attack authorization or target selection.
198
+ """
199
+
200
+ def __init__(self, threshold: float = 0.7):
201
+ self.threshold = threshold
202
+ self.total_decisions = 0
203
+ self.history = []
204
+
205
+ def reach_consensus(self, proposals: List[Dict], min_voters: int = 3) -> Optional[Dict]:
206
+ """
207
+ Process nanobot proposals and reach consensus.
208
+
209
+ Each proposal has:
210
+ - bot_id: identifying the nanobot
211
+ - action: proposed action
212
+ - confidence: 0.0-1.0 confidence in the proposal
213
+ - evidence: supporting evidence
214
+ """
215
+ if len(proposals) < min_voters:
216
+ return None
217
+
218
+ # Group proposals by action
219
+ action_votes = {}
220
+ for prop in proposals:
221
+ action = prop.get("action", "unknown")
222
+ confidence = prop.get("confidence", 0.5)
223
+ if action not in action_votes:
224
+ action_votes[action] = []
225
+ action_votes[action].append(confidence)
226
+
227
+ # Find action with highest weighted support
228
+ action_scores = {
229
+ action: (sum(confidences) / len(confidences)) * (len(confidences) / len(proposals))
230
+ for action, confidences in action_votes.items()
231
+ }
232
+
233
+ best_action = max(action_scores, key=action_scores.get)
234
+ best_score = action_scores[best_action]
235
+
236
+ result = {
237
+ "consensus_reached": best_score >= self.threshold,
238
+ "selected_action": best_action if best_score >= self.threshold else "no_consensus",
239
+ "confidence": best_score,
240
+ "threshold": self.threshold,
241
+ "total_voters": len(proposals),
242
+ "actions_proposed": list(action_votes.keys()),
243
+ "action_scores": action_scores,
244
+ }
245
+
246
+ self.total_decisions += 1
247
+ self.history.append(result)
248
+
249
+ return result