Skip to main content

axon/
lib.rs

1//! AXON runtime library — exposes the full AXON runtime: compiler
2//! frontend (re-exported from `axon-frontend`), handlers, runtime
3//! primitives, ESK, HTTP/WebSocket servers, persistence, OTS pipelines.
4//!
5//! Used by the `axon` binary and by integration tests.
6//!
7//! # Frontend vs runtime
8//!
9//! §Fase 12.a — the compiler frontend (lexer, parser, AST, type checker,
10//! IR generator, top-level checker, and the closed catalogs used by the
11//! type checker) lives in the sibling crate `axon-frontend`, which has
12//! zero runtime dependencies. This crate re-exports those modules
13//! transparently so every existing caller (76 call sites across 26
14//! files) keeps compiling without changes. The crate `axon-lsp`
15//! consumes `axon-frontend` directly, skipping the runtime surface.
16
17// ── §Fase 12.a — frontend re-exports (transparent to callers) ───────
18pub use axon_frontend::{
19    ast,
20    checker,
21    epistemic,
22    ir_generator,
23    ir_nodes,
24    legal_basis,
25    lexer,
26    parser,
27    refinement,
28    // §Fase 41.a — the session-type algebra (duality, regular-coinductive
29    // equality, §41.c credit-refined backpressure, §41.e SSE-polarity
30    // predicate). Re-exported so downstream consumers (the enterprise
31    // server's §Fase 41.f WS surface in `axon-enterprise`) reach it via the
32    // single `axon = …` workspace dep without an extra `axon-frontend`
33    // dependency line.
34    session,
35    // §Fase 41.h — multiparty session types (global types + projection).
36    // The orchestration story for n-agent skill/tool topologies: declare
37    // a `GlobalType`, project per role, drive each role's binary
38    // `SessionType` over the §41.d/41.f runtime — composition stays in
39    // lock-step by construction.
40    multiparty,
41    store_introspect,
42    store_schema,
43    store_schema_manifest,
44    stream_effect,
45    tokens,
46    type_checker,
47};
48
49// `ots_catalog` is the compile-time slug catalog; the runtime `ots`
50// module (below) re-exports these constants for backward compatibility.
51
52// ── Runtime modules (stay in this crate) ────────────────────────────
53
54pub mod anchor_checker;
55pub mod api_keys;
56pub mod audit_trail;
57pub mod auth_middleware;
58pub mod axon_server;
59pub mod backend;
60pub mod backend_error;
61pub mod circuit_breaker;
62pub mod compiler;
63pub mod config_persistence;
64pub mod conversation;
65pub mod cors;
66pub mod cost_estimator;
67pub mod daemon;
68pub mod db_pool;
69pub mod deployer;
70pub mod emcp;
71pub mod event_bus;
72/// §λ-L-E Fase 2 — Handler layer (Free Monad + CPS). Port of `axon/runtime/handlers/`.
73pub mod handlers;
74/// §λ-L-E Fase 3 + 5 runtime primitives. Port of `axon/runtime/` (lease kernel,
75/// reconcile loop, ensemble aggregator, immune kernels).
76pub mod runtime;
77/// §Fase 41.d — the **runtime** of a session-typed dialogue. The static
78/// algebra (`axon_frontend::session`: duality, regular-coinductive
79/// equality, credit-refined backpressure index `!ⁿA.S`) gets a dynamic
80/// counterpart here: an operational state machine (`SessionRuntime`)
81/// with one method per algebra rule, a wire envelope (`Frame`), and an
82/// RFC 6455 WebSocket carrier (`ws::drive`) that runs a session type
83/// against a peer. Carrier-agnostic core; the WS layer is one binding.
84pub mod session_runtime;
85/// §Fase 51.e — the `quant` cognitive primitive's RUNTIME: the
86/// [`quant::QuantBackend`] port + a usable dense-statevector reference
87/// simulator capped at n ≤ 10 (the OSS half; enterprise mounts the QuIDD /
88/// VRAM / QPU engine behind the same trait in §51.f–i).
89pub mod quant;
90/// §Fase 23.f — Algebraic effects runtime. FSM dispatch loop +
91/// handler stack + Free-Monad interpretation of CPS-lowered IR
92/// (consumes the JSON IR emitted by the Python frontend in 23.b/c/d).
93pub mod effects;
94/// §Fase 24.b — Native Rust LLM backends. Per-provider async clients
95/// behind a `Backend` trait + `Registry`. Per-provider modules
96/// (anthropic.rs / openai.rs / gemini.rs / kimi.rs / glm.rs / ollama.rs
97/// / openrouter.rs) land in 24.c–24.i; this module ships the shared
98/// infra (trait + types + error + retry + observability + locked_model
99/// + tokens dispatch).
100pub mod backends;
101/// §Fase 36.b — the Backend Resolution Contract (D1): the pure,
102/// deterministic precedence ladder that resolves a flow's execution
103/// backend (request → axonendpoint `backend:` → server default →
104/// environment-available `auto` → honest failure).
105pub mod backend_resolution;
106/// §Fase 68.c — pure capability-aware model resolution: a step's
107/// `requires_context:` + a backend's §68.a model catalog → the smallest model
108/// that fits, or honest fail-closed (never a too-small model).
109pub mod model_resolution;
110/// §Fase 69.a — the Advantage Witness: a transversal law
111/// (`axon://logic/no_unwitnessed_advantage`). A primitive may not claim an
112/// advantage over a cheaper baseline without a machine-checkable witness on real
113/// data; the `AdvantageWitness` trait + closed metric catalog + verdict.
114pub mod advantage_witness;
115/// §Fase 69.b — quant as the first Advantage-Witness instance: the amplitude-
116/// fidelity ≡ cosine theorem made executable + the `QuantKernelWitness` that
117/// fails closed (no advantage over the classical baseline).
118pub mod quant_witness;
119/// §Fase 69.d — the SECOND Advantage-Witness instance (transversality proof):
120/// retrieval / navigate via the `ranking_lift` metric over flat cosine retrieval.
121pub mod retrieval_witness;
122/// §ESK Fase 6 — Epistemic Security Kernel. Port of `axon/runtime/esk/`.
123pub mod esk;
124/// §Fase 51 — Proof-Carrying Code. apx/axonendpoint carry a portable,
125/// machine-checkable proof object an INDEPENDENT verifier checks
126/// against the artifact WITHOUT trusting the compiler that produced it
127/// (the move from `esk`'s builder-signed attestation to a consumer-
128/// verifiable proof). §51.a ships the kernel + the ComplianceCoverage
129/// property class.
130pub mod pcc;
131/// CLI handlers for the ESK audit commands (dossier, sbom, audit, evidence-package).
132pub mod audit_cli;
133/// §Fase 51.f — CLI handlers for the PCC commands (`axon pcc prove` /
134/// `axon pcc verify`). Closes the Proof-Carrying Code loop at the
135/// command line: generate a proof bundle from source, then
136/// independently verify it against a recompile of that source.
137pub mod pcc_cli;
138pub mod flow_inspect;
139/// §Fase 33.x.g — Closed-catalog runtime warnings for the SSE
140/// production path. Surfaces `axon-W002 streaming-not-supported`
141/// when the async streaming path falls back to legacy synchronous
142/// delivery (D5 — no silent degradation).
143pub mod runtime_warnings;
144/// §Fase 33.x.h — Process-wide runtime opt-in flags. Today carries
145/// the `tokenizer_fallback` flag that gates BPE-tokenized chunking
146/// on the SSE LEGACY path (D9 — opt-in; defaults OFF for v1.24.0
147/// wire byte-compat).
148pub mod runtime_flags;
149/// §Fase 33.x.b — Streaming-shaped execution plan extractor. Builds
150/// `StreamingExecutionPlan` from `.axon` source for the production
151/// async SSE path; pre-resolves per-step `BackpressurePolicy` via
152/// `stream_effect_dispatcher` so the hot per-chunk loop in
153/// `axon_server::server_execute_streaming_async` does not re-walk
154/// the AST per chunk. Rejects flows that use 33.x.b-unsupported
155/// features (anchors / lambda apply / let bindings / mid-stream
156/// use_tool / hibernate / pix) with a closed-catalog `PlanFallback`
157/// so the SSE handler can route them to the legacy synchronous path.
158pub mod flow_plan;
159/// §Fase 33.y.b — Per-IRFlowNode async dispatcher skeleton. Closed-
160/// catalog, compiler-enforced exhaustive match over the 45-variant
161/// `IRFlowNode` enum. Subsequent sub-fases 33.y.c–j replace the
162/// transitional legacy shim with real per-variant async handlers.
163/// 33.y.l retires the shim + the `LegacyShimHandled` outcome variant
164/// once every IR variant has its real handler.
165pub mod flow_dispatcher;
166/// §Fase 33.z.b — Streaming-via-dispatcher graft skeleton. Lifts
167/// `flow_dispatcher::dispatch_node` (Fase 33.y, 45/45 structurally
168/// complete) into the production SSE hot path behind the
169/// `AXON_STREAMING_VIA_DISPATCHER` runtime flag (default OFF;
170/// flip to ON for v1.27.0 stable in 33.z.c; legacy path retired
171/// in 33.z.e).
172pub mod streaming_via_dispatcher;
173pub mod flow_version;
174pub mod epistemic_capture;
175pub mod exec_context;
176pub mod graceful_shutdown;
177pub mod graph_export;
178pub mod health_check;
179pub mod hooks;
180pub mod http_tool;
181pub mod inspect;
182pub mod lambda_data;
183pub mod lambda_runtime;
184pub mod logging;
185pub mod migrations;
186pub mod output;
187pub mod mdn;
188pub mod mdn_memory;
189pub mod mdn_provenance;
190pub mod parallel;
191pub mod pix_mdn_pcc;
192pub mod pix_navigator;
193pub mod plan_diff;
194pub mod plan_export;
195pub mod rate_limiter;
196pub mod request_binding;
197pub mod request_log;
198pub mod request_middleware;
199pub mod repl;
200pub mod replay;
201pub mod request_tracing;
202// §Fase 32.c — Body schema validation for first-class axonendpoint
203// routes. `route_schema` hosts the pure `validate_body` primitive +
204// `collect_type_table` walker. The fallback handler in `axon_server`
205// consults the table at request time per (method, path).
206pub mod route_schema;
207// §Fase 32.f — Idempotency-Key store for POST/PUT axonendpoint routes.
208// Stripe-compatible. Cross-tenant isolation via (client_id, path, key)
209// composite key. 24h default retention. Same-key-different-body
210// returns 422 per industry convention.
211pub mod idempotency;
212// §Fase 32.g — Auth scope (capability subset matching) for first-class
213// axonendpoint routes. `requires: [admin, legal.read, ...]` declarations
214// gate dispatch on declared_requires ⊆ token_capabilities. Closed slug
215// grammar shared with `axon_frontend::parser`. Mirror of Python
216// `_is_valid_capability_slug`.
217pub mod auth_scope;
218// §Fase 32.h — Replay-token binding for first-class axonendpoint routes.
219// Append-only log keyed by trace_id; populated on every successful 2xx
220// POST/PUT where `replay:` resolves to true. `GET /v1/replay/<trace_id>`
221// returns the original request body + response body + metadata for
222// regulatory audit (PCI DSS Req 10, FedRAMP AU-2, FRE 502, 21 CFR Part 11).
223pub mod axonendpoint_replay;
224// §Fase 33.b — Layer 1: flow execution event stream. Closed catalog of
225// {FlowStart, StepStart, StepToken, StepComplete, FlowComplete,
226// FlowError} per D2. Consumed by execute_sse_handler (33.c) for live
227// SSE forwarding; cross-stack drift-gated against the Python mirror.
228pub mod flow_execution_event;
229pub mod resilient_backend;
230pub mod retry_policy;
231pub mod runner;
232// §Fase 40.b — public shield-scanner registration hook. OSS ships no
233// scanners (identity); enterprise vertical crates register HIPAA/legal/AML
234// scanners here at boot. The `shield apply` handler consults it.
235pub mod shield_registry;
236pub mod server_config;
237pub mod server_metrics;
238pub mod session_scope;
239pub mod session_store;
240pub mod step_deps;
241pub mod storage;
242pub mod storage_postgres;
243// §Fase 35 — the `axonstore` cognitive data plane runtime. 35.b ships
244// `store::filter` (the parameterized where-expression compiler).
245pub mod store;
246pub mod stdlib;
247pub mod tenant;
248pub mod tenant_secrets;
249// §Fase 10.e — JWT signature verification + JWKS client. Used by
250// tenant::tenant_extractor_middleware when AXON_JWT_JWKS_URL is set.
251pub mod jwt_verifier;
252// §λ-L-E Fase 11.a runtime — `trust_verifiers` holds the runtime
253// implementations that the compiler recognises; `stream_runtime` is
254// the Stream<T> channel with policy dispatch. The compile-time
255// `refinement` and `stream_effect` catalogs live in `axon-frontend`.
256pub mod trust_verifiers;
257pub mod stream_runtime;
258// §Fase 33.e — Stream-effect dispatcher (Layer 4 of the Fase 33 cycle).
259// Bridges the `effects: <stream:<policy>>` declarations on tool
260// definitions to actual runtime backpressure behavior on the SSE
261// wire. The dispatcher itself is a thin composition over
262// `stream_runtime::Stream<T>` (which carries the policy semantics)
263// and the AST resolver (which extracts the declared policy from the
264// tool referenced by each step).
265pub mod stream_effect_dispatcher;
266// §Fase 33.f — Cooperative cancellation primitives (D6 cancel-safety).
267// `CancellationFlag` + `CancelOnDrop` are the building blocks that
268// bind SSE response lifetime to the executor's spawn_blocking task:
269// when the wire client disconnects, the consumer cancels the flag,
270// which the producer observes between event emissions and exits
271// early instead of running the flow to completion against a dropped
272// channel.
273pub mod cancel_token;
274// §Fase 33.z.k (v1.28.0) — Wire-format adapter framework.
275// `wire_format` defines the WireFormatAdapter trait + per-dialect
276// adapters (axon / openai / anthropic). The SSE producer in
277// `axon_server::execute_sse_handler` uses `select_adapter(dialect)`
278// to translate internal FlowExecutionEvents into the dialect-
279// specific wire shape adopters' SDKs expect.
280pub mod wire_format;
281// §Fase 39.b — Pure Silicon Cognition wire envelope. The canonical
282// `FlowEnvelope` payload for `transport: json` axonendpoint responses
283// + legacy `POST /v1/execute`. Isomorphic serialization of the
284// ψ-vector `⟨T, V, E⟩`. See `docs/fase/fase_39_pure_silicon_cognition.md`.
285pub mod wire_envelope;
286// §Fase 39.c — Wire envelope producer helpers. Closed-taxonomy
287// translators from runtime execution metadata into the wire envelope's
288// epistemic fields (`provenance_chain` + `blame_attribution`).
289pub mod wire_envelope_producers;
290// §Fase 39.f — Rust CLI binary parity. New subcommands that closed
291// the gap vs the Python CLI (`axon parse` aggregator + `axon fmt`
292// round-trip formatter).
293pub mod cli_parse;
294pub mod cli_fmt;
295// §λ-L-E Fase 11.b — Zero-Copy Multimodal Buffers.
296// `buffer` defines ZeroCopyBuffer (Arc<[u8]>-backed) + BufferKind
297// (open registry) + BufferPool (slab allocator with per-tenant
298// soft-limit accounting). `ingest` hosts the network deposit paths
299// (multipart/form-data streaming parser, WebSocket binary-frame
300// accumulator) that populate buffers without intermediate copies.
301pub mod buffer;
302pub mod ingest;
303// §λ-L-E Fase 11.c runtime — `replay_token` hosts ReplayToken canonical
304// hashing + pluggable ReplayLog + ReplayExecutor for re-running from
305// any token. The compile-time `legal_basis` catalog lives in
306// `axon-frontend`.
307pub mod replay_token;
308// §λ-L-E Fase 11.d — Stateful PEM over WebSocket. `pem::state`
309// defines CognitiveState with Q32.32 fixed-point float encoding
310// so density-matrix round-trips are bit-identical across reconnects.
311// `pem::continuity_token` is an HMAC-signed handshake that proves
312// a reconnecting client is the original party. `pem::backend`
313// exposes the PersistenceBackend async trait + in-memory impl;
314// production uses axon_enterprise::cognitive_states (Postgres +
315// envelope encryption).
316pub mod pem;
317// §λ-L-E Fase 11.e — Ontological Tool Synthesis binary pipelines.
318// `ots::pipeline` hosts Transformer trait + TransformerRegistry +
319// Dijkstra-based path search. `ots::native` seeds μ-law ↔ PCM16
320// + resample (8k/16k/48k ladder). `ots::subprocess::ffmpeg` is
321// the subprocess fallback with warm-pool + availability detection.
322// The compile-time slug catalog lives in `axon-frontend::ots_catalog`.
323pub mod ots;
324pub mod tool_executor;
325pub mod tool_registry;
326// §Fase 34.b (v1.29.0) — Tool trait + ToolChunk closed-catalog
327// surface for tools-as-stream-producers. Bridges adopter-source
328// `effects: <stream:<policy>>` declarations into the runtime via
329// the dispatcher's per-chunk wire emission path (Fase 34.d/g lands
330// the wiring; this module is the structural foundation).
331pub mod tool_trait;
332// §Fase 34.d (v1.29.0) — Bridge from ToolEntry (registry shape) to
333// Tool trait impls (dispatcher's streaming surface). The dispatcher's
334// `pure_shape::run_step` calls `tool_dispatch_bridge::resolve_streaming_tool`
335// for is_streaming-flagged tools + drains the resulting Stream<ToolChunk>
336// chunk-by-chunk into the wire.
337pub mod tool_dispatch_bridge;
338pub mod tool_validator;
339pub mod trace_export;
340pub mod trace_store;
341pub mod trace_stats;
342pub mod tracer;
343pub mod version_diff;
344pub mod webhook_delivery;
345pub mod webhooks;