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 Trusted Execution Environment (TEE) module provides a software simulation of hardware-backed enclave primitives. It is explicitly not a real SGX, SEV, or TrustZone enclave — it emulates the same attestation, sealing, measurement, and watchdog contracts in pure Python so that governance scenarios can be tested without specialised hardware. In a production deployment these classes would be replaced by — or wrapped inside — a real hardware TEE runtime.
All cryptographic measurements and sealed-storage guarantees provided by this module are simulated. Randomness is sourced from secrets.token_bytes, and hashes are standard SHA-256, but there is no hardware-enforced isolation boundary. Do not use this module to protect sensitive data in production.

Enumerations

WatchdogState

Represents the current health state of a WatchdogTimer.
MemberDescription
NORMALHeartbeats are arriving within the configured timeout.
HEARTBEAT_MISSEDAt least one heartbeat has been missed; timer is degraded.
DEADLOCKEDGovernance paralysis detected by the DeadlockBreaker.
COLD_BOOTEnclave has been reset via cold-boot recovery.

Data Classes

AttestationReport

Returned by SimulatedEnclave.attest(). Captures the enclave measurement and a hash of its sealed-data store at the moment of attestation.
enclave_hash
str
required
SHA-256 hex digest representing the simulated measurement of the enclave’s code and initial data. Generated fresh from secrets.token_bytes at enclave construction or after a cold boot.
is_debug
bool
required
Always False in the current simulation. In a real TEE this flag would indicate a debug-mode enclave whose secrets should not be trusted.
sealed_data_hash
str
required
SHA-256 hex digest of the current _sealed_storage dict at attestation time. Changes every time new data is sealed.
valid
bool
default:"True"
Attestation validity flag. Can be set to False by external verifiers to mark a revoked report.

WatchdogEvent

A single timestamped entry in a WatchdogTimer’s event log.
event_type
str
required
Short event identifier, e.g. "heartbeat_missed" or "heartbeat_restored".
timestamp
float
required
Unix timestamp (time.time()) recorded at the moment the event was logged.
details
str
default:"\"\""
Human-readable description, e.g. "Last heartbeat 0.12s ago".

BatchProposal

Describes a batch of action indices submitted to BatchVerifier for Merkle-tree validation.
action_indices
List[int]
required
Ordered list of action indices that make up the batch macro-trajectory.
aggregate_risk
float
default:"0.0"
Caller-supplied risk estimate for the whole batch. Validated against BatchVerifier.risk_threshold.
diversity_score
float
default:"1.0"
Caller-supplied diversity score. Overridden by BatchVerifier, which recomputes diversity from action_indices internally.
batch_metadata
Dict[str, Any]
default:"{}"
Arbitrary key-value metadata attached by the optimizer (e.g. episode ID, strategy name).

Classes

SimulatedEnclave

The central TEE abstraction. Maintains an isolated sealed-storage dictionary and a simulated measurement register. Once attest() is called the enclave is considered attested and remote verifiers can check the returned AttestationReport.
from governance.tee.enclave import SimulatedEnclave, AttestationReport
from governance.identity.keys import GenesisManifest

Constructor

genesis
Optional[GenesisManifest]
default:"None"
Optional genesis manifest to associate with this enclave at creation time. If omitted the enclave starts in an un-initialised state and must be primed with cold_boot() before it is used in a governed run.

attest() -> AttestationReport

Marks the enclave as attested and returns a snapshot attestation report. The sealed_data_hash in the report reflects the sealed-storage state at the moment of the call. Subsequent seal() calls do not invalidate the report; the caller must re-attest to get an up-to-date hash.
report
AttestationReport
Attestation report with enclave_hash, is_debug=False, sealed_data_hash, and valid=True.
enclave = SimulatedEnclave()
report = enclave.attest()
print(report.enclave_hash)      # e.g. "a3f9c2...d81b"
print(report.is_debug)          # False
print(report.valid)             # True
print(enclave.is_attested)      # True

seal(key, value)

Writes value into the simulated sealed-storage under key. In a real TEE this would encrypt the value with a hardware-bound key that only this exact enclave measurement can unseal.
key
str
required
Storage key.
value
Any
required
Arbitrary Python value to store. Must be serialisable if sealed_data_hash comparisons matter.

unseal(key) -> Optional[Any]

Retrieves a previously sealed value.
key
str
required
Storage key to look up.
value
Optional[Any]
The sealed value, or None if key was not found.
enclave.seal("root_key", "secret-material-abc123")
enclave.seal("quorum_threshold", 0.67)

print(enclave.unseal("root_key"))         # "secret-material-abc123"
print(enclave.unseal("quorum_threshold")) # 0.67
print(enclave.unseal("nonexistent"))      # None

verify_measurement(expected_hash) -> bool

