AEGISdocs
API Reference

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]"          # 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.

from aegis_governance import AegisConfig

Fields

FieldTypeDefaultDescription
epsilon_Rfloat0.01Risk epsilon floor (prevents division by zero)
epsilon_Pfloat0.01Profit epsilon floor
risk_trigger_factorfloat2.0Normalized risk threshold multiplier
profit_trigger_factorfloat2.0Normalized profit threshold multiplier
trigger_confidence_probfloat0.95Bayesian posterior confidence threshold
novelty_N0float0.7Novelty gate logistic inflection point
novelty_kfloat10.0Novelty gate logistic steepness
novelty_thresholdfloat0.6Novelty gate pass threshold
complexity_floorfloat0.5Complexity hard floor (cannot be overridden)
quality_min_scorefloat0.7Minimum quality score
quality_no_zero_subscoreboolTrueReject zero quality subscores
gammafloat0.3Utility function risk aversion
kappafloat1.0Utility function scaling factor
phi_Sfloat100.0Utility function setup cost
phi_Dfloat2000.0Utility function disruption cost
lcb_alphafloat0.05Utility LCB significance level
migration_budgetfloat5000.0Utility migration budget
utility_thresholdfloat0.0Utility gate LCB threshold
kl_driftKLDriftConfigSee belowKL divergence drift detection config
telemetry_url`strNone`None
mcp_rate_limitint60MCP 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 exist
  • ImportError -- if PyYAML is not installed (install with pip 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+ observations
config.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.

FieldTypeDefaultDescription
tau_warningfloat0.3KL divergence warning threshold
tau_criticalfloat0.5KL divergence critical threshold
window_daysint30Drift observation window in days

Decision Interface

PCWContext

Dataclass containing all inputs for a governance decision.

from aegis_governance import PCWContext, PCWPhase

Fields

FieldTypeDefaultDescription
agent_idstr(required)Agent/caller identifier
session_idstr(required)Session identifier for correlation
phasePCWPhase(required)Current lifecycle phase
proposal_summarystr(required)Brief description of the proposal
estimated_impactstr(required)Impact level: low, medium, high, critical
risk_baselinefloat0.0Current risk level before change (0.0-1.0)
risk_proposedfloat0.0Predicted risk after change (0.0-1.0)
profit_baselinefloat0.0Current profit/performance metric
profit_proposedfloat0.0Expected profit/performance after change
novelty_scorefloat0.5How unprecedented the proposal is (0.0-1.0)
complexity_scorefloat0.5Normalized complexity (higher = simpler, 0.0-1.0)
quality_scorefloat0.7Overall proposal quality (0.0-1.0)
quality_subscoreslist[float][0.7, 0.7, 0.7]Detailed quality subscores
utility_result`UtilityResultNone`None
requires_human_approvalboolFalseForce human approval
time_sensitiveboolFalseMark as time-sensitive
reversibleboolTrueWhether the action is reversible
metadatadict[str, Any]{}Additional key-value metadata

PCWPhase

Enum for Plan-Commit-Work lifecycle phases.

ValueDescription
PCWPhase.PLANPlanning phase -- evaluate feasibility
PCWPhase.COMMITCommit phase -- authorize execution
PCWPhase.WORKWork phase -- execute with monitoring

PCWStatus

Enum for decision outcomes.

ValueDescription
PCWStatus.PROCEEDSafe to proceed
PCWStatus.PAUSEPause for human review
PCWStatus.HALTStop immediately
PCWStatus.ESCALATEEscalate to higher authority

PCWDecision

Dataclass containing the full decision result.

FieldTypeDescription
statusPCWStatusDecision outcome
confidencefloatMinimum confidence across all gates
gates_passedintNumber of gates that passed
gates_failedintNumber of gates that failed
failing_gateslist[str]Names of failed gates
rationalestrHuman-readable decision rationale
next_stepslist[str]Recommended next actions
constraintslist[str]Active constraints (e.g., drift warnings)
decision_idstrUnique decision UUID
timestampdatetimeUTC timestamp of the decision
override_eligibleboolWhether override is possible
override_requireslist[str]Roles required for override
gate_evaluation`GateEvaluationResultNone`
decision_trace`DecisionTraceNone`
shadow_result`ShadowResultNone`
drift_result`DriftResultNone`

ShadowResult

Dataclass attached to PCWDecision.shadow_result when shadow_mode=True.

FieldTypeDescription
drift_result`DriftResultNone`
observation_valueslist[float]Observed risk/profit deltas
baseline_hash`strNone`
shadow_onlyboolAlways 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:

ParameterTypeDefaultDescription
contextPCWContext(required)Proposal context with metrics
gate_evaluator`GateEvaluatorNone`None
prometheus_exporter`PrometheusExporterNone`None
rbac_enforcer`RBACEnforcerNone`None
shadow_modeboolFalseEvaluate without enforcing (for calibration). Requires Professional tier or higher on the SaaS API.
drift_monitor`DriftMonitorNone`None
telemetry_emitter`TelemetryEmitterNone`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
    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:

ParameterTypeDefaultDescription
agent_idstr(required)Agent identifier (logged for audit)
action_descriptionstr(required)Brief description of the action
risk_scorefloat(required)Estimated risk score (0.0-1.0)
thresholdfloat0.5Risk 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_impact is "high" or "critical"
  • reversible is False
  • requires_human_approval is True
  • 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.

ValueGateTrigger Condition
GateType.RISKRisk gateP(delta >= 2 | data) > 0.95 (Bayesian)
GateType.PROFITProfit gateP(delta >= 2 | data) > 0.95 (Bayesian)
GateType.NOVELTYNovelty gateG(N) >= 0.6 (logistic function)
GateType.COMPLEXITYComplexity floorC_norm >= 0.5 (hard floor, non-overridable)
GateType.QUALITYQuality gateQ >= 0.7, no zero subscores
GateType.UTILITYUtility LCB gateLCB(U) > theta

GateResult

Dataclass for a single gate evaluation result.

FieldTypeDescription
gate_typeGateTypeWhich gate was evaluated
passedboolWhether the gate passed
valuefloatComputed gate value
thresholdfloatGate threshold used
confidence`floatNone`
posterior_probability`floatNone`
message`strNone`

Properties:

  • margin -> float -- distance from threshold (value - threshold)

GateEvaluationResult

Dataclass for the result of evaluating all gates.

FieldTypeDescription
gatesdict[GateType, GateResult]Per-gate results
all_passedboolWhether all gates passed
override_eligibleboolWhether override is available
min_confidencefloatMinimum 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,
)
ParameterTypeDefaultDescription
urlstr(required)HTTPS URL for event POST
headers`dict[str, str]None`None
timeoutint10Request timeout in seconds
allow_insecureboolFalseAllow 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,
)
ParameterTypeDefaultDescription
urlstr(required)HTTPS URL for batch POST
headers`dict[str, str]None`None
timeoutint10Request timeout in seconds
batch_sizeint100Events per batch
flush_interval_secondsint60Time-based flush interval
max_retriesint1Retry count on failure
retry_delay_secondsfloat1.0Delay between retries
allow_insecureboolFalseAllow 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 an HTTPEventSink
  • batch_size=int returns a BatchHTTPSink

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 HSM

Parameters:

ParameterTypeDefaultDescription
provider_typestr"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:

VariableDescription
AEGIS_KMS_KEY_IDKMS key ARN or alias
AEGIS_KMS_WRAPPED_PRIVATE_KEYBase64-encoded KMS-encrypted private key
AEGIS_MASTER_KEK_PUBLICBase64-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:

VariableDescription
AEGIS_HSM_PKCS11_LIBPath to PKCS#11 shared library
AEGIS_HSM_TOKEN_LABELHSM token label
AEGIS_HSM_PINUser PIN
AEGIS_HSM_WRAPPING_KEY_LABELAES wrapping key label in HSM
AEGIS_HSM_WRAPPED_PRIVATE_KEYBase64-encoded wrapped private key
AEGIS_MASTER_KEK_PUBLICBase64-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")
FlagTrue when
KMS_KEK_AVAILABLEboto3 is installed
HSM_KEK_AVAILABLEpython-pkcs11 is installed
HYBRID_KEM_AVAILABLEliboqs-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 configuration
  • KLDriftConfig -- KL divergence drift thresholds

Decision Interface

  • pcw_decide() -- primary decision function
  • quick_risk_check() -- simplified risk check
  • require_human_approval() -- human approval check
  • PCWContext -- decision input context
  • PCWDecision -- decision result
  • PCWPhase -- lifecycle phase enum
  • PCWStatus -- decision status enum
  • ShadowResult -- shadow mode metadata

Gate Engine

  • GateEvaluator -- gate evaluation engine
  • GateType -- gate type enum
  • GateResult -- single gate result
  • GateEvaluationResult -- all-gates result
  • BayesianPosterior -- Bayesian posterior calculator
  • ComplexityDecomposer -- complexity decomposition
  • DriftMonitor -- KL divergence drift detector
  • DriftResult, DriftStatus, DriftAction -- drift types
  • UtilityCalculator -- utility function calculator
  • UtilityResult, UtilityComponents -- utility types

Actors

  • Actor, ActorRole, ActorCapabilities -- actor base types
  • Proposer, Analyst, Approver, Executor -- actor implementations
  • Calibrator -- threshold calibration actor
  • Governance -- governance enforcement actor

Workflows

  • ProposalWorkflow, ProposalState -- proposal lifecycle
  • ConsensusWorkflow, ConsensusResult, VoteOutcome -- multi-model consensus
  • OverrideWorkflow -- two-key override workflow
  • DualSignatureValidator -- BIP-322 dual signature validation

Integration

  • AFABridge -- AFA specification bridge
  • DecisionRequest, DecisionResponse -- AFA request/response types

Telemetry

  • HTTPEventSink -- per-event HTTP POST sink
  • BatchHTTPSink -- batching HTTP POST sink
  • http_sink() -- sink factory function

Key Management

  • get_kek_provider() -- KEK provider factory (auto-detects KMS/HSM/env)
  • AWSKMSKEKProvider -- AWS KMS envelope encryption provider
  • HSMKEKProvider -- PKCS#11 HSM envelope encryption provider
  • KEKProvider -- abstract base class for key providers
  • KEKMetadata -- provider metadata dataclass
  • KMS_KEK_AVAILABLE -- True if boto3 installed
  • HSM_KEK_AVAILABLE -- True if python-pkcs11 installed
  • HYBRID_KEM_AVAILABLE -- True if liboqs-python installed

Version

  • __version__ -- package version string

On this page