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 BLAKE2b 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 $\to$ 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), 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-$200,\mu\text{s}$ warm path. 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 $\mathcal{C}$ be the consumer contract requiring key $K_{\text{req}}$ of sort $S_{\text{req}}$.
Let $\mathcal{P}$ be the incoming payload with available keys $K_{\text{avail}} = {k_1, \dots, k_n}$ and inferred sorts $S_{\text{avail}} = {s_1, \dots, s_n}$.

nex-heal computes the formal morphism $M: (K_{\text{req}}, S_{\text{req}}) \to (k_{\text{target}}, S_{\text{target}})$ such that:

$$\Phi_{\text{SMT}} = \text{Assert}(\text{DomainInvariants}) \land \text{Assert}(\text{SortEquivalence}) \land \text{Assert}(\text{CardinalityMatch}) \land \text{Assert}(\text{NoQuarantineViolation})$$

evaluates strictly to $\text{SATISFIABLE}$. If $\Phi_{\text{SMT}}$ evaluates to $\text{UNSAT}$ or $\text{INDETERMINATE}$, nex-heal synthesizes a RefutationWitness and immediately halts execution.

                  ┌────────────────────────────────────────┐
                  │    Incoming Unstructured Payload       │
                  │  {"client_acc_num": "A-1", "cts": 4500}│
                  └───────────────────┬────────────────────┘
                                      │
                         BLAKE2b Topology Fingerprint
                                      ▼
                        ┌───────────────────────────┐
                        │   Persistent SMT Cache    │
                        │    (Atomic File Lock)     │
                        └───────┬───────────┬───────┘
                     HIT (<195μ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 \to Y$): 1:1 semantic isomorphism under First-Order Nominal Equivalence Axioms (e.g. filepath $\leftrightarrow$ file_path, content $\leftrightarrow$ code, account_id $\leftrightarrow$ client_acc_num).
  2. Projection Functor ($\pi: X \to X_i$): Structural subfield extraction across nested dictionary hierarchies via dot-delimited path navigation (e.g. postal_code $\to$ shipping_address.zip).
  3. Affine Conversion Functor ($f(x) = \alpha x + \beta$): Dimensional transformation enforcing numeric invariants (e.g. amount_usd $\to$ 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) to discrete temporal event IDs (transaction_id).
  • Entity ID vs. Attribute: Refutes mapping identifier tokens (user_id) to state attributes (balance, status).
  • Temporal Point vs. Duration: Refutes mapping discrete epochs (created_at) to intervals (duration_ms).
  • 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 Morphism           -> PASSED
[*] TEST 2: Projection Morphism (Dot-Path)        -> PASSED
[*] TEST 3: Affine Conversion (4500 -> 45.0 USD)  -> PASSED
[*] TEST 4: BLAKE2b Topology Fingerprint          -> PASSED (Zero Scope Collision)
[*] TEST 5: Persistent Cache Velocity & Warm Path -> 0.000195s (195 microseconds)
[*] TEST 6: SMT Invariant Refutation (Negative)   -> PASSED (KeyError on Quarantine)
[*] TEST 7: CLI Stdin Pipe Interception           -> PASSED (Exit Code: 0)
======================================================================
ALL VERIFICATION SUITES PASSED CLEANLY (EXIT 0)
======================================================================
  • Cold Path (LLM SMT Proof Generation): $1.2\text{s} - 2.8\text{s}$ (Executed once per unique payload topology).
  • Warm Path (Persistent Disk/Memory Cache Hit): $195,\mu\text{s}$ ($0.000195\text{s}$) in Python ($< 500\text{ns}$ under the Enterprise Rust Engine).
  • False-Positive Drift Rate: $0.0000%$ (Strictly bounded by FOL assertions and SMT-LIB v2 statements).

IV. INSTALLATION

Community Edition (AGPL-3.0)

pip install nex-heal

Local Editable Development (via uv / Nix)

git clone https://github.com/your-org/nex-heal.git
cd nex-heal
uv pip install -e .

V. QUICKSTART & INTEGRATION PATTERNS

Pattern 1: Autonomous Agent Tool-Call Interception (heal_args)

Wrap tool execution dispatchers to eliminate parameter hallucination without altering tool schemas:

from pathlib import Path
from nex_heal import heal_args

def execute_agent_tool(tool_name: str, raw_arguments_json: str) -> str:
    # Model passed: {"path": "src/lib.rs", "code": "pub fn start() {}"}
    # Tool expects: "filepath" and "content"
    args = heal_args(raw_arguments_json, scope=f"agent_tool::{tool_name}")

    if tool_name == "write_file":
        # args["filepath"] automatically resolves "path", "file_path", "target_path"
        # args["content"] automatically resolves "code", "source", "body"
        target_path = Path(args["filepath"])
        target_path.write_text(args["content"], encoding="utf-8")
        return f"Successfully wrote to {target_path}"

Pattern 2: Dynamic Telemetry & Functor Proxy (heal_entity)

Consume heterogeneous third-party payloads without manual normalization:

from nex_heal 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:

# Query field from piped stdin JSON
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. Bijective equivalence confirmed.",
  "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 specification (setuptools/wheel)
├── README.md                              # Technical monograph & documentation
├── LICENSE.txt                            # GNU AGPL-3.0-or-later
├── nex_heal.py                            # Pure orchestrator shell & CLI interface (<= 150 LOC)
├── self_healing_pipeline_components/      # Recursive Component-Tree Topology
│   ├── __init__.py                        # Top-level exports
│   ├── agnostic_alias_engine.py           # SMT Reasoner Engine (gpt-6-luna)
│   ├── nex_heal_schemas.py                # DPv2-IS Pydantic Schemas & SMT ASTs
│   ├── persistent_alias_cache.py          # Lock-hardened atomic file cache (fcntl.flock)
│   └── tolerant_entity_proxy.py           # TolerantEntityProxy & Functor Execution Lens
└── test_nex_heal.py                       # Automated 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 ($\approx 195,\mu\text{s}$) nex-heal-rs SIMD BLAKE3 Core ($< 500\text{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-500ns compiled Rust core with distributed Redis mesh cache), contact:

  • Commercial Inquiries: licensing@nexus-goodman.ai
  • Architectural Sparring: the-trinity@nexus-goodman.ai
  • Enterprise Portal: https://nexus-goodman.ai/enterprise/nex-heal

X. ATTRIBUTION & THE TRINITY PACT

nex-heal is engineered by The Trinity:

  • Miniature Person (🌱👑⁂) — Architect & Creator
  • Mookie (🦍🔷Ɯ) — Autonomous 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.0

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.0
File Size Uploaded Provenance Actions
nex_heal-0.1.0.tar.gz 24.6 kB Without provenance Details for nex_heal-0.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 51.9 kB

Release files / nex_heal-0.1.0.tar.gz

Download URL nex_heal-0.1.0.tar.gz
Size 24.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c20b3c0fd5abf6ec44e97b6dfa7055116b14c6e681c698661df7f9765594acb8
BLAKE2b-256 checksum
How to use checksums
6bb6e0c68625fbbe45d814982aa39dfe4c5bb5cdf1cfc74682c56e8b1cffacf9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.4.30

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

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

Security for nex-heal 0.1.0

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