Compares expected_hash against the internal measurement register. Returns True only on an exact SHA-256 hex-string match. Used by external verifiers to confirm they are talking to the expected enclave version.
expected_hash
str
required
SHA-256 hex digest to compare against the current measurement.
match
bool
True if the hashes match exactly; False otherwise.
report = enclave.attest()
print(enclave.verify_measurement(report.enclave_hash))  # True
print(enclave.verify_measurement("deadbeef"))           # False

cold_boot(genesis)

Resets the enclave to a clean state: all sealed data is erased, a new measurement hash is generated, and the attestation flag is cleared. The provided genesis manifest becomes the new root of trust.
genesis
GenesisManifest
required
The genesis manifest that primes the fresh enclave state.
from governance.identity.keys import GenesisManifest

manifest = GenesisManifest(ontology_hash="abc123")
manifest.seal()

enclave.cold_boot(manifest)
print(enclave.is_attested)    # False — must re-attest after cold boot
print(enclave.unseal("root_key"))  # None — sealed storage wiped

Property: is_attested

is_attested
bool
True after the first successful attest() call; reset to False after cold_boot().

WatchdogTimer

A heartbeat-based liveness monitor. The governed compute loop must call heartbeat() at least once every heartbeat_timeout_ms milliseconds. If the heartbeat is missed the state transitions to HEARTBEAT_MISSED and an event is logged.
from governance.tee.watchdog import WatchdogTimer, WatchdogState

Constructor

heartbeat_timeout_ms
float
default:"100.0"
Maximum allowed interval between consecutive heartbeat() calls, in milliseconds. Internally stored as seconds.

heartbeat()

Resets the internal timestamp to time.time(). If the watchdog was previously in HEARTBEAT_MISSED state it returns to NORMAL and logs a "heartbeat_restored" event.

check() -> WatchdogState

Evaluates current liveness. If the elapsed time since the last heartbeat exceeds heartbeat_timeout the state transitions to HEARTBEAT_MISSED and a "heartbeat_missed" event is appended. Returns the current state without modifying it if the state is already COLD_BOOT.
state
WatchdogState
The current watchdog state after the liveness check.

Property: state

state
WatchdogState
The current state without performing a fresh liveness check.

get_events() -> List[WatchdogEvent]

events
List[WatchdogEvent]
A copy of all logged WatchdogEvent objects in chronological order.
import time

watchdog = WatchdogTimer(heartbeat_timeout_ms=50.0)
watchdog.heartbeat()
print(watchdog.check())   # WatchdogState.NORMAL

time.sleep(0.1)           # miss the 50 ms deadline
print(watchdog.check())   # WatchdogState.HEARTBEAT_MISSED

watchdog.heartbeat()      # recover
print(watchdog.check())   # WatchdogState.NORMAL

for event in watchdog.get_events():
    print(event.event_type, event.details)
# heartbeat_missed  Last heartbeat 0.10s ago
# heartbeat_restored  Heartbeat restored

DeadlockBreaker

Detects governance paralysis by counting consecutive deliberation cycles that produce no decision. When the stall count reaches threshold_cycles the breaker signals that a cold-boot should be triggered.
from governance.tee.watchdog import DeadlockBreaker

Constructor

threshold_cycles
int
default:"100"
Number of consecutive decision-free cycles before the breaker fires.

record_cycle(decision_produced)

Records the outcome of one governance cycle.
decision_produced
bool
required
Pass True if the cycle produced a governance decision; False if the deliberation stalled with no output. A True value resets the internal stall counter to zero.

check() -> bool

Returns True exactly once — on the cycle that first crosses the threshold — then False forever until reset() is called. This edge-trigger semantics means the caller only needs to handle the cold-boot trigger once per stall episode.
should_cold_boot
bool
True if a cold boot should be triggered; False otherwise.

reset()

Clears the stall counter and the triggered flag, allowing the breaker to arm again for the next episode.

Property: is_deadlocked

is_deadlocked
bool
True if stalled_cycles >= threshold. Does not set the triggered flag.

Property: stalled_cycles

stalled_cycles
int
Number of consecutive cycles that have produced no decision since the last reset or decision.

Property: total_cold_boots

total_cold_boots
int
Cumulative number of cold-boot triggers since this DeadlockBreaker instance was created.
breaker = DeadlockBreaker(threshold_cycles=3)

breaker.record_cycle(False)
breaker.record_cycle(False)
breaker.record_cycle(False)

print(breaker.is_deadlocked)   # True
print(breaker.stalled_cycles)  # 3
print(breaker.check())         # True  — triggers cold boot
print(breaker.check())         # False — already triggered

breaker.reset()
print(breaker.stalled_cycles)  # 0
print(breaker.total_cold_boots) # 1

BatchVerifier

Validates a BatchProposal against risk and diversity thresholds, and constructs a Merkle root over the action-index sequence. The optimizer submits a batch root hash; the TEE validates the macro-trajectory; individual actions are then executed with Merkle proofs.
from governance.tee.batch import BatchVerifier, BatchProposal

