"""Polyhedra FastAPI server. Runs the Slack webhook handler plus a /health endpoint. Start with:: uvicorn polyhedra.app:app --host 0.0.0.0 --port 8000 Environment variables --------------------- SLACK_BOT_TOKEN — Slack Bot OAuth token (xoxb-…) SLACK_SIGNING_SECRET — Slack signing secret for request verification """ from __future__ import annotations import asyncio import hashlib import hmac import json import logging import os import re import tempfile import time from datetime import UTC, datetime from pathlib import Path from typing import Any # Load .env for local development (no-op when env vars are already injected) try: from dotenv import load_dotenv load_dotenv() except ImportError: pass logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Ensure Bolt's own logger surfaces so auth failures are visible in HF logs logging.getLogger("slack_bolt").setLevel(logging.DEBUG) logging.getLogger("slack_bolt.App").setLevel(logging.DEBUG) logging.getLogger("httpx").setLevel(logging.WARNING) # Imported at module scope so FastAPI's get_type_hints() can resolve them # even with `from __future__ import annotations` (PEP 563) active. try: from fastapi import FastAPI, Request from fastapi.responses import FileResponse, HTMLResponse, JSONResponse except ImportError: # pragma: no cover FastAPI = Request = FileResponse = HTMLResponse = JSONResponse = None # type: ignore[assignment,misc] _WEB_STATIC_DIR = Path(__file__).resolve().parent / "web" / "static" _RUNS: dict[str, dict[str, Any]] = {} _RUN_TASKS: set[asyncio.Task[Any]] = set() _YOLO_RUNS_DIR = "yolo_runs" def _extract_ui_tickers(text: str) -> list[str]: """Extract ticker-like UI input while keeping command words out of scope.""" stopwords = {"YOLO", "RUN", "INIT", "ANALYSIS", "QUANT", "V6", "V5"} tickers: list[str] = [] for token in re.findall(r"\b[A-Za-z]{1,5}\b", text.upper()): if token in stopwords: continue if token not in tickers: tickers.append(token) return tickers def _llm_config_status() -> dict[str, Any]: provider = os.getenv("POLYHEDRA_LLM_PROVIDER", "anthropic").lower() key_by_provider = { "anthropic": "ANTHROPIC_API_KEY", "openai": "OPENAI_API_KEY", "gemini": "GEMINI_API_KEY", "openrouter": "OPENROUTER_API_KEY", } key_name = key_by_provider.get(provider, "") configured = bool(key_name and os.getenv(key_name)) available_keys = [ name for name in key_by_provider.values() if os.getenv(name) ] note = "" if not configured: note = f"Set {key_name or 'a supported provider key'} for provider '{provider}'." if provider == "anthropic" and "GEMINI_API_KEY" in available_keys: note = ( "GEMINI_API_KEY is present, but POLYHEDRA_LLM_PROVIDER defaults to " "'anthropic'. Set POLYHEDRA_LLM_PROVIDER=gemini." ) return { "provider": provider, "configured": configured, "required_key": key_name, "available_key_names": available_keys, "note": note, } def _register_quant_agents(session: Any) -> None: """Register the same quant agents used by Slack YOLO sessions.""" from polyhedra.agents.quant import ( BacktesterAgent, BTCAnalyst, DataFetcherAgent, EventRouter, GLDAnalyst, MacroContextWatcher, MarketEventWatcher, OptionsFlowWatcher, PortfolioMonitorAgent, PublisherAgent, QQQAnalyst, QuantResearcherAgent, QuantStrategistAgent, RiskAnalystAgent, SentimentAnalystAgent, SPYAnalyst, TrendAnalystAgent, UnusualEventDetector, VizAgent, ) from polyhedra.core.role_registry import RoleEntry for agent_cls, role in [ (DataFetcherAgent, "datafetcher"), (TrendAnalystAgent, "trendanalyst"), (SentimentAnalystAgent, "sentimentanalyst"), (MarketEventWatcher, "marketeventwatcher"), (OptionsFlowWatcher, "optionsflowwatcher"), (MacroContextWatcher, "macrocontextwatcher"), (UnusualEventDetector, "unusualeventdetector"), (EventRouter, "eventrouter"), (BTCAnalyst, "btcanalyst"), (SPYAnalyst, "spyanalyst"), (QQQAnalyst, "qqqanalyst"), (GLDAnalyst, "gldanalyst"), (QuantResearcherAgent, "quantresearcher"), (BacktesterAgent, "backtester"), (RiskAnalystAgent, "riskanalyst"), (QuantStrategistAgent, "quantstrategist"), (VizAgent, "vizagent"), (PortfolioMonitorAgent, "portfoliomonitor"), (PublisherAgent, "publisher"), ]: session.registry.register(RoleEntry(role=role, agent=agent_cls())) def _seed_quant_watchlist(session: Any, tickers: list[str]) -> None: from polyhedra.core.research_state import QuantState, ResearchStateManager manager = ResearchStateManager(session.session_dir) state = manager.load() if state.quant_state is None: state.quant_state = QuantState() state.quant_state.mode = "yolo" for ticker in tickers: if ticker not in state.quant_state.watchlist: state.quant_state.watchlist.append(ticker) manager.save(state) def _quant_state_payload(session: Any) -> dict[str, Any]: try: quant_state = session.research_state.quant_state except Exception: return {} return quant_state.to_dict() if quant_state is not None else {} def _thread_messages(session_id: str, last_n: int = 200) -> list[dict[str, Any]]: from polyhedra.core.session import SessionManager session = SessionManager().resume(session_id) if session is None: return [] return session.thread_history(last_n=last_n) def _session_payload(session_id: str) -> dict[str, Any] | None: from polyhedra.agents.coordinator import _ROLE_LABELS, _planned_quant_path from polyhedra.core.session import SessionManager session = SessionManager().resume(session_id) if session is None: return None run = _RUNS.get(session_id, {}) if run.get("runtime_schema") == "8.0": return _typed_session_payload(session, run) messages = session.thread_history(last_n=300) quant_state = _quant_state_payload(session) run_started_at = str(quant_state.get("yolo_run_started_at") or "") current_run_messages = _messages_since(messages, run_started_at) if run_started_at else messages path_messages = current_run_messages or messages workflow_name, planned_roles = _planned_quant_path(session.goal) completed_roles = [ message.get("from_role", "") for message in path_messages if message.get("from_role") in planned_roles ] unique_completed = list(dict.fromkeys(completed_roles)) failed = run.get("status") == "failed" blocker = _first_blocker(path_messages) blocked = blocker is not None finished = "publisher" in unique_completed status = ( "failed" if failed else "blocked" if blocked else "completed" if finished else run.get("status", "running") ) finley = next( ( message for message in reversed(path_messages) if message.get("from_role") == "publisher" ), None, ) options_artifact = _latest_artifact_text(session.session_dir, "quant/options_flow_") blocked_role = blocker.get("role") if blocker else "" path = [] current_agent: dict[str, str] = {} for role in planned_roles: role_status = "completed" if role in unique_completed else "pending" if role == blocked_role: role_status = "blocked" path.append({ "role": role, "label": _ROLE_LABELS.get(role, role), "status": role_status, }) if status == "running": running_step = next((step for step in path if step["status"] != "completed"), None) if running_step: running_step["status"] = "running" current_agent = { "role": running_step["role"], "label": running_step["label"], } elif blocked_role: current_agent = { "role": blocked_role, "label": _ROLE_LABELS.get(blocked_role, blocked_role), } committee = _strategist_committee_payload(session.session_dir, quant_state) options_context = _summarize_options_artifact(options_artifact) diagnostics = _yolo_diagnostics( session.session_dir, path_messages, blocker=blocker, options_context=options_context, ) proposal_state = _proposal_state( session.session_dir, status=status, path=path, current_agent=current_agent, diagnostics=diagnostics, ) blocked_payload = {} if blocker: blocked_payload = { "agent": blocked_role, "label": _ROLE_LABELS.get(blocked_role, blocked_role), "reason": blocker.get("message", ""), } return { "session_id": session.session_id, "run_id": run.get("run_id", ""), "goal": session.goal, "created_at": session.created_at.isoformat(), "platform": session.platform, "status": status, "workflow": workflow_name, "run_mode": quant_state.get("yolo_run_mode", ""), "run_mode_label": _yolo_mode_label(quant_state), "yolo_context": { "run_started_at": quant_state.get("yolo_run_started_at"), "run_count": quant_state.get("yolo_run_count", 0), "baseline_complete": quant_state.get("yolo_baseline_complete", False), "baseline_artifacts": quant_state.get("yolo_baseline_artifacts", {}), "missing_baseline_artifacts": quant_state.get( "yolo_missing_baseline_artifacts", [] ), "baseline_snapshot_dir": quant_state.get("yolo_baseline_snapshot_dir", ""), }, "current_agent": current_agent, "blocked": blocked_payload, "path": path, "messages": messages, "finley": finley, "committee": committee, "options_context": options_context, "diagnostics": diagnostics, "proposal_state": proposal_state, "run_status_message": run.get("status_message", ""), "error": run.get("error", "") or (blocker.get("message", "") if blocker else ""), } def _typed_session_payload(session: Any, run: dict[str, Any]) -> dict[str, Any]: """Project a live or completed V8 run into the existing UI response shape.""" from polyhedra.agents.coordinator import _ROLE_LABELS, _TYPED_AGENT_ROLES from polyhedra.agents.quant.io_registry import quant_artifact_schema from polyhedra.core.active_routing import build_active_routing_plan from polyhedra.core.dependency_executor import AgentExecutionState from polyhedra.core.quant_contracts import ExecutionContext, load_quant_contracts from polyhedra.services.quant_run_record import QuantRunRecord run_id = str(run.get("run_id") or "") tickers = [str(item).upper() for item in run.get("tickers") or []] record = None raw_record = run.get("typed_record") if raw_record: record = QuantRunRecord.model_validate(raw_record) elif run_id: path = session.session_dir / _YOLO_RUNS_DIR / f"{run_id}.json" if path.exists(): try: record = QuantRunRecord.model_validate_json( path.read_text(encoding="utf-8"), strict=True, ) except Exception: record = None plan = record.routing_plan if record else build_active_routing_plan( run_id=run_id, execution_context=ExecutionContext.YOLO, tickers=tickers, ) live_states = dict(run.get("agent_states") or {}) records = {item.agent: item for item in record.execution.records} if record else {} path_rows = [] for item in plan.active_agents: execution = records.get(item.agent) state = execution.state.value if execution else live_states.get( item.agent, AgentExecutionState.WAITING.value, ) artifact_ref = ( execution.artifact_ref.model_dump(mode="json") if execution and execution.artifact_ref else None ) references = _typed_agent_references(session.session_dir, artifact_ref) live_times = (run.get("agent_times") or {}).get(item.agent, {}) input_snapshot = ( record.input_snapshot_paths.get(item.agent, "") if record else "" ) if not input_snapshot: candidate = f"quant/runs/{run_id}/inputs/{item.agent}.json" if (session.session_dir / candidate).is_file(): input_snapshot = candidate path_rows.append({ "role": _TYPED_AGENT_ROLES[item.agent], "agent": item.agent, "label": _ROLE_LABELS.get(_TYPED_AGENT_ROLES[item.agent], item.agent), "status": state.lower(), "result_status": execution.result_status.value if execution and execution.result_status else "", "effective_ticker_scope": list(item.effective_ticker_scope), "dependencies": [dep.agent for dep in item.required_dependencies], "artifact_ref": artifact_ref, "input_snapshot": input_snapshot, "input_refs": references["input_refs"], "baseline_refs": references["baseline_refs"], "started_at": ( execution.started_at.isoformat() if execution and execution.started_at else live_times.get("started_at", "") ), "finished_at": ( execution.finished_at.isoformat() if execution and execution.finished_at else live_times.get("finished_at", "") ), "error": execution.error if execution else None, "blocked_by": list(execution.blocked_by) if execution else [], }) status = record.status.value if record else str(run.get("status") or "running") current = next((item for item in path_rows if item["status"] == "running"), None) if current is None and status in {"running", "pending"}: current = next((item for item in path_rows if item["status"] == "waiting"), None) messages = session.thread_history(last_n=300) finley = _typed_finley(session.session_dir, run_id) if finley is None and record is None: finley = next( (message for message in reversed(messages) if message.get("from_role") == "publisher"), None, ) options_context = _typed_options_context(session.session_dir, run_id) diagnostics = _typed_diagnostics(session.session_dir, path_rows) proposal_state = _typed_proposal_state(session.session_dir, run_id, path_rows) quant_state = _quant_state_payload(session) baseline_run_id = record.baseline_run_id if record else None contracts = load_quant_contracts() permissions = [] for item in plan.active_agents: contract = contracts.for_agent(item.agent) templates = ( record.permission_templates.get(item.agent) if record and record.permission_templates else None ) or contract.permissions.model_dump(mode="json") resolved = ( record.permission_snapshots.get(item.agent) if record and record.permission_snapshots else None ) or _resolve_permission_paths( templates, run_id=run_id, baseline_run_id=baseline_run_id, tickers=list(item.effective_ticker_scope), ) permissions.append({ "agent": item.agent, "active": True, "inactive_reason": "", "templates": templates, "resolved": resolved, "input_snapshot": ( record.input_snapshot_paths.get(item.agent, "") if record else "" ), "published_output": next( (row["artifact_ref"] for row in path_rows if row["agent"] == item.agent), None, ), }) for item in plan.inactive_agents: permissions.append({ "agent": item.agent, "active": False, "inactive_reason": item.reason.value, "templates": contracts.for_agent(item.agent).permissions.model_dump(mode="json"), "resolved": {}, "input_snapshot": "", "published_output": None, }) routing = { "schema_version": "8.0", "active": [item.model_dump(mode="json") for item in plan.active_agents], "inactive": [item.model_dump(mode="json") for item in plan.inactive_agents], } blocked = next((row for row in path_rows if row["status"] in {"failed", "blocked"}), None) return { "session_id": session.session_id, "run_id": run_id, "goal": session.goal, "created_at": session.created_at.isoformat(), "platform": session.platform, "status": status, "workflow": "V8 typed quant dependency graph", "run_mode": ( record.run_mode.value if record else quant_state.get("yolo_run_mode", "") ), "run_mode_label": _yolo_mode_label(quant_state), "yolo_context": { "run_started_at": quant_state.get("yolo_run_started_at"), "run_count": quant_state.get("yolo_run_count", 0), "baseline_run_id": baseline_run_id, "baseline_complete": bool(baseline_run_id), "baseline_artifacts": quant_state.get("yolo_baseline_artifacts", {}), "missing_baseline_artifacts": quant_state.get("yolo_missing_baseline_artifacts", []), "baseline_snapshot_dir": quant_state.get("yolo_baseline_snapshot_dir", ""), }, "current_agent": ({"role": current["role"], "label": current["label"]} if current else {}), "blocked": ({ "agent": blocked["agent"], "label": blocked["label"], "reason": blocked.get("error") or ( "Blocked by " + ", ".join(blocked.get("blocked_by") or []) ), } if blocked else {}), "path": path_rows, "messages": messages, "finley": finley, "committee": _strategist_committee_payload(session.session_dir, quant_state), "options_context": options_context, "diagnostics": diagnostics, "proposal_state": proposal_state, "routing": routing, "permissions": permissions, "artifact_inventory": ( [item.model_dump(mode="json") for item in record.artifact_inventory] if record else [] ), "run_status_message": run.get("status_message", ""), "error": run.get("error", "") or (blocked.get("error", "") if blocked else ""), } def _typed_agent_references( session_dir: Path, artifact_ref: dict[str, Any] | None, ) -> dict[str, list[dict[str, Any]]]: """Read exact current and baseline references from one published output.""" empty = {"input_refs": [], "baseline_refs": []} if not artifact_ref or not artifact_ref.get("path"): return empty path = session_dir / str(artifact_ref["path"]) try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return empty return { "input_refs": list(data.get("input_refs") or []), "baseline_refs": list(data.get("baseline_refs") or []), } def _typed_options_context(session_dir: Path, run_id: str) -> dict[str, Any]: path = session_dir / "quant" / "runs" / run_id / "options_flow.json" if not path.exists(): return {"status": "missing", "summary": "No options context artifact for this run."} try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: return {"status": "data_gap", "summary": f"Options artifact could not be read: {exc}"} status = str(data.get("status") or "UNAVAILABLE") gaps = data.get("data_gaps") or [] summary = json.dumps({ "status": status, "ticker_scope": data.get("ticker_scope") or [], "data_gaps": gaps, "payload": data.get("payload") or {}, }, indent=2) return {"status": "ok" if status == "COMPLETE" else "data_gap", "summary": summary} def _typed_finley(session_dir: Path, run_id: str) -> dict[str, Any] | None: path = session_dir / "quant" / "runs" / run_id / "post.json" if not path.exists(): return None try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return None payload = data.get("payload") or {} content = str(payload.get("slack_rendering") or "") if not content: return None return { "from_role": "publisher", "content": content, "timestamp": data.get("created_at") or "", } def _typed_diagnostics(session_dir: Path, path_rows: list[dict[str, Any]]) -> dict[str, Any]: issues = [] for row in path_rows: if row["status"] in {"failed", "blocked"}: detail = row.get("error") or ( "Blocked by " + ", ".join(row.get("blocked_by") or []) ) issue_status = row["status"] if row["status"] == "failed" and "API request timed out" in detail: issue_status = "llm_timeout" issues.append({ "agent": row["agent"], "label": row["label"], "severity": "blocked", "status": issue_status, "detail": detail, }) elif row.get("result_status") == "UNAVAILABLE" and row.get("artifact_ref"): artifact = session_dir / row["artifact_ref"]["path"] gaps = [] try: gaps = json.loads(artifact.read_text(encoding="utf-8")).get("data_gaps") or [] except (OSError, json.JSONDecodeError): pass issues.append({ "agent": row["agent"], "label": row["label"], "severity": "warning", "status": "data_gap", "detail": "; ".join(str(gap.get("message") or gap) for gap in gaps) or "Agent completed with unavailable evidence.", }) summary = "No YOLO pipeline issues detected." if issues: summary = f"{issues[0]['label']}: {issues[0]['detail']}" return {"summary": summary, "issues": issues} def _typed_proposal_state( session_dir: Path, run_id: str, path_rows: list[dict[str, Any]], ) -> dict[str, Any]: strategy_path = session_dir / "quant" / "runs" / run_id / "trade_proposals.json" post_path = session_dir / "quant" / "runs" / run_id / "post.json" if strategy_path.exists(): try: strategy = json.loads(strategy_path.read_text(encoding="utf-8")) payload = strategy.get("payload") or {} outcome = str(payload.get("outcome") or "ANALYSIS_UNAVAILABLE") proposals = payload.get("proposals") or [] paper_proposals = [item for item in proposals if "direction" in item] decision_proposals = [item for item in proposals if "outcome" in item] reason = None if post_path.exists(): reason = (json.loads(post_path.read_text(encoding="utf-8")).get("payload") or {}).get( "no_proposal_reason" ) return { "status": outcome.lower(), "label": outcome.replace("_", " ").title(), "detail": ( f"{len(paper_proposals)} paper trade proposal(s) are ready for human review." if paper_proposals else f"{len(decision_proposals)} explicit {outcome} decision proposal(s)." if decision_proposals else f"No proposal: {reason or outcome}." ), "proposal_count": len(proposals), "no_proposal_reason": reason, } except (OSError, json.JSONDecodeError): pass pending = next( (row for row in path_rows if row["agent"] in {"QuantStrategist", "Publisher"} and row["status"] != "completed"), None, ) return { "status": "agent_pending", "label": "Agent Pending", "detail": ( f"No proposal decision yet: {pending['label']} is {pending['status']}." if pending else "No typed strategy artifact is available for this run." ), "proposal_count": 0, } def _resolve_permission_paths( templates: dict[str, list[str]], *, run_id: str, baseline_run_id: str | None, tickers: list[str], ) -> dict[str, list[str]]: resolved: dict[str, list[str]] = {} for operation, paths in templates.items(): values = [] for template in paths: selected_run = baseline_run_id if operation.startswith("baseline_") else run_id if not selected_run and ("{run_id}" in template or "{baseline_run_id}" in template): continue path = template.replace("{run_id}", selected_run or "").replace( "{baseline_run_id}", selected_run or "", ) if "{ticker}" in path: values.extend(path.replace("{ticker}", ticker) for ticker in tickers) else: values.append(path) resolved[operation] = values return resolved def _messages_since(messages: list[dict[str, Any]], started_at: str) -> list[dict[str, Any]]: try: started = datetime.fromisoformat(started_at) except ValueError: return messages filtered: list[dict[str, Any]] = [] for message in messages: ts = str(message.get("timestamp") or "") try: if datetime.fromisoformat(ts) >= started: filtered.append(message) except ValueError: filtered.append(message) return filtered def _yolo_mode_label(quant_state: dict[str, Any]) -> str: mode = quant_state.get("yolo_run_mode", "") if mode == "session_delta": return "Session-delta YOLO" if mode == "baseline": return "Baseline YOLO" return "YOLO" def _first_blocker(messages: list[dict[str, Any]]) -> dict[str, str] | None: for message in messages: content = str(message.get("content", "")) role = str(message.get("from_role", "agent")) if content.startswith("Skipped —"): return {"role": role, "message": content} if "ohlcv fetch failed for all tickers" in content.lower(): return { "role": role, "message": ( "@datafetcher could not produce OHLCV history, so TrendAnalyst " "and the LLM analysis pipeline cannot run." ), } if _is_unavailable_llm_content(content): detail = _llm_unavailable_detail(content) detail_suffix = f": {detail}" if detail else "." return { "role": role, "message": ( f"@{role} could not run because the configured LLM service is unavailable" f"{detail_suffix}" ), } return None def _is_unavailable_llm_content(content: str) -> bool: lowered = content.lower() return ( "llm unavailable" in lowered or "llm service is unavailable" in lowered or "llm service is not available" in lowered or "llm unavailable — fallback" in lowered ) def _llm_unavailable_detail(content: str) -> str: match = re.search(r"LLM unavailable(?::\s*([^)]+))?\)", content, re.IGNORECASE) if not match: return "" return (match.group(1) or "").strip() def _yolo_diagnostics( session_dir: Path, messages: list[dict[str, Any]], *, blocker: dict[str, str] | None, options_context: dict[str, Any], ) -> dict[str, Any]: issues: list[dict[str, str]] = [] if blocker: role = blocker.get("role", "") blocker_detail = blocker.get("message", "") blocker_status = "llm_unavailable" if _is_unavailable_llm_content(blocker_detail) else "blocked" issues.append({ "agent": role, "label": _diagnostic_label(role), "severity": "blocked", "status": blocker_status, "detail": blocker_detail, }) data_issue = _latest_raw_data_quality_issue(session_dir) if data_issue: issues.append(data_issue) if options_context.get("status") == "data_gap": issues.append({ "agent": "optionsflowwatcher", "label": _diagnostic_label("optionsflowwatcher"), "severity": "warning", "status": "data_gap", "detail": _options_issue_detail( str(options_context.get("summary") or ""), fallback="Options evidence was excluded or incomplete.", ), }) for message in messages: content = str(message.get("content", "")) role = str(message.get("from_role", "agent")) if _is_unavailable_llm_content(content): if any( issue.get("agent") == role and issue.get("status") == "llm_unavailable" for issue in issues ): continue issues.append({ "agent": role, "label": _diagnostic_label(role), "severity": "blocked", "status": "llm_unavailable", "detail": f"@{role} could not complete because the configured LLM was unavailable.", }) deduped: list[dict[str, str]] = [] seen: set[tuple[str, str, str]] = set() for issue in issues: key = (issue.get("agent", ""), issue.get("status", ""), issue.get("detail", "")) if key in seen: continue seen.add(key) deduped.append(issue) summary = "No YOLO pipeline issues detected." if deduped: first = deduped[0] summary = f"{first['label']}: {first['detail']}" return {"summary": summary, "issues": deduped} def _proposal_state( session_dir: Path, *, status: str, path: list[dict[str, str]], current_agent: dict[str, str], diagnostics: dict[str, Any], ) -> dict[str, Any]: proposals_md = _latest_artifact_text(session_dir, "quant/trade_proposals_") parsed_proposals: list[dict[str, Any]] = [] if proposals_md: from polyhedra.agents.quant.routing import parse_proposals_block parsed_proposals = parse_proposals_block(proposals_md) if parsed_proposals: return { "status": "paper_trade_suggestion", "label": "Paper Trade Suggestion", "detail": f"{len(parsed_proposals)} paper trade proposal(s) are ready for human review.", "proposal_count": len(parsed_proposals), } quant_step = next((step for step in path if step.get("role") == "quantstrategist"), {}) publisher_step = next((step for step in path if step.get("role") == "publisher"), {}) quant_done = quant_step.get("status") == "completed" publisher_done = publisher_step.get("status") == "completed" if not quant_done: agent = current_agent.get("label") or _first_incomplete_label(path) or "YOLO" return { "status": "agent_pending", "label": "Agent Pending", "detail": ( f"No proposal decision yet: QuantStrategist has not completed. " f"Current/blocked stage: {agent}." ), "proposal_count": 0, } data_issue = _first_data_loss_issue(diagnostics) if data_issue is not None: return { "status": "data_loss", "label": "Data Loss", "detail": ( "No proposal was made because one or more evidence sources were " f"excluded or unavailable. {data_issue.get('label')}: {data_issue.get('detail')}" ), "proposal_count": 0, } outcome = _infer_no_proposal_outcome(proposals_md) if quant_done and publisher_done: return { "status": "true_no_trade_or_watch", "label": "True No-Trade / Watch", "detail": ( f"QuantStrategist completed and produced zero paper trades. " f"Outcome: {outcome}." ), "proposal_count": 0, } return { "status": "agent_pending", "label": "Agent Pending", "detail": "QuantStrategist has produced no structured proposal yet; waiting for Finley/publisher completion.", "proposal_count": 0, } def _first_incomplete_label(path: list[dict[str, str]]) -> str: for step in path: if step.get("status") != "completed": return step.get("label", "") return "" def _first_data_loss_issue(diagnostics: dict[str, Any]) -> dict[str, str] | None: for issue in diagnostics.get("issues") or []: if issue.get("status") in {"data_gap", "provider_partial_data"}: return issue return None def _infer_no_proposal_outcome(proposals_md: str) -> str: upper = proposals_md.upper() if "WATCH_FOR_CONFIRMATION" in upper: return "WATCH_FOR_CONFIRMATION" if "NO_TRADE" in upper: return "NO_TRADE" return "ZERO_PROPOSALS" def _latest_raw_data_quality_issue(session_dir: Path) -> dict[str, str] | None: raw_dir = session_dir / "quant" / "raw" if not raw_dir.exists(): return None summaries = sorted(raw_dir.glob("*_summary.md")) for path in reversed(summaries): text = path.read_text(encoding="utf-8", errors="replace") if "## Data Quality" not in text: continue section = text.split("## Data Quality", 1)[1].split("\n## ", 1)[0] lines = [line.strip(" -") for line in section.splitlines() if line.strip()] status_line = next((line for line in lines if line.startswith("OHLCV status:")), "") if "provider_partial_data" not in status_line: continue detail_parts = [line for line in lines if not line.startswith("OHLCV status:")][:4] detail = "; ".join(detail_parts) or "Provider returned partial OHLCV rows; invalid rows were excluded." return { "agent": "datafetcher", "label": _diagnostic_label("datafetcher"), "severity": "warning", "status": "provider_partial_data", "detail": detail, } return None def _first_meaningful_line(text: str, *, fallback: str) -> str: for line in text.splitlines(): stripped = line.strip() if stripped and not stripped.startswith("#"): return stripped return fallback def _options_issue_detail(text: str, *, fallback: str) -> str: for line in text.splitlines(): stripped = line.strip(" -") upper = stripped.upper() if "DATA_GAP" in upper or "ERROR" in upper: return stripped for line in text.splitlines(): stripped = line.strip(" -") if "UNAVAILABLE" in stripped.upper(): return stripped for line in text.splitlines(): stripped = line.strip(" -") if ( stripped and not stripped.startswith("#") and "paper trading simulation" not in stripped.lower() and not stripped.lower().startswith("symbols:") ): return stripped return fallback def _diagnostic_label(role: str) -> str: labels = { "datafetcher": "DataFetcher", "trendanalyst": "TrendAnalyst", "sentimentanalyst": "SentimentAnalyst", "marketeventwatcher": "MarketEventWatcher", "optionsflowwatcher": "OptionsFlowWatcher", "macrocontextwatcher": "MacroContextWatcher", "unusualeventdetector": "UnusualEventDetector", "eventrouter": "EventRouter", "btcanalyst": "BTCAnalyst", "spyanalyst": "SPYAnalyst", "qqqanalyst": "QQQAnalyst", "gldanalyst": "GLDAnalyst", "quantresearcher": "QuantResearcher", "backtester": "Backtester", "riskanalyst": "RiskAnalyst", "quantstrategist": "QuantStrategist", "publisher": "Finley", } return labels.get(role, role or "YOLO") def _latest_artifact_text(session_dir: Path, prefix: str) -> str: quant_dir = session_dir / "quant" if not quant_dir.exists(): return "" name_prefix = prefix.split("/")[-1] matches = sorted( path for path in quant_dir.iterdir() if path.is_file() and path.name.startswith(name_prefix) ) if not matches: return "" return matches[-1].read_text(encoding="utf-8", errors="replace") def _summarize_options_artifact(text: str) -> dict[str, Any]: if not text: return {"status": "missing", "summary": "No options context artifact yet."} status = "ok" if "## OPTIONS_MARKET_CONTEXT" in text and "DATA_GAP" not in text else "data_gap" excerpt = "\n".join(line for line in text.splitlines() if line.strip())[:1200] return {"status": status, "summary": excerpt} def _strategist_committee_payload(session_dir: Path, quant_state: dict[str, Any]) -> dict[str, Any]: artifact_path = session_dir / "quant" / "strategist_performance.json" artifact_payload: dict[str, Any] = {} if artifact_path.exists(): try: artifact_payload = json.loads(artifact_path.read_text(encoding="utf-8")) except json.JSONDecodeError: artifact_payload = {} votes = list( quant_state.get("strategist_committee_votes") or artifact_payload.get("vote_history") or [] ) weights = dict( quant_state.get("strategist_committee_weights") or artifact_payload.get("weights") or {} ) updates = list( quant_state.get("strategist_weight_updates") or artifact_payload.get("weight_updates") or [] ) return { "votes": votes, "weights": weights, "aggregation": dict(artifact_payload.get("latest_aggregation") or {}), "weight_updates": updates, "artifact_path": "quant/strategist_performance.json" if artifact_payload else "", } def _resolve_session_tickers(session: Any, raw_tickers: Any = "") -> list[str]: if isinstance(raw_tickers, list): ticker_text = " ".join(str(item) for item in raw_tickers) else: ticker_text = str(raw_tickers or "") tickers = _extract_ui_tickers(ticker_text) if tickers: return tickers quant_state = _quant_state_payload(session) watchlist = quant_state.get("watchlist") or [] return [str(t).upper() for t in watchlist if str(t).strip()] async def _start_yolo_run_for_session( session: Any, *, tickers: list[str], goal: str, ) -> dict[str, Any]: from polyhedra.agents.coordinator import CheckpointResult, CoordinatorService _seed_quant_watchlist(session, tickers) run_state: dict[str, Any] = { "session_id": session.session_id, "run_id": datetime.now(tz=UTC).strftime("%Y%m%d_%H%M%S"), "status": "pending", "started_at": datetime.now(tz=UTC).isoformat(), "tickers": tickers, "messages": [], "status_message": "", "error": "", "runtime_schema": "8.0", } _RUNS[session.session_id] = run_state async def post_fn(from_role: str, content: str) -> None: run_state["messages"].append({ "from_role": from_role, "content": content, "timestamp": datetime.now(tz=UTC).isoformat(), }) async def checkpoint_fn(summary: str) -> CheckpointResult: run_state["messages"].append({ "from_role": "coordinator", "content": f"Checkpoint auto-approved for YOLO UI run: {summary}", "timestamp": datetime.now(tz=UTC).isoformat(), }) return CheckpointResult(approved=True) async def yolo_update_fn(status_text: str) -> None: run_state["status_message"] = status_text run_state["agent_states"] = dict(getattr(service, "_typed_yolo_states", {})) run_state["agent_times"] = dict(getattr(service, "_typed_yolo_times", {})) run_state["messages"].append({ "from_role": "coordinator", "content": status_text, "timestamp": datetime.now(tz=UTC).isoformat(), }) service = CoordinatorService( session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn, mode="yolo", yolo_update_fn=yolo_update_fn, ) context = service.prepare_yolo_run(tickers) run_state["run_id"] = context.run_id run_state["run_mode"] = context.run_mode run_state["run_mode_label"] = context.label async def run_pipeline() -> None: run_state["status"] = "running" try: if not session.full_thread(): await service.initialize_session( goal=goal, selected_roles=session.active_roles or list(session.registry.roles()), human_roles=[], ) result = await service.run_yolo(tickers) run_state["run_id"] = result.record.run_id run_state["status"] = result.record.status.value run_state["typed_record"] = result.record.model_dump(mode="json") except Exception as exc: from polyhedra.services.error_sanitizer import sanitize_exception safe_error = sanitize_exception(exc) logger.error("UI YOLO run failed: %s", safe_error) run_state["status"] = "failed" run_state["error"] = safe_error payload = _session_payload(session.session_id) if payload is not None: _persist_yolo_run_record(session.session_id, payload) task = asyncio.create_task(run_pipeline()) _RUN_TASKS.add(task) task.add_done_callback(_RUN_TASKS.discard) return run_state async def _wait_for_yolo_terminal(session_id: str, timeout_seconds: int = 600) -> None: """Wait until the session reaches Finley, blocks, fails, or idles out.""" run = _RUNS.get(session_id, {}) deadline = time.monotonic() + timeout_seconds last_count = -1 idle_ticks = 0 while time.monotonic() < deadline: payload = _session_payload(session_id) if payload is None: run["status"] = "failed" run["error"] = "Session disappeared before the YOLO run completed." return if payload["status"] in {"completed", "blocked", "failed"}: run["status"] = payload["status"] _persist_yolo_run_record(session_id, payload) return count = len(payload.get("messages", [])) if count == last_count: idle_ticks += 1 else: last_count = count idle_ticks = 0 if idle_ticks >= 180: run["status"] = "blocked" run["error"] = "No agent progress for three minutes; inspect the session or Slack logs." payload = _session_payload(session_id) if payload is not None: _persist_yolo_run_record(session_id, payload) return await asyncio.sleep(1) run["status"] = "blocked" run["error"] = "Timed out waiting for Finley to post the final YOLO output." payload = _session_payload(session_id) if payload is not None: _persist_yolo_run_record(session_id, payload) def _persist_yolo_run_record(session_id: str, payload: dict[str, Any]) -> None: from polyhedra.core.session import SessionManager from polyhedra.services.evidence_ledger import write_evidence_ledger session = SessionManager().resume(session_id) if session is None: return run = _RUNS.get(session_id, {}) run_id = str(payload.get("run_id") or run.get("run_id") or datetime.now(tz=UTC).strftime("%Y%m%d_%H%M%S")) existing = session.session_dir / _YOLO_RUNS_DIR / f"{run_id}.json" if existing.exists(): try: from polyhedra.services.quant_run_record import QuantRunRecord QuantRunRecord.model_validate_json(existing.read_text(encoding="utf-8"), strict=True) return except Exception: pass payload["run_id"] = run_id payload["replay_label"] = "Prior YOLO run replay - UI-only, not deterministic/frozen replay." payload["recorded_at"] = datetime.now(tz=UTC).isoformat() ticker_scope = _extract_ui_tickers(session.goal) if run.get("tickers"): ticker_scope = [str(t).upper() for t in run.get("tickers") or []] ledger_paths = write_evidence_ledger( session.session_dir, run_id=run_id, session_id=session_id, ticker_scope=ticker_scope, diagnostics=payload.get("diagnostics") or {}, proposal_state=payload.get("proposal_state") or {}, ) payload["evidence_ledger"] = ledger_paths record_dir = session.session_dir / _YOLO_RUNS_DIR record_dir.mkdir(parents=True, exist_ok=True) (record_dir / f"{run_id}.json").write_text( json.dumps(payload, indent=2), encoding="utf-8", ) def _list_yolo_run_records(session_id: str) -> list[dict[str, Any]]: from polyhedra.core.session import SessionManager session = SessionManager().resume(session_id) if session is None: raise FileNotFoundError(session_id) record_dir = session.session_dir / _YOLO_RUNS_DIR if not record_dir.exists(): return [] records: list[dict[str, Any]] = [] for path in sorted(record_dir.glob("*.json"), reverse=True): try: data = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: continue is_typed = data.get("schema_version") == "8.0" and "routing_plan" in data records.append({ "run_id": data.get("run_id") or path.stem, "status": data.get("status", ""), "run_mode": data.get("run_mode", ""), "run_mode_label": data.get("run_mode_label", "") or ( "Session-delta YOLO" if data.get("run_mode") == "DELTA" else "Baseline YOLO" ), "goal": data.get("goal", "") or session.goal, "recorded_at": data.get("recorded_at", "") or data.get("completed_at", ""), "proposal_state": data.get("proposal_state", {}), "replay_label": data.get("replay_label", "") or ( "Prior typed YOLO run replay - UI-only." if is_typed else "" ), "schema_version": data.get("schema_version", "legacy"), }) return records def _yolo_run_record(session_id: str, run_id: str) -> dict[str, Any]: from polyhedra.core.session import SessionManager session = SessionManager().resume(session_id) if session is None: raise FileNotFoundError(session_id) path = session.session_dir / _YOLO_RUNS_DIR / f"{run_id}.json" if not path.exists(): raise FileNotFoundError(run_id) raw = path.read_text(encoding="utf-8") data = json.loads(raw) if data.get("schema_version") == "8.0" and "routing_plan" in data: from polyhedra.services.quant_run_record import QuantRunRecord record = QuantRunRecord.model_validate_json(raw, strict=True) data = _typed_session_payload(session, { "runtime_schema": "8.0", "session_id": session_id, "run_id": run_id, "status": record.status.value, "tickers": list(record.ticker_scope), "typed_record": record.model_dump(mode="json"), "messages": [], "status_message": "", "error": "", }) data["replay"] = True data["replay_label"] = data.get("replay_label") or "Prior YOLO run replay - UI-only." return data def create_app(): """Build and return the FastAPI application.""" if FastAPI is None: raise ImportError("fastapi is required: pip install fastapi uvicorn") app = FastAPI( title="Polyhedra", description="Governed multi-agent quant analysis system", version="8.0.0", ) @app.get("/health", tags=["ops"]) async def health() -> dict: """Liveness probe.""" from polyhedra import __version__ return {"status": "ok", "service": "polyhedra", "version": __version__} @app.get("/ping", tags=["ops"]) async def ping() -> dict: """Simple reachability probe.""" return {"ok": True} @app.get("/", tags=["web"]) async def web_index() -> HTMLResponse: index = _WEB_STATIC_DIR / "index.html" if not index.exists(): return HTMLResponse("

