yf176 commited on
Commit ·
30cc2cc
1
Parent(s): cdd6437
feat: integrate governed quant runtime
Browse files- src/polyhedra/agents/coordinator.py +174 -4
- src/polyhedra/agents/quant/decision_contracts.py +24 -6
- src/polyhedra/agents/quant/product_contracts.py +4 -2
- src/polyhedra/app.py +394 -12
- src/polyhedra/messaging/slack.py +5 -18
- src/polyhedra/services/evidence_ledger.py +108 -0
- src/polyhedra/services/file_writer.py +18 -0
- src/polyhedra/services/quant_run_record.py +23 -1
- src/polyhedra/services/quant_runtime.py +625 -0
- src/polyhedra/services/strategist_performance.py +8 -4
- src/polyhedra/web/static/index.html +438 -26
- tests/test_quant_runtime.py +321 -0
- tests/test_quant_v6/test_scope_routing.py +9 -4
- tests/test_v611_web_ui.py +120 -0
src/polyhedra/agents/coordinator.py
CHANGED
|
@@ -111,6 +111,28 @@ _V6_DOWNSTREAM_PATH: list[str] = [
|
|
| 111 |
"publisher",
|
| 112 |
]
|
| 113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
def _is_llm_unavailable_output(content: str) -> bool:
|
| 116 |
lowered = content.lower()
|
|
@@ -275,6 +297,9 @@ class CoordinatorService:
|
|
| 275 |
self._yolo_update_fn = yolo_update_fn
|
| 276 |
self._yolo_completed: list[str] = [] # agents finished in this YOLO run
|
| 277 |
self._yolo_run_context: YoloRunContext | None = None
|
|
|
|
|
|
|
|
|
|
| 278 |
self._parser = MentionParser(session.registry)
|
| 279 |
|
| 280 |
# V4.4 STRUCT-1: delegate to focused sub-components
|
|
@@ -312,6 +337,151 @@ class CoordinatorService:
|
|
| 312 |
)
|
| 313 |
return self._yolo_run_context
|
| 314 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
async def dispatch(self, from_role: str, text: str, origin_id: str = "") -> None:
|
| 316 |
"""
|
| 317 |
Entry point for every incoming message.
|
|
@@ -756,11 +926,8 @@ class CoordinatorService:
|
|
| 756 |
|
| 757 |
def _yolo_mode_label(self) -> str:
|
| 758 |
"""Return a Slack/UI-friendly YOLO run mode label."""
|
| 759 |
-
yolo_run_context = getattr(self, "_yolo_run_context", None)
|
| 760 |
-
if yolo_run_context is not None:
|
| 761 |
-
return yolo_run_context.label
|
| 762 |
try:
|
| 763 |
-
qs = self.session.
|
| 764 |
except Exception:
|
| 765 |
qs = None
|
| 766 |
mode = getattr(qs, "yolo_run_mode", "") if qs is not None else ""
|
|
@@ -768,6 +935,9 @@ class CoordinatorService:
|
|
| 768 |
return "Session-delta YOLO"
|
| 769 |
if mode == "baseline":
|
| 770 |
return "Baseline YOLO"
|
|
|
|
|
|
|
|
|
|
| 771 |
return "YOLO"
|
| 772 |
|
| 773 |
async def _on_agent_blocked(self, event: AgentBlockedEvent) -> None:
|
|
|
|
| 111 |
"publisher",
|
| 112 |
]
|
| 113 |
|
| 114 |
+
_TYPED_AGENT_ROLES: dict[str, str] = {
|
| 115 |
+
"DataFetcher": "datafetcher",
|
| 116 |
+
"OptionsFlowWatcher": "optionsflowwatcher",
|
| 117 |
+
"TrendAnalyst": "trendanalyst",
|
| 118 |
+
"SentimentAnalyst": "sentimentanalyst",
|
| 119 |
+
"MarketEventWatcher": "marketeventwatcher",
|
| 120 |
+
"MacroContextWatcher": "macrocontextwatcher",
|
| 121 |
+
"UnusualEventDetector": "unusualeventdetector",
|
| 122 |
+
"EventRouter": "eventrouter",
|
| 123 |
+
"BTCAnalyst": "btcanalyst",
|
| 124 |
+
"SPYAnalyst": "spyanalyst",
|
| 125 |
+
"QQQAnalyst": "qqqanalyst",
|
| 126 |
+
"GLDAnalyst": "gldanalyst",
|
| 127 |
+
"QuantResearcher": "quantresearcher",
|
| 128 |
+
"Backtester": "backtester",
|
| 129 |
+
"RiskAnalyst": "riskanalyst",
|
| 130 |
+
"QuantStrategist": "quantstrategist",
|
| 131 |
+
"Publisher": "publisher",
|
| 132 |
+
"VizAgent": "vizagent",
|
| 133 |
+
"PortfolioMonitor": "portfoliomonitor",
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
|
| 137 |
def _is_llm_unavailable_output(content: str) -> bool:
|
| 138 |
lowered = content.lower()
|
|
|
|
| 297 |
self._yolo_update_fn = yolo_update_fn
|
| 298 |
self._yolo_completed: list[str] = [] # agents finished in this YOLO run
|
| 299 |
self._yolo_run_context: YoloRunContext | None = None
|
| 300 |
+
self._typed_yolo_run_started = False
|
| 301 |
+
self._typed_yolo_states: dict[str, str] = {}
|
| 302 |
+
self._typed_yolo_times: dict[str, dict[str, str]] = {}
|
| 303 |
self._parser = MentionParser(session.registry)
|
| 304 |
|
| 305 |
# V4.4 STRUCT-1: delegate to focused sub-components
|
|
|
|
| 337 |
)
|
| 338 |
return self._yolo_run_context
|
| 339 |
|
| 340 |
+
async def run_yolo(self, tickers: list[str]) -> Any:
|
| 341 |
+
"""Run the shared typed quant graph and post Finley's product output."""
|
| 342 |
+
from datetime import UTC, datetime
|
| 343 |
+
|
| 344 |
+
from polyhedra.core.active_routing import build_active_routing_plan
|
| 345 |
+
from polyhedra.core.dependency_executor import AgentExecutionState
|
| 346 |
+
from polyhedra.core.quant_contracts import ExecutionContext
|
| 347 |
+
from polyhedra.services.quant_runtime import QuantRuntime
|
| 348 |
+
|
| 349 |
+
if not tickers:
|
| 350 |
+
raise ValueError("YOLO requires at least one ticker")
|
| 351 |
+
if self._yolo_run_context is None or self._typed_yolo_run_started:
|
| 352 |
+
self.prepare_yolo_run(tickers)
|
| 353 |
+
context = self._yolo_run_context
|
| 354 |
+
if context is None:
|
| 355 |
+
raise RuntimeError("YOLO run context was not created")
|
| 356 |
+
self._typed_yolo_run_started = True
|
| 357 |
+
|
| 358 |
+
plan = build_active_routing_plan(
|
| 359 |
+
run_id=context.run_id,
|
| 360 |
+
execution_context=ExecutionContext.YOLO,
|
| 361 |
+
tickers=tickers,
|
| 362 |
+
)
|
| 363 |
+
self._typed_yolo_states = {
|
| 364 |
+
item.agent: AgentExecutionState.WAITING.value for item in plan.active_agents
|
| 365 |
+
}
|
| 366 |
+
self._typed_yolo_times = {item.agent: {} for item in plan.active_agents}
|
| 367 |
+
|
| 368 |
+
agents = {}
|
| 369 |
+
for item in plan.active_agents:
|
| 370 |
+
role = _TYPED_AGENT_ROLES[item.agent]
|
| 371 |
+
entry = self.session.registry.get(role)
|
| 372 |
+
if entry is None or entry.is_human:
|
| 373 |
+
raise RuntimeError(f"@{role} is not available for the automated YOLO run")
|
| 374 |
+
agents[item.agent] = entry.agent
|
| 375 |
+
|
| 376 |
+
writer = FileWriter(
|
| 377 |
+
self.session.session_dir,
|
| 378 |
+
session_id=self.session.session_id,
|
| 379 |
+
cache=self._cache,
|
| 380 |
+
rag=self._rag,
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
async def progress(agent, state, detail: str) -> None:
|
| 384 |
+
self._typed_yolo_states[agent] = state.value
|
| 385 |
+
timestamp = datetime.now(tz=UTC).isoformat()
|
| 386 |
+
if state == AgentExecutionState.RUNNING:
|
| 387 |
+
self._typed_yolo_times[agent]["started_at"] = timestamp
|
| 388 |
+
elif state in {
|
| 389 |
+
AgentExecutionState.COMPLETED,
|
| 390 |
+
AgentExecutionState.FAILED,
|
| 391 |
+
AgentExecutionState.BLOCKED,
|
| 392 |
+
}:
|
| 393 |
+
self._typed_yolo_times[agent]["finished_at"] = timestamp
|
| 394 |
+
if state == AgentExecutionState.COMPLETED:
|
| 395 |
+
role = _TYPED_AGENT_ROLES[agent]
|
| 396 |
+
if role not in self._yolo_completed:
|
| 397 |
+
self._yolo_completed.append(role)
|
| 398 |
+
if self._yolo_update_fn is not None:
|
| 399 |
+
await self._yolo_update_fn(self._build_typed_yolo_status(tickers, detail))
|
| 400 |
+
|
| 401 |
+
async def before_agent(agent, inputs) -> None:
|
| 402 |
+
await self._maybe_gate_typed_cost(agent, inputs.model_dump_json())
|
| 403 |
+
|
| 404 |
+
runtime = QuantRuntime(
|
| 405 |
+
session_dir=self.session.session_dir,
|
| 406 |
+
session_id=self.session.session_id,
|
| 407 |
+
agents=agents,
|
| 408 |
+
writer=writer,
|
| 409 |
+
trace=self._trace,
|
| 410 |
+
progress=progress,
|
| 411 |
+
before_agent=before_agent,
|
| 412 |
+
)
|
| 413 |
+
result = await runtime.run_yolo(
|
| 414 |
+
run_id=context.run_id,
|
| 415 |
+
tickers=tickers,
|
| 416 |
+
started_at=datetime.fromisoformat(context.run_started_at),
|
| 417 |
+
)
|
| 418 |
+
await self._cache.async_flush_to_disk(self.session.session_dir)
|
| 419 |
+
|
| 420 |
+
if result.finley is not None:
|
| 421 |
+
content = result.finley.payload.slack_rendering
|
| 422 |
+
await self._post("publisher", content)
|
| 423 |
+
self.session.post("publisher", content)
|
| 424 |
+
else:
|
| 425 |
+
failures = [
|
| 426 |
+
record for record in result.record.execution.records
|
| 427 |
+
if record.state != AgentExecutionState.COMPLETED
|
| 428 |
+
]
|
| 429 |
+
detail = "\n".join(
|
| 430 |
+
f"- {record.agent}: {record.state.value}"
|
| 431 |
+
+ (f" ({record.error})" if record.error else "")
|
| 432 |
+
+ (f" (blocked by {', '.join(record.blocked_by)})" if record.blocked_by else "")
|
| 433 |
+
for record in failures
|
| 434 |
+
)
|
| 435 |
+
message = (
|
| 436 |
+
"YOLO analysis did not reach Finley. No market opinion was produced.\n\n"
|
| 437 |
+
f"{detail or '- Publisher output is unavailable.'}"
|
| 438 |
+
)
|
| 439 |
+
await self._post("coordinator", message)
|
| 440 |
+
self.session.post("coordinator", message)
|
| 441 |
+
if result.record.status.value == "completed":
|
| 442 |
+
mark_yolo_run_completed(self.session.session_dir)
|
| 443 |
+
return result
|
| 444 |
+
|
| 445 |
+
async def _maybe_gate_typed_cost(self, agent: str, prompt: str) -> None:
|
| 446 |
+
role = _TYPED_AGENT_ROLES[agent]
|
| 447 |
+
entry = self.session.registry.get(role)
|
| 448 |
+
llm = self._llm or (getattr(entry.agent, "_llm", None) if entry else None)
|
| 449 |
+
if llm is None:
|
| 450 |
+
return
|
| 451 |
+
input_tokens = llm.estimate_tokens(prompt)
|
| 452 |
+
estimated_cost = llm.calculate_cost(input_tokens, 1_024, None)
|
| 453 |
+
if not self._cost_gate.requires_approval(estimated_cost):
|
| 454 |
+
return
|
| 455 |
+
summary = self._cost_gate.format_approval_request(
|
| 456 |
+
estimated_cost,
|
| 457 |
+
f"@{role} ({input_tokens:,} input + 1,024 output tokens)",
|
| 458 |
+
)
|
| 459 |
+
result = await self._checkpoint(summary)
|
| 460 |
+
if not result.approved:
|
| 461 |
+
raise _CostRejected(f"@{role} cost approval was declined")
|
| 462 |
+
|
| 463 |
+
def _build_typed_yolo_status(self, tickers: list[str], detail: str = "") -> str:
|
| 464 |
+
grouped: dict[str, list[str]] = {
|
| 465 |
+
"RUNNING": [], "COMPLETED": [], "WAITING": [], "FAILED": [], "BLOCKED": [],
|
| 466 |
+
}
|
| 467 |
+
for agent, state in self._typed_yolo_states.items():
|
| 468 |
+
grouped.setdefault(state, []).append(agent)
|
| 469 |
+
lines = [
|
| 470 |
+
f"⚡ YOLO run in progress — {', '.join(tickers)}",
|
| 471 |
+
f" {self._yolo_mode_label()} | dependency-based agent execution",
|
| 472 |
+
]
|
| 473 |
+
for state, label in (
|
| 474 |
+
("RUNNING", "Running"), ("COMPLETED", "Completed"),
|
| 475 |
+
("WAITING", "Waiting"), ("FAILED", "Failed"), ("BLOCKED", "Blocked"),
|
| 476 |
+
):
|
| 477 |
+
if grouped[state]:
|
| 478 |
+
lines.append(f" {label}: {', '.join(grouped[state])}")
|
| 479 |
+
if detail and (grouped["FAILED"] or grouped["BLOCKED"]):
|
| 480 |
+
lines.append(f" Detail: {detail}")
|
| 481 |
+
if grouped["COMPLETED"] and not any(grouped[state] for state in ("RUNNING", "WAITING")):
|
| 482 |
+
lines[0] = f"⚡ YOLO run finished — {', '.join(tickers)}"
|
| 483 |
+
return "\n".join(lines)
|
| 484 |
+
|
| 485 |
async def dispatch(self, from_role: str, text: str, origin_id: str = "") -> None:
|
| 486 |
"""
|
| 487 |
Entry point for every incoming message.
|
|
|
|
| 926 |
|
| 927 |
def _yolo_mode_label(self) -> str:
|
| 928 |
"""Return a Slack/UI-friendly YOLO run mode label."""
|
|
|
|
|
|
|
|
|
|
| 929 |
try:
|
| 930 |
+
qs = ResearchStateManager(self.session.session_dir).load().quant_state
|
| 931 |
except Exception:
|
| 932 |
qs = None
|
| 933 |
mode = getattr(qs, "yolo_run_mode", "") if qs is not None else ""
|
|
|
|
| 935 |
return "Session-delta YOLO"
|
| 936 |
if mode == "baseline":
|
| 937 |
return "Baseline YOLO"
|
| 938 |
+
yolo_run_context = getattr(self, "_yolo_run_context", None)
|
| 939 |
+
if yolo_run_context is not None:
|
| 940 |
+
return yolo_run_context.label
|
| 941 |
return "YOLO"
|
| 942 |
|
| 943 |
async def _on_agent_blocked(self, event: AgentBlockedEvent) -> None:
|
src/polyhedra/agents/quant/decision_contracts.py
CHANGED
|
@@ -93,7 +93,7 @@ class QuantResearcherInput(AgentInput[QuantResearcherDependencies, QuantResearch
|
|
| 93 |
(self.optional_context.unusual_events, "UnusualEventDetector"),
|
| 94 |
):
|
| 95 |
if value is not None:
|
| 96 |
-
_current_output(value, producer, self)
|
| 97 |
return self
|
| 98 |
|
| 99 |
|
|
@@ -289,12 +289,19 @@ class RiskAnalystInput(AgentInput[RiskAnalystDependencies, RiskAnalystContext]):
|
|
| 289 |
_current_output(self.dependencies.backtests, "Backtester", self)
|
| 290 |
for value, producer in (
|
| 291 |
(self.optional_context.trend, "TrendAnalyst"),
|
| 292 |
-
(self.optional_context.macro_context, "MacroContextWatcher"),
|
| 293 |
):
|
| 294 |
if value is not None:
|
| 295 |
_current_output(value, producer, self)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
if self.optional_context.asset_analyses is not None:
|
| 297 |
-
_current_collection(self.optional_context.asset_analyses, self)
|
| 298 |
outside = {
|
| 299 |
item.ticker for item in self.optional_context.open_positions
|
| 300 |
} - set(self.ticker_scope)
|
|
@@ -476,13 +483,24 @@ class QuantStrategistInput(AgentInput[QuantStrategistDependencies, QuantStrategi
|
|
| 476 |
for value, producer in (
|
| 477 |
(self.optional_context.signals, "QuantResearcher"),
|
| 478 |
(self.optional_context.backtests, "Backtester"),
|
| 479 |
-
(self.optional_context.sentiment, "SentimentAnalyst"),
|
| 480 |
-
(self.optional_context.macro_context, "MacroContextWatcher"),
|
| 481 |
):
|
| 482 |
if value is not None:
|
| 483 |
_current_output(value, producer, self)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
if self.optional_context.asset_analyses is not None:
|
| 485 |
-
_current_collection(self.optional_context.asset_analyses, self)
|
| 486 |
return self
|
| 487 |
|
| 488 |
|
|
|
|
| 93 |
(self.optional_context.unusual_events, "UnusualEventDetector"),
|
| 94 |
):
|
| 95 |
if value is not None:
|
| 96 |
+
_current_output(value, producer, self, specialized)
|
| 97 |
return self
|
| 98 |
|
| 99 |
|
|
|
|
| 289 |
_current_output(self.dependencies.backtests, "Backtester", self)
|
| 290 |
for value, producer in (
|
| 291 |
(self.optional_context.trend, "TrendAnalyst"),
|
|
|
|
| 292 |
):
|
| 293 |
if value is not None:
|
| 294 |
_current_output(value, producer, self)
|
| 295 |
+
specialized = set(self.ticker_scope) & {"BTC", "SPY", "QQQ", "GLD"}
|
| 296 |
+
if self.optional_context.macro_context is not None:
|
| 297 |
+
_current_output(
|
| 298 |
+
self.optional_context.macro_context,
|
| 299 |
+
"MacroContextWatcher",
|
| 300 |
+
self,
|
| 301 |
+
specialized,
|
| 302 |
+
)
|
| 303 |
if self.optional_context.asset_analyses is not None:
|
| 304 |
+
_current_collection(self.optional_context.asset_analyses, self, specialized)
|
| 305 |
outside = {
|
| 306 |
item.ticker for item in self.optional_context.open_positions
|
| 307 |
} - set(self.ticker_scope)
|
|
|
|
| 483 |
for value, producer in (
|
| 484 |
(self.optional_context.signals, "QuantResearcher"),
|
| 485 |
(self.optional_context.backtests, "Backtester"),
|
|
|
|
|
|
|
| 486 |
):
|
| 487 |
if value is not None:
|
| 488 |
_current_output(value, producer, self)
|
| 489 |
+
specialized = set(self.ticker_scope) & {"BTC", "SPY", "QQQ", "GLD"}
|
| 490 |
+
general = set(self.ticker_scope) - specialized
|
| 491 |
+
if self.optional_context.sentiment is not None:
|
| 492 |
+
_current_output(
|
| 493 |
+
self.optional_context.sentiment, "SentimentAnalyst", self, general,
|
| 494 |
+
)
|
| 495 |
+
if self.optional_context.macro_context is not None:
|
| 496 |
+
_current_output(
|
| 497 |
+
self.optional_context.macro_context,
|
| 498 |
+
"MacroContextWatcher",
|
| 499 |
+
self,
|
| 500 |
+
specialized,
|
| 501 |
+
)
|
| 502 |
if self.optional_context.asset_analyses is not None:
|
| 503 |
+
_current_collection(self.optional_context.asset_analyses, self, specialized)
|
| 504 |
return self
|
| 505 |
|
| 506 |
|
src/polyhedra/agents/quant/product_contracts.py
CHANGED
|
@@ -70,12 +70,14 @@ class PublisherInput(AgentInput[PublisherDependencies, PublisherContext]):
|
|
| 70 |
_current_output(self.dependencies.strategy, "QuantStrategist", self)
|
| 71 |
for value, producer in (
|
| 72 |
(self.optional_context.trend, "TrendAnalyst"),
|
| 73 |
-
(self.optional_context.sentiment, "SentimentAnalyst"),
|
| 74 |
(self.optional_context.risk, "RiskAnalyst"),
|
| 75 |
-
(self.optional_context.macro_context, "MacroContextWatcher"),
|
| 76 |
):
|
| 77 |
if value is not None:
|
| 78 |
_current_output(value, producer, self)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
if self.optional_context.asset_analyses is not None:
|
| 80 |
collection = self.optional_context.asset_analyses
|
| 81 |
if (collection.run_id, collection.session_id) != (self.run_id, self.session_id):
|
|
|
|
| 70 |
_current_output(self.dependencies.strategy, "QuantStrategist", self)
|
| 71 |
for value, producer in (
|
| 72 |
(self.optional_context.trend, "TrendAnalyst"),
|
|
|
|
| 73 |
(self.optional_context.risk, "RiskAnalyst"),
|
|
|
|
| 74 |
):
|
| 75 |
if value is not None:
|
| 76 |
_current_output(value, producer, self)
|
| 77 |
+
if self.optional_context.sentiment is not None:
|
| 78 |
+
_current_output(self.optional_context.sentiment, "SentimentAnalyst", self)
|
| 79 |
+
if self.optional_context.macro_context is not None:
|
| 80 |
+
_current_output(self.optional_context.macro_context, "MacroContextWatcher", self)
|
| 81 |
if self.optional_context.asset_analyses is not None:
|
| 82 |
collection = self.optional_context.asset_analyses
|
| 83 |
if (collection.run_id, collection.session_id) != (self.run_id, self.session_id):
|
src/polyhedra/app.py
CHANGED
|
@@ -188,6 +188,9 @@ def _session_payload(session_id: str) -> dict[str, Any] | None:
|
|
| 188 |
session = SessionManager().resume(session_id)
|
| 189 |
if session is None:
|
| 190 |
return None
|
|
|
|
|
|
|
|
|
|
| 191 |
messages = session.thread_history(last_n=300)
|
| 192 |
quant_state = _quant_state_payload(session)
|
| 193 |
run_started_at = str(quant_state.get("yolo_run_started_at") or "")
|
|
@@ -200,7 +203,6 @@ def _session_payload(session_id: str) -> dict[str, Any] | None:
|
|
| 200 |
if message.get("from_role") in planned_roles
|
| 201 |
]
|
| 202 |
unique_completed = list(dict.fromkeys(completed_roles))
|
| 203 |
-
run = _RUNS.get(session_id, {})
|
| 204 |
failed = run.get("status") == "failed"
|
| 205 |
blocker = _first_blocker(path_messages)
|
| 206 |
blocked = blocker is not None
|
|
@@ -305,6 +307,353 @@ def _session_payload(session_id: str) -> dict[str, Any] | None:
|
|
| 305 |
}
|
| 306 |
|
| 307 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
def _messages_since(messages: list[dict[str, Any]], started_at: str) -> list[dict[str, Any]]:
|
| 309 |
try:
|
| 310 |
started = datetime.fromisoformat(started_at)
|
|
@@ -702,6 +1051,7 @@ async def _start_yolo_run_for_session(
|
|
| 702 |
"messages": [],
|
| 703 |
"status_message": "",
|
| 704 |
"error": "",
|
|
|
|
| 705 |
}
|
| 706 |
_RUNS[session.session_id] = run_state
|
| 707 |
|
|
@@ -722,6 +1072,8 @@ async def _start_yolo_run_for_session(
|
|
| 722 |
|
| 723 |
async def yolo_update_fn(status_text: str) -> None:
|
| 724 |
run_state["status_message"] = status_text
|
|
|
|
|
|
|
| 725 |
run_state["messages"].append({
|
| 726 |
"from_role": "coordinator",
|
| 727 |
"content": status_text,
|
|
@@ -749,11 +1101,10 @@ async def _start_yolo_run_for_session(
|
|
| 749 |
selected_roles=session.active_roles or list(session.registry.roles()),
|
| 750 |
human_roles=[],
|
| 751 |
)
|
| 752 |
-
await service.
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
)
|
| 756 |
-
await _wait_for_yolo_terminal(session.session_id)
|
| 757 |
except Exception as exc:
|
| 758 |
logger.exception("UI YOLO run failed: %s", exc)
|
| 759 |
run_state["status"] = "failed"
|
|
@@ -814,6 +1165,15 @@ def _persist_yolo_run_record(session_id: str, payload: dict[str, Any]) -> None:
|
|
| 814 |
return
|
| 815 |
run = _RUNS.get(session_id, {})
|
| 816 |
run_id = str(payload.get("run_id") or run.get("run_id") or datetime.now(tz=UTC).strftime("%Y%m%d_%H%M%S"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 817 |
payload["run_id"] = run_id
|
| 818 |
payload["replay_label"] = "Prior YOLO run replay - UI-only, not deterministic/frozen replay."
|
| 819 |
payload["recorded_at"] = datetime.now(tz=UTC).isoformat()
|
|
@@ -852,15 +1212,21 @@ def _list_yolo_run_records(session_id: str) -> list[dict[str, Any]]:
|
|
| 852 |
data = json.loads(path.read_text(encoding="utf-8"))
|
| 853 |
except json.JSONDecodeError:
|
| 854 |
continue
|
|
|
|
| 855 |
records.append({
|
| 856 |
"run_id": data.get("run_id") or path.stem,
|
| 857 |
"status": data.get("status", ""),
|
| 858 |
"run_mode": data.get("run_mode", ""),
|
| 859 |
-
"run_mode_label": data.get("run_mode_label", "")
|
| 860 |
-
|
| 861 |
-
|
|
|
|
|
|
|
| 862 |
"proposal_state": data.get("proposal_state", {}),
|
| 863 |
-
"replay_label": data.get("replay_label", "")
|
|
|
|
|
|
|
|
|
|
| 864 |
})
|
| 865 |
return records
|
| 866 |
|
|
@@ -874,9 +1240,25 @@ def _yolo_run_record(session_id: str, run_id: str) -> dict[str, Any]:
|
|
| 874 |
path = session.session_dir / _YOLO_RUNS_DIR / f"{run_id}.json"
|
| 875 |
if not path.exists():
|
| 876 |
raise FileNotFoundError(run_id)
|
| 877 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 878 |
data["replay"] = True
|
| 879 |
-
data["replay_label"] = data.get("replay_label") or "Prior YOLO run replay - UI-only
|
| 880 |
return data
|
| 881 |
|
| 882 |
|
|
|
|
| 188 |
session = SessionManager().resume(session_id)
|
| 189 |
if session is None:
|
| 190 |
return None
|
| 191 |
+
run = _RUNS.get(session_id, {})
|
| 192 |
+
if run.get("runtime_schema") == "8.0":
|
| 193 |
+
return _typed_session_payload(session, run)
|
| 194 |
messages = session.thread_history(last_n=300)
|
| 195 |
quant_state = _quant_state_payload(session)
|
| 196 |
run_started_at = str(quant_state.get("yolo_run_started_at") or "")
|
|
|
|
| 203 |
if message.get("from_role") in planned_roles
|
| 204 |
]
|
| 205 |
unique_completed = list(dict.fromkeys(completed_roles))
|
|
|
|
| 206 |
failed = run.get("status") == "failed"
|
| 207 |
blocker = _first_blocker(path_messages)
|
| 208 |
blocked = blocker is not None
|
|
|
|
| 307 |
}
|
| 308 |
|
| 309 |
|
| 310 |
+
def _typed_session_payload(session: Any, run: dict[str, Any]) -> dict[str, Any]:
|
| 311 |
+
"""Project a live or completed V8 run into the existing UI response shape."""
|
| 312 |
+
from polyhedra.agents.coordinator import _ROLE_LABELS, _TYPED_AGENT_ROLES
|
| 313 |
+
from polyhedra.agents.quant.io_registry import quant_artifact_schema
|
| 314 |
+
from polyhedra.core.active_routing import build_active_routing_plan
|
| 315 |
+
from polyhedra.core.dependency_executor import AgentExecutionState
|
| 316 |
+
from polyhedra.core.quant_contracts import ExecutionContext, load_quant_contracts
|
| 317 |
+
from polyhedra.services.quant_run_record import QuantRunRecord
|
| 318 |
+
|
| 319 |
+
run_id = str(run.get("run_id") or "")
|
| 320 |
+
tickers = [str(item).upper() for item in run.get("tickers") or []]
|
| 321 |
+
record = None
|
| 322 |
+
raw_record = run.get("typed_record")
|
| 323 |
+
if raw_record:
|
| 324 |
+
record = QuantRunRecord.model_validate(raw_record)
|
| 325 |
+
elif run_id:
|
| 326 |
+
path = session.session_dir / _YOLO_RUNS_DIR / f"{run_id}.json"
|
| 327 |
+
if path.exists():
|
| 328 |
+
try:
|
| 329 |
+
record = QuantRunRecord.model_validate_json(
|
| 330 |
+
path.read_text(encoding="utf-8"), strict=True,
|
| 331 |
+
)
|
| 332 |
+
except Exception:
|
| 333 |
+
record = None
|
| 334 |
+
|
| 335 |
+
plan = record.routing_plan if record else build_active_routing_plan(
|
| 336 |
+
run_id=run_id,
|
| 337 |
+
execution_context=ExecutionContext.YOLO,
|
| 338 |
+
tickers=tickers,
|
| 339 |
+
)
|
| 340 |
+
live_states = dict(run.get("agent_states") or {})
|
| 341 |
+
records = {item.agent: item for item in record.execution.records} if record else {}
|
| 342 |
+
path_rows = []
|
| 343 |
+
for item in plan.active_agents:
|
| 344 |
+
execution = records.get(item.agent)
|
| 345 |
+
state = execution.state.value if execution else live_states.get(
|
| 346 |
+
item.agent, AgentExecutionState.WAITING.value,
|
| 347 |
+
)
|
| 348 |
+
artifact_ref = (
|
| 349 |
+
execution.artifact_ref.model_dump(mode="json")
|
| 350 |
+
if execution and execution.artifact_ref else None
|
| 351 |
+
)
|
| 352 |
+
references = _typed_agent_references(session.session_dir, artifact_ref)
|
| 353 |
+
live_times = (run.get("agent_times") or {}).get(item.agent, {})
|
| 354 |
+
input_snapshot = (
|
| 355 |
+
record.input_snapshot_paths.get(item.agent, "") if record else ""
|
| 356 |
+
)
|
| 357 |
+
if not input_snapshot:
|
| 358 |
+
candidate = f"quant/runs/{run_id}/inputs/{item.agent}.json"
|
| 359 |
+
if (session.session_dir / candidate).is_file():
|
| 360 |
+
input_snapshot = candidate
|
| 361 |
+
path_rows.append({
|
| 362 |
+
"role": _TYPED_AGENT_ROLES[item.agent],
|
| 363 |
+
"agent": item.agent,
|
| 364 |
+
"label": _ROLE_LABELS.get(_TYPED_AGENT_ROLES[item.agent], item.agent),
|
| 365 |
+
"status": state.lower(),
|
| 366 |
+
"result_status": execution.result_status.value if execution and execution.result_status else "",
|
| 367 |
+
"effective_ticker_scope": list(item.effective_ticker_scope),
|
| 368 |
+
"dependencies": [dep.agent for dep in item.required_dependencies],
|
| 369 |
+
"artifact_ref": artifact_ref,
|
| 370 |
+
"input_snapshot": input_snapshot,
|
| 371 |
+
"input_refs": references["input_refs"],
|
| 372 |
+
"baseline_refs": references["baseline_refs"],
|
| 373 |
+
"started_at": (
|
| 374 |
+
execution.started_at.isoformat() if execution and execution.started_at
|
| 375 |
+
else live_times.get("started_at", "")
|
| 376 |
+
),
|
| 377 |
+
"finished_at": (
|
| 378 |
+
execution.finished_at.isoformat() if execution and execution.finished_at
|
| 379 |
+
else live_times.get("finished_at", "")
|
| 380 |
+
),
|
| 381 |
+
"error": execution.error if execution else None,
|
| 382 |
+
"blocked_by": list(execution.blocked_by) if execution else [],
|
| 383 |
+
})
|
| 384 |
+
|
| 385 |
+
status = record.status.value if record else str(run.get("status") or "running")
|
| 386 |
+
current = next((item for item in path_rows if item["status"] == "running"), None)
|
| 387 |
+
if current is None and status in {"running", "pending"}:
|
| 388 |
+
current = next((item for item in path_rows if item["status"] == "waiting"), None)
|
| 389 |
+
messages = session.thread_history(last_n=300)
|
| 390 |
+
finley = _typed_finley(session.session_dir, run_id)
|
| 391 |
+
if finley is None and record is None:
|
| 392 |
+
finley = next(
|
| 393 |
+
(message for message in reversed(messages) if message.get("from_role") == "publisher"),
|
| 394 |
+
None,
|
| 395 |
+
)
|
| 396 |
+
options_context = _typed_options_context(session.session_dir, run_id)
|
| 397 |
+
diagnostics = _typed_diagnostics(session.session_dir, path_rows)
|
| 398 |
+
proposal_state = _typed_proposal_state(session.session_dir, run_id, path_rows)
|
| 399 |
+
quant_state = _quant_state_payload(session)
|
| 400 |
+
baseline_run_id = record.baseline_run_id if record else None
|
| 401 |
+
contracts = load_quant_contracts()
|
| 402 |
+
permissions = []
|
| 403 |
+
for item in plan.active_agents:
|
| 404 |
+
contract = contracts.for_agent(item.agent)
|
| 405 |
+
templates = (
|
| 406 |
+
record.permission_templates.get(item.agent)
|
| 407 |
+
if record and record.permission_templates else None
|
| 408 |
+
) or contract.permissions.model_dump(mode="json")
|
| 409 |
+
resolved = (
|
| 410 |
+
record.permission_snapshots.get(item.agent)
|
| 411 |
+
if record and record.permission_snapshots else None
|
| 412 |
+
) or _resolve_permission_paths(
|
| 413 |
+
templates,
|
| 414 |
+
run_id=run_id,
|
| 415 |
+
baseline_run_id=baseline_run_id,
|
| 416 |
+
tickers=list(item.effective_ticker_scope),
|
| 417 |
+
)
|
| 418 |
+
permissions.append({
|
| 419 |
+
"agent": item.agent,
|
| 420 |
+
"active": True,
|
| 421 |
+
"inactive_reason": "",
|
| 422 |
+
"templates": templates,
|
| 423 |
+
"resolved": resolved,
|
| 424 |
+
"input_snapshot": (
|
| 425 |
+
record.input_snapshot_paths.get(item.agent, "") if record else ""
|
| 426 |
+
),
|
| 427 |
+
"published_output": next(
|
| 428 |
+
(row["artifact_ref"] for row in path_rows if row["agent"] == item.agent),
|
| 429 |
+
None,
|
| 430 |
+
),
|
| 431 |
+
})
|
| 432 |
+
for item in plan.inactive_agents:
|
| 433 |
+
permissions.append({
|
| 434 |
+
"agent": item.agent,
|
| 435 |
+
"active": False,
|
| 436 |
+
"inactive_reason": item.reason.value,
|
| 437 |
+
"templates": contracts.for_agent(item.agent).permissions.model_dump(mode="json"),
|
| 438 |
+
"resolved": {},
|
| 439 |
+
"input_snapshot": "",
|
| 440 |
+
"published_output": None,
|
| 441 |
+
})
|
| 442 |
+
|
| 443 |
+
routing = {
|
| 444 |
+
"schema_version": "8.0",
|
| 445 |
+
"active": [item.model_dump(mode="json") for item in plan.active_agents],
|
| 446 |
+
"inactive": [item.model_dump(mode="json") for item in plan.inactive_agents],
|
| 447 |
+
}
|
| 448 |
+
blocked = next((row for row in path_rows if row["status"] in {"failed", "blocked"}), None)
|
| 449 |
+
return {
|
| 450 |
+
"session_id": session.session_id,
|
| 451 |
+
"run_id": run_id,
|
| 452 |
+
"goal": session.goal,
|
| 453 |
+
"created_at": session.created_at.isoformat(),
|
| 454 |
+
"platform": session.platform,
|
| 455 |
+
"status": status,
|
| 456 |
+
"workflow": "V8 typed quant dependency graph",
|
| 457 |
+
"run_mode": (
|
| 458 |
+
record.run_mode.value if record else quant_state.get("yolo_run_mode", "")
|
| 459 |
+
),
|
| 460 |
+
"run_mode_label": _yolo_mode_label(quant_state),
|
| 461 |
+
"yolo_context": {
|
| 462 |
+
"run_started_at": quant_state.get("yolo_run_started_at"),
|
| 463 |
+
"run_count": quant_state.get("yolo_run_count", 0),
|
| 464 |
+
"baseline_run_id": baseline_run_id,
|
| 465 |
+
"baseline_complete": bool(baseline_run_id),
|
| 466 |
+
"baseline_artifacts": quant_state.get("yolo_baseline_artifacts", {}),
|
| 467 |
+
"missing_baseline_artifacts": quant_state.get("yolo_missing_baseline_artifacts", []),
|
| 468 |
+
"baseline_snapshot_dir": quant_state.get("yolo_baseline_snapshot_dir", ""),
|
| 469 |
+
},
|
| 470 |
+
"current_agent": ({"role": current["role"], "label": current["label"]} if current else {}),
|
| 471 |
+
"blocked": ({
|
| 472 |
+
"agent": blocked["agent"], "label": blocked["label"],
|
| 473 |
+
"reason": blocked.get("error") or (
|
| 474 |
+
"Blocked by " + ", ".join(blocked.get("blocked_by") or [])
|
| 475 |
+
),
|
| 476 |
+
} if blocked else {}),
|
| 477 |
+
"path": path_rows,
|
| 478 |
+
"messages": messages,
|
| 479 |
+
"finley": finley,
|
| 480 |
+
"committee": _strategist_committee_payload(session.session_dir, quant_state),
|
| 481 |
+
"options_context": options_context,
|
| 482 |
+
"diagnostics": diagnostics,
|
| 483 |
+
"proposal_state": proposal_state,
|
| 484 |
+
"routing": routing,
|
| 485 |
+
"permissions": permissions,
|
| 486 |
+
"artifact_inventory": (
|
| 487 |
+
[item.model_dump(mode="json") for item in record.artifact_inventory]
|
| 488 |
+
if record else []
|
| 489 |
+
),
|
| 490 |
+
"run_status_message": run.get("status_message", ""),
|
| 491 |
+
"error": run.get("error", "") or (blocked.get("error", "") if blocked else ""),
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def _typed_agent_references(
|
| 496 |
+
session_dir: Path,
|
| 497 |
+
artifact_ref: dict[str, Any] | None,
|
| 498 |
+
) -> dict[str, list[dict[str, Any]]]:
|
| 499 |
+
"""Read exact current and baseline references from one published output."""
|
| 500 |
+
empty = {"input_refs": [], "baseline_refs": []}
|
| 501 |
+
if not artifact_ref or not artifact_ref.get("path"):
|
| 502 |
+
return empty
|
| 503 |
+
path = session_dir / str(artifact_ref["path"])
|
| 504 |
+
try:
|
| 505 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 506 |
+
except (OSError, json.JSONDecodeError):
|
| 507 |
+
return empty
|
| 508 |
+
return {
|
| 509 |
+
"input_refs": list(data.get("input_refs") or []),
|
| 510 |
+
"baseline_refs": list(data.get("baseline_refs") or []),
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def _typed_options_context(session_dir: Path, run_id: str) -> dict[str, Any]:
|
| 515 |
+
path = session_dir / "quant" / "runs" / run_id / "options_flow.json"
|
| 516 |
+
if not path.exists():
|
| 517 |
+
return {"status": "missing", "summary": "No options context artifact for this run."}
|
| 518 |
+
try:
|
| 519 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 520 |
+
except (OSError, json.JSONDecodeError) as exc:
|
| 521 |
+
return {"status": "data_gap", "summary": f"Options artifact could not be read: {exc}"}
|
| 522 |
+
status = str(data.get("status") or "UNAVAILABLE")
|
| 523 |
+
gaps = data.get("data_gaps") or []
|
| 524 |
+
summary = json.dumps({
|
| 525 |
+
"status": status,
|
| 526 |
+
"ticker_scope": data.get("ticker_scope") or [],
|
| 527 |
+
"data_gaps": gaps,
|
| 528 |
+
"payload": data.get("payload") or {},
|
| 529 |
+
}, indent=2)
|
| 530 |
+
return {"status": "ok" if status == "COMPLETE" else "data_gap", "summary": summary}
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def _typed_finley(session_dir: Path, run_id: str) -> dict[str, Any] | None:
|
| 534 |
+
path = session_dir / "quant" / "runs" / run_id / "post.json"
|
| 535 |
+
if not path.exists():
|
| 536 |
+
return None
|
| 537 |
+
try:
|
| 538 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 539 |
+
except (OSError, json.JSONDecodeError):
|
| 540 |
+
return None
|
| 541 |
+
payload = data.get("payload") or {}
|
| 542 |
+
content = str(payload.get("slack_rendering") or "")
|
| 543 |
+
if not content:
|
| 544 |
+
return None
|
| 545 |
+
return {
|
| 546 |
+
"from_role": "publisher",
|
| 547 |
+
"content": content,
|
| 548 |
+
"timestamp": data.get("created_at") or "",
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def _typed_diagnostics(session_dir: Path, path_rows: list[dict[str, Any]]) -> dict[str, Any]:
|
| 553 |
+
issues = []
|
| 554 |
+
for row in path_rows:
|
| 555 |
+
if row["status"] in {"failed", "blocked"}:
|
| 556 |
+
issues.append({
|
| 557 |
+
"agent": row["agent"],
|
| 558 |
+
"label": row["label"],
|
| 559 |
+
"severity": "blocked",
|
| 560 |
+
"status": row["status"],
|
| 561 |
+
"detail": row.get("error") or (
|
| 562 |
+
"Blocked by " + ", ".join(row.get("blocked_by") or [])
|
| 563 |
+
),
|
| 564 |
+
})
|
| 565 |
+
elif row.get("result_status") == "UNAVAILABLE" and row.get("artifact_ref"):
|
| 566 |
+
artifact = session_dir / row["artifact_ref"]["path"]
|
| 567 |
+
gaps = []
|
| 568 |
+
try:
|
| 569 |
+
gaps = json.loads(artifact.read_text(encoding="utf-8")).get("data_gaps") or []
|
| 570 |
+
except (OSError, json.JSONDecodeError):
|
| 571 |
+
pass
|
| 572 |
+
issues.append({
|
| 573 |
+
"agent": row["agent"],
|
| 574 |
+
"label": row["label"],
|
| 575 |
+
"severity": "warning",
|
| 576 |
+
"status": "data_gap",
|
| 577 |
+
"detail": "; ".join(str(gap.get("message") or gap) for gap in gaps)
|
| 578 |
+
or "Agent completed with unavailable evidence.",
|
| 579 |
+
})
|
| 580 |
+
summary = "No YOLO pipeline issues detected."
|
| 581 |
+
if issues:
|
| 582 |
+
summary = f"{issues[0]['label']}: {issues[0]['detail']}"
|
| 583 |
+
return {"summary": summary, "issues": issues}
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def _typed_proposal_state(
|
| 587 |
+
session_dir: Path,
|
| 588 |
+
run_id: str,
|
| 589 |
+
path_rows: list[dict[str, Any]],
|
| 590 |
+
) -> dict[str, Any]:
|
| 591 |
+
strategy_path = session_dir / "quant" / "runs" / run_id / "trade_proposals.json"
|
| 592 |
+
post_path = session_dir / "quant" / "runs" / run_id / "post.json"
|
| 593 |
+
if strategy_path.exists():
|
| 594 |
+
try:
|
| 595 |
+
strategy = json.loads(strategy_path.read_text(encoding="utf-8"))
|
| 596 |
+
payload = strategy.get("payload") or {}
|
| 597 |
+
outcome = str(payload.get("outcome") or "ANALYSIS_UNAVAILABLE")
|
| 598 |
+
proposals = payload.get("proposals") or []
|
| 599 |
+
reason = None
|
| 600 |
+
if post_path.exists():
|
| 601 |
+
reason = (json.loads(post_path.read_text(encoding="utf-8")).get("payload") or {}).get(
|
| 602 |
+
"no_proposal_reason"
|
| 603 |
+
)
|
| 604 |
+
return {
|
| 605 |
+
"status": outcome.lower(),
|
| 606 |
+
"label": outcome.replace("_", " ").title(),
|
| 607 |
+
"detail": (
|
| 608 |
+
f"{len(proposals)} paper trade proposal(s) are ready for human review."
|
| 609 |
+
if proposals else f"No proposal: {reason or outcome}."
|
| 610 |
+
),
|
| 611 |
+
"proposal_count": len(proposals),
|
| 612 |
+
"no_proposal_reason": reason,
|
| 613 |
+
}
|
| 614 |
+
except (OSError, json.JSONDecodeError):
|
| 615 |
+
pass
|
| 616 |
+
pending = next(
|
| 617 |
+
(row for row in path_rows if row["agent"] in {"QuantStrategist", "Publisher"}
|
| 618 |
+
and row["status"] != "completed"),
|
| 619 |
+
None,
|
| 620 |
+
)
|
| 621 |
+
return {
|
| 622 |
+
"status": "agent_pending",
|
| 623 |
+
"label": "Agent Pending",
|
| 624 |
+
"detail": (
|
| 625 |
+
f"No proposal decision yet: {pending['label']} is {pending['status']}."
|
| 626 |
+
if pending else "No typed strategy artifact is available for this run."
|
| 627 |
+
),
|
| 628 |
+
"proposal_count": 0,
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def _resolve_permission_paths(
|
| 633 |
+
templates: dict[str, list[str]],
|
| 634 |
+
*,
|
| 635 |
+
run_id: str,
|
| 636 |
+
baseline_run_id: str | None,
|
| 637 |
+
tickers: list[str],
|
| 638 |
+
) -> dict[str, list[str]]:
|
| 639 |
+
resolved: dict[str, list[str]] = {}
|
| 640 |
+
for operation, paths in templates.items():
|
| 641 |
+
values = []
|
| 642 |
+
for template in paths:
|
| 643 |
+
selected_run = baseline_run_id if operation.startswith("baseline_") else run_id
|
| 644 |
+
if not selected_run and ("{run_id}" in template or "{baseline_run_id}" in template):
|
| 645 |
+
continue
|
| 646 |
+
path = template.replace("{run_id}", selected_run or "").replace(
|
| 647 |
+
"{baseline_run_id}", selected_run or "",
|
| 648 |
+
)
|
| 649 |
+
if "{ticker}" in path:
|
| 650 |
+
values.extend(path.replace("{ticker}", ticker) for ticker in tickers)
|
| 651 |
+
else:
|
| 652 |
+
values.append(path)
|
| 653 |
+
resolved[operation] = values
|
| 654 |
+
return resolved
|
| 655 |
+
|
| 656 |
+
|
| 657 |
def _messages_since(messages: list[dict[str, Any]], started_at: str) -> list[dict[str, Any]]:
|
| 658 |
try:
|
| 659 |
started = datetime.fromisoformat(started_at)
|
|
|
|
| 1051 |
"messages": [],
|
| 1052 |
"status_message": "",
|
| 1053 |
"error": "",
|
| 1054 |
+
"runtime_schema": "8.0",
|
| 1055 |
}
|
| 1056 |
_RUNS[session.session_id] = run_state
|
| 1057 |
|
|
|
|
| 1072 |
|
| 1073 |
async def yolo_update_fn(status_text: str) -> None:
|
| 1074 |
run_state["status_message"] = status_text
|
| 1075 |
+
run_state["agent_states"] = dict(getattr(service, "_typed_yolo_states", {}))
|
| 1076 |
+
run_state["agent_times"] = dict(getattr(service, "_typed_yolo_times", {}))
|
| 1077 |
run_state["messages"].append({
|
| 1078 |
"from_role": "coordinator",
|
| 1079 |
"content": status_text,
|
|
|
|
| 1101 |
selected_roles=session.active_roles or list(session.registry.roles()),
|
| 1102 |
human_roles=[],
|
| 1103 |
)
|
| 1104 |
+
result = await service.run_yolo(tickers)
|
| 1105 |
+
run_state["run_id"] = result.record.run_id
|
| 1106 |
+
run_state["status"] = result.record.status.value
|
| 1107 |
+
run_state["typed_record"] = result.record.model_dump(mode="json")
|
|
|
|
| 1108 |
except Exception as exc:
|
| 1109 |
logger.exception("UI YOLO run failed: %s", exc)
|
| 1110 |
run_state["status"] = "failed"
|
|
|
|
| 1165 |
return
|
| 1166 |
run = _RUNS.get(session_id, {})
|
| 1167 |
run_id = str(payload.get("run_id") or run.get("run_id") or datetime.now(tz=UTC).strftime("%Y%m%d_%H%M%S"))
|
| 1168 |
+
existing = session.session_dir / _YOLO_RUNS_DIR / f"{run_id}.json"
|
| 1169 |
+
if existing.exists():
|
| 1170 |
+
try:
|
| 1171 |
+
from polyhedra.services.quant_run_record import QuantRunRecord
|
| 1172 |
+
|
| 1173 |
+
QuantRunRecord.model_validate_json(existing.read_text(encoding="utf-8"), strict=True)
|
| 1174 |
+
return
|
| 1175 |
+
except Exception:
|
| 1176 |
+
pass
|
| 1177 |
payload["run_id"] = run_id
|
| 1178 |
payload["replay_label"] = "Prior YOLO run replay - UI-only, not deterministic/frozen replay."
|
| 1179 |
payload["recorded_at"] = datetime.now(tz=UTC).isoformat()
|
|
|
|
| 1212 |
data = json.loads(path.read_text(encoding="utf-8"))
|
| 1213 |
except json.JSONDecodeError:
|
| 1214 |
continue
|
| 1215 |
+
is_typed = data.get("schema_version") == "8.0" and "routing_plan" in data
|
| 1216 |
records.append({
|
| 1217 |
"run_id": data.get("run_id") or path.stem,
|
| 1218 |
"status": data.get("status", ""),
|
| 1219 |
"run_mode": data.get("run_mode", ""),
|
| 1220 |
+
"run_mode_label": data.get("run_mode_label", "") or (
|
| 1221 |
+
"Session-delta YOLO" if data.get("run_mode") == "DELTA" else "Baseline YOLO"
|
| 1222 |
+
),
|
| 1223 |
+
"goal": data.get("goal", "") or session.goal,
|
| 1224 |
+
"recorded_at": data.get("recorded_at", "") or data.get("completed_at", ""),
|
| 1225 |
"proposal_state": data.get("proposal_state", {}),
|
| 1226 |
+
"replay_label": data.get("replay_label", "") or (
|
| 1227 |
+
"Prior typed YOLO run replay - UI-only." if is_typed else ""
|
| 1228 |
+
),
|
| 1229 |
+
"schema_version": data.get("schema_version", "legacy"),
|
| 1230 |
})
|
| 1231 |
return records
|
| 1232 |
|
|
|
|
| 1240 |
path = session.session_dir / _YOLO_RUNS_DIR / f"{run_id}.json"
|
| 1241 |
if not path.exists():
|
| 1242 |
raise FileNotFoundError(run_id)
|
| 1243 |
+
raw = path.read_text(encoding="utf-8")
|
| 1244 |
+
data = json.loads(raw)
|
| 1245 |
+
if data.get("schema_version") == "8.0" and "routing_plan" in data:
|
| 1246 |
+
from polyhedra.services.quant_run_record import QuantRunRecord
|
| 1247 |
+
|
| 1248 |
+
record = QuantRunRecord.model_validate_json(raw, strict=True)
|
| 1249 |
+
data = _typed_session_payload(session, {
|
| 1250 |
+
"runtime_schema": "8.0",
|
| 1251 |
+
"session_id": session_id,
|
| 1252 |
+
"run_id": run_id,
|
| 1253 |
+
"status": record.status.value,
|
| 1254 |
+
"tickers": list(record.ticker_scope),
|
| 1255 |
+
"typed_record": record.model_dump(mode="json"),
|
| 1256 |
+
"messages": [],
|
| 1257 |
+
"status_message": "",
|
| 1258 |
+
"error": "",
|
| 1259 |
+
})
|
| 1260 |
data["replay"] = True
|
| 1261 |
+
data["replay_label"] = data.get("replay_label") or "Prior YOLO run replay - UI-only."
|
| 1262 |
return data
|
| 1263 |
|
| 1264 |
|
src/polyhedra/messaging/slack.py
CHANGED
|
@@ -516,10 +516,7 @@ class SlackIntegration:
|
|
| 516 |
goal_tickers = _extract_tickers_from_text(goal)
|
| 517 |
if goal_tickers:
|
| 518 |
await self._seed_service_watchlist(service, goal_tickers)
|
| 519 |
-
await service.
|
| 520 |
-
from_role="human",
|
| 521 |
-
text=f"@datafetcher run {' '.join(goal_tickers)}".strip(),
|
| 522 |
-
)
|
| 523 |
|
| 524 |
async def _auto_init(
|
| 525 |
self,
|
|
@@ -648,10 +645,7 @@ class SlackIntegration:
|
|
| 648 |
f" Watchlist: {wl_str}{mode_hint} | Run `@PolyTest help` for commands."
|
| 649 |
)
|
| 650 |
if yolo:
|
| 651 |
-
await service.
|
| 652 |
-
from_role="human",
|
| 653 |
-
text=f"@datafetcher run {' '.join(watchlist)}".strip(),
|
| 654 |
-
)
|
| 655 |
|
| 656 |
async def _cmd_goal_from_mention(self, channel_id: str, new_goal: str, say: Any) -> None:
|
| 657 |
"""Handle `@coordinator goal "<text>"` mention (V4.5 FR-3.3)."""
|
|
@@ -813,10 +807,7 @@ class SlackIntegration:
|
|
| 813 |
goal_tickers = _extract_tickers_from_text(goal)
|
| 814 |
if goal_tickers:
|
| 815 |
await self._seed_service_watchlist(service, goal_tickers)
|
| 816 |
-
await service.
|
| 817 |
-
from_role="human",
|
| 818 |
-
text=f"@datafetcher run {' '.join(goal_tickers)}".strip(),
|
| 819 |
-
)
|
| 820 |
|
| 821 |
async def _cmd_goal(self, client: Any, channel_id: str, args: str) -> None:
|
| 822 |
"""Handle `/poly goal "<text>"` — update the session goal (V4.5 FR-3.3)."""
|
|
@@ -1045,18 +1036,14 @@ class SlackIntegration:
|
|
| 1045 |
await client.chat_postMessage(channel=channel_id, text=status_text)
|
| 1046 |
|
| 1047 |
service._yolo_update_fn = _yolo_update
|
| 1048 |
-
context = service.prepare_yolo_run(requested)
|
| 1049 |
await client.chat_postMessage(
|
| 1050 |
channel=channel_id,
|
| 1051 |
text=(
|
| 1052 |
-
f"⚡ *
|
| 1053 |
"_Same Polyhedra agent workflow; Finley posts the final output._"
|
| 1054 |
),
|
| 1055 |
)
|
| 1056 |
-
await service.
|
| 1057 |
-
from_role="human",
|
| 1058 |
-
text=f"@datafetcher run {' '.join(requested)}",
|
| 1059 |
-
)
|
| 1060 |
|
| 1061 |
async def _seed_service_watchlist(self, service: Any, tickers: list[str]) -> None:
|
| 1062 |
from polyhedra.core.research_state import QuantState, ResearchStateManager
|
|
|
|
| 516 |
goal_tickers = _extract_tickers_from_text(goal)
|
| 517 |
if goal_tickers:
|
| 518 |
await self._seed_service_watchlist(service, goal_tickers)
|
| 519 |
+
await service.run_yolo(goal_tickers)
|
|
|
|
|
|
|
|
|
|
| 520 |
|
| 521 |
async def _auto_init(
|
| 522 |
self,
|
|
|
|
| 645 |
f" Watchlist: {wl_str}{mode_hint} | Run `@PolyTest help` for commands."
|
| 646 |
)
|
| 647 |
if yolo:
|
| 648 |
+
await service.run_yolo(watchlist)
|
|
|
|
|
|
|
|
|
|
| 649 |
|
| 650 |
async def _cmd_goal_from_mention(self, channel_id: str, new_goal: str, say: Any) -> None:
|
| 651 |
"""Handle `@coordinator goal "<text>"` mention (V4.5 FR-3.3)."""
|
|
|
|
| 807 |
goal_tickers = _extract_tickers_from_text(goal)
|
| 808 |
if goal_tickers:
|
| 809 |
await self._seed_service_watchlist(service, goal_tickers)
|
| 810 |
+
await service.run_yolo(goal_tickers)
|
|
|
|
|
|
|
|
|
|
| 811 |
|
| 812 |
async def _cmd_goal(self, client: Any, channel_id: str, args: str) -> None:
|
| 813 |
"""Handle `/poly goal "<text>"` — update the session goal (V4.5 FR-3.3)."""
|
|
|
|
| 1036 |
await client.chat_postMessage(channel=channel_id, text=status_text)
|
| 1037 |
|
| 1038 |
service._yolo_update_fn = _yolo_update
|
|
|
|
| 1039 |
await client.chat_postMessage(
|
| 1040 |
channel=channel_id,
|
| 1041 |
text=(
|
| 1042 |
+
f"⚡ *YOLO starting* — {', '.join(requested)}\n"
|
| 1043 |
"_Same Polyhedra agent workflow; Finley posts the final output._"
|
| 1044 |
),
|
| 1045 |
)
|
| 1046 |
+
await service.run_yolo(requested)
|
|
|
|
|
|
|
|
|
|
| 1047 |
|
| 1048 |
async def _seed_service_watchlist(self, service: Any, tickers: list[str]) -> None:
|
| 1049 |
from polyhedra.core.research_state import QuantState, ResearchStateManager
|
src/polyhedra/services/evidence_ledger.py
CHANGED
|
@@ -7,6 +7,8 @@ from datetime import UTC, datetime
|
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Any
|
| 9 |
|
|
|
|
|
|
|
| 10 |
|
| 11 |
def write_evidence_ledger(
|
| 12 |
session_dir: Path,
|
|
@@ -49,6 +51,112 @@ def write_evidence_ledger(
|
|
| 49 |
}
|
| 50 |
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
def _collect_entries(
|
| 53 |
session_dir: Path,
|
| 54 |
*,
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Any
|
| 9 |
|
| 10 |
+
from polyhedra.core.dependency_executor import AgentExecutionState
|
| 11 |
+
|
| 12 |
|
| 13 |
def write_evidence_ledger(
|
| 14 |
session_dir: Path,
|
|
|
|
| 51 |
}
|
| 52 |
|
| 53 |
|
| 54 |
+
def write_typed_evidence_ledger(session_dir: Path, record: Any) -> dict[str, str]:
|
| 55 |
+
"""Write a V8 ledger from recorded publications and actual artifact references."""
|
| 56 |
+
created_at = datetime.now(tz=UTC).isoformat()
|
| 57 |
+
entries: list[dict[str, Any]] = []
|
| 58 |
+
seen: set[tuple[str, str, str]] = set()
|
| 59 |
+
|
| 60 |
+
def add(*, agent: str, path: str, usage: str, evidence_type: str,
|
| 61 |
+
summary: str, gap: str = "") -> None:
|
| 62 |
+
key = (path, usage, summary)
|
| 63 |
+
if key in seen:
|
| 64 |
+
return
|
| 65 |
+
seen.add(key)
|
| 66 |
+
entries.append({
|
| 67 |
+
"ledger_id": f"{record.run_id}:{len(entries) + 1}",
|
| 68 |
+
"run_id": record.run_id,
|
| 69 |
+
"session_id": record.session_id,
|
| 70 |
+
"created_at": created_at,
|
| 71 |
+
"ticker_scope": list(record.ticker_scope),
|
| 72 |
+
"agent_role": agent,
|
| 73 |
+
"artifact_path": path,
|
| 74 |
+
"evidence_type": evidence_type,
|
| 75 |
+
"source": "typed_runtime_reference",
|
| 76 |
+
"source_timestamp": created_at,
|
| 77 |
+
"freshness_state": "unavailable" if gap else "recorded",
|
| 78 |
+
"usage_state": usage,
|
| 79 |
+
"summary": summary,
|
| 80 |
+
"linked_decision": record.status.value,
|
| 81 |
+
"data_gap_reason": gap,
|
| 82 |
+
})
|
| 83 |
+
|
| 84 |
+
by_path = {item.path: item for item in record.artifact_inventory}
|
| 85 |
+
for execution in record.execution.records:
|
| 86 |
+
if execution.state != AgentExecutionState.COMPLETED or execution.artifact_ref is None:
|
| 87 |
+
reason = execution.error or (
|
| 88 |
+
"Blocked by " + ", ".join(execution.blocked_by)
|
| 89 |
+
if execution.blocked_by else "No artifact was published."
|
| 90 |
+
)
|
| 91 |
+
add(
|
| 92 |
+
agent=execution.agent,
|
| 93 |
+
path="",
|
| 94 |
+
usage="excluded",
|
| 95 |
+
evidence_type="execution_status",
|
| 96 |
+
summary=f"{execution.state.value}: {reason}",
|
| 97 |
+
gap=reason,
|
| 98 |
+
)
|
| 99 |
+
continue
|
| 100 |
+
output_path = execution.artifact_ref.path
|
| 101 |
+
add(
|
| 102 |
+
agent=execution.agent,
|
| 103 |
+
path=output_path,
|
| 104 |
+
usage="produced",
|
| 105 |
+
evidence_type="agent_output",
|
| 106 |
+
summary=f"Published {execution.result_status.value} typed output.",
|
| 107 |
+
)
|
| 108 |
+
try:
|
| 109 |
+
artifact = json.loads((session_dir / output_path).read_text(encoding="utf-8"))
|
| 110 |
+
except (OSError, json.JSONDecodeError):
|
| 111 |
+
continue
|
| 112 |
+
for reference in [*(artifact.get("input_refs") or []), *(artifact.get("baseline_refs") or [])]:
|
| 113 |
+
path = str(reference.get("path") or "")
|
| 114 |
+
add(
|
| 115 |
+
agent=execution.agent,
|
| 116 |
+
path=path,
|
| 117 |
+
usage="used",
|
| 118 |
+
evidence_type="baseline_input" if reference.get("run_id") != record.run_id else "current_input",
|
| 119 |
+
summary=f"Actually referenced by {execution.agent}.",
|
| 120 |
+
)
|
| 121 |
+
for gap in artifact.get("data_gaps") or []:
|
| 122 |
+
message = str(gap.get("message") or "Recorded data gap.")
|
| 123 |
+
add(
|
| 124 |
+
agent=execution.agent,
|
| 125 |
+
path=output_path,
|
| 126 |
+
usage="data_gap",
|
| 127 |
+
evidence_type="recorded_exclusion",
|
| 128 |
+
summary=message,
|
| 129 |
+
gap=message,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
for path, reference in by_path.items():
|
| 133 |
+
if any(entry["artifact_path"] == path for entry in entries):
|
| 134 |
+
continue
|
| 135 |
+
add(
|
| 136 |
+
agent=reference.producer,
|
| 137 |
+
path=path,
|
| 138 |
+
usage="published_not_cited",
|
| 139 |
+
evidence_type="runtime_artifact",
|
| 140 |
+
summary="Published in this run but not cited by an agent output.",
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
payload = {
|
| 144 |
+
"run_id": record.run_id,
|
| 145 |
+
"session_id": record.session_id,
|
| 146 |
+
"created_at": created_at,
|
| 147 |
+
"ticker_scope": list(record.ticker_scope),
|
| 148 |
+
"entries": entries,
|
| 149 |
+
}
|
| 150 |
+
quant_dir = session_dir / "quant"
|
| 151 |
+
quant_dir.mkdir(parents=True, exist_ok=True)
|
| 152 |
+
stem = f"evidence_ledger_{record.run_id}"
|
| 153 |
+
json_path = quant_dir / f"{stem}.json"
|
| 154 |
+
md_path = quant_dir / f"{stem}.md"
|
| 155 |
+
json_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
| 156 |
+
md_path.write_text(_render_markdown(payload), encoding="utf-8")
|
| 157 |
+
return {"json": f"quant/{stem}.json", "markdown": f"quant/{stem}.md"}
|
| 158 |
+
|
| 159 |
+
|
| 160 |
def _collect_entries(
|
| 161 |
session_dir: Path,
|
| 162 |
*,
|
src/polyhedra/services/file_writer.py
CHANGED
|
@@ -373,6 +373,24 @@ class ScopedFileWriter:
|
|
| 373 |
normalized, content, mode="overwrite", agent_role=self.agent, metadata=metadata,
|
| 374 |
)
|
| 375 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
def list(self, prefix: str | None = None) -> list[str]:
|
| 377 |
allowed = self._list | self._baseline_list
|
| 378 |
if prefix is not None:
|
|
|
|
| 373 |
normalized, content, mode="overwrite", agent_role=self.agent, metadata=metadata,
|
| 374 |
)
|
| 375 |
|
| 376 |
+
def replace_atomic(
|
| 377 |
+
self,
|
| 378 |
+
path: str,
|
| 379 |
+
content: str,
|
| 380 |
+
*,
|
| 381 |
+
metadata: dict | None = None,
|
| 382 |
+
) -> None:
|
| 383 |
+
"""Create or replace one mutable ACL-owned file atomically."""
|
| 384 |
+
normalized = self._allowed(path, "create", self._create)
|
| 385 |
+
if normalized not in self._edit:
|
| 386 |
+
raise ArtifactAccessError(f"{self.agent} cannot edit {normalized}")
|
| 387 |
+
self._performance_capability(normalized)
|
| 388 |
+
if self._publications.is_published(normalized):
|
| 389 |
+
raise ArtifactAccessError("published artifact is immutable")
|
| 390 |
+
self._writer.write_atomic(
|
| 391 |
+
normalized, content, agent_role=self.agent, metadata=metadata,
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
def list(self, prefix: str | None = None) -> list[str]:
|
| 395 |
allowed = self._list | self._baseline_list
|
| 396 |
if prefix is not None:
|
src/polyhedra/services/quant_run_record.py
CHANGED
|
@@ -7,7 +7,7 @@ from enum import StrEnum
|
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Self
|
| 9 |
|
| 10 |
-
from pydantic import AwareDatetime, model_validator
|
| 11 |
|
| 12 |
from polyhedra.core.active_routing import ActiveRoutingPlan
|
| 13 |
from polyhedra.core.artifacts import (
|
|
@@ -40,6 +40,8 @@ class QuantRunRecord(TypedModel):
|
|
| 40 |
routing_plan: ActiveRoutingPlan
|
| 41 |
execution: DependencyExecutionResult
|
| 42 |
input_snapshot_paths: dict[AgentName, str]
|
|
|
|
|
|
|
| 43 |
artifact_inventory: list[ArtifactRef]
|
| 44 |
|
| 45 |
@model_validator(mode="after")
|
|
@@ -74,6 +76,22 @@ class QuantRunRecord(TypedModel):
|
|
| 74 |
raise ValueError("input snapshot belongs to an inactive agent")
|
| 75 |
if path != f"quant/runs/{self.run_id}/inputs/{agent}.json":
|
| 76 |
raise ValueError("input snapshot path contradicts run or agent")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
paths: set[str] = set()
|
| 79 |
identities: set[str] = set()
|
|
@@ -104,6 +122,8 @@ def build_quant_run_record(
|
|
| 104 |
started_at: datetime,
|
| 105 |
completed_at: datetime,
|
| 106 |
input_snapshot_paths: dict[AgentName, str],
|
|
|
|
|
|
|
| 107 |
additional_artifacts: list[ArtifactRef] | None = None,
|
| 108 |
) -> QuantRunRecord:
|
| 109 |
inventory = [
|
|
@@ -125,6 +145,8 @@ def build_quant_run_record(
|
|
| 125 |
routing_plan=plan,
|
| 126 |
execution=execution,
|
| 127 |
input_snapshot_paths=input_snapshot_paths,
|
|
|
|
|
|
|
| 128 |
artifact_inventory=inventory,
|
| 129 |
)
|
| 130 |
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Self
|
| 9 |
|
| 10 |
+
from pydantic import AwareDatetime, Field, model_validator
|
| 11 |
|
| 12 |
from polyhedra.core.active_routing import ActiveRoutingPlan
|
| 13 |
from polyhedra.core.artifacts import (
|
|
|
|
| 40 |
routing_plan: ActiveRoutingPlan
|
| 41 |
execution: DependencyExecutionResult
|
| 42 |
input_snapshot_paths: dict[AgentName, str]
|
| 43 |
+
permission_templates: dict[AgentName, dict[str, list[str]]] = Field(default_factory=dict)
|
| 44 |
+
permission_snapshots: dict[AgentName, dict[str, list[str]]] = Field(default_factory=dict)
|
| 45 |
artifact_inventory: list[ArtifactRef]
|
| 46 |
|
| 47 |
@model_validator(mode="after")
|
|
|
|
| 76 |
raise ValueError("input snapshot belongs to an inactive agent")
|
| 77 |
if path != f"quant/runs/{self.run_id}/inputs/{agent}.json":
|
| 78 |
raise ValueError("input snapshot path contradicts run or agent")
|
| 79 |
+
operations = {"read", "create", "edit", "list", "baseline_read", "baseline_list"}
|
| 80 |
+
for label, snapshots in (
|
| 81 |
+
("permission template", self.permission_templates),
|
| 82 |
+
("permission", self.permission_snapshots),
|
| 83 |
+
):
|
| 84 |
+
if snapshots and set(snapshots) != active:
|
| 85 |
+
raise ValueError(f"{label} snapshots must cover every active agent")
|
| 86 |
+
for agent, snapshot in snapshots.items():
|
| 87 |
+
if set(snapshot) != operations:
|
| 88 |
+
raise ValueError(f"{label} snapshot for {agent} is incomplete")
|
| 89 |
+
for paths in snapshot.values():
|
| 90 |
+
if len(paths) != len(set(paths)) or any(
|
| 91 |
+
not path or path.startswith("/") or "\\" in path or ".." in path.split("/")
|
| 92 |
+
for path in paths
|
| 93 |
+
):
|
| 94 |
+
raise ValueError(f"{label} snapshot contains an invalid filename")
|
| 95 |
|
| 96 |
paths: set[str] = set()
|
| 97 |
identities: set[str] = set()
|
|
|
|
| 122 |
started_at: datetime,
|
| 123 |
completed_at: datetime,
|
| 124 |
input_snapshot_paths: dict[AgentName, str],
|
| 125 |
+
permission_templates: dict[AgentName, dict[str, list[str]]] | None = None,
|
| 126 |
+
permission_snapshots: dict[AgentName, dict[str, list[str]]] | None = None,
|
| 127 |
additional_artifacts: list[ArtifactRef] | None = None,
|
| 128 |
) -> QuantRunRecord:
|
| 129 |
inventory = [
|
|
|
|
| 145 |
routing_plan=plan,
|
| 146 |
execution=execution,
|
| 147 |
input_snapshot_paths=input_snapshot_paths,
|
| 148 |
+
permission_templates=permission_templates or {},
|
| 149 |
+
permission_snapshots=permission_snapshots or {},
|
| 150 |
artifact_inventory=inventory,
|
| 151 |
)
|
| 152 |
|
src/polyhedra/services/quant_runtime.py
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared typed quant runtime used by Slack and the browser YOLO entry."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import inspect
|
| 6 |
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
from pydantic import BaseModel
|
| 12 |
+
|
| 13 |
+
from polyhedra.agents.base import AgentResponse
|
| 14 |
+
from polyhedra.agents.quant.asset_contracts import (
|
| 15 |
+
AssetAnalysisCollection, BTCAnalystOutput, GLDAnalystOutput,
|
| 16 |
+
QQQAnalystOutput, SPYAnalystOutput,
|
| 17 |
+
)
|
| 18 |
+
from polyhedra.agents.quant.decision_contracts import CommitteePerformance
|
| 19 |
+
from polyhedra.agents.quant.io_registry import quant_artifact_schema, quant_io_binding
|
| 20 |
+
from polyhedra.agents.quant.market_data_contracts import MarketDataArtifact
|
| 21 |
+
from polyhedra.agents.quant.product_contracts import PublisherOutput
|
| 22 |
+
from polyhedra.core.active_routing import ActiveAgentPlan, build_active_routing_plan
|
| 23 |
+
from polyhedra.core.artifacts import JsonArtifactRef, RunMode
|
| 24 |
+
from polyhedra.core.baseline_selector import BaselineSelection, select_typed_yolo_baseline
|
| 25 |
+
from polyhedra.core.dependency_executor import (
|
| 26 |
+
AgentCompletion, AgentExecutionState, DependencyExecutionResult,
|
| 27 |
+
DependencyExecutor,
|
| 28 |
+
)
|
| 29 |
+
from polyhedra.core.quant_contracts import AgentName, ExecutionContext, load_quant_contracts
|
| 30 |
+
from polyhedra.core.research_state import ResearchStateManager
|
| 31 |
+
from polyhedra.core.state_patcher import StatePatcher
|
| 32 |
+
from polyhedra.core.trace_logger import TraceLogger
|
| 33 |
+
from polyhedra.services.artifact_publisher import ArtifactPublisher
|
| 34 |
+
from polyhedra.services.asset_analysis_collection import build_asset_analysis_collection
|
| 35 |
+
from polyhedra.services.file_writer import FileWriter, PublicationRegistry, ScopedFileWriter
|
| 36 |
+
from polyhedra.services.evidence_ledger import write_typed_evidence_ledger
|
| 37 |
+
from polyhedra.services.published_inputs import ActivationArtifactSnapshot, PublishedInputResolver
|
| 38 |
+
from polyhedra.services.quant_run_record import (
|
| 39 |
+
QuantRunRecord, QuantRunRecordStore, QuantRunStatus, build_quant_run_record,
|
| 40 |
+
)
|
| 41 |
+
from polyhedra.services.strategist_performance import StrategistPerformanceTracker
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
ProgressFn = Callable[[AgentName, AgentExecutionState, str], Awaitable[None]]
|
| 45 |
+
BeforeAgentFn = Callable[[AgentName, BaseModel], Awaitable[None]]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass(frozen=True)
|
| 49 |
+
class QuantRuntimeResult:
|
| 50 |
+
record: QuantRunRecord
|
| 51 |
+
finley: PublisherOutput | None
|
| 52 |
+
baseline: BaselineSelection
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass(frozen=True)
|
| 56 |
+
class _Activation:
|
| 57 |
+
inputs: BaseModel
|
| 58 |
+
files: ScopedFileWriter
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class QuantRuntime:
|
| 62 |
+
"""Execute existing quant agents from the packaged routing and ACL tables."""
|
| 63 |
+
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
*,
|
| 67 |
+
session_dir,
|
| 68 |
+
session_id: str,
|
| 69 |
+
agents: Mapping[AgentName, Any],
|
| 70 |
+
writer: FileWriter,
|
| 71 |
+
trace: TraceLogger,
|
| 72 |
+
progress: ProgressFn | None = None,
|
| 73 |
+
before_agent: BeforeAgentFn | None = None,
|
| 74 |
+
) -> None:
|
| 75 |
+
self._session_dir = session_dir
|
| 76 |
+
self._session_id = session_id
|
| 77 |
+
self._agents = dict(agents)
|
| 78 |
+
self._writer = writer
|
| 79 |
+
self._trace = trace
|
| 80 |
+
self._progress = progress
|
| 81 |
+
self._before_agent = before_agent
|
| 82 |
+
self._patcher = StatePatcher()
|
| 83 |
+
self._publications = PublicationRegistry()
|
| 84 |
+
self._outputs: dict[AgentName, BaseModel] = {}
|
| 85 |
+
self._asset_collection_ref: JsonArtifactRef | None = None
|
| 86 |
+
self._input_paths: dict[AgentName, str] = {}
|
| 87 |
+
self._research_state: dict[str, Any] = {}
|
| 88 |
+
self._selection: BaselineSelection | None = None
|
| 89 |
+
self._publisher: ArtifactPublisher | None = None
|
| 90 |
+
self._as_of: datetime | None = None
|
| 91 |
+
|
| 92 |
+
async def run_yolo(
|
| 93 |
+
self,
|
| 94 |
+
*,
|
| 95 |
+
run_id: str,
|
| 96 |
+
tickers: list[str],
|
| 97 |
+
started_at: datetime | None = None,
|
| 98 |
+
) -> QuantRuntimeResult:
|
| 99 |
+
"""Run the frozen YOLO graph and persist its immutable typed record."""
|
| 100 |
+
self._as_of = started_at or datetime.now(tz=timezone.utc)
|
| 101 |
+
store = QuantRunRecordStore(self._session_dir, session_id=self._session_id)
|
| 102 |
+
self._selection = select_typed_yolo_baseline(
|
| 103 |
+
store.baseline_candidates(),
|
| 104 |
+
session_id=self._session_id,
|
| 105 |
+
current_run_id=run_id,
|
| 106 |
+
ticker_scope=tickers,
|
| 107 |
+
)
|
| 108 |
+
for reference in self._selection.baseline_artifacts:
|
| 109 |
+
self._publications.publish(reference.path, reference)
|
| 110 |
+
|
| 111 |
+
plan = build_active_routing_plan(
|
| 112 |
+
run_id=run_id,
|
| 113 |
+
execution_context=ExecutionContext.YOLO,
|
| 114 |
+
tickers=tickers,
|
| 115 |
+
)
|
| 116 |
+
missing = {item.agent for item in plan.active_agents} - set(self._agents)
|
| 117 |
+
if missing:
|
| 118 |
+
raise RuntimeError(f"active quant agents are not registered: {', '.join(sorted(missing))}")
|
| 119 |
+
|
| 120 |
+
self._publisher = ArtifactPublisher(
|
| 121 |
+
self._writer, session_id=self._session_id, run_id=run_id,
|
| 122 |
+
)
|
| 123 |
+
self._research_state = ResearchStateManager(self._session_dir).load().to_dict()
|
| 124 |
+
self._update_run_state()
|
| 125 |
+
|
| 126 |
+
executor = DependencyExecutor(
|
| 127 |
+
plan,
|
| 128 |
+
session_id=self._session_id,
|
| 129 |
+
runner=self._run_agent,
|
| 130 |
+
input_capture=self._capture_input,
|
| 131 |
+
)
|
| 132 |
+
execution = await executor.run()
|
| 133 |
+
await self._report_blocked(execution)
|
| 134 |
+
completed_at = datetime.now(tz=timezone.utc)
|
| 135 |
+
additional = [
|
| 136 |
+
reference for reference in self._publications.references()
|
| 137 |
+
if reference.run_id == run_id
|
| 138 |
+
]
|
| 139 |
+
record = build_quant_run_record(
|
| 140 |
+
plan=plan,
|
| 141 |
+
execution=execution,
|
| 142 |
+
session_id=self._session_id,
|
| 143 |
+
run_mode=self._selection.run_mode,
|
| 144 |
+
baseline_run_id=self._selection.baseline_run_id,
|
| 145 |
+
started_at=self._as_of,
|
| 146 |
+
completed_at=completed_at,
|
| 147 |
+
input_snapshot_paths=dict(self._input_paths),
|
| 148 |
+
permission_templates=self._permission_templates(plan),
|
| 149 |
+
permission_snapshots=self._permission_snapshots(plan),
|
| 150 |
+
additional_artifacts=_unique_additional_artifacts(execution, additional),
|
| 151 |
+
)
|
| 152 |
+
write_typed_evidence_ledger(self._session_dir, record)
|
| 153 |
+
store.save(record)
|
| 154 |
+
self._persist_state(record, completed_at)
|
| 155 |
+
finley = self._outputs.get("Publisher")
|
| 156 |
+
return QuantRuntimeResult(
|
| 157 |
+
record=record,
|
| 158 |
+
finley=finley if isinstance(finley, PublisherOutput) else None,
|
| 159 |
+
baseline=self._selection,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def _capture_input(
|
| 163 |
+
self,
|
| 164 |
+
item: ActiveAgentPlan,
|
| 165 |
+
dependencies,
|
| 166 |
+
) -> _Activation:
|
| 167 |
+
if item.agent == "QuantResearcher":
|
| 168 |
+
self._publish_asset_collection(item)
|
| 169 |
+
files = self._scoped_files(item)
|
| 170 |
+
readable = set(files.readable_paths())
|
| 171 |
+
required_refs = tuple(
|
| 172 |
+
record.artifact_ref
|
| 173 |
+
for record in dependencies
|
| 174 |
+
if record.artifact_ref is not None and record.artifact_ref.path in readable
|
| 175 |
+
)
|
| 176 |
+
snapshot = PublishedInputResolver(files).capture(required_refs=required_refs)
|
| 177 |
+
inputs = self._build_input(item, snapshot, files)
|
| 178 |
+
return _Activation(inputs=inputs, files=files)
|
| 179 |
+
|
| 180 |
+
async def _run_agent(
|
| 181 |
+
self,
|
| 182 |
+
item: ActiveAgentPlan,
|
| 183 |
+
activation: _Activation,
|
| 184 |
+
) -> AgentCompletion:
|
| 185 |
+
if self._publisher is None:
|
| 186 |
+
raise RuntimeError("quant runtime publisher is not initialized")
|
| 187 |
+
agent = self._agents[item.agent]
|
| 188 |
+
if self._before_agent is not None:
|
| 189 |
+
await self._before_agent(item.agent, activation.inputs)
|
| 190 |
+
await self._notify(item.agent, AgentExecutionState.RUNNING, "")
|
| 191 |
+
trace_id = self._trace.start_run(
|
| 192 |
+
getattr(agent, "role", item.agent),
|
| 193 |
+
prompt=activation.inputs.model_dump_json(),
|
| 194 |
+
session_id=self._session_id,
|
| 195 |
+
)
|
| 196 |
+
token_log = _token_log(self._research_state)
|
| 197 |
+
role = getattr(agent, "role", item.agent)
|
| 198 |
+
role_count = sum(entry.get("agent_role") == role for entry in token_log)
|
| 199 |
+
try:
|
| 200 |
+
kwargs: dict[str, Any] = {
|
| 201 |
+
"files": activation.files,
|
| 202 |
+
"publisher": self._publisher,
|
| 203 |
+
}
|
| 204 |
+
signature = inspect.signature(agent.execute_typed)
|
| 205 |
+
if "research_state" in signature.parameters:
|
| 206 |
+
kwargs["research_state"] = self._research_state
|
| 207 |
+
completion = await agent.execute_typed(activation.inputs, **kwargs)
|
| 208 |
+
output = self._load_output(completion.artifact_ref)
|
| 209 |
+
self._outputs[item.agent] = output
|
| 210 |
+
self._input_paths[item.agent] = (
|
| 211 |
+
f"quant/runs/{completion.artifact_ref.run_id}/inputs/{item.agent}.json"
|
| 212 |
+
)
|
| 213 |
+
if item.agent == "QuantStrategist":
|
| 214 |
+
self._record_committee(output, activation.files)
|
| 215 |
+
usage = [
|
| 216 |
+
entry for entry in _token_log(self._research_state)
|
| 217 |
+
if entry.get("agent_role") == role
|
| 218 |
+
][role_count:]
|
| 219 |
+
response = AgentResponse(
|
| 220 |
+
agent_role=role,
|
| 221 |
+
content=output.model_dump_json(),
|
| 222 |
+
artifact_path=completion.artifact_ref.path,
|
| 223 |
+
output=output,
|
| 224 |
+
)
|
| 225 |
+
self._trace.end_run(
|
| 226 |
+
trace_id,
|
| 227 |
+
response,
|
| 228 |
+
prompt_tokens=sum(int(entry.get("prompt_tokens", 0)) for entry in usage),
|
| 229 |
+
completion_tokens=sum(int(entry.get("completion_tokens", 0)) for entry in usage),
|
| 230 |
+
estimated_cost_usd=sum(float(entry.get("estimated_cost_usd", 0)) for entry in usage),
|
| 231 |
+
)
|
| 232 |
+
await self._notify(item.agent, AgentExecutionState.COMPLETED, completion.result_status)
|
| 233 |
+
return completion
|
| 234 |
+
except BaseException as exc:
|
| 235 |
+
response = AgentResponse(
|
| 236 |
+
agent_role=role,
|
| 237 |
+
content=f"{type(exc).__name__}: {exc}",
|
| 238 |
+
error=f"{type(exc).__name__}: {exc}",
|
| 239 |
+
)
|
| 240 |
+
self._trace.end_run(trace_id, response)
|
| 241 |
+
await self._notify(item.agent, AgentExecutionState.FAILED, str(exc))
|
| 242 |
+
raise
|
| 243 |
+
|
| 244 |
+
def _build_input(
|
| 245 |
+
self,
|
| 246 |
+
item: ActiveAgentPlan,
|
| 247 |
+
snapshot: ActivationArtifactSnapshot,
|
| 248 |
+
files: ScopedFileWriter,
|
| 249 |
+
) -> BaseModel:
|
| 250 |
+
if self._selection is None or self._as_of is None:
|
| 251 |
+
raise RuntimeError("quant runtime input context is not initialized")
|
| 252 |
+
current = [*snapshot.required, *snapshot.optional]
|
| 253 |
+
baseline = list(snapshot.baseline)
|
| 254 |
+
output = lambda producer: _agent_output(current, producer)
|
| 255 |
+
prior = lambda producer: _agent_output(baseline, producer)
|
| 256 |
+
markets = lambda scope: [
|
| 257 |
+
loaded.value for loaded in current
|
| 258 |
+
if isinstance(loaded.value, MarketDataArtifact) and loaded.value.ticker in scope
|
| 259 |
+
]
|
| 260 |
+
refs = [loaded.reference for loaded in baseline]
|
| 261 |
+
scope = list(item.effective_ticker_scope)
|
| 262 |
+
common: dict[str, Any] = {
|
| 263 |
+
"run_id": self._selection.current_run_id,
|
| 264 |
+
"session_id": self._session_id,
|
| 265 |
+
"run_mode": self._selection.run_mode,
|
| 266 |
+
"as_of": self._as_of,
|
| 267 |
+
"ticker_scope": scope,
|
| 268 |
+
}
|
| 269 |
+
agent = item.agent
|
| 270 |
+
if agent == "DataFetcher":
|
| 271 |
+
raw = {
|
| 272 |
+
loaded.value.ticker: loaded.reference
|
| 273 |
+
for loaded in baseline
|
| 274 |
+
if isinstance(loaded.value, MarketDataArtifact) and loaded.value.ticker in scope
|
| 275 |
+
}
|
| 276 |
+
data = {**common, "baseline_refs": raw}
|
| 277 |
+
else:
|
| 278 |
+
data = {**common, "baseline_refs": refs}
|
| 279 |
+
if agent == "OptionsFlowWatcher":
|
| 280 |
+
data.update(dependencies={}, optional_context={"provider_fetch_cutoff": self._as_of})
|
| 281 |
+
elif agent == "TrendAnalyst":
|
| 282 |
+
data.update(
|
| 283 |
+
dependencies={"data_fetch": output("DataFetcher"), "market_data": markets(scope)},
|
| 284 |
+
optional_context={"prior_trend": prior("TrendAnalyst")},
|
| 285 |
+
)
|
| 286 |
+
elif agent in {"SentimentAnalyst", "MarketEventWatcher"}:
|
| 287 |
+
prior_name = "SentimentAnalyst" if agent == "SentimentAnalyst" else "MarketEventWatcher"
|
| 288 |
+
prior_field = "prior_sentiment" if agent == "SentimentAnalyst" else "prior_market_events"
|
| 289 |
+
data.update(
|
| 290 |
+
dependencies={"data_fetch": output("DataFetcher"), "market_data": markets(scope)},
|
| 291 |
+
optional_context={
|
| 292 |
+
"current_trend": output("TrendAnalyst"),
|
| 293 |
+
prior_field: prior(prior_name),
|
| 294 |
+
},
|
| 295 |
+
)
|
| 296 |
+
elif agent == "MacroContextWatcher":
|
| 297 |
+
data.update(
|
| 298 |
+
dependencies={
|
| 299 |
+
"market_events": output("MarketEventWatcher"),
|
| 300 |
+
"options_flow": output("OptionsFlowWatcher"),
|
| 301 |
+
},
|
| 302 |
+
optional_context={"prior_macro": prior("MacroContextWatcher")},
|
| 303 |
+
)
|
| 304 |
+
elif agent == "UnusualEventDetector":
|
| 305 |
+
data.update(
|
| 306 |
+
dependencies={
|
| 307 |
+
"market_events": output("MarketEventWatcher"),
|
| 308 |
+
"macro_context": output("MacroContextWatcher"),
|
| 309 |
+
"options_flow": output("OptionsFlowWatcher"),
|
| 310 |
+
},
|
| 311 |
+
optional_context={"prior_events": prior("UnusualEventDetector")},
|
| 312 |
+
)
|
| 313 |
+
elif agent == "EventRouter":
|
| 314 |
+
data.update(
|
| 315 |
+
dependencies={"unusual_events": output("UnusualEventDetector")},
|
| 316 |
+
optional_context={
|
| 317 |
+
"market_events": output("MarketEventWatcher"),
|
| 318 |
+
"options_flow": output("OptionsFlowWatcher"),
|
| 319 |
+
"prior_route": prior("EventRouter"),
|
| 320 |
+
},
|
| 321 |
+
)
|
| 322 |
+
elif agent in {"BTCAnalyst", "SPYAnalyst", "QQQAnalyst", "GLDAnalyst"}:
|
| 323 |
+
scoped_sentiment = output("SentimentAnalyst")
|
| 324 |
+
if (
|
| 325 |
+
scoped_sentiment is not None
|
| 326 |
+
and not set(scope).intersection(scoped_sentiment.ticker_scope)
|
| 327 |
+
):
|
| 328 |
+
scoped_sentiment = None
|
| 329 |
+
data.update(
|
| 330 |
+
dependencies={
|
| 331 |
+
"trend": output("TrendAnalyst"),
|
| 332 |
+
"event_route": output("EventRouter"),
|
| 333 |
+
},
|
| 334 |
+
optional_context={
|
| 335 |
+
"market_events": output("MarketEventWatcher"),
|
| 336 |
+
"options_flow": None if agent == "BTCAnalyst" else output("OptionsFlowWatcher"),
|
| 337 |
+
"macro_context": output("MacroContextWatcher"),
|
| 338 |
+
"unusual_events": output("UnusualEventDetector"),
|
| 339 |
+
"sentiment": scoped_sentiment,
|
| 340 |
+
},
|
| 341 |
+
)
|
| 342 |
+
elif agent == "QuantResearcher":
|
| 343 |
+
data.update(
|
| 344 |
+
dependencies={
|
| 345 |
+
"trend": output("TrendAnalyst"),
|
| 346 |
+
"sentiment": output("SentimentAnalyst"),
|
| 347 |
+
"asset_analyses": _runtime_collection(current),
|
| 348 |
+
},
|
| 349 |
+
optional_context={
|
| 350 |
+
"macro_context": output("MacroContextWatcher"),
|
| 351 |
+
"unusual_events": output("UnusualEventDetector"),
|
| 352 |
+
},
|
| 353 |
+
)
|
| 354 |
+
elif agent == "Backtester":
|
| 355 |
+
data.update(
|
| 356 |
+
dependencies={"signals": output("QuantResearcher")},
|
| 357 |
+
optional_context={"market_data": markets(scope)},
|
| 358 |
+
)
|
| 359 |
+
elif agent == "RiskAnalyst":
|
| 360 |
+
data.update(
|
| 361 |
+
dependencies={"backtests": output("Backtester")},
|
| 362 |
+
optional_context={
|
| 363 |
+
"trend": output("TrendAnalyst"),
|
| 364 |
+
"asset_analyses": _runtime_collection(current),
|
| 365 |
+
"macro_context": output("MacroContextWatcher"),
|
| 366 |
+
"open_positions": self._risk_positions(scope),
|
| 367 |
+
},
|
| 368 |
+
)
|
| 369 |
+
elif agent == "QuantStrategist":
|
| 370 |
+
tracker = StrategistPerformanceTracker.load(
|
| 371 |
+
files.for_trusted_performance_tool()
|
| 372 |
+
)
|
| 373 |
+
data.update(
|
| 374 |
+
dependencies={"risk": output("RiskAnalyst")},
|
| 375 |
+
optional_context={
|
| 376 |
+
"signals": output("QuantResearcher"),
|
| 377 |
+
"backtests": output("Backtester"),
|
| 378 |
+
"sentiment": output("SentimentAnalyst"),
|
| 379 |
+
"asset_analyses": _runtime_collection(current),
|
| 380 |
+
"macro_context": output("MacroContextWatcher"),
|
| 381 |
+
"committee_performance": CommitteePerformance(
|
| 382 |
+
weights=tracker.current_weights(), recorded_at=self._as_of,
|
| 383 |
+
),
|
| 384 |
+
},
|
| 385 |
+
)
|
| 386 |
+
elif agent == "Publisher":
|
| 387 |
+
data.update(
|
| 388 |
+
dependencies={"strategy": output("QuantStrategist")},
|
| 389 |
+
optional_context={
|
| 390 |
+
"trend": output("TrendAnalyst"),
|
| 391 |
+
"sentiment": output("SentimentAnalyst"),
|
| 392 |
+
"risk": output("RiskAnalyst"),
|
| 393 |
+
"asset_analyses": _runtime_collection(current),
|
| 394 |
+
"macro_context": output("MacroContextWatcher"),
|
| 395 |
+
},
|
| 396 |
+
)
|
| 397 |
+
else:
|
| 398 |
+
raise ValueError(f"{agent} is not a YOLO agent")
|
| 399 |
+
return quant_io_binding(agent).input_schema.model_validate(data)
|
| 400 |
+
|
| 401 |
+
def _scoped_files(self, item: ActiveAgentPlan) -> ScopedFileWriter:
|
| 402 |
+
if self._selection is None:
|
| 403 |
+
raise RuntimeError("baseline selection is unavailable")
|
| 404 |
+
return ScopedFileWriter(
|
| 405 |
+
self._writer,
|
| 406 |
+
agent=item.agent,
|
| 407 |
+
run_id=self._selection.current_run_id,
|
| 408 |
+
ticker_scope=list(item.effective_ticker_scope),
|
| 409 |
+
baseline_run_id=self._selection.baseline_run_id,
|
| 410 |
+
publications=self._publications,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
def _load_output(self, reference: JsonArtifactRef) -> BaseModel:
|
| 414 |
+
raw = self._writer.read(reference.path)
|
| 415 |
+
if raw is None:
|
| 416 |
+
raise FileNotFoundError(reference.path)
|
| 417 |
+
return quant_artifact_schema(reference.producer).model_validate_json(raw, strict=True)
|
| 418 |
+
|
| 419 |
+
def _publish_asset_collection(self, item: ActiveAgentPlan) -> None:
|
| 420 |
+
if self._asset_collection_ref is not None:
|
| 421 |
+
return
|
| 422 |
+
specialized = [ticker for ticker in item.effective_ticker_scope if ticker in {"BTC", "SPY", "QQQ", "GLD"}]
|
| 423 |
+
if not specialized:
|
| 424 |
+
return
|
| 425 |
+
if self._selection is None:
|
| 426 |
+
raise RuntimeError("baseline selection is unavailable")
|
| 427 |
+
outputs = [
|
| 428 |
+
value for value in self._outputs.values()
|
| 429 |
+
if isinstance(value, (BTCAnalystOutput, SPYAnalystOutput, QQQAnalystOutput, GLDAnalystOutput))
|
| 430 |
+
and value.ticker_scope[0] in specialized
|
| 431 |
+
]
|
| 432 |
+
collection = build_asset_analysis_collection(
|
| 433 |
+
run_id=self._selection.current_run_id,
|
| 434 |
+
session_id=self._session_id,
|
| 435 |
+
created_at=datetime.now(tz=timezone.utc),
|
| 436 |
+
ticker_scope=specialized,
|
| 437 |
+
outputs=outputs,
|
| 438 |
+
publications=self._publications,
|
| 439 |
+
)
|
| 440 |
+
path = f"quant/runs/{self._selection.current_run_id}/asset_analysis.json"
|
| 441 |
+
self._writer.write_atomic(path, collection.model_dump_json(indent=2), agent_role="Runtime")
|
| 442 |
+
reference = JsonArtifactRef(
|
| 443 |
+
schema_version="8.0",
|
| 444 |
+
artifact_id=collection.artifact_id,
|
| 445 |
+
run_id=collection.run_id,
|
| 446 |
+
session_id=collection.session_id,
|
| 447 |
+
producer="Runtime",
|
| 448 |
+
path=path,
|
| 449 |
+
)
|
| 450 |
+
self._publications.publish(path, reference)
|
| 451 |
+
self._asset_collection_ref = reference
|
| 452 |
+
|
| 453 |
+
def _risk_positions(self, scope: Sequence[str]) -> list[dict[str, Any]]:
|
| 454 |
+
quant = self._research_state.get("quant_state") or {}
|
| 455 |
+
positions = []
|
| 456 |
+
for position in quant.get("portfolio") or []:
|
| 457 |
+
if position.get("status", "open") != "open" or position.get("ticker") not in scope:
|
| 458 |
+
continue
|
| 459 |
+
positions.append({
|
| 460 |
+
"position_id": position["position_id"],
|
| 461 |
+
"ticker": position["ticker"],
|
| 462 |
+
"direction": str(position["direction"]).upper(),
|
| 463 |
+
"entry_price": float(position["entry_price"]),
|
| 464 |
+
"portfolio_fraction": float(position["size_pct"]) / 100.0,
|
| 465 |
+
})
|
| 466 |
+
return positions
|
| 467 |
+
|
| 468 |
+
def _record_committee(self, output: BaseModel, files: ScopedFileWriter) -> None:
|
| 469 |
+
payload = output.payload
|
| 470 |
+
trusted_files = files.for_trusted_performance_tool()
|
| 471 |
+
tracker = StrategistPerformanceTracker.load(trusted_files)
|
| 472 |
+
votes = [
|
| 473 |
+
{
|
| 474 |
+
"member_id": vote.member_id,
|
| 475 |
+
"vote": vote.vote.value,
|
| 476 |
+
"confidence": vote.confidence.value,
|
| 477 |
+
"rationale": vote.thesis,
|
| 478 |
+
"evidence_used": [item.model_dump(mode="json") for item in vote.cited_evidence],
|
| 479 |
+
"proposal_impact": vote.proposal_impact,
|
| 480 |
+
}
|
| 481 |
+
for vote in payload.committee_votes
|
| 482 |
+
]
|
| 483 |
+
result = tracker.record_votes(
|
| 484 |
+
trusted_files,
|
| 485 |
+
votes,
|
| 486 |
+
run_mode=self._selection.run_mode.value if self._selection else "BASELINE",
|
| 487 |
+
outcome=payload.outcome.value,
|
| 488 |
+
)
|
| 489 |
+
quant = self._research_state.get("quant_state")
|
| 490 |
+
if not isinstance(quant, dict):
|
| 491 |
+
quant = {}
|
| 492 |
+
self._research_state["quant_state"] = quant
|
| 493 |
+
quant["strategist_committee_votes"] = tracker.vote_history
|
| 494 |
+
quant["strategist_committee_weights"] = result["weights"]
|
| 495 |
+
quant["strategist_weight_updates"] = result["weight_updates"]
|
| 496 |
+
quant["strategist_proposal_updates"] = [
|
| 497 |
+
item.model_dump(mode="json") for item in payload.proposal_updates
|
| 498 |
+
]
|
| 499 |
+
quant["trade_proposals_raw"] = [
|
| 500 |
+
item.model_dump(mode="json") for item in payload.proposals
|
| 501 |
+
]
|
| 502 |
+
|
| 503 |
+
def _update_run_state(self) -> None:
|
| 504 |
+
if self._selection is None or self._as_of is None:
|
| 505 |
+
return
|
| 506 |
+
self._patcher.apply(self._session_dir, {
|
| 507 |
+
"yolo_run_mode": (
|
| 508 |
+
"session_delta" if self._selection.run_mode == RunMode.DELTA else "baseline"
|
| 509 |
+
),
|
| 510 |
+
"yolo_run_id": self._selection.current_run_id,
|
| 511 |
+
"yolo_run_started_at": self._as_of.isoformat(),
|
| 512 |
+
"yolo_baseline_complete": self._selection.baseline_run_id is not None,
|
| 513 |
+
"yolo_baseline_artifacts": {
|
| 514 |
+
reference.producer: reference.path
|
| 515 |
+
for reference in self._selection.baseline_artifacts
|
| 516 |
+
},
|
| 517 |
+
"yolo_missing_baseline_artifacts": list(self._selection.missing_tickers),
|
| 518 |
+
})
|
| 519 |
+
|
| 520 |
+
def _persist_state(self, record: QuantRunRecord, completed_at: datetime) -> None:
|
| 521 |
+
quant = self._research_state.get("quant_state") or {}
|
| 522 |
+
patch = {
|
| 523 |
+
key: quant[key]
|
| 524 |
+
for key in (
|
| 525 |
+
"token_log", "trade_proposals_raw", "strategist_committee_votes",
|
| 526 |
+
"strategist_committee_weights", "strategist_weight_updates",
|
| 527 |
+
"strategist_proposal_updates",
|
| 528 |
+
)
|
| 529 |
+
if key in quant
|
| 530 |
+
}
|
| 531 |
+
if record.status == QuantRunStatus.COMPLETED:
|
| 532 |
+
patch["yolo_last_completed_at"] = completed_at.isoformat()
|
| 533 |
+
self._patcher.apply(self._session_dir, patch)
|
| 534 |
+
|
| 535 |
+
def _permission_snapshots(self, plan) -> dict[AgentName, dict[str, list[str]]]:
|
| 536 |
+
baseline_run_id = self._selection.baseline_run_id if self._selection else None
|
| 537 |
+
contracts = load_quant_contracts()
|
| 538 |
+
snapshots: dict[AgentName, dict[str, list[str]]] = {}
|
| 539 |
+
for item in plan.active_agents:
|
| 540 |
+
permissions = contracts.for_agent(item.agent).permissions.model_dump(mode="json")
|
| 541 |
+
resolved: dict[str, list[str]] = {}
|
| 542 |
+
for operation, templates in permissions.items():
|
| 543 |
+
paths: list[str] = []
|
| 544 |
+
selected_run = baseline_run_id if operation.startswith("baseline_") else plan.run_id
|
| 545 |
+
for template in templates:
|
| 546 |
+
if not selected_run and "{baseline_run_id}" in template:
|
| 547 |
+
continue
|
| 548 |
+
path = template.replace("{run_id}", selected_run or "").replace(
|
| 549 |
+
"{baseline_run_id}", selected_run or "",
|
| 550 |
+
)
|
| 551 |
+
if "{ticker}" in path:
|
| 552 |
+
paths.extend(
|
| 553 |
+
path.replace("{ticker}", ticker)
|
| 554 |
+
for ticker in item.effective_ticker_scope
|
| 555 |
+
)
|
| 556 |
+
else:
|
| 557 |
+
paths.append(path)
|
| 558 |
+
resolved[operation] = paths
|
| 559 |
+
snapshots[item.agent] = resolved
|
| 560 |
+
return snapshots
|
| 561 |
+
|
| 562 |
+
def _permission_templates(self, plan) -> dict[AgentName, dict[str, list[str]]]:
|
| 563 |
+
contracts = load_quant_contracts()
|
| 564 |
+
return {
|
| 565 |
+
item.agent: contracts.for_agent(item.agent).permissions.model_dump(mode="json")
|
| 566 |
+
for item in plan.active_agents
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
async def _report_blocked(self, execution: DependencyExecutionResult) -> None:
|
| 570 |
+
for record in execution.records:
|
| 571 |
+
if record.state == AgentExecutionState.BLOCKED:
|
| 572 |
+
await self._notify(
|
| 573 |
+
record.agent,
|
| 574 |
+
record.state,
|
| 575 |
+
", ".join(record.blocked_by),
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
async def _notify(self, agent: AgentName, state: AgentExecutionState, detail: Any) -> None:
|
| 579 |
+
if self._progress is not None:
|
| 580 |
+
await self._progress(agent, state, str(detail or ""))
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def _agent_output(loaded, producer: str) -> BaseModel | None:
|
| 584 |
+
for item in loaded:
|
| 585 |
+
if item.reference.producer != producer:
|
| 586 |
+
continue
|
| 587 |
+
if producer == "DataFetcher" and isinstance(item.value, MarketDataArtifact):
|
| 588 |
+
continue
|
| 589 |
+
if producer != "Runtime" and isinstance(item.value, quant_artifact_schema(producer)):
|
| 590 |
+
return item.value
|
| 591 |
+
return None
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def _runtime_collection(loaded) -> AssetAnalysisCollection | None:
|
| 595 |
+
return next(
|
| 596 |
+
(item.value for item in loaded if isinstance(item.value, AssetAnalysisCollection)),
|
| 597 |
+
None,
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def _token_log(state: dict[str, Any]) -> list[dict[str, Any]]:
|
| 602 |
+
quant = state.get("quant_state")
|
| 603 |
+
if not isinstance(quant, dict):
|
| 604 |
+
quant = {}
|
| 605 |
+
state["quant_state"] = quant
|
| 606 |
+
return quant.setdefault("token_log", [])
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def _unique_additional_artifacts(
|
| 610 |
+
execution: DependencyExecutionResult,
|
| 611 |
+
references,
|
| 612 |
+
) -> list:
|
| 613 |
+
completed = {
|
| 614 |
+
record.artifact_ref.path
|
| 615 |
+
for record in execution.records
|
| 616 |
+
if record.artifact_ref is not None
|
| 617 |
+
}
|
| 618 |
+
seen = set(completed)
|
| 619 |
+
additional = []
|
| 620 |
+
for reference in references:
|
| 621 |
+
if reference.path in seen:
|
| 622 |
+
continue
|
| 623 |
+
seen.add(reference.path)
|
| 624 |
+
additional.append(reference)
|
| 625 |
+
return additional
|
src/polyhedra/services/strategist_performance.py
CHANGED
|
@@ -11,7 +11,7 @@ from dataclasses import dataclass, field
|
|
| 11 |
from datetime import datetime, timezone
|
| 12 |
from typing import Any
|
| 13 |
|
| 14 |
-
from polyhedra.services.file_writer import FileWriter
|
| 15 |
|
| 16 |
|
| 17 |
DEFAULT_COMMITTEE_WEIGHTS: dict[str, float] = {
|
|
@@ -33,7 +33,7 @@ class StrategistPerformanceTracker:
|
|
| 33 |
weight_updates: list[dict[str, Any]] = field(default_factory=list)
|
| 34 |
|
| 35 |
@classmethod
|
| 36 |
-
def load(cls, files: FileWriter) -> "StrategistPerformanceTracker":
|
| 37 |
raw = files.read(_ARTIFACT_PATH)
|
| 38 |
if not raw:
|
| 39 |
return cls()
|
|
@@ -58,7 +58,7 @@ class StrategistPerformanceTracker:
|
|
| 58 |
|
| 59 |
def record_votes(
|
| 60 |
self,
|
| 61 |
-
files: FileWriter,
|
| 62 |
votes: list[dict[str, Any]],
|
| 63 |
*,
|
| 64 |
run_mode: str,
|
|
@@ -71,7 +71,11 @@ class StrategistPerformanceTracker:
|
|
| 71 |
self.vote_history.extend(normalized_votes)
|
| 72 |
payload = self.to_dict()
|
| 73 |
payload["latest_aggregation"] = aggregation
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
return {
|
| 76 |
"weights": self.current_weights(),
|
| 77 |
"votes": normalized_votes,
|
|
|
|
| 11 |
from datetime import datetime, timezone
|
| 12 |
from typing import Any
|
| 13 |
|
| 14 |
+
from polyhedra.services.file_writer import FileWriter, ScopedFileWriter
|
| 15 |
|
| 16 |
|
| 17 |
DEFAULT_COMMITTEE_WEIGHTS: dict[str, float] = {
|
|
|
|
| 33 |
weight_updates: list[dict[str, Any]] = field(default_factory=list)
|
| 34 |
|
| 35 |
@classmethod
|
| 36 |
+
def load(cls, files: FileWriter | ScopedFileWriter) -> "StrategistPerformanceTracker":
|
| 37 |
raw = files.read(_ARTIFACT_PATH)
|
| 38 |
if not raw:
|
| 39 |
return cls()
|
|
|
|
| 58 |
|
| 59 |
def record_votes(
|
| 60 |
self,
|
| 61 |
+
files: FileWriter | ScopedFileWriter,
|
| 62 |
votes: list[dict[str, Any]],
|
| 63 |
*,
|
| 64 |
run_mode: str,
|
|
|
|
| 71 |
self.vote_history.extend(normalized_votes)
|
| 72 |
payload = self.to_dict()
|
| 73 |
payload["latest_aggregation"] = aggregation
|
| 74 |
+
serialized = json.dumps(payload, indent=2)
|
| 75 |
+
if isinstance(files, ScopedFileWriter):
|
| 76 |
+
files.replace_atomic(_ARTIFACT_PATH, serialized)
|
| 77 |
+
else:
|
| 78 |
+
files.write_atomic(_ARTIFACT_PATH, serialized)
|
| 79 |
return {
|
| 80 |
"weights": self.current_weights(),
|
| 81 |
"votes": normalized_votes,
|
src/polyhedra/web/static/index.html
CHANGED
|
@@ -26,16 +26,13 @@
|
|
| 26 |
min-height: 100vh;
|
| 27 |
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
| 28 |
color: var(--ink);
|
| 29 |
-
background:
|
| 30 |
-
linear-gradient(135deg, rgba(15, 123, 108, 0.12), rgba(186, 74, 0, 0.08)),
|
| 31 |
-
var(--page);
|
| 32 |
}
|
| 33 |
|
| 34 |
header {
|
| 35 |
padding: 24px clamp(16px, 3vw, 36px) 14px;
|
| 36 |
border-bottom: 1px solid rgba(23, 32, 42, 0.08);
|
| 37 |
-
background: rgba(255, 255, 255, 0.
|
| 38 |
-
backdrop-filter: blur(12px);
|
| 39 |
position: sticky;
|
| 40 |
top: 0;
|
| 41 |
z-index: 2;
|
|
@@ -123,6 +120,135 @@
|
|
| 123 |
gap: 18px;
|
| 124 |
}
|
| 125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
.section {
|
| 127 |
padding: 16px;
|
| 128 |
}
|
|
@@ -203,7 +329,8 @@
|
|
| 203 |
|
| 204 |
.step.completed { border-left-color: var(--good); }
|
| 205 |
.step.running { border-left-color: var(--accent-2); }
|
| 206 |
-
.step.blocked { border-left-color: var(--
|
|
|
|
| 207 |
.step .label { font-weight: 700; font-size: 13px; }
|
| 208 |
.step .state { color: var(--muted); font-size: 12px; margin-top: 4px; }
|
| 209 |
|
|
@@ -321,14 +448,18 @@
|
|
| 321 |
@media (max-width: 880px) {
|
| 322 |
main { grid-template-columns: 1fr; }
|
| 323 |
.runbar { grid-template-columns: 1fr; }
|
| 324 |
-
button, .download { width: 100%; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
}
|
| 326 |
</style>
|
| 327 |
</head>
|
| 328 |
<body>
|
| 329 |
<header>
|
| 330 |
<h1>Polyhedra YOLO Console</h1>
|
| 331 |
-
<p class="subhead">
|
| 332 |
<div id="systemStatus" class="system-status">Checking runtime...</div>
|
| 333 |
</header>
|
| 334 |
|
|
@@ -339,6 +470,13 @@
|
|
| 339 |
<button id="runButton" type="button">Run YOLO</button>
|
| 340 |
</div>
|
| 341 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
<div class="panel section">
|
| 343 |
<h2>Run Status</h2>
|
| 344 |
<p id="sessionMeta" class="meta">No active browser run yet.</p>
|
|
@@ -377,6 +515,57 @@
|
|
| 377 |
<p id="committeeMeta" class="meta">Committee votes will appear after QuantStrategist runs.</p>
|
| 378 |
<div id="committeeVotes" class="committee-grid"></div>
|
| 379 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
</section>
|
| 381 |
|
| 382 |
<aside class="panel section">
|
|
@@ -408,9 +597,24 @@
|
|
| 408 |
const runReplayList = document.getElementById("runReplayList");
|
| 409 |
const downloadLink = document.getElementById("downloadLink");
|
| 410 |
const systemStatus = document.getElementById("systemStatus");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
|
| 412 |
let activeSessionId = "";
|
|
|
|
|
|
|
| 413 |
let pollTimer = 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
|
| 415 |
function setBusy(isBusy) {
|
| 416 |
runButton.disabled = isBusy;
|
|
@@ -419,9 +623,12 @@
|
|
| 419 |
|
| 420 |
function renderStatus(payload) {
|
| 421 |
if (!payload) return;
|
|
|
|
| 422 |
activeSessionId = payload.session_id;
|
|
|
|
|
|
|
| 423 |
const runMode = payload.run_mode_label || "YOLO";
|
| 424 |
-
sessionMeta.textContent = `${payload.goal} | session ${payload.session_id} | ${
|
| 425 |
currentAgent.textContent = payload.current_agent?.label
|
| 426 |
? `Current agent: ${payload.current_agent.label}`
|
| 427 |
: "Current agent: idle";
|
|
@@ -444,11 +651,11 @@
|
|
| 444 |
runAgainButton.style.display = "inline-flex";
|
| 445 |
|
| 446 |
const path = payload.path || [];
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
const state = step.status === "completed" ? "completed" : step.status === "blocked" ? "blocked" : step.status === "running" ? "running" : index === firstPending && payload.status === "running" ? "running" : "pending";
|
| 450 |
const label = escapeHtml(step.label || step.role);
|
| 451 |
-
|
|
|
|
| 452 |
}).join("");
|
| 453 |
|
| 454 |
if ((payload.status === "blocked" || payload.status === "failed") && payload.error) {
|
|
@@ -458,6 +665,8 @@
|
|
| 458 |
}
|
| 459 |
optionsOutput.textContent = payload.options_context?.summary || "Options context has not been generated yet.";
|
| 460 |
renderCommittee(payload.committee || {});
|
|
|
|
|
|
|
| 461 |
setBusy(payload.status === "pending" || payload.status === "running");
|
| 462 |
|
| 463 |
if (["completed", "blocked", "failed"].includes(payload.status)) {
|
|
@@ -466,6 +675,154 @@
|
|
| 466 |
}
|
| 467 |
}
|
| 468 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
function renderProposalState(proposalState) {
|
| 470 |
if (!proposalState.status) {
|
| 471 |
proposalStateEl.style.display = "none";
|
|
@@ -526,6 +883,8 @@
|
|
| 526 |
async function startRun() {
|
| 527 |
const tickers = tickerInput.value.trim();
|
| 528 |
if (!tickers) return;
|
|
|
|
|
|
|
| 529 |
setBusy(true);
|
| 530 |
const response = await fetch("/api/yolo", {
|
| 531 |
method: "POST",
|
|
@@ -549,6 +908,8 @@
|
|
| 549 |
|
| 550 |
async function startSessionRun() {
|
| 551 |
if (!activeSessionId) return;
|
|
|
|
|
|
|
| 552 |
setBusy(true);
|
| 553 |
const response = await fetch(`/api/sessions/${activeSessionId}/yolo`, {
|
| 554 |
method: "POST",
|
|
@@ -570,29 +931,50 @@
|
|
| 570 |
await loadRuns(payload.session_id);
|
| 571 |
}
|
| 572 |
|
| 573 |
-
async function loadSession(sessionId, includeRuns = true) {
|
| 574 |
-
const
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
}
|
| 579 |
|
| 580 |
async function loadRun(sessionId, runId) {
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 586 |
}
|
| 587 |
|
| 588 |
function startPolling(sessionId) {
|
| 589 |
window.clearInterval(pollTimer);
|
| 590 |
-
pollTimer = window.setInterval(() =>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 591 |
}
|
| 592 |
|
| 593 |
async function refreshActive() {
|
| 594 |
if (activeSessionId) {
|
| 595 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 596 |
}
|
| 597 |
await loadSessions();
|
| 598 |
}
|
|
@@ -622,6 +1004,10 @@
|
|
| 622 |
}).join("") || `<p class="meta">No prior YOLO run snapshots found.</p>`;
|
| 623 |
runReplayList.querySelectorAll(".run-row").forEach((row) => {
|
| 624 |
row.addEventListener("click", () => loadRun(sessionId, row.dataset.run));
|
|
|
|
|
|
|
|
|
|
|
|
|
| 625 |
});
|
| 626 |
}
|
| 627 |
|
|
@@ -636,7 +1022,15 @@
|
|
| 636 |
return `<div class="session-row" data-session="${id}"><strong>${goal}</strong><span>${id} | ${created}</span></div>`;
|
| 637 |
}).join("") || `<p class="meta">No saved sessions found.</p>`;
|
| 638 |
sessionsEl.querySelectorAll(".session-row").forEach((row) => {
|
| 639 |
-
row.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 640 |
});
|
| 641 |
}
|
| 642 |
|
|
@@ -668,6 +1062,24 @@
|
|
| 668 |
tickerInput.addEventListener("keydown", (event) => {
|
| 669 |
if (event.key === "Enter") startRun();
|
| 670 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 671 |
loadHealth();
|
| 672 |
loadSessions();
|
| 673 |
</script>
|
|
|
|
| 26 |
min-height: 100vh;
|
| 27 |
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
| 28 |
color: var(--ink);
|
| 29 |
+
background: var(--page);
|
|
|
|
|
|
|
| 30 |
}
|
| 31 |
|
| 32 |
header {
|
| 33 |
padding: 24px clamp(16px, 3vw, 36px) 14px;
|
| 34 |
border-bottom: 1px solid rgba(23, 32, 42, 0.08);
|
| 35 |
+
background: rgba(255, 255, 255, 0.96);
|
|
|
|
| 36 |
position: sticky;
|
| 37 |
top: 0;
|
| 38 |
z-index: 2;
|
|
|
|
| 120 |
gap: 18px;
|
| 121 |
}
|
| 122 |
|
| 123 |
+
.view { display: none; }
|
| 124 |
+
.view.active { display: grid; gap: 18px; }
|
| 125 |
+
|
| 126 |
+
.tabs {
|
| 127 |
+
display: flex;
|
| 128 |
+
align-items: center;
|
| 129 |
+
gap: 4px;
|
| 130 |
+
padding: 5px;
|
| 131 |
+
box-shadow: none;
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
.tab-button, .mode-button {
|
| 135 |
+
min-height: 36px;
|
| 136 |
+
padding: 8px 12px;
|
| 137 |
+
color: var(--muted);
|
| 138 |
+
background: transparent;
|
| 139 |
+
border: 1px solid transparent;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
.tab-button[aria-selected="true"], .mode-button[aria-pressed="true"] {
|
| 143 |
+
color: var(--ink);
|
| 144 |
+
background: #eef5f3;
|
| 145 |
+
border-color: #bfd8d2;
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
.section-head {
|
| 149 |
+
display: flex;
|
| 150 |
+
align-items: flex-start;
|
| 151 |
+
justify-content: space-between;
|
| 152 |
+
gap: 12px;
|
| 153 |
+
flex-wrap: wrap;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
.inline-control {
|
| 157 |
+
display: inline-flex;
|
| 158 |
+
align-items: center;
|
| 159 |
+
gap: 8px;
|
| 160 |
+
color: var(--muted);
|
| 161 |
+
font-size: 13px;
|
| 162 |
+
font-weight: 700;
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
.inline-control input { width: auto; }
|
| 166 |
+
|
| 167 |
+
.mode-switch {
|
| 168 |
+
display: inline-flex;
|
| 169 |
+
gap: 3px;
|
| 170 |
+
padding: 3px;
|
| 171 |
+
border: 1px solid var(--line);
|
| 172 |
+
border-radius: 6px;
|
| 173 |
+
background: #f7f9fa;
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
.table-wrap {
|
| 177 |
+
margin-top: 12px;
|
| 178 |
+
overflow: auto;
|
| 179 |
+
border: 1px solid var(--line);
|
| 180 |
+
border-radius: 7px;
|
| 181 |
+
max-width: 100%;
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
table {
|
| 185 |
+
width: 100%;
|
| 186 |
+
border-collapse: collapse;
|
| 187 |
+
min-width: 760px;
|
| 188 |
+
font-size: 13px;
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
th, td {
|
| 192 |
+
padding: 10px;
|
| 193 |
+
border-bottom: 1px solid var(--line);
|
| 194 |
+
text-align: left;
|
| 195 |
+
vertical-align: top;
|
| 196 |
+
overflow-wrap: anywhere;
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
th {
|
| 200 |
+
position: sticky;
|
| 201 |
+
top: 0;
|
| 202 |
+
z-index: 1;
|
| 203 |
+
color: var(--muted);
|
| 204 |
+
background: #f7f9fa;
|
| 205 |
+
font-size: 12px;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
tbody tr:last-child td { border-bottom: 0; }
|
| 209 |
+
tbody tr.selectable { cursor: pointer; }
|
| 210 |
+
tbody tr.selectable:hover, tbody tr.selected { background: #eef8f5; }
|
| 211 |
+
tbody tr:focus { outline: 2px solid var(--accent); outline-offset: -2px; }
|
| 212 |
+
|
| 213 |
+
.state-text { font-weight: 700; }
|
| 214 |
+
.state-text.completed { color: var(--good); }
|
| 215 |
+
.state-text.running { color: var(--accent-2); }
|
| 216 |
+
.state-text.failed, .state-text.blocked { color: var(--bad); }
|
| 217 |
+
.state-text.waiting, .state-text.inactive { color: var(--muted); }
|
| 218 |
+
|
| 219 |
+
.detail-grid {
|
| 220 |
+
display: grid;
|
| 221 |
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
| 222 |
+
gap: 12px;
|
| 223 |
+
margin-top: 12px;
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
.detail-block {
|
| 227 |
+
min-width: 0;
|
| 228 |
+
border-top: 1px solid var(--line);
|
| 229 |
+
padding-top: 10px;
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
.detail-block h3 { margin: 0 0 7px; font-size: 13px; }
|
| 233 |
+
.detail-block p, .detail-block li {
|
| 234 |
+
color: var(--muted);
|
| 235 |
+
font-size: 12px;
|
| 236 |
+
line-height: 1.45;
|
| 237 |
+
overflow-wrap: anywhere;
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
.detail-block ul { margin: 0; padding-left: 18px; }
|
| 241 |
+
.detail-block .none { color: #87939e; }
|
| 242 |
+
|
| 243 |
+
.summary-line {
|
| 244 |
+
display: flex;
|
| 245 |
+
gap: 12px;
|
| 246 |
+
flex-wrap: wrap;
|
| 247 |
+
margin-top: 10px;
|
| 248 |
+
color: var(--muted);
|
| 249 |
+
font-size: 13px;
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
.section {
|
| 253 |
padding: 16px;
|
| 254 |
}
|
|
|
|
| 329 |
|
| 330 |
.step.completed { border-left-color: var(--good); }
|
| 331 |
.step.running { border-left-color: var(--accent-2); }
|
| 332 |
+
.step.failed, .step.blocked { border-left-color: var(--bad); background: #fff8f7; }
|
| 333 |
+
.step.waiting { border-left-color: #a8b2bc; }
|
| 334 |
.step .label { font-weight: 700; font-size: 13px; }
|
| 335 |
.step .state { color: var(--muted); font-size: 12px; margin-top: 4px; }
|
| 336 |
|
|
|
|
| 448 |
@media (max-width: 880px) {
|
| 449 |
main { grid-template-columns: 1fr; }
|
| 450 |
.runbar { grid-template-columns: 1fr; }
|
| 451 |
+
.runbar button, .actions button, .actions .download { width: 100%; }
|
| 452 |
+
.tabs { overflow-x: auto; }
|
| 453 |
+
.tab-button { flex: 0 0 auto; }
|
| 454 |
+
.detail-grid { grid-template-columns: 1fr; }
|
| 455 |
+
header { position: static; }
|
| 456 |
}
|
| 457 |
</style>
|
| 458 |
</head>
|
| 459 |
<body>
|
| 460 |
<header>
|
| 461 |
<h1>Polyhedra YOLO Console</h1>
|
| 462 |
+
<p class="subhead">Quant analysis workspace. Paper trading simulation only.</p>
|
| 463 |
<div id="systemStatus" class="system-status">Checking runtime...</div>
|
| 464 |
</header>
|
| 465 |
|
|
|
|
| 470 |
<button id="runButton" type="button">Run YOLO</button>
|
| 471 |
</div>
|
| 472 |
|
| 473 |
+
<nav class="panel tabs" role="tablist" aria-label="Run views">
|
| 474 |
+
<button class="tab-button" type="button" role="tab" data-view="run" aria-selected="true">Run</button>
|
| 475 |
+
<button class="tab-button" type="button" role="tab" data-view="routing" aria-selected="false">Routing Table</button>
|
| 476 |
+
<button class="tab-button" type="button" role="tab" data-view="permissions" aria-selected="false">Permissions</button>
|
| 477 |
+
</nav>
|
| 478 |
+
|
| 479 |
+
<div id="viewRun" class="view active" role="tabpanel">
|
| 480 |
<div class="panel section">
|
| 481 |
<h2>Run Status</h2>
|
| 482 |
<p id="sessionMeta" class="meta">No active browser run yet.</p>
|
|
|
|
| 515 |
<p id="committeeMeta" class="meta">Committee votes will appear after QuantStrategist runs.</p>
|
| 516 |
<div id="committeeVotes" class="committee-grid"></div>
|
| 517 |
</div>
|
| 518 |
+
</div>
|
| 519 |
+
|
| 520 |
+
<div id="viewRouting" class="view" role="tabpanel">
|
| 521 |
+
<div class="panel section">
|
| 522 |
+
<div class="section-head">
|
| 523 |
+
<div>
|
| 524 |
+
<h2>Routing Table</h2>
|
| 525 |
+
<p id="routingMeta" class="meta">No run selected.</p>
|
| 526 |
+
</div>
|
| 527 |
+
<label class="inline-control">
|
| 528 |
+
<input id="fullRegistryToggle" type="checkbox">
|
| 529 |
+
Full registry
|
| 530 |
+
</label>
|
| 531 |
+
</div>
|
| 532 |
+
<div class="table-wrap" tabindex="0" aria-label="Agent routing table">
|
| 533 |
+
<table>
|
| 534 |
+
<thead><tr><th>Agent</th><th>Scope</th><th>Effective tickers</th><th>Required dependencies</th><th>Execution</th><th>Result</th></tr></thead>
|
| 535 |
+
<tbody id="routingRows"><tr><td colspan="6">No routing snapshot available.</td></tr></tbody>
|
| 536 |
+
</table>
|
| 537 |
+
</div>
|
| 538 |
+
</div>
|
| 539 |
+
<div class="panel section">
|
| 540 |
+
<h2 id="agentDetailTitle">Agent Details</h2>
|
| 541 |
+
<div id="agentDetail" class="detail-grid"><p class="meta">Select an agent from the routing table.</p></div>
|
| 542 |
+
</div>
|
| 543 |
+
</div>
|
| 544 |
+
|
| 545 |
+
<div id="viewPermissions" class="view" role="tabpanel">
|
| 546 |
+
<div class="panel section">
|
| 547 |
+
<div class="section-head">
|
| 548 |
+
<div>
|
| 549 |
+
<h2>Permissions</h2>
|
| 550 |
+
<p id="permissionsMeta" class="meta">No permission snapshot available.</p>
|
| 551 |
+
</div>
|
| 552 |
+
<div class="mode-switch" role="group" aria-label="Permission path mode">
|
| 553 |
+
<button class="mode-button" type="button" data-permission-mode="templates" aria-pressed="false">Templates</button>
|
| 554 |
+
<button class="mode-button" type="button" data-permission-mode="resolved" aria-pressed="true">Resolved</button>
|
| 555 |
+
</div>
|
| 556 |
+
</div>
|
| 557 |
+
<div class="table-wrap" tabindex="0" aria-label="Agent permissions table">
|
| 558 |
+
<table>
|
| 559 |
+
<thead><tr><th>Agent</th><th>State</th><th>Read</th><th>Create</th><th>Edit</th><th>List</th><th>Baseline read</th></tr></thead>
|
| 560 |
+
<tbody id="permissionRows"><tr><td colspan="7">No permission snapshot available.</td></tr></tbody>
|
| 561 |
+
</table>
|
| 562 |
+
</div>
|
| 563 |
+
</div>
|
| 564 |
+
<div class="panel section">
|
| 565 |
+
<h2 id="permissionDetailTitle">Permission Details</h2>
|
| 566 |
+
<div id="permissionDetail" class="detail-grid"><p class="meta">Select an agent from the permissions table.</p></div>
|
| 567 |
+
</div>
|
| 568 |
+
</div>
|
| 569 |
</section>
|
| 570 |
|
| 571 |
<aside class="panel section">
|
|
|
|
| 597 |
const runReplayList = document.getElementById("runReplayList");
|
| 598 |
const downloadLink = document.getElementById("downloadLink");
|
| 599 |
const systemStatus = document.getElementById("systemStatus");
|
| 600 |
+
const routingMeta = document.getElementById("routingMeta");
|
| 601 |
+
const routingRows = document.getElementById("routingRows");
|
| 602 |
+
const agentDetailTitle = document.getElementById("agentDetailTitle");
|
| 603 |
+
const agentDetail = document.getElementById("agentDetail");
|
| 604 |
+
const permissionRows = document.getElementById("permissionRows");
|
| 605 |
+
const permissionsMeta = document.getElementById("permissionsMeta");
|
| 606 |
+
const permissionDetailTitle = document.getElementById("permissionDetailTitle");
|
| 607 |
+
const permissionDetail = document.getElementById("permissionDetail");
|
| 608 |
+
const fullRegistryToggle = document.getElementById("fullRegistryToggle");
|
| 609 |
|
| 610 |
let activeSessionId = "";
|
| 611 |
+
let activeRunId = "";
|
| 612 |
+
let replaySelected = false;
|
| 613 |
let pollTimer = 0;
|
| 614 |
+
let currentView = "run";
|
| 615 |
+
let selectedAgent = "";
|
| 616 |
+
let permissionMode = "resolved";
|
| 617 |
+
let latestPayload = null;
|
| 618 |
|
| 619 |
function setBusy(isBusy) {
|
| 620 |
runButton.disabled = isBusy;
|
|
|
|
| 623 |
|
| 624 |
function renderStatus(payload) {
|
| 625 |
if (!payload) return;
|
| 626 |
+
latestPayload = payload;
|
| 627 |
activeSessionId = payload.session_id;
|
| 628 |
+
activeRunId = payload.run_id || "";
|
| 629 |
+
replaySelected = Boolean(payload.replay);
|
| 630 |
const runMode = payload.run_mode_label || "YOLO";
|
| 631 |
+
sessionMeta.textContent = `${payload.goal} | session ${payload.session_id} | run ${activeRunId || "pending"} | ${runMode}`;
|
| 632 |
currentAgent.textContent = payload.current_agent?.label
|
| 633 |
? `Current agent: ${payload.current_agent.label}`
|
| 634 |
: "Current agent: idle";
|
|
|
|
| 651 |
runAgainButton.style.display = "inline-flex";
|
| 652 |
|
| 653 |
const path = payload.path || [];
|
| 654 |
+
progress.innerHTML = path.map((step) => {
|
| 655 |
+
const state = step.status || "waiting";
|
|
|
|
| 656 |
const label = escapeHtml(step.label || step.role);
|
| 657 |
+
const result = step.result_status ? ` / ${escapeHtml(step.result_status)}` : "";
|
| 658 |
+
return `<div class="step ${escapeHtml(state)}"><div class="label">${label}</div><div class="state">${escapeHtml(state)}${result}</div></div>`;
|
| 659 |
}).join("");
|
| 660 |
|
| 661 |
if ((payload.status === "blocked" || payload.status === "failed") && payload.error) {
|
|
|
|
| 665 |
}
|
| 666 |
optionsOutput.textContent = payload.options_context?.summary || "Options context has not been generated yet.";
|
| 667 |
renderCommittee(payload.committee || {});
|
| 668 |
+
renderRouting(payload);
|
| 669 |
+
renderPermissions(payload);
|
| 670 |
setBusy(payload.status === "pending" || payload.status === "running");
|
| 671 |
|
| 672 |
if (["completed", "blocked", "failed"].includes(payload.status)) {
|
|
|
|
| 675 |
}
|
| 676 |
}
|
| 677 |
|
| 678 |
+
function setView(view) {
|
| 679 |
+
currentView = view;
|
| 680 |
+
document.querySelectorAll(".tab-button").forEach((button) => {
|
| 681 |
+
button.setAttribute("aria-selected", String(button.dataset.view === view));
|
| 682 |
+
});
|
| 683 |
+
document.querySelectorAll(".view").forEach((panel) => panel.classList.remove("active"));
|
| 684 |
+
const target = document.getElementById(`view${view[0].toUpperCase()}${view.slice(1)}`);
|
| 685 |
+
if (target) target.classList.add("active");
|
| 686 |
+
}
|
| 687 |
+
|
| 688 |
+
function renderRouting(payload) {
|
| 689 |
+
const active = payload.routing?.active || [];
|
| 690 |
+
const inactive = payload.routing?.inactive || [];
|
| 691 |
+
const statusByAgent = Object.fromEntries((payload.path || []).map((row) => [row.agent, row]));
|
| 692 |
+
const rows = active.map((entry) => ({
|
| 693 |
+
...entry,
|
| 694 |
+
active: true,
|
| 695 |
+
execution: statusByAgent[entry.agent] || {}
|
| 696 |
+
}));
|
| 697 |
+
if (fullRegistryToggle.checked) {
|
| 698 |
+
rows.push(...inactive.map((entry) => ({ ...entry, active: false, execution: {} })));
|
| 699 |
+
}
|
| 700 |
+
routingMeta.textContent = active.length
|
| 701 |
+
? `${active.length} active agent(s) | ${inactive.length} inactive | frozen run ${payload.run_id || "pending"}`
|
| 702 |
+
: "Routing snapshot unavailable for this recorded version.";
|
| 703 |
+
if (!rows.length) {
|
| 704 |
+
routingRows.innerHTML = `<tr><td colspan="6">Routing snapshot unavailable for this recorded version.</td></tr>`;
|
| 705 |
+
agentDetail.innerHTML = `<p class="meta">No agent details are recorded.</p>`;
|
| 706 |
+
return;
|
| 707 |
+
}
|
| 708 |
+
if (!selectedAgent || !rows.some((row) => row.agent === selectedAgent)) {
|
| 709 |
+
selectedAgent = rows[0].agent;
|
| 710 |
+
}
|
| 711 |
+
routingRows.innerHTML = rows.map((row) => {
|
| 712 |
+
const execution = row.execution || {};
|
| 713 |
+
const state = row.active ? (execution.status || "waiting") : "inactive";
|
| 714 |
+
const dependencies = row.required_dependencies || [];
|
| 715 |
+
const dependencyNames = dependencies.map((item) => item.agent).join(", ") || "None";
|
| 716 |
+
const effective = row.effective_ticker_scope?.join(", ") || "None";
|
| 717 |
+
const result = execution.result_status || (row.active ? "Pending" : row.reason || "Inactive");
|
| 718 |
+
return `<tr class="selectable ${row.agent === selectedAgent ? "selected" : ""}" tabindex="0" data-agent="${escapeHtml(row.agent)}">
|
| 719 |
+
<td><strong>${escapeHtml(row.agent)}</strong></td>
|
| 720 |
+
<td>${escapeHtml(row.declared_scope || "")}</td>
|
| 721 |
+
<td>${escapeHtml(effective)}</td>
|
| 722 |
+
<td>${escapeHtml(dependencyNames)}</td>
|
| 723 |
+
<td><span class="state-text ${escapeHtml(state)}">${escapeHtml(state)}</span></td>
|
| 724 |
+
<td>${escapeHtml(result)}</td>
|
| 725 |
+
</tr>`;
|
| 726 |
+
}).join("");
|
| 727 |
+
bindAgentRows(routingRows);
|
| 728 |
+
renderAgentDetail(payload, rows.find((row) => row.agent === selectedAgent));
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
function renderAgentDetail(payload, route) {
|
| 732 |
+
if (!route) return;
|
| 733 |
+
const execution = route.execution || {};
|
| 734 |
+
agentDetailTitle.textContent = route.agent;
|
| 735 |
+
const dependencyStates = (route.required_dependencies || []).map((dependency) => {
|
| 736 |
+
const state = (payload.path || []).find((row) => row.agent === dependency.agent)?.status || "inactive";
|
| 737 |
+
return `${dependency.agent}: ${state}`;
|
| 738 |
+
});
|
| 739 |
+
const output = execution.artifact_ref ? [formatRef(execution.artifact_ref)] : [];
|
| 740 |
+
agentDetail.innerHTML = [
|
| 741 |
+
detailBlock("Execution", [
|
| 742 |
+
`State: ${execution.status || (route.active ? "waiting" : "inactive")}`,
|
| 743 |
+
`Result: ${execution.result_status || "None"}`,
|
| 744 |
+
`Started: ${execution.started_at || "None"}`,
|
| 745 |
+
`Finished: ${execution.finished_at || "None"}`,
|
| 746 |
+
execution.error ? `Error: ${execution.error}` : "",
|
| 747 |
+
execution.blocked_by?.length ? `Blocked by: ${execution.blocked_by.join(", ")}` : ""
|
| 748 |
+
]),
|
| 749 |
+
detailBlock("Dependencies", dependencyStates),
|
| 750 |
+
detailBlock("Current inputs", (execution.input_refs || []).map(formatRef)),
|
| 751 |
+
detailBlock("Baseline inputs (read-only)", (execution.baseline_refs || []).map(formatRef)),
|
| 752 |
+
detailBlock("Input snapshot", execution.input_snapshot ? [`${execution.input_snapshot} (read-only)`] : []),
|
| 753 |
+
detailBlock("Published output (read-only)", output)
|
| 754 |
+
].join("");
|
| 755 |
+
}
|
| 756 |
+
|
| 757 |
+
function renderPermissions(payload) {
|
| 758 |
+
const permissions = payload.permissions || [];
|
| 759 |
+
permissionsMeta.textContent = permissions.length
|
| 760 |
+
? `${permissions.filter((item) => item.active).length} active permission binding(s) | ${permissionMode}`
|
| 761 |
+
: "Permission snapshot unavailable for this recorded version.";
|
| 762 |
+
if (!permissions.length) {
|
| 763 |
+
permissionRows.innerHTML = `<tr><td colspan="7">Permission snapshot unavailable for this recorded version.</td></tr>`;
|
| 764 |
+
permissionDetail.innerHTML = `<p class="meta">No permission details are recorded.</p>`;
|
| 765 |
+
return;
|
| 766 |
+
}
|
| 767 |
+
const visible = fullRegistryToggle.checked ? permissions : permissions.filter((item) => item.active);
|
| 768 |
+
if (!selectedAgent || !visible.some((item) => item.agent === selectedAgent)) {
|
| 769 |
+
selectedAgent = visible[0]?.agent || "";
|
| 770 |
+
}
|
| 771 |
+
permissionRows.innerHTML = visible.map((item) => {
|
| 772 |
+
const paths = item[permissionMode] || {};
|
| 773 |
+
const count = (name) => (paths[name] || []).length || "None";
|
| 774 |
+
return `<tr class="selectable ${item.agent === selectedAgent ? "selected" : ""}" tabindex="0" data-agent="${escapeHtml(item.agent)}">
|
| 775 |
+
<td><strong>${escapeHtml(item.agent)}</strong></td>
|
| 776 |
+
<td>${item.active ? "Active" : escapeHtml(item.inactive_reason || "Inactive")}</td>
|
| 777 |
+
<td>${count("read")}</td><td>${count("create")}</td><td>${count("edit")}</td><td>${count("list")}</td><td>${count("baseline_read")}</td>
|
| 778 |
+
</tr>`;
|
| 779 |
+
}).join("");
|
| 780 |
+
bindAgentRows(permissionRows);
|
| 781 |
+
renderPermissionDetail(visible.find((item) => item.agent === selectedAgent));
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
function renderPermissionDetail(item) {
|
| 785 |
+
if (!item) return;
|
| 786 |
+
permissionDetailTitle.textContent = item.agent;
|
| 787 |
+
const paths = item[permissionMode] || {};
|
| 788 |
+
permissionDetail.innerHTML = ["read", "create", "edit", "list", "baseline_read", "baseline_list"]
|
| 789 |
+
.map((operation) => detailBlock(operation.replaceAll("_", " "), (paths[operation] || []).map((path) => {
|
| 790 |
+
const readonly = operation.startsWith("baseline_") || Boolean(item.published_output && item.published_output.path === path);
|
| 791 |
+
return `${path}${readonly ? " (read-only)" : ""}`;
|
| 792 |
+
}))).join("") + detailBlock("Actual publication", item.published_output ? [formatRef(item.published_output) + " (read-only)"] : []);
|
| 793 |
+
}
|
| 794 |
+
|
| 795 |
+
function bindAgentRows(container) {
|
| 796 |
+
container.querySelectorAll("tr[data-agent]").forEach((row) => {
|
| 797 |
+
const select = () => {
|
| 798 |
+
selectedAgent = row.dataset.agent;
|
| 799 |
+
if (latestPayload) {
|
| 800 |
+
renderRouting(latestPayload);
|
| 801 |
+
renderPermissions(latestPayload);
|
| 802 |
+
}
|
| 803 |
+
};
|
| 804 |
+
row.addEventListener("click", select);
|
| 805 |
+
row.addEventListener("keydown", (event) => {
|
| 806 |
+
if (event.key === "Enter" || event.key === " ") {
|
| 807 |
+
event.preventDefault();
|
| 808 |
+
select();
|
| 809 |
+
}
|
| 810 |
+
});
|
| 811 |
+
});
|
| 812 |
+
}
|
| 813 |
+
|
| 814 |
+
function detailBlock(title, values) {
|
| 815 |
+
const clean = values.filter(Boolean);
|
| 816 |
+
const body = clean.length
|
| 817 |
+
? `<ul>${clean.map((value) => `<li>${escapeHtml(value)}</li>`).join("")}</ul>`
|
| 818 |
+
: `<p class="none">None</p>`;
|
| 819 |
+
return `<div class="detail-block"><h3>${escapeHtml(title)}</h3>${body}</div>`;
|
| 820 |
+
}
|
| 821 |
+
|
| 822 |
+
function formatRef(reference) {
|
| 823 |
+
return `${reference.producer || "Unknown"} | ${reference.path || "unknown path"} | ${reference.schema_version || "unknown schema"}`;
|
| 824 |
+
}
|
| 825 |
+
|
| 826 |
function renderProposalState(proposalState) {
|
| 827 |
if (!proposalState.status) {
|
| 828 |
proposalStateEl.style.display = "none";
|
|
|
|
| 883 |
async function startRun() {
|
| 884 |
const tickers = tickerInput.value.trim();
|
| 885 |
if (!tickers) return;
|
| 886 |
+
replaySelected = false;
|
| 887 |
+
selectedAgent = "";
|
| 888 |
setBusy(true);
|
| 889 |
const response = await fetch("/api/yolo", {
|
| 890 |
method: "POST",
|
|
|
|
| 908 |
|
| 909 |
async function startSessionRun() {
|
| 910 |
if (!activeSessionId) return;
|
| 911 |
+
replaySelected = false;
|
| 912 |
+
selectedAgent = "";
|
| 913 |
setBusy(true);
|
| 914 |
const response = await fetch(`/api/sessions/${activeSessionId}/yolo`, {
|
| 915 |
method: "POST",
|
|
|
|
| 931 |
await loadRuns(payload.session_id);
|
| 932 |
}
|
| 933 |
|
| 934 |
+
async function loadSession(sessionId, includeRuns = true, preserveScroll = false) {
|
| 935 |
+
const scrollTop = window.scrollY;
|
| 936 |
+
try {
|
| 937 |
+
const response = await fetch(`/api/sessions/${sessionId}`);
|
| 938 |
+
if (!response.ok) throw new Error(`Refresh failed (${response.status}).`);
|
| 939 |
+
replaySelected = false;
|
| 940 |
+
renderStatus(await response.json());
|
| 941 |
+
if (includeRuns) await loadRuns(sessionId);
|
| 942 |
+
if (preserveScroll) requestAnimationFrame(() => window.scrollTo(0, scrollTop));
|
| 943 |
+
} catch (error) {
|
| 944 |
+
systemStatus.textContent = error.message || "Run refresh failed.";
|
| 945 |
+
}
|
| 946 |
}
|
| 947 |
|
| 948 |
async function loadRun(sessionId, runId) {
|
| 949 |
+
try {
|
| 950 |
+
const response = await fetch(`/api/sessions/${sessionId}/runs/${runId}`);
|
| 951 |
+
if (!response.ok) throw new Error(`Replay unavailable (${response.status}).`);
|
| 952 |
+
window.clearInterval(pollTimer);
|
| 953 |
+
pollTimer = 0;
|
| 954 |
+
replaySelected = true;
|
| 955 |
+
renderStatus(await response.json());
|
| 956 |
+
} catch (error) {
|
| 957 |
+
replayBanner.textContent = error.message || "Replay unavailable.";
|
| 958 |
+
replayBanner.style.display = "block";
|
| 959 |
+
}
|
| 960 |
}
|
| 961 |
|
| 962 |
function startPolling(sessionId) {
|
| 963 |
window.clearInterval(pollTimer);
|
| 964 |
+
pollTimer = window.setInterval(() => {
|
| 965 |
+
if (!replaySelected && activeSessionId === sessionId) {
|
| 966 |
+
loadSession(sessionId, false, true);
|
| 967 |
+
}
|
| 968 |
+
}, 2000);
|
| 969 |
}
|
| 970 |
|
| 971 |
async function refreshActive() {
|
| 972 |
if (activeSessionId) {
|
| 973 |
+
if (replaySelected && activeRunId) {
|
| 974 |
+
await loadRun(activeSessionId, activeRunId);
|
| 975 |
+
} else {
|
| 976 |
+
await loadSession(activeSessionId);
|
| 977 |
+
}
|
| 978 |
}
|
| 979 |
await loadSessions();
|
| 980 |
}
|
|
|
|
| 1004 |
}).join("") || `<p class="meta">No prior YOLO run snapshots found.</p>`;
|
| 1005 |
runReplayList.querySelectorAll(".run-row").forEach((row) => {
|
| 1006 |
row.addEventListener("click", () => loadRun(sessionId, row.dataset.run));
|
| 1007 |
+
row.setAttribute("tabindex", "0");
|
| 1008 |
+
row.addEventListener("keydown", (event) => {
|
| 1009 |
+
if (event.key === "Enter" || event.key === " ") loadRun(sessionId, row.dataset.run);
|
| 1010 |
+
});
|
| 1011 |
});
|
| 1012 |
}
|
| 1013 |
|
|
|
|
| 1022 |
return `<div class="session-row" data-session="${id}"><strong>${goal}</strong><span>${id} | ${created}</span></div>`;
|
| 1023 |
}).join("") || `<p class="meta">No saved sessions found.</p>`;
|
| 1024 |
sessionsEl.querySelectorAll(".session-row").forEach((row) => {
|
| 1025 |
+
row.setAttribute("tabindex", "0");
|
| 1026 |
+
const select = () => {
|
| 1027 |
+
selectedAgent = "";
|
| 1028 |
+
loadSession(row.dataset.session);
|
| 1029 |
+
};
|
| 1030 |
+
row.addEventListener("click", select);
|
| 1031 |
+
row.addEventListener("keydown", (event) => {
|
| 1032 |
+
if (event.key === "Enter" || event.key === " ") select();
|
| 1033 |
+
});
|
| 1034 |
});
|
| 1035 |
}
|
| 1036 |
|
|
|
|
| 1062 |
tickerInput.addEventListener("keydown", (event) => {
|
| 1063 |
if (event.key === "Enter") startRun();
|
| 1064 |
});
|
| 1065 |
+
document.querySelectorAll(".tab-button").forEach((button) => {
|
| 1066 |
+
button.addEventListener("click", () => setView(button.dataset.view));
|
| 1067 |
+
});
|
| 1068 |
+
document.querySelectorAll(".mode-button").forEach((button) => {
|
| 1069 |
+
button.addEventListener("click", () => {
|
| 1070 |
+
permissionMode = button.dataset.permissionMode;
|
| 1071 |
+
document.querySelectorAll(".mode-button").forEach((item) => {
|
| 1072 |
+
item.setAttribute("aria-pressed", String(item === button));
|
| 1073 |
+
});
|
| 1074 |
+
if (latestPayload) renderPermissions(latestPayload);
|
| 1075 |
+
});
|
| 1076 |
+
});
|
| 1077 |
+
fullRegistryToggle.addEventListener("change", () => {
|
| 1078 |
+
if (latestPayload) {
|
| 1079 |
+
renderRouting(latestPayload);
|
| 1080 |
+
renderPermissions(latestPayload);
|
| 1081 |
+
}
|
| 1082 |
+
});
|
| 1083 |
loadHealth();
|
| 1084 |
loadSessions();
|
| 1085 |
</script>
|
tests/test_quant_runtime.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Integrated V8 runtime coverage through the existing quant agent classes."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import zipfile
|
| 5 |
+
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from types import SimpleNamespace
|
| 9 |
+
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from polyhedra.agents.quant import (
|
| 13 |
+
BacktesterAgent, DataFetcherAgent, EventRouter, MacroContextWatcher,
|
| 14 |
+
MarketEventWatcher, OptionsFlowWatcher, PublisherAgent, QuantResearcherAgent,
|
| 15 |
+
QuantStrategistAgent, RiskAnalystAgent, SentimentAnalystAgent, SPYAnalyst,
|
| 16 |
+
TrendAnalystAgent,
|
| 17 |
+
UnusualEventDetector,
|
| 18 |
+
)
|
| 19 |
+
from polyhedra.agents.quant.product_contracts import PublisherPayload
|
| 20 |
+
from polyhedra.core.research_state import QuantState, ResearchStateManager
|
| 21 |
+
from polyhedra.core.session import SessionManager
|
| 22 |
+
from polyhedra.core.trace_logger import TraceLogger
|
| 23 |
+
from polyhedra.services.file_writer import FileWriter
|
| 24 |
+
from polyhedra.services.options_data import OptionsDataSnapshot
|
| 25 |
+
from polyhedra.services.quant_runtime import QuantRuntime
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
AT = datetime(2026, 9, 20, 12, tzinfo=timezone.utc)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class FailingFinnhub:
|
| 32 |
+
async def fetch_ticker_data(self, ticker, session_dir):
|
| 33 |
+
raise RuntimeError("controlled market-data outage")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class UnavailableOptions:
|
| 37 |
+
provider = "controlled-options"
|
| 38 |
+
max_expirations = 1
|
| 39 |
+
max_contracts_per_side = 1
|
| 40 |
+
|
| 41 |
+
def fetch(self, ticker):
|
| 42 |
+
return OptionsDataSnapshot(
|
| 43 |
+
symbol=ticker,
|
| 44 |
+
provider=self.provider,
|
| 45 |
+
retrieved_at=AT.isoformat(),
|
| 46 |
+
status="unavailable",
|
| 47 |
+
note="Controlled options outage.",
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class OnlyFinleyLLM:
|
| 52 |
+
async def complete_structured(self, prompt, schema):
|
| 53 |
+
if schema is not PublisherPayload:
|
| 54 |
+
raise AssertionError(f"unexpected LLM call for {schema.__name__}")
|
| 55 |
+
typed_input, _ = json.JSONDecoder().raw_decode(prompt.split("Typed input:\n", 1)[1])
|
| 56 |
+
strategy = typed_input["dependencies"]["strategy"]
|
| 57 |
+
strategy_ref = {
|
| 58 |
+
"schema_version": "8.0",
|
| 59 |
+
"artifact_id": strategy["artifact_id"],
|
| 60 |
+
"run_id": strategy["run_id"],
|
| 61 |
+
"session_id": strategy["session_id"],
|
| 62 |
+
"producer": "QuantStrategist",
|
| 63 |
+
"path": f"quant/runs/{strategy['run_id']}/trade_proposals.json",
|
| 64 |
+
"format": "JSON",
|
| 65 |
+
}
|
| 66 |
+
evidence_refs = [{
|
| 67 |
+
"artifact": strategy_ref,
|
| 68 |
+
"field_path": "/payload/outcome",
|
| 69 |
+
}]
|
| 70 |
+
prior_post = next((
|
| 71 |
+
reference for reference in typed_input["baseline_refs"]
|
| 72 |
+
if reference["producer"] == "Publisher"
|
| 73 |
+
), None)
|
| 74 |
+
if prior_post is not None:
|
| 75 |
+
evidence_refs.append({
|
| 76 |
+
"artifact": prior_post,
|
| 77 |
+
"field_path": "/payload/market_summary",
|
| 78 |
+
})
|
| 79 |
+
return SimpleNamespace(
|
| 80 |
+
output=PublisherPayload(
|
| 81 |
+
headline="Analysis unavailable",
|
| 82 |
+
market_summary="Required market evidence was unavailable.",
|
| 83 |
+
what_to_watch=["Restore current market data before drawing a conclusion."],
|
| 84 |
+
displayed_proposal_ids=[],
|
| 85 |
+
no_proposal_reason="DATA_LOSS",
|
| 86 |
+
disclaimer="Paper trading simulation only. Not financial advice.",
|
| 87 |
+
approximate_word_count=1,
|
| 88 |
+
slack_rendering="placeholder",
|
| 89 |
+
delta_state="UNCHANGED" if prior_post else "NOT_COMPARED",
|
| 90 |
+
evidence_refs=evidence_refs,
|
| 91 |
+
data_gaps=[],
|
| 92 |
+
),
|
| 93 |
+
input_tokens=40,
|
| 94 |
+
output_tokens=20,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class FailingTrend:
|
| 99 |
+
role = "trendanalyst"
|
| 100 |
+
|
| 101 |
+
async def execute_typed(self, inputs, **kwargs):
|
| 102 |
+
raise RuntimeError("controlled TrendAnalyst failure")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@pytest.mark.asyncio
|
| 106 |
+
async def test_specialized_unavailable_run_reaches_finley_with_typed_provenance(tmp_path: Path):
|
| 107 |
+
session_dir = tmp_path / "session1"
|
| 108 |
+
session_dir.mkdir()
|
| 109 |
+
manager = ResearchStateManager(session_dir)
|
| 110 |
+
state = manager.load()
|
| 111 |
+
state.quant_state = QuantState(watchlist=["SPY"], mode="yolo")
|
| 112 |
+
manager.save(state)
|
| 113 |
+
|
| 114 |
+
bomb = OnlyFinleyLLM()
|
| 115 |
+
agents = {
|
| 116 |
+
"DataFetcher": DataFetcherAgent(FailingFinnhub()),
|
| 117 |
+
"OptionsFlowWatcher": OptionsFlowWatcher(UnavailableOptions()),
|
| 118 |
+
"TrendAnalyst": TrendAnalystAgent(bomb),
|
| 119 |
+
"MarketEventWatcher": MarketEventWatcher(bomb),
|
| 120 |
+
"MacroContextWatcher": MacroContextWatcher(bomb),
|
| 121 |
+
"UnusualEventDetector": UnusualEventDetector(bomb),
|
| 122 |
+
"EventRouter": EventRouter(bomb),
|
| 123 |
+
"SPYAnalyst": SPYAnalyst(bomb),
|
| 124 |
+
"QuantResearcher": QuantResearcherAgent(bomb),
|
| 125 |
+
"Backtester": BacktesterAgent(bomb),
|
| 126 |
+
"RiskAnalyst": RiskAnalystAgent(bomb),
|
| 127 |
+
"QuantStrategist": QuantStrategistAgent(bomb),
|
| 128 |
+
"Publisher": PublisherAgent(bomb),
|
| 129 |
+
}
|
| 130 |
+
runtime = QuantRuntime(
|
| 131 |
+
session_dir=session_dir,
|
| 132 |
+
session_id="session1",
|
| 133 |
+
agents=agents,
|
| 134 |
+
writer=FileWriter(session_dir, session_id="session1"),
|
| 135 |
+
trace=TraceLogger(session_dir),
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
result = await runtime.run_yolo(run_id="run1", tickers=["SPY"], started_at=AT)
|
| 139 |
+
|
| 140 |
+
assert result.record.status == "completed", result.record.execution.model_dump_json(indent=2)
|
| 141 |
+
assert result.finley is not None
|
| 142 |
+
assert result.finley.payload.no_proposal_reason == "DATA_LOSS"
|
| 143 |
+
assert "No paper trade proposal" in result.finley.payload.slack_rendering
|
| 144 |
+
assert all(item.state == "COMPLETED" for item in result.record.execution.records)
|
| 145 |
+
assert set(result.record.permission_snapshots) == {
|
| 146 |
+
item.agent for item in result.record.routing_plan.active_agents
|
| 147 |
+
}
|
| 148 |
+
assert (session_dir / f"yolo_runs/{result.record.run_id}.json").is_file()
|
| 149 |
+
assert (session_dir / f"quant/evidence_ledger_{result.record.run_id}.json").is_file()
|
| 150 |
+
ledger = (session_dir / f"quant/evidence_ledger_{result.record.run_id}.json").read_text()
|
| 151 |
+
assert "typed_runtime_reference" in ledger
|
| 152 |
+
assert "controlled market-data outage" in ledger
|
| 153 |
+
assert len((session_dir / "trace.jsonl").read_text().splitlines()) == len(
|
| 154 |
+
result.record.routing_plan.active_agents
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@pytest.mark.asyncio
|
| 159 |
+
async def test_second_run_freezes_first_typed_run_as_delta_baseline(tmp_path: Path):
|
| 160 |
+
session_dir = tmp_path / "session1"
|
| 161 |
+
session_dir.mkdir()
|
| 162 |
+
manager = ResearchStateManager(session_dir)
|
| 163 |
+
state = manager.load()
|
| 164 |
+
state.quant_state = QuantState(watchlist=["SPY"], mode="yolo")
|
| 165 |
+
manager.save(state)
|
| 166 |
+
|
| 167 |
+
bomb = OnlyFinleyLLM()
|
| 168 |
+
agents = {
|
| 169 |
+
"DataFetcher": DataFetcherAgent(FailingFinnhub()),
|
| 170 |
+
"OptionsFlowWatcher": OptionsFlowWatcher(UnavailableOptions()),
|
| 171 |
+
"TrendAnalyst": TrendAnalystAgent(bomb),
|
| 172 |
+
"MarketEventWatcher": MarketEventWatcher(bomb),
|
| 173 |
+
"MacroContextWatcher": MacroContextWatcher(bomb),
|
| 174 |
+
"UnusualEventDetector": UnusualEventDetector(bomb),
|
| 175 |
+
"EventRouter": EventRouter(bomb),
|
| 176 |
+
"SPYAnalyst": SPYAnalyst(bomb),
|
| 177 |
+
"QuantResearcher": QuantResearcherAgent(bomb),
|
| 178 |
+
"Backtester": BacktesterAgent(bomb),
|
| 179 |
+
"RiskAnalyst": RiskAnalystAgent(bomb),
|
| 180 |
+
"QuantStrategist": QuantStrategistAgent(bomb),
|
| 181 |
+
"Publisher": PublisherAgent(bomb),
|
| 182 |
+
}
|
| 183 |
+
runtime_args = {
|
| 184 |
+
"session_dir": session_dir,
|
| 185 |
+
"session_id": "session1",
|
| 186 |
+
"agents": agents,
|
| 187 |
+
"writer": FileWriter(session_dir, session_id="session1"),
|
| 188 |
+
"trace": TraceLogger(session_dir),
|
| 189 |
+
}
|
| 190 |
+
first = await QuantRuntime(**runtime_args).run_yolo(
|
| 191 |
+
run_id="run1", tickers=["SPY"], started_at=AT,
|
| 192 |
+
)
|
| 193 |
+
second = await QuantRuntime(**runtime_args).run_yolo(
|
| 194 |
+
run_id="run2", tickers=["SPY"], started_at=AT,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
assert first.record.run_mode == "BASELINE"
|
| 198 |
+
assert second.record.run_mode == "DELTA"
|
| 199 |
+
assert second.record.baseline_run_id == "run1"
|
| 200 |
+
assert second.finley is not None
|
| 201 |
+
assert second.finley.payload.delta_state == "UNCHANGED"
|
| 202 |
+
assert any(ref.run_id == "run1" for ref in second.finley.baseline_refs)
|
| 203 |
+
assert len(json.loads(
|
| 204 |
+
(session_dir / "quant/strategist_performance.json").read_text()
|
| 205 |
+
)["vote_history"]) == 0
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@pytest.mark.asyncio
|
| 209 |
+
async def test_mixed_general_and_specialized_scope_joins_in_one_typed_run(tmp_path: Path):
|
| 210 |
+
session_dir = tmp_path / "session1"
|
| 211 |
+
session_dir.mkdir()
|
| 212 |
+
bomb = OnlyFinleyLLM()
|
| 213 |
+
agents = {
|
| 214 |
+
"DataFetcher": DataFetcherAgent(FailingFinnhub()),
|
| 215 |
+
"OptionsFlowWatcher": OptionsFlowWatcher(UnavailableOptions()),
|
| 216 |
+
"TrendAnalyst": TrendAnalystAgent(bomb),
|
| 217 |
+
"SentimentAnalyst": SentimentAnalystAgent(bomb),
|
| 218 |
+
"MarketEventWatcher": MarketEventWatcher(bomb),
|
| 219 |
+
"MacroContextWatcher": MacroContextWatcher(bomb),
|
| 220 |
+
"UnusualEventDetector": UnusualEventDetector(bomb),
|
| 221 |
+
"EventRouter": EventRouter(bomb),
|
| 222 |
+
"SPYAnalyst": SPYAnalyst(bomb),
|
| 223 |
+
"QuantResearcher": QuantResearcherAgent(bomb),
|
| 224 |
+
"Backtester": BacktesterAgent(bomb),
|
| 225 |
+
"RiskAnalyst": RiskAnalystAgent(bomb),
|
| 226 |
+
"QuantStrategist": QuantStrategistAgent(bomb),
|
| 227 |
+
"Publisher": PublisherAgent(bomb),
|
| 228 |
+
}
|
| 229 |
+
result = await QuantRuntime(
|
| 230 |
+
session_dir=session_dir,
|
| 231 |
+
session_id="session1",
|
| 232 |
+
agents=agents,
|
| 233 |
+
writer=FileWriter(session_dir, session_id="session1"),
|
| 234 |
+
trace=TraceLogger(session_dir),
|
| 235 |
+
).run_yolo(run_id="mixed1", tickers=["AAPL", "SPY"], started_at=AT)
|
| 236 |
+
|
| 237 |
+
active = {item.agent: item for item in result.record.routing_plan.active_agents}
|
| 238 |
+
assert result.record.status == "completed"
|
| 239 |
+
assert active["SentimentAnalyst"].effective_ticker_scope == ("AAPL",)
|
| 240 |
+
assert active["SPYAnalyst"].effective_ticker_scope == ("SPY",)
|
| 241 |
+
assert {item.agent for item in active["QuantResearcher"].required_dependencies} == {
|
| 242 |
+
"TrendAnalyst", "SentimentAnalyst", "SPYAnalyst",
|
| 243 |
+
}
|
| 244 |
+
assert result.finley is not None
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@pytest.mark.asyncio
|
| 248 |
+
async def test_failed_agent_blocks_dependents_without_finley_opinion(tmp_path: Path):
|
| 249 |
+
session_dir = tmp_path / "session1"
|
| 250 |
+
session_dir.mkdir()
|
| 251 |
+
agents = {
|
| 252 |
+
"DataFetcher": DataFetcherAgent(FailingFinnhub()),
|
| 253 |
+
"OptionsFlowWatcher": OptionsFlowWatcher(UnavailableOptions()),
|
| 254 |
+
"TrendAnalyst": FailingTrend(),
|
| 255 |
+
"MarketEventWatcher": MarketEventWatcher(OnlyFinleyLLM()),
|
| 256 |
+
"MacroContextWatcher": MacroContextWatcher(OnlyFinleyLLM()),
|
| 257 |
+
"UnusualEventDetector": UnusualEventDetector(OnlyFinleyLLM()),
|
| 258 |
+
"EventRouter": EventRouter(OnlyFinleyLLM()),
|
| 259 |
+
"SPYAnalyst": SPYAnalyst(OnlyFinleyLLM()),
|
| 260 |
+
"QuantResearcher": QuantResearcherAgent(OnlyFinleyLLM()),
|
| 261 |
+
"Backtester": BacktesterAgent(OnlyFinleyLLM()),
|
| 262 |
+
"RiskAnalyst": RiskAnalystAgent(OnlyFinleyLLM()),
|
| 263 |
+
"QuantStrategist": QuantStrategistAgent(OnlyFinleyLLM()),
|
| 264 |
+
"Publisher": PublisherAgent(OnlyFinleyLLM()),
|
| 265 |
+
}
|
| 266 |
+
result = await QuantRuntime(
|
| 267 |
+
session_dir=session_dir,
|
| 268 |
+
session_id="session1",
|
| 269 |
+
agents=agents,
|
| 270 |
+
writer=FileWriter(session_dir, session_id="session1"),
|
| 271 |
+
trace=TraceLogger(session_dir),
|
| 272 |
+
).run_yolo(run_id="failed1", tickers=["SPY"], started_at=AT)
|
| 273 |
+
|
| 274 |
+
records = {item.agent: item for item in result.record.execution.records}
|
| 275 |
+
assert result.record.status == "failed"
|
| 276 |
+
assert records["TrendAnalyst"].state == "FAILED"
|
| 277 |
+
assert "controlled TrendAnalyst failure" in records["TrendAnalyst"].error
|
| 278 |
+
assert records["SPYAnalyst"].state == "BLOCKED"
|
| 279 |
+
assert records["QuantResearcher"].state == "BLOCKED"
|
| 280 |
+
assert records["Publisher"].state == "BLOCKED"
|
| 281 |
+
assert result.finley is None
|
| 282 |
+
assert not (session_dir / "quant/runs/failed1/post.json").exists()
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
@pytest.mark.asyncio
|
| 286 |
+
async def test_export_contains_every_recorded_input_output_and_ledger(tmp_path: Path):
|
| 287 |
+
sessions_dir = tmp_path / "sessions"
|
| 288 |
+
manager = SessionManager(sessions_dir)
|
| 289 |
+
session = manager.create(goal="SPY export", platform="web")
|
| 290 |
+
bomb = OnlyFinleyLLM()
|
| 291 |
+
agents = {
|
| 292 |
+
"DataFetcher": DataFetcherAgent(FailingFinnhub()),
|
| 293 |
+
"OptionsFlowWatcher": OptionsFlowWatcher(UnavailableOptions()),
|
| 294 |
+
"TrendAnalyst": TrendAnalystAgent(bomb),
|
| 295 |
+
"MarketEventWatcher": MarketEventWatcher(bomb),
|
| 296 |
+
"MacroContextWatcher": MacroContextWatcher(bomb),
|
| 297 |
+
"UnusualEventDetector": UnusualEventDetector(bomb),
|
| 298 |
+
"EventRouter": EventRouter(bomb),
|
| 299 |
+
"SPYAnalyst": SPYAnalyst(bomb),
|
| 300 |
+
"QuantResearcher": QuantResearcherAgent(bomb),
|
| 301 |
+
"Backtester": BacktesterAgent(bomb),
|
| 302 |
+
"RiskAnalyst": RiskAnalystAgent(bomb),
|
| 303 |
+
"QuantStrategist": QuantStrategistAgent(bomb),
|
| 304 |
+
"Publisher": PublisherAgent(bomb),
|
| 305 |
+
}
|
| 306 |
+
result = await QuantRuntime(
|
| 307 |
+
session_dir=session.session_dir,
|
| 308 |
+
session_id=session.session_id,
|
| 309 |
+
agents=agents,
|
| 310 |
+
writer=FileWriter(session.session_dir, session_id=session.session_id),
|
| 311 |
+
trace=TraceLogger(session.session_dir),
|
| 312 |
+
).run_yolo(run_id="export1", tickers=["SPY"], started_at=AT)
|
| 313 |
+
|
| 314 |
+
archive_path = manager.export(session.session_id, tmp_path / "exports")
|
| 315 |
+
with zipfile.ZipFile(archive_path) as archive:
|
| 316 |
+
names = set(archive.namelist())
|
| 317 |
+
assert f"yolo_runs/{result.record.run_id}.json" in names
|
| 318 |
+
assert f"quant/evidence_ledger_{result.record.run_id}.json" in names
|
| 319 |
+
assert "quant/strategist_performance.json" in names
|
| 320 |
+
assert set(result.record.input_snapshot_paths.values()).issubset(names)
|
| 321 |
+
assert {item.path for item in result.record.artifact_inventory}.issubset(names)
|
tests/test_quant_v6/test_scope_routing.py
CHANGED
|
@@ -58,6 +58,7 @@ class _FakeYoloService(_FakeService):
|
|
| 58 |
super().__init__(session_dir)
|
| 59 |
self.session.goal = "YOLO & SPY Analysis Session"
|
| 60 |
self.prepared: list[list[str]] = []
|
|
|
|
| 61 |
self._mode = "investigation"
|
| 62 |
self._yolo_update_fn = None
|
| 63 |
|
|
@@ -65,6 +66,9 @@ class _FakeYoloService(_FakeService):
|
|
| 65 |
self.prepared.append(tickers)
|
| 66 |
return SimpleNamespace(label="Session-delta YOLO", run_mode="session_delta")
|
| 67 |
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
class _FakeLLM:
|
| 70 |
async def complete(self, prompt: str, model: str | None = None):
|
|
@@ -360,7 +364,7 @@ async def test_quant_command_keeps_non_v6_markets_on_v5_flow(tmp_path: Path) ->
|
|
| 360 |
|
| 361 |
|
| 362 |
@pytest.mark.asyncio
|
| 363 |
-
async def
|
| 364 |
integration = SlackIntegration.__new__(SlackIntegration)
|
| 365 |
service = _FakeYoloService(tmp_path)
|
| 366 |
integration._sessions = {"C123": service}
|
|
@@ -369,9 +373,10 @@ async def test_yolo_command_reuses_active_session_and_dispatches_datafetcher(tmp
|
|
| 369 |
await SlackIntegration._cmd_yolo(integration, client, "C123", "SPY")
|
| 370 |
|
| 371 |
assert service._mode == "yolo"
|
| 372 |
-
assert service.
|
| 373 |
-
assert service.
|
| 374 |
-
assert
|
|
|
|
| 375 |
|
| 376 |
|
| 377 |
@pytest.mark.asyncio
|
|
|
|
| 58 |
super().__init__(session_dir)
|
| 59 |
self.session.goal = "YOLO & SPY Analysis Session"
|
| 60 |
self.prepared: list[list[str]] = []
|
| 61 |
+
self.runs: list[list[str]] = []
|
| 62 |
self._mode = "investigation"
|
| 63 |
self._yolo_update_fn = None
|
| 64 |
|
|
|
|
| 66 |
self.prepared.append(tickers)
|
| 67 |
return SimpleNamespace(label="Session-delta YOLO", run_mode="session_delta")
|
| 68 |
|
| 69 |
+
async def run_yolo(self, tickers: list[str]):
|
| 70 |
+
self.runs.append(tickers)
|
| 71 |
+
|
| 72 |
|
| 73 |
class _FakeLLM:
|
| 74 |
async def complete(self, prompt: str, model: str | None = None):
|
|
|
|
| 364 |
|
| 365 |
|
| 366 |
@pytest.mark.asyncio
|
| 367 |
+
async def test_yolo_command_reuses_active_session_and_invokes_shared_runtime(tmp_path: Path) -> None:
|
| 368 |
integration = SlackIntegration.__new__(SlackIntegration)
|
| 369 |
service = _FakeYoloService(tmp_path)
|
| 370 |
integration._sessions = {"C123": service}
|
|
|
|
| 373 |
await SlackIntegration._cmd_yolo(integration, client, "C123", "SPY")
|
| 374 |
|
| 375 |
assert service._mode == "yolo"
|
| 376 |
+
assert service.runs == [["SPY"]]
|
| 377 |
+
assert service.prepared == []
|
| 378 |
+
assert service.dispatched == []
|
| 379 |
+
assert any("YOLO starting" in message for message in client.messages)
|
| 380 |
|
| 381 |
|
| 382 |
@pytest.mark.asyncio
|
tests/test_v611_web_ui.py
CHANGED
|
@@ -5,8 +5,10 @@ import json
|
|
| 5 |
import sys
|
| 6 |
import types
|
| 7 |
import zipfile
|
|
|
|
| 8 |
from pathlib import Path
|
| 9 |
|
|
|
|
| 10 |
from fastapi.testclient import TestClient
|
| 11 |
|
| 12 |
sentence_transformers_stub = types.ModuleType("sentence_transformers")
|
|
@@ -15,10 +17,17 @@ sys.modules.setdefault("sentence_transformers", sentence_transformers_stub)
|
|
| 15 |
|
| 16 |
from polyhedra import app as app_module # noqa: E402
|
| 17 |
from polyhedra.core import session as session_module # noqa: E402
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
from polyhedra.core.research_state import QuantState, ResearchStateManager # noqa: E402
|
| 19 |
from polyhedra.core.session import SessionManager # noqa: E402
|
| 20 |
from polyhedra.core.yolo_context import prepare_yolo_run_context # noqa: E402
|
| 21 |
from polyhedra.services.evidence_ledger import write_evidence_ledger # noqa: E402
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
def _client(tmp_path: Path, monkeypatch) -> TestClient:
|
|
@@ -34,6 +43,117 @@ def test_v611_ui_index_loads(tmp_path: Path, monkeypatch) -> None:
|
|
| 34 |
assert response.status_code == 200
|
| 35 |
assert "Polyhedra YOLO Console" in response.text
|
| 36 |
assert "Run YOLO" in response.text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def test_v611_yolo_api_rejects_empty_ticker_input(tmp_path: Path, monkeypatch) -> None:
|
|
|
|
| 5 |
import sys
|
| 6 |
import types
|
| 7 |
import zipfile
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
from pathlib import Path
|
| 10 |
|
| 11 |
+
import pytest
|
| 12 |
from fastapi.testclient import TestClient
|
| 13 |
|
| 14 |
sentence_transformers_stub = types.ModuleType("sentence_transformers")
|
|
|
|
| 17 |
|
| 18 |
from polyhedra import app as app_module # noqa: E402
|
| 19 |
from polyhedra.core import session as session_module # noqa: E402
|
| 20 |
+
from polyhedra.core.active_routing import build_active_routing_plan # noqa: E402
|
| 21 |
+
from polyhedra.core.artifacts import JsonArtifactRef # noqa: E402
|
| 22 |
+
from polyhedra.core.dependency_executor import AgentCompletion, DependencyExecutor # noqa: E402
|
| 23 |
+
from polyhedra.core.quant_contracts import load_quant_contracts # noqa: E402
|
| 24 |
from polyhedra.core.research_state import QuantState, ResearchStateManager # noqa: E402
|
| 25 |
from polyhedra.core.session import SessionManager # noqa: E402
|
| 26 |
from polyhedra.core.yolo_context import prepare_yolo_run_context # noqa: E402
|
| 27 |
from polyhedra.services.evidence_ledger import write_evidence_ledger # noqa: E402
|
| 28 |
+
from polyhedra.services.quant_run_record import ( # noqa: E402
|
| 29 |
+
QuantRunRecordStore, build_quant_run_record,
|
| 30 |
+
)
|
| 31 |
|
| 32 |
|
| 33 |
def _client(tmp_path: Path, monkeypatch) -> TestClient:
|
|
|
|
| 43 |
assert response.status_code == 200
|
| 44 |
assert "Polyhedra YOLO Console" in response.text
|
| 45 |
assert "Run YOLO" in response.text
|
| 46 |
+
assert "Routing Table" in response.text
|
| 47 |
+
assert "Permissions" in response.text
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@pytest.mark.asyncio
|
| 51 |
+
async def test_v8_typed_replay_surfaces_frozen_routing_acl_and_references(
|
| 52 |
+
tmp_path: Path,
|
| 53 |
+
monkeypatch,
|
| 54 |
+
) -> None:
|
| 55 |
+
client = _client(tmp_path, monkeypatch)
|
| 56 |
+
session = SessionManager().create(goal="YOLO & SPY Analysis Session", platform="web")
|
| 57 |
+
run_id = "typed-run-1"
|
| 58 |
+
plan = build_active_routing_plan(
|
| 59 |
+
run_id=run_id, execution_context="YOLO", tickers=["SPY"],
|
| 60 |
+
)
|
| 61 |
+
contracts = load_quant_contracts()
|
| 62 |
+
|
| 63 |
+
async def runner(item):
|
| 64 |
+
template = next(
|
| 65 |
+
path for path in contracts.for_agent(item.agent).permissions.create
|
| 66 |
+
if path.endswith(".json") and path != "quant/strategist_performance.json"
|
| 67 |
+
)
|
| 68 |
+
return AgentCompletion(
|
| 69 |
+
result_status="PARTIAL",
|
| 70 |
+
artifact_ref=JsonArtifactRef(
|
| 71 |
+
schema_version="8.0",
|
| 72 |
+
artifact_id=f"{run_id}-{item.agent}",
|
| 73 |
+
run_id=run_id,
|
| 74 |
+
session_id=session.session_id,
|
| 75 |
+
producer=item.agent,
|
| 76 |
+
path=template.replace("{run_id}", run_id).replace(
|
| 77 |
+
"{ticker}", item.effective_ticker_scope[0],
|
| 78 |
+
),
|
| 79 |
+
),
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
execution = await DependencyExecutor(
|
| 83 |
+
plan, session_id=session.session_id, runner=runner,
|
| 84 |
+
).run()
|
| 85 |
+
templates = {
|
| 86 |
+
item.agent: contracts.for_agent(item.agent).permissions.model_dump(mode="json")
|
| 87 |
+
for item in plan.active_agents
|
| 88 |
+
}
|
| 89 |
+
resolved = {
|
| 90 |
+
agent: {
|
| 91 |
+
operation: [
|
| 92 |
+
path.replace("{run_id}", run_id).replace("{ticker}", "SPY")
|
| 93 |
+
for path in paths
|
| 94 |
+
]
|
| 95 |
+
for operation, paths in permissions.items()
|
| 96 |
+
}
|
| 97 |
+
for agent, permissions in templates.items()
|
| 98 |
+
}
|
| 99 |
+
now = datetime(2026, 9, 20, 12, tzinfo=timezone.utc)
|
| 100 |
+
record = build_quant_run_record(
|
| 101 |
+
plan=plan,
|
| 102 |
+
execution=execution,
|
| 103 |
+
session_id=session.session_id,
|
| 104 |
+
run_mode="BASELINE",
|
| 105 |
+
baseline_run_id=None,
|
| 106 |
+
started_at=now,
|
| 107 |
+
completed_at=now,
|
| 108 |
+
input_snapshot_paths={},
|
| 109 |
+
permission_templates=templates,
|
| 110 |
+
permission_snapshots=resolved,
|
| 111 |
+
)
|
| 112 |
+
QuantRunRecordStore(
|
| 113 |
+
session.session_dir, session_id=session.session_id,
|
| 114 |
+
).save(record)
|
| 115 |
+
|
| 116 |
+
strategy_ref = next(
|
| 117 |
+
item.artifact_ref for item in execution.records
|
| 118 |
+
if item.agent == "QuantStrategist"
|
| 119 |
+
)
|
| 120 |
+
post_ref = next(
|
| 121 |
+
item.artifact_ref for item in execution.records if item.agent == "Publisher"
|
| 122 |
+
)
|
| 123 |
+
options_ref = next(
|
| 124 |
+
item.artifact_ref for item in execution.records if item.agent == "OptionsFlowWatcher"
|
| 125 |
+
)
|
| 126 |
+
for reference, content in (
|
| 127 |
+
(strategy_ref, {"payload": {"outcome": "NO_TRADE", "proposals": []}}),
|
| 128 |
+
(post_ref, {
|
| 129 |
+
"created_at": now.isoformat(),
|
| 130 |
+
"payload": {"slack_rendering": "Typed Finley result."},
|
| 131 |
+
"input_refs": [strategy_ref.model_dump(mode="json")],
|
| 132 |
+
"baseline_refs": [],
|
| 133 |
+
}),
|
| 134 |
+
(options_ref, {
|
| 135 |
+
"status": "PARTIAL", "ticker_scope": ["SPY"],
|
| 136 |
+
"data_gaps": [{"message": "Delayed options sample."}], "payload": {},
|
| 137 |
+
}),
|
| 138 |
+
):
|
| 139 |
+
path = session.session_dir / reference.path
|
| 140 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 141 |
+
path.write_text(json.dumps(content), encoding="utf-8")
|
| 142 |
+
|
| 143 |
+
response = client.get(f"/api/sessions/{session.session_id}/runs/{run_id}")
|
| 144 |
+
payload = response.json()
|
| 145 |
+
|
| 146 |
+
assert response.status_code == 200
|
| 147 |
+
assert payload["workflow"] == "V8 typed quant dependency graph"
|
| 148 |
+
assert payload["finley"]["content"] == "Typed Finley result."
|
| 149 |
+
assert all(row["status"] == "completed" for row in payload["path"])
|
| 150 |
+
assert all(row["result_status"] == "PARTIAL" for row in payload["path"])
|
| 151 |
+
assert all(row["started_at"] and row["finished_at"] for row in payload["path"])
|
| 152 |
+
assert any(row["agent"] == "VizAgent" for row in payload["routing"]["inactive"])
|
| 153 |
+
assert len(payload["permissions"]) == 19
|
| 154 |
+
publisher = next(row for row in payload["path"] if row["agent"] == "Publisher")
|
| 155 |
+
assert publisher["input_refs"][0]["path"] == strategy_ref.path
|
| 156 |
+
assert payload["proposal_state"]["status"] == "no_trade"
|
| 157 |
|
| 158 |
|
| 159 |
def test_v611_yolo_api_rejects_empty_ticker_input(tmp_path: Path, monkeypatch) -> None:
|