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    // §Fase 80.f/80.g — the blessed preset catalog + the voice/preset
48    // desugar surface (`axon desugar` renders from these).
49    upstream_presets,
50    voice_desugar,
51};
52
53// `ots_catalog` is the compile-time slug catalog; the runtime `ots`
54// module (below) re-exports these constants for backward compatibility.
55
56// ── Runtime modules (stay in this crate) ────────────────────────────
57
58pub mod anchor_checker;
59pub mod api_keys;
60pub mod audit_trail;
61pub mod auth_middleware;
62pub mod axon_server;
63pub mod backend;
64pub mod backend_error;
65pub mod circuit_breaker;
66pub mod compiler;
67pub mod config_persistence;
68pub mod conversation;
69pub mod cors;
70pub mod cost_estimator;
71pub mod daemon;
72/// §Fase 108.b — the deterministic columnar engine behind `dataspace`
73/// (immutable record batches, validity bitmaps, zone maps, provenance).
74pub mod dataspace_engine;
75pub mod db_pool;
76pub mod deployer;
77pub mod emcp;
78pub mod event_bus;
79/// §Fase 74.c — the durable event outbox (the append-only log + processed
80/// cursor that makes `emit` survive the consumer being down).
81pub mod event_outbox;
82/// §λ-L-E Fase 2 — Handler layer (Free Monad + CPS). Port of `axon/runtime/handlers/`.
83pub mod handlers;
84/// §λ-L-E Fase 3 + 5 runtime primitives. Port of `axon/runtime/` (lease kernel,
85/// reconcile loop, ensemble aggregator, immune kernels).
86pub mod runtime;
87/// §Fase 41.d — the **runtime** of a session-typed dialogue. The static
88/// algebra (`axon_frontend::session`: duality, regular-coinductive
89/// equality, credit-refined backpressure index `!ⁿA.S`) gets a dynamic
90/// counterpart here: an operational state machine (`SessionRuntime`)
91/// with one method per algebra rule, a wire envelope (`Frame`), and an
92/// RFC 6455 WebSocket carrier (`ws::drive`) that runs a session type
93/// against a peer. Carrier-agnostic core; the WS layer is one binding.
94pub mod session_runtime;
95/// §Fase 80.d — the `upstream` runtime: the CLIENT dual of the §41.d
96/// carrier. Dials OUT to a third-party vendor (STT/TTS/realtime speech)
97/// over RFC 6455 + TLS, applies the declared auth handshake, transcodes
98/// wire↔session per the compiled `map:` projection (T849-total), applies
99/// the declared `overflow:` policy when the vendor is the slow side, and
100/// reconnects with witnessed, fail-closed exponential backoff. A new
101/// vendor is a new DECLARATION, never new Rust code.
102pub mod upstream_runtime;
103/// §Fase 51.e — the `quant` cognitive primitive's RUNTIME: the
104/// [`quant::QuantBackend`] port + a usable dense-statevector reference
105/// simulator capped at n ≤ 10 (the OSS half; enterprise mounts the QuIDD /
106/// VRAM / QPU engine behind the same trait in §51.f–i).
107pub mod quant;
108/// §Fase 23.f — Algebraic effects runtime. FSM dispatch loop +
109/// handler stack + Free-Monad interpretation of CPS-lowered IR
110/// (consumes the JSON IR emitted by the Python frontend in 23.b/c/d).
111pub mod effects;
112/// §Fase 24.b — Native Rust LLM backends. Per-provider async clients
113/// behind a `Backend` trait + `Registry`. Per-provider modules
114/// (anthropic.rs / openai.rs / gemini.rs / kimi.rs / glm.rs / ollama.rs
115/// / openrouter.rs) land in 24.c–24.i; this module ships the shared
116/// infra (trait + types + error + retry + observability + locked_model
117/// + tokens dispatch).
118pub mod backends;
119/// §Fase 36.b — the Backend Resolution Contract (D1): the pure,
120/// deterministic precedence ladder that resolves a flow's execution
121/// backend (request → axonendpoint `backend:` → server default →
122/// environment-available `auto` → honest failure).
123pub mod backend_resolution;
124/// §Fase 68.c — pure capability-aware model resolution: a step's
125/// `requires_context:` + a backend's §68.a model catalog → the smallest model
126/// that fits, or honest fail-closed (never a too-small model).
127pub mod model_resolution;
128/// §Fase 69.a — the Advantage Witness: a transversal law
129/// (`axon://logic/no_unwitnessed_advantage`). A primitive may not claim an
130/// advantage over a cheaper baseline without a machine-checkable witness on real
131/// data; the `AdvantageWitness` trait + closed metric catalog + verdict.
132pub mod advantage_witness;
133/// §Fase 69.b — quant as the first Advantage-Witness instance: the amplitude-
134/// fidelity ≡ cosine theorem made executable + the `QuantKernelWitness` that
135/// fails closed (no advantage over the classical baseline).
136pub mod quant_witness;
137/// §Fase 69.d — the SECOND Advantage-Witness instance (transversality proof):
138/// retrieval / navigate via the `ranking_lift` metric over flat cosine retrieval.
139pub mod retrieval_witness;
140/// §ESK Fase 6 — Epistemic Security Kernel. Port of `axon/runtime/esk/`.
141pub mod esk;
142/// §Fase 51 — Proof-Carrying Code. apx/axonendpoint carry a portable,
143/// machine-checkable proof object an INDEPENDENT verifier checks
144/// against the artifact WITHOUT trusting the compiler that produced it
145/// (the move from `esk`'s builder-signed attestation to a consumer-
146/// verifiable proof). §51.a ships the kernel + the ComplianceCoverage
147/// property class.
148pub mod pcc;
149/// CLI handlers for the ESK audit commands (dossier, sbom, audit, evidence-package).
150pub mod audit_cli;
151/// §Fase 51.f — CLI handlers for the PCC commands (`axon pcc prove` /
152/// `axon pcc verify`). Closes the Proof-Carrying Code loop at the
153/// command line: generate a proof bundle from source, then
154/// independently verify it against a recompile of that source.
155pub mod pcc_cli;
156pub mod flow_inspect;
157/// §Fase 33.x.g — Closed-catalog runtime warnings for the SSE
158/// production path. Surfaces `axon-W002 streaming-not-supported`
159/// when the async streaming path falls back to legacy synchronous
160/// delivery (D5 — no silent degradation).
161pub mod runtime_warnings;
162/// §Fase 33.x.h — Process-wide runtime opt-in flags. Today carries
163/// the `tokenizer_fallback` flag that gates BPE-tokenized chunking
164/// on the SSE LEGACY path (D9 — opt-in; defaults OFF for v1.24.0
165/// wire byte-compat).
166pub mod runtime_flags;
167/// §Fase 33.x.b — Streaming-shaped execution plan extractor. Builds
168/// `StreamingExecutionPlan` from `.axon` source for the production
169/// async SSE path; pre-resolves per-step `BackpressurePolicy` via
170/// `stream_effect_dispatcher` so the hot per-chunk loop in
171/// `axon_server::server_execute_streaming_async` does not re-walk
172/// the AST per chunk. Rejects flows that use 33.x.b-unsupported
173/// features (anchors / lambda apply / let bindings / mid-stream
174/// use_tool / hibernate / pix) with a closed-catalog `PlanFallback`
175/// so the SSE handler can route them to the legacy synchronous path.
176pub mod flow_plan;
177/// §Fase 33.y.b — Per-IRFlowNode async dispatcher skeleton. Closed-
178/// catalog, compiler-enforced exhaustive match over the 45-variant
179/// `IRFlowNode` enum. Subsequent sub-fases 33.y.c–j replace the
180/// transitional legacy shim with real per-variant async handlers.
181/// 33.y.l retires the shim + the `LegacyShimHandled` outcome variant
182/// once every IR variant has its real handler.
183pub mod flow_dispatcher;
184/// §Fase 33.z.b — Streaming-via-dispatcher graft skeleton. Lifts
185/// `flow_dispatcher::dispatch_node` (Fase 33.y, 45/45 structurally
186/// complete) into the production SSE hot path behind the
187/// `AXON_STREAMING_VIA_DISPATCHER` runtime flag (default OFF;
188/// flip to ON for v1.27.0 stable in 33.z.c; legacy path retired
189/// in 33.z.e).
190pub mod streaming_via_dispatcher;
191pub mod flow_version;
192pub mod epistemic_capture;
193pub mod exec_context;
194pub mod graceful_shutdown;
195pub mod graph_export;
196pub mod health_check;
197pub mod hooks;
198pub mod http_tool;
199/// §Fase 99.e/f — the deterministic OOXML writer (DOCX/PPTX/XLSX) behind the
200/// `DocumentRenderer` native tool. Byte-deterministic + provenance-embedding.
201pub mod ooxml;
202/// §Fase 100.b — the read-only filesystem capability + path sandbox.
203pub mod fs_sandbox;
204/// §Fase 100.c/d — the OOXML reader: bounded, born-Untrusted, Parsed text tree.
205pub mod ooxml_read;
206/// §Fase 100.e — the surgical edit engine + per-part hash manifest.
207pub mod ooxml_edit;
208/// §Fase 101.a — the `Inferred`-extraction contract: the `ExtractionEngine`
209/// trait, the born-`Inferred` span with measured confidence, and the
210/// confidence-floor quarantine gate. The producers §100 left the class without.
211pub mod extraction;
212/// §Fase 101.c — the IDP-E recognizer kernel: the deterministic geometry+topology
213/// engine (Otsu → cubical β₀/β₁ → geometric discrimination → reading order →
214/// pix-navigable canonical tree). Reads a bounded PGM/PBM raster; real image
215/// decode is the sidecar (§101.e). Scoped to clean machine-print (D101.17).
216pub mod idpe;
217/// §Fase 101.d — the active-inference foveation planner: spend the recognizer on
218/// the highest-information-scent regions until the answer resolves or the budget
219/// (§72) is exhausted; every foveation is a replayable `ledger` trail entry.
220pub mod foveation;
221/// §Fase 101.e — the IDP-E image front-end: deterministic Perona-Malik anisotropic
222/// diffusion (Catté-regularised) + Gabor phase-tensor orientation energy that
223/// clean and analyse a raster before recognition. The CVE-prone image DECODE is
224/// isolated in the sidecar binary (`src/bin/idpe_sidecar.rs`), which feeds this
225/// front-end already-decoded grayscale — hostile bytes never reach the runtime.
226pub mod idpe_frontend;
227pub mod inspect;
228/// §Fase 98.e — Native Web Acquisition runtime (`scrape_http` / `scrape_dom` /
229/// `scrape_crawl`); born-Untrusted content, pluggable stealth fetcher.
230pub mod scrape_tool;
231/// §Fase 104.a — Governed Contact Enrichment (`scrape_enrich`): structured
232/// contact lookup via a pluggable enterprise provider; results born Inferred
233/// (≤ believe-ceiling) + Untrusted. OSS default = typed refusal (no fabrication).
234pub mod enrichment;
235/// §Fase 105 — Governed CRM Delivery (`deliver`): the egress-dual of acquisition.
236/// Canonical, idempotent CRM operations delivered via a pluggable enterprise
237/// transducer; each field carries its epistemic provenance (D105.2) or the author
238/// vouched (T920). OSS default = typed refusal (no fabricated receipt).
239pub mod delivery;
240pub mod lambda_data;
241pub mod lambda_runtime;
242pub mod logging;
243pub mod migrations;
244pub mod output;
245pub mod mdn;
246pub mod mdn_memory;
247pub mod mdn_provenance;
248pub mod parallel;
249pub mod pix_mdn_pcc;
250pub mod pix_navigator;
251pub mod plan_diff;
252pub mod plan_export;
253pub mod rate_limiter;
254pub mod request_binding;
255pub mod request_log;
256pub mod request_middleware;
257pub mod repl;
258pub mod replay;
259pub mod request_tracing;
260// §Fase 32.c — Body schema validation for first-class axonendpoint
261// routes. `route_schema` hosts the pure `validate_body` primitive +
262// `collect_type_table` walker. The fallback handler in `axon_server`
263// consults the table at request time per (method, path).
264pub mod route_schema;
265// §Fase 32.f — Idempotency-Key store for POST/PUT axonendpoint routes.
266// Stripe-compatible. Cross-tenant isolation via (client_id, path, key)
267// composite key. 24h default retention. Same-key-different-body
268// returns 422 per industry convention.
269pub mod idempotency;
270// §Fase 32.g — Auth scope (capability subset matching) for first-class
271// axonendpoint routes. `requires: [admin, legal.read, ...]` declarations
272// gate dispatch on declared_requires ⊆ token_capabilities. Closed slug
273// grammar shared with `axon_frontend::parser`. Mirror of Python
274// `_is_valid_capability_slug`.
275pub mod auth_scope;
276// §Fase 32.h — Replay-token binding for first-class axonendpoint routes.
277// Append-only log keyed by trace_id; populated on every successful 2xx
278// POST/PUT where `replay:` resolves to true. `GET /v1/replay/<trace_id>`
279// returns the original request body + response body + metadata for
280// regulatory audit (PCI DSS Req 10, FedRAMP AU-2, FRE 502, 21 CFR Part 11).
281pub mod axonendpoint_replay;
282// §Fase 33.b — Layer 1: flow execution event stream. Closed catalog of
283// {FlowStart, StepStart, StepToken, StepComplete, FlowComplete,
284// FlowError} per D2. Consumed by execute_sse_handler (33.c) for live
285// SSE forwarding; cross-stack drift-gated against the Python mirror.
286pub mod flow_execution_event;
287pub mod resilient_backend;
288pub mod retry_policy;
289pub mod runner;
290// §Fase 40.b — public shield-scanner registration hook. OSS ships no
291// scanners (identity); enterprise vertical crates register HIPAA/legal/AML
292// scanners here at boot. The `shield apply` handler consults it.
293pub mod shield_registry;
294pub mod server_config;
295pub mod server_metrics;
296pub mod session_scope;
297pub mod session_store;
298pub mod step_deps;
299pub mod storage;
300pub mod storage_postgres;
301// §Fase 35 — the `axonstore` cognitive data plane runtime. 35.b ships
302// `store::filter` (the parameterized where-expression compiler).
303pub mod store;
304pub mod stdlib;
305pub mod tenant;
306pub mod tenant_secrets;
307// §Fase 10.e — JWT signature verification + JWKS client. Used by
308// tenant::tenant_extractor_middleware when AXON_JWT_JWKS_URL is set.
309pub mod jwt_verifier;
310// §λ-L-E Fase 11.a runtime — `trust_verifiers` holds the runtime
311// implementations that the compiler recognises; `stream_runtime` is
312// the Stream<T> channel with policy dispatch. The compile-time
313// `refinement` and `stream_effect` catalogs live in `axon-frontend`.
314pub mod trust_verifiers;
315pub mod stream_runtime;
316// §Fase 33.e — Stream-effect dispatcher (Layer 4 of the Fase 33 cycle).
317// Bridges the `effects: <stream:<policy>>` declarations on tool
318// definitions to actual runtime backpressure behavior on the SSE
319// wire. The dispatcher itself is a thin composition over
320// `stream_runtime::Stream<T>` (which carries the policy semantics)
321// and the AST resolver (which extracts the declared policy from the
322// tool referenced by each step).
323pub mod stream_effect_dispatcher;
324// §Fase 33.f — Cooperative cancellation primitives (D6 cancel-safety).
325// `CancellationFlag` + `CancelOnDrop` are the building blocks that
326// bind SSE response lifetime to the executor's spawn_blocking task:
327// when the wire client disconnects, the consumer cancels the flag,
328// which the producer observes between event emissions and exits
329// early instead of running the flow to completion against a dropped
330// channel.
331pub mod cancel_token;
332// §Fase 33.z.k (v1.28.0) — Wire-format adapter framework.
333// `wire_format` defines the WireFormatAdapter trait + per-dialect
334// adapters (axon / openai / anthropic). The SSE producer in
335// `axon_server::execute_sse_handler` uses `select_adapter(dialect)`
336// to translate internal FlowExecutionEvents into the dialect-
337// specific wire shape adopters' SDKs expect.
338pub mod wire_format;
339// §Fase 39.b — Pure Silicon Cognition wire envelope. The canonical
340// `FlowEnvelope` payload for `transport: json` axonendpoint responses
341// + legacy `POST /v1/execute`. Isomorphic serialization of the
342// ψ-vector `⟨T, V, E⟩`. See `docs/fase/fase_39_pure_silicon_cognition.md`.
343pub mod wire_envelope;
344// §Fase 39.c — Wire envelope producer helpers. Closed-taxonomy
345// translators from runtime execution metadata into the wire envelope's
346// epistemic fields (`provenance_chain` + `blame_attribution`).
347pub mod wire_envelope_producers;
348// §Fase 39.f — Rust CLI binary parity. New subcommands that closed
349// the gap vs the Python CLI (`axon parse` aggregator + `axon fmt`
350// round-trip formatter).
351pub mod cli_parse;
352pub mod cli_fmt;
353// §λ-L-E Fase 11.b — Zero-Copy Multimodal Buffers.
354// `buffer` defines ZeroCopyBuffer (Arc<[u8]>-backed) + BufferKind
355// (open registry) + BufferPool (slab allocator with per-tenant
356// soft-limit accounting). `ingest` hosts the network deposit paths
357// (multipart/form-data streaming parser, WebSocket binary-frame
358// accumulator) that populate buffers without intermediate copies.
359pub mod buffer;
360pub mod ingest;
361// §λ-L-E Fase 11.c runtime — `replay_token` hosts ReplayToken canonical
362// hashing + pluggable ReplayLog + ReplayExecutor for re-running from
363// any token. The compile-time `legal_basis` catalog lives in
364// `axon-frontend`.
365pub mod replay_token;
366// §λ-L-E Fase 11.d — Stateful PEM over WebSocket. `pem::state`
367// defines CognitiveState with Q32.32 fixed-point float encoding
368// so density-matrix round-trips are bit-identical across reconnects.
369// `pem::continuity_token` is an HMAC-signed handshake that proves
370// a reconnecting client is the original party. `pem::backend`
371// exposes the PersistenceBackend async trait + in-memory impl;
372// production uses axon_enterprise::cognitive_states (Postgres +
373// envelope encryption).
374pub mod pem;
375// §λ-L-E Fase 11.e — Ontological Tool Synthesis binary pipelines.
376// `ots::pipeline` hosts Transformer trait + TransformerRegistry +
377// Dijkstra-based path search. `ots::native` seeds μ-law ↔ PCM16
378// + resample (8k/16k/48k ladder). `ots::subprocess::ffmpeg` is
379// the subprocess fallback with warm-pool + availability detection.
380// The compile-time slug catalog lives in `axon-frontend::ots_catalog`.
381pub mod ots;
382pub mod tool_executor;
383pub mod tool_registry;
384// §Fase 34.b (v1.29.0) — Tool trait + ToolChunk closed-catalog
385// surface for tools-as-stream-producers. Bridges adopter-source
386// `effects: <stream:<policy>>` declarations into the runtime via
387// the dispatcher's per-chunk wire emission path (Fase 34.d/g lands
388// the wiring; this module is the structural foundation).
389pub mod tool_trait;
390// §Fase 34.d (v1.29.0) — Bridge from ToolEntry (registry shape) to
391// Tool trait impls (dispatcher's streaming surface). The dispatcher's
392// `pure_shape::run_step` calls `tool_dispatch_bridge::resolve_streaming_tool`
393// for is_streaming-flagged tools + drains the resulting Stream<ToolChunk>
394// chunk-by-chunk into the wire.
395pub mod tool_dispatch_bridge;
396// §Fase 84.d — Remote Hands runtime: pure argv render + confirmation-hash
397// binding + output bounding + the axon⇄agent wire protocol.
398pub mod technician_dispatch;
399// §Fase 85.d — result-memoization cache core: content-addressed keys,
400// in-process LRU tier with single-flight + TTL jitter + size bound, the
401// `CacheBackend` trait (enterprise injects Redis), and policy resolution.
402pub mod cache_runtime;
403// §Fase 86 — the mathematical core of `forge` Directed Creative Synthesis:
404// Boden profiles, NCD novelty (the computable Kolmogorov-novelty proxy),
405// best-of-N selection, and fail-closed verification.
406pub mod forge;
407// §Fase 87.e — the `HolographBackend` port + the OSS reference HRR codec
408// (circular-convolution binding via a self-contained radix-2 FFT), the
409// `savant` long-horizon memory-compression layer (paper §5).
410pub mod holograph;
411// §Fase 87.f — the remaining `savant` runtime ports + OSS reference impls:
412// `inference` (classical VFE/EFE active inference, no advantage claim),
413// `topology` (Vietoris–Rips β₀/β₁ + PHC-proxy centrality), and `synth`
414// (deny-by-default dynamic tool synthesis — the Extism executor is enterprise).
415pub mod inference;
416pub mod synth;
417pub mod topology;
418// §Fase 88.d — the `WardenBackend` port + the OSS reference static analyzer
419// (attested `Vulnerability` findings; authorization + deny-by-default enforced;
420// paraconsistent finding-validator). The enterprise LLM engine mounts §88.f.
421pub mod warden;
422pub mod tool_validator;
423pub mod trace_export;
424pub mod trace_store;
425pub mod trace_stats;
426pub mod tracer;
427pub mod version_diff;
428pub mod webhook_delivery;
429pub mod webhooks;
430/// §Fase 92.c — the `CredentialMinter` port behind the `mint` flow verb
431/// (attenuated, TTL-bounded ephemeral credentials; fail-closed when absent).
432pub mod credential_minter;
433/// §Fase 94.d — the `SecretCustody` port behind the `backend: secrets`
434/// metadata store, the `rotate` verb and the `tool { secret: }` injection
435/// (`rotation_without_revelation`; fail-closed when absent).
436pub mod secret_custody;
437/// §Fase 91.b — declared cognitive time: the runtime half of `now:` (one
438/// capture per run, deterministic prompt line, envelope record).
439pub mod temporal_context;
440/// §Fase 71.b — the runtime for the `window` temporal execution guard
441/// (timezone-aware `is_in_window` / `next_window_open` via chrono-tz).
442pub mod window;