Skip to main content

axon_frontend/
ast.rs

1//! AXON AST node definitions — direct port of axon/compiler/ast_nodes.py.
2//!
3//! Tier 1 constructs have fully typed structs.
4//! Tier 2+ constructs use `GenericDeclaration` (structural fallback).
5
6#![allow(dead_code)]
7
8use crate::tokens::Trivia;
9
10// ── Location helper ──────────────────────────────────────────────────────────
11
12/// Source location shared by all AST nodes.
13#[derive(Debug, Clone, Default)]
14pub struct Loc {
15    pub line: u32,
16    pub column: u32,
17}
18
19// ── Trivia channel (v1.5.2 — Lossless lexing) ─────────────────────────────
20//
21// The Python AST attaches `leading_trivia` / `trailing_trivia` directly
22// to each ASTNode (97+ subclasses inherit empty defaults). The Rust
23// structs do not have inheritance, so adding two `Vec<Trivia>` fields
24// to every node would require touching each of the 97 structs and
25// every fixture test that constructs them — high mechanical churn for
26// a use case (LSP / formatter / doc gen) that can be served just as
27// well by indexing trivia by declaration position.
28//
29// `DeclarationTrivia` is a side-channel attached to `Program`. The
30// parser populates it in lockstep with `declarations` so consumer code
31// can do `program.declaration_trivia[i]` to get the leading/trailing
32// trivia of `program.declarations[i]`. This preserves the AST shape
33// (no breaking changes), keeps `IRProgram` JSON byte-identical with
34// the Python reference (trivia is never serialised), and ships the
35// adopter-reported feature end-to-end.
36//
37// If a future sub-phase wants per-node trivia inside the AST itself
38// (mirror of the Python ASTNode shape), this side-channel is the seed:
39// every `DeclarationTrivia` already carries the data; spreading it
40// into the structs is a mechanical refactor at that point.
41
42/// Comments attached to a single top-level declaration. Indexed
43/// in parallel with `Program.declarations`.
44#[derive(Debug, Clone, Default)]
45pub struct DeclarationTrivia {
46    /// Comment trivia that appeared before the declaration's first
47    /// token (since the previous declaration or file start).
48    pub leading: Vec<Trivia>,
49    /// Comment trivia on the same line as the declaration's last
50    /// effective token, before the next newline.
51    pub trailing: Vec<Trivia>,
52}
53
54// ── Top-level ────────────────────────────────────────────────────────────────
55
56#[derive(Debug)]
57pub struct Program {
58    pub declarations: Vec<Declaration>,
59    /// v1.5.2 — comment trivia attached per declaration (parallel
60    /// with `declarations`). Empty by default; populated by the parser
61    /// when source carries comments. Defaults preserve every existing
62    /// `Program { declarations, loc }` constructor — `..Default::default()`
63    /// on a `Program` literal fills in the new field.
64    pub declaration_trivia: Vec<DeclarationTrivia>,
65    pub loc: Loc,
66}
67
68/// A single top-level declaration in an AXON program.
69#[derive(Debug)]
70pub enum Declaration {
71    Import(ImportNode),
72    Persona(PersonaDefinition),
73    Context(ContextDefinition),
74    Anchor(AnchorConstraint),
75    Memory(MemoryDefinition),
76    Tool(ToolDefinition),
77    Type(TypeDefinition),
78    Flow(FlowDefinition),
79    /// v2.87.0 — `effect E { Op(p: T) -> R }`. A peer of `tool`, per
80    /// `the design plan` section 3.1.
81    Effect(EffectDefinition),
82    Intent(IntentNode),
83    Run(RunStatement),
84    Epistemic(EpistemicBlock),
85    Let(LetStatement),
86    /// Lambda Data (ΛD) — Epistemic State Vector definition.
87    LambdaData(LambdaDataDefinition),
88    // ── Tier 2 declarations (full AST) ──
89    Agent(AgentDefinition),
90    Shield(ShieldDefinition),
91    /// v2.27.0 — a temporal execution-window guard.
92    Window(WindowDefinition),
93    /// v2.69.0 — a TOP-LEVEL `budget <Name> { … }`. Governs every flow that
94    /// calls the tools its quotas name — not just a daemon's.
95    Budget(BudgetBlock),
96    Pix(PixDefinition),
97    Ledger(LedgerDefinition),
98    Psyche(PsycheDefinition),
99    Corpus(CorpusDefinition),
100    Dataspace(DataspaceDefinition),
101    Ots(OtsDefinition),
102    Mandate(MandateDefinition),
103    Compute(ComputeDefinition),
104    Daemon(DaemonDefinition),
105    AxonStore(AxonStoreDefinition),
106    AxonEndpoint(AxonEndpointDefinition),
107    /// v2.5.0 — Closed-catalog extension mechanism. Declares
108    /// adopter-specific PROVENANCE members for a closed catalog
109    /// (`effects` bases or shield `scan` categories) so the
110    /// type-checker + PCC treat them as first-class. Auditable +
111    /// gateable; never extends the enforceable effect set (invariant
112    /// #2 — provenance-class only).
113    Extension(ExtensionDefinition),
114    /// v1.1.0 — I/O cognitivo primitives.
115    Resource(ResourceDefinition),
116    Fabric(FabricDefinition),
117    Manifest(ManifestDefinition),
118    Observe(ObserveDefinition),
119    /// v1.1.0 — Control cognitivo primitives.
120    Reconcile(ReconcileDefinition),
121    Lease(LeaseDefinition),
122    Ensemble(EnsembleDefinition),
123    /// v1.1.0 — Topology + π-calculus binary sessions.
124    Session(SessionDefinition),
125    Topology(TopologyDefinition),
126    /// v1.1.0 — Cognitive immune system (per docs/paper_immune_v2.md).
127    Immune(ImmuneDefinition),
128    Reflex(ReflexDefinition),
129    Heal(HealDefinition),
130    /// v1.3.1 — UI cognitiva declarativa.
131    Component(ComponentDefinition),
132    View(ViewDefinition),
133    /// v1.6.0 — Mobile typed channels (paper_mobile_channels.md).
134    Channel(ChannelDefinition),
135    /// v2.3.0 — typed WebSocket transport binding a `session` protocol
136    /// (paper_websocket_cognitive_primitive.md).
137    Socket(SocketDefinition),
138    /// v2.37.0 — the dual transport role of `socket`: a persistent,
139    /// config-resolved OUTBOUND connection to a third-party vendor, typed by
140    /// the same v2.3.0 session algebra on the axon-facing side and transcoded
141    /// to the vendor's wire frames by a declared total projection
142    /// (the design plan).
143    Upstream(UpstreamDefinition),
144    /// v2.37.0 — the voice-agent simplicity layer: macro-expands
145    /// (inspectable via `axon desugar`, the design decision) to `ots` + carrier
146    /// `session`/`socket` + `upstream` legs. The declaration stays in the
147    /// AST for provenance + v2.37.0 validation (T852); the IR carries only
148    /// the expansion — sugar the compliance reviewer can always see through.
149    Voice(VoiceDefinition),
150    /// v2.38.0 — a named, referenced browser-origin policy (mirrors
151    /// `shield`'s shape exactly), resolved per `axonendpoint.cors:`
152    /// reference (the design plan).
153    Cors(CorsDefinition),
154    /// v2.40.0 — a named, referenced result-memoization policy (mirrors
155    /// `cors`'s shape), resolved per `tool.cache:` / `retrieve.cache:`
156    /// (the design plan).
157    Cache(CacheDefinition),
158    /// v2.42.0 — the long-horizon autonomous research primitive: a governed
159    /// ORCHESTRATOR (not a monolith) that composes existing primitives
160    /// (`memory`/`corpus`, `par`, `quant`, `forge`, `daemon`, the v2.28.0 budget,
161    /// the v2.36.0 interruptible session, the v2.34.0 signed egress) into a
162    /// budget-bounded, interruptible, fail-closed, provenance-witnessed
163    /// research loop. Enterprise-exclusive at scale (charter split R1); the
164    /// keyword + type discipline + ports live in OSS
165    /// (the design plan).
166    Savant(SavantDefinition),
167    /// v2.42.0 — a dynamic tool-synthesis policy: the closed set of
168    /// conditions (risk ceiling, source language, mandatory WASM zero-trust
169    /// sandbox, Coder/Reviewer consensus) under which a `savant` may
170    /// synthesise + execute a tool at runtime. The paper's "OTS = Ontological
171    /// Tool Synthesis" grounded to a real keyword (`ots` already means
172    /// one-shot media transform — paper section 9.1). OSS declares + statically
173    /// disciplines the policy and ships a DENY-BY-DEFAULT reference; the real
174    /// Extism/WASM executor is enterprise (v2.42.0).
175    Synth(SynthDefinition),
176    /// v2.43.0 — an authorization scope: the signed envelope (`targets`
177    /// allowlist + `depth` ceiling + `approver`) a `warden` adversarial-analysis
178    /// block MUST run `within`. The load-bearing safety construct that makes
179    /// warden a governed auditor, not a weapon: no in-scope authorization ⇒ no
180    /// analysis (fail-closed). Referenced by `warden(t) within <Scope>`
181    /// (the design plan).
182    Scope(ScopeDefinition),
183    /// v2.46.0 — a named ephemeral-credential contract: TTL-bounded,
184    /// capability-attenuated bearer minting (`authority_only_attenuates` —
185    /// grants ⊆ the minter's own capabilities at mint, TTL ≤ the closed
186    /// ceiling). Declared once (the `cors`/`scope` shape), referenced by the
187    /// `mint <Credential> as <binding>` flow verb
188    /// (the design plan).
189    Credential(CredentialDefinition),
190    /// v2.4.0 — a Pauli-sum observable `M = Σ cₖ Pₖ` that a `quant`
191    /// block measures against (paper section 3.2; plan D5).
192    Observable(ObservableDefinition),
193    /// v2.23.0 — an Advantage Witness: a machine-checkable proof obligation
194    /// that a primitive's `claim` beats a cheaper `baseline` by a `metric` above
195    /// a `threshold` on real `data` (doctrine `axon://logic/no_unwitnessed_advantage`).
196    Witness(WitnessDefinition),
197    /// v2.53.0 — Native Document Synthesis: a declarative, compile-time-
198    /// validated DOCX/PPTX/XLSX structure that is the point where a value LEAVES
199    /// the epistemic lattice and becomes a human artifact. `target:` selects a
200    /// serializer, not a capability (the design decision — identical effect rows). The
201    /// assertion-laundering barrier refuses a value below `believe` in
202    /// an assertive slot without an `attribute:` or a shield
203    /// (the design plan).
204    Document(DocumentDefinition),
205    /// v2.60.0 — Governed CRM Delivery: a declarative, compile-time-validated
206    /// egress of assertions into a system of record (a CRM). The dual of
207    /// acquisition (`scrape`, v2.52.0): where `document` leaves the lattice into a
208    /// human artifact, `deliver` leaves it into a machine system others treat as
209    /// fact. The provenance-stripping barrier (the design decision, axon-T920) refuses a
210    /// `provenance: cleared` delivery of an unshielded flow value — a guess must
211    /// arrive labeled as a guess (the design plan).
212    Deliver(DeliverDefinition),
213    /// v2.66.0 — governed human notification.
214    Notify(NotifyDefinition),
215    /// Tier 3+ declarations parsed structurally (balanced braces, no detailed AST).
216    Generic(GenericDeclaration),
217}
218
219/// v2.76.0 — the named surface of a declaration: `(name, kind, loc)`,
220/// or `None` for the statement-like declarations that do not bind a
221/// referenceable top-level name (`import` / `run` / `let` / the epistemic
222/// block wrapper, whose body registers recursively).
223///
224/// # Parity contract
225///
226/// The `kind` strings here MUST match the kinds the type-checker's
227/// `register_declarations` assigns (that is what `TypeChecker::lookup`
228/// compares against when a `run` / reference names the symbol). The match
229/// below is deliberately **exhaustive — no wildcard arm** — so adding a
230/// `Declaration` variant without deciding its export surface is a compile
231/// error, not a silent gap in the module system.
232pub fn declaration_surface(decl: &Declaration) -> Option<(String, String, Loc)> {
233    match decl {
234        Declaration::Import(_)
235        | Declaration::Run(_)
236        | Declaration::Let(_)
237        | Declaration::Epistemic(_) => None,
238        Declaration::Persona(n) => Some((n.name.clone(), "persona".into(), n.loc.clone())),
239        Declaration::Context(n) => Some((n.name.clone(), "context".into(), n.loc.clone())),
240        Declaration::Anchor(n) => Some((n.name.clone(), "anchor".into(), n.loc.clone())),
241        Declaration::Memory(n) => Some((n.name.clone(), "memory".into(), n.loc.clone())),
242        Declaration::Tool(n) => Some((n.name.clone(), "tool".into(), n.loc.clone())),
243        Declaration::Type(n) => Some((n.name.clone(), "type".into(), n.loc.clone())),
244        Declaration::Flow(n) => Some((n.name.clone(), "flow".into(), n.loc.clone())),
245        // v2.87.0 — an `effect` IS exportable. A module that declares one and
246        // a flow in another module that handles it is the compositional case
247        // the whole paradigm rests on; hiding it from the module surface would
248        // make an effect usable only in the file that declares it.
249        Declaration::Effect(n) => Some((n.name.clone(), "effect".into(), n.loc.clone())),
250        Declaration::Intent(n) => Some((n.name.clone(), "intent".into(), n.loc.clone())),
251        Declaration::LambdaData(n) => Some((n.name.clone(), "lambda_data".into(), n.loc.clone())),
252        Declaration::Agent(n) => Some((n.name.clone(), "agent".into(), n.loc.clone())),
253        Declaration::Shield(n) => Some((n.name.clone(), "shield".into(), n.loc.clone())),
254        Declaration::Window(n) => Some((n.name.clone(), "window".into(), n.loc.clone())),
255        Declaration::Budget(n) => Some((n.name.clone(), "budget".into(), n.loc.clone())),
256        Declaration::Pix(n) => Some((n.name.clone(), "pix".into(), n.loc.clone())),
257        Declaration::Ledger(n) => Some((n.name.clone(), "ledger".into(), n.loc.clone())),
258        Declaration::Psyche(n) => Some((n.name.clone(), "psyche".into(), n.loc.clone())),
259        Declaration::Corpus(n) => Some((n.name.clone(), "corpus".into(), n.loc.clone())),
260        Declaration::Dataspace(n) => Some((n.name.clone(), "dataspace".into(), n.loc.clone())),
261        Declaration::Ots(n) => Some((n.name.clone(), "ots".into(), n.loc.clone())),
262        Declaration::Mandate(n) => Some((n.name.clone(), "mandate".into(), n.loc.clone())),
263        Declaration::Compute(n) => Some((n.name.clone(), "compute".into(), n.loc.clone())),
264        Declaration::Daemon(n) => Some((n.name.clone(), "daemon".into(), n.loc.clone())),
265        Declaration::AxonStore(n) => Some((n.name.clone(), "axonstore".into(), n.loc.clone())),
266        Declaration::AxonEndpoint(n) => {
267            Some((n.name.clone(), "axonendpoint".into(), n.loc.clone()))
268        }
269        Declaration::Extension(n) => Some((n.name.clone(), "extension".into(), n.loc.clone())),
270        Declaration::Resource(n) => Some((n.name.clone(), "resource".into(), n.loc.clone())),
271        Declaration::Fabric(n) => Some((n.name.clone(), "fabric".into(), n.loc.clone())),
272        Declaration::Manifest(n) => Some((n.name.clone(), "manifest".into(), n.loc.clone())),
273        Declaration::Observe(n) => Some((n.name.clone(), "observe".into(), n.loc.clone())),
274        Declaration::Reconcile(n) => Some((n.name.clone(), "reconcile".into(), n.loc.clone())),
275        Declaration::Lease(n) => Some((n.name.clone(), "lease".into(), n.loc.clone())),
276        Declaration::Ensemble(n) => Some((n.name.clone(), "ensemble".into(), n.loc.clone())),
277        Declaration::Session(n) => Some((n.name.clone(), "session".into(), n.loc.clone())),
278        Declaration::Topology(n) => Some((n.name.clone(), "topology".into(), n.loc.clone())),
279        Declaration::Immune(n) => Some((n.name.clone(), "immune".into(), n.loc.clone())),
280        Declaration::Reflex(n) => Some((n.name.clone(), "reflex".into(), n.loc.clone())),
281        Declaration::Heal(n) => Some((n.name.clone(), "heal".into(), n.loc.clone())),
282        Declaration::Component(n) => Some((n.name.clone(), "component".into(), n.loc.clone())),
283        Declaration::View(n) => Some((n.name.clone(), "view".into(), n.loc.clone())),
284        Declaration::Channel(n) => Some((n.name.clone(), "channel".into(), n.loc.clone())),
285        Declaration::Socket(n) => Some((n.name.clone(), "socket".into(), n.loc.clone())),
286        Declaration::Upstream(n) => Some((n.name.clone(), "upstream".into(), n.loc.clone())),
287        Declaration::Voice(n) => Some((n.name.clone(), "voice".into(), n.loc.clone())),
288        Declaration::Cors(n) => Some((n.name.clone(), "cors".into(), n.loc.clone())),
289        Declaration::Cache(n) => Some((n.name.clone(), "cache".into(), n.loc.clone())),
290        Declaration::Savant(n) => Some((n.name.clone(), "savant".into(), n.loc.clone())),
291        Declaration::Synth(n) => Some((n.name.clone(), "synth".into(), n.loc.clone())),
292        Declaration::Scope(n) => Some((n.name.clone(), "scope".into(), n.loc.clone())),
293        Declaration::Credential(n) => Some((n.name.clone(), "credential".into(), n.loc.clone())),
294        Declaration::Observable(n) => Some((n.name.clone(), "observable".into(), n.loc.clone())),
295        Declaration::Witness(n) => Some((n.name.clone(), "witness".into(), n.loc.clone())),
296        Declaration::Document(n) => Some((n.name.clone(), "document".into(), n.loc.clone())),
297        Declaration::Deliver(n) => Some((n.name.clone(), "deliver".into(), n.loc.clone())),
298        Declaration::Notify(n) => Some((n.name.clone(), "notify".into(), n.loc.clone())),
299        Declaration::Generic(n) => {
300            if n.name.is_empty() {
301                None
302            } else {
303                Some((n.name.clone(), n.keyword.clone(), n.loc.clone()))
304            }
305        }
306    }
307}
308
309// ── v2.53.0 — Native Document Synthesis ─────────────────────────────────────
310
311/// v2.53.0 — a declarative document. `target:` picks the serializer
312/// (docx|pptx|xlsx); `provenance:` picks how the provenance part is emitted
313/// (none|embedded|signed); `template:` names an enterprise template; `effects:`
314/// carries the propagated `sensitive:`/`legal:` basis. `blocks` is the body —
315/// a closed-catalog tree of [`DocBlock`]s whose vocabulary the checker validates
316/// against `target` (a `slide` in a `docx` is `axon-T9xx`, the design decision).
317#[derive(Debug, Default)]
318pub struct DocumentDefinition {
319    pub name: String,
320    /// `docx | pptx | xlsx` — closed catalog (axon-T910).
321    pub target: String,
322    /// Optional enterprise template reference (`.dotx/.potx/.xltx`, v2.53.0).
323    pub template: String,
324    /// `none | embedded | signed` — how the provenance part is emitted
325    ///. Empty ⇒ `none`. Closed catalog (axon-T911).
326    pub provenance: String,
327    /// The propagated effect row — `io`, `storage` (blob sink), and any
328    /// `sensitive:<cat>`/`legal:<basis>` the bound data carries.
329    pub effects: Option<EffectRow>,
330    /// The document body — the closed-catalog block tree.
331    pub blocks: Vec<DocBlock>,
332    pub loc: Loc,
333    pub leading_trivia: Vec<crate::tokens::Trivia>,
334    pub trailing_trivia: Vec<crate::tokens::Trivia>,
335}
336
337/// v2.53.0 — one block in a document body. A generic-but-closed node: `kind`
338/// is validated against the `target`'s vocabulary, `fields` against the kind's
339/// allowed set, and `children` are nested blocks (a `section` holds `para`s; a
340/// `slide` holds `bullets`; a `sheet` holds `row`s). Keeping the node generic
341/// (rather than one struct per block kind) keeps the grammar/IR small while the
342/// checker (`check_document`) enforces the same closed-catalog discipline.
343#[derive(Debug, Default)]
344pub struct DocBlock {
345    /// `section|heading|para|table|chart|image|toc|page_break|footnote|slide|
346    /// placeholder|bullets|notes|sheet|row|formula|range|format` — validated
347    /// per `target` at check time.
348    pub kind: String,
349    /// Scalar/list fields (`text:`, `columns:`, `range:`, `attribute:`, …).
350    pub fields: Vec<(String, DocScalar)>,
351    /// Nested child blocks.
352    pub children: Vec<DocBlock>,
353    pub loc: Loc,
354}
355
356impl DocBlock {
357    /// Look up a scalar field by name.
358    pub fn field(&self, name: &str) -> Option<&DocScalar> {
359        self.fields.iter().find(|(k, _)| k == name).map(|(_, v)| v)
360    }
361    /// Whether a field is present.
362    pub fn has_field(&self, name: &str) -> bool {
363        self.fields.iter().any(|(k, _)| k == name)
364    }
365}
366
367/// v2.53.0 — a document field value. A `Ref` is a binding to a flow value
368/// (the epistemic-egress barrier reads its level); a `Text` is a literal; a
369/// `List` is a bracketed set; `Int` is a scalar count.
370#[derive(Debug, Clone, PartialEq)]
371pub enum DocScalar {
372    /// A quoted string literal (`"Q3 Results"`, `"B2:B9"`).
373    Text(String),
374    /// A bare identifier — a reference to a flow value / declared name. THIS is
375    /// what the assertion-laundering barrier inspects at an assertive slot.
376    Ref(String),
377    /// A bracketed list of strings/identifiers (`["Region","Revenue"]`).
378    List(Vec<String>),
379    /// An integer scalar.
380    Int(i64),
381    /// A boolean scalar.
382    Bool(bool),
383}
384
385impl DocScalar {
386    /// The referenced name, if this value is a `Ref`.
387    pub fn as_ref_name(&self) -> Option<&str> {
388        match self {
389            DocScalar::Ref(s) => Some(s.as_str()),
390            _ => None,
391        }
392    }
393    /// The literal text, if this value is `Text`.
394    pub fn as_text(&self) -> Option<&str> {
395        match self {
396            DocScalar::Text(s) => Some(s.as_str()),
397            _ => None,
398        }
399    }
400}
401
402// ── v2.60.0 — Governed CRM Delivery ────────────────────────────────────────
403
404/// v2.60.0 — a declarative CRM delivery. `target:` picks the destination class
405/// (`crm`, closed catalog — axon-T921); `provenance:` picks how the epistemic
406/// origin of each delivered field is treated at the boundary (`attached` default
407/// | `cleared` — axon-T922); `secret:` names the per-tenant credential key
408/// (v2.48.0 custody, required — axon-T923); `effects:` carries the propagated row
409/// (must include `web` — axon-T924). `ops` is the body — a non-empty list of
410/// [`DeliverOp`]s whose `kind` the checker validates against a closed operation
411/// catalog (axon-T925). Field values reuse [`DocScalar`]: a `Ref` is a binding to
412/// a flow value (what the T920 barrier inspects), the rest are literals.
413#[derive(Debug, Default)]
414
415pub struct DeliverDefinition {
416    pub name: String,
417    /// `crm` — closed catalog (axon-T921).
418    pub target: String,
419    /// `attached | cleared` — how field provenance crosses the boundary
420    ///. Empty ⇒ `attached` (the safe default: provenance travels).
421    /// Closed catalog (axon-T922).
422    pub provenance: String,
423    /// The per-tenant credential key resolved via v2.48.0 custody at dispatch — the
424    /// value never enters cognition. Required (axon-T923).
425    pub secret: String,
426    /// The propagated effect row — must include `web` (a CRM write crosses the
427    /// trust boundary over the network, axon-T924).
428    pub effects: Option<EffectRow>,
429    /// The delivery body — the closed-catalog operation list.
430    pub ops: Vec<DeliverOp>,
431    pub loc: Loc,
432    pub leading_trivia: Vec<crate::tokens::Trivia>,
433    pub trailing_trivia: Vec<crate::tokens::Trivia>,
434}
435
436/// v2.66.0 — Governed Human Notification: the third egress dual
437/// (`deliver` = systems of record, `document` = artifacts, `notify` =
438/// human attention). Three laws: T933 (the evidence barrier — a guess
439/// reaches a human labeled as a guess, or is refused), T934 (structure:
440/// closed channel catalog; the recipient is a v2.48.0 secret-class ref,
441/// NEVER a literal — PII never rides source or IR), T935 (attention:
442/// a `window:` is mandatory — unbounded interruption is refused).
443#[derive(Debug, Default)]
444pub struct NotifyDefinition {
445    pub name: String,
446    /// `sms | whatsapp | telegram` — closed catalog (axon-T934).
447    pub channel: String,
448    /// The v2.48.0 secret-class ref the recipient resolves from AT DISPATCH
449    /// (`to: secret(ops.oncall_phone)`). The literal number/chat-id never
450    /// appears anywhere axon stores or reasons over.
451    pub to_secret: String,
452    /// True iff `to:` was written in the `secret(...)` form. A literal
453    /// recipient is an axon-T934 refusal (with a teaching message).
454    pub to_is_secret: bool,
455    /// The message template; `${ref}` slots bind flow values post-run.
456    pub template: String,
457    /// v2.27.0-style duration (`30m`, `4h`, `1d`) — at-most-once-per-window
458    /// per recipient (axon-T935; enforced durably by the ENT ledger).
459    pub window: String,
460    /// `attached | cleared` — how epistemic labels cross to the human
461    ///. Empty ⇒ `attached` (the safe default).
462    pub provenance: String,
463    /// Must include `web` (a notification crosses the trust boundary).
464    pub effects: Option<EffectRow>,
465    pub loc: Loc,
466    pub leading_trivia: Vec<crate::tokens::Trivia>,
467    pub trailing_trivia: Vec<crate::tokens::Trivia>,
468}
469
470/// v2.60.0 — one CRM operation in a delivery body. `kind ∈ {upsert_contact,
471/// create_deal, add_note}` (validated per-target, axon-T925). Each operation
472/// binds a set of `(field, value)` pairs; a `Ref` field carries a flow value
473/// into the CRM and is the T920 barrier's subject. Every operation requires a
474/// `key:` field — the idempotency key (the design decision, axon-T926) so an at-least-once
475/// retry never double-creates a record.
476#[derive(Debug, Default)]
477pub struct DeliverOp {
478    /// `upsert_contact | create_deal | add_note` — validated at check time.
479    pub kind: String,
480    /// Scalar/ref fields (`key:`, `email:`, `firstname:`, `amount:`, …).
481    pub fields: Vec<(String, DocScalar)>,
482    pub loc: Loc,
483}
484
485impl DeliverOp {
486    /// Look up a scalar field by name.
487    pub fn field(&self, name: &str) -> Option<&DocScalar> {
488        self.fields.iter().find(|(k, _)| k == name).map(|(_, v)| v)
489    }
490    /// Whether a field is present.
491    pub fn has_field(&self, name: &str) -> bool {
492        self.fields.iter().any(|(k, _)| k == name)
493    }
494    /// The flow-value references this operation binds (the barrier's subjects).
495    pub fn ref_fields(&self) -> impl Iterator<Item = (&str, &str)> {
496        self.fields.iter().filter_map(|(k, v)| match v {
497            DocScalar::Ref(name) => Some((k.as_str(), name.as_str())),
498            _ => None,
499        })
500    }
501}
502
503// ── v1.1.0 — Resource primitive ───────────────────────────────────────
504
505/// `resource Name { kind, endpoint, capacity, lifetime, certainty_floor, shield }`
506///
507/// An infrastructure resource declared as a linear, affine, or persistent
508/// token. Linear/affine resources cannot be aliased across manifests
509/// (Separation Logic `*` disjointness).
510#[derive(Debug, Default)]
511pub struct ResourceDefinition {
512    pub name: String,
513    /// v2.67.0 — a CLOSED catalog (`VALID_RESOURCE_KINDS`). Until v2.67.0 this
514    /// was a free string that **nothing validated**: `check_resource` never
515    /// read it, and no catalog const existed anywhere in the workspace.
516    pub kind: String,
517    /// v2.67.0 — the DSN, as a **per-tenant config key** (`axon-T944`).
518    ///
519    /// A production DB URI in source is exactly what `axon-T850` already
520    /// forbids one declaration over (*"URLs and credentials never appear in
521    /// source"*) and what v2.48.0 custody exists to refuse. `resource` was a
522    /// grandfathered violation of the language's own law.
523    pub endpoint: String,
524    /// v2.67.0 — **the pool size**, and the proof this cycle is a wire and not
525    /// a label. Before v2.67.0 every axonstore pool was hardcoded at 10.
526    pub capacity: Option<i64>,
527    /// v2.67.0 — **how many holders may name this resource** (Linear Logic):
528    /// `linear` = exactly one · `affine` = at most one (sharing is a breach) ·
529    /// `persistent` = the `!` exponential, freely shared. Default: `affine`.
530    pub lifetime: String,
531    pub certainty_floor: Option<f64>, // epistemic gate c ∈ [0.0, 1.0]
532    pub shield_ref: String,           // optional shield reference
533    /// v2.67.0 — the `fabric` this resource lives in. **One field ⇒
534    /// Separation-Logic disjointness is unrepresentable, not verified.**
535    pub within: String,
536    pub loc: Loc,
537    /// v1.5.2 — leading comment trivia attached to this declaration
538    /// (comments preceding the declaration's first token, since the
539    /// previous declaration or file start). Empty by default.
540    pub leading_trivia: Vec<crate::tokens::Trivia>,
541    /// v1.5.2 — trailing comment trivia (same line as the
542    /// declaration's last effective token). Empty by default.
543    pub trailing_trivia: Vec<crate::tokens::Trivia>,
544}
545
546/// `fabric Name { provider, region, zones, ephemeral, shield }`
547///
548/// A tagged substrate — the topological container where resources are
549/// provisioned. Maps to VPC / cluster / namespace.
550#[derive(Debug, Default)]
551pub struct FabricDefinition {
552    pub name: String,
553    pub provider: String, // aws | gcp | azure | kubernetes | bare_metal | custom
554    pub region: String,   // provider-specific region id
555    pub zones: Option<i64>, // number of availability zones
556    pub ephemeral: Option<bool>, // true = destroy on program end
557    pub shield_ref: String, // optional shield reference
558    pub loc: Loc,
559    /// v1.5.2 — leading comment trivia attached to this declaration
560    /// (comments preceding the declaration's first token, since the
561    /// previous declaration or file start). Empty by default.
562    pub leading_trivia: Vec<crate::tokens::Trivia>,
563    /// v1.5.2 — trailing comment trivia (same line as the
564    /// declaration's last effective token). Empty by default.
565    pub trailing_trivia: Vec<crate::tokens::Trivia>,
566}
567
568/// `manifest Name { resources, fabric, region, zones, compliance }`
569///
570/// A declarative specification of desired shape — not a "desired state" in
571/// the Terraform sense, a *belief* about structure. Linear/affine resources
572/// in `resources` must be disjoint (Separation Logic `*`).
573#[derive(Debug, Default)]
574pub struct ManifestDefinition {
575    pub name: String,
576    pub resources: Vec<String>, // references to ResourceDefinition names
577    pub fabric_ref: String,     // reference to FabricDefinition name
578    pub region: String,
579    pub zones: Option<i64>,
580    pub compliance: Vec<String>, // κ — regulatory class (v1.2.0)
581    pub loc: Loc,
582    /// v1.5.2 — leading comment trivia attached to this declaration
583    /// (comments preceding the declaration's first token, since the
584    /// previous declaration or file start). Empty by default.
585    pub leading_trivia: Vec<crate::tokens::Trivia>,
586    /// v1.5.2 — trailing comment trivia (same line as the
587    /// declaration's last effective token). Empty by default.
588    pub trailing_trivia: Vec<crate::tokens::Trivia>,
589}
590
591/// `observe Name from Manifest { sources, quorum, timeout, on_partition, certainty_floor }`
592///
593/// A quorum-gated observation of a manifest's real state. Each output
594/// carries ΛD envelope E = ⟨c, τ, ρ, δ⟩; `τ` records observation lag.
595/// `on_partition: fail` raises a CT-3 (Network Error) — partitions are ⊥ void.
596#[derive(Debug, Default)]
597pub struct ObserveDefinition {
598    pub name: String,
599    pub target: String, // name of ManifestDefinition being observed
600    pub sources: Vec<String>,
601    pub quorum: Option<i64>,  // Byzantine quorum threshold
602    pub timeout: String,      // duration literal "5s", "100ms"
603    pub on_partition: String, // fail (CT-3) | shield_quarantine
604    pub certainty_floor: Option<f64>,
605    pub loc: Loc,
606    /// v1.5.2 — leading comment trivia attached to this declaration
607    /// (comments preceding the declaration's first token, since the
608    /// previous declaration or file start). Empty by default.
609    pub leading_trivia: Vec<crate::tokens::Trivia>,
610    /// v1.5.2 — trailing comment trivia (same line as the
611    /// declaration's last effective token). Empty by default.
612    pub trailing_trivia: Vec<crate::tokens::Trivia>,
613}
614
615// ── v1.1.0 — Control cognitivo primitives ─────────────────────────────
616
617/// `reconcile Name { observe, threshold, tolerance, on_drift, shield, mandate, max_retries }`
618///
619/// A cognitive control loop that minimises variational free energy
620/// `F = D_KL(q(s) || p(s, o))` between a manifest belief and an observe
621/// evidence. Acting on the environment (`on_drift: provision`) is one of
622/// the two classical routes to reducing F (the other is belief revision).
623#[derive(Debug, Default)]
624pub struct ReconcileDefinition {
625    pub name: String,
626    pub observe_ref: String,
627    pub threshold: Option<f64>, // epistemic gate c ∈ [0.0, 1.0]
628    pub tolerance: Option<f64>, // drift tolerance [0.0, 1.0]
629    pub on_drift: String,       // provision | alert | refine (default: provision)
630    pub shield_ref: String,
631    pub mandate_ref: String,
632    pub max_retries: i64, // default: 3
633    pub loc: Loc,
634    /// v1.5.2 — leading comment trivia attached to this declaration
635    /// (comments preceding the declaration's first token, since the
636    /// previous declaration or file start). Empty by default.
637    pub leading_trivia: Vec<crate::tokens::Trivia>,
638    /// v1.5.2 — trailing comment trivia (same line as the
639    /// declaration's last effective token). Empty by default.
640    pub trailing_trivia: Vec<crate::tokens::Trivia>,
641}
642
643/// `lease Name { resource, duration, acquire, on_expire }`
644///
645/// Affine/linear lease on a resource, with explicit Δt encoded in the `τ`
646/// of the ΛD envelope. Runtime materializes each lease as a revocable
647/// token; use post-expiry raises `LeaseExpiredError` (CT-2) per D2.
648#[derive(Debug, Default)]
649pub struct LeaseDefinition {
650    pub name: String,
651    pub resource_ref: String,
652    pub duration: String,  // "30s", "5m", "2h"
653    pub acquire: String,   // on_start | on_demand (default: on_start)
654    pub on_expire: String, // anchor_breach | release | extend (default: anchor_breach)
655    pub loc: Loc,
656    /// v1.5.2 — leading comment trivia attached to this declaration
657    /// (comments preceding the declaration's first token, since the
658    /// previous declaration or file start). Empty by default.
659    pub leading_trivia: Vec<crate::tokens::Trivia>,
660    /// v1.5.2 — trailing comment trivia (same line as the
661    /// declaration's last effective token). Empty by default.
662    pub trailing_trivia: Vec<crate::tokens::Trivia>,
663}
664
665/// `ensemble Name { observations, quorum, aggregation, certainty_mode }`
666///
667/// Byzantine quorum aggregator over ≥2 independent observations. Yields
668/// common knowledge `Cφ` (Fagin-Halpern) when at least `quorum` observers
669/// agree. Failed observations are excluded; below quorum raises CT-3.
670#[derive(Debug, Default)]
671pub struct EnsembleDefinition {
672    pub name: String,
673    pub observations: Vec<String>,
674    pub quorum: Option<i64>,
675    pub aggregation: String, // majority | weighted | byzantine (default: majority)
676    pub certainty_mode: String, // min | weighted | harmonic (default: min)
677    pub loc: Loc,
678    /// v1.5.2 — leading comment trivia attached to this declaration
679    /// (comments preceding the declaration's first token, since the
680    /// previous declaration or file start). Empty by default.
681    pub leading_trivia: Vec<crate::tokens::Trivia>,
682    /// v1.5.2 — trailing comment trivia (same line as the
683    /// declaration's last effective token). Empty by default.
684    pub trailing_trivia: Vec<crate::tokens::Trivia>,
685}
686
687// ── v1.1.0 — Topology + π-calculus binary sessions ──────────────────
688
689/// One step in a session protocol.
690///
691/// v1.1.0: `send T` | `receive T` | `loop` | `end`. v2.3.0 adds **choice**:
692/// `select { ℓ: [..], … }` (⊕ — this role chooses) and `branch { ℓ: [..], … }`
693/// (& — this role offers); for those `op`s the labelled continuations live in
694/// [`SessionStep::branches`] (a nested sub-protocol per label).
695#[derive(Debug, Clone, Default)]
696pub struct SessionStep {
697    pub op: String,           // send | receive | loop | end | select | branch | interrupt
698    pub message_type: String, // send/receive: payload type · interrupt: the `on <Signal>` cause
699    /// v2.3.0 — populated only for `op == "select" | "branch"`: the labelled
700    /// branches, each a nested step sequence (its own sub-protocol).
701    ///
702    /// v2.36.0 — reused for `op == "interrupt"`: exactly two labelled arms,
703    /// `body` (the interruptible region) and `handler` (runs on the signal). The
704    /// handler may end in a `resume` step (back to `body`) or reach `end` (the
705    /// abandon exit) — see the paper section 3.5 two-exit construct.
706    pub branches: Vec<SessionBranch>,
707    /// v2.36.0 — `op == "interrupt"` only: the handler's signal binder from
708    /// `... as <sig> ...`. Empty for every other op. The handler references the
709    /// received `CallInterruptCause` value under this name.
710    pub binder: String,
711    /// v2.36.0 — `op == "interrupt"` only: `true` when the block declares a
712    /// `resumable { … }` handler (the v1 surface always does). Default `false`
713    /// keeps every non-interrupt step byte-identical in the IR (skip-if-false).
714    pub resumable: bool,
715    pub loc: Loc,
716}
717
718/// v2.3.0 — one labelled arm of a `select`/`branch` choice: `ℓ: [steps]`.
719#[derive(Debug, Clone, Default)]
720pub struct SessionBranch {
721    pub label: String,
722    pub steps: Vec<SessionStep>,
723    pub loc: Loc,
724}
725
726/// One role in a binary session — name + ordered list of steps.
727#[derive(Debug, Default)]
728pub struct SessionRole {
729    pub name: String,
730    pub steps: Vec<SessionStep>,
731    pub loc: Loc,
732}
733
734/// `session Name { role1: [step, …]  role2: [step, …] }`
735///
736/// A binary session type — exactly two roles whose protocols MUST be
737/// pairwise Honda-Vasconcelos dual. Duality is verified by the type
738/// checker; non-dual programs are rejected at compile time.
739#[derive(Debug, Default)]
740pub struct SessionDefinition {
741    pub name: String,
742    pub roles: Vec<SessionRole>,
743    pub loc: Loc,
744    /// v1.5.2 — leading comment trivia attached to this declaration
745    /// (comments preceding the declaration's first token, since the
746    /// previous declaration or file start). Empty by default.
747    pub leading_trivia: Vec<crate::tokens::Trivia>,
748    /// v1.5.2 — trailing comment trivia (same line as the
749    /// declaration's last effective token). Empty by default.
750    pub trailing_trivia: Vec<crate::tokens::Trivia>,
751}
752
753/// `socket Name { protocol: SessionRef, backpressure: credit(n), reconnect:
754/// cognitive_state, legal_basis: ... }`
755///
756/// v2.3.0 — the typed WebSocket transport (paper_websocket_cognitive_primitive.md).
757/// `socket` is NOT the protocol — the protocol is a `session` it references by
758/// name (protocol and transport kept separate but composable). The type checker
759/// resolves `protocol` to a declared `session` (whose two roles are already
760/// duality-checked via the v2.3.0 algebra), so the dialogue carried over the WS
761/// connection is conformant + deadlock-free by construction.
762#[derive(Debug, Default)]
763pub struct SocketDefinition {
764    pub name: String,
765    /// The referenced `session` declaration's name — the protocol.
766    pub protocol: String,
767    /// The credit window of the typed-resource backpressure (`credit(n)`);
768    /// `None` if unspecified. A `0` credit is rejected by the type checker.
769    pub backpressure_credit: Option<i64>,
770    /// `reconnect: cognitive_state` → `true` (resume mid-dialogue via a sealed
771    /// v2.0.0 snapshot); absent or `reconnect: none` → `false`.
772    pub reconnect: bool,
773    /// Optional `legal_basis:` annotation (enterprise audit/shield gate).
774    pub legal_basis: Option<String>,
775    pub loc: Loc,
776    /// v1.5.2 — leading comment trivia.
777    pub leading_trivia: Vec<crate::tokens::Trivia>,
778    /// v1.5.2 — trailing comment trivia.
779    pub trailing_trivia: Vec<crate::tokens::Trivia>,
780}
781
782/// `upstream Name { transport:, protocol:, role:, resolve:, secret:, auth:,
783/// map: [...], reconnect: {...}, overflow:, backpressure: credit(n) }`
784///
785/// v2.37.0 — the client dual of `socket`: axon dials OUT to a third-party
786/// vendor (STT/TTS/realtime speech APIs). The axon-facing interface is a
787/// declared `session` (referenced by `protocol:`, same field meaning as
788/// `socket`) of which axon plays `role:`; the vendor side is realised by the
789/// `map:` projection rules — a compile-time-total transcoding contract
790/// (v2.37.0, axon-T849). `resolve:`/`secret:` name per-tenant config keys,
791/// never URL/credential literals (axon-T850) — the same "config, not code"
792/// property v2.8.0 gave `tool`, extended to persistent duplex streams.
793#[derive(Debug, Default)]
794pub struct UpstreamDefinition {
795    pub name: String,
796    /// Wire transport axon dials. Closed catalog; v1 sole member `websocket`.
797    pub transport: String,
798    /// The referenced `session` declaration's name — the axon-facing protocol.
799    pub protocol: String,
800    /// Which of the session's two roles axon plays; the peer role is the
801    /// vendor's, realised by the `map:` transcoding, never by axon code.
802    pub role: String,
803    /// Per-tenant config key holding the vendor URL (dot-separated,
804    /// `SecretKeyPolicy`-shaped — never a URL literal).
805    pub resolve: String,
806    /// v2.69.0 — the `resource` this upstream's channel runs on
807    /// (`upstream X { resource: Api }`). When present, the upstream DERIVES
808    /// its dial address from `resource.endpoint` (a per-tenant config key,
809    /// axon-T944) and its **max concurrent connection INSTANCES** from
810    /// `resource.capacity` — frames are already governed by
811    /// `backpressure_credit`, so capacity bounds CONNECTIONS, never frames
812    /// (making it frames would state one fact twice). Mutually exclusive
813    /// with `resolve:` (axon-T951): `resource:` beside a `resolve:` would
814    /// declare the channel's address twice — the v2.67.0 islands defect.
815    /// Authority attenuation: the resource encapsulates its own address
816    /// resolution; the upstream only names WHICH channel it rides.
817    pub resource_ref: String,
818    /// Per-tenant secret binding for the vendor credential (same charset).
819    pub secret: String,
820    /// Auth handshake kind: `header` | `query` | `signed_url`.
821    pub auth_kind: String,
822    /// Header/query-param name (`header("Authorization")` / `query("token")`).
823    pub auth_name: Option<String>,
824    /// Optional header value prefix (`header("Authorization", "Token ")`).
825    pub auth_prefix: Option<String>,
826    /// The wire↔session transcoding contract; totality checked at v2.37.0.
827    pub map: Vec<UpstreamMapRule>,
828    /// `reconnect: { backoff_ms:, max_attempts:, on_exhausted: }`.
829    pub reconnect: Option<UpstreamReconnect>,
830    /// Outbound-queue policy when the VENDOR is the slow side — a member of
831    /// the existing `BackpressurePolicy` catalog. `None` ⇒ `fail` (honest
832    /// default: no silently-lossy audio unless the adopter opts in).
833    pub overflow: Option<String>,
834    /// Axon-facing credit window, identical semantics to `socket`.
835    pub backpressure_credit: Option<i64>,
836    /// v2.37.0 — set when declared via `upstream X from Preset@vN {…}`;
837    /// carries the `Preset@vN` reference the desugar pass expanded.
838    pub preset: Option<String>,
839    pub loc: Loc,
840    /// v1.5.2 — leading comment trivia.
841    pub leading_trivia: Vec<crate::tokens::Trivia>,
842    /// v1.5.2 — trailing comment trivia.
843    pub trailing_trivia: Vec<crate::tokens::Trivia>,
844}
845
846/// One `map:` projection rule: `send M as json [tag "X"]` /
847/// `send M as binary` / `receive M as json [when "f" [= "v"]]` /
848/// `receive M as binary`. Inbound `json` payloads land as v2.26.0 `Json` (total
849/// navigation); the session message name is the routing + duality skeleton.
850#[derive(Debug, Default)]
851pub struct UpstreamMapRule {
852    /// `send` (axon → vendor) or `receive` (vendor → axon).
853    pub direction: String,
854    /// The session message type this rule transcodes.
855    pub message: String,
856    /// `json` or `binary` (raw passthrough).
857    pub framing: String,
858    /// send-json only. Absent ⇒ the payload is sent VERBATIM (the vendor's
859    /// exact wire shape, e.g. ElevenLabs `{"text": …}`); present ⇒ the tag
860    /// is injected as `"type": "<tag>"` into the payload object (the
861    /// Deepgram/OpenAI-Realtime envelope family).
862    pub tag: Option<String>,
863    /// receive-json only: discriminator field. Absent ⇒ the default
864    /// equality discriminator `"type" = "<MessageName>"`.
865    pub when_field: Option<String>,
866    /// receive-json only. `Some(v)` ⇒ equality match on `when_field`;
867    /// `None` with `when_field` present ⇒ field-PRESENCE match (vendors
868    /// like Gemini Live mark frame kinds by which key exists). Equality
869    /// rules dispatch before presence rules.
870    pub when_value: Option<String>,
871    pub loc: Loc,
872}
873
874/// `voice Name { stt:/tts: XOR realtime:, carrier:, interruptible:,
875/// legal_basis:, persona:, context: }`
876///
877/// v2.37.0 — the simplicity layer over v2.37.0's `upstream`: a blessed-
878/// preset phone agent in under 20 lines. `stt:`+`tts:` (cascaded) XOR
879/// `realtime:` (fused) — the design decision: one grammar, both architectures, never a
880/// special-cased second path. Each leg is a `Preset@vN` reference or a
881/// declared `upstream` name. Expansion is pure macro-lowering to existing
882/// primitives; `axon desugar` prints it.
883#[derive(Debug, Default)]
884pub struct VoiceDefinition {
885    pub name: String,
886    /// Cascaded STT leg (preset ref like `DeepgramSTT@v1` or upstream name).
887    pub stt: Option<String>,
888    /// Cascaded TTS leg.
889    pub tts: Option<String>,
890    /// Fused speech-to-speech leg (mutually exclusive with stt/tts — T852).
891    pub realtime: Option<String>,
892    /// Carrier codec: `mulaw8k` (default — PSTN; expansion emits the ots
893    /// μ-law↔PCM16 pair) or `pcm16` (browser/WebRTC-style, no transcode).
894    pub carrier: String,
895    /// `true` ⇒ the carrier session is a v2.36.0 interruptible region (barge-in
896    /// capable) and the socket parks residuals — which REQUIRES
897    /// `legal_basis:` (T852; the sugar must not generate a program
898    /// `ParkedResidualSoundness` refutes).
899    pub interruptible: bool,
900    /// Rides onto the generated socket (the v2.36.0 data-at-rest obligation).
901    pub legal_basis: Option<String>,
902    /// Optional references wired for the flow layer (validated to exist).
903    pub persona: Option<String>,
904    pub context: Option<String>,
905    pub loc: Loc,
906    /// v1.5.2 — leading comment trivia.
907    pub leading_trivia: Vec<crate::tokens::Trivia>,
908    /// v1.5.2 — trailing comment trivia.
909    pub trailing_trivia: Vec<crate::tokens::Trivia>,
910}
911
912/// `cors Name { allow_origins:, allow_methods:, allow_headers:,
913/// allow_credentials:, max_age:, expose_headers: }`
914///
915/// v2.38.0 — a named, referenced origin-policy declaration, mirroring
916/// `shield`'s shape exactly: declared once, referenced from any number of
917/// `axonendpoint`s via `cors: <Name>` (`AxonEndpointDefinition::cors_ref`).
918/// Makes the browser-facing origin policy a property of the ENDPOINT,
919/// resolved per the tenant's live deployed bundle — the shape a single
920/// process-wide CORS knob (the market-standard pattern) cannot express for
921/// a multi-tenant deploy where different bundles need different origins
922/// for a path with the same name.
923///
924/// **Unknown fields are a hard parse error** — a CORS policy is
925/// security-relevant, so `upstream`/`voice`'s stricter posture is followed
926/// here, not `shield`'s lenient `axon-W010` record-and-skip.
927#[derive(Debug, Default)]
928pub struct CorsDefinition {
929    pub name: String,
930    /// `["https://app.example.com", "https://*.kivi.io"]` — exact origins
931    /// or a single leading-wildcard host-label glob (the design decision/T854); no full
932    /// regex, matching the closed/decidable spirit of the rest of the
933    /// language. `["*"]` (any-origin) is legal UNLESS `allow_credentials`
934    /// is also `true` — that combination is `axon-T853` (the design decision, the CORS
935    /// spec's own rule, caught at compile time instead of a silent browser
936    /// rejection).
937    pub allow_origins: Vec<String>,
938    /// Reuses the closed `axonendpoint` method catalog (GET/POST/PUT/
939    /// PATCH/DELETE) — validated against the same list, not a free string
940    /// (T855).
941    pub allow_methods: Vec<String>,
942    /// Request headers the preflight may allow (e.g. `["Content-Type",
943    /// "Authorization"]`) — free-form header-name strings (hyphens are
944    /// common in real header names, hence string literals, not bare
945    /// identifiers).
946    pub allow_headers: Vec<String>,
947    /// `true` ⇒ `Access-Control-Allow-Credentials: true` is emitted.
948    /// Forbidden together with an any-origin `allow_origins` (T853).
949    pub allow_credentials: bool,
950    /// `Access-Control-Max-Age` — a duration literal (`"3600s"`, `"1h"`),
951    /// same lexer/token convention as `axonendpoint.timeout`. `None` ⇒ the
952    /// header is omitted (browser default caching applies).
953    pub max_age: Option<String>,
954    /// `Access-Control-Expose-Headers` — response headers the browser's
955    /// JS may read beyond the CORS-safelisted set. Free-form strings, same
956    /// rationale as `allow_headers`.
957    pub expose_headers: Vec<String>,
958    pub loc: Loc,
959    /// v1.5.2 — leading comment trivia.
960    pub leading_trivia: Vec<crate::tokens::Trivia>,
961    /// v1.5.2 — trailing comment trivia.
962    pub trailing_trivia: Vec<crate::tokens::Trivia>,
963}
964
965/// v2.46.0 — `credential <Name> { ttl: grants: }`: a named
966/// ephemeral-credential contract. `mint <Name> as <binding>` (v2.46.0) mints
967/// a TTL-bounded bearer carrying exactly `grants` — and the runtime law
968/// (`authority_only_attenuates`) admits the mint only when
969/// `grants ⊆ capabilities(minter)`. An unknown field in a `credential { }`
970/// block is a HARD PARSE ERROR (the v2.38.0 posture — this is security
971/// surface; a typo'd field must not silently produce a permissive
972/// contract).
973#[derive(Debug, Default)]
974pub struct CredentialDefinition {
975    pub name: String,
976    /// The bearer's lifetime — a duration literal (`"15m"`, `"900s"`),
977    /// REQUIRED. Validated by `axon-T894`: parseable, > 0, and ≤ the closed
978    /// 24h ceiling (an "ephemeral" credential that lives for days is a
979    /// service account wearing a costume — v2.46.0 covers that shape).
980    pub ttl: String,
981    /// The capability slugs the minted bearer carries — REQUIRED,
982    /// non-empty (`axon-T893`), each a dotted slug per
983    /// `is_valid_capability_slug` (the `requires:` grammar). Attenuation
984    /// (`⊆ minter`) is the runtime/mint-time half of the law.
985    pub grants: Vec<String>,
986    pub loc: Loc,
987    /// v1.5.2 — leading comment trivia.
988    pub leading_trivia: Vec<crate::tokens::Trivia>,
989    /// v1.5.2 — trailing comment trivia.
990    pub trailing_trivia: Vec<crate::tokens::Trivia>,
991}
992
993/// `cache Name { backend:, ttl:, key:, default:, apply_to_effects:,
994/// invalidate_on: }` — v2.40.0, a named, referenced result-memoization
995/// policy resolved per `tool.cache:` / `retrieve.cache:` (mirrors
996/// `CorsDefinition`'s named-and-referenced shape).
997///
998/// The load-bearing idea: cacheability derives from the type system's
999/// existing `effects: pure` proof — a `pure` tool is safe to cache by
1000/// construction. A `default: true` cache auto-covers every `pure` tool with
1001/// zero per-tool annotation; widening `apply_to_effects:` beyond `[pure]` is
1002/// allowed but the compiler names every non-pure tool it covers (W013) AND
1003/// forces a finite `ttl:` (T865 — you may cache a proven-deterministic result
1004/// forever, never a non-deterministic one).
1005///
1006/// **Unknown fields are a hard parse error** (the v2.38.0 the design decision discipline) — a
1007/// cache governs correctness (serving a stale/foreign result is a real bug), so
1008/// a typo'd field can never silently mean "no policy."
1009#[derive(Debug, Default)]
1010pub struct CacheDefinition {
1011    pub name: String,
1012    /// `redis` (multi-replica, enterprise tier) or `in_process` (the OSS
1013    /// default single-replica tier). Empty ⇒ `in_process`. Validated against a
1014    /// closed catalog at check time.
1015    pub backend: String,
1016    /// Time-to-live as a duration literal (`"10s"`, `"5m"`, `"1h"`), same lexer
1017    /// convention as `cors.max_age`/`tool.timeout`. `None` ⇒ "cache forever" —
1018    /// sound ONLY for a provably-`pure` cache; a non-pure cache with no `ttl:`
1019    /// is `axon-T865`.
1020    pub ttl: Option<String>,
1021    /// `key: [param, ...]` — the SUBSET of the covered tool's `parameters:`
1022    /// whose bound values form the cache key. Empty ⇒ ALL bound parameters
1023    /// (the automatic, zero-friction default). Used when one bound arg — e.g. a
1024    /// `request_id` — must NOT affect the key.
1025    pub key_params: Vec<String>,
1026    /// `default: true` ⇒ this cache auto-covers every eligible tool in the
1027    /// module without a per-tool `cache:` reference. At most one per module
1028    /// (`axon-T863`). Default `false`.
1029    pub default_policy: bool,
1030    /// `apply_to_effects: [pure, ...]` — the effect classes this cache is
1031    /// willing to memoise. Empty ⇒ `[pure]` (the only provably-safe default).
1032    /// Any member beyond `pure` is a WIDENING (W013 names each covered tool)
1033    /// and forces a finite `ttl:` (T865).
1034    pub apply_to_effects: Vec<String>,
1035    /// `invalidate_on: [Channel, ...]` — an `emit` on any listed channel
1036    /// flushes this cache's namespace. Each must resolve to a declared
1037    /// `channel` (`axon-T864`). Reuses the v1.6.0 pub/sub, not a second mechanism.
1038    pub invalidate_on: Vec<String>,
1039    pub loc: Loc,
1040    /// v1.5.2 — leading comment trivia.
1041    pub leading_trivia: Vec<crate::tokens::Trivia>,
1042    /// v1.5.2 — trailing comment trivia.
1043    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1044}
1045
1046/// v2.42.0 — `savant <Name> { domain:, cognition{…}, memory{…}, budget{…},
1047/// mandate <M> {…} … }` — the long-horizon autonomous research primitive.
1048///
1049/// A `savant` is a declarative ORCHESTRATOR, not a new engine: it composes the
1050/// primitives Axon already ships (memory/corpus retention, `par` swarms, the
1051/// `quant` Hilbert substrate, `forge` novelty synthesis, the `daemon` host, the
1052/// v2.28.0 linear budget, the v2.36.0 interruptible session, the v2.34.0 signed egress)
1053/// into a single governed research loop. The paper's vision (papers/
1054/// paper_primitiva_savant.md) grounded to real primitives in its section 9.
1055///
1056/// v2.42.0 parses the FULL block surface; the semantics land incrementally:
1057/// param-catalog + typed-output validation is v2.42.0 (checker), memory-ref
1058/// resolution + v2.28.0 budget binding + v2.36.0 interruptibility is v2.42.0, and the
1059/// `SavantSoundness` PCC proof is v2.42.0. **Unknown fields are a hard parse
1060/// error** (the v2.38.0 the design decision discipline, as `cache`/`cors`): a savant governs an
1061/// expensive, risk-bearing autonomous process, so a typo'd field can never
1062/// silently mean "no policy."
1063#[derive(Debug, Default)]
1064pub struct SavantDefinition {
1065    pub name: String,
1066    /// `domain: "…"` — the ontological scope of the generative boundary (the
1067    /// research topic the free-energy loop minimises surprise over). Required
1068    /// (v2.42.0 `axon-T873`); empty until parsed.
1069    pub domain: String,
1070    /// `cognition { … }` — the epistemic parameters of the active-inference
1071    /// engine (depth / entropic threshold / divergence). `None` ⇒ engine
1072    /// defaults (v2.42.0 supplies a catalog-checked default).
1073    pub cognition: Option<SavantCognition>,
1074    /// `memory { … }` — the retention layer. `backend` resolves to a declared
1075    /// `memory`/`corpus` primitive in v2.42.0 (`axon-T875`); `None` ⇒ ephemeral.
1076    pub memory: Option<SavantMemory>,
1077    /// `budget { … }` — the compute ceiling. Bound to a v2.28.0 linear budget
1078    /// (`RateLease`) in v2.42.0 so `max_iterations` is a TYPE-enforced ceiling,
1079    /// not a hope. `None` ⇒ v2.42.0 rejects (a weeks-long autonomous loop with no
1080    /// budget is uninsurable).
1081    pub budget: Option<SavantBudget>,
1082    /// `mandate <Name> { objective:, output: }` — one or more epistemic
1083    /// mandates the savant autonomously decomposes into tasks. At least one
1084    /// required (v2.42.0 `axon-T874`).
1085    pub mandates: Vec<SavantMandate>,
1086    pub loc: Loc,
1087    /// v1.5.2 — leading comment trivia.
1088    pub leading_trivia: Vec<crate::tokens::Trivia>,
1089    /// v1.5.2 — trailing comment trivia.
1090    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1091}
1092
1093/// v2.42.0 — the `cognition { … }` sub-block of a [`SavantDefinition`]: the
1094/// active-inference engine's epistemic parameters (paper section 3, section 7.1).
1095#[derive(Debug, Default)]
1096pub struct SavantCognition {
1097    /// `depth: standard | deep | hyper` — the HRR dimensionality tier of the
1098    /// holographic memory codec. Closed catalog (v2.42.0 `axon-T876`).
1099    pub depth: String,
1100    /// `entropic_threshold: <float>` — the Expected-Free-Energy convergence
1101    /// bound: the loop halts synthesis when no policy reduces EFE below this.
1102    /// Must be `> 0` (v2.42.0). `None` ⇒ engine default.
1103    pub entropic_threshold: Option<f64>,
1104    /// `divergence: low | med | high` — how aggressively the loop explores
1105    /// epistemic (β₂) voids vs. exploiting known structure. Closed catalog.
1106    pub divergence: String,
1107    pub loc: Loc,
1108}
1109
1110/// v2.42.0 — the `memory { … }` sub-block of a [`SavantDefinition`]: the
1111/// durable retention layer, composed from existing `memory`/`corpus` primitives.
1112#[derive(Debug, Default)]
1113pub struct SavantMemory {
1114    /// `backend: <Name>` — a reference to a declared `memory` or `corpus`
1115    /// primitive (resolved in v2.42.0 `axon-T875`). Empty ⇒ ephemeral memory.
1116    pub backend: String,
1117    /// `corpus_graph: <bool>` — whether to iteratively index the ingested
1118    /// corpus as a simplicial-complex graph for the topological (β_n) reading.
1119    pub corpus_graph: bool,
1120    /// `isolation_level: strict | …` — per-tenant tensor partitioning. The
1121    /// enterprise engine enforces it; OSS records it. Empty ⇒ default.
1122    pub isolation_level: String,
1123    pub loc: Loc,
1124}
1125
1126/// v2.42.0 — the `budget { … }` sub-block of a [`SavantDefinition`]: the
1127/// compute ceiling, bound to a v2.28.0 linear budget in v2.42.0.
1128#[derive(Debug, Default)]
1129pub struct SavantBudget {
1130    /// `max_iterations: <int>` — the hard ceiling on FEP-loop iterations before
1131    /// the savant pauses (the paper's `compute_budget`). `> 0` (v2.42.0).
1132    pub max_iterations: Option<i64>,
1133    /// `max_tool_synth: <int>` — the hard ceiling on `synth` (v2.42.0) dynamic
1134    /// tool-creation events per mandate. `None` ⇒ 0 (no synthesis).
1135    pub max_tool_synth: Option<i64>,
1136    pub loc: Loc,
1137}
1138
1139/// v2.42.0 — a `mandate <Name> { objective:, output: }` sub-block of a
1140/// [`SavantDefinition`]: one epistemic research goal the savant pursues.
1141#[derive(Debug, Default)]
1142pub struct SavantMandate {
1143    pub name: String,
1144    /// `objective: "…"` — the natural-language research goal. Required
1145    /// (non-empty, v2.42.0 `axon-T874`).
1146    pub objective: String,
1147    /// `output: <Type>` — the declared type the final report must inhabit
1148    /// (resolved to a declared `type` in v2.42.0). Required.
1149    pub output_type: String,
1150    pub loc: Loc,
1151}
1152
1153/// v2.42.0 — `synth <Name> { target:, risk:, language:, sandbox:, review:,
1154/// max_lines: }` — a dynamic tool-synthesis policy.
1155///
1156/// A `savant` that hits an epistemic gap it has no tool for can, under such a
1157/// policy, deduce + write a tool (a Coder sub-agent, a Reviewer sub-agent — a
1158/// `par` with an agreement condition), compile it to `wasm32-wasi`, and run it
1159/// in an Extism zero-trust sandbox, feeding stdout back as empirical evidence
1160/// (paper section 6). The policy declares the SAFETY ENVELOPE; the runtime enforces it.
1161///
1162/// **Deny-by-default (D87.d):** OSS parses + statically disciplines this policy
1163/// but ships a `SynthBackend` reference that REFUSES to execute — running
1164/// untrusted synthesised code needs the enterprise Extism/gVisor isolation
1165/// (v2.42.0). The checker therefore requires `sandbox: wasm` (T882): a synth
1166/// policy that would run code outside a sandbox can never compile.
1167///
1168/// **Unknown fields are a hard parse error**: a synth policy governs
1169/// arbitrary-code execution — the highest-stakes surface in the language.
1170#[derive(Debug, Default)]
1171pub struct SynthDefinition {
1172    pub name: String,
1173    /// `target: "…"` — what the synthesised tools are for (the capability scope).
1174    /// Required (v2.42.0 `axon-T879`).
1175    pub target: String,
1176    /// `risk: low | medium | high | critical` — the ceiling risk class the
1177    /// policy admits; governs review + isolation strictness. Required
1178    /// (v2.42.0 `axon-T880`).
1179    pub risk: String,
1180    /// `language: rust | c | python` — the allowed synthesis source language
1181    /// (all compiled to `wasm32-wasi`). Empty ⇒ any admitted language
1182    /// (v2.42.0 `axon-T881` validates when present).
1183    pub language: String,
1184    /// `sandbox: wasm` — the isolation tier. MUST be `wasm` (v2.42.0 `axon-T882`
1185    /// deny-by-default): synthesised code may only run in a zero-trust WASM
1186    /// sandbox. Empty ⇒ error (never a silent "no sandbox").
1187    pub sandbox: String,
1188    /// `review: required | none` — the Coder/Reviewer consensus requirement.
1189    /// Empty ⇒ `required` (the safe default). `none` is FORBIDDEN for
1190    /// `high`/`critical` risk (v2.42.0 `axon-T883`).
1191    pub review: String,
1192    /// `max_lines: <int>` — an optional hard cap on synthesised source length
1193    /// (a smaller attack + review surface). `None` ⇒ engine default.
1194    pub max_lines: Option<i64>,
1195    pub loc: Loc,
1196    /// v1.5.2 — leading comment trivia.
1197    pub leading_trivia: Vec<crate::tokens::Trivia>,
1198    /// v1.5.2 — trailing comment trivia.
1199    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1200}
1201
1202/// `reconnect: { backoff_ms: 500, max_attempts: 5, on_exhausted: fail }` —
1203/// exponential backoff (doubling from `backoff_ms`, jittered at runtime), at
1204/// most `max_attempts` redials; `on_exhausted` is a closed catalog mirroring
1205/// `budget`'s style (v1 sole member `fail` — fail-closed, the flow sees the
1206/// exhaustion; `degrade`/`park` are named deferred scope).
1207#[derive(Debug, Default)]
1208pub struct UpstreamReconnect {
1209    pub backoff_ms: i64,
1210    pub max_attempts: i64,
1211    pub on_exhausted: String,
1212}
1213
1214/// `source -> target : Session` — one directed edge of a topology.
1215///
1216/// Convention: the source plays the FIRST role of the session; the target
1217/// plays the SECOND role. Fixed so assignment is unambiguous.
1218#[derive(Debug, Default)]
1219pub struct TopologyEdge {
1220    pub source: String,
1221    pub target: String,
1222    pub session_ref: String,
1223    pub loc: Loc,
1224}
1225
1226/// `topology Name { nodes: […]  edges: [A -> B : Session, …] }`
1227///
1228/// A typed directed graph over Axon entities. Edges carry session references
1229/// whose duality the type checker enforces; the graph is statically analysed
1230/// for Honda-liveness (deadlock-prone cycles).
1231#[derive(Debug, Default)]
1232pub struct TopologyDefinition {
1233    pub name: String,
1234    pub nodes: Vec<String>,
1235    pub edges: Vec<TopologyEdge>,
1236    pub loc: Loc,
1237    /// v1.5.2 — leading comment trivia attached to this declaration
1238    /// (comments preceding the declaration's first token, since the
1239    /// previous declaration or file start). Empty by default.
1240    pub leading_trivia: Vec<crate::tokens::Trivia>,
1241    /// v1.5.2 — trailing comment trivia (same line as the
1242    /// declaration's last effective token). Empty by default.
1243    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1244}
1245
1246// ── v1.1.0 — Cognitive immune system (per paper_immune_v2.md) ────────
1247
1248/// `immune Name { watch, sensitivity, baseline, window, scope, tau, decay }`
1249///
1250/// A continuous anomaly sensor over a declared observation vector.
1251/// Computes D_KL(q_baseline || p_observed) (paper section 3.2) and emits a
1252/// HealthReport at an epistemic level derived from the KL magnitude.
1253///
1254/// Pure sensor — `immune` takes NO action. Actions belong to `reflex`
1255/// and `heal`, which consume its HealthReport.
1256#[derive(Debug, Default)]
1257pub struct ImmuneDefinition {
1258    pub name: String,
1259    pub watch: Vec<String>,       // observe / ensemble / any declared ref
1260    pub sensitivity: Option<f64>, // [0.0, 1.0]
1261    pub baseline: String,         // "learned" (default) or name of a prior
1262    pub window: i64,              // samples used to estimate baseline (default: 100)
1263    pub scope: String, // tenant | flow | global (MANDATORY, paper section 8.2)
1264    pub tau: String,              // duration half-life
1265    pub decay: String,            // exponential (default) | linear | none
1266    pub loc: Loc,
1267    /// v1.5.2 — leading comment trivia attached to this declaration
1268    /// (comments preceding the declaration's first token, since the
1269    /// previous declaration or file start). Empty by default.
1270    pub leading_trivia: Vec<crate::tokens::Trivia>,
1271    /// v1.5.2 — trailing comment trivia (same line as the
1272    /// declaration's last effective token). Empty by default.
1273    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1274}
1275
1276/// `reflex Name { trigger, on_level, action, scope, sla }`
1277///
1278/// Deterministic, O(1) motor response. Contract invariants (paper section 4.2):
1279/// never invokes an LLM; no long-running I/O; every activation emits a
1280/// signed_trace; idempotent on the same HealthReport.
1281#[derive(Debug, Default)]
1282pub struct ReflexDefinition {
1283    pub name: String,
1284    pub trigger: String,  // immune name (MANDATORY)
1285    pub on_level: String, // know | believe | speculate | doubt (default: doubt)
1286    pub action: String,   // drop | revoke | emit | redact | quarantine | terminate | alert
1287    pub scope: String, // MANDATORY, paper section 8.2
1288    pub sla: String,      // duration budget (e.g. "1ms")
1289    pub loc: Loc,
1290    /// v1.5.2 — leading comment trivia attached to this declaration
1291    /// (comments preceding the declaration's first token, since the
1292    /// previous declaration or file start). Empty by default.
1293    pub leading_trivia: Vec<crate::tokens::Trivia>,
1294    /// v1.5.2 — trailing comment trivia (same line as the
1295    /// declaration's last effective token). Empty by default.
1296    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1297}
1298
1299/// `heal Name { source, on_level, mode, scope, review_sla, shield, max_patches }`
1300///
1301/// Linear-Logic one-shot patch synthesis. Patch type:
1302/// `!Synthesized ⊸ Applied ⊸ Collapsed` (paper section 6) — each transition
1303/// consumes its predecessor, guaranteeing single application + forced collapse.
1304///
1305/// Mode ∈ {audit_only | human_in_loop | adversarial} controls automation
1306/// (paper section 7); `adversarial` REQUIRES a shield gate (paper section 7.3).
1307#[derive(Debug, Default)]
1308pub struct HealDefinition {
1309    pub name: String,
1310    pub source: String,     // immune name (MANDATORY)
1311    pub on_level: String,   // know | believe | speculate | doubt
1312    pub mode: String,       // audit_only | human_in_loop | adversarial
1313    pub scope: String,      // MANDATORY
1314    pub review_sla: String, // duration
1315    pub shield_ref: String, // optional shield gate (required for adversarial)
1316    pub max_patches: i64,   // bounded heal attempts (default: 3)
1317    pub loc: Loc,
1318    /// v1.5.2 — leading comment trivia attached to this declaration
1319    /// (comments preceding the declaration's first token, since the
1320    /// previous declaration or file start). Empty by default.
1321    pub leading_trivia: Vec<crate::tokens::Trivia>,
1322    /// v1.5.2 — trailing comment trivia (same line as the
1323    /// declaration's last effective token). Empty by default.
1324    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1325}
1326
1327// ── v1.3.1 — UI cognitiva (component / view) ─────────────────────────
1328
1329/// `component Name { renders, via_shield, on_interact, render_hint }`.
1330///
1331/// A reusable UI fragment. `renders` is the data type the component
1332/// visualizes; if that type has κ, `via_shield` is mandatory and its
1333/// compliance set MUST cover the type's κ (compile-time enforcement).
1334#[derive(Debug, Default)]
1335pub struct ComponentDefinition {
1336    pub name: String,
1337    pub renders: String,
1338    pub via_shield: String,
1339    pub on_interact: String,
1340    pub render_hint: String, // card | list | form | chart | custom
1341    pub loc: Loc,
1342    /// v1.5.2 — leading comment trivia attached to this declaration
1343    /// (comments preceding the declaration's first token, since the
1344    /// previous declaration or file start). Empty by default.
1345    pub leading_trivia: Vec<crate::tokens::Trivia>,
1346    /// v1.5.2 — trailing comment trivia (same line as the
1347    /// declaration's last effective token). Empty by default.
1348    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1349}
1350
1351/// `view Name { title, components: [...], route }`.
1352///
1353/// A top-level screen. `components` is an ordered list of declared
1354/// `component` names composed in the view's primary layout.
1355#[derive(Debug, Default)]
1356pub struct ViewDefinition {
1357    pub name: String,
1358    pub title: String,
1359    pub components: Vec<String>,
1360    pub route: String,
1361    pub loc: Loc,
1362    /// v1.5.2 — leading comment trivia attached to this declaration
1363    /// (comments preceding the declaration's first token, since the
1364    /// previous declaration or file start). Empty by default.
1365    pub leading_trivia: Vec<crate::tokens::Trivia>,
1366    /// v1.5.2 — trailing comment trivia (same line as the
1367    /// declaration's last effective token). Empty by default.
1368    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1369}
1370
1371// ── Tier 2+ structural fallback ──────────────────────────────────────────────
1372
1373/// A declaration we recognize by keyword but parse only structurally.
1374/// Validates brace balance and captures keyword + name.
1375#[derive(Debug)]
1376pub struct GenericDeclaration {
1377    pub keyword: String,
1378    pub name: String,
1379    pub loc: Loc,
1380    /// v1.5.2 — leading comment trivia attached to this declaration
1381    /// (comments preceding the declaration's first token, since the
1382    /// previous declaration or file start). Empty by default.
1383    pub leading_trivia: Vec<crate::tokens::Trivia>,
1384    /// v1.5.2 — trailing comment trivia (same line as the
1385    /// declaration's last effective token). Empty by default.
1386    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1387}
1388
1389// ── Agent ────────────────────────────────────────────────────────────────────
1390
1391#[derive(Debug)]
1392pub struct AgentDefinition {
1393    pub name: String,
1394    pub goal: String,
1395    pub tools: Vec<String>,
1396    pub memory_ref: String,
1397    pub strategy: String, // react | reflexion | plan_and_execute | custom
1398    pub on_stuck: String, // forge | hibernate | escalate | retry
1399    pub shield_ref: String,
1400    pub max_iterations: Option<i64>,
1401    pub max_tokens: Option<i64>,
1402    pub max_time: String,
1403    pub max_cost: Option<f64>,
1404    /// The declared result type of the agent — `return: T` inside the block,
1405    /// or the `-> T` position after the name. Empty when undeclared. Checked
1406    /// against the declared types (axon-T1219) and against the `output:` of
1407    /// the step that calls the agent.
1408    pub return_type: String,
1409    /// The `step … { … }` sequence written inside the agent block — the control
1410    /// policy of `strategy: custom`. Empty for every other strategy (a body
1411    /// under `react`/`reflexion`/`plan_and_execute` is axon-T1217). Until 4.1.0
1412    /// the parser discarded these blocks and `custom` was refused at dispatch.
1413    pub body: Vec<StepNode>,
1414    pub loc: Loc,
1415    /// v1.5.2 — leading comment trivia attached to this declaration
1416    /// (comments preceding the declaration's first token, since the
1417    /// previous declaration or file start). Empty by default.
1418    pub leading_trivia: Vec<crate::tokens::Trivia>,
1419    /// v1.5.2 — trailing comment trivia (same line as the
1420    /// declaration's last effective token). Empty by default.
1421    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1422}
1423
1424// ── v2.5.0 — Closed-catalog extension mechanism ────────────────────────────
1425
1426/// One member of an `extension` declaration. For `category: effects`
1427/// the `name` is a provenance base (e.g. `"epistemic:believe"`) with
1428/// optional `semantics` + `default_confidence` (a CEILING, never a
1429/// floor — v2.5.0 tainted-overriding). For `category: scan` the `name`
1430/// is a scan-category identifier and the metadata is typically absent.
1431#[derive(Debug, Clone)]
1432pub struct ExtensionMember {
1433    pub name: String,
1434    pub semantics: Option<String>,
1435    pub default_confidence: Option<f64>,
1436    pub loc: Loc,
1437}
1438
1439/// `extension Name { category: effects|scan, members: [ "x" : { … }, … ] }`
1440///
1441/// v2.5.0. A first-class, auditable + gateable declaration that
1442/// expands a closed catalog with adopter-specific PROVENANCE members.
1443/// Soundness invariants (validated in v2.5.0/v2.5.0): members are
1444/// provenance-class only (never the enforceable effect set), must not
1445/// shadow a canonical base/category, and ride in the IR + proof bundle
1446/// so an independent PCC verifier re-derives against the same artifact.
1447#[derive(Debug)]
1448pub struct ExtensionDefinition {
1449    pub name: String,
1450    /// `effects` | `scan` — validated against the closed category set
1451    /// in v2.5.0 (the type-checker), not the parser.
1452    pub category: String,
1453    pub members: Vec<ExtensionMember>,
1454    pub loc: Loc,
1455    /// v1.5.2 — leading comment trivia. Empty by default.
1456    pub leading_trivia: Vec<crate::tokens::Trivia>,
1457    /// v1.5.2 — trailing comment trivia. Empty by default.
1458    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1459}
1460
1461// ── Shield ───────────────────────────────────────────────────────────────────
1462
1463/// v2.27.0 — a temporal execution-window guard. Where `shield` guards the
1464/// CONTENT of an emission and `anchor` guards its TRUTH, `window` guards its
1465/// TIMING: whether a scheduled (cron) tick runs, by timezone-aware day/hour
1466/// windows. The runtime decision (`is_in_window`) lands in v2.27.0; the daemon
1467/// binding + the defer ledger in v2.27.0.
1468#[derive(Debug)]
1469pub struct WindowDefinition {
1470    pub name: String,
1471    /// IANA timezone (`"America/Bogota"`). Format-checked at compile time
1472    /// (v2.27.0); full IANA membership validated by the runtime (v2.27.0, chrono-tz).
1473    pub timezone: String,
1474    /// The allowed day/hour spans (at least one). A tick inside ANY span runs.
1475    pub allow: Vec<WindowSpan>,
1476    /// v2.27.0 — excluded dates (holidays): ISO `YYYY-MM-DD` date-string
1477    /// literals (`exclude: [ "2026-12-25", "2026-01-01" ]`). A tick whose local
1478    /// date (in `timezone`) is in this set is OUTSIDE the window regardless of the
1479    /// hour spans. The dates are LITERAL — part of the verified program, so the
1480    /// decision stays a pure, replayable function of `(now, the window, the tz-db
1481    /// version)` (the `time_is_an_explicit_input` doctrine). Empty ⇒ no holidays.
1482    pub exclude: Vec<String>,
1483    /// What to do when a tick falls OUTSIDE every allowed span:
1484    /// `skip` | `defer` | `warn` (closed catalog).
1485    pub on_outside: String,
1486    pub loc: Loc,
1487    pub leading_trivia: Vec<crate::tokens::Trivia>,
1488    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1489}
1490
1491/// v2.27.0 — one allowed day/hour span, `{ days: Mon..Fri, hours: 9..18 }`.
1492/// `days` are inclusive weekday-name bounds; `hours` are inclusive 0–23 bounds.
1493#[derive(Debug)]
1494pub struct WindowSpan {
1495    pub day_start: String,
1496    pub day_end: String,
1497    pub hour_start: i64,
1498    pub hour_end: i64,
1499    pub loc: Loc,
1500}
1501
1502#[derive(Debug)]
1503pub struct ShieldDefinition {
1504    pub name: String,
1505    pub scan: Vec<String>,
1506    pub strategy: String, // pattern | classifier | dual_llm | canary | perplexity | ensemble
1507    pub on_breach: String, // halt | sanitize_and_retry | escalate | quarantine | deflect
1508    pub severity: String, // low | medium | high | critical
1509    pub quarantine: String,
1510    pub max_retries: Option<i64>,
1511    pub confidence_threshold: Option<f64>,
1512    pub allow_tools: Vec<String>,
1513    pub deny_tools: Vec<String>,
1514    pub sandbox: Option<bool>,
1515    pub redact: Vec<String>,
1516    pub log: String,
1517    pub deflect_message: String,
1518    pub taint: String,
1519    /// ESK — regulatory coverage (HIPAA, PCI_DSS, GDPR, …).
1520    pub compliance: Vec<String>,
1521    /// v2.34.0 — egress signing algorithm (closed catalog: `hmac_sha256`,
1522    /// `axon-T846`). Empty = the shield does not sign. A shield with `sign:`
1523    /// is an EGRESS shield: `publish <Channel> within <Shield>` marks the
1524    /// channel for signed external delivery (v2.34.0).
1525    pub sign: String,
1526    /// v2.34.0 (`axon-W010`) — block fields the parser did not recognize,
1527    /// with their source locations. Pre-77 the parser silently discarded
1528    /// these (`_ => skip_value()`), so a typo or an unsupported field passed
1529    /// `axon check` unremarked (Kivi brief #51 B.3). The parser still skips
1530    /// the VALUE (leniency preserved — existing programs keep compiling) but
1531    /// records the NAME so the type checker can warn honestly.
1532    pub unknown_fields: Vec<(String, Loc)>,
1533    pub loc: Loc,
1534    /// v1.5.2 — leading comment trivia attached to this declaration
1535    /// (comments preceding the declaration's first token, since the
1536    /// previous declaration or file start). Empty by default.
1537    pub leading_trivia: Vec<crate::tokens::Trivia>,
1538    /// v1.5.2 — trailing comment trivia (same line as the
1539    /// declaration's last effective token). Empty by default.
1540    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1541}
1542
1543// ── Pix ──────────────────────────────────────────────────────────────────────
1544
1545#[derive(Debug)]
1546pub struct PixDefinition {
1547    pub name: String,
1548    pub source: String,
1549    pub depth: Option<i64>,
1550    pub branching: Option<i64>,
1551    pub model: String,
1552    pub loc: Loc,
1553    /// v1.5.2 — leading comment trivia attached to this declaration
1554    /// (comments preceding the declaration's first token, since the
1555    /// previous declaration or file start). Empty by default.
1556    pub leading_trivia: Vec<crate::tokens::Trivia>,
1557    /// v1.5.2 — trailing comment trivia (same line as the
1558    /// declaration's last effective token). Empty by default.
1559    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1560}
1561
1562// ── Ledger ─────────────────────────────────────────────────────────────────
1563// v2.12.0 — the append-only, hash-linked audit chain. Took over the
1564// Provenance-Index role that `pix` historically (and only in the ℰMCP doc)
1565// occupied, so `pix` is freed for its true meaning: the PIX retrieval
1566// navigator (paper `paper_pix_formal_research.md`). A `ledger` binds a chain
1567// recorder to an audited surface (`axonstore://X`, `flow://X`, …); `depth`
1568// is chain retention, `branching` the Merkle factor, `model` the hash slug.
1569
1570#[derive(Debug)]
1571pub struct LedgerDefinition {
1572    pub name: String,
1573    pub source: String,
1574    pub depth: Option<i64>,
1575    pub branching: Option<i64>,
1576    pub model: String,
1577    pub loc: Loc,
1578    pub leading_trivia: Vec<crate::tokens::Trivia>,
1579    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1580}
1581
1582// ── Psyche ───────────────────────────────────────────────────────────────────
1583
1584#[derive(Debug)]
1585pub struct PsycheDefinition {
1586    pub name: String,
1587    pub dimensions: Vec<String>,
1588    pub manifold_noise: Option<f64>,
1589    pub manifold_momentum: Option<f64>,
1590    pub safety_constraints: Vec<String>,
1591    pub quantum_enabled: Option<bool>,
1592    pub inference_mode: String, // active | passive
1593    pub loc: Loc,
1594    /// v1.5.2 — leading comment trivia attached to this declaration
1595    /// (comments preceding the declaration's first token, since the
1596    /// previous declaration or file start). Empty by default.
1597    pub leading_trivia: Vec<crate::tokens::Trivia>,
1598    /// v1.5.2 — trailing comment trivia (same line as the
1599    /// declaration's last effective token). Empty by default.
1600    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1601}
1602
1603// ── Corpus ───────────────────────────────────────────────────────────────────
1604
1605/// v2.13.0 — a typed, weighted edge of an MDN corpus graph: `etype(from, to,
1606/// weight)`. `etype` is from the closed relation catalog (cite / elaborate /
1607/// corroborate / depend / implement / exemplify / contradict / supersede);
1608/// `from`/`to` name documents declared in the corpus; `weight ∈ (0, 1]`.
1609#[derive(Debug, Clone)]
1610pub struct CorpusRelation {
1611    pub etype: String,
1612    pub from: String,
1613    pub to: String,
1614    pub weight: f64,
1615    pub loc: Loc,
1616}
1617
1618#[derive(Debug)]
1619pub struct CorpusDefinition {
1620    pub name: String,
1621    pub documents: Vec<String>, // simplified: list of pix refs
1622    /// v2.13.0 — the typed weighted edges that make this corpus an MDN graph
1623    /// `C = (D, R, τ, ω, σ)`. Empty ⇒ the flat (edgeless) corpus.
1624    pub relations: Vec<CorpusRelation>,
1625    /// v2.13.0 — `adaptive: true` enables the memory endofunctor: navigations
1626    /// over this corpus learn (semantic edge reinforcement + procedural bias),
1627    /// and subsequent navigations use the memory-modified EPR. Requires the
1628    /// graph to carry edges (static `relations:` OR a store-sourced edge store).
1629    pub adaptive: bool,
1630    pub mcp_server: String,
1631    pub mcp_resource_uri: String,
1632    /// v2.14.0 — when `Some`, this is a DYNAMIC store-sourced MDN graph
1633    /// (`corpus N from axonstore { documents: DocStore(id, title)  relations:
1634    /// EdgeStore(from, to, etype, weight) }`): the documents and typed edges live
1635    /// as ROWS in two declared `axonstore`s and the graph is built from the live
1636    /// rows at navigate-time (per-tenant, growing). Mutually exclusive with the
1637    /// static v2.13.0 form — the `documents`/`relations`/`mcp_*` fields stay empty.
1638    /// `None` ⇒ the static compile-time corpus (back-compat byte-identical).
1639    pub store_source: Option<CorpusStoreSource>,
1640    pub loc: Loc,
1641    /// v1.5.2 — leading comment trivia attached to this declaration
1642    /// (comments preceding the declaration's first token, since the
1643    /// previous declaration or file start). Empty by default.
1644    pub leading_trivia: Vec<crate::tokens::Trivia>,
1645    /// v1.5.2 — trailing comment trivia (same line as the
1646    /// declaration's last effective token). Empty by default.
1647    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1648}
1649
1650/// v2.14.0 — the dynamic, `axonstore`-sourced backing of an MDN corpus graph.
1651/// The graph's documents and typed edges are ROWS in two declared `axonstore`s,
1652/// so the graph grows at runtime (a new `persist` = a new node/edge) and is
1653/// per-tenant by inheritance from the store's v2.0.0 column-proof / RLS scope. The
1654/// runtime builds the `mdn::Corpus` from the live rows at navigate-time.
1655///
1656/// Surface:
1657/// ```text
1658/// corpus LtmGraph from axonstore {
1659///     documents: LtmSummaries( id, summary )                 // (id-col, title-col)
1660///     relations: LtmEdges( from_id, to_id, etype, weight )   // (from, to, etype, weight)
1661///     adaptive: true
1662/// }
1663/// ```
1664/// Documents and edges live in SEPARATE stores (an `axonstore` is one table with
1665/// one column schema). The type-checker (`check_corpus`) validates that both
1666/// stores are declared and — when they carry a v1.31.0 column schema — that the
1667/// mapped columns exist with compatible types (id present; title text-like;
1668/// from/to match the id type; etype text-like; weight numeric). The weight-range
1669/// invariant `ω ∈ (0, 1]` (G4) becomes a RUNTIME check here, since weights are
1670/// per-row dynamic (clamp on read + store CHECK), not a compile-time literal.
1671#[derive(Debug, Clone)]
1672pub struct CorpusStoreSource {
1673    pub doc_store: String,
1674    pub doc_id_col: String,
1675    pub doc_title_col: String,
1676    pub edge_store: String,
1677    pub edge_from_col: String,
1678    pub edge_to_col: String,
1679    pub edge_type_col: String,
1680    pub edge_weight_col: String,
1681    pub loc: Loc,
1682}
1683
1684// ── Dataspace ────────────────────────────────────────────────────────────────
1685
1686/// v2.63.0 — the closed dataspace column-type catalog.
1687///
1688/// Six types, because a dataspace column type maps 1:1 to a physical
1689/// columnar buffer layout in the deterministic engine (v2.63.0, plan section 5.1):
1690///
1691/// | Type        | Physical layout                                    |
1692/// |-------------|----------------------------------------------------|
1693/// | `Text`      | offsets `O ∈ ℤ₊^{N+1}` + raw UTF-8 byte buffer     |
1694/// | `Int`       | contiguous `i64` buffer (8 bytes/element)          |
1695/// | `Float`     | contiguous `f64` buffer (8 bytes/element)          |
1696/// | `Bool`      | bit-packed buffer                                  |
1697/// | `Timestamp` | contiguous `i64` epoch-microseconds buffer         |
1698/// | `Json`      | offsets + raw serialized-JSON byte buffer          |
1699///
1700/// Deliberately NOT `StoreColumnType` (v1.31.0): that catalog is
1701/// SQL-backend-oriented (Uuid, Numeric, Bytea, …); this one is the
1702/// engine's physical truth. `Float` is **f64** — diverging from the
1703/// research paper's Float32 on purpose: axon's determinism norm is
1704/// exact f64 (the v2.4.0 reference-simulator precedent), and halving
1705/// width is a performance claim we do not make pre-Sandbox.
1706/// Every column is nullable via the validity bitmap; nullability is
1707/// the ONLY flexibility.
1708#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1709pub enum DataspaceColumnType {
1710    Text,
1711    Int,
1712    Float,
1713    Bool,
1714    Timestamp,
1715    Json,
1716}
1717
1718impl DataspaceColumnType {
1719    /// The closed catalog in canonical declaration order.
1720    pub fn all() -> [DataspaceColumnType; 6] {
1721        [
1722            DataspaceColumnType::Text,
1723            DataspaceColumnType::Int,
1724            DataspaceColumnType::Float,
1725            DataspaceColumnType::Bool,
1726            DataspaceColumnType::Timestamp,
1727            DataspaceColumnType::Json,
1728        ]
1729    }
1730
1731    pub fn canonical_name(self) -> &'static str {
1732        match self {
1733            DataspaceColumnType::Text => "Text",
1734            DataspaceColumnType::Int => "Int",
1735            DataspaceColumnType::Float => "Float",
1736            DataspaceColumnType::Bool => "Bool",
1737            DataspaceColumnType::Timestamp => "Timestamp",
1738            DataspaceColumnType::Json => "Json",
1739        }
1740    }
1741
1742    pub fn all_canonical_names() -> Vec<&'static str> {
1743        Self::all().iter().map(|t| t.canonical_name()).collect()
1744    }
1745
1746    /// Resolve a declared type token — canonical names plus the common
1747    /// lowercase aliases (the v1.31.0 `from_token` convention).
1748    pub fn from_token(name: &str) -> Option<DataspaceColumnType> {
1749        match name {
1750            "Text" | "text" | "string" | "String" => Some(DataspaceColumnType::Text),
1751            "Int" | "int" | "integer" | "i64" => Some(DataspaceColumnType::Int),
1752            "Float" | "float" | "double" | "f64" => Some(DataspaceColumnType::Float),
1753            "Bool" | "bool" | "boolean" => Some(DataspaceColumnType::Bool),
1754            "Timestamp" | "timestamp" | "datetime" => Some(DataspaceColumnType::Timestamp),
1755            "Json" | "json" => Some(DataspaceColumnType::Json),
1756            _ => None,
1757        }
1758    }
1759}
1760
1761/// v2.63.0 — one declared dataspace column: `column <name>: <Type>`.
1762/// The type is kept RAW at parse time (the string the adopter wrote);
1763/// the v2.63.0 type-checker resolves it against the closed catalog and
1764/// emits `axon-T928` on a miss — so ALL schema errors in a declaration
1765/// accumulate in one compile, instead of dying at the first bad token.
1766#[derive(Debug)]
1767pub struct DataspaceColumn {
1768    pub name: String,
1769    pub declared_type: String,
1770    pub loc: Loc,
1771}
1772
1773#[derive(Debug)]
1774pub struct DataspaceDefinition {
1775    pub name: String,
1776    /// v2.63.0 — the typed columnar schema. A dataspace IS its
1777    /// schema: the v2.63.0 type-checker refuses an empty one (axon-T928).
1778    pub columns: Vec<DataspaceColumn>,
1779    pub loc: Loc,
1780    /// v1.5.2 — leading comment trivia attached to this declaration
1781    /// (comments preceding the declaration's first token, since the
1782    /// previous declaration or file start). Empty by default.
1783    pub leading_trivia: Vec<crate::tokens::Trivia>,
1784    /// v1.5.2 — trailing comment trivia (same line as the
1785    /// declaration's last effective token). Empty by default.
1786    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1787}
1788
1789// ── OTS ──────────────────────────────────────────────────────────────────────
1790
1791#[derive(Debug)]
1792pub struct OtsDefinition {
1793    pub name: String,
1794    pub teleology: String,
1795    pub homotopy_search: String, // shallow | deep | speculative
1796    pub loss_function: String,
1797    pub loc: Loc,
1798    /// v1.5.2 — leading comment trivia attached to this declaration
1799    /// (comments preceding the declaration's first token, since the
1800    /// previous declaration or file start). Empty by default.
1801    pub leading_trivia: Vec<crate::tokens::Trivia>,
1802    /// v1.5.2 — trailing comment trivia (same line as the
1803    /// declaration's last effective token). Empty by default.
1804    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1805}
1806
1807// ── Mandate ──────────────────────────────────────────────────────────────────
1808
1809#[derive(Debug)]
1810pub struct MandateDefinition {
1811    pub name: String,
1812    pub constraint: String,
1813    pub kp: Option<f64>,
1814    pub ki: Option<f64>,
1815    pub kd: Option<f64>,
1816    pub tolerance: Option<f64>,
1817    pub max_steps: Option<i64>,
1818    /// v2.83.0 — declared drift bound `D` (`sup|drift(t)|`, paper_mandate
1819    /// section 3). A HYPOTHESIS the runtime must discharge by measurement, not a fact.
1820    pub drift_bound: Option<f64>,
1821    /// v2.83.0 — declared Lipschitz constant `L` of the refinement map
1822    /// (prompt_opt section 6.3). Same standing as `drift_bound`.
1823    pub lipschitz: Option<f64>,
1824    pub on_violation: String, // coerce | halt | retry
1825    pub loc: Loc,
1826    /// v1.5.2 — leading comment trivia attached to this declaration
1827    /// (comments preceding the declaration's first token, since the
1828    /// previous declaration or file start). Empty by default.
1829    pub leading_trivia: Vec<crate::tokens::Trivia>,
1830    /// v1.5.2 — trailing comment trivia (same line as the
1831    /// declaration's last effective token). Empty by default.
1832    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1833}
1834
1835// ── Compute ──────────────────────────────────────────────────────────────────
1836
1837#[derive(Debug)]
1838pub struct ComputeDefinition {
1839    pub name: String,
1840    pub shield_ref: String,
1841    /// v2.67.0 — the typed parameters. Before v2.67.0, `parse_compute` SKIPPED
1842    /// everything between the name and the brace ("Skip optional parameters/
1843    /// return type"), so a compute had no inputs at all — which is one reason it
1844    /// could not compute anything.
1845    pub parameters: Vec<Parameter>,
1846    /// v2.67.0 — the declared result type.
1847    pub return_type: String,
1848    /// v2.67.0 — **the body**: a v2.26.0 `Expr`.
1849    ///
1850    /// This is what makes `compute` honest. The README sells it as "Deterministic
1851    /// muscle — native Fast-Path execution BYPASSING the LLM" and even asserts a
1852    /// complexity class ("compute steps: O(n)"). A v2.26.0 expression is exactly that
1853    /// and nothing more: a closed, total, side-effect-free term the runtime
1854    /// evaluates with `eval_expr` — the same native evaluator `let`, `grad` and
1855    /// `conditional` already use. Linear in the term. No model in the loop.
1856    ///
1857    /// `None` ⇒ a compute that cannot compute; applying it is refused
1858    /// (axon-T941), rather than binding the literal string `"compute:Name(args)"`
1859    /// as the pre-v2.67.0 runtime did — which a downstream step then consumed as if
1860    /// it were a number.
1861    pub body: Option<Expr>,
1862    pub loc: Loc,
1863    /// v1.5.2 — leading comment trivia attached to this declaration
1864    /// (comments preceding the declaration's first token, since the
1865    /// previous declaration or file start). Empty by default.
1866    pub leading_trivia: Vec<crate::tokens::Trivia>,
1867    /// v1.5.2 — trailing comment trivia (same line as the
1868    /// declaration's last effective token). Empty by default.
1869    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1870}
1871
1872// ── Daemon ───────────────────────────────────────────────────────────────────
1873
1874#[derive(Debug)]
1875pub struct DaemonDefinition {
1876    pub name: String,
1877    pub goal: String,
1878    pub tools: Vec<String>,
1879    pub memory_ref: String,
1880    pub strategy: String, // react | reflexion | plan_and_execute | custom
1881    pub on_stuck: String, // hibernate | escalate | retry | forge
1882    pub shield_ref: String,
1883    /// v2.27.0 — the `window:` temporal binding (a `window` primitive name,
1884    /// v2.27.0). When set, the supervisor evaluates the bound window before
1885    /// claiming a scheduled tick: inside ⇒ fire; outside ⇒ `skip`/`warn`/`defer`
1886    /// per the window's `on_outside`. Empty for daemons with no temporal guard.
1887    pub window_ref: String,
1888    /// v2.28.0 — the `budget { … }` linear-effect rate limit. When set, each
1889    /// `on Tool(X)` quota gates that tool's dispatch on a renewable token bucket
1890    /// (the v2.28.0 `RateLease`): a call consumes a token, exhaustion applies
1891    /// `on_exhausted`. `None` for daemons with no effect budget.
1892    pub budget: Option<BudgetBlock>,
1893    pub max_tokens: Option<i64>,
1894    pub max_time: String,
1895    pub max_cost: Option<f64>,
1896    /// v1.6.0 D4 — listen blocks captured for type-checker
1897    /// validation (typed-channel ref + dual-mode deprecation warning).
1898    /// Pre-v1.6.0 the parser discarded these structurally; we now
1899    /// retain them so 13.b/13.f can validate emit/publish/discover
1900    /// inside listener bodies and surface D4 string-topic warnings.
1901    pub listeners: Vec<ListenStep>,
1902    /// v2.4.0 — the capability scope a daemon's runs are confined to
1903    /// (`requires: [cap, …]`, the same closed slug grammar as `axonendpoint
1904    /// requires:`). A scheduled (cron) daemon MUST declare this (it is a
1905    /// standing autonomous privilege); the enterprise supervisor mints a
1906    /// per-run principal scoped to EXACTLY these capabilities (least privilege,
1907    /// v2.4.0). Empty for event-only daemons / pre-v2.4.0 daemons.
1908    pub requires_capabilities: Vec<String>,
1909    pub loc: Loc,
1910    /// v1.5.2 — leading comment trivia attached to this declaration
1911    /// (comments preceding the declaration's first token, since the
1912    /// previous declaration or file start). Empty by default.
1913    pub leading_trivia: Vec<crate::tokens::Trivia>,
1914    /// v1.5.2 — trailing comment trivia (same line as the
1915    /// declaration's last effective token). Empty by default.
1916    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1917}
1918
1919/// v2.28.0 — a `budget { … }` block: a set of per-effect rate quotas plus the
1920/// exhaustion policy. Where `window` guards an effect's TIMING, `budget` guards
1921/// its RATE — a tool call consumes one token from a renewable bucket, and
1922/// over-emission is impossible by construction (the Logic pillar's linearity
1923/// made real for external effects).
1924#[derive(Debug)]
1925pub struct BudgetBlock {
1926    /// v2.69.0 — the budget's NAME when it is declared **top-level**.
1927    ///
1928    /// Empty ⇒ the daemon-attached form (`daemon D { budget { … } }`), which is
1929    /// anonymous and scoped to that daemon's ticks.
1930    ///
1931    /// # Why top-level had to exist
1932    ///
1933    /// Until v2.69.0, `budget` was a **field of `daemon` and nothing else**. So an
1934    /// adopter deploying an HTTP endpoint that calls a vendor tool had **no way in
1935    /// the language to bound how often it does that.** Not "the bound did not
1936    /// work" — **the bound could not be written.** And the HTTP endpoint is what
1937    /// people actually deploy.
1938    pub name: String,
1939    /// The per-effect quotas (`rate:`/`max:` lines). At least one.
1940    pub quotas: Vec<BudgetQuota>,
1941    /// What to do when a quota is exhausted: `block` (fail-closed, the default) |
1942    /// `defer` (reschedule via the v2.27.0 defer ledger) | `shed` (skip the call).
1943    pub on_exhausted: String,
1944    pub loc: Loc,
1945    /// v2.69.0 — comment trivia, so a top-level `budget` does not silently lose
1946    /// its doc comments through the formatter (v1.5.2). Empty for the
1947    /// daemon-attached form.
1948    pub leading_trivia: Vec<crate::tokens::Trivia>,
1949    pub trailing_trivia: Vec<crate::tokens::Trivia>,
1950}
1951
1952/// v2.28.0 — one quota line of a [`BudgetBlock`]:
1953/// `<kind>: <limit> per <period> on Tool(<effect>)`.
1954#[derive(Debug)]
1955pub struct BudgetQuota {
1956    /// `rate` (a renewable bucket that refills `limit` tokens per `period`) or
1957    /// `max` (a windowed hard cap of `limit` per `period`, no intra-window refill).
1958    pub kind: String,
1959    /// The token allowance per period (> 0).
1960    pub limit: i64,
1961    /// The renewal/window period: `second` | `minute` | `hour` | `day`.
1962    pub period: String,
1963    /// The effect this quota governs — a declared `Tool` name (`on Tool(X)`).
1964    pub effect: String,
1965    pub loc: Loc,
1966}
1967
1968// ── AxonStore ────────────────────────────────────────────────────────────────
1969
1970#[derive(Debug)]
1971pub struct AxonStoreDefinition {
1972    pub name: String,
1973    pub backend: String, // in_memory | postgresql | secrets
1974    /// The DSN — **the field that actually runs today**. `connection:` →
1975    /// `resolve_dsn` → a real sqlx pool, with no global-pool fallback.
1976    ///
1977    /// v2.67.0: still accepted (the live deployment depends on it), but it
1978    /// **warns**, and a store declared this way is INELIGIBLE for
1979    /// `lease` / `observe` / `reconcile`. *You cannot govern what you did not
1980    /// declare.*
1981    pub connection: String,
1982    /// v2.67.0 — the `resource` this store runs on. When present, the store
1983    /// DERIVES its DSN, its **pool size** and its sharing discipline from the
1984    /// resource. The derivation is the point; a bare reference would be the
1985    /// nominal link this cycle exists to avoid.
1986    pub resource_ref: String,
1987    pub confidence_floor: Option<f64>,
1988    pub isolation: String, // read_committed | repeatable_read | serializable
1989    pub on_breach: String, // rollback | raise | log
1990    /// v1.30.0 (D11) — Pillar IV: the capability slug required to
1991    /// access this store. Empty = no capability gate. Validated at
1992    /// parse time against the closed slug grammar (shared with the
1993    /// v1.23.0 `requires:` grammar).
1994    pub capability: String,
1995    /// v2.48.0 — the secret-class prefix of a `backend: secrets`
1996    /// metadata store (doctrine `rotation_without_revelation`). A
1997    /// dotted lowercase identifier, e.g. `crm` — the store enumerates
1998    /// the tenant's secrets whose keys live under `<class>.` (so
1999    /// `class: crm` covers `crm.hubspot`, `crm.zoho.acct_x`, …).
2000    /// REQUIRED when `backend: secrets` and FORBIDDEN otherwise
2001    /// (`axon-T900`): a class-less secrets store would enumerate the
2002    /// tenant's ENTIRE secret namespace (`llm.*` included) — that
2003    /// over-broad view is unrepresentable, not discouraged.
2004    pub class: String,
2005    /// v1.31.0 (D1) — the OPTIONAL column-schema declaration. Three
2006    /// closed forms (inline / manifest-ref / env-var); `None` means the
2007    /// 37.x runtime+deploy path applies verbatim (D5 absolute). The
2008    /// v1.31.0 / v1.31.0 `StoreColumnProof` pass consumes this; the v1.31.0
2009    /// CLI exports it. For a `backend: secrets` store this is always
2010    /// `None` in the AST (declaring one is `axon-T900`) — the fixed
2011    /// metadata schema is synthesized at IR time
2012    /// (`store_schema::secrets_metadata_schema`).
2013    pub column_schema: Option<crate::store_schema::StoreColumnSchema>,
2014    pub loc: Loc,
2015    /// v1.5.2 — leading comment trivia attached to this declaration
2016    /// (comments preceding the declaration's first token, since the
2017    /// previous declaration or file start). Empty by default.
2018    pub leading_trivia: Vec<crate::tokens::Trivia>,
2019    /// v1.5.2 — trailing comment trivia (same line as the
2020    /// declaration's last effective token). Empty by default.
2021    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2022}
2023
2024// ── AxonEndpoint ─────────────────────────────────────────────────────────────
2025
2026#[derive(Debug)]
2027pub struct AxonEndpointDefinition {
2028    pub name: String,
2029    pub method: String, // GET | POST | PUT | DELETE
2030    pub path: String,
2031    pub body_type: String,
2032    pub execute_flow: String,
2033    pub output_type: String,
2034    pub shield_ref: String,
2035    /// v2.38.0 — the `cors: <Name>` reference, or `""` if absent
2036    /// (the design decision: absent ⇒ no CORS headers, ever — secure by default). Same
2037    /// empty-string sentinel convention as `shield_ref`, not `Option`.
2038    pub cors_ref: String,
2039    pub retries: Option<i64>,
2040    pub timeout: String,
2041    /// ESK — regulatory coverage on the boundary.
2042    pub compliance: Vec<String>,
2043    /// v1.21.0 — HTTP wire transport for the response. Closed enum
2044    /// per D2 ratified 2026-05-10: {"json" | "sse" | "ndjson"}.
2045    /// Default "json" (D1 — backwards-compat preserved). When set
2046    /// to "sse", the type-checker (30.c) verifies that
2047    /// `execute_flow` produces a Stream<T> (D3).
2048    pub transport: String,
2049    /// v1.21.0 — Keepalive comment interval for SSE transport (D6).
2050    /// Optional; default applied at runtime when transport == "sse"
2051    /// (default 15s). Closed enum at parse time:
2052    /// {"5s" | "15s" | "30s" | "60s"}. Empty string means
2053    /// "use runtime default".
2054    pub keepalive: String,
2055    /// v1.22.0 — Type-Driven Wire Inference (D1, D7).
2056    /// `transport_explicit` is `true` if the source declared
2057    /// `transport:` explicitly (any of json/sse/ndjson). `false` if
2058    /// the field was omitted, in which case `transport` reflects the
2059    /// D1 default `"json"` but `implicit_transport` (computed by the
2060    /// `axon_frontend::type_checker::compute_implicit_transports`
2061    /// pass) carries the inferred value.
2062    pub transport_explicit: bool,
2063    /// v1.22.0 — Inferred wire transport per D1:
2064    ///   implicit_transport(E) =
2065    ///     declared_transport(E)   if transport_explicit
2066    ///     "sse"                    if produces_stream(execute_flow) ∧ ¬explicit
2067    ///     "json"                   otherwise
2068    /// Empty string `""` before the type-checker runs. The Python
2069    /// reference implementation in `axon/compiler/type_checker.py`
2070    /// sets the field byte-identically (D7 cross-stack contract).
2071    pub implicit_transport: String,
2072    /// v1.23.0 (D8) — Auth scope: capability slugs the request
2073    /// bearer must hold for the endpoint to dispatch. Empty vec
2074    /// means "no auth gate" (D9 backwards-compat). Slug grammar
2075    /// (closed): `^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$`. Examples:
2076    /// `admin`, `legal.read`, `hipaa.phi.read`. The runtime checks
2077    /// declared_requires ⊆ token_capabilities (AND semantics — every
2078    /// declared capability must be present in the bearer's claims).
2079    pub requires_capabilities: Vec<String>,
2080    /// v2.44.0 — `public: true` is the EXPLICIT authorization-coverage
2081    /// opt-out (doctrine `every_boundary_is_guarded`). An `axonendpoint`
2082    /// compiles iff it is covered by ≥1 discipline (`requires:` / `shield:` /
2083    /// `compliance:`) OR declares `public: true`. Omitting BOTH is a hard
2084    /// error (`axon-T890`, v2.44.0) — this is what closes Modo 1 (a guard
2085    /// bypassable by silent omission). `public: true` does NOT bypass HTTP
2086    /// authentication (the enterprise `require_auth` middleware is a
2087    /// SEPARATE concern); it declares — deliberately + auditably — that the
2088    /// endpoint carries no capability/shield/compliance coverage. Default
2089    /// `false` (parser + programmatic construction); the v2.44.0 rule reads it.
2090    pub public: bool,
2091    /// v1.23.0 — Replay-token binding (D9 plan-vivo).
2092    /// `replay_explicit` is `true` when the source declared `replay:`
2093    /// explicitly. `false` when the field was omitted, in which case
2094    /// `replay` reflects the method-default (POST/PUT → true, GET/
2095    /// DELETE → false) computed at deploy time. When the effective
2096    /// value resolves to `true`, every successful 2xx response is
2097    /// recorded in the runtime's axonendpoint replay log keyed by
2098    /// trace_id; auditors retrieve it via GET /v1/replay/<trace_id>.
2099    pub replay_explicit: bool,
2100    pub replay: bool,
2101    /// v1.28.0 — Selected SSE wire-format dialect.
2102    ///
2103    /// Populated when the source uses the parametrized grammar
2104    /// `transport: sse(<dialect>)`. Closed catalog
2105    /// (`AXONENDPOINT_TRANSPORT_DIALECTS`): `{axon, openai, anthropic}`.
2106    /// Empty string `""` when:
2107    ///   - the source declared a non-SSE transport (`json`/`ndjson`), OR
2108    ///   - the source declared bare `transport: sse` without parens, OR
2109    ///   - the source omitted `transport:` entirely (D1 implicit path).
2110    ///
2111    /// When empty + the effective wire is SSE (per the runtime
2112    /// classifier `classify_dynamic_route_wire`), the runtime
2113    /// resolves the dialect via the Q1 algebraic-effect-driven
2114    /// default: openai for tool-streaming flows (algebraic predicate
2115    /// true), axon for type-annotation-only flows (algebraic predicate
2116    /// false). D3 explicit `transport: sse(<dialect>)` overrides the
2117    /// default.
2118    pub transport_dialect: String,
2119    /// v1.27.1 — Algebraic-effect override predicate.
2120    ///
2121    /// `true` when `execute_flow` references a tool that declares
2122    /// `effects: <stream:<policy>>` (v1.21.0 algebraic-effect surface).
2123    /// Mirrors `type_checker::flow_uses_streaming_tool(execute_flow, program)`.
2124    ///
2125    /// Used by the runtime classifier
2126    /// (`axon_server::classify_dynamic_route_wire`) to OVERRIDE the
2127    /// v1.22.0 D6 backwards-compat gate: a tool with a declared stream
2128    /// effect is a LANGUAGE-LEVEL commitment to streaming, not a
2129    /// client preference. When this field is `true` AND
2130    /// `transport: json` is NOT explicitly declared (D3 opt-out remains
2131    /// sacred), the route wire is unconditionally `Sse` — no
2132    /// `Accept: text/event-stream` header required, no
2133    /// `AXON_STRICT_TYPE_DRIVEN_TRANSPORT=1` runtime flag required.
2134    ///
2135    /// Computed in lockstep with `implicit_transport` by the
2136    /// `compute_implicit_transports` pass. Default `false` before the
2137    /// pass runs (matches AST construction defaults; D9 backwards-
2138    /// compat preserved for older AST consumers).
2139    pub has_algebraic_stream_effect: bool,
2140    /// v1.31.0 (D2) — the declared execution backend for the flow
2141    /// behind this endpoint. Empty string `""` means "not declared"
2142    /// (the endpoint resolves its backend down the v1.31.0 D1
2143    /// precedence ladder — server default → environment-available
2144    /// `auto`). When non-empty the parser has validated it against the
2145    /// closed catalog [`crate::parser::AXONENDPOINT_BACKEND_VALUES`]
2146    /// and the type-checker rejects an unknown name as a compile
2147    /// error. A declared `backend:` is rung 2 of the resolution
2148    /// contract.
2149    pub backend: String,
2150    /// v1.32.0 (D1) — Path parameter names extracted from the
2151    /// `path:` string at parse time. For `path: "/api/tenants/{tenant_id}/secrets/{secret_name}"`
2152    /// this is `["tenant_id", "secret_name"]`. Empty Vec when the
2153    /// path has no `{name}` placeholders (D5 backwards-compat — an
2154    /// endpoint without path params produces byte-identical IR to
2155    /// v1.38.4).
2156    ///
2157    /// Names are deduplicated + recorded in declaration order. A
2158    /// duplicate `{tenant_id}` in the same path is a parse error
2159    /// (HTTP route patterns reject duplicates structurally — `axum`
2160    /// would panic at registration). Type binding is always `Text`
2161    /// in v1.38.5 (HTTP path-segment convention); a future v1.32.0
2162    /// may add per-placeholder type-override grammar `{tenant_id: Uuid}`.
2163    ///
2164    /// The v1.32.0 D2 totality check (extended by 37.y D3) treats
2165    /// every name here as covering an equivalent flow parameter
2166    /// declared `Text`. Collision with a body field of the same name
2167    /// is a compile error (`axon-T901`, D4).
2168    pub path_params: Vec<String>,
2169    /// v1.32.0 (D2) — Query parameters declared via the inline
2170    /// `query: { name: Type, name: Type? }` block on the endpoint.
2171    /// Empty Vec when the source omits the block (D5 backwards-compat).
2172    ///
2173    /// Closed type catalog (parser-enforced):
2174    /// `{Text, Int, Float, Bool, Uuid}`. The runtime receives every
2175    /// query value as a textual `String` and binds it to the same-named
2176    /// flow parameter; the closed catalog enables future per-type
2177    /// parsing/validation without breaking the manifest format.
2178    ///
2179    /// The optional flag (`?` suffix in the source) reuses
2180    /// `TypeExpr.optional`. An optional query param need not be
2181    /// covered by a flow parameter (D3 totality is over required
2182    /// params); a required query param missing from the flow signature
2183    /// is a `axon-T?nn` future arm. For v1.38.5 the totality check
2184    /// treats every query param as a binding-source candidate for any
2185    /// same-named flow param.
2186    ///
2187    /// Reusing `TypeField` (shared with body type declarations) keeps
2188    /// the D2 totality check uniform — the same `field.type_expr.name
2189    /// == param.type_expr.name` comparator works for body fields AND
2190    /// query params.
2191    pub query_params: Vec<TypeField>,
2192    pub loc: Loc,
2193    /// v1.5.2 — leading comment trivia attached to this declaration
2194    /// (comments preceding the declaration's first token, since the
2195    /// previous declaration or file start). Empty by default.
2196    pub leading_trivia: Vec<crate::tokens::Trivia>,
2197    /// v1.5.2 — trailing comment trivia (same line as the
2198    /// declaration's last effective token). Empty by default.
2199    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2200}
2201
2202// ── Import ───────────────────────────────────────────────────────────────────
2203
2204#[derive(Debug)]
2205pub struct ImportNode {
2206    pub module_path: Vec<String>,
2207    pub names: Vec<String>,
2208    /// v2.76.0 — the `@allow_downgrade` ECC valve: acknowledges an
2209    /// epistemic downgrade across this import edge (silences `axon-W017`,
2210    /// downgrades `axon-T954` to a *visible* `axon-W017`). `false` for
2211    /// every import written before v2.76.0.
2212    pub allow_downgrade: bool,
2213    pub loc: Loc,
2214    /// v1.5.2 — leading comment trivia attached to this declaration
2215    /// (comments preceding the declaration's first token, since the
2216    /// previous declaration or file start). Empty by default.
2217    pub leading_trivia: Vec<crate::tokens::Trivia>,
2218    /// v1.5.2 — trailing comment trivia (same line as the
2219    /// declaration's last effective token). Empty by default.
2220    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2221}
2222
2223// ── Persona ──────────────────────────────────────────────────────────────────
2224
2225#[derive(Debug)]
2226pub struct PersonaDefinition {
2227    pub name: String,
2228    pub domain: Vec<String>,
2229    pub tone: String,
2230    pub confidence_threshold: Option<f64>,
2231    pub cite_sources: Option<bool>,
2232    pub refuse_if: Vec<String>,
2233    pub language: String,
2234    pub description: String,
2235    pub loc: Loc,
2236    /// v1.5.2 — leading comment trivia attached to this declaration
2237    /// (comments preceding the declaration's first token, since the
2238    /// previous declaration or file start). Empty by default.
2239    pub leading_trivia: Vec<crate::tokens::Trivia>,
2240    /// v1.5.2 — trailing comment trivia (same line as the
2241    /// declaration's last effective token). Empty by default.
2242    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2243}
2244
2245// ── Context ──────────────────────────────────────────────────────────────────
2246
2247#[derive(Debug)]
2248pub struct ContextDefinition {
2249    pub name: String,
2250    pub memory_scope: String,
2251    pub language: String,
2252    pub depth: String,
2253    pub max_tokens: Option<i64>,
2254    pub temperature: Option<f64>,
2255    pub cite_sources: Option<bool>,
2256    /// v2.46.0 — the conversational frame's declared cognitive timezone
2257    /// (IANA name). Every step running within this context carries the run's
2258    /// captured instant rendered in this zone, unless the step declares its
2259    /// own `now:` override. Format-checked (`axon-T892`); `None` → no
2260    /// temporal injection (back-compat).
2261    pub now_tz: Option<String>,
2262    pub loc: Loc,
2263    /// v1.5.2 — leading comment trivia attached to this declaration
2264    /// (comments preceding the declaration's first token, since the
2265    /// previous declaration or file start). Empty by default.
2266    pub leading_trivia: Vec<crate::tokens::Trivia>,
2267    /// v1.5.2 — trailing comment trivia (same line as the
2268    /// declaration's last effective token). Empty by default.
2269    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2270}
2271
2272// ── Anchor ───────────────────────────────────────────────────────────────────
2273
2274#[derive(Debug)]
2275pub struct AnchorConstraint {
2276    pub name: String,
2277    pub require: String,
2278    pub reject: Vec<String>,
2279    pub enforce: String,
2280    pub description: String,
2281    pub confidence_floor: Option<f64>,
2282    pub unknown_response: String,
2283    pub on_violation: String,
2284    pub on_violation_target: String,
2285    pub loc: Loc,
2286    /// v1.5.2 — leading comment trivia attached to this declaration
2287    /// (comments preceding the declaration's first token, since the
2288    /// previous declaration or file start). Empty by default.
2289    pub leading_trivia: Vec<crate::tokens::Trivia>,
2290    /// v1.5.2 — trailing comment trivia (same line as the
2291    /// declaration's last effective token). Empty by default.
2292    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2293}
2294
2295// ── Memory ───────────────────────────────────────────────────────────────────
2296
2297#[derive(Debug)]
2298pub struct MemoryDefinition {
2299    pub name: String,
2300    pub store: String,
2301    pub backend: String,
2302    pub retrieval: String,
2303    pub decay: String,
2304    pub loc: Loc,
2305    /// v1.5.2 — leading comment trivia attached to this declaration
2306    /// (comments preceding the declaration's first token, since the
2307    /// previous declaration or file start). Empty by default.
2308    pub leading_trivia: Vec<crate::tokens::Trivia>,
2309    /// v1.5.2 — trailing comment trivia (same line as the
2310    /// declaration's last effective token). Empty by default.
2311    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2312}
2313
2314// ── Tool ─────────────────────────────────────────────────────────────────────
2315
2316#[derive(Debug)]
2317pub struct ToolDefinition {
2318    pub name: String,
2319    pub provider: String,
2320    pub max_results: Option<i64>,
2321    pub filter_expr: String,
2322    pub timeout: String,
2323    pub runtime: String,
2324    /// v2.69.0 — the `resource` this tool's channel runs on (`tool T { resource: Api }`).
2325    ///
2326    /// When present, the tool DERIVES its endpoint from `resource.endpoint`, its
2327    /// concurrency bound from `resource.capacity`, and (via `lease`/`observe`) its
2328    /// lifecycle and health from the resource. `runtime:` then names the PATH
2329    /// within that channel, not the channel itself.
2330    ///
2331    /// This is what governs `tool.runtime` — the third island. An absolute
2332    /// `runtime: "https://…"` (a production URL in source, with no lifetime, no
2333    /// capacity, no shield) is now refused; the address lives on the resource.
2334    ///
2335    /// Empty ⇒ the legacy form (slug `runtime:` joined onto a per-tenant base URL,
2336    /// which already conforms). Ungoverned, and therefore ineligible for the
2337    /// channel `shield` / `lease` / `observe`.
2338    pub resource_ref: String,
2339    pub sandbox: Option<bool>,
2340    pub effects: Option<EffectRow>,
2341    /// v2.8.0 — the tool's typed INPUT SCHEMA (W2: the caller↔tool
2342    /// contract). Each entry is a named, typed parameter that the canonical
2343    /// `use Tool(k = v, …)` invocation binds against and the type-checker
2344    /// validates the caller's args against (CT-2 caller blame, pre-HTTP).
2345    /// Empty for a schema-less tool — the legacy single-`on <arg>` form still
2346    /// applies (v2.8.0 D5 back-compat). Reuses `Parameter` (same `TypeExpr`
2347    /// grammar as flow params).
2348    pub parameters: Vec<Parameter>,
2349    /// v2.8.0 — the tool's declared OUTPUT type, so a tool-step's result
2350    /// is referenceable as `${Step.output}` with a real type (v2.8.0 D8). Flat
2351    /// string (mirrors step `output:`); `None` when undeclared.
2352    pub output_type: Option<String>,
2353    /// v2.77.0 — the authorization scopes this tool's operation
2354    /// requires (`requires: ["w_organization_social"]`): flat capability atoms,
2355    /// the same vocabulary as `credential.grants` (v2.46.0) and endpoint
2356    /// `requires_capabilities` (v2.4.0). `axon-T956` enforces subset coverage —
2357    /// every `use` of a tool with a non-empty `requires` must occur where the
2358    /// program's granted set covers it. Empty = no scope demand (every
2359    /// pre-v2.77.0 tool, unchanged). Flat SETS by design: OAuth scopes are
2360    /// per-platform atoms with no hierarchy — a scope tree would model
2361    /// structure the domain does not have.
2362    pub requires: Vec<String>,
2363    /// v2.48.0 — the per-tenant secret KEY injected into every dispatch
2364    /// of this tool (doctrine `rotation_without_revelation`): at `use`
2365    /// time the runtime resolves the key against the tenant's secret
2366    /// custody and injects the value into the tool-server request under
2367    /// the reserved `axon_secret` field — the flow never touches it. The
2368    /// v2.37.0 posture extended to tools: this is a config KEY, never a
2369    /// credential literal (`axon-T902`, the T850 charset mirror). Empty =
2370    /// no injection (every pre-v2.48.0 tool). Meaningless on a
2371    /// `target:`-bound technician tool (execve dispatch, no HTTP request
2372    /// to inject into) — declaring both is `axon-T902`.
2373    pub secret: String,
2374    /// v2.49.0 — the `secret_partition:` field (doctrine
2375    /// `selection_without_revelation`): the name of one of THIS tool's own
2376    /// `parameters:` whose runtime value is appended as a single key
2377    /// SEGMENT to `secret:` at dispatch, so one tool serves N sub-tenants
2378    /// multiplexed under one axon-tenant. With `secret: crm.hubspot` and
2379    /// `secret_partition: tenant_id`, a `use CrmCrearContacto(tenant_id =
2380    /// "acme", …)` resolves the custody key `crm.hubspot.acme`. The
2381    /// `secret:` class prefix is pinned at compile time (a literal); only
2382    /// this bounded segment is dynamic — the resolved key can NEVER leave
2383    /// the tool's declared class (the segment is charset-checked to a
2384    /// single dot-free run at dispatch, fail-closed). Empty = the v2.48.0
2385    /// static-key behaviour, unchanged. `axon-T903` governs its laws:
2386    /// requires a non-empty `secret:`, must name a `String` parameter of
2387    /// this tool, forbidden on a technician tool. The value SELECTED is
2388    /// still never revealed to cognition — `secret_partition` chooses
2389    /// WHICH borrowed authority to spend, never reads it.
2390    pub secret_partition: String,
2391    /// v2.39.0 — Remote Hands. The `socket` this technician tool dispatches
2392    /// over: a program acting on a real machine dials `axon` as a `socket`
2393    /// client, and a `target:`-bound tool call sends its rendered argv down
2394    /// that connection. `None` ⇒ today's unchanged in-process / model-surface
2395    /// behaviour (zero regression; the whole v2.39.0 surface is inert unless
2396    /// `target:` is set). Resolved to a declared `socket` and duality-checked
2397    /// by `axon-T861`.
2398    pub target: Option<String>,
2399    /// v2.39.0 — the operation's risk class, a v1-closed catalog of exactly
2400    /// `safe | destructive` (`technician::VALID_RISK_LEVELS`). `destructive`
2401    /// forces the bound session to carry a reachable `branch{approved/denied}`
2402    /// confirmation (`axon-T860`). `None` on a non-technician tool.
2403    pub risk: Option<String>,
2404    /// v2.39.0 — the **argv template**: an ordered list of argv elements,
2405    /// each either a literal token (`"ping"`, `"-c"`) or a *whole-element*
2406    /// `${param}` placeholder (`"${host}"`). A placeholder binds to a declared
2407    /// `parameters:` entry and is substituted as ONE opaque argv argument at
2408    /// dispatch — never concatenated, never re-parsed by a shell. This
2409    /// is the injection-safety keystone: the market's free `template:` STRING
2410    /// is deliberately NOT offered. Empty for a non-technician tool; required
2411    /// (`axon-T858`) when `target:` is set on a `provider: bash` tool.
2412    pub argv: Vec<String>,
2413    /// v2.40.0 — the result-memoization policy for this tool. Names a
2414    /// declared `cache` (`axon-T864`), or the reserved sentinel `none` to opt
2415    /// OUT of an active `cache { default: true }` policy (the escape hatch for
2416    /// a rare mislabeled-`pure` tool). Empty ⇒ governed by the module default
2417    /// if one exists and this tool is eligible (`pure`, or covered by the
2418    /// default's `apply_to_effects`). Distinct from `memory`.
2419    pub cache: String,
2420    /// v2.52.0 — Native Web Acquisition. The closed-catalog scrape
2421    /// configuration for a tool whose `provider:` is one of the three
2422    /// web-acquisition engines (`scrape_http` | `scrape_dom` |
2423    /// `scrape_crawl`). `None` ⇒ this is not a scrape tool — the entire
2424    /// v2.52.0 surface is inert (zero regression). Present ⇒ the tool acquires
2425    /// content from the OPEN, ADVERSARIAL web: its output is born
2426    /// epistemically Untrusted (⊥, the design decision) and its `effects:` row MUST
2427    /// carry the first-class `web` base (`axon-T904`, effect honesty).
2428    /// The sub-block is a closed catalog — an unknown field is a hard
2429    /// parse error (the v2.38.0/v2.39.0 discipline, the design decision).
2430    pub scrape: Option<ScrapeSpec>,
2431    pub loc: Loc,
2432    /// v1.5.2 — leading comment trivia attached to this declaration
2433    /// (comments preceding the declaration's first token, since the
2434    /// previous declaration or file start). Empty by default.
2435    pub leading_trivia: Vec<crate::tokens::Trivia>,
2436    /// v1.5.2 — trailing comment trivia (same line as the
2437    /// declaration's last effective token). Empty by default.
2438    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2439}
2440
2441/// v2.52.0 — the closed-catalog scrape configuration block
2442/// (`scrape: { … }`) on a web-acquisition `tool`. Every field is
2443/// optional/defaulted so a minimal `scrape: {}` is legal; the fields
2444/// that apply depend on the tool's `provider:` (the type-checker cross-
2445/// validates provider ↔ field applicability, `axon-T905`). The whole
2446/// struct is deliberately flat + serializable-friendly (`Option`/`Vec`/
2447/// scalar), mirroring the v2.39.0 technician-field discipline, so the IR
2448/// stays byte-stable and the runtime classifies identically.
2449#[derive(Debug, Default)]
2450pub struct ScrapeSpec {
2451    /// The acquisition engine: `impersonate` (HTTP-fingerprint stealth,
2452    /// the GA tier) | `browser` (headless-render sidecar, the gray tier).
2453    /// `None` ⇒ `impersonate`. Closed catalog (`axon-T905`).
2454    /// Applies to `scrape_http` / `scrape_crawl`.
2455    pub engine: Option<String>,
2456    /// The browser-fingerprint impersonation PROFILE name
2457    /// (`chrome`, `firefox`, `safari` — closed catalog). Only meaningful
2458    /// with `engine: impersonate`. The concrete JA3/JA4 + HTTP/2 profile
2459    /// is resolved by the enterprise engine (v2.52.0); OSS records the
2460    /// declared intent. `None` ⇒ the engine's default profile.
2461    pub impersonate: Option<String>,
2462    /// The post-navigation settle wait for `engine: browser` (a Duration,
2463    /// e.g. `2s`) — how long to let JS render before snapshotting. Bounded
2464    ///. Ignored by the impersonate engine (no JS runtime).
2465    pub render_wait: Option<String>,
2466    /// The per-tenant proxy-pool config KEY (a dotted key, resolved via
2467    /// the same SecretResolver `secret:`/`tool.base_url` use — the design decision),
2468    /// never a proxy URL literal. Empty ⇒ direct connection.
2469    pub proxy: String,
2470    /// Whether `robots.txt` is honored (default TRUE, the design decision). Setting
2471    /// `respect_robots: false` is the audited, `scrape.aggressive`-gated
2472    /// override (enforced enterprise-side, v2.52.0); in OSS it is recorded.
2473    pub respect_robots: Option<bool>,
2474    /// `scrape_dom` extraction spec: an ordered list of `name=selector`
2475    /// FieldSpecs (`["title=h1", "price=.amount"]`). A closed, bracketed
2476    /// string list (reuses the v2.38.0/v2.39.0 list helper). Each entry must be a
2477    /// single `name=selector` pair (`axon-T906`).
2478    pub extract: Vec<String>,
2479    /// `scrape_dom` adaptive relocation: when a declared selector misses,
2480    /// the engine attempts a HEURISTIC relocation above `similarity_floor`
2481    /// (the design decision — a heuristic, NOT a proof). `None`/`false` ⇒ strict
2482    /// selectors only. Enabling it makes the tool carry `<storage>` (the
2483    /// per-tenant selector-memory, v2.52.0).
2484    pub adaptive: Option<bool>,
2485    /// The similarity threshold ∈ [0,1] governing adaptive relocation
2486    /// (`axon-T907`). Only meaningful with `adaptive: true`.
2487    pub similarity_floor: Option<f64>,
2488    /// `scrape_crawl` link-follow selector/pattern: which links to enqueue
2489    /// from each fetched page. Empty ⇒ no expansion (single-page crawl).
2490    pub follow: String,
2491    /// `scrape_crawl` maximum link depth from the seed (bounded, the design decision).
2492    pub max_depth: Option<i64>,
2493    /// `scrape_crawl` maximum total pages fetched (bounded, the design decision). A
2494    /// hostile/infinite site can never exhaust the crawler (`axon-T908`).
2495    pub max_pages: Option<i64>,
2496    /// `scrape_crawl` fetch concurrency (bounded, ≥ 1).
2497    pub concurrency: Option<i64>,
2498    /// `scrape_crawl` politeness/rate reference: a declared `budget`
2499    /// (`budget{rate:/max:}`, v2.28.0) governing per-host request pacing
2500    /// (D98 reuse of the budget kernel). Empty ⇒ engine default pacing.
2501    pub politeness: String,
2502    /// `scrape_crawl` checkpoint store reference: a declared `axonstore`
2503    /// the crawler persists frontier/visited state into for resumable,
2504    /// at-least-once crawling. Empty ⇒ in-memory (non-resumable).
2505    pub checkpoint: String,
2506    pub loc: Loc,
2507}
2508
2509#[derive(Debug)]
2510pub struct EffectRow {
2511    pub effects: Vec<String>,
2512    pub epistemic_level: String,
2513    pub loc: Loc,
2514}
2515
2516// ── Type ─────────────────────────────────────────────────────────────────────
2517
2518#[derive(Debug)]
2519pub struct TypeDefinition {
2520    pub name: String,
2521    pub fields: Vec<TypeField>,
2522    pub range_constraint: Option<RangeConstraint>,
2523    pub where_clause: Option<WhereClause>,
2524    /// ESK — κ regulatory class attached to a type.
2525    pub compliance: Vec<String>,
2526    pub loc: Loc,
2527    /// v1.5.2 — leading comment trivia attached to this declaration
2528    /// (comments preceding the declaration's first token, since the
2529    /// previous declaration or file start). Empty by default.
2530    pub leading_trivia: Vec<crate::tokens::Trivia>,
2531    /// v1.5.2 — trailing comment trivia (same line as the
2532    /// declaration's last effective token). Empty by default.
2533    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2534}
2535
2536#[derive(Debug, Clone)]
2537pub struct TypeExpr {
2538    pub name: String,
2539    pub generic_param: String,
2540    pub optional: bool,
2541    pub loc: Loc,
2542}
2543
2544#[derive(Debug)]
2545pub struct TypeField {
2546    pub name: String,
2547    pub type_expr: TypeExpr,
2548    pub loc: Loc,
2549}
2550
2551#[derive(Debug)]
2552pub struct RangeConstraint {
2553    pub min_value: f64,
2554    pub max_value: f64,
2555    pub loc: Loc,
2556}
2557
2558#[derive(Debug)]
2559pub struct WhereClause {
2560    pub expression: String,
2561    pub loc: Loc,
2562}
2563
2564// ── Flow ─────────────────────────────────────────────────────────────────────
2565
2566#[derive(Debug)]
2567pub struct FlowDefinition {
2568    pub name: String,
2569    pub parameters: Vec<Parameter>,
2570    pub return_type: Option<TypeExpr>,
2571    pub body: Vec<FlowStep>,
2572    pub loc: Loc,
2573    /// v1.5.2 — leading comment trivia attached to this declaration
2574    /// (comments preceding the declaration's first token, since the
2575    /// previous declaration or file start). Empty by default.
2576    pub leading_trivia: Vec<crate::tokens::Trivia>,
2577    /// v1.5.2 — trailing comment trivia (same line as the
2578    /// declaration's last effective token). Empty by default.
2579    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2580}
2581
2582#[derive(Debug)]
2583pub struct Parameter {
2584    pub name: String,
2585    pub type_expr: TypeExpr,
2586    pub loc: Loc,
2587}
2588
2589/// Statements that can appear inside a flow body.
2590#[derive(Debug)]
2591pub enum FlowStep {
2592    Step(StepNode),
2593    If(ConditionalNode),
2594    ForIn(ForInStatement),
2595    Let(LetStatement),
2596    Return(ReturnStatement),
2597    /// v1.14.0 — `break` keyword. Payload-free; carries only its
2598    /// source location for error reporting.
2599    Break(BreakStatement),
2600    /// v1.14.0 — `continue` keyword. Payload-free; same shape as
2601    /// `Break`.
2602    Continue(ContinueStatement),
2603    /// Lambda Data application in a flow step.
2604    LambdaDataApply(LambdaDataApplyNode),
2605    // ── Tier 2 flow steps ──
2606    Probe(ProbeStep),
2607    Reason(ReasonStep),
2608    Validate(ValidateStep),
2609    Refine(RefineStep),
2610    Weave(WeaveStep),
2611    UseTool(UseToolStep),
2612    Remember(RememberStep),
2613    Recall(RecallStep),
2614    Par(ParBlock),
2615    Hibernate(HibernateStep),
2616    Deliberate(DeliberateBlock),
2617    Consensus(ConsensusBlock),
2618    Forge(ForgeBlock),
2619    Focus(FocusStep),
2620    /// v2.65.0 — the proof-carrying derivative step.
2621    Grad(GradStep),
2622    Associate(AssociateStep),
2623    Aggregate(AggregateStep),
2624    ExploreStep(ExploreStepNode),
2625    Ingest(IngestStep),
2626    ShieldApply(ShieldApplyStep),
2627    Stream(StreamBlock),
2628    /// v2.87.0 — `handle E { … } in { … }`, the delimited handler scope.
2629    Handle(HandleBlock),
2630    /// v2.87.0 — `perform Op(args)`. Legal at flow level and inside a step
2631    /// body (where it lands on [`StepNode::performs`], NOT on `pix_ops`: a
2632    /// `pix_op` is an ELEVATION that runs BEFORE generation, and a `perform`
2633    /// whose argument is the step's own output must run AFTER it).
2634    Perform(PerformStep),
2635    /// v2.87.0 — `resume(v)`. Clause bodies only.
2636    Resume(ResumeStep),
2637    /// v2.87.0 — `abort(v)`. Clause bodies only.
2638    Abort(AbortStep),
2639    /// v2.87.0 — `forward Op(args)` (D12). Clause bodies only.
2640    Forward(ForwardStep),
2641    Navigate(NavigateStep),
2642    Drill(DrillStep),
2643    Trail(TrailStep),
2644    Corroborate(CorroborateStep),
2645    OtsApply(OtsApplyStep),
2646    MandateApply(MandateApplyStep),
2647    ComputeApply(ComputeApplyStep),
2648    /// v2.83.0 — `<Agent>(arg, …)`, the step-body invocation of a
2649    /// declared agent. Dispatches v2.83.0's bounded control loop.
2650    AgentCall(AgentCallStep),
2651    Listen(ListenStep),
2652    DaemonStep(DaemonStepNode),
2653    /// v1.6.0 — π-calculus output prefix `c⟨v⟩.P` (Chan-Output / Chan-Mobility).
2654    Emit(EmitStatement),
2655    /// v2.46.0 — `mint <Credential> as <binding>`: ephemeral-credential
2656    /// minting (attenuated, TTL-bounded; `authority_only_attenuates`).
2657    Mint(MintStep),
2658    /// v2.48.0 — `rotate <SecretsStore> [where "…"] with <Tool> as
2659    /// <binding>`: mediated secret renewal (`rotation_without_revelation`).
2660    Rotate(RotateStep),
2661    /// v1.6.0 — capability extrusion (Publish-Ext, paper section 4.3).
2662    Publish(PublishStatement),
2663    /// v1.6.0 — dual of publish (dynamic typed handle import).
2664    Discover(DiscoverStatement),
2665    Persist(PersistStep),
2666    Retrieve(RetrieveStep),
2667    Mutate(MutateStep),
2668    Purge(PurgeStep),
2669    Transact(TransactBlock),
2670    /// v2.43.0 — `warden(<target>) within <Scope> { … }` adversarial
2671    /// security-analysis block. A flow-body block (like `quant`): a target
2672    /// reference + a mandatory `within <Scope>` authorization clause + a nested
2673    /// body (`find_exploits()` → `list[Vulnerability]`, `fortify`). NOT a
2674    /// top-level declaration.
2675    Warden(WardenBlock),
2676    /// v2.4.0 — `quant { … }` cognitive block (Hilbert-space projection).
2677    /// Carries an optional attribute header + a real nested body of flow steps
2678    /// (so v2.4.0's Continuous Type Invariant can scan it). Lives inside a flow
2679    /// body like `par`; NOT a top-level declaration.
2680    Quant(QuantBlock),
2681    /// v2.4.0 — `yield <expr>` measurement point inside a `quant` block.
2682    /// Collapses the evolved amplitudes back to classical silicon; the effect
2683    /// operation whose resolution is a one-shot delimited continuation. Only
2684    /// well-formed inside a `quant` block (the checker rejects it elsewhere).
2685    Yield(YieldStatement),
2686    /// v2.4.0 — `run <Flow>(args)` as a flow-step: invoke a declared flow
2687    /// from inside a body (notably a `daemon`'s `listen` handler — the Q3 ask).
2688    /// Reuses the top-level [`RunStatement`] shape (flow name + args + optional
2689    /// persona/context/anchors). Distinct from `Declaration::Run` only by
2690    /// position (a step inside a body vs. a program-root run).
2691    Run(RunStatement),
2692    /// Flow-level statements we recognize but parse structurally.
2693    GenericStep(GenericFlowStep),
2694}
2695
2696/// A flow step we recognize by keyword but parse only structurally.
2697#[derive(Debug)]
2698pub struct GenericFlowStep {
2699    pub keyword: String,
2700    pub loc: Loc,
2701}
2702
2703// ── Step ─────────────────────────────────────────────────────────────────────
2704
2705/// v2.83.0 — a governance application written INSIDE the step it
2706/// governs: `mandate SECCompliance on data`, `shield PatientShield on symptoms
2707/// -> clean_data`, `ots Extract on raw`.
2708///
2709/// README XV has always written the application in this position — a mandate
2710/// next to the `output:` it constrains, scoped to THIS step's generation — and
2711/// the parser accepted the same form only at flow level, which is why README
2712/// blocks 40–42 never compiled. The AST node is deliberately the same shape as
2713/// the flow-level `*ApplyStep` family: one concept, two positions.
2714#[derive(Debug)]
2715pub struct StepGuardNode {
2716    /// Which primitive: `"mandate"` | `"shield"` | `"ots"`.
2717    pub kind: String,
2718    /// The declared governor this guard names (e.g. `SECCompliance`).
2719    pub name: String,
2720    /// What it is applied to — a binding or a call expression, verbatim
2721    /// (`data`, `ContractDrafter(terms)`). Empty when no `on` clause.
2722    pub target: String,
2723    /// The binding the guarded result flows into (`-> clean_data`). Empty when
2724    /// absent.
2725    pub binding: String,
2726    pub loc: Loc,
2727}
2728
2729#[derive(Debug)]
2730pub struct StepNode {
2731    pub name: String,
2732    pub persona_ref: String,
2733    pub given: String,
2734    pub ask: String,
2735    pub output_type: String,
2736    pub confidence_floor: Option<f64>,
2737    pub navigate_ref: String,
2738    pub apply_ref: String,
2739    /// v2.22.0 — the step's declared MODEL CAPABILITY requirement: the
2740    /// context window (in tokens) the cognitive act needs. The v2.22.0 resolver
2741    /// maps it to the smallest concrete model that satisfies it (per the
2742    /// resolved backend's v2.22.0 catalog); `None` → the backend default
2743    /// (back-compat). Declare the NEED, not the vendor SKU.
2744    pub requires_context: Option<u32>,
2745    /// v2.46.0 — the step's declared cognitive timezone: an IANA name
2746    /// (`"America/Bogota"`, `"UTC"`). When present, the runtime injects the
2747    /// run's captured instant — rendered in THIS zone — into the step's
2748    /// cognitive context (`time_is_an_explicit_input`, the v2.27.0 doctrine
2749    /// applied to cognition). Format-checked at compile time (`axon-T892`);
2750    /// full IANA membership is the runtime's job (chrono-tz, v2.46.0).
2751    /// Overrides a bound `context`'s `now:` for this step. `None` → no
2752    /// temporal injection (back-compat).
2753    pub now_tz: Option<String>,
2754    /// v2.83.0 — the governance applications declared in this
2755    /// step's body, in source order. Empty for every pre-v2.83.0 program.
2756    pub guards: Vec<StepGuardNode>,
2757    /// v2.83.0 — the STATEMENTS written in this step's body, in source
2758    /// order: the PIX verbs (`navigate` / `drill` / `trail` / `validate`)
2759    /// and the step-scoped invocations (`probe … for […]`, `use_tool … with
2760    /// …`, a bare `<Agent>(args)` call, `par { … }`).
2761    ///
2762    /// README's pix/corpus family writes them exactly here, with a braceless
2763    /// field list, and each produces a binding (`as: relevant_sections`) the
2764    /// step's own `ask:` then interpolates. So they are ELEVATIONS, the same
2765    /// shape v2.83.0 gave `lambda`/`ots`: dispatch runs them BEFORE the step's
2766    /// generation. Reusing the flow-level node types (no new AST shapes) is
2767    /// the the design decision doctrine — one concept, two positions.
2768    pub pix_ops: Vec<FlowStep>,
2769    /// v2.83.0 — a `stream<T> { … }` written in THIS step's body.
2770    ///
2771    /// Deliberately NOT a [`Self::pix_ops`] entry, and the distinction is the
2772    /// whole design. Every `pix_ops` statement is an ELEVATION: dispatch runs it
2773    /// BEFORE the step generates, so its binding is available to the step's
2774    /// `ask:`. A stream handler is the opposite — `on_chunk` runs DURING the
2775    /// step's own output, once per chunk, and there is nothing to elevate.
2776    ///
2777    /// Filing it under `pix_ops` would also have produced a specific, silent
2778    /// bug: README block 15's `step Stream` declares no `ask:` at all, so
2779    /// `run_step` would have run the handlers as an elevation and then fallen
2780    /// through to the LLM path with an EMPTY prompt — a real upstream call, made
2781    /// on nothing, once per run. The field is what tells the dispatcher this
2782    /// step's output IS the stream.
2783    pub stream: Option<Box<StreamBlock>>,
2784    /// v2.87.0 — the `perform Op(args)` statements written in THIS step's
2785    /// body, in source order.
2786    ///
2787    /// A THIRD position, and for the same reason v2.83.0 needed a second one.
2788    /// `the design plan` section 3.1 publishes:
2789    ///
2790    /// ```text
2791    /// step generate {
2792    ///     given: prompt
2793    ///     let response = ask "Generate response"
2794    ///     perform Emit(response.token)
2795    ///     perform Done()
2796    /// }
2797    /// ```
2798    ///
2799    /// The performed argument IS the step's own output. Filing these under
2800    /// [`Self::pix_ops`] would run them BEFORE generation, so `response.token`
2801    /// would resolve against a binding that does not exist yet — the handler
2802    /// would receive an unresolved symbol and the wire would carry a name where
2803    /// the adopter expected a token. Dispatch runs `performs` AFTER the step
2804    /// generates, with the step's output in scope.
2805    pub performs: Vec<PerformStep>,
2806    pub loc: Loc,
2807}
2808
2809// ── Intent ───────────────────────────────────────────────────────────────────
2810
2811#[derive(Debug)]
2812pub struct IntentNode {
2813    pub name: String,
2814    pub given: String,
2815    pub ask: String,
2816    pub output_type: Option<TypeExpr>,
2817    pub confidence_floor: Option<f64>,
2818    pub loc: Loc,
2819    /// v1.5.2 — leading comment trivia attached to this declaration
2820    /// (comments preceding the declaration's first token, since the
2821    /// previous declaration or file start). Empty by default.
2822    pub leading_trivia: Vec<crate::tokens::Trivia>,
2823    /// v1.5.2 — trailing comment trivia (same line as the
2824    /// declaration's last effective token). Empty by default.
2825    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2826}
2827
2828// ── Run ──────────────────────────────────────────────────────────────────────
2829
2830#[derive(Debug)]
2831pub struct RunStatement {
2832    pub flow_name: String,
2833    pub arguments: Vec<String>,
2834    pub persona: String,
2835    pub context: String,
2836    pub anchors: Vec<String>,
2837    pub on_failure: String,
2838    pub on_failure_params: Vec<(String, String)>,
2839    pub output_to: String,
2840    pub effort: String,
2841    pub loc: Loc,
2842    /// v1.5.2 — leading comment trivia attached to this declaration
2843    /// (comments preceding the declaration's first token, since the
2844    /// previous declaration or file start). Empty by default.
2845    pub leading_trivia: Vec<crate::tokens::Trivia>,
2846    /// v1.5.2 — trailing comment trivia (same line as the
2847    /// declaration's last effective token). Empty by default.
2848    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2849}
2850
2851// ── Epistemic ────────────────────────────────────────────────────────────────
2852
2853#[derive(Debug)]
2854pub struct EpistemicBlock {
2855    pub mode: String,
2856    pub body: Vec<Declaration>,
2857    pub loc: Loc,
2858    /// v1.5.2 — leading comment trivia attached to this declaration
2859    /// (comments preceding the declaration's first token, since the
2860    /// previous declaration or file start). Empty by default.
2861    pub leading_trivia: Vec<crate::tokens::Trivia>,
2862    /// v1.5.2 — trailing comment trivia (same line as the
2863    /// declaration's last effective token). Empty by default.
2864    pub trailing_trivia: Vec<crate::tokens::Trivia>,
2865}
2866
2867// ── v2.26.0 — the pure expression engine (`Expr`) ─────────────────────────
2868
2869/// A pure, total expression in AXON's closed-catalog expression sublanguage
2870/// (v2.26.0). Evaluates to a value with no side effects, no I/O, no recursion
2871/// and no unbounded loops — so it is decidable and const-foldable. Mounted as
2872/// the condition of an `if` (and, in later steps, `let` values + `where:`
2873/// predicates). Field/index access and the builtin catalog land in v2.26.0.
2874#[derive(Debug, Clone)]
2875pub enum Expr {
2876    /// A typed literal (`42`, `3.14`, `true`, `"hello"`).
2877    Lit(ExprLit),
2878    /// A reference to a binding or dotted path (`x`, `User.tier`).
2879    Ref(String),
2880    /// A unary operation (`-x`, `not x`).
2881    Unary(UnOp, Box<Expr>),
2882    /// A binary operation (`a + b`, `a >= b`, `a and b`).
2883    Binary(BinOp, Box<Expr>, Box<Expr>),
2884    /// v2.26.0 — a closed-catalog builtin call. `args[0]` is the receiver
2885    /// (the value before the `.`); any further entries are the call arguments.
2886    /// E.g. `recent.length` → `Call(Length, [Ref("recent")])`,
2887    /// `name.starts_with("Dr")` → `Call(StartsWith, [Ref("name"), Lit(Str)])`.
2888    Call(Builtin, Vec<Expr>),
2889    /// v2.26.0 — field access on a non-reference base (`items[0].name`,
2890    /// `(expr).field`). A plain dotted path stays a `Ref` (`a.b.c`) for
2891    /// back-compat; this node is the structured form the JSONB SQL lowering
2892    /// (deferred v2.26.0) consumes. The `String` is the field name.
2893    Field(Box<Expr>, String),
2894    /// v2.26.0 — index access `base[index]` (array element / string char).
2895    Index(Box<Expr>, Box<Expr>),
2896    /// v2.83.0 — `let <name> = <value>` scoped over `<body>`: the classic
2897    /// let-in term, `let x = e₁ in e₂`.
2898    ///
2899    /// **Why the expression engine and not a list of bindings on the compute.**
2900    /// Every published `compute` writes a CHAIN —
2901    /// `logic { let a = …  let b = …  return e }` — and the obvious shortcut is
2902    /// to hang a `Vec<(String, Expr)>` off `ComputeDefinition` and substitute at
2903    /// evaluation time. That is wrong twice over: substitution DUPLICATES the
2904    /// bound term at every use site (so `let t = expensive()` evaluates once per
2905    /// mention, changing cost and, for anything non-total, meaning), and it
2906    /// confines `let` to computes when it is a property of expressions.
2907    ///
2908    /// As a `Let` term the chain nests — `Let(a, e₁, Let(b, e₂, e₃))` — which is
2909    /// exactly one evaluation per binding, shadowing that falls out of the
2910    /// nesting instead of being reimplemented, and a `let` usable anywhere an
2911    /// expression is.
2912    Let {
2913        name: String,
2914        value: Box<Expr>,
2915        body: Box<Expr>,
2916    },
2917}
2918
2919/// The closed catalog of pure builtins (v2.26.0). All are total + pure.
2920/// Collection/string predicates only; the predicate-taking folds (`any`/`all`/
2921/// `none`) need lambdas and are deferred, as are `sum`/`min`/`max` and `in`/`??`.
2922#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2923pub enum Builtin {
2924    /// `.length` — collection element count, or character count of a string.
2925    Length,
2926    /// `.count` — alias of `length`.
2927    Count,
2928    /// `.is_empty` — `length == 0`.
2929    IsEmpty,
2930    /// `.is_null` — the value is absent / empty / `null`.
2931    IsNull,
2932    /// `.contains(x)` — array membership, or string substring.
2933    Contains,
2934    /// `.starts_with(s)` — string prefix test.
2935    StartsWith,
2936    /// `.ends_with(s)` — string suffix test.
2937    EndsWith,
2938    /// v2.26.0 — `.as_int` — honest coercion of a `Json` value to an
2939    /// integer. Fail-closed: a value that is not a JSON integer resolves
2940    /// to `null`, never a panic (doctrine `open_data_is_total`).
2941    AsInt,
2942    /// v2.26.0 — `.as_float` — honest coercion to a float (an integer
2943    /// widens; anything else → `null`).
2944    AsFloat,
2945    /// v2.26.0 — `.as_string` — honest coercion to a string (only a
2946    /// JSON string succeeds; a number / bool / null → `null`).
2947    AsString,
2948    /// v2.26.0 — `.as_bool` — honest coercion to a boolean (only a
2949    /// JSON bool succeeds; anything else → `null`).
2950    AsBool,
2951}
2952
2953impl Builtin {
2954    /// The number of arguments AFTER the receiver (`args[0]`).
2955    pub fn extra_arity(self) -> usize {
2956        match self {
2957            Builtin::Length
2958            | Builtin::Count
2959            | Builtin::IsEmpty
2960            | Builtin::IsNull
2961            | Builtin::AsInt
2962            | Builtin::AsFloat
2963            | Builtin::AsString
2964            | Builtin::AsBool => 0,
2965            Builtin::Contains | Builtin::StartsWith | Builtin::EndsWith => 1,
2966        }
2967    }
2968
2969    /// The surface name (after the `.`).
2970    pub fn surface(self) -> &'static str {
2971        match self {
2972            Builtin::Length => "length",
2973            Builtin::Count => "count",
2974            Builtin::IsEmpty => "is_empty",
2975            Builtin::IsNull => "is_null",
2976            Builtin::Contains => "contains",
2977            Builtin::StartsWith => "starts_with",
2978            Builtin::EndsWith => "ends_with",
2979            Builtin::AsInt => "as_int",
2980            Builtin::AsFloat => "as_float",
2981            Builtin::AsString => "as_string",
2982            Builtin::AsBool => "as_bool",
2983        }
2984    }
2985
2986    /// Resolve a name (after a `.`) to a builtin, or `None` if it is an ordinary
2987    /// field / path segment.
2988    pub fn from_name(name: &str) -> Option<Builtin> {
2989        Some(match name {
2990            "length" => Builtin::Length,
2991            "count" => Builtin::Count,
2992            "is_empty" => Builtin::IsEmpty,
2993            "is_null" => Builtin::IsNull,
2994            "contains" => Builtin::Contains,
2995            "starts_with" => Builtin::StartsWith,
2996            "ends_with" => Builtin::EndsWith,
2997            "as_int" => Builtin::AsInt,
2998            "as_float" => Builtin::AsFloat,
2999            "as_string" => Builtin::AsString,
3000            "as_bool" => Builtin::AsBool,
3001            _ => return None,
3002        })
3003    }
3004}
3005
3006/// A literal value inside an [`Expr`]. The lexical form is preserved enough to
3007/// round-trip; the runtime evaluator (v2.26.0) coerces across these per the
3008/// existing string-runtime discipline.
3009#[derive(Debug, Clone)]
3010pub enum ExprLit {
3011    Int(i64),
3012    Float(f64),
3013    Bool(bool),
3014    Str(String),
3015}
3016
3017/// Unary operators (closed catalog).
3018#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3019pub enum UnOp {
3020    /// Arithmetic negation `-`.
3021    Neg,
3022    /// Boolean negation `not`.
3023    Not,
3024}
3025
3026/// Binary operators (closed catalog). Precedence is encoded in the Pratt parser.
3027#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3028pub enum BinOp {
3029    Add,
3030    Sub,
3031    Mul,
3032    Div,
3033    Mod,
3034    Eq,
3035    Ne,
3036    Lt,
3037    Le,
3038    Gt,
3039    Ge,
3040    And,
3041    Or,
3042}
3043
3044// ── Control flow ─────────────────────────────────────────────────────────────
3045
3046#[derive(Debug)]
3047pub struct ConditionalNode {
3048    pub condition: String,
3049    pub comparison_op: String,
3050    pub comparison_value: String,
3051    pub then_body: Vec<FlowStep>,
3052    pub else_body: Vec<FlowStep>,
3053    pub conditions: Vec<(String, String, String)>,
3054    pub conjunctor: String,
3055    /// v2.26.0 — the parsed expression form of the condition. `None` when
3056    /// the condition fits the legacy `(condition, op, value)` + `or` shape
3057    /// (then the legacy fields drive evaluation, byte-identical to pre-v2.26.0);
3058    /// `Some` only for the richer forms the legacy triple cannot express
3059    /// (`and`, `not`, arithmetic, parentheses, nesting), which the runtime
3060    /// evaluates via the pure expression evaluator. Zero IR drift for existing
3061    /// programs.
3062    pub cond: Option<Expr>,
3063    pub loc: Loc,
3064}
3065
3066#[derive(Debug)]
3067pub struct ForInStatement {
3068    pub variable: String,
3069    pub iterable: String,
3070    pub body: Vec<FlowStep>,
3071    pub loc: Loc,
3072}
3073
3074#[derive(Debug)]
3075pub struct LetStatement {
3076    pub identifier: String,
3077    pub value_expr: String,
3078    /// v1.12.0 — preserves the parser's tokenization intent so the
3079    /// runtime dispatcher can distinguish a quoted literal from a
3080    /// dotted-identifier reference. One of "literal", "reference",
3081    /// "expression". Defaults to "literal" so any pre-cycle-17 caller
3082    /// that constructs a LetStatement directly behaves as a literal.
3083    pub value_kind: String,
3084    /// v2.4.0 — optional type annotation `let x: <TypeExpr> = …`.
3085    /// `None` for the bare `let x = …` form (all pre-51.c.3 lets). Inside a
3086    /// `quant` block the Continuous Type Invariant inspects this to enforce the
3087    /// continuous-carrier discipline (`DensityMatrix[D]` D=2ⁿ; reject discrete
3088    /// conversational types). Carries the typed encoder-boundary contract.
3089    pub type_annotation: Option<TypeExpr>,
3090    /// v2.26.0 — the parsed expression form of the value, present only when
3091    /// `value_kind == "expression"` (`let total = price * qty + tax`). The
3092    /// runtime evaluates it via the pure expression evaluator instead of the
3093    /// pre-v2.26.0 behaviour (which treated an expression as an opaque literal
3094    /// string). `None` for literal / reference / list values (byte-identical to
3095    /// pre-v2.26.0).
3096    pub value_ast: Option<Expr>,
3097    pub loc: Loc,
3098    /// v1.5.2 — leading comment trivia attached to this declaration
3099    /// (comments preceding the declaration's first token, since the
3100    /// previous declaration or file start). Empty by default.
3101    pub leading_trivia: Vec<crate::tokens::Trivia>,
3102    /// v1.5.2 — trailing comment trivia (same line as the
3103    /// declaration's last effective token). Empty by default.
3104    pub trailing_trivia: Vec<crate::tokens::Trivia>,
3105}
3106
3107#[derive(Debug)]
3108pub struct ReturnStatement {
3109    pub value_expr: String,
3110    pub loc: Loc,
3111}
3112
3113/// v2.4.0 — `yield <expr>` measurement point inside a `quant` block.
3114#[derive(Debug)]
3115pub struct YieldStatement {
3116    /// The measured expression (the structural hypothesis / density-matrix
3117    /// surrogate collapsed out of the Hilbert-space scope).
3118    pub value_expr: String,
3119    /// Tokenization intent (`literal` / `reference` / `expression`), mirroring
3120    /// `LetStatement.value_kind` so the runtime resolves the yielded value.
3121    pub value_kind: String,
3122    pub loc: Loc,
3123}
3124
3125/// v1.14.0 — `break` keyword inside a for-in body. Carries no
3126/// payload; the runner translates it into a sentinel that
3127/// terminates the loop. Parser scope check (`loop_depth`)
3128/// guarantees this only appears inside a for-in body.
3129#[derive(Debug)]
3130pub struct BreakStatement {
3131    pub loc: Loc,
3132}
3133
3134/// v1.14.0 — `continue` keyword inside a for-in body. Same
3135/// shape as ``BreakStatement``; the runner uses a different
3136/// sentinel type to distinguish loop-exit from iteration-skip.
3137#[derive(Debug)]
3138pub struct ContinueStatement {
3139    pub loc: Loc,
3140}
3141
3142// ── Lambda Data (ΛD) — Epistemic State Vectors ─────────────────────────────
3143
3144/// Top-level ΛD definition: ψ = ⟨T, V, E⟩ where E = ⟨c, τ, ρ, δ⟩.
3145#[derive(Debug)]
3146pub struct LambdaDataDefinition {
3147    pub name: String,
3148    pub ontology: String,             // T ∈ O — ontological type
3149    pub certainty: f64,               // c ∈ [0,1] — epistemic certainty scalar
3150    pub temporal_frame_start: String, // τ_start
3151    pub temporal_frame_end: String,   // τ_end
3152    pub provenance: String,           // ρ ∈ EntityRef — causal origin
3153    pub derivation: String, // δ ∈ Δ — see derivation catalogue (raw, derived, inferred, aggregated, transformed)
3154    pub loc: Loc,
3155    /// v1.5.2 — leading comment trivia attached to this declaration
3156    /// (comments preceding the declaration's first token, since the
3157    /// previous declaration or file start). Empty by default.
3158    pub leading_trivia: Vec<crate::tokens::Trivia>,
3159    /// v1.5.2 — trailing comment trivia (same line as the
3160    /// declaration's last effective token). Empty by default.
3161    pub trailing_trivia: Vec<crate::tokens::Trivia>,
3162}
3163
3164/// In-flow ΛD application: binds epistemic state vector to a data target.
3165#[derive(Debug)]
3166pub struct LambdaDataApplyNode {
3167    pub lambda_data_name: String, // reference to LambdaDataDefinition
3168    pub target: String,           // expression to bind
3169    pub output_type: String,      // result type after epistemic binding
3170    pub loc: Loc,
3171}
3172
3173// ── Tier 2 flow step nodes ──────────────────────────────────────────────────
3174
3175#[derive(Debug)]
3176pub struct ProbeStep {
3177    pub target: String,
3178    /// v2.83.0 — the extraction list README writes:
3179    /// `probe doc for [parties, obligations, dates]`. Pre-v2.83.0 the step
3180    /// body reached `probe` and ran `skip_flow_step_structural`, which
3181    /// DISCARDED it (the v2.67.0 silent-drop shape); the flow-level form kept
3182    /// only the target and never had a slot for the fields at all.
3183    pub fields: Vec<String>,
3184    pub loc: Loc,
3185}
3186/// v2.83.0 — `reason { given: … ask: "…" depth: N }`, the README's
3187/// most-published cognitive block (16 occurrences) and, until this cycle, the
3188/// most expensive silent drop in the language.
3189///
3190/// **What was wrong.** The block form had NO home in this struct: `strategy`
3191/// and `target` were its only fields. Written at flow level, `reason { … }`
3192/// did not parse at all (the parser wanted `reason <target>`); written inside a
3193/// `step { }` body — the only place the README ever writes it — it hit
3194/// `skip_flow_step_structural`, which threw the whole block away. Measured on
3195/// 2.85.0: a step whose ENTIRE cognition was a `reason { given ask depth }`
3196/// block passed `axon check` with exit 0 and lowered to `"ask": ""`,
3197/// `"given": ""`. `advertised.rs` attested `reason` as
3198/// `Real { proof: "pure_shape::run_reason" }` — and the attestation was true
3199/// of an engine no published program could reach. v2.67.0's own words: motor
3200/// real, cable muerto.
3201///
3202/// The field set is CLOSED (v2.83.0's rule: when a block skips what it does
3203/// not recognise, ask which direction the silence fails in — a typo'd `ask:`
3204/// yields a promptless deliberation, which is weaker, not louder).
3205#[derive(Debug)]
3206pub struct ReasonStep {
3207    /// `chain_of_thought: enabled` and `strategy: <name>` both land here.
3208    pub strategy: String,
3209    /// The pre-v2.83.0 positional form `reason <target>`. Empty for the
3210    /// block form, which names its evidence in `given` instead.
3211    pub target: String,
3212    /// `given:` — the evidence this deliberation reasons OVER. One reference,
3213    /// a comma list (`given: Initialize.output, sessions`) or a bracketed list
3214    /// (`given: [baseline.topology, current.topology]`); all three forms occur
3215    /// in the published README. Resolved against the flow bindings at dispatch.
3216    pub given: String,
3217    /// `ask:` — the question. This is the deliberation's actual prompt; before
3218    /// v2.83.0 it reached the model in exactly zero published programs.
3219    pub ask: String,
3220    /// `depth:` — the declared deliberation depth. Consumed by the dispatch
3221    /// FRAMING (like `strategy`, the other declared-posture field), not by a
3222    /// runtime iteration bound. Stated plainly so the field is not read as a
3223    /// loop count it has never been.
3224    pub depth: Option<u32>,
3225    pub loc: Loc,
3226}
3227#[derive(Debug)]
3228pub struct ValidateStep {
3229    pub target: String,
3230    pub rule: String,
3231    /// v2.88.0 — `if confidence < 0.8 -> refine(max_attempts: 2)`, ATTACHED
3232    /// to the validation it governs.
3233    ///
3234    /// The guard is a field of the `validate` rather than a sibling statement,
3235    /// and the difference is what makes `confidence` unambiguous BY
3236    /// CONSTRUCTION. As a sibling, "which confidence does this guard read?"
3237    /// needs a resolution rule (nearest preceding validate), a compile error
3238    /// for the zero case, and dispatch-side re-pairing — three places to
3239    /// drift. As a field there is exactly one validation it can mean, the
3240    /// pairing survives into the IR untouched, and a guard with no validation
3241    /// is UNREPRESENTABLE rather than refused.
3242    pub guard: Option<ConfidenceGuard>,
3243    pub loc: Loc,
3244}
3245
3246/// v2.88.0 — the self-correction guard three README blocks publish:
3247///
3248/// ```text
3249/// validate Assess.output against: ContractSchema
3250/// if confidence < 0.8 -> refine(max_attempts: 2)
3251/// ```
3252///
3253/// NOT control flow. It has no `else`, no braced body, no nesting; the metric,
3254/// the comparison and the action are each a CLOSED catalog of one. What it
3255/// declares is a floor and a bounded recovery: *if the validation's CSR is
3256/// below `threshold`, refine the validated value — at most `max_attempts`
3257/// times — re-scoring each attempt.* Landing it as a guard keeps "no
3258/// imperative branching inside a step body" true by construction while the
3259/// published surface compiles verbatim.
3260#[derive(Debug)]
3261pub struct ConfidenceGuard {
3262    /// The floor. The type-checker requires `0 < threshold ≤ 1`: the CSR lives
3263    /// in `[0, 1]`, so a floor of 0 can never fire (dead governance that reads
3264    /// as live) and a floor above 1 always fires (a retry loop disguised as a
3265    /// conditional). Both are refused, not warned.
3266    pub threshold: f64,
3267    /// Bound on recovery attempts. Required by the grammar itself — the
3268    /// published form always carries it — and the type-checker refuses 0 (a
3269    /// guard that promises recovery and performs none). Termination is by
3270    /// construction: attempts strictly increase toward this bound.
3271    pub max_attempts: u32,
3272    pub loc: Loc,
3273}
3274#[derive(Debug)]
3275pub struct RefineStep {
3276    pub target: String,
3277    pub strategy: String,
3278    pub loc: Loc,
3279}
3280/// v2.83.0 — `weave [a, b] format: T include: [x, y]`, the synthesis
3281/// statement the README closes fourteen of its examples with.
3282///
3283/// **What was wrong.** The parser accepted only the BRACED field form
3284/// (`weave { sources: [...] format: T }`), which the README never writes. The
3285/// published bracket form fell into `skip_flow_step_structural` — and that
3286/// skipper stops at the first `output` KEYWORD it meets, so
3287/// `weave [A.output, B.output]` left the parser mid-list and the step then
3288/// failed with `Expected Colon` pointing at the comma. A silent drop that also
3289/// mislocated its own error.
3290#[derive(Debug)]
3291pub struct WeaveStep {
3292    pub sources: Vec<String>,
3293    pub target: String,
3294    pub format_type: String,
3295    pub priority: Vec<String>,
3296    pub style: String,
3297    /// v2.83.0 — `include: [summary, risks, recommendations]`: the parts
3298    /// the synthesis must contain. Published in twelve of the fourteen README
3299    /// weaves and, until this cycle, had no slot at any position. Consumed by
3300    /// the dispatch framing, like `priority` and `style`.
3301    pub include: Vec<String>,
3302    pub loc: Loc,
3303}
3304/// v2.8.0 — the closed catalog of `use <Tool>` argument forms. The
3305/// invocation surfaces are mutually exclusive, so a sum type models them
3306/// exactly (no ambiguous dual-empty state). NOTE: `apply: Tool given: <struct>`
3307/// (the splat form) is NOT here — it rides `StepNode.apply_ref` and is
3308/// validated against the tool schema in v2.8.0, not parsed as a `use`.
3309#[derive(Debug, Clone, PartialEq)]
3310pub enum UseArgs {
3311    /// `use Tool on "${arg}"` / `use Tool on query` — the v2.7.0 single
3312    /// positional argument. D5 back-compat: behaves byte-identically to the
3313    /// pre-58 `argument: String` (empty string when no `on` clause).
3314    LegacyPositional(String),
3315    /// `use Tool(query = "${q}", max_results = 5)` — D2 canonical multi-field
3316    /// keyword args. Each entry is `(name, value, value_kind)`: `value` is the
3317    /// expression STRING (the frontend has no structured `Expr`; mirrors
3318    /// `argument` / `parse_argument_list`); `value_kind` is `"literal"` or
3319    /// `"reference"` — the v2.10.0 classification from `parse_let_atom`, so the
3320    /// runtime resolves a bare identifier / `Step.output` as a binding lookup
3321    /// (like `let`) instead of passing the name literally. The type-checker
3322    /// (v2.8.0 + v2.10.0) validates each entry against the tool's declared input
3323    /// schema (W2 / CT-2 caller blame) and references against their source.
3324    Named(Vec<(String, String, String)>),
3325}
3326
3327impl UseArgs {
3328    /// v2.8.0 transitional — the legacy single-arg string for the IR `argument`
3329    /// field (still `String` until v2.8.0 carries structured named args).
3330    /// `Named` projects an empty argument here; the type-checker validates
3331    /// named args from the AST, and v2.8.0 wire their structured dispatch.
3332    pub fn legacy_argument(&self) -> String {
3333        match self {
3334            UseArgs::LegacyPositional(s) => s.clone(),
3335            UseArgs::Named(_) => String::new(),
3336        }
3337    }
3338}
3339
3340#[derive(Debug)]
3341pub struct UseToolStep {
3342    pub tool_name: String,
3343    pub args: UseArgs,
3344    pub loc: Loc,
3345}
3346#[derive(Debug)]
3347pub struct RememberStep {
3348    pub expression: String,
3349    pub memory_target: String,
3350    pub loc: Loc,
3351}
3352#[derive(Debug)]
3353pub struct RecallStep {
3354    pub query: String,
3355    pub memory_source: String,
3356    pub loc: Loc,
3357}
3358#[derive(Debug)]
3359pub struct ParBlock {
3360    /// v2.15.0 — the concurrent branches. Each top-level statement inside
3361    /// `par { … }` is one branch (a single-statement body); they execute
3362    /// concurrently at runtime. Empty for a `par {}` with no statements
3363    /// (degenerate no-op). Before v2.15.0 this was payload-free (the branches were
3364    /// skipped at parse time), so `par` ran as a stub.
3365    pub branches: Vec<Vec<FlowStep>>,
3366    pub loc: Loc,
3367}
3368#[derive(Debug)]
3369pub struct HibernateStep {
3370    pub event_name: String,
3371    pub timeout: String,
3372    pub loc: Loc,
3373}
3374#[derive(Debug)]
3375pub struct DeliberateBlock {
3376    pub loc: Loc,
3377}
3378#[derive(Debug)]
3379pub struct ConsensusBlock {
3380    pub loc: Loc,
3381}
3382/// v2.41.0 — `forge <Name>(seed: <string>) -> <Type> { mode:, novelty:,
3383/// depth:, branches:, constraints: }` — Directed Creative Synthesis. A
3384/// flow-body block that runs the Poincaré-Hadamard four-phase creative process
3385/// (Preparation → Incubation → Illumination → Verification) under a **measured,
3386/// fail-closed novelty guarantee**: the returned typed value must
3387/// clear a Normalized-Compression-Distance novelty floor against the obvious
3388/// baseline AND its `constraints:` anchor, or the forge fails structurally.
3389///
3390/// Before v2.41.0 this was a no-op stub (`{ loc }` only, body discarded). v2.41.0 makes
3391/// the README's long-standing claim true.
3392#[derive(Debug, Default)]
3393pub struct ForgeBlock {
3394    /// The synthesis name (`forge Artwork(...)` → `"Artwork"`).
3395    pub name: String,
3396    /// The creative seed — the conceptual starting point (`seed: "..."`).
3397    pub seed: String,
3398    /// The declared output type (`-> Visual` → `"Visual"`).
3399    pub output_type: String,
3400    /// Boden creativity mode (closed catalog: `combinatorial | exploratory |
3401    /// transformational`, `axon-T868`). Empty ⇒ defaults to `exploratory`.
3402    pub mode: String,
3403    /// Novelty target `[0.0, 1.0]` (`axon-T869`) — sets the fail-closed novelty
3404    /// floor and blends the incubation temperature. Default 0.5.
3405    pub novelty: f64,
3406    /// Incubation iterations (`depth ≥ 1`, `axon-T870`). Default 1.
3407    pub depth: i64,
3408    /// Illumination parallel branches (best-of-N, `branches ≥ 1`, `axon-T870`).
3409    /// Default 1.
3410    pub branches: i64,
3411    /// Optional `constraints:` reference to a declared `anchor` (`axon-T871`) —
3412    /// the verification predicate + coherence floor. Empty ⇒ novelty-floor-only
3413    /// verification.
3414    pub constraints_ref: String,
3415    pub loc: Loc,
3416}
3417#[derive(Debug)]
3418pub struct FocusStep {
3419    /// v2.63.0 — the declared dataspace this σ∘π reads (the field
3420    /// keeps its historical name; T930 requires it to resolve to a
3421    /// `dataspace` symbol).
3422    pub expression: String,
3423    /// v2.63.0 — the data-plane `where:` clause (the v1.30.0 closed
3424    /// filter grammar, shared with retrieve/navigate — the design decision). Empty
3425    /// ⇒ no filter. Validated fail-closed at dispatch, like retrieve.
3426    pub where_expr: String,
3427    /// v2.63.0 — π: the projected columns (empty ⇒ all).
3428    pub select: Vec<String>,
3429    /// v2.63.0 — the binding name for the result (`as:`). Empty ⇒
3430    /// the dataspace name.
3431    pub output: String,
3432    pub loc: Loc,
3433}
3434/// v2.65.0 — `grad <letName> wrt <x> [as <name>]`: differentiate the
3435/// EXPRESSION a prior rich `let` bound (its AST rides the IR), at compile
3436/// time, symbolically. The derivative is checked (T931/T932), simplified,
3437/// and stored in the IR — a proof-carrying artifact, re-derived at deploy.
3438#[derive(Debug)]
3439pub struct GradStep {
3440    /// The prior rich `let` whose expression is differentiated.
3441    pub target: String,
3442    /// The variables to differentiate against (`wrt x` / `wrt [x, y]`).
3443    pub wrt: Vec<String>,
3444    /// Result binding (`as:`). Empty ⇒ `d_<target>`.
3445    pub output: String,
3446    pub loc: Loc,
3447}
3448
3449#[derive(Debug)]
3450pub struct AssociateStep {
3451    pub left: String,
3452    pub right: String,
3453    pub using_field: String,
3454    /// v2.63.0 — result binding name (`as:`). Empty ⇒ `<L>_<R>`.
3455    pub output: String,
3456    pub loc: Loc,
3457}
3458#[derive(Debug)]
3459pub struct AggregateStep {
3460    pub target: String,
3461    pub group_by: Vec<String>,
3462    pub alias: String,
3463    /// v2.63.0 — the closed aggregate catalog entries
3464    /// (`count` | `count(col)` | `sum(col)` | `avg(col)` | `min(col)` |
3465    /// `max(col)`), kept RAW here; T930 validates shape + columns.
3466    pub compute: Vec<String>,
3467    /// v2.63.0 — data-plane `where:`. Empty ⇒ no filter.
3468    pub where_expr: String,
3469    pub loc: Loc,
3470}
3471#[derive(Debug)]
3472pub struct ExploreStepNode {
3473    pub target: String,
3474    pub limit: Option<i64>,
3475    /// v2.63.0 — result binding name (`as:`). Empty ⇒ the target.
3476    pub output: String,
3477    pub loc: Loc,
3478}
3479#[derive(Debug)]
3480pub struct IngestStep {
3481    pub source: String,
3482    pub target: String,
3483    /// v2.63.0 — the declared wire format of the source bytes
3484    /// (closed catalog: `csv` | `json`). Kept RAW at parse; the v2.63.0
3485    /// type-checker requires it and validates it (`axon-T929`) — an
3486    /// ingest that does not declare what it is parsing is refused.
3487    pub format: String,
3488    /// v2.63.0 — bounds enforced on the RAW byte stream BEFORE any
3489    /// parsing (the v2.54.0 discipline). `None` ⇒ the engine's conservative
3490    /// defaults apply (bounded by default, never unbounded).
3491    pub max_bytes: Option<u64>,
3492    pub max_rows: Option<u64>,
3493    pub loc: Loc,
3494}
3495#[derive(Debug)]
3496pub struct ShieldApplyStep {
3497    pub shield_name: String,
3498    pub target: String,
3499    pub output_type: String,
3500    pub loc: Loc,
3501}
3502/// v1.29.0 / v2.67.0 / **v2.83.0** — `stream<T> { on_chunk … on_complete … }`.
3503///
3504/// The body used to NOT EXIST. `parse_block_step` — shared with `deliberate`,
3505/// `consensus` and (pre-retraction) `transact` — called `skip_braced_block()`
3506/// and threw the block's contents away at PARSE time. The handler was not a
3507/// no-op because someone forgot to implement it; it was a no-op because the
3508/// body never reached the AST for anything to execute. Four advertised
3509/// primitives died in that one function.
3510///
3511/// **v2.83.0 — and v2.67.0 closed that with the WRONG SHAPE.** It gave the block a
3512/// `body: Vec<FlowStep>`, which no published block and no paper writes. The
3513/// specified surface — `the design plan` section 3.7, whose D8
3514/// promises *"backward compat for `stream<τ>` 100%, cero cambios en `.axon`
3515/// source files de adopters"* — is `stream<T> { on_chunk: B₁ on_complete: B₂ }`,
3516/// and README block 15 publishes exactly that. Measured before this landed:
3517///
3518///   * at FLOW level the published body was a hard parse error
3519///     (`Unexpected token in flow body: 'on_chunk'`);
3520///   * in a STEP body the whole block was silently discarded by
3521///     `skip_flow_step_structural`, so block 15's `step Stream` reached the
3522///     dispatcher with `pix_ops=0`, `ask=""`, `output=""` — an EMPTY step, whose
3523///     `Stream.output` the next step then reasoned over.
3524///
3525/// So v2.67.0's attestation was the v2.83.0 `reason` defect one more time: a real
3526/// engine behind a grammar no adopter could write. `body` is KEPT (it parses, it
3527/// lowers, it runs, and removing it would break any program written against
3528/// v2.67.0), but it is no longer the primitive's published face.
3529#[derive(Debug)]
3530pub struct StreamBlock {
3531    /// The `<T>` in `stream<T>` — the CHUNK type. Empty when the block is
3532    /// written without one.
3533    ///
3534    /// It used to be discarded silently: `parse_stream_block`'s "tolerate the
3535    /// pre-111 form" loop advanced to the first `{`, eating `<QuoteData>` on the
3536    /// way. A type parameter consumed by nothing is the v2.67.0 defect, so it is
3537    /// captured here and type-checked at the handler boundary.
3538    pub chunk_type: String,
3539    /// `on_chunk: { … }` — run ONCE PER CHUNK, with the chunk bound under
3540    /// `chunk`. `None` when the handler is absent.
3541    ///
3542    /// It is a [`StepNode`], not a `Vec<FlowStep>`, because the published arm
3543    /// body is a STEP body and not a flow body: block 15 writes
3544    /// `on_chunk: { probe chunk for […] output: QuoteSnapshot }`, and `output:`
3545    /// is a step field that has no flow-level position at all. Sharing the shape
3546    /// means the arm reuses `run_step` — the design decision's "one concept, two positions",
3547    /// so there is no second dispatch implementation to drift.
3548    pub on_chunk: Option<StepNode>,
3549    /// `on_complete: { … }` — run ONCE, after the source closes, with the
3550    /// accumulated stream bound under `complete`. `None` when absent.
3551    pub on_complete: Option<StepNode>,
3552    /// v2.83.0 — `on_error: { … }` — run when the SOURCE fails, with the
3553    /// failure bound under `error`.
3554    ///
3555    /// It handles a failure of the **producer**, never a failure of the author's
3556    /// own handlers. If `on_chunk` panics its way to a dispatch error, that is a
3557    /// bug in the program, and routing it here would let a broken handler
3558    /// silently catch itself and report the stream as healthy. Cancellation is
3559    /// not a failure either — a cancelled stream propagates as cancelled.
3560    ///
3561    /// When present and the source fails, the step COMPLETES with this arm's
3562    /// output: the author declared what to do, so the recovery is explicit
3563    /// rather than a swallowed error. When absent, the failure propagates.
3564    pub on_error: Option<StepNode>,
3565    /// v2.67.0's body form: `stream { <steps> }`. Executed in order; each
3566    /// one's fragments are emitted on the flow's event channel as produced.
3567    /// Retained for compatibility — see the type-level note above.
3568    pub body: Vec<FlowStep>,
3569    pub loc: Loc,
3570}
3571// ── v2.87.0 — algebraic effects (Plotkin/Pretnar) ─────────────────────────
3572//
3573// The four constructs `the design plan` section 3.6/section 3.7 fixes: a top-level `effect`
3574// declaration, `perform` in a step or flow body, `handle … in …` in a flow
3575// body, and `resume()` / `abort()` / `forward` inside a handler clause.
3576//
3577// ⚠️ These are NOT the `Instruction` types in `axon-rs/src/effects/ir.rs`.
3578// That module is a self-contained FSM over a JSON instruction alphabet whose
3579// catch-all variant (`Instruction::Passthrough`, `#[serde(other)]`) is INERT —
3580// lowering a handler body onto it would make every non-effect node in the body
3581// a no-op, which is precisely the v2.67.0 defect this cycle exists not to repeat.
3582// the design decision: the effect machine is the DISPATCHER, and the instruction alphabet is
3583// `IRFlowNode`, so a handler clause can `emit`, `use` a tool or `persist` like
3584// any other body. See `the design plan`.
3585
3586/// `effect SSE { Emit(token: Token) -> Unit  Done() -> Never }` — a top-level
3587/// declaration, a peer of `tool` / `persona` / `anchor` per `the design plan` section 3.1.
3588///
3589/// The declaration is what makes the operation catalog CLOSED. the design decision resolves
3590/// a bare `perform Emit(x)` against exactly this set: one declarer ⇒ resolved,
3591/// two ⇒ a compile error naming both, zero ⇒ a compile error. Without the
3592/// declaration there is no catalog and `effect_name` would have to be guessed.
3593#[derive(Debug)]
3594pub struct EffectDefinition {
3595    pub name: String,
3596    pub operations: Vec<EffectOperation>,
3597    pub loc: Loc,
3598    /// v1.5.2 — leading comment trivia attached to this declaration.
3599    pub leading_trivia: Vec<crate::tokens::Trivia>,
3600    /// v1.5.2 — trailing comment trivia.
3601    pub trailing_trivia: Vec<crate::tokens::Trivia>,
3602}
3603
3604/// One operation inside an `effect` declaration: `Emit(token: Token) -> Unit`.
3605#[derive(Debug)]
3606pub struct EffectOperation {
3607    pub name: String,
3608    pub parameters: Vec<Parameter>,
3609    /// The declared return type. `Never` is the bottom sentinel `the design plan` section 3.1
3610    /// writes on `Done() -> Never` — an operation whose handler is not expected
3611    /// to `resume`. Empty when the source omits `-> T`.
3612    pub return_type: String,
3613    pub loc: Loc,
3614}
3615
3616/// `handle SSE { Emit(token) -> { … } } in { … }` — the delimited handler
3617/// scope (D3: an effect is interceptable only inside `body`).
3618#[derive(Debug)]
3619pub struct HandleBlock {
3620    /// `handle E1, E2 { … }` — the effects this frame intercepts. More than one
3621    /// is legal; `IRHandlerFrame.effect_names` in the cycle-23 IR is a `Vec` for
3622    /// the same reason.
3623    pub effect_names: Vec<String>,
3624    pub clauses: Vec<HandlerClause>,
3625    /// The `in { … }` block. Ordinary flow steps — this is what the design decision buys.
3626    pub body: Vec<FlowStep>,
3627    pub loc: Loc,
3628}
3629
3630/// One clause of a [`HandleBlock`]: `Emit(token) -> { … }`.
3631#[derive(Debug)]
3632pub struct HandlerClause {
3633    pub operation_name: String,
3634    /// The clause's binders. `perform Emit(x)`'s argument is bound under the
3635    /// clause's parameter name for the duration of the clause body — the same
3636    /// discipline `EffectRuntime::dispatch_clause_for` uses (save, bind,
3637    /// restore), so a clause cannot leak a binding into its continuation.
3638    pub parameter_names: Vec<String>,
3639    pub body: Vec<FlowStep>,
3640    pub loc: Loc,
3641}
3642
3643/// `perform Emit(x)` (bare) or `perform SSE.Emit(x)` (qualified).
3644///
3645/// the design decision accepts both. `effect_name` is `None` for the bare form as written;
3646/// the IR generator resolves it against the declared catalog and the
3647/// type-checker refuses an ambiguous or unknown operation with the offending
3648/// location. The bare form is what `the design plan` section 3.1 publishes, and under v2.83.0's
3649/// doctrine the published surface is the promise.
3650#[derive(Debug)]
3651pub struct PerformStep {
3652    pub effect_name: Option<String>,
3653    pub operation_name: String,
3654    /// Argument expressions, verbatim source text. The cycle-23 IR carries
3655    /// `arguments: Vec<String>` for the same reason: resolution against the
3656    /// live bindings is a RUNTIME act, and pre-resolving here would freeze a
3657    /// value the enclosing step has not produced yet.
3658    pub arguments: Vec<String>,
3659    pub loc: Loc,
3660}
3661
3662/// `resume()` / `resume(value)` — invoke the captured one-shot continuation.
3663/// Legal only inside a handler clause body (D2, and the parser enforces it).
3664#[derive(Debug)]
3665pub struct ResumeStep {
3666    /// The resumed value, verbatim. Empty ⇒ `resume()` ⇒ Unit.
3667    pub value_expr: String,
3668    pub loc: Loc,
3669}
3670
3671/// `abort()` / `abort(value)` — terminate the enclosing `handle` without
3672/// resuming. The continuation is dropped, never invoked.
3673#[derive(Debug)]
3674pub struct AbortStep {
3675    pub value_expr: String,
3676    pub loc: Loc,
3677}
3678
3679/// `forward Emit(t)` / `forward SSE.Emit(t)` (D12) — propagate the operation to
3680/// the next OUTER frame, bypassing this one. What makes a handler a decorator
3681/// rather than a terminator.
3682#[derive(Debug)]
3683pub struct ForwardStep {
3684    pub effect_name: Option<String>,
3685    pub operation_name: String,
3686    pub arguments: Vec<String>,
3687    pub loc: Loc,
3688}
3689
3690#[derive(Debug)]
3691pub struct NavigateStep {
3692    /// v2.83.0 — per-navigation `depth:` override (README's pix family
3693    /// writes it inline). `None` ⇒ the navigator's bounded-rationality
3694    /// default. Threaded into `NavConfig.d_max` at dispatch, so this field
3695    /// DECIDES something — adding one consumed by nothing would be the v2.67.0
3696    /// defect this cycle exists to end.
3697    pub depth: Option<i64>,
3698    pub pix_name: String,
3699    pub corpus_name: String,
3700    pub query_expr: String,
3701    pub trail_enabled: bool,
3702    pub output_name: String,
3703    /// v2.13.0 — for MDN corpus-graph navigation: the seed document `from:`
3704    /// to start the ε-informative traversal. Empty for PIX tree navigation.
3705    pub seed: String,
3706    /// v2.13.0 — for MDN: the `budget:` (max documents). `None` = default.
3707    pub budget: Option<i64>,
3708    /// v2.17.0 (Q2) — optional column-scope filter (`where:`) for a
3709    /// `corpus from axonstore`. A raw filter expr (same shape as `retrieve …
3710    /// where`) pushed to the SELECT sourcing the corpus rows, so an adopter
3711    /// multiplexing sub-tenants in one axon-tenant via a column can scope the
3712    /// MDN graph to a single sub-tenant. Empty = no column filter (RLS-only).
3713    pub where_expr: String,
3714    pub loc: Loc,
3715}
3716#[derive(Debug)]
3717pub struct DrillStep {
3718    pub pix_name: String,
3719    pub subtree_path: String,
3720    pub query_expr: String,
3721    pub output_name: String,
3722    pub loc: Loc,
3723}
3724#[derive(Debug)]
3725pub struct TrailStep {
3726    pub navigate_ref: String,
3727    pub loc: Loc,
3728}
3729#[derive(Debug)]
3730pub struct CorroborateStep {
3731    pub navigate_ref: String,
3732    pub output_name: String,
3733    pub loc: Loc,
3734}
3735#[derive(Debug)]
3736pub struct OtsApplyStep {
3737    pub ots_name: String,
3738    pub target: String,
3739    pub output_type: String,
3740    pub loc: Loc,
3741}
3742#[derive(Debug)]
3743pub struct MandateApplyStep {
3744    pub mandate_name: String,
3745    pub target: String,
3746    pub output_type: String,
3747    pub loc: Loc,
3748}
3749/// v2.83.0 — `<Agent>(arg, …)` written as a step-body statement: the
3750/// form the README uses in every one of its agent examples, and the last piece
3751/// that makes v2.83.0's executor reachable from source.
3752///
3753/// It is a distinct node rather than a reuse of [`ComputeApplyStep`] because
3754/// the two are opposites: a `compute` is a PURE function with no model in the
3755/// loop and no budget, and an agent is a bounded deliberation that spends. A
3756/// shared node would invite a shared handler, and the first person to add a
3757/// field would have to decide which of the two it meant.
3758#[derive(Debug)]
3759pub struct AgentCallStep {
3760    /// The declared `agent` being invoked. A NAME — never dotted.
3761    pub agent_name: String,
3762    /// Positional arguments, each a v2.83.0 SUBJECT (a dotted reference or a
3763    /// literal). README writes `TrendAnalyzer(Gather.output)`.
3764    pub arguments: Vec<String>,
3765    pub loc: Loc,
3766}
3767#[derive(Debug)]
3768pub struct ComputeApplyStep {
3769    pub compute_name: String,
3770    pub arguments: Vec<String>,
3771    pub output_name: String,
3772    pub loc: Loc,
3773}
3774/// v1.6.0 D4 — dual-mode listen.
3775///
3776/// `channel_is_ref = true` ⇒ `channel` is the name of a declared
3777/// `ChannelDefinition` (canonical v1.6.0 form). `false` ⇒ legacy
3778/// string topic (deprecated; type checker emits a warning).
3779#[derive(Debug)]
3780pub struct ListenStep {
3781    pub channel: String,
3782    pub channel_is_ref: bool,
3783    pub event_alias: String,
3784    /// v2.4.0 — the handler body: real flow-steps executed on each event /
3785    /// scheduled tick. Pre-v2.4.0 the `{ … }` block was `skip_braced_block`'d
3786    /// (the listener was inert); now it is parsed so a `daemon` can run logic
3787    /// (e.g. `run <Flow>(…)`) per trigger. Empty for a bodyless `listen`.
3788    pub body: Vec<FlowStep>,
3789    pub loc: Loc,
3790}
3791#[derive(Debug)]
3792pub struct DaemonStepNode {
3793    pub daemon_ref: String,
3794    pub loc: Loc,
3795}
3796#[derive(Debug)]
3797pub struct PersistStep {
3798    pub store_name: String,
3799    /// v1.30.0 — the `{ col: value }` field block. Empty when the
3800    /// step is written without a block (`persist <store>`), in which
3801    /// case the runtime falls back to writing the flow's user
3802    /// bindings as a row (backward-compatible with v1.30.0).
3803    pub fields: Vec<(String, String)>,
3804    pub loc: Loc,
3805}
3806#[derive(Debug)]
3807pub struct RetrieveStep {
3808    pub store_name: String,
3809    pub where_expr: String,
3810    pub alias: String,
3811    /// v2.21.0 — optional `order_by:` clause: a closed
3812    /// comma-separated list of `column [asc|desc]` (same identifier
3813    /// discipline as `where:` columns — no injection). Empty = no
3814    /// ordering. Raw string, parsed + validated by the runtime
3815    /// (`filter::render_bounds`) and at `axon check` (v1.31.0 `axon-T807`).
3816    pub order_by: String,
3817    /// v2.21.0 — optional `limit:` clause: a `u32` literal OR a
3818    /// `${binding}` resolved to a `u32` at runtime. Empty = no limit.
3819    /// Raw string (`"100"` or `"${max}"`), validated at `axon check`
3820    /// (v1.31.0 `axon-T808`).
3821    pub limit_expr: String,
3822    /// v2.33.0 — optional `aggregate:` clause: a member of the CLOSED
3823    /// catalog `count` | `sum(<col>)` | `avg(<col>)` | `min(<col>)` |
3824    /// `max(<col>)`. Empty = a plain `SELECT *` retrieve. Raw string,
3825    /// parsed + validated by the runtime (`filter::parse_aggregate_clause`)
3826    /// and at `axon check` (v2.33.0 `axon-T843`/`T844`/`T845`).
3827    pub aggregate: String,
3828    /// v2.33.0 — optional `group_by:` clause: a comma-separated list
3829    /// of column identifiers (same discipline as `order_by:` columns).
3830    /// Requires an `aggregate:`. Empty = no grouping.
3831    pub group_by: String,
3832    /// v2.40.0 — optional `cache:` reference. A `retrieve` reads a store
3833    /// (a `storage` effect — never `pure`), so caching it is always a WIDENING
3834    /// that accepts staleness: the named `cache` MUST carry a finite `ttl:`
3835    /// (`axon-T865`) and typically an `invalidate_on:`. Names a declared
3836    /// `cache` (`axon-T864`); empty = uncached. Never governed by a
3837    /// `default: true` policy (defaults only auto-cover provably-`pure` tools).
3838    pub cache: String,
3839    pub loc: Loc,
3840}
3841#[derive(Debug)]
3842pub struct MutateStep {
3843    pub store_name: String,
3844    pub where_expr: String,
3845    /// v1.30.0 — the `{ col: value }` SET assignments. Empty when
3846    /// the step declares no columns, in which case the runtime falls
3847    /// back to writing the flow's user bindings as the `SET` clause
3848    /// (backward-compatible with v1.31.0).
3849    pub fields: Vec<(String, String)>,
3850    pub loc: Loc,
3851}
3852#[derive(Debug)]
3853pub struct PurgeStep {
3854    pub store_name: String,
3855    pub where_expr: String,
3856    pub loc: Loc,
3857}
3858#[derive(Debug)]
3859pub struct TransactBlock {
3860    pub loc: Loc,
3861}
3862
3863/// v2.43.0 — `scope <Name> { targets:, depth:, approver: }` — the
3864/// authorization scope a `warden` block runs `within`. The load-bearing safety
3865/// construct (paper section 5.2): it declares which resources may be analysed
3866/// (`targets` allowlist), how invasively (`depth` ceiling), and who authorised
3867/// it (`approver` capability). A `warden` with no resolvable in-scope
3868/// authorization does not compile (fail-closed). Named + referenced, like
3869/// `cache`/`cors`. **Unknown fields are a hard parse error**: a scope
3870/// governs an offensive-capable analysis, so a typo can never silently widen it.
3871#[derive(Debug, Default)]
3872pub struct ScopeDefinition {
3873    pub name: String,
3874    /// `targets: [ "<resource>", … ]` — the allowlist of resources the operator
3875    /// owns/controls and authorises for analysis. Required + non-empty (v2.43.0
3876    /// `axon-T88x`); a target outside this list is a typed rejection.
3877    pub targets: Vec<String>,
3878    /// `depth: static_artifact | memory_dump | live_network` — the MOST invasive
3879    /// analysis depth this scope permits (the ceiling). Closed catalog, ordered
3880    /// least→most invasive; empty ⇒ the safest default `static_artifact` (v2.43.0).
3881    pub depth: String,
3882    /// `approver: [requires] "<capability>"` — the capability whose holder
3883    /// authorised this scope (segregation of duties, the `mandate` v1.13.1 model).
3884    /// Required (v2.43.0).
3885    pub approver: String,
3886    pub loc: Loc,
3887    /// v1.5.2 — leading comment trivia.
3888    pub leading_trivia: Vec<crate::tokens::Trivia>,
3889    /// v1.5.2 — trailing comment trivia.
3890    pub trailing_trivia: Vec<crate::tokens::Trivia>,
3891}
3892
3893/// v2.43.0 — the `warden(<target>) within <Scope> { … }` adversarial
3894/// security-analysis block. A flow-body block (like `quant`): it audits a
3895/// `target` under a paraconsistent adversarial framing, emitting attested
3896/// `Vulnerability` findings — but ONLY `within` a signed authorization `scope`.
3897/// v2.43.0 ships the SURFACE only; scope resolution + the depth/witness discipline
3898/// is v2.43.0, and the real analysis engine is v2.43.0 (enterprise).
3899#[derive(Debug, Default)]
3900pub struct WardenBlock {
3901    /// `warden(<target>)` — a reference to the resource under analysis (a
3902    /// let-bound value / declared target). v2.43.0 checks it is within the scope's
3903    /// `targets` allowlist.
3904    pub target: String,
3905    /// `within <Scope>` — the MANDATORY authorization scope reference. Empty is a
3906    /// hard error (v2.43.0 `axon-T88x`, fail-closed): no scope ⇒ no analysis.
3907    pub scope_ref: String,
3908    /// The nested flow-body statements (`find_exploits()`, `fortify`, `emit`),
3909    /// parsed like `par`/`quant` branches so v2.43.0 can walk them.
3910    pub body: Vec<FlowStep>,
3911    pub loc: Loc,
3912}
3913
3914/// v2.4.0 — the `quant` cognitive primitive block surface
3915/// (`papers/paper_primitiva_quant.md`; enterprise v2.4.0).
3916///
3917/// `quant` projects an MEK semantic tensor into a complex Hilbert space,
3918/// evolves it under a variational / kernel-feature map, and collapses back to
3919/// classical silicon. The attribute header is OPTIONAL — the bare `quant { … }`
3920/// form (the paper's example) leaves every attribute defaulted. The richer form
3921/// `quant(encoding: amplitude, observable: M, qubits: 10, depth: 4,
3922/// bandwidth: 0.5, backend: quant_sim) { … }` pins the encoding scheme (D2),
3923/// the Pauli-sum observable (D5), the register width / circuit depth, the
3924/// projected-kernel bandwidth γ (D7), and the algebraic-effect backend (D1/D9).
3925///
3926/// v2.4.0 ships the SURFACE only. The Continuous Type Invariant over `body`
3927/// (v2.4.0), the typed continuous grammar incl. typed `let` + `Observable`
3928/// (v2.4.0), and the `quant_sim`/`qpu_native` effect injection + `yield`
3929/// measurement point (v2.4.0) land in subsequent steps.
3930#[derive(Debug, Default)]
3931pub struct QuantBlock {
3932    /// `encoding:` — `amplitude` (default) or `angle` (shallow). `None` = the
3933    /// compiler default (amplitude). Carried as the surface spelling; v2.4.0
3934    /// validates against the closed scheme set.
3935    pub encoding: Option<String>,
3936    /// `observable:` — the name of a declared `Observable` (Pauli-sum, D5).
3937    /// `None` if unspecified (v2.4.0 resolves + Hermiticity-checks it).
3938    pub observable: Option<String>,
3939    /// `qubits:` — the register width n (D = 2ⁿ). `None` = inferred from the
3940    /// encoded tensor dimensionality. The OSS reference backend caps n ≤ 10
3941    /// (D1); that bound is enforced at v2.4.0, not here.
3942    pub qubits: Option<i64>,
3943    /// `depth:` — the variational circuit depth L. `None` = backend default.
3944    pub depth: Option<i64>,
3945    /// `bandwidth:` — the projected-quantum-kernel bandwidth γ (D7). `None` =
3946    /// backend default.
3947    pub bandwidth: Option<f64>,
3948    /// v2.23.0 — `reupload:` L, the number of DATA RE-UPLOADING layers. `None`
3949    /// or `1` = no re-uploading (the data enters once → a quadratic form, provably
3950    /// classical for amplitude+Pauli, v2.23.0). `L ≥ 2` interleaves the data
3951    /// encoding with entangling layers L times — the ONLY provable escape from the
3952    /// quadratic bound (Havlíček-style; canonical with `encoding: angle`). The
3953    /// resulting kernel must still pass an Advantage Witness to be deployed
3954    /// claiming advantage (v2.23.0).
3955    pub reupload: Option<i64>,
3956    /// The algebraic-effect backend tag: `quant_sim` (default) or `qpu_native`
3957    /// (D1/D9). Stored as the bare backend name; v2.4.0 injects the full
3958    /// `ots:backend:<tag>` effect into the enclosing flow's effect row.
3959    pub effect: String,
3960    /// The nested flow-body statements (parsed like `par` branches, so v2.4.0
3961    /// can apply the Continuous Type Invariant to real AST). Empty for an
3962    /// empty `quant {}`.
3963    pub body: Vec<FlowStep>,
3964    pub loc: Loc,
3965}
3966
3967/// v2.4.0 — one term `cₖ · Pₖ` of a Pauli-sum observable.
3968///
3969/// `coefficient` is a real scalar (parsed as `f64`); `pauli` is a Pauli string
3970/// over the closed alphabet `{I, X, Y, Z}` (one char per qubit), e.g. `"ZZ"` or
3971/// `"XI"`. A real linear combination of Pauli strings is **Hermitian by
3972/// construction** (each Pauli string is Hermitian; real-weighted sums preserve
3973/// Hermiticity), which is why the observable needs no separate Hermiticity check.
3974#[derive(Debug, Default, Clone)]
3975pub struct PauliTerm {
3976    pub coefficient: f64,
3977    pub pauli: String,
3978    pub loc: Loc,
3979}
3980
3981/// v2.4.0 — the `observable <Name> { qubits, term: cₖ·Pₖ … }` declaration
3982/// (paper section 3.2; plan D5). A typed Pauli-sum `M = Σ cₖ Pₖ` that a `quant` block
3983/// measures the evolved state against. The type-checker validates the closed
3984/// `{I,X,Y,Z}` alphabet + equal term lengths + non-empty sum; Hermiticity is
3985/// guaranteed by construction (real coefficients).
3986#[derive(Debug, Default)]
3987pub struct ObservableDefinition {
3988    pub name: String,
3989    /// `qubits: n` — the register width every Pauli string must span. `None`
3990    /// = inferred from the (equal) term lengths.
3991    pub qubits: Option<i64>,
3992    pub terms: Vec<PauliTerm>,
3993    pub loc: Loc,
3994    /// v1.5.2 — leading comment trivia.
3995    pub leading_trivia: Vec<crate::tokens::Trivia>,
3996    /// v1.5.2 — trailing comment trivia.
3997    pub trailing_trivia: Vec<crate::tokens::Trivia>,
3998}
3999
4000/// v2.23.0 — `witness <Name> { claim: <ref> against: <baseline>
4001/// metric: <metric>  threshold: <ε>  data: <source> }`. The Advantage-Witness
4002/// proof obligation. The compiler proves it WELL-FORMED (v2.23.0, `axon-E0790`);
4003/// the advantage VALUE is computed on real `data` at deploy/runtime and carried
4004/// as a verdict (v2.23.0+). Fields are order-free `key: value` pairs.
4005#[derive(Debug)]
4006pub struct WitnessDefinition {
4007    pub name: String,
4008    /// The primitive instance whose advantage is claimed (e.g. an `observable` /
4009    /// `corpus` name, or a quant kernel reference).
4010    pub claim: String,
4011    /// The cheaper alternative the claim must beat (a closed-catalog baseline
4012    /// like `cosine` / `flat_retrieval` / `single_shot`, or a reference).
4013    pub baseline: String,
4014    /// How advantage is measured — a closed-catalog metric (`geometric_difference`,
4015    /// `kernel_target_alignment`, `ranking_lift`, `outcome_lift`).
4016    pub metric: String,
4017    /// The minimum advantage that justifies the cost (ε ≥ 0).
4018    pub threshold: f64,
4019    /// The real-data source the witness is evaluated on (a ref to an axonstore /
4020    /// corpus / labelled set). Required — advantage cannot be claimed in the abstract.
4021    pub data: String,
4022    pub loc: Loc,
4023    pub leading_trivia: Vec<crate::tokens::Trivia>,
4024    pub trailing_trivia: Vec<crate::tokens::Trivia>,
4025}
4026
4027// ── v1.6.0 — Mobile Typed Channels ──────────────────────────────────
4028
4029/// `channel Name { message: T, qos: X, lifetime: ℓ, persistence: π, shield: σ }`.
4030///
4031/// First-class affine resource carrying a typed message.  Direct port
4032/// of `axon.compiler.ast_nodes.ChannelDefinition`.  `message` retains
4033/// the surface spelling (e.g. `"Order"` or `"Channel<Order>"`) so the
4034/// type checker can resolve nested mobility (paper section 3.3).
4035#[derive(Debug)]
4036pub struct ChannelDefinition {
4037    pub name: String,
4038    pub message: String,     // type name OR "Channel<T>" for second-order
4039    pub qos: String,         // at_most_once | at_least_once | exactly_once | broadcast | queue
4040    pub lifetime: String,    // linear | affine | persistent (D1 default: affine)
4041    pub persistence: String, // ephemeral | persistent_axonstore
4042    pub shield_ref: String,  // optional σ-shield gate for publish (D8)
4043    pub loc: Loc,
4044    /// v1.5.2 — leading comment trivia attached to this declaration
4045    /// (comments preceding the declaration's first token, since the
4046    /// previous declaration or file start). Empty by default.
4047    pub leading_trivia: Vec<crate::tokens::Trivia>,
4048    /// v1.5.2 — trailing comment trivia (same line as the
4049    /// declaration's last effective token). Empty by default.
4050    pub trailing_trivia: Vec<crate::tokens::Trivia>,
4051}
4052
4053/// `emit ChannelName(value_ref)` — π-calculus output prefix `c⟨v⟩.P`.
4054///
4055/// Direct port of `axon.compiler.ast_nodes.EmitStatement`.  Handles
4056/// both Chan-Output (scalar payload) and Chan-Mobility (channel-as-
4057/// value); the type checker dispatches based on whether `value_ref`
4058/// resolves to a `ChannelDefinition`.
4059#[derive(Debug)]
4060pub struct EmitStatement {
4061    pub channel_ref: String,
4062    pub value_ref: String,
4063    pub loc: Loc,
4064}
4065
4066/// v2.46.0 — `mint <Credential> as <binding>`: the flow-step verb that
4067/// mints a declared ephemeral `credential` at runtime. The binding
4068/// receives the raw bearer string (shown once — the type checker forbids
4069/// it from flowing into a `persist` payload, `axon-T896`: credentials do
4070/// not enter stores). Undeclared credential reference = `axon-T895`.
4071#[derive(Debug)]
4072pub struct MintStep {
4073    pub credential_ref: String,
4074    pub binding: String,
4075    pub loc: Loc,
4076}
4077
4078/// v2.48.0 — `rotate <SecretsStore> [where "<filter>"] with <Tool> as
4079/// <binding>`: the mediated secret-renewal flow verb (doctrine
4080/// `rotation_without_revelation`). Set-oriented like `mutate`: every
4081/// custody entry of the store's class matching the filter (whole class
4082/// when the filter is omitted — the post-breach bulk-rotation shape) is
4083/// renewed through ONE mediated exchange per key: the runtime reveals
4084/// the current value only into the tool call, the tool returns the new
4085/// value, the runtime commits it (CAS on version — concurrent rotators
4086/// cannot double-spend a refresh credential). The binding receives the
4087/// METADATA-ONLY summary `{attempted, rotated, failed}` — no term
4088/// evaluates to a secret value. `rotate` on a non-secrets store =
4089/// `axon-T898`; an undeclared tool = `axon-T899`.
4090#[derive(Debug)]
4091pub struct RotateStep {
4092    pub store_ref: String,
4093    /// The v2.21.0-grammar metadata filter (`expires_at < now() + interval
4094    /// '10 minutes'`, `key LIKE 'crm.%'`, …). Empty = the whole class.
4095    pub where_expr: String,
4096    pub tool_ref: String,
4097    pub binding: String,
4098    pub loc: Loc,
4099}
4100
4101/// `publish ChannelName within ShieldName` — capability extrusion.
4102///
4103/// Paper section 4.3 (Publish-Ext) materialized as a flow step. The `within
4104/// <Shield>` clause is mandatory (D8) — the parser rejects bare
4105/// `publish C`, the type checker rejects publishes whose shield does
4106/// not cover κ(message_type) (v1.2.0 + paper section 3.4).
4107#[derive(Debug)]
4108pub struct PublishStatement {
4109    pub channel_ref: String,
4110    pub shield_ref: String,
4111    pub loc: Loc,
4112}
4113
4114/// `discover ChannelName as alias` — dual of publish.
4115///
4116/// Imports a previously-published handle into a fresh affine local
4117/// binding.  The `as <alias>` is mandatory; the type checker rejects
4118/// discovery of channels that were never declared with `shield_ref`.
4119#[derive(Debug)]
4120pub struct DiscoverStatement {
4121    pub capability_ref: String,
4122    pub alias: String,
4123    pub loc: Loc,
4124}