Architecture & Language Guide · Neuro-Symbolic Programming

Neuro-Symbolic Programming in Axioma: Neural Proposes; Symbolic Checks, Grounds, Optimizes, and Explains

Status: Live Implementation & Language Guide — December 2026. Every code fence in this guide is executed against axioma --no-kb during verification; see also Manual §30.2 and Cheatsheet §§18–19.

Companion essays & studies: Axioma vs. McCarthy's Advice Taker; Axioma and the Calculemus Lineage; Epistemic Grounding; Gaps & Gluts.

Overview

Modern AI applications face a structural divide:

Axioma unites both halves inside a single programming language and four-repository ecosystem without letting statistical guesses masquerade as proven truth. Every neural output enters the runtime under an explicit epistemic grounding ceiling ("hypothesis" or "datum", never "axiom" or "theorem"), and earns promotion only by passing deterministic symbolic checks, exact probabilistic inference, gradient-based calibration, or universal Z3 verification.

Unstructured Input ("Typhoon halts Hsinchu 3nm wafer cluster for 3 weeks.")
       │
       ▼
┌──────────────────────────────────────────────────────────────────────────┐
│ 1. PERCEIVE & LINK (Neural Proposal — Capped at @hypothesis)             │
│    • ai.soft_match(text, kb_entities, opts)  ─► dense / cassette / 3-gram│
│    • ai.infer(text, TargetType, opts)        ─► checked(val, TargetType) │
└──────────────────────────────────────────────────────────────────────────┘
       │
       ▼
┌──────────────────────────────────────────────────────────────────────────┐
│ 2. REASON, WEIGH & CALIBRATE (Symbolic + Differentiable Engines)         │
│    • Belnap B4 KB & 6-tier grounding         ─► localized conflict ⊤⊥ᵇ   │
│    • [logic/datalog/<semiring> | …]          ─► minplus/maxtimes/why     │
│    • [logic/datalog/prob | …] & [logic/wmc]  ─► exact Rational BDD WMC   │
│    • grad / wmc_prob / semantic_loss         ─► exact WMC gradients      │
└──────────────────────────────────────────────────────────────────────────┘
       │
       ▼
┌──────────────────────────────────────────────────────────────────────────┐
│ 3. SYNTHESIZE, VERIFY & EXPLAIN (Promoted to @theorem)                   │
│    • ai.cegis_infer / [solver/cegis | …]     ─► Z3 ∀ Int/Real repair     │
│    • [solver/advisor | …]                    ─► contingent action plans  │
│    • proof(rel, args…) / why <conclusion>    ─► full derivation trace    │
└──────────────────────────────────────────────────────────────────────────┘

Part I — Language-Level Neuro-Symbolic Primitives (AxiomaLang)

1.1 Typed, Schema-Checked Neural Inference (ai.infer, ai.cassette)

ai.infer(prompt, TargetType [, opts]) (global alias infer_typed) compiles a JSON-compatible Axioma type descriptor (record schema type T = { … }, Dictionary, Array, Tuple, Union, or primitive) into a structured JSON prompt, parses the model output via from_json, and validates every field and nested constraint strictly via checked(val, TargetType).

type SupplyShock = {
    supplier      :: String,
    severity_days :: Integer,
    event_kind    :: String
}

c: ai.cassette({
    "Typhoon halts Hsinchu 3nm wafer cluster for 21 days":
        "{\"supplier\": \"TSMC\", \"severity_days\": 21, \"event_kind\": \"fab_halt\"}"
})

res: ai.infer("Typhoon halts Hsinchu 3nm wafer cluster for 21 days", SupplyShock, {cassette: c})
expect res.value.supplier == "TSMC" and res.value.severity_days == 21
expect res.grounding == "hypothesis" and res.valid == true
expect try(ai.infer("Typhoon halts Hsinchu 3nm wafer cluster for 21 days", SupplyShock, {cassette: c, grounding: "theorem"})) is Error

1.2 Epistemically Grounded Embeddings & Vector Cassettes (ai.embed, ai.soft_match)

Entity linking maps noisy surface mentions ("Hsinchu 3nm wafer cluster", "Taiwan Semi foundry") onto canonical Knowledge Base entities. ai.embed(text [, opts]) (embed_text), ai.cosine(u, v) (cosine_sim), and ai.soft_match(query, candidates [, opts]) (semantic_match) support three execution modes (reported in .mode):

Mode How to Select Behavior
"hashed" Default (no opts needed) Deterministic L2-normalized signed token + character 3-gram feature hashing (dims default 64, up to 4096), zero network I/O
"cassette" opts: {cassette: vec_map} Deterministic dense-vector replay from a String → Array of Float dictionary or ai.cassette(...)
"live" opts: {provider: "openai" | "openrouter" | "gemini" | "ollama" | "fake"} Live dense vector embeddings from the configured provider with automatic L2 normalization

