Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AHEM Banner

AHEM v0.1

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.

Core Contract

  • 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

Stable TensorLogic v0.1.0 API Sequence

  1. let mut symbols = SymbolTable::new();
  2. symbols.add_domain(DomainInfo::new(...)); symbols.add_predicate(PredicateInfo::new(...));
  3. let mut compiler = ahem::bridge::TlCompiler::new(symbols);
  4. let graph = compiler.compile(&rule)?;
  5. let executor = Scirs2Exec::new();
  6. executor.add_tensor(...); let output = executor.forward(&graph)?;

Zero-Copy Interop

ahem::interop provides raw-pointer/stride adapters between:

  • faer::MatRef / faer::MatMut
  • scirs2_core::ndarray::ArrayView2 / ArrayViewMut2

These adapters are intended to avoid heap allocation and avoid clone/copy at the boundary.

Live Injection (Rolling SSM Feed)

ahem::live provides:

  • TrajectorySource trait for live [batch, seq, feat] windows
  • LiveInjector runner that evaluates each rolling window through CognitiveEngineBridge

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_inject

Then pipe CSV observations (4 floats per line in current demo config).

Rule Pack Engineering

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.

Dynamic Rule Synthesis (Phase 1)

ahem::dynamic_rule_synthesis provides a complete pipeline for postmortem rule generation:

  • FailureEvent - structured failure event from external systems
  • LatentSnapshotRingBuffer - ring buffer capturing projected latent snapshots with TTL-based pruning
  • FailureEventIngestor - JSONL bus reader for failure events
  • Phase1Manager - orchestrates event ingestion, latent correlation, synthesis, and candidate persistence
  • SynthesisEngine trait - pluggable synthesis backends (default: ConstrainedDslSynthesizer)
  • CandidateStore - filesystem-backed persistence for synthesized rule candidates
  • ActiveRuleRegistry - in-memory registry of activated rule graphs
  • approve_candidate - compiles and activates a staged candidate into the live registry
  • mark_candidate_approved - transitions candidate state from Staged to Approved

Candidate lifecycle: Staged -> Approved -> Activated

Cognitive Rollback (Phase 3)

ahem::cognitive_rollback provides token-level retry control:

  • RollbackOps trait - interface for LLM session control (ban token, rewind state, set retry sampling)
  • RetryController - bounded retry loop with per-step token banning
  • GateDecision - Allow, Retry, or Abort

OS Sandbox Bridge

ahem::os_bridge provides guarded OS command execution for bspwm environments:

  • OsSandboxBridge - evaluates actions through TensorLogic safety rules before execution
  • AgentAction - strict JSON schema for exec_bspc or exec_bash commands
  • GateDecision - Allow or Veto
  • 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, workspaces
  • query_desktop_context - queries bspwm via bspc

MNN FFI Integration

LFM Latent Interception (MNN Surgery)

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):

  1. Interception point: The hook captures the final hidden state tensor from the last transformer block, immediately before lm_head projection
  2. Thread safety: A mutex (g_lfm_latent_mutex) protects the shared tensor pointer
  3. Layout normalization: ensure_dense_layout() converts packed tensors (e.g., NC4HW4) to dense standard layout before exposing to Rust
  4. C-ABI export: get_lfm_latent_pointer() returns the raw float* pointer and dimensions via out_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 Linking

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.

Rust FFI Bridge

ahem::mnn_ffi provides live gate callbacks for MNN-based LLM inference:

  • fetch_and_evaluate_lfm_state - fetches latent pointer from MNN and evaluates rule
  • register_live_gate_callback - registers per-step ALLOW/REJECT callback into MNN decode loop
  • LiveGateRegistration - RAII handle that unregisters callback on drop
  • GateTelemetry - callback call count, last score, threshold, decision, retry count, rewind calls
  • run_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

Persistent Memory Vault

ahem::memory::vault (feature ruvector-vault) provides vector-backed persistence:

  • SafetyVault - VectorDB-backed store for latent snapshots, rule graphs, and their links
  • LatentSnapshotRecord - 350-dimensional vector with metadata
  • RuleGraphRecord - rule AST JSON + fingerprint
  • RuleSnapshotLink - triggered_by relationship between rules and snapshots
  • persist_candidate_activation - stores activated candidates with full provenance
  • get_active_boundaries - queries active rules and their linked snapshots

Quickstart

cargo check
cargo test

Enable TensorLogic bridge compilation:

cargo check --features tensorlogic

Enable all features (SSM live + MNN FFI + vector vault):

cargo check --features tensorlogic,ssm-live,mnn-ffi,ruvector-vault

Binaries

  • ssm_live_inject - stdin CSV observer -> SSM prediction -> TensorLogic evaluation (feature ssm-live)
  • mnn_live_gate - MNN latent pointer polling / decode-gated LLM inference (feature mnn-ffi)
    • Modes: poll (default), callback, decode
  • Governance CLI: ahem rules list / ahem rules approve --candidate=<id> (feature tensorlogic)

Minimal End-to-End Example (Grounding Path)

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 Flags

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

About

AHEM: Neuro-Symbolic System 1 → System 2 Cognitive Bridge | A zero-allocation Rust engine evaluating continuous neural latent states to pivot between System 1 local reflexes and System 2 deep reasoning. Intercepting inference mid-flight, AHEM mathematically guarantees safety and routes complex logic before any text token is generated.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages