Skip to main content

axon/
wire_envelope.rs

1//! §Fase 39.b — Pure Silicon Cognition: the canonical wire payload type
2//! for axonendpoint responses on `transport: json`.
3//!
4//! Isomorphic to the ψ-vector `ψ = ⟨T, V, E⟩` (paper §5):
5//!
6//! - **T** — the ontological type the value claims to inhabit
7//!   (`FlowEnvelope.ontological_type`)
8//! - **V** — the typed payload, member of T
9//!   (`FlowEnvelope.result`)
10//! - **E** — the epistemic envelope: certainty (Theorem 5.1) +
11//!   provenance + audit-chain + blame attribution
12//!   (the remaining fields)
13//!
14//! Defined ONCE in Rust; no Python mirror; no drift gate (per D3 +
15//! [[feedback_zero_py_files_north_star]]). This module is the
16//! Rust-canonical source of truth for the v2.0.0 wire shape.
17//!
18//! ## Construction
19//!
20//! The canonical builder is
21//! [`FlowEnvelope::from_execution_result`] — converts the v1.x
22//! [`crate::execution_result::ServerExecutionResult`] into a v2.0.0
23//! envelope. The conversion is total: every field of the legacy
24//! struct maps to a pillar-organized slot of the envelope, with no
25//! information loss. Epistemic fields (`certainty`,
26//! `provenance_chain`, `blame_attribution`) receive Fase-39.b safe
27//! defaults; their full producer logic lands in Fase 39.c.
28//!
29//! ## Sealing
30//!
31//! [`FlowEnvelope::seal`] is the single egress point before HTTP
32//! serialization. In Fase 39.b it runs the Rust-side fallback for
33//! Theorem 5.1 enforcement (clamp `certainty ≤ 0.99` if derived) +
34//! computes the `audit_chain_hash` over the canonical provenance
35//! representation. In Fase 39.c this method delegates to the C23
36//! kernel `axon-csys::effects::envelope::validate_epistemic_degradation`,
37//! making the bound structurally unbypassable from any Rust caller.
38//!
39//! ## Pillars
40//!
41//! - **Pillar I (Epistemic)** — `ontological_type`, `result`,
42//!   `certainty` (Theorem 5.1 bounded)
43//! - **Pillar II (Audit-chained)** — `provenance_chain`,
44//!   `step_audit`, `audit_chain_hash`
45//! - **Pillar III (Streaming)** — N/A (SSE has its own event family
46//!   per D9; this envelope is JSON-transport-only)
47//! - **Pillar IV (Capability)** — `blame_attribution` (carries
48//!   `BlameKind` of failure when present)
49//!
50//! See plan vivo `docs/fase/fase_39_pure_silicon_cognition.md` §4 for
51//! the full wire-shape contract.
52
53use serde::{Deserialize, Serialize};
54use sha2::{Digest, Sha256};
55
56// ════════════════════════════════════════════════════════════════════
57// FlowEnvelope — the canonical wire payload for `transport: json`
58// ════════════════════════════════════════════════════════════════════
59
60/// §Fase 39 (D1, D2, D5) — the wire payload of every `transport: json`
61/// axonendpoint response (HTTP 2xx) and every legacy
62/// `POST /v1/execute` invocation.
63///
64/// Fields are organized by Pillar (see module docs). At wire
65/// emission, `result` carries a `serde_json::Value` (monomorphic at
66/// runtime); D5 validation (Fase 32.d) — once simplified in 39.d —
67/// will type-check this slot against the declared inner T of the
68/// adopter's `output: FlowEnvelope<T>` declaration.
69#[derive(Serialize, Deserialize, Debug, Clone)]
70pub struct FlowEnvelope {
71    // ── Pillar I (Epistemic) — the ψ-vector slots ────────────────
72    /// The ontological type declared at the endpoint surface (the
73    /// inner T of `output: FlowEnvelope<T>`). Slug form:
74    /// `TenantRecord`, `List<PatientRecord>`, `Stream<Token>`.
75    /// For legacy `/v1/execute` invocations (no endpoint
76    /// declaration), this is the runtime-inferred type slug.
77    pub ontological_type: String,
78
79    /// The typed payload — member of `ontological_type`.
80    /// `serde_json::Value` at the wire layer because the runtime
81    /// is monomorphic; D5 (when simplified in 39.d) validates the
82    /// inner shape against the declared T.
83    pub result: serde_json::Value,
84
85    /// Certainty `c ∈ [0.0, 1.0]`, bounded by Theorem 5.1:
86    /// `c ≤ 0.99` whenever `derived_status = true`. In Fase 39.b
87    /// the bound is enforced by [`FlowEnvelope::seal`]'s Rust
88    /// fallback; in Fase 39.c the bound moves to the C23 kernel
89    /// `axon-csys::effects::envelope::validate_epistemic_degradation`,
90    /// making it structurally unbypassable.
91    pub certainty: f64,
92
93    /// §Fase 55.b — the Theorem 5.1 `(base, scope, confidence)` triple of
94    /// every flow-level `use <Tool>` dispatch whose tool declares an
95    /// `epistemic:<level>` effect. Surfaces the epistemic degradation on
96    /// the wire — the §50.i.4 parity gate, promoted (the competitive
97    /// differential: an adopter sees a query routed through an
98    /// `epistemic:speculate` tool decay to `confidence ≤ 0.80`). Empty —
99    /// and elided from the JSON — for flows with no epistemic tool (D5
100    /// backward-compat: byte-identical wire for every pre-55.b flow).
101    #[serde(default, skip_serializing_if = "Vec::is_empty")]
102    pub epistemic_envelopes: Vec<crate::epistemic_capture::EpistemicEnvelope>,
103
104    // ── Pillar II (Audit-chained) — provenance + step trail ──────
105    /// Ordered list of `kind:identifier` tuples capturing the
106    /// lineage of `result`. Examples:
107    ///   - `["flow:FetchTenants", "retrieve:tenants", "backend:stub"]`
108    ///   - `["step:Triage", "shield:Hipaa", "backend:anthropic"]`
109    /// Empty for endpoints with no derived state (singular literal
110    /// returns); populated by [`FlowEnvelope::from_execution_result`].
111    pub provenance_chain: Vec<String>,
112
113    /// Per-step audit trail. Survives from v1.x as the canonical
114    /// observability surface; here it is structured (not just
115    /// `Vec<String>`). Step results are TYPED `Value` post-39.b
116    /// (pre-v2.0.0 they were stringified — the typed form is a D5
117    /// simplification dividend).
118    pub step_audit: StepAuditTrail,
119
120    /// HMAC-SHA256 hex of the canonical form of `provenance_chain
121    /// || step_audit`. Computed by [`FlowEnvelope::seal`]; in
122    /// Fase 39.c the hash moves to the C23 kernel for byte-
123    /// deterministic cross-deployment verification.
124    pub audit_chain_hash: String,
125
126    // ── Pillar IV (Capability) — blame attribution ───────────────
127    /// Populated only when the flow's success path produced a
128    /// degraded posture (anchor breach, shield rejection, backend
129    /// soft-fail, store breach, type-mismatch on recoverable path).
130    /// `None` on the clean happy path.
131    pub blame_attribution: Option<BlameContext>,
132
133    // ── Cross-cutting — observability + correlation ──────────────
134    /// Execution metrics — latency, tokens, backend identity.
135    /// Always populated.
136    pub execution_metrics: ExecutionMetrics,
137
138    /// Correlation anchor (matches `X-Axon-Trace-Id` header).
139    /// String form for cross-stack compat (the v1.x `trace_id: u64`
140    /// is reborn here as Uuid v4 hex string).
141    pub trace_id: String,
142
143    /// §Fase 65.F — the HONEST hard-failure detail when the flow aborted on
144    /// a node's `DispatchError` (a failing `persist`/`mutate`/`purge` store
145    /// write, a backend error, etc.). `Some("flow 'F' failed at persist into
146    /// 'S': <cause>")` names the failing node + the underlying cause. This is
147    /// distinct from `blame_attribution`, which is reserved for SOFT
148    /// degradation reported ON the success path — a hard fail needs its own
149    /// slot. Mirrors the streaming dispatcher's `FlowError.error` so a
150    /// non-streaming endpoint surfaces store-write failures with the SAME
151    /// honesty the SSE path always had (closing the §65.E.2 silent-abort
152    /// regression). `None` — and elided from the JSON — on the clean path, so
153    /// every pre-§65.F happy-path wire stays byte-identical.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub error: Option<String>,
156
157    /// §Fase 91.b — the run's temporal record when any step rendered a
158    /// declared `now:` (`time_is_an_explicit_input` applied to cognition):
159    /// the single captured instant (RFC 3339 UTC), the tz-database release
160    /// it resolved against, and the declared zones actually rendered — the
161    /// triple that makes the exact prompt the model saw reconstructible
162    /// byte-for-byte. `None` — and elided from the JSON — for every
163    /// `now:`-less flow, so every pre-§91 wire stays byte-identical.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub temporal_context: Option<crate::temporal_context::TemporalRecord>,
166}
167
168/// §Fase 39 (D5) — per-step audit surface. Structured replacement
169/// for the v1.x `Vec<String>` step results.
170#[derive(Serialize, Deserialize, Debug, Clone, Default)]
171pub struct StepAuditTrail {
172    pub step_names: Vec<String>,
173    /// §Fase 39.b — TYPED. The v1.x stringified results are parsed
174    /// as JSON values when constructible; opaque strings fall back
175    /// to `Value::String(...)`. The D5 simplification in 39.d
176    /// leverages this typed form.
177    pub step_results: Vec<serde_json::Value>,
178    pub anchor_checks: usize,
179    pub anchor_breaches: usize,
180    pub errors: usize,
181    pub steps_executed: usize,
182    /// §Fase 33.x.d carry-over — per-step EnforcementSummary entries
183    /// (from `StreamPolicyEnforcer` runs). Empty in the legacy sync
184    /// path; populated by `server_execute_streaming` per the D2
185    /// contract.
186    #[serde(default, skip_serializing_if = "Vec::is_empty")]
187    pub enforcement_summaries:
188        Vec<(String, crate::execution_result::EnforcementSummaryWire)>,
189    /// §Fase 33.e carry-over — per-step `<stream:<policy>>` slugs
190    /// declared in source. Empty when no step declares one.
191    #[serde(default, skip_serializing_if = "Vec::is_empty")]
192    pub effect_policies: Vec<(String, String)>,
193    /// §Fase 33.x.g carry-over — closed-catalog runtime warnings
194    /// (only populated on legacy-path fallback under axon-W002 —
195    /// structurally unreachable post-33.z but the slot survives
196    /// for forward-compat with future warnings).
197    #[serde(default, skip_serializing_if = "Vec::is_empty")]
198    pub runtime_warnings: Vec<crate::runtime_warnings::RuntimeWarning>,
199}
200
201/// §Fase 39 (D5) — execution metrics + provenance identity. Always
202/// populated.
203#[derive(Serialize, Deserialize, Debug, Clone, Default)]
204pub struct ExecutionMetrics {
205    pub latency_ms: u64,
206    pub tokens_input: u64,
207    pub tokens_output: u64,
208    pub backend: String,
209    pub flow_name: String,
210    pub source_file: String,
211}
212
213// ════════════════════════════════════════════════════════════════════
214// BlameContext — Pillar IV attribution surface
215// ════════════════════════════════════════════════════════════════════
216
217/// §Fase 39 (D11) — closed-catalog blame attribution. Surfaces
218/// WHICH layer produced the degraded posture on a 2xx response.
219/// Hard-fails (4xx/5xx) are handled by the existing error envelopes
220/// (not this struct) — `BlameContext` is for SOFT degradation
221/// reported on the success path.
222#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
223pub struct BlameContext {
224    pub kind: BlameKind,
225    /// `file:line:col` (compile-time origin) OR `step:name`
226    /// (runtime origin). Empty string when the origin cannot be
227    /// pinpointed.
228    pub location: String,
229    /// Human-readable diagnostic. Forms the audit_log entry's
230    /// primary message.
231    pub message: String,
232    /// Optional anchor back to a plan-vivo D-letter (e.g. "39.c",
233    /// "33.x.d") for forward correlation when the blame ties to a
234    /// specific architectural commitment.
235    pub d_letter: Option<String>,
236}
237
238/// §Fase 39 (D11) — closed catalog of blame kinds. Adding a variant
239/// is a non-breaking surface change (consumers MUST handle
240/// `#[non_exhaustive]`-style fall-through).
241#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
242#[serde(rename_all = "snake_case")]
243pub enum BlameKind {
244    /// Pillar IV — an anchor's `require:` predicate failed; flow
245    /// chose to proceed (degraded path).
246    AnchorBreach,
247    /// Pillar I — a shield scanner flagged content; flow chose to
248    /// proceed.
249    ShieldRejection,
250    /// Backend returned a degraded response (truncated, partial,
251    /// soft-rate-limited).
252    BackendSoftFail,
253    /// Pillar II — store mutation chain verification failed; flow
254    /// proceeded with the prior-state read.
255    StoreBreach,
256    /// D5 detected partial typing inconsistency that is recoverable
257    /// (e.g. missing optional field with a sane default).
258    TypeMismatch,
259}
260
261// ════════════════════════════════════════════════════════════════════
262// FlowEnvelope::from_execution_result — v1.x → v2.0.0 converter
263// ════════════════════════════════════════════════════════════════════
264
265impl FlowEnvelope {
266    /// §Fase 39.b — convert a v1.x [`crate::execution_result::ServerExecutionResult`]
267    /// into a v2.0.0 envelope. Total: every legacy field maps to a
268    /// pillar-organized slot; no information loss.
269    ///
270    /// Epistemic field defaults applied here (refined in 39.c):
271    /// - `certainty = 1.0` when `anchor_breaches == 0` and
272    ///   `errors == 0` (clean happy path; no derived posture).
273    /// - `certainty = 0.99` when `anchor_breaches > 0 ||
274    ///   errors > 0` (Theorem 5.1: derived states bounded ≤ 0.99).
275    /// - `provenance_chain` built from
276    ///   `flow_name + step_names + backend`.
277    /// - `blame_attribution = None` always at this layer (the soft-
278    ///   degradation surface is populated by the runtime when it
279    ///   detects anchor/shield/store/backend events — 39.c lands
280    ///   that wiring).
281    ///
282    /// The `result` slot is populated from the LAST step's typed
283    /// output (`step_results.last()` parsed as `Value`). For flows
284    /// with no steps (degenerate) the result is `Value::Null`.
285    ///
286    /// `trace_id` is converted from the legacy `u64` to a Uuid v4
287    /// hex string. When the legacy id is 0 (pre-record), a fresh
288    /// Uuid is minted.
289    pub fn from_execution_result(
290        exec_result: crate::execution_result::ServerExecutionResult,
291        ontological_type: String,
292    ) -> Self {
293        // ── Pillar II — provenance chain ──
294        // §Fase 39.c.y — interleave semantic provenance events
295        // (`retrieve:*`, `shield:*`, etc.) with the canonical
296        // step/backend entries. Order: `flow:F`, then taxonomy
297        // events from execution_units walk, then `step:S` entries
298        // for each canonical step, then `backend:B` last. This
299        // gives auditors a complete lineage from flow declaration
300        // through every observable runtime event.
301        let mut provenance_chain = Vec::with_capacity(
302            2 + exec_result.step_names.len() + exec_result.provenance_events.len(),
303        );
304        provenance_chain.push(format!("flow:{}", exec_result.flow_name));
305        for event in &exec_result.provenance_events {
306            provenance_chain.push(event.clone());
307        }
308        for step_name in &exec_result.step_names {
309            provenance_chain.push(format!("step:{}", step_name));
310        }
311        provenance_chain.push(format!("backend:{}", exec_result.backend));
312
313        // ── Pillar II — typed step_results ──
314        // Parse each stringified result as JSON if possible; fall
315        // back to a String Value preserving the raw text.
316        let step_results_typed: Vec<serde_json::Value> = exec_result
317            .step_results
318            .iter()
319            .map(|s| {
320                serde_json::from_str::<serde_json::Value>(s)
321                    .unwrap_or_else(|_| serde_json::Value::String(s.to_string()))
322            })
323            .collect();
324
325        // ── Pillar I — the `result` slot ──
326        // Canonically the last step's typed value is the flow output.
327        // When the flow has no steps (degenerate), result is Null.
328        let result = step_results_typed
329            .last()
330            .cloned()
331            .unwrap_or(serde_json::Value::Null);
332
333        // ── Pillar I — certainty (Theorem 5.1 Rust-side fallback) ──
334        // The C23 kernel in 39.c will replace this; here we apply
335        // the same algebra so wire bytes are stable across the
336        // 39.b → 39.c transition.
337        let derived =
338            exec_result.anchor_breaches > 0 || exec_result.errors > 0;
339        let certainty = if derived { 0.99 } else { 1.0 };
340
341        // ── Pillar IV — blame ──
342        // §Fase 39.c.z — propagate the blame attribution from the
343        // runtime walk (populated by `derive_blame_from_report` in
344        // `wire_envelope_producers`). `None` on clean happy path;
345        // populated when the runtime surfaced an anchor breach,
346        // shield rejection, store breach, backend soft-fail, or
347        // recoverable type mismatch. The first-emitted (highest-
348        // priority) blame wins per `merge_blame`.
349        let blame_attribution: Option<BlameContext> =
350            exec_result.blame_attribution;
351
352        // ── Cross-cutting — trace_id ──
353        let trace_id = if exec_result.trace_id == 0 {
354            uuid::Uuid::new_v4().to_string()
355        } else {
356            // Pre-39 the trace_id was a u64; here we render it as
357            // a 16-char hex string (preserve the value semantically;
358            // future code paths will mint Uuids directly).
359            format!("{:016x}", exec_result.trace_id)
360        };
361
362        Self {
363            ontological_type,
364            result,
365            certainty,
366            // §Fase 55.b — surface the IR-derived epistemic envelopes.
367            epistemic_envelopes: exec_result.epistemic_envelopes,
368            provenance_chain,
369            step_audit: StepAuditTrail {
370                step_names: exec_result.step_names.clone(),
371                step_results: step_results_typed,
372                anchor_checks: exec_result.anchor_checks,
373                anchor_breaches: exec_result.anchor_breaches,
374                errors: exec_result.errors,
375                steps_executed: exec_result.steps_executed,
376                enforcement_summaries: exec_result.enforcement_summaries,
377                effect_policies: exec_result.effect_policies,
378                runtime_warnings: exec_result.runtime_warnings,
379            },
380            audit_chain_hash: String::new(), // computed by seal()
381            blame_attribution,
382            execution_metrics: ExecutionMetrics {
383                latency_ms: exec_result.latency_ms,
384                tokens_input: exec_result.tokens_input,
385                tokens_output: exec_result.tokens_output,
386                backend: exec_result.backend,
387                flow_name: exec_result.flow_name,
388                source_file: exec_result.source_file,
389            },
390            trace_id,
391            // §Fase 65.F — the honest hard-failure detail (named node + cause),
392            // verbatim from the runtime walk. `None` on the clean path.
393            error: exec_result.error,
394            // §Fase 91.b — the temporal record, verbatim from the runtime walk.
395            temporal_context: exec_result.temporal_context,
396        }
397    }
398}
399
400// ════════════════════════════════════════════════════════════════════
401// FlowEnvelope::seal — single egress before HTTP serialization
402// ════════════════════════════════════════════════════════════════════
403
404impl FlowEnvelope {
405    /// §Fase 39.b — apply epistemic enforcement + compute the
406    /// `audit_chain_hash` before wire serialization. This is the
407    /// ONLY public sealing surface; the wire bytes emitted by
408    /// `axon_server` MUST pass through this method (the `seal()`
409    /// invariant — Fase 39.b establishes it; 39.h grep gate locks
410    /// it structurally).
411    ///
412    /// ## Fase 39.c.x implementation (C23 kernel canonical)
413    ///
414    /// 1. Theorem 5.1 enforcement DELEGATES to the C23 kernel
415    ///    `axon-csys::envelope::validate_degradation`. The kernel:
416    ///    a. Defensively normalises NaN / Inf / out-of-range
417    ///       certainty into `[0.0, 1.0]`.
418    ///    b. Clamps `certainty ≤ 0.99` when `derived_status = true`.
419    ///    c. Returns the envelope with `derived_status` +
420    ///       `epistemic_kind` passed through unchanged.
421    ///    The C23 kernel is the SINGLE point of structural truth —
422    ///    no Rust path bypasses it for production code paths.
423    /// 2. `derived_status` algebra (Rust-side, matches the producer
424    ///    in [`FlowEnvelope::from_execution_result`] verbatim):
425    ///    `derived = step_audit.anchor_breaches > 0
426    ///             || step_audit.errors > 0`. The Rust side decides
427    ///    WHO is derived (semantic); the C23 kernel enforces WHAT
428    ///    the ceiling looks like (structural).
429    /// 3. `audit_chain_hash` = SHA-256 hex of the canonical-JSON
430    ///    serialization of `[provenance_chain, step_audit]`.
431    ///    Deterministic on identical inputs; tamper-evident.
432    ///    (39.c.x leaves the SHA-256 in Rust pending a future
433    ///    sub-fase that moves it to axon-csys::crypto for true
434    ///    silicon-grounded tamper-evidence.)
435    pub fn seal(mut self) -> Self {
436        // §Fase 55.e — epistemic ceiling propagates to the HEADLINE
437        // certainty: a flow can be no more certain than its least-certain
438        // epistemic tool. The λD lattice meet (⊓) of the per-tool ceilings
439        // is their minimum; each envelope's `confidence` IS that tool's
440        // applied ceiling (§55.a/b), so `min(confidences)` is the flow's
441        // epistemic upper bound. Applied BEFORE the C23 kernel so the kernel
442        // consolidates the full degradation (Theorem 5.1) at the single
443        // egress — no gateway can read a nominal `know` headline while an
444        // internal tool degraded the computation to `speculate`
445        // (Epistemic Transparency / taint propagation). No epistemic tool ⇒
446        // no change (D5 wire byte-compat for every pre-55 flow).
447        if let Some(min_ceiling) = self
448            .epistemic_envelopes
449            .iter()
450            .map(|e| e.confidence)
451            .reduce(f64::min)
452        {
453            self.certainty = self.certainty.min(min_ceiling);
454        }
455        // Theorem 5.1 — DELEGATE to C23 kernel. The algebra for
456        // `derived_status` matches the producer in
457        // `from_execution_result` (anchor_breaches > 0 || errors > 0)
458        // so producer + sealer agree on WHO is derived.
459        let derived = self.step_audit.anchor_breaches > 0
460            || self.step_audit.errors > 0;
461        let epistemic_kind = if !derived {
462            axon_csys::EpistemicKind::Clean
463        } else if self.blame_attribution.is_some() {
464            // Multi-source degradation — anchor/shield/store/backend
465            // surfaced an explicit blame producer (Pillar IV).
466            axon_csys::EpistemicKind::Degraded
467        } else if self.step_audit.anchor_breaches > 0 {
468            axon_csys::EpistemicKind::Breached
469        } else {
470            axon_csys::EpistemicKind::Derived
471        };
472        let env = axon_csys::EpistemicEnvelope::new(
473            self.certainty,
474            derived,
475            epistemic_kind,
476        );
477        let clamped = axon_csys::validate_degradation(env);
478        self.certainty = clamped.certainty;
479        // Audit chain hash — SHA-256 over canonical JSON of
480        // [provenance_chain, step_audit]. We use serde_json for
481        // canonicalization (sorted keys on structs by design; we
482        // accept the array-of-(provenance, audit) tuple as the
483        // canonical input).
484        let canonical = serde_json::to_string(&(
485            &self.provenance_chain,
486            &self.step_audit,
487        ))
488        .unwrap_or_default();
489        let mut hasher = Sha256::new();
490        hasher.update(canonical.as_bytes());
491        let digest = hasher.finalize();
492        self.audit_chain_hash = format!("{digest:x}");
493        self
494    }
495}
496
497// ════════════════════════════════════════════════════════════════════
498// Helpers
499// ════════════════════════════════════════════════════════════════════
500
501/// §Fase 39.b — derive the `ontological_type` slug for an endpoint's
502/// declared `output: T`. When the endpoint declares
503/// `output: FlowEnvelope<T>` (the canonical form post-39.e), this
504/// extracts the inner T. For legacy declarations (pre-39.e — still
505/// in tree until atomic deploy), returns the declared type verbatim.
506/// For empty / missing declarations returns `"Any"` (the singular
507/// catch-all).
508pub fn extract_inner_ontological_type(declared: &str) -> String {
509    let t = declared.trim();
510    if t.is_empty() {
511        return "Any".to_string();
512    }
513    if let Some(rest) = t.strip_prefix("FlowEnvelope<") {
514        if let Some(inner) = rest.strip_suffix('>') {
515            return inner.trim().to_string();
516        }
517    }
518    t.to_string()
519}
520
521// ════════════════════════════════════════════════════════════════════
522// Tests
523// ════════════════════════════════════════════════════════════════════
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528    use crate::execution_result::ServerExecutionResult;
529
530    fn fixture_exec_result() -> ServerExecutionResult {
531        ServerExecutionResult {
532            success: true,
533            flow_name: "FetchTenants".to_string(),
534            source_file: "tenants.axon".to_string(),
535            backend: "stub".to_string(),
536            steps_executed: 1,
537            latency_ms: 142,
538            tokens_input: 0,
539            tokens_output: 0,
540            anchor_checks: 0,
541            anchor_breaches: 0,
542            errors: 0,
543            step_names: vec!["RetrieveAll".to_string()],
544            step_results: vec![
545                r#"[{"id":1,"name":"foo"},{"id":2,"name":"bar"}]"#.to_string(),
546            ],
547            trace_id: 0,
548            effect_policies: Vec::new(),
549            enforcement_summaries: Vec::new(),
550            runtime_warnings: Vec::new(),
551            provenance_events: Vec::new(),
552            blame_attribution: None,
553            epistemic_envelopes: Vec::new(),
554            error: None,
555            temporal_context: None,
556        }
557    }
558
559    #[test]
560    fn fase39b_from_execution_result_clean_happy_path() {
561        let exec = fixture_exec_result();
562        let env = FlowEnvelope::from_execution_result(
563            exec,
564            "List<TenantRecord>".to_string(),
565        );
566        assert_eq!(env.ontological_type, "List<TenantRecord>");
567        assert_eq!(env.certainty, 1.0, "clean path → certainty 1.0");
568        assert_eq!(env.execution_metrics.flow_name, "FetchTenants");
569        assert_eq!(env.execution_metrics.latency_ms, 142);
570        assert!(env.blame_attribution.is_none());
571        assert_eq!(
572            env.provenance_chain,
573            vec![
574                "flow:FetchTenants",
575                "step:RetrieveAll",
576                "backend:stub"
577            ]
578        );
579    }
580
581    #[test]
582    fn fase39b_typed_result_slot_from_last_step() {
583        let exec = fixture_exec_result();
584        let env = FlowEnvelope::from_execution_result(
585            exec,
586            "List<TenantRecord>".to_string(),
587        );
588        // result is the LAST step's JSON-parsed value
589        let arr = env.result.as_array().expect("result must be array");
590        assert_eq!(arr.len(), 2);
591        assert_eq!(arr[0]["id"], 1);
592        assert_eq!(arr[0]["name"], "foo");
593        assert_eq!(arr[1]["id"], 2);
594        assert_eq!(arr[1]["name"], "bar");
595    }
596
597    #[test]
598    fn fase39b_typed_step_results_parsed_when_json() {
599        let exec = fixture_exec_result();
600        let env = FlowEnvelope::from_execution_result(
601            exec,
602            "List<TenantRecord>".to_string(),
603        );
604        assert_eq!(env.step_audit.step_results.len(), 1);
605        assert!(env.step_audit.step_results[0].is_array());
606    }
607
608    #[test]
609    fn fase39b_opaque_step_result_falls_back_to_string_value() {
610        let mut exec = fixture_exec_result();
611        exec.step_results = vec!["(stub model response)".to_string()];
612        let env = FlowEnvelope::from_execution_result(exec, "String".to_string());
613        // Opaque non-JSON text → Value::String wrapping the raw text
614        assert_eq!(env.step_audit.step_results.len(), 1);
615        assert_eq!(
616            env.step_audit.step_results[0],
617            serde_json::Value::String("(stub model response)".to_string())
618        );
619    }
620
621    #[test]
622    fn fase39b_certainty_bounded_on_derived_state() {
623        let mut exec = fixture_exec_result();
624        exec.anchor_breaches = 1;
625        let env = FlowEnvelope::from_execution_result(exec, "Any".to_string());
626        assert_eq!(env.certainty, 0.99, "derived state → 0.99 per Theorem 5.1");
627    }
628
629    #[test]
630    fn fase39b_certainty_bounded_on_errors() {
631        let mut exec = fixture_exec_result();
632        exec.errors = 1;
633        let env = FlowEnvelope::from_execution_result(exec, "Any".to_string());
634        assert_eq!(env.certainty, 0.99, "errors → derived → 0.99");
635    }
636
637    #[test]
638    fn fase39b_seal_populates_audit_chain_hash() {
639        let env = FlowEnvelope::from_execution_result(
640            fixture_exec_result(),
641            "List<TenantRecord>".to_string(),
642        );
643        assert_eq!(env.audit_chain_hash, "", "pre-seal: empty");
644        let sealed = env.seal();
645        assert_eq!(
646            sealed.audit_chain_hash.len(),
647            64,
648            "post-seal: SHA-256 hex digest (64 chars)"
649        );
650        assert!(
651            sealed.audit_chain_hash.chars().all(|c| c.is_ascii_hexdigit()),
652            "post-seal: lowercase hex"
653        );
654    }
655
656    #[test]
657    fn fase39b_seal_is_deterministic_on_identical_inputs() {
658        let a = FlowEnvelope::from_execution_result(
659            fixture_exec_result(),
660            "List<TenantRecord>".to_string(),
661        )
662        .seal();
663        let b = FlowEnvelope::from_execution_result(
664            fixture_exec_result(),
665            "List<TenantRecord>".to_string(),
666        )
667        .seal();
668        assert_eq!(
669            a.audit_chain_hash, b.audit_chain_hash,
670            "seal must be deterministic"
671        );
672    }
673
674    #[test]
675    fn fase39b_seal_changes_hash_on_provenance_drift() {
676        let a = FlowEnvelope::from_execution_result(
677            fixture_exec_result(),
678            "List<TenantRecord>".to_string(),
679        )
680        .seal();
681        let mut exec_b = fixture_exec_result();
682        exec_b.step_names = vec!["RetrieveAllRenamed".to_string()];
683        let b = FlowEnvelope::from_execution_result(
684            exec_b,
685            "List<TenantRecord>".to_string(),
686        )
687        .seal();
688        assert_ne!(
689            a.audit_chain_hash, b.audit_chain_hash,
690            "tamper detection: provenance drift changes the hash"
691        );
692    }
693
694    #[test]
695    fn fase39b_seal_clamps_certainty_on_derived() {
696        // §Theorem 5.1 enforcement — even if a producer set certainty
697        // > 0.99 on a derived state, seal() clamps it.
698        // The 39.b algebra: derived ⇔ anchor_breaches > 0 || errors > 0
699        // (matches from_execution_result verbatim).
700        let mut env = FlowEnvelope {
701            ontological_type: "Any".to_string(),
702            result: serde_json::Value::Null,
703            certainty: 1.0, // misbehaving producer
704            epistemic_envelopes: Vec::new(),
705            provenance_chain: vec!["flow:Derived".to_string()],
706            step_audit: StepAuditTrail {
707                anchor_breaches: 1, // makes this derived per 39.b algebra
708                ..StepAuditTrail::default()
709            },
710            audit_chain_hash: String::new(),
711            blame_attribution: None,
712            execution_metrics: ExecutionMetrics::default(),
713            trace_id: "x".to_string(),
714            error: None,
715            temporal_context: None,
716        };
717        env.certainty = 1.0;
718        let sealed = env.seal();
719        assert!(
720            sealed.certainty <= 0.99,
721            "Theorem 5.1: certainty must be clamped to ≤ 0.99 on \
722             derived states (anchor_breaches > 0). Got: {}",
723            sealed.certainty
724        );
725    }
726
727    #[test]
728    fn fase39b_seal_preserves_certainty_on_clean_path() {
729        // §Theorem 5.1 — only derived states are clamped. A flow
730        // with no derivation (just the flow:_ provenance prefix and
731        // nothing else) keeps certainty = 1.0.
732        let mut exec = fixture_exec_result();
733        exec.step_names = Vec::new(); // strip the step to remove derivation
734        let env = FlowEnvelope::from_execution_result(exec, "Any".to_string());
735        // After from_execution_result the provenance chain has only
736        // ["flow:FetchTenants", "backend:stub"]. That's 2 entries
737        // (> 1), so this counts as derived per our algebra.
738        // To get a NON-derived state we'd need a flow with NO
739        // backend either — i.e. a degenerate flow. For the test we
740        // assert the algebra by directly constructing.
741        let degenerate = FlowEnvelope {
742            ontological_type: "Any".to_string(),
743            result: serde_json::Value::Null,
744            certainty: 1.0,
745            epistemic_envelopes: Vec::new(),
746            provenance_chain: vec!["flow:Empty".to_string()],
747            step_audit: StepAuditTrail::default(),
748            audit_chain_hash: String::new(),
749            blame_attribution: None,
750            execution_metrics: ExecutionMetrics::default(),
751            trace_id: "x".to_string(),
752            error: None,
753            temporal_context: None,
754        };
755        let sealed = degenerate.seal();
756        assert_eq!(sealed.certainty, 1.0);
757        let _ = env;
758    }
759
760    #[test]
761    fn fase39b_extract_inner_ontological_type_unwraps_envelope() {
762        assert_eq!(
763            extract_inner_ontological_type("FlowEnvelope<List<TenantRecord>>"),
764            "List<TenantRecord>"
765        );
766        assert_eq!(
767            extract_inner_ontological_type("FlowEnvelope<TenantRecord>"),
768            "TenantRecord"
769        );
770        // Legacy: bare type — returned verbatim (pre-39.e tolerance).
771        assert_eq!(extract_inner_ontological_type("TenantRecord"), "TenantRecord");
772        assert_eq!(extract_inner_ontological_type("List<X>"), "List<X>");
773        // Missing / empty — defaults to Any (singular catch-all).
774        assert_eq!(extract_inner_ontological_type(""), "Any");
775        assert_eq!(extract_inner_ontological_type("   "), "Any");
776    }
777
778    #[test]
779    fn fase39b_serialization_round_trip() {
780        let env = FlowEnvelope::from_execution_result(
781            fixture_exec_result(),
782            "List<TenantRecord>".to_string(),
783        )
784        .seal();
785        let serialized = serde_json::to_string(&env).expect("serialize");
786        let parsed: FlowEnvelope =
787            serde_json::from_str(&serialized).expect("deserialize");
788        assert_eq!(parsed.ontological_type, env.ontological_type);
789        assert_eq!(parsed.certainty, env.certainty);
790        assert_eq!(parsed.audit_chain_hash, env.audit_chain_hash);
791        assert_eq!(parsed.trace_id, env.trace_id);
792        assert_eq!(parsed.provenance_chain, env.provenance_chain);
793    }
794
795    #[test]
796    fn fase39b_wire_shape_has_canonical_field_order() {
797        // §Fase 39 §4 — the wire is the ψ-vector. Verify the
798        // serialized form carries every field the contract names.
799        let env = FlowEnvelope::from_execution_result(
800            fixture_exec_result(),
801            "List<TenantRecord>".to_string(),
802        )
803        .seal();
804        let json = serde_json::to_value(&env).expect("to_value");
805        let obj = json.as_object().expect("envelope is a JSON object");
806        // ψ = ⟨T, V, E⟩ — every component MUST be present.
807        assert!(obj.contains_key("ontological_type"), "T component");
808        assert!(obj.contains_key("result"), "V component");
809        assert!(obj.contains_key("certainty"), "E: epistemic");
810        assert!(obj.contains_key("provenance_chain"), "E: audit");
811        assert!(obj.contains_key("step_audit"), "E: audit detail");
812        assert!(obj.contains_key("audit_chain_hash"), "E: tamper-evidence");
813        assert!(obj.contains_key("blame_attribution"), "E: blame");
814        assert!(obj.contains_key("execution_metrics"), "observability");
815        assert!(obj.contains_key("trace_id"), "correlation");
816    }
817
818    #[test]
819    fn fase39b_blame_kind_serializes_snake_case() {
820        // Wire-shape contract: BlameKind serializes as snake_case.
821        let blame = BlameContext {
822            kind: BlameKind::AnchorBreach,
823            location: "step:Triage".to_string(),
824            message: "Confidence below threshold".to_string(),
825            d_letter: Some("39.c".to_string()),
826        };
827        let json = serde_json::to_value(&blame).expect("to_value");
828        assert_eq!(json["kind"], "anchor_breach");
829
830        let blame2 = BlameContext {
831            kind: BlameKind::BackendSoftFail,
832            location: String::new(),
833            message: "Truncated".to_string(),
834            d_letter: None,
835        };
836        let json2 = serde_json::to_value(&blame2).expect("to_value");
837        assert_eq!(json2["kind"], "backend_soft_fail");
838    }
839
840    #[test]
841    fn fase39b_trace_id_minted_when_legacy_is_zero() {
842        let exec = fixture_exec_result(); // trace_id = 0
843        let env = FlowEnvelope::from_execution_result(exec, "Any".to_string());
844        // Uuid v4 is 36 chars with dashes; legacy hex (16) is 16.
845        assert!(
846            env.trace_id.len() == 36 || env.trace_id.len() == 16,
847            "trace_id length must be Uuid (36) or legacy hex (16). \
848             Got len={}: {}",
849            env.trace_id.len(),
850            env.trace_id
851        );
852        assert_ne!(env.trace_id, "0");
853    }
854
855    #[test]
856    fn fase39b_trace_id_carries_legacy_value_when_nonzero() {
857        let mut exec = fixture_exec_result();
858        exec.trace_id = 0xDEADBEEF;
859        let env = FlowEnvelope::from_execution_result(exec, "Any".to_string());
860        assert_eq!(env.trace_id, "00000000deadbeef");
861    }
862}