Epistemic grounding rule: Exact lexical identity (query == candidate) receives "datum" grounding; every non-identical semantic match is capped at "hypothesis" grounding regardless of cosine similarity score, preventing high-cosine false positives from silently corrupting strict axioms.

vecs: {
    "Hsinchu 3nm wafer cluster":   [0.92, 0.36, 0.15],
    "TSMC (Taiwan Semiconductor)": [0.90, 0.40, 0.18],
    "ASML Lithography Systems":    [0.25, 0.88, 0.40]
}

matches: ai.soft_match(
    "Hsinchu 3nm wafer cluster",
    ["TSMC (Taiwan Semiconductor)", "ASML Lithography Systems"],
    0.70,
    {cassette: vecs}
)
expect matches[1].label == "TSMC (Taiwan Semiconductor)"
expect matches[1].mode == "cassette" and matches[1].grounding == "hypothesis"

1.3 Provenance Semirings, [logic/datalog/prob], and [logic/wmc]

Provenance semirings on relation/datalog

A third segment on an explicit Datalog query ([logic/datalog/<semiring> | proj <- goal]) tags every answer by combining body tags along a derivation with ⊗ and merging alternative derivations with ⊕ over assert/weight: metadata:

Mode Algebra (⊕, ⊗, 1) Weights Computes
minplus min , +, 0 number  ≥ 0, Money, Quantity Cheapest derivation / shortest path
maxtimes max , ×, 1 number in [0, 1] Single most probable derivation path
maxmin max , min , 1 number in [0, 1] Best bottleneck capacity / fuzzy degree
count +, ×, 1 positive Integer Number of derivations (acyclic)
why ⊆-minimal ∪, pairwise ∪, {∅} not read Minimal witness sets of base facts
prob (WMC) Memoized Shannon-BDD WMC over why DNF Rational / Float in [0, 1] Exact possible-world marginal probability

Why prob and [logic/wmc] matter on diamond graphs

In correlated supply-chain, biological, or fault-tree DAGs, two paths often share an upstream cause (s -> a -> t and s -> b -> t both depend on s). Naive multiplication double-counts s, while maxtimes considers only one path. Both [logic/datalog/prob | …] and [logic/wmc | …] ([logic/problog | …]) compile lineages into Boolean formulas and run memoized Shannon-cofactor Weighted Model Counting with exact Rational arithmetic:

# Annotated disjunction (minor vs. severe outage cannot co-occur) + Bayesian conditioning:
wmc: [logic/wmc |
    1/2 :: halt_minor("TSMC") | 1/3 :: halt_severe("TSMC")
    4/5 :: single_source("NVDA", "TSMC")
    3/5 :: single_source("AAPL", "TSMC")

    halt_any(Fab)    <== halt_minor(Fab) or halt_severe(Fab)
    disrupted(Firm)  <== single_source(Firm, Fab) and halt_any(Fab)
    severe_hit(Firm) <== single_source(Firm, Fab) and halt_severe(Fab)

    evidence disrupted("NVDA")
    ? severe_hit("AAPL")
]
expect wmc.result == 6/25 and wmc.grounding == "theorem"

1.4 Reverse-Mode Autodiff, T-Norms & Differentiable Exact WMC (grad, import "neurosym")

Symbolic structure and gradient optimization meet on Axioma's reverse-mode Wengert tape (evaluator/neurosym_autodiff.go + lib/neurosym/Core.ax):

import "neurosym"

loss_fn: func(theta) [
    q_prob: [logic/wmc |
        sigmoid(theta[1]) :: fab_halt("TSMC")
        0.9 :: depends("NVDA", "TSMC")
        0.8 :: depends("AAPL", "TSMC")
        joint <== depends("NVDA", "TSMC") and depends("AAPL", "TSMC") and fab_halt("TSMC")
        ? joint
    ].result
    (q_prob - 0.54) ^ 2
]

fit: gd_minimize(loss_fn, [0.0], 2.0, 80)
expect abs(sigmoid(fit.params[1]) - 0.75) < 0.02

1.5 Closed-Loop Z3 Synthesis & Neural Repair ([solver/cegis], ai.cegis_infer)

Testing an LLM-written financial mandate or control rule on 10 sample inputs misses division-by-zero, cap-overflow, and boundary violations across continuous Real or unbounded Int domains.

