@trac3er/oh-my-god 2.0.0 → 2.0.2

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 (243) hide show
  1. package/.claude-plugin/marketplace.json +8 -8
  2. package/.claude-plugin/plugin.json +5 -4
  3. package/.claude-plugin/scripts/uninstall.sh +74 -3
  4. package/.claude-plugin/scripts/update.sh +78 -3
  5. package/.coveragerc +26 -0
  6. package/.mcp.json +4 -4
  7. package/CHANGELOG.md +14 -0
  8. package/CODE_OF_CONDUCT.md +27 -0
  9. package/CONTRIBUTING.md +62 -0
  10. package/OMG-setup.sh +1201 -355
  11. package/README.md +77 -56
  12. package/SECURITY.md +25 -0
  13. package/agents/__init__.py +1 -0
  14. package/agents/model_roles.py +196 -0
  15. package/agents/omg-architect-mode.md +3 -5
  16. package/agents/omg-backend-engineer.md +3 -5
  17. package/agents/omg-database-engineer.md +3 -5
  18. package/agents/omg-frontend-designer.md +4 -5
  19. package/agents/omg-implement-mode.md +4 -5
  20. package/agents/omg-infra-engineer.md +3 -5
  21. package/agents/omg-research-mode.md +4 -6
  22. package/agents/omg-security-auditor.md +3 -5
  23. package/agents/omg-testing-engineer.md +3 -5
  24. package/build/lib/yaml.py +321 -0
  25. package/commands/OMG:ai-commit.md +101 -14
  26. package/commands/OMG:arch.md +302 -19
  27. package/commands/OMG:ccg.md +12 -7
  28. package/commands/OMG:compat.md +25 -17
  29. package/commands/OMG:cost.md +173 -13
  30. package/commands/OMG:crazy.md +1 -1
  31. package/commands/OMG:create-agent.md +170 -20
  32. package/commands/OMG:deps.md +235 -17
  33. package/commands/OMG:domain-init.md +1 -1
  34. package/commands/OMG:escalate.md +41 -12
  35. package/commands/OMG:health-check.md +37 -13
  36. package/commands/OMG:init.md +122 -14
  37. package/commands/OMG:project-init.md +1 -1
  38. package/commands/OMG:session-branch.md +76 -9
  39. package/commands/OMG:session-fork.md +42 -5
  40. package/commands/OMG:session-merge.md +124 -8
  41. package/commands/OMG:setup.md +69 -12
  42. package/commands/OMG:stats.md +215 -14
  43. package/commands/OMG:teams.md +19 -10
  44. package/config/lsp_languages.yaml +8 -0
  45. package/hooks/__init__.py +0 -0
  46. package/hooks/_agent_registry.py +423 -0
  47. package/hooks/_analytics.py +291 -0
  48. package/hooks/_budget.py +31 -0
  49. package/hooks/_common.py +569 -0
  50. package/hooks/_compression_optimizer.py +119 -0
  51. package/hooks/_cost_ledger.py +176 -0
  52. package/hooks/_learnings.py +126 -0
  53. package/hooks/_memory.py +103 -0
  54. package/hooks/_protected_context.py +150 -0
  55. package/hooks/_token_counter.py +221 -0
  56. package/hooks/branch_manager.py +236 -0
  57. package/hooks/budget_governor.py +232 -0
  58. package/hooks/circuit-breaker.py +270 -0
  59. package/hooks/compression_feedback.py +254 -0
  60. package/hooks/config-guard.py +216 -0
  61. package/hooks/context_pressure.py +53 -0
  62. package/hooks/credential_store.py +1020 -0
  63. package/hooks/fetch-rate-limits.py +212 -0
  64. package/hooks/firewall.py +48 -0
  65. package/hooks/hashline-formatter-bridge.py +224 -0
  66. package/hooks/hashline-injector.py +273 -0
  67. package/hooks/hashline-validator.py +216 -0
  68. package/hooks/idle-detector.py +95 -0
  69. package/hooks/intentgate-keyword-detector.py +188 -0
  70. package/hooks/magic-keyword-router.py +195 -0
  71. package/hooks/policy_engine.py +505 -0
  72. package/hooks/post-tool-failure.py +19 -0
  73. package/hooks/post-write.py +219 -0
  74. package/hooks/post_write.py +46 -0
  75. package/hooks/pre-compact.py +398 -0
  76. package/hooks/pre-tool-inject.py +98 -0
  77. package/hooks/prompt-enhancer.py +672 -0
  78. package/hooks/quality-runner.py +191 -0
  79. package/hooks/query.py +512 -0
  80. package/hooks/secret-guard.py +61 -0
  81. package/hooks/secret_audit.py +144 -0
  82. package/hooks/session-end-capture.py +137 -0
  83. package/hooks/session-start.py +277 -0
  84. package/hooks/setup_wizard.py +582 -0
  85. package/hooks/shadow_manager.py +297 -0
  86. package/hooks/state_migration.py +225 -0
  87. package/hooks/stop-gate.py +7 -0
  88. package/hooks/stop_dispatcher.py +945 -0
  89. package/hooks/test-validator.py +361 -0
  90. package/hooks/test_generator_hook.py +123 -0
  91. package/hooks/todo-state-tracker.py +114 -0
  92. package/hooks/tool-ledger.py +149 -0
  93. package/hooks/trust_review.py +585 -0
  94. package/hud/omg-hud.mjs +31 -1
  95. package/lab/__init__.py +1 -0
  96. package/lab/pipeline.py +75 -0
  97. package/lab/policies.py +52 -0
  98. package/package.json +7 -18
  99. package/plugins/README.md +33 -61
  100. package/plugins/advanced/commands/OMG:deep-plan.md +3 -3
  101. package/plugins/advanced/commands/OMG:learn.md +1 -1
  102. package/plugins/advanced/commands/OMG:security-review.md +3 -3
  103. package/plugins/advanced/commands/OMG:ship.md +1 -1
  104. package/plugins/advanced/plugin.json +1 -1
  105. package/plugins/core/plugin.json +8 -3
  106. package/plugins/dephealth/__init__.py +0 -0
  107. package/plugins/dephealth/cve_scanner.py +188 -0
  108. package/plugins/dephealth/license_checker.py +135 -0
  109. package/plugins/dephealth/manifest_detector.py +423 -0
  110. package/plugins/dephealth/vuln_analyzer.py +169 -0
  111. package/plugins/testgen/__init__.py +0 -0
  112. package/plugins/testgen/codamosa_engine.py +402 -0
  113. package/plugins/testgen/edge_case_synthesizer.py +184 -0
  114. package/plugins/testgen/framework_detector.py +271 -0
  115. package/plugins/testgen/skeleton_generator.py +219 -0
  116. package/plugins/viz/__init__.py +0 -0
  117. package/plugins/viz/ast_parser.py +139 -0
  118. package/plugins/viz/diagram_generator.py +192 -0
  119. package/plugins/viz/graph_builder.py +444 -0
  120. package/plugins/viz/native_parsers.py +259 -0
  121. package/plugins/viz/regex_parser.py +112 -0
  122. package/pyproject.toml +81 -0
  123. package/rules/contextual/write-verify.md +2 -2
  124. package/rules/core/00-truth.md +1 -1
  125. package/rules/core/01-surgical.md +1 -1
  126. package/rules/core/02-circuit-breaker.md +2 -2
  127. package/rules/core/03-ensemble.md +3 -3
  128. package/rules/core/04-testing.md +3 -3
  129. package/runtime/__init__.py +32 -0
  130. package/runtime/adapters/__init__.py +13 -0
  131. package/runtime/adapters/claude.py +60 -0
  132. package/runtime/adapters/gpt.py +53 -0
  133. package/runtime/adapters/local.py +53 -0
  134. package/runtime/adoption.py +212 -0
  135. package/runtime/business_workflow.py +220 -0
  136. package/runtime/cli_provider.py +85 -0
  137. package/runtime/compat.py +1299 -0
  138. package/runtime/custom_agent_loader.py +366 -0
  139. package/runtime/dispatcher.py +47 -0
  140. package/runtime/ecosystem.py +371 -0
  141. package/runtime/legacy_compat.py +7 -0
  142. package/runtime/mcp_config_writers.py +115 -0
  143. package/runtime/mcp_lifecycle.py +153 -0
  144. package/runtime/mcp_memory_server.py +135 -0
  145. package/runtime/memory_parsers/__init__.py +0 -0
  146. package/runtime/memory_parsers/chatgpt_parser.py +257 -0
  147. package/runtime/memory_parsers/claude_import.py +107 -0
  148. package/runtime/memory_parsers/export.py +97 -0
  149. package/runtime/memory_parsers/gemini_import.py +91 -0
  150. package/runtime/memory_parsers/kimi_import.py +91 -0
  151. package/runtime/memory_store.py +215 -0
  152. package/runtime/omc_compat.py +7 -0
  153. package/runtime/providers/__init__.py +0 -0
  154. package/runtime/providers/codex_provider.py +112 -0
  155. package/runtime/providers/gemini_provider.py +128 -0
  156. package/runtime/providers/kimi_provider.py +151 -0
  157. package/runtime/providers/opencode_provider.py +144 -0
  158. package/runtime/subagent_dispatcher.py +362 -0
  159. package/runtime/team_router.py +1167 -0
  160. package/runtime/tmux_session_manager.py +169 -0
  161. package/scripts/check-omg-compat-contract-snapshot.py +137 -0
  162. package/scripts/check-omg-contract-snapshot.py +12 -0
  163. package/scripts/check-omg-public-ready.py +193 -0
  164. package/scripts/check-omg-standalone-clean.py +103 -0
  165. package/scripts/legacy_to_omg_migrate.py +29 -0
  166. package/scripts/migrate-legacy.py +464 -0
  167. package/scripts/omc_to_omg_migrate.py +12 -0
  168. package/scripts/omg.py +492 -0
  169. package/scripts/settings-merge.py +283 -0
  170. package/scripts/verify-standalone.sh +8 -4
  171. package/settings.json +126 -29
  172. package/templates/profile.yaml +1 -1
  173. package/tools/__init__.py +2 -0
  174. package/tools/browser_consent.py +289 -0
  175. package/tools/browser_stealth.py +481 -0
  176. package/tools/browser_tool.py +448 -0
  177. package/tools/changelog_generator.py +347 -0
  178. package/tools/commit_splitter.py +746 -0
  179. package/tools/config_discovery.py +151 -0
  180. package/tools/config_merger.py +449 -0
  181. package/tools/dashboard_generator.py +300 -0
  182. package/tools/git_inspector.py +298 -0
  183. package/tools/lsp_client.py +275 -0
  184. package/tools/lsp_discovery.py +231 -0
  185. package/tools/lsp_operations.py +392 -0
  186. package/tools/pr_generator.py +404 -0
  187. package/tools/python_repl.py +656 -0
  188. package/tools/python_sandbox.py +609 -0
  189. package/tools/search_providers/__init__.py +77 -0
  190. package/tools/search_providers/brave.py +115 -0
  191. package/tools/search_providers/exa.py +116 -0
  192. package/tools/search_providers/jina.py +104 -0
  193. package/tools/search_providers/perplexity.py +139 -0
  194. package/tools/search_providers/synthetic.py +74 -0
  195. package/tools/session_snapshot.py +736 -0
  196. package/tools/ssh_manager.py +912 -0
  197. package/tools/theme_engine.py +294 -0
  198. package/tools/theme_selector.py +137 -0
  199. package/tools/web_search.py +622 -0
  200. package/yaml.py +321 -0
  201. package/.claude-plugin/scripts/install.sh +0 -9
  202. package/bun.lock +0 -23
  203. package/bunfig.toml +0 -3
  204. package/hooks/_budget.ts +0 -1
  205. package/hooks/_common.ts +0 -63
  206. package/hooks/circuit-breaker.ts +0 -101
  207. package/hooks/config-guard.ts +0 -4
  208. package/hooks/firewall.ts +0 -20
  209. package/hooks/policy_engine.ts +0 -156
  210. package/hooks/post-tool-failure.ts +0 -22
  211. package/hooks/post-write.ts +0 -4
  212. package/hooks/pre-tool-inject.ts +0 -4
  213. package/hooks/prompt-enhancer.ts +0 -46
  214. package/hooks/quality-runner.ts +0 -24
  215. package/hooks/secret-guard.ts +0 -4
  216. package/hooks/session-end-capture.ts +0 -19
  217. package/hooks/session-start.ts +0 -19
  218. package/hooks/shadow_manager.ts +0 -81
  219. package/hooks/stop-gate.ts +0 -22
  220. package/hooks/stop_dispatcher.ts +0 -147
  221. package/hooks/test-generator-hook.ts +0 -4
  222. package/hooks/tool-ledger.ts +0 -27
  223. package/hooks/trust_review.ts +0 -175
  224. package/lab/pipeline.ts +0 -75
  225. package/lab/policies.ts +0 -68
  226. package/runtime/common.ts +0 -111
  227. package/runtime/compat.ts +0 -174
  228. package/runtime/dispatcher.ts +0 -25
  229. package/runtime/ecosystem.ts +0 -186
  230. package/runtime/provider_bootstrap.ts +0 -99
  231. package/runtime/provider_smoke.ts +0 -34
  232. package/runtime/release_readiness.ts +0 -186
  233. package/runtime/team_router.ts +0 -144
  234. package/scripts/check-omg-compat-contract-snapshot.ts +0 -20
  235. package/scripts/check-omg-standalone-clean.ts +0 -12
  236. package/scripts/check-runtime-clean.ts +0 -94
  237. package/scripts/omg.ts +0 -352
  238. package/scripts/settings-merge.ts +0 -93
  239. package/tools/commit_splitter.ts +0 -23
  240. package/tools/git_inspector.ts +0 -18
  241. package/tools/session_snapshot.ts +0 -47
  242. package/trac3er-oh-my-god-2.0.0.tgz +0 -0
  243. package/tsconfig.json +0 -15
