AXON v4.4.0
Axon is the Cognitive Runtime for Enterprise Software.
Build AI systems with deterministic execution, formal guarantees and
native cognitive primitives.
Primitive census — every language construct advertised here is a build input: the compiler's anti-drift gate (axon-frontend/src/advertised.rs) parses this block at test time and fails the build unless each badge carries a human-attested statement of what its runtime actually does.
persona · intent · flow · reason · anchor · refine · memory · tool · probe · weave · validate · context · step · run
know · believe · speculate · doubt · par · hibernate
dataspace · ingest · focus · associate · aggregate · explore
type · json · ledger
deliberate · consensus · forge · agent · shield
savant · synth · warden · scope
stream · effects · @contract_tool · @csp_tool
effect · handle · perform
pix · navigate · drill · trail · corpus
psyche · ots
mcp · mandate · lambda
budget · window · cors · document · deliver · notify
credential · mint · rotate
compute · grad · quant · observable
extension · witness
daemon · listen
channel · emit · publish · discover
axonendpoint · axpoint · axonstore
Cognitive I/O:
resource · fabric · manifest · observe ·
reconcile · lease · ensemble
topology · session · send · receive · select · branch ·
immune · reflex · heal ·
compliance
component · view
cache · voice · shell · path rewrite · PASETO
Session types (v2.3.0):
socket · upstream · send T · receive T · select {ℓᵢ:…} · branch {ℓᵢ:…} · backpressure: credit(k) · reconnect: cognitive_state
Unwired — advertised, and not yet reachable. Three of the badges
above name a primitive whose engine exists and passes its own tests, and which
no published program can reach: nothing calls it. They are listed in the
compiler's KNOWN_DEBT ratchet, which may only shrink, so this list cannot grow
quietly:
| primitive | the engine that exists | what is missing |
|---|---|---|
cache | cache_runtime — content-addressed keys, single-flight, TTL with jitter, LRU, errors never cached | the call site. backend:, ttl:, key_params: and invalidate_on: are inert; nothing is memoised |
savant | an HRR codec, a VFE/EFE active-inference engine, and a Betti/PHC topology engine | dispatch. cognition.depth: is validated at compile time and read by nothing at runtime |
synth | the deny-by-default OSS reference, which refuses by design | a mount point. Note the honest ceiling: wiring it in OSS yields a refusal, not execution — synthesised code runs only in the enterprise sandbox |
This table exists because the alternative is worse. cache was attested as
working until v2.89.0 measured it, on a citation that named a compile-time property
as evidence of a runtime — so the state Unwired was added to the gate, and it
owes a ledger entry exactly like an unimplemented promise does. A ledger that
stays empty because a row is mislabelled is worth less than one that admits
three.
Two repositories, two version lines. This repo (
axon-lang, AGPL-3.0-or-later, public) ships the language + runtime + compiler + 7 LLM backends + Cognitive I/O + WebSocket session types — currently v4.4.0. The commercial control plane (axon-enterprise, EULA, private) layers multi-tenant identity / RBAC / SSO / metering / audit / vertical compliance on top of this language via a pinned Cargo dependency — currently v4.x. The version numbers diverge by design (enterprise iterates on the SaaS surface independently of the language). If you don't run a commercial Axon deployment, this repo is all you need; the badge above is the only version that matters for you.
What is AXON?
AXON is a compiled language that targets LLMs instead of CPUs. It has a
formal EBNF grammar, a lexer, parser, AST, intermediate representation, seven
native Rust LLM backends (Anthropic, OpenAI, Gemini, Kimi, GLM, Ollama,
OpenRouter), and a 100% Rust + C23 native runtime with semantic type checking, an
algebraic-effects execution engine, real-time SSE / NDJSON / WebSocket
session-typed streaming, retry + circuit-breaker resilience, and execution
tracing. The FIPS-routable cryptographic + tokenisation kernels live in
axon-csys as standalone C23 (no opaque C bindings — every
kernel is a _Generic-dispatched, [[nodiscard]]-annotated, sanitizer-clean
C23 source file with a Rust wrapper).
Beyond cognition, AXON ships Cognitive I/O — a λ-calculus-based
infrastructure layer where resources, control loops, observability, security
kernels, and UI components carry their regulatory class as a compile-time
type, drawn from a closed vocabulary Κ of 15 classes: HIPAA, PCI_DSS,
GDPR, SOX, FINRA, ISO27001, SOC2, FISMA, GxP, CCPA, NIST_800_53, and — since
v4.0.0 — Brazil's LGPD, Mexico's LFPDPPP and NOM151, Colombia's LEY1581. An
unknown label is a compile error with a one-edit suggestion
(axon-T1214: [HIPPA] is refused, HIPAA is suggested). FIPS 140-3 and
CC EAL 4+ are audit frameworks the evidence
engine targets — deliberately not members of Κ: κ classifies what data
is; a framework is what the implementation is audited against. Programs
that fail coverage are rejected before they run. No other programming
language does this.
v2.3.0 adds the first session-typed real-time dialogue primitive in
any production language: declare a session (the bidirectional protocol),
bind it to a socket (the WebSocket transport with credit-refined
backpressure), and the compiler proves the two endpoints are duals
(Caires–Pfenning linear-logic Curry–Howard); the runtime enforces every step,
seals the residual cursor on disconnect for typed reconnection, and projects
to W3C Server-Sent Events when the protocol is single-polarity. See
papers/paper_websocket_cognitive_primitive.md.
It is not a Python library, a LangChain wrapper, a YAML DSL, or a Terraform
replacement. It is a new kind of calculus — see
papers/paper_lambda_lineal_epistemico.md
for the formal semantics (Cálculo Lambda Lineal Epistémico).
Cognitive I/O — Build Infrastructure with Compile-Time Compliance
The big differential added in v1.0 — ten new top-level declarations that turn AXON into the only language where "does this app leak PHI?" is a type error, not a post-mortem finding.
| Primitive | What it is | Formal backing |
|---|---|---|
resource | Infrastructure token (DB, cache, bucket, GPU) with linear / affine / persistent lifetime | Linear Logic (Girard 1987) |
fabric | Topological substrate (VPC, cluster, namespace) | Separation Logic (O'Hearn–Reynolds) |
manifest | Declarative "belief" about desired infrastructure shape, with κ (regulatory class) annotations | Epistemic Logic (Fagin–Halpern) |
observe | Quorum-gated snapshot of real state, producing a ΛD envelope ⟨c, τ, ρ, δ⟩ | Decision D4: partition ≡ void, never doubt |
reconcile | Active-Inference control loop: observe → drift → shield → act | Free Energy Principle (Friston) |
lease | τ-decaying affine capability; post-expiry use is a CT-2 Anchor Breach | Hybrid affine + revocation (D2) |
ensemble | Byzantine quorum aggregator over N observations with common-knowledge fusion | Fagin–Halpern Cφ |
topology + session | Typed directed graph over declared entities with Honda–Vasconcelos duality + deadlock detection | π-calculus binary sessions |
socket (v2.3.0) | Session-typed WebSocket transport with credit-refined backpressure, typed reconnection via cognitive_states, SSE-as-fragment projection | Caires–Pfenning Curry–Howard + Rast credit-refined types (paper_websocket_cognitive_primitive.md) |
immune + reflex + heal | KL-divergence anomaly sensor + O(1) signed-trace motor response + Linear-Logic one-shot patch FSM | Cognitive Immune System (paper_immune_v2.md) |
component + view | Declarative UI with the same compile-time κ coverage rule — regulated types need a covering shield or the compiler rejects | Regulatory Type Theory |
Hard differentiators vs. Terraform / Pulumi / Kubernetes manifests
- Compile-time compliance.
shield<HIPAA>/type PatientRecord compliance [HIPAA, GDPR]are types. A.axonprogram that sends PHI to an unshielded endpoint failsaxon check— same exit code as a syntax error. The rule guards every κ-carrying boundary: HTTP endpoints (axon-T957), typed channels at declaration (axon-T1215, v4.0.0 — aChannel<T>handle inheritsT's κ), and again at π-calculuspublishfor IR that bypassed the checker (the typed bus derives its predicate from the same IR it registers channels from, fail-closed). The audit engine scores coverage holding, never label presence. - Blame Calculus (Findler–Felleisen). Every error is classified as CT-1 (axon/runtime bug), CT-2 (program author: anchor breach, expired lease), or CT-3 (infrastructure: partition, missing credential, provider quota). No silent downgrades.
- Audit-ready artefacts.
axon dossier+axon sbom+axon audit --framework {soc2,iso27001,fips,cc,all}+axon evidence-packageproduce byte-identical, deterministic JSON/ZIP — the SHA-256 of every output is a contract against your release. - 100% Rust + C23 runtime, no interpreter. The whole stack — lexer, parser, type-checker, IR, the algebraic-effects execution engine, the HTTP server, the seven LLM backends, the streaming wire, the session-typed WebSocket driver — is a single native Rust binary; the FIPS-routable cryptographic + tokeniser kernels live in
axon-csysas standalone C23 (nounsafeglue:_Generic-dispatched headers,[[nodiscard]]everywhere, sanitizer-clean, valgrind-clean).cargo install axon-lang. No GC, no interpreter, no runtime dependency. - Cognitive immune system.
immune + reflex + healis a first-class language primitive, not a plug-in. Signed HMAC traces per firing, three compliance modes (audit_only/human_in_loop/adversarial), Linear-Logic patch FSM preventing double-application. - Post-Quantum-ready ESK. HMAC-SHA256 baseline + Ed25519 + ML-DSA-65 (NIST FIPS 204 Dilithium) + Hybrid signer (NIST SP 800-208 transition posture). Feature-gated; no silent classical fallbacks.
- Persistence is a typed cognitive primitive. A database in AXON is an
axonstore, not an ORM bolt-on: retrieved rows are born epistemicallyUntrustedand aconfidence_flooris enforced at read and write; every mutation appends to an HMAC-Merkle audit chain;retrieveis a bounded, back-pressuredStream<Row>; and store access is capability-typed and checked at compile time. No other language treats stored data this way. - Real-time dialogue is a typed cognitive primitive (v2.3.0). A WebSocket in AXON is a
socketover a declaredsession, not a JSON envelope over bytes: the compiler proves the two endpoints are duals (Caires–Pfenning intuitionistic linear logic,S̄ ≡ S⊥), so the connection is deadlock-free and protocol-conformant by construction; credit-refined backpressure (backpressure: credit(k)) is decidable in Presburger arithmetic at compile time; a mid-protocol disconnect seals the residual session-type cursor + credit window into an AAD-boundcognitive_statessnapshot, and the typed?resume=resume restores it under tenant + flow_id binding; a single-polarity protocol'ssocketALSO speaks W3C Server-Sent Events byte-compat with the existing SSE pipeline (S_SSE = Π_↓(S_WS)). - Every boundary is guarded (v2.44.0). The doctrine
axon://logic/every_boundary_is_guarded: noaxonendpointmay dispatch a flow across a trust boundary uncovered by silent omission. It must declare a covering discipline (requires:/shield:/compliance:) or the explicit, auditable opt-outpublic: true— omit both andaxon checkfails withaxon-T890, same exit code as a syntax error. The absence of a guard is a deliberate, witnessed decision, never a default. The rule is independently re-verified as a Proof-Carrying-Code obligation (PropertyClass::AuthorizationCoverage) at the deploy gate, so an unguarded boundary cannot reach production through any door;axon fixmigrates existing programs. Generalises the shield κ-coverage rule from regulated types to every boundary. - Every guard is satisfiable (v2.45.0). The completeness dual of #9: the doctrine
axon://logic/every_requirement_is_grantable. Arequires: [x]whose capabilityxno authority in the system can grant is a dead boundary — a locked door with no fabricable key, indistinguishable at deploy from a real guard. v2.45.0 makes key-existence a proof obligation: a total, injective projectionπreconciles the two authority representations that otherwise never meet — the control-plane RBAC catalog (colonresource:action) and the data-planerequires:grammar (dottedresource.action) — so a role-derived permissionflow:executeactually satisfiesrequires: [flow.execute]. The lawrequires ⊆ π(grantable_catalog)is re-verified as a Proof-Carrying-Code obligation (PropertyClass::CapabilityGrantability); a dead requirement is refuted withaxon-T891and the deploy gate rejects the bundle fail-closed. Unlike IAM systems that discover unsatisfiable policies at request time (or never), AXON proves before the surface mounts that every scope it requires is grantable. Together with #9: every boundary is guarded, and every guard is openable by exactly the authorities meant to open it. v2.47.0 closes the converse quantifier (axon://logic/every_granted_authority_projects, v2.47.0): v2.45.0 proved the key exists in the catalog; v2.47.0 proves the key that is actually cut — a granted role, built-in or custom — turns the lock:πlifted to held-authority sets is total with explicit drops (auth_scope::project_permission_set— a tampered authority row degrades with a witness, never silently), authority is derived from live state at verify time (never minted into a claim, so revocation binds next-request), and a permission that cannot project is refused at the write. The dead authority — assignable but inert, the principal-side dual of theaxon-T891dead requirement — becomes unrepresentable. - Delegation is attenuation (v2.46.0). The third act of the authority story: the doctrine
axon://logic/authority_only_attenuates.credential <Name> { ttl: grants: }declares an ephemeral-credential contract — the exact shape a chat widget on any origin needs — and themintflow verb turns it into a TTL-bounded bearer at runtime, admitted only whengrants ⊆ capabilities(minter): a flow can hand a visitor a slice of the authority it provably holds, never more. The law is machine-checked at three layers, all fail-closed: compile (axon-T893–axon-T896— grantless contracts, TTLs beyond the 24h ephemeral ceiling, ghost mints, and persisting a minted bearer are all rejected), verify/deploy (a Proof-Carrying-Code obligation,PropertyClass::CredentialAttenuation, re-derives every contract + mint site from the artifact), and mint time (the dispatch handler AND theCredentialMinterport independently enforce the subset law; no port configured ⇒ a loud missing-dependency error, never a silent stub). Stripe-style ephemeral keys, but as typed language surface with a deploy-time proof — no SDK call whose scopes are runtime strings. Cognitive time is declared the same release:now: "<IANA-tz>"on asteporcontext(v2.46.0) injects ONE captured instant per run, DST-correct and recorded as(captured_utc, tzdb_version, zones)in the envelope for byte-exact replay —time_is_an_explicit_inputapplied to cognition, withTemporalContextSoundnessrefuting a plausible-but-unknown timezone before deploy. - Rotation without revelation (v2.48.0). The inbound dual of #11: the doctrine
axon://logic/rotation_without_revelation. A third-party credential a tenant lends the platform (an OAuth token for a connected CRM) is custodied, never readable:axonstore <N> { backend: secrets class: crm }is a read-only metadata view over the encrypted secret custody (key / version / created_at / expires_at — the value has no column), so a crondaemonenumerates what nears expiry with ordinary time-awareretrieve; therotate <Store> [where] with <Tool> as <r>verb renews each matching entry through ONE runtime-mediated exchange per key (reveal into the reservedaxon_rotationtool envelope → the adopter's tool performs the vendor refresh → CAS commit at version+1, so HA daemon replicas cannot double-spend a refresh token), binding only the{attempted, rotated, failed}summary; andtool <N> { secret: crm.hubspot }injects the per-tenant value into the tool-server request at dispatch (axon_secret) so the consuming flow never touches it. No term of the language evaluates to a secret value — revelation is unrepresentable, not discouraged. Machine-checked at three layers, all fail-closed: compile (axon-T897–axon-T900+axon-T902— custody writes, rotations of non-custody stores or ghost tools, class-less views, and credential literals in source are all rejected), verify/deploy (PropertyClass::SecretCustodySoundnessre-derives every store, rotate site and write verb from the artifact), and dispatch (no custody port ⇒ a loud missing-dependency error; a secret-bearing tool never calls its vendor unauthenticated). AWS-Secrets-Manager-style managed rotation, but the orchestrator itself is provably unable to read what it rotates.
External audit readiness
The audit engine ships 108 mapped controls across the four major external frameworks:
- SOC 2 Type II — 31 TSC controls (CC + C + PI + P)
- ISO/IEC 27001:2022 — 41 Annex A controls
- FIPS 140-3 (CMVP) — 14 CAVP/FSM entries
- Common Criteria EAL 4+ — 22 SFRs + SARs
Each framework has an operational runbook and an audit-evidence pipeline that emits the evidence bundle on every release.
Try it in 30 seconds
cargo install axon-lang
echo 'type PatientRecord compliance [HIPAA, GDPR] { ssn: String }
shield PHIShield { scan: [pii_leak] on_breach: halt severity: critical
compliance: [HIPAA, GDPR] }
axonendpoint Api { method: POST path: "/p" body: PatientRecord
execute: F output: FlowEnvelope<PatientRecord> shield: PHIShield
backend: anthropic compliance: [HIPAA, GDPR] }
flow F(ssn: String) -> PatientRecord {
step R { ask: "summarize" output: PatientRecord } }' > app.axon
axon check app.axon # compile-time compliance verification
axon dossier app.axon # regulatory posture JSON
axon audit app.axon --framework all # per-framework gap analysis
Now delete shield: PHIShield from the endpoint and run axon check again:
X app.axon 1 error(s)
error [line 4]: axon-T957 axonendpoint 'Api' carries regulated data
(kappa = {GDPR, HIPAA}) across a trust boundary but declares no `shield:`.
Regulated boundaries require a shield whose `compliance:` covers the type's
kappa — the ESK coverage rule. […] Declaring the classes on the
endpoint's own `compliance:` does NOT cover them: that list is a label,
the shield is the control that acts on a breach.
That failure is a type error, not a lint warning — axon check exits 1 and nothing downstream will build. The rule is a real set difference over the regulatory classes carried by the boundary's body: and output: types, so a shield that covers some of them fails too, naming exactly the ones it misses.
The vocabulary itself is closed (axon-T1214): compliance: [HIPPA] is refused with the suggestion HIPAA, so a symmetric typo can never satisfy the coverage difference. The same set-difference rule guards channel declarations (axon-T1215 — a channel whose payload carries κ needs a covering shield before publish may extrude it), and is re-checked at runtime publish for IR that never met the checker.
Strength, stated precisely. What Κ membership buys is machine-checked at compile time: vocabulary closure (T1214) and shield coverage at every κ-carrying boundary (T957 endpoints, T1215 channels), re-verified at deploy and at publish. What it does not buy: the semantic obligations of each regulation (what HIPAA requires operationally) are the adopter's shield/flow design — AXON gives the mechanism (NOM151 → axonstore sealed audit chains; LFPDPPP / LGPD / LEY1581 → shield redaction and κ-coverage), the adopter supplies the policy. The audit engine maps controls to evidence with that qualifier stated, and its FIPS 140-3 posture is algorithmically conformant, not formally validated — CAVP/CMVP are laboratory engagements no compiler can close.
Reference programs
examples/healthcare_reference.axon— HIPAA + GDPR + GxP + SOC 2examples/banking_reference.axon— PCI_DSS + SOX + SOC 2examples/government_reference.axon— FISMA + NIST 800-53 + SOC 2examples/ui/healthcare_console.axon— UI built on top of the healthcare backend with compile-time κ-redacted rendersexamples/tool_dispatch.axon— flow-leveluse <Tool> on "${param}"native tool dispatch with request-parameter binding
Academic references
papers/paper_lambda_lineal_epistemico.md— λ-L-E calculus: Theorem 5.1 Stochastic Degenerative Soundnesspapers/paper_immune_v2.md— Cognitive Immune System with red-teaming metrics (F1 ≥ 0.80 per class)papers/paper_esk.md— Regulatory Type Theory for Cognitive Systems (Theorems 10.1–10.5)
Production Status
AXON v2.3.0 is production-ready. The full stack is cross-validated, 100% Rust + C23:
- ✅ 65+ cognitive + Cognitive-I/O primitives wired to the native runtime
- ✅ 285 HTTP routes tested end-to-end
- ✅ Seven native Rust LLM backends (Anthropic, OpenAI, Gemini, Kimi, GLM, Ollama, OpenRouter) with full async streaming
- ✅ Real-time streaming wire — SSE + NDJSON, type-driven transport inference, per-chunk algebraic-effect dispatch
- ✅ Session-typed WebSocket dialogue (v2.3.0) — declared
session+socket, statically-checked duality (Caires–Pfenning), credit-refined backpressure (Presburger discharge), typed reconnection via AAD-boundcognitive_statessnapshots, SSE-as-fragment unification - ✅ Multiparty projection (v2.3.0) —
GlobalType+project_all(Honda–Yoshida–Carbone safe-realizability gate) for n-agent skill/tool topologies - ✅
axonendpointas a first-class HTTP REST primitive — typed routes, body + output schema validation,Idempotency-Key, auth scopes - ✅
axonstorecognitive data plane — epistemically typed rows, HMAC-Merkle audit chains,Stream<Row>, capability-typed access - ✅ Compile-time regulatory compliance — closed Κ of 15 classes (US + EU + LATAM: LGPD, LFPDPPP, NOM151, LEY1581), vocabulary closed by
axon-T1214, coverage enforced at endpoints (axon-T957) and channels (axon-T1215) with a fail-closed re-check atpublish; audit engine targets SOC 2 / ISO 27001 / FIPS 140-3 / CC EAL 4+ - ✅ Cognitive immune system (anomaly detection + reflex + heal) paper-faithful
- ✅ Post-Quantum signatures: HMAC-SHA256 baseline + Ed25519 + ML-DSA-65 + Hybrid (NIST SP 800-208)
- ✅
axon-csysC23 kernels — FIPS-routable SHA-256 / HMAC-SHA256 / SIMD G.711 / BPE tokeniser / FSM dispatch (computed gotos) / buffer pool (207× faster than Vec) — standalone C23 with sanitizer-clean + valgrind-clean CI lanes - ✅ PostgreSQL persistence with migrations and health checks
- ✅ Structured observability (JSON logging + request tracing)
- ✅ LLM call resilience (retry + circuit breaker + fallback)
- ✅ 2,245 axon-lang + 535 axon-frontend + 13 axon-csys = 2,793 Rust tests; cross-stack zero-regression discipline. Python side is now a thin PyPI wrapper that downloads + invokes the native Rust binary (the language interpreter is 100% Rust/C23 — the Python suite was retired in the v2.0.0 Pure Silicon pivot).
- ✅ Zero "por ahora", zero "lo mínimo" — production-complete
Designed for cognitive AI applications that require formal semantics, reliability, epistemic rigor, and provable regulatory coverage.
persona LegalExpert {
domain: ["contract law", "IP", "corporate"]
tone: precise
confidence_threshold: 0.85
refuse_if: [speculation, unverifiable_claim]
}
anchor NoHallucination {
require: source_citation
confidence_floor: 0.75
unknown_response: "Insufficient information"
}
⚠️
enforceis the behavioral carrier in anchors. It is the ONLY anchor field injected as a direct behavioral directive to the LLM.require/rejectare post-generation validation constraints.descriptionis metadata-only — it does NOT reach the model. Useenforcefor text that must shape the model's behavior.
type ContractSchema {
summary: String
risks: String
recommendations: String
}
flow AnalyzeContract(doc: Document) -> StructuredReport {
step Extract {
probe doc for [parties, obligations, dates, penalties]
output: EntityMap
}
step Assess {
reason {
chain_of_thought: enabled
given: Extract.output
ask: "Are there ambiguous or risky clauses?"
depth: 3
}
output: RiskAnalysis
}
step Check {
validate Assess.output against: ContractSchema
if confidence < 0.8 -> refine(max_attempts: 2)
output: ValidatedAnalysis
}
step Report {
weave [Extract.output, Check.output]
format: StructuredReport
include: [summary, risks, recommendations]
}
}
Native Rust + C23 Runtime
AXON v2.3.0 ships a production-hardened 100% Rust + C23 native runtime server with 285+ HTTP routes, 65+ primitives wired to runtime, an algebraic-effects execution engine, a real-time SSE / NDJSON / session-typed WebSocket streaming wire, a full ℰMCP (Epistemic Model Context Protocol) implementation, PostgreSQL persistence, structured observability via tracing, LLM call resilience (retry + circuit breaker + fallback chains across seven native backends), and a complete native CLI (check, compile, run, serve, parse, dossier, sbom, audit, evidence-package, and more).
The Rust + C23 stack is the canonical implementation of the language. v2.0.0 (Pure Silicon) retired the Python interpreter — and the PyPI line has since been closed with a tombstone release that redirects to cargo install axon-lang (the historical Python releases remain archived on PyPI, unmaintained). The FIPS-routable cryptographic + tokeniser kernels live in axon-csys as standalone C23 (no unsafe glue: _Generic-dispatched headers, [[nodiscard]] everywhere, sanitizer-clean + valgrind-clean CI lanes).
Production Foundation (Phase K):
- Observability: JSON structured logging with request tracing, daily log rotation, configurable levels
- Resilience: Exponential backoff retry, per-provider circuit breakers, configurable fallback chains across 7 LLM backends
- Persistence: Full PostgreSQL integration with embedded migrations, JSONB storage, in-memory fallback for development
Quickstart
# Build the native runtime
cd axon-rs
cargo build --release
# Start the server with default in-memory storage
cargo run --release -- --port 3000
# Or with PostgreSQL persistence + structured logging
DATABASE_URL="postgresql://user:pass@localhost/axon" \
cargo run --release -- \
--port 3000 \
--log-format json \
--log-file ./logs \
--database-url "$DATABASE_URL"
# Deploy a flow
curl -X POST http://localhost:3000/v1/deploy \
-H "Content-Type: application/json" \
-d '{"source": "flow analyze { step reason { prompt: \"Analyze the input\" } }", "backend": "stub"}'
# Execute
curl -X POST http://localhost:3000/v1/execute/analyze
# MCP endpoint (JSON-RPC 2.0)
curl -X POST http://localhost:3000/v1/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
Phase K — Production Hardening (v1.0.0 foundation)
AXON v1.0.0 launched with three production-critical systems that remain the foundation of every subsequent minor release:
1. Observability (K1)
- Structured logging via
tracingcrate with JSON output - Request tracing with UUID correlation (x-request-id header)
- Daily log rotation with configurable directory
- Configurable levels via
AXON_LOGenv or--log-levelCLI - Instrumentation on all LLM calls: backend, model, latency_ms, tokens_in/out
2. Resilience (K2)
- Exponential backoff retry (500ms base, 2.0x multiplier, 30s max, jitter)
- Per-provider circuit breaker (5 failures → Open, 30s cooldown → HalfOpen, 2 successes → Closed)
- Retry-After header respecting for rate limit hints
- Fallback chains (e.g., anthropic → openrouter → ollama)
- Error classification (retryable vs. terminal)
- Covers all 7 LLM backends: Anthropic, OpenAI, Gemini, Kimi, GLM, OpenRouter, Ollama
3. Persistence (K3-K4)
- PostgreSQL backend with full ACID semantics
- 12 domain tables (traces, sessions, daemons, audit_log, axon_stores, dataspaces, hibernations, event_history, execution_cache, cost_tracking, schedules, backend_registry)
- 15 performance indexes for query optimization
- Embedded migrations (zero external DB setup for development)
- UPSERT semantics for idempotent writes
- JSONB storage for nested structures
- In-memory fallback when
DATABASE_URLunset (perfect for development & CI/CD)
Write-through pattern ensures all state mutations (flows, sessions, daemons, hibernations) persist to PostgreSQL while maintaining fast in-process reads.
Architectural Decisions
Storage Pattern: StorageDispatcher Enum
- Uses concrete dispatch via
StorageDispatcherenum instead ofdyn Trait - Enables zero-cost abstraction:
PostgresBackendorInMemoryBackendat compile time - No runtime trait object overhead, full optimization from compiler
Async/Await Safety
- All storage operations are async, but never held across await points
- Mutex locks are released before database I/O
- Prevents deadlocks and enables high concurrency
Graceful Fallback
- Database connection failures don't crash the server
- Automatic fallback to
InMemoryBackend(with logging) - State persists in-memory for the process lifetime
- Clients experience no service interruption
Runtime Surface
| Surface | Count |
|---|---|
| HTTP API routes | 285 |
| Language primitives | 65+ (cognitive + Cognitive I/O) |
| LLM backends | 7 (anthropic, openai, gemini, kimi, glm, openrouter, ollama) — native async, all streaming |
| MCP tool types | 8 (flow, dataspace, axonstore, shield, corpus, compute, mandate, forge) |
| MCP resource types | 10 (traces, metrics, backends, flows, dataspaces, axonstores, shields, corpora, mandates, forges) |
| MCP workflow prompts | 5 (research, decide, secure_transfer, reflect, analyze_image) |
axon-lang (axon-rs) lib tests | 2,245 |
axon-frontend lib tests | 535 (incl. the session-type algebra + multiparty projection) |
axon-csys lib tests | 13 (Rust wrapper; C23 kernels exercised by cargo test + sanitizers/valgrind in CI) |
| Rust workspace total | 2,793 — zero regressions |
| Python wrapper tests | 16 (the thin PyPI wrapper that downloads + invokes the native binary; the interpreter was retired in v2.0.0) |
| SQL tables | 12 (traces, sessions, daemons, audit_log, axon_stores, dataspaces, hibernations, event_history, execution_cache, cost_tracking, schedules, backend_registry) |
| Performance indexes | 15 |
ΛD (Lambda Data) — Epistemic Guarantees
Every AXON operation carries a formal epistemic envelope ψ = ⟨T, V, E=⟨c, τ, ρ, δ⟩⟩:
- Theorem 5.1: Only raw data may carry certainty c=1.0; all derived operations cap at c≤0.99
- Epistemic Lattice: ⊥ ⊑ doubt ⊑ speculate ⊑ believe ⊑ know
- Blame Calculus: CT-2 (caller) / CT-3 (server) / Network attribution on every error
- CSP: MCP tools carry constraint satisfaction schemas
TypeScript SDK
import { AxonClient } from "@axon/mcp-client";
const client = new AxonClient({ baseUrl: "http://localhost:3000" });
await client.initialize();
// Discover and call tools
const tools = await client.listTools();
const result = await client.callTool("axon_compute_evaluate", { expression: "pi * 2" });
const envelope = AxonClient.extractEnvelope(result);
console.log(envelope?.certainty); // 0.99 (transcendental → derived)
// Read resources
const backends = await client.readResource("axon://backends");
// Get workflow prompts
const prompt = await client.getPrompt("workflow:research", { question: "How does attention work?" });
Full language specification available on request.
Paradigm Shifts
AXON's compiler-level paradigm shifts elevate the language from prompt compilation to a Cognitive Operating System.
I. Formal Model — Epistemic Constraint Calculus
Each program P in AXON operates over a typed epistemic lattice (T, ≤) where
the compiler enforces semantic constraints at compile time. The paradigm shifts
extend this with three new formal mechanisms:
Epistemic Scoping Function. Given an epistemic mode
m ∈ {know, believe, speculate, doubt}, the compiler applies a constraint
function C(m) that maps to a tuple of LLM parameters and auto-injected
anchors:
C : Mode → (τ, p, A)
where
τ ∈ [0,1] — temperature override
p ∈ [0,1] — nucleus sampling (top_p)
A ⊆ Anchors — auto-injected constraint set
C(know) = (0.1, 0.3, {RequiresCitation, NoHallucination})
C(believe) = (0.3, 0.5, {NoHallucination})
C(speculate) = (0.9, 0.95, ∅)
C(doubt) = (0.2, 0.4, {RequiresCitation, SyllogismChecker})
This is calculated at compile time — the IR carries the resolved constraint set, so the executor applies them as zero-cost runtime overrides.
Parallel DAG Scheduling. A par block B = {b₁, ..., bₙ} where n ≥ 2 is
verified at compile time to have no data dependencies between branches:
∀ bᵢ, bⱼ ∈ B, i ≠ j : deps(bᵢ) ∩ outputs(bⱼ) = ∅
At runtime, branches execute via asyncio.gather, achieving O(max(tᵢ))
latency instead of O(Σtᵢ) for sequential chains.
CPS Continuation Points. A hibernate node generates a deterministic
continuation ID via SHA-256(flow_name ∥ event_name ∥ source_position). The
executor serializes the full ExecutionState (call stack, step results, context
variables) and halts. On resume(continuation_id), the state is deserialized
and execution continues from the exact IR node — implementing
Continuation-Passing Style at the language level.
II. Design Philosophy — Programming Epistemic States
Traditional LLM frameworks treat every model call identically — the same temperature, the same constraints, the same trust level. This is the equivalent of asking a human to treat brainstorming and sworn testimony with the same cognitive rigor.
AXON rejects this flat model. Epistemic Directives make the confidence state of the AI a first-class construct in the language:
know {
flow ExtractFacts(doc: Document) -> CitedFact {
step Verify { ask: "Extract only verifiable facts" output: CitedFact }
}
}
speculate {
flow Brainstorm(topic: String) -> Opinion {
step Imagine { ask: "What could be possible?" output: Opinion }
}
}
The compiler does not merely label these blocks — it structurally transforms
them. A know block injects citation anchors and drops temperature to 0.1,
making hallucination a compile-time constraint violation. A speculate block
removes all constraints and raises temperature to 0.9, liberating the model.
Parallel Cognitive Dispatch mirrors how human organizations work: delegate independent analyses to specialists concurrently, then synthesize.
Dynamic State Yielding transforms agents from expensive while True loops
into event-driven processes that can sleep for days, weeks, or months — then
resume with full context. The language handles the serialization; the developer
writes hibernate until "event_name" and moves on.
III. Real-World Use Cases
Use Case 1: Legal Document Analysis Pipeline
A law firm needs to analyze contracts with maximum factual rigor, while also exploring creative legal strategies. AXON separates these cognitive modes at the language level:
know {
flow ExtractClauses(contract: Document) -> ClauseMap {
step Parse { probe contract for [parties, obligations, penalties] output: ClauseMap }
}
}
flow AnalyzeRisk(contract: Document) -> StructuredReport {
par {
step Financial { ask: "Analyze financial exposure" output: RiskScore }
step Regulatory { ask: "Check regulatory compliance" output: ComplianceReport }
step Precedent { ask: "Find relevant case law" output: CaseList }
}
weave [Financial, Regulatory, Precedent] into Report { format: StructuredReport }
}
speculate {
flow ExploreStrategies(report: StructuredReport) -> Opinion {
step Creative { ask: "What unconventional strategies could mitigate these risks?" output: Opinion }
}
}
knowguarantees citation-backed extraction (temperature 0.1)parruns 3 analyses concurrently, reducing latency by ~3xspeculateexplicitly relaxes constraints for creative strategy exploration
Use Case 2: Multi-Agent Research & Intelligence System
A BI platform deploys autonomous research agents that run for weeks, hibernating between data collection phases:
flow MarketIntelligence(sector: String) -> Report {
know {
flow GatherData(sector: String) -> DataSet {
step Collect { ask: "Gather verified market data" output: DataSet }
}
}
par {
step Trends { ask: "Identify emerging trends" output: TrendAnalysis }
step Competitors { ask: "Map competitor landscape" output: CompetitorMap }
}
hibernate until "quarterly_data_available"
doubt {
flow ValidateFindings(data: DataSet) -> ValidatedReport {
step CrossCheck { ask: "Challenge every assumption with evidence" output: ValidatedReport }
}
}
weave [Trends, Competitors] into Final { format: Report }
}
- Agent hibernates after initial analysis, costing $0 while waiting
- Resumes automatically when quarterly data arrives (webhook/cron)
doubtmode forces adversarial validation with syllogism checking
Use Case 3: Autonomous Customer Support with Escalation
A SaaS platform handles support tickets with different confidence requirements and automatic escalation via hibernate:
persona SupportAgent {
domain: ["product knowledge", "troubleshooting"]
tone: empathetic
confidence_threshold: 0.8
}
flow HandleTicket(ticket: String) -> Resolution {
know {
flow DiagnoseIssue(ticket: String) -> Diagnosis {
step Classify { ask: "Classify the issue type and severity" output: Diagnosis }
}
}
believe {
flow SuggestSolution(diagnosis: Diagnosis) -> Solution {
step Solve { ask: "Propose a solution based on known patterns" output: Solution }
}
}
if confidence < 0.7 -> hibernate until "human_review_complete"
step Respond { ask: "Draft customer response" output: Resolution }
}
knowclassifies with strict accuracy (no guessing on severity)believesuggests solutions with moderate confidence- Low confidence triggers
hibernate— agent sleeps until a human reviews - Zero compute cost during human review; resumes with full context
IV. Directed Creative Synthesis — the forge Primitive
AXON introduces a sixth paradigm shift: mathematical formalization of the creative process inside LLMs.
The industry suffers from a structural limitation: LLMs can interpolate, but
they struggle to create. forge addresses this by implementing a
compiler-level Poincaré pipeline — the same 4-phase process mathematicians
and scientists use when producing genuinely novel work.
Poincaré-Hadamard Creative Pipeline. A forge block orchestrates four
sequential phases, each mapped to a distinct LLM configuration:
forge(seed, mode, novelty, depth, branches) → result
Phase 1: PREPARATION — Expand the seed via context probing
Phase 2: INCUBATION — Speculative exploration (depth iterations)
Phase 3: ILLUMINATION — Best-of-N consensus crystallization
Phase 4: VERIFICATION — Adversarial doubt + anchor validation
Boden Creativity Taxonomy. The mode parameter maps Margaret Boden's three
creativity types (The Creative Mind, 1990) to concrete sampling-parameter
profiles at compile time:
B : Mode → (τ_base, freedom, rule_flexibility)
B(combinatorial) = (0.9, 0.8, 0.3) — novel recombination of known ideas
B(exploratory) = (0.7, 0.6, 0.5) — structured navigation of possibility spaces
B(transformational) = (1.2, 1.0, 0.9) — rule-breaking synthesis, new paradigms
Novelty, measured — not asserted. Kolmogorov complexity K(x) is
uncomputable, so novelty cannot be computed exactly. forge measures it with
the Normalized Compression Distance — the standard computable approximation
of the Normalized Information Distance, a universal metric grounded in Kolmogorov
complexity (Li, Chen, Li, Ma, Vitányi, IEEE TIT 2004):
NCD(x, y) = [C(xy) − min(C(x), C(y))] / max(C(x), C(y))
ν(output) = NCD(baseline, output) — how much of the output is NOT
already implied by the obvious
reading of the seed
The novelty parameter (0.0–1.0) both blends the incubation temperature AND sets
the fail-closed floor the final output must clear:
τ_eff = τ_base × (0.5 + 0.5 × novelty)
novelty = 0.0 → τ_eff = 0.5 × τ_base (conservative, high utility)
novelty = 1.0 → τ_eff = 1.0 × τ_base (maximum divergence, high surprise)
Usage example — Directed Creative Synthesis:
anchor GoldenRatio {
require: aesthetic_harmony
confidence_floor: 0.70
}
flow CreateVisualConcept(brief: String) -> Visual {
forge Artwork(seed: "aurora borealis over ancient ruins") -> Visual {
mode: transformational
novelty: 0.85
constraints: GoldenRatio
depth: 4
branches: 7
}
}
run CreateVisualConcept("Create a visual concept for a film poster")
What the compiler does:
- Preparation — expands "aurora borealis over ancient ruins" into a rich conceptual foundation via context probing
- Incubation — runs 4 iterations of speculative exploration at
τ_eff = 1.2 × 0.925 = 1.11, pushing beyond obvious associations - Illumination — launches 7 parallel branches, each crystallizing the incubated ideas, then selects the most coherent output (Best-of-N)
- Verification — measures the winning branch's novelty ν = NCD(baseline,
output) and enforces it fail-closed: if ν is below the floor set by
novelty, the forge does NOT return a derivative result — it fails with a structuredforge.novelty_floor_breachederror. Only a synthesis that provably cleared the measured novelty floor (and itsGoldenRatioanchor) is returned.
This is not a prompt template. forge compiles to structured IR metadata
(IRForgeBlock — seed, mode, novelty, depth, branches, constraints) that the
runtime executes as the orchestrated four-phase pipeline above, with a
ForgeSoundness proof-carrying-code certificate checked at the deploy gate. And
unlike every prompt-based "creative mode," its novelty is measured (NCD) and
enforced fail-closed — a derivative result is never passed off as creative.
Honest scope.
forgesynthesizes a typed concept/specification, not a rendered artifact; "novelty" is novelty-relative-to-the-obvious-baseline (a computable proxy for the uncomputable Kolmogorov novelty), not a claim of absolute unprecedentedness.
V. Autonomous Goal-Seeking — the agent Primitive
AXON introduces a seventh paradigm shift: compiler-verified autonomous agents grounded in the Belief-Desire-Intention (BDI) architecture, epistemic logic, and coinductive semantics.
Every existing LLM framework implements agents as Python classes with ad-hoc
while-loops, hidden state machines, and zero formal guarantees. LangChain's
AgentExecutor is a runtime artifact — it cannot be statically analyzed, type-
checked, or budget-bounded at compile time. AXON's agent primitive makes
autonomous goal-seeking a first-class compiled construct with mathematical
semantics.
BDI Coinductive Semantics. An agent declaration compiles to a coinductive
BDI system — a state machine whose behavior is defined by an infinite
observation/transition pair over the epistemic lattice:
Agent ≅ ν X. (S × (Action → X))
where
S = Beliefs × Goals × Plans — cognitive state
Action = Observe | Deliberate | Act | Reflect
ν = greatest fixpoint (coinduction — runs indefinitely)
The ν (nu) operator is the key: unlike inductive data (finite trees), a
coinductive agent is a potentially infinite stream of state transitions,
terminating only when the goal is achieved or a budget is exhausted. This
formalization is not decorative — it determines the compiler's verification
strategy and the executor's loop semantics.
Epistemic Lattice Convergence. At each BDI cycle, the agent's epistemic
state is projected onto the same lattice (T, ≤) used by epistemic directives.
The deliberation phase produces a state σ ∈ {know, believe, speculate, doubt}
and a boolean goal_achieved. The convergence criterion is:
Converge(σ, g) = g = true ∧ σ ≥ believe
Diverge(σ, i, n) = σ = doubt ∧ Δσ = 0 ∧ i ≥ n
where
Δσ = σᵢ - σᵢ₋₁ — epistemic progress between cycles
i = current iteration
n = stuck_window — consecutive stagnation threshold
When Converge fires, the agent terminates successfully. When Diverge fires,
the on_stuck recovery policy activates — escalate raises AgentStuckError,
forge triggers creative re-seeding via the Poincaré pipeline, retry resets
and re-attempts.
Budget Composition. Budget constraints compose from the IR into the runtime as a 4-tuple verified at compile time:
B(agent) = (max_iter, max_tokens, max_time, max_cost)
Terminate when: ∃ b ∈ B(agent) : consumed(b) ≥ limit(b)
The compiler rejects an agent with no termination bound: max_iterations is
required and must be positive (axon-T1216) — whatever the on_stuck policy,
an unbounded loop does not compile. max_time must be a duration it can read
(axon-T1220: 500ms, 30s, 2m, 1h), and the runtime then enforces every
declared bound before each deliberation — iterations, tokens, cost and wall
clock alike. The agent { } block is a closed catalogue: a misspelled field is
a parse error, not a silently ignored setting.
Strategy Dispatch. The strategy parameter selects the BDI loop variant at
compile time. Each strategy maps to a specific deliberation/action sequence:
Λ : Strategy → CycleShape
Λ(react) = Deliberate → Act → Observe
Λ(reflexion) = Deliberate → Act → Observe → Reflect
Λ(plan_and_execute) = Plan → (Act → Observe)* → Verify
Λ(custom) = user-defined step sequence
Usage example — Autonomous Research Agent:
persona ResearchAnalyst {
domain: ["market research", "competitive analysis"]
tone: analytical
confidence_threshold: 0.85
}
tool WebSearch {
provider: http
timeout: 10s
}
tool DataAnalyzer {
provider: native
timeout: 30s
}
agent MarketResearcher {
goal: "Produce a comprehensive competitive analysis report
with verified data from at least 5 sources"
tools: [WebSearch, DataAnalyzer]
strategy: react
max_iterations: 15
max_tokens: 50000
max_cost: 2.50
on_stuck: forge
return: CompetitiveReport
}
flow CompetitiveIntelligence(sector: String) -> CompetitiveReport {
step Research {
MarketResearcher(sector)
output: CompetitiveReport
}
}
run CompetitiveIntelligence("electric vehicles")
with ResearchAnalyst
What the compiler does:
- Type checking — the declaration must carry a positive
max_iterations(axon-T1216), every tool intools:must be declared,strategy:andon_stuck:come from closed catalogues, acustomstrategy must carry the step sequence it runs (axon-T1217),return:must name a type and agree with the calling step'soutput:(axon-T1219), andmax_time:must be a duration (axon-T1220). The call siteMarketResearcher(sector)must name a declared agent (axon-T1218). - IR Generation — the
agentblock compiles to anIRAgentnode carrying goal, tools, the bounds (15 iter / 50k tokens / $2.50), strategy (react), recovery policy (forge), the return type and — for a declared struct type — its field schema; the call compiles to anagent_callnode inside the step's body, preserving compositional semantics. - Runtime Execution — the dispatcher's agent loop resolves the
declaration (an undeclared agent is refused before any spend), then runs
the strategy's control shape. Every deliberation goes through the same step
core as any cognitive step (same wire events, audit row, cancellation and
effect policy). Under
reactthe model answersACT: <Tool>orANSWER: <text>; a tool outside the agent's declared grant is refused and recorded, never dispatched. Every bound — iterations, tokens, cost, wall clock — is checked before each deliberation; when one bites,on_stuckdecides. A declared return type is validated on the final answer. - Trace Events — every deliberation is a step in the flow's wire events
(
StepStart/StepCompleteunder<Agent>:<move>, e.g.MarketResearcher:react), and every tool dispatch the agent makes is a step of its own, giving full observability into the reasoning trajectory.
Why this matters: The agent is not a Python class that wraps while True.
It is a compiled cognitive primitive — the compiler verifies its budget
boundedness (axon-T1216), refuses a call to an agent nobody declared
(axon-T1218), and checks its return type (axon-T1219: return: must name a
type, and the step that calls the agent must declare the same output:); when
the return type is a declared type, the runtime validates the agent's final
answer against its fields and routes a non-conforming answer through
on_stuck rather than calling it a result. The backend generates
strategy-specific prompts, and the runtime executes a formally-defined BDI loop
with epistemic convergence criteria. This is the difference between duct-taping
an LLM into a loop and engineering an autonomous system with mathematical
guarantees.
Agent Use Case 1: Autonomous Legal Research Agent
A law firm deploys an agent that autonomously researches case law until it finds sufficient precedent — or exhausts its budget and escalates to a human attorney:
// The tools this agent uses must EXIST: an agent naming a tool nobody
// declared is an incomplete example, not a grammar gap.
tool WebSearch {
timeout: 10s
}
tool PDFExtractor {
timeout: 30s
}
agent CaseLawResearcher {
goal: "Find 3+ relevant precedents for the contract dispute
with verified court citations"
tools: [WebSearch, PDFExtractor]
strategy: reflexion
max_iterations: 20
max_cost: 5.00
on_stuck: escalate
return: CaseLawReport
}
reflexionstrategy adds self-critique after each cycle — the agent evaluates whether its found precedents are truly relevant, not just keyword matcheson_stuck: escalatemeans if the agent doubts its findings after 20 cycles, it raisesAgentStuckErrorwith full context, so the human reviews exactly where the agent got stuck- Budget cap of $5.00 prevents runaway API costs — the compiler guarantees termination
Agent Use Case 2: Multi-Agent Data Pipeline
A BI platform chains two agents: one gathers data, the other analyzes it. Both execute within the same compiled flow:
tool WebSearch { provider: http timeout: 10s }
tool FileReader { provider: native timeout: 5s }
tool Calculator { provider: native }
tool DataAnalyzer { provider: native timeout: 30s }
agent DataGatherer {
goal: "Collect quarterly revenue data from public filings"
tools: [WebSearch, FileReader]
strategy: react
max_iterations: 10
on_stuck: retry
return: DataSet
}
agent TrendAnalyzer {
goal: "Identify year-over-year growth patterns and anomalies"
tools: [Calculator, DataAnalyzer]
strategy: plan_and_execute
max_iterations: 8
on_stuck: forge
return: TrendReport
}
flow QuarterlyIntelligence(sector: String) -> TrendReport {
step Gather { DataGatherer(sector) output: DataSet }
step Analyze { TrendAnalyzer(Gather.output) output: TrendReport }
}
- Two agents, two strategies:
reactfor data gathering (fast, tool-heavy),plan_and_executefor analysis (structured, plan-then-verify) - Each agent has independent budget tracking — if
DataGatherercosts $0.50,TrendAnalyzerstill has its full budget - If
TrendAnalyzergets stuck,forgetriggers creative re-seeding via the Poincaré pipeline, generating novel analytical angles
Agent Use Case 3: Customer Onboarding Agent with Dynamic Recovery
A SaaS platform uses an agent to guide new customers through a personalized onboarding flow, adapting when it gets stuck:
tool APICall {
timeout: 10s
}
tool Calculator {
timeout: 5s
}
persona OnboardingSpecialist {
domain: ["product knowledge", "user experience"]
tone: empathetic
confidence_threshold: 0.80
}
type OnboardingReport {
workspace: String
tutorial_steps: List<String>
confidence: Float
}
agent OnboardingGuide {
goal: "Complete the customer's onboarding checklist with
personalized recommendations for their industry"
tools: [APICall, Calculator]
strategy: custom
max_iterations: 12
max_tokens: 30000
on_stuck: forge
return: OnboardingReport
step Greet { ask: "Welcome the user and assess their goals" }
step Configure { ask: "Recommend workspace configuration" }
step Train { ask: "Generate personalized tutorial sequence" }
}
customstrategy: the agent follows a user-defined step sequence (Greet → Configure → Train), not a generic loopon_stuck: forge— if the agent can't personalize recommendations (e.g., unknown industry), it triggers creative synthesis to propose novel onboarding paths instead of failingcustomis the one strategy that carries a body:strategy: customwith no steps, or steps under any other strategy, is a compile error (axon-T1217) — a step sequence is never silently ignored- The
return: OnboardingReporttype is checked by the type checker (it must name a type, and a step calling the agent must agree onoutput:), and becauseOnboardingReportis a declaredtype, the runtime validates the agent's final answer against its fields — a structurally valid report, not just free text
VI. Compile-Time Security — the shield Primitive
AXON introduces an eighth paradigm shift: Information Flow Control (IFC) as a first-class compiled construct, providing compile-time security guarantees against LLM-specific attack vectors.
Every LLM framework treats security as an afterthought — runtime guardrails
bolted on top of applications. AXON's shield primitive makes security a
compiler-verified property of your program, grounded in taint analysis and
Information Flow Control theory.
Trust Lattice (Denning-style IFC). The shield system operates over a trust lattice where data flows from untrusted sources through shield application points to trusted sinks. The compiler statically verifies that every path from an untrusted source to a trusted sink passes through at least one shield:
U : DataLabel → TrustLevel
TrustLevel = Untrusted < Scanned < Sanitized < Trusted
∀ path(source, sink) ∈ Flow :
label(source) = Untrusted ∧ label(sink) = Trusted
→ ∃ shield ∈ path : label(shield.output) ≥ Sanitized
Threat Taxonomy. The scan field declares which threats the shield detects,
drawn from a formal taxonomy of 11 LLM attack categories:
T = { prompt_injection, jailbreak, data_exfil, pii_leak, toxicity,
bias, hallucination, code_injection, social_engineering,
model_theft, training_poisoning }
Detection Strategies. The strategy parameter selects the detection
mechanism, each with different cost/accuracy tradeoffs:
Σ : Strategy → (Cost, Accuracy, Latency)
Σ(pattern) = (low, medium, fast) — regex/heuristic scan
Σ(classifier) = (medium, high, medium) — fine-tuned classifier (Llama Guard)
Σ(dual_llm) = (high, highest, slow) — privileged/quarantined model pair
Σ(canary) = (low, medium, fast) — traceable token injection
Σ(perplexity) = (medium, high, medium) — statistical anomaly detection
Σ(ensemble) = (high, highest, slow) — majority voting across multiple strategies
Capability Enforcement. The compiler statically verifies that agent tool access is a subset of the shield's allow list — preventing privilege escalation at compile time:
∀ agent A with shield S :
tools(A) ⊆ allow_tools(S) — verified at compile time
tools(A) ∩ deny_tools(S) = ∅ — also verified
Usage example — LLM Input Shield:
tool WebSearch { provider: http timeout: 10s }
tool Calculator { provider: native }
shield InputGuard {
scan: [prompt_injection, jailbreak, pii_leak]
strategy: dual_llm
on_breach: halt
severity: critical
allow_tools: [WebSearch, Calculator]
deny_tools: [code_executor]
sandbox: true
redact: [email, phone]
confidence_threshold: 0.85
}
persona SecureAssistant {
domain: ["customer support"]
tone: formal
confidence_threshold: 0.80
}
agent SecureBot {
goal: "Answer customer queries safely"
tools: [WebSearch, Calculator]
shield: InputGuard
strategy: react
max_iterations: 10
return: SafeResponse
}
flow SecureSupport(query: String) -> SafeResponse {
shield InputGuard on query -> SanitizedQuery
step Process {
SecureBot(SanitizedQuery)
output: SafeResponse
}
}
run SecureSupport("Help me with my account")
with SecureAssistant
What the compiler does:
- Type Checking — validates all scan categories, strategies, breach policies, severity levels, and confidence thresholds. Detects allow/deny overlaps and invalid configurations at compile time.
- Capability Enforcement — verifies that
SecureBotonly uses[web_search, calculator]which are inInputGuard.allow, and that neither appears indeny. IfSecureBottried to usecode_executor, the compiler would reject the program. - Taint Analysis — verifies that
query(untrusted) passes throughshield InputGuard on querybefore reaching the agent's trusted context. - Runtime Execution — the shield step emits
SHIELD_SCAN_START, scans for prompt injection/jailbreak/PII, and either passes (SHIELD_SCAN_PASS) or raisesShieldBreachError(SHIELD_SCAN_BREACH).
Shield Use Case 1: Financial Data Pipeline with PII Redaction
shield DataShield {
scan: [pii_leak, data_exfil]
strategy: classifier
on_breach: sanitize_and_retry
max_retries: 3
severity: high
redact: [ssn, credit_card, bank_account]
}
flow ProcessFinancialQuery(input: String) -> Report {
shield DataShield on input -> CleanInput
step Analyze {
given: CleanInput
ask: "Analyze the financial data"
output: Report
}
}
- PII fields (SSN, credit card, bank account) are auto-redacted before the LLM sees the data
sanitize_and_retrymeans detected threats are cleaned and re-scanned up to 3 times, not just blocked- The compiler guarantees the LLM never processes raw PII
Shield Use Case 2: Multi-Agent System with Capability Isolation
shield ResearchShield {
scan: [data_exfil, model_theft]
strategy: ensemble
on_breach: quarantine
allow: [web_search, file_reader]
deny: [code_executor, api_call]
sandbox: true
}
tool web_search {
timeout: 10s
}
tool file_reader {
timeout: 10s
}
agent Researcher {
goal: "Gather market intelligence from public sources"
tools: [web_search, file_reader]
shield: ResearchShield
strategy: reflexion
max_iterations: 15
return: IntelligenceReport
}
ensemblestrategy runs multiple detectors with majority voting — highest accuracy for sensitive operationssandbox: trueruns tool execution in an isolated environment- Capability enforcement: the compiler rejects any agent that tries to use
code_executororapi_call— preventing privilege escalation by design quarantinebreach policy isolates suspicious data for human review instead of blocking operations