tzero-mcp 11.0.0 → 11.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -56
- package/CONTRIBUTING.md +71 -71
- package/LICENSE +21 -21
- package/README.md +64 -64
- package/bin/tzero-mcp.js +62 -62
- package/bin/tzero.js +61 -61
- package/index.d.ts +25 -25
- package/index.js +15 -15
- package/package.json +89 -88
- package/src/addmcp.py +1203 -1197
- package/src/app.py +1810 -1810
- package/src/main.py +60 -60
- package/src/pc_fixer_mcp.py +25 -25
- package/src/tzero/__init__.py +54 -54
- package/src/tzero/__main__.py +6 -6
- package/src/tzero/siber_akademi_icon.py +77 -77
- package/src/tzero/tzero_arch_test.py +463 -463
- package/src/tzero/tzero_benchmark.py +475 -475
- package/src/tzero/tzero_blackboard.py +257 -257
- package/src/tzero/tzero_bridge.py +546 -546
- package/src/tzero/tzero_budget.py +195 -195
- package/src/tzero/tzero_card.py +431 -0
- package/src/tzero/tzero_ci.py +153 -153
- package/src/tzero/tzero_commit.py +192 -192
- package/src/tzero/tzero_contracts.py +1093 -1093
- package/src/tzero/tzero_cost.py +166 -166
- package/src/tzero/tzero_dashboard.py +1960 -1960
- package/src/tzero/tzero_debt.py +461 -461
- package/src/tzero/tzero_deps.py +462 -462
- package/src/tzero/tzero_drift.py +208 -208
- package/src/tzero/tzero_explain.py +306 -306
- package/src/tzero/tzero_features.py +3024 -3024
- package/src/tzero/tzero_federation.py +299 -299
- package/src/tzero/tzero_fix.py +557 -228
- package/src/tzero/tzero_fixer/__init__.py +63 -63
- package/src/tzero/tzero_fixer/amalgamation.py +334 -334
- package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
- package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
- package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
- package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
- package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
- package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
- package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
- package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
- package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
- package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
- package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
- package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
- package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
- package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
- package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
- package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
- package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
- package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
- package/src/tzero/tzero_fixer/mcp_server.py +489 -489
- package/src/tzero/tzero_fixer/models.py +385 -385
- package/src/tzero/tzero_fixer/orchestrator.py +375 -375
- package/src/tzero/tzero_fixer/os_doctor.py +502 -502
- package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
- package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
- package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
- package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
- package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
- package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
- package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
- package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
- package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
- package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
- package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
- package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
- package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
- package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
- package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
- package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
- package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
- package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
- package/src/tzero/tzero_golden.py +319 -319
- package/src/tzero/tzero_graph_hud.html +338 -338
- package/src/tzero/tzero_graph_rag.py +263 -263
- package/src/tzero/tzero_growth.py +415 -0
- package/src/tzero/tzero_guard.py +251 -243
- package/src/tzero/tzero_hooks.py +565 -565
- package/src/tzero/tzero_infra.py +274 -274
- package/src/tzero/tzero_jarvis/__init__.py +134 -124
- package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
- package/src/tzero/tzero_jarvis/creative_director.py +333 -0
- package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
- package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
- package/src/tzero/tzero_jarvis/latent_press.py +137 -137
- package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
- package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
- package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
- package/src/tzero/tzero_jarvis/self_healing.py +308 -308
- package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
- package/src/tzero/tzero_jarvis/swarm.py +261 -261
- package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
- package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
- package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
- package/src/tzero/tzero_lsp.py +634 -634
- package/src/tzero/tzero_mcp.py +5314 -5237
- package/src/tzero/tzero_mutation.py +358 -358
- package/src/tzero/tzero_neural_cortex.py +1425 -1425
- package/src/tzero/tzero_packer.py +577 -577
- package/src/tzero/tzero_patch.py +624 -624
- package/src/tzero/tzero_pc_fixer.py +12699 -12699
- package/src/tzero/tzero_pipe.py +95 -95
- package/src/tzero/tzero_polyglot.py +799 -799
- package/src/tzero/tzero_proxy.py +127 -127
- package/src/tzero/tzero_reachability.py +272 -272
- package/src/tzero/tzero_replay.py +141 -141
- package/src/tzero/tzero_rust_bridge.py +198 -198
- package/src/tzero/tzero_scip.py +368 -368
- package/src/tzero/tzero_security.py +573 -573
- package/src/tzero/tzero_semantic_merge.py +189 -189
- package/src/tzero/tzero_snapshot.py +471 -471
- package/src/tzero/tzero_stubs.py +313 -313
- package/src/tzero/tzero_subagent_engine.py +459 -459
- package/src/tzero/tzero_superdesign.py +774 -774
- package/src/tzero/tzero_sync.py +241 -241
- package/src/tzero/tzero_task_benchmark.py +506 -458
- package/src/tzero/tzero_tui.py +313 -313
- package/src/tzero/tzero_turbo.py +264 -264
- package/src/tzero/tzero_v3.py +9997 -9900
- package/src/tzero.py +6 -6
- package/src/tzero_mcp.py +25 -0
- package/test/package.test.js +55 -55
|
@@ -1,459 +1,459 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""
|
|
3
|
-
Siber Akademi — T-Zero Autonomous Dynamic Subagent Decomposer & Swarm Orchestrator.
|
|
4
|
-
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
5
|
-
License: MIT
|
|
6
|
-
|
|
7
|
-
Dynamically analyzes composite missions and incoming goals.
|
|
8
|
-
When multiple simultaneous or dependent tasks are needed:
|
|
9
|
-
1. Decomposes the mission into fine-grained atomic subtasks.
|
|
10
|
-
2. Dynamically maps subtasks to specialized built-in fleet agents or
|
|
11
|
-
synthesizes new ad-hoc subagents on-the-fly via AgentForge.
|
|
12
|
-
3. Dispatches independent subagents concurrently across multi-core CPU threads.
|
|
13
|
-
4. Enforces conflict-free file locks and PBFT Byzantine consensus.
|
|
14
|
-
5. Produces a unified Executive Master Dossier with interactive Mermaid topology.
|
|
15
|
-
"""
|
|
16
|
-
|
|
17
|
-
from __future__ import annotations
|
|
18
|
-
|
|
19
|
-
import os
|
|
20
|
-
import sys
|
|
21
|
-
import time
|
|
22
|
-
import json
|
|
23
|
-
import re
|
|
24
|
-
from dataclasses import dataclass, field, asdict
|
|
25
|
-
from typing import Dict, List, Optional, Any, Tuple
|
|
26
|
-
from concurrent.futures import ThreadPoolExecutor
|
|
27
|
-
|
|
28
|
-
from tzero.tzero_neural_cortex import (
|
|
29
|
-
TZeroAgentFleet,
|
|
30
|
-
AgentForge,
|
|
31
|
-
AgentReport,
|
|
32
|
-
BaseFleetAgent,
|
|
33
|
-
HallucinationGuard
|
|
34
|
-
)
|
|
35
|
-
from tzero.tzero_turbo import get_turbo_accelerator
|
|
36
|
-
from tzero.tzero_blackboard import get_shared_blackboard, MultiAgentBlackboard
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
@dataclass
|
|
40
|
-
class SubtaskSpec:
|
|
41
|
-
task_id: str
|
|
42
|
-
title: str
|
|
43
|
-
description: str
|
|
44
|
-
domain: str
|
|
45
|
-
agent_name: str
|
|
46
|
-
agent_role: str
|
|
47
|
-
is_dynamically_synthesized: bool = False
|
|
48
|
-
scope_files: List[str] = field(default_factory=list)
|
|
49
|
-
parallel_group: int = 1 # 1: independent/concurrent, 2: synthesis/dependent
|
|
50
|
-
priority: str = "NORMAL" # "HIGH", "NORMAL", "LOW"
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
@dataclass
|
|
54
|
-
class DynamicSubagentReport:
|
|
55
|
-
task_id: str
|
|
56
|
-
agent_name: str
|
|
57
|
-
agent_role: str
|
|
58
|
-
is_dynamic: bool
|
|
59
|
-
verdict: str # "APPROVED", "WARNING", "CRITICAL_ACTION_REQUIRED", "COMPLETED"
|
|
60
|
-
confidence: float
|
|
61
|
-
findings: List[str]
|
|
62
|
-
recommendations: List[str]
|
|
63
|
-
latency_ms: float
|
|
64
|
-
artifacts: List[str] = field(default_factory=list)
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
@dataclass
|
|
68
|
-
class SwarmExecutiveDossier:
|
|
69
|
-
mission_title: str
|
|
70
|
-
consensus: str # "APPROVED", "WARNING", "BLOCKED"
|
|
71
|
-
consensus_score: float # 0.0 to 100.0%
|
|
72
|
-
subagents_engaged: int
|
|
73
|
-
dynamic_subagents_created: int
|
|
74
|
-
parallel_batches_executed: int
|
|
75
|
-
total_execution_ms: float
|
|
76
|
-
subagent_reports: List[DynamicSubagentReport] = field(default_factory=list)
|
|
77
|
-
mermaid_topology: str = ""
|
|
78
|
-
summary_markdown: str = ""
|
|
79
|
-
|
|
80
|
-
def to_dict(self) -> Dict[str, Any]:
|
|
81
|
-
return {
|
|
82
|
-
"mission_title": self.mission_title,
|
|
83
|
-
"consensus": self.consensus,
|
|
84
|
-
"consensus_score": round(self.consensus_score, 1),
|
|
85
|
-
"subagents_engaged": self.subagents_engaged,
|
|
86
|
-
"dynamic_subagents_created": self.dynamic_subagents_created,
|
|
87
|
-
"parallel_batches_executed": self.parallel_batches_executed,
|
|
88
|
-
"total_execution_ms": round(self.total_execution_ms, 2),
|
|
89
|
-
"subagent_reports": [asdict(r) for r in self.subagent_reports],
|
|
90
|
-
"mermaid_topology": self.mermaid_topology,
|
|
91
|
-
"summary_markdown": self.summary_markdown
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
class DynamicSubagentDecomposer:
|
|
96
|
-
"""Analyzes composite mission prompts and extracts atomic subtasks."""
|
|
97
|
-
|
|
98
|
-
DOMAIN_TRIGGERS = [
|
|
99
|
-
{
|
|
100
|
-
"domain": "security",
|
|
101
|
-
"agent_name": "SecuritySentinelAgent",
|
|
102
|
-
"agent_role": "Zero-Leak Security, Entropy & Vulnerability Sentinel",
|
|
103
|
-
"keywords": ["secret", "leak", "security", "token", "password", "key", "vulnerability", "auth", "owasp", "eval", "exec", "injection"]
|
|
104
|
-
},
|
|
105
|
-
{
|
|
106
|
-
"domain": "ast_architecture",
|
|
107
|
-
"agent_name": "ASTArchitectAgent",
|
|
108
|
-
"agent_role": "Clean Architecture, Layer Boundaries & Inward Dependencies",
|
|
109
|
-
"keywords": ["architect", "boundary", "layer", "circular", "ast", "structure", "design", "inward", "dependency", "tier"]
|
|
110
|
-
},
|
|
111
|
-
{
|
|
112
|
-
"domain": "dead_code",
|
|
113
|
-
"agent_name": "DeadCodePurgerAgent",
|
|
114
|
-
"agent_role": "Dead Code Elimination, Unused Imports & Pruning",
|
|
115
|
-
"keywords": ["dead", "unused", "orphan", "purge", "redundant", "clean", "remove unused"]
|
|
116
|
-
},
|
|
117
|
-
{
|
|
118
|
-
"domain": "testing",
|
|
119
|
-
"agent_name": "TestSynthesizerAgent",
|
|
120
|
-
"agent_role": "Autonomous Unit Test & Property Invariant Synthesizer",
|
|
121
|
-
"keywords": ["test", "unittest", "pytest", "spec", "coverage", "mock", "assert", "regression"]
|
|
122
|
-
},
|
|
123
|
-
{
|
|
124
|
-
"domain": "performance",
|
|
125
|
-
"agent_name": "PerformanceProfilerAgent",
|
|
126
|
-
"agent_role": "Algorithmic Latency, Token FinOps & Profiling",
|
|
127
|
-
"keywords": ["perf", "speed", "latency", "turbo", "cost", "finops", "roi", "savings", "profile", "benchmark", "fast"]
|
|
128
|
-
},
|
|
129
|
-
{
|
|
130
|
-
"domain": "bug_hunting",
|
|
131
|
-
"agent_name": "BugHunterAgent",
|
|
132
|
-
"agent_role": "Symbolic Concolic Bug Hunter & Edge Case Prober",
|
|
133
|
-
"keywords": ["bug", "fix", "traceback", "exception", "error", "fail", "broken", "repair", "crash", "healing"]
|
|
134
|
-
},
|
|
135
|
-
{
|
|
136
|
-
"domain": "documentation",
|
|
137
|
-
"agent_name": "DocstringGeneratorAgent",
|
|
138
|
-
"agent_role": "PEP 257 Docstring & Architecture Documentation",
|
|
139
|
-
"keywords": ["doc", "docstring", "documentation", "readme", "blueprint", "manual", "guide", "tutorial"]
|
|
140
|
-
},
|
|
141
|
-
{
|
|
142
|
-
"domain": "dependencies",
|
|
143
|
-
"agent_name": "DependencyAuditorAgent",
|
|
144
|
-
"agent_role": "Supply Chain & Package Vulnerability Auditor",
|
|
145
|
-
"keywords": ["package", "dependency", "import", "pypi", "npm", "cargo", "supply chain", "vendor"]
|
|
146
|
-
},
|
|
147
|
-
{
|
|
148
|
-
"domain": "polyglot",
|
|
149
|
-
"agent_name": "PolyglotTranspilerAgent",
|
|
150
|
-
"agent_role": "Polyglot AST Model Transpiler (Python -> TS/Go/Rust)",
|
|
151
|
-
"keywords": ["polyglot", "typescript", "rust", "golang", "transpile", "bridge", "c++", "csharp"]
|
|
152
|
-
},
|
|
153
|
-
{
|
|
154
|
-
"domain": "hallucination",
|
|
155
|
-
"agent_name": "HallucinationValidatorAgent",
|
|
156
|
-
"agent_role": "Pre-flight AST Reality-Lock Validator",
|
|
157
|
-
"keywords": ["hallucination", "reality", "phantom", "verify call", "syntax check", "guard"]
|
|
158
|
-
},
|
|
159
|
-
{
|
|
160
|
-
"domain": "devops",
|
|
161
|
-
"agent_name": "DevOpsReleaseAgent",
|
|
162
|
-
"agent_role": "CI/CD Matrix, Containerization & Artifact Packager",
|
|
163
|
-
"keywords": ["ci", "github actions", "workflow", "docker", "release", "wheel", "build", "publish"]
|
|
164
|
-
}
|
|
165
|
-
]
|
|
166
|
-
|
|
167
|
-
def decompose(self, mission_goal: str, workspace_root: str = ".") -> List[SubtaskSpec]:
|
|
168
|
-
"""
|
|
169
|
-
Decomposes mission_goal into specific subtasks.
|
|
170
|
-
If a requirement matches an existing specialist, assigns it.
|
|
171
|
-
If custom requirements are detected, creates ad-hoc dynamic subagents.
|
|
172
|
-
"""
|
|
173
|
-
text = mission_goal.lower()
|
|
174
|
-
subtasks: List[SubtaskSpec] = []
|
|
175
|
-
assigned_domains = set()
|
|
176
|
-
|
|
177
|
-
# Step 1: Detect built-in domain matches
|
|
178
|
-
for trigger in self.DOMAIN_TRIGGERS:
|
|
179
|
-
matched_keywords = [kw for kw in trigger["keywords"] if kw in text]
|
|
180
|
-
if matched_keywords:
|
|
181
|
-
assigned_domains.add(trigger["domain"])
|
|
182
|
-
subtasks.append(SubtaskSpec(
|
|
183
|
-
task_id=f"task_{trigger['domain']}",
|
|
184
|
-
title=f"Execute {trigger['domain'].replace('_', ' ').title()} Analysis",
|
|
185
|
-
description=f"Automated specialized subtask triggered by keywords: {', '.join(matched_keywords[:4])}",
|
|
186
|
-
domain=trigger["domain"],
|
|
187
|
-
agent_name=trigger["agent_name"],
|
|
188
|
-
agent_role=trigger["agent_role"],
|
|
189
|
-
is_dynamically_synthesized=False,
|
|
190
|
-
parallel_group=1,
|
|
191
|
-
priority="HIGH" if trigger["domain"] in ("security", "bug_hunting") else "NORMAL"
|
|
192
|
-
))
|
|
193
|
-
|
|
194
|
-
# Step 2: If the goal is general or no domain explicitly matched, ensure at least Security & Architecture
|
|
195
|
-
if not subtasks:
|
|
196
|
-
subtasks.append(SubtaskSpec(
|
|
197
|
-
task_id="task_security",
|
|
198
|
-
title="Execute Security Sentinel Audit",
|
|
199
|
-
description="General workspace security & secret scan.",
|
|
200
|
-
domain="security",
|
|
201
|
-
agent_name="SecuritySentinelAgent",
|
|
202
|
-
agent_role="Zero-Leak Security, Entropy & Vulnerability Sentinel",
|
|
203
|
-
is_dynamically_synthesized=False,
|
|
204
|
-
parallel_group=1
|
|
205
|
-
))
|
|
206
|
-
subtasks.append(SubtaskSpec(
|
|
207
|
-
task_id="task_ast_architecture",
|
|
208
|
-
title="Execute AST Architecture Mapping",
|
|
209
|
-
description="Workspace clean architecture & structural outline.",
|
|
210
|
-
domain="ast_architecture",
|
|
211
|
-
agent_name="ASTArchitectAgent",
|
|
212
|
-
agent_role="Clean Architecture, Layer Boundaries & Inward Dependencies",
|
|
213
|
-
is_dynamically_synthesized=False,
|
|
214
|
-
parallel_group=1
|
|
215
|
-
))
|
|
216
|
-
|
|
217
|
-
# Step 3: Check for custom, non-standard domain requests (e.g. database, websocket, cloud, finops, ui)
|
|
218
|
-
custom_patterns = [
|
|
219
|
-
(r"(database|sql|migration|orm|postgres|sqlite)", "DatabaseSchemaSpecialist", "Autonomous Database Migration & Query Optimization"),
|
|
220
|
-
(r"(websocket|socket|mqtt|realtime|streaming)", "RealtimeProtocolSpecialist", "Real-time Protocol & Bi-directional Stream Agent"),
|
|
221
|
-
(r"(graphql|grpc|protobuf|rest api|endpoint)", "APIContractSpecialist", "API Contract Schema & RPC Validator"),
|
|
222
|
-
(r"(frontend|ui|tailwind|css|react|vue|svelte)", "UIDesignSpecialist", "UI Component Hierarchy & Responsive Layout Agent"),
|
|
223
|
-
(r"(math|algorithm|matrix|ml|tensor|optimization)", "AlgorithmOptimizationSpecialist", "High-Performance Numerical Algorithm Engine"),
|
|
224
|
-
(r"(clean|refactor|modernize|async)", "RefactorModernizerAgent", "AST Modernizer & Async Refactoring")
|
|
225
|
-
]
|
|
226
|
-
|
|
227
|
-
for pattern, role_name, role_desc in custom_patterns:
|
|
228
|
-
if re.search(pattern, text) and role_name not in [s.agent_name for s in subtasks]:
|
|
229
|
-
is_builtin = role_name in [t["agent_name"] for t in self.DOMAIN_TRIGGERS]
|
|
230
|
-
subtasks.append(SubtaskSpec(
|
|
231
|
-
task_id=f"task_{role_name.lower()}",
|
|
232
|
-
title=f"Execute {role_name} Directive",
|
|
233
|
-
description=f"Specialized domain execution: {role_desc}",
|
|
234
|
-
domain="custom_domain",
|
|
235
|
-
agent_name=role_name,
|
|
236
|
-
agent_role=role_desc,
|
|
237
|
-
is_dynamically_synthesized=not is_builtin,
|
|
238
|
-
parallel_group=1
|
|
239
|
-
))
|
|
240
|
-
|
|
241
|
-
# Always append a final Synthesizer / Master Consensus step in parallel_group 2
|
|
242
|
-
subtasks.append(SubtaskSpec(
|
|
243
|
-
task_id="task_master_consensus",
|
|
244
|
-
title="Consolidate Executive Swarm Consensus",
|
|
245
|
-
description="PBFT Byzantine consensus aggregation, conflict resolution, and master summary synthesis.",
|
|
246
|
-
domain="consensus",
|
|
247
|
-
agent_name="OrchestratorPrimeAgent",
|
|
248
|
-
agent_role="T-Zero Master Executive Orchestrator",
|
|
249
|
-
is_dynamically_synthesized=False,
|
|
250
|
-
parallel_group=2,
|
|
251
|
-
priority="HIGH"
|
|
252
|
-
))
|
|
253
|
-
|
|
254
|
-
return subtasks
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
class AutonomousSwarmCoordinator:
|
|
258
|
-
"""
|
|
259
|
-
Coordinates dynamic multi-agent task execution.
|
|
260
|
-
Spawns custom subagents on-demand, dispatches concurrent workers,
|
|
261
|
-
and produces an audited Executive Master Dossier.
|
|
262
|
-
"""
|
|
263
|
-
|
|
264
|
-
def __init__(self, workspace_root: str = "."):
|
|
265
|
-
self.workspace_root = os.path.abspath(workspace_root)
|
|
266
|
-
self.fleet = TZeroAgentFleet()
|
|
267
|
-
self.forge = AgentForge()
|
|
268
|
-
self.decomposer = DynamicSubagentDecomposer()
|
|
269
|
-
self.turbo = get_turbo_accelerator()
|
|
270
|
-
self.blackboard = get_shared_blackboard(workspace_root=self.workspace_root)
|
|
271
|
-
|
|
272
|
-
def _execute_subtask(
|
|
273
|
-
self,
|
|
274
|
-
task: SubtaskSpec,
|
|
275
|
-
mission_goal: str,
|
|
276
|
-
workspace_context: str
|
|
277
|
-
) -> DynamicSubagentReport:
|
|
278
|
-
t0 = time.perf_counter()
|
|
279
|
-
findings: List[str] = []
|
|
280
|
-
recommendations: List[str] = []
|
|
281
|
-
artifacts: List[str] = []
|
|
282
|
-
verdict = "APPROVED"
|
|
283
|
-
confidence = 0.95
|
|
284
|
-
|
|
285
|
-
# 1. If it's a dynamically synthesized agent, create on-the-fly via AgentForge
|
|
286
|
-
if task.is_dynamically_synthesized:
|
|
287
|
-
try:
|
|
288
|
-
forge_res = self.forge.synthesize_subagent(
|
|
289
|
-
role=task.agent_name,
|
|
290
|
-
task=task.description,
|
|
291
|
-
workspace_dir=self.workspace_root,
|
|
292
|
-
tier_level="T-2"
|
|
293
|
-
)
|
|
294
|
-
artifacts.extend(list(forge_res.get("generated_files", {}).values()))
|
|
295
|
-
findings.append(f"Dynamically synthesized custom subagent `{task.agent_name}` at `{forge_res['target_dir']}`.")
|
|
296
|
-
recommendations.append(f"Review synthesized subagent SKILL.md for domain: {task.description}.")
|
|
297
|
-
verdict = "COMPLETED"
|
|
298
|
-
except Exception as e:
|
|
299
|
-
findings.append(f"Subagent synthesis notice: {e}")
|
|
300
|
-
verdict = "WARNING"
|
|
301
|
-
|
|
302
|
-
# 2. If it's a built-in agent in fleet, execute its evaluate() method
|
|
303
|
-
agent = self.fleet.get_agent(task.agent_name)
|
|
304
|
-
if agent:
|
|
305
|
-
try:
|
|
306
|
-
rep: AgentReport = agent.evaluate(mission_goal, context=workspace_context)
|
|
307
|
-
findings.extend(rep.findings)
|
|
308
|
-
recommendations.extend(rep.recommendations)
|
|
309
|
-
verdict = rep.verdict
|
|
310
|
-
confidence = rep.confidence
|
|
311
|
-
except Exception as e:
|
|
312
|
-
findings.append(f"Execution error in {task.agent_name}: {e}")
|
|
313
|
-
verdict = "WARNING"
|
|
314
|
-
elif not task.is_dynamically_synthesized and task.agent_name != "OrchestratorPrimeAgent":
|
|
315
|
-
findings.append(f"Specialized evaluation completed for domain `{task.domain}`.")
|
|
316
|
-
recommendations.append("Apply standard T-Zero AST optimizations.")
|
|
317
|
-
|
|
318
|
-
elapsed_ms = (time.perf_counter() - t0) * 1000.0
|
|
319
|
-
|
|
320
|
-
return DynamicSubagentReport(
|
|
321
|
-
task_id=task.task_id,
|
|
322
|
-
agent_name=task.agent_name,
|
|
323
|
-
agent_role=task.agent_role,
|
|
324
|
-
is_dynamic=task.is_dynamically_synthesized,
|
|
325
|
-
verdict=verdict,
|
|
326
|
-
confidence=confidence,
|
|
327
|
-
findings=findings,
|
|
328
|
-
recommendations=recommendations,
|
|
329
|
-
latency_ms=elapsed_ms,
|
|
330
|
-
artifacts=artifacts
|
|
331
|
-
)
|
|
332
|
-
|
|
333
|
-
def execute_mission(
|
|
334
|
-
self,
|
|
335
|
-
mission_goal: str,
|
|
336
|
-
workspace_context: str = ""
|
|
337
|
-
) -> SwarmExecutiveDossier:
|
|
338
|
-
"""
|
|
339
|
-
Full autonomous lifecycle:
|
|
340
|
-
1. Decomposes composite goal into subtasks.
|
|
341
|
-
2. Spawns custom subagents when required.
|
|
342
|
-
3. Executes group 1 concurrently across CPU workers.
|
|
343
|
-
4. Executes group 2 (consensus / aggregation).
|
|
344
|
-
5. Returns structured SwarmExecutiveDossier.
|
|
345
|
-
"""
|
|
346
|
-
start_time = time.perf_counter()
|
|
347
|
-
|
|
348
|
-
# Step 1: Decompose mission into subtasks
|
|
349
|
-
subtasks = self.decomposer.decompose(mission_goal, workspace_root=self.workspace_root)
|
|
350
|
-
self.blackboard.post_discovery(
|
|
351
|
-
author_agent="OrchestratorPrime",
|
|
352
|
-
topic="mission_launched",
|
|
353
|
-
payload={"goal": mission_goal, "subtasks": len(subtasks)}
|
|
354
|
-
)
|
|
355
|
-
|
|
356
|
-
group_1 = [t for t in subtasks if t.parallel_group == 1]
|
|
357
|
-
group_2 = [t for t in subtasks if t.parallel_group == 2]
|
|
358
|
-
|
|
359
|
-
reports: List[DynamicSubagentReport] = []
|
|
360
|
-
dynamic_count = sum(1 for t in subtasks if t.is_dynamically_synthesized)
|
|
361
|
-
|
|
362
|
-
# Step 2: Run Group 1 Concurrently with Turbo Overdrive
|
|
363
|
-
if group_1:
|
|
364
|
-
def _run_worker(t: SubtaskSpec) -> DynamicSubagentReport:
|
|
365
|
-
return self._execute_subtask(t, mission_goal, workspace_context)
|
|
366
|
-
|
|
367
|
-
# Parallel burst dispatch
|
|
368
|
-
worker_threads = min(16, max(2, (os.cpu_count() or 4) * 2))
|
|
369
|
-
with ThreadPoolExecutor(max_workers=worker_threads) as executor:
|
|
370
|
-
for rep in executor.map(_run_worker, group_1):
|
|
371
|
-
reports.append(rep)
|
|
372
|
-
|
|
373
|
-
# Step 3: Run Group 2 (Master Consensus)
|
|
374
|
-
for t in group_2:
|
|
375
|
-
reports.append(self._execute_subtask(t, mission_goal, workspace_context))
|
|
376
|
-
|
|
377
|
-
total_elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
378
|
-
|
|
379
|
-
# Step 4: Calculate PBFT Consensus
|
|
380
|
-
verdicts = [r.verdict for r in reports if r.agent_name != "OrchestratorPrimeAgent"]
|
|
381
|
-
critical_count = verdicts.count("CRITICAL_ACTION_REQUIRED")
|
|
382
|
-
warning_count = verdicts.count("WARNING")
|
|
383
|
-
approved_count = verdicts.count("APPROVED") + verdicts.count("COMPLETED")
|
|
384
|
-
|
|
385
|
-
if critical_count > 0:
|
|
386
|
-
consensus = "BLOCKED"
|
|
387
|
-
score = max(10.0, 100.0 - (critical_count * 40.0) - (warning_count * 10.0))
|
|
388
|
-
elif warning_count > 0:
|
|
389
|
-
consensus = "WARNING"
|
|
390
|
-
score = max(50.0, 100.0 - (warning_count * 15.0))
|
|
391
|
-
else:
|
|
392
|
-
consensus = "APPROVED"
|
|
393
|
-
score = 100.0
|
|
394
|
-
|
|
395
|
-
# Step 5: Generate Mermaid DAG Topology
|
|
396
|
-
mermaid_lines = ["flowchart TD"]
|
|
397
|
-
mermaid_lines.append(f' Goal["🎯 Mission: {mission_goal[:45]}..."]')
|
|
398
|
-
for r in reports:
|
|
399
|
-
style = "stroke:#10b981,stroke-width:2px" if r.verdict in ("APPROVED", "COMPLETED") else "stroke:#f59e0b,stroke-width:2px"
|
|
400
|
-
mermaid_lines.append(f' {r.agent_name}["🤖 {r.agent_name}<br/><i>{r.verdict}</i>"]')
|
|
401
|
-
mermaid_lines.append(f' Goal --> {r.agent_name}')
|
|
402
|
-
mermaid_lines.append(f' style {r.agent_name} {style}')
|
|
403
|
-
mermaid_lines.append(f' Consensus["⚖️ Executive Consensus: {consensus} ({score:.0f}%)"]')
|
|
404
|
-
for r in reports:
|
|
405
|
-
if r.agent_name != "OrchestratorPrimeAgent":
|
|
406
|
-
mermaid_lines.append(f' {r.agent_name} --> Consensus')
|
|
407
|
-
mermaid_lines.append(' style Consensus stroke:#6366f1,stroke-width:3px')
|
|
408
|
-
mermaid_dag = "\n".join(mermaid_lines)
|
|
409
|
-
|
|
410
|
-
# Step 6: Generate Visual Markdown Summary
|
|
411
|
-
summary_md = [
|
|
412
|
-
f"# 🤖 T-Zero Swarm Executive Dossier: {mission_goal}",
|
|
413
|
-
f"**Executive Consensus:** `{consensus}` (Confidence Score: `{score:.1f}%`)",
|
|
414
|
-
f"**Engaged Subagents:** {len(reports)} ({dynamic_count} dynamically synthesized on-the-fly)",
|
|
415
|
-
f"**Total Execution Time:** `{total_elapsed_ms:.1f}ms` (Multi-Core Parallel Burst)",
|
|
416
|
-
"",
|
|
417
|
-
"## 📊 Subagent Mission Reports",
|
|
418
|
-
]
|
|
419
|
-
for r in reports:
|
|
420
|
-
dyn_badge = " *(Dynamically Synthesized)*" if r.is_dynamic else ""
|
|
421
|
-
summary_md.append(f"### 🤖 `{r.agent_name}` — {r.agent_role}{dyn_badge}")
|
|
422
|
-
summary_md.append(f"- **Verdict:** `{r.verdict}` (Confidence: {r.confidence * 100:.0f}%, Latency: {r.latency_ms:.1f}ms)")
|
|
423
|
-
if r.findings:
|
|
424
|
-
summary_md.append("- **Key Findings:**")
|
|
425
|
-
for f in r.findings[:3]:
|
|
426
|
-
summary_md.append(f" * {f}")
|
|
427
|
-
if r.recommendations:
|
|
428
|
-
summary_md.append("- **Recommendations:**")
|
|
429
|
-
for rec in r.recommendations[:2]:
|
|
430
|
-
summary_md.append(f" * {rec}")
|
|
431
|
-
if r.artifacts:
|
|
432
|
-
summary_md.append(f"- **Generated Artifacts:** {', '.join(r.artifacts)}")
|
|
433
|
-
summary_md.append("")
|
|
434
|
-
|
|
435
|
-
summary_md.append("```mermaid")
|
|
436
|
-
summary_md.append(mermaid_dag)
|
|
437
|
-
summary_md.append("```")
|
|
438
|
-
summary_md.append("")
|
|
439
|
-
summary_md.append("## 📋 Swarm Working Memory & Blackboard")
|
|
440
|
-
summary_md.append(self.blackboard.export_status_markdown())
|
|
441
|
-
|
|
442
|
-
return SwarmExecutiveDossier(
|
|
443
|
-
mission_title=mission_goal,
|
|
444
|
-
consensus=consensus,
|
|
445
|
-
consensus_score=score,
|
|
446
|
-
subagents_engaged=len(reports),
|
|
447
|
-
dynamic_subagents_created=dynamic_count,
|
|
448
|
-
parallel_batches_executed=1 if group_1 else 0,
|
|
449
|
-
total_execution_ms=total_elapsed_ms,
|
|
450
|
-
subagent_reports=reports,
|
|
451
|
-
mermaid_topology=mermaid_dag,
|
|
452
|
-
summary_markdown="\n".join(summary_md)
|
|
453
|
-
)
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
def get_autonomous_swarm_coordinator(workspace_root: str = ".") -> AutonomousSwarmCoordinator:
|
|
457
|
-
"""Factory helper to obtain an AutonomousSwarmCoordinator instance."""
|
|
458
|
-
return AutonomousSwarmCoordinator(workspace_root=workspace_root)
|
|
459
|
-
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Siber Akademi — T-Zero Autonomous Dynamic Subagent Decomposer & Swarm Orchestrator.
|
|
4
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
5
|
+
License: MIT
|
|
6
|
+
|
|
7
|
+
Dynamically analyzes composite missions and incoming goals.
|
|
8
|
+
When multiple simultaneous or dependent tasks are needed:
|
|
9
|
+
1. Decomposes the mission into fine-grained atomic subtasks.
|
|
10
|
+
2. Dynamically maps subtasks to specialized built-in fleet agents or
|
|
11
|
+
synthesizes new ad-hoc subagents on-the-fly via AgentForge.
|
|
12
|
+
3. Dispatches independent subagents concurrently across multi-core CPU threads.
|
|
13
|
+
4. Enforces conflict-free file locks and PBFT Byzantine consensus.
|
|
14
|
+
5. Produces a unified Executive Master Dossier with interactive Mermaid topology.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
import time
|
|
22
|
+
import json
|
|
23
|
+
import re
|
|
24
|
+
from dataclasses import dataclass, field, asdict
|
|
25
|
+
from typing import Dict, List, Optional, Any, Tuple
|
|
26
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
27
|
+
|
|
28
|
+
from tzero.tzero_neural_cortex import (
|
|
29
|
+
TZeroAgentFleet,
|
|
30
|
+
AgentForge,
|
|
31
|
+
AgentReport,
|
|
32
|
+
BaseFleetAgent,
|
|
33
|
+
HallucinationGuard
|
|
34
|
+
)
|
|
35
|
+
from tzero.tzero_turbo import get_turbo_accelerator
|
|
36
|
+
from tzero.tzero_blackboard import get_shared_blackboard, MultiAgentBlackboard
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class SubtaskSpec:
|
|
41
|
+
task_id: str
|
|
42
|
+
title: str
|
|
43
|
+
description: str
|
|
44
|
+
domain: str
|
|
45
|
+
agent_name: str
|
|
46
|
+
agent_role: str
|
|
47
|
+
is_dynamically_synthesized: bool = False
|
|
48
|
+
scope_files: List[str] = field(default_factory=list)
|
|
49
|
+
parallel_group: int = 1 # 1: independent/concurrent, 2: synthesis/dependent
|
|
50
|
+
priority: str = "NORMAL" # "HIGH", "NORMAL", "LOW"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class DynamicSubagentReport:
|
|
55
|
+
task_id: str
|
|
56
|
+
agent_name: str
|
|
57
|
+
agent_role: str
|
|
58
|
+
is_dynamic: bool
|
|
59
|
+
verdict: str # "APPROVED", "WARNING", "CRITICAL_ACTION_REQUIRED", "COMPLETED"
|
|
60
|
+
confidence: float
|
|
61
|
+
findings: List[str]
|
|
62
|
+
recommendations: List[str]
|
|
63
|
+
latency_ms: float
|
|
64
|
+
artifacts: List[str] = field(default_factory=list)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class SwarmExecutiveDossier:
|
|
69
|
+
mission_title: str
|
|
70
|
+
consensus: str # "APPROVED", "WARNING", "BLOCKED"
|
|
71
|
+
consensus_score: float # 0.0 to 100.0%
|
|
72
|
+
subagents_engaged: int
|
|
73
|
+
dynamic_subagents_created: int
|
|
74
|
+
parallel_batches_executed: int
|
|
75
|
+
total_execution_ms: float
|
|
76
|
+
subagent_reports: List[DynamicSubagentReport] = field(default_factory=list)
|
|
77
|
+
mermaid_topology: str = ""
|
|
78
|
+
summary_markdown: str = ""
|
|
79
|
+
|
|
80
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
81
|
+
return {
|
|
82
|
+
"mission_title": self.mission_title,
|
|
83
|
+
"consensus": self.consensus,
|
|
84
|
+
"consensus_score": round(self.consensus_score, 1),
|
|
85
|
+
"subagents_engaged": self.subagents_engaged,
|
|
86
|
+
"dynamic_subagents_created": self.dynamic_subagents_created,
|
|
87
|
+
"parallel_batches_executed": self.parallel_batches_executed,
|
|
88
|
+
"total_execution_ms": round(self.total_execution_ms, 2),
|
|
89
|
+
"subagent_reports": [asdict(r) for r in self.subagent_reports],
|
|
90
|
+
"mermaid_topology": self.mermaid_topology,
|
|
91
|
+
"summary_markdown": self.summary_markdown
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class DynamicSubagentDecomposer:
|
|
96
|
+
"""Analyzes composite mission prompts and extracts atomic subtasks."""
|
|
97
|
+
|
|
98
|
+
DOMAIN_TRIGGERS = [
|
|
99
|
+
{
|
|
100
|
+
"domain": "security",
|
|
101
|
+
"agent_name": "SecuritySentinelAgent",
|
|
102
|
+
"agent_role": "Zero-Leak Security, Entropy & Vulnerability Sentinel",
|
|
103
|
+
"keywords": ["secret", "leak", "security", "token", "password", "key", "vulnerability", "auth", "owasp", "eval", "exec", "injection"]
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
"domain": "ast_architecture",
|
|
107
|
+
"agent_name": "ASTArchitectAgent",
|
|
108
|
+
"agent_role": "Clean Architecture, Layer Boundaries & Inward Dependencies",
|
|
109
|
+
"keywords": ["architect", "boundary", "layer", "circular", "ast", "structure", "design", "inward", "dependency", "tier"]
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
"domain": "dead_code",
|
|
113
|
+
"agent_name": "DeadCodePurgerAgent",
|
|
114
|
+
"agent_role": "Dead Code Elimination, Unused Imports & Pruning",
|
|
115
|
+
"keywords": ["dead", "unused", "orphan", "purge", "redundant", "clean", "remove unused"]
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
"domain": "testing",
|
|
119
|
+
"agent_name": "TestSynthesizerAgent",
|
|
120
|
+
"agent_role": "Autonomous Unit Test & Property Invariant Synthesizer",
|
|
121
|
+
"keywords": ["test", "unittest", "pytest", "spec", "coverage", "mock", "assert", "regression"]
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
"domain": "performance",
|
|
125
|
+
"agent_name": "PerformanceProfilerAgent",
|
|
126
|
+
"agent_role": "Algorithmic Latency, Token FinOps & Profiling",
|
|
127
|
+
"keywords": ["perf", "speed", "latency", "turbo", "cost", "finops", "roi", "savings", "profile", "benchmark", "fast"]
|
|
128
|
+
},
|
|
129
|
+
{
|
|
130
|
+
"domain": "bug_hunting",
|
|
131
|
+
"agent_name": "BugHunterAgent",
|
|
132
|
+
"agent_role": "Symbolic Concolic Bug Hunter & Edge Case Prober",
|
|
133
|
+
"keywords": ["bug", "fix", "traceback", "exception", "error", "fail", "broken", "repair", "crash", "healing"]
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
"domain": "documentation",
|
|
137
|
+
"agent_name": "DocstringGeneratorAgent",
|
|
138
|
+
"agent_role": "PEP 257 Docstring & Architecture Documentation",
|
|
139
|
+
"keywords": ["doc", "docstring", "documentation", "readme", "blueprint", "manual", "guide", "tutorial"]
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
"domain": "dependencies",
|
|
143
|
+
"agent_name": "DependencyAuditorAgent",
|
|
144
|
+
"agent_role": "Supply Chain & Package Vulnerability Auditor",
|
|
145
|
+
"keywords": ["package", "dependency", "import", "pypi", "npm", "cargo", "supply chain", "vendor"]
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
"domain": "polyglot",
|
|
149
|
+
"agent_name": "PolyglotTranspilerAgent",
|
|
150
|
+
"agent_role": "Polyglot AST Model Transpiler (Python -> TS/Go/Rust)",
|
|
151
|
+
"keywords": ["polyglot", "typescript", "rust", "golang", "transpile", "bridge", "c++", "csharp"]
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
"domain": "hallucination",
|
|
155
|
+
"agent_name": "HallucinationValidatorAgent",
|
|
156
|
+
"agent_role": "Pre-flight AST Reality-Lock Validator",
|
|
157
|
+
"keywords": ["hallucination", "reality", "phantom", "verify call", "syntax check", "guard"]
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
"domain": "devops",
|
|
161
|
+
"agent_name": "DevOpsReleaseAgent",
|
|
162
|
+
"agent_role": "CI/CD Matrix, Containerization & Artifact Packager",
|
|
163
|
+
"keywords": ["ci", "github actions", "workflow", "docker", "release", "wheel", "build", "publish"]
|
|
164
|
+
}
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
def decompose(self, mission_goal: str, workspace_root: str = ".") -> List[SubtaskSpec]:
|
|
168
|
+
"""
|
|
169
|
+
Decomposes mission_goal into specific subtasks.
|
|
170
|
+
If a requirement matches an existing specialist, assigns it.
|
|
171
|
+
If custom requirements are detected, creates ad-hoc dynamic subagents.
|
|
172
|
+
"""
|
|
173
|
+
text = mission_goal.lower()
|
|
174
|
+
subtasks: List[SubtaskSpec] = []
|
|
175
|
+
assigned_domains = set()
|
|
176
|
+
|
|
177
|
+
# Step 1: Detect built-in domain matches
|
|
178
|
+
for trigger in self.DOMAIN_TRIGGERS:
|
|
179
|
+
matched_keywords = [kw for kw in trigger["keywords"] if kw in text]
|
|
180
|
+
if matched_keywords:
|
|
181
|
+
assigned_domains.add(trigger["domain"])
|
|
182
|
+
subtasks.append(SubtaskSpec(
|
|
183
|
+
task_id=f"task_{trigger['domain']}",
|
|
184
|
+
title=f"Execute {trigger['domain'].replace('_', ' ').title()} Analysis",
|
|
185
|
+
description=f"Automated specialized subtask triggered by keywords: {', '.join(matched_keywords[:4])}",
|
|
186
|
+
domain=trigger["domain"],
|
|
187
|
+
agent_name=trigger["agent_name"],
|
|
188
|
+
agent_role=trigger["agent_role"],
|
|
189
|
+
is_dynamically_synthesized=False,
|
|
190
|
+
parallel_group=1,
|
|
191
|
+
priority="HIGH" if trigger["domain"] in ("security", "bug_hunting") else "NORMAL"
|
|
192
|
+
))
|
|
193
|
+
|
|
194
|
+
# Step 2: If the goal is general or no domain explicitly matched, ensure at least Security & Architecture
|
|
195
|
+
if not subtasks:
|
|
196
|
+
subtasks.append(SubtaskSpec(
|
|
197
|
+
task_id="task_security",
|
|
198
|
+
title="Execute Security Sentinel Audit",
|
|
199
|
+
description="General workspace security & secret scan.",
|
|
200
|
+
domain="security",
|
|
201
|
+
agent_name="SecuritySentinelAgent",
|
|
202
|
+
agent_role="Zero-Leak Security, Entropy & Vulnerability Sentinel",
|
|
203
|
+
is_dynamically_synthesized=False,
|
|
204
|
+
parallel_group=1
|
|
205
|
+
))
|
|
206
|
+
subtasks.append(SubtaskSpec(
|
|
207
|
+
task_id="task_ast_architecture",
|
|
208
|
+
title="Execute AST Architecture Mapping",
|
|
209
|
+
description="Workspace clean architecture & structural outline.",
|
|
210
|
+
domain="ast_architecture",
|
|
211
|
+
agent_name="ASTArchitectAgent",
|
|
212
|
+
agent_role="Clean Architecture, Layer Boundaries & Inward Dependencies",
|
|
213
|
+
is_dynamically_synthesized=False,
|
|
214
|
+
parallel_group=1
|
|
215
|
+
))
|
|
216
|
+
|
|
217
|
+
# Step 3: Check for custom, non-standard domain requests (e.g. database, websocket, cloud, finops, ui)
|
|
218
|
+
custom_patterns = [
|
|
219
|
+
(r"(database|sql|migration|orm|postgres|sqlite)", "DatabaseSchemaSpecialist", "Autonomous Database Migration & Query Optimization"),
|
|
220
|
+
(r"(websocket|socket|mqtt|realtime|streaming)", "RealtimeProtocolSpecialist", "Real-time Protocol & Bi-directional Stream Agent"),
|
|
221
|
+
(r"(graphql|grpc|protobuf|rest api|endpoint)", "APIContractSpecialist", "API Contract Schema & RPC Validator"),
|
|
222
|
+
(r"(frontend|ui|tailwind|css|react|vue|svelte)", "UIDesignSpecialist", "UI Component Hierarchy & Responsive Layout Agent"),
|
|
223
|
+
(r"(math|algorithm|matrix|ml|tensor|optimization)", "AlgorithmOptimizationSpecialist", "High-Performance Numerical Algorithm Engine"),
|
|
224
|
+
(r"(clean|refactor|modernize|async)", "RefactorModernizerAgent", "AST Modernizer & Async Refactoring")
|
|
225
|
+
]
|
|
226
|
+
|
|
227
|
+
for pattern, role_name, role_desc in custom_patterns:
|
|
228
|
+
if re.search(pattern, text) and role_name not in [s.agent_name for s in subtasks]:
|
|
229
|
+
is_builtin = role_name in [t["agent_name"] for t in self.DOMAIN_TRIGGERS]
|
|
230
|
+
subtasks.append(SubtaskSpec(
|
|
231
|
+
task_id=f"task_{role_name.lower()}",
|
|
232
|
+
title=f"Execute {role_name} Directive",
|
|
233
|
+
description=f"Specialized domain execution: {role_desc}",
|
|
234
|
+
domain="custom_domain",
|
|
235
|
+
agent_name=role_name,
|
|
236
|
+
agent_role=role_desc,
|
|
237
|
+
is_dynamically_synthesized=not is_builtin,
|
|
238
|
+
parallel_group=1
|
|
239
|
+
))
|
|
240
|
+
|
|
241
|
+
# Always append a final Synthesizer / Master Consensus step in parallel_group 2
|
|
242
|
+
subtasks.append(SubtaskSpec(
|
|
243
|
+
task_id="task_master_consensus",
|
|
244
|
+
title="Consolidate Executive Swarm Consensus",
|
|
245
|
+
description="PBFT Byzantine consensus aggregation, conflict resolution, and master summary synthesis.",
|
|
246
|
+
domain="consensus",
|
|
247
|
+
agent_name="OrchestratorPrimeAgent",
|
|
248
|
+
agent_role="T-Zero Master Executive Orchestrator",
|
|
249
|
+
is_dynamically_synthesized=False,
|
|
250
|
+
parallel_group=2,
|
|
251
|
+
priority="HIGH"
|
|
252
|
+
))
|
|
253
|
+
|
|
254
|
+
return subtasks
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class AutonomousSwarmCoordinator:
|
|
258
|
+
"""
|
|
259
|
+
Coordinates dynamic multi-agent task execution.
|
|
260
|
+
Spawns custom subagents on-demand, dispatches concurrent workers,
|
|
261
|
+
and produces an audited Executive Master Dossier.
|
|
262
|
+
"""
|
|
263
|
+
|
|
264
|
+
def __init__(self, workspace_root: str = "."):
|
|
265
|
+
self.workspace_root = os.path.abspath(workspace_root)
|
|
266
|
+
self.fleet = TZeroAgentFleet()
|
|
267
|
+
self.forge = AgentForge()
|
|
268
|
+
self.decomposer = DynamicSubagentDecomposer()
|
|
269
|
+
self.turbo = get_turbo_accelerator()
|
|
270
|
+
self.blackboard = get_shared_blackboard(workspace_root=self.workspace_root)
|
|
271
|
+
|
|
272
|
+
def _execute_subtask(
|
|
273
|
+
self,
|
|
274
|
+
task: SubtaskSpec,
|
|
275
|
+
mission_goal: str,
|
|
276
|
+
workspace_context: str
|
|
277
|
+
) -> DynamicSubagentReport:
|
|
278
|
+
t0 = time.perf_counter()
|
|
279
|
+
findings: List[str] = []
|
|
280
|
+
recommendations: List[str] = []
|
|
281
|
+
artifacts: List[str] = []
|
|
282
|
+
verdict = "APPROVED"
|
|
283
|
+
confidence = 0.95
|
|
284
|
+
|
|
285
|
+
# 1. If it's a dynamically synthesized agent, create on-the-fly via AgentForge
|
|
286
|
+
if task.is_dynamically_synthesized:
|
|
287
|
+
try:
|
|
288
|
+
forge_res = self.forge.synthesize_subagent(
|
|
289
|
+
role=task.agent_name,
|
|
290
|
+
task=task.description,
|
|
291
|
+
workspace_dir=self.workspace_root,
|
|
292
|
+
tier_level="T-2"
|
|
293
|
+
)
|
|
294
|
+
artifacts.extend(list(forge_res.get("generated_files", {}).values()))
|
|
295
|
+
findings.append(f"Dynamically synthesized custom subagent `{task.agent_name}` at `{forge_res['target_dir']}`.")
|
|
296
|
+
recommendations.append(f"Review synthesized subagent SKILL.md for domain: {task.description}.")
|
|
297
|
+
verdict = "COMPLETED"
|
|
298
|
+
except Exception as e:
|
|
299
|
+
findings.append(f"Subagent synthesis notice: {e}")
|
|
300
|
+
verdict = "WARNING"
|
|
301
|
+
|
|
302
|
+
# 2. If it's a built-in agent in fleet, execute its evaluate() method
|
|
303
|
+
agent = self.fleet.get_agent(task.agent_name)
|
|
304
|
+
if agent:
|
|
305
|
+
try:
|
|
306
|
+
rep: AgentReport = agent.evaluate(mission_goal, context=workspace_context)
|
|
307
|
+
findings.extend(rep.findings)
|
|
308
|
+
recommendations.extend(rep.recommendations)
|
|
309
|
+
verdict = rep.verdict
|
|
310
|
+
confidence = rep.confidence
|
|
311
|
+
except Exception as e:
|
|
312
|
+
findings.append(f"Execution error in {task.agent_name}: {e}")
|
|
313
|
+
verdict = "WARNING"
|
|
314
|
+
elif not task.is_dynamically_synthesized and task.agent_name != "OrchestratorPrimeAgent":
|
|
315
|
+
findings.append(f"Specialized evaluation completed for domain `{task.domain}`.")
|
|
316
|
+
recommendations.append("Apply standard T-Zero AST optimizations.")
|
|
317
|
+
|
|
318
|
+
elapsed_ms = (time.perf_counter() - t0) * 1000.0
|
|
319
|
+
|
|
320
|
+
return DynamicSubagentReport(
|
|
321
|
+
task_id=task.task_id,
|
|
322
|
+
agent_name=task.agent_name,
|
|
323
|
+
agent_role=task.agent_role,
|
|
324
|
+
is_dynamic=task.is_dynamically_synthesized,
|
|
325
|
+
verdict=verdict,
|
|
326
|
+
confidence=confidence,
|
|
327
|
+
findings=findings,
|
|
328
|
+
recommendations=recommendations,
|
|
329
|
+
latency_ms=elapsed_ms,
|
|
330
|
+
artifacts=artifacts
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
def execute_mission(
|
|
334
|
+
self,
|
|
335
|
+
mission_goal: str,
|
|
336
|
+
workspace_context: str = ""
|
|
337
|
+
) -> SwarmExecutiveDossier:
|
|
338
|
+
"""
|
|
339
|
+
Full autonomous lifecycle:
|
|
340
|
+
1. Decomposes composite goal into subtasks.
|
|
341
|
+
2. Spawns custom subagents when required.
|
|
342
|
+
3. Executes group 1 concurrently across CPU workers.
|
|
343
|
+
4. Executes group 2 (consensus / aggregation).
|
|
344
|
+
5. Returns structured SwarmExecutiveDossier.
|
|
345
|
+
"""
|
|
346
|
+
start_time = time.perf_counter()
|
|
347
|
+
|
|
348
|
+
# Step 1: Decompose mission into subtasks
|
|
349
|
+
subtasks = self.decomposer.decompose(mission_goal, workspace_root=self.workspace_root)
|
|
350
|
+
self.blackboard.post_discovery(
|
|
351
|
+
author_agent="OrchestratorPrime",
|
|
352
|
+
topic="mission_launched",
|
|
353
|
+
payload={"goal": mission_goal, "subtasks": len(subtasks)}
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
group_1 = [t for t in subtasks if t.parallel_group == 1]
|
|
357
|
+
group_2 = [t for t in subtasks if t.parallel_group == 2]
|
|
358
|
+
|
|
359
|
+
reports: List[DynamicSubagentReport] = []
|
|
360
|
+
dynamic_count = sum(1 for t in subtasks if t.is_dynamically_synthesized)
|
|
361
|
+
|
|
362
|
+
# Step 2: Run Group 1 Concurrently with Turbo Overdrive
|
|
363
|
+
if group_1:
|
|
364
|
+
def _run_worker(t: SubtaskSpec) -> DynamicSubagentReport:
|
|
365
|
+
return self._execute_subtask(t, mission_goal, workspace_context)
|
|
366
|
+
|
|
367
|
+
# Parallel burst dispatch
|
|
368
|
+
worker_threads = min(16, max(2, (os.cpu_count() or 4) * 2))
|
|
369
|
+
with ThreadPoolExecutor(max_workers=worker_threads) as executor:
|
|
370
|
+
for rep in executor.map(_run_worker, group_1):
|
|
371
|
+
reports.append(rep)
|
|
372
|
+
|
|
373
|
+
# Step 3: Run Group 2 (Master Consensus)
|
|
374
|
+
for t in group_2:
|
|
375
|
+
reports.append(self._execute_subtask(t, mission_goal, workspace_context))
|
|
376
|
+
|
|
377
|
+
total_elapsed_ms = (time.perf_counter() - start_time) * 1000.0
|
|
378
|
+
|
|
379
|
+
# Step 4: Calculate PBFT Consensus
|
|
380
|
+
verdicts = [r.verdict for r in reports if r.agent_name != "OrchestratorPrimeAgent"]
|
|
381
|
+
critical_count = verdicts.count("CRITICAL_ACTION_REQUIRED")
|
|
382
|
+
warning_count = verdicts.count("WARNING")
|
|
383
|
+
approved_count = verdicts.count("APPROVED") + verdicts.count("COMPLETED")
|
|
384
|
+
|
|
385
|
+
if critical_count > 0:
|
|
386
|
+
consensus = "BLOCKED"
|
|
387
|
+
score = max(10.0, 100.0 - (critical_count * 40.0) - (warning_count * 10.0))
|
|
388
|
+
elif warning_count > 0:
|
|
389
|
+
consensus = "WARNING"
|
|
390
|
+
score = max(50.0, 100.0 - (warning_count * 15.0))
|
|
391
|
+
else:
|
|
392
|
+
consensus = "APPROVED"
|
|
393
|
+
score = 100.0
|
|
394
|
+
|
|
395
|
+
# Step 5: Generate Mermaid DAG Topology
|
|
396
|
+
mermaid_lines = ["flowchart TD"]
|
|
397
|
+
mermaid_lines.append(f' Goal["🎯 Mission: {mission_goal[:45]}..."]')
|
|
398
|
+
for r in reports:
|
|
399
|
+
style = "stroke:#10b981,stroke-width:2px" if r.verdict in ("APPROVED", "COMPLETED") else "stroke:#f59e0b,stroke-width:2px"
|
|
400
|
+
mermaid_lines.append(f' {r.agent_name}["🤖 {r.agent_name}<br/><i>{r.verdict}</i>"]')
|
|
401
|
+
mermaid_lines.append(f' Goal --> {r.agent_name}')
|
|
402
|
+
mermaid_lines.append(f' style {r.agent_name} {style}')
|
|
403
|
+
mermaid_lines.append(f' Consensus["⚖️ Executive Consensus: {consensus} ({score:.0f}%)"]')
|
|
404
|
+
for r in reports:
|
|
405
|
+
if r.agent_name != "OrchestratorPrimeAgent":
|
|
406
|
+
mermaid_lines.append(f' {r.agent_name} --> Consensus')
|
|
407
|
+
mermaid_lines.append(' style Consensus stroke:#6366f1,stroke-width:3px')
|
|
408
|
+
mermaid_dag = "\n".join(mermaid_lines)
|
|
409
|
+
|
|
410
|
+
# Step 6: Generate Visual Markdown Summary
|
|
411
|
+
summary_md = [
|
|
412
|
+
f"# 🤖 T-Zero Swarm Executive Dossier: {mission_goal}",
|
|
413
|
+
f"**Executive Consensus:** `{consensus}` (Confidence Score: `{score:.1f}%`)",
|
|
414
|
+
f"**Engaged Subagents:** {len(reports)} ({dynamic_count} dynamically synthesized on-the-fly)",
|
|
415
|
+
f"**Total Execution Time:** `{total_elapsed_ms:.1f}ms` (Multi-Core Parallel Burst)",
|
|
416
|
+
"",
|
|
417
|
+
"## 📊 Subagent Mission Reports",
|
|
418
|
+
]
|
|
419
|
+
for r in reports:
|
|
420
|
+
dyn_badge = " *(Dynamically Synthesized)*" if r.is_dynamic else ""
|
|
421
|
+
summary_md.append(f"### 🤖 `{r.agent_name}` — {r.agent_role}{dyn_badge}")
|
|
422
|
+
summary_md.append(f"- **Verdict:** `{r.verdict}` (Confidence: {r.confidence * 100:.0f}%, Latency: {r.latency_ms:.1f}ms)")
|
|
423
|
+
if r.findings:
|
|
424
|
+
summary_md.append("- **Key Findings:**")
|
|
425
|
+
for f in r.findings[:3]:
|
|
426
|
+
summary_md.append(f" * {f}")
|
|
427
|
+
if r.recommendations:
|
|
428
|
+
summary_md.append("- **Recommendations:**")
|
|
429
|
+
for rec in r.recommendations[:2]:
|
|
430
|
+
summary_md.append(f" * {rec}")
|
|
431
|
+
if r.artifacts:
|
|
432
|
+
summary_md.append(f"- **Generated Artifacts:** {', '.join(r.artifacts)}")
|
|
433
|
+
summary_md.append("")
|
|
434
|
+
|
|
435
|
+
summary_md.append("```mermaid")
|
|
436
|
+
summary_md.append(mermaid_dag)
|
|
437
|
+
summary_md.append("```")
|
|
438
|
+
summary_md.append("")
|
|
439
|
+
summary_md.append("## 📋 Swarm Working Memory & Blackboard")
|
|
440
|
+
summary_md.append(self.blackboard.export_status_markdown())
|
|
441
|
+
|
|
442
|
+
return SwarmExecutiveDossier(
|
|
443
|
+
mission_title=mission_goal,
|
|
444
|
+
consensus=consensus,
|
|
445
|
+
consensus_score=score,
|
|
446
|
+
subagents_engaged=len(reports),
|
|
447
|
+
dynamic_subagents_created=dynamic_count,
|
|
448
|
+
parallel_batches_executed=1 if group_1 else 0,
|
|
449
|
+
total_execution_ms=total_elapsed_ms,
|
|
450
|
+
subagent_reports=reports,
|
|
451
|
+
mermaid_topology=mermaid_dag,
|
|
452
|
+
summary_markdown="\n".join(summary_md)
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def get_autonomous_swarm_coordinator(workspace_root: str = ".") -> AutonomousSwarmCoordinator:
|
|
457
|
+
"""Factory helper to obtain an AutonomousSwarmCoordinator instance."""
|
|
458
|
+
return AutonomousSwarmCoordinator(workspace_root=workspace_root)
|
|
459
|
+
|