@@ -0,0 +1,1167 @@
1
+ """Internal team router for OMG standalone operation."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, asdict
5
+ from datetime import datetime, timezone
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ import glob
8
+ import json
9
+ import logging
10
+ import os
11
+ import re
12
+ import shlex
13
+ import shutil
14
+ import subprocess
15
+ import threading
16
+ import uuid
17
+ from typing import Any
18
+
19
+ # --- Path resolution (never relies on CWD) ---
20
+ _ROUTER_DIR = os.path.dirname(os.path.abspath(__file__))
21
+ _OMG_ROOT = os.path.dirname(_ROUTER_DIR)
22
+
23
+ _logger = logging.getLogger(__name__)
24
+
25
+ # Import providers to trigger auto-registration in provider registry
26
+ try:
27
+ import runtime.providers.codex_provider # noqa: F401 # pyright: ignore[reportUnusedImport]
28
+ import runtime.providers.gemini_provider # noqa: F401 # pyright: ignore[reportUnusedImport]
29
+ import runtime.providers.opencode_provider # noqa: F401 # pyright: ignore[reportUnusedImport]
30
+ import runtime.providers.kimi_provider # noqa: F401 # pyright: ignore[reportUnusedImport]
31
+ except ImportError:
32
+ pass
33
+
34
+ @dataclass
35
+ class TeamDispatchRequest:
36
+ target: str # codex | gemini | ccg | auto
37
+ problem: str
38
+ context: str = ""
39
+ files: list[str] | None = None
40
+ expected_outcome: str = ""
41
+
42
+
43
+ @dataclass
44
+ class TeamDispatchResult:
45
+ status: str
46
+ findings: list[str]
47
+ actions: list[str]
48
+ evidence: dict[str, Any]
49
+
50
+ def to_dict(self) -> dict[str, Any]:
51
+ out = asdict(self)
52
+ out["schema"] = "TeamDispatchResult"
53
+ return out
54
+
55
+
56
+ def _infer_target(problem: str) -> str:
57
+ p = problem.lower()
58
+ # Explicit target keywords should always win.
59
+ ccg_kw = bool(re.search(r"\bccg\b", p)) or "tri-track" in p or "tri track" in p
60
+ gemini_kw = bool(re.search(r"\bgemini\b", p))
61
+ codex_kw = bool(re.search(r"\bcodex\b", p))
62
+
63
+ if ccg_kw or (gemini_kw and codex_kw):
64
+ return "ccg"
65
+ if gemini_kw:
66
+ return "gemini"
67
+ if codex_kw:
68
+ return "codex"
69
+
70
+ ui_signals = ["ui", "ux", "layout", "css", "visual", "responsive", "frontend"]
71
+ code_signals = ["auth", "security", "backend", "debug", "performance", "algorithm"]
72
+ ccg_signals = [
73
+ "full-stack",
74
+ "full stack",
75
+ "front-end and back-end",
76
+ "frontend and backend",
77
+ "backend and frontend",
78
+ "cross-functional",
79
+ "review everything",
80
+ "architecture",
81
+ "system design",
82
+ "e2e",
83
+ "end-to-end",
84
+ ]
85
+
86
+ ui_hit = any(k in p for k in ui_signals)
87
+ code_hit = any(k in p for k in code_signals)
88
+ ccg_hit = any(k in p for k in ccg_signals)
89
+
90
+ if ccg_hit or (ui_hit and code_hit):
91
+ return "ccg"
92
+ if ui_hit:
93
+ return "gemini"
94
+ if code_hit:
95
+ return "codex"
96
+ return "codex"
97
+
98
+
99
+ def _check_tool_available(tool_name: str) -> bool:
100
+ """Return True if *tool_name* is on PATH, else log a warning."""
101
+ if shutil.which(tool_name) is not None:
102
+ return True
103
+ _logger.warning("Tool %r not found on PATH — skipping %s dispatch", tool_name, tool_name)
104
+ return False
105
+
106
+
107
+ def _run_tool(cmd: list[str], *, timeout: int = 30) -> subprocess.CompletedProcess[str]:
108
+ """Run an external tool with a mandatory timeout.
109
+
110
+ Every subprocess call in the team router MUST go through this helper
111
+ to guarantee the ``timeout`` parameter is always set.
112
+ """
113
+ return subprocess.run(
114
+ cmd,
115
+ capture_output=True,
116
+ text=True,
117
+ check=False,
118
+ timeout=timeout,
119
+ )
120
+
121
+
122
+ _TOOL_MAP: dict[str, str] = {
123
+ "codex": "codex",
124
+ "gemini": "gemini",
125
+ }
126
+
127
+ _INSTALL_HINTS: dict[str, str] = {
128
+ "codex": "Install Codex CLI: npm install -g @openai/codex",
129
+ "gemini": "Install Gemini CLI: npm install -g @google/gemini-cli",
130
+ }
131
+
132
+
133
+ _tmux_mgr: Any = None
134
+
135
+
136
+ def _get_tmux_mgr() -> Any:
137
+ """Return the module-level TmuxSessionManager singleton (lazy init)."""
138
+ global _tmux_mgr
139
+ if _tmux_mgr is None:
140
+ try:
141
+ from runtime.tmux_session_manager import TmuxSessionManager # pyright: ignore[reportMissingImports]
142
+
143
+ _tmux_mgr = TmuxSessionManager()
144
+ except ImportError:
145
+ class _FallbackMgr: # type: ignore[no-redef]
146
+ def is_tmux_available(self):
147
+ return False
148
+
149
+ _tmux_mgr = _FallbackMgr()
150
+ return _tmux_mgr
151
+
152
+
153
+ def _should_use_tmux() -> bool:
154
+ """Return True only when tmux is usable in this execution context.
155
+
156
+ Returns False if:
157
+ - tmux is not installed
158
+ - TERM env var is 'dumb' or empty (non-interactive terminal)
159
+ - Running inside a ThreadPoolExecutor worker thread
160
+ """
161
+ try:
162
+ if not _get_tmux_mgr().is_tmux_available():
163
+ return False
164
+ term = os.environ.get("TERM", "")
165
+ if term in ("dumb", ""):
166
+ return False
167
+ # Detect ThreadPoolExecutor worker threads (named 'ThreadPoolExecutor-N_N')
168
+ thread_name = threading.current_thread().name
169
+ if "ThreadPoolExecutor" in thread_name:
170
+ return False
171
+ return True
172
+ except Exception:
173
+ return False
174
+
175
+
176
+ def _auth_status_command(tool_name: str) -> list[str] | None:
177
+ if tool_name == "codex":
178
+ return ["codex", "auth", "status"]
179
+ if tool_name == "gemini":
180
+ return ["gemini", "auth", "status"]
181
+ return None
182
+
183
+
184
+ def _check_tool_auth(tool_name: str) -> tuple[bool | None, str]:
185
+ cmd = _auth_status_command(tool_name)
186
+ if cmd is None:
187
+ return None, "auth status check not supported"
188
+ try:
189
+ probe = _run_tool(cmd, timeout=15)
190
+ except subprocess.TimeoutExpired:
191
+ return None, "auth status check timed out"
192
+ except FileNotFoundError:
193
+ return False, "CLI is not installed"
194
+ except Exception as exc:
195
+ return None, f"auth status check failed: {exc}"
196
+
197
+ output = f"{probe.stdout}\n{probe.stderr}".lower()
198
+ if probe.returncode == 0:
199
+ if "not logged" in output or "not authenticated" in output or "login required" in output:
200
+ return False, "CLI is installed but not authenticated"
201
+ return True, "CLI is authenticated"
202
+
203
+ unsupported_markers = ("unknown command", "unrecognized", "invalid choice", "did you mean")
204
+ if any(marker in output for marker in unsupported_markers):
205
+ return None, "auth status subcommand is unavailable"
206
+ if "not logged" in output or "not authenticated" in output or "login" in output:
207
+ return False, "CLI is installed but not authenticated"
208
+ return None, f"unable to verify auth status (exit={probe.returncode})"
209
+
210
+
211
+ def _collect_cli_health(target: str) -> dict[str, dict[str, Any]]:
212
+ if target == "ccg":
213
+ providers = ("codex", "gemini")
214
+ elif target in ("codex", "gemini"):
215
+ providers = (target,)
216
+ else:
217
+ providers = tuple()
218
+
219
+ health: dict[str, dict[str, Any]] = {}
220
+ for provider in providers:
221
+ available = _check_tool_available(provider)
222
+ auth_ok: bool | None = None
223
+ auth_message = "CLI is not installed"
224
+ if available:
225
+ auth_ok, auth_message = _check_tool_auth(provider)
226
+ live_connection = bool(available and auth_ok is True)
227
+ health[provider] = {
228
+ "available": available,
229
+ "auth_ok": auth_ok,
230
+ "live_connection": live_connection,
231
+ "status_message": auth_message,
232
+ "install_hint": _INSTALL_HINTS.get(provider, ""),
233
+ }
234
+ return health
235
+
236
+
237
+ def dispatch_team(req: TeamDispatchRequest) -> TeamDispatchResult:
238
+ target = req.target.lower().strip()
239
+ if target == "auto":
240
+ target = _infer_target(req.problem)
241
+
242
+ findings = [f"Target router selected: {target}", f"Problem: {req.problem}"]
243
+ if req.files:
244
+ findings.append(f"Focus files: {', '.join(req.files[:8])}")
245
+ if req.expected_outcome:
246
+ findings.append(f"Expected: {req.expected_outcome}")
247
+
248
+ cli_health = _collect_cli_health(target)
249
+ for provider, info in cli_health.items():
250
+ if info.get("live_connection"):
251
+ findings.append(f"{provider} live connection: ready")
252
+ continue
253
+ if not info.get("available"):
254
+ findings.append(f"{provider} live connection: missing CLI ({info.get('install_hint', '').strip()})")
255
+ continue
256
+ findings.append(f"{provider} live connection: unavailable ({info.get('status_message', 'unknown status')})")
257
+
258
+ actions = []
259
+ if target == "codex":
260
+ actions.extend(
261
+ [
262
+ "Perform deep code-level analysis",
263
+ "Prioritize security and root-cause checks",
264
+ "Return fix strategy with verification commands",
265
+ ]
266
+ )
267
+ elif target == "gemini":
268
+ actions.extend(
269
+ [
270
+ "Perform UI/UX and visual structure review",
271
+ "Return accessibility and responsive design improvements",
272
+ "Return component-level edit suggestions",
273
+ ]
274
+ )
275
+ else:
276
+ actions.extend(
277
+ [
278
+ "Run parallel backend and frontend review tracks",
279
+ "Synthesize cross-cutting findings",
280
+ "Return merged action plan with dependency order",
281
+ ]
282
+ )
283
+
284
+ evidence = {
285
+ "target": target,
286
+ "generated_at": datetime.now(timezone.utc).isoformat(),
287
+ "context_length": len(req.context or ""),
288
+ "file_count": len(req.files or []),
289
+ "cli_health": cli_health,
290
+ "live_connection": all(h.get("live_connection") for h in cli_health.values()) if cli_health else True,
291
+ }
292
+
293
+ return TeamDispatchResult(status="ok", findings=findings, actions=actions, evidence=evidence)
294
+
295
+
296
+ def package_prompt(agent_name: str, user_prompt: str, project_dir: str) -> str:
297
+ """Build structured prompt for external CLI dispatch with rich context.
298
+
299
+ Enriches prompt with:
300
+ - Agent description from registry
301
+ - Working memory excerpt (if .omg/state/working-memory.md exists)
302
+ - Profile context (if .omg/state/profile.yaml exists)
303
+ - Recent failure history (if .omg/state/ledger/ exists)
304
+
305
+ Total prompt capped at 4000 chars (default), configurable via OMG_PROMPT_MAX_CHARS.
306
+ """
307
+ import sys as _sys
308
+
309
+ _hooks_dir = os.path.join(
310
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
311
+ "hooks",
312
+ )
313
+ if _hooks_dir not in _sys.path:
314
+ _sys.path.insert(0, _hooks_dir)
315
+
316
+ max_chars = int(os.environ.get("OMG_PROMPT_MAX_CHARS", "4000"))
317
+ sections = []
318
+
319
+ try:
320
+ from _agent_registry import AGENT_REGISTRY # pyright: ignore[reportMissingImports]
321
+
322
+ agent = AGENT_REGISTRY.get(agent_name, {})
323
+ description = agent.get("description", f"{agent_name} specialist")
324
+ model_version = agent.get("model_version", "not specified")
325
+
326
+ sections.append(f"You are a {description}")
327
+ sections.append(f"Model: {model_version}")
328
+
329
+ except Exception:
330
+ sections.append(f"Agent: {agent_name}")
331
+
332
+ sections.append(f"Project: {project_dir}")
333
+
334
+ working_memory_excerpt = _read_working_memory(project_dir)
335
+ if working_memory_excerpt:
336
+ sections.append(f"Working Memory:\n{working_memory_excerpt}")
337
+
338
+ profile_context = _read_profile_context(project_dir)
339
+ if profile_context:
340
+ sections.append(f"Profile:\n{profile_context}")
341
+
342
+ failure_history = _read_failure_history(project_dir)
343
+ if failure_history:
344
+ sections.append(f"Recent Failures:\n{failure_history}")
345
+
346
+ sections.append(f"Task: {user_prompt}")
347
+
348
+ sections.append("Constraints: Follow existing patterns. No hardcoded secrets. Verify changes.")
349
+
350
+ result = "\n\n".join(sections)
351
+
352
+ if len(result) > max_chars:
353
+ result = result[:max_chars].rstrip()
354
+
355
+ return result
356
+
357
+
358
+ def _read_working_memory(project_dir: str) -> str:
359
+ """Read working memory excerpt from .omg/state/working-memory.md."""
360
+ working_memory_path = os.path.join(project_dir, ".omg", "state", "working-memory.md")
361
+ if not os.path.exists(working_memory_path):
362
+ return ""
363
+
364
+ try:
365
+ with open(working_memory_path, "r") as f:
366
+ content = f.read()
367
+ if len(content) > 500:
368
+ content = content[:500] + "..."
369
+ return content
370
+ except OSError:
371
+ return ""
372
+
373
+
374
+ def _read_profile_context(project_dir: str) -> str:
375
+ """Read profile context from .omg/state/profile.yaml."""
376
+ profile_path = os.path.join(project_dir, ".omg", "state", "profile.yaml")
377
+ if not os.path.exists(profile_path):
378
+ return ""
379
+
380
+ try:
381
+ with open(profile_path, "r") as f:
382
+ content = f.read()
383
+ if len(content) > 300:
384
+ content = content[:300] + "..."
385
+ return content
386
+ except OSError:
387
+ return ""
388
+
389
+
390
+ def _read_failure_history(project_dir: str) -> str:
391
+ """Read recent failures from .omg/state/ledger/."""
392
+ ledger_dir = os.path.join(project_dir, ".omg", "state", "ledger")
393
+ if not os.path.exists(ledger_dir):
394
+ return ""
395
+
396
+ try:
397
+ failure_files = sorted(glob.glob(os.path.join(ledger_dir, "failure-*.jsonl")))
398
+ if not failure_files:
399
+ return ""
400
+
401
+ failures = []
402
+ for file_path in failure_files[-5:]:
403
+ try:
404
+ with open(file_path, "r") as f:
405
+ for line in f:
406
+ if line.strip():
407
+ entry = json.loads(line)
408
+ error_msg = entry.get("error", "Unknown error")
409
+ failures.append(f"- {error_msg}")
410
+ if len(failures) >= 5:
411
+ break
412
+ except (OSError, json.JSONDecodeError):
413
+ continue
414
+
415
+ if failures:
416
+ return "\n".join(failures[:5])
417
+ return ""
418
+ except Exception:
419
+ return ""
420
+
421
+
422
+ def invoke_codex(prompt: str, project_dir: str, timeout: int = 120) -> dict[str, Any]:
423
+ """Invoke codex-cli as subprocess. Returns result dict with model/output/exit_code or error/fallback."""
424
+ if not _check_tool_available("codex"):
425
+ return {"error": "codex-cli not found", "fallback": "claude"}
426
+ try:
427
+ result = _run_tool(
428
+ ["codex", "exec", "--json", prompt],
429
+ timeout=timeout,
430
+ )
431
+ return {
432
+ "model": "codex-cli",
433
+ "output": result.stdout,
434
+ "exit_code": result.returncode,
435
+ }
436
+ except subprocess.TimeoutExpired:
437
+ return {"error": "codex-cli timeout", "fallback": "claude"}
438
+ except FileNotFoundError:
439
+ return {"error": "codex-cli not found", "fallback": "claude"}
440
+ except Exception as exc:
441
+ return {"error": str(exc), "fallback": "claude"}
442
+
443
+
444
+ _TMUX_EXIT_MARKER = "__OMG_TMUX_EXIT_CODE__"
445
+ _TMUX_EXIT_CODE_RE = re.compile(r"(?:\r?\n)?__OMG_TMUX_EXIT_CODE__:(\d+)\s*$")
446
+
447
+
448
+ def _parse_tmux_command_result(output: str) -> tuple[str, int]:
449
+ """Extract exit code marker from tmux output and return cleaned output + exit code."""
450
+ match = _TMUX_EXIT_CODE_RE.search(output)
451
+ if not match:
452
+ raise RuntimeError("tmux output missing exit code marker")
453
+ exit_code = int(match.group(1))
454
+ cleaned = _TMUX_EXIT_CODE_RE.sub("", output).rstrip()
455
+ return cleaned, exit_code
456
+
457
+
458
+ def invoke_codex_tmux(prompt: str, project_dir: str, timeout: int = 120) -> dict[str, Any]:
459
+ """Invoke codex-cli via persistent tmux session. Falls back to subprocess on error."""
460
+ if not _check_tool_available("codex"):
461
+ return {"error": "codex-cli not found", "fallback": "claude"}
462
+
463
+ mgr = _get_tmux_mgr()
464
+ session: str | None = None
465
+ try:
466
+ session_name = mgr.make_session_name("codex", unique_id=str(uuid.uuid4())[:8])
467
+ session = mgr.get_or_create_session(session_name)
468
+ quoted_prompt = shlex.quote(prompt)
469
+ cmd = f"codex exec --json {quoted_prompt}; printf '\\n{_TMUX_EXIT_MARKER}:%s\\n' \"$?\""
470
+ raw_output = mgr.send_command(session, cmd, timeout=timeout)
471
+ output, exit_code = _parse_tmux_command_result(raw_output)
472
+ return {"model": "codex-cli", "output": output, "exit_code": exit_code}
473
+ except Exception as exc:
474
+ _logger.warning("tmux codex invocation failed, falling back to subprocess: %s", exc)
475
+ return invoke_codex(prompt, project_dir, timeout=timeout)
476
+ finally:
477
+ if session:
478
+ mgr.kill_session(session)
479
+
480
+
481
+ def invoke_gemini(prompt: str, project_dir: str, timeout: int = 120) -> dict[str, Any]:
482
+ """Invoke gemini-cli as subprocess. Returns result dict with model/output/exit_code or error/fallback."""
483
+ if not _check_tool_available("gemini"):
484
+ return {"error": "gemini-cli not found", "fallback": "claude"}
485
+ try:
486
+ result = _run_tool(
487
+ ["gemini", "-p", prompt],
488
+ timeout=timeout,
489
+ )
490
+ return {
491
+ "model": "gemini-cli",
492
+ "output": result.stdout,
493
+ "exit_code": result.returncode,
494
+ }
495
+ except subprocess.TimeoutExpired:
496
+ return {"error": "gemini-cli timeout", "fallback": "claude"}
497
+ except FileNotFoundError:
498
+ return {"error": "gemini-cli not found", "fallback": "claude"}
499
+ except Exception as exc:
500
+ return {"error": str(exc), "fallback": "claude"}
501
+
502
+
503
+ def invoke_gemini_tmux(prompt: str, project_dir: str, timeout: int = 120) -> dict[str, Any]:
504
+ """Invoke gemini-cli via persistent tmux session. Falls back to subprocess on error."""
505
+ if not _check_tool_available("gemini"):
506
+ return {"error": "gemini-cli not found", "fallback": "claude"}
507
+
508
+ mgr = _get_tmux_mgr()
509
+ session: str | None = None
510
+ try:
511
+ session_name = mgr.make_session_name("gemini", unique_id=str(uuid.uuid4())[:8])
512
+ session = mgr.get_or_create_session(session_name)
513
+ quoted_prompt = shlex.quote(prompt)
514
+ cmd = f"gemini -p {quoted_prompt}; printf '\\n{_TMUX_EXIT_MARKER}:%s\\n' \"$?\""
515
+ raw_output = mgr.send_command(session, cmd, timeout=timeout)
516
+ output, exit_code = _parse_tmux_command_result(raw_output)
517
+ return {"model": "gemini-cli", "output": output, "exit_code": exit_code}
518
+ except Exception as exc:
519
+ _logger.warning("tmux gemini invocation failed, falling back to subprocess: %s", exc)
520
+ return invoke_gemini(prompt, project_dir, timeout=timeout)
521
+ finally:
522
+ if session:
523
+ mgr.kill_session(session)
524
+
525
+
526
+ def dispatch_to_model(agent_name: str, user_prompt: str, project_dir: str) -> dict[str, Any]:
527
+ """Dispatch a task to the preferred model for this agent.
528
+
529
+ Returns result dict. If preferred model unavailable, returns fallback dict.
530
+ """
531
+ import sys as _sys
532
+
533
+ _hooks_dir = os.path.join(
534
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
535
+ "hooks",
536
+ )
537
+ if _hooks_dir not in _sys.path:
538
+ _sys.path.insert(0, _hooks_dir)
539
+ try:
540
+ from _agent_registry import AGENT_REGISTRY, detect_available_models # pyright: ignore[reportMissingImports]
541
+
542
+ agent = AGENT_REGISTRY.get(agent_name)
543
+ if not agent:
544
+ return {"error": f"Unknown agent: {agent_name}", "fallback": "claude"}
545
+
546
+ available = detect_available_models()
547
+ preferred = agent.get("preferred_model", "claude")
548
+ packaged = package_prompt(agent_name, user_prompt, project_dir)
549
+
550
+ provider_name_map = {
551
+ "codex-cli": "codex",
552
+ "gemini-cli": "gemini",
553
+ "opencode-cli": "opencode",
554
+ "kimi-cli": "kimi",
555
+ }
556
+ provider_name = provider_name_map.get(preferred)
557
+
558
+ if provider_name and available.get(preferred, True):
559
+ from runtime.cli_provider import get_provider
560
+
561
+ provider = get_provider(provider_name)
562
+ if provider and provider.detect():
563
+ if _should_use_tmux():
564
+ return provider.invoke_tmux(packaged, project_dir)
565
+ return provider.invoke(packaged, project_dir)
566
+
567
+ if preferred == "codex-cli" and available.get("codex-cli"):
568
+ if _should_use_tmux():
569
+ return invoke_codex_tmux(packaged, project_dir)
570
+ return invoke_codex(packaged, project_dir)
571
+ if preferred == "gemini-cli" and available.get("gemini-cli"):
572
+ if _should_use_tmux():
573
+ return invoke_gemini_tmux(packaged, project_dir)
574
+ return invoke_gemini(packaged, project_dir)
575
+ # Fallback: use Claude native task() dispatch
576
+ return {
577
+ "fallback": "claude",
578
+ "category": agent.get("task_category", "deep"),
579
+ "skills": agent.get("skills", []),
580
+ "model_version": agent.get("model_version", "unknown"),
581
+ }
582
+ except Exception as exc:
583
+ return {"error": str(exc), "fallback": "claude"}
584
+
585
+
586
+ def get_core_agent_model(agent_name: str) -> dict[str, Any] | None:
587
+ """Get model preference for a core (non-keyword-matched) agent."""
588
+ import sys as _sys
589
+ _hooks_dir = os.path.join(
590
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
591
+ "hooks",
592
+ )
593
+ if _hooks_dir not in _sys.path:
594
+ _sys.path.insert(0, _hooks_dir)
595
+ try:
596
+ from _agent_registry import CORE_AGENT_MODELS # pyright: ignore[reportMissingImports]
597
+ return CORE_AGENT_MODELS.get(agent_name)
598
+ except Exception:
599
+ return None
600
+
601
+
602
+
603
+ def execute_agents_sequentially(
604
+ agent_tasks: list[dict[str, Any]],
605
+ project_dir: str,
606
+ timeout_per_agent: int = 120
607
+ ) -> list[dict[str, Any]]:
608
+ """Execute agents sequentially (one at a time) for CRAZY mode.
609
+
610
+ Args:
611
+ agent_tasks: List of {agent_name, prompt, order} dicts
612
+ project_dir: Working directory
613
+ timeout_per_agent: Timeout for each agent invocation
614
+
615
+ Returns:
616
+ List of results in execution order
617
+ """
618
+ # Sort by order if specified
619
+ sorted_tasks = sorted(agent_tasks, key=lambda x: x.get("order", 0))
620
+
621
+ results: list[dict[str, Any]] = []
622
+
623
+ for task in sorted_tasks:
624
+ agent_name = task.get("agent_name", "executor")
625
+ prompt = task.get("prompt", "")
626
+
627
+ print(f"[CRAZY] Launching {agent_name}...")
628
+
629
+ # Dispatch to the appropriate model
630
+ result = dispatch_to_model(agent_name, prompt, project_dir)
631
+
632
+ if result.get("fallback") == "claude":
633
+ print(f"[CRAZY] {agent_name} using Claude (native)")
634
+ status = "fallback-claude"
635
+ elif "error" in result:
636
+ print(f"[CRAZY] {agent_name} error: {result['error']}")
637
+ status = "error"
638
+ else:
639
+ print(f"[CRAZY] {agent_name} completed (exit={result.get('exit_code', 'unknown')})")
640
+ status = "completed" if result.get("exit_code") == 0 else "failed"
641
+
642
+ results.append({
643
+ "agent": agent_name,
644
+ "order": task.get("order", 0),
645
+ "status": status,
646
+ **result
647
+ })
648
+
649
+ return results
650
+
651
+
652
+ def execute_agents_parallel(
653
+ agent_tasks: list[dict[str, Any]],
654
+ project_dir: str,
655
+ timeout_per_agent: int = 120,
656
+ ) -> list[dict[str, Any]]:
657
+ indexed_tasks: list[tuple[int, int, dict[str, Any]]] = [
658
+ (idx, int(task.get("order", 0)), task) for idx, task in enumerate(agent_tasks)
659
+ ]
660
+ sorted_tasks = sorted(indexed_tasks, key=lambda x: (x[1], x[0]))
661
+ if not sorted_tasks:
662
+ return []
663
+
664
+ max_workers = min(len(sorted_tasks), 5)
665
+ results_by_index: dict[int, dict[str, Any]] = {}
666
+
667
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
668
+ future_map = {
669
+ pool.submit(
670
+ dispatch_to_model,
671
+ str(task_info[2].get("agent_name", "executor")),
672
+ str(task_info[2].get("prompt", "")),
673
+ project_dir,
674
+ ): task_info
675
+ for task_info in sorted_tasks
676
+ }
677
+
678
+ for future in as_completed(future_map):
679
+ task_info = future_map[future]
680
+ task = task_info[2]
681
+ order = task_info[1]
682
+ task_index = task_info[0]
683
+ agent_name = str(task.get("agent_name", "executor"))
684
+
685
+ try:
686
+ result = future.result(timeout=timeout_per_agent)
687
+ except Exception as exc:
688
+ result = {"error": str(exc), "fallback": "claude"}
689
+
690
+ if result.get("fallback") == "claude":
691
+ status = "fallback-claude"
692
+ elif "error" in result:
693
+ status = "error"
694
+ else:
695
+ status = "completed" if result.get("exit_code") == 0 else "failed"
696
+
697
+ results_by_index[task_index] = {
698
+ "agent": agent_name,
699
+ "order": order,
700
+ "status": status,
701
+ **result,
702
+ }
703
+
704
+ ordered_results = [results_by_index[task_info[0]] for task_info in sorted_tasks]
705
+ return ordered_results
706
+
707
+
708
+ def execute_crazy_mode(
709
+ problem: str,
710
+ project_dir: str,
711
+ context: str | None = None,
712
+ files: list[str] | None = None
713
+ ) -> dict[str, Any]:
714
+ print("[CRAZY] Starting parallel agent execution...")
715
+ print(f"[CRAZY] Problem: {problem[:100]}...")
716
+
717
+ # Build context package
718
+ context_parts = []
719
+ if context:
720
+ context_parts.append(context)
721
+ if files:
722
+ context_parts.append(f"Focus files: {', '.join(files[:8])}")
723
+ full_context = "\n\n".join(context_parts) if context_parts else ""
724
+
725
+ worker_tasks = [
726
+ {
727
+ "agent_name": "architect-mode",
728
+ "prompt": (
729
+ f"Plan decomposition for: {problem}\n\n"
730
+ f"Focus: scope, sequencing, dependency ordering, risk control.\n\n"
731
+ f"Context:\n{full_context}"
732
+ ),
733
+ "order": 1,
734
+ },
735
+ {
736
+ "agent_name": "backend-engineer",
737
+ "prompt": (
738
+ f"Backend implementation strategy for: {problem}\n\n"
739
+ f"Focus: APIs, data flow, failure handling, performance.\n\n"
740
+ f"Context:\n{full_context}"
741
+ ),
742
+ "order": 2,
743
+ },
744
+ {
745
+ "agent_name": "frontend-designer",
746
+ "prompt": (
747
+ f"Frontend/UI strategy for: {problem}\n\n"
748
+ f"Focus: UX, accessibility, responsive behavior, component structure.\n\n"
749
+ f"Context:\n{full_context}"
750
+ ),
751
+ "order": 3,
752
+ },
753
+ {
754
+ "agent_name": "security-auditor",
755
+ "prompt": (
756
+ f"Security review strategy for: {problem}\n\n"
757
+ f"Focus: auth, secrets, input validation, abuse vectors.\n\n"
758
+ f"Context:\n{full_context}"
759
+ ),
760
+ "order": 4,
761
+ },
762
+ {
763
+ "agent_name": "testing-engineer",
764
+ "prompt": (
765
+ f"Verification strategy for: {problem}\n\n"
766
+ f"Focus: unit/integration/e2e coverage and failure reproduction.\n\n"
767
+ f"Context:\n{full_context}"
768
+ ),
769
+ "order": 5,
770
+ },
771
+ ]
772
+
773
+ results = execute_agents_parallel(worker_tasks, project_dir)
774
+
775
+ result_blocks: list[str] = []
776
+ for r in results:
777
+ result_blocks.append(
778
+ f"**{r.get('agent', 'unknown')} [{r.get('status', 'unknown')}]:**\n"
779
+ f"{r.get('output', r.get('error', 'No output'))}"
780
+ )
781
+
782
+ synthesis_prompt = (
783
+ "Synthesize results from five specialized tracks:\n\n"
784
+ + "\n\n".join(result_blocks)
785
+ + "\n\nProvide a unified action plan with dependency ordering."
786
+ )
787
+
788
+ model_mix = {
789
+ "gpt": [r.get("agent") for r in results if r.get("model") == "codex-cli"],
790
+ "gemini": [r.get("agent") for r in results if r.get("model") == "gemini-cli"],
791
+ "claude": [r.get("agent") for r in results if r.get("fallback") == "claude"],
792
+ }
793
+
794
+ return {
795
+ "status": "ok",
796
+ "phases": [
797
+ {"phase": 1, "agent": "claude-orchestrator", "status": "completed"},
798
+ *[
799
+ {
800
+ "phase": idx,
801
+ "agent": r.get("agent"),
802
+ "status": r.get("status", "unknown"),
803
+ "model": r.get("model", r.get("fallback", "unknown")),
804
+ "output": r.get("output", ""),
805
+ }
806
+ for idx, r in enumerate(results, start=2)
807
+ ],
808
+ {"phase": 7, "agent": "claude-synthesis", "prompt": synthesis_prompt},
809
+ ],
810
+ "parallel_execution": True,
811
+ "sequential_execution": False,
812
+ "worker_count": len(results),
813
+ "target_worker_count": 5,
814
+ "model_mix": model_mix,
815
+ "findings": [
816
+ f"Workers launched: {len(results)}/5",
817
+ f"GPT tracks: {len(model_mix['gpt'])}",
818
+ f"Gemini tracks: {len(model_mix['gemini'])}",
819
+ f"Claude tracks: {len(model_mix['claude'])}",
820
+ ],
821
+ }
822
+
823
+
824
+ def execute_ccg_mode(
825
+ problem: str,
826
+ project_dir: str,
827
+ context: str | None = None,
828
+ files: list[str] | None = None,
829
+ ) -> dict[str, Any]:
830
+ """CCG (Claude-Codex-Gemini) execution mode — 2-track parallel analysis.
831
+
832
+ Track 1: backend-engineer (Codex path) — backend/code analysis
833
+ Track 2: frontend-designer (Gemini path) — UI/UX analysis
834
+ Then synthesises both tracks into unified output.
835
+ """
836
+ print("[CCG] Starting 2-track parallel agent execution...")
837
+ print(f"[CCG] Problem: {problem[:100]}...")
838
+
839
+ # Build context package
840
+ context_parts: list[str] = []
841
+ if context:
842
+ context_parts.append(context)
843
+ if files:
844
+ context_parts.append(f"Focus files: {', '.join(files[:8])}")
845
+ full_context = "\n\n".join(context_parts) if context_parts else ""
846
+
847
+ worker_tasks = [
848
+ {
849
+ "agent_name": "backend-engineer",
850
+ "prompt": (
851
+ f"Backend implementation strategy for: {problem}\n\n"
852
+ f"Focus: APIs, data flow, failure handling, performance.\n\n"
853
+ f"Context:\n{full_context}"
854
+ ),
855
+ "order": 1,
856
+ },
857
+ {
858
+ "agent_name": "frontend-designer",
859
+ "prompt": (
860
+ f"Frontend/UI strategy for: {problem}\n\n"
861
+ f"Focus: UX, accessibility, responsive behavior, component structure.\n\n"
862
+ f"Context:\n{full_context}"
863
+ ),
864
+ "order": 2,
865
+ },
866
+ ]
867
+
868
+ results = execute_agents_parallel(worker_tasks, project_dir)
869
+
870
+ result_blocks: list[str] = []
871
+ for r in results:
872
+ result_blocks.append(
873
+ f"**{r.get('agent', 'unknown')} [{r.get('status', 'unknown')}]:**\n"
874
+ f"{r.get('output', r.get('error', 'No output'))}"
875
+ )
876
+
877
+ synthesis_prompt = (
878
+ "Synthesize results from two specialized CCG tracks:\n\n"
879
+ + "\n\n".join(result_blocks)
880
+ + "\n\nProvide a unified action plan merging backend and frontend perspectives."
881
+ )
882
+
883
+ model_mix = {
884
+ "gpt": [r.get("agent") for r in results if r.get("model") == "codex-cli"],
885
+ "gemini": [r.get("agent") for r in results if r.get("model") == "gemini-cli"],
886
+ "claude": [r.get("agent") for r in results if r.get("fallback") == "claude"],
887
+ }
888
+
889
+ return {
890
+ "status": "ok",
891
+ "phases": [
892
+ {"phase": 1, "agent": "claude-orchestrator", "status": "completed"},
893
+ *[
894
+ {
895
+ "phase": idx,
896
+ "agent": r.get("agent"),
897
+ "status": r.get("status", "unknown"),
898
+ "model": r.get("model", r.get("fallback", "unknown")),
899
+ "output": r.get("output", ""),
900
+ }
901
+ for idx, r in enumerate(results, start=2)
902
+ ],
903
+ {"phase": len(results) + 2, "agent": "claude-synthesis", "prompt": synthesis_prompt},
904
+ ],
905
+ "parallel_execution": True,
906
+ "sequential_execution": False,
907
+ "worker_count": len(results),
908
+ "target_worker_count": 2,
909
+ "model_mix": model_mix,
910
+ "findings": [
911
+ f"Workers launched: {len(results)}/2",
912
+ f"GPT tracks: {len(model_mix['gpt'])}",
913
+ f"Gemini tracks: {len(model_mix['gemini'])}",
914
+ f"Claude tracks: {len(model_mix['claude'])}",
915
+ ],
916
+ }
917
+
918
+
919
+ # =============================================================================
920
+ # Round-Robin Credential Distribution (Feature: OMG_ROUND_ROBIN_ENABLED)
921
+ # =============================================================================
922
+
923
+
924
+ def _fnv1a_hash(data: str) -> int:
925
+ """FNV-1a 32-bit hash for session-stable key assignment.
926
+
927
+ Deterministic: same input always produces the same hash.
928
+ Used to pin a session to a consistent starting key index.
929
+ """
930
+ h = 2166136261
931
+ for c in data.encode():
932
+ h ^= c
933
+ h = (h * 16777619) & 0xFFFFFFFF
934
+ return h
935
+
936
+
937
+ def _get_hooks_imports():
938
+ """Lazy-import credential_store and get_feature_flag.
939
+
940
+ Returns (credential_store_module, get_feature_flag_func) or (None, None).
941
+ Adds hooks dir to sys.path if needed (same pattern as package_prompt).
942
+ """
943
+ import sys as _sys
944
+
945
+ _hooks_dir = os.path.join(_OMG_ROOT, "hooks")
946
+ if _hooks_dir not in _sys.path:
947
+ _sys.path.insert(0, _hooks_dir)
948
+ try:
949
+ from _common import get_feature_flag # pyright: ignore[reportMissingImports]
950
+ import credential_store # pyright: ignore[reportMissingImports]
951
+
952
+ return credential_store, get_feature_flag
953
+ except ImportError:
954
+ return None, None
955
+
956
+
957
+ def get_active_credential(provider: str, session_id: str | None = None) -> str | None:
958
+ """Get active API key for provider via round-robin.
959
+
960
+ Returns key string or None if credential store disabled/unavailable.
961
+ Feature flag: OMG_ROUND_ROBIN_ENABLED
962
+
963
+ Args:
964
+ provider: Provider name (e.g., 'anthropic', 'openai')
965
+ session_id: Optional session ID for deterministic key assignment via FNV-1a hash
966
+ """
967
+ cred_mod, get_flag = _get_hooks_imports()
968
+ if cred_mod is None or get_flag is None:
969
+ return None
970
+
971
+ if not get_flag("ROUND_ROBIN", default=False):
972
+ return None
973
+
974
+ passphrase = os.environ.get("OMG_CREDENTIAL_PASSPHRASE")
975
+ if not passphrase:
976
+ return None
977
+
978
+ try:
979
+ store = cred_mod.load_store(passphrase)
980
+ except (ValueError, OSError):
981
+ return None
982
+
983
+ providers = store.get("providers", {})
984
+ if provider not in providers:
985
+ return None
986
+
987
+ pdata = providers[provider]
988
+ keys = pdata.get("keys", [])
989
+ if not keys:
990
+ return None
991
+
992
+ # Pick key index: session-stable via FNV-1a or current active_index
993
+ if session_id:
994
+ idx = _fnv1a_hash(session_id) % len(keys)
995
+ else:
996
+ idx = pdata.get("active_index", 0)
997
+ if idx < 0 or idx >= len(keys):
998
+ idx = 0
999
+
1000
+ # Track usage on selected key
1001
+ keys[idx]["usage_count"] = keys[idx].get("usage_count", 0) + 1
1002
+ keys[idx]["last_used"] = datetime.now(timezone.utc).isoformat()
1003
+
1004
+ # Advance active_index for next non-session call (round-robin)
1005
+ if not session_id:
1006
+ pdata["active_index"] = (idx + 1) % len(keys)
1007
+
1008
+ # Persist updated stats (best-effort)
1009
+ try:
1010
+ cred_mod.save_store(store, passphrase)
1011
+ except (ValueError, OSError):
1012
+ pass
1013
+
1014
+ return keys[idx].get("key")
1015
+
1016
+
1017
+ def on_rate_limit(provider: str, session_id: str | None = None) -> str | None:
1018
+ """Advance to next credential for provider on 429. Returns new active key.
1019
+
1020
+ Called when a rate limit (HTTP 429) is encountered. Advances to the next
1021
+ available key in the rotation and returns it.
1022
+
1023
+ Args:
1024
+ provider: Provider name (e.g., 'anthropic', 'openai')
1025
+ session_id: Optional session ID (currently unused, reserved for future)
1026
+ """
1027
+ cred_mod, get_flag = _get_hooks_imports()
1028
+ if cred_mod is None or get_flag is None:
1029
+ return None
1030
+
1031
+ if not get_flag("ROUND_ROBIN", default=False):
1032
+ return None
1033
+
1034
+ passphrase = os.environ.get("OMG_CREDENTIAL_PASSPHRASE")
1035
+ if not passphrase:
1036
+ return None
1037
+
1038
+ try:
1039
+ store = cred_mod.load_store(passphrase)
1040
+ except (ValueError, OSError):
1041
+ return None
1042
+
1043
+ providers = store.get("providers", {})
1044
+ if provider not in providers:
1045
+ return None
1046
+
1047
+ pdata = providers[provider]
1048
+ keys = pdata.get("keys", [])
1049
+ if not keys:
1050
+ return None
1051
+
1052
+ current_idx = pdata.get("active_index", 0)
1053
+ if current_idx < 0 or current_idx >= len(keys):
1054
+ current_idx = 0
1055
+
1056
+ # Advance to next key
1057
+ new_idx = (current_idx + 1) % len(keys)
1058
+ pdata["active_index"] = new_idx
1059
+
1060
+ # Persist (best-effort)
1061
+ try:
1062
+ cred_mod.save_store(store, passphrase)
1063
+ except (ValueError, OSError):
1064
+ pass
1065
+
1066
+ return keys[new_idx].get("key")
1067
+
1068
+
1069
+ # =============================================================================
1070
+ # Role-Based Routing (Feature: OMG_ROLE_ROUTING_ENABLED)
1071
+ # =============================================================================
1072
+
1073
+
1074
+ def get_role_from_env() -> str | None:
1075
+ """Read the active role from OMG_ACTIVE_ROLE environment variable.
1076
+
1077
+ Returns:
1078
+ Role name string (e.g., 'smol', 'slow') or None if not set.
1079
+ """
1080
+ val = os.environ.get("OMG_ACTIVE_ROLE", "").strip().lower()
1081
+ return val if val else None
1082
+
1083
+
1084
+ def route_with_role(task_text: str, role: str | None = None) -> dict[str, Any]:
1085
+ """Select model based on role + task classification.
1086
+
1087
+ Resolution order for role:
1088
+ 1. Explicit `role` parameter
1089
+ 2. OMG_ACTIVE_ROLE env var (via get_role_from_env())
1090
+ 3. CLI args (--smol, --slow, --plan, --commit) via parse_role_args()
1091
+ 4. None → fall back to existing routing
1092
+
1093
+ Feature flag: OMG_ROLE_ROUTING_ENABLED (default: False)
1094
+ When disabled, returns a baseline dict from existing _infer_target().
1095
+
1096
+ Args:
1097
+ task_text: Description of the task to route.
1098
+ role: Optional explicit role name override.
1099
+
1100
+ Returns:
1101
+ Dict with keys: model, provider, role, reason
1102
+ """
1103
+ import sys as _sys
1104
+
1105
+ # Baseline: always compute the existing routing target
1106
+ existing_target = _infer_target(task_text)
1107
+ baseline = {
1108
+ "model": None,
1109
+ "provider": existing_target,
1110
+ "role": None,
1111
+ "reason": f"intent-based routing to {existing_target}",
1112
+ }
1113
+
1114
+ # Check feature flag via lazy import
1115
+ _hooks_dir = os.path.join(_OMG_ROOT, "hooks")
1116
+ if _hooks_dir not in _sys.path:
1117
+ _sys.path.insert(0, _hooks_dir)
1118
+ try:
1119
+ from _common import get_feature_flag # pyright: ignore[reportMissingImports]
1120
+ except ImportError:
1121
+ # If _common unavailable, check env var directly
1122
+ env_val = os.environ.get("OMG_ROLE_ROUTING_ENABLED", "").lower()
1123
+ if env_val not in ("1", "true", "yes"):
1124
+ return baseline
1125
+ get_feature_flag = None # type: ignore[assignment]
1126
+
1127
+ if get_feature_flag is not None and not get_feature_flag("ROLE_ROUTING", default=False):
1128
+ return baseline
1129
+
1130
+ # Resolve role: explicit param → env var → CLI args
1131
+ resolved_role = role
1132
+ if resolved_role is None:
1133
+ resolved_role = get_role_from_env()
1134
+ if resolved_role is None:
1135
+ # Lazy import parse_role_args from agents.model_roles
1136
+ _agents_dir = os.path.join(_OMG_ROOT, "agents")
1137
+ if _agents_dir not in _sys.path:
1138
+ _sys.path.insert(0, _agents_dir)
1139
+ try:
1140
+ from model_roles import parse_role_args # pyright: ignore[reportMissingImports]
1141
+ resolved_role = parse_role_args(_sys.argv[1:])
1142
+ except ImportError:
1143
+ pass
1144
+
1145
+ # No role resolved → return baseline
1146
+ if resolved_role is None:
1147
+ return baseline
1148
+
1149
+ # Get role config via lazy import
1150
+ _agents_dir = os.path.join(_OMG_ROOT, "agents")
1151
+ if _agents_dir not in _sys.path:
1152
+ _sys.path.insert(0, _agents_dir)
1153
+ try:
1154
+ from model_roles import get_role # pyright: ignore[reportMissingImports]
1155
+ role_config = get_role(resolved_role)
1156
+ except ImportError:
1157
+ return baseline
1158
+
1159
+ if not role_config:
1160
+ return baseline
1161
+
1162
+ return {
1163
+ "model": role_config.get("model"),
1164
+ "provider": role_config.get("model", existing_target),
1165
+ "role": resolved_role,
1166
+ "reason": f"role-based routing: {resolved_role} → {role_config.get('model', 'unknown')}",
1167
+ }