"""Support contexts use the governed routing, ACL, trace, and record runtime.""" from datetime import datetime, timezone from pathlib import Path import pytest from polyhedra.agents.quant.market_data_contracts import MarketDataArtifact from polyhedra.agents.quant.portfoliomonitor import PortfolioMonitorAgent from polyhedra.agents.quant.product_contracts import PaperPosition from polyhedra.agents.quant.vizagent import VizAgent from polyhedra.core.research_state import ResearchStateManager from polyhedra.core.trace_logger import TraceLogger from polyhedra.services.artifact_publisher import ArtifactPublisher from polyhedra.services.file_writer import FileWriter, PublicationRegistry, ScopedFileWriter from polyhedra.services.llm_service import StructuredCompletion from polyhedra.services.quant_support_runtime import QuantSupportRuntime AT = datetime(2026, 9, 20, 16, tzinfo=timezone.utc) class _CaptionLLM: async def complete_structured(self, _prompt, output_schema): return StructuredCompletion( output_schema.model_validate({"caption": "SPY closed above its moving average."}), 8, 7, 1, ) def _market_data() -> MarketDataArtifact: return MarketDataArtifact.model_validate({ "schema_version": "8.0", "artifact_id": "source-market-SPY", "session_id": "session1", "run_id": "source1", "producer": "DataFetcher", "ticker": "SPY", "retrieved_at": AT, "market_date": "2026-09-18", "status": "COMPLETE", "ohlcv": [{ "market_date": "2026-09-18", "open": 650.0, "high": 656.0, "low": 648.0, "close": 655.0, "adjusted_close": 655.0, "volume": 42_000_000.0, }], "indicators": {"points": [{ "market_date": "2026-09-18", "sma_20": 645.0, "ema_20": 647.0, "rsi_14": 58.0, "macd": 1.2, "macd_signal": 0.9, "macd_histogram": 0.3, }]}, "news": [], "earnings": [], "provenance": [{ "component": component, "provider": provider, "retrieved_at": AT, "source_observed_at": observed, "freshness": freshness, "availability": availability, "record_count": count, } for component, provider, observed, freshness, availability, count in ( ("OHLCV", "controlled", AT, "FRESH", "AVAILABLE", 1), ("INDICATORS", "computed", AT, "FRESH", "AVAILABLE", 1), ("NEWS", "controlled", None, "UNKNOWN", "AVAILABLE", 0), ("EARNINGS", None, None, "UNKNOWN", "NOT_APPLICABLE", 0), )], "quality_issues": [], "baseline_ref": None, }) def _runtime(tmp_path: Path, agents): session = tmp_path / "session1" session.mkdir(exist_ok=True) return session, FileWriter(session, session_id="session1"), QuantSupportRuntime( session_dir=session, session_id="session1", agents=agents, writer=FileWriter(session, session_id="session1"), trace=TraceLogger(session), ) @pytest.mark.asyncio async def test_visualization_uses_one_frozen_source_run_and_records_png(tmp_path: Path): session, writer, runtime = _runtime(tmp_path, {"VizAgent": VizAgent(_CaptionLLM())}) registry = PublicationRegistry() source_files = ScopedFileWriter( writer, agent="DataFetcher", run_id="source1", ticker_scope=["SPY"], publications=registry, ) source = ArtifactPublisher( writer, session_id="session1", run_id="source1", ).publish_auxiliary( source_files, _market_data(), schema=MarketDataArtifact, json_path="quant/runs/source1/raw/SPY.json", markdown_path="quant/runs/source1/raw/SPY_summary.md", render_markdown=lambda _: "# SPY\n", ).artifact_ref result = await runtime.run_visualization( run_id="viz1", ticker_scope=["SPY"], source_run_id="source1", source_artifacts=[source], chart_type="CANDLESTICK", ticker="SPY", started_at=AT, ) assert result.record.execution_context == "VISUALIZATION" assert result.record.baseline_run_id == "source1" assert result.output is not None, result.record.execution.for_agent("VizAgent").error assert result.output.payload.charts[0].source_artifact_refs == [source] assert (session / "quant/runs/viz1/viz/candlestick_SPY.png").read_bytes().startswith( b"\x89PNG\r\n\x1a\n" ) assert (session / "support_runs/viz1.json").exists() assert (session / "quant/evidence_ledger_viz1.json").exists() assert "source1" in result.record.permission_snapshots["VizAgent"]["read"][0] @pytest.mark.asyncio async def test_monitor_records_alert_and_updates_timestamp_without_mutating_position(tmp_path: Path): session, _writer, runtime = _runtime( tmp_path, {"PortfolioMonitor": PortfolioMonitorAgent()}, ) position = PaperPosition( position_id="p1", ticker="SPY", direction="LONG", entry_price=100.0, size_percentage=10.0, ) async def quotes(_tickers): return {"SPY": 106.0} result = await runtime.run_portfolio_monitor( run_id="monitor1", ticker_scope=["SPY"], positions=[position], thresholds={"stop_loss_percentage": 5.0, "take_profit_percentage": 5.0}, paused=False, market_hours="OPEN", quote_provider={"provider": "finnhub", "configured": True}, quote_fetcher=quotes, started_at=AT, ) assert result.record.execution_context == "PORTFOLIO_MONITOR" assert result.output.payload.alerts[0].alert_type == "TAKE_PROFIT" assert position.size_percentage == 10.0 assert (session / "support_runs/monitor1.json").exists() assert ResearchStateManager(session).load().quant_state.last_monitor_run is not None assert (session / "trace.jsonl").read_text(encoding="utf-8").count("portfoliomonitor") >= 1