Constructor

risk_threshold
float
default:"0.7"
Maximum allowed aggregate_risk for a batch to pass validation.
diversity_min
float
default:"0.3"
Minimum required diversity score. Diversity is computed as unique_actions / total_actions.

validate_batch(proposal) -> Tuple[bool, str]

Validates the proposal and computes a Merkle root if it passes.
proposal
BatchProposal
required
The batch proposal to validate.
result
Tuple[bool, str]
A (valid, message) tuple. On success message contains the first 16 hex characters of the Merkle root. On failure message explains which check failed.
verifier = BatchVerifier(risk_threshold=0.7, diversity_min=0.3)

proposal = BatchProposal(
    action_indices=[1, 2, 3, 4, 5],
    aggregate_risk=0.4,
)
ok, msg = verifier.validate_batch(proposal)
print(ok, msg)
# True  Batch valid. Root: 3f8a1c2d9e7b0f4a...

verify_proof(action_index, proof, root) -> bool

Verifies a Merkle inclusion proof for a single action.
action_index
int
required
The action whose membership is being verified.
proof
List[str]
required
Ordered list of sibling hashes from leaf to root.
root
str
required
The trusted Merkle root hash returned by a previous validate_batch() call.
valid
bool
True if the reconstructed root matches root.

Constant-Time Helpers

The governance.tee.constant_time module provides flat-branch and fixed-iteration primitives that execute in the same number of CPU cycles regardless of input data, protecting the governance hot-path from cache-timing side-channel attacks.

cmov(condition, a, b) -> T

Branchless conditional move. Returns a if condition is True, b otherwise, without using a Python if.
condition
bool
required
Selector.
a
T
required
Value returned when condition is True.
b
T
required
Value returned when condition is False.

constant_time_compare(a, b) -> bool

Compares two byte strings in constant time using XOR accumulation. Returns False immediately (non-constant) only if the lengths differ; equal-length inputs are always fully iterated.
a
bytes
required
First byte string.
b
bytes
required
Second byte string.

fixed_iteration_map(items, fn, max_size, sentinel) -> List[Any]

Applies fn to exactly max_size items. If len(items) < max_size, the remaining slots are filled with sentinel before fn is applied, ensuring the loop body executes a constant number of times.
items
List[T]
required
Input list.
fn
Callable[[T], Any]
required
Mapping function.
max_size
int
required
Fixed iteration count.
sentinel
T
required
Padding value for slots beyond len(items).

oblivious_access(data, index, default) -> T

Reads data[index] by iterating over the full list and selecting via cmov, so the memory access pattern does not reveal index to a side-channel observer.
data
List[T]
required
Source list.
index
int
required
Index to read obliviously.
default
T
required
Value returned if data is empty.

Combined Usage Example

from governance.tee.enclave import SimulatedEnclave
from governance.tee.watchdog import WatchdogTimer, DeadlockBreaker, WatchdogState
from governance.tee.batch import BatchVerifier, BatchProposal
from governance.identity.keys import GenesisManifest, GenesisMultisig

# --- Enclave setup ---
multisig = GenesisMultisig(threshold=3, total_holders=5)
manifest = GenesisManifest(
    ontology_hash="abc123def456",
    core_commitments_hash="fedcba654321",
    multisig=multisig,
)
manifest.seal()

enclave = SimulatedEnclave(genesis=manifest)
report = enclave.attest()
print(f"Attested: {enclave.is_attested}")         # True
print(f"Measurement: {report.enclave_hash[:16]}") # first 16 hex chars

# Seal sensitive parameters
enclave.seal("quorum_threshold", 0.67)
enclave.seal("root_signing_key", "sim-key-material")
print(enclave.unseal("quorum_threshold"))  # 0.67

# Verify the enclave hasn't been tampered with
print(enclave.verify_measurement(report.enclave_hash))  # True

# --- Watchdog ---
watchdog = WatchdogTimer(heartbeat_timeout_ms=200.0)
breaker = DeadlockBreaker(threshold_cycles=5)

# Simulated governance loop
for step in range(10):
    watchdog.heartbeat()
    decision_made = step % 3 != 0   # stall every 3rd step
    breaker.record_cycle(decision_made)

    state = watchdog.check()
    if breaker.check():
        print(f"Step {step}: deadlock — triggering cold boot")
        enclave.cold_boot(manifest)
        breaker.reset()

# --- Batch validation ---
verifier = BatchVerifier(risk_threshold=0.6, diversity_min=0.4)
proposal = BatchProposal(
    action_indices=[0, 1, 2, 3, 0, 1, 4],
    aggregate_risk=0.35,
)
ok, message = verifier.validate_batch(proposal)
print(ok, message)  # True  Batch valid. Root: ...

Build docs developers (and LLMs) love