Skip to main content

axon_frontend/
ir_nodes.rs

1//! AXON IR node definitions — direct port of axon/compiler/ir_nodes.py.
2//!
3//! All nodes serialize to JSON matching the Python IR output format exactly.
4
5#![allow(dead_code)]
6
7use serde::Serialize;
8
9// ── Program root ─────────────────────────────────────────────────────────────
10
11/// §Fase 112.b — `Clone` is additive and every member IR type already derives it.
12/// The Cognitive-I/O supervisor owns the compiled program it drives (it outlives
13/// the deploy call that built it), and a lifetime-bound supervisor would have to be
14/// threaded through `ServerState` for no benefit.
15#[derive(Debug, Clone, Serialize)]
16pub struct IRProgram {
17    pub node_type: &'static str,
18    pub source_line: u32,
19    pub source_column: u32,
20    pub personas: Vec<IRPersona>,
21    pub contexts: Vec<IRContext>,
22    pub anchors: Vec<IRAnchor>,
23    pub tools: Vec<IRToolSpec>,
24    pub memories: Vec<IRMemory>,
25    pub types: Vec<IRType>,
26    pub flows: Vec<IRFlow>,
27    pub runs: Vec<IRRun>,
28    pub imports: Vec<IRImport>,
29    pub agents: Vec<IRAgent>,
30    pub shields: Vec<IRShield>,
31    /// §Fase 71.a — temporal execution-window guards.
32    pub windows: Vec<IRWindow>,
33    /// §Fase 114.a — top-level `budget` declarations. A daemon's anonymous budget
34    /// stays on the daemon; these govern EVERY flow that calls the tools they
35    /// name, including the HTTP endpoints adopters actually deploy.
36    #[serde(default, skip_serializing_if = "Vec::is_empty")]
37    pub budgets: Vec<IRBudget>,
38    pub daemons: Vec<IRDaemon>,
39    pub ots_specs: Vec<IROts>,
40    pub pix_specs: Vec<IRPix>,
41    /// §Fase 62.0 — audit-chain (`ledger`) declarations. Distinct from
42    /// `pix_specs` (the retrieval navigator); a ledger binds a hash-linked
43    /// recorder to an audited surface.
44    pub ledger_specs: Vec<IRLedger>,
45    pub corpus_specs: Vec<IRCorpus>,
46    pub psyche_specs: Vec<IRPsyche>,
47    pub mandate_specs: Vec<IRMandate>,
48    pub lambda_data_specs: Vec<IRLambdaData>,
49    pub compute_specs: Vec<IRCompute>,
50    pub axonstore_specs: Vec<IRAxonStore>,
51    pub endpoints: Vec<IRAxonEndpoint>,
52    /// §Fase 53 — closed-catalog extension declarations (compiled).
53    /// `#[serde(skip)]` so the field is NOT emitted into the IR JSON —
54    /// this keeps the static IR-JSON drift-gate fixtures green without
55    /// regenerating them (the pattern `dataspace_specs` also used until
56    /// §108.b un-skipped it).
57    /// The in-memory field feeds the §53.c type-checker + §53.d PCC (both
58    /// read `&IRProgram`); soundness invariant #1 holds via SOURCE
59    /// re-derivation — both the prover and the verifier read the
60    /// source-derived IR, which carries the extensions. §53.x hardening
61    /// (optional): un-skip + regenerate fixtures + bind extensions into
62    /// the PCC `artifact_digest` (today the digest omits them; the
63    /// witness still binds them by re-derivation). Deterministically
64    /// sorted by `name` at the end of IR generation (§53.b founder
65    /// refinement B) so multi-file declaration order can never perturb
66    /// the proof-bundle hash.
67    #[serde(skip)]
68    pub extensions: Vec<IRExtension>,
69    /// §Fase 108.b — the compiled dataspace schemas, SERIALIZED into the
70    /// IR JSON (un-skipped). History: this field was `#[serde(skip)]` for
71    /// byte-identical parity with the retired Python reference frontend
72    /// (§8.2.h.1) — which meant the runtime literally could not see a
73    /// declared dataspace (the §108 ground-truth finding). The parity
74    /// constraint is gone; the deploy hook walks this field to
75    /// instantiate the deterministic columnar engine's stores. Additive
76    /// for consumers: no IR deserializer uses `deny_unknown_fields`
77    /// (verified 2026-07-12), and `IRProgram` is `Serialize`-only —
78    /// consumers re-derive from source.
79    pub dataspace_specs: Vec<IRDataspace>,
80    /// §λ-L-E Fase 1 — I/O cognitivo primitives (compiled).
81    pub resources: Vec<IRResource>,
82    pub fabrics: Vec<IRFabric>,
83    pub manifests: Vec<IRManifest>,
84    pub observations: Vec<IRObserve>,
85    /// §λ-L-E Fase 1 (Free Monad root) — populated when the program
86    /// declares manifests/observes. `None` ⇒ serialises as `null`
87    /// (matches Python when the field is `None`).
88    pub intention_tree: Option<IRIntentionTree>,
89    /// §λ-L-E Fase 3 — Control cognitivo primitives (compiled).
90    pub reconciles: Vec<IRReconcile>,
91    pub leases: Vec<IRLease>,
92    pub ensembles: Vec<IREnsemble>,
93    /// §λ-L-E Fase 4 — Topology + Session (compiled).
94    pub sessions: Vec<IRSession>,
95    pub topologies: Vec<IRTopology>,
96    /// §λ-L-E Fase 5 — Immune system (compiled).
97    pub immunes: Vec<IRImmune>,
98    pub reflexes: Vec<IRReflex>,
99    pub heals: Vec<IRHeal>,
100    /// §λ-L-E Fase 9 — UI cognitiva declarativa (compiled).
101    pub components: Vec<IRComponent>,
102    pub views: Vec<IRView>,
103    /// §λ-L-E Fase 13 — Mobile typed channels (compiled).
104    pub channels: Vec<IRChannel>,
105    /// §Fase 41.b — typed WebSocket transports (compiled). Each carries its
106    /// referenced `session` protocol + the credit-window backpressure so
107    /// axon-rs can realise the typed endpoint over a `tokio` WebSocket.
108    pub sockets: Vec<IRSocket>,
109    /// §Fase 51.c.2 — Pauli-sum observable declarations (compiled). Each carries
110    /// its real-coefficient × Pauli-string terms so axon-rs can build the
111    /// Hermitian measurement operator `M = Σ cₖ Pₖ` a `quant` block measures
112    /// against. `#[serde(skip)]` (like `extensions` / `dataspace_specs`) so the
113    /// static IR-JSON drift fixtures stay green; the in-memory field feeds the
114    /// §51.c.2 checker + the §51.d/e runtime. The checker resolves
115    /// `quant(observable: …)` against the AST symbol table, not this field.
116    #[serde(skip)]
117    pub observables: Vec<IRObservable>,
118    /// §Fase 69.a — Advantage-Witness declarations. `skip_serializing_if = empty`
119    /// keeps a witness-less program's IR JSON byte-identical (zero IR-SHA drift,
120    /// the §52/§67 pattern); when present it rides the IR to the enterprise
121    /// deploy/runtime evaluator (§69.b+).
122    #[serde(default, skip_serializing_if = "Vec::is_empty")]
123    pub witnesses: Vec<IRWitness>,
124    /// §Fase 80.b — outbound vendor connections (compiled). Each carries its
125    /// axon-facing session binding (`protocol`/`role`), the per-tenant config
126    /// keys (`resolve`/`secret`), the auth handshake, the total wire↔session
127    /// projection (`map`) and the reconnect/overflow policies, so axon-rs can
128    /// dial + transcode without vendor-specific code. `skip_serializing_if =
129    /// empty` keeps an upstream-less program's IR JSON byte-identical (zero
130    /// IR-SHA drift — the standing §76.d discipline).
131    #[serde(default, skip_serializing_if = "Vec::is_empty")]
132    pub upstreams: Vec<IRUpstream>,
133    /// §Fase 83.a — named, referenced browser-origin policies. `skip_serializing_if
134    /// = empty` keeps a cors-less program's IR JSON byte-identical (zero IR-SHA
135    /// drift — the standing §76.d discipline).
136    #[serde(default, skip_serializing_if = "Vec::is_empty")]
137    pub cors_policies: Vec<IRCors>,
138    /// §Fase 85.b — named, referenced result-memoization policies. Same
139    /// `skip_serializing_if = empty` IR-SHA discipline as `cors_policies`.
140    #[serde(default, skip_serializing_if = "Vec::is_empty")]
141    pub caches: Vec<IRCache>,
142    /// §Fase 92.a — ephemeral-credential contracts (`credential { ttl:
143    /// grants: }`), minted at runtime by the `mint` flow verb under the
144    /// attenuation law (`authority_only_attenuates`). Same
145    /// `skip_serializing_if = empty` IR-SHA discipline.
146    #[serde(default, skip_serializing_if = "Vec::is_empty")]
147    pub credentials: Vec<IRCredential>,
148    /// §Fase 87.a — long-horizon autonomous research primitives (compiled). Each
149    /// carries its domain, cognition params, memory binding, compute budget and
150    /// mandates so the enterprise engine (§87.h+) can drive the active-inference
151    /// loop. Same `skip_serializing_if = empty` IR-SHA discipline as `caches`
152    /// (a savant-less program's IR JSON stays byte-identical — zero drift).
153    #[serde(default, skip_serializing_if = "Vec::is_empty")]
154    pub savants: Vec<IRSavant>,
155    /// §Fase 99.b — compiled document declarations. Same
156    /// `skip_serializing_if = empty` IR-SHA discipline (a document-less
157    /// program's IR JSON stays byte-identical). Consumed by the runtime
158    /// `DocumentRenderer` tool + the `DocumentProvenanceSoundness` PCC class.
159    #[serde(default, skip_serializing_if = "Vec::is_empty")]
160    pub documents: Vec<IRDocument>,
161    /// §Fase 105 — compiled CRM delivery declarations. Same
162    /// `skip_serializing_if = empty` IR-SHA discipline (a delivery-less program's
163    /// IR JSON stays byte-identical). Consumed by the runtime delivery dispatch
164    /// (`axon::delivery`) + the `DeliveryProvenanceSoundness` PCC class (T920).
165    #[serde(default, skip_serializing_if = "Vec::is_empty")]
166    pub deliveries: Vec<IRDeliver>,
167    /// §Fase 110 — governed human notifications (the third egress dual).
168    pub notifications: Vec<IRNotify>,
169    /// §Fase 87.d — dynamic tool-synthesis policies (compiled). Same
170    /// `skip_serializing_if = empty` IR-SHA discipline as `savants`.
171    #[serde(default, skip_serializing_if = "Vec::is_empty")]
172    pub synths: Vec<IRSynth>,
173    /// §Fase 88.a — authorization-scope policies (compiled). Same
174    /// `skip_serializing_if = empty` IR-SHA discipline as `synths`.
175    #[serde(default, skip_serializing_if = "Vec::is_empty")]
176    pub scopes: Vec<IRScope>,
177    /// §Fase 23 — algebraic effect declarations (compiled).
178    /// Each declared effect persists into IR so axon-rs can build the
179    /// per-effect operation table at startup. The CPS state graph for
180    /// perform/handle sites lives inline within IRFlow.steps (each
181    /// IRPerform / IRHandlerFrame carries its assigned state_id /
182    /// frame_id).
183    ///
184    /// This Rust port mirrors the Python-side
185    /// `IRProgram.effects: tuple[IREffectDeclaration, ...]` field so
186    /// the byte-identical structural-parity gate stays green. The Rust
187    /// frontend (axon-frontend) does not yet emit Fase 23 IR itself —
188    /// the field exists to preserve serialization shape; the actual
189    /// algebraic-effects compiler lives on the Python side, and the
190    /// Rust runtime (axon-rs/src/effects/) consumes the JSON IR
191    /// emitted by Python.
192    pub effects: Vec<IREffectDeclaration>,
193    /// §Fase 115.e — per-module provenance of a LINKED program: for every
194    /// module the linker merged, its path, origin file, both EMS hashes and
195    /// the virtual-line window its declarations occupy (the driver renumbers
196    /// each module's lines by a base offset so diagnostics and IR
197    /// `source_line`s stay globally unambiguous — map back with
198    /// `line − line_base`). `skip_serializing_if = empty` keeps every
199    /// single-file program's IR JSON byte-identical (zero IR-SHA drift —
200    /// the standing §76.d discipline).
201    #[serde(default, skip_serializing_if = "Vec::is_empty")]
202    pub modules: Vec<IRModuleProvenance>,
203}
204
205/// §Fase 115.e — one linked module's provenance record: the audit chain
206/// from a deployed multi-module artifact back to its sources.
207#[derive(Debug, Serialize, Clone)]
208pub struct IRModuleProvenance {
209    /// Dotted module path (`axon.security`).
210    pub module: String,
211    /// Display origin (file path or bundle key).
212    pub origin: String,
213    /// SHA-256 of the module's source bytes.
214    pub content_hash: String,
215    /// SHA-256 of the module's `.axi` interface (comment-stable).
216    pub interface_hash: String,
217    /// First virtual line assigned to this module by the link renumbering.
218    pub line_base: u32,
219    /// Number of source lines the module occupies.
220    pub line_count: u32,
221    /// The module's exported declaration names (deterministic order).
222    pub declarations: Vec<String>,
223}
224
225impl IRProgram {
226    pub fn new() -> Self {
227        IRProgram {
228            node_type: "program",
229            source_line: 1,
230            source_column: 1,
231            personas: Vec::new(),
232            contexts: Vec::new(),
233            anchors: Vec::new(),
234            tools: Vec::new(),
235            memories: Vec::new(),
236            types: Vec::new(),
237            flows: Vec::new(),
238            runs: Vec::new(),
239            imports: Vec::new(),
240            agents: Vec::new(),
241            shields: Vec::new(),
242            windows: Vec::new(),
243            budgets: Vec::new(),
244            daemons: Vec::new(),
245            ots_specs: Vec::new(),
246            pix_specs: Vec::new(),
247            ledger_specs: Vec::new(),
248            corpus_specs: Vec::new(),
249            psyche_specs: Vec::new(),
250            mandate_specs: Vec::new(),
251            lambda_data_specs: Vec::new(),
252            compute_specs: Vec::new(),
253            axonstore_specs: Vec::new(),
254            endpoints: Vec::new(),
255            extensions: Vec::new(),
256            dataspace_specs: Vec::new(),
257            resources: Vec::new(),
258            fabrics: Vec::new(),
259            manifests: Vec::new(),
260            observations: Vec::new(),
261            intention_tree: None,
262            reconciles: Vec::new(),
263            leases: Vec::new(),
264            ensembles: Vec::new(),
265            sessions: Vec::new(),
266            topologies: Vec::new(),
267            immunes: Vec::new(),
268            reflexes: Vec::new(),
269            heals: Vec::new(),
270            components: Vec::new(),
271            views: Vec::new(),
272            channels: Vec::new(),
273            sockets: Vec::new(),
274            observables: Vec::new(),
275            witnesses: Vec::new(),
276            upstreams: Vec::new(),
277            cors_policies: Vec::new(),
278            caches: Vec::new(),
279            credentials: Vec::new(),
280            savants: Vec::new(),
281            documents: Vec::new(),
282            deliveries: Vec::new(),
283            notifications: Vec::new(),
284            synths: Vec::new(),
285            scopes: Vec::new(),
286            effects: Vec::new(),
287            modules: Vec::new(),
288        }
289    }
290}
291
292/// §Fase 51.d.2 — IR for the `yield <expr>` measurement point.
293#[derive(Debug, Clone, Serialize)]
294pub struct IRYield {
295    pub node_type: &'static str,
296    pub source_line: u32,
297    pub source_column: u32,
298    pub value_expr: String,
299    pub value_kind: String,
300}
301
302/// §Fase 51.c.2 — one term `cₖ · Pₖ` of a Pauli-sum observable (compiled).
303#[derive(Debug, Clone, Serialize)]
304pub struct IRPauliTerm {
305    pub coefficient: f64,
306    pub pauli: String,
307}
308
309/// §Fase 51.c.2 — IR for a Pauli-sum observable `M = Σ cₖ Pₖ`.
310#[derive(Debug, Clone, Serialize)]
311pub struct IRObservable {
312    pub node_type: &'static str,
313    pub source_line: u32,
314    pub source_column: u32,
315    pub name: String,
316    #[serde(skip_serializing_if = "Option::is_none")]
317    pub qubits: Option<i64>,
318    pub terms: Vec<IRPauliTerm>,
319}
320
321/// §Fase 69.a — IR for an Advantage Witness. The deploy/runtime evaluator reads
322/// `metric` + `threshold` + `baseline`, computes the metric over `data`, and
323/// emits the verdict; a `holds == false` verdict is the honest fail-closed
324/// signal (`axon-W007`/`W008`). `claim`/`data` are references resolved per domain.
325#[derive(Debug, Clone, Serialize)]
326pub struct IRWitness {
327    pub node_type: &'static str,
328    pub source_line: u32,
329    pub source_column: u32,
330    pub name: String,
331    pub claim: String,
332    pub baseline: String,
333    pub metric: String,
334    pub threshold: f64,
335    pub data: String,
336}
337
338// ── §Fase 23 — Algebraic effect declarations ─────────────────────────────────
339//
340// Mirror of Python's `IREffectDeclaration` and `IREffectOperation`
341// dataclasses. The Rust frontend (axon-frontend) does not yet emit
342// Fase 23 IR itself — these structs exist so the byte-identical
343// structural-parity gate stays green when Python emits an empty
344// `effects: []` field. The actual algebraic-effects compiler lives on
345// the Python side; the Rust runtime (axon-rs/src/effects/) consumes
346// the JSON IR via its own deserialize structs.
347
348#[derive(Debug, Serialize, Default, Clone)]
349pub struct IREffectDeclaration {
350    pub node_type: &'static str,
351    pub source_line: u32,
352    pub source_column: u32,
353    pub name: String,
354    pub operations: Vec<IREffectOperation>,
355}
356
357impl IREffectDeclaration {
358    pub fn new() -> Self {
359        Self {
360            node_type: "effect_declaration",
361            source_line: 0,
362            source_column: 0,
363            name: String::new(),
364            operations: Vec::new(),
365        }
366    }
367}
368
369#[derive(Debug, Serialize, Default, Clone)]
370pub struct IREffectOperation {
371    pub node_type: &'static str,
372    pub source_line: u32,
373    pub source_column: u32,
374    pub name: String,
375    pub type_parameters: Vec<String>,
376    pub parameter_names: Vec<String>,
377    pub parameter_types: Vec<String>,
378    pub return_type: String,
379}
380
381impl IREffectOperation {
382    pub fn new() -> Self {
383        Self {
384            node_type: "effect_operation",
385            source_line: 0,
386            source_column: 0,
387            name: String::new(),
388            type_parameters: Vec::new(),
389            parameter_names: Vec::new(),
390            parameter_types: Vec::new(),
391            return_type: String::new(),
392        }
393    }
394}
395
396// ── §λ-L-E Fase 1 — IRResource ──────────────────────────────────────────────
397
398/// Compiled resource declaration — linear/affine infrastructure token.
399///
400/// Python counterpart: `axon.compiler.ir_nodes.IRResource`.
401#[derive(Debug, Clone, Serialize)]
402pub struct IRResource {
403    pub node_type: &'static str,
404    pub source_line: u32,
405    pub source_column: u32,
406    pub name: String,
407    pub kind: String,
408    pub endpoint: String,
409    /// §Fase 113 — the pool size. Until §113 this was **read by nothing**: every
410    /// `postgresql` axonstore in existence got a hardcoded
411    /// `MAX_POOL_CONNECTIONS = 10` (`store/postgres_backend.rs`), with no env
412    /// var and no source-level knob. `capacity:` is that missing knob, and
413    /// wiring it is what makes `resource` a WIRE rather than a LABEL.
414    pub capacity: Option<i64>,
415    /// §Fase 113 — **how many holders may name this resource** (Linear Logic).
416    ///
417    /// Not "how long the connection lives" — that is `idle_timeout`, an
418    /// operational knob. The Linear-Logic reading is about *sharing*:
419    ///
420    /// - `linear` — **exactly one** holder, and failing to name it is itself a
421    ///   breach (a linear resource must be consumed).
422    /// - `affine` — **at most one** holder. It may go unused; **sharing it is a
423    ///   breach**.
424    /// - `persistent` — the `!` exponential. Freely shared.
425    ///
426    /// Before §113, two stores shared a connection pool by **accidental DSN
427    /// collision** (the registry keys its pool cache on the resolved DSN).
428    /// Sharing is now *declared*, and `axon-T945` checks it.
429    pub lifetime: String,
430    pub certainty_floor: Option<f64>, // c ∈ [0.0, 1.0]
431    pub shield_ref: String,
432    /// §Fase 113 — the `fabric` this resource lives in (`within: Prod`).
433    ///
434    /// **One field, therefore Separation-Logic disjointness is UNREPRESENTABLE
435    /// rather than verified**: a resource cannot be in two fabrics because
436    /// there is no syntax for it. A checked invariant is what you settle for
437    /// when you could not make the bad state unwritable; here we could.
438    ///
439    /// Empty ⇒ no fabric declared. Skip-if-empty ⇒ every pre-§113 program
440    /// serializes byte-identically (IR-SHA stability, the §94.a `class`
441    /// precedent).
442    #[serde(default, skip_serializing_if = "String::is_empty")]
443    pub within: String,
444}
445
446impl IRResource {
447    pub fn new(name: String, line: u32, column: u32) -> Self {
448        IRResource {
449            node_type: "resource",
450            source_line: line,
451            source_column: column,
452            name,
453            kind: String::new(),
454            endpoint: String::new(),
455            capacity: None,
456            lifetime: "affine".to_string(),
457            certainty_floor: None,
458            shield_ref: String::new(),
459            within: String::new(),
460        }
461    }
462}
463
464// ── §λ-L-E Fase 1 — IRFabric ────────────────────────────────────────────────
465
466/// Compiled fabric declaration — topological substrate for resources.
467#[derive(Debug, Clone, Serialize)]
468pub struct IRFabric {
469    pub node_type: &'static str,
470    pub source_line: u32,
471    pub source_column: u32,
472    pub name: String,
473    pub provider: String,
474    pub region: String,
475    pub zones: Option<i64>,
476    pub ephemeral: Option<bool>,
477    pub shield_ref: String,
478}
479
480// ── §λ-L-E Fase 1 — IRManifest ──────────────────────────────────────────────
481
482/// Compiled manifest declaration — declarative belief about desired shape.
483#[derive(Debug, Clone, Serialize)]
484pub struct IRManifest {
485    pub node_type: &'static str,
486    pub source_line: u32,
487    pub source_column: u32,
488    pub name: String,
489    pub resources: Vec<String>,
490    pub fabric_ref: String,
491    pub region: String,
492    pub zones: Option<i64>,
493    pub compliance: Vec<String>,
494}
495
496// ── §λ-L-E Fase 1 — IRObserve ───────────────────────────────────────────────
497
498// ── §λ-L-E Fase 1 — IRIntentionTree (Free Monad root) ──────────────────────
499
500/// A single operation node in the intention tree.
501///
502/// Operations are heterogeneous IR nodes (manifests, observes) that the
503/// Handler layer (Fase 2) interprets via CPS. The enum is `#[serde(untagged)]`
504/// so JSON output is just the inner struct — matching Python's `asdict`
505/// behaviour on a polymorphic `tuple[IRNode, ...]`.
506#[derive(Debug, Clone, Serialize)]
507#[serde(untagged)]
508pub enum IRIntentionOperation {
509    Manifest(IRManifest),
510    Observe(IRObserve),
511}
512
513/// The Free Monad F_Σ(X) — a pure description of I/O intentions. Flat in
514/// Fase 1; nested continuations arrive with handlers + reconcile loops.
515#[derive(Debug, Clone, Serialize)]
516pub struct IRIntentionTree {
517    pub node_type: &'static str,
518    pub source_line: u32,
519    pub source_column: u32,
520    pub operations: Vec<IRIntentionOperation>,
521}
522
523/// Compiled observe declaration — quorum-gated observation with lag τ.
524#[derive(Debug, Clone, Serialize)]
525pub struct IRObserve {
526    pub node_type: &'static str,
527    pub source_line: u32,
528    pub source_column: u32,
529    pub name: String,
530    pub target: String,
531    pub sources: Vec<String>,
532    pub quorum: Option<i64>,
533    pub timeout: String,
534    pub on_partition: String,
535    pub certainty_floor: Option<f64>,
536}
537
538// ── §λ-L-E Fase 3 — IRReconcile / IRLease / IREnsemble ──────────────────────
539
540/// Compiled reconcile declaration — free-energy minimizing control loop.
541#[derive(Debug, Clone, Serialize)]
542pub struct IRReconcile {
543    pub node_type: &'static str,
544    pub source_line: u32,
545    pub source_column: u32,
546    pub name: String,
547    pub observe_ref: String,
548    pub threshold: Option<f64>,
549    pub tolerance: Option<f64>,
550    pub on_drift: String,
551    pub shield_ref: String,
552    pub mandate_ref: String,
553    pub max_retries: i64,
554}
555
556/// Compiled lease declaration — τ-decaying affine resource token.
557#[derive(Debug, Clone, Serialize)]
558pub struct IRLease {
559    pub node_type: &'static str,
560    pub source_line: u32,
561    pub source_column: u32,
562    pub name: String,
563    pub resource_ref: String,
564    pub duration: String,
565    pub acquire: String,
566    pub on_expire: String,
567}
568
569/// Compiled ensemble declaration — Byzantine quorum aggregator.
570#[derive(Debug, Clone, Serialize)]
571pub struct IREnsemble {
572    pub node_type: &'static str,
573    pub source_line: u32,
574    pub source_column: u32,
575    pub name: String,
576    pub observations: Vec<String>,
577    pub quorum: Option<i64>,
578    pub aggregation: String,
579    pub certainty_mode: String,
580}
581
582// ── §λ-L-E Fase 4 — IRSession / IRTopology ──────────────────────────────────
583
584/// One operation in a compiled session protocol
585/// (send / receive / loop / end / select / branch — §Fase 41.b adds the choices).
586#[derive(Debug, Clone, Serialize)]
587pub struct IRSessionStep {
588    pub node_type: &'static str,
589    pub source_line: u32,
590    pub source_column: u32,
591    pub op: String,
592    pub message_type: String,
593    /// §Fase 41.b — labelled branches (only for `op == "select" | "branch"`;
594    /// §Fase 79.b reuses them for `op == "interrupt"`: `body` + `handler` arms).
595    #[serde(skip_serializing_if = "Vec::is_empty", default)]
596    pub branches: Vec<IRSessionBranch>,
597    /// §Fase 79.b — `op == "interrupt"` only: the handler's signal binder
598    /// (`... as <sig> ...`). Skip-if-empty ⇒ zero IR-SHA drift for every
599    /// non-interrupt step (the §76.d/§77.a additive-only discipline).
600    #[serde(skip_serializing_if = "String::is_empty", default)]
601    pub binder: String,
602    /// §Fase 79.b — `op == "interrupt"` only: the block declares a `resumable`
603    /// handler. Skip-if-false ⇒ byte-identical IR for every other op.
604    #[serde(skip_serializing_if = "std::ops::Not::not", default)]
605    pub resumable: bool,
606}
607
608/// §Fase 41.b — one labelled arm of a compiled `select`/`branch` choice.
609#[derive(Debug, Clone, Serialize)]
610pub struct IRSessionBranch {
611    pub node_type: &'static str,
612    pub label: String,
613    pub steps: Vec<IRSessionStep>,
614}
615
616/// A role's name and its ordered protocol steps.
617#[derive(Debug, Clone, Serialize)]
618pub struct IRSessionRole {
619    pub node_type: &'static str,
620    pub source_line: u32,
621    pub source_column: u32,
622    pub name: String,
623    pub steps: Vec<IRSessionStep>,
624}
625
626/// Compiled binary session — exactly two dual roles (verified at type-check).
627#[derive(Debug, Clone, Serialize)]
628pub struct IRSession {
629    pub node_type: &'static str,
630    pub source_line: u32,
631    pub source_column: u32,
632    pub name: String,
633    pub roles: Vec<IRSessionRole>,
634}
635
636/// Directed, session-typed edge between two topology nodes.
637#[derive(Debug, Clone, Serialize)]
638pub struct IRTopologyEdge {
639    pub node_type: &'static str,
640    pub source_line: u32,
641    pub source_column: u32,
642    pub source: String,
643    pub target: String,
644    pub session_ref: String,
645}
646
647/// Compiled topology — typed graph over Axon entities.
648#[derive(Debug, Clone, Serialize)]
649pub struct IRTopology {
650    pub node_type: &'static str,
651    pub source_line: u32,
652    pub source_column: u32,
653    pub name: String,
654    pub nodes: Vec<String>,
655    pub edges: Vec<IRTopologyEdge>,
656}
657
658// ── §λ-L-E Fase 5 — IRImmune / IRReflex / IRHeal ────────────────────────────
659
660/// Compiled immune sensor — KL+FEP anomaly detector descriptor.
661#[derive(Debug, Clone, Serialize)]
662pub struct IRImmune {
663    pub node_type: &'static str,
664    pub source_line: u32,
665    pub source_column: u32,
666    pub name: String,
667    pub watch: Vec<String>,
668    pub sensitivity: Option<f64>,
669    pub baseline: String,
670    pub window: i64,
671    pub scope: String,
672    pub tau: String,
673    pub decay: String,
674}
675
676/// Compiled reflex — deterministic O(1) motor response descriptor.
677#[derive(Debug, Clone, Serialize)]
678pub struct IRReflex {
679    pub node_type: &'static str,
680    pub source_line: u32,
681    pub source_column: u32,
682    pub name: String,
683    pub trigger: String,
684    pub on_level: String,
685    pub action: String,
686    pub scope: String,
687    pub sla: String,
688}
689
690/// Compiled heal — Linear-Logic one-shot patch kernel descriptor.
691#[derive(Debug, Clone, Serialize)]
692pub struct IRHeal {
693    pub node_type: &'static str,
694    pub source_line: u32,
695    pub source_column: u32,
696    pub name: String,
697    pub source: String,
698    pub on_level: String,
699    pub mode: String,
700    pub scope: String,
701    pub review_sla: String,
702    pub shield_ref: String,
703    pub max_patches: i64,
704}
705
706// ── §λ-L-E Fase 9 — IRComponent / IRView ────────────────────────────────────
707
708/// Compiled UI component — reusable fragment over a typed data source.
709#[derive(Debug, Clone, Serialize)]
710pub struct IRComponent {
711    pub node_type: &'static str,
712    pub source_line: u32,
713    pub source_column: u32,
714    pub name: String,
715    pub renders: String,
716    pub via_shield: String,
717    pub on_interact: String,
718    pub render_hint: String,
719}
720
721/// Compiled UI view — top-level screen composing declared components.
722#[derive(Debug, Clone, Serialize)]
723pub struct IRView {
724    pub node_type: &'static str,
725    pub source_line: u32,
726    pub source_column: u32,
727    pub name: String,
728    pub title: String,
729    pub components: Vec<String>,
730    pub route: String,
731}
732
733// ── Import ───────────────────────────────────────────────────────────────────
734
735#[derive(Debug, Serialize, Clone)]
736pub struct IRImport {
737    pub node_type: &'static str,
738    pub source_line: u32,
739    pub source_column: u32,
740    pub module_path: Vec<String>,
741    pub names: Vec<String>,
742    /// §Fase 115.e — `true` iff the EMS resolved this import against a
743    /// module in the compilation (the fields this paper-era struct always
744    /// promised). Skipped when `false` so every pre-§115 program's IR
745    /// JSON stays byte-identical (zero IR-SHA drift).
746    #[serde(default, skip_serializing_if = "ir_import_unresolved")]
747    pub resolved: bool,
748    /// §Fase 115.e — the resolved module's `.axi` interface hash.
749    #[serde(default, skip_serializing_if = "Option::is_none")]
750    pub interface_hash: Option<String>,
751}
752
753/// Serde helper: skip `resolved` while it is `false`.
754fn ir_import_unresolved(resolved: &bool) -> bool {
755    !*resolved
756}
757
758// ── Persona ──────────────────────────────────────────────────────────────────
759
760#[derive(Debug, Clone, Serialize)]
761pub struct IRPersona {
762    pub node_type: &'static str,
763    pub source_line: u32,
764    pub source_column: u32,
765    pub name: String,
766    pub domain: Vec<String>,
767    pub tone: String,
768    pub confidence_threshold: Option<f64>,
769    pub cite_sources: Option<bool>,
770    pub refuse_if: Vec<String>,
771    pub language: String,
772    pub description: String,
773}
774
775// ── Context ──────────────────────────────────────────────────────────────────
776
777#[derive(Debug, Clone, Serialize)]
778pub struct IRContext {
779    pub node_type: &'static str,
780    pub source_line: u32,
781    pub source_column: u32,
782    pub name: String,
783    pub memory_scope: String,
784    pub language: String,
785    pub depth: String,
786    pub max_tokens: Option<i64>,
787    pub temperature: Option<f64>,
788    pub cite_sources: Option<bool>,
789    /// §Fase 91.a — the frame's declared cognitive timezone (IANA name).
790    /// Elided when absent → pre-§91 context IR JSON stays byte-identical.
791    #[serde(default, skip_serializing_if = "Option::is_none")]
792    pub now_tz: Option<String>,
793}
794
795// ── Anchor ───────────────────────────────────────────────────────────────────
796
797#[derive(Debug, Clone, Serialize)]
798pub struct IRAnchor {
799    pub node_type: &'static str,
800    pub source_line: u32,
801    pub source_column: u32,
802    pub name: String,
803    pub description: String,
804    pub require: String,
805    pub reject: Vec<String>,
806    pub enforce: String,
807    pub confidence_floor: Option<f64>,
808    pub unknown_response: String,
809    pub on_violation: String,
810    pub on_violation_target: String,
811}
812
813// ── Tool ─────────────────────────────────────────────────────────────────────
814
815/// §Fase 58.c — one typed parameter of a tool's input schema (the IR mirror of
816/// the AST `Parameter`). `type_name` is the flattened BASE type string
817/// (`String`, `List<String>`); optionality (`T?`) is carried in `optional`, so
818/// `required` is derivable with no parallel bool (§58 D1, single source of
819/// truth). Lossless round-trip is gated in §58.i.
820#[derive(Debug, Clone, Serialize, PartialEq)]
821pub struct IRToolParam {
822    pub name: String,
823    pub type_name: String,
824    pub optional: bool,
825}
826
827/// §Fase 58.c — one bound keyword argument of a `use Tool(k = v, …)` call (the
828/// IR mirror of `UseArgs::Named`). `value` is an expression string (the
829/// frontend has no structured `Expr`). The runtime (§58.e) assembles these into
830/// the structured JSON request body.
831#[derive(Debug, Clone, Serialize, PartialEq)]
832pub struct IRNamedArg {
833    pub name: String,
834    pub value: String,
835    /// §Fase 60 — `"literal"` or `"reference"` (classified by `parse_let_atom`).
836    /// A `"reference"` value (a bare identifier or `Step.output`) is resolved at
837    /// runtime against the bindings (flow-param / `let` / step output), like a
838    /// `let` reference — instead of being passed as the literal name (the pre-60
839    /// bug). `"literal"` values keep `${…}` interpolation + typed coercion.
840    pub value_kind: String,
841}
842
843#[derive(Debug, Serialize, Clone)]
844pub struct IRToolSpec {
845    pub node_type: &'static str,
846    pub source_line: u32,
847    pub source_column: u32,
848    pub name: String,
849    pub provider: String,
850    pub max_results: Option<i64>,
851    pub filter_expr: String,
852    pub timeout: String,
853    pub runtime: String,
854    /// §Fase 114.c — the `resource` this tool's channel runs on. Empty ⇒ legacy
855    /// form. Skip-if-empty ⇒ every pre-§114 tool serializes byte-identically.
856    #[serde(default, skip_serializing_if = "String::is_empty")]
857    pub resource_ref: String,
858    pub sandbox: Option<bool>,
859    pub input_schema: Vec<String>,
860    pub output_schema: String,
861    /// §Fase 58.c — the tool's typed INPUT SCHEMA (D1). Distinct from the §32
862    /// `input_schema`/`output_schema` validation hints (those say HOW to
863    /// validate raw output: JSON/number/…); these are the caller↔tool TYPE
864    /// contract the type-checker enforces (§58.d) and the runtime binds
865    /// structured args against (§58.e). Empty for a schema-less tool (D5).
866    pub parameters: Vec<IRToolParam>,
867    /// §Fase 58.c — the tool's declared OUTPUT type (D8), so `${Step.output}`
868    /// is typed. `None` when undeclared. Single source of truth (lives here,
869    /// not denormalised onto each call site).
870    pub output_type: Option<String>,
871    /// §Fase 94.c — the per-tenant secret KEY injected into every dispatch
872    /// under the reserved `axon_secret` request field (resolved against the
873    /// tenant's custody at `use` time; the flow never touches the value).
874    /// Elided when empty — every pre-§94 tool serializes byte-identically
875    /// (IR-SHA stability).
876    #[serde(default, skip_serializing_if = "String::is_empty")]
877    pub secret: String,
878    /// §Fase 95.a — the `secret_partition:` parameter name whose runtime
879    /// value is appended as a single segment to `secret` at dispatch
880    /// (`selection_without_revelation`). Elided when empty, so every §94 and
881    /// pre-§94 tool serializes byte-identically (IR-SHA stability). The
882    /// class prefix lives in `secret`; this only names the dynamic segment
883    /// source — no value ever rides the IR.
884    #[serde(default, skip_serializing_if = "String::is_empty")]
885    pub secret_partition: String,
886    pub effect_row: Vec<String>,
887    /// §Fase 84.b — Remote Hands. All three fields are `skip_serializing_if`
888    /// so a program using none of them serialises **byte-identically** to the
889    /// pre-§84 IR (the §76.d IR-SHA / additive-only gate — no drift for the
890    /// entire existing corpus).
891    #[serde(skip_serializing_if = "Option::is_none")]
892    pub target: Option<String>,
893    #[serde(skip_serializing_if = "Option::is_none")]
894    pub risk: Option<String>,
895    #[serde(skip_serializing_if = "Vec::is_empty")]
896    pub argv: Vec<String>,
897    /// §Fase 85.b — the cache-policy reference (a declared `cache` name, or the
898    /// `none` opt-out sentinel). Empty ⇒ module-default-governed. Elided when
899    /// empty (IR-SHA stable for cache-less programs).
900    #[serde(default, skip_serializing_if = "String::is_empty")]
901    pub cache: String,
902    /// §Fase 98.b — the closed-catalog web-acquisition config. `None` for
903    /// every non-scrape tool, and `skip_serializing_if` so the entire
904    /// pre-§98 corpus serialises byte-identically (the §76.d IR-SHA /
905    /// additive-only gate). Present ⇒ this tool acquires open-web content
906    /// (born Untrusted, D98.1) and its `effect_row` carries `web`.
907    #[serde(skip_serializing_if = "Option::is_none")]
908    pub scrape: Option<IRScrapeSpec>,
909}
910
911/// §Fase 98.b — the IR mirror of `ast::ScrapeSpec`. Every field is
912/// `skip_serializing_if` on its empty/none form so a minimal `scrape: {}`
913/// and each partially-populated block serialise deterministically with no
914/// null noise, keeping the IR-SHA additive.
915#[derive(Debug, Serialize, Clone)]
916pub struct IRScrapeSpec {
917    pub node_type: &'static str,
918    #[serde(skip_serializing_if = "Option::is_none")]
919    pub engine: Option<String>,
920    #[serde(skip_serializing_if = "Option::is_none")]
921    pub impersonate: Option<String>,
922    #[serde(skip_serializing_if = "Option::is_none")]
923    pub render_wait: Option<String>,
924    #[serde(default, skip_serializing_if = "String::is_empty")]
925    pub proxy: String,
926    #[serde(skip_serializing_if = "Option::is_none")]
927    pub respect_robots: Option<bool>,
928    #[serde(default, skip_serializing_if = "Vec::is_empty")]
929    pub extract: Vec<String>,
930    #[serde(skip_serializing_if = "Option::is_none")]
931    pub adaptive: Option<bool>,
932    #[serde(skip_serializing_if = "Option::is_none")]
933    pub similarity_floor: Option<f64>,
934    #[serde(default, skip_serializing_if = "String::is_empty")]
935    pub follow: String,
936    #[serde(skip_serializing_if = "Option::is_none")]
937    pub max_depth: Option<i64>,
938    #[serde(skip_serializing_if = "Option::is_none")]
939    pub max_pages: Option<i64>,
940    #[serde(skip_serializing_if = "Option::is_none")]
941    pub concurrency: Option<i64>,
942    #[serde(default, skip_serializing_if = "String::is_empty")]
943    pub politeness: String,
944    #[serde(default, skip_serializing_if = "String::is_empty")]
945    pub checkpoint: String,
946}
947
948// ── Memory ───────────────────────────────────────────────────────────────────
949
950#[derive(Debug, Serialize, Clone)]
951pub struct IRMemory {
952    pub node_type: &'static str,
953    pub source_line: u32,
954    pub source_column: u32,
955    pub name: String,
956    pub store: String,
957    pub backend: String,
958    pub retrieval: String,
959    pub decay: String,
960}
961
962// ── Type ─────────────────────────────────────────────────────────────────────
963
964#[derive(Debug, Clone, Serialize)]
965pub struct IRTypeField {
966    pub node_type: &'static str,
967    pub source_line: u32,
968    pub source_column: u32,
969    pub name: String,
970    pub type_name: String,
971    pub generic_param: String,
972    pub optional: bool,
973}
974
975#[derive(Debug, Serialize, Clone)]
976pub struct IRType {
977    pub node_type: &'static str,
978    pub source_line: u32,
979    pub source_column: u32,
980    pub name: String,
981    pub fields: Vec<IRTypeField>,
982    pub range_min: Option<f64>,
983    pub range_max: Option<f64>,
984    pub where_expression: String,
985    /// §ESK Fase 6.1 — κ regulatory class.
986    pub compliance: Vec<String>,
987}
988
989// ── Flow ─────────────────────────────────────────────────────────────────────
990
991#[derive(Debug, Clone, Serialize)]
992pub struct IRParameter {
993    pub node_type: &'static str,
994    pub source_line: u32,
995    pub source_column: u32,
996    pub name: String,
997    pub type_name: String,
998    pub generic_param: String,
999    pub optional: bool,
1000}
1001
1002#[derive(Debug, Clone, Serialize)]
1003pub struct IRDataEdge {
1004    pub node_type: &'static str,
1005    pub source_line: u32,
1006    pub source_column: u32,
1007    pub source_step: String,
1008    pub target_step: String,
1009    pub type_name: String,
1010}
1011
1012#[derive(Debug, Clone, Serialize)]
1013pub struct IRStep {
1014    pub node_type: &'static str,
1015    pub source_line: u32,
1016    pub source_column: u32,
1017    pub name: String,
1018    pub persona_ref: String,
1019    pub given: String,
1020    pub ask: String,
1021    pub use_tool: Option<serde_json::Value>,
1022    pub probe: Option<serde_json::Value>,
1023    pub reason: Option<serde_json::Value>,
1024    pub weave: Option<serde_json::Value>,
1025    pub output_type: String,
1026    pub confidence_floor: Option<f64>,
1027    pub navigate_ref: String,
1028    pub apply_ref: String,
1029    /// §Fase 68.b — the step's model-capability requirement (context window in
1030    /// tokens). `skip_serializing_if = Option::is_none` keeps every pre-§68 step's
1031    /// IR JSON byte-identical (no IR-SHA drift, D68.4); a legacy IR deserialises
1032    /// to `None` → the §68.c resolver picks the backend default exactly as today.
1033    #[serde(default, skip_serializing_if = "Option::is_none")]
1034    pub requires_context: Option<u32>,
1035    /// §Fase 91.a — the step's declared cognitive timezone (IANA name). The
1036    /// runtime renders the run's captured instant in this zone into the step's
1037    /// cognitive context. Elided when absent → every pre-§91 step's IR JSON is
1038    /// byte-identical (no IR-SHA drift); legacy IR → `None` → no injection.
1039    #[serde(default, skip_serializing_if = "Option::is_none")]
1040    pub now_tz: Option<String>,
1041    pub body: Vec<serde_json::Value>,
1042}
1043
1044#[derive(Debug, Clone, Serialize)]
1045pub struct IRFlow {
1046    pub node_type: &'static str,
1047    pub source_line: u32,
1048    pub source_column: u32,
1049    pub name: String,
1050    pub parameters: Vec<IRParameter>,
1051    pub return_type_name: String,
1052    pub return_type_generic: String,
1053    pub return_type_optional: bool,
1054    pub steps: Vec<IRFlowNode>,
1055    pub edges: Vec<IRDataEdge>,
1056    pub execution_levels: Vec<Vec<String>>,
1057}
1058
1059// ── Run ──────────────────────────────────────────────────────────────────────
1060
1061#[derive(Debug, Clone, Serialize)]
1062pub struct IRRun {
1063    pub node_type: &'static str,
1064    pub source_line: u32,
1065    pub source_column: u32,
1066    pub flow_name: String,
1067    pub arguments: Vec<String>,
1068    pub persona_name: String,
1069    pub context_name: String,
1070    pub anchor_names: Vec<String>,
1071    pub on_failure: String,
1072    pub on_failure_params: Vec<Vec<String>>,
1073    pub output_to: String,
1074    pub effort: String,
1075    pub resolved_flow: Option<IRFlow>,
1076    pub resolved_persona: Option<IRPersona>,
1077    pub resolved_context: Option<IRContext>,
1078    pub resolved_anchors: Vec<IRAnchor>,
1079}
1080
1081// ── Lambda Data (ΛD) — Epistemic State Vectors ─────────────────────────────
1082
1083#[derive(Debug, Clone, Serialize)]
1084pub struct IRLambdaData {
1085    pub node_type: &'static str,
1086    pub source_line: u32,
1087    pub source_column: u32,
1088    pub name: String,
1089    pub ontology: String,             // T — ontological type
1090    pub certainty: f64,               // c ∈ [0,1]
1091    pub temporal_frame_start: String, // τ_start
1092    pub temporal_frame_end: String,   // τ_end
1093    pub provenance: String,           // ρ — EntityRef origin
1094    pub derivation: String,           // δ ∈ Δ
1095}
1096
1097#[derive(Debug, Clone, Serialize)]
1098pub struct IRLambdaDataApply {
1099    pub node_type: &'static str,
1100    pub source_line: u32,
1101    pub source_column: u32,
1102    pub lambda_data_name: String, // reference to declared ΛD
1103    pub target: String,           // expression being bound
1104    pub output_type: String,      // result type after binding
1105}
1106
1107// ── Flow step IR nodes ──────────────────────────────────────────────────────
1108
1109/// Polymorphic flow body node — serializes via #[serde(untagged)] so each
1110/// variant emits its inner struct's JSON (with its own `node_type` field).
1111#[derive(Debug, Clone, Serialize)]
1112#[serde(untagged)]
1113pub enum IRFlowNode {
1114    Step(IRStep),
1115    Probe(IRProbe),
1116    Reason(IRReasonStep),
1117    Validate(IRValidateStep),
1118    Refine(IRRefineStep),
1119    Weave(IRWeaveStep),
1120    UseTool(IRUseToolStep),
1121    Remember(IRRememberStep),
1122    Recall(IRRecallStep),
1123    Conditional(IRConditional),
1124    ForIn(IRForIn),
1125    Let(IRLetBinding),
1126    Return(IRReturnStep),
1127    /// Fase 19.e — exit the enclosing for-in body. Payload-free;
1128    /// the runner translates it into a sentinel that terminates the
1129    /// loop. Parser scope check guarantees this only appears inside
1130    /// a for-in body.
1131    Break(IRBreakStep),
1132    /// Fase 19.e — skip to the next iteration of the enclosing for-in
1133    /// body. Same shape as Break — payload-free, sentinel-driven at
1134    /// runtime.
1135    Continue(IRContinueStep),
1136    LambdaDataApply(IRLambdaDataApply),
1137    Par(IRParallelBlock),
1138    Hibernate(IRHibernateStep),
1139    Deliberate(IRDeliberateBlock),
1140    Consensus(IRConsensusBlock),
1141    Forge(IRForgeBlock),
1142    /// §Fase 109 — the proof-carrying derivative step.
1143    Grad(IRGradStep),
1144    Focus(IRFocusStep),
1145    Associate(IRAssociateStep),
1146    Aggregate(IRAggregateStep),
1147    Explore(IRExploreStep),
1148    Ingest(IRIngestStep),
1149    ShieldApply(IRShieldApplyStep),
1150    Stream(IRStreamBlock),
1151    Navigate(IRNavigateStep),
1152    Drill(IRDrillStep),
1153    Trail(IRTrailStep),
1154    Corroborate(IRCorroborateStep),
1155    OtsApply(IROtsApplyStep),
1156    MandateApply(IRMandateApplyStep),
1157    ComputeApply(IRComputeApplyStep),
1158    Listen(IRListenStep),
1159    DaemonStep(IRDaemonStepNode),
1160    /// §λ-L-E Fase 13 — π-calc output prefix (Chan-Output / Chan-Mobility).
1161    Emit(IREmit),
1162    /// §Fase 92.b — ephemeral-credential minting (attenuated, TTL-bounded).
1163    Mint(IRMintStep),
1164    /// §Fase 94.b — mediated secret renewal (`rotation_without_revelation`).
1165    Rotate(IRRotateStep),
1166    /// §λ-L-E Fase 13 — capability extrusion (Publish-Ext).
1167    Publish(IRPublish),
1168    /// §λ-L-E Fase 13 — dual of publish (typed handle import).
1169    Discover(IRDiscover),
1170    Persist(IRPersistStep),
1171    Retrieve(IRRetrieveStep),
1172    Mutate(IRMutateStep),
1173    Purge(IRPurgeStep),
1174    Transact(IRTransactBlock),
1175    /// §Fase 88.a — the `warden` adversarial security-analysis block.
1176    Warden(IRWarden),
1177    /// §Fase 51.a — the `quant` cognitive block (Hilbert-space projection).
1178    Quant(IRQuant),
1179    /// §Fase 51.d.2 — the `yield` measurement point inside a `quant` block.
1180    Yield(IRYield),
1181    /// §Fase 52.c — `run <Flow>(args)` flow-step: invoke a declared flow from a
1182    /// body (a daemon listen handler). Reuses [`IRRun`] (the top-level run IR).
1183    Run(IRRun),
1184}
1185
1186#[derive(Debug, Clone, Serialize)]
1187pub struct IRProbe {
1188    pub node_type: &'static str,
1189    pub source_line: u32,
1190    pub source_column: u32,
1191    pub target: String,
1192}
1193
1194#[derive(Debug, Clone, Serialize)]
1195pub struct IRReasonStep {
1196    pub node_type: &'static str,
1197    pub source_line: u32,
1198    pub source_column: u32,
1199    pub strategy: String,
1200    pub target: String,
1201}
1202
1203#[derive(Debug, Clone, Serialize)]
1204pub struct IRValidateStep {
1205    pub node_type: &'static str,
1206    pub source_line: u32,
1207    pub source_column: u32,
1208    pub target: String,
1209    pub rule: String,
1210}
1211
1212#[derive(Debug, Clone, Serialize)]
1213pub struct IRRefineStep {
1214    pub node_type: &'static str,
1215    pub source_line: u32,
1216    pub source_column: u32,
1217    pub target: String,
1218    pub strategy: String,
1219}
1220
1221#[derive(Debug, Clone, Serialize)]
1222pub struct IRWeaveStep {
1223    pub node_type: &'static str,
1224    pub source_line: u32,
1225    pub source_column: u32,
1226    pub sources: Vec<String>,
1227    pub target: String,
1228    pub format_type: String,
1229    pub priority: Vec<String>,
1230    pub style: String,
1231}
1232
1233#[derive(Debug, Clone, Serialize)]
1234pub struct IRUseToolStep {
1235    pub node_type: &'static str,
1236    pub source_line: u32,
1237    pub source_column: u32,
1238    pub tool_name: String,
1239    pub argument: String,
1240    /// §Fase 58.c — the bound keyword args of `use Tool(k = v, …)` (W1: the
1241    /// structured args survive to the IR, no longer collapsed to one opaque
1242    /// string). Empty for the legacy single-`on <arg>` form (`argument`
1243    /// carries that, D5).
1244    pub named_args: Vec<IRNamedArg>,
1245}
1246
1247#[derive(Debug, Clone, Serialize)]
1248pub struct IRRememberStep {
1249    pub node_type: &'static str,
1250    pub source_line: u32,
1251    pub source_column: u32,
1252    pub expression: String,
1253    pub memory_target: String,
1254}
1255
1256#[derive(Debug, Clone, Serialize)]
1257pub struct IRRecallStep {
1258    pub node_type: &'static str,
1259    pub source_line: u32,
1260    pub source_column: u32,
1261    pub query: String,
1262    pub memory_source: String,
1263}
1264
1265/// §Fase 70.a — the lowered form of a pure expression (`Expr`). Carried in the
1266/// IR for conditions the legacy `(condition, op, value)` triple cannot express.
1267/// Operators are canonical lowercase strings so the JSON is stable + readable;
1268/// the runtime evaluator (§70.f) matches on them. Externally-tagged by `kind`.
1269#[derive(Debug, Clone, Serialize)]
1270#[serde(tag = "kind", rename_all = "snake_case")]
1271pub enum IRExpr {
1272    /// A typed literal.
1273    Lit { lit: IRExprLit },
1274    /// A reference to a binding / dotted path.
1275    Ref { path: String },
1276    /// Unary op — `op ∈ {neg, not}`.
1277    Unary { op: String, operand: Box<IRExpr> },
1278    /// Binary op — `op ∈ {add,sub,mul,div,mod,eq,ne,lt,le,gt,ge,and,or}`.
1279    Binary {
1280        op: String,
1281        lhs: Box<IRExpr>,
1282        rhs: Box<IRExpr>,
1283    },
1284    /// §Fase 70.c — a closed-catalog builtin call. `args[0]` is the receiver.
1285    /// `builtin ∈ {length,count,is_empty,is_null,contains,starts_with,ends_with}`.
1286    Call {
1287        builtin: String,
1288        args: Vec<IRExpr>,
1289    },
1290    /// §Fase 70.d — field access on a non-reference base (the JSONB seam).
1291    Field {
1292        base: Box<IRExpr>,
1293        field: String,
1294    },
1295    /// §Fase 70.d — index access `base[index]`.
1296    Index {
1297        base: Box<IRExpr>,
1298        index: Box<IRExpr>,
1299    },
1300}
1301
1302/// §Fase 70.a — a literal inside an [`IRExpr`].
1303#[derive(Debug, Clone, Serialize)]
1304#[serde(tag = "ty", rename_all = "snake_case")]
1305pub enum IRExprLit {
1306    Int { value: i64 },
1307    Float { value: f64 },
1308    Bool { value: bool },
1309    Str { value: String },
1310}
1311
1312#[derive(Debug, Clone, Serialize)]
1313pub struct IRConditional {
1314    pub node_type: &'static str,
1315    pub source_line: u32,
1316    pub source_column: u32,
1317    pub condition: String,
1318    pub comparison_op: String,
1319    pub comparison_value: String,
1320    pub then_body: Vec<IRFlowNode>,
1321    pub else_body: Vec<IRFlowNode>,
1322    pub conditions: Vec<(String, String, String)>,
1323    pub conjunctor: String,
1324    /// §Fase 70.a — the lowered expression form, present only for conditions
1325    /// the legacy triple cannot express. `skip_serializing_if` keeps the IR
1326    /// JSON (and its SHA) byte-identical for every pre-§70 program.
1327    #[serde(skip_serializing_if = "Option::is_none")]
1328    pub cond: Option<IRExpr>,
1329}
1330
1331#[derive(Debug, Clone, Serialize)]
1332pub struct IRForIn {
1333    pub node_type: &'static str,
1334    pub source_line: u32,
1335    pub source_column: u32,
1336    pub variable: String,
1337    pub iterable: String,
1338    pub body: Vec<IRFlowNode>,
1339}
1340
1341#[derive(Debug, Clone, Serialize)]
1342pub struct IRLetBinding {
1343    pub node_type: &'static str,
1344    pub source_line: u32,
1345    pub source_column: u32,
1346    pub target: String,
1347    pub value: String,
1348    /// Fase 17.a — preserves parser tokenization intent.
1349    /// One of "literal" | "reference" | "expression".
1350    pub value_kind: String,
1351    /// §Fase 70.f — the lowered expression form of the value, present only for
1352    /// `value_kind == "expression"`. The runtime evaluates it instead of
1353    /// treating the value string as an opaque literal. `skip_serializing_if`
1354    /// keeps the IR byte-identical for every literal / reference let.
1355    #[serde(skip_serializing_if = "Option::is_none")]
1356    pub value_ast: Option<IRExpr>,
1357}
1358
1359#[derive(Debug, Clone, Serialize)]
1360pub struct IRReturnStep {
1361    pub node_type: &'static str,
1362    pub source_line: u32,
1363    pub source_column: u32,
1364    pub value_expr: String,
1365}
1366
1367/// Fase 19.e — `break` keyword IR node. Payload-free (the runner
1368/// raises a sentinel; no value is carried). Mirrors Python's
1369/// ``IRBreak`` (axon/compiler/ir_nodes.py).
1370#[derive(Debug, Clone, Serialize)]
1371pub struct IRBreakStep {
1372    pub node_type: &'static str,
1373    pub source_line: u32,
1374    pub source_column: u32,
1375}
1376
1377/// Fase 19.e — `continue` keyword IR node. Same shape as
1378/// ``IRBreakStep``; the runner uses a different sentinel type to
1379/// distinguish loop-exit (break) from iteration-skip (continue).
1380#[derive(Debug, Clone, Serialize)]
1381pub struct IRContinueStep {
1382    pub node_type: &'static str,
1383    pub source_line: u32,
1384    pub source_column: u32,
1385}
1386
1387#[derive(Debug, Clone, Serialize)]
1388pub struct IRParallelBlock {
1389    pub node_type: &'static str,
1390    pub source_line: u32,
1391    pub source_column: u32,
1392    /// §Fase 65 — the concurrent branches lowered from the AST `par { … }`.
1393    /// Each branch is a flow-IR body run concurrently by the dispatcher's
1394    /// `run_branches_concurrently`. `skip_serializing_if = "Vec::is_empty"` so a
1395    /// payload-free / empty `par` serializes byte-identically to the pre-§65
1396    /// shape (D5 back-compat); a `par` with real branches carries them.
1397    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1398    pub branches: Vec<Vec<IRFlowNode>>,
1399}
1400
1401#[derive(Debug, Clone, Serialize)]
1402pub struct IRHibernateStep {
1403    pub node_type: &'static str,
1404    pub source_line: u32,
1405    pub source_column: u32,
1406    pub event_name: String,
1407    pub timeout: String,
1408}
1409
1410#[derive(Debug, Clone, Serialize)]
1411pub struct IRDeliberateBlock {
1412    pub node_type: &'static str,
1413    pub source_line: u32,
1414    pub source_column: u32,
1415}
1416
1417#[derive(Debug, Clone, Serialize)]
1418pub struct IRConsensusBlock {
1419    pub node_type: &'static str,
1420    pub source_line: u32,
1421    pub source_column: u32,
1422}
1423
1424/// §Fase 86 — the compiled Directed Creative Synthesis block. This IS the
1425/// "structured IR metadata that the runtime executes as an orchestrated
1426/// pipeline" the README always claimed — pre-§86 it carried only a source
1427/// location. New fields are `skip_serializing_if`-elided so a program with no
1428/// `forge` stays IR-SHA stable.
1429#[derive(Debug, Clone, Serialize, Default)]
1430pub struct IRForgeBlock {
1431    pub node_type: &'static str,
1432    pub source_line: u32,
1433    pub source_column: u32,
1434    #[serde(default, skip_serializing_if = "String::is_empty")]
1435    pub name: String,
1436    #[serde(default, skip_serializing_if = "String::is_empty")]
1437    pub seed: String,
1438    #[serde(default, skip_serializing_if = "String::is_empty")]
1439    pub output_type: String,
1440    #[serde(default, skip_serializing_if = "String::is_empty")]
1441    pub mode: String,
1442    #[serde(default, skip_serializing_if = "is_default_novelty")]
1443    pub novelty: f64,
1444    #[serde(default, skip_serializing_if = "is_one_i64")]
1445    pub depth: i64,
1446    #[serde(default, skip_serializing_if = "is_one_i64")]
1447    pub branches: i64,
1448    #[serde(default, skip_serializing_if = "String::is_empty")]
1449    pub constraints_ref: String,
1450}
1451
1452fn is_default_novelty(v: &f64) -> bool {
1453    (*v - 0.5).abs() < f64::EPSILON
1454}
1455fn is_one_i64(v: &i64) -> bool {
1456    *v == 1
1457}
1458
1459/// §Fase 109.a — the proof-carrying derivative. `original` is the
1460/// differentiated `let`'s expression; `derivatives[i]` = ∂original/∂wrt[i],
1461/// SIMPLIFIED (D109.4) — computed at compile time by the symbolic
1462/// differentiator and re-derived at deploy by PCC `GradientSoundness`.
1463/// `original: None` / empty `derivatives` only in a stale artifact — the
1464/// runtime fails CLOSED on it and the PCC refutes it.
1465#[derive(Debug, Clone, Serialize)]
1466pub struct IRGradStep {
1467    pub node_type: &'static str,
1468    pub source_line: u32,
1469    pub source_column: u32,
1470    /// The prior rich `let` differentiated.
1471    pub target: String,
1472    pub wrt: Vec<String>,
1473    /// Result binding (empty ⇒ `d_<target>`).
1474    pub output: String,
1475    pub original: Option<IRExpr>,
1476    pub derivatives: Vec<IRExpr>,
1477}
1478
1479#[derive(Debug, Clone, Serialize)]
1480pub struct IRFocusStep {
1481    pub node_type: &'static str,
1482    pub source_line: u32,
1483    pub source_column: u32,
1484    pub expression: String,
1485    /// §Fase 108.d — the data-plane `where:` (D108.9; empty ⇒ no filter).
1486    pub where_expr: String,
1487    /// §Fase 108.d — π: projected columns (empty ⇒ all).
1488    pub select: Vec<String>,
1489    /// §Fase 108.d — result binding (`as:`; empty ⇒ the dataspace name).
1490    pub output: String,
1491}
1492
1493#[derive(Debug, Clone, Serialize)]
1494pub struct IRAssociateStep {
1495    pub node_type: &'static str,
1496    pub source_line: u32,
1497    pub source_column: u32,
1498    pub left: String,
1499    pub right: String,
1500    pub using_field: String,
1501    /// §Fase 108.d — result binding (`as:`; empty ⇒ `<L>_<R>`).
1502    pub output: String,
1503}
1504
1505#[derive(Debug, Clone, Serialize)]
1506pub struct IRAggregateStep {
1507    pub node_type: &'static str,
1508    pub source_line: u32,
1509    pub source_column: u32,
1510    pub target: String,
1511    pub group_by: Vec<String>,
1512    pub alias: String,
1513    /// §Fase 108.d — the closed aggregate catalog entries, raw
1514    /// (`count`, `sum(score)`, …) — canonical spelling, T930-validated.
1515    pub compute: Vec<String>,
1516    /// §Fase 108.d — the data-plane `where:` (D108.9).
1517    pub where_expr: String,
1518}
1519
1520#[derive(Debug, Clone, Serialize)]
1521pub struct IRExploreStep {
1522    pub node_type: &'static str,
1523    pub source_line: u32,
1524    pub source_column: u32,
1525    pub target: String,
1526    pub limit: Option<i64>,
1527    /// §Fase 108.d — result binding (`as:`; empty ⇒ the target).
1528    pub output: String,
1529}
1530
1531#[derive(Debug, Clone, Serialize)]
1532pub struct IRIngestStep {
1533    pub node_type: &'static str,
1534    pub source_line: u32,
1535    pub source_column: u32,
1536    pub source: String,
1537    pub target: String,
1538    /// §Fase 108.c — the declared wire format (`csv` | `json`, validated
1539    /// by axon-T929). Empty only in a pre-108.c artifact — the runtime
1540    /// handler fails CLOSED on it.
1541    pub format: String,
1542    /// §Fase 108.c — bounds enforced on the raw byte stream BEFORE
1543    /// parsing (§100). `None` ⇒ the engine's conservative defaults.
1544    pub max_bytes: Option<u64>,
1545    pub max_rows: Option<u64>,
1546}
1547
1548/// §Fase 114.w — a shield's compiled BREACH POLICY, resolved onto the nodes
1549/// that enforce it (`IRShieldApplyStep` / `IREmit`) at LOWERING — the same
1550/// discipline as `IREmit.shield_ref`: the policy rides the artifact, so every
1551/// dispatch path honors it by construction (no per-ctx shield map a forgotten
1552/// site could miss). Before §114.w the whole `on_breach:` catalog
1553/// (`halt|sanitize_and_retry|escalate|quarantine|deflect`) was documented,
1554/// parsed, type-checked — and the runtime always `halt`ed.
1555#[derive(Debug, Clone, Serialize)]
1556pub struct IRBreachPolicy {
1557    /// The declared policy (validated against `VALID_ON_BREACH_POLICIES`).
1558    pub on_breach: String,
1559    /// The quarantine SINK name (`on_breach: quarantine` requires it, axon-T952).
1560    #[serde(default, skip_serializing_if = "String::is_empty")]
1561    pub quarantine: String,
1562    /// The canned safe reply (`on_breach: deflect` requires it, axon-T952).
1563    #[serde(default, skip_serializing_if = "String::is_empty")]
1564    pub deflect_message: String,
1565    /// Fields masked by `sanitize_and_retry` (requires ≥ 1, axon-T952).
1566    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1567    pub redact: Vec<String>,
1568    /// Re-scan budget for `sanitize_and_retry` (parser default: 3).
1569    pub max_retries: i64,
1570}
1571
1572#[derive(Debug, Clone, Serialize)]
1573pub struct IRShieldApplyStep {
1574    pub node_type: &'static str,
1575    pub source_line: u32,
1576    pub source_column: u32,
1577    pub shield_name: String,
1578    pub target: String,
1579    pub output_type: String,
1580    /// §Fase 114.w — the named shield's breach policy, resolved at lowering.
1581    /// `None` ⇒ the shield declares no `on_breach:` (halt, the fail-closed
1582    /// default) — and every pre-§114.w program serializes byte-identically.
1583    #[serde(default, skip_serializing_if = "Option::is_none")]
1584    pub breach_policy: Option<IRBreachPolicy>,
1585}
1586
1587#[derive(Debug, Clone, Serialize)]
1588pub struct IRStreamBlock {
1589    pub node_type: &'static str,
1590    pub source_line: u32,
1591    pub source_column: u32,
1592    /// §Fase 111.e — the block's lowered body. ADDITIVE: `skip_serializing_if`
1593    /// elides it when empty, so every pre-111 program's IR JSON stays
1594    /// byte-identical and a legacy IR deserialises to an empty body (which then
1595    /// executes as a no-op, exactly as before — no silent behaviour change for
1596    /// an artifact compiled by an older frontend).
1597    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1598    pub body: Vec<IRFlowNode>,
1599}
1600
1601#[derive(Debug, Clone, Serialize)]
1602pub struct IRNavigateStep {
1603    pub node_type: &'static str,
1604    pub source_line: u32,
1605    pub source_column: u32,
1606    pub pix_ref: String,
1607    pub corpus_ref: String,
1608    pub query: String,
1609    pub trail_enabled: bool,
1610    pub output_name: String,
1611    /// §Fase 63.B — MDN corpus-graph navigation: the seed document (`from:`).
1612    #[serde(default, skip_serializing_if = "String::is_empty")]
1613    pub seed: String,
1614    /// §Fase 63.B — MDN navigation budget (`budget:` = max documents).
1615    #[serde(default, skip_serializing_if = "Option::is_none")]
1616    pub budget: Option<i64>,
1617    /// §Fase 66 (Q2) — column-scope filter for a `corpus from axonstore`. A raw
1618    /// filter expr threaded to `read_all_store_rows` → `stream_retrieve` for
1619    /// BOTH the documents and edges stores, so the sourced MDN graph is scoped
1620    /// to a sub-tenant column (`where: "tenant_id == '${tenant_id}'"`). The
1621    /// §37.d filter compiler resolves `${name}` → `$N` bind params (injection-
1622    /// safe). Empty = no column filter (axon-tenant RLS scope only).
1623    #[serde(default, skip_serializing_if = "String::is_empty")]
1624    pub where_expr: String,
1625}
1626
1627#[derive(Debug, Clone, Serialize)]
1628pub struct IRDrillStep {
1629    pub node_type: &'static str,
1630    pub source_line: u32,
1631    pub source_column: u32,
1632    pub pix_ref: String,
1633    pub subtree_path: String,
1634    pub query: String,
1635    pub output_name: String,
1636}
1637
1638#[derive(Debug, Clone, Serialize)]
1639pub struct IRTrailStep {
1640    pub node_type: &'static str,
1641    pub source_line: u32,
1642    pub source_column: u32,
1643    pub navigate_ref: String,
1644}
1645
1646#[derive(Debug, Clone, Serialize)]
1647pub struct IRCorroborateStep {
1648    pub node_type: &'static str,
1649    pub source_line: u32,
1650    pub source_column: u32,
1651    pub navigate_ref: String,
1652    pub output_name: String,
1653}
1654
1655#[derive(Debug, Clone, Serialize)]
1656pub struct IROtsApplyStep {
1657    pub node_type: &'static str,
1658    pub source_line: u32,
1659    pub source_column: u32,
1660    pub ots_name: String,
1661    pub target: String,
1662    pub output_type: String,
1663}
1664
1665#[derive(Debug, Clone, Serialize)]
1666pub struct IRMandateApplyStep {
1667    pub node_type: &'static str,
1668    pub source_line: u32,
1669    pub source_column: u32,
1670    pub mandate_name: String,
1671    pub target: String,
1672    pub output_type: String,
1673}
1674
1675#[derive(Debug, Clone, Serialize)]
1676pub struct IRComputeApplyStep {
1677    pub node_type: &'static str,
1678    pub source_line: u32,
1679    pub source_column: u32,
1680    pub compute_name: String,
1681    pub arguments: Vec<String>,
1682    pub output_name: String,
1683}
1684
1685#[derive(Debug, Clone, Serialize)]
1686pub struct IRListenStep {
1687    pub node_type: &'static str,
1688    pub source_line: u32,
1689    pub source_column: u32,
1690    pub channel: String,
1691    /// §λ-L-E Fase 13 D4 — true ⇒ `channel` is a declared
1692    /// `IRChannel` ref; false ⇒ legacy string topic.
1693    pub channel_is_ref: bool,
1694    pub event_alias: String,
1695    /// §Fase 52.a — the handler body's lowered flow-steps, executed per event /
1696    /// scheduled tick by the §52.c runtime. `skip_serializing_if` keeps a
1697    /// bodyless `listen`'s JSON byte-identical to the pre-§52.a shape (D8).
1698    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1699    pub body: Vec<IRFlowNode>,
1700}
1701
1702#[derive(Debug, Clone, Serialize)]
1703pub struct IRDaemonStepNode {
1704    pub node_type: &'static str,
1705    pub source_line: u32,
1706    pub source_column: u32,
1707    pub daemon_ref: String,
1708}
1709
1710#[derive(Debug, Clone, Serialize)]
1711pub struct IRPersistStep {
1712    pub node_type: &'static str,
1713    pub source_line: u32,
1714    pub source_column: u32,
1715    pub store_name: String,
1716    /// §Fase 35.o — declared `{ col: value }` field block (value
1717    /// expressions kept raw; interpolated at runtime). Empty ⇒ the
1718    /// runtime writes the flow's user bindings (v1.30.0 fallback).
1719    pub fields: Vec<(String, String)>,
1720}
1721
1722#[derive(Debug, Clone, Serialize)]
1723pub struct IRRetrieveStep {
1724    pub node_type: &'static str,
1725    pub source_line: u32,
1726    pub source_column: u32,
1727    pub store_name: String,
1728    pub where_expr: String,
1729    pub alias: String,
1730    /// §Fase 67.b — `order_by:` clause (raw `"col [asc|desc], …"`).
1731    /// `skip_serializing_if` empty so a store that doesn't order never
1732    /// perturbs the serialized IR bytes (the §52 brief-#33 /
1733    /// [[feedback-boot-hydrate-self-heal]] no-drift discipline).
1734    #[serde(skip_serializing_if = "String::is_empty", default)]
1735    pub order_by: String,
1736    /// §Fase 67.b — `limit:` clause (raw `"100"` or `"${max}"`).
1737    #[serde(skip_serializing_if = "String::is_empty", default)]
1738    pub limit_expr: String,
1739    /// §Fase 76.d — `aggregate:` clause (raw, closed catalog: `count` /
1740    /// `sum(col)` / `avg(col)` / `min(col)` / `max(col)`).
1741    /// `skip_serializing_if` empty so a non-aggregating retrieve never
1742    /// perturbs the serialized IR bytes (the same §67.b no-drift
1743    /// discipline — zero IR-SHA drift for existing programs).
1744    #[serde(skip_serializing_if = "String::is_empty", default)]
1745    pub aggregate: String,
1746    /// §Fase 76.d — `group_by:` clause (raw `"col, col2"`).
1747    #[serde(skip_serializing_if = "String::is_empty", default)]
1748    pub group_by: String,
1749    /// §Fase 85.b — `cache:` reference (a declared `cache` name). Empty ⇒
1750    /// uncached. Elided when empty (IR-SHA stable for cache-less retrieves).
1751    #[serde(skip_serializing_if = "String::is_empty", default)]
1752    pub cache: String,
1753}
1754
1755#[derive(Debug, Clone, Serialize)]
1756pub struct IRMutateStep {
1757    pub node_type: &'static str,
1758    pub source_line: u32,
1759    pub source_column: u32,
1760    pub store_name: String,
1761    pub where_expr: String,
1762    /// §Fase 35.p — declared `{ col: value }` SET assignments (value
1763    /// expressions kept raw; interpolated at runtime). Empty ⇒ the
1764    /// runtime writes the flow's user bindings (v1.31.0 fallback).
1765    pub fields: Vec<(String, String)>,
1766}
1767
1768#[derive(Debug, Clone, Serialize)]
1769pub struct IRPurgeStep {
1770    pub node_type: &'static str,
1771    pub source_line: u32,
1772    pub source_column: u32,
1773    pub store_name: String,
1774    pub where_expr: String,
1775}
1776
1777#[derive(Debug, Clone, Serialize)]
1778pub struct IRTransactBlock {
1779    pub node_type: &'static str,
1780    pub source_line: u32,
1781    pub source_column: u32,
1782}
1783
1784/// §Fase 88.a — IR for the `warden` adversarial-analysis block. Carries the
1785/// target, the mandatory `scope_ref`, and the recursively-lowered body so the
1786/// enterprise engine (§88.f) can drive the analysis and §88.c can enforce the
1787/// authorization discipline.
1788#[derive(Debug, Clone, Serialize)]
1789pub struct IRWarden {
1790    pub node_type: &'static str,
1791    pub source_line: u32,
1792    pub source_column: u32,
1793    pub target: String,
1794    pub scope_ref: String,
1795    /// Nested flow-body IR (recursively lowered).
1796    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1797    pub body: Vec<IRFlowNode>,
1798}
1799
1800/// §Fase 88.a — IR for a `scope` authorization-policy declaration.
1801#[derive(Debug, Clone, Serialize)]
1802pub struct IRScope {
1803    pub node_type: &'static str,
1804    pub source_line: u32,
1805    pub source_column: u32,
1806    pub name: String,
1807    pub targets: Vec<String>,
1808    pub depth: String,
1809    pub approver: String,
1810}
1811
1812/// §Fase 51.a — IR for the `quant` cognitive block (Hilbert-space projection).
1813/// Mirrors `ast::QuantBlock`. Optional attributes serialize only when present
1814/// (`skip_serializing_if`) so a bare `quant {}` lowers to a minimal node and
1815/// the JSON stays diff-stable. The body lowers recursively, like `par` branches.
1816#[derive(Debug, Clone, Serialize)]
1817pub struct IRQuant {
1818    pub node_type: &'static str,
1819    pub source_line: u32,
1820    pub source_column: u32,
1821    /// Encoding scheme surface spelling (`amplitude` | `angle`); `None` = default.
1822    #[serde(default, skip_serializing_if = "Option::is_none")]
1823    pub encoding: Option<String>,
1824    /// Referenced `Observable` (Pauli-sum) name; `None` if unspecified.
1825    #[serde(default, skip_serializing_if = "Option::is_none")]
1826    pub observable: Option<String>,
1827    /// Register width n; `None` = inferred.
1828    #[serde(default, skip_serializing_if = "Option::is_none")]
1829    pub qubits: Option<i64>,
1830    /// Variational circuit depth L; `None` = backend default.
1831    #[serde(default, skip_serializing_if = "Option::is_none")]
1832    pub depth: Option<i64>,
1833    /// Projected-kernel bandwidth γ (D7); `None` = backend default.
1834    #[serde(default, skip_serializing_if = "Option::is_none")]
1835    pub bandwidth: Option<f64>,
1836    /// §Fase 69.c — data re-uploading layers L (`None`/`1` = no re-uploading).
1837    /// `skip_serializing_if` keeps a non-re-uploading block's IR byte-identical.
1838    #[serde(default, skip_serializing_if = "Option::is_none")]
1839    pub reupload: Option<i64>,
1840    /// Algebraic-effect backend tag (`quant_sim` | `qpu_native`).
1841    pub effect: String,
1842    /// Nested flow-body IR (recursively lowered).
1843    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1844    pub body: Vec<IRFlowNode>,
1845}
1846
1847// ── Tier 2 IR nodes ─────────────────────────────────────────────────────────
1848
1849#[derive(Debug, Clone, Serialize)]
1850pub struct IRAgent {
1851    pub node_type: &'static str,
1852    pub source_line: u32,
1853    pub source_column: u32,
1854    pub name: String,
1855    pub goal: String,
1856    pub tools: Vec<String>,
1857    pub memory_ref: String,
1858    pub strategy: String,
1859    pub on_stuck: String,
1860    pub shield_ref: String,
1861    pub max_iterations: Option<i64>,
1862    pub max_tokens: Option<i64>,
1863    pub max_time: String,
1864    pub max_cost: Option<f64>,
1865}
1866
1867/// §Fase 71.a — the lowered temporal execution-window guard. The runtime
1868/// (§71.b) evaluates `is_in_window(now, tz, allow)`; the daemon binding +
1869/// coalesced defer ledger are §71.c/d.
1870#[derive(Debug, Clone, Serialize)]
1871pub struct IRWindow {
1872    pub node_type: &'static str,
1873    pub source_line: u32,
1874    pub source_column: u32,
1875    pub name: String,
1876    pub timezone: String,
1877    pub allow: Vec<IRWindowSpan>,
1878    /// §Fase 71.e — excluded dates (holidays): ISO `YYYY-MM-DD` literals. A tick
1879    /// whose local date is in this set is OUTSIDE regardless of the hour spans.
1880    /// `skip_serializing_if` keeps a holiday-less window's JSON byte-identical.
1881    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1882    pub exclude: Vec<String>,
1883    pub on_outside: String,
1884}
1885
1886/// §Fase 71.a — one allowed day/hour span.
1887#[derive(Debug, Clone, Serialize)]
1888pub struct IRWindowSpan {
1889    pub day_start: String,
1890    pub day_end: String,
1891    pub hour_start: i64,
1892    pub hour_end: i64,
1893}
1894
1895/// §Fase 72.a — the `budget { … }` linear-effect rate limit lowered to IR. Each
1896/// quota gates a declared tool's dispatch on a renewable token bucket (the §72.b
1897/// `RateLease`); `on_exhausted` is the exhaustion policy.
1898#[derive(Debug, Clone, Serialize)]
1899pub struct IRBudget {
1900    pub node_type: &'static str,
1901    pub source_line: u32,
1902    pub source_column: u32,
1903    /// §Fase 114.a — the name of a **top-level** `budget`. Empty ⇒ the anonymous
1904    /// daemon-attached form. Skip-if-empty ⇒ every pre-§114 program serializes
1905    /// byte-identically (IR-SHA stability).
1906    #[serde(default, skip_serializing_if = "String::is_empty")]
1907    pub name: String,
1908    pub quotas: Vec<IRBudgetQuota>,
1909    /// `block` (fail-closed) | `defer` (reschedule via the §71 defer ledger) |
1910    /// `shed` (skip the call). An omitted policy lowers to `block` (the safe
1911    /// fail-closed default).
1912    pub on_exhausted: String,
1913}
1914
1915/// §Fase 72.a — one quota: `<kind>: <limit> per <period> on Tool(<effect>)`.
1916#[derive(Debug, Clone, Serialize)]
1917pub struct IRBudgetQuota {
1918    /// `rate` (renewable bucket) | `max` (windowed hard cap, no intra-window refill).
1919    pub kind: String,
1920    /// Token allowance per period (> 0, validated by `axon-T831`).
1921    pub limit: i64,
1922    /// `second` | `minute` | `hour` | `day` (closed catalog, `axon-T832`).
1923    pub period: String,
1924    /// The declared tool this quota governs (`on Tool(X)`; resolved by `axon-T830`).
1925    pub effect: String,
1926}
1927
1928#[derive(Debug, Clone, Serialize)]
1929pub struct IRShield {
1930    pub node_type: &'static str,
1931    pub source_line: u32,
1932    pub source_column: u32,
1933    pub name: String,
1934    pub scan: Vec<String>,
1935    pub strategy: String,
1936    pub on_breach: String,
1937    pub severity: String,
1938    pub quarantine: String,
1939    /// §8.2.h.3 — Python emits concrete 0, not null. AST keeps `Option<i64>`
1940    /// so the parser can distinguish "not set"; IR lowering collapses.
1941    pub max_retries: i64,
1942    pub confidence_threshold: f64,
1943    pub allow_tools: Vec<String>,
1944    pub deny_tools: Vec<String>,
1945    pub sandbox: bool,
1946    pub redact: Vec<String>,
1947    pub log: String,
1948    pub deflect_message: String,
1949    // `taint` exists on `ShieldDefinition` (AST) but Python's reference
1950    // IRShield doesn't emit it. Hidden from JSON output for §8.2.h parity.
1951    #[serde(skip)]
1952    pub taint: String,
1953    /// §ESK Fase 6.1 — covered regulatory classes for this shield.
1954    pub compliance: Vec<String>,
1955    /// §Fase 77.a — egress signing algorithm (`hmac_sha256`; empty = the
1956    /// shield does not sign). Elided from JSON when empty so every pre-§77
1957    /// program's IR stays byte-identical (zero IR-SHA drift).
1958    #[serde(skip_serializing_if = "String::is_empty")]
1959    pub sign: String,
1960}
1961
1962#[derive(Debug, Clone, Serialize)]
1963pub struct IRPix {
1964    pub node_type: &'static str,
1965    pub source_line: u32,
1966    pub source_column: u32,
1967    pub name: String,
1968    pub source: String,
1969    pub depth: Option<i64>,
1970    pub branching: Option<i64>,
1971    pub model: String,
1972}
1973
1974/// §Fase 62.0 — the audit-chain (`ledger`) IR node. Same shape as [`IRPix`]
1975/// but a DISTINCT node (`node_type: "ledger"`): a ledger binds a hash-linked
1976/// recorder to an audited surface (`source`), retaining `depth` rows under a
1977/// `branching`-factor Merkle tree, hashed with `model`. Kept separate from
1978/// `IRPix` so the navigator and the audit chain never alias on the wire.
1979#[derive(Debug, Clone, Serialize)]
1980pub struct IRLedger {
1981    pub node_type: &'static str,
1982    pub source_line: u32,
1983    pub source_column: u32,
1984    pub name: String,
1985    pub source: String,
1986    pub depth: Option<i64>,
1987    pub branching: Option<i64>,
1988    pub model: String,
1989}
1990
1991#[derive(Debug, Clone, Serialize)]
1992pub struct IRPsyche {
1993    pub node_type: &'static str,
1994    pub source_line: u32,
1995    pub source_column: u32,
1996    pub name: String,
1997    pub dimensions: Vec<String>,
1998    pub manifold_noise: Option<f64>,
1999    pub manifold_momentum: Option<f64>,
2000    pub safety_constraints: Vec<String>,
2001    pub quantum_enabled: Option<bool>,
2002    pub inference_mode: String,
2003}
2004
2005#[derive(Debug, Clone, Serialize)]
2006pub struct IRCorpus {
2007    pub node_type: &'static str,
2008    pub source_line: u32,
2009    pub source_column: u32,
2010    pub name: String,
2011    pub documents: Vec<String>,
2012    /// §Fase 63.A — typed weighted edges. Non-empty ⇒ this corpus is an MDN
2013    /// graph `C = (D, R, τ, ω, σ)`; the runtime builds an `mdn::Corpus` from it.
2014    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2015    pub relations: Vec<IRCorpusRelation>,
2016    /// §Fase 63.C — `adaptive: true` enables the memory endofunctor on this
2017    /// corpus's navigations.
2018    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2019    pub adaptive: bool,
2020    pub mcp_server: String,
2021    pub mcp_resource_uri: String,
2022    /// §Fase 64.A — when present, this is a DYNAMIC store-sourced MDN graph: the
2023    /// documents and typed edges are rows in two declared `axonstore`s and the
2024    /// runtime builds the `mdn::Corpus` from the live rows at navigate-time
2025    /// (per-tenant, growing). Absent ⇒ the static §63 corpus (byte-identical IR).
2026    #[serde(default, skip_serializing_if = "Option::is_none")]
2027    pub store_source: Option<IRCorpusStoreSource>,
2028}
2029
2030/// §Fase 63.A — a lowered MDN corpus-graph edge `(from, to, τ, ω)`.
2031#[derive(Debug, Clone, Serialize)]
2032pub struct IRCorpusRelation {
2033    pub etype: String,
2034    pub from: String,
2035    pub to: String,
2036    pub weight: f64,
2037}
2038
2039/// §Fase 64.A — the lowered store-mapping of a dynamic, `axonstore`-sourced MDN
2040/// corpus graph. `doc_store(doc_id, doc_title)` maps rows → nodes;
2041/// `edge_store(edge_from, edge_to, edge_type, edge_weight)` maps rows → typed
2042/// weighted edges. The runtime (§64.B) reads these stores tenant-scoped at
2043/// navigate-time to build the `mdn::Corpus`.
2044#[derive(Debug, Clone, Serialize)]
2045pub struct IRCorpusStoreSource {
2046    pub doc_store: String,
2047    pub doc_id: String,
2048    pub doc_title: String,
2049    pub edge_store: String,
2050    pub edge_from: String,
2051    pub edge_to: String,
2052    pub edge_type: String,
2053    pub edge_weight: String,
2054}
2055
2056/// §Fase 108.b — one compiled dataspace column. `column_type` is the
2057/// CANONICAL catalog name (`Text` / `Int` / `Float` / `Bool` /
2058/// `Timestamp` / `Json`) — aliases are resolved at IR generation, so
2059/// every downstream consumer (the engine's deploy hook, the §108.d PCC
2060/// class) reads one spelling.
2061#[derive(Debug, Clone, Serialize)]
2062pub struct IRDataspaceColumn {
2063    pub name: String,
2064    pub column_type: String,
2065}
2066
2067#[derive(Debug, Clone, Serialize)]
2068pub struct IRDataspace {
2069    pub node_type: &'static str,
2070    pub source_line: u32,
2071    pub source_column: u32,
2072    pub name: String,
2073    /// §Fase 108.b — the typed columnar schema (canonical type names).
2074    pub columns: Vec<IRDataspaceColumn>,
2075}
2076
2077#[derive(Debug, Clone, Serialize)]
2078pub struct IROts {
2079    pub node_type: &'static str,
2080    pub source_line: u32,
2081    pub source_column: u32,
2082    pub name: String,
2083    pub teleology: String,
2084    pub homotopy_search: String,
2085    pub loss_function: String,
2086}
2087
2088#[derive(Debug, Clone, Serialize)]
2089pub struct IRMandate {
2090    pub node_type: &'static str,
2091    pub source_line: u32,
2092    pub source_column: u32,
2093    pub name: String,
2094    pub constraint: String,
2095    pub kp: Option<f64>,
2096    pub ki: Option<f64>,
2097    pub kd: Option<f64>,
2098    pub tolerance: Option<f64>,
2099    pub max_steps: Option<i64>,
2100    pub on_violation: String,
2101}
2102
2103#[derive(Debug, Clone, Serialize)]
2104pub struct IRCompute {
2105    pub node_type: &'static str,
2106    pub source_line: u32,
2107    pub source_column: u32,
2108    pub name: String,
2109    pub shield_ref: String,
2110    /// §Fase 111.f — typed parameters. ADDITIVE (`skip_serializing_if`), so every
2111    /// pre-111 program's IR JSON stays byte-identical.
2112    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2113    pub parameters: Vec<IRParameter>,
2114    /// §Fase 111.f — the declared result type.
2115    #[serde(default, skip_serializing_if = "String::is_empty")]
2116    pub return_type: String,
2117    /// §Fase 111.f — the lowered §70 expression the runtime evaluates natively.
2118    /// `None` ⇒ the apply is refused (axon-T941): a compute with no body cannot
2119    /// compute, and binding a placeholder string in its place is how the old
2120    /// runtime handed a downstream step the text `"compute:Name(args)"` where it
2121    /// expected a number.
2122    #[serde(default, skip_serializing_if = "Option::is_none")]
2123    pub body: Option<IRExpr>,
2124}
2125
2126#[derive(Debug, Clone, Serialize)]
2127pub struct IRDaemon {
2128    pub node_type: &'static str,
2129    pub source_line: u32,
2130    pub source_column: u32,
2131    pub name: String,
2132    pub goal: String,
2133    pub tools: Vec<String>,
2134    pub memory_ref: String,
2135    pub strategy: String,
2136    pub on_stuck: String,
2137    pub shield_ref: String,
2138    /// §Fase 71.c — the `window:` temporal binding (a `window` primitive name).
2139    /// Empty ⇒ no temporal guard; `skip_serializing_if` keeps a windowless
2140    /// daemon's JSON byte-identical (D8 zero-drift).
2141    #[serde(default, skip_serializing_if = "String::is_empty")]
2142    pub window_ref: String,
2143    /// §Fase 72.a — the `budget { … }` linear-effect rate limit. `None` ⇒ no
2144    /// budget; `skip_serializing_if` keeps a budgetless daemon's JSON
2145    /// byte-identical (D8 zero-drift).
2146    #[serde(default, skip_serializing_if = "Option::is_none")]
2147    pub budget: Option<IRBudget>,
2148    pub max_tokens: Option<i64>,
2149    pub max_time: String,
2150    pub max_cost: Option<f64>,
2151    /// §Fase 52.a — the daemon's `listen` listeners (channel + alias + handler
2152    /// body). Pre-§52.a these were DROPPED at lowering (the IR daemon carried no
2153    /// listeners at all); now they survive so the §52.c runtime can mount + run
2154    /// them and the §52.d enterprise supervisor can extract them per-tenant.
2155    /// `skip_serializing_if` keeps a listenerless daemon's JSON unchanged (D8).
2156    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2157    pub listeners: Vec<IRListenStep>,
2158    /// §Fase 52.d — the capability scope the daemon's runs are confined to
2159    /// (`requires: [cap, …]`). The enterprise supervisor mints a per-run
2160    /// principal scoped to exactly these. `skip_serializing_if` keeps a
2161    /// requires-less daemon's JSON byte-identical (D8).
2162    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2163    pub requires_capabilities: Vec<String>,
2164}
2165
2166// ── §Fase 87 — the long-horizon autonomous research primitive ────────────────
2167
2168/// §Fase 87.a — a compiled `savant` (long-horizon autonomous research
2169/// primitive). A governed orchestrator: the IR carries the declared surface so
2170/// the enterprise active-inference engine (§87.h+) can drive the FEP loop, and
2171/// the §87.c checker can bind `memory` to a declared store, `budget` to a §72
2172/// linear budget, and the body to a §79 interruptible session.
2173#[derive(Debug, Clone, Serialize)]
2174pub struct IRSavant {
2175    pub node_type: &'static str,
2176    pub source_line: u32,
2177    pub source_column: u32,
2178    pub name: String,
2179    pub domain: String,
2180    #[serde(default, skip_serializing_if = "Option::is_none")]
2181    pub cognition: Option<IRSavantCognition>,
2182    #[serde(default, skip_serializing_if = "Option::is_none")]
2183    pub memory: Option<IRSavantMemory>,
2184    #[serde(default, skip_serializing_if = "Option::is_none")]
2185    pub budget: Option<IRSavantBudget>,
2186    pub mandates: Vec<IRSavantMandate>,
2187}
2188
2189/// §Fase 87.a — the compiled `cognition { … }` sub-block (active-inference
2190/// engine parameters).
2191#[derive(Debug, Clone, Serialize)]
2192pub struct IRSavantCognition {
2193    /// `standard | deep | hyper` — HRR dimensionality tier (validated §87.b).
2194    pub depth: String,
2195    /// Expected-Free-Energy convergence bound (`> 0`, §87.b). `None` ⇒ default.
2196    #[serde(default, skip_serializing_if = "Option::is_none")]
2197    pub entropic_threshold: Option<f64>,
2198    /// `low | med | high` — explore/exploit balance (validated §87.b).
2199    pub divergence: String,
2200}
2201
2202/// §Fase 87.a — the compiled `memory { … }` sub-block (retention binding).
2203#[derive(Debug, Clone, Serialize)]
2204pub struct IRSavantMemory {
2205    /// A declared `memory`/`corpus` name (resolved §87.c). Empty ⇒ ephemeral.
2206    pub backend: String,
2207    /// Whether to index the corpus as a simplicial-complex graph (topological
2208    /// β_n reading).
2209    pub corpus_graph: bool,
2210    /// Per-tenant tensor partitioning level (enforced by the enterprise engine).
2211    pub isolation_level: String,
2212}
2213
2214/// §Fase 87.a — the compiled `budget { … }` sub-block (compute ceiling, bound to
2215/// a §72 linear budget in §87.c).
2216#[derive(Debug, Clone, Serialize)]
2217pub struct IRSavantBudget {
2218    /// Hard ceiling on FEP-loop iterations before the savant pauses.
2219    #[serde(default, skip_serializing_if = "Option::is_none")]
2220    pub max_iterations: Option<i64>,
2221    /// Hard ceiling on `synth` (§87.d) tool-creation events per mandate.
2222    #[serde(default, skip_serializing_if = "Option::is_none")]
2223    pub max_tool_synth: Option<i64>,
2224}
2225
2226/// §Fase 87.a — a compiled `mandate <Name> { … }` sub-block (one research goal).
2227#[derive(Debug, Clone, Serialize)]
2228pub struct IRSavantMandate {
2229    pub name: String,
2230    pub objective: String,
2231    pub output_type: String,
2232}
2233
2234// ── §Fase 99.b — Native Document Synthesis IR ─────────────────────────────────
2235
2236/// §Fase 99.b — a compiled document declaration. The runtime `DocumentRenderer`
2237/// tool serialises this to deterministic OOXML bytes (§99.e); the
2238/// `DocumentProvenanceSoundness` PCC class (§99.d) re-derives the barrier from
2239/// it. `blocks` is the closed-catalog body tree.
2240#[derive(Debug, Clone, Serialize)]
2241pub struct IRDocument {
2242    pub node_type: &'static str,
2243    pub source_line: u32,
2244    pub source_column: u32,
2245    pub name: String,
2246    /// `docx | pptx | xlsx`.
2247    pub target: String,
2248    #[serde(default, skip_serializing_if = "String::is_empty")]
2249    pub template: String,
2250    #[serde(default, skip_serializing_if = "String::is_empty")]
2251    pub provenance: String,
2252    /// The propagated effect row (`io`, `storage`, `sensitive:*`, `legal:*`).
2253    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2254    pub effect_row: Vec<String>,
2255    /// §Fase 99.d — the enclosing `epistemic { mode: … }` at compile time
2256    /// (`believe`/`know` vouch the whole document is ≥ believe, satisfying the
2257    /// assertion-laundering barrier without per-field `attribute:`). Empty at
2258    /// top level. Recorded so the `DocumentProvenanceSoundness` PCC class
2259    /// re-derives the barrier identically (no false refutation).
2260    #[serde(default, skip_serializing_if = "String::is_empty")]
2261    pub epistemic_mode: String,
2262    pub blocks: Vec<IRDocBlock>,
2263}
2264
2265/// §Fase 99.b — one compiled document block. `fields` preserves declaration
2266/// order (a `Vec` of `(name, value)`), so the render is deterministic.
2267#[derive(Debug, Clone, Serialize)]
2268pub struct IRDocBlock {
2269    pub kind: String,
2270    pub fields: Vec<IRDocField>,
2271    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2272    pub children: Vec<IRDocBlock>,
2273}
2274
2275/// §Fase 99.b — a compiled `(field, value)` pair. `kind` tags the value shape
2276/// (`text`|`ref`|`list`|`int`|`bool`) so the renderer + the barrier can
2277/// discriminate a literal from a flow-value reference without re-parsing.
2278#[derive(Debug, Clone, Serialize)]
2279pub struct IRDocField {
2280    pub name: String,
2281    /// `text | ref | list | int | bool`.
2282    pub kind: &'static str,
2283    #[serde(default, skip_serializing_if = "String::is_empty")]
2284    pub value: String,
2285    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2286    pub items: Vec<String>,
2287}
2288
2289// ── §Fase 105 — Governed CRM Delivery IR ─────────────────────────────────────
2290
2291/// §Fase 105 — a compiled delivery declaration. The runtime delivery dispatch
2292/// (`axon::delivery`) transduces this to the configured CRM engine; the
2293/// `DeliveryProvenanceSoundness` PCC class (T920) re-derives the barrier from it.
2294/// `ops` is the closed-catalog operation list.
2295/// §Fase 110 — the compiled `notify` declaration. `epistemic_mode`
2296/// records the enclosing vouch (the §99.d/§105 discipline) so T933
2297/// re-derives identically at deploy (PCC `NotificationProvenanceSoundness`).
2298#[derive(Debug, Clone, Serialize)]
2299pub struct IRNotify {
2300    pub node_type: &'static str,
2301    pub source_line: u32,
2302    pub source_column: u32,
2303    pub name: String,
2304    pub channel: String,
2305    /// The §94 secret-class ref (the recipient value NEVER rides the IR).
2306    pub to_secret: String,
2307    pub template: String,
2308    pub window: String,
2309    #[serde(default, skip_serializing_if = "String::is_empty")]
2310    pub provenance: String,
2311    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2312    pub effects: Vec<String>,
2313    #[serde(default, skip_serializing_if = "String::is_empty")]
2314    pub epistemic_mode: String,
2315}
2316
2317#[derive(Debug, Clone, Serialize)]
2318pub struct IRDeliver {
2319    pub node_type: &'static str,
2320    pub source_line: u32,
2321    pub source_column: u32,
2322    pub name: String,
2323    /// `crm`.
2324    pub target: String,
2325    /// `attached | cleared` (empty ⇒ `attached`). How field provenance crosses
2326    /// the boundary (D105.2) — the T920 barrier's subject.
2327    #[serde(default, skip_serializing_if = "String::is_empty")]
2328    pub provenance: String,
2329    /// The per-tenant credential key (§94 custody — resolved at dispatch, never
2330    /// in cognition).
2331    #[serde(default, skip_serializing_if = "String::is_empty")]
2332    pub secret: String,
2333    /// The propagated effect row (`web`, `sensitive:*`, `legal:*`).
2334    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2335    pub effect_row: Vec<String>,
2336    /// The enclosing `epistemic { mode: … }` at compile time (`believe`/`know`
2337    /// vouch the delivered values are ≥ believe, satisfying the T920 barrier for
2338    /// a `provenance: cleared` delivery). Empty at top level. Recorded so the
2339    /// `DeliveryProvenanceSoundness` PCC class re-derives the barrier identically.
2340    #[serde(default, skip_serializing_if = "String::is_empty")]
2341    pub epistemic_mode: String,
2342    pub ops: Vec<IRDeliverOp>,
2343}
2344
2345/// §Fase 105 — one compiled delivery operation. `fields` preserves declaration
2346/// order (a `Vec` of `(name, value)`) so the transduced request is deterministic.
2347/// Reuses [`IRDocField`] — the same `(name, kind, value)` shape a document block
2348/// field carries, so the barrier + transducer discriminate a literal from a
2349/// flow-value `ref` without re-parsing.
2350#[derive(Debug, Clone, Serialize)]
2351pub struct IRDeliverOp {
2352    /// `upsert_contact | create_deal | add_note`.
2353    pub kind: String,
2354    pub fields: Vec<IRDocField>,
2355}
2356
2357/// §Fase 87.d — a compiled `synth` dynamic tool-synthesis policy. The IR carries
2358/// the safety envelope so the enterprise Extism/WASM executor (§87.j) enforces
2359/// it; OSS ships a deny-by-default `SynthBackend` that refuses execution.
2360#[derive(Debug, Clone, Serialize)]
2361pub struct IRSynth {
2362    pub node_type: &'static str,
2363    pub source_line: u32,
2364    pub source_column: u32,
2365    pub name: String,
2366    pub target: String,
2367    pub risk: String,
2368    #[serde(default, skip_serializing_if = "String::is_empty")]
2369    pub language: String,
2370    pub sandbox: String,
2371    /// `required | none`; an omitted policy lowers to `required` (fail-closed).
2372    pub review: String,
2373    #[serde(default, skip_serializing_if = "Option::is_none")]
2374    pub max_lines: Option<i64>,
2375}
2376
2377// ── §Fase 53 — Closed-catalog extension mechanism ────────────────────────────
2378
2379/// §Fase 53 — one compiled member of an `extension`. For `effects`
2380/// the `name` is a provenance base; `default_confidence` is a CEILING
2381/// (§53.d tainted-overriding). Metadata is elided from JSON when absent
2382/// so the serialised shape stays minimal once the `extensions` field is
2383/// un-skipped alongside the Python IR mirror.
2384#[derive(Debug, Clone, Serialize)]
2385pub struct IRExtensionMember {
2386    pub name: String,
2387    #[serde(default, skip_serializing_if = "Option::is_none")]
2388    pub semantics: Option<String>,
2389    #[serde(default, skip_serializing_if = "Option::is_none")]
2390    pub default_confidence: Option<f64>,
2391}
2392
2393/// §Fase 53 — a compiled `extension` declaration. Rides in the IR (and,
2394/// once un-skipped, the proof bundle) so an independent PCC verifier
2395/// re-derives `is_known_base` against the artifact's own extensions
2396/// (soundness invariant #1). `category` ∈ {`effects`, `scan`} — the
2397/// type-checker (§53.c) enforces the closed category + no-shadowing +
2398/// provenance-class invariants before this IR is trusted.
2399#[derive(Debug, Clone, Serialize)]
2400pub struct IRExtension {
2401    pub node_type: &'static str,
2402    pub source_line: u32,
2403    pub source_column: u32,
2404    pub name: String,
2405    pub category: String,
2406    pub members: Vec<IRExtensionMember>,
2407}
2408
2409#[derive(Debug, Clone, Serialize)]
2410pub struct IRAxonStore {
2411    pub node_type: &'static str,
2412    pub source_line: u32,
2413    pub source_column: u32,
2414    pub name: String,
2415    pub backend: String,
2416    /// The DSN. **This is the field that actually runs.**
2417    ///
2418    /// `connection:` → `resolve_dsn` → a real sqlx `PgPool`. It is the sole DSN
2419    /// source for every store op in every deployed flow; there is no
2420    /// global-pool fallback. §113's census established this, and it is why
2421    /// §113 is delicate: moving authority to `resource` moves it *away* from
2422    /// the one field that governs anything, *toward* the half that governs
2423    /// nothing. A `resource:` that merely renames this string would be the
2424    /// nominal link — wired and hollow.
2425    ///
2426    /// §113: still parsed, but **deprecated in favour of [`Self::resource_ref`]**,
2427    /// and a store declared this way is INELIGIBLE for `lease` / `observe` /
2428    /// `reconcile`. *You cannot govern what you did not declare.*
2429    pub connection: String,
2430    /// §Fase 113 — the `resource` this store runs on (`axonstore U { resource: Db }`).
2431    ///
2432    /// When present, the store DERIVES its DSN (`resource.endpoint`), its pool
2433    /// size (`resource.capacity` — a knob that did not exist before §113; the
2434    /// pool was hardcoded at 10), and its sharing discipline
2435    /// (`resource.lifetime`, `axon-T941`) from the resource. **That derivation
2436    /// — not the reference — is what makes this real.**
2437    ///
2438    /// Empty ⇒ the legacy un-resourced form. Skip-if-empty ⇒ every pre-§113
2439    /// store serializes byte-identically (the §94.a `class` precedent).
2440    #[serde(default, skip_serializing_if = "String::is_empty")]
2441    pub resource_ref: String,
2442    pub confidence_floor: Option<f64>,
2443    pub isolation: String,
2444    pub on_breach: String,
2445    /// §Fase 35.j (D11) — Pillar IV: the capability slug required to
2446    /// access this store (empty = no gate).
2447    pub capability: String,
2448    /// §Fase 94.a — the secret-class prefix of a `backend: secrets`
2449    /// metadata store (`rotation_without_revelation`). Non-empty ⇔
2450    /// `backend == "secrets"` (both directions enforced by `axon-T900`
2451    /// before the IR ships). Elided from the wire when empty — every
2452    /// pre-§94 store serializes byte-identically (IR-SHA stability).
2453    #[serde(default, skip_serializing_if = "String::is_empty")]
2454    pub class: String,
2455    /// §Fase 38.b (D1) — the OPTIONAL column-schema declaration. Three
2456    /// closed forms (inline / manifest-ref / env-var). `None` means the
2457    /// 37.x runtime+deploy path applies verbatim (D5 absolute). The
2458    /// §38.d / §38.e type-checker proves every store reference against
2459    /// this when present. §Fase 94.a: for a `backend: secrets` store the
2460    /// generator synthesizes the FIXED metadata schema here (the artifact
2461    /// is self-describing; PCC and the deploy gate re-derive against it).
2462    #[serde(default, skip_serializing_if = "Option::is_none")]
2463    pub column_schema: Option<IRStoreColumnSchema>,
2464}
2465
2466/// §Fase 38.b (D1) — IR mirror of [`crate::store_schema::StoreColumnSchema`].
2467/// Serializes as a tagged union: `{"form": "inline" | "manifest_ref" |
2468/// "env_var", …}`.
2469#[derive(Debug, Clone, Serialize)]
2470#[serde(tag = "form", rename_all = "snake_case")]
2471pub enum IRStoreColumnSchema {
2472    Inline { columns: Vec<IRStoreColumn> },
2473    ManifestRef { qualified_name: String },
2474    EnvVar { var_name: String },
2475}
2476
2477/// §Fase 38.b (D1) — IR mirror of [`crate::store_schema::StoreColumn`].
2478/// The serialized `col_type` is the canonical PascalCase name (e.g.
2479/// `"Uuid"`, `"Int"`, `"Timestamptz"`).
2480#[derive(Debug, Clone, Serialize)]
2481pub struct IRStoreColumn {
2482    pub name: String,
2483    pub col_type: String,
2484    #[serde(default, skip_serializing_if = "is_false")]
2485    pub primary_key: bool,
2486    #[serde(default, skip_serializing_if = "is_false")]
2487    pub auto_increment: bool,
2488    #[serde(default, skip_serializing_if = "is_false")]
2489    pub not_null: bool,
2490    #[serde(default, skip_serializing_if = "is_false")]
2491    pub unique: bool,
2492    #[serde(default, skip_serializing_if = "String::is_empty")]
2493    pub default_value: String,
2494    /// §Fase 38.x.c (D2, D5) — `true` iff the column is declared with
2495    /// `GENERATED ALWAYS AS IDENTITY` or `GENERATED BY DEFAULT AS
2496    /// IDENTITY`. Distinct from `auto_increment` (legacy SERIAL via
2497    /// `nextval(...)` default). `skip_serializing_if` keeps IR JSON
2498    /// byte-identical to v1.38.2 for any column where `identity = false`.
2499    #[serde(default, skip_serializing_if = "is_false")]
2500    pub identity: bool,
2501    /// §Fase 73.f (D1) — `true` iff the column carries the `index`
2502    /// declaration. Surfaced into the IR so the deployment layer (the
2503    /// enterprise deploy gate) SEES the index as a declared capability and
2504    /// can materialize it (a GIN path index for a `Json`/`Jsonb` column, a
2505    /// b-tree otherwise) — never a silent out-of-band DBA action.
2506    /// `skip_serializing_if` keeps IR JSON byte-identical for any column
2507    /// where `indexed = false`.
2508    #[serde(default, skip_serializing_if = "is_false")]
2509    pub indexed: bool,
2510    /// §Fase 73.g (D1) — the OPTIONAL `Json<T>` shape-lens struct name on a
2511    /// `Json`/`Jsonb` column (`payload: Json<UserEvent>` → `Some("UserEvent")`).
2512    /// Surfaced into the IR so the PCC `JsonShapeSoundness` proof can
2513    /// RE-DERIVE, from the artifact alone, that every lens shape resolves
2514    /// to a declared struct `type` — the §73.a/§73.e lens well-formedness
2515    /// made an independently-verifiable proof object. `skip_serializing_if`
2516    /// keeps IR JSON byte-identical for any column with no shape lens.
2517    #[serde(default, skip_serializing_if = "Option::is_none")]
2518    pub json_shape: Option<String>,
2519}
2520
2521#[inline]
2522fn is_false(b: &bool) -> bool {
2523    !*b
2524}
2525
2526#[derive(Debug, Clone, Serialize)]
2527pub struct IRAxonEndpoint {
2528    pub node_type: &'static str,
2529    pub source_line: u32,
2530    pub source_column: u32,
2531    pub name: String,
2532    pub method: String,
2533    pub path: String,
2534    pub body_type: String,
2535    pub execute_flow: String,
2536    pub output_type: String,
2537    pub shield_ref: String,
2538    /// §8.2.h.3 — Python emits concrete `0`; AST stays `Option<i64>`.
2539    pub retries: i64,
2540    pub timeout: String,
2541    /// §ESK Fase 6.1 — κ regulatory class on the boundary.
2542    pub compliance: Vec<String>,
2543    /// §Fase 37.y (D1) — Path parameter names extracted from the
2544    /// `path:` string. Mirrors `AxonEndpointDefinition.path_params`.
2545    /// **`skip_serializing_if = Vec::is_empty`** so a pre-v1.38.5 IR
2546    /// JSON snapshot (without the field) is byte-identical to a
2547    /// v1.38.5 IR JSON for the same endpoint — D5 backwards-compat
2548    /// absolute. The runtime + adopter tools that consume the IR
2549    /// JSON parse `path_params` as an absent key → empty Vec via
2550    /// serde's `default` semantics.
2551    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2552    pub path_params: Vec<String>,
2553    /// §Fase 37.y (D2) — Query parameters from the inline
2554    /// `query: { … }` block. Mirrors `AxonEndpointDefinition.query_params`
2555    /// using `IRTypeField` (shared with body type fields → uniform
2556    /// downstream tooling). **`skip_serializing_if = Vec::is_empty`**
2557    /// — same D5 IR-JSON byte-identity guarantee as `path_params`.
2558    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2559    pub query_params: Vec<IRTypeField>,
2560    /// §Fase 51.x — capability scopes the request bearer must hold
2561    /// (the `requires: [scope.dotted]` declaration, §Fase 32.g). Mirror
2562    /// of `AxonEndpointDefinition.requires_capabilities`, lowered into
2563    /// the IR so the PCC CapabilityContainment property can prove that
2564    /// the stores this endpoint's flow reaches are all covered by the
2565    /// declared requires. **`skip_serializing_if = Vec::is_empty`** so a
2566    /// pre-§51.x IR-JSON snapshot (no `requires:`) stays byte-identical
2567    /// (D5 backwards-compat — empty key parses back to empty Vec).
2568    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2569    pub requires_capabilities: Vec<String>,
2570    /// §Fase 83.a — the `cors: <Name>` reference, or `""` when absent
2571    /// (D83.5: no CORS headers, ever). NEW field on an EXISTING struct —
2572    /// `skip_serializing_if` (not `shield_ref`'s bare/always-emitted
2573    /// historical shape) so a cors-less endpoint's IR stays byte-identical
2574    /// to pre-§83 (zero IR-SHA drift — the standing §76.d discipline).
2575    #[serde(default, skip_serializing_if = "String::is_empty")]
2576    pub cors_ref: String,
2577    /// §Fase 89.a — the explicit authorization-coverage opt-out lowered into
2578    /// the IR so the enterprise runtime (§89.d) and the PCC
2579    /// `AuthorizationCoverage` witness (§89.c) can read it. `false` (the
2580    /// default + the common case) elides from JSON via `is_false` so a
2581    /// pre-§89 IR-JSON snapshot stays byte-identical (zero IR-SHA drift —
2582    /// the standing §76.d discipline).
2583    #[serde(default, skip_serializing_if = "is_false")]
2584    pub public: bool,
2585}
2586
2587// ── §λ-L-E Fase 13 — Mobile Typed Channels IR ───────────────────────────────
2588
2589/// Compiled `channel Name { … }` declaration.
2590///
2591/// Direct port of `axon.compiler.ir_nodes.IRChannel`.  Lives in
2592/// `IRProgram.channels`; emit/publish/discover reductions embed in
2593/// their containing flow/listener (paper §3 + §4 — π-calc prefix
2594/// discipline preserved structurally, not lifted to top-level ops).
2595#[derive(Debug, Clone, Serialize)]
2596pub struct IRChannel {
2597    pub node_type: &'static str,
2598    pub source_line: u32,
2599    pub source_column: u32,
2600    pub name: String,
2601    pub message: String, // surface spelling — Order | Channel<Order> | …
2602    pub qos: String,
2603    pub lifetime: String,
2604    pub persistence: String,
2605    pub shield_ref: String,
2606    /// §Fase 77.b — non-empty ⇒ some `publish <this> within <Shield>` site
2607    /// referenced a SIGNING shield: the channel is an EGRESS channel and
2608    /// its durable events are signed-deliverable to registered external
2609    /// subscribers under this algorithm (first publish site wins;
2610    /// deterministic — the catalog has one algorithm in v1). Elided from
2611    /// JSON when empty (zero IR-SHA drift for pre-§77 programs).
2612    #[serde(skip_serializing_if = "String::is_empty")]
2613    pub egress_sign: String,
2614}
2615
2616/// §Fase 41.b — compiled typed WebSocket transport. `protocol` names the
2617/// `session` it carries; `backpressure_credit` is the typed-resource window
2618/// (`null` if unspecified). axon-rs realises the endpoint over a `tokio` WS,
2619/// crediting/decrementing the window per §4.2 of the paper.
2620#[derive(Debug, Clone, Serialize)]
2621pub struct IRSocket {
2622    pub node_type: &'static str,
2623    pub source_line: u32,
2624    pub source_column: u32,
2625    pub name: String,
2626    pub protocol: String,
2627    pub backpressure_credit: Option<i64>,
2628    pub reconnect: bool,
2629    pub legal_basis: Option<String>,
2630}
2631
2632/// §Fase 80.b — compiled outbound vendor connection (the client dual of
2633/// [`IRSocket`]). `protocol`/`role` bind the axon-facing session interface;
2634/// `resolve`/`secret` are per-tenant config keys (never literals — T850);
2635/// `map` is the compile-time-total wire↔session projection (T849). Optional
2636/// fields elide when absent so the IR shape is purely additive.
2637#[derive(Debug, Clone, Serialize)]
2638pub struct IRUpstream {
2639    pub node_type: &'static str,
2640    pub source_line: u32,
2641    pub source_column: u32,
2642    pub name: String,
2643    pub transport: String,
2644    pub protocol: String,
2645    pub role: String,
2646    pub resolve: String,
2647    /// §Fase 114.u — the `resource` this upstream's channel rides. When set,
2648    /// `resolve` above was DERIVED from the resource's `endpoint` at LOWERING
2649    /// (the §114 shield-egress discipline: derivation stamped into the
2650    /// artifact reaches every dial path by construction — no per-site wiring
2651    /// to forget) and `capacity` below carries the resource's bound. Elided
2652    /// when empty — every pre-§114.u upstream serializes byte-identically.
2653    #[serde(default, skip_serializing_if = "String::is_empty")]
2654    pub resource_ref: String,
2655    /// §Fase 114.u — **max concurrent connection INSTANCES** of this upstream
2656    /// (from `resource.capacity`). Frames are already flow-controlled by
2657    /// `backpressure_credit`; this bounds CONNECTIONS. The runtime holds a
2658    /// per-process semaphore permit for the life of each dialed handle —
2659    /// the same in-memory/per-process bound §114.e documented for tools.
2660    #[serde(default, skip_serializing_if = "Option::is_none")]
2661    pub capacity: Option<i64>,
2662    pub secret: String,
2663    pub auth_kind: String,
2664    #[serde(default, skip_serializing_if = "Option::is_none")]
2665    pub auth_name: Option<String>,
2666    #[serde(default, skip_serializing_if = "Option::is_none")]
2667    pub auth_prefix: Option<String>,
2668    pub map: Vec<IRUpstreamMapRule>,
2669    #[serde(default, skip_serializing_if = "Option::is_none")]
2670    pub reconnect: Option<IRUpstreamReconnect>,
2671    #[serde(default, skip_serializing_if = "Option::is_none")]
2672    pub overflow: Option<String>,
2673    #[serde(default, skip_serializing_if = "Option::is_none")]
2674    pub backpressure_credit: Option<i64>,
2675    /// §80.f — the `Preset@vN` reference this declaration was expanded from
2676    /// (provenance for the compliance reviewer); absent for hand-written ones.
2677    #[serde(default, skip_serializing_if = "Option::is_none")]
2678    pub preset: Option<String>,
2679}
2680
2681/// §Fase 80.b — one compiled `map:` projection rule.
2682#[derive(Debug, Clone, Serialize)]
2683pub struct IRUpstreamMapRule {
2684    pub node_type: &'static str,
2685    pub direction: String,
2686    pub message: String,
2687    pub framing: String,
2688    #[serde(default, skip_serializing_if = "Option::is_none")]
2689    pub tag: Option<String>,
2690    #[serde(default, skip_serializing_if = "Option::is_none")]
2691    pub when_field: Option<String>,
2692    #[serde(default, skip_serializing_if = "Option::is_none")]
2693    pub when_value: Option<String>,
2694}
2695
2696/// §Fase 80.b — compiled reconnect policy (all three fields required by the
2697/// parser — a reconnection policy with a hole is not a policy).
2698#[derive(Debug, Clone, Serialize)]
2699pub struct IRUpstreamReconnect {
2700    pub backoff_ms: i64,
2701    pub max_attempts: i64,
2702    pub on_exhausted: String,
2703}
2704
2705/// §Fase 83.a — a named, referenced browser-origin policy. Mirrors
2706/// `IRShield`'s field-for-field shape; consumed by `IRAxonEndpoint.cors_ref`.
2707/// Wildcard+credentials (T853), origin-glob shape (T854), and closed-method
2708/// (T855) violations are all rejected before this node is ever lowered — the
2709/// checker re-derives the same closed catalogs at deploy time (§83.c,
2710/// `CorsPolicyConsistency`), so an IR that reaches the runtime is already
2711/// proven consistent.
2712#[derive(Debug, Clone, Serialize)]
2713pub struct IRCors {
2714    pub node_type: &'static str,
2715    pub source_line: u32,
2716    pub source_column: u32,
2717    pub name: String,
2718    pub allow_origins: Vec<String>,
2719    pub allow_methods: Vec<String>,
2720    pub allow_headers: Vec<String>,
2721    pub allow_credentials: bool,
2722    /// Duration literal (`"3600s"`) — same string-carries-the-unit
2723    /// convention as `axonendpoint.timeout`; the consumer (enterprise's
2724    /// dynamic CORS middleware) parses it into seconds at request time.
2725    #[serde(default, skip_serializing_if = "Option::is_none")]
2726    pub max_age: Option<String>,
2727    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2728    pub expose_headers: Vec<String>,
2729}
2730
2731/// §Fase 85.b — compiled `cache` policy. The checker (§85.c) re-derives the
2732/// same laws at the deploy gate (`CacheSoundness`), so an IR that reaches the
2733/// runtime is already proven sound (one default max, non-pure ⇒ finite ttl,
2734/// references resolve). Every optional field is `skip_serializing_if` so a
2735/// bundle using `cache` only pays IR bytes for what it declares, and a bundle
2736/// with no `cache` never emits a `caches` key (IR-SHA stable, §76.d).
2737#[derive(Debug, Clone, Serialize)]
2738pub struct IRCache {
2739    pub node_type: &'static str,
2740    pub source_line: u32,
2741    pub source_column: u32,
2742    pub name: String,
2743    /// `"redis"` | `"in_process"`; empty ⇒ runtime default (`in_process`).
2744    #[serde(default, skip_serializing_if = "String::is_empty")]
2745    pub backend: String,
2746    /// Duration literal (`"10s"`) — same string-carries-the-unit convention as
2747    /// `cors.max_age`. `None` ⇒ cache-forever (sound only for a `pure` cache).
2748    #[serde(default, skip_serializing_if = "Option::is_none")]
2749    pub ttl: Option<String>,
2750    /// The parameter-name subset forming the key; empty ⇒ all bound params.
2751    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2752    pub key_params: Vec<String>,
2753    /// `true` ⇒ auto-covers every eligible tool (at most one per module).
2754    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2755    pub default_policy: bool,
2756    /// Effect classes this cache memoises; empty ⇒ `["pure"]`.
2757    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2758    pub apply_to_effects: Vec<String>,
2759    /// Channel names whose `emit` flushes this cache's namespace.
2760    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2761    pub invalidate_on: Vec<String>,
2762}
2763
2764/// Compiled emit step — `c⟨v⟩.P` (Chan-Output / Chan-Mobility).
2765///
2766/// `value_is_channel = true` ⇒ resolved at lowering time as a channel
2767/// handle (second-order mobility, paper §3.2); the runtime dispatches
2768/// on this flag without re-resolving symbols.
2769#[derive(Debug, Clone, Serialize)]
2770pub struct IREmit {
2771    pub node_type: &'static str,
2772    pub source_line: u32,
2773    pub source_column: u32,
2774    pub channel_ref: String,
2775    pub value_ref: String,
2776    pub value_is_channel: bool,
2777    /// §Fase 114 (owed) — the σ-shield the target `channel` declares
2778    /// (`channel C { … shield: S }`), RESOLVED here at lowering (Phase 0
2779    /// pre-pass, like `IRPublish.sign`) so the runtime `run_emit` scans the
2780    /// emitted value through S on EVERY dispatch path without re-deriving the
2781    /// channel↔shield map. Empty ⇒ an unshielded channel (byte-identical to a
2782    /// pre-§114 emit: `skip_serializing_if` elides it → zero IR-SHA drift for
2783    /// programs whose channels declare no shield).
2784    #[serde(default, skip_serializing_if = "String::is_empty")]
2785    pub shield_ref: String,
2786    /// §Fase 114.w — the σ-shield's breach policy, resolved at lowering beside
2787    /// `shield_ref` (same Phase 0 pre-pass). `None` ⇒ no `on_breach:` declared
2788    /// (halt, the fail-closed default); elided → zero IR-SHA drift.
2789    #[serde(default, skip_serializing_if = "Option::is_none")]
2790    pub breach_policy: Option<IRBreachPolicy>,
2791}
2792
2793/// §Fase 92.a — compiled `credential` contract. The TTL is carried as
2794/// SECONDS (converted at lowering from the duration literal) so every
2795/// consumer — the OSS minter port, the enterprise PASETO minter, the
2796/// deploy gate — shares one arithmetic-ready representation.
2797#[derive(Debug, Clone, Serialize)]
2798pub struct IRCredential {
2799    pub node_type: &'static str,
2800    pub source_line: u32,
2801    pub source_column: u32,
2802    pub name: String,
2803    /// The bearer lifetime in seconds (from the `ttl:` duration literal;
2804    /// `0` = unparseable, rejected by `axon-T894` before the IR ships).
2805    pub ttl_secs: u64,
2806    /// The capability slugs the minted bearer carries (validated dotted
2807    /// slugs; non-empty per `axon-T893`).
2808    pub grants: Vec<String>,
2809}
2810
2811/// §Fase 92.b — compiled `mint <Credential> as <binding>` step. The runtime
2812/// resolves the contract, enforces the attenuation law
2813/// (`grants ⊆ capabilities(minter)`, fail-closed), mints via the
2814/// `CredentialMinter` port, and binds the raw bearer under `binding`.
2815#[derive(Debug, Clone, Serialize)]
2816pub struct IRMintStep {
2817    pub node_type: &'static str,
2818    pub source_line: u32,
2819    pub source_column: u32,
2820    pub credential_ref: String,
2821    pub binding: String,
2822}
2823
2824/// §Fase 94.b — compiled `rotate <SecretsStore> [where "…"] with <Tool>
2825/// as <binding>` step. The runtime enumerates the custody entries of the
2826/// store's class matching `where_expr` (whole class when empty), performs
2827/// ONE mediated exchange per key through the named tool (reveal → tool
2828/// renews → CAS commit at version+1), and binds the METADATA-ONLY
2829/// summary. Fail-closed without a custody port; each per-key failure
2830/// degrades with a witness, never destructively.
2831#[derive(Debug, Clone, Serialize)]
2832pub struct IRRotateStep {
2833    pub node_type: &'static str,
2834    pub source_line: u32,
2835    pub source_column: u32,
2836    pub store_ref: String,
2837    /// §67 metadata filter; empty = the whole class (elided from the wire).
2838    #[serde(default, skip_serializing_if = "String::is_empty")]
2839    pub where_expr: String,
2840    pub tool_ref: String,
2841    pub binding: String,
2842}
2843
2844/// Compiled publish step — capability extrusion (Publish-Ext, paper §4.3).
2845#[derive(Debug, Clone, Serialize)]
2846pub struct IRPublish {
2847    pub node_type: &'static str,
2848    pub source_line: u32,
2849    pub source_column: u32,
2850    pub channel_ref: String,
2851    pub shield_ref: String,
2852    /// §Fase 77.b — the referenced shield's `sign:` algorithm, RESOLVED at
2853    /// lowering (order-independent pre-pass over every declared shield).
2854    /// Non-empty ⇒ this publish is an EGRESS declaration: the channel's
2855    /// events are signed-deliverable to registered external subscribers.
2856    /// Elided from JSON when empty (zero IR-SHA drift for pre-§77 programs).
2857    #[serde(skip_serializing_if = "String::is_empty")]
2858    pub sign: String,
2859}
2860
2861/// Compiled discover step — dual of publish.
2862#[derive(Debug, Clone, Serialize)]
2863pub struct IRDiscover {
2864    pub node_type: &'static str,
2865    pub source_line: u32,
2866    pub source_column: u32,
2867    pub capability_ref: String,
2868    pub alias: String,
2869}