1120 lines
40 KiB
Python
1120 lines
40 KiB
Python
"""Converged workflow-driven situational awareness, sessions, dynamic ViewSpec, watches, and stage presentations API."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import replace
|
|
from datetime import UTC, datetime
|
|
import hashlib
|
|
import json
|
|
import uuid
|
|
from typing import Any, Literal, Self
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
|
|
from fastapi.responses import StreamingResponse
|
|
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
from sqlalchemy import desc, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.api.v1.compute_intelligence import configuration_admin, selected_countries
|
|
from app.core.access_gate import require_earth_or_api_access
|
|
from app.db.session import get_db
|
|
from app.models.situational_assessment import (
|
|
ComputeEvidenceCandidate,
|
|
EvidenceRecord,
|
|
InvestigationSession,
|
|
TopicWatch,
|
|
WorkflowRun,
|
|
)
|
|
from app.models.system_log import AuditLog
|
|
from app.models.user import User
|
|
from app.schemas.compute_configuration import ComputeConfiguration, source_for
|
|
from app.services.compute_configuration import read_configuration
|
|
from app.services.compute_history import MODE_DENOMINATOR, ComputeSeriesMode
|
|
from app.services.ai.access_policy import (
|
|
AccessContext,
|
|
enforce_paid_research_gate,
|
|
enforce_resource_ownership,
|
|
ensure_session_owner_identity,
|
|
resolve_access_context,
|
|
)
|
|
from app.services.ai.copilot_agent import (
|
|
export_revision_bound_markdown_report,
|
|
run_contextual_copilot,
|
|
)
|
|
from app.services.ai.domain_catalog import ReportSubjectType, WorkbenchDomain
|
|
from app.services.ai.posture_agent import generate_or_get_compute_posture
|
|
from app.services.ai.presentation_compiler import (
|
|
get_or_compile_presentation_by_key,
|
|
list_or_compile_presentations,
|
|
)
|
|
from app.services.ai.proactive_pipeline import (
|
|
audit_situational_hygiene,
|
|
process_bgp_snapshot_proactive_delta,
|
|
retry_pending_compute_presentations,
|
|
)
|
|
from app.services.ai.semantic_delta import extract_compute_candidates_deterministic
|
|
from app.services.ai.tool_registry import TimeBasis, query_compute_posture_tool
|
|
from app.services.ai.workflow_runtime import (
|
|
ViewPreset,
|
|
cancel_active_run_handle,
|
|
execute_session_turn,
|
|
get_active_run_handle,
|
|
read_frozen_result_revision,
|
|
)
|
|
from app.services.ai.stream_turn import stream_session_turn
|
|
from app.services.ai_client import AIProviderClient, get_ai_provider_client
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
class SessionCreateRequest(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
domain: WorkbenchDomain = "compute"
|
|
selected_codes: list[str] = Field(default_factory=lambda: ["CN", "US"], max_length=12)
|
|
mode: ComputeSeriesMode = "global_share"
|
|
focus_year: int | None = Field(default=None, ge=2000, le=2100)
|
|
entity_id: str | None = Field(default=None, max_length=160)
|
|
visible_layers: dict[str, bool] = Field(default_factory=dict)
|
|
time_basis: TimeBasis = "retrospective"
|
|
cutoff_at: str | None = Field(default=None, max_length=40)
|
|
publish_id: str | None = Field(default=None, max_length=64)
|
|
as_of: str | None = Field(default=None, max_length=64)
|
|
include_drill: bool = False
|
|
|
|
|
|
class SessionPinUpdateRequest(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
pinned_items: list[dict[str, Any]] = Field(default_factory=list, max_length=12)
|
|
|
|
|
|
class HistoryMessageItem(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
role: Literal["user", "assistant"]
|
|
content: str = Field(min_length=1, max_length=6000)
|
|
|
|
|
|
class EarthTargetItem(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
entity_type: str = Field(min_length=1, max_length=64)
|
|
entity_id: str | None = Field(default=None, max_length=160)
|
|
label: str = Field(default="", max_length=200)
|
|
latitude: float | None = None
|
|
longitude: float | None = None
|
|
layer: str | None = Field(default=None, max_length=80)
|
|
kind: str | None = Field(default=None, max_length=80)
|
|
properties: dict[str, Any] = Field(default_factory=dict)
|
|
|
|
|
|
class SessionTurnRequest(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
question: str = Field(min_length=2, max_length=1000)
|
|
workflow_id: str | None = Field(default=None, max_length=80, pattern=r"^[A-Za-z0-9_.-]+$")
|
|
targets: list[EarthTargetItem] = Field(default_factory=list, max_length=8)
|
|
domain: WorkbenchDomain | None = None
|
|
selected_codes: list[str] | None = Field(default=None, max_length=12)
|
|
mode: ComputeSeriesMode | None = None
|
|
focus_year: int | None = Field(default=None, ge=2000, le=2100)
|
|
entity_id: str | None = Field(default=None, max_length=160)
|
|
visible_layers: dict[str, bool] | None = None
|
|
time_basis: TimeBasis | None = None
|
|
cutoff_at: str | None = Field(default=None, max_length=40)
|
|
publish_id: str | None = Field(default=None, max_length=64)
|
|
as_of: str | None = Field(default=None, max_length=64)
|
|
include_drill: bool | None = None
|
|
preset: ViewPreset | None = None
|
|
prefer_llm: bool | Literal["auto"] = False
|
|
external_urls: list[str] = Field(default_factory=list, max_length=3)
|
|
news_context: dict[str, Any] | None = None
|
|
history: list[HistoryMessageItem] = Field(default_factory=list, max_length=40)
|
|
conversation_summary: str | None = Field(default=None, max_length=2400)
|
|
memory_notes: list[str] = Field(default_factory=list, max_length=12)
|
|
pinned_summaries: list[str] = Field(default_factory=list, max_length=8)
|
|
run_id: str | None = Field(default=None, min_length=4, max_length=64, pattern=r"^[A-Za-z0-9_-]+$")
|
|
|
|
|
|
class TopicWatchCreateRequest(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
watch_key: str = Field(min_length=2, max_length=160)
|
|
domain: WorkbenchDomain = "compute"
|
|
target_scope: dict[str, Any] = Field(default_factory=dict)
|
|
trigger_policy: dict[str, Any] = Field(default_factory=dict)
|
|
|
|
|
|
class ProactiveSnapshotTriggerRequest(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
domain: Literal["compute", "bgp"] = "bgp"
|
|
source: str = Field(default="ripe_ris", max_length=80)
|
|
record_count: int = Field(default=100, ge=0)
|
|
status: Literal["success", "failed"] = "success"
|
|
completed_at: str | None = None
|
|
error: str | None = None
|
|
|
|
|
|
class SpatialInvestigateRequest(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
domain: WorkbenchDomain = "compute"
|
|
selected_codes: list[str] = Field(default_factory=lambda: ["CN", "US"], max_length=12)
|
|
focus_year: int | None = Field(default=None, ge=2000, le=2100)
|
|
mode: ComputeSeriesMode = "global_share"
|
|
entity_id: str | None = Field(default=None, max_length=160)
|
|
visible_layers: dict[str, bool] = Field(default_factory=dict)
|
|
question: str = Field(min_length=2, max_length=1000)
|
|
time_basis: TimeBasis = "retrospective"
|
|
cutoff_at: str | None = Field(default=None, max_length=40)
|
|
publish_id: str | None = Field(default=None, max_length=64)
|
|
as_of: str | None = Field(default=None, max_length=64)
|
|
include_drill: bool = False
|
|
external_urls: list[str] = Field(default_factory=list, max_length=3)
|
|
|
|
|
|
class ReportExportRequest(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
subject_type: ReportSubjectType = "compute_posture"
|
|
countries: list[str] = Field(default_factory=lambda: ["CN", "US"], max_length=12)
|
|
mode: ComputeSeriesMode = "global_share"
|
|
incident_key: str | None = Field(default=None, max_length=160)
|
|
result_id: str | None = Field(default=None, max_length=255)
|
|
expected_revision: int | None = Field(default=None, ge=1)
|
|
time_basis: TimeBasis = "retrospective"
|
|
cutoff_at: str | None = Field(default=None, max_length=40)
|
|
|
|
|
|
APPROVE_REASON_CODES = frozenset(
|
|
{
|
|
"newer_authoritative_report",
|
|
"corrects_prior_error",
|
|
"adds_missing_observation",
|
|
"methodology_update",
|
|
}
|
|
)
|
|
REJECT_REASON_CODES = frozenset(
|
|
{
|
|
"unverifiable_source",
|
|
"denominator_mismatch",
|
|
"extraction_error",
|
|
"superseded",
|
|
"duplicate",
|
|
}
|
|
)
|
|
|
|
|
|
class CandidateExtractRequest(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
year: int = Field(ge=2000, le=2100)
|
|
excerpt: str = Field(min_length=5, max_length=5000)
|
|
source_id: str = Field(min_length=1, max_length=80)
|
|
source_title: str = Field(min_length=1, max_length=300)
|
|
source_url: str = Field(min_length=8, max_length=2000)
|
|
publisher: str = Field(default="Research Institute", max_length=200)
|
|
locator: str = Field(default="Extracted excerpt", max_length=300)
|
|
period_label: str | None = Field(default=None, max_length=40)
|
|
published_at: str | None = Field(default=None, max_length=40)
|
|
report_year: int | None = Field(default=None, ge=2000, le=2100)
|
|
|
|
|
|
class CandidateReviewRequest(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
decision: Literal["approved", "rejected"]
|
|
reason_code: Literal[
|
|
"newer_authoritative_report",
|
|
"corrects_prior_error",
|
|
"adds_missing_observation",
|
|
"methodology_update",
|
|
"unverifiable_source",
|
|
"denominator_mismatch",
|
|
"extraction_error",
|
|
"superseded",
|
|
"duplicate",
|
|
]
|
|
reason: str = Field(min_length=2, max_length=1000)
|
|
|
|
@model_validator(mode="after")
|
|
def matching_reason_code(self) -> Self:
|
|
allowed = APPROVE_REASON_CODES if self.decision == "approved" else REJECT_REASON_CODES
|
|
if self.reason_code not in allowed:
|
|
raise ValueError(
|
|
f"reason_code '{self.reason_code}' is not valid for decision '{self.decision}'"
|
|
)
|
|
return self
|
|
|
|
|
|
# ============================================================================
|
|
# Group 1 & 2: Continuous Workbench Sessions & Multi-Turn Execution
|
|
# ============================================================================
|
|
|
|
|
|
@router.post("/sessions")
|
|
async def create_investigation_session(
|
|
payload: SessionCreateRequest,
|
|
response: Response,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
codes = selected_countries(",".join(payload.selected_codes)) if payload.selected_codes else ["CN", "US"]
|
|
owner_key, issued_token = ensure_session_owner_identity(access, response)
|
|
session_id = f"sess-{uuid.uuid4().hex[:12]}"
|
|
context_state = {
|
|
"domain": payload.domain,
|
|
"selected_codes": codes,
|
|
"mode": payload.mode,
|
|
"focus_year": payload.focus_year,
|
|
"entity_id": payload.entity_id,
|
|
"visible_layers": dict(payload.visible_layers or {}),
|
|
"time_basis": payload.time_basis,
|
|
"cutoff_at": payload.cutoff_at,
|
|
"publish_id": payload.publish_id,
|
|
"as_of": payload.as_of,
|
|
"include_drill": payload.include_drill,
|
|
"active_result_id": None,
|
|
"active_revision": None,
|
|
"active_preset": "default",
|
|
"active_run_id": None,
|
|
}
|
|
record = InvestigationSession(
|
|
id=session_id,
|
|
domain=payload.domain,
|
|
owner_key=owner_key,
|
|
access_tier=access.tier,
|
|
context_state=context_state,
|
|
pinned_items=[],
|
|
)
|
|
if hasattr(db, "add") and hasattr(db, "commit"):
|
|
db.add(record)
|
|
await db.commit()
|
|
if hasattr(db, "refresh"):
|
|
await db.refresh(record)
|
|
out = record.to_dict()
|
|
if issued_token:
|
|
out["session_token"] = issued_token
|
|
return out
|
|
|
|
|
|
async def _load_owned_session_or_fail(
|
|
session_id: str,
|
|
access: AccessContext,
|
|
db: AsyncSession,
|
|
) -> InvestigationSession:
|
|
record = (
|
|
await db.execute(select(InvestigationSession).where(InvestigationSession.id == session_id))
|
|
).scalar_one_or_none()
|
|
if record is None:
|
|
if not access.has_session_credential:
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail=f"Authentication or valid session token required to access session: {session_id}",
|
|
)
|
|
raise HTTPException(status_code=404, detail=f"Session not found: {session_id}")
|
|
enforce_resource_ownership(record.owner_key, access, "session")
|
|
return record
|
|
|
|
|
|
@router.get("/sessions/{session_id}")
|
|
async def get_investigation_session(
|
|
session_id: str,
|
|
response: Response,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
response.headers["Cache-Control"] = "no-store"
|
|
record = await _load_owned_session_or_fail(session_id, access, db)
|
|
return record.to_dict()
|
|
|
|
|
|
@router.patch("/sessions/{session_id}/pins")
|
|
async def update_session_pins(
|
|
session_id: str,
|
|
payload: SessionPinUpdateRequest,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
record = await _load_owned_session_or_fail(session_id, access, db)
|
|
record.pinned_items = payload.pinned_items[:12]
|
|
await db.commit()
|
|
return record.to_dict()
|
|
|
|
|
|
@router.get("/sessions/{session_id}/runs")
|
|
async def list_session_runs(
|
|
session_id: str,
|
|
response: Response,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
response.headers["Cache-Control"] = "no-store"
|
|
session_row = await _load_owned_session_or_fail(session_id, access, db)
|
|
rows = (
|
|
(
|
|
await db.execute(
|
|
select(WorkflowRun)
|
|
.where(WorkflowRun.session_id == session_id)
|
|
.order_by(desc(WorkflowRun.started_at))
|
|
.limit(20)
|
|
)
|
|
)
|
|
.scalars()
|
|
.all()
|
|
)
|
|
active_run_id = (session_row.context_state or {}).get("active_run_id")
|
|
return {
|
|
"session_id": session_id,
|
|
"active_run_id": active_run_id,
|
|
"items": [r.to_dict() for r in rows],
|
|
}
|
|
|
|
|
|
@router.post("/sessions/{session_id}/turns")
|
|
async def create_session_turn(
|
|
session_id: str,
|
|
payload: SessionTurnRequest,
|
|
response: Response,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
ai_client: AIProviderClient = Depends(get_ai_provider_client),
|
|
) -> dict[str, Any]:
|
|
session_row: InvestigationSession | None = None
|
|
effective_access = access
|
|
issued_token: str | None = None
|
|
if session_id == "stateless":
|
|
owner_key, issued_token = ensure_session_owner_identity(access, response)
|
|
effective_access = replace(access, actor_key=owner_key, has_session_credential=True)
|
|
else:
|
|
session_row = await _load_owned_session_or_fail(session_id, access, db)
|
|
|
|
codes = (
|
|
selected_countries(",".join(payload.selected_codes))
|
|
if payload.selected_codes
|
|
else None
|
|
)
|
|
overrides = {
|
|
"domain": payload.domain,
|
|
"selected_codes": codes,
|
|
"mode": payload.mode,
|
|
"focus_year": payload.focus_year,
|
|
"entity_id": payload.entity_id,
|
|
"visible_layers": payload.visible_layers,
|
|
"time_basis": payload.time_basis,
|
|
"cutoff_at": payload.cutoff_at,
|
|
"publish_id": payload.publish_id,
|
|
"as_of": payload.as_of,
|
|
"include_drill": payload.include_drill,
|
|
}
|
|
turn_result = await execute_session_turn(
|
|
db,
|
|
session=session_row,
|
|
question=payload.question,
|
|
context_override=overrides,
|
|
explicit_preset=payload.preset,
|
|
prefer_llm=payload.prefer_llm,
|
|
external_urls=payload.external_urls or None,
|
|
access=effective_access,
|
|
ai_client=ai_client,
|
|
client_run_id=payload.run_id,
|
|
)
|
|
if hasattr(db, "commit"):
|
|
await db.commit()
|
|
if issued_token:
|
|
turn_result["session_token"] = issued_token
|
|
return turn_result
|
|
|
|
|
|
@router.post("/sessions/{session_id}/turns/stream")
|
|
async def stream_investigation_session_turn(
|
|
session_id: str,
|
|
payload: SessionTurnRequest,
|
|
request: Request,
|
|
response: Response,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
ai_client: AIProviderClient = Depends(get_ai_provider_client),
|
|
) -> StreamingResponse:
|
|
"""Adaptive SSE endpoint streaming LLM reasoning & answer when configured, else grounded baseline."""
|
|
session_row: InvestigationSession | None = None
|
|
effective_access = access
|
|
issued_token: str | None = None
|
|
if session_id == "stateless":
|
|
owner_key, issued_token = ensure_session_owner_identity(access, response)
|
|
effective_access = replace(access, actor_key=owner_key, has_session_credential=True)
|
|
else:
|
|
session_row = await _load_owned_session_or_fail(session_id, access, db)
|
|
|
|
codes = (
|
|
selected_countries(",".join(payload.selected_codes))
|
|
if payload.selected_codes
|
|
else None
|
|
)
|
|
overrides = {
|
|
"domain": payload.domain,
|
|
"selected_codes": codes,
|
|
"mode": payload.mode,
|
|
"focus_year": payload.focus_year,
|
|
"entity_id": payload.entity_id,
|
|
"visible_layers": payload.visible_layers,
|
|
"time_basis": payload.time_basis,
|
|
"cutoff_at": payload.cutoff_at,
|
|
"publish_id": payload.publish_id,
|
|
"as_of": payload.as_of,
|
|
"include_drill": payload.include_drill,
|
|
}
|
|
headers = {
|
|
"Cache-Control": "no-cache",
|
|
"X-Accel-Buffering": "no",
|
|
}
|
|
return StreamingResponse(
|
|
stream_session_turn(
|
|
db,
|
|
request=request,
|
|
session=session_row,
|
|
question=payload.question,
|
|
context_override=overrides,
|
|
news_context=payload.news_context,
|
|
history=[item.model_dump() for item in payload.history],
|
|
conversation_summary=payload.conversation_summary,
|
|
memory_notes=payload.memory_notes,
|
|
pinned_summaries=payload.pinned_summaries,
|
|
workflow_id=payload.workflow_id,
|
|
targets=[t.model_dump() for t in payload.targets],
|
|
access=effective_access,
|
|
ai_client=ai_client,
|
|
client_run_id=payload.run_id,
|
|
issued_session_token=issued_token,
|
|
),
|
|
media_type="text/event-stream",
|
|
headers=headers,
|
|
)
|
|
|
|
|
|
# ============================================================================
|
|
# Group 3: WorkflowRun Inspection & Explicit Cancellation
|
|
# ============================================================================
|
|
|
|
|
|
@router.get("/runs/{run_id}")
|
|
async def get_workflow_run(
|
|
run_id: str,
|
|
response: Response,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
response.headers["Cache-Control"] = "no-store"
|
|
active_handle = get_active_run_handle(run_id)
|
|
row = (
|
|
await db.execute(select(WorkflowRun).where(WorkflowRun.id == run_id))
|
|
).scalar_one_or_none()
|
|
if row is None and active_handle is None:
|
|
if not access.has_session_credential:
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail=f"Authentication or valid session token required to access run: {run_id}",
|
|
)
|
|
raise HTTPException(status_code=404, detail=f"WorkflowRun not found: {run_id}")
|
|
owner_key = active_handle.actor_key if active_handle is not None else row.actor_key
|
|
enforce_resource_ownership(owner_key, access, "workflow run")
|
|
if row is not None:
|
|
return row.to_dict()
|
|
return active_handle.to_dict()
|
|
|
|
|
|
@router.post("/runs/{run_id}/cancel")
|
|
async def cancel_workflow_run(
|
|
run_id: str,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
active_handle = get_active_run_handle(run_id)
|
|
row = (
|
|
await db.execute(select(WorkflowRun).where(WorkflowRun.id == run_id))
|
|
).scalar_one_or_none()
|
|
if row is None and active_handle is None:
|
|
if not access.has_session_credential:
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail=f"Authentication or valid session token required to cancel run: {run_id}",
|
|
)
|
|
raise HTTPException(status_code=404, detail=f"WorkflowRun not found: {run_id}")
|
|
|
|
owner_key = active_handle.actor_key if active_handle is not None else row.actor_key
|
|
enforce_resource_ownership(owner_key, access, "workflow run")
|
|
|
|
cancel_active_run_handle(run_id)
|
|
if row is not None:
|
|
if row.status in {"queued", "running"}:
|
|
row.status = "cancelled"
|
|
row.completed_at = datetime.now(UTC)
|
|
if row.session_id:
|
|
session_row = (
|
|
await db.execute(
|
|
select(InvestigationSession).where(InvestigationSession.id == row.session_id)
|
|
)
|
|
).scalar_one_or_none()
|
|
if session_row is not None:
|
|
curr_ctx = dict(session_row.context_state or {})
|
|
if curr_ctx.get("active_run_id") == run_id:
|
|
curr_ctx["active_run_id"] = None
|
|
session_row.context_state = curr_ctx
|
|
await db.commit()
|
|
return row.to_dict()
|
|
return active_handle.to_dict()
|
|
|
|
|
|
# ============================================================================
|
|
# Group 4: Frozen ResultRevision Read, Zero-Token View Projection & Export (R7)
|
|
# ============================================================================
|
|
|
|
|
|
@router.get(
|
|
"/results/{result_id:path}/revisions/{revision}",
|
|
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
|
|
)
|
|
async def get_frozen_result_revision(
|
|
result_id: str,
|
|
revision: int,
|
|
response: Response,
|
|
view: ViewPreset = "default",
|
|
output_format: Literal["json", "markdown", "onepager"] = Query("json", alias="format"),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
response.headers["Cache-Control"] = "no-store"
|
|
return await read_frozen_result_revision(
|
|
db,
|
|
result_id=result_id,
|
|
revision=revision,
|
|
preset=view,
|
|
output_format=output_format,
|
|
)
|
|
|
|
|
|
# ============================================================================
|
|
# Group 5: Read-Only Stage Presentations (R1/R2/R5) & Proactive TopicWatches
|
|
# ============================================================================
|
|
|
|
|
|
@router.get(
|
|
"/presentations",
|
|
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
|
|
)
|
|
async def get_presentations(
|
|
response: Response,
|
|
after_cursor: int = Query(0, ge=0),
|
|
countries: str = "CN,US",
|
|
time_basis: TimeBasis = "retrospective",
|
|
cutoff_at: str | None = None,
|
|
include_drill: bool = False,
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
codes = selected_countries(countries)
|
|
response.headers["Cache-Control"] = "no-store"
|
|
return await list_or_compile_presentations(
|
|
db,
|
|
after_cursor=after_cursor,
|
|
countries=codes,
|
|
time_basis=time_basis,
|
|
cutoff_at=cutoff_at,
|
|
include_drill=include_drill,
|
|
persist=False,
|
|
)
|
|
|
|
|
|
@router.get(
|
|
"/presentations/{presentation_key:path}",
|
|
dependencies=[Depends(require_earth_or_api_access("situational:read"))],
|
|
)
|
|
async def get_presentation_by_key(
|
|
presentation_key: str,
|
|
response: Response,
|
|
countries: str = "CN,US",
|
|
time_basis: TimeBasis = "retrospective",
|
|
cutoff_at: str | None = None,
|
|
include_drill: bool = False,
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
codes = selected_countries(countries)
|
|
response.headers["Cache-Control"] = "no-store"
|
|
item = await get_or_compile_presentation_by_key(
|
|
db,
|
|
presentation_key,
|
|
countries=codes,
|
|
time_basis=time_basis,
|
|
cutoff_at=cutoff_at,
|
|
include_drill=include_drill or ("replay-as13335" in presentation_key),
|
|
)
|
|
if item is not None:
|
|
return item
|
|
raise HTTPException(status_code=404, detail=f"Presentation not found: {presentation_key}")
|
|
|
|
|
|
@router.get("/watches")
|
|
async def list_topic_watches(
|
|
response: Response,
|
|
domain: Literal["all", "global", "compute", "bgp", "cable", "satellite", "vessel"] = "all",
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
response.headers["Cache-Control"] = "no-store"
|
|
if not access.has_session_credential:
|
|
return {"items": []}
|
|
stmt = (
|
|
select(TopicWatch)
|
|
.where(TopicWatch.owner_key == access.actor_key)
|
|
.order_by(desc(TopicWatch.id))
|
|
.limit(50)
|
|
)
|
|
if domain != "all":
|
|
stmt = stmt.where(TopicWatch.domain == domain)
|
|
rows = (await db.execute(stmt)).scalars().all()
|
|
return {"items": [r.to_dict() for r in rows]}
|
|
|
|
|
|
@router.post("/watches")
|
|
async def create_topic_watch(
|
|
payload: TopicWatchCreateRequest,
|
|
response: Response,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
owner_key, issued_token = ensure_session_owner_identity(access, response)
|
|
existing = (
|
|
await db.execute(
|
|
select(TopicWatch).where(
|
|
TopicWatch.owner_key == owner_key,
|
|
TopicWatch.watch_key == payload.watch_key,
|
|
)
|
|
)
|
|
).scalar_one_or_none()
|
|
if existing is not None:
|
|
existing.status = "active"
|
|
existing.target_scope = payload.target_scope
|
|
existing.trigger_policy = payload.trigger_policy
|
|
await db.commit()
|
|
out = existing.to_dict()
|
|
if issued_token:
|
|
out["session_token"] = issued_token
|
|
return out
|
|
|
|
watch = TopicWatch(
|
|
watch_key=payload.watch_key,
|
|
domain=payload.domain,
|
|
target_scope=payload.target_scope,
|
|
trigger_policy=payload.trigger_policy,
|
|
owner_key=owner_key,
|
|
status="active",
|
|
)
|
|
db.add(watch)
|
|
await db.commit()
|
|
await db.refresh(watch)
|
|
out = watch.to_dict()
|
|
if issued_token:
|
|
out["session_token"] = issued_token
|
|
return out
|
|
|
|
|
|
@router.delete("/watches/{watch_id}")
|
|
async def delete_topic_watch(
|
|
watch_id: int,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
row = (
|
|
await db.execute(select(TopicWatch).where(TopicWatch.id == watch_id))
|
|
).scalar_one_or_none()
|
|
if row is None:
|
|
if not access.has_session_credential:
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail="Authentication or valid session token required to modify TopicWatch.",
|
|
)
|
|
raise HTTPException(status_code=404, detail="TopicWatch not found")
|
|
enforce_resource_ownership(row.owner_key, access, "topic watch")
|
|
row.status = "paused"
|
|
await db.commit()
|
|
return row.to_dict()
|
|
|
|
|
|
# ============================================================================
|
|
# Group 6: Admin Hygiene Audit, Proactive Trigger & Compatible Endpoints
|
|
# ============================================================================
|
|
|
|
|
|
@router.get("/audit/hygiene")
|
|
async def get_situational_hygiene_audit(
|
|
response: Response,
|
|
_actor: User = Depends(configuration_admin),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
response.headers["Cache-Control"] = "no-store"
|
|
return await audit_situational_hygiene(db)
|
|
|
|
|
|
@router.post("/proactive/evaluate")
|
|
async def evaluate_proactive_snapshot(
|
|
payload: ProactiveSnapshotTriggerRequest,
|
|
_actor: User = Depends(configuration_admin),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
if payload.domain == "compute":
|
|
res = await retry_pending_compute_presentations(db)
|
|
else:
|
|
res = await process_bgp_snapshot_proactive_delta(
|
|
db,
|
|
source=payload.source,
|
|
record_count=payload.record_count,
|
|
status=payload.status,
|
|
completed_at=payload.completed_at,
|
|
error=payload.error,
|
|
)
|
|
await db.commit()
|
|
return res
|
|
|
|
|
|
@router.get("/posture/compute")
|
|
async def get_compute_posture(
|
|
response: Response,
|
|
countries: str = "CN,US",
|
|
mode: ComputeSeriesMode = "global_share",
|
|
time_basis: TimeBasis = "retrospective",
|
|
cutoff_at: str | None = None,
|
|
as_of: str | None = None,
|
|
publish_id: str | None = None,
|
|
prefer_llm: bool = False,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
ai_client: AIProviderClient = Depends(get_ai_provider_client),
|
|
) -> dict[str, Any]:
|
|
if prefer_llm:
|
|
await enforce_paid_research_gate(access, db, workflow_id="compute.compare")
|
|
codes = selected_countries(countries)
|
|
response.headers["Cache-Control"] = "no-store"
|
|
series = await query_compute_posture_tool(
|
|
db,
|
|
codes,
|
|
mode=mode,
|
|
time_basis=time_basis,
|
|
cutoff_at=cutoff_at,
|
|
as_of=as_of,
|
|
publish_id=publish_id,
|
|
)
|
|
# GET is strictly 100% read-only (`persist=False`) when `prefer_llm=False`
|
|
return await generate_or_get_compute_posture(
|
|
db,
|
|
countries=codes,
|
|
mode=mode,
|
|
series_payload=series,
|
|
ai_client=ai_client if prefer_llm else None,
|
|
prefer_llm=prefer_llm,
|
|
time_basis=time_basis,
|
|
cutoff_at=cutoff_at,
|
|
persist=False,
|
|
)
|
|
|
|
|
|
@router.post("/investigate")
|
|
async def investigate_spatial_context(
|
|
payload: SpatialInvestigateRequest,
|
|
access: AccessContext = Depends(resolve_access_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
ai_client: AIProviderClient = Depends(get_ai_provider_client),
|
|
) -> dict[str, Any]:
|
|
workflow_id = (
|
|
"compute.explain_gap"
|
|
if payload.domain == "compute"
|
|
else ("incident.overview" if payload.domain == "bgp" else f"{payload.domain}.overview")
|
|
)
|
|
await enforce_paid_research_gate(
|
|
access,
|
|
db,
|
|
workflow_id=workflow_id,
|
|
needs_external_fetch=bool(payload.external_urls),
|
|
)
|
|
codes = selected_countries(",".join(payload.selected_codes)) if payload.selected_codes else ["CN", "US"]
|
|
result = await run_contextual_copilot(
|
|
db,
|
|
domain=payload.domain,
|
|
selected_codes=codes,
|
|
focus_year=payload.focus_year,
|
|
mode=payload.mode,
|
|
entity_id=payload.entity_id,
|
|
visible_layers=payload.visible_layers,
|
|
question=payload.question,
|
|
time_basis=payload.time_basis,
|
|
cutoff_at=payload.cutoff_at,
|
|
publish_id=payload.publish_id,
|
|
as_of=payload.as_of,
|
|
allow_drill=payload.include_drill,
|
|
ai_client=ai_client,
|
|
)
|
|
if hasattr(db, "commit"):
|
|
await db.commit()
|
|
return result
|
|
|
|
|
|
@router.post("/reports/export")
|
|
async def export_situational_report(
|
|
payload: ReportExportRequest,
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
codes = selected_countries(",".join(payload.countries)) if payload.countries else ["CN", "US"]
|
|
return await export_revision_bound_markdown_report(
|
|
db,
|
|
subject_type=payload.subject_type,
|
|
countries=codes,
|
|
mode=payload.mode,
|
|
incident_key=payload.incident_key,
|
|
result_id=payload.result_id,
|
|
expected_revision=payload.expected_revision,
|
|
time_basis=payload.time_basis,
|
|
cutoff_at=payload.cutoff_at,
|
|
)
|
|
|
|
|
|
@router.get("/candidates")
|
|
async def list_compute_candidates(
|
|
status_filter: Literal["all", "pending", "approved", "rejected"] = Query("all", alias="status"),
|
|
_actor: User = Depends(configuration_admin),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
stmt = select(ComputeEvidenceCandidate).order_by(desc(ComputeEvidenceCandidate.id)).limit(100)
|
|
if status_filter != "all":
|
|
stmt = stmt.where(ComputeEvidenceCandidate.status == status_filter)
|
|
rows = (await db.execute(stmt)).scalars().all()
|
|
return {"items": [row.to_dict() for row in rows]}
|
|
|
|
|
|
def _candidate_dedupe_fingerprint(
|
|
*,
|
|
source_id: str,
|
|
metric: str,
|
|
year: int,
|
|
period_label: str | None,
|
|
values: dict[str, Any],
|
|
) -> str:
|
|
sorted_vals = {
|
|
str(k): round(float(v), 6)
|
|
for k, v in sorted((values or {}).items(), key=lambda kv: str(kv[0]))
|
|
}
|
|
raw = f"{source_id}|{metric}|{year}|{period_label or ''}|{json.dumps(sorted_vals, sort_keys=True, separators=(',', ':'))}"
|
|
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
|
|
|
|
|
def _build_candidate_comparison(
|
|
*,
|
|
current_config: ComputeConfiguration,
|
|
current_publish_id: str,
|
|
proposed: dict[str, Any],
|
|
) -> dict[str, Any]:
|
|
metric = str(proposed.get("metric") or "global_share")
|
|
year = int(proposed.get("year") or 0)
|
|
proposed_period = (proposed.get("period_label") or None)
|
|
existing_row = next(
|
|
(obs for obs in current_config.observations if obs.metric == metric and obs.year == year),
|
|
None,
|
|
)
|
|
existing_period = existing_row.period_label if existing_row is not None else None
|
|
period_conflict = bool(
|
|
existing_row is not None and (existing_period or None) != (proposed_period or None)
|
|
)
|
|
codes_comparison: dict[str, dict[str, Any]] = {}
|
|
has_historical_revision = False
|
|
for code, raw_new in sorted((proposed.get("values") or {}).items()):
|
|
new_val = float(raw_new)
|
|
if existing_row is not None and code in existing_row.values:
|
|
old_val = float(existing_row.values[code])
|
|
old_src = source_for(existing_row, code)
|
|
delta = round(new_val - old_val, 4)
|
|
change_kind = "historical_revision" if delta != 0 else "unchanged"
|
|
if change_kind == "historical_revision":
|
|
has_historical_revision = True
|
|
else:
|
|
old_val = None
|
|
old_src = None
|
|
delta = round(new_val, 4)
|
|
change_kind = "new_observation"
|
|
codes_comparison[code] = {
|
|
"old_value": old_val,
|
|
"new_value": new_val,
|
|
"delta": delta,
|
|
"change_kind": change_kind,
|
|
"old_source_id": old_src,
|
|
}
|
|
return {
|
|
"publish_id": current_publish_id,
|
|
"metric": metric,
|
|
"year": year,
|
|
"period_label": proposed_period,
|
|
"existing_period_label": existing_period,
|
|
"period_conflict": period_conflict,
|
|
"denominator": MODE_DENOMINATOR.get(metric),
|
|
"codes": codes_comparison,
|
|
"has_historical_revision": has_historical_revision,
|
|
}
|
|
|
|
|
|
@router.post("/candidates/extract")
|
|
async def extract_compute_candidates(
|
|
payload: CandidateExtractRequest,
|
|
actor: User = Depends(configuration_admin),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
effective_report_year = payload.report_year or payload.year
|
|
source_meta: dict[str, Any] = {
|
|
"id": payload.source_id,
|
|
"title": payload.source_title,
|
|
"url": payload.source_url,
|
|
"publisher": payload.publisher,
|
|
"report_year": effective_report_year,
|
|
"published_at": payload.published_at,
|
|
"locator": payload.locator,
|
|
}
|
|
extracted = extract_compute_candidates_deterministic(
|
|
payload.excerpt,
|
|
year=payload.year,
|
|
source_meta=source_meta,
|
|
period_label=payload.period_label,
|
|
)
|
|
envelope = await read_configuration(db)
|
|
current_config = ComputeConfiguration.model_validate(envelope["config"])
|
|
current_publish_id = str(envelope.get("publish_id") or envelope["revision"])
|
|
|
|
# Upsert immutable EvidenceRecord without overwriting existing record.
|
|
if extracted and hasattr(db, "execute") and hasattr(db, "add"):
|
|
existing_ev = (
|
|
await db.execute(select(EvidenceRecord).where(EvidenceRecord.id == payload.source_id))
|
|
).scalar_one_or_none()
|
|
if existing_ev is None:
|
|
db.add(
|
|
EvidenceRecord(
|
|
id=payload.source_id,
|
|
source_type="curated_report",
|
|
title=payload.source_title,
|
|
publisher=payload.publisher,
|
|
url=payload.source_url,
|
|
locator=payload.locator,
|
|
excerpt=payload.excerpt,
|
|
content_sha256=hashlib.sha256(payload.excerpt.encode("utf-8")).hexdigest(),
|
|
published_at=payload.published_at or str(effective_report_year),
|
|
metadata_json={
|
|
"report_year": effective_report_year,
|
|
"period_label": payload.period_label,
|
|
},
|
|
)
|
|
)
|
|
|
|
created: list[ComputeEvidenceCandidate] = []
|
|
ordered_entries: list[tuple[ComputeEvidenceCandidate, bool]] = []
|
|
for item in extracted:
|
|
proposed = item["proposed_payload"]
|
|
fp = _candidate_dedupe_fingerprint(
|
|
source_id=str(proposed.get("source_id") or payload.source_id),
|
|
metric=str(proposed.get("metric") or "global_share"),
|
|
year=int(proposed.get("year") or payload.year),
|
|
period_label=proposed.get("period_label"),
|
|
values=proposed.get("values") or {},
|
|
)
|
|
existing_cand = (
|
|
await db.execute(
|
|
select(ComputeEvidenceCandidate)
|
|
.where(ComputeEvidenceCandidate.dedupe_fingerprint == fp)
|
|
.order_by(desc(ComputeEvidenceCandidate.id))
|
|
.limit(1)
|
|
)
|
|
).scalar_one_or_none()
|
|
if existing_cand is not None:
|
|
ordered_entries.append((existing_cand, True))
|
|
continue
|
|
|
|
comparison = _build_candidate_comparison(
|
|
current_config=current_config,
|
|
current_publish_id=current_publish_id,
|
|
proposed=proposed,
|
|
)
|
|
record = ComputeEvidenceCandidate(
|
|
status="pending",
|
|
candidate_type=item["candidate_type"],
|
|
proposed_payload=proposed,
|
|
source_payload=item["source_payload"],
|
|
comparison=comparison,
|
|
dedupe_fingerprint=fp,
|
|
confidence=item["confidence"],
|
|
extractor_note=item["extractor_note"],
|
|
)
|
|
db.add(record)
|
|
created.append(record)
|
|
ordered_entries.append((record, False))
|
|
|
|
db.add(
|
|
AuditLog(
|
|
actor_id=actor.id,
|
|
actor_name=actor.username,
|
|
action="compute_candidates.extract",
|
|
target_type="compute_evidence_candidates",
|
|
target_id=payload.source_id,
|
|
details={
|
|
"count": len(created),
|
|
"duplicates": sum(1 for _, is_dup in ordered_entries if is_dup),
|
|
"year": payload.year,
|
|
},
|
|
)
|
|
)
|
|
await db.commit()
|
|
for rec in created:
|
|
await db.refresh(rec)
|
|
return {
|
|
"items": [
|
|
{**rec.to_dict(), "duplicate": is_dup}
|
|
for rec, is_dup in ordered_entries
|
|
]
|
|
}
|
|
|
|
|
|
@router.post("/candidates/{candidate_id}/review")
|
|
async def review_compute_candidate(
|
|
candidate_id: int,
|
|
payload: CandidateReviewRequest,
|
|
actor: User = Depends(configuration_admin),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
record = (
|
|
await db.execute(
|
|
select(ComputeEvidenceCandidate).where(ComputeEvidenceCandidate.id == candidate_id)
|
|
)
|
|
).scalar_one_or_none()
|
|
if record is None:
|
|
raise HTTPException(status_code=404, detail="Candidate not found")
|
|
if record.published_publish_id:
|
|
raise HTTPException(
|
|
status_code=409,
|
|
detail="Candidate has already been published and cannot be modified.",
|
|
)
|
|
previous_status = record.status
|
|
record.status = payload.decision
|
|
record.review_reason_code = payload.reason_code
|
|
record.review_reason = payload.reason
|
|
record.reviewed_by = actor.username
|
|
record.reviewed_at = datetime.now(UTC)
|
|
db.add(
|
|
AuditLog(
|
|
actor_id=actor.id,
|
|
actor_name=actor.username,
|
|
action=f"compute_candidates.{payload.decision}",
|
|
target_type="compute_evidence_candidates",
|
|
target_id=str(candidate_id),
|
|
details={
|
|
"before_status": previous_status,
|
|
"after_status": payload.decision,
|
|
"reason_code": payload.reason_code,
|
|
"reason": payload.reason,
|
|
},
|
|
)
|
|
)
|
|
await db.commit()
|
|
return record.to_dict()
|