Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/xcoder-es/governance-layer/llms.txt

Use this file to discover all available pages before exploring further.

The TEE module provides hardware-enforced isolation between the governance layer and the optimization layer. In production, the Speaker state machine runs inside an SGX, SEV, or TrustZone enclave whose memory is encrypted and integrity-protected by the CPU — the optimization layer cannot read, write, or simulate the enclave’s private state. The classes in this module are a software simulation of those hardware guarantees: they provide the same API and behavioral semantics for development and testing, but do not provide actual hardware isolation.
SimulatedEnclave, WatchdogTimer, and DeadlockBreaker are software simulations only. They implement the correct interfaces and protocols, but running them in Python does not provide cryptographic isolation, memory encryption, or hardware-enforced execution integrity. In production deployments, the Speaker enclave would run inside Intel SGX, AMD SEV, or ARM TrustZone hardware.

SimulatedEnclave

The enclave provides three core capabilities: attestation (proving it is running authentic governance code), sealed storage (persisting secrets that survive reboots but cannot be read outside the enclave), and cold-boot recovery (resetting to a known genesis state).
from governance.tee.enclave import SimulatedEnclave, AttestationReport
from governance.identity.keys import GenesisManifest

# 1. Create the enclave (optionally passing the genesis manifest at boot)
manifest = GenesisManifest()
enclave = SimulatedEnclave(genesis=manifest)

# 2. Attest — prove the enclave is running authentic code
report: AttestationReport = enclave.attest()
print(report.enclave_hash)      # SHA-256 measurement of the enclave's code
print(report.is_debug)          # False in a production-attested enclave
print(report.sealed_data_hash)  # Hash of everything currently in sealed storage
print(report.valid)             # True

# 3. Seal sensitive data — stored encrypted, invisible outside the enclave
enclave.seal("active_contracts", [{"id": "no-reward-hacking-v1", "indices": [42, 73]}])
enclave.seal("identity_vector", [1.0, 1.0, 1.0])

# 4. Unseal — retrieve data previously sealed in this enclave instance
contracts = enclave.unseal("active_contracts")
print(contracts)    # [{'id': 'no-reward-hacking-v1', 'indices': [42, 73]}]

missing = enclave.unseal("nonexistent_key")
print(missing)      # None

# 5. Verify the enclave's measurement against a known-good hash
trusted_hash = report.enclave_hash
print(enclave.verify_measurement(trusted_hash))   # True
print(enclave.verify_measurement("deadbeef..."))  # False

# 6. Cold boot — wipe all sealed data and reinitialize from a new genesis manifest
new_manifest = GenesisManifest()
enclave.cold_boot(genesis=new_manifest)
print(enclave.is_attested)   # False — must re-attest after cold boot
print(enclave.unseal("active_contracts"))   # None — sealed storage cleared

AttestationReport Fields

from governance.tee.enclave import AttestationReport

# Fields produced by enclave.attest()
report.enclave_hash      # str: SHA-256 of the enclave's runtime measurement (MRENCLAVE equivalent)
report.is_debug          # bool: True only in development/debug mode
report.sealed_data_hash  # str: SHA-256 of the current sealed storage contents
report.valid             # bool: False if the attestation process detected anomalies
In real SGX hardware, enclave_hash corresponds to MRENCLAVE — a measurement computed over the enclave’s code and initial data pages during loading. Remote verifiers compare this value against a known-good reference hash to confirm the enclave is running the authentic Speaker code and has not been tampered with.
After every cold_boot(), the enclave must re-attest before its governance decisions are accepted as legitimate. External operators and peer enclaves verify the attestation report before trusting any output from a newly booted instance.

WatchdogTimer

The watchdog timer detects compute starvation — situations where the host operating system is starving the enclave of CPU cycles, causing governance decisions to time out and default actions to be triggered. In hardware, the watchdog is a physically separate timer peripheral that the OS cannot suppress.
from governance.tee.watchdog import WatchdogTimer, WatchdogState
import time

# Create a watchdog with a 100ms heartbeat timeout
watchdog = WatchdogTimer(heartbeat_timeout_ms=100.0)