Axioma provides two tightly coupled CEGIS workflows (evaluator/neurosym_cegis.go, evaluator/neurosym_cegis_infer.go):

  1. [solver/cegis | …] ([solver/synthesize | …]): Grammar-based affine / piecewise if-then-else synthesis, candidate-pool filtering (candidates), or inline neural proposal (propose "..." + optional cassette).
  2. ai.cegis_infer(prompt, cegis_spec [, opts]) (cegis_infer): Closed-loop neural proposal + Z3 universal verification (+, -, *, /, min, max, abs, nested if-then-else over Int and Real). When Z3 finds a counterexample (including exact rational Real witnesses such as 1/2), Axioma records a SemCDCL-style nogood (rejected_candidates) and feeds the violating witness back to the model for repair — promoting .grounding from "hypothesis" to "theorem" only when Z3 proves unsat across the entire domain.
mandate_cassette: ai.cassette({
    "round:1": "{\"expression\": \"nav * max(0.02, shock_prob * var_99)\"}",
    "round:2": "{\"expression\": \"nav * min(0.25, max(0.02, shock_prob * var_99))\"}"
})

verified: ai.cegis_infer(
    "Synthesize IPS cash buffer over Real nav, shock_prob, var_99 with 2% floor and 25% cap.",
    "synthesize buf(nav, shock_prob, var_99) :: Real
     spec (nav >= 0.0 and shock_prob >= 0.0 and shock_prob <= 1.0 and var_99 >= 0.0 and var_99 <= 1.0) implies (
         buf(nav, shock_prob, var_99) >= 0.02 * nav and
         buf(nav, shock_prob, var_99) <= 0.25 * nav and
         (shock_prob * var_99 >= 0.25 implies buf(nav, shock_prob, var_99) == 0.25 * nav)
     )",
    {cassette: mandate_cassette, max_rounds: 4}
)
expect verified.solved and verified.status == "proven" and verified.grounding == "theorem" and verified.rounds == 2

Part II — Knowledge-Base & Verification Foundations (AxiomaLang + AxiomaCascade + AxiomaKB)

2.1 Six-Grade Epistemic Grounding as a Trust Ratchet

Every fact in the Axioma Knowledge Base carries a provenance grade:

axiom > postulate > theorem > conjecture > hypothesis > datum

2.2 Belnap B4 Paraconsistent Truth (⊤ᵇ, ⊥ᵇ, ?ᵇ, ⊤⊥ᵇ)

In classical logic, a single contradictory extraction (P ∧ ¬P) triggers ex falso quodlibet, corrupting every unrelated query. Axioma's Belnap B4 bilattice represents conflicting evidence explicitly as ⊤⊥ᵇ (both) and missing evidence as ?ᵇ (neither). Contradictions propagate locally along dependent rule chains via the B4 meet without exploding unrelated derivations.

2.3 Defeasible Rules, Auditable cancel() Overrides & proof() Provenance

2.4 External Registry Verification (AxiomaCascade)

AxiomaCascade (cascade ingest --verify and cascade verify-external) cross-references LLM-extracted entities, claims, and citations against Wikidata, ROR (Research Organization Registry), Wikipedia, and CrossRef before promoting facts into AxiomaKB — catching fabricated organizations and nonexistent DOIs automatically (unresolved verdict).


Part III — End-to-End Practical Walkthrough: Institutional Supply-Chain & Mandate Pipeline

Suppose an analyst or AxiomaAgent receives breaking unstructured intelligence:

"Typhoon halts Hsinchu 3nm wafer cluster for 3 weeks."

Here is how all five neuro-symbolic layers collaborate in a single self-contained .ax script:

import "neurosym"

# 1. Dense/cassette soft entity linking (@hypothesis ceiling):
entity_vecs: {
    "Hsinchu 3nm wafer cluster": [0.94, 0.31, 0.12],
    "TSMC":                      [0.92, 0.35, 0.15],
    "Samsung Foundry":           [0.35, 0.82, 0.45]
}
linked: ai.soft_match("Hsinchu 3nm wafer cluster", ["TSMC", "Samsung Foundry"], 0.70, {cassette: entity_vecs})
fab_id: linked[1].label   # "TSMC" (@hypothesis)

# 2. Schema-checked event extraction (@hypothesis ceiling):
type OutageAlert = { fab :: String, halt_days :: Integer }
alert_fx: ai.cassette({"Typhoon halts Hsinchu 3nm wafer cluster for 3 weeks.": "{\"fab\": \"TSMC\", \"halt_days\": 21}"})
alert: ai.infer("Typhoon halts Hsinchu 3nm wafer cluster for 3 weeks.", OutageAlert, {cassette: alert_fx})

# 3. Exact probabilistic Datalog over multi-tier diamond supply graph (@theorem):
relation/datalog supplies(src, dst)
relation/datalog path(src, dst)
assert/weight: (3/4) supplies("Hsinchu_3nm", "TSMC")
assert/weight: (4/5) supplies("TSMC", "CoWoS_Packager")
assert/weight: (1/2) supplies("TSMC", "HBM_Integrator")
assert supplies("CoWoS_Packager", "NVDA")
assert supplies("HBM_Integrator", "NVDA")

