Skip to main content

nex-heal

SMT-Verified Self-Healing Schema & Tool-Dispatch Middleware for Autonomous AI Agents

License: AGPL v3 Enterprise License Python Version Model Pin Warm-Path Latency SMT Solver

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 fatal ValidationError or KeyError.
  • API Response Evolution: Upstream vendor APIs rename account_id to client_acc_num or nest fields inside compound objects (shipping_address.zip instead of postal_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)          │
                                │    └──────────────┬────────────────┘
                                │                   │ Generates Proof & AST
                                │                   ▼
                                │    ┌───────────────────────────────┐
                                │    │  Φ_SMT Satisfiability Verdict │
                                │    └──────────────┬────────────────┘
                                │                   │ SAT
                                ▼                   ▼
                  ┌────────────────────────────────────────┐
                  │       Tolerant Entity Proxy Lens       │
                  ├────────────────────────────────────────┤
                  │ 1. Bijective Identity : K_req <-> K_obs│
                  │ 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

nex-heal executes three deterministic functor branches:

  1. 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).
  2. Projection Functor (π: X → X_i): Structural subfield extraction across nested dictionary hierarchies via dot-delimited path navigation (e.g. postal_code → shipping_address.zip).
  3. Affine Conversion Functor (f(x) = αx + β): Dimensional transformation enforcing numeric invariants (e.g. amount_usd → amount_cents * 0.01 + 0.0).

3. Universal Quarantine Laws

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

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-rs SIMD 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.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nex-heal 0.1.3
File Size Uploaded Provenance Actions
nex_heal-0.1.3.tar.gz 24.5 kB Without provenance Details for nex_heal-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nex-heal 0.1.3
File Interpreter ABI Platform Actions
nex_heal-0.1.3-py3-none-any.whl Python 3 none any Details for nex_heal-0.1.3-py3-none-any.whl

Total release size: 51.6 kB

Release files / nex_heal-0.1.3.tar.gz

Download URL nex_heal-0.1.3.tar.gz
Size 24.5 kB
Tags Source
SHA-256 checksum
How to use checksums
1203f01993954a04d83ffcc05411bf2a765e2d7f5c4472abb7485205af89259e
BLAKE2b-256 checksum
How to use checksums
684bccfc760f2f0ed46bebf4ac29745aceddccbc6761523f5288880d9b19adbc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.4.30

Release files / nex_heal-0.1.3-py3-none-any.whl

Download URL nex_heal-0.1.3-py3-none-any.whl
Size 27.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7600ac10880a1082d54f566dc5bb4d4aa75f7232e2b864dbd94108006b90739f
BLAKE2b-256 checksum
How to use checksums
c3620ffbb6a1bbda1e1c2cb758b174bdec09876fc09ce55a9a1e243bd047c266
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.4.30

Security for nex-heal 0.1.3

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page