AHEM is a deterministic neuro-symbolic bridge crate that maps System 1 latent trajectories to System 2 TensorLogic rule evaluation. It provides a complete pipeline from live SSM latent inference through grounding, rule compilation, evaluation, dynamic rule synthesis, OS sandbox safety, cognitive rollback, and persistent memory.
- Input latent shape:
[batch, seq, feat] - Projection: temporal mean over
seq->[batch, feat] - Grounding: deterministic feature index to
(domain_row, domain_col)mapping - Output: TensorLogic-compatible 2D predicate tensor
let mut symbols = SymbolTable::new();symbols.add_domain(DomainInfo::new(...)); symbols.add_predicate(PredicateInfo::new(...));let mut compiler = ahem::bridge::TlCompiler::new(symbols);let graph = compiler.compile(&rule)?;let executor = Scirs2Exec::new();executor.add_tensor(...); let output = executor.forward(&graph)?;
ahem::interop provides raw-pointer/stride adapters between:
faer::MatRef/faer::MatMutscirs2_core::ndarray::ArrayView2/ArrayViewMut2
These adapters are intended to avoid heap allocation and avoid clone/copy at the boundary.
ahem::live provides:
TrajectorySourcetrait for live[batch, seq, feat]windowsLiveInjectorrunner that evaluates each rolling window throughCognitiveEngineBridge
This is the integration seam for wiring real ssm-latent-rs inference output into AHEM.
ahem::ssm_live adds a concrete source implementation:
SsmLatentSource(stepwise inference-backed rolling window emitter)SsmLiveConfig(Mamba/SSM + stream shape configuration)
Run demo live injector:
cargo run --features ssm-live --bin ssm_live_injectThen pipe CSV observations (4 floats per line in current demo config).
Versioned rule packs live under rulepacks/.
- Schema and loader:
ahem::rules::RulePack - Anomaly gate pack:
rulepacks/anomaly_gate_v1.json - Hardware safety pack:
rulepacks/hardware_safety_v1.json - BSPWM sandbox pack:
rulepacks/bspwm_safety_v1.json
The pack defines:
- domains
- predicates
- hard and soft rule expressions
and can be converted into TensorLogic symbol tables + compiled expressions.
ahem::dynamic_rule_synthesis provides a complete pipeline for postmortem rule generation:
FailureEvent- structured failure event from external systemsLatentSnapshotRingBuffer- ring buffer capturing projected latent snapshots with TTL-based pruningFailureEventIngestor- JSONL bus reader for failure eventsPhase1Manager- orchestrates event ingestion, latent correlation, synthesis, and candidate persistenceSynthesisEnginetrait - pluggable synthesis backends (default:ConstrainedDslSynthesizer)CandidateStore- filesystem-backed persistence for synthesized rule candidatesActiveRuleRegistry- in-memory registry of activated rule graphsapprove_candidate- compiles and activates a staged candidate into the live registrymark_candidate_approved- transitions candidate state from Staged to Approved
Candidate lifecycle: Staged -> Approved -> Activated
ahem::cognitive_rollback provides token-level retry control:
RollbackOpstrait - interface for LLM session control (ban token, rewind state, set retry sampling)RetryController- bounded retry loop with per-step token banningGateDecision-Allow,Retry, orAbort
ahem::os_bridge provides guarded OS command execution for bspwm environments:
OsSandboxBridge- evaluates actions through TensorLogic safety rules before executionAgentAction- strict JSON schema forexec_bspcorexec_bashcommandsGateDecision-AlloworVeto- Safety scoring for config files, network access, and destructive deletes
- Failure event logging to JSONL bus on command errors
ahem::bspwm_ipc provides bspwm desktop context queries:
BspwmDesktopContext- active window, workspace, monitor, workspacesquery_desktop_context- queries bspwm viabspc
The integration modifies MNN's LLM forward pass to intercept the continuous latent state before it is projected into text logits by lm_head. This is done via a C++ hook (mnn_hooks/mnn_lfm_latent_hook.cpp):
- Interception point: The hook captures the final hidden state tensor from the last transformer block, immediately before
lm_headprojection - Thread safety: A mutex (
g_lfm_latent_mutex) protects the shared tensor pointer - Layout normalization:
ensure_dense_layout()converts packed tensors (e.g., NC4HW4) to dense standard layout before exposing to Rust - C-ABI export:
get_lfm_latent_pointer()returns the rawfloat*pointer and dimensions viaout_rows/out_cols
The hook is integrated into the MNN LLM runtime (e.g., project/llm/llm.cpp) and must be called from the forward path where the final hidden state exists.
build.rs links against MNN shared libraries when mnn-ffi feature is enabled:
libMNN.so(core)libMNN_Express.so(express)libllm.so(LLM runtime)
Library paths can be overridden via environment variables: MNN_LIB_DIR, MNN_CORE_LIB_NAME, MNN_LLM_LIB_NAME, MNN_EXPRESS_LIB_NAME.
ahem::mnn_ffi provides live gate callbacks for MNN-based LLM inference:
fetch_and_evaluate_lfm_state- fetches latent pointer from MNN and evaluates ruleregister_live_gate_callback- registers per-step ALLOW/REJECT callback into MNN decode loopLiveGateRegistration- RAII handle that unregisters callback on dropGateTelemetry- callback call count, last score, threshold, decision, retry count, rewind callsrun_llm_prompt_with_registered_gate/run_llm_prompt_without_gate- LLM inference with/without gate
Safety invariants:
- Null-pointer check before unsafe view construction
- Synchronous critical section via
LatentReadGuard(release on drop) - Active rule registry overlay evaluation
- Zero heap allocation at the C++/Rust boundary
ahem::memory::vault (feature ruvector-vault) provides vector-backed persistence:
SafetyVault- VectorDB-backed store for latent snapshots, rule graphs, and their linksLatentSnapshotRecord- 350-dimensional vector with metadataRuleGraphRecord- rule AST JSON + fingerprintRuleSnapshotLink-triggered_byrelationship between rules and snapshotspersist_candidate_activation- stores activated candidates with full provenanceget_active_boundaries- queries active rules and their linked snapshots
cargo check
cargo testEnable TensorLogic bridge compilation:
cargo check --features tensorlogicEnable all features (SSM live + MNN FFI + vector vault):
cargo check --features tensorlogic,ssm-live,mnn-ffi,ruvector-vaultssm_live_inject- stdin CSV observer -> SSM prediction -> TensorLogic evaluation (featuressm-live)mnn_live_gate- MNN latent pointer polling / decode-gated LLM inference (featuremnn-ffi)- Modes:
poll(default),callback,decode
- Modes:
- Governance CLI:
ahem rules list/ahem rules approve --candidate=<id>(featuretensorlogic)
use ahem::GroundingSchema;
use scirs2_core::ndarray::array;
let schema = GroundingSchema::new(
3,
1,
3,
vec![(0, 0), (0, 1), (0, 2)],
)?;
let latent = array![
[[1.0, 3.0, 5.0], [3.0, 5.0, 7.0]],
[[2.0, 4.0, 6.0], [4.0, 6.0, 8.0]],
]; // [batch=2, seq=2, feat=3]
let predicate = schema.ground_latent_to_predicate(&latent)?;
assert_eq!(predicate.shape(), &[1, 3]);| Feature | Description |
|---|---|
tensorlogic |
Enables TensorLogic compiler/executor bridge |
ssm-live |
Enables SSM latent source + live injection binary |
mnn-ffi |
Enables MNN FFI gate callback integration |
ruvector-vault |
Enables vector-backed persistent memory vault |
