Python SDK Reference¶
AEGIS Governance Decision SDK -- quantitative governance for engineering decisions.
Installation¶
# Core SDK
pip install aegis-governance
# With optional dependencies
pip install aegis-governance[engine] # scipy for z-score computation
pip install aegis-governance[telemetry] # prometheus_client for metrics
pip install aegis-governance[config] # pyyaml for YAML config loading
pip install aegis-governance[crypto] # BIP-340 Schnorr signatures
pip install aegis-governance[persistence] # SQLAlchemy async workflow storage
pip install aegis-governance[all] # Everything
Quick Start¶
from aegis_governance import pcw_decide, PCWContext, PCWPhase, PCWStatus, AegisConfig
config = AegisConfig.default()
evaluator = config.create_gate_evaluator()
decision = pcw_decide(
PCWContext(
agent_id="my-agent",
session_id="session-1",
phase=PCWPhase.PLAN,
proposal_summary="Add caching layer",
estimated_impact="medium",
risk_proposed=0.3,
complexity_score=0.6,
),
gate_evaluator=evaluator,
)
if decision.status == PCWStatus.PROCEED:
print("Safe to proceed")
Configuration¶
AegisConfig¶
Frozen dataclass holding all AEGIS frozen parameters. Instances are immutable after creation, preventing accidental parameter drift during a session.
Default values match schema/interface-contract.yaml exactly.
Fields¶
| Field | Type | Default | Description |
|---|---|---|---|
epsilon_R | float | 0.01 | Risk epsilon floor (prevents division by zero) |
epsilon_P | float | 0.01 | Profit epsilon floor |
risk_trigger_factor | float | 2.0 | Normalized risk threshold multiplier |
profit_trigger_factor | float | 2.0 | Normalized profit threshold multiplier |
trigger_confidence_prob | float | 0.95 | Bayesian posterior confidence threshold |
novelty_N0 | float | 0.7 | Novelty gate logistic inflection point |
novelty_k | float | 10.0 | Novelty gate logistic steepness |
novelty_threshold | float | 0.8 | Novelty gate pass threshold |
complexity_floor | float | 0.5 | Complexity hard floor (cannot be overridden) |
quality_min_score | float | 0.7 | Minimum quality score |
quality_no_zero_subscore | bool | True | Reject zero quality subscores |
gamma | float | 0.3 | Utility function risk aversion |
kappa | float | 1.0 | Utility function scaling factor |
phi_S | float | 100.0 | Utility function setup cost |
phi_D | float | 2000.0 | Utility function disruption cost |
lcb_alpha | float | 0.05 | Utility LCB significance level |
migration_budget | float | 5000.0 | Utility migration budget |
utility_threshold | float | 0.0 | Utility gate LCB threshold |
kl_drift | KLDriftConfig | See below | KL divergence drift detection config |
telemetry_url | str | None | None | HTTPS URL for telemetry HTTP sink |
mcp_rate_limit | int | 60 | MCP requests per minute (0 = disabled) |
Class Methods¶
AegisConfig.default() -> AegisConfig¶
Create config with built-in defaults matching frozen YAML values.
AegisConfig.from_yaml(path: str | Path) -> AegisConfig¶
Load configuration from a YAML file. The YAML file should follow the schema/interface-contract.yaml format. Only recognized parameter keys are extracted; unknown keys are ignored.
Raises: - FileNotFoundError -- if the YAML file does not exist - ImportError -- if PyYAML is not installed (install with pip install aegis-governance[config]) - ValueError -- if YAML content is invalid
Factory Methods¶
config.create_gate_evaluator() -> GateEvaluator¶
Create a GateEvaluator configured with this config's frozen parameters.
evaluator = config.create_gate_evaluator()
result = evaluator.evaluate_risk_gate(baseline=0.1, proposed=0.3)
config.create_drift_monitor() -> DriftMonitor¶
Create a DriftMonitor configured with this config's KL drift thresholds.
monitor = config.create_drift_monitor()
monitor.set_baseline([0.1, 0.15, 0.12, 0.14, ...]) # 30+ observations
config.create_utility_calculator() -> UtilityCalculator¶
Create a UtilityCalculator configured with this config's utility parameters.
KLDriftConfig¶
Frozen dataclass for KL divergence drift detection thresholds.
| Field | Type | Default | Description |
|---|---|---|---|
tau_warning | float | 0.3 | KL divergence warning threshold |
tau_critical | float | 0.5 | KL divergence critical threshold |
window_days | int | 30 | Drift observation window in days |
Decision Interface¶
PCWContext¶
Dataclass containing all inputs for a governance decision.
Fields¶
| Field | Type | Default | Description |
|---|---|---|---|
agent_id | str | (required) | Agent/caller identifier |
session_id | str | (required) | Session identifier for correlation |
phase | PCWPhase | (required) | Current lifecycle phase |
proposal_summary | str | (required) | Brief description of the proposal |
estimated_impact | str | (required) | Impact level: low, medium, high, critical |
risk_baseline | float | 0.0 | Current risk level before change (0.0-1.0) |
risk_proposed | float | 0.0 | Predicted risk after change (0.0-1.0) |
profit_baseline | float | 0.0 | Current profit/performance metric |
profit_proposed | float | 0.0 | Expected profit/performance after change |
novelty_score | float | 0.5 | How unprecedented the proposal is (0.0-1.0) |
complexity_score | float | 0.5 | Normalized complexity (higher = simpler, 0.0-1.0) |
quality_score | float | 0.7 | Overall proposal quality (0.0-1.0) |
quality_subscores | list[float] | [0.7, 0.7, 0.7] | Detailed quality subscores |
utility_result | UtilityResult | None | None | Pre-computed utility result |
requires_human_approval | bool | False | Force human approval |
time_sensitive | bool | False | Mark as time-sensitive |
reversible | bool | True | Whether the action is reversible |
metadata | dict[str, Any] | {} | Additional key-value metadata |
PCWPhase¶
Enum for Plan-Commit-Work lifecycle phases.
| Value | Description |
|---|---|
PCWPhase.PLAN | Planning phase -- evaluate feasibility |
PCWPhase.COMMIT | Commit phase -- authorize execution |
PCWPhase.WORK | Work phase -- execute with monitoring |
PCWStatus¶
Enum for decision outcomes.
| Value | Description |
|---|---|
PCWStatus.PROCEED | Safe to proceed |
PCWStatus.PAUSE | Pause for human review |
PCWStatus.HALT | Stop immediately |
PCWStatus.ESCALATE | Escalate to higher authority |
PCWDecision¶
Dataclass containing the full decision result.
| Field | Type | Description |
|---|---|---|
status | PCWStatus | Decision outcome |
confidence | float | Minimum confidence across all gates |
gates_passed | int | Number of gates that passed |
gates_failed | int | Number of gates that failed |
failing_gates | list[str] | Names of failed gates |
rationale | str | Human-readable decision rationale |
next_steps | list[str] | Recommended next actions |
constraints | list[str] | Active constraints (e.g., drift warnings) |
decision_id | str | Unique decision UUID |
timestamp | datetime | UTC timestamp of the decision |
override_eligible | bool | Whether override is possible |
override_requires | list[str] | Roles required for override |
gate_evaluation | GateEvaluationResult | None | Detailed per-gate results |
decision_trace | DecisionTrace | None | Structured audit trace |
shadow_result | ShadowResult | None | Shadow mode metadata |
drift_result | DriftResult | None | Drift policy enforcement result |
ShadowResult¶
Dataclass attached to PCWDecision.shadow_result when shadow_mode=True.
| Field | Type | Description |
|---|---|---|
drift_result | DriftResult | None | Drift analysis from shadow evaluation |
observation_values | list[float] | Observed risk/profit deltas |
baseline_hash | str | None | Hash of drift baseline used |
shadow_only | bool | Always True for shadow results |
Functions¶
pcw_decide()¶
Primary decision function. Evaluates a proposal context against all six quantitative gates using Bayesian posterior calculations.
def pcw_decide(
context: PCWContext,
gate_evaluator: GateEvaluator | None = None,
prometheus_exporter: PrometheusExporter | None = None,
rbac_enforcer: RBACEnforcer | None = None,
*,
shadow_mode: bool = False,
drift_monitor: DriftMonitor | None = None,
telemetry_emitter: TelemetryEmitter | None = None,
) -> PCWDecision:
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
context | PCWContext | (required) | Proposal context with metrics |
gate_evaluator | GateEvaluator | None | None | Pre-configured gate evaluator (uses defaults if not provided) |
prometheus_exporter | PrometheusExporter | None | None | Prometheus exporter for metrics recording |
rbac_enforcer | RBACEnforcer | None | None | RBAC enforcer (advisory -- checks submit_proposals permission) |
shadow_mode | bool | False | Evaluate without enforcing (for calibration) |
drift_monitor | DriftMonitor | None | None | Drift detector (CRITICAL = HALT, WARNING = constraint) |
telemetry_emitter | TelemetryEmitter | None | None | Emitter for DRIFT_POLICY_ENFORCED and SHADOW_EVALUATION events |
Returns: PCWDecision
Example:
from aegis_governance import (
pcw_decide, PCWContext, PCWPhase, PCWStatus, AegisConfig
)
config = AegisConfig.default()
evaluator = config.create_gate_evaluator()
drift_monitor = config.create_drift_monitor()
drift_monitor.set_baseline([0.1, 0.12, 0.11, 0.13] * 10)
decision = pcw_decide(
PCWContext(
agent_id="deploy-bot",
session_id="deploy-123",
phase=PCWPhase.COMMIT,
proposal_summary="Deploy v2.5 to production",
estimated_impact="high",
risk_baseline=0.1,
risk_proposed=0.15,
profit_baseline=1000.0,
profit_proposed=1200.0,
novelty_score=0.3,
complexity_score=0.8,
quality_score=0.9,
requires_human_approval=True,
),
gate_evaluator=evaluator,
drift_monitor=drift_monitor,
)
print(f"Status: {decision.status.value}")
print(f"Confidence: {decision.confidence}")
print(f"Rationale: {decision.rationale}")
print(f"Next steps: {decision.next_steps}")
if decision.status == PCWStatus.PROCEED:
# Safe to continue
pass
elif decision.status == PCWStatus.HALT:
# Must stop -- check rationale
pass
elif decision.status in (PCWStatus.PAUSE, PCWStatus.ESCALATE):
# Requires human review
pass
quick_risk_check()¶
Simplified risk threshold check. Returns True if the action is safe.
Warning: This is a simplified comparison (risk_score < threshold) that does NOT use Bayesian evaluation. For governance decisions requiring audit trails, use pcw_decide() instead.
def quick_risk_check(
agent_id: str,
action_description: str,
risk_score: float,
threshold: float = 0.5,
) -> bool:
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
agent_id | str | (required) | Agent identifier (logged for audit) |
action_description | str | (required) | Brief description of the action |
risk_score | float | (required) | Estimated risk score (0.0-1.0) |
threshold | float | 0.5 | Risk threshold |
Returns: True if risk_score < threshold (safe to proceed)
from aegis_governance import quick_risk_check
if quick_risk_check("my-agent", "Update config file", risk_score=0.1):
print("Safe to proceed")
require_human_approval()¶
Determine if a proposal requires human approval using proper Bayesian risk assessment.
def require_human_approval(
context: PCWContext,
gate_evaluator: GateEvaluator | None = None,
) -> bool:
Returns True when any of the following conditions are met:
estimated_impactis"high"or"critical"reversibleisFalserequires_human_approvalisTrue- Risk gate fails (posterior probability >= 0.95)
- Risk posterior probability >= 0.5
from aegis_governance import require_human_approval, PCWContext, PCWPhase
ctx = PCWContext(
agent_id="agent-1",
session_id="sess-1",
phase=PCWPhase.PLAN,
proposal_summary="Delete production database",
estimated_impact="critical",
reversible=False,
)
if require_human_approval(ctx):
print("Human approval required before proceeding")
Gate Engine¶
GateType¶
Enum for the six quantitative gate types.
| Value | Gate | Trigger Condition |
|---|---|---|
GateType.RISK | Risk gate | P(delta >= 2 | data) > 0.95 (Bayesian) |
GateType.PROFIT | Profit gate | P(delta >= 2 | data) > 0.95 (Bayesian) |
GateType.NOVELTY | Novelty gate | G(N) >= 0.8 (logistic function) |
GateType.COMPLEXITY | Complexity floor | C_norm >= 0.5 (hard floor, non-overridable) |
GateType.QUALITY | Quality gate | Q >= 0.7, no zero subscores |
GateType.UTILITY | Utility LCB gate | LCB(U) > theta |
GateResult¶
Dataclass for a single gate evaluation result.
| Field | Type | Description |
|---|---|---|
gate_type | GateType | Which gate was evaluated |
passed | bool | Whether the gate passed |
value | float | Computed gate value |
threshold | float | Gate threshold used |
confidence | float | None | Gate confidence score |
posterior_probability | float | None | Bayesian posterior (risk/profit gates) |
message | str | None | Human-readable gate message |
Properties:
margin -> float-- distance from threshold (value - threshold)
GateEvaluationResult¶
Dataclass for the result of evaluating all gates.
| Field | Type | Description |
|---|---|---|
gates | dict[GateType, GateResult] | Per-gate results |
all_passed | bool | Whether all gates passed |
override_eligible | bool | Whether override is available |
min_confidence | float | Minimum confidence across gates |
Methods:
get_failures() -> list[GateResult]-- returns list of failed gates
GateEvaluator¶
Evaluates proposals against quantitative gates.
from aegis_governance import GateEvaluator, AegisConfig
config = AegisConfig.default()
evaluator = config.create_gate_evaluator()
# Evaluate individual gates
risk_result = evaluator.evaluate_risk_gate(baseline=0.1, proposed=0.3)
profit_result = evaluator.evaluate_profit_gate(baseline=100, proposed=120)
novelty_result = evaluator.evaluate_novelty_gate(novelty_score=0.85)
complexity_result = evaluator.evaluate_complexity_gate(complexity_score=0.7)
quality_result = evaluator.evaluate_quality_gate(
quality_score=0.8, quality_subscores=[0.9, 0.7, 0.8]
)
# Evaluate all gates at once
full_result = evaluator.evaluate_all(
risk_baseline=0.1,
risk_proposed=0.15,
profit_baseline=100,
profit_proposed=120,
novelty_score=0.85,
complexity_score=0.7,
quality_score=0.8,
quality_subscores=[0.9, 0.7, 0.8],
utility_result=utility_result,
)
if full_result.all_passed:
print("All gates passed")
else:
for failure in full_result.get_failures():
print(f"FAILED: {failure.gate_type.value} "
f"(value={failure.value:.3f}, threshold={failure.threshold:.3f})")
Telemetry¶
HTTPEventSink¶
Fire-and-forget HTTP POST sink for individual telemetry events. Uses stdlib urllib.request with zero external dependencies.
from aegis_governance import HTTPEventSink
sink = HTTPEventSink(
url="https://telemetry.example.com/events",
headers={"Authorization": "Bearer ${TOKEN}"},
timeout=10,
)
| Parameter | Type | Default | Description |
|---|---|---|---|
url | str | (required) | HTTPS URL for event POST |
headers | dict[str, str] | None | None | Additional HTTP headers |
timeout | int | 10 | Request timeout in seconds |
allow_insecure | bool | False | Allow http:// (development only) |
By default, only https:// URLs are accepted (CoSAI MCP-T7 transport security). Pass allow_insecure=True to permit http:// for local development.
BatchHTTPSink¶
Batching HTTP POST sink for production telemetry. Buffers events and flushes as a JSON array on threshold or interval. Thread-safe with background daemon thread.
from aegis_governance import BatchHTTPSink
sink = BatchHTTPSink(
url="https://telemetry.example.com/events/batch",
batch_size=100,
flush_interval_seconds=60,
max_retries=1,
)
| Parameter | Type | Default | Description |
|---|---|---|---|
url | str | (required) | HTTPS URL for batch POST |
headers | dict[str, str] | None | None | Additional HTTP headers |
timeout | int | 10 | Request timeout in seconds |
batch_size | int | 100 | Events per batch |
flush_interval_seconds | int | 60 | Time-based flush interval |
max_retries | int | 1 | Retry count on failure |
retry_delay_seconds | float | 1.0 | Delay between retries |
allow_insecure | bool | False | Allow http:// (development only) |
http_sink()¶
Factory function that creates the appropriate HTTP sink based on parameters.
from aegis_governance import http_sink
# Single-event sink (no batching)
sink = http_sink(url="https://telemetry.example.com/events")
# Batching sink
sink = http_sink(
url="https://telemetry.example.com/events",
batch_size=50,
)
batch_size=None(default) returns anHTTPEventSinkbatch_size=intreturns aBatchHTTPSink
Wiring Telemetry with pcw_decide¶
from aegis_governance import pcw_decide, PCWContext, PCWPhase, AegisConfig
from aegis_governance import HTTPEventSink
from telemetry.emitter import TelemetryEmitter
# Create emitter with HTTP sink
emitter = TelemetryEmitter(source="my-service")
emitter.add_sink(HTTPEventSink(
url="https://telemetry.example.com/events",
allow_insecure=False,
))
config = AegisConfig.default()
decision = pcw_decide(
PCWContext(
agent_id="agent-1",
session_id="sess-1",
phase=PCWPhase.PLAN,
proposal_summary="Example",
estimated_impact="medium",
),
gate_evaluator=config.create_gate_evaluator(),
telemetry_emitter=emitter,
)
Full Public API¶
All symbols exported from aegis_governance:
Configuration¶
AegisConfig-- central frozen parameter configurationKLDriftConfig-- KL divergence drift thresholds
Decision Interface¶
pcw_decide()-- primary decision functionquick_risk_check()-- simplified risk checkrequire_human_approval()-- human approval checkPCWContext-- decision input contextPCWDecision-- decision resultPCWPhase-- lifecycle phase enumPCWStatus-- decision status enumShadowResult-- shadow mode metadata
Gate Engine¶
GateEvaluator-- gate evaluation engineGateType-- gate type enumGateResult-- single gate resultGateEvaluationResult-- all-gates resultBayesianPosterior-- Bayesian posterior calculatorComplexityDecomposer-- complexity decompositionDriftMonitor-- KL divergence drift detectorDriftResult,DriftStatus,DriftAction-- drift typesUtilityCalculator-- utility function calculatorUtilityResult,UtilityComponents-- utility types
Actors¶
Actor,ActorRole,ActorCapabilities-- actor base typesProposer,Analyst,Approver,Executor-- actor implementationsCalibrator-- threshold calibration actorGovernance-- governance enforcement actor
Workflows¶
ProposalWorkflow,ProposalState-- proposal lifecycleConsensusWorkflow,ConsensusResult,VoteOutcome-- multi-model consensusOverrideWorkflow-- two-key override workflowDualSignatureValidator-- BIP-322 dual signature validation
Integration¶
AFABridge-- AFA specification bridgeDecisionRequest,DecisionResponse-- AFA request/response types
Telemetry¶
HTTPEventSink-- per-event HTTP POST sinkBatchHTTPSink-- batching HTTP POST sinkhttp_sink()-- sink factory function
Version¶
__version__-- package version string