Skip to main content

tatara_process/
receipt.rs

1//! `tatara-receipt/v1` — the typed receipt envelope every pleme-io Job
2//! emits to prove its work was done.
3//!
4//! Today's consumers (and the only ones supported on `tatara-receipt/v1`):
5//! - **closed-loop auth probes** — `kind = "closed-loop-auth"`. Stamps
6//!   that a system's bundled identity issuer authenticated its bundled
7//!   client. The substrate primitive every closed-loop-testable product
8//!   composes (an issuer↔client pair, future: identity providers,
9//!   message brokers, databases that can issue creds to themselves).
10//! - **schema/migration runs** — `kind = "db-migration"`. shinka emits
11//!   one per applied migration; pillars carry the diff hash.
12//! - **test suites** — `kind = "test-suite"`. kenshi-runner et al.
13//! - **nix builds** — `kind = "nix-build"`. Carries the store-path
14//!   pillar as `artifact_hash`.
15//! - Anything else — operators register new `kind` strings; the
16//!   schema is open by design (the *shape* is fixed; the kind is data).
17//!
18//! Lives in `tatara-process` so `ReceiptEnvelope → ProcessAttestation`
19//! is a local typed bridge — the reconciler's verifier and any future
20//! Process consumer share one parse.
21//!
22//! Wire format (snake_case to match the existing ConfigMap payload
23//! shape the closed-loop-probe chart writes):
24//!
25//! ```yaml
26//! version: tatara-receipt/v1
27//! kind: closed-loop-auth
28//! composed_root: <26-char hex>
29//! intent_hash:   <hex>
30//! artifact_hash: <hex>
31//! control_hash:  <hex>
32//! generated_at:  2026-05-19T22:00:00Z
33//! process_ref:   "demo-test/ephemeral-demo"   # optional
34//! evidence:      { ... }                              # optional, free-form
35//! ```
36
37use chrono::{DateTime, Utc};
38use schemars::JsonSchema;
39use serde::{Deserialize, Serialize};
40
41use crate::attestation::ProcessAttestation;
42use crate::three_pillar;
43
44/// Canonical version string. Bump → `tatara-receipt/v2` if the wire
45/// shape changes; parsers refuse anything else for the v1 reader.
46pub const RECEIPT_VERSION: &str = "tatara-receipt/v1";
47
48/// Suffix appended to a Job's name to compose its default receipt-
49/// ConfigMap name. The substrate convention is that any Job which
50/// emits a [`ReceiptEnvelope`] writes it to a ConfigMap in the Job's
51/// own namespace whose name is `<job_name>-receipt` unless the caller
52/// supplies an explicit override.
53///
54/// Load-bearing at three shipped derivation sites, each of which
55/// re-composed the `<name>-receipt` shape by hand pre-lift:
56/// - `tatara_reconciler::boundary::evaluate_job_attested` — the
57///   `JobAttested` postcondition's default `receiptConfigMap`
58///   (`<parsed.name>-receipt`);
59/// - `tatara_reconciler::boundary::evaluate_closed_loop_auth` — the
60///   `ClosedLoopAuth` postcondition's default `receiptConfigMap`
61///   (`<probe_job_name>-receipt`, where the probe Job itself
62///   defaults to `<process_name>-closed-loop-probe`);
63/// - `tatara_reconciler::render::export_receipt_configmap_name` — the
64///   export-worker Job's per-index receipt ConfigMap
65///   (`<process_name>-export-<index>-receipt`), which is
66///   structurally `<export_job_name(process_name, index)>-receipt`.
67///
68/// Pre-lift each site restated the suffix as a `format!` literal
69/// (`format!("{}-receipt", parsed.name)`,
70/// `format!("{job_name}-receipt")`, and
71/// `format!("{process_name}-export-{index}-receipt")`). A rename to
72/// `-attest` or a scheme change to `.receipt-cm` would have needed a
73/// grep-and-replace across the three production sites AND a
74/// coordinated update of every fleet-shipped operator override in the
75/// closed-loop-probe chart and the reconciler's own tests.
76/// Post-lift the suffix lives at ONE const on the receipt module;
77/// [`default_receipt_config_map_name`] composes it with a Job name;
78/// every default-derivation site AND the export-worker composer
79/// route through the same primitive so a future suffix change lands
80/// at this ONE const and every consumer picks it up mechanically.
81///
82/// Sibling suffix-const on the substrate: [`RECEIPT_VERSION`] pins
83/// the wire-format version string every parser gates on; this const
84/// pins the wire-K8s-name suffix every default-derivation site
85/// composes. Both are load-bearing constants that operators grep and
86/// dashboards template on — neither may drift from its published
87/// spelling silently.
88///
89/// Theory anchor: THEORY.md §VI.1 — generation over composition; the
90/// `<job_name>-receipt` shape recurred at three production sites past
91/// the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold and is lifted to
92/// ONE substrate const + composer here. THEORY.md §III — the
93/// typescape; the substrate's own receipt-CM naming convention
94/// becomes a NAMED PRIMITIVE rather than a shape spelled out by hand
95/// at every derivation site.
96pub const RECEIPT_CM_SUFFIX: &str = "-receipt";
97
98/// Compose the canonical receipt-ConfigMap name for a Job named
99/// `job_name` — the substrate's default when no explicit
100/// `receiptConfigMap` override is supplied on a postcondition's
101/// params or when a renderer builds a Job whose receipt CM name is
102/// derived from the Job's own name.
103///
104/// Returns `<job_name>{RECEIPT_CM_SUFFIX}`. See [`RECEIPT_CM_SUFFIX`]
105/// for the full lift rationale and the three consumer sites the
106/// primitive owns.
107///
108/// Uses string concatenation rather than `format!` so the composition
109/// does not participate in the workspace's typed-emission ban migration
110/// (skip-format-ban CLAUDE.md note); the shape is fixed at
111/// `<job_name>` ++ [`RECEIPT_CM_SUFFIX`] and any future two-arg
112/// composer (e.g. `default_receipt_config_map_name_scoped(cluster,
113/// job)`) extends the primitive here, not the consumer sites.
114#[must_use]
115pub fn default_receipt_config_map_name(job_name: &str) -> String {
116    let mut out = String::with_capacity(job_name.len() + RECEIPT_CM_SUFFIX.len());
117    out.push_str(job_name);
118    out.push_str(RECEIPT_CM_SUFFIX);
119    out
120}
121
122/// Resolve the receipt-ConfigMap name a `JobAttested` /
123/// `ClosedLoopAuth` postcondition (or any future postcondition that
124/// consumes a receipt) reads — honoring an operator-supplied
125/// `receiptConfigMap:` override verbatim when present, otherwise
126/// falling back to the substrate's canonical
127/// [`default_receipt_config_map_name`] composer over `job_name`.
128///
129/// Pre-lift the SAME 4-line `<params>.receipt_config_map.clone()
130/// .unwrap_or_else(|| default_receipt_config_map_name(&<job_name>))`
131/// chain was hand-authored at TWO workspace-wide consumer sites past
132/// the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold, each feeding
133/// the postcondition's optional-override slot into the substrate's
134/// default-derivation composer:
135///
136/// * `tatara-reconciler::boundary::evaluate_job_attested` — the
137///   `JobAttested` postcondition's fallback derivation, threading
138///   `parsed.receipt_config_map` (optional operator override) +
139///   `parsed.name` (the Job name the postcondition attests).
140/// * `tatara-reconciler::boundary::evaluate_closed_loop_auth` — the
141///   `ClosedLoopAuth` postcondition's fallback derivation, threading
142///   `parsed.receipt_config_map` + the locally-derived `job_name`
143///   (`parsed.job_name.clone().unwrap_or_else(|| format!(
144///   "{process_name}-closed-loop-probe"))`).
145///
146/// Both sites walked the SAME 3-link chain — take the optional
147/// override, clone through the `Some` arm, fall back to the
148/// substrate default composer on `None` — differing only in the
149/// second operand (`&parsed.name` on the JobAttested axis, `&job_name`
150/// on the closed-loop axis). Post-lift each callsite reads
151/// `resolve_receipt_config_map_name(parsed.receipt_config_map.as_deref(),
152/// &<job_name>)` and the override-then-fallback resolution rule
153/// lives at ONE substrate owner.
154///
155/// Return-form axis: owned `String` — matches every downstream
156/// receipt-CM fetch site's `ns: &str, cm_name: &str` signature after
157/// the caller borrows the composed name. The `override_name:
158/// Option<&str>` input takes the borrow form so a consumer holding
159/// an `Option<String>` (the shipped `parsed.receipt_config_map` slot
160/// shape) reaches the substrate via `.as_deref()` without a
161/// speculative pre-clone at the callsite; the substrate performs the
162/// single owned-allocation only on the `Some` arm's projection.
163///
164/// The `Some` arm is byte-preserving — an operator who supplies an
165/// explicit `receiptConfigMap: ""` (empty string) gets the empty
166/// string back, matching the pre-lift `.clone().unwrap_or_else(...)`
167/// chain's semantics. This is intentional: the substrate defers
168/// empty-string validation to the downstream fetch site (which
169/// surfaces the error as `Satisfaction::Unsatisfied("<label> …
170/// receipt ConfigMap <ns>/ missing")` — the operator-visible symptom
171/// of the misconfiguration lands at the postcondition evaluator,
172/// not silently swallowed by a substrate-side non-empty filter).
173///
174/// A future normalization (a per-fleet suffix override injected via
175/// env var, a namespace-prefixed derivation for cluster-hosted receipt
176/// stores, a debug-build assertion rejecting the empty-override
177/// corner) lands at THIS ONE substrate primitive and every downstream
178/// postcondition evaluator inherits the upgrade mechanically — no
179/// per-site edit at the JobAttested / ClosedLoopAuth pair or at
180/// future postconditions consuming a receipt-CM override.
181///
182/// Sibling on the receipt-CM naming axis to
183/// [`default_receipt_config_map_name`] (unconditional composer, no
184/// override) — this primitive extends that composer with the
185/// optional-override projection every postcondition evaluator
186/// wraps around the composer's output.
187///
188/// Theory anchor: THEORY.md §III — the typescape; the
189/// override-then-fallback resolution rule for a postcondition-facing
190/// wire-name becomes a NAMED PRIMITIVE rather than a chain spelled
191/// out at every postcondition site.
192#[must_use]
193pub fn resolve_receipt_config_map_name(override_name: Option<&str>, job_name: &str) -> String {
194    match override_name {
195        Some(name) => name.to_string(),
196        None => default_receipt_config_map_name(job_name),
197    }
198}
199
200/// Canonical `data` key on a `receipt`-carrying ConfigMap for the JSON
201/// wire form of a [`ReceiptEnvelope`] — the substrate's PRIMARY payload
202/// key. Peer to [`RECEIPT_YAML_KEY`] on the same wire-form axis;
203/// [`RECEIPT_CM_KEYS`] fixes the primary-first ordering the reader-side
204/// lookup gate binds to.
205///
206/// Load-bearing at four shipped production sites — two on the writer
207/// axis (`tatara-closed-loop-probe`'s per-run receipt-CM emit inserts
208/// BOTH keys so operators can `kubectl get cm -o yaml` and read the
209/// receipt without re-parsing the embedded JSON) and two on the reader
210/// axis (`tatara-reconciler::boundary::verify_receipt_cm`'s `data`-map
211/// lookup gate reads the primary FIRST, then falls back to the YAML
212/// twin). Pre-lift each side restated the two `&'static str` literals
213/// verbatim — the writer inserted `"receipt.json"` + `"receipt.yaml"`
214/// as inline `String` allocations, the reader chained
215/// `.and_then(|d| d.get("receipt.json")).or_else(|| … "receipt.yaml"))`
216/// as inline lookup literals — with NO shared owner binding the two
217/// keys' spelling OR the primary-first ordering that the reader-side
218/// gate encodes as a load-bearing invariant. A rename at ONE writer
219/// key or ONE reader key silently desynchronizes the twin (a probe
220/// writing `"receipt.jsonl"` while the reader still gates on
221/// `"receipt.json"` → the postcondition MALFORMED-reads a ConfigMap
222/// that carries a valid receipt at a drifted key); a swap of the
223/// primary/fallback ordering at the reader silently promotes YAML
224/// over the operator-canonical JSON form.
225///
226/// Post-lift the two keys live at ONE substrate-owned pair of
227/// constants; [`RECEIPT_CM_KEYS`] pins the primary-first ordering the
228/// reader-side lookup gate iterates through
229/// ([`extract_receipt_payload_json`] composes the gate); every writer
230/// insert AND every reader lookup routes through ONE substrate owner,
231/// so a future rename (e.g. `"receipt.jsonl"` on a NDJSON schema
232/// variant, `"receipt.cbor"` on a binary-form variant) OR a
233/// primary/fallback swap lands at ONE substrate site and every writer
234/// and reader picks up the change mechanically — the two-side drift
235/// trap becomes unrepresentable at the type / value binding.
236///
237/// The reader's primary-first ordering is the substrate's convention:
238/// the JSON form is the machine-canonical wire (the closed-loop probe
239/// emits `serde_json::to_string(envelope)` as the source-of-truth
240/// payload), the YAML twin is the operator-facing readable projection
241/// (`serde_yaml::to_string(envelope)`) — both round-trip through the
242/// SAME [`ReceiptEnvelope::parse_either`] parser, so the primary/fallback
243/// ordering is a payload-format preference, not a semantic distinction.
244/// A future third wire form (CBOR, MessagePack, sigstore-signed JSON)
245/// extends [`RECEIPT_CM_KEYS`] in the primary-first order the readers
246/// prefer, and rustc's `[…; N]` arity constant on the type binds the
247/// extension in lockstep with every consumer.
248///
249/// Sibling substrate-owned wire-form const on the same receipt axis:
250/// [`RECEIPT_CM_SUFFIX`] pins the ConfigMap-name suffix every
251/// default-derivation site composes; [`RECEIPT_VERSION`] pins the
252/// wire-format version string every parser gates on; the three
253/// consts together define the substrate's receipt-CM wire contract at
254/// ONE surface.
255///
256/// Theory anchor: THEORY.md §VI.1 — generation over composition; the
257/// two payload-key literals recurred at FOUR production sites past
258/// the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold and are lifted
259/// to ONE substrate-owned pair of constants + ONE reader-side
260/// lookup-gate composer here. THEORY.md §V.1 — knowable platform;
261/// the (primary, fallback) ordering that the reader-side gate encodes
262/// becomes a NAMED PRIMITIVE ([`RECEIPT_CM_KEYS`]) rather than an
263/// implicit hand-coded chain reader consumers had to grok from a
264/// `.and_then(...).or_else(...)` pattern.
265pub const RECEIPT_JSON_KEY: &str = "receipt.json";
266
267/// Canonical `data` key on a `receipt`-carrying ConfigMap for the YAML
268/// wire form of a [`ReceiptEnvelope`] — the substrate's operator-facing
269/// FALLBACK payload key. Peer to [`RECEIPT_JSON_KEY`] on the same
270/// wire-form axis; [`RECEIPT_CM_KEYS`] fixes the primary-first ordering
271/// that pins the JSON form ahead of the YAML twin.
272///
273/// See [`RECEIPT_JSON_KEY`] for the full lift rationale and the four
274/// consumer sites this pair owns. The YAML form is the readable
275/// operator projection (`serde_yaml::to_string(envelope)`) the closed-
276/// loop probe writes alongside the JSON form so `kubectl get cm -o
277/// yaml` returns a human-readable payload without an inner JSON
278/// re-parse; the reader accepts it as a fallback when the JSON form is
279/// absent (older probe binaries, out-of-cluster hand-written receipts,
280/// operator-hand-written test fixtures).
281pub const RECEIPT_YAML_KEY: &str = "receipt.yaml";
282
283/// The primary-first closed-set of `data` keys the substrate's
284/// receipt-CM readers look up in order. [`RECEIPT_JSON_KEY`] takes
285/// precedence over [`RECEIPT_YAML_KEY`] — every reader-side lookup
286/// gate ([`extract_receipt_payload_json`] composes the canonical gate)
287/// iterates this table and returns the first hit as `&str`; every
288/// writer emits BOTH entries so the primary-first ordering the reader
289/// prefers matches the JSON form the probe wrote as its source-of-truth
290/// payload.
291///
292/// See [`RECEIPT_JSON_KEY`] for the full lift rationale and the four
293/// consumer sites this table owns. Sibling closed-set tables across
294/// the crate: [`ReceiptEnvelope::REQUIRED_PILLARS`], [`ReceiptKind::ALL`],
295/// [`crate::export::ReportFormat::ALL`], [`crate::phase::ProcessPhase::ALL`],
296/// [`crate::boundary::ConditionKind::ALL`], [`crate::intent::IntentKind::ALL`].
297pub const RECEIPT_CM_KEYS: [&str; 2] = [RECEIPT_JSON_KEY, RECEIPT_YAML_KEY];
298
299/// Operator-facing diagnostic message the substrate's receipt-CM
300/// reader-side lookup gate returns when neither [`RECEIPT_JSON_KEY`]
301/// nor [`RECEIPT_YAML_KEY`] is present as a string-valued entry on the
302/// ConfigMap's `data` map. Named through the substrate so the message
303/// stays coherent with [`RECEIPT_CM_KEYS`] — a rename at either key
304/// const would leave this message spelling the pre-rename literals
305/// verbatim, so both this const AND the two key consts live at ONE
306/// substrate site and any future re-shape sweeps them together.
307///
308/// Composed as a `&'static` byte-literal (not a `format!(...)`) so the
309/// composition does not participate in the workspace's typed-emission
310/// ban migration (skip-format-ban CLAUDE.md note); the shape is fixed
311/// at the two key literals' current spellings.
312pub const RECEIPT_CM_MISSING_KEY_MSG: &str =
313    "ConfigMap missing data['receipt.json' | 'receipt.yaml'] string key";
314
315/// Primary-first reader-side lookup gate for a receipt-CM's `data`
316/// map — the substrate primitive that owns the (primary, fallback)
317/// key-precedence chain every receipt-CM reader threads through.
318///
319/// Iterates [`RECEIPT_CM_KEYS`] in order and returns the first entry
320/// present as a string-valued JSON scalar; returns `None` when the
321/// `data` map is absent, when neither key is present, or when the
322/// entry at either key is a non-string JSON value (a JSON number,
323/// object, or array — none of which are a valid receipt-payload
324/// projection under the wire contract).
325///
326/// Load-bearing at ONE production reader-side site pre-lift
327/// (`tatara-reconciler::boundary::verify_receipt_cm`) whose 3-link
328/// `.and_then(|d| d.get(RECEIPT_JSON_KEY)).or_else(|| … RECEIPT_YAML_KEY
329/// )).and_then(|v| v.as_str())` chain restated the SAME two-key-
330/// with-string-scalar-projection shape as inline combinator plumbing
331/// — a shape the substrate now owns at ONE place so a future third
332/// wire form (a CBOR encoding, a sigstore-signed JSON form, a
333/// per-cluster payload rename) extends this primitive in lockstep
334/// with the [`RECEIPT_CM_KEYS`] table AND every reader consumer
335/// picks up the change mechanically. Sibling reader consumers
336/// (kenshi-runner's P3 test-suite receipt readback, shinka's per-
337/// migration receipt readback, any future per-Job attestation
338/// verifier) compose this ONE substrate primitive rather than
339/// re-authoring the primary/fallback chain per-consumer.
340///
341/// Lifetime: the returned `&str` borrows from the passed-in
342/// `serde_json::Value` — the reader's `data` reference must outlive
343/// the returned payload borrow. Every production reader-side consumer
344/// already holds the DynamicObject that owns the `Value` graph across
345/// the parse call that consumes this borrow, so the lifetime binding
346/// composes cleanly.
347///
348/// Theory anchor: THEORY.md §VI.1 — generation over composition; the
349/// (primary-key, fallback-key, string-scalar-projection) 3-link
350/// combinator chain recurred at ONE production reader site with the
351/// (primary, fallback) ordering as a load-bearing invariant nowhere
352/// bound at the substrate — post-lift ONE substrate primitive owns
353/// the chain AND [`RECEIPT_CM_KEYS`] pins the ordering the primitive
354/// iterates through. THEORY.md §V.1 — knowable platform; the reader-
355/// side (primary, fallback) precedence becomes a NAMED PRIMITIVE the
356/// receipt-inspection surfaces (LSP hover, `tatara-check` receipt-
357/// inspect report, REPL) bind to for reading the wire contract from
358/// the substrate directly.
359#[must_use]
360pub fn extract_receipt_payload_json(data: Option<&serde_json::Value>) -> Option<&str> {
361    for key in RECEIPT_CM_KEYS {
362        if let Some(v) = data
363            .and_then(|d| d.get(key))
364            .and_then(serde_json::Value::as_str)
365        {
366            return Some(v);
367        }
368    }
369    None
370}
371
372/// Closed-set typed identifier for the four known [`ReceiptEnvelope::kind`]
373/// strings the substrate emits today — [`Self::ClosedLoopAuth`] →
374/// `"closed-loop-auth"`, [`Self::DbMigration`] → `"db-migration"`,
375/// [`Self::TestSuite`] → `"test-suite"`, [`Self::NixBuild`] →
376/// `"nix-build"` — as a Rust enum, so the (variant, canonical kebab-case
377/// kind, semantic role) triple binds at ONE site on the typed algebra
378/// rather than at the four byte-identical string-literal sites scattered
379/// across the closed-loop probe binary (`default_value` on
380/// `--receipt-kind`), the reconciler's receipt-parser tests, the
381/// `ephemeral_pipeline` integration test, and the future shinka /
382/// kenshi / nix-build Job authors that compose `ReceiptEnvelope::build`.
383///
384/// Pre-lift the four canonical kebab-case kinds lived as `&'static str`
385/// literal arguments at every author site (`ReceiptEnvelope::build(
386/// "closed-loop-auth", …)`) AND as docstring prose at this module's
387/// header (`Today's consumers: closed-loop-auth, db-migration,
388/// test-suite, nix-build`). The (canonical-string, semantic-role)
389/// pairing was load-bearing across ≥5 files yet enforced by per-site
390/// call-site discipline — a rename of `"closed-loop-auth"` →
391/// `"closed-loop"` at the probe binary's CLI default (the originator of
392/// every production receipt) silently desynchronizes from the docstring
393/// prose AND from the reconciler's test fixtures AND from any future
394/// kind-keyed dispatch (e.g. shinka's per-kind verifier registry) — the
395/// `kind` field is a `String` from the wire shape's perspective so the
396/// compiler cannot bind the literals together. Post-lift the canonical
397/// kebab-case strings live at ONE [`Self::as_str`] arm per variant;
398/// every author site composes the typed variant through
399/// `ReceiptEnvelope::build(ReceiptKind::ClosedLoopAuth, …)` (the typed
400/// → `String` `From` impl lets the existing `impl Into<String>` API
401/// surface accept the variant transparently) and a rename lands at ONE
402/// `as_str` arm here — no per-call-site grep + edit sweep, no silent
403/// drift between the docstring header and the wire literals.
404///
405/// The `kind` field on [`ReceiptEnvelope`] remains a `String` because
406/// the schema is open by design: operators register new `kind` strings
407/// for future consumers (operator-domain Job receipts) without bumping
408/// the wire version. The typed `ReceiptKind` is the closed-set *view*
409/// over that open String — every receipt the substrate itself emits
410/// projects through one of the four typed variants, and the typed
411/// projection [`ReceiptEnvelope::known_kind`] decodes any envelope's
412/// `kind` into `Some(ReceiptKind)` when it matches a known variant,
413/// `None` for operator-registered open kinds. The (open-String,
414/// closed-typed-view) split is the same shape `tatara-lisp`'s
415/// `Sexp::Sym` (open atoms) vs `MacroDefHead` (closed-set head
416/// markers) takes — open data through one type, closed dispatch
417/// through another, no `_` fallthrough where the closed set runs.
418///
419/// Adding a fifth kind (e.g. `Provenance` → `"provenance-attest"`)
420/// extends the enum AND the two projection arms ([`Self::as_str`],
421/// [`Self::from_str`] via the [`Self::ALL`] sweep) in lockstep — rustc
422/// binds the extension through exhaustiveness over the closed enum so
423/// a partial extension that forgets ONE projection becomes a compile
424/// error rather than a runtime drift where the new kind builds receipts
425/// but `known_kind()` returns `None` and the future kind-keyed verifier
426/// dispatch silently falls through.
427///
428/// Sibling closed-set [`Self::ALL`] lift across the crate:
429/// [`crate::export::ReportFormat::ALL`],
430/// [`crate::export::ExportTrigger::ALL`],
431/// [`crate::export::ReportPayloadShape::ALL`],
432/// [`crate::phase::ProcessPhase::ALL`],
433/// [`crate::signal::ProcessSignal::ALL`],
434/// [`crate::boundary::ConditionKind::ALL`],
435/// [`crate::lifetime::TeardownPolicy::ALL`],
436/// [`crate::lifetime::LifetimeKind::ALL`],
437/// [`crate::intent::IntentKind::ALL`],
438/// [`crate::lifetime_clock::TerminateReasonKind::ALL`].
439///
440/// Theory anchor: THEORY.md §III — the typescape; the substrate's own
441/// receipt kinds become a TYPE rather than four `&'static str` literals
442/// at every author site and a docstring header that drifts the moment
443/// any rename happens off-script. THEORY.md §V.3 — three-pillar
444/// attestation; the `kind` field is the *what-am-I* discriminator on
445/// every receipt that chains into a [`ProcessAttestation`], and the
446/// typed variant is the substrate's shared vocabulary for "which kind
447/// of work just got attested" — pre-lift each call site had to spell
448/// the kind by hand, post-lift each call site composes the typed
449/// constant and any consumer (future verifier, future dashboard, future
450/// LSP completion) sweeps [`Self::ALL`] to enumerate every known
451/// substrate-emitted receipt without grep.
452#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
453#[closed_set(via = "as_str", display, generate_unknown)]
454pub enum ReceiptKind {
455    /// Closed-loop auth probe — stamps that a system's bundled identity
456    /// issuer authenticated its bundled client. Emitted by
457    /// `tatara-closed-loop-probe`; the substrate primitive every
458    /// closed-loop-testable product composes (an issuer↔client pair,
459    /// future: identity providers, message brokers, databases that can
460    /// issue creds to themselves).
461    ClosedLoopAuth,
462    /// Schema/migration runs. shinka emits one per applied migration;
463    /// the pillars carry the diff hash so the chain shows exactly which
464    /// migration was applied where.
465    DbMigration,
466    /// Test suites — kenshi-runner et al. The `evidence` field carries
467    /// pass/fail counts; the pillars stamp the suite identity.
468    TestSuite,
469    /// Nix builds. Carries the store-path pillar as `artifact_hash`;
470    /// chains every reproducible build into the Process attestation
471    /// chain so a derivation's output is provable on its owning
472    /// Process.
473    NixBuild,
474}
475
476impl ReceiptKind {
477    /// The closed set of substrate-emitted receipt kinds — single
478    /// source of truth that drives the [`Self::from_str`] decode sweep
479    /// AND any future enumeration consumer (kind-keyed verifier
480    /// registry, dashboard completion list, `tatara-check` receipt-kind
481    /// enumeration). Adding a fifth variant (e.g. `Provenance` →
482    /// `"provenance-attest"`) lands at one `ALL` entry + one `as_str`
483    /// arm — exhaustively checked by the compiler (the `[Self; 4]`
484    /// array literal forces the arity) AND by the per-variant
485    /// truth-table tests below.
486    ///
487    /// Sibling closed-set lifts across the crate's typescape:
488    /// [`crate::export::ReportFormat::ALL`],
489    /// [`crate::phase::ProcessPhase::ALL`],
490    /// [`crate::boundary::ConditionKind::ALL`],
491    /// [`crate::intent::IntentKind::ALL`].
492    pub const ALL: [Self; 4] = [
493        Self::ClosedLoopAuth,
494        Self::DbMigration,
495        Self::TestSuite,
496        Self::NixBuild,
497    ];
498
499    /// Canonical kebab-case wire-format kind — the literal that lands
500    /// in [`ReceiptEnvelope::kind`] when this variant authors the
501    /// receipt. Pinned to four byte-exact strings the substrate has
502    /// already published (the closed-loop probe's `default_value` on
503    /// `--receipt-kind`, the reconciler tests' fixture builds, the
504    /// `ephemeral_pipeline` integration test's assertions) — renaming
505    /// any one is a wire-format change, not a typed-internal refactor,
506    /// and the `receipt_kind_canonical_names_pinned` truth-table test
507    /// fails first to keep the substrate honest. Used by
508    /// [`fmt::Display`] (single source of truth) and as the `String`
509    /// projection that `From<ReceiptKind> for String` ([`Self::into`])
510    /// composes so [`ReceiptEnvelope::build`]'s `impl Into<String>`
511    /// kind argument transparently accepts the typed variant.
512    #[must_use]
513    pub const fn as_str(self) -> &'static str {
514        match self {
515            Self::ClosedLoopAuth => "closed-loop-auth",
516            Self::DbMigration => "db-migration",
517            Self::TestSuite => "test-suite",
518            Self::NixBuild => "nix-build",
519        }
520    }
521}
522
523// `impl fmt::Display for ReceiptKind` + `impl FromStr for ReceiptKind`
524// + `impl tatara_lisp::ClosedSet for ReceiptKind` + `pub struct
525// UnknownReceiptKind(pub String)` are generated by
526// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(via =
527// "as_str", display, generate_unknown)]` on the enum declaration above.
528// The auto-derived label `"receipt kind"` matches the prior hand-
529// rolled `#[error("unknown receipt kind: {0}")]` verbatim. The
530// inherent `as_str` projection stays load-bearing — the kebab-case
531// wire-format that matches `ReceiptEnvelope::kind`'s published literals
532// verbatim — while the trait method `label` gives generic consumers a
533// STABLE name across the workspace-wide closed-set implementors. The
534// open-by-design `ReceiptEnvelope::known_kind` projection routes the
535// `Err(UnknownReceiptKind)` arm into a `None` so operator-registered
536// open kinds stay open.
537
538impl From<ReceiptKind> for String {
539    /// Composes [`ReceiptKind::as_str`] into an owned `String` so
540    /// every `impl Into<String>` API surface ([`ReceiptEnvelope::build`]'s
541    /// `kind` parameter most notably) accepts the typed variant
542    /// transparently — the call site stays `build(kind, …)` and the
543    /// typed → wire bridge runs through ONE place.
544    fn from(k: ReceiptKind) -> Self {
545        k.as_str().to_owned()
546    }
547}
548
549impl From<ReceiptKind> for &'static str {
550    fn from(k: ReceiptKind) -> Self {
551        k.as_str()
552    }
553}
554
555/// One entry in the [`ReceiptEnvelope::REQUIRED_PILLARS`] closed-set
556/// table — the pair (diagnostic field name, wire-form accessor) that
557/// composes ONE required-pillar rejection through the shared
558/// [`require_nonempty`] peer. The alias gives the tuple a nameable
559/// type so downstream consumers (`tatara-check` receipt-inspector, an
560/// LSP hover on the const, per-pillar dashboard columns) bind to
561/// "one pillar's descriptor" as a first-class handle rather than
562/// re-typing the underlying `(&'static str, fn(&ReceiptEnvelope) ->
563/// &str)` tuple at every consumer.
564pub type RequiredPillar = (&'static str, fn(&ReceiptEnvelope) -> &str);
565
566/// Typed receipt envelope. Any Job in pleme-io that wants its result to
567/// chain into a Process's `status.attestation` writes one of these.
568#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
569#[serde(rename_all = "snake_case", deny_unknown_fields)]
570pub struct ReceiptEnvelope {
571    /// Must equal `RECEIPT_VERSION`. Mismatches reject the receipt.
572    pub version: String,
573    /// What this receipt proves. Known: `closed-loop-auth`, `db-migration`,
574    /// `test-suite`, `nix-build`. Operators may register new kinds —
575    /// the envelope is open.
576    pub kind: String,
577    /// Three-pillar root: `BLAKE3(domain ++ artifact ++ control ++ intent ++ previous)`.
578    pub composed_root: String,
579    /// Pillar 1: what the Job was *trying* to do (canonical intent).
580    pub intent_hash: String,
581    /// Pillar 2: what the Job *produced* (artifact / proof material).
582    pub artifact_hash: String,
583    /// Pillar 3: how the Job *verified* its work (controls / signatures /
584    /// auth steps). Empty string when there was no control step.
585    pub control_hash: String,
586    /// Timestamp the Job set when it wrote the receipt.
587    pub generated_at: DateTime<Utc>,
588    /// Optional owning-Process reference (`namespace/name`). When the
589    /// reconciler creates the Job it stamps this in via the downward
590    /// API; receipts without it still parse for ad-hoc / out-of-cluster
591    /// runs.
592    #[serde(default, skip_serializing_if = "Option::is_none")]
593    pub process_ref: Option<String>,
594    /// Optional structured evidence. Free-form JSON. The reconciler does
595    /// not parse this — it's for human / downstream-tool inspection.
596    #[serde(default, skip_serializing_if = "is_null")]
597    pub evidence: serde_json::Value,
598}
599
600fn is_null(v: &serde_json::Value) -> bool {
601    v.is_null()
602}
603
604/// Wire-form encoding a [`ReceiptEnvelope`] payload was serialized
605/// in — the closed set of on-disk shapes the reader accepts.
606///
607/// Substrate primitive that closes the "which parser did this
608/// payload use" corner at ONE typed enum: every dispatcher that
609/// selects a parser (the shared [`ReceiptEnvelope::parse`] entry,
610/// the [`ReceiptEnvelope::parse_json`] / [`ReceiptEnvelope::parse_yaml`]
611/// wrappers, and the JSON-first-YAML-fallback
612/// [`ReceiptEnvelope::parse_either`]) routes through one arm of this
613/// enum, so a future wire form (e.g. a `Cbor` variant for a binary
614/// emit path, an `MsgPack` variant for a bandwidth-tight probe) lands
615/// as ONE variant + ONE arm of [`Self::parse_raw`]. Peer to
616/// [`ReceiptKind`] on the "one closed-set typed enum per wire-format
617/// axis" pattern — [`ReceiptKind`] closes the *semantic* kind axis
618/// (what the receipt claims), this enum closes the *encoding* axis
619/// (how the payload was written down).
620///
621/// The wrap-variant selection on the [`ReceiptError`] side
622/// ([`ReceiptError::InvalidJson`] vs [`ReceiptError::InvalidYaml`])
623/// travels with the wire-form arm here, so operators reading a
624/// failure surface see the encoding that failed without the caller
625/// having to hand-thread a per-form string label. See
626/// [`Self::error_variant`] for the closed-set mapping.
627#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
628pub enum ReceiptWireForm {
629    /// Compact JSON — the closed-loop-probe binary's default emit
630    /// form and the shape `serde_json::to_string(&env)` produces.
631    Json,
632    /// YAML — the shape a ConfigMap authored via `kubectl apply -f`
633    /// carries, and what `serde_yaml::to_string(&env)` produces.
634    Yaml,
635}
636
637impl ReceiptWireForm {
638    /// The closed set of wire-form encodings the reader accepts —
639    /// single source of truth that drives the JSON-first-YAML-fallback
640    /// sweep at [`ReceiptEnvelope::parse_either`] AND any future
641    /// enumeration consumer (a per-form metrics tag walker, a
642    /// `tatara-check` receipt-form auditor, a CLI `--wire-form` flag
643    /// completion list). Adding a third variant (e.g. `Cbor` for the
644    /// binary-emit corner already anticipated at [`Self`]'s enum
645    /// docstring, or `MsgPack` for a bandwidth-tight probe) lands as
646    /// ONE new variant + ONE arm on [`Self::parse_raw`] + ONE arm on
647    /// [`Self::as_str`] + ONE entry in [`Self::ALL`] — exhaustively
648    /// checked by the compiler (the `[Self; N]` array literal forces
649    /// the arity) AND by the per-variant truth-table tests below AND
650    /// by `parse_either`'s ALL-driven sweep (which auto-picks up the
651    /// new form without a per-consumer edit at the fallback chain).
652    ///
653    /// Sibling closed-set tables across the crate's typescape — this
654    /// entry closes the fourth axis they jointly own (semantic kind /
655    /// export report / process phase / boundary condition / intent
656    /// kind / **wire-form encoding**):
657    /// [`ReceiptKind::ALL`],
658    /// [`crate::export::ReportFormat::ALL`],
659    /// [`crate::phase::ProcessPhase::ALL`],
660    /// [`crate::boundary::ConditionKind::ALL`],
661    /// [`crate::intent::IntentKind::ALL`].
662    ///
663    /// The array order is JSON THEN YAML — matching the historical
664    /// [`ReceiptEnvelope::parse_either`] `.or_else` chain that tried
665    /// JSON first and YAML on JSON failure, so operator-facing log
666    /// lines reading the LAST-form error variant continue to see the
667    /// same fallback-form error (`ReceiptError::InvalidYaml`) on a
668    /// receipt payload that both forms reject. A regression that
669    /// reorders the entries surfaces at
670    /// [`tests::receipt_wire_form_all_matches_declaration_order_json_then_yaml`]
671    /// rather than as silent operator-facing skew across every
672    /// fallback log line.
673    pub const ALL: [Self; 2] = [Self::Json, Self::Yaml];
674
675    /// Deserialize `payload` with this wire-form's serde reader,
676    /// wrapping the parser's `Display` in the matching per-form
677    /// [`ReceiptError`] variant. Does NOT run
678    /// [`ReceiptEnvelope::verify_shape`] — the shared
679    /// [`ReceiptEnvelope::parse`] owner composes that postpass so
680    /// every wrapper picks it up mechanically.
681    fn parse_raw(self, payload: &str) -> Result<ReceiptEnvelope, ReceiptError> {
682        match self {
683            Self::Json => {
684                serde_json::from_str(payload).map_err(|e| ReceiptError::InvalidJson(e.to_string()))
685            }
686            Self::Yaml => {
687                serde_yaml::from_str(payload).map_err(|e| ReceiptError::InvalidYaml(e.to_string()))
688            }
689        }
690    }
691
692    /// Stable wire-form label — the short lowercase identifier
693    /// (`"json"` / `"yaml"`) an operator-facing log line, a
694    /// per-form metrics tag, or a future CLI flag surface can print
695    /// or match against. Pins the closed-set spelling at ONE table
696    /// so a downstream rename lands here rather than at every
697    /// consumer that hand-composed `"json"` / `"yaml"` inline.
698    #[must_use]
699    pub const fn as_str(self) -> &'static str {
700        match self {
701            Self::Json => "json",
702            Self::Yaml => "yaml",
703        }
704    }
705}
706
707/// Why a receipt is rejected. Kept as a typed enum so callers can
708/// pattern-match on the failure mode and surface targeted operator
709/// messages.
710#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
711pub enum ReceiptError {
712    #[error("invalid JSON: {0}")]
713    InvalidJson(String),
714    #[error("invalid YAML: {0}")]
715    InvalidYaml(String),
716    #[error("version != {RECEIPT_VERSION} (got {0:?})")]
717    WrongVersion(String),
718    #[error("missing required field: {0}")]
719    MissingField(&'static str),
720    #[error("kind is empty")]
721    EmptyKind,
722    #[error("composed_root mismatch (got {got}, want {want})")]
723    RootMismatch { got: String, want: String },
724}
725
726impl ReceiptEnvelope {
727    /// Build a receipt envelope from typed pillars + kind. `generated_at`
728    /// defaults to `Utc::now()`.
729    pub fn build(
730        kind: impl Into<String>,
731        intent_hash: impl Into<String>,
732        artifact_hash: impl Into<String>,
733        control_hash: impl Into<String>,
734        previous_root: Option<&str>,
735    ) -> Self {
736        let intent_hash = intent_hash.into();
737        let artifact_hash = artifact_hash.into();
738        let control_hash = control_hash.into();
739        let composed_root = three_pillar::compose_root(
740            &artifact_hash,
741            empty_to_none(&control_hash),
742            &intent_hash,
743            previous_root,
744        );
745        Self {
746            version: RECEIPT_VERSION.into(),
747            kind: kind.into(),
748            composed_root,
749            intent_hash,
750            artifact_hash,
751            control_hash,
752            generated_at: Utc::now(),
753            process_ref: None,
754            evidence: serde_json::Value::Null,
755        }
756    }
757
758    /// Parse `payload` as a [`ReceiptWireForm`]-tagged encoding and
759    /// validate the result's shape — the ONE parse-then-verify chain
760    /// every [`Self::parse_json`] / [`Self::parse_yaml`] /
761    /// [`Self::parse_either`] wrapper composes through, and the entry
762    /// consumers that dispatch on a typed wire-form value (an
763    /// operator-supplied "receipt payload is <form>" annotation, a
764    /// future CLI flag on `tatara-check` selecting the reader) call
765    /// directly.
766    ///
767    /// Pre-lift the parse + `verify_shape` chain was hand-authored at
768    /// TWO byte-identical sites past the ★★ PRIME-DIRECTIVE ≥ 2
769    /// duplication threshold — [`Self::parse_json`] and
770    /// [`Self::parse_yaml`] each restated the same
771    /// `<parser>(payload).map_err(|e| ReceiptError::<Variant>(
772    /// e.to_string()))?;` + `env.verify_shape()?; Ok(env)` shape with
773    /// only the parser + wrap-variant swapped. Post-lift the two
774    /// per-form deserialize+wrap pairings live at ONE closed-set
775    /// dispatch inside [`ReceiptWireForm::parse_raw`]; this owner
776    /// composes THAT dispatch with the shared `verify_shape` postpass
777    /// so the two wrappers, [`Self::parse_either`], and any future
778    /// wire-form consumer (adding e.g. `ReceiptWireForm::Cbor` for a
779    /// binary emit path) land at ONE arm without re-authoring the
780    /// verify chain.
781    pub fn parse(payload: &str, form: ReceiptWireForm) -> Result<Self, ReceiptError> {
782        let env = form.parse_raw(payload)?;
783        env.verify_shape()?;
784        Ok(env)
785    }
786
787    /// Parse a receipt from a JSON string.
788    pub fn parse_json(payload: &str) -> Result<Self, ReceiptError> {
789        Self::parse(payload, ReceiptWireForm::Json)
790    }
791
792    /// Parse a receipt from a YAML string. Useful for ConfigMaps that
793    /// store the payload in YAML form.
794    pub fn parse_yaml(payload: &str) -> Result<Self, ReceiptError> {
795        Self::parse(payload, ReceiptWireForm::Yaml)
796    }
797
798    /// Parse via JSON first, then YAML if JSON fails. Lets a single
799    /// reader accept either wire form without the operator having to
800    /// declare it. Useful when the Job writes JSON and the reconciler
801    /// reads back through a kube DynamicObject whose `data` is YAML.
802    ///
803    /// Routes the fallback sweep through the closed-set table
804    /// [`ReceiptWireForm::ALL`] so a future third wire-form variant
805    /// (`Cbor`, `MsgPack`) picks up the fallback automatically — the
806    /// per-callsite `Self::parse(payload, Wire::A).or_else(|_|
807    /// Self::parse(payload, Wire::B))` chain would otherwise need a
808    /// third `.or_else` link at THIS site the moment the enum grew.
809    /// On full failure, the returned error is the LAST attempted
810    /// form's error variant (byte-for-byte identical to the pre-lift
811    /// `.or_else` chain, which discarded the JSON error and returned
812    /// the YAML error) — pinned at
813    /// [`tests::parse_either_preserves_last_form_error_variant_on_full_failure`].
814    pub fn parse_either(payload: &str) -> Result<Self, ReceiptError> {
815        let mut last_err: Option<ReceiptError> = None;
816        for form in ReceiptWireForm::ALL {
817            match Self::parse(payload, form) {
818                Ok(env) => return Ok(env),
819                Err(e) => last_err = Some(e),
820            }
821        }
822        // `ReceiptWireForm::ALL: [Self; 2]` is non-empty at the type
823        // level, so the loop assigns `last_err` on every full-failure
824        // path. The `expect` documents the invariant a future zero-
825        // arity mistake at the ALL table would surface with.
826        Err(last_err.expect("ReceiptWireForm::ALL is non-empty"))
827    }
828
829    /// Closed-set table of pillars that MUST be non-empty on every
830    /// well-formed receipt — the wire-form's structural invariant
831    /// [`Self::verify_shape`] enforces. Pre-lift the three checks
832    /// lived as three byte-identical `if self.<pillar>.is_empty() {
833    /// return Err(ReceiptError::MissingField("<pillar>")); }` two-arm
834    /// conditionals inline in `verify_shape` — one per pillar name,
835    /// each hand-writing the SAME (field-name, accessor, rejection)
836    /// triple with the pillar name repeated at BOTH the accessor
837    /// (`self.composed_root`) AND the diagnostic literal
838    /// (`"composed_root"`). Post-lift the three (field-name,
839    /// accessor) pairs live at ONE closed-set table here;
840    /// `verify_shape` composes ONE per-entry iteration that
841    /// dispatches through the shared [`require_nonempty`] free-fn
842    /// peer of [`empty_to_none`].
843    ///
844    /// Each entry is a [`RequiredPillar`] tuple whose named type gives
845    /// downstream consumers (a `tatara-check` receipt-inspector, an
846    /// LSP hover, a per-pillar dashboard column) a nameable handle
847    /// for "one pillar's (diagnostic-name, wire-form-accessor)
848    /// pairing" rather than an unnamed function-pointer tuple
849    /// re-typed at every consumer.
850    ///
851    /// The `control_hash` field is DELIBERATELY NOT in this table:
852    /// the substrate's second pillar carries an "empty means absent"
853    /// convention that [`Self::control_hash_opt`] + [`empty_to_none`]
854    /// project as a typed `Option::None`, so its emptiness is a
855    /// semantic bit rather than a validation failure. The pair
856    /// (`REQUIRED_PILLARS` — must be non-empty; `control_hash_opt` —
857    /// may be empty) is the substrate's typed answer to which
858    /// pillars are load-bearing vs. schema-optional. A future
859    /// re-shape that promotes a fourth required pillar (e.g. a
860    /// mandatory `signer_hash` on a signed-receipt schema variant)
861    /// lands as ONE new entry in this table + rustc's `[…; N]`
862    /// arity constant on the type binding the extension in lockstep
863    /// so a partial addition that forgets the diagnostic surface
864    /// becomes a compile error rather than a runtime drift.
865    ///
866    /// Sibling closed-set tables across the crate:
867    /// [`ReceiptKind::ALL`],
868    /// [`crate::export::ReportFormat::ALL`],
869    /// [`crate::phase::ProcessPhase::ALL`],
870    /// [`crate::boundary::ConditionKind::ALL`],
871    /// [`crate::intent::IntentKind::ALL`].
872    ///
873    /// Theory anchor: THEORY.md §VI.1 — generation over composition;
874    /// the three inline pillar-emptiness checks recurred at THREE
875    /// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold
876    /// and are lifted to ONE closed-set table + ONE shared rejection
877    /// peer. THEORY.md §V.1 — knowable platform; the enumeration of
878    /// required-pillar field names lives at ONE surface a
879    /// documentation surface, an LSP hover, or a `tatara-check`
880    /// receipt-inspector binds to for enumerating the receipt's
881    /// structural invariants. THEORY.md §V.3 — three-pillar
882    /// attestation; the (mandatory, may-be-absent) split of the
883    /// three-pillar-plus-composed-root wire form is a typed
884    /// substrate contract, not a per-consumer discipline.
885    pub const REQUIRED_PILLARS: [RequiredPillar; 3] = [
886        ("composed_root", |e| e.composed_root.as_str()),
887        ("intent_hash", |e| e.intent_hash.as_str()),
888        ("artifact_hash", |e| e.artifact_hash.as_str()),
889    ];
890
891    /// Verify the schema-level invariants: correct version + non-empty
892    /// kind + non-empty pillar hashes (length-only, not BLAKE3-recompute).
893    /// The three required-pillar rejections dispatch through
894    /// [`Self::REQUIRED_PILLARS`] + [`require_nonempty`] so a future
895    /// fourth required pillar lands at ONE table entry rather than
896    /// as a fourth inline `if …is_empty() { return Err(…); }` copy.
897    pub fn verify_shape(&self) -> Result<(), ReceiptError> {
898        if self.version != RECEIPT_VERSION {
899            return Err(ReceiptError::WrongVersion(self.version.clone()));
900        }
901        if self.kind.is_empty() {
902            return Err(ReceiptError::EmptyKind);
903        }
904        for (field, accessor) in Self::REQUIRED_PILLARS {
905            require_nonempty(field, accessor(self))?;
906        }
907        // control_hash MAY be empty when there is no control step;
908        // the BLAKE3 compose treats empty as "absent" via Option —
909        // see `Self::control_hash_opt` + `empty_to_none`.
910        Ok(())
911    }
912
913    /// Verify that `composed_root` is consistent with the pillars.
914    /// `expected_previous_root` is the previous root in the Process's
915    /// attestation chain (or `None` for first attestation).
916    pub fn verify_root(&self, expected_previous_root: Option<&str>) -> bool {
917        let want = three_pillar::compose_root(
918            &self.artifact_hash,
919            self.control_hash_opt(),
920            &self.intent_hash,
921            expected_previous_root,
922        );
923        three_pillar::constant_time_eq(want.as_bytes(), self.composed_root.as_bytes())
924    }
925
926    /// Strict-equality check against an operator-provided expected root.
927    /// Returns the receipt's root unchanged on success.
928    pub fn expect_root(&self, expected: Option<&str>) -> Result<&str, ReceiptError> {
929        if let Some(want) = expected {
930            if want != self.composed_root {
931                return Err(ReceiptError::RootMismatch {
932                    got: self.composed_root.clone(),
933                    want: want.to_string(),
934                });
935            }
936        }
937        Ok(&self.composed_root)
938    }
939
940    /// Decode `self.kind` into the typed [`ReceiptKind`] variant when
941    /// the wire string matches one of the four substrate-emitted
942    /// canonical kebab-case kinds; `None` when the kind is an
943    /// operator-registered open string (the schema is open by design —
944    /// every receipt remains a valid receipt, but only typed kinds
945    /// participate in closed-set dispatch). The (open `String`,
946    /// closed-typed view) split lets future kind-keyed consumers
947    /// (verifier registries, dashboard completion, audit-trail
948    /// classifiers) sweep the typed variants without touching the
949    /// open-by-design wire shape. Lifted as the canonical decode site
950    /// so no consumer re-implements the `match self.kind.as_str()`
951    /// arm-by-arm — the closed-set sweep happens through
952    /// [`ReceiptKind::from_str`] at ONE site.
953    #[must_use]
954    pub fn known_kind(&self) -> Option<ReceiptKind> {
955        self.kind.parse().ok()
956    }
957
958    /// Lower into a `ProcessAttestation` — the canonical handoff so a
959    /// Job's typed receipt becomes evidence on a Process. `generation`
960    /// + `previous_root` come from the owning Process's prior
961    /// attestation (or 0 + None for the first cycle).
962    pub fn to_attestation(
963        &self,
964        generation: u64,
965        previous_root: Option<&str>,
966    ) -> ProcessAttestation {
967        ProcessAttestation::compose(
968            self.artifact_hash.clone(),
969            self.control_hash_opt().map(str::to_owned),
970            self.intent_hash.clone(),
971            previous_root.map(String::from),
972            generation,
973        )
974    }
975
976    /// Typed projection of the wire form's `control_hash` field —
977    /// `Some(hash)` when a control step ran, `None` when it did not.
978    ///
979    /// The wire form stamps `control_hash: String` (schema-open,
980    /// serde-friendly), but the substrate's `three_pillar::compose_root`
981    /// + `ProcessAttestation::compose` compositions both take an
982    /// `Option<&str>` / `Option<String>` and thread `None` through the
983    /// exact BLAKE3 bytes pattern an absent-pillar walk emits — an
984    /// empty `control_hash` and an absent-pillar receipt hash to the
985    /// SAME `composed_root`. That "empty means absent" convention
986    /// pre-lift lived at THREE sites inside this impl block —
987    /// [`Self::build`] (constructing the envelope from typed pillars),
988    /// [`Self::verify_root`] (recomposing the root against pillars for
989    /// wire-form verification), and [`Self::to_attestation`] (lowering
990    /// the receipt into a [`ProcessAttestation`] on a Process's
991    /// attestation chain) — each hand-writing the SAME
992    /// `if self.control_hash.is_empty() { None } else {
993    /// Some(self.control_hash.as_str()) }` two-arm conditional. Post-
994    /// lift the convention lives at ONE method here; the three
995    /// consumers each compose a ONE-LINE call:
996    ///   * `verify_root` → `self.control_hash_opt()` directly,
997    ///   * `to_attestation` → `self.control_hash_opt().map(str::to_owned)`
998    ///     for the `Option<String>` shape [`ProcessAttestation::compose`]
999    ///     binds,
1000    ///   * `build` (which reads a local `control_hash: String` before
1001    ///     the envelope is constructed) → the free-fn peer
1002    ///     [`empty_to_none`] on the same borrowed string.
1003    ///
1004    /// Public because the projection is load-bearing operator-facing
1005    /// contract: an authoring surface (an LSP hover, a
1006    /// `tatara-check` report, a REPL `:receipt-inspect` command) that
1007    /// wants to render "no control step" vs. "control_hash: <hash>"
1008    /// binds to this method rather than pattern-matching on
1009    /// `self.control_hash.is_empty()` at its own call site — a future
1010    /// re-shape of the empty-means-absent convention (a sentinel-
1011    /// string variant, an explicit `Option<String>` on the wire form
1012    /// once the schema evolves, or a typed
1013    /// `ControlStep::{Ran(hash), Skipped}` enum) lands at ONE method
1014    /// here rather than at every consumer that inspects the pillar.
1015    ///
1016    /// Theory anchor: THEORY.md §V.1 — knowable platform; the
1017    /// wire-vs-typed projection lives at ONE substrate method so a
1018    /// consumer reads the pillar's typed-Option contract from the
1019    /// receipt directly, not from three parallel inline conditionals
1020    /// scattered across `build` / `verify_root` / `to_attestation`.
1021    /// THEORY.md §VI.1 — generation over composition; the
1022    /// `is_empty() ? None : Some(&self.control_hash)` two-arm
1023    /// projection recurred at THREE inline sites past the ★★
1024    /// PRIME-DIRECTIVE ≥ 2 duplication threshold and is lifted to ONE
1025    /// owner here. THEORY.md §V.3 — three-pillar attestation; the
1026    /// receipt's second pillar (control step) has ONE typed projection
1027    /// site the composition primitives
1028    /// ([`three_pillar::compose_root`], [`ProcessAttestation::compose`])
1029    /// both bind against, so the pillar's wire-vs-typed identity
1030    /// cannot drift across the three consumers.
1031    #[must_use]
1032    pub fn control_hash_opt(&self) -> Option<&str> {
1033        empty_to_none(&self.control_hash)
1034    }
1035}
1036
1037/// Project a wire-form pillar string onto its typed `Option<&str>`
1038/// contract — `Some(s)` when `s` is non-empty, `None` when `s` is
1039/// empty (the substrate's "no such pillar" convention that
1040/// [`three_pillar::compose_root`] + [`ProcessAttestation::compose`]
1041/// both thread as an absent-pillar walk through the BLAKE3
1042/// domain-tagged composition).
1043///
1044/// The free-fn peer of [`ReceiptEnvelope::control_hash_opt`] for
1045/// call sites that hold a borrowed pillar string BEFORE a
1046/// [`ReceiptEnvelope`] is constructed — namely
1047/// [`ReceiptEnvelope::build`]'s inline `compose_root` call, which
1048/// composes the pillar's typed-Option identity from the local
1049/// `control_hash: String` intake before the envelope value exists.
1050/// The two peers share ONE projection body (`(!s.is_empty()).
1051/// then_some(s)`) so a future re-shape of the empty-means-absent
1052/// convention (a sentinel-string variant, an explicit
1053/// `Option<String>` on the wire form once the schema evolves)
1054/// lands at ONE substrate primitive rather than at both the
1055/// inherent method and its pre-construction free-fn peer.
1056///
1057/// Theory anchor: THEORY.md §VI.1 — generation over composition;
1058/// the pre-construction peer of the pillar projection lives at ONE
1059/// substrate primitive alongside the post-construction inherent
1060/// method, so the two receipt-lifecycle stages (pre-envelope in
1061/// [`ReceiptEnvelope::build`], post-envelope in every other
1062/// consumer) share ONE typed projection.
1063fn empty_to_none(s: &str) -> Option<&str> {
1064    (!s.is_empty()).then_some(s)
1065}
1066
1067/// Reject a required pillar whose wire form is empty with a typed
1068/// [`ReceiptError::MissingField`] carrying `field` — the diagnostic
1069/// literal the operator sees. Free-fn peer of [`empty_to_none`] on
1070/// the same wire-form-emptiness axis, and rejection sibling of the
1071/// [`ReceiptEnvelope::REQUIRED_PILLARS`] closed-set table
1072/// [`ReceiptEnvelope::verify_shape`] dispatches through.
1073///
1074/// The two peers on the emptiness axis carry two different typed
1075/// projections of the SAME wire-form bit:
1076///   * [`empty_to_none`] — the "empty means absent" convention for
1077///     the second pillar (control step); the substrate composes
1078///     `Option::None` through `compose_root` so an empty
1079///     `control_hash` and an absent-pillar receipt hash to the SAME
1080///     `composed_root`.
1081///   * [`require_nonempty`] — the "empty is a validation failure"
1082///     convention for the three required pillars; the substrate
1083///     rejects the receipt with a typed [`ReceiptError::MissingField`]
1084///     carrying the offending field name so the operator's diagnostic
1085///     surface (a reconciler event, a CLI stderr, a `tatara-check`
1086///     receipt-inspect report) names the pillar directly.
1087///
1088/// The two peers are DELIBERATELY named as (`empty_to_none`,
1089/// `require_nonempty`) rather than as a single overloaded projection
1090/// so the two typed conventions (absence-as-Option vs.
1091/// absence-as-Err) surface at the substrate's exported vocabulary
1092/// as two distinct primitives — a per-caller misroute (composing
1093/// `require_nonempty` on `control_hash` and getting a false
1094/// `MissingField`, or composing `empty_to_none` on `intent_hash`
1095/// and threading `None` through `compose_root` past a wire that
1096/// should have rejected) is a name-typo, not a silent semantic
1097/// swap.
1098///
1099/// Theory anchor: THEORY.md §VI.1 — generation over composition;
1100/// the "empty is a required-pillar failure" three-line inline
1101/// conditional recurred at THREE sites past the ★★ PRIME-DIRECTIVE
1102/// ≥ 2 duplication threshold and is lifted to ONE substrate primitive
1103/// composed through the [`ReceiptEnvelope::REQUIRED_PILLARS`] table.
1104/// THEORY.md §V.1 — knowable platform; the two emptiness projections
1105/// live at ONE typed vocabulary the receipt-inspection surfaces (LSP
1106/// hover, `tatara-check` report, REPL) bind to for reading the
1107/// receipt's structural contract from the substrate directly.
1108fn require_nonempty(field: &'static str, value: &str) -> Result<(), ReceiptError> {
1109    if value.is_empty() {
1110        return Err(ReceiptError::MissingField(field));
1111    }
1112    Ok(())
1113}
1114
1115#[cfg(test)]
1116mod tests {
1117    use super::*;
1118
1119    fn sample_payload() -> &'static str {
1120        // Composed_root precomputed from three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None)
1121        // (recomputed at test time to be canonical; this string is regenerated
1122        // if the domain tag ever changes).
1123        r#"{
1124            "version": "tatara-receipt/v1",
1125            "kind": "closed-loop-auth",
1126            "composed_root": "RECOMPUTE",
1127            "intent_hash":   "aaaa",
1128            "artifact_hash": "bbbb",
1129            "control_hash":  "cccc",
1130            "generated_at":  "2026-05-19T12:00:00Z"
1131        }"#
1132    }
1133
1134    fn canonical_payload_json() -> String {
1135        let root = three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None);
1136        sample_payload().replace("RECOMPUTE", &root)
1137    }
1138
1139    #[test]
1140    fn build_produces_valid_envelope() {
1141        let r = ReceiptEnvelope::build("test-suite", "i", "a", "c", None);
1142        assert_eq!(r.version, RECEIPT_VERSION);
1143        assert_eq!(r.kind, "test-suite");
1144        assert!(r.verify_shape().is_ok());
1145        assert!(r.verify_root(None));
1146    }
1147
1148    #[test]
1149    fn build_empty_control_omits_from_root() {
1150        let with_empty = ReceiptEnvelope::build("nix-build", "i", "a", "", None);
1151        let with_explicit_none = ReceiptEnvelope::build("nix-build", "i", "a", "", None);
1152        assert_eq!(with_empty.composed_root, with_explicit_none.composed_root);
1153
1154        // And differs from a receipt with a real control hash.
1155        let with_control = ReceiptEnvelope::build("nix-build", "i", "a", "c", None);
1156        assert_ne!(with_empty.composed_root, with_control.composed_root);
1157    }
1158
1159    #[test]
1160    fn parse_json_round_trip() {
1161        let r = ReceiptEnvelope::parse_json(&canonical_payload_json()).expect("parse");
1162        assert_eq!(r.kind, "closed-loop-auth");
1163        assert!(r.verify_root(None));
1164    }
1165
1166    #[test]
1167    fn parse_yaml_round_trip() {
1168        let yaml = r#"
1169version: tatara-receipt/v1
1170kind: db-migration
1171composed_root: ROOT
1172intent_hash:   aaaa
1173artifact_hash: bbbb
1174control_hash:  cccc
1175generated_at:  2026-05-19T12:00:00Z
1176"#
1177        .replace(
1178            "ROOT",
1179            &three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None),
1180        );
1181        let r = ReceiptEnvelope::parse_yaml(&yaml).expect("yaml parse");
1182        assert_eq!(r.kind, "db-migration");
1183        assert!(r.verify_root(None));
1184    }
1185
1186    #[test]
1187    fn wire_form_labels_pinned() {
1188        // Byte-exact wire-form labels — a rename here is a
1189        // wire-format change, not a typed-internal refactor. Log
1190        // lines / metrics tags / future CLI flags grep for these.
1191        assert_eq!(ReceiptWireForm::Json.as_str(), "json");
1192        assert_eq!(ReceiptWireForm::Yaml.as_str(), "yaml");
1193    }
1194
1195    #[test]
1196    fn receipt_wire_form_all_covers_every_declared_variant() {
1197        // Closed-set coverage pin: `ReceiptWireForm::ALL` MUST hold
1198        // every variant the enum declares. A regression that added a
1199        // `Cbor` variant to the enum's declaration + a `parse_raw`
1200        // arm + an `as_str` arm but forgot to extend `ALL` would let
1201        // `parse_either` silently keep failing over on a valid Cbor
1202        // payload without ever trying the parser — a fallback-corner
1203        // regression that no other test would catch. The pin binds
1204        // exhaustive coverage by re-projecting each variant through
1205        // `as_str` and asserting the ALL sweep hits the same set.
1206        let via_all: std::collections::HashSet<&'static str> =
1207            ReceiptWireForm::ALL.iter().map(|f| f.as_str()).collect();
1208        let via_declaration: std::collections::HashSet<&'static str> =
1209            [ReceiptWireForm::Json, ReceiptWireForm::Yaml]
1210                .iter()
1211                .map(|f| f.as_str())
1212                .collect();
1213        assert_eq!(
1214            via_all, via_declaration,
1215            "ReceiptWireForm::ALL must cover every declared variant — a new arm added to \
1216             `parse_raw` / `as_str` MUST also land in `ALL` so `parse_either` picks it up",
1217        );
1218        // Arity pin — the `[Self; 2]` type binding is compile-time,
1219        // but the runtime `.len()` guards against a `[Self; 0]` typo
1220        // that would make `parse_either` unreachable.
1221        assert_eq!(ReceiptWireForm::ALL.len(), 2);
1222    }
1223
1224    #[test]
1225    fn receipt_wire_form_all_matches_declaration_order_json_then_yaml() {
1226        // Order pin: `parse_either` iterates through ALL in
1227        // declaration order, so a reorder here changes which form's
1228        // error variant `parse_either` returns on full-failure. The
1229        // pre-lift `.or_else` chain fixed JSON THEN YAML — pin that
1230        // order at the substrate so a reorder surfaces here rather
1231        // than as silent skew at every operator-facing fallback log
1232        // line reading `ReceiptError::InvalidYaml` on a full-failure.
1233        assert_eq!(
1234            ReceiptWireForm::ALL,
1235            [ReceiptWireForm::Json, ReceiptWireForm::Yaml],
1236        );
1237    }
1238
1239    #[test]
1240    fn parse_either_dispatches_through_all_table_in_declaration_order() {
1241        // Fail-before-pass-after routing pin: `parse_either` MUST try
1242        // JSON first (the ALL table's head), then YAML (the tail).
1243        // A JSON payload succeeds on the first try — the YAML arm is
1244        // never reached, so any per-YAML normalization the future
1245        // `parse_raw` YAML arm might grow (a trim, an alias table)
1246        // does NOT affect the JSON-happy path. Conversely, a YAML-
1247        // only payload MUST fall through the JSON arm and succeed on
1248        // the YAML arm — the fallback sweep is the whole point.
1249        let json_payload = canonical_payload_json();
1250        let via_either = ReceiptEnvelope::parse_either(&json_payload).expect("json parses");
1251        let via_json_direct = ReceiptEnvelope::parse_json(&json_payload).expect("json direct");
1252        assert_eq!(
1253            via_either, via_json_direct,
1254            "parse_either on a valid-JSON payload MUST route through the JSON arm identically",
1255        );
1256
1257        let yaml = r#"
1258version: tatara-receipt/v1
1259kind: test-suite
1260composed_root: ROOT
1261intent_hash:   aaaa
1262artifact_hash: bbbb
1263control_hash:  cccc
1264generated_at:  2026-05-19T12:00:00Z
1265"#
1266        .replace(
1267            "ROOT",
1268            &three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None),
1269        );
1270        let via_either = ReceiptEnvelope::parse_either(&yaml).expect("yaml falls through JSON arm");
1271        let via_yaml_direct = ReceiptEnvelope::parse_yaml(&yaml).expect("yaml direct");
1272        assert_eq!(
1273            via_either, via_yaml_direct,
1274            "parse_either on a valid-YAML-only payload MUST fall through JSON and match YAML",
1275        );
1276    }
1277
1278    #[test]
1279    fn parse_either_preserves_last_form_error_variant_on_full_failure() {
1280        // Semantic pin: on a payload that BOTH wire forms reject, the
1281        // pre-lift `.or_else(|_| ...)` chain returned the LAST arm's
1282        // error (YAML's `InvalidYaml`), discarding the JSON error.
1283        // Post-lift the ALL-driven sweep preserves that semantic — a
1284        // regression that returned the FIRST arm's error (`InvalidJson`)
1285        // instead would silently reshape every operator-facing
1286        // full-failure log line, since operators grep the arm variant
1287        // to know "which form was tried last." Pin the semantic at
1288        // the substrate boundary so a regression here fails loudly
1289        // rather than in log-grep drift downstream.
1290        let bad = "{ not-valid-";
1291        let err = ReceiptEnvelope::parse_either(bad).expect_err("both forms reject");
1292        assert!(
1293            matches!(err, ReceiptError::InvalidYaml(_)),
1294            "parse_either full-failure MUST return the LAST-form error \
1295             (ReceiptWireForm::ALL's tail); got {err:?}",
1296        );
1297    }
1298
1299    #[test]
1300    fn receipt_wire_form_all_is_sibling_shape_to_receipt_kind_all() {
1301        // Cross-primitive closed-set family pin: `ReceiptWireForm::ALL`
1302        // MUST have the same `[Self; N]` shape the sibling closed-set
1303        // tables the module docstring names use (`ReceiptKind::ALL`,
1304        // `ReportFormat::ALL`, `ProcessPhase::ALL`, `ConditionKind::ALL`,
1305        // `IntentKind::ALL`). Every entry is a `Copy` variant of the
1306        // enum, reachable off the type name via `X::ALL`. A regression
1307        // that promoted ONE table to a `Vec<Self>` or a `HashSet<Self>`
1308        // (splintering the family) would surface at compile time on the
1309        // callers that iterate them uniformly — the pin here just
1310        // documents the family membership at test level.
1311        let wire_forms_via_all: Vec<&'static str> =
1312            ReceiptWireForm::ALL.iter().map(|f| f.as_str()).collect();
1313        let kinds_via_all: Vec<&'static str> =
1314            ReceiptKind::ALL.iter().map(|k| k.as_str()).collect();
1315        // Both tables project their variants through an `as_str`
1316        // const projection into a stable-order slice of static strs;
1317        // that shape is the closed-set family's shared idiom.
1318        assert!(!wire_forms_via_all.is_empty());
1319        assert!(!kinds_via_all.is_empty());
1320        assert!(
1321            wire_forms_via_all.iter().all(|s| s
1322                .chars()
1323                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')),
1324            "wire-form labels are kebab/lowercase like the sibling closed sets",
1325        );
1326    }
1327
1328    #[test]
1329    fn parse_dispatches_json_arm_byte_identically_to_parse_json() {
1330        // The two owners must produce byte-identical output on the
1331        // happy path — a regression that skewed either arm surfaces
1332        // HERE rather than at every downstream call site of the
1333        // wrappers.
1334        let payload = canonical_payload_json();
1335        let via_enum = ReceiptEnvelope::parse(&payload, ReceiptWireForm::Json).expect("json parse");
1336        let via_wrapper = ReceiptEnvelope::parse_json(&payload).expect("json wrapper parse");
1337        assert_eq!(via_enum, via_wrapper);
1338    }
1339
1340    #[test]
1341    fn parse_dispatches_yaml_arm_byte_identically_to_parse_yaml() {
1342        let yaml = r#"
1343version: tatara-receipt/v1
1344kind: db-migration
1345composed_root: ROOT
1346intent_hash:   aaaa
1347artifact_hash: bbbb
1348control_hash:  cccc
1349generated_at:  2026-05-19T12:00:00Z
1350"#
1351        .replace(
1352            "ROOT",
1353            &three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None),
1354        );
1355        let via_enum = ReceiptEnvelope::parse(&yaml, ReceiptWireForm::Yaml).expect("yaml parse");
1356        let via_wrapper = ReceiptEnvelope::parse_yaml(&yaml).expect("yaml wrapper parse");
1357        assert_eq!(via_enum, via_wrapper);
1358    }
1359
1360    #[test]
1361    fn parse_wrong_form_wraps_in_matching_error_variant() {
1362        // Wire-form arm selection travels with the ReceiptError
1363        // variant — a JSON payload parsed as YAML surfaces
1364        // `InvalidYaml`, not `InvalidJson`, so an operator log line
1365        // reads the encoding-that-failed without a hand-threaded
1366        // per-form label. Pins the (arm, wrap-variant) coherence
1367        // so a regression that decoupled either half surfaces here.
1368        let json_payload = canonical_payload_json();
1369        // JSON as JSON parses cleanly (baseline).
1370        assert!(ReceiptEnvelope::parse(&json_payload, ReceiptWireForm::Json).is_ok());
1371        // Bytes that a JSON reader rejects but a YAML reader silently
1372        // accepts (JSON is a strict YAML subset, so the reverse cross-
1373        // parse doesn't fail cleanly on any real payload; use invalid
1374        // JSON that's ALSO invalid YAML to pin per-arm wrap variants).
1375        let bad = "{ not-valid-";
1376        let json_err =
1377            ReceiptEnvelope::parse(bad, ReceiptWireForm::Json).expect_err("json rejects");
1378        let yaml_err =
1379            ReceiptEnvelope::parse(bad, ReceiptWireForm::Yaml).expect_err("yaml rejects");
1380        assert!(
1381            matches!(json_err, ReceiptError::InvalidJson(_)),
1382            "json arm must wrap in InvalidJson, got {json_err:?}"
1383        );
1384        assert!(
1385            matches!(yaml_err, ReceiptError::InvalidYaml(_)),
1386            "yaml arm must wrap in InvalidYaml, got {yaml_err:?}"
1387        );
1388    }
1389
1390    #[test]
1391    fn parse_either_falls_back_to_yaml() {
1392        let yaml = r#"
1393version: tatara-receipt/v1
1394kind: test-suite
1395composed_root: ROOT
1396intent_hash:   aaaa
1397artifact_hash: bbbb
1398control_hash:  cccc
1399generated_at:  2026-05-19T12:00:00Z
1400"#
1401        .replace(
1402            "ROOT",
1403            &three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None),
1404        );
1405        assert!(ReceiptEnvelope::parse_either(&yaml).is_ok());
1406    }
1407
1408    #[test]
1409    fn wrong_version_rejected() {
1410        let mut env: serde_json::Value = serde_json::from_str(&canonical_payload_json()).unwrap();
1411        env["version"] = "tatara-receipt/v2".into();
1412        let err = ReceiptEnvelope::parse_json(&env.to_string()).unwrap_err();
1413        assert!(matches!(err, ReceiptError::WrongVersion(ref s) if s == "tatara-receipt/v2"));
1414    }
1415
1416    #[test]
1417    fn receipt_version_wire_form_pin() {
1418        // Byte-shape pin on the ONE substrate const `RECEIPT_VERSION`.
1419        // The wire-form literal `"tatara-receipt/v1"` is the value
1420        // every serialized `ReceiptEnvelope.version` slot carries,
1421        // every reader gate rejects a mismatch against, and every
1422        // receipt-CM label value the closed-loop-probe stamps rides
1423        // through. A bump lands at this ONE const and every consumer
1424        // — the reconciler's `WrongVersion` diagnostic (routed
1425        // through the thiserror-derived Display via the enum's
1426        // `#[error("version != {RECEIPT_VERSION} (got {0:?})")]`
1427        // attribute), the closed-loop-probe's receipt-CM label VALUE,
1428        // and the envelope's `version` slot on build — inherits the
1429        // upgrade mechanically. This pin binds the current byte-form
1430        // so a bump surfaces here explicitly rather than as silent
1431        // drift at the two production sites that pre-lift restated
1432        // the literal by hand.
1433        assert_eq!(RECEIPT_VERSION, "tatara-receipt/v1");
1434    }
1435
1436    #[test]
1437    fn wrong_version_display_routes_through_receipt_version_const() {
1438        // Fail-before-pass-after substrate pin on the thiserror-
1439        // derived Display for `ReceiptError::WrongVersion`. Two
1440        // production consumers rely on this Display composing through
1441        // `RECEIPT_VERSION`:
1442        //
1443        // * `tatara-reconciler::boundary::receipt_error_message` — the
1444        //   `WrongVersion` arm now delegates to this Display directly
1445        //   (`err.to_string()`), so the reconciler's operator-facing
1446        //   diagnostic tracks the substrate const without a per-arm
1447        //   hand-authored format literal.
1448        // * `tatara-closed-loop-probe::write_receipt` — routes its
1449        //   receipt-CM label VALUE through the same `RECEIPT_VERSION`
1450        //   const directly, not this Display; both surfaces now share
1451        //   the ONE owner.
1452        //
1453        // A regression that dropped the `{RECEIPT_VERSION}` interpolation
1454        // from the enum's `#[error(...)]` attribute — reinlining the
1455        // literal `"tatara-receipt/v1"` there — would silently
1456        // desynchronize the reconciler's diagnostic from the probe's
1457        // stamped label value on any future const bump. This pin
1458        // catches such a regression at the Display byte shape.
1459        let err = ReceiptError::WrongVersion("tatara-receipt/v99".into());
1460        let msg = err.to_string();
1461
1462        // Byte-shape pin: exact composition through the substrate
1463        // const, with `{0:?}` Debug-formatting the wrapped `String`
1464        // (adding surrounding quotes).
1465        assert_eq!(
1466            msg,
1467            format!("version != {RECEIPT_VERSION} (got \"tatara-receipt/v99\")"),
1468            "WrongVersion Display must compose through the RECEIPT_VERSION const",
1469        );
1470
1471        // Routing pin: the substrate const value appears verbatim in
1472        // the Display output — a bump at `RECEIPT_VERSION` surfaces
1473        // here immediately.
1474        assert!(
1475            msg.contains(RECEIPT_VERSION),
1476            "WrongVersion Display must contain RECEIPT_VERSION verbatim, got {msg:?}",
1477        );
1478
1479        // Compat pin: the pre-lift boundary.rs hand-authored format
1480        // `format!("version != tatara-receipt/v1 (got {v:?})")` on
1481        // the same wrapped `String` produces the same bytes as the
1482        // Display — surfaces at THIS test as a byte equality, so the
1483        // reconciler's `WrongVersion` arm's routing swap (from an
1484        // inline `format!` to `err.to_string()`) preserves the
1485        // dashboard-anchored substring `"version != tatara-receipt/v1"`
1486        // that operators grep on.
1487        let v = "tatara-receipt/v99".to_string();
1488        let pre_lift = format!("version != tatara-receipt/v1 (got {v:?})");
1489        assert_eq!(
1490            msg, pre_lift,
1491            "WrongVersion Display must byte-match the pre-lift boundary.rs format literal",
1492        );
1493    }
1494
1495    #[test]
1496    fn missing_field_rejected() {
1497        let mut env: serde_json::Value = serde_json::from_str(&canonical_payload_json()).unwrap();
1498        env.as_object_mut().unwrap().remove("intent_hash");
1499        let err = ReceiptEnvelope::parse_json(&env.to_string()).unwrap_err();
1500        assert!(matches!(err, ReceiptError::InvalidJson(_)));
1501    }
1502
1503    #[test]
1504    fn unknown_field_rejected() {
1505        let mut env: serde_json::Value = serde_json::from_str(&canonical_payload_json()).unwrap();
1506        env["forged_extra"] = "should-fail".into();
1507        let err = ReceiptEnvelope::parse_json(&env.to_string()).unwrap_err();
1508        assert!(matches!(err, ReceiptError::InvalidJson(_)));
1509    }
1510
1511    #[test]
1512    fn empty_kind_rejected_in_verify_shape() {
1513        let mut r = ReceiptEnvelope::build("k", "i", "a", "c", None);
1514        r.kind = String::new();
1515        assert!(matches!(r.verify_shape(), Err(ReceiptError::EmptyKind)));
1516    }
1517
1518    #[test]
1519    fn expect_root_matches_or_mismatches() {
1520        let r = ReceiptEnvelope::build("test-suite", "i", "a", "c", None);
1521        let root = r.composed_root.clone();
1522        assert!(r.expect_root(Some(&root)).is_ok());
1523        let err = r.expect_root(Some("nope")).unwrap_err();
1524        assert!(matches!(err, ReceiptError::RootMismatch { .. }));
1525        assert!(r.expect_root(None).is_ok());
1526    }
1527
1528    #[test]
1529    fn lower_to_attestation_chains_pillars() {
1530        let r = ReceiptEnvelope::build("closed-loop-auth", "i", "a", "c", None);
1531        let a = r.to_attestation(0, None);
1532        assert_eq!(a.intent_hash, "i");
1533        assert_eq!(a.artifact_hash, "a");
1534        assert_eq!(a.control_hash.as_deref(), Some("c"));
1535        // Both compose the same root.
1536        assert_eq!(a.composed_root, r.composed_root);
1537        assert!(a.verify());
1538
1539        let next = r.to_attestation(1, Some(&a.composed_root));
1540        assert_eq!(next.generation, 1);
1541        assert_eq!(
1542            next.previous_root.as_deref(),
1543            Some(a.composed_root.as_str())
1544        );
1545        // The composed_root differs because previous_root is included.
1546        assert_ne!(next.composed_root, a.composed_root);
1547    }
1548
1549    #[test]
1550    fn verify_root_detects_tamper() {
1551        let mut r = ReceiptEnvelope::build("closed-loop-auth", "i", "a", "c", None);
1552        assert!(r.verify_root(None));
1553        r.intent_hash = "tampered".into();
1554        assert!(!r.verify_root(None));
1555    }
1556
1557    #[test]
1558    fn process_ref_optional_and_round_trips() {
1559        let mut r = ReceiptEnvelope::build("test-suite", "i", "a", "c", None);
1560        r.process_ref = Some("demo-test/ephemeral".into());
1561        let s = serde_json::to_string(&r).unwrap();
1562        let back = ReceiptEnvelope::parse_json(&s).expect("round-trip");
1563        assert_eq!(back.process_ref.as_deref(), Some("demo-test/ephemeral"));
1564    }
1565
1566    #[test]
1567    fn evidence_round_trips() {
1568        let mut r = ReceiptEnvelope::build("test-suite", "i", "a", "c", None);
1569        r.evidence = serde_json::json!({ "passed": 12, "failed": 0, "duration_ms": 4200 });
1570        let s = serde_json::to_string(&r).unwrap();
1571        let back = ReceiptEnvelope::parse_json(&s).expect("round-trip");
1572        assert_eq!(back.evidence["passed"], 12);
1573    }
1574
1575    // ── ReceiptKind closed-set truth-table ───────────────────────────
1576
1577    /// Structural well-formedness of [`ReceiptKind`] as a
1578    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
1579    /// testkit lift that pins all three structural invariants (`ALL`
1580    /// is non-empty, every variant round-trips through
1581    /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
1582    /// outside the closed set) at ONE call site. Replaces the hand-
1583    /// derived `receipt_kind_all_enumerates_each_variant_exactly_once`
1584    /// + `receipt_kind_from_str_round_trips_canonical_names` + the
1585    /// empty-input arm of `receipt_kind_from_str_rejects_open_kinds`.
1586    /// `FromStr` delegates to
1587    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
1588    /// exercises the same code path operators hit when parsing a wire
1589    /// `kind` field back to the typed kind.
1590    #[test]
1591    fn receipt_kind_is_well_formed_closed_set() {
1592        tatara_closed_set::assert_closed_set_well_formed::<ReceiptKind>();
1593    }
1594
1595    #[test]
1596    fn receipt_kind_canonical_names_pinned() {
1597        // Byte-exact wire-format pin — renaming any of these is a
1598        // wire-format change, not a typed-internal refactor.
1599        assert_eq!(ReceiptKind::ClosedLoopAuth.as_str(), "closed-loop-auth");
1600        assert_eq!(ReceiptKind::DbMigration.as_str(), "db-migration");
1601        assert_eq!(ReceiptKind::TestSuite.as_str(), "test-suite");
1602        assert_eq!(ReceiptKind::NixBuild.as_str(), "nix-build");
1603    }
1604
1605    #[test]
1606    fn receipt_kind_from_str_rejects_open_kinds() {
1607        // Future / typo / wrong-case all surface a typed
1608        // UnknownReceiptKind carrying the offending input verbatim
1609        // (operator-facing diagnostic); the schema is open at the
1610        // wire layer, but the closed-set view is byte-exact. The
1611        // empty-input arm is pinned by
1612        // [`receipt_kind_is_well_formed_closed_set`] via the
1613        // `tatara_lisp::ClosedSet` testkit; the cases here pin the
1614        // verbatim-echo contract on the [`UnknownReceiptKind`] newtype,
1615        // which the trait's `make_unknown` can't see.
1616        for bad in ["closed_loop_auth", "ClosedLoopAuth", "operator-custom-kind"] {
1617            let err = bad.parse::<ReceiptKind>().unwrap_err();
1618            assert_eq!(err, UnknownReceiptKind(bad.to_string()));
1619        }
1620    }
1621
1622    #[test]
1623    fn receipt_kind_display_delegates_to_as_str() {
1624        for k in ReceiptKind::ALL {
1625            assert_eq!(format!("{k}"), k.as_str());
1626        }
1627    }
1628
1629    #[test]
1630    fn receipt_kind_into_string_matches_as_str() {
1631        for k in ReceiptKind::ALL {
1632            let s: String = k.into();
1633            assert_eq!(s, k.as_str());
1634        }
1635    }
1636
1637    #[test]
1638    fn build_accepts_typed_receipt_kind() {
1639        // The typed → wire bridge: `build(ReceiptKind::X, …)` produces
1640        // a receipt whose `kind` field is exactly `X.as_str()`.
1641        for k in ReceiptKind::ALL {
1642            let env = ReceiptEnvelope::build(k, "i", "a", "c", None);
1643            assert_eq!(env.kind, k.as_str());
1644            assert!(env.verify_shape().is_ok());
1645            assert!(env.verify_root(None));
1646        }
1647    }
1648
1649    #[test]
1650    fn known_kind_decodes_built_receipts() {
1651        for k in ReceiptKind::ALL {
1652            let env = ReceiptEnvelope::build(k, "i", "a", "c", None);
1653            assert_eq!(env.known_kind(), Some(k));
1654        }
1655    }
1656
1657    #[test]
1658    fn known_kind_returns_none_for_open_kinds() {
1659        // Open-by-design: a custom operator-registered kind still
1660        // parses, still verifies, and still attests — it just doesn't
1661        // project through the closed-set typed view.
1662        let env = ReceiptEnvelope::build("operator-custom-kind", "i", "a", "c", None);
1663        assert_eq!(env.known_kind(), None);
1664        assert!(
1665            env.verify_shape().is_ok(),
1666            "open kind must remain a valid receipt"
1667        );
1668    }
1669
1670    // ── `control_hash_opt` / `empty_to_none` — the wire-form-to-typed
1671    //    projection of the second pillar (control step). Pre-lift the
1672    //    `is_empty() ? None : Some(&self.control_hash)` two-arm
1673    //    conditional lived at THREE inline sites — `build`,
1674    //    `verify_root`, `to_attestation` — each hand-writing the SAME
1675    //    projection with slightly-different ownership shapes
1676    //    (`Option<&str>` for the two composers, `Option<String>` for
1677    //    the attestation composer). Post-lift the projection lives at
1678    //    ONE inherent method + ONE free-fn peer for the pre-envelope
1679    //    call site. The tests below pin the substrate primitive's
1680    //    contract at its boundary so a regression at the projection
1681    //    surfaces here rather than as a silent `composed_root` drift
1682    //    at every consumer that composes the pillar.
1683
1684    #[test]
1685    fn empty_to_none_projects_empty_to_none_and_non_empty_to_some_verbatim() {
1686        // The pre-envelope free-fn peer of `control_hash_opt` — used
1687        // by `build` before the envelope exists. Pin BOTH arms of the
1688        // projection: an empty string projects to `None` (the "no
1689        // such pillar" convention that `compose_root` threads through
1690        // the absent-pillar BLAKE3 bytes pattern), and any non-empty
1691        // string projects to `Some(s)` byte-identical to the input.
1692        // A regression that (a) inverted the arms (folding `""` to
1693        // `Some("")` and every non-empty into `None`), (b) normalized
1694        // the payload (trimming whitespace, lowercasing hex), or (c)
1695        // introduced a sentinel-string special case (`"none"`, `"-"`,
1696        // etc.) would surface here rather than as a silent
1697        // `composed_root` shift at every consumer that composes the
1698        // pillar.
1699        assert_eq!(super::empty_to_none(""), None);
1700        assert_eq!(super::empty_to_none("c"), Some("c"));
1701        assert_eq!(super::empty_to_none("cccc"), Some("cccc"));
1702        // A whitespace-only string is NOT empty by the pillar's typed
1703        // contract — the substrate composes bytes verbatim through
1704        // BLAKE3, so a `" "` control hash IS a distinct pillar from
1705        // an absent one; the projection must preserve that
1706        // distinction.
1707        assert_eq!(super::empty_to_none(" "), Some(" "));
1708    }
1709
1710    #[test]
1711    fn control_hash_opt_matches_the_free_fn_peer_on_every_receipt() {
1712        // Post-envelope inherent method routes through the same
1713        // `empty_to_none` free-fn body — pin the equivalence across
1714        // both arms so a future regression that split the two
1715        // projections (e.g. the inherent method starts trimming, the
1716        // free-fn stays byte-verbatim) surfaces here rather than as a
1717        // `composed_root` mismatch between `build` (uses the free-fn
1718        // peer) and `verify_root` / `to_attestation` (use the
1719        // inherent method).
1720        let with_control = ReceiptEnvelope::build("test-suite", "i", "a", "cccc", None);
1721        assert_eq!(with_control.control_hash_opt(), Some("cccc"));
1722        assert_eq!(
1723            with_control.control_hash_opt(),
1724            super::empty_to_none(&with_control.control_hash),
1725        );
1726
1727        let no_control = ReceiptEnvelope::build("nix-build", "i", "a", "", None);
1728        assert_eq!(no_control.control_hash_opt(), None);
1729        assert_eq!(
1730            no_control.control_hash_opt(),
1731            super::empty_to_none(&no_control.control_hash),
1732        );
1733    }
1734
1735    #[test]
1736    fn control_hash_opt_composes_the_same_root_the_three_consumers_bind() {
1737        // End-to-end pin at the receipt-lifecycle boundary — the
1738        // three consumers (`build`, `verify_root`, `to_attestation`)
1739        // must land on the SAME `composed_root` for a given pillar
1740        // tuple regardless of which projection body they route
1741        // through. Sweeps BOTH pillar arms (present control + empty
1742        // control) so a regression that mis-wired ONE consumer to
1743        // the pre-lift inline conditional or that changed the
1744        // projection at ONE site surfaces here rather than as a
1745        // silent divergence between `verify_root`'s decision and
1746        // `to_attestation`'s written `composed_root`.
1747        for control in ["", "control-hash-cccc"] {
1748            let env = ReceiptEnvelope::build("test-suite", "i", "a", control, None);
1749            // `verify_root` composes through the inherent method AND
1750            // through the same `three_pillar::compose_root(&artifact, control_opt,
1751            // &intent, previous)` skeleton `build` binds — so the
1752            // envelope must verify against its own composed root.
1753            assert!(
1754                env.verify_root(None),
1755                "verify_root failed for control={control:?}",
1756            );
1757            // `to_attestation` composes the same pillar tuple through
1758            // `ProcessAttestation::compose`'s `Option<String>` shape;
1759            // the attestation's `composed_root` must match the
1760            // envelope's `composed_root` byte-for-byte because both
1761            // compose the SAME BLAKE3 domain-tagged skeleton over
1762            // the SAME typed-Option pillar identity.
1763            let att = env.to_attestation(0, None);
1764            assert_eq!(
1765                att.composed_root, env.composed_root,
1766                "attestation root drift for control={control:?}",
1767            );
1768        }
1769    }
1770
1771    // ── `REQUIRED_PILLARS` / `require_nonempty` — the closed-set
1772    //    table + shared rejection peer that `verify_shape` composes
1773    //    the three required-pillar emptiness checks through. Pre-lift
1774    //    the three `if self.<pillar>.is_empty() { return Err(
1775    //    ReceiptError::MissingField("<pillar>")); }` two-arm
1776    //    conditionals lived inline in `verify_shape` — one per pillar
1777    //    name, each hand-writing the SAME (field-name, accessor,
1778    //    rejection) triple. Post-lift the three (field-name,
1779    //    accessor) pairs live at ONE `REQUIRED_PILLARS` const, and
1780    //    the rejection body lives at ONE `require_nonempty` peer. The
1781    //    tests below pin the substrate primitives' contract at their
1782    //    boundary so a regression at the projection surfaces here
1783    //    rather than as a silent shift in the receipt's structural
1784    //    validation semantics.
1785
1786    #[test]
1787    fn require_nonempty_rejects_empty_with_the_named_field_and_passes_non_empty_verbatim() {
1788        // The shared rejection peer of `empty_to_none` — used by
1789        // `verify_shape` through the `REQUIRED_PILLARS` sweep. Pin
1790        // BOTH arms of the projection: an empty value rejects with
1791        // `ReceiptError::MissingField(field)` carrying the literal
1792        // `field` byte-identically (so a rename at the table entry
1793        // reaches the operator's diagnostic surface — the reconciler
1794        // event, the CLI stderr, the `tatara-check` receipt-inspect
1795        // report), and any non-empty value passes with `Ok(())`
1796        // (regardless of the payload's shape — a whitespace-only `" "`
1797        // is NOT empty by the pillar's typed contract). A regression
1798        // that (a) mis-named the field on the rejection (leaking a
1799        // caller-controlled `&str` in place of the `&'static` diagnostic
1800        // literal), (b) rejected non-empty values (folding `" "` or
1801        // some other sentinel into `MissingField`), or (c) accepted
1802        // the empty payload silently would surface here rather than
1803        // as a silent semantic shift in `verify_shape`'s rejection
1804        // vocabulary.
1805        assert_eq!(
1806            super::require_nonempty("composed_root", ""),
1807            Err(ReceiptError::MissingField("composed_root")),
1808        );
1809        assert_eq!(
1810            super::require_nonempty("intent_hash", ""),
1811            Err(ReceiptError::MissingField("intent_hash")),
1812        );
1813        assert_eq!(super::require_nonempty("composed_root", "aaaa"), Ok(()));
1814        // Whitespace-only strings pass the rejection gate — the
1815        // substrate composes bytes verbatim through BLAKE3 so `" "`
1816        // IS a distinct pillar from an absent one; the rejection
1817        // must preserve that distinction.
1818        assert_eq!(super::require_nonempty("intent_hash", " "), Ok(()));
1819    }
1820
1821    #[test]
1822    fn required_pillars_table_is_pairwise_distinct_and_enumerates_the_three_names() {
1823        // The closed-set table `verify_shape` dispatches through.
1824        // Pin: (a) the arity is exactly THREE (rustc's `[…; 3]`
1825        // constant on the type binds this at compile time; the pin
1826        // here checks the runtime enumeration matches so a future
1827        // arity bump surfaces as a coordinated update rather than a
1828        // silent drift), (b) each entry's field name is a
1829        // pillar-unique string (a duplicate entry — the same pillar
1830        // listed twice — would evaluate the same rejection twice at
1831        // ONE run, hiding a distinct pillar's absence behind the
1832        // duplicate's success), (c) the three names match the
1833        // byte-exact wire literals the reconciler tests + operator
1834        // diagnostics have already published (`"composed_root"`,
1835        // `"intent_hash"`, `"artifact_hash"`) — renaming any of them
1836        // is a wire-diagnostic change, not a typed-internal refactor.
1837        let names: Vec<&'static str> = ReceiptEnvelope::REQUIRED_PILLARS
1838            .iter()
1839            .map(|(name, _)| *name)
1840            .collect();
1841        assert_eq!(names, vec!["composed_root", "intent_hash", "artifact_hash"]);
1842
1843        // Pairwise-distinct check — the table's arity is small
1844        // enough for a hand-authored O(n^2) sweep, and a duplicate
1845        // would defeat the whole point of the enumeration.
1846        for i in 0..names.len() {
1847            for j in (i + 1)..names.len() {
1848                assert_ne!(
1849                    names[i], names[j],
1850                    "REQUIRED_PILLARS[{i}] and [{j}] share field name {}",
1851                    names[i],
1852                );
1853            }
1854        }
1855
1856        // control_hash is DELIBERATELY not in the table (it carries
1857        // the "empty means absent" semantic bit — see
1858        // `control_hash_opt` + `empty_to_none`). Pin the exclusion so
1859        // a future well-meaning addition that promotes control_hash
1860        // to a required pillar surfaces here as a contract change
1861        // rather than as a silent rejection of receipts the
1862        // substrate's own compose_root treats as valid absent-pillar
1863        // walks.
1864        assert!(
1865            !names.contains(&"control_hash"),
1866            "control_hash must not be in REQUIRED_PILLARS — its emptiness \
1867             is the substrate's absent-pillar convention",
1868        );
1869    }
1870
1871    #[test]
1872    fn verify_shape_rejects_each_required_pillar_when_emptied_with_the_typed_field_name() {
1873        // End-to-end pin at the `verify_shape` boundary — each entry
1874        // in `REQUIRED_PILLARS` must surface a
1875        // `ReceiptError::MissingField(field)` carrying the entry's
1876        // OWN name when its accessor's value is empty. Sweeps the
1877        // table so a future fourth required pillar picks up the
1878        // rejection through the SAME per-entry iteration + the SAME
1879        // shared `require_nonempty` peer, and a mis-wired accessor
1880        // (an entry naming "intent_hash" whose accessor reads
1881        // `self.artifact_hash`) surfaces here as a mismatched typed
1882        // rejection rather than as a silent semantic drift at
1883        // production.
1884        for (field, accessor) in ReceiptEnvelope::REQUIRED_PILLARS {
1885            let mut env = ReceiptEnvelope::build("test-suite", "i", "a", "c", None);
1886            // Empty ONLY the pillar under test by zeroing the field
1887            // through the wire-form struct's own mutable access
1888            // (which the `#[serde(deny_unknown_fields)]` wire shape
1889            // doesn't restrict at the Rust level).
1890            match field {
1891                "composed_root" => env.composed_root.clear(),
1892                "intent_hash" => env.intent_hash.clear(),
1893                "artifact_hash" => env.artifact_hash.clear(),
1894                other => panic!("unknown REQUIRED_PILLARS entry {other}"),
1895            }
1896            assert!(
1897                accessor(&env).is_empty(),
1898                "accessor for {field} did not read the emptied field",
1899            );
1900            let err = env
1901                .verify_shape()
1902                .expect_err("verify_shape must reject empty required pillar");
1903            assert_eq!(
1904                err,
1905                ReceiptError::MissingField(field),
1906                "verify_shape returned {err:?} — expected MissingField({field:?})",
1907            );
1908        }
1909    }
1910
1911    // ── RECEIPT_CM_SUFFIX + default_receipt_config_map_name ──────────
1912    //
1913    // Fail-before-pass-after pins for the substrate-level naming
1914    // convention that the reconciler's JobAttested + ClosedLoopAuth
1915    // evaluators AND the export-worker renderer all route through
1916    // for their default-derivation callsites. A regression that
1917    // renamed the suffix (e.g. `-receipt` → `-attest`, `-cm`, or
1918    // `.receipt`) OR that swapped the composition order at the
1919    // composer (e.g. `<suffix><job>` instead of `<job><suffix>`)
1920    // would silently misroute every default-derivation receipt-CM
1921    // read against a ConfigMap the Job never wrote to — the pins
1922    // here catch the drift at the primitive itself, before it
1923    // reaches any downstream consumer.
1924
1925    #[test]
1926    fn receipt_cm_suffix_pinned_to_dash_receipt() {
1927        // Byte-exact wire-format pin — renaming this is a wire-name
1928        // change, not a typed-internal refactor. Operators grep for
1929        // the `-receipt` suffix in kubectl output; dashboards and
1930        // export tooling template on it; the closed-loop-probe chart
1931        // publishes ConfigMaps at this suffix. A silent rename here
1932        // would desync all of them at once.
1933        assert_eq!(RECEIPT_CM_SUFFIX, "-receipt");
1934    }
1935
1936    #[test]
1937    fn default_receipt_config_map_name_appends_suffix_to_job_name() {
1938        // The canonical composition every default-derivation site
1939        // routed through pre-lift as `format!("{name}-receipt")`.
1940        assert_eq!(default_receipt_config_map_name("my-job"), "my-job-receipt");
1941        assert_eq!(
1942            default_receipt_config_map_name("probe-job"),
1943            "probe-job-receipt"
1944        );
1945    }
1946
1947    #[test]
1948    fn default_receipt_config_map_name_composes_through_the_suffix_const() {
1949        // Cross-primitive coherence pin — the composer's output must
1950        // equal `<job_name>{RECEIPT_CM_SUFFIX}` verbatim across a
1951        // sweep of shipped Job-name shapes (bare, hierarchical
1952        // export-index, closed-loop probe derivation, one-char, and
1953        // empty). A regression that inlined the suffix at the
1954        // composer (breaking the const's role as the ONE source of
1955        // truth) fails HERE at the shipped-shape sweep because the
1956        // pin re-reads the const at test time.
1957        for job_name in [
1958            "my-job",
1959            "r1-export-0",
1960            "attest-export-5",
1961            "closed-loop-attest-closed-loop-probe",
1962            "x",
1963            "",
1964        ] {
1965            let mut expected = String::new();
1966            expected.push_str(job_name);
1967            expected.push_str(RECEIPT_CM_SUFFIX);
1968            assert_eq!(
1969                default_receipt_config_map_name(job_name),
1970                expected,
1971                "default_receipt_config_map_name({job_name:?}) drifted from \
1972                 <job>++RECEIPT_CM_SUFFIX composition",
1973            );
1974        }
1975    }
1976
1977    // ── resolve_receipt_config_map_name ────────────────────────────
1978    //
1979    // Fail-before-pass-after pins for the substrate-level
1980    // override-then-fallback resolution rule the reconciler's
1981    // JobAttested + ClosedLoopAuth postcondition evaluators both
1982    // route through post-lift. A regression that swapped the arm
1983    // priority (fallback beating a Some override), stripped the
1984    // empty-string preservation on the Some arm, or drifted the
1985    // None arm off the substrate composer would silently misroute
1986    // every postcondition-facing receipt-CM read — the pins here
1987    // catch the drift at the primitive itself, before it reaches
1988    // the shipped `evaluate_*` sites.
1989    //
1990    // Pre-lift the SAME 4-line `.clone().unwrap_or_else(||
1991    // default_receipt_config_map_name(&<job>))` chain was hand-
1992    // authored at TWO boundary.rs sites past the ★★ PRIME-DIRECTIVE
1993    // ≥ 2 duplication threshold; post-lift both route through this
1994    // ONE substrate primitive and any future normalization (a per-
1995    // fleet suffix override, a namespace-prefixed derivation) lands
1996    // here rather than at the pair of evaluator sites.
1997
1998    #[test]
1999    fn resolve_receipt_config_map_name_prefers_supplied_override_verbatim() {
2000        // The Some arm is byte-preserving — an operator who supplies
2001        // an explicit `receiptConfigMap: "custom-cm"` on the
2002        // postcondition's params gets `"custom-cm"` back, regardless
2003        // of the fallback Job name the postcondition would otherwise
2004        // derive against. Pins the pre-lift `.clone().unwrap_or_else(
2005        // || default_receipt_config_map_name(...))` semantics — the
2006        // Some arm never touches the fallback composer.
2007        assert_eq!(
2008            resolve_receipt_config_map_name(Some("custom-cm"), "my-job"),
2009            "custom-cm",
2010        );
2011        assert_eq!(
2012            resolve_receipt_config_map_name(Some("op-supplied-name"), "unrelated-job"),
2013            "op-supplied-name",
2014        );
2015    }
2016
2017    #[test]
2018    fn resolve_receipt_config_map_name_falls_back_to_default_composer_on_none() {
2019        // The None arm delegates to the substrate composer verbatim —
2020        // the wire-name that lands here is byte-identical to what the
2021        // sibling `default_receipt_config_map_name(<job>)` produces at
2022        // the same Job name. Pins the pre-lift `.unwrap_or_else(||
2023        // default_receipt_config_map_name(&<job>))` fallback path.
2024        for job_name in [
2025            "my-job",
2026            "closed-loop-attest-closed-loop-probe",
2027            "svc-abc-job-42",
2028        ] {
2029            assert_eq!(
2030                resolve_receipt_config_map_name(None, job_name),
2031                default_receipt_config_map_name(job_name),
2032                "resolve_receipt_config_map_name(None, {job_name:?}) must byte-match \
2033                 default_receipt_config_map_name({job_name:?}) — the None arm's fallback \
2034                 routing off the substrate composer drifted",
2035            );
2036        }
2037    }
2038
2039    #[test]
2040    fn resolve_receipt_config_map_name_preserves_empty_override_bytewise() {
2041        // The `.clone().unwrap_or_else(...)` chain pre-lift returned
2042        // the empty string verbatim when the operator supplied
2043        // `receiptConfigMap: ""` — an empty Some, not None. Pin that
2044        // the substrate primitive matches: the empty-string corner
2045        // routes through the Some arm, not the None fallback, so the
2046        // operator-visible misconfiguration surfaces downstream at
2047        // the postcondition evaluator's fetch site (as an
2048        // `Unsatisfied` diagnostic) rather than being silently
2049        // reshaped into the derived-default name.
2050        assert_eq!(resolve_receipt_config_map_name(Some(""), "my-job"), "");
2051    }
2052
2053    #[test]
2054    fn resolve_receipt_config_map_name_matches_pre_lift_boundary_chain_shape() {
2055        // Byte-shape parity pin — for every combination of (override,
2056        // job_name) that the two pre-lift boundary.rs sites could
2057        // have fed the `.clone().unwrap_or_else(||
2058        // default_receipt_config_map_name(&<job>))` chain, the post-
2059        // lift substrate primitive produces the same String. A
2060        // regression that reshaped either arm (a stray `.trim()`, an
2061        // implicit `String::new()` on an empty Some, a swap of the
2062        // second-argument's borrow form) surfaces HERE at the
2063        // reconstructed pre-lift chain, not at the shipped evaluator.
2064        let cases: &[(Option<&str>, &str)] = &[
2065            (None, "job-a"),
2066            (Some("override-cm"), "job-b"),
2067            (Some(""), "job-c"),
2068            (None, ""),
2069            (Some("custom"), ""),
2070        ];
2071        for (override_name, job_name) in cases {
2072            let via_substrate = resolve_receipt_config_map_name(*override_name, job_name);
2073            let pre_lift = override_name
2074                .map(str::to_string)
2075                .unwrap_or_else(|| default_receipt_config_map_name(job_name));
2076            assert_eq!(
2077                via_substrate, pre_lift,
2078                "resolve_receipt_config_map_name({override_name:?}, {job_name:?}) \
2079                 drifted from the pre-lift `.clone().unwrap_or_else(|| \
2080                 default_receipt_config_map_name(&<job>))` chain shape",
2081            );
2082        }
2083    }
2084
2085    // ── RECEIPT_JSON_KEY / RECEIPT_YAML_KEY / RECEIPT_CM_KEYS /
2086    //    RECEIPT_CM_MISSING_KEY_MSG / extract_receipt_payload_json ─────
2087    //
2088    // Fail-before-pass-after pins for the substrate-level (primary,
2089    // fallback) receipt-CM `data`-key pair AND the reader-side lookup
2090    // gate composer that every receipt-CM consumer routes through.
2091    // A regression that renamed either key OR that swapped the
2092    // primary/fallback ordering at the reader gate would silently
2093    // desynchronize writer/reader pairs across the workspace — the
2094    // pins here catch the drift at the primitives themselves, before
2095    // it reaches any downstream ConfigMap-fetch site.
2096    //
2097    // Pre-lift the two keys appeared as inline `&'static str` literals
2098    // at FOUR production sites (2 writer inserts + 2 reader lookups)
2099    // with no shared owner binding their spelling OR the primary-first
2100    // ordering that the reader-side gate encodes as a load-bearing
2101    // invariant.
2102
2103    #[test]
2104    fn receipt_cm_keys_pinned_to_wire_form_literals() {
2105        // Byte-exact wire-format pin — renaming either is a wire-name
2106        // change, not a typed-internal refactor. Operators grep for
2107        // these keys in kubectl output; the closed-loop-probe chart
2108        // publishes ConfigMaps carrying them; the reconciler's
2109        // JobAttested/ClosedLoopAuth evaluators gate on them. A silent
2110        // rename here would desync every writer/reader pair fleet-wide.
2111        assert_eq!(RECEIPT_JSON_KEY, "receipt.json");
2112        assert_eq!(RECEIPT_YAML_KEY, "receipt.yaml");
2113    }
2114
2115    #[test]
2116    fn receipt_cm_keys_table_pins_primary_first_ordering() {
2117        // The primary/fallback ordering is load-bearing — the reader
2118        // gate returns the FIRST hit, so JSON must precede YAML to
2119        // preserve the substrate's "JSON is machine-canonical, YAML
2120        // is operator-facing readable twin" contract. A regression
2121        // that reordered the table would silently promote YAML over
2122        // JSON — the payload STILL parses (both wire forms round-trip
2123        // through the same `ReceiptEnvelope::parse_either`), but the
2124        // reader now prefers the operator-facing form when both are
2125        // present, breaking the substrate's payload-form preference.
2126        assert_eq!(RECEIPT_CM_KEYS, [RECEIPT_JSON_KEY, RECEIPT_YAML_KEY]);
2127        assert_eq!(RECEIPT_CM_KEYS[0], RECEIPT_JSON_KEY);
2128        assert_eq!(RECEIPT_CM_KEYS[1], RECEIPT_YAML_KEY);
2129        assert_eq!(RECEIPT_CM_KEYS.len(), 2);
2130    }
2131
2132    #[test]
2133    fn receipt_cm_missing_key_msg_names_both_keys_in_primary_first_order() {
2134        // The diagnostic message the reader-side gate returns when
2135        // neither key is present must NAME both keys so the operator
2136        // reading a `ReceiptVerdict::Malformed(...)` event knows
2137        // exactly which `data.<key>` entries the reader looked up.
2138        // Pin the message contains BOTH key literals (a rename at
2139        // either key const would drift the message spelling silently
2140        // if the message were `format!`-composed at the callsite;
2141        // the substrate owns the message const alongside the two key
2142        // consts so a coordinated update lands here).
2143        assert!(
2144            RECEIPT_CM_MISSING_KEY_MSG.contains(RECEIPT_JSON_KEY),
2145            "missing-key diagnostic must name {RECEIPT_JSON_KEY}",
2146        );
2147        assert!(
2148            RECEIPT_CM_MISSING_KEY_MSG.contains(RECEIPT_YAML_KEY),
2149            "missing-key diagnostic must name {RECEIPT_YAML_KEY}",
2150        );
2151        // Primary before fallback in the diagnostic text — the
2152        // operator's mental model matches the reader's iteration order.
2153        let json_pos = RECEIPT_CM_MISSING_KEY_MSG
2154            .find(RECEIPT_JSON_KEY)
2155            .expect("json key present");
2156        let yaml_pos = RECEIPT_CM_MISSING_KEY_MSG
2157            .find(RECEIPT_YAML_KEY)
2158            .expect("yaml key present");
2159        assert!(
2160            json_pos < yaml_pos,
2161            "diagnostic must name {RECEIPT_JSON_KEY} before {RECEIPT_YAML_KEY}",
2162        );
2163    }
2164
2165    #[test]
2166    fn extract_receipt_payload_json_returns_none_when_data_absent() {
2167        // The reader-side gate handles the `data` map's own absence
2168        // gracefully — `obj.data.get("data")` returns `None` when the
2169        // ConfigMap carries no `data` map, and the gate must project
2170        // that to `None` rather than panic or return a spurious hit.
2171        assert_eq!(extract_receipt_payload_json(None), None);
2172    }
2173
2174    #[test]
2175    fn extract_receipt_payload_json_returns_none_when_neither_key_present() {
2176        // A ConfigMap with `data` but no receipt payload — the gate
2177        // returns `None` so the caller can project to the typed
2178        // `ReceiptVerdict::Malformed(RECEIPT_CM_MISSING_KEY_MSG)`.
2179        let data = serde_json::json!({ "unrelated.key": "value" });
2180        assert_eq!(extract_receipt_payload_json(Some(&data)), None);
2181    }
2182
2183    #[test]
2184    fn extract_receipt_payload_json_prefers_primary_over_fallback_when_both_present() {
2185        // Load-bearing primary-first invariant — when BOTH keys are
2186        // present (the normal writer emit shape), the reader must
2187        // return the JSON form. A regression that swapped the
2188        // iteration order would silently promote YAML over JSON with
2189        // NO observable failure at parse time (both round-trip through
2190        // `parse_either`), so the pin here catches the ordering drift
2191        // at the reader gate itself.
2192        let data = serde_json::json!({
2193            RECEIPT_JSON_KEY: "json-payload",
2194            RECEIPT_YAML_KEY: "yaml-payload",
2195        });
2196        assert_eq!(
2197            extract_receipt_payload_json(Some(&data)),
2198            Some("json-payload"),
2199            "reader must prefer {RECEIPT_JSON_KEY} over {RECEIPT_YAML_KEY} when both present",
2200        );
2201    }
2202
2203    #[test]
2204    fn extract_receipt_payload_json_falls_back_to_yaml_when_json_absent() {
2205        // Fallback arm — an older probe binary or a hand-authored
2206        // fixture that only wrote the YAML form still reads
2207        // successfully. Pins that the YAML entry is reachable through
2208        // the gate.
2209        let data = serde_json::json!({
2210            RECEIPT_YAML_KEY: "yaml-payload",
2211        });
2212        assert_eq!(
2213            extract_receipt_payload_json(Some(&data)),
2214            Some("yaml-payload"),
2215        );
2216    }
2217
2218    #[test]
2219    fn extract_receipt_payload_json_returns_first_key_when_only_primary_present() {
2220        // Primary-only arm — the writer emitted just the JSON form
2221        // (e.g. a future probe that dropped the YAML twin). Reader
2222        // still resolves the payload through the primary key.
2223        let data = serde_json::json!({
2224            RECEIPT_JSON_KEY: "json-payload",
2225        });
2226        assert_eq!(
2227            extract_receipt_payload_json(Some(&data)),
2228            Some("json-payload"),
2229        );
2230    }
2231
2232    #[test]
2233    fn extract_receipt_payload_json_rejects_non_string_scalar_values() {
2234        // The wire contract says receipt payload values are string
2235        // scalars — a JSON number, object, or array at either key is
2236        // NOT a valid payload. The gate returns `None` (the caller
2237        // then projects to a `Malformed` verdict) rather than a
2238        // spurious hit that would panic downstream in the parser.
2239        let data = serde_json::json!({
2240            RECEIPT_JSON_KEY: 42,
2241            RECEIPT_YAML_KEY: ["not", "a", "string"],
2242        });
2243        assert_eq!(extract_receipt_payload_json(Some(&data)), None);
2244    }
2245
2246    #[test]
2247    fn extract_receipt_payload_json_skips_non_string_primary_and_falls_back_to_string_fallback() {
2248        // Mixed case — the primary key exists but carries a non-string
2249        // value (a malformed writer, a partially-migrated wire form),
2250        // and the fallback key carries a valid string payload. The
2251        // gate treats the non-string primary as absent for the
2252        // string-scalar projection contract and returns the string
2253        // fallback. This preserves availability at the reader when a
2254        // writer half-populated the primary.
2255        let data = serde_json::json!({
2256            RECEIPT_JSON_KEY: { "nested": "object" },
2257            RECEIPT_YAML_KEY: "yaml-payload",
2258        });
2259        assert_eq!(
2260            extract_receipt_payload_json(Some(&data)),
2261            Some("yaml-payload"),
2262        );
2263    }
2264
2265    #[test]
2266    fn extract_receipt_payload_json_matches_hand_authored_pre_lift_chain_bytewise() {
2267        // Byte-identity pin against the pre-lift 3-link combinator
2268        // chain that `verify_receipt_cm` composed inline:
2269        //     data.and_then(|d| d.get(RECEIPT_JSON_KEY))
2270        //         .or_else(|| data.and_then(|d| d.get(RECEIPT_YAML_KEY)))
2271        //         .and_then(|v| v.as_str())
2272        // Sweeps the four (primary-present × fallback-present)
2273        // combinations so a regression at the primitive that broke
2274        // the byte identity with the pre-lift shape surfaces here
2275        // rather than as a subtle divergence at ONE quadrant.
2276        for (json_val, yaml_val) in [
2277            (Some("json"), Some("yaml")),
2278            (Some("json"), None::<&str>),
2279            (None::<&str>, Some("yaml")),
2280            (None::<&str>, None::<&str>),
2281        ] {
2282            let mut map = serde_json::Map::new();
2283            if let Some(j) = json_val {
2284                map.insert(RECEIPT_JSON_KEY.into(), serde_json::Value::String(j.into()));
2285            }
2286            if let Some(y) = yaml_val {
2287                map.insert(RECEIPT_YAML_KEY.into(), serde_json::Value::String(y.into()));
2288            }
2289            let data = serde_json::Value::Object(map);
2290            let via_primitive = extract_receipt_payload_json(Some(&data));
2291            let via_pre_lift_chain = data
2292                .get(RECEIPT_JSON_KEY)
2293                .or_else(|| data.get(RECEIPT_YAML_KEY))
2294                .and_then(serde_json::Value::as_str);
2295            assert_eq!(
2296                via_primitive, via_pre_lift_chain,
2297                "extract_receipt_payload_json diverged from pre-lift chain at \
2298                 (json={json_val:?}, yaml={yaml_val:?})",
2299            );
2300        }
2301    }
2302
2303    #[test]
2304    fn default_receipt_config_map_name_matches_prior_hand_authored_format_shape() {
2305        // Path-uniformity pin against the three pre-lift `format!`
2306        // literals — each callsite spelled the shape a slightly
2307        // different way (`format!("{}-receipt", parsed.name)` /
2308        // `format!("{job_name}-receipt")` /
2309        // `format!("{process_name}-export-{index}-receipt")`) but
2310        // all three composed the SAME `<job>-receipt` byte sequence
2311        // once evaluated. The lift preserves that byte identity so
2312        // no downstream ConfigMap grep or fleet-shipped operator
2313        // override changes meaning. A regression at the primitive
2314        // that broke the byte identity (e.g. inserted a separator,
2315        // uppercased the suffix, dropped the leading dash) would
2316        // fail HERE against the pre-lift `format!` literal for a
2317        // hand-picked Job-name that carries no ambiguity around
2318        // separators.
2319        let job_name = "svc-abc-export-3";
2320        let pre_lift = format!("{job_name}-receipt");
2321        let post_lift = default_receipt_config_map_name(job_name);
2322        assert_eq!(
2323            pre_lift, post_lift,
2324            "post-lift primitive drifted from pre-lift `format!(\"{{name}}-receipt\")` byte shape",
2325        );
2326    }
2327}