| """Pure governance API service logic. | |
| This module intentionally avoids FastAPI imports so the decision path can be | |
| tested in environments where the async runtime is unavailable. | |
| """ | |
| from __future__ import annotations | |
| from collections import Counter | |
| from datetime import datetime, timezone | |
| from typing import Any, Dict, List, Optional | |
| from nexus_os.db.manager import DBConfig, DatabaseManager | |
| from nexus_os.governor.base import NexusGovernor | |
| from nexus_os.governor.kaiju_auth import Decision | |
| def utc_now() -> str: | |
| """Return an ISO-8601 UTC timestamp.""" | |
| return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") | |
| def proposal_status_from_decision(decision: Decision) -> str: | |
| """Map Governor decisions to proposal lifecycle states.""" | |
| if decision == Decision.ALLOW: | |
| return "approved" | |
| if decision == Decision.DENY: | |
| return "rejected" | |
| if decision == Decision.HOLD: | |
| return "held" | |
| return "halted" | |
| class GovernanceAPIState: | |
| """Stateful proposal registry backed by the canonical NexusGovernor.""" | |
| def __init__(self, db_path: str = "nexus_api.db"): | |
| self.db = DatabaseManager( | |
| DBConfig( | |
| db_path=db_path, | |
| passphrase="", | |
| encrypted=False, | |
| allow_unencrypted=True, | |
| ) | |
| ) | |
| self.db.setup_schema() | |
| self.governor = NexusGovernor(self.db) | |
| self.proposals: Dict[str, Dict[str, Any]] = {} | |
| self.task_runs: Dict[str, Dict[str, Any]] = {} | |
| self.route_logs: Dict[str, Dict[str, Any]] = {} | |
| def close(self) -> None: | |
| self.db.close() | |
| def audit_count(self) -> int: | |
| try: | |
| adapter = self.db.get_connection() | |
| cursor = adapter.execute("SELECT COUNT(*) FROM audit_logs") | |
| row = adapter.fetchone(cursor) | |
| return int(row[0]) if row else 0 | |
| except Exception: | |
| return 0 | |
| def propose_skill( | |
| self, | |
| *, | |
| proposal_id: str, | |
| model_id: str, | |
| skill: Optional[Dict[str, Any]], | |
| rationale: str, | |
| timestamp: Optional[str] = None, | |
| ) -> Dict[str, Any]: | |
| if proposal_id in self.proposals: | |
| raise ValueError(f"Proposal already exists: {proposal_id}") | |
| skill_data = skill or {} | |
| result = self.governor.check_access( | |
| agent_id=str(skill_data.get("agent_id") or model_id), | |
| project_id=str(skill_data.get("project_id") or "nexus-os"), | |
| action=str(skill_data.get("action") or "execute"), | |
| scope=str(skill_data.get("scope") or "project"), | |
| intent=rationale, | |
| impact=str(skill_data.get("impact") or "low"), | |
| clearance=str(skill_data.get("clearance") or "contributor"), | |
| trace_id=proposal_id, | |
| context={ | |
| "proposal_id": proposal_id, | |
| "model_id": model_id, | |
| "skill": skill_data, | |
| "timestamp": timestamp or utc_now(), | |
| }, | |
| ) | |
| record = { | |
| "proposal_id": proposal_id, | |
| "model_id": model_id, | |
| "skill": skill_data, | |
| "rationale": rationale, | |
| "timestamp": timestamp or utc_now(), | |
| "status": proposal_status_from_decision(result.decision), | |
| "decision": result.decision.value, | |
| "reason": result.reason, | |
| "trace_id": result.trace_id, | |
| "review": None, | |
| } | |
| self.proposals[proposal_id] = record | |
| return record | |
| def get_proposal(self, proposal_id: str) -> Optional[Dict[str, Any]]: | |
| return self.proposals.get(proposal_id) | |
| def list_proposals(self) -> Dict[str, Any]: | |
| return { | |
| "count": len(self.proposals), | |
| "proposals": list(self.proposals.values()), | |
| } | |
| def review_proposal( | |
| self, | |
| *, | |
| proposal_id: str, | |
| decision: str, | |
| reviewer: str = "speci", | |
| reason: str = "", | |
| ) -> Optional[Dict[str, Any]]: | |
| record = self.proposals.get(proposal_id) | |
| if record is None: | |
| return None | |
| if decision == "approve": | |
| record["status"] = "approved" | |
| record["decision"] = "allow" | |
| elif decision == "reject": | |
| record["status"] = "rejected" | |
| record["decision"] = "deny" | |
| elif decision == "hold": | |
| record["status"] = "held" | |
| record["decision"] = "hold" | |
| else: | |
| raise ValueError("decision must be approve, reject, or hold") | |
| record["review"] = { | |
| "reviewer": reviewer, | |
| "reason": reason, | |
| "reviewed_at": utc_now(), | |
| } | |
| return record | |
| def record_route_log( | |
| self, | |
| *, | |
| route_class: str, | |
| provider_id: str, | |
| model_family: str, | |
| latency_ms: float, | |
| success: bool, | |
| failure_code: Optional[str] = None, | |
| fallback_count: int = 0, | |
| stream_disconnect: bool = False, | |
| timestamp: Optional[str] = None, | |
| metadata: Optional[Dict[str, Any]] = None, | |
| ) -> Dict[str, Any]: | |
| """Record a route attempt log for governance audit.""" | |
| log_id = f"{provider_id}:{timestamp or utc_now()}" | |
| record = { | |
| "log_id": log_id, | |
| "route_class": route_class, | |
| "provider_id": provider_id, | |
| "model_family": model_family, | |
| "latency_ms": latency_ms, | |
| "success": success, | |
| "failure_code": failure_code, | |
| "fallback_count": fallback_count, | |
| "stream_disconnect": stream_disconnect, | |
| "timestamp": timestamp or utc_now(), | |
| "metadata": metadata or {}, | |
| } | |
| self.route_logs[log_id] = record | |
| return record | |
| def list_route_logs( | |
| self, | |
| provider_id: Optional[str] = None, | |
| route_class: Optional[str] = None, | |
| limit: int = 100, | |
| ) -> Dict[str, Any]: | |
| """List route logs with optional filtering.""" | |
| logs = list(self.route_logs.values()) | |
| if provider_id: | |
| logs = [log for log in logs if log["provider_id"] == provider_id] | |
| if route_class: | |
| logs = [log for log in logs if log["route_class"] == route_class] | |
| # Sort by timestamp descending | |
| logs.sort(key=lambda x: x["timestamp"], reverse=True) | |
| return { | |
| "count": len(logs), | |
| "logs": logs[:limit], | |
| } | |
| def dashboard_stats(self) -> Dict[str, Any]: | |
| counts = Counter(record["status"] for record in self.proposals.values()) | |
| task_counts = Counter(record["status"] for record in self.task_runs.values()) | |
| route_success = sum(1 for r in self.route_logs.values() if r["success"]) | |
| route_total = len(self.route_logs) | |
| return { | |
| "status": "operational", | |
| "service": "nexus-governance-api", | |
| "proposal_count": len(self.proposals), | |
| "approved": counts.get("approved", 0), | |
| "rejected": counts.get("rejected", 0), | |
| "held": counts.get("held", 0), | |
| "audit_entries": self.audit_count(), | |
| "task_count": len(self.task_runs), | |
| "tasks_active": task_counts.get("working", 0) + task_counts.get("heartbeat", 0), | |
| "tasks_completed": task_counts.get("completed", 0), | |
| "tasks_failed": task_counts.get("failed", 0), | |
| "route_logs_total": route_total, | |
| "route_logs_success": route_success, | |
| "route_logs_failure": route_total - route_success, | |
| } | |
| def record_task_heartbeat( | |
| self, | |
| *, | |
| task_id: str, | |
| agent_id: str, | |
| trace_id: str, | |
| progress: int = 0, | |
| status: str = "heartbeat", | |
| details: Optional[Dict[str, Any]] = None, | |
| timestamp: Optional[str] = None, | |
| ) -> Dict[str, Any]: | |
| record = self.task_runs.setdefault( | |
| task_id, | |
| { | |
| "task_id": task_id, | |
| "agent_id": agent_id, | |
| "trace_id": trace_id, | |
| "status": status, | |
| "progress": max(0, min(100, progress)), | |
| "created_at": timestamp or utc_now(), | |
| "updated_at": timestamp or utc_now(), | |
| "details": {}, | |
| "heartbeats": [], | |
| "result": None, | |
| }, | |
| ) | |
| record["agent_id"] = agent_id | |
| record["trace_id"] = trace_id | |
| record["status"] = status | |
| record["progress"] = max(0, min(100, progress)) | |
| record["updated_at"] = timestamp or utc_now() | |
| if details: | |
| record["details"].update(details) | |
| record["heartbeats"].append( | |
| { | |
| "timestamp": timestamp or utc_now(), | |
| "status": status, | |
| "progress": record["progress"], | |
| "details": details or {}, | |
| } | |
| ) | |
| return record | |
| def record_task_result( | |
| self, | |
| *, | |
| task_id: str, | |
| agent_id: str, | |
| trace_id: str, | |
| outcome: str, | |
| summary: str = "", | |
| artifacts: Optional[Dict[str, Any]] = None, | |
| timestamp: Optional[str] = None, | |
| ) -> Dict[str, Any]: | |
| terminal_status = { | |
| "success": "completed", | |
| "completed": "completed", | |
| "failure": "failed", | |
| "failed": "failed", | |
| "cancelled": "cancelled", | |
| }.get(outcome, outcome) | |
| record = self.task_runs.setdefault( | |
| task_id, | |
| { | |
| "task_id": task_id, | |
| "agent_id": agent_id, | |
| "trace_id": trace_id, | |
| "status": terminal_status, | |
| "progress": 100 if terminal_status == "completed" else 0, | |
| "created_at": timestamp or utc_now(), | |
| "updated_at": timestamp or utc_now(), | |
| "details": {}, | |
| "heartbeats": [], | |
| "result": None, | |
| }, | |
| ) | |
| record["agent_id"] = agent_id | |
| record["trace_id"] = trace_id | |
| record["status"] = terminal_status | |
| record["progress"] = 100 if terminal_status == "completed" else record.get("progress", 0) | |
| record["updated_at"] = timestamp or utc_now() | |
| record["result"] = { | |
| "outcome": outcome, | |
| "summary": summary, | |
| "artifacts": artifacts or {}, | |
| "timestamp": timestamp or utc_now(), | |
| } | |
| return record | |
| def get_task_status(self, task_id: str) -> Optional[Dict[str, Any]]: | |
| return self.task_runs.get(task_id) | |
Xet Storage Details
- Size:
- 10.7 kB
- Xet hash:
- a41f8a24a211dd63c6a321810c0f7ade909ad2475db282a9500ae355a6b6cb0d
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.