@ctxthuta/cxops 0.0.0-stage → 1.0.1

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.
Files changed (54) hide show
  1. package/.agents/agents/academic_researcher/agent.md +97 -0
  2. package/.agents/agents/ai_ml_engineer/agent.md +43 -0
  3. package/.agents/agents/backend_engineer/agent.md +44 -0
  4. package/.agents/agents/code_reviewer/agent.md +38 -0
  5. package/.agents/agents/cxagents/agent.md +47 -0
  6. package/.agents/agents/devops_engineer/agent.md +41 -0
  7. package/.agents/agents/frontend_engineer/agent.md +43 -0
  8. package/.agents/agents/qa_engineer/agent.md +42 -0
  9. package/.agents/agents/rnd_researcher/agent.md +44 -0
  10. package/.agents/agents/software_engineer/agent.md +37 -0
  11. package/.agents/agents/system_architect/agent.md +56 -0
  12. package/.agents/agents/uiux_designer/agent.md +52 -0
  13. package/AGENTS.md +226 -0
  14. package/IMPLEMENTATION_GUIDE.md +241 -0
  15. package/README.md +147 -2
  16. package/bin/cxops.js +430 -0
  17. package/package.json +52 -4
  18. package/plugin/agents/academic_researcher.md +97 -0
  19. package/plugin/agents/ai_ml_engineer.md +43 -0
  20. package/plugin/agents/backend_engineer.md +44 -0
  21. package/plugin/agents/code_reviewer.md +38 -0
  22. package/plugin/agents/cxagents.md +47 -0
  23. package/plugin/agents/devops_engineer.md +41 -0
  24. package/plugin/agents/frontend_engineer.md +43 -0
  25. package/plugin/agents/qa_engineer.md +42 -0
  26. package/plugin/agents/rnd_researcher.md +44 -0
  27. package/plugin/agents/software_engineer.md +37 -0
  28. package/plugin/agents/system_architect.md +56 -0
  29. package/plugin/agents/uiux_designer.md +52 -0
  30. package/plugin/plugin.json +23 -0
  31. package/plugin/rules/AGENTS.md +226 -0
  32. package/plugin/skills/academic-researcher/SKILL.md +29 -0
  33. package/plugin/skills/ai-ml-engineer/SKILL.md +28 -0
  34. package/plugin/skills/backend-engineer/SKILL.md +35 -0
  35. package/plugin/skills/code-reviewer/SKILL.md +26 -0
  36. package/plugin/skills/cxagents/SKILL.md +35 -0
  37. package/plugin/skills/devops-engineer/SKILL.md +27 -0
  38. package/plugin/skills/frontend-engineer/SKILL.md +41 -0
  39. package/plugin/skills/qa-engineer/SKILL.md +25 -0
  40. package/plugin/skills/rnd-researcher/SKILL.md +31 -0
  41. package/plugin/skills/software-engineer/SKILL.md +28 -0
  42. package/plugin/skills/system-architect/SKILL.md +43 -0
  43. package/plugin/skills/uiux-designer/SKILL.md +41 -0
  44. package/requirements.txt +5 -0
  45. package/src/agents/personas.py +618 -0
  46. package/src/dashboard.py +376 -0
  47. package/src/main.py +49 -0
  48. package/src/team.py +125 -0
  49. package/src/tools/arxiv_search.py +90 -0
  50. package/src/tools/code_tools.py +92 -0
  51. package/src/tools/cortex_tools.py +175 -0
  52. package/src/tools/test_runner.py +45 -0
  53. package/src/tools/web_research.py +106 -0
  54. package/verify_agents.py +61 -0