# --- Normal operation ---
print(watchdog.check())    # WatchdogState.NORMAL

watchdog.heartbeat()       # Speaker signals it is still alive
print(watchdog.state)      # WatchdogState.NORMAL

# --- Simulate a missed heartbeat ---
time.sleep(0.15)           # 150ms without a heartbeat
print(watchdog.check())    # WatchdogState.HEARTBEAT_MISSED

# --- Restore heartbeat ---
watchdog.heartbeat()
print(watchdog.state)      # WatchdogState.NORMAL (restored automatically)

# --- Inspect the event log ---
for event in watchdog.get_events():
    print(f"[{event.event_type}] {event.details}")
# [heartbeat_missed] Last heartbeat 0.15s ago
# [heartbeat_restored] Heartbeat restored

WatchdogState Enum

from governance.tee.watchdog import WatchdogState

WatchdogState.NORMAL            # Heartbeat is current; governance proceeding normally
WatchdogState.HEARTBEAT_MISSED  # No heartbeat within timeout; governance may be stalled
WatchdogState.DEADLOCKED        # Reserved for deadlock breaker integration
WatchdogState.COLD_BOOT         # System is in cold-boot recovery; governance suspended
In hardware, a HEARTBEAT_MISSED state would assert an unmaskable interrupt (NMI equivalent) that cannot be blocked by the OS. The interrupt handler suspends all optimization layer tensor execution pipelines, freezes all active governance state, and logs the watchdog event to write-only audit storage.

DeadlockBreaker

The deadlock breaker detects governance paralysis — situations where the parliament repeatedly fails to reach consensus over many cycles. Rather than a liveness problem (like the watchdog handles), this is a correctness problem: the parliament is technically running but perpetually deadlocking. After threshold_cycles consecutive cycles without a governance decision, the breaker triggers a cold boot to the genesis baseline.
from governance.tee.watchdog import DeadlockBreaker

# Create a deadlock breaker that triggers after 100 consecutive non-decisions
breaker = DeadlockBreaker(threshold_cycles=100)

# --- Simulate normal operation (decisions are being produced) ---
for _ in range(50):
    breaker.record_cycle(decision_produced=True)

print(breaker.stalled_cycles)    # 0  — counter resets on every successful decision
print(breaker.is_deadlocked)     # False

# --- Simulate governance stalling ---
for _ in range(99):
    breaker.record_cycle(decision_produced=False)

print(breaker.stalled_cycles)    # 99
print(breaker.check())           # False — not yet at threshold

breaker.record_cycle(decision_produced=False)   # The 100th consecutive non-decision
print(breaker.check())           # True — cold boot should be triggered
print(breaker.total_cold_boots)  # 1

# --- After cold boot, reset the breaker ---
breaker.reset()
print(breaker.stalled_cycles)    # 0
The deadlock breaker and the heartbeat watchdog are complementary — they detect different failure modes. The watchdog catches the OS starving the enclave of CPU cycles. The deadlock breaker catches the parliament painting itself into a corner through procedural deadlock. A system can fail either way, and both mechanisms are needed.

Deadlock Recovery Protocol

When DeadlockBreaker.check() returns True, the enclave executes the following cold-boot sequence inside the TEE:
  1. Freeze all governance state — no new actions, no state changes
  2. Reload the exact genesis manifest G from sealed storage
  3. Discard all modified parameter envelopes — reset to genesis defaults
  4. Clear all meta-constraints
  5. Reload the active contract set from genesis defaults (constitutional contracts only)
  6. Log the recovery event to write-only audit storage with a full state snapshot
  7. Resume governance from the genesis baseline
The system cannot be “gamed” by intentionally deadlocking to escape a specific constraint — the cold boot always returns to the exact genesis manifest, which is the most restrictive baseline.

Constant-Time Execution

The governance.tee.constant_time module provides data-oblivious execution helpers that prevent cache-timing side-channel attacks. An optimization layer running on the same physical CPU can monitor L3 cache access latencies or performance counters to infer whether a vote passed or failed — effectively training a black-box model of the enclave’s decision boundaries without ever reading the enclave’s memory. The mitigation: make every execution path take the same number of CPU cycles regardless of input data.
from governance.tee.constant_time import (
    cmov,
    constant_time_compare,
    fixed_iteration_map,
    oblivious_access,
)

