Python SDK Reference
AEGIS Governance Decision SDK -- quantitative governance for engineering decisions.
AEGIS Governance Decision SDK -- quantitative governance for engineering decisions.
Installation
Source access requires a BSL-1.1 license. Clone the repository and install locally:
# Core SDK (from repo root)
pip install -e "."
# With optional dependencies
pip install -e ".[engine]" # scipy for z-score computation
pip install -e ".[telemetry]" # prometheus_client for metrics
pip install -e ".[config]" # pyyaml for YAML config loading
pip install -e ".[crypto]" # BIP-340 Schnorr signatures
pip install -e ".[persistence]" # SQLAlchemy async workflow storage
pip install -e ".[kms]" # AWS KMS envelope encryption
pip install -e ".[hsm]" # HSM PKCS#11 envelope encryption
pip install -e ".[all]" # EverythingQuick 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.
from aegis_governance import AegisConfigFields
| 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.6 | 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 |
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.
config = AegisConfig.default()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.
config = AegisConfig.from_yaml("schema/interface-contract.yaml")Raises:
FileNotFoundError-- if the YAML file does not existImportError-- if PyYAML is not installed (install withpip install -e ".[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+ observationsconfig.create_utility_calculator() -> UtilityCalculator
Create a UtilityCalculator configured with this config's utility parameters.
calculator = config.create_utility_calculator()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.
from aegis_governance import PCWContext, PCWPhaseFields
| 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 |
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` |
decision_trace | `DecisionTrace | None` |
shadow_result | `ShadowResult | None` |
drift_result | `DriftResult | None` |
ShadowResult
Dataclass attached to PCWDecision.shadow_result when shadow_mode=True.
| Field | Type | Description |
|---|---|---|
drift_result | `DriftResult | None` |
observation_values | list[float] | Observed risk/profit deltas |
baseline_hash | `str | None` |
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 |
prometheus_exporter | `PrometheusExporter | None` | None |
rbac_enforcer | `RBACEnforcer | None` | None |
shadow_mode | bool | False | Evaluate without enforcing (for calibration). Requires Professional tier or higher on the SaaS API. |
drift_monitor | `DriftMonitor | None` | None |
telemetry_emitter | `TelemetryEmitter | None` | None |
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
passquick_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.6 (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` |
posterior_probability | `float | None` |
message | `str | None` |
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 |
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 |
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,
)Key Management (KEK Providers)
AEGIS supports envelope encryption for HybridKEM private keys at rest. HSM/KMS wraps the key material; post-quantum crypto operations run in software.
get_kek_provider()
Factory function that returns the best available KEK provider.
from aegis_governance import get_kek_provider
provider = get_kek_provider() # auto-detect
provider = get_kek_provider("kms") # force AWS KMS
provider = get_kek_provider("hsm") # force PKCS#11 HSMParameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
provider_type | str | "auto" | One of "auto", "kms", "hsm", "environment", "in_memory" |
Auto-detection order: KMS → HSM → Environment → InMemory.
Returns: KEKProvider
Raises: RuntimeError if the requested provider type is unavailable or misconfigured.
AWSKMSKEKProvider
AWS KMS envelope encryption provider. Wraps the HybridKEM private key using
KMS Encrypt/Decrypt. Requires pip install -e ".[kms]".
from aegis_governance import AWSKMSKEKProvider
# From explicit parameters
provider = AWSKMSKEKProvider(
kms_key_id="arn:aws:kms:us-west-2:123456789012:key/...",
wrapped_private_key=b"...",
public_key_bytes=b"...",
)
# From environment variables (recommended)
provider = AWSKMSKEKProvider.from_environment()Environment Variables:
| Variable | Description |
|---|---|
AEGIS_KMS_KEY_ID | KMS key ARN or alias |
AEGIS_KMS_WRAPPED_PRIVATE_KEY | Base64-encoded KMS-encrypted private key |
AEGIS_MASTER_KEK_PUBLIC | Base64-encoded HybridKEM public key |
HSMKEKProvider
PKCS#11 HSM envelope encryption provider. Uses CKM_AES_KEY_WRAP_KWP
(RFC 5649) with session pooling. Requires pip install -e ".[hsm]".
Supported HSMs: AWS CloudHSM, YubiHSM 2, SoftHSM2.
from aegis_governance import HSMKEKProvider
# From environment variables (recommended)
provider = HSMKEKProvider.from_environment()Environment Variables:
| Variable | Description |
|---|---|
AEGIS_HSM_PKCS11_LIB | Path to PKCS#11 shared library |
AEGIS_HSM_TOKEN_LABEL | HSM token label |
AEGIS_HSM_PIN | User PIN |
AEGIS_HSM_WRAPPING_KEY_LABEL | AES wrapping key label in HSM |
AEGIS_HSM_WRAPPED_PRIVATE_KEY | Base64-encoded wrapped private key |
AEGIS_MASTER_KEK_PUBLIC | Base64-encoded HybridKEM public key |
Session pool size defaults to 4; configure via pool_size parameter.
Availability Flags
from aegis_governance import KMS_KEK_AVAILABLE, HSM_KEK_AVAILABLE, HYBRID_KEM_AVAILABLE
if KMS_KEK_AVAILABLE:
provider = get_kek_provider("kms")| Flag | True when |
|---|---|
KMS_KEK_AVAILABLE | boto3 is installed |
HSM_KEK_AVAILABLE | python-pkcs11 is installed |
HYBRID_KEM_AVAILABLE | liboqs-python + native liboqs are installed |
Override Workflow
AEGIS enforces two-key approval for overriding failed governance gates. The
DualSignatureValidator validates dual signatures from Risk Lead and Security
Lead before approving.
For the complete workflow guide, see Override Workflow.
Approver with Signature Verification
from aegis_governance import Approver
from crypto.bip322_provider import BIP322Provider
approver = Approver(
actor_id="risk-lead-1",
name="Risk Lead",
is_risk_lead=True,
signature_verifier=BIP322Provider(),
)
result = approver.authorize_override(
proposal_id="prop-001",
failed_gates=["risk"],
justification="Emergency hotfix required",
signature=risk_sig_b64, # base64-encoded BIP-322 signature
public_key=risk_public_key, # 32-byte x-only public key
)DualSignatureValidator Two-Key Flow
from aegis_governance import DualSignatureValidator, OverrideWorkflow
# Create validator and message hash
validator = DualSignatureValidator()
msg_hash = validator.create_message_hash(
proposal_id="prop-001",
justification="Emergency hotfix",
failed_gates=["risk"],
)
# Use OverrideWorkflow for full two-key flow
workflow = OverrideWorkflow(
proposal_id="prop-001",
justification="Emergency hotfix",
failed_gates=["risk"],
requested_by="engineer-1",
)
# Each custodian adds their signature
workflow.add_signature("risk-lead-1", "risk_lead", risk_sig_b64, risk_pub_b64)
workflow.add_signature("sec-lead-1", "security_lead", sec_sig_b64, sec_pub_b64)
result = workflow.get_result()
if result.approved:
print(f"Override approved until {result.expires_at}")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
Key Management
get_kek_provider()-- KEK provider factory (auto-detects KMS/HSM/env)AWSKMSKEKProvider-- AWS KMS envelope encryption providerHSMKEKProvider-- PKCS#11 HSM envelope encryption providerKEKProvider-- abstract base class for key providersKEKMetadata-- provider metadata dataclassKMS_KEK_AVAILABLE--Trueif boto3 installedHSM_KEK_AVAILABLE--Trueif python-pkcs11 installedHYBRID_KEM_AVAILABLE--Trueif liboqs-python installed
Version
__version__-- package version string