@@ -0,0 +1,376 @@
1
+ #!/usr/bin/env python3
2
+ """Cross-Platform Colored Operational Dashboard for CortexOps Multi-Agent Framework.
3
+
4
+ Displays agent registry health, Antigravity token telemetry, ThutaCortex second brain
5
+ metrics, and git version control status on Linux, macOS, and Windows with ANSI color styling.
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ import os
11
+ import platform
12
+ import sys
13
+ import time
14
+ from pathlib import Path
15
+
16
+ BASE_DIR = Path(__file__).resolve().parent.parent
17
+ PLUGIN_AGENTS_DIR = BASE_DIR / "plugin" / "agents"
18
+
19
+
20
+ class Colors:
21
+ """ANSI color codes with automatic terminal detection."""
22
+ def __init__(self, enabled: bool = True):
23
+ self.enabled = enabled
24
+
25
+ @property
26
+ def RESET(self) -> str:
27
+ return "\033[0m" if self.enabled else ""
28
+
29
+ @property
30
+ def BOLD(self) -> str:
31
+ return "\033[1m" if self.enabled else ""
32
+
33
+ @property
34
+ def DIM(self) -> str:
35
+ return "\033[2m" if self.enabled else ""
36
+
37
+ @property
38
+ def UNDERLINE(self) -> str:
39
+ return "\033[4m" if self.enabled else ""
40
+
41
+ @property
42
+ def RED(self) -> str:
43
+ return "\033[31m" if self.enabled else ""
44
+
45
+ @property
46
+ def GREEN(self) -> str:
47
+ return "\033[32m" if self.enabled else ""
48
+
49
+ @property
50
+ def YELLOW(self) -> str:
51
+ return "\033[33m" if self.enabled else ""
52
+
53
+ @property
54
+ def BLUE(self) -> str:
55
+ return "\033[34m" if self.enabled else ""
56
+
57
+ @property
58
+ def MAGENTA(self) -> str:
59
+ return "\033[35m" if self.enabled else ""
60
+
61
+ @property
62
+ def CYAN(self) -> str:
63
+ return "\033[36m" if self.enabled else ""
64
+
65
+ @property
66
+ def WHITE(self) -> str:
67
+ return "\033[37m" if self.enabled else ""
68
+
69
+ @property
70
+ def BRIGHT_GREEN(self) -> str:
71
+ return "\033[92m" if self.enabled else ""
72
+
73
+ @property
74
+ def BRIGHT_YELLOW(self) -> str:
75
+ return "\033[93m" if self.enabled else ""
76
+
77
+ @property
78
+ def BRIGHT_BLUE(self) -> str:
79
+ return "\033[94m" if self.enabled else ""
80
+
81
+ @property
82
+ def BRIGHT_MAGENTA(self) -> str:
83
+ return "\033[95m" if self.enabled else ""
84
+
85
+ @property
86
+ def BRIGHT_CYAN(self) -> str:
87
+ return "\033[96m" if self.enabled else ""
88
+
89
+ @property
90
+ def BRIGHT_WHITE(self) -> str:
91
+ return "\033[97m" if self.enabled else ""
92
+
93
+
94
+ def _get_antigravity_brain_dir() -> Path | None:
95
+ """Locates the Antigravity session brain directory across OS environments."""
96
+ home = Path.home()
97
+ candidates = [
98
+ home / ".gemini" / "antigravity-cli" / "brain",
99
+ home / ".gemini" / "antigravity" / "brain",
100
+ ]
101
+ for c in candidates:
102
+ if c.exists():
103
+ return c
104
+ return None
105
+
106
+
107
+ def _get_cortex_dir() -> Path | None:
108
+ """Locates ThutaCortex vault directory across OS environments."""
109
+ home = Path.home()
110
+ candidates = [
111
+ home / "Documents" / "ThutaCortex",
112
+ home / "Documents" / "Obsidian" / "ThutaCortex",
113
+ Path("/home/lenovo/Documents/ThutaCortex"),
114
+ ]
115
+ for c in candidates:
116
+ if c.exists():
117
+ return c
118
+ return None
119
+
120
+
121
+ def _get_latest_session_transcript(brain_dir: Path | None) -> tuple[Path | None, str]:
122
+ """Finds the most recently modified session transcript."""
123
+ if not brain_dir or not brain_dir.exists():
124
+ return None, "Not Found"
125
+
126
+ latest_file = None
127
+ latest_mtime = 0.0
128
+ session_id = "Unknown"
129
+
130
+ for session_folder in brain_dir.iterdir():
131
+ if session_folder.is_dir() and not session_folder.name.startswith("."):
132
+ t_file = session_folder / ".system_generated" / "logs" / "transcript.jsonl"
133
+ if t_file.exists():
134
+ mtime = t_file.stat().st_mtime
135
+ if mtime > latest_mtime:
136
+ latest_mtime = mtime
137
+ latest_file = t_file
138
+ session_id = session_folder.name
139
+
140
+ return latest_file, session_id
141
+
142
+
143
+ def parse_antigravity_telemetry(transcript_file: Path | None) -> dict:
144
+ """Parses transcript log to extract token usage, turns, and tool calls."""
145
+ metrics = {
146
+ "turns": 0,
147
+ "input_tokens": 0,
148
+ "output_tokens": 0,
149
+ "cache_read_tokens": 0,
150
+ "total_tokens": 0,
151
+ "tool_calls": {},
152
+ "last_activity": "None",
153
+ }
154
+ if not transcript_file or not transcript_file.exists():
155
+ return metrics
156
+
157
+ try:
158
+ with open(transcript_file, "r", encoding="utf-8") as f:
159
+ for line in f:
160
+ if not line.strip():
161
+ continue
162
+ data = json.loads(line)
163
+ if data.get("type") == "PLANNER_RESPONSE":
164
+ metrics["turns"] += 1
165
+ in_tok = data.get("input_tokens", 0)
166
+ out_tok = data.get("output_tokens", 0)
167
+ cache_tok = data.get("cache_read_tokens", 0)
168
+ metrics["input_tokens"] += in_tok
169
+ metrics["output_tokens"] += out_tok
170
+ metrics["cache_read_tokens"] += cache_tok
171
+ metrics["total_tokens"] += (in_tok + out_tok + cache_tok)
172
+ metrics["last_activity"] = data.get("created_at", "Unknown")
173
+
174
+ for call in data.get("tool_calls", []):
175
+ name = call.get("name", "unknown")
176
+ metrics["tool_calls"][name] = metrics["tool_calls"].get(name, 0) + 1
177
+ except Exception as e:
178
+ metrics["error"] = str(e)
179
+
180
+ return metrics
181
+
182
+
183
+ def get_cortex_metrics(cortex_dir: Path | None) -> dict:
184
+ """Computes second brain inventory statistics."""
185
+ stats = {
186
+ "available": False,
187
+ "path": "Not configured",
188
+ "total_notes": 0,
189
+ "concepts": 0,
190
+ "projects": 0,
191
+ "areas": 0,
192
+ "references": 0,
193
+ }
194
+ if not cortex_dir or not cortex_dir.exists():
195
+ return stats
196
+
197
+ stats["available"] = True
198
+ stats["path"] = str(cortex_dir)
199
+
200
+ for root, dirs, files in os.walk(cortex_dir):
201
+ if ".obsidian" in root or ".git" in root:
202
+ continue
203
+ for f in files:
204
+ if f.endswith(".md"):
205
+ stats["total_notes"] += 1
206
+ rel = Path(root).relative_to(cortex_dir)
207
+ if "Concepts" in rel.parts:
208
+ stats["concepts"] += 1
209
+ elif "Projects" in rel.parts:
210
+ stats["projects"] += 1
211
+ elif "Areas" in rel.parts:
212
+ stats["areas"] += 1
213
+ elif "References" in rel.parts:
214
+ stats["references"] += 1
215
+
216
+ return stats
217
+
218
+
219
+ def get_agent_roster() -> list[dict]:
220
+ """Retrieves all registered subagents from the plugin repository."""
221
+ roster = []
222
+ if not PLUGIN_AGENTS_DIR.exists():
223
+ return roster
224
+
225
+ for agent_file in sorted(PLUGIN_AGENTS_DIR.glob("*.md")):
226
+ name = agent_file.stem
227
+ desc = "No description"
228
+ try:
229
+ with open(agent_file, "r", encoding="utf-8") as f:
230
+ for line in f:
231
+ if line.startswith("description:"):
232
+ desc = line.replace("description:", "").strip().strip('"').strip("'")
233
+ break
234
+ except Exception:
235
+ pass
236
+ roster.append({
237
+ "name": name,
238
+ "description": desc,
239
+ "status": "ONLINE",
240
+ })
241
+ return roster
242
+
243
+
244
+ def get_git_status() -> dict:
245
+ """Retrieves git repository metadata."""
246
+ status = {"branch": "unknown", "commit": "unknown", "clean": True}
247
+ try:
248
+ git_dir = BASE_DIR / ".git"
249
+ if not git_dir.exists():
250
+ return status
251
+
252
+ head_file = git_dir / "HEAD"
253
+ if head_file.exists():
254
+ ref = head_file.read_text().strip()
255
+ if ref.startswith("ref: refs/heads/"):
256
+ status["branch"] = ref.replace("ref: refs/heads/", "")
257
+ branch_file = git_dir / "refs" / "heads" / status["branch"]
258
+ if branch_file.exists():
259
+ status["commit"] = branch_file.read_text().strip()[:7]
260
+ else:
261
+ status["commit"] = ref[:7]
262
+ except Exception:
263
+ pass
264
+ return status
265
+
266
+
267
+ def render_dashboard(c: Colors) -> str:
268
+ """Constructs the full stylized ANSI colored dashboard."""
269
+ brain_dir = _get_antigravity_brain_dir()
270
+ transcript_file, session_id = _get_latest_session_transcript(brain_dir)
271
+ telemetry = parse_antigravity_telemetry(transcript_file)
272
+ cortex_dir = _get_cortex_dir()
273
+ cortex_metrics = get_cortex_metrics(cortex_dir)
274
+ roster = get_agent_roster()
275
+ git_meta = get_git_status()
276
+
277
+ global_plugin_dir = Path.home() / ".gemini" / "config" / "plugins" / "cortexops"
278
+ legacy_plugin_dir = Path.home() / ".gemini" / "config" / "plugins" / "thea-engineering-team"
279
+ plugin_connected = global_plugin_dir.exists() or legacy_plugin_dir.exists()
280
+
281
+ W = 86
282
+ lines = []
283
+
284
+ # Border
285
+ border = f"{c.CYAN}{'=' * W}{c.RESET}"
286
+ divider = f"{c.DIM}{'-' * (W - 4)}{c.RESET}"
287
+
288
+ lines.append(border)
289
+ lines.append(f"{c.BOLD}{c.BRIGHT_CYAN} CORTEXOPS - OPERATIONAL STATUS & TELEMETRY DASHBOARD{c.RESET}")
290
+ lines.append(f"{c.DIM} OS: {platform.system()} {platform.release()} ({platform.machine()}) | Python: {platform.python_version()} | Antigravity: {c.RESET}{c.BOLD}{c.BRIGHT_GREEN}Connected{c.RESET}")
291
+ lines.append(border)
292
+
293
+ # System infrastructure and connections
294
+ lines.append(f"\n{c.BOLD}{c.BRIGHT_BLUE}[1] SYSTEM CONNECTIONS & INFRASTRUCTURE{c.RESET}")
295
+ lines.append(f" * Git Branch: {c.BOLD}{c.BRIGHT_WHITE}{git_meta['branch']}{c.RESET} {c.DIM}(Commit: {git_meta['commit']}){c.RESET}")
296
+
297
+ plug_text = f"{c.BOLD}{c.BRIGHT_GREEN}ENABLED (Symlinked){c.RESET}" if plugin_connected else f"{c.YELLOW}LOCAL ONLY{c.RESET}"
298
+ lines.append(f" * Antigravity Global Plugin: {plug_text}")
299
+ lines.append(f" * Antigravity Active Session: {c.CYAN}{session_id}{c.RESET}")
300
+
301
+ cortex_text = f"{c.BOLD}{c.BRIGHT_GREEN}CONNECTED{c.RESET}" if cortex_metrics['available'] else f"{c.RED}DISCONNECTED{c.RESET}"
302
+ lines.append(f" * ThutaCortex Second Brain: {cortex_text}")
303
+ lines.append(f" - Vault Root: {c.DIM}{cortex_metrics['path']}{c.RESET}")
304
+ lines.append(f" - Inventory: {c.BOLD}{c.BRIGHT_WHITE}{cortex_metrics['total_notes']}{c.RESET} total notes {c.DIM}(Concepts: {cortex_metrics['concepts']}, Projects: {cortex_metrics['projects']}, Areas: {cortex_metrics['areas']}){c.RESET}")
305
+
306
+ # Antigravity token and session telemetry
307
+ lines.append(f"\n{c.BOLD}{c.BRIGHT_BLUE}[2] ANTIGRAVITY TOKEN CONSUMPTION & TELEMETRY{c.RESET}")
308
+ lines.append(f" * Interaction Turns: {c.BOLD}{c.BRIGHT_WHITE}{telemetry['turns']:,}{c.RESET}")
309
+ lines.append(f" * Prompt Input Tokens: {c.BRIGHT_YELLOW}{telemetry['input_tokens']:,}{c.RESET}")
310
+ lines.append(f" * Candidate Output Tokens: {c.BRIGHT_GREEN}{telemetry['output_tokens']:,}{c.RESET}")
311
+ lines.append(f" * Cached Read Tokens: {c.CYAN}{telemetry['cache_read_tokens']:,}{c.RESET}")
312
+ lines.append(f" * Total Processed Tokens: {c.BOLD}{c.BRIGHT_CYAN}{telemetry['total_tokens']:,}{c.RESET}")
313
+ lines.append(f" * Last Turn Activity: {c.DIM}{telemetry['last_activity']}{c.RESET}")
314
+
315
+ # Tool invocation breakdown
316
+ lines.append(f"\n {c.UNDERLINE}Tool Invocations Breakdown:{c.RESET}")
317
+ if telemetry["tool_calls"]:
318
+ for tool, count in sorted(telemetry["tool_calls"].items(), key=lambda x: -x[1]):
319
+ bar_len = min(30, max(1, int(count / 10)))
320
+ bar_color = c.BRIGHT_GREEN if "file" in tool else c.BRIGHT_CYAN if "command" in tool else c.BRIGHT_MAGENTA
321
+ bar = f"{bar_color}{'#' * bar_len}{c.RESET}"
322
+ lines.append(f" - {c.BOLD}{tool:22s}{c.RESET} : {c.BRIGHT_WHITE}{count:4d}{c.RESET} calls | {bar}")
323
+ else:
324
+ lines.append(f" {c.DIM}- No tool invocations recorded in active session.{c.RESET}")
325
+
326
+ # Autonomous subagent roster
327
+ lines.append(f"\n{c.BOLD}{c.BRIGHT_BLUE}[3] AUTONOMOUS SUBAGENT ROSTER ({len(roster)} Verified Senior Roles){c.RESET}")
328
+ lines.append(f" {c.BOLD}{c.CYAN}{'ROLE / SUBAGENT':24s} | {'STATUS':16s} | {'PRIMARY DOMAIN & RESPONSIBILITY'}{c.RESET}")
329
+ lines.append(" " + divider)
330
+ for agent in roster:
331
+ name = agent["name"]
332
+ name_pad = max(0, 24 - len(name))
333
+ col_name = f"{c.BOLD}{c.BRIGHT_WHITE}{name}{c.RESET}{' ' * name_pad}"
334
+
335
+ status_text = "[ONLINE]"
336
+ status_pad = max(0, 16 - len(status_text))
337
+ col_status = f"{c.BOLD}{c.BRIGHT_GREEN}{status_text}{c.RESET}{' ' * status_pad}"
338
+
339
+ desc = agent["description"][:38] + "..." if len(agent["description"]) > 38 else agent["description"]
340
+ lines.append(f" {col_name} | {col_status} | {c.DIM}{desc}{c.RESET}")
341
+
342
+ lines.append("\n" + border)
343
+ lines.append(f"{c.DIM} Dashboard updated at: {time.strftime('%Y-%m-%d %H:%M:%S')}. Clean code standard enforced.{c.RESET}")
344
+ lines.append(border)
345
+ return "\n".join(lines)
346
+
347
+
348
+ def main():
349
+ # Enable ANSI escape sequences on Windows PowerShell/CMD
350
+ if os.name == "nt":
351
+ os.system("")
352
+
353
+ parser = argparse.ArgumentParser(description="CortexOps Multi-Agent Framework Operational Dashboard")
354
+ parser.add_argument("--watch", "-w", action="store_true", help="Continuously poll and refresh the dashboard")
355
+ parser.add_argument("--interval", "-i", type=int, default=3, help="Refresh interval in seconds (default: 3s)")
356
+ parser.add_argument("--no-color", action="store_true", help="Disable ANSI color codes")
357
+ parser.add_argument("--color", action="store_true", default=True, help="Force ANSI color codes (default: enabled)")
358
+ args = parser.parse_args()
359
+
360
+ color_enabled = not args.no_color
361
+ c = Colors(enabled=color_enabled)
362
+
363
+ if args.watch:
364
+ try:
365
+ while True:
366
+ os.system("cls" if os.name == "nt" else "clear")
367
+ print(render_dashboard(c))
368
+ time.sleep(args.interval)
369
+ except KeyboardInterrupt:
370
+ print(f"\n{c.DIM}Dashboard monitoring terminated.{c.RESET}")
371
+ else:
372
+ print(render_dashboard(c))
373
+
374
+
375
+ if __name__ == "__main__":
376
+ main()
package/src/main.py ADDED
@@ -0,0 +1,49 @@
1
+ """CLI Entrypoint for CortexOps Multi-Agent Framework."""
2
+
3
+ import asyncio
4
+ import sys
5
+ import os
6
+ from pathlib import Path
7
+
8
+ REPO_ROOT = Path(__file__).resolve().parent.parent
9
+ if str(REPO_ROOT) not in sys.path:
10
+ sys.path.insert(0, str(REPO_ROOT))
11
+
12
+ from google.antigravity import Agent
13
+ from src.team import create_cortexops_team
14
+
15
+ async def run_task(prompt: str, model: str = "gemini-2.0-flash"):
16
+ """Runs a complete software engineering or research lifecycle task with the CortexOps team."""
17
+ config = create_cortexops_team(model=model)
18
+
19
+ print("=" * 70)
20
+ print("CORTEXOPS MULTI-AGENT FRAMEWORK - ACTIVE")
21
+ print("Roles: TPM Director | Staff R&D | Principal Architect | UI/UX | Frontend | Backend | DevOps | ML | QA | Reviewer | Academic Researcher | Software Engineer | cxagents")
22
+ print(f"Model: {model}")
23
+ print(f"Goal: {prompt}")
24
+ print("=" * 70 + "\n")
25
+
26
+ async with Agent(config) as team:
27
+ response = await team.chat(prompt)
28
+ print("\n" + "=" * 70)
29
+ print("ENGINEERING OUTCOME:")
30
+ print("=" * 70)
31
+ async for chunk in response:
32
+ print(chunk, end="", flush=True)
33
+ print("\n")
34
+
35
+ def main():
36
+ if len(sys.argv) > 1:
37
+ prompt = " ".join(sys.argv[1:])
38
+ else:
39
+ print("Enter the engineering project or feature request:")
40
+ prompt = input("> ").strip()
41
+
42
+ if not prompt:
43
+ print("No task provided. Exiting.")
44
+ sys.exit(1)
45
+
46
+ asyncio.run(run_task(prompt))
47
+
48
+ if __name__ == "__main__":
49
+ main()
package/src/team.py ADDED
@@ -0,0 +1,125 @@
1
+ """CortexOps Multi-Agent Framework Assembler & Configuration."""
2
+
3
+ from google.antigravity import LocalAgentConfig, types
4
+ from src.agents.personas import (
5
+ rnd_researcher,
6
+ system_architect,
7
+ uiux_designer,
8
+ frontend_engineer,
9
+ backend_engineer,
10
+ ai_ml_engineer,
11
+ devops_engineer,
12
+ qa_engineer,
13
+ code_reviewer,
14
+ software_engineer,
15
+ academic_researcher,
16
+ cxagents,
17
+ )
18
+ from src.tools.code_tools import view_file, create_file, list_directory
19
+ from src.tools.test_runner import run_command
20
+ from src.tools.cortex_tools import search_cortex, read_cortex_note, ingest_concept_to_cortex
21
+
22
+ LEAD_PM_DIRECTOR_INSTRUCTIONS = """You are the Lead Technical Product Manager & Director of Engineering for CortexOps Multi-Agent Framework.
23
+ You orchestrate an elite, senior-level autonomous engineering organization.
24
+
25
+ YOUR CORE MANDATE:
26
+ You own the end-to-end software delivery lifecycle, translating business stakeholder requirements into verified, secure, high-performance production microservices and user experiences.
27
+ You hold all subagents to Staff/Principal engineering standards.
28
+
29
+ STAGED DELIVERY LIFECYCLE:
30
+ 1. Requirements Engineering & Scope (Lead PM):
31
+ - Decompose ambiguous user requests into functional user stories, non-functional requirements (latency p99, throughput QPS, availability), edge cases, and verifiable acceptance criteria.
32
+ - Author 'SPEC.md'.
33
+ 2. Deep Literature & SOTA Research (Staff R&D Engineer - rnd_researcher):
34
+ - For novel algorithms, streaming mathematics, or unfamiliar libraries, delegate to 'rnd_researcher'.
35
+ - Verify that 'RESEARCH_REPORT.md' contains concrete Big-O bounds, paper citations, and library license reviews.
36
+ 3. System Architecture & Schema Design (Principal Architect - system_architect):
37
+ - Delegate to 'system_architect' to produce 'ARCHITECTURE.md' detailing microservice boundaries, relational PostgreSQL DDL, composite indexing, API DTOs, and concurrency models.
38
+ 4. UI/UX Design & Token Handshake (Senior UI/UX Engineer - uiux_designer):
39
+ - Have 'uiux_designer' create 'UIUX_SPEC.md' with wireframes, design tokens (Material Design 3, shadcn/ui), component state matrices, and Figma autolayout mappings.
40
+ 5. Frontend Engineering & SEO/GEO (Senior Frontend Engineer - frontend_engineer):
41
+ - Have 'frontend_engineer' build accessible React 19 / Next.js App Router components with Material UI, TanStack, and shadcn/ui.
42
+ - Enforce Core Web Vitals budgets, complete metatags, structured JSON-LD data, and Agentic Search / GEO optimization.
43
+ 6. Backend Microservices Engineering (Senior Backend Engineer - backend_engineer):
44
+ - Have 'backend_engineer' build high-throughput microservices in Go (Gin), Express with Bun, Fastify, NestJS, and Python (AI).
45
+ - Enforce clean architecture, connection pooling, prepared statements, and defensive validation.
46
+ 7. AI/ML Engineering & Guardrails (Staff AI/ML Engineer - ai_ml_engineer):
47
+ - If AI/LLMs are involved, have 'ai_ml_engineer' formulate 'AI_SPEC.md' with strict JSON schemas, token budgets, and deterministic fallbacks.
48
+ 8. Containerization & DevOps (Senior DevOps/SRE - devops_engineer):
49
+ - Have 'devops_engineer' deliver multi-stage Dockerfiles, Docker Compose, Nginx gateway configs, and GitHub Actions CI/CD workflows.
50
+ 9. Deterministic Verification Gate (Senior QA Engineer - qa_engineer):
51
+ - Mandate that 'qa_engineer' runs actual compilers, linters, and test runners (pytest, go test -race, npm test).
52
+ - CRITICAL: Never declare success on conversational statements. If tests fail, feed the exact stderr trace back to developers for remediation.
53
+ 10. Security & Quality Audit (Staff Code Reviewer - code_reviewer):
54
+ - Have 'code_reviewer' audit the diff for OWASP vulnerabilities, deadlocks, and code hygiene before final sign-off.
55
+ 11. Academic Research & Scientific Manuscript Authoring (Principal Scientist - academic_researcher):
56
+ - When academic papers, conference submissions, or experimental research are requested, delegate to 'academic_researcher'.
57
+ - Enforce rigorous experimental design (multi-seed evaluation, ablation studies, baseline reimplementation) across Data Science, AIOps, Computer Vision, ML, Neural Networks, and Software Engineering.
58
+ - Enforce manuscript story-arc authoring, direct active voice, zero-tolerance for AI-sounding prose (crucial, delve, tapestry, etc.), zero narrative colons, zero body semicolons, and strict number/unit rules.
59
+
60
+ SENIOR CODING & HYGIENE INVARIANTS:
61
+ - Zero emojis anywhere in code, markdown, review comments, or logs.
62
+ - Minimized inline comments: write self-documenting code with expressive naming; explain 'why', never 'what'.
63
+ - Absolutely NO numbered steps in comments (no '// Step 1:', '// Step 2:', '# 1. Initialize').
64
+ - Human-crafted clean code: idiomatic syntax, OOP best practices (interfaces, dependency injection, repository pattern).
65
+ - Deterministic gates over agent opinions: test exit code == 0 is required.
66
+ """
67
+
68
+ def create_cortexops_team(model: str = "gemini-2.0-flash") -> LocalAgentConfig:
69
+ """Assembles the CortexOps autonomous engineering and research team.
70
+
71
+ The Root Agent acts as the Lead Technical Product Manager & Engineering Director,
72
+ orchestrating the specialized staff/principal subagents.
73
+ """
74
+ subagents = [
75
+ rnd_researcher,
76
+ system_architect,
77
+ uiux_designer,
78
+ frontend_engineer,
79
+ backend_engineer,
80
+ ai_ml_engineer,
81
+ devops_engineer,
82
+ qa_engineer,
83
+ code_reviewer,
84
+ software_engineer,
85
+ academic_researcher,
86
+ cxagents,
87
+ ]
88
+
89
+ return LocalAgentConfig(
90
+ model=model,
91
+ subagents=subagents,
92
+ tools=[
93
+ view_file,
94
+ create_file,
95
+ list_directory,
96
+ run_command,
97
+ search_cortex,
98
+ read_cortex_note,
99
+ ingest_concept_to_cortex,
100
+ ],
101
+ capabilities=types.CapabilitiesConfig(
102
+ enable_subagents=True,
103
+ max_subagent_depth=2,
104
+ allowed_subagents=[
105
+ "rnd_researcher",
106
+ "system_architect",
107
+ "uiux_designer",
108
+ "frontend_engineer",
109
+ "backend_engineer",
110
+ "ai_ml_engineer",
111
+ "devops_engineer",
112
+ "qa_engineer",
113
+ "code_reviewer",
114
+ "software_engineer",
115
+ "academic_researcher",
116
+ "cxagents",
117
+ ],
118
+ run_command_config=types.RunCommandConfig(enable_sandbox=True),
119
+ ),
120
+ system_instructions=LEAD_PM_DIRECTOR_INSTRUCTIONS,
121
+ )
122
+
123
+ def create_thea_engineering_team(model: str = "gemini-2.0-flash") -> LocalAgentConfig:
124
+ """Backwards compatibility alias for create_cortexops_team."""
125
+ return create_cortexops_team(model=model)
@@ -0,0 +1,90 @@
1
+ """arXiv Academic Research Tools for R&D Engineer."""
2
+
3
+ import urllib.request
4
+ import urllib.parse
5
+ import xml.etree.ElementTree as ET
6
+ import os
7
+ import tempfile
8
+ import io
9
+ import pypdf
10
+
11
+ def search_arxiv(query: str, max_results: int = 5) -> str:
12
+ """Searches the arXiv scientific preprint repository for academic papers.
13
+
14
+ Args:
15
+ query: Academic search keywords (e.g., 'streaming anomaly detection metric telemetry').
16
+ max_results: Maximum number of papers to retrieve (default: 5).
17
+
18
+ Returns:
19
+ Structured summary containing Paper Title, arXiv ID, Authors, Published Date,
20
+ and the full Abstract.
21
+ """
22
+ clean_query = query.strip()
23
+ encoded = urllib.parse.quote(clean_query)
24
+ url = f"http://export.arxiv.org/api/query?search_query=all:{encoded}&start=0&max_results={max_results}&sortBy=relevance&sortOrder=descending"
25
+
26
+ req = urllib.request.Request(url, headers={"User-Agent": "Thea-Engineering-Team-Agent/1.0"})
27
+ try:
28
+ with urllib.request.urlopen(req, timeout=15) as response:
29
+ xml_data = response.read()
30
+
31
+ root = ET.fromstring(xml_data)
32
+ namespace = {"atom": "http://www.w3.org/2005/Atom"}
33
+ entries = root.findall("atom:entry", namespace)
34
+
35
+ if not entries:
36
+ return f"No papers found on arXiv matching query: '{clean_query}'"
37
+
38
+ results = [f"Found {len(entries)} arXiv papers for query: '{clean_query}'\n"]
39
+ for i, entry in enumerate(entries, 1):
40
+ title = entry.find("atom:title", namespace).text.strip().replace("\n", " ")
41
+ summary = entry.find("atom:summary", namespace).text.strip().replace("\n", " ")
42
+ published = entry.find("atom:published", namespace).text[:10]
43
+ id_url = entry.find("atom:id", namespace).text.strip()
44
+ arxiv_id = id_url.split("/abs/")[-1]
45
+
46
+ authors = [a.find("atom:name", namespace).text for a in entry.findall("atom:author", namespace)]
47
+ authors_str = ", ".join(authors[:4]) + (" et al." if len(authors) > 4 else "")
48
+
49
+ results.append(
50
+ f"[{i}] {title}\n"
51
+ f" arXiv ID: {arxiv_id}\n"
52
+ f" Authors: {authors_str} ({published})\n"
53
+ f" PDF URL: https://arxiv.org/pdf/{arxiv_id}.pdf\n"
54
+ f" Abstract: {summary}\n"
55
+ )
56
+
57
+ return "\n".join(results)
58
+ except Exception as e:
59
+ return f"Error searching arXiv: {str(e)}"
60
+
61
+ def read_arxiv_paper_pdf(arxiv_id: str, max_pages: int = 5) -> str:
62
+ """Downloads an arXiv paper PDF and extracts clean text from the first several pages.
63
+
64
+ Args:
65
+ arxiv_id: The arXiv identifier (e.g., '2305.12345' or '1706.03762').
66
+ max_pages: Number of pages to extract (default: 5, focuses on Abstract, Intro, Methodology).
67
+
68
+ Returns:
69
+ Extracted plain text of the paper for deep algorithmic analysis.
70
+ """
71
+ clean_id = arxiv_id.strip().replace("abs/", "").replace(".pdf", "")
72
+ pdf_url = f"https://arxiv.org/pdf/{clean_id}.pdf"
73
+
74
+ req = urllib.request.Request(pdf_url, headers={"User-Agent": "Thea-Engineering-Team-Agent/1.0"})
75
+ try:
76
+ with urllib.request.urlopen(req, timeout=25) as response:
77
+ pdf_bytes = response.read()
78
+
79
+ reader = pypdf.PdfReader(io.BytesIO(pdf_bytes))
80
+ num_pages = len(reader.pages)
81
+ pages_to_read = min(max_pages, num_pages)
82
+
83
+ extracted = [f"=== arXiv:{clean_id} (Extracted {pages_to_read} of {num_pages} pages) ===\n"]
84
+ for p in range(pages_to_read):
85
+ text = reader.pages[p].extract_text()
86
+ extracted.append(f"--- PAGE {p+1} ---\n{text}\n")
87
+
88
+ return "\n".join(extracted)
89
+ except Exception as e:
90
+ return f"Error downloading/parsing arXiv PDF {clean_id}: {str(e)}"