Polyhedra

UI asset missing.

", status_code=500) return HTMLResponse(index.read_text(encoding="utf-8")) @app.get("/api/health", tags=["web"]) async def api_health() -> JSONResponse: """Health endpoint for the quant workspace UI.""" from polyhedra import __version__ return JSONResponse({ "status": "ok", "service": "polyhedra", "version": __version__, "ui": "v8.0-quant-workspace", "llm": _llm_config_status(), }) @app.post("/api/provider-smoke", tags=["web"]) async def api_provider_smoke(request: Request) -> JSONResponse: """Run read-only live checks for the selected YOLO provider surfaces.""" from polyhedra.services.provider_smoke import run_provider_smoke try: body = await request.json() except Exception: body = {} ticker = str(body.get("ticker", "")).strip().upper() if not re.fullmatch(r"[A-Z]{1,5}", ticker): return JSONResponse({"error": "Enter one valid ticker."}, status_code=400) return JSONResponse(await run_provider_smoke(ticker)) @app.get("/api/sessions", tags=["web"]) async def api_sessions() -> JSONResponse: from polyhedra.core.session import SessionManager sessions = sorted( SessionManager().list_sessions(), key=lambda item: item.get("created_at", ""), reverse=True, ) return JSONResponse({"sessions": sessions[:50]}) @app.post("/api/yolo", tags=["web"]) async def api_yolo(request: Request) -> JSONResponse: try: body = await request.json() except Exception: body = {} raw_tickers = body.get("tickers", "") if isinstance(raw_tickers, list): ticker_text = " ".join(str(item) for item in raw_tickers) else: ticker_text = str(raw_tickers) tickers = _extract_ui_tickers(ticker_text) if not tickers: return JSONResponse({"error": "Enter at least one ticker."}, status_code=400) llm_status = _llm_config_status() if not llm_status["configured"]: return JSONResponse( { "error": "YOLO requires a configured LLM provider.", "llm": llm_status, }, status_code=503, ) from polyhedra.core.session import SessionManager goal = f"YOLO & {' | '.join(tickers)} Analysis Session" session = SessionManager().create(goal=goal, platform="web") _register_quant_agents(session) await _start_yolo_run_for_session(session, tickers=tickers, goal=goal) return JSONResponse( _session_payload(session.session_id) or {"session_id": session.session_id}, status_code=202, ) @app.post("/api/sessions/{session_id}/yolo", tags=["web"]) async def api_session_yolo(session_id: str, request: Request) -> JSONResponse: try: body = await request.json() except Exception: body = {} llm_status = _llm_config_status() if not llm_status["configured"]: return JSONResponse( { "error": "YOLO requires a configured LLM provider.", "llm": llm_status, }, status_code=503, ) from polyhedra.core.session import SessionManager session = SessionManager().resume(session_id) if session is None: return JSONResponse({"error": "Session not found."}, status_code=404) _register_quant_agents(session) tickers = _resolve_session_tickers(session, body.get("tickers", "")) if not tickers: return JSONResponse({"error": "Session has no ticker watchlist."}, status_code=400) await _start_yolo_run_for_session(session, tickers=tickers, goal=session.goal) return JSONResponse( _session_payload(session.session_id) or {"session_id": session.session_id}, status_code=202, ) @app.get("/api/sessions/{session_id}", tags=["web"]) async def api_session(session_id: str) -> JSONResponse: payload = _session_payload(session_id) if payload is None: return JSONResponse({"error": "Session not found."}, status_code=404) return JSONResponse(payload) @app.get("/api/sessions/{session_id}/events", tags=["web"]) async def api_session_events(session_id: str) -> JSONResponse: payload = _session_payload(session_id) if payload is None: return JSONResponse({"error": "Session not found."}, status_code=404) return JSONResponse({ "session_id": session_id, "status": payload["status"], "run_mode": payload["run_mode"], "run_mode_label": payload["run_mode_label"], "yolo_context": payload["yolo_context"], "current_agent": payload["current_agent"], "blocked": payload["blocked"], "path": payload["path"], "messages": payload["messages"], "finley": payload["finley"], "committee": payload["committee"], "options_context": payload["options_context"], "diagnostics": payload["diagnostics"], "proposal_state": payload["proposal_state"], "run_status_message": payload["run_status_message"], "error": payload["error"], }) @app.get("/api/sessions/{session_id}/runs", tags=["web"]) async def api_session_runs(session_id: str) -> JSONResponse: try: runs = _list_yolo_run_records(session_id) except FileNotFoundError: return JSONResponse({"error": "Session not found."}, status_code=404) return JSONResponse({"session_id": session_id, "runs": runs}) @app.get("/api/sessions/{session_id}/runs/{run_id}", tags=["web"]) async def api_session_run_detail(session_id: str, run_id: str) -> JSONResponse: try: payload = _yolo_run_record(session_id, run_id) except FileNotFoundError: return JSONResponse({"error": "Run not found."}, status_code=404) return JSONResponse(payload) @app.post("/api/sessions/{session_id}/visualizations", tags=["web"]) async def api_session_visualization(session_id: str, request: Request) -> JSONResponse: """Render one typed chart from the selected frozen YOLO run.""" try: body = await request.json() except Exception: body = {} llm_status = _llm_config_status() if not llm_status["configured"]: return JSONResponse( {"error": "Visualization captions require a configured LLM provider."}, status_code=503, ) from polyhedra.agents.coordinator import CheckpointResult, CoordinatorService from polyhedra.core.session import SessionManager session = SessionManager().resume(session_id) if session is None: return JSONResponse({"error": "Session not found."}, status_code=404) _register_quant_agents(session) messages: list[dict[str, str]] = [] async def post_fn(from_role: str, content: str) -> None: messages.append({"from_role": from_role, "content": content}) async def checkpoint_fn(_summary: str) -> CheckpointResult: return CheckpointResult(approved=True) service = CoordinatorService( session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn, mode="investigation", ) try: result = await service.run_visualization( str(body.get("chart_type") or "").upper(), ticker=(str(body["ticker"]).upper() if body.get("ticker") else None), source_run_id=str(body.get("source_run_id") or "") or None, ) except (FileNotFoundError, ValueError, RuntimeError) as exc: return JSONResponse({"error": str(exc)}, status_code=422) if result.output is None: execution = result.record.execution.for_agent("VizAgent") return JSONResponse( {"error": execution.error or "VizAgent did not publish an output."}, status_code=422, ) charts = [ { **chart.model_dump(mode="json"), "image_url": ( f"/api/sessions/{session_id}/visualizations/" f"{result.record.run_id}/{Path(chart.image_ref.path).name}" ), } for chart in result.output.payload.charts ] return JSONResponse({ "run_id": result.record.run_id, "source_run_id": result.record.baseline_run_id, "status": result.output.status.value, "caption": result.output.payload.caption, "errors": [item.model_dump(mode="json") for item in result.output.payload.errors], "charts": charts, "messages": messages, }) @app.get( "/api/sessions/{session_id}/visualizations/{run_id}/{filename}", tags=["web"], ) async def api_session_visualization_image( session_id: str, run_id: str, filename: str, ): """Serve only a PNG declared by the selected visualization run record.""" from polyhedra.core.quant_contracts import ExecutionContext from polyhedra.core.session import SessionManager from polyhedra.services.quant_run_record import QuantSupportRunRecordStore if Path(filename).name != filename or not filename.endswith(".png"): return JSONResponse({"error": "Chart not found."}, status_code=404) session = SessionManager().resume(session_id) if session is None: return JSONResponse({"error": "Session not found."}, status_code=404) try: record = QuantSupportRunRecordStore( session.session_dir, session_id=session_id, ).load(run_id) except (FileNotFoundError, ValueError): return JSONResponse({"error": "Chart run not found."}, status_code=404) if record.execution_context != ExecutionContext.VISUALIZATION: return JSONResponse({"error": "Chart run not found."}, status_code=404) reference = next(( item for item in record.artifact_inventory if item.path.endswith(f"/viz/{filename}") and getattr(item, "format", None) == "PNG" ), None) if reference is None: return JSONResponse({"error": "Chart not found."}, status_code=404) path = session.session_dir / reference.path if not path.is_file(): return JSONResponse({"error": "Chart file is unavailable."}, status_code=404) return FileResponse(path, media_type="image/png", filename=filename) @app.get("/api/sessions/{session_id}/export", tags=["web"]) async def api_session_export(session_id: str): from polyhedra.core.session import SessionManager try: zip_path = SessionManager().export( session_id, Path(tempfile.gettempdir()) / "polyhedra_exports", ) except FileNotFoundError: return JSONResponse({"error": "Session not found."}, status_code=404) return FileResponse( zip_path, media_type="application/zip", filename=f"polyhedra-session-{session_id}.zip", ) # Try to initialise Bolt — optional, only works when secrets are set. _bolt_handler = None try: from slack_bolt.adapter.fastapi.async_handler import AsyncSlackRequestHandler from polyhedra.messaging.slack import SlackIntegration slack = SlackIntegration() if slack._app is not None: _bolt_handler = AsyncSlackRequestHandler(slack._app) logger.info("Slack Bolt handler initialised") except Exception as exc: from polyhedra.services.error_sanitizer import sanitize_error_text logger.warning("Slack Bolt init skipped: %s", sanitize_error_text(exc)) # Signing secret loaded at startup — used for manual HMAC check below. _signing_secret: str = os.environ.get("SLACK_SIGNING_SECRET", "") logger.info( "Slack signing secret %s", "configured" if _signing_secret else "not configured", ) # /slack/events is ALWAYS registered so Slack URL verification works # even before env-var secrets are confirmed live. @app.post("/slack/events") async def slack_events(request: Request) -> JSONResponse: raw = await request.body() # Starlette caches this; Bolt re-reads from cache # ── Diagnostic logging ────────────────────────────────────────── sig_header = request.headers.get("x-slack-signature", "") ts_header = request.headers.get("x-slack-request-timestamp", "") if not sig_header: logger.warning( "SLACK 401 CAUSE: x-slack-signature header is MISSING — " "proxy may be stripping it" ) if not ts_header: logger.warning( "SLACK 401 CAUSE: x-slack-request-timestamp header is MISSING — " "proxy may be stripping it" ) if ts_header: age = int(time.time()) - int(ts_header) if abs(age) > 300: logger.warning( "SLACK 401 CAUSE: timestamp is %d seconds old (>5 min). " "Check server clock — run 'w32tm /query /status' or 'date'.", age, ) else: logger.info("Slack request timestamp age: %d seconds (ok)", age) if sig_header and ts_header and _signing_secret: # Manually verify HMAC to confirm secret correctness before Bolt does it. base = f"v0:{ts_header}:{raw.decode()}".encode() expected = "v0=" + hmac.new(_signing_secret.encode(), base, hashlib.sha256).hexdigest() # type: ignore[attr-defined] if hmac.compare_digest(expected, sig_header): logger.info("Manual HMAC check: PASSED") else: logger.warning( "SLACK 401 CAUSE: HMAC mismatch — signing secret in .env does NOT match " "the Slack app dashboard. Copy the signing secret from " "https://api.slack.com/apps → Basic Information → App Credentials." ) # ─────────────────────────────────────────────────────────────── # Handle url_verification before Bolt (no HMAC check needed for handshake). try: body = json.loads(raw) except Exception: body = {} if body.get("type") == "url_verification": return JSONResponse({"challenge": body.get("challenge", "")}) # All other events go through Bolt, which does HMAC verification itself. if _bolt_handler is not None: return await _bolt_handler.handle(request) return JSONResponse({"ok": True}) @app.get("/debug/slack", tags=["ops"]) async def debug_slack() -> JSONResponse: """Diagnostic endpoint — shows signing-secret status and server time.""" secret = os.environ.get("SLACK_SIGNING_SECRET", "") return JSONResponse({ "signing_secret_set": bool(secret), "signing_secret_len": len(secret), "signing_secret_preview": ( f"{secret[:4]}…{secret[-4:]}" if len(secret) >= 8 else "" ), "bot_token_set": bool(os.environ.get("SLACK_BOT_TOKEN", "")), "server_epoch": int(time.time()), "bolt_handler_ready": _bolt_handler is not None, }) return app # Module-level instance consumed by uvicorn app = create_app()