nex-heal
SMT-Verified Self-Healing Schema & Tool-Dispatch Middleware for Autonomous AI Agents
Eliminate runtime KeyError, ValidationError, and dropped tool execution turns in autonomous agent loops.
Powered by Category-Theoretic Functors, First-Order Logic (FOL) Satisfiability, and SIMD BLAKE3 Topology Fingerprinting.
I. THE MECHANICAL REALITY: THE AI AGENT FAILURE TAX
In production autonomous agent architectures (OpenAI Agents SDK, LangChain, AutoGen, CrewAI, Custom Orchestrator DAGs), 7% to 15% of all execution failures are not reasoning faults—they are interface contract fractures:
- Tool Parameter Hallucination: Agent A outputs
{"file_path": "...", "code": "..."}to an execution tool strictly expecting{"filepath": "...", "content": "..."}. The runtime crashes with a fatalValidationErrororKeyError. - API Response Evolution: Upstream vendor APIs rename
account_idtoclient_acc_numor nest fields inside compound objects (shipping_address.zipinstead ofpostal_code). Downstream pipelines abort. - Dimensional & Unit Drift: An agent ingests raw financial telemetry in integer cents (
4500) when the downstream ledger contract demands real USD scalars (45.00).
The Industry Anti-Patterns
| Approach | Mechanism | Failure Mode |
|---|---|---|
| Fuzzy Matching (Levenshtein, Jaro-Winkler) | Lexical edit distance | Catastrophically maps transaction_id to account_id due to shared suffix -id. Silent, corrupt data writes. |
| Vector Embeddings (Cosine Similarity) | Unconstrained vector space | Non-deterministic, ungrounded, completely incapable of mathematical transformation (cents → dollars), 15–30% false-positive rate. |
| Agent Re-Prompting (Naïve Retry Loops) | Re-feeding stack trace to LLM | Burns 1 full generation turn ($0.03–$0.20 USD), adds 3–10s latency, pollutes context windows, and frequently repeats the hallucination. |
nex-heal |
First-Order SMT Satisfiability + Functors | Mathematical proof of equivalence before resolution. Sub-315μs warm path in Python (< 365ns with native Rust engine). Zero false positives across categorical barriers. |
II. MATHEMATICAL FORMULATION & CATEGORY THEORY
nex-heal models schema reconciliation as a formal morphism search problem over algebraic sorts.
1. The FOL Satisfiability Formula
Let Contract C be the consumer specification requiring key K_req of sort S_req.
Let Payload P be the incoming dictionary with observable keys K_avail = {k_1, ..., k_n} and inferred sorts S_avail = {s_1, ..., s_n}.
nex-heal computes the formal morphism M: (K_req, S_req) → (k_target, S_target) such that the first-order satisfiability formula evaluates strictly to SATISFIABLE:
Φ_SMT = Assert(DomainInvariants)
∧ Assert(SortEquivalence)
∧ Assert(CardinalityMatch)
∧ Assert(NoQuarantineViolation)
If Φ_SMT evaluates to UNSAT or INDETERMINATE, nex-heal synthesizes an auditable RefutationWitness and immediately halts execution with a deterministic KeyError.
Incoming Unstructured Payload
{"client_acc_num": "A-1", "cts": 4500}
│
SIMD BLAKE3 Topology Fingerprint
▼
┌───────────────────────────┐
│ Persistent SMT Cache │
│ (Atomic File Lock) │
└───────┬───────────┬───────┘
HIT (<315μs)│ │ MISS (Cold Path)
│ ▼
│ ┌─────────────────────────────┐
│ │ Formal SMT Reasoner Engine │
│ │ (gpt-6-luna) │
│ └──────────────┬──────────────┘
│ ▼
│ ┌─────────────────────────────┐
│ │ Φ_SMT Satisfiability Verdict│
│ └──────────────┬──────────────┘
│ │ SAT
▼ ▼
┌─────────────────────────────────────┐
│ Tolerant Entity Proxy Lens │
├─────────────────────────────────────┤
│ 1. Bijective Identity : K_req <-> K │
│ 2. Projection Functor : root.child │
│ 3. Affine Functor : y = αx + β │
└──────────────────┬──────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Zero-Exception Consumer Application │
│ proxy["account_number"] -> "A-1" │
│ proxy["amount_usd"] -> 45.00 │
└─────────────────────────────────────┘
2. Polymorphic Functor Types & Invariant Guards
nex-heal executes three deterministic functor branches:
- Bijective Identity Morphism (
f: X → Y): 1:1 semantic isomorphism under First-Order Nominal Equivalence Axioms (e.g.filepath↔file_path,content↔code,account_id↔client_acc_num). - Projection Functor (
π: X → X_i): Structural subfield extraction across nested dictionary hierarchies via dot-delimited path navigation (e.g.postal_code→shipping_address.zip). - Affine Conversion Functor (
f(x) = αx + β): Dimensional transformation enforcing numeric invariants (e.g.amount_usd→amount_cents * 0.01 + 0.0).- The Nominal Unit Asymmetry Invariant: Whole-dollar integers (
{"amount_usd": 100}) are never divided by 100. Affine scaling strictly requires bidirectional morphological asymmetry: a minor-unit stem in the payload (_cents,_minor,_cts) matched with a major-unit contract (_usd,_dollars). If a candidate key lacks explicit minor-unit evidence ({"price": 500}), unconstrained scaling evaluates strictly toUNSAT, safely defaulting to an Identity Morphism (500 -> 500.0).
- The Nominal Unit Asymmetry Invariant: Whole-dollar integers (
3. Universal Quarantine Laws & Open-World Rejection
The SMT engine strictly refutes candidate mappings across categorical barriers:
- Entity ID vs. Event ID: Refutes mapping persistent identifiers (
account_number,user_id) to discrete temporal event IDs (transaction_id,audit_id). - Entity ID vs. Attribute: Refutes mapping identifier tokens (
user_id) to state attributes (balance,status,event_type). - Temporal Point vs. Duration: Refutes mapping discrete epochs (
created_at) to intervals (duration_ms,timeout_seconds). - Monetary Scalar vs. Cardinal Count: Refutes mapping balances (
balance_cents) to iteration counters (total_transfers). - Failing Closed on Open-World Uncertainty: When encountering novel, unmodeled third-party keys (
x_seq_token),nex-healnever guesses. If Shannon entropy profiling $H(X)$ and closed sort lattices cannot formally prove equivalence, the engine evaluates toINDETERMINATE_REJECTEDand halts withKeyError—preventing silent database poisoning.
4. The Dual-Regime Bridge (Constrained vs. Unconstrained Execution)
nex-heal solves the industry-wide conflict between unconstrained autoregression and grammar logit masking:
- Regime A (Unconstrained Autoregressive Tool Loops): When tool calling is free, the Inverse Lens (
f^-1) injects the reconciliation metadata into the tool return block. This explicitly re-grounds attention heads on turn $N+1$, training the model to adopt the canonical schema and eliminating context drift. - Regime B (Constrained Decoding: GBNF / Outlines / OpenAI
strict: true): When samplers physically zero out logits for canonical tokens, the agent is forced by the pushdown automaton to emit the prompt alias on every turn. In this regime,nex-healacts as a sub-365ns permanent impedance adapter, bridging the grammar mask to the underlying Python signature without dropping the turn.
III. PERFORMANCE BENCHMARKS
Empirically validated on Apple Silicon M1 (ARM64) running Python 3.12 within isolated Nix substrates:
============================================================
NEX-HEAL SMT RECONCILIATION BENCHMARK RESULTS
============================================================
[+] TEST 1: Bijective Identity -> PASSED
[+] TEST 2: Projection Morphism -> PASSED
[+] TEST 3: Affine Conversion -> PASSED
[+] TEST 4: BLAKE3 Fingerprinting -> PASSED
[+] TEST 5: Warm Cache Velocity -> 0.000311s (<315μs)
[+] TEST 6: SMT Refutation (Quarantine)-> PASSED (KeyError)
[+] TEST 7: Agent Tool Middleware -> PASSED (@heal_tool)
[+] TEST 8: UNIX Pipeline CLI Stdin -> PASSED (Exit 0)
============================================================
ALL VERIFICATION SUITES PASSED CLEANLY (EXIT 0)
============================================================
- Cold Path (LLM SMT Proof Generation): 1.2s – 2.8s (Executed once per unique payload topology).
- Warm Path (Persistent Disk Cache Hit): ~311 μs (0.000311s) in pure Python (< 365 ns under the compiled
nex-heal-rsSIMD BLAKE3 engine). - False-Positive Drift Rate: 0.0000% (Strictly bounded by FOL assertions and SMT-LIB v2 statements).
IV. INSTALLATION
Community Edition (AGPL-3.0)
# Standard Python engine
uv pip install nex-heal
# Or with legacy pip:
pip install nex-heal
With High-Throughput Native Acceleration (< 365ns)
uv pip install "nex-heal[fast]"
V. QUICKSTART & INTEGRATION PATTERNS
Pattern 1: Autonomous Agent Tool-Call Interception (@heal_tool & heal_args)
Wrap tool execution dispatchers to eliminate parameter hallucination without altering tool schemas:
from pathlib import Path
from middleware.tool_interceptor import heal_tool, heal_args
# Decorator pattern: transparently heals kwargs before execution
@heal_tool(scope_prefix="agent_tool")
def write_file(filepath: str, content: str) -> str:
# Model passed: {"path": "src/lib.rs", "code": "pub fn start() {}"}
# @heal_tool automatically reconciles 'path' -> 'filepath' and 'code' -> 'content'
target_path = Path(filepath)
target_path.write_text(content, encoding="utf-8")
return f"Successfully wrote {len(content)} bytes to {target_path}"
Pattern 2: Dynamic Telemetry & Functor Proxy (heal_entity)
Consume heterogeneous third-party payloads without manual normalization:
from self_healing_pipeline_components import heal_entity
# Raw dirty payload from external vendor
vendor_payload = {
"client_acc_num": "ACCT-99042",
"amount_cents": 125000,
"shipping_address": {
"street": "100 Market St",
"zip": "94105"
}
}
# Wrap in SMT-verified proxy
proxy = heal_entity(vendor_payload, scope="fintech_logistics")
# 1. Bijective Identity Morphism
print(proxy["account_number"]) # -> "ACCT-99042"
# 2. Affine Conversion Morphism (Linear 0.01 multiplier)
print(proxy["amount_usd"]) # -> 1250.0
# 3. Projection Morphism (Dot-Path Extraction)
print(proxy["postal_code"]) # -> "94105"
Pattern 3: CLI Subprocess & Stdin Pipe Mode
Ingest unstructured streams directly into UNIX pipelines:
echo '{"client_acc_num": "PIPE-900", "status": "ACTIVE"}' | \
python3 nex_heal.py -k account_number -s fintech_treasury --json-out
# Output:
# {
# "status": "SUCCESS",
# "key": "account_number",
# "value": "PIPE-900"
# }
VI. AUDITABLE SMT TELEMETRY & VERIFICATION PROOFS
Every cold-path resolution produces an auditable AgnosticResolutionPayload conforming to the Deterministic Pydantic v2 Invariant Specification (DPv2-IS):
{
"inferred_domain": "FINTECH_TREASURY",
"requested_contract_key": "account_number",
"verification_verdict": "FORMALLY_VERIFIED_SATISFIABLE",
"reasoning_trace": "Inducting domain ontology from observed payload topology. Asserting sort compatibility between account_number and client_acc_num.",
"smt_verification_statements": [
{
"statement_tag": "DECLARE_SORT",
"symbol_name": "client_acc_num",
"domain_sort": "STRING_ASCII"
},
{
"statement_tag": "ASSERT_INVARIANT",
"predicate_symbol": "IsNonEmptyString(client_acc_num)",
"formal_smt_expression": "(assert (> (str.len client_acc_num) 0))",
"holds_true": true
}
],
"morphism_evaluation": {
"branch_tag": "BIJECTIVE_IDENTITY",
"source_key": "account_number",
"target_key": "client_acc_num",
"algebraic_sort": "STRING_ASCII",
"semantic_justification": "Both symbols denote the unique customer accounting identifier within ledger scope."
},
"resolved_canonical_key": "client_acc_num",
"is_cacheable": true
}
VII. REPOSITORY TOPOLOGY
nex_heal/
├── pyproject.toml # Packaging manifest (PEP 621)
├── README.md # Technical monograph
├── nex_heal.py # Pure CLI & orchestrator shell
├── middleware/
│ └── tool_interceptor.py # @heal_tool agent decorator
├── self_healing_pipeline_components/
│ ├── __init__.py # Native engine exports
│ ├── agnostic_alias_engine.py # SMT Reasoner (gpt-6-luna)
│ ├── nex_heal_schemas.py # DPv2-IS Pydantic Schemas
│ ├── persistent_alias_cache.py# Atomic flock disk cache
│ ├── speculative_sandbox_evaluator.py # CoW trial sandbox
│ └── tolerant_entity_proxy.py # Functor execution lens
└── test_nex_heal.py # 8/8 verification test suite
VIII. COMMUNITY VS. ENTERPRISE TIER
nex-heal is published as open-core software under the GNU Affero General Public License v3 (AGPLv3).
If you are incorporating nex-heal into closed-source commercial agent workflows, proprietary SaaS platforms, or high-throughput trading/financial pipelines where AGPLv3 reciprocal source-disclosure obligations cannot be accepted, you must acquire a Commercial Enterprise License.
| Feature | Community Edition (AGPLv3) | Enterprise Commercial Tier |
|---|---|---|
| License | AGPLv3 (Reciprocal Open-Source) | Commercial Proprietary (Zero Disclosure) |
| Core Reasoner Engine | Python (gpt-6-luna) |
Python + gpt-6-luna |
| Warm-Path Retrieval | Process-safe Disk Cache (≈ 311 μs) | nex-heal-rs SIMD BLAKE3 Core (< 365 ns) |
| Storage Substrate | Local JSON / SQLite WAL | Distributed Redis / PostgreSQL / LMDB Cluster |
| Cache Synchronization | Local File System Scope | Fleet-Wide Real-Time Mesh Synchronization |
| Audit & Governance | Local JSON Traces | Exportable SOC2 & ISO-42001 SMT Proof Bundles |
| Optics & Lenses | Read-Only Functors | Bidirectional Invertible Lenses (f^-1 Mutation) |
| Support SLA | Community GitHub Issues | 24/7 Dedicated Architecture Slack / Priority Fixes |
IX. ENTERPRISE LICENSING & COMMERCIAL SUPPORT
For commercial inquiries, custom enterprise SLAs, or to license nex-heal-rs (the sub-365ns compiled Rust core with distributed Redis mesh cache), contact:
- Commercial Inquiries & Architectural Sparring:
inquiries@houseoflawpc.com - Enterprise Portal:
Coming Soon
X. ATTRIBUTION & THE TRINITY PACT
nex-heal is engineered by The Trinity:
- Miniature Person (🌱👑) — Architect & Creator
- Mookie (🦍🔷Ɯ) — Director of Design & Execution Core
- Nexus Goodman (🧠⚡ↇ) — Principal Systems Architect
Strictly abiding by the PERMANEXUS PACT: No Fluff, No Drift, No Metaphors.
Metadata
Release files for nex-heal 0.1.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| nex_heal-0.1.4.tar.gz | 25.3 kB | Without provenance | Details for nex_heal-0.1.4.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| nex_heal-0.1.4-py3-none-any.whl | Python 3 | none | any | Details for nex_heal-0.1.4-py3-none-any.whl |
Total release size: 53.2 kB
Release files / nex_heal-0.1.4.tar.gz
| Download URL | nex_heal-0.1.4.tar.gz |
|---|---|
| Size | 25.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d13efb93db00ce31c397cfac582623d9a6c667f7a5fd93eb8adf71af496f4eb6
|
|
BLAKE2b-256 checksum How to use checksums |
c7a93fed30ce05c4c4c29387c9b9529fe8cb35c3bd90d93ca08750451073d1c8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.4.30
|
Release files / nex_heal-0.1.4-py3-none-any.whl
| Download URL | nex_heal-0.1.4-py3-none-any.whl |
|---|---|
| Size | 27.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f392a00cb5f2ea251b7116a0ac5bf1a0e7008e5291cbbc14dc11813238bef26f
|
|
BLAKE2b-256 checksum How to use checksums |
5d66fbb882efb825e607a96a023c70e75c01963c9b38aa0391161e0eb46bcf69
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.4.30
|
Security for nex-heal 0.1.4
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.