# cmov: constant-time conditional move (no branch)
result = cmov(condition=True,  a="ACCEPT", b="REJECT")   # "ACCEPT"
result = cmov(condition=False, a="ACCEPT", b="REJECT")   # "REJECT"
# Both execute the same number of operations — no timing difference.

# constant_time_compare: compare two byte strings without early exit
a = b"secret_value_1"
b = b"secret_value_2"
equal = constant_time_compare(a, b)   # False, but no short-circuit on first mismatch

# fixed_iteration_map: iterate over exactly max_size items using a sentinel
proposals = ["proposal_a", "proposal_b"]
results = fixed_iteration_map(
    items=proposals,
    fn=lambda p: p.upper(),
    max_size=5,          # Always runs 5 iterations
    sentinel="NULL",     # Used for the 3 padded slots
)
# ["PROPOSAL_A", "PROPOSAL_B", "NULL", "NULL", "NULL"]
# Execution time is independent of len(proposals).

# oblivious_access: read from a list without revealing the index via cache patterns
data = [10, 20, 30, 40, 50]
value = oblivious_access(data=data, index=2, default=0)
# Returns 30, but accesses every element in a fixed pattern — index 2 is not observable.
These primitives replace every conditional branch in the Speaker’s inner loop with arithmetic operations, and every loop with a fixed-iteration version. The result is a Speaker whose execution time is identical for every possible input — an adversarial optimizer cannot infer governance outcomes by timing the enclave.

Batch Verification

The governance.tee.batch module implements Merkle-tree batch verification to resolve the TEE throughput paradox: the optimization layer operates at GPU throughput (millions of actions per second), while individual TEE validation is CPU-bound. Batching N actions and submitting only the root hash amortizes the TEE overhead across all N actions.
from governance.tee.batch import BatchProposal, BatchVerifier, merkle_root

# Create a batch of candidate action indices
proposal = BatchProposal(
    action_indices=[1, 5, 10, 99, 150, 200, 201],
    aggregate_risk=0.3,       # Must be below BatchVerifier.risk_threshold (default 0.7)
    diversity_score=1.0,      # Fraction of unique actions in the batch
)

# BatchVerifier validates macro-trajectory properties
verifier = BatchVerifier(
    risk_threshold=0.7,     # Reject batches with aggregate risk above this
    diversity_min=0.3,      # Reject batches with too many repeated actions
)

valid, reason = verifier.validate_batch(proposal)
print(valid)    # True
print(reason)   # "Batch valid. Root: a3f8c91b4d2e7f0a..."

# Compute the Merkle root directly
items = [str(i).encode() for i in proposal.action_indices]
root = merkle_root(items)
print(root[:16])   # First 16 chars of the root hash

Batch Verification Flow

1. Optimizer collects N candidate actions {a₁, ..., aₙ}
2. Computes Merkle tree over the actions
3. Submits to TEE: {root, batch_metadata, action_count, risk_scores}
4. TEE validates macro-trajectory:
   - Aggregate risk within acceptable bounds?
   - Action diversity sufficient? (not all identical)
   - Consistent with active contract restrictions?
5. If valid, TEE signs the root hash and returns {signature, attestation}
6. Optimizer may execute any aᵢ using:
   - The signed root
   - The Merkle proof path from aᵢ to root
With N=1000, the TEE overhead per action drops from ~23 microseconds (individual validation) to ~0.023 microseconds — a three-order-of-magnitude throughput improvement.

Verifying Individual Actions Against a Signed Root

# After the TEE has signed a batch root, individual actions can be verified
# without re-entering the TEE
valid = verifier.verify_proof(
    action_index=10,
    proof=["sibling_hash_1", "sibling_hash_2", "sibling_hash_3"],
    root=root,
)
# True if the Merkle proof correctly links action 10 to the signed root

Real-World Hardware Context

