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 /// Deserialize `payload` with this wire-form's serde reader,
639 /// wrapping the parser's `Display` in the matching per-form
640 /// [`ReceiptError`] variant. Does NOT run
641 /// [`ReceiptEnvelope::verify_shape`] — the shared
642 /// [`ReceiptEnvelope::parse`] owner composes that postpass so
643 /// every wrapper picks it up mechanically.
644 fn parse_raw(self, payload: &str) -> Result<ReceiptEnvelope, ReceiptError> {
645 match self {
646 Self::Json => {
647 serde_json::from_str(payload).map_err(|e| ReceiptError::InvalidJson(e.to_string()))
648 }
649 Self::Yaml => {
650 serde_yaml::from_str(payload).map_err(|e| ReceiptError::InvalidYaml(e.to_string()))
651 }
652 }
653 }
654
655 /// Stable wire-form label — the short lowercase identifier
656 /// (`"json"` / `"yaml"`) an operator-facing log line, a
657 /// per-form metrics tag, or a future CLI flag surface can print
658 /// or match against. Pins the closed-set spelling at ONE table
659 /// so a downstream rename lands here rather than at every
660 /// consumer that hand-composed `"json"` / `"yaml"` inline.
661 #[must_use]
662 pub const fn as_str(self) -> &'static str {
663 match self {
664 Self::Json => "json",
665 Self::Yaml => "yaml",
666 }
667 }
668}
669
670/// Why a receipt is rejected. Kept as a typed enum so callers can
671/// pattern-match on the failure mode and surface targeted operator
672/// messages.
673#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
674pub enum ReceiptError {
675 #[error("invalid JSON: {0}")]
676 InvalidJson(String),
677 #[error("invalid YAML: {0}")]
678 InvalidYaml(String),
679 #[error("version != {RECEIPT_VERSION} (got {0:?})")]
680 WrongVersion(String),
681 #[error("missing required field: {0}")]
682 MissingField(&'static str),
683 #[error("kind is empty")]
684 EmptyKind,
685 #[error("composed_root mismatch (got {got}, want {want})")]
686 RootMismatch { got: String, want: String },
687}
688
689impl ReceiptEnvelope {
690 /// Build a receipt envelope from typed pillars + kind. `generated_at`
691 /// defaults to `Utc::now()`.
692 pub fn build(
693 kind: impl Into<String>,
694 intent_hash: impl Into<String>,
695 artifact_hash: impl Into<String>,
696 control_hash: impl Into<String>,
697 previous_root: Option<&str>,
698 ) -> Self {
699 let intent_hash = intent_hash.into();
700 let artifact_hash = artifact_hash.into();
701 let control_hash = control_hash.into();
702 let composed_root = three_pillar::compose_root(
703 &artifact_hash,
704 empty_to_none(&control_hash),
705 &intent_hash,
706 previous_root,
707 );
708 Self {
709 version: RECEIPT_VERSION.into(),
710 kind: kind.into(),
711 composed_root,
712 intent_hash,
713 artifact_hash,
714 control_hash,
715 generated_at: Utc::now(),
716 process_ref: None,
717 evidence: serde_json::Value::Null,
718 }
719 }
720
721 /// Parse `payload` as a [`ReceiptWireForm`]-tagged encoding and
722 /// validate the result's shape — the ONE parse-then-verify chain
723 /// every [`Self::parse_json`] / [`Self::parse_yaml`] /
724 /// [`Self::parse_either`] wrapper composes through, and the entry
725 /// consumers that dispatch on a typed wire-form value (an
726 /// operator-supplied "receipt payload is <form>" annotation, a
727 /// future CLI flag on `tatara-check` selecting the reader) call
728 /// directly.
729 ///
730 /// Pre-lift the parse + `verify_shape` chain was hand-authored at
731 /// TWO byte-identical sites past the ★★ PRIME-DIRECTIVE ≥ 2
732 /// duplication threshold — [`Self::parse_json`] and
733 /// [`Self::parse_yaml`] each restated the same
734 /// `<parser>(payload).map_err(|e| ReceiptError::<Variant>(
735 /// e.to_string()))?;` + `env.verify_shape()?; Ok(env)` shape with
736 /// only the parser + wrap-variant swapped. Post-lift the two
737 /// per-form deserialize+wrap pairings live at ONE closed-set
738 /// dispatch inside [`ReceiptWireForm::parse_raw`]; this owner
739 /// composes THAT dispatch with the shared `verify_shape` postpass
740 /// so the two wrappers, [`Self::parse_either`], and any future
741 /// wire-form consumer (adding e.g. `ReceiptWireForm::Cbor` for a
742 /// binary emit path) land at ONE arm without re-authoring the
743 /// verify chain.
744 pub fn parse(payload: &str, form: ReceiptWireForm) -> Result<Self, ReceiptError> {
745 let env = form.parse_raw(payload)?;
746 env.verify_shape()?;
747 Ok(env)
748 }
749
750 /// Parse a receipt from a JSON string.
751 pub fn parse_json(payload: &str) -> Result<Self, ReceiptError> {
752 Self::parse(payload, ReceiptWireForm::Json)
753 }
754
755 /// Parse a receipt from a YAML string. Useful for ConfigMaps that
756 /// store the payload in YAML form.
757 pub fn parse_yaml(payload: &str) -> Result<Self, ReceiptError> {
758 Self::parse(payload, ReceiptWireForm::Yaml)
759 }
760
761 /// Parse via JSON first, then YAML if JSON fails. Lets a single
762 /// reader accept either wire form without the operator having to
763 /// declare it. Useful when the Job writes JSON and the reconciler
764 /// reads back through a kube DynamicObject whose `data` is YAML.
765 pub fn parse_either(payload: &str) -> Result<Self, ReceiptError> {
766 Self::parse(payload, ReceiptWireForm::Json)
767 .or_else(|_| Self::parse(payload, ReceiptWireForm::Yaml))
768 }
769
770 /// Closed-set table of pillars that MUST be non-empty on every
771 /// well-formed receipt — the wire-form's structural invariant
772 /// [`Self::verify_shape`] enforces. Pre-lift the three checks
773 /// lived as three byte-identical `if self.<pillar>.is_empty() {
774 /// return Err(ReceiptError::MissingField("<pillar>")); }` two-arm
775 /// conditionals inline in `verify_shape` — one per pillar name,
776 /// each hand-writing the SAME (field-name, accessor, rejection)
777 /// triple with the pillar name repeated at BOTH the accessor
778 /// (`self.composed_root`) AND the diagnostic literal
779 /// (`"composed_root"`). Post-lift the three (field-name,
780 /// accessor) pairs live at ONE closed-set table here;
781 /// `verify_shape` composes ONE per-entry iteration that
782 /// dispatches through the shared [`require_nonempty`] free-fn
783 /// peer of [`empty_to_none`].
784 ///
785 /// Each entry is a [`RequiredPillar`] tuple whose named type gives
786 /// downstream consumers (a `tatara-check` receipt-inspector, an
787 /// LSP hover, a per-pillar dashboard column) a nameable handle
788 /// for "one pillar's (diagnostic-name, wire-form-accessor)
789 /// pairing" rather than an unnamed function-pointer tuple
790 /// re-typed at every consumer.
791 ///
792 /// The `control_hash` field is DELIBERATELY NOT in this table:
793 /// the substrate's second pillar carries an "empty means absent"
794 /// convention that [`Self::control_hash_opt`] + [`empty_to_none`]
795 /// project as a typed `Option::None`, so its emptiness is a
796 /// semantic bit rather than a validation failure. The pair
797 /// (`REQUIRED_PILLARS` — must be non-empty; `control_hash_opt` —
798 /// may be empty) is the substrate's typed answer to which
799 /// pillars are load-bearing vs. schema-optional. A future
800 /// re-shape that promotes a fourth required pillar (e.g. a
801 /// mandatory `signer_hash` on a signed-receipt schema variant)
802 /// lands as ONE new entry in this table + rustc's `[…; N]`
803 /// arity constant on the type binding the extension in lockstep
804 /// so a partial addition that forgets the diagnostic surface
805 /// becomes a compile error rather than a runtime drift.
806 ///
807 /// Sibling closed-set tables across the crate:
808 /// [`ReceiptKind::ALL`],
809 /// [`crate::export::ReportFormat::ALL`],
810 /// [`crate::phase::ProcessPhase::ALL`],
811 /// [`crate::boundary::ConditionKind::ALL`],
812 /// [`crate::intent::IntentKind::ALL`].
813 ///
814 /// Theory anchor: THEORY.md §VI.1 — generation over composition;
815 /// the three inline pillar-emptiness checks recurred at THREE
816 /// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold
817 /// and are lifted to ONE closed-set table + ONE shared rejection
818 /// peer. THEORY.md §V.1 — knowable platform; the enumeration of
819 /// required-pillar field names lives at ONE surface a
820 /// documentation surface, an LSP hover, or a `tatara-check`
821 /// receipt-inspector binds to for enumerating the receipt's
822 /// structural invariants. THEORY.md §V.3 — three-pillar
823 /// attestation; the (mandatory, may-be-absent) split of the
824 /// three-pillar-plus-composed-root wire form is a typed
825 /// substrate contract, not a per-consumer discipline.
826 pub const REQUIRED_PILLARS: [RequiredPillar; 3] = [
827 ("composed_root", |e| e.composed_root.as_str()),
828 ("intent_hash", |e| e.intent_hash.as_str()),
829 ("artifact_hash", |e| e.artifact_hash.as_str()),
830 ];
831
832 /// Verify the schema-level invariants: correct version + non-empty
833 /// kind + non-empty pillar hashes (length-only, not BLAKE3-recompute).
834 /// The three required-pillar rejections dispatch through
835 /// [`Self::REQUIRED_PILLARS`] + [`require_nonempty`] so a future
836 /// fourth required pillar lands at ONE table entry rather than
837 /// as a fourth inline `if …is_empty() { return Err(…); }` copy.
838 pub fn verify_shape(&self) -> Result<(), ReceiptError> {
839 if self.version != RECEIPT_VERSION {
840 return Err(ReceiptError::WrongVersion(self.version.clone()));
841 }
842 if self.kind.is_empty() {
843 return Err(ReceiptError::EmptyKind);
844 }
845 for (field, accessor) in Self::REQUIRED_PILLARS {
846 require_nonempty(field, accessor(self))?;
847 }
848 // control_hash MAY be empty when there is no control step;
849 // the BLAKE3 compose treats empty as "absent" via Option —
850 // see `Self::control_hash_opt` + `empty_to_none`.
851 Ok(())
852 }
853
854 /// Verify that `composed_root` is consistent with the pillars.
855 /// `expected_previous_root` is the previous root in the Process's
856 /// attestation chain (or `None` for first attestation).
857 pub fn verify_root(&self, expected_previous_root: Option<&str>) -> bool {
858 let want = three_pillar::compose_root(
859 &self.artifact_hash,
860 self.control_hash_opt(),
861 &self.intent_hash,
862 expected_previous_root,
863 );
864 three_pillar::constant_time_eq(want.as_bytes(), self.composed_root.as_bytes())
865 }
866
867 /// Strict-equality check against an operator-provided expected root.
868 /// Returns the receipt's root unchanged on success.
869 pub fn expect_root(&self, expected: Option<&str>) -> Result<&str, ReceiptError> {
870 if let Some(want) = expected {
871 if want != self.composed_root {
872 return Err(ReceiptError::RootMismatch {
873 got: self.composed_root.clone(),
874 want: want.to_string(),
875 });
876 }
877 }
878 Ok(&self.composed_root)
879 }
880
881 /// Decode `self.kind` into the typed [`ReceiptKind`] variant when
882 /// the wire string matches one of the four substrate-emitted
883 /// canonical kebab-case kinds; `None` when the kind is an
884 /// operator-registered open string (the schema is open by design —
885 /// every receipt remains a valid receipt, but only typed kinds
886 /// participate in closed-set dispatch). The (open `String`,
887 /// closed-typed view) split lets future kind-keyed consumers
888 /// (verifier registries, dashboard completion, audit-trail
889 /// classifiers) sweep the typed variants without touching the
890 /// open-by-design wire shape. Lifted as the canonical decode site
891 /// so no consumer re-implements the `match self.kind.as_str()`
892 /// arm-by-arm — the closed-set sweep happens through
893 /// [`ReceiptKind::from_str`] at ONE site.
894 #[must_use]
895 pub fn known_kind(&self) -> Option<ReceiptKind> {
896 self.kind.parse().ok()
897 }
898
899 /// Lower into a `ProcessAttestation` — the canonical handoff so a
900 /// Job's typed receipt becomes evidence on a Process. `generation`
901 /// + `previous_root` come from the owning Process's prior
902 /// attestation (or 0 + None for the first cycle).
903 pub fn to_attestation(
904 &self,
905 generation: u64,
906 previous_root: Option<&str>,
907 ) -> ProcessAttestation {
908 ProcessAttestation::compose(
909 self.artifact_hash.clone(),
910 self.control_hash_opt().map(str::to_owned),
911 self.intent_hash.clone(),
912 previous_root.map(String::from),
913 generation,
914 )
915 }
916
917 /// Typed projection of the wire form's `control_hash` field —
918 /// `Some(hash)` when a control step ran, `None` when it did not.
919 ///
920 /// The wire form stamps `control_hash: String` (schema-open,
921 /// serde-friendly), but the substrate's `three_pillar::compose_root`
922 /// + `ProcessAttestation::compose` compositions both take an
923 /// `Option<&str>` / `Option<String>` and thread `None` through the
924 /// exact BLAKE3 bytes pattern an absent-pillar walk emits — an
925 /// empty `control_hash` and an absent-pillar receipt hash to the
926 /// SAME `composed_root`. That "empty means absent" convention
927 /// pre-lift lived at THREE sites inside this impl block —
928 /// [`Self::build`] (constructing the envelope from typed pillars),
929 /// [`Self::verify_root`] (recomposing the root against pillars for
930 /// wire-form verification), and [`Self::to_attestation`] (lowering
931 /// the receipt into a [`ProcessAttestation`] on a Process's
932 /// attestation chain) — each hand-writing the SAME
933 /// `if self.control_hash.is_empty() { None } else {
934 /// Some(self.control_hash.as_str()) }` two-arm conditional. Post-
935 /// lift the convention lives at ONE method here; the three
936 /// consumers each compose a ONE-LINE call:
937 /// * `verify_root` → `self.control_hash_opt()` directly,
938 /// * `to_attestation` → `self.control_hash_opt().map(str::to_owned)`
939 /// for the `Option<String>` shape [`ProcessAttestation::compose`]
940 /// binds,
941 /// * `build` (which reads a local `control_hash: String` before
942 /// the envelope is constructed) → the free-fn peer
943 /// [`empty_to_none`] on the same borrowed string.
944 ///
945 /// Public because the projection is load-bearing operator-facing
946 /// contract: an authoring surface (an LSP hover, a
947 /// `tatara-check` report, a REPL `:receipt-inspect` command) that
948 /// wants to render "no control step" vs. "control_hash: <hash>"
949 /// binds to this method rather than pattern-matching on
950 /// `self.control_hash.is_empty()` at its own call site — a future
951 /// re-shape of the empty-means-absent convention (a sentinel-
952 /// string variant, an explicit `Option<String>` on the wire form
953 /// once the schema evolves, or a typed
954 /// `ControlStep::{Ran(hash), Skipped}` enum) lands at ONE method
955 /// here rather than at every consumer that inspects the pillar.
956 ///
957 /// Theory anchor: THEORY.md §V.1 — knowable platform; the
958 /// wire-vs-typed projection lives at ONE substrate method so a
959 /// consumer reads the pillar's typed-Option contract from the
960 /// receipt directly, not from three parallel inline conditionals
961 /// scattered across `build` / `verify_root` / `to_attestation`.
962 /// THEORY.md §VI.1 — generation over composition; the
963 /// `is_empty() ? None : Some(&self.control_hash)` two-arm
964 /// projection recurred at THREE inline sites past the ★★
965 /// PRIME-DIRECTIVE ≥ 2 duplication threshold and is lifted to ONE
966 /// owner here. THEORY.md §V.3 — three-pillar attestation; the
967 /// receipt's second pillar (control step) has ONE typed projection
968 /// site the composition primitives
969 /// ([`three_pillar::compose_root`], [`ProcessAttestation::compose`])
970 /// both bind against, so the pillar's wire-vs-typed identity
971 /// cannot drift across the three consumers.
972 #[must_use]
973 pub fn control_hash_opt(&self) -> Option<&str> {
974 empty_to_none(&self.control_hash)
975 }
976}
977
978/// Project a wire-form pillar string onto its typed `Option<&str>`
979/// contract — `Some(s)` when `s` is non-empty, `None` when `s` is
980/// empty (the substrate's "no such pillar" convention that
981/// [`three_pillar::compose_root`] + [`ProcessAttestation::compose`]
982/// both thread as an absent-pillar walk through the BLAKE3
983/// domain-tagged composition).
984///
985/// The free-fn peer of [`ReceiptEnvelope::control_hash_opt`] for
986/// call sites that hold a borrowed pillar string BEFORE a
987/// [`ReceiptEnvelope`] is constructed — namely
988/// [`ReceiptEnvelope::build`]'s inline `compose_root` call, which
989/// composes the pillar's typed-Option identity from the local
990/// `control_hash: String` intake before the envelope value exists.
991/// The two peers share ONE projection body (`(!s.is_empty()).
992/// then_some(s)`) so a future re-shape of the empty-means-absent
993/// convention (a sentinel-string variant, an explicit
994/// `Option<String>` on the wire form once the schema evolves)
995/// lands at ONE substrate primitive rather than at both the
996/// inherent method and its pre-construction free-fn peer.
997///
998/// Theory anchor: THEORY.md §VI.1 — generation over composition;
999/// the pre-construction peer of the pillar projection lives at ONE
1000/// substrate primitive alongside the post-construction inherent
1001/// method, so the two receipt-lifecycle stages (pre-envelope in
1002/// [`ReceiptEnvelope::build`], post-envelope in every other
1003/// consumer) share ONE typed projection.
1004fn empty_to_none(s: &str) -> Option<&str> {
1005 (!s.is_empty()).then_some(s)
1006}
1007
1008/// Reject a required pillar whose wire form is empty with a typed
1009/// [`ReceiptError::MissingField`] carrying `field` — the diagnostic
1010/// literal the operator sees. Free-fn peer of [`empty_to_none`] on
1011/// the same wire-form-emptiness axis, and rejection sibling of the
1012/// [`ReceiptEnvelope::REQUIRED_PILLARS`] closed-set table
1013/// [`ReceiptEnvelope::verify_shape`] dispatches through.
1014///
1015/// The two peers on the emptiness axis carry two different typed
1016/// projections of the SAME wire-form bit:
1017/// * [`empty_to_none`] — the "empty means absent" convention for
1018/// the second pillar (control step); the substrate composes
1019/// `Option::None` through `compose_root` so an empty
1020/// `control_hash` and an absent-pillar receipt hash to the SAME
1021/// `composed_root`.
1022/// * [`require_nonempty`] — the "empty is a validation failure"
1023/// convention for the three required pillars; the substrate
1024/// rejects the receipt with a typed [`ReceiptError::MissingField`]
1025/// carrying the offending field name so the operator's diagnostic
1026/// surface (a reconciler event, a CLI stderr, a `tatara-check`
1027/// receipt-inspect report) names the pillar directly.
1028///
1029/// The two peers are DELIBERATELY named as (`empty_to_none`,
1030/// `require_nonempty`) rather than as a single overloaded projection
1031/// so the two typed conventions (absence-as-Option vs.
1032/// absence-as-Err) surface at the substrate's exported vocabulary
1033/// as two distinct primitives — a per-caller misroute (composing
1034/// `require_nonempty` on `control_hash` and getting a false
1035/// `MissingField`, or composing `empty_to_none` on `intent_hash`
1036/// and threading `None` through `compose_root` past a wire that
1037/// should have rejected) is a name-typo, not a silent semantic
1038/// swap.
1039///
1040/// Theory anchor: THEORY.md §VI.1 — generation over composition;
1041/// the "empty is a required-pillar failure" three-line inline
1042/// conditional recurred at THREE sites past the ★★ PRIME-DIRECTIVE
1043/// ≥ 2 duplication threshold and is lifted to ONE substrate primitive
1044/// composed through the [`ReceiptEnvelope::REQUIRED_PILLARS`] table.
1045/// THEORY.md §V.1 — knowable platform; the two emptiness projections
1046/// live at ONE typed vocabulary the receipt-inspection surfaces (LSP
1047/// hover, `tatara-check` report, REPL) bind to for reading the
1048/// receipt's structural contract from the substrate directly.
1049fn require_nonempty(field: &'static str, value: &str) -> Result<(), ReceiptError> {
1050 if value.is_empty() {
1051 return Err(ReceiptError::MissingField(field));
1052 }
1053 Ok(())
1054}
1055
1056#[cfg(test)]
1057mod tests {
1058 use super::*;
1059
1060 fn sample_payload() -> &'static str {
1061 // Composed_root precomputed from three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None)
1062 // (recomputed at test time to be canonical; this string is regenerated
1063 // if the domain tag ever changes).
1064 r#"{
1065 "version": "tatara-receipt/v1",
1066 "kind": "closed-loop-auth",
1067 "composed_root": "RECOMPUTE",
1068 "intent_hash": "aaaa",
1069 "artifact_hash": "bbbb",
1070 "control_hash": "cccc",
1071 "generated_at": "2026-05-19T12:00:00Z"
1072 }"#
1073 }
1074
1075 fn canonical_payload_json() -> String {
1076 let root = three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None);
1077 sample_payload().replace("RECOMPUTE", &root)
1078 }
1079
1080 #[test]
1081 fn build_produces_valid_envelope() {
1082 let r = ReceiptEnvelope::build("test-suite", "i", "a", "c", None);
1083 assert_eq!(r.version, RECEIPT_VERSION);
1084 assert_eq!(r.kind, "test-suite");
1085 assert!(r.verify_shape().is_ok());
1086 assert!(r.verify_root(None));
1087 }
1088
1089 #[test]
1090 fn build_empty_control_omits_from_root() {
1091 let with_empty = ReceiptEnvelope::build("nix-build", "i", "a", "", None);
1092 let with_explicit_none = ReceiptEnvelope::build("nix-build", "i", "a", "", None);
1093 assert_eq!(with_empty.composed_root, with_explicit_none.composed_root);
1094
1095 // And differs from a receipt with a real control hash.
1096 let with_control = ReceiptEnvelope::build("nix-build", "i", "a", "c", None);
1097 assert_ne!(with_empty.composed_root, with_control.composed_root);
1098 }
1099
1100 #[test]
1101 fn parse_json_round_trip() {
1102 let r = ReceiptEnvelope::parse_json(&canonical_payload_json()).expect("parse");
1103 assert_eq!(r.kind, "closed-loop-auth");
1104 assert!(r.verify_root(None));
1105 }
1106
1107 #[test]
1108 fn parse_yaml_round_trip() {
1109 let yaml = r#"
1110version: tatara-receipt/v1
1111kind: db-migration
1112composed_root: ROOT
1113intent_hash: aaaa
1114artifact_hash: bbbb
1115control_hash: cccc
1116generated_at: 2026-05-19T12:00:00Z
1117"#
1118 .replace(
1119 "ROOT",
1120 &three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None),
1121 );
1122 let r = ReceiptEnvelope::parse_yaml(&yaml).expect("yaml parse");
1123 assert_eq!(r.kind, "db-migration");
1124 assert!(r.verify_root(None));
1125 }
1126
1127 #[test]
1128 fn wire_form_labels_pinned() {
1129 // Byte-exact wire-form labels — a rename here is a
1130 // wire-format change, not a typed-internal refactor. Log
1131 // lines / metrics tags / future CLI flags grep for these.
1132 assert_eq!(ReceiptWireForm::Json.as_str(), "json");
1133 assert_eq!(ReceiptWireForm::Yaml.as_str(), "yaml");
1134 }
1135
1136 #[test]
1137 fn parse_dispatches_json_arm_byte_identically_to_parse_json() {
1138 // The two owners must produce byte-identical output on the
1139 // happy path — a regression that skewed either arm surfaces
1140 // HERE rather than at every downstream call site of the
1141 // wrappers.
1142 let payload = canonical_payload_json();
1143 let via_enum = ReceiptEnvelope::parse(&payload, ReceiptWireForm::Json).expect("json parse");
1144 let via_wrapper = ReceiptEnvelope::parse_json(&payload).expect("json wrapper parse");
1145 assert_eq!(via_enum, via_wrapper);
1146 }
1147
1148 #[test]
1149 fn parse_dispatches_yaml_arm_byte_identically_to_parse_yaml() {
1150 let yaml = r#"
1151version: tatara-receipt/v1
1152kind: db-migration
1153composed_root: ROOT
1154intent_hash: aaaa
1155artifact_hash: bbbb
1156control_hash: cccc
1157generated_at: 2026-05-19T12:00:00Z
1158"#
1159 .replace(
1160 "ROOT",
1161 &three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None),
1162 );
1163 let via_enum = ReceiptEnvelope::parse(&yaml, ReceiptWireForm::Yaml).expect("yaml parse");
1164 let via_wrapper = ReceiptEnvelope::parse_yaml(&yaml).expect("yaml wrapper parse");
1165 assert_eq!(via_enum, via_wrapper);
1166 }
1167
1168 #[test]
1169 fn parse_wrong_form_wraps_in_matching_error_variant() {
1170 // Wire-form arm selection travels with the ReceiptError
1171 // variant — a JSON payload parsed as YAML surfaces
1172 // `InvalidYaml`, not `InvalidJson`, so an operator log line
1173 // reads the encoding-that-failed without a hand-threaded
1174 // per-form label. Pins the (arm, wrap-variant) coherence
1175 // so a regression that decoupled either half surfaces here.
1176 let json_payload = canonical_payload_json();
1177 // JSON as JSON parses cleanly (baseline).
1178 assert!(ReceiptEnvelope::parse(&json_payload, ReceiptWireForm::Json).is_ok());
1179 // Bytes that a JSON reader rejects but a YAML reader silently
1180 // accepts (JSON is a strict YAML subset, so the reverse cross-
1181 // parse doesn't fail cleanly on any real payload; use invalid
1182 // JSON that's ALSO invalid YAML to pin per-arm wrap variants).
1183 let bad = "{ not-valid-";
1184 let json_err =
1185 ReceiptEnvelope::parse(bad, ReceiptWireForm::Json).expect_err("json rejects");
1186 let yaml_err =
1187 ReceiptEnvelope::parse(bad, ReceiptWireForm::Yaml).expect_err("yaml rejects");
1188 assert!(
1189 matches!(json_err, ReceiptError::InvalidJson(_)),
1190 "json arm must wrap in InvalidJson, got {json_err:?}"
1191 );
1192 assert!(
1193 matches!(yaml_err, ReceiptError::InvalidYaml(_)),
1194 "yaml arm must wrap in InvalidYaml, got {yaml_err:?}"
1195 );
1196 }
1197
1198 #[test]
1199 fn parse_either_falls_back_to_yaml() {
1200 let yaml = r#"
1201version: tatara-receipt/v1
1202kind: test-suite
1203composed_root: ROOT
1204intent_hash: aaaa
1205artifact_hash: bbbb
1206control_hash: cccc
1207generated_at: 2026-05-19T12:00:00Z
1208"#
1209 .replace(
1210 "ROOT",
1211 &three_pillar::compose_root("bbbb", Some("cccc"), "aaaa", None),
1212 );
1213 assert!(ReceiptEnvelope::parse_either(&yaml).is_ok());
1214 }
1215
1216 #[test]
1217 fn wrong_version_rejected() {
1218 let mut env: serde_json::Value = serde_json::from_str(&canonical_payload_json()).unwrap();
1219 env["version"] = "tatara-receipt/v2".into();
1220 let err = ReceiptEnvelope::parse_json(&env.to_string()).unwrap_err();
1221 assert!(matches!(err, ReceiptError::WrongVersion(ref s) if s == "tatara-receipt/v2"));
1222 }
1223
1224 #[test]
1225 fn receipt_version_wire_form_pin() {
1226 // Byte-shape pin on the ONE substrate const `RECEIPT_VERSION`.
1227 // The wire-form literal `"tatara-receipt/v1"` is the value
1228 // every serialized `ReceiptEnvelope.version` slot carries,
1229 // every reader gate rejects a mismatch against, and every
1230 // receipt-CM label value the closed-loop-probe stamps rides
1231 // through. A bump lands at this ONE const and every consumer
1232 // — the reconciler's `WrongVersion` diagnostic (routed
1233 // through the thiserror-derived Display via the enum's
1234 // `#[error("version != {RECEIPT_VERSION} (got {0:?})")]`
1235 // attribute), the closed-loop-probe's receipt-CM label VALUE,
1236 // and the envelope's `version` slot on build — inherits the
1237 // upgrade mechanically. This pin binds the current byte-form
1238 // so a bump surfaces here explicitly rather than as silent
1239 // drift at the two production sites that pre-lift restated
1240 // the literal by hand.
1241 assert_eq!(RECEIPT_VERSION, "tatara-receipt/v1");
1242 }
1243
1244 #[test]
1245 fn wrong_version_display_routes_through_receipt_version_const() {
1246 // Fail-before-pass-after substrate pin on the thiserror-
1247 // derived Display for `ReceiptError::WrongVersion`. Two
1248 // production consumers rely on this Display composing through
1249 // `RECEIPT_VERSION`:
1250 //
1251 // * `tatara-reconciler::boundary::receipt_error_message` — the
1252 // `WrongVersion` arm now delegates to this Display directly
1253 // (`err.to_string()`), so the reconciler's operator-facing
1254 // diagnostic tracks the substrate const without a per-arm
1255 // hand-authored format literal.
1256 // * `tatara-closed-loop-probe::write_receipt` — routes its
1257 // receipt-CM label VALUE through the same `RECEIPT_VERSION`
1258 // const directly, not this Display; both surfaces now share
1259 // the ONE owner.
1260 //
1261 // A regression that dropped the `{RECEIPT_VERSION}` interpolation
1262 // from the enum's `#[error(...)]` attribute — reinlining the
1263 // literal `"tatara-receipt/v1"` there — would silently
1264 // desynchronize the reconciler's diagnostic from the probe's
1265 // stamped label value on any future const bump. This pin
1266 // catches such a regression at the Display byte shape.
1267 let err = ReceiptError::WrongVersion("tatara-receipt/v99".into());
1268 let msg = err.to_string();
1269
1270 // Byte-shape pin: exact composition through the substrate
1271 // const, with `{0:?}` Debug-formatting the wrapped `String`
1272 // (adding surrounding quotes).
1273 assert_eq!(
1274 msg,
1275 format!("version != {RECEIPT_VERSION} (got \"tatara-receipt/v99\")"),
1276 "WrongVersion Display must compose through the RECEIPT_VERSION const",
1277 );
1278
1279 // Routing pin: the substrate const value appears verbatim in
1280 // the Display output — a bump at `RECEIPT_VERSION` surfaces
1281 // here immediately.
1282 assert!(
1283 msg.contains(RECEIPT_VERSION),
1284 "WrongVersion Display must contain RECEIPT_VERSION verbatim, got {msg:?}",
1285 );
1286
1287 // Compat pin: the pre-lift boundary.rs hand-authored format
1288 // `format!("version != tatara-receipt/v1 (got {v:?})")` on
1289 // the same wrapped `String` produces the same bytes as the
1290 // Display — surfaces at THIS test as a byte equality, so the
1291 // reconciler's `WrongVersion` arm's routing swap (from an
1292 // inline `format!` to `err.to_string()`) preserves the
1293 // dashboard-anchored substring `"version != tatara-receipt/v1"`
1294 // that operators grep on.
1295 let v = "tatara-receipt/v99".to_string();
1296 let pre_lift = format!("version != tatara-receipt/v1 (got {v:?})");
1297 assert_eq!(
1298 msg, pre_lift,
1299 "WrongVersion Display must byte-match the pre-lift boundary.rs format literal",
1300 );
1301 }
1302
1303 #[test]
1304 fn missing_field_rejected() {
1305 let mut env: serde_json::Value = serde_json::from_str(&canonical_payload_json()).unwrap();
1306 env.as_object_mut().unwrap().remove("intent_hash");
1307 let err = ReceiptEnvelope::parse_json(&env.to_string()).unwrap_err();
1308 assert!(matches!(err, ReceiptError::InvalidJson(_)));
1309 }
1310
1311 #[test]
1312 fn unknown_field_rejected() {
1313 let mut env: serde_json::Value = serde_json::from_str(&canonical_payload_json()).unwrap();
1314 env["forged_extra"] = "should-fail".into();
1315 let err = ReceiptEnvelope::parse_json(&env.to_string()).unwrap_err();
1316 assert!(matches!(err, ReceiptError::InvalidJson(_)));
1317 }
1318
1319 #[test]
1320 fn empty_kind_rejected_in_verify_shape() {
1321 let mut r = ReceiptEnvelope::build("k", "i", "a", "c", None);
1322 r.kind = String::new();
1323 assert!(matches!(r.verify_shape(), Err(ReceiptError::EmptyKind)));
1324 }
1325
1326 #[test]
1327 fn expect_root_matches_or_mismatches() {
1328 let r = ReceiptEnvelope::build("test-suite", "i", "a", "c", None);
1329 let root = r.composed_root.clone();
1330 assert!(r.expect_root(Some(&root)).is_ok());
1331 let err = r.expect_root(Some("nope")).unwrap_err();
1332 assert!(matches!(err, ReceiptError::RootMismatch { .. }));
1333 assert!(r.expect_root(None).is_ok());
1334 }
1335
1336 #[test]
1337 fn lower_to_attestation_chains_pillars() {
1338 let r = ReceiptEnvelope::build("closed-loop-auth", "i", "a", "c", None);
1339 let a = r.to_attestation(0, None);
1340 assert_eq!(a.intent_hash, "i");
1341 assert_eq!(a.artifact_hash, "a");
1342 assert_eq!(a.control_hash.as_deref(), Some("c"));
1343 // Both compose the same root.
1344 assert_eq!(a.composed_root, r.composed_root);
1345 assert!(a.verify());
1346
1347 let next = r.to_attestation(1, Some(&a.composed_root));
1348 assert_eq!(next.generation, 1);
1349 assert_eq!(
1350 next.previous_root.as_deref(),
1351 Some(a.composed_root.as_str())
1352 );
1353 // The composed_root differs because previous_root is included.
1354 assert_ne!(next.composed_root, a.composed_root);
1355 }
1356
1357 #[test]
1358 fn verify_root_detects_tamper() {
1359 let mut r = ReceiptEnvelope::build("closed-loop-auth", "i", "a", "c", None);
1360 assert!(r.verify_root(None));
1361 r.intent_hash = "tampered".into();
1362 assert!(!r.verify_root(None));
1363 }
1364
1365 #[test]
1366 fn process_ref_optional_and_round_trips() {
1367 let mut r = ReceiptEnvelope::build("test-suite", "i", "a", "c", None);
1368 r.process_ref = Some("demo-test/ephemeral".into());
1369 let s = serde_json::to_string(&r).unwrap();
1370 let back = ReceiptEnvelope::parse_json(&s).expect("round-trip");
1371 assert_eq!(back.process_ref.as_deref(), Some("demo-test/ephemeral"));
1372 }
1373
1374 #[test]
1375 fn evidence_round_trips() {
1376 let mut r = ReceiptEnvelope::build("test-suite", "i", "a", "c", None);
1377 r.evidence = serde_json::json!({ "passed": 12, "failed": 0, "duration_ms": 4200 });
1378 let s = serde_json::to_string(&r).unwrap();
1379 let back = ReceiptEnvelope::parse_json(&s).expect("round-trip");
1380 assert_eq!(back.evidence["passed"], 12);
1381 }
1382
1383 // ── ReceiptKind closed-set truth-table ───────────────────────────
1384
1385 /// Structural well-formedness of [`ReceiptKind`] as a
1386 /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
1387 /// testkit lift that pins all three structural invariants (`ALL`
1388 /// is non-empty, every variant round-trips through
1389 /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
1390 /// outside the closed set) at ONE call site. Replaces the hand-
1391 /// derived `receipt_kind_all_enumerates_each_variant_exactly_once`
1392 /// + `receipt_kind_from_str_round_trips_canonical_names` + the
1393 /// empty-input arm of `receipt_kind_from_str_rejects_open_kinds`.
1394 /// `FromStr` delegates to
1395 /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
1396 /// exercises the same code path operators hit when parsing a wire
1397 /// `kind` field back to the typed kind.
1398 #[test]
1399 fn receipt_kind_is_well_formed_closed_set() {
1400 tatara_closed_set::assert_closed_set_well_formed::<ReceiptKind>();
1401 }
1402
1403 #[test]
1404 fn receipt_kind_canonical_names_pinned() {
1405 // Byte-exact wire-format pin — renaming any of these is a
1406 // wire-format change, not a typed-internal refactor.
1407 assert_eq!(ReceiptKind::ClosedLoopAuth.as_str(), "closed-loop-auth");
1408 assert_eq!(ReceiptKind::DbMigration.as_str(), "db-migration");
1409 assert_eq!(ReceiptKind::TestSuite.as_str(), "test-suite");
1410 assert_eq!(ReceiptKind::NixBuild.as_str(), "nix-build");
1411 }
1412
1413 #[test]
1414 fn receipt_kind_from_str_rejects_open_kinds() {
1415 // Future / typo / wrong-case all surface a typed
1416 // UnknownReceiptKind carrying the offending input verbatim
1417 // (operator-facing diagnostic); the schema is open at the
1418 // wire layer, but the closed-set view is byte-exact. The
1419 // empty-input arm is pinned by
1420 // [`receipt_kind_is_well_formed_closed_set`] via the
1421 // `tatara_lisp::ClosedSet` testkit; the cases here pin the
1422 // verbatim-echo contract on the [`UnknownReceiptKind`] newtype,
1423 // which the trait's `make_unknown` can't see.
1424 for bad in ["closed_loop_auth", "ClosedLoopAuth", "operator-custom-kind"] {
1425 let err = bad.parse::<ReceiptKind>().unwrap_err();
1426 assert_eq!(err, UnknownReceiptKind(bad.to_string()));
1427 }
1428 }
1429
1430 #[test]
1431 fn receipt_kind_display_delegates_to_as_str() {
1432 for k in ReceiptKind::ALL {
1433 assert_eq!(format!("{k}"), k.as_str());
1434 }
1435 }
1436
1437 #[test]
1438 fn receipt_kind_into_string_matches_as_str() {
1439 for k in ReceiptKind::ALL {
1440 let s: String = k.into();
1441 assert_eq!(s, k.as_str());
1442 }
1443 }
1444
1445 #[test]
1446 fn build_accepts_typed_receipt_kind() {
1447 // The typed → wire bridge: `build(ReceiptKind::X, …)` produces
1448 // a receipt whose `kind` field is exactly `X.as_str()`.
1449 for k in ReceiptKind::ALL {
1450 let env = ReceiptEnvelope::build(k, "i", "a", "c", None);
1451 assert_eq!(env.kind, k.as_str());
1452 assert!(env.verify_shape().is_ok());
1453 assert!(env.verify_root(None));
1454 }
1455 }
1456
1457 #[test]
1458 fn known_kind_decodes_built_receipts() {
1459 for k in ReceiptKind::ALL {
1460 let env = ReceiptEnvelope::build(k, "i", "a", "c", None);
1461 assert_eq!(env.known_kind(), Some(k));
1462 }
1463 }
1464
1465 #[test]
1466 fn known_kind_returns_none_for_open_kinds() {
1467 // Open-by-design: a custom operator-registered kind still
1468 // parses, still verifies, and still attests — it just doesn't
1469 // project through the closed-set typed view.
1470 let env = ReceiptEnvelope::build("operator-custom-kind", "i", "a", "c", None);
1471 assert_eq!(env.known_kind(), None);
1472 assert!(
1473 env.verify_shape().is_ok(),
1474 "open kind must remain a valid receipt"
1475 );
1476 }
1477
1478 // ── `control_hash_opt` / `empty_to_none` — the wire-form-to-typed
1479 // projection of the second pillar (control step). Pre-lift the
1480 // `is_empty() ? None : Some(&self.control_hash)` two-arm
1481 // conditional lived at THREE inline sites — `build`,
1482 // `verify_root`, `to_attestation` — each hand-writing the SAME
1483 // projection with slightly-different ownership shapes
1484 // (`Option<&str>` for the two composers, `Option<String>` for
1485 // the attestation composer). Post-lift the projection lives at
1486 // ONE inherent method + ONE free-fn peer for the pre-envelope
1487 // call site. The tests below pin the substrate primitive's
1488 // contract at its boundary so a regression at the projection
1489 // surfaces here rather than as a silent `composed_root` drift
1490 // at every consumer that composes the pillar.
1491
1492 #[test]
1493 fn empty_to_none_projects_empty_to_none_and_non_empty_to_some_verbatim() {
1494 // The pre-envelope free-fn peer of `control_hash_opt` — used
1495 // by `build` before the envelope exists. Pin BOTH arms of the
1496 // projection: an empty string projects to `None` (the "no
1497 // such pillar" convention that `compose_root` threads through
1498 // the absent-pillar BLAKE3 bytes pattern), and any non-empty
1499 // string projects to `Some(s)` byte-identical to the input.
1500 // A regression that (a) inverted the arms (folding `""` to
1501 // `Some("")` and every non-empty into `None`), (b) normalized
1502 // the payload (trimming whitespace, lowercasing hex), or (c)
1503 // introduced a sentinel-string special case (`"none"`, `"-"`,
1504 // etc.) would surface here rather than as a silent
1505 // `composed_root` shift at every consumer that composes the
1506 // pillar.
1507 assert_eq!(super::empty_to_none(""), None);
1508 assert_eq!(super::empty_to_none("c"), Some("c"));
1509 assert_eq!(super::empty_to_none("cccc"), Some("cccc"));
1510 // A whitespace-only string is NOT empty by the pillar's typed
1511 // contract — the substrate composes bytes verbatim through
1512 // BLAKE3, so a `" "` control hash IS a distinct pillar from
1513 // an absent one; the projection must preserve that
1514 // distinction.
1515 assert_eq!(super::empty_to_none(" "), Some(" "));
1516 }
1517
1518 #[test]
1519 fn control_hash_opt_matches_the_free_fn_peer_on_every_receipt() {
1520 // Post-envelope inherent method routes through the same
1521 // `empty_to_none` free-fn body — pin the equivalence across
1522 // both arms so a future regression that split the two
1523 // projections (e.g. the inherent method starts trimming, the
1524 // free-fn stays byte-verbatim) surfaces here rather than as a
1525 // `composed_root` mismatch between `build` (uses the free-fn
1526 // peer) and `verify_root` / `to_attestation` (use the
1527 // inherent method).
1528 let with_control = ReceiptEnvelope::build("test-suite", "i", "a", "cccc", None);
1529 assert_eq!(with_control.control_hash_opt(), Some("cccc"));
1530 assert_eq!(
1531 with_control.control_hash_opt(),
1532 super::empty_to_none(&with_control.control_hash),
1533 );
1534
1535 let no_control = ReceiptEnvelope::build("nix-build", "i", "a", "", None);
1536 assert_eq!(no_control.control_hash_opt(), None);
1537 assert_eq!(
1538 no_control.control_hash_opt(),
1539 super::empty_to_none(&no_control.control_hash),
1540 );
1541 }
1542
1543 #[test]
1544 fn control_hash_opt_composes_the_same_root_the_three_consumers_bind() {
1545 // End-to-end pin at the receipt-lifecycle boundary — the
1546 // three consumers (`build`, `verify_root`, `to_attestation`)
1547 // must land on the SAME `composed_root` for a given pillar
1548 // tuple regardless of which projection body they route
1549 // through. Sweeps BOTH pillar arms (present control + empty
1550 // control) so a regression that mis-wired ONE consumer to
1551 // the pre-lift inline conditional or that changed the
1552 // projection at ONE site surfaces here rather than as a
1553 // silent divergence between `verify_root`'s decision and
1554 // `to_attestation`'s written `composed_root`.
1555 for control in ["", "control-hash-cccc"] {
1556 let env = ReceiptEnvelope::build("test-suite", "i", "a", control, None);
1557 // `verify_root` composes through the inherent method AND
1558 // through the same `three_pillar::compose_root(&artifact, control_opt,
1559 // &intent, previous)` skeleton `build` binds — so the
1560 // envelope must verify against its own composed root.
1561 assert!(
1562 env.verify_root(None),
1563 "verify_root failed for control={control:?}",
1564 );
1565 // `to_attestation` composes the same pillar tuple through
1566 // `ProcessAttestation::compose`'s `Option<String>` shape;
1567 // the attestation's `composed_root` must match the
1568 // envelope's `composed_root` byte-for-byte because both
1569 // compose the SAME BLAKE3 domain-tagged skeleton over
1570 // the SAME typed-Option pillar identity.
1571 let att = env.to_attestation(0, None);
1572 assert_eq!(
1573 att.composed_root, env.composed_root,
1574 "attestation root drift for control={control:?}",
1575 );
1576 }
1577 }
1578
1579 // ── `REQUIRED_PILLARS` / `require_nonempty` — the closed-set
1580 // table + shared rejection peer that `verify_shape` composes
1581 // the three required-pillar emptiness checks through. Pre-lift
1582 // the three `if self.<pillar>.is_empty() { return Err(
1583 // ReceiptError::MissingField("<pillar>")); }` two-arm
1584 // conditionals lived inline in `verify_shape` — one per pillar
1585 // name, each hand-writing the SAME (field-name, accessor,
1586 // rejection) triple. Post-lift the three (field-name,
1587 // accessor) pairs live at ONE `REQUIRED_PILLARS` const, and
1588 // the rejection body lives at ONE `require_nonempty` peer. The
1589 // tests below pin the substrate primitives' contract at their
1590 // boundary so a regression at the projection surfaces here
1591 // rather than as a silent shift in the receipt's structural
1592 // validation semantics.
1593
1594 #[test]
1595 fn require_nonempty_rejects_empty_with_the_named_field_and_passes_non_empty_verbatim() {
1596 // The shared rejection peer of `empty_to_none` — used by
1597 // `verify_shape` through the `REQUIRED_PILLARS` sweep. Pin
1598 // BOTH arms of the projection: an empty value rejects with
1599 // `ReceiptError::MissingField(field)` carrying the literal
1600 // `field` byte-identically (so a rename at the table entry
1601 // reaches the operator's diagnostic surface — the reconciler
1602 // event, the CLI stderr, the `tatara-check` receipt-inspect
1603 // report), and any non-empty value passes with `Ok(())`
1604 // (regardless of the payload's shape — a whitespace-only `" "`
1605 // is NOT empty by the pillar's typed contract). A regression
1606 // that (a) mis-named the field on the rejection (leaking a
1607 // caller-controlled `&str` in place of the `&'static` diagnostic
1608 // literal), (b) rejected non-empty values (folding `" "` or
1609 // some other sentinel into `MissingField`), or (c) accepted
1610 // the empty payload silently would surface here rather than
1611 // as a silent semantic shift in `verify_shape`'s rejection
1612 // vocabulary.
1613 assert_eq!(
1614 super::require_nonempty("composed_root", ""),
1615 Err(ReceiptError::MissingField("composed_root")),
1616 );
1617 assert_eq!(
1618 super::require_nonempty("intent_hash", ""),
1619 Err(ReceiptError::MissingField("intent_hash")),
1620 );
1621 assert_eq!(super::require_nonempty("composed_root", "aaaa"), Ok(()));
1622 // Whitespace-only strings pass the rejection gate — the
1623 // substrate composes bytes verbatim through BLAKE3 so `" "`
1624 // IS a distinct pillar from an absent one; the rejection
1625 // must preserve that distinction.
1626 assert_eq!(super::require_nonempty("intent_hash", " "), Ok(()));
1627 }
1628
1629 #[test]
1630 fn required_pillars_table_is_pairwise_distinct_and_enumerates_the_three_names() {
1631 // The closed-set table `verify_shape` dispatches through.
1632 // Pin: (a) the arity is exactly THREE (rustc's `[…; 3]`
1633 // constant on the type binds this at compile time; the pin
1634 // here checks the runtime enumeration matches so a future
1635 // arity bump surfaces as a coordinated update rather than a
1636 // silent drift), (b) each entry's field name is a
1637 // pillar-unique string (a duplicate entry — the same pillar
1638 // listed twice — would evaluate the same rejection twice at
1639 // ONE run, hiding a distinct pillar's absence behind the
1640 // duplicate's success), (c) the three names match the
1641 // byte-exact wire literals the reconciler tests + operator
1642 // diagnostics have already published (`"composed_root"`,
1643 // `"intent_hash"`, `"artifact_hash"`) — renaming any of them
1644 // is a wire-diagnostic change, not a typed-internal refactor.
1645 let names: Vec<&'static str> = ReceiptEnvelope::REQUIRED_PILLARS
1646 .iter()
1647 .map(|(name, _)| *name)
1648 .collect();
1649 assert_eq!(names, vec!["composed_root", "intent_hash", "artifact_hash"]);
1650
1651 // Pairwise-distinct check — the table's arity is small
1652 // enough for a hand-authored O(n^2) sweep, and a duplicate
1653 // would defeat the whole point of the enumeration.
1654 for i in 0..names.len() {
1655 for j in (i + 1)..names.len() {
1656 assert_ne!(
1657 names[i], names[j],
1658 "REQUIRED_PILLARS[{i}] and [{j}] share field name {}",
1659 names[i],
1660 );
1661 }
1662 }
1663
1664 // control_hash is DELIBERATELY not in the table (it carries
1665 // the "empty means absent" semantic bit — see
1666 // `control_hash_opt` + `empty_to_none`). Pin the exclusion so
1667 // a future well-meaning addition that promotes control_hash
1668 // to a required pillar surfaces here as a contract change
1669 // rather than as a silent rejection of receipts the
1670 // substrate's own compose_root treats as valid absent-pillar
1671 // walks.
1672 assert!(
1673 !names.contains(&"control_hash"),
1674 "control_hash must not be in REQUIRED_PILLARS — its emptiness \
1675 is the substrate's absent-pillar convention",
1676 );
1677 }
1678
1679 #[test]
1680 fn verify_shape_rejects_each_required_pillar_when_emptied_with_the_typed_field_name() {
1681 // End-to-end pin at the `verify_shape` boundary — each entry
1682 // in `REQUIRED_PILLARS` must surface a
1683 // `ReceiptError::MissingField(field)` carrying the entry's
1684 // OWN name when its accessor's value is empty. Sweeps the
1685 // table so a future fourth required pillar picks up the
1686 // rejection through the SAME per-entry iteration + the SAME
1687 // shared `require_nonempty` peer, and a mis-wired accessor
1688 // (an entry naming "intent_hash" whose accessor reads
1689 // `self.artifact_hash`) surfaces here as a mismatched typed
1690 // rejection rather than as a silent semantic drift at
1691 // production.
1692 for (field, accessor) in ReceiptEnvelope::REQUIRED_PILLARS {
1693 let mut env = ReceiptEnvelope::build("test-suite", "i", "a", "c", None);
1694 // Empty ONLY the pillar under test by zeroing the field
1695 // through the wire-form struct's own mutable access
1696 // (which the `#[serde(deny_unknown_fields)]` wire shape
1697 // doesn't restrict at the Rust level).
1698 match field {
1699 "composed_root" => env.composed_root.clear(),
1700 "intent_hash" => env.intent_hash.clear(),
1701 "artifact_hash" => env.artifact_hash.clear(),
1702 other => panic!("unknown REQUIRED_PILLARS entry {other}"),
1703 }
1704 assert!(
1705 accessor(&env).is_empty(),
1706 "accessor for {field} did not read the emptied field",
1707 );
1708 let err = env
1709 .verify_shape()
1710 .expect_err("verify_shape must reject empty required pillar");
1711 assert_eq!(
1712 err,
1713 ReceiptError::MissingField(field),
1714 "verify_shape returned {err:?} — expected MissingField({field:?})",
1715 );
1716 }
1717 }
1718
1719 // ── RECEIPT_CM_SUFFIX + default_receipt_config_map_name ──────────
1720 //
1721 // Fail-before-pass-after pins for the substrate-level naming
1722 // convention that the reconciler's JobAttested + ClosedLoopAuth
1723 // evaluators AND the export-worker renderer all route through
1724 // for their default-derivation callsites. A regression that
1725 // renamed the suffix (e.g. `-receipt` → `-attest`, `-cm`, or
1726 // `.receipt`) OR that swapped the composition order at the
1727 // composer (e.g. `<suffix><job>` instead of `<job><suffix>`)
1728 // would silently misroute every default-derivation receipt-CM
1729 // read against a ConfigMap the Job never wrote to — the pins
1730 // here catch the drift at the primitive itself, before it
1731 // reaches any downstream consumer.
1732
1733 #[test]
1734 fn receipt_cm_suffix_pinned_to_dash_receipt() {
1735 // Byte-exact wire-format pin — renaming this is a wire-name
1736 // change, not a typed-internal refactor. Operators grep for
1737 // the `-receipt` suffix in kubectl output; dashboards and
1738 // export tooling template on it; the closed-loop-probe chart
1739 // publishes ConfigMaps at this suffix. A silent rename here
1740 // would desync all of them at once.
1741 assert_eq!(RECEIPT_CM_SUFFIX, "-receipt");
1742 }
1743
1744 #[test]
1745 fn default_receipt_config_map_name_appends_suffix_to_job_name() {
1746 // The canonical composition every default-derivation site
1747 // routed through pre-lift as `format!("{name}-receipt")`.
1748 assert_eq!(default_receipt_config_map_name("my-job"), "my-job-receipt");
1749 assert_eq!(
1750 default_receipt_config_map_name("probe-job"),
1751 "probe-job-receipt"
1752 );
1753 }
1754
1755 #[test]
1756 fn default_receipt_config_map_name_composes_through_the_suffix_const() {
1757 // Cross-primitive coherence pin — the composer's output must
1758 // equal `<job_name>{RECEIPT_CM_SUFFIX}` verbatim across a
1759 // sweep of shipped Job-name shapes (bare, hierarchical
1760 // export-index, closed-loop probe derivation, one-char, and
1761 // empty). A regression that inlined the suffix at the
1762 // composer (breaking the const's role as the ONE source of
1763 // truth) fails HERE at the shipped-shape sweep because the
1764 // pin re-reads the const at test time.
1765 for job_name in [
1766 "my-job",
1767 "r1-export-0",
1768 "attest-export-5",
1769 "closed-loop-attest-closed-loop-probe",
1770 "x",
1771 "",
1772 ] {
1773 let mut expected = String::new();
1774 expected.push_str(job_name);
1775 expected.push_str(RECEIPT_CM_SUFFIX);
1776 assert_eq!(
1777 default_receipt_config_map_name(job_name),
1778 expected,
1779 "default_receipt_config_map_name({job_name:?}) drifted from \
1780 <job>++RECEIPT_CM_SUFFIX composition",
1781 );
1782 }
1783 }
1784
1785 // ── resolve_receipt_config_map_name ────────────────────────────
1786 //
1787 // Fail-before-pass-after pins for the substrate-level
1788 // override-then-fallback resolution rule the reconciler's
1789 // JobAttested + ClosedLoopAuth postcondition evaluators both
1790 // route through post-lift. A regression that swapped the arm
1791 // priority (fallback beating a Some override), stripped the
1792 // empty-string preservation on the Some arm, or drifted the
1793 // None arm off the substrate composer would silently misroute
1794 // every postcondition-facing receipt-CM read — the pins here
1795 // catch the drift at the primitive itself, before it reaches
1796 // the shipped `evaluate_*` sites.
1797 //
1798 // Pre-lift the SAME 4-line `.clone().unwrap_or_else(||
1799 // default_receipt_config_map_name(&<job>))` chain was hand-
1800 // authored at TWO boundary.rs sites past the ★★ PRIME-DIRECTIVE
1801 // ≥ 2 duplication threshold; post-lift both route through this
1802 // ONE substrate primitive and any future normalization (a per-
1803 // fleet suffix override, a namespace-prefixed derivation) lands
1804 // here rather than at the pair of evaluator sites.
1805
1806 #[test]
1807 fn resolve_receipt_config_map_name_prefers_supplied_override_verbatim() {
1808 // The Some arm is byte-preserving — an operator who supplies
1809 // an explicit `receiptConfigMap: "custom-cm"` on the
1810 // postcondition's params gets `"custom-cm"` back, regardless
1811 // of the fallback Job name the postcondition would otherwise
1812 // derive against. Pins the pre-lift `.clone().unwrap_or_else(
1813 // || default_receipt_config_map_name(...))` semantics — the
1814 // Some arm never touches the fallback composer.
1815 assert_eq!(
1816 resolve_receipt_config_map_name(Some("custom-cm"), "my-job"),
1817 "custom-cm",
1818 );
1819 assert_eq!(
1820 resolve_receipt_config_map_name(Some("op-supplied-name"), "unrelated-job"),
1821 "op-supplied-name",
1822 );
1823 }
1824
1825 #[test]
1826 fn resolve_receipt_config_map_name_falls_back_to_default_composer_on_none() {
1827 // The None arm delegates to the substrate composer verbatim —
1828 // the wire-name that lands here is byte-identical to what the
1829 // sibling `default_receipt_config_map_name(<job>)` produces at
1830 // the same Job name. Pins the pre-lift `.unwrap_or_else(||
1831 // default_receipt_config_map_name(&<job>))` fallback path.
1832 for job_name in [
1833 "my-job",
1834 "closed-loop-attest-closed-loop-probe",
1835 "svc-abc-job-42",
1836 ] {
1837 assert_eq!(
1838 resolve_receipt_config_map_name(None, job_name),
1839 default_receipt_config_map_name(job_name),
1840 "resolve_receipt_config_map_name(None, {job_name:?}) must byte-match \
1841 default_receipt_config_map_name({job_name:?}) — the None arm's fallback \
1842 routing off the substrate composer drifted",
1843 );
1844 }
1845 }
1846
1847 #[test]
1848 fn resolve_receipt_config_map_name_preserves_empty_override_bytewise() {
1849 // The `.clone().unwrap_or_else(...)` chain pre-lift returned
1850 // the empty string verbatim when the operator supplied
1851 // `receiptConfigMap: ""` — an empty Some, not None. Pin that
1852 // the substrate primitive matches: the empty-string corner
1853 // routes through the Some arm, not the None fallback, so the
1854 // operator-visible misconfiguration surfaces downstream at
1855 // the postcondition evaluator's fetch site (as an
1856 // `Unsatisfied` diagnostic) rather than being silently
1857 // reshaped into the derived-default name.
1858 assert_eq!(resolve_receipt_config_map_name(Some(""), "my-job"), "");
1859 }
1860
1861 #[test]
1862 fn resolve_receipt_config_map_name_matches_pre_lift_boundary_chain_shape() {
1863 // Byte-shape parity pin — for every combination of (override,
1864 // job_name) that the two pre-lift boundary.rs sites could
1865 // have fed the `.clone().unwrap_or_else(||
1866 // default_receipt_config_map_name(&<job>))` chain, the post-
1867 // lift substrate primitive produces the same String. A
1868 // regression that reshaped either arm (a stray `.trim()`, an
1869 // implicit `String::new()` on an empty Some, a swap of the
1870 // second-argument's borrow form) surfaces HERE at the
1871 // reconstructed pre-lift chain, not at the shipped evaluator.
1872 let cases: &[(Option<&str>, &str)] = &[
1873 (None, "job-a"),
1874 (Some("override-cm"), "job-b"),
1875 (Some(""), "job-c"),
1876 (None, ""),
1877 (Some("custom"), ""),
1878 ];
1879 for (override_name, job_name) in cases {
1880 let via_substrate = resolve_receipt_config_map_name(*override_name, job_name);
1881 let pre_lift = override_name
1882 .map(str::to_string)
1883 .unwrap_or_else(|| default_receipt_config_map_name(job_name));
1884 assert_eq!(
1885 via_substrate, pre_lift,
1886 "resolve_receipt_config_map_name({override_name:?}, {job_name:?}) \
1887 drifted from the pre-lift `.clone().unwrap_or_else(|| \
1888 default_receipt_config_map_name(&<job>))` chain shape",
1889 );
1890 }
1891 }
1892
1893 // ── RECEIPT_JSON_KEY / RECEIPT_YAML_KEY / RECEIPT_CM_KEYS /
1894 // RECEIPT_CM_MISSING_KEY_MSG / extract_receipt_payload_json ─────
1895 //
1896 // Fail-before-pass-after pins for the substrate-level (primary,
1897 // fallback) receipt-CM `data`-key pair AND the reader-side lookup
1898 // gate composer that every receipt-CM consumer routes through.
1899 // A regression that renamed either key OR that swapped the
1900 // primary/fallback ordering at the reader gate would silently
1901 // desynchronize writer/reader pairs across the workspace — the
1902 // pins here catch the drift at the primitives themselves, before
1903 // it reaches any downstream ConfigMap-fetch site.
1904 //
1905 // Pre-lift the two keys appeared as inline `&'static str` literals
1906 // at FOUR production sites (2 writer inserts + 2 reader lookups)
1907 // with no shared owner binding their spelling OR the primary-first
1908 // ordering that the reader-side gate encodes as a load-bearing
1909 // invariant.
1910
1911 #[test]
1912 fn receipt_cm_keys_pinned_to_wire_form_literals() {
1913 // Byte-exact wire-format pin — renaming either is a wire-name
1914 // change, not a typed-internal refactor. Operators grep for
1915 // these keys in kubectl output; the closed-loop-probe chart
1916 // publishes ConfigMaps carrying them; the reconciler's
1917 // JobAttested/ClosedLoopAuth evaluators gate on them. A silent
1918 // rename here would desync every writer/reader pair fleet-wide.
1919 assert_eq!(RECEIPT_JSON_KEY, "receipt.json");
1920 assert_eq!(RECEIPT_YAML_KEY, "receipt.yaml");
1921 }
1922
1923 #[test]
1924 fn receipt_cm_keys_table_pins_primary_first_ordering() {
1925 // The primary/fallback ordering is load-bearing — the reader
1926 // gate returns the FIRST hit, so JSON must precede YAML to
1927 // preserve the substrate's "JSON is machine-canonical, YAML
1928 // is operator-facing readable twin" contract. A regression
1929 // that reordered the table would silently promote YAML over
1930 // JSON — the payload STILL parses (both wire forms round-trip
1931 // through the same `ReceiptEnvelope::parse_either`), but the
1932 // reader now prefers the operator-facing form when both are
1933 // present, breaking the substrate's payload-form preference.
1934 assert_eq!(RECEIPT_CM_KEYS, [RECEIPT_JSON_KEY, RECEIPT_YAML_KEY]);
1935 assert_eq!(RECEIPT_CM_KEYS[0], RECEIPT_JSON_KEY);
1936 assert_eq!(RECEIPT_CM_KEYS[1], RECEIPT_YAML_KEY);
1937 assert_eq!(RECEIPT_CM_KEYS.len(), 2);
1938 }
1939
1940 #[test]
1941 fn receipt_cm_missing_key_msg_names_both_keys_in_primary_first_order() {
1942 // The diagnostic message the reader-side gate returns when
1943 // neither key is present must NAME both keys so the operator
1944 // reading a `ReceiptVerdict::Malformed(...)` event knows
1945 // exactly which `data.<key>` entries the reader looked up.
1946 // Pin the message contains BOTH key literals (a rename at
1947 // either key const would drift the message spelling silently
1948 // if the message were `format!`-composed at the callsite;
1949 // the substrate owns the message const alongside the two key
1950 // consts so a coordinated update lands here).
1951 assert!(
1952 RECEIPT_CM_MISSING_KEY_MSG.contains(RECEIPT_JSON_KEY),
1953 "missing-key diagnostic must name {RECEIPT_JSON_KEY}",
1954 );
1955 assert!(
1956 RECEIPT_CM_MISSING_KEY_MSG.contains(RECEIPT_YAML_KEY),
1957 "missing-key diagnostic must name {RECEIPT_YAML_KEY}",
1958 );
1959 // Primary before fallback in the diagnostic text — the
1960 // operator's mental model matches the reader's iteration order.
1961 let json_pos = RECEIPT_CM_MISSING_KEY_MSG
1962 .find(RECEIPT_JSON_KEY)
1963 .expect("json key present");
1964 let yaml_pos = RECEIPT_CM_MISSING_KEY_MSG
1965 .find(RECEIPT_YAML_KEY)
1966 .expect("yaml key present");
1967 assert!(
1968 json_pos < yaml_pos,
1969 "diagnostic must name {RECEIPT_JSON_KEY} before {RECEIPT_YAML_KEY}",
1970 );
1971 }
1972
1973 #[test]
1974 fn extract_receipt_payload_json_returns_none_when_data_absent() {
1975 // The reader-side gate handles the `data` map's own absence
1976 // gracefully — `obj.data.get("data")` returns `None` when the
1977 // ConfigMap carries no `data` map, and the gate must project
1978 // that to `None` rather than panic or return a spurious hit.
1979 assert_eq!(extract_receipt_payload_json(None), None);
1980 }
1981
1982 #[test]
1983 fn extract_receipt_payload_json_returns_none_when_neither_key_present() {
1984 // A ConfigMap with `data` but no receipt payload — the gate
1985 // returns `None` so the caller can project to the typed
1986 // `ReceiptVerdict::Malformed(RECEIPT_CM_MISSING_KEY_MSG)`.
1987 let data = serde_json::json!({ "unrelated.key": "value" });
1988 assert_eq!(extract_receipt_payload_json(Some(&data)), None);
1989 }
1990
1991 #[test]
1992 fn extract_receipt_payload_json_prefers_primary_over_fallback_when_both_present() {
1993 // Load-bearing primary-first invariant — when BOTH keys are
1994 // present (the normal writer emit shape), the reader must
1995 // return the JSON form. A regression that swapped the
1996 // iteration order would silently promote YAML over JSON with
1997 // NO observable failure at parse time (both round-trip through
1998 // `parse_either`), so the pin here catches the ordering drift
1999 // at the reader gate itself.
2000 let data = serde_json::json!({
2001 RECEIPT_JSON_KEY: "json-payload",
2002 RECEIPT_YAML_KEY: "yaml-payload",
2003 });
2004 assert_eq!(
2005 extract_receipt_payload_json(Some(&data)),
2006 Some("json-payload"),
2007 "reader must prefer {RECEIPT_JSON_KEY} over {RECEIPT_YAML_KEY} when both present",
2008 );
2009 }
2010
2011 #[test]
2012 fn extract_receipt_payload_json_falls_back_to_yaml_when_json_absent() {
2013 // Fallback arm — an older probe binary or a hand-authored
2014 // fixture that only wrote the YAML form still reads
2015 // successfully. Pins that the YAML entry is reachable through
2016 // the gate.
2017 let data = serde_json::json!({
2018 RECEIPT_YAML_KEY: "yaml-payload",
2019 });
2020 assert_eq!(
2021 extract_receipt_payload_json(Some(&data)),
2022 Some("yaml-payload"),
2023 );
2024 }
2025
2026 #[test]
2027 fn extract_receipt_payload_json_returns_first_key_when_only_primary_present() {
2028 // Primary-only arm — the writer emitted just the JSON form
2029 // (e.g. a future probe that dropped the YAML twin). Reader
2030 // still resolves the payload through the primary key.
2031 let data = serde_json::json!({
2032 RECEIPT_JSON_KEY: "json-payload",
2033 });
2034 assert_eq!(
2035 extract_receipt_payload_json(Some(&data)),
2036 Some("json-payload"),
2037 );
2038 }
2039
2040 #[test]
2041 fn extract_receipt_payload_json_rejects_non_string_scalar_values() {
2042 // The wire contract says receipt payload values are string
2043 // scalars — a JSON number, object, or array at either key is
2044 // NOT a valid payload. The gate returns `None` (the caller
2045 // then projects to a `Malformed` verdict) rather than a
2046 // spurious hit that would panic downstream in the parser.
2047 let data = serde_json::json!({
2048 RECEIPT_JSON_KEY: 42,
2049 RECEIPT_YAML_KEY: ["not", "a", "string"],
2050 });
2051 assert_eq!(extract_receipt_payload_json(Some(&data)), None);
2052 }
2053
2054 #[test]
2055 fn extract_receipt_payload_json_skips_non_string_primary_and_falls_back_to_string_fallback() {
2056 // Mixed case — the primary key exists but carries a non-string
2057 // value (a malformed writer, a partially-migrated wire form),
2058 // and the fallback key carries a valid string payload. The
2059 // gate treats the non-string primary as absent for the
2060 // string-scalar projection contract and returns the string
2061 // fallback. This preserves availability at the reader when a
2062 // writer half-populated the primary.
2063 let data = serde_json::json!({
2064 RECEIPT_JSON_KEY: { "nested": "object" },
2065 RECEIPT_YAML_KEY: "yaml-payload",
2066 });
2067 assert_eq!(
2068 extract_receipt_payload_json(Some(&data)),
2069 Some("yaml-payload"),
2070 );
2071 }
2072
2073 #[test]
2074 fn extract_receipt_payload_json_matches_hand_authored_pre_lift_chain_bytewise() {
2075 // Byte-identity pin against the pre-lift 3-link combinator
2076 // chain that `verify_receipt_cm` composed inline:
2077 // data.and_then(|d| d.get(RECEIPT_JSON_KEY))
2078 // .or_else(|| data.and_then(|d| d.get(RECEIPT_YAML_KEY)))
2079 // .and_then(|v| v.as_str())
2080 // Sweeps the four (primary-present × fallback-present)
2081 // combinations so a regression at the primitive that broke
2082 // the byte identity with the pre-lift shape surfaces here
2083 // rather than as a subtle divergence at ONE quadrant.
2084 for (json_val, yaml_val) in [
2085 (Some("json"), Some("yaml")),
2086 (Some("json"), None::<&str>),
2087 (None::<&str>, Some("yaml")),
2088 (None::<&str>, None::<&str>),
2089 ] {
2090 let mut map = serde_json::Map::new();
2091 if let Some(j) = json_val {
2092 map.insert(RECEIPT_JSON_KEY.into(), serde_json::Value::String(j.into()));
2093 }
2094 if let Some(y) = yaml_val {
2095 map.insert(RECEIPT_YAML_KEY.into(), serde_json::Value::String(y.into()));
2096 }
2097 let data = serde_json::Value::Object(map);
2098 let via_primitive = extract_receipt_payload_json(Some(&data));
2099 let via_pre_lift_chain = data
2100 .get(RECEIPT_JSON_KEY)
2101 .or_else(|| data.get(RECEIPT_YAML_KEY))
2102 .and_then(serde_json::Value::as_str);
2103 assert_eq!(
2104 via_primitive, via_pre_lift_chain,
2105 "extract_receipt_payload_json diverged from pre-lift chain at \
2106 (json={json_val:?}, yaml={yaml_val:?})",
2107 );
2108 }
2109 }
2110
2111 #[test]
2112 fn default_receipt_config_map_name_matches_prior_hand_authored_format_shape() {
2113 // Path-uniformity pin against the three pre-lift `format!`
2114 // literals — each callsite spelled the shape a slightly
2115 // different way (`format!("{}-receipt", parsed.name)` /
2116 // `format!("{job_name}-receipt")` /
2117 // `format!("{process_name}-export-{index}-receipt")`) but
2118 // all three composed the SAME `<job>-receipt` byte sequence
2119 // once evaluated. The lift preserves that byte identity so
2120 // no downstream ConfigMap grep or fleet-shipped operator
2121 // override changes meaning. A regression at the primitive
2122 // that broke the byte identity (e.g. inserted a separator,
2123 // uppercased the suffix, dropped the leading dash) would
2124 // fail HERE against the pre-lift `format!` literal for a
2125 // hand-picked Job-name that carries no ambiguity around
2126 // separators.
2127 let job_name = "svc-abc-export-3";
2128 let pre_lift = format!("{job_name}-receipt");
2129 let post_lift = default_receipt_config_map_name(job_name);
2130 assert_eq!(
2131 pre_lift, post_lift,
2132 "post-lift primitive drifted from pre-lift `format!(\"{{name}}-receipt\")` byte shape",
2133 );
2134 }
2135}