path(X, Y) :- supplies(X, Y)
path(X, Z) :- supplies(X, Y), path(Y, Z)

why_nvda:  [logic/datalog/why  | Y <- path("Hsinchu_3nm", Y)].result["NVDA"]
best_nvda: [logic/datalog/maxtimes | Y <- path("Hsinchu_3nm", Y)].result["NVDA"]
prob_nvda: [logic/datalog/prob | Y <- path("Hsinchu_3nm", Y)].result["NVDA"]
# Shared upstream link("Hsinchu_3nm", "TSMC") is factored once:
# maxtimes == 3/5 (24/40), exact WMC prob_nvda == 27/40 (neither 24/40 nor naive 30/40!)

# 4. Closed-loop Z3 CEGIS synthesis of the IPS cash-buffer rule (@hypothesis -> @theorem):
ips_fx: ai.cassette({
    "round:1": "{\"expression\": \"nav * min(0.25, max(0.02, shock_prob * 0.30))\"}"
})
mandate: ai.cegis_infer(
    "Synthesize IPS cash buffer with 2% floor and 25% cap.",
    "synthesize buf(nav, shock_prob) :: Real
     spec (nav >= 0.0 and shock_prob >= 0.0 and shock_prob <= 1.0) implies (
         buf(nav, shock_prob) >= 0.02 * nav and buf(nav, shock_prob) <= 0.25 * nav
     )",
    {cassette: ips_fx}
)

expect fab_id == "TSMC" and alert.value.halt_days == 21
expect best_nvda == 3/5 and prob_nvda == 27/40 and len(why_nvda) == 2
expect mandate.solved and mandate.grounding == "theorem"

Part IV — Honest Scope & Positioning

Dimension Supported in Axioma Today Outside Scope (Handled Externally)
Structured LLM extraction ai.infer + checked(val, TargetType) + epistemic ceiling + offline cassette Token-level logit masking during LLM decoding (e.g., Outlines / llguidance)
Semantic entity linking ai.embed + ai.soft_match (hashed, cassette, and live openai/openrouter/gemini/ollama) Billion-vector ANN index hosting (use pgvector / Qdrant externally if needed)
Probabilistic logic Exact Shannon-BDD WMC ([logic/datalog/prob], [logic/wmc], annotated disjunctions, evidence, exact Rational, up to 28 base facts per query lineage) Approximate MCMC / variational inference over thousands of dense graphical variables
Differentiable reasoning Reverse-mode Wengert tape (grad, value_and_grad), t-norms, exact wmc_prob & semantic_loss, [logic/wmc] inside grad / gd_minimize Distributed GPU tensor pretraining / LLM weight fine-tuning (PyTorch / JAX / Mojo)
Formal synthesis & repair Z3 CEGIS ([solver/cegis], ai.cegis_infer) with universal Int/Real verification and SemCDCL nogoods (@hypothesis → @theorem) Higher-order inductive theorem synthesis over arbitrary recursive data structures (Lean 4)
Contradiction & auditability Belnap B4 (⊤⊥ᵇ), 6-grade grounding, proof() / why, cancel(), AxiomaCascade Wikidata/ROR/CrossRef checks Detecting subtle factual fabrications composed entirely of real, externally valid entities without a contradicting rule or source

Quick Reference & Source Map

Capability Primary Surface Implementation
Typed neural inference & cassettes ai.infer, ai.cassette, infer_typed evaluator/neurosym_ai.go, ai/ai.go
Dense, cassette & hashed embeddings ai.embed, ai.cosine, ai.soft_match ai/embed.go, evaluator/neurosym_ai.go
Provenance semirings (minplus, maxtimes, maxmin, count, why) assert/weight:, [logic/datalog/<semiring> | …] evaluator/logic_semiring.go, evaluator/logic_semiring_fixpoint.go
Exact probabilistic Datalog & differentiable WMC [logic/datalog/prob | …], wmc_prob, semantic_loss evaluator/neurosym_datalog_prob.go, lib/neurosym/Core.ax
ProbLog WMC, annotated disjunctions & evidence [logic/wmc | …], [logic/problog | …] evaluator/neurosym_wmc.go
Reverse-mode autodiff & t-norms grad, value_and_grad, sigmoid, relu, soft_* evaluator/neurosym_autodiff.go, lib/neurosym/Core.ax
Z3 CEGIS synthesis & closed-loop neural repair [solver/cegis | …], ai.cegis_infer evaluator/neurosym_cegis.go, evaluator/neurosym_cegis_infer.go
Belnap B4, Gödel G3 & 6-grade KB grounding belnap, intuit3, grounding, proof, why, cancel evaluator/mvl_belnap.go, evaluator/mvl_godel_g3.go, kb/epistem.go
External registry verification cascade ingest --verify, cascade verify-external axiomacascade/cascade/core/verify.py