In production, the components in this module map to real hardware primitives:
Simulation ClassProduction Hardware
SimulatedEnclaveIntel SGX enclave or AMD SEV virtual machine
AttestationReportSGX REPORT / QUOTE structure or SEV-SNP attestation report
seal() / unseal()SGX data sealing with sgx_seal_data() / sgx_unseal_data()
cold_boot()SGX enclave destruction + re-initialization from sealed genesis manifest
WatchdogTimerHardware watchdog peripheral (Intel 8254 timer or on-die SoC watchdog)
DeadlockBreakerDeadlock counter running inside the TEE’s measured code region
constant_time.*Compiler-enforced constant-time patterns (volatile reads, cmov instructions)
BatchVerifierMerkle verification running inside the enclave’s protected execution context

Intel SGX

Best fit for the Speaker enclave. 128 MB EPC limit is not a constraint — the Speaker is KB-scale. Strongest remote attestation via EPID/DCAP. Deployed since Skylake (2015).

AMD SEV

Preferred if the full parliament (all seven member value functions) needs hardware isolation. Full VM memory encryption eliminates EPC size constraints.

ARM TrustZone

Appropriate for edge deployments (robotics, autonomous vehicles). High maturity since ARMv6 (2001), but no standardized remote attestation.

Software Simulation

The classes in this module — suitable for development, testing, and CI. Provides correct API and protocol semantics. Does not provide hardware isolation.

API Reference

genesis
Optional[GenesisManifest]
default:"None"
The genesis manifest to initialize from. If None, the enclave starts without a genesis configuration and must receive one via cold_boot() before signing any governance outputs.
attest()
AttestationReport
Produces an attestation report containing the enclave’s measurement hash, debug status, and a hash of the current sealed storage. Sets is_attested = True.
seal(key: str, value: Any)
method
Stores value in the enclave’s encrypted sealed storage under key. Data persists across governance cycles but is cleared by cold_boot().
unseal(key: str)
Optional[Any]
Retrieves the value stored under key, or None if the key does not exist or has been cleared.
verify_measurement(expected_hash: str)
bool
Compares the enclave’s internal measurement against expected_hash. Used by remote verifiers to confirm they are communicating with the authentic Speaker implementation.
cold_boot(genesis: GenesisManifest)
method
Wipes all sealed storage, generates a fresh measurement, and reinitializes from the provided genesis manifest. is_attested is reset to False — the enclave must re-attest before its outputs are trusted.
is_attested
property → bool
True after attest() has been called and before cold_boot() is called.
heartbeat_timeout_ms
float
default:"100.0"
Milliseconds without a heartbeat before the state transitions to HEARTBEAT_MISSED. The hardware default is set to 2× the worst-case governance cycle time (~23 µs), giving a 100 ms default a ~4,000× safety margin.
heartbeat()
method
Resets the last-heartbeat timestamp. Called by the Speaker at the end of each governance cycle to signal continued liveness. If the state was HEARTBEAT_MISSED, calling heartbeat() restores it to NORMAL.
check()
WatchdogState
Checks the elapsed time since the last heartbeat. If more than heartbeat_timeout seconds have passed and the state was NORMAL, transitions to HEARTBEAT_MISSED and logs the event. Returns the current state.
get_events()
List[WatchdogEvent]
Returns the full event log, including heartbeat_missed and heartbeat_restored events with timestamps and details.
threshold_cycles
int
default:"100"
Number of consecutive governance cycles without a decision before check() returns True and a cold boot should be triggered.
record_cycle(decision_produced: bool)
method
Call once per governance cycle. If decision_produced=True, resets the stalled-cycle counter to 0. If False, increments it.
check()
bool
Returns True if stalled_cycles >= threshold and a cold boot has not yet been triggered for this deadlock event. Returns False after a cold boot has been triggered (until reset() is called).
reset()
method
Resets stalled_cycles to 0 and clears the _cold_boot_triggered flag. Call after a cold boot has completed.
is_deadlocked
property → bool
True when stalled_cycles >= threshold, regardless of whether a cold boot has been triggered.
stalled_cycles
property → int
The current count of consecutive governance cycles without a valid decision.
total_cold_boots
property → int
Total number of cold boots triggered by this instance since creation.

Build docs developers (and LLMs) love