Skip to main content

tatara_process/
status.rs

1//! `ProcessStatus` sub-structures — conditions, checked boundaries, Flux refs.
2
3use chrono::{DateTime, Utc};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7
8use crate::boundary::Condition;
9use crate::crd::Process;
10use crate::json_object::ValueGetExt;
11use crate::k8s_condition::K8sConditionStatus;
12
13/// Standard K8s Condition (shape of `metav1.Condition`).
14#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
15#[serde(rename_all = "camelCase")]
16pub struct ProcessCondition {
17    #[serde(rename = "type")]
18    pub type_: String,
19    pub status: String,
20    pub last_transition_time: DateTime<Utc>,
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub reason: Option<String>,
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub message: Option<String>,
25}
26
27impl ProcessCondition {
28    pub fn ready(reason: impl Into<String>, message: Option<String>) -> Self {
29        Self {
30            type_: "Ready".into(),
31            status: K8sConditionStatus::True.as_wire_str().into(),
32            last_transition_time: Utc::now(),
33            reason: Some(reason.into()),
34            message,
35        }
36    }
37
38    pub fn not_ready(reason: impl Into<String>, message: impl Into<String>) -> Self {
39        Self {
40            type_: "Ready".into(),
41            status: K8sConditionStatus::False.as_wire_str().into(),
42            last_transition_time: Utc::now(),
43            reason: Some(reason.into()),
44            message: Some(message.into()),
45        }
46    }
47
48    pub fn attested(root: &str) -> Self {
49        Self {
50            type_: "Attested".into(),
51            status: K8sConditionStatus::True.as_wire_str().into(),
52            last_transition_time: Utc::now(),
53            reason: Some("AttestationWritten".into()),
54            message: Some(format!("composed_root={root}")),
55        }
56    }
57}
58
59/// Reference to a FluxCD resource emitted as part of this Process.
60#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
61#[serde(rename_all = "camelCase")]
62pub struct FluxResourceRef {
63    pub api_version: String,
64    pub kind: String,
65    pub name: String,
66    pub namespace: String,
67    #[serde(default)]
68    pub ready: bool,
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub message: Option<String>,
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub last_check: Option<DateTime<Utc>>,
73}
74
75impl FluxResourceRef {
76    /// Pure typed projection of the four fetch coordinates
77    /// `(namespace, api_version, kind, name)` every consumer that
78    /// dispatches this persisted reference through kube-rs's dynamic-
79    /// object surface splats by hand pre-lift. The 4-tuple binds the
80    /// slot order at ONE typed accessor so a copy-paste at any downstream
81    /// consumer cannot swap two adjacent `&str` slots in the fetch call.
82    ///
83    /// Peer projection to
84    /// [`crate::k8s_wire_identity::K8sWireIdentity`] on the static-
85    /// identity axis: [`K8sWireIdentity`] carries a
86    /// `(&'static str, &'static str)` closed-set variant's pair for
87    /// emit-time (RENDER phase) composition; this method carries the
88    /// full `(ns, apiVersion, kind, name)` 4-slot borrow for fetch-time
89    /// (VERIFY / ATTEST-heartbeat) composition where the ref's payload
90    /// comes back off the persisted `ProcessStatus.flux_resources`
91    /// slice with owned `String`s rather than static literals. The two
92    /// primitives partition the fetch axis by whether the caller starts
93    /// from a closed-set variant (emit-time) or a persisted status
94    /// slice (fetch-time).
95    ///
96    /// Pre-lift the 5-slot `ssapply::fetch(client, &r.namespace,
97    /// &r.api_version, &r.kind, &r.name)` splat was hand-authored at
98    /// TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold
99    /// in `tatara-reconciler::phase_machine`:
100    /// * `handle_running` — the VERIFY-phase per-ref readiness probe
101    ///   that populates the updated `FluxResourceRef` slice with
102    ///   `ready` + `message` + `last_check`.
103    /// * `handle_attested` — the ATTEST-heartbeat drift detector that
104    ///   short-circuits on the first non-Ready ref.
105    ///
106    /// Both sites splatted the SAME four `&r.X` field borrows in the
107    /// SAME order into raw `ssapply::fetch`. A copy-paste that swapped
108    /// two adjacent `&str` slots (`&r.api_version` and `&r.kind` are
109    /// both strings that look interchangeable to a mechanical
110    /// substitution) would silently 404 at wire time and diagnose as a
111    /// broken CRD rather than as slot skew at the callsite. Post-lift
112    /// each site names the ref ONCE and unpacks it through this ONE
113    /// projection; the slot order binds structurally at the tuple
114    /// return so a caller cannot desync one axis.
115    ///
116    /// A future addition (a case-fold normalization on the group, a
117    /// virtual-cluster prefix rewrite for multi-tenancy, a
118    /// `generateName` fallback on the name slot, a cluster-cache
119    /// short-circuit inserted between the projection and the fetch
120    /// call) lands at this ONE method and every downstream fetch
121    /// consumer inherits the upgrade mechanically — no per-site edit
122    /// at `handle_running` / `handle_attested` / any future kenshi-
123    /// runner / mirror-audit / drift-probe consumer that grows a third
124    /// consumer.
125    ///
126    /// Return-order pin lives at
127    /// [`tests::flux_resource_ref_fetch_coords_binds_slots_by_position`]
128    /// so a regression that swapped `namespace` and `api_version`
129    /// (both `String`, same type) inside the tuple constructor fails-
130    /// loudly here rather than as a silent wire-time 404 at every
131    /// downstream fetch consumer.
132    ///
133    /// Theory grounding: THEORY.md §II.1 invariant 5 (composition
134    /// preserves proofs — the 4-tuple slot order binds at ONE typed
135    /// projection so a regression across the two fields of the same
136    /// `String` type fails at the projection's positional pin rather
137    /// than at every downstream fetch consumer). THEORY.md §VI.1
138    /// (generation over composition — the 5-slot splat recurred at
139    /// two hand-authored sites past the ≥ 2 duplication trigger, and
140    /// is lifted to ONE typed borrow-projection here).
141    pub fn fetch_coords(&self) -> (&str, &str, &str, &str) {
142        (&self.namespace, &self.api_version, &self.kind, &self.name)
143    }
144
145    /// Compose a `FluxResourceRef` stamped at "observed now" — the
146    /// `last_check` slot is set to `Some(Utc::now())` at ONE substrate
147    /// owner, and the four coordinate slots + `ready` + `message`
148    /// are bound positionally so a slot-swap regression surfaces at
149    /// the constructor's positional pin rather than as silent drift
150    /// at every downstream `ProcessStatus.flux_resources` writer.
151    ///
152    /// Pre-lift the 7-slot `FluxResourceRef { …, last_check:
153    /// Some(chrono::Utc::now()) }` struct-literal was hand-authored
154    /// at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
155    /// threshold in `tatara-reconciler::phase_machine`:
156    /// * `handle_running` — the VERIFY-phase per-ref rebuild that
157    ///   restamps each polled ref with fresh `ready` + `message` +
158    ///   `last_check`.
159    /// * `flux_ref_from_json` — the post-SSA initial-state seeder
160    ///   that stamps a freshly-applied ref as `ready = false`,
161    ///   `message = Some("applied; awaiting reconciliation")`,
162    ///   `last_check = Some(Utc::now())`.
163    ///
164    /// Both sites restated the SAME seven field bindings in the
165    /// SAME order, and both restated the SAME `Some(chrono::Utc::
166    /// now())` stamp. A copy-paste that swapped two adjacent
167    /// `String` slots (`api_version` and `kind`, `kind` and `name`,
168    /// or `name` and `namespace` are all mechanically
169    /// indistinguishable at the type level) would silently persist
170    /// a slot-inverted ref that the downstream Flux fetch consumer
171    /// (via [`Self::fetch_coords`]) would then 404 on. Post-lift
172    /// both sites name the six inputs ONCE and route through this
173    /// ONE composer; the seventh slot (`last_check`) is stamped at
174    /// the composer's body so a future injection point (a fake
175    /// clock for testing, a monotonic-clock cross-check, a per-
176    /// fleet skew tolerance) lands at ONE substrate site rather
177    /// than at every hand-authored `Some(chrono::Utc::now())` stamp.
178    ///
179    /// Return-order pin lives at
180    /// [`tests::flux_resource_ref_observed_binds_slots_by_position`]
181    /// so a regression that swapped `api_version` and `kind` (both
182    /// `String`, same type) inside the constructor's argument list
183    /// fails-loudly here rather than as a silent wire-time 404 at
184    /// every downstream fetch consumer.
185    ///
186    /// Theory grounding: THEORY.md §II.1 invariant 5 (composition
187    /// preserves proofs — the 6-slot positional binding + the
188    /// `last_check` stamp compose at ONE typed owner, so a
189    /// regression across the four `String` coordinate slots fails
190    /// at the composer's positional pin rather than at every
191    /// downstream Flux status writer). THEORY.md §VI.1 (generation
192    /// over composition — the 7-slot struct-literal recurred at two
193    /// hand-authored sites past the ≥ 2 duplication trigger, and is
194    /// lifted to ONE typed composer here).
195    pub fn observed(
196        api_version: String,
197        kind: String,
198        name: String,
199        namespace: String,
200        ready: bool,
201        message: Option<String>,
202    ) -> Self {
203        Self {
204            api_version,
205            kind,
206            name,
207            namespace,
208            ready,
209            message,
210            last_check: Some(Utc::now()),
211        }
212    }
213
214    /// Compose a `FluxResourceRef` in the pre-observation shape — the
215    /// 4-slot coordinate binding with the three status slots defaulted
216    /// (`ready: false`, `message: None`, `last_check: None`). The
217    /// deterministic-fixture peer of [`Self::observed`] on the same
218    /// `→ FluxResourceRef` composer axis: `observed` reads the wall
219    /// clock and takes 6 args (a live post-fetch stamp), `pending`
220    /// reads no clock and takes 4 args (a pre-observation fixture
221    /// seed, and the natural base for `..base.clone()` spread updates
222    /// that vary a single slot for a per-corner test sweep).
223    ///
224    /// Pre-lift the SAME 7-slot `FluxResourceRef { api_version, kind,
225    /// name, namespace, ready: false, message: None, last_check: None
226    /// }` struct-literal was hand-authored at THREE workspace-wide
227    /// fixture sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
228    /// threshold:
229    ///
230    /// * [`crate::crd`]
231    ///   `crd::observed_flux_resources_tests::sample_flux_ref(name)`
232    ///   — the shared `Kustomization`/`flux-system` fixture the
233    ///   `Process::observed_flux_resources` pin family destructures
234    ///   for its `flux_resources`-populated corners.
235    /// * `tatara-reconciler::ssapply::tests::sample_flux_ref_for_diag`
236    ///   — the `HelmRelease`/`flux-system` fixture the
237    ///   `flux_ref_fetch_error_context` diagnostic-wording pin
238    ///   family destructures for its (kind, name) slot-coverage
239    ///   sweep.
240    /// * `tatara-reconciler::ssapply::tests::
241    ///   flux_ref_fetch_error_context_matches_pre_lift_hand_authored_wording`
242    ///   — the inline 7-slot literal inside the cross-substrate
243    ///   coherence pin's per-case sweep over three distinct
244    ///   `(api_version, kind, name, namespace)` tuples.
245    ///
246    /// All THREE sites restated the SAME seven field bindings in the
247    /// SAME order and the SAME three defaulted status slots (`ready:
248    /// false, message: None, last_check: None`), differing only in
249    /// the four coordinate `String` values. Post-lift each callsite
250    /// reads `FluxResourceRef::pending(<api_version>, <kind>, <name>,
251    /// <namespace>)` and the four-slot bind + three-slot default
252    /// sinks live at ONE substrate owner.
253    ///
254    /// The `impl Into<String>` signature accepts BOTH `&'static str`
255    /// (the fixture-helper sites that spell coordinate literals
256    /// inline) AND owned `String` (a future callsite handing off a
257    /// dynamically-derived coordinate) without widening. Matches the
258    /// discipline of the sibling substrate composers
259    /// [`crate::pool::PoolMember::unallocated`] +
260    /// [`crate::allocation::AllocationRef::new`] on the identity-slot
261    /// axis.
262    ///
263    /// A future normalization (a case-fold on the group, a
264    /// virtual-cluster prefix rewrite for multi-tenancy, a stricter
265    /// kind gate, a `generateName` fallback on the name slot, a
266    /// canonical rename of one of the three defaulted status slots
267    /// to a typed `PreObservation` marker) lands at THIS ONE
268    /// substrate primitive and every downstream fixture / helper
269    /// inherits the upgrade mechanically — no per-site edit at any
270    /// of the THREE listed callers or at future consumers (a
271    /// stable-name claim-arbiter's pending-ref seed, a kenshi-runner
272    /// pre-observation fixture, a mirror-audit drift-probe test
273    /// helper).
274    ///
275    /// Theory grounding: THEORY.md §II.1 invariant 5 (composition
276    /// preserves proofs — the 4-slot positional binding + the three
277    /// defaulted status slots compose at ONE typed owner, so a
278    /// regression across the four `String` coordinate slots fails at
279    /// the composer's positional pin rather than at every downstream
280    /// fixture consumer). THEORY.md §VI.1 (generation over
281    /// composition — the 7-slot struct-literal recurred at three
282    /// hand-authored fixture sites past the ≥ 2 duplication trigger,
283    /// and is lifted to ONE typed composer here).
284    #[must_use]
285    pub fn pending(
286        api_version: impl Into<String>,
287        kind: impl Into<String>,
288        name: impl Into<String>,
289        namespace: impl Into<String>,
290    ) -> Self {
291        Self {
292            api_version: api_version.into(),
293            kind: kind.into(),
294            name: name.into(),
295            namespace: namespace.into(),
296            ready: false,
297            message: None,
298            last_check: None,
299        }
300    }
301}
302
303/// Identifying coordinates of a rendered K8s resource — the
304/// `(apiVersion, kind, metadata.name, metadata.namespace)` 4-tuple
305/// every consumer that walks a rendered `serde_json::Value` resource
306/// unwraps by hand pre-lift.
307///
308/// The three K8s API-path segments (`apiVersion`, `kind`,
309/// `metadata.name`) are REQUIRED — a rendered resource missing any
310/// of them cannot be applied via kube-rs's dynamic API surface, so
311/// the extraction fails fast at the boundary rather than as a
312/// downstream `Api::patch` panic. `metadata.namespace` is
313/// intentionally kept as `Option<String>` because different consumers
314/// resolve the fallback differently: `apply_owned` uses the
315/// caller-supplied `namespace: &str` argument (the reconciler already
316/// resolved the target namespace upstream), while `flux_ref_from_json`
317/// records the K8s canonical `"default"` fallback into the persisted
318/// `FluxResourceRef.namespace` slot. The peer method
319/// [`Self::namespace_or_default`] applies the K8s canonical fallback
320/// (`Process::DEFAULT_NAMESPACE = "default"`) for consumers wanting
321/// the same shape [`FluxResourceRef.namespace`] carries.
322///
323/// Pre-lift the 3+1 slot extraction was hand-authored at TWO sites
324/// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold across
325/// `tatara-reconciler`:
326/// * `tatara-reconciler::phase_machine::flux_ref_from_json` — the
327///   post-SSA `FluxResourceRef` builder that persists into
328///   `ProcessStatus.flux_resources`; namespace half fallback-
329///   defaulted to `"default"`.
330/// * `tatara-reconciler::ssapply::apply_owned` — the SSA entry
331///   point that extracts (apiVersion, kind, name) for the
332///   [`kube::Api::patch`] call; namespace half discarded (the
333///   `namespace: &str` argument comes from the caller upstream).
334///
335/// Both callsites restated the same three
336/// `.get(K).and_then(|v| v.as_str()).ok_or_else(|| anyhow!(...))?
337/// .to_string()` incantations with subtly different error wording
338/// (`"resource missing X"` vs `"rendered resource missing X"`); post-
339/// lift both route through this ONE substrate owner with the
340/// canonical `"rendered resource missing X"` wording. A future
341/// addition (case-fold on the group, a rename of the namespace
342/// fallback, a stricter kind gate, a Unicode-safe collation step,
343/// support for `metadata.generateName` as a name fallback) lands at
344/// the primitive's body on the substrate, not at 2 independent
345/// hand-writes across 2 reconciler files.
346///
347/// Namespace fallback const is shared with
348/// [`Process::DEFAULT_NAMESPACE`] — a rename of the K8s canonical
349/// default namespace lands at that ONE workspace-wide const, not at
350/// per-primitive local literals that would drift silently.
351#[derive(Clone, Debug, PartialEq, Eq)]
352pub struct RenderedResourceCoords {
353    /// `apiVersion` — the group+version pair kube-rs uses to resolve
354    /// the `ApiResource` for the SSA call.
355    pub api_version: String,
356    /// `kind` — the resource kind (Kustomization, HelmRelease, …).
357    pub kind: String,
358    /// `metadata.name` — the API-path leaf segment.
359    pub name: String,
360    /// `metadata.namespace` — raw from the resource, `None` when the
361    /// slot is absent (a cluster-scoped resource, or a namespaced
362    /// resource whose namespace was left for the API server to
363    /// substitute). Consumers apply their own fallback:
364    /// [`Self::namespace_or_default`] applies the K8s canonical
365    /// `"default"` (matching what [`FluxResourceRef.namespace`]
366    /// records); other consumers substitute a caller-supplied string
367    /// (see `tatara-reconciler::ssapply::apply_owned`).
368    pub namespace: Option<String>,
369}
370
371impl RenderedResourceCoords {
372    /// Extract the 4-tuple from a rendered K8s resource JSON `Value`.
373    ///
374    /// Fails with a canonical `"rendered resource missing X"` message
375    /// when any of the three required slots (`apiVersion`, `kind`,
376    /// `metadata.name`) is absent or non-string; `metadata.namespace`
377    /// is optional and captured as `None` when absent.
378    ///
379    /// The error wording is pinned by
380    /// [`tests::rendered_resource_coords_error_wording_is_canonical`]
381    /// so a regression that reshaped the message surfaces at the test
382    /// surface rather than as silent drift between the two pre-lift
383    /// call sites (which used subtly different wording — `"resource
384    /// missing X"` in `apply_owned` vs `"rendered resource missing
385    /// X"` in `flux_ref_from_json`).
386    pub fn from_json(res: &Value) -> anyhow::Result<Self> {
387        // The three REQUIRED-slot extracts (`apiVersion`, `kind`,
388        // `metadata.name`) route through the ONE substrate primitive
389        // `Self::required_str` — the required-extract sibling of
390        // `crate::json_object::ValueGetExt::get_str` on the same
391        // rendered-resource axis. A future normalization (Unicode
392        // NFC-fold, whitespace trim, empty-string rejection) lands
393        // at the primitive body and every downstream consumer of the
394        // canonical `"rendered resource missing X"` wire form inherits
395        // it mechanically. The optional `metadata.namespace` slot
396        // continues to route through the pre-existing `get_str` READ
397        // primitive since its absent-arm is `None`, not an error.
398        let api_version = Self::required_str(Some(res), "apiVersion", "apiVersion")?;
399        let kind = Self::required_str(Some(res), "kind", "kind")?;
400        let metadata = res.get("metadata");
401        let name = Self::required_str(metadata, "name", "metadata.name")?;
402        let namespace = metadata
403            .and_then(|m| m.get_str("namespace"))
404            .map(str::to_string);
405        Ok(Self {
406            api_version,
407            kind,
408            name,
409            namespace,
410        })
411    }
412
413    /// Diagnostic prefix stamped ahead of every required-slot label in
414    /// the canonical error wire form. Owned in ONE workspace-wide place
415    /// so a rename (a fleet-wide switch to `"resource is missing"` /
416    /// `"missing rendered-resource field"`) lands here and every
417    /// downstream `.to_string()`-consumer + operator-facing log grep
418    /// inherits the rename mechanically, not at 3 hand-authored
419    /// `anyhow!(…)` restatements.
420    pub const MISSING_MESSAGE_PREFIX: &'static str = "rendered resource missing";
421
422    /// Required-slot extract on a rendered-resource JSON `Value` — the
423    /// substrate owner of the paired `.get_str(<key>).ok_or_else(||
424    /// anyhow!("rendered resource missing <slot>"))?.to_string()`
425    /// four-link chain every REQUIRED slot on a rendered `Value`
426    /// walks pre-lift.
427    ///
428    /// The primitive accepts an `Option<&Value>` receiver so BOTH
429    /// shallow reads (top-level `apiVersion` / `kind` on the resource
430    /// root, callers thread `Some(res)`) AND one-level-nested reads
431    /// (`metadata.name` walking through `res.get("metadata")`,
432    /// callers thread the `Option<&Value>` handle the `.get()` step
433    /// returns) reach the same owner. The `key` slot is the wire-form
434    /// name the underlying [`ValueGetExt::get_str`] looks up on the
435    /// object; the `error_slot` slot is the diagnostic label stamped
436    /// into the error's `Display` output. The two are decoupled so
437    /// `metadata.name` can look up `"name"` on the `metadata` sub-
438    /// object while reporting the dotted `"metadata.name"` path an
439    /// operator bisecting a fault sees in the log.
440    ///
441    /// Ok arm returns `String` (owned) rather than the borrowed
442    /// `&str` [`ValueGetExt::get_str`] returns — every downstream
443    /// slot on the [`RenderedResourceCoords`] struct is an owned
444    /// `String`, so the primitive absorbs the `str::to_string`
445    /// coerce that pre-lift lived at three hand-authored callsites.
446    /// Err arm carries an `anyhow::Error` whose `Display` reads
447    /// exactly `"<Self::MISSING_MESSAGE_PREFIX> <error_slot>"` —
448    /// byte-identical to the pre-lift hand-authored `anyhow!(
449    /// "rendered resource missing {slot}")` wire form.
450    ///
451    /// ### Fires on all four absent-shape corners
452    ///
453    /// The primitive returns `Err` on ALL four ways a required
454    /// slot can miss:
455    ///
456    /// 1. Receiver is `None` — the `metadata.name` corner when the
457    ///    top-level `metadata` object itself is absent (the caller
458    ///    threaded `res.get("metadata")` which returned `None`).
459    /// 2. Slot is absent — the receiver is present but does not
460    ///    carry a value at `key`.
461    /// 3. Slot is present but non-string — a fixture bug that
462    ///    stamped a JSON number / bool / object / array at the
463    ///    slot; the `get_str` step falls through and the primitive
464    ///    reports the slot as missing (matching the pre-lift
465    ///    behavior where every non-string variant surfaced as the
466    ///    same `"missing"` diagnostic — pinning "cannot be applied
467    ///    via kube-rs's dynamic API surface" as the shared
468    ///    failure mode).
469    /// 4. Receiver is non-object — a resource authored as a JSON
470    ///    array / string / null at any of the levels the primitive
471    ///    walks (the `get_str` step returns `None` verbatim).
472    ///
473    /// All four corners produce the SAME wire form so an operator's
474    /// `rg "rendered resource missing"` sweep hits exactly one
475    /// footprint per faulted slot, not four differently-worded
476    /// diagnostics per absent-shape variant.
477    ///
478    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
479    /// the 4-link `.get_str(<key>).ok_or_else(|| anyhow!("rendered
480    /// resource missing <slot>"))?.to_string()` shape recurred at 3
481    /// hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
482    /// duplication trigger, and is lifted to ONE substrate owner
483    /// here). THEORY.md §II.1 invariant 5 (composition preserves
484    /// proofs — a regression that drifted the diagnostic prefix
485    /// wording at ONE site would silently pass the two sibling
486    /// pins and fail HERE; post-lift the wire form is owned once
487    /// at [`Self::MISSING_MESSAGE_PREFIX`] and every downstream
488    /// composition inherits the rename mechanically).
489    fn required_str(
490        v: Option<&Value>,
491        key: &'static str,
492        error_slot: &'static str,
493    ) -> anyhow::Result<String> {
494        v.and_then(|x| x.get_str(key))
495            .map(str::to_string)
496            .ok_or_else(|| {
497                anyhow::anyhow!(
498                    "{prefix} {slot}",
499                    prefix = Self::MISSING_MESSAGE_PREFIX,
500                    slot = error_slot,
501                )
502            })
503    }
504
505    /// `metadata.namespace` slice with the K8s canonical `"default"`
506    /// fallback applied — matching what [`Process::DEFAULT_NAMESPACE`]
507    /// spells for the `Process`-borne coordinate primitive family
508    /// and what [`FluxResourceRef.namespace`] records into
509    /// `ProcessStatus.flux_resources`.
510    pub fn namespace_or_default(&self) -> &str {
511        self.namespace
512            .as_deref()
513            .unwrap_or(Process::DEFAULT_NAMESPACE)
514    }
515}
516
517/// A boundary condition paired with its current satisfaction state.
518#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
519#[serde(rename_all = "camelCase")]
520pub struct CheckedCondition {
521    #[serde(flatten)]
522    pub condition: Condition,
523    pub satisfied: bool,
524    #[serde(default, skip_serializing_if = "Option::is_none")]
525    pub last_check: Option<DateTime<Utc>>,
526    #[serde(default, skip_serializing_if = "Option::is_none")]
527    pub message: Option<String>,
528}
529
530impl CheckedCondition {
531    /// True iff every [`CheckedCondition`] in the slice has
532    /// `satisfied == true` — the ONE-line collapse of the paired
533    /// `checked.iter().all(|c| c.satisfied)` incantation the
534    /// reconciler's precondition + postcondition boundary gates both
535    /// spelled by hand pre-lift.
536    ///
537    /// Pre-lift the SAME `.iter().all(|c| c.satisfied)` chain was
538    /// hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
539    /// duplication threshold in `tatara-reconciler::phase_machine`,
540    /// each walking the SAME `Vec<CheckedCondition>` → `bool`
541    /// projection to gate a phase transition on a boundary predicate:
542    /// * `handle_execing` — the PROVE-phase precondition gate that
543    ///   stays in Execing (heartbeat requeue) while any precondition
544    ///   remains unsatisfied and proceeds to RENDER only when every
545    ///   precondition holds.
546    /// * `handle_running` — the VERIFY-phase postcondition gate that
547    ///   stays in Running (heartbeat requeue) while any postcondition
548    ///   remains unsatisfied and advances to Attested only when every
549    ///   postcondition holds.
550    ///
551    /// Both sites walked the SAME `Iterator::all` short-circuit on the
552    /// SAME `bool` slot of the SAME struct. Post-lift both consumers
553    /// name the slice ONCE and route through this ONE primitive; the
554    /// vacuous-truth corner (empty slice → `true`, matching
555    /// [`Iterator::all`]'s empty-input identity) sits at ONE substrate
556    /// site so a future normalization (a per-slot weight overlay, a
557    /// per-kind override that treats `Warn`-severity failures as
558    /// satisfied, a compliance-baseline gate that requires N-of-M
559    /// rather than all-of-M) lands at ONE substrate function and both
560    /// downstream phase gates inherit the upgrade mechanically.
561    ///
562    /// Return-form axis: `bool` — the exact type each phase gate
563    /// pre-lift bound at `let all_pass = <chain>;` and immediately
564    /// consumed in a `!all_pass` short-circuit + a `message` slot's
565    /// ternary branch. The `&[Self]` argument accepts every pre-lift
566    /// slice provenance verbatim: a `&Vec<CheckedCondition>` (both
567    /// pre-lift sites had the `Vec` on the stack from
568    /// [`crate::phase_machine::evaluate_conditions`]'s owned return)
569    /// coerces through auto-deref, so no callsite has to change its
570    /// upstream provenance to route through the primitive.
571    ///
572    /// Peer to the sibling projection [`Self::satisfied`] on the (row
573    /// scope × predicate) axis pair: `satisfied` is the per-row
574    /// projection; `all_satisfied` is the slice-wide fold of the same
575    /// bit. Both live on `CheckedCondition` so a future rename or
576    /// per-slot normalization travels through the same owner without
577    /// splitting between "per-row" and "slice-wide" call sinks.
578    ///
579    /// Return-shape pin lives at
580    /// [`tests::checked_condition_all_satisfied_matches_pre_lift_iter_all_chain_shape`]
581    /// so a regression that flipped the fold direction (`any` for
582    /// `all`), inverted the bit (`!c.satisfied`), or reshaped the
583    /// return form (an owned `Vec<bool>` instead of the folded `bool`)
584    /// fails-loudly here rather than as silent operator-facing skew
585    /// between the pre-lift `if !all_pass { requeue }` gate and the
586    /// post-lift call — every downstream consumer would still
587    /// short-circuit but on inverted semantics.
588    ///
589    /// Theory grounding: THEORY.md §VI.1 (generation over composition
590    /// — the 1-line `.iter().all(...)` chain recurred at two hand-
591    /// authored sites past the ≥ 2 duplication trigger, and is lifted
592    /// to ONE typed fold here). THEORY.md §II.1 invariant 5
593    /// (composition preserves proofs — the empty-slice vacuous-truth
594    /// corner + the fold direction + the projected bit's polarity all
595    /// bind at ONE substrate site, so a regression across any of the
596    /// three surfaces at [`tests::checked_condition_all_satisfied_*`]
597    /// pin rather than as silent gate-flip at every downstream phase
598    /// handler).
599    #[must_use]
600    pub fn all_satisfied(checked: &[Self]) -> bool {
601        checked.iter().all(|c| c.satisfied)
602    }
603}
604
605/// Summary of boundary verification.
606#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
607#[serde(rename_all = "camelCase")]
608pub struct BoundaryStatus {
609    #[serde(default)]
610    pub preconditions: Vec<CheckedCondition>,
611    #[serde(default)]
612    pub postconditions: Vec<CheckedCondition>,
613    /// Absolute deadline for VERIFY (derived from `spec.boundary.timeout`).
614    #[serde(default, skip_serializing_if = "Option::is_none")]
615    pub deadline: Option<DateTime<Utc>>,
616}
617
618/// Summary of compliance checks at the latest attestation.
619#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
620#[serde(rename_all = "camelCase")]
621pub struct ComplianceStatus {
622    #[serde(default, skip_serializing_if = "Option::is_none")]
623    pub baseline: Option<String>,
624    pub satisfied: u32,
625    pub violated: u32,
626    pub total: u32,
627    #[serde(default)]
628    pub violations: Vec<String>,
629}
630
631#[cfg(test)]
632mod tests {
633    use super::*;
634    use serde_json::json;
635
636    // ─── ProcessCondition writer / K8sConditionStatus substrate pins ─
637    //
638    // Byte-shape parity pins between `ProcessCondition::{ready,
639    // not_ready, attested}` writer output and the pre-lift hand-
640    // authored `"True"` / `"False"` `status` slot literals every
641    // downstream K8s API server + K8s-Condition-reading peer depends
642    // on. Post-lift the writers compose through
643    // `K8sConditionStatus::<V>.as_wire_str()`; these pins catch a
644    // regression at the substrate primitive (a lower-case drift, a
645    // whitespace prefix, a `serde(rename)` addition on the enum)
646    // that would silently reshape every emitted Process
647    // `status.conditions[]` slot away from the K8s wire form.
648
649    /// Fail-before-pass-after: `ProcessCondition::ready` emits the
650    /// exact-case ASCII `"True"` on the `status` slot the K8s API
651    /// server accepts, byte-identical to the pre-lift hand-authored
652    /// `status: "True".into()` literal. A regression at the substrate
653    /// primitive (a `to_lowercase` pass, a case-drifted variant
654    /// literal in `k8s_condition::K8sConditionStatus::as_wire_str`)
655    /// surfaces HERE, not as silent operator-facing wire-form skew
656    /// on the emitted Process CRD.
657    #[test]
658    fn ready_writer_status_slot_matches_pre_lift_true_literal_bytewise() {
659        let c = ProcessCondition::ready("ObservedRunning", Some("healthy".into()));
660        assert_eq!(c.type_, "Ready");
661        assert_eq!(c.status, "True");
662    }
663
664    /// Fail-before-pass-after: `ProcessCondition::not_ready` emits
665    /// the exact-case ASCII `"False"` on the `status` slot, byte-
666    /// identical to the pre-lift hand-authored `status: "False".
667    /// into()` literal.
668    #[test]
669    fn not_ready_writer_status_slot_matches_pre_lift_false_literal_bytewise() {
670        let c = ProcessCondition::not_ready("ObservedFailed", "boom");
671        assert_eq!(c.type_, "Ready");
672        assert_eq!(c.status, "False");
673    }
674
675    /// Fail-before-pass-after: `ProcessCondition::attested` emits
676    /// the exact-case ASCII `"True"` on the `status` slot with the
677    /// `"Attested"` type row, byte-identical to the pre-lift hand-
678    /// authored `type_: "Attested".into()` + `status: "True".into()`
679    /// pair.
680    #[test]
681    fn attested_writer_status_slot_matches_pre_lift_true_literal_bytewise() {
682        let c = ProcessCondition::attested("blake3:abc123");
683        assert_eq!(c.type_, "Attested");
684        assert_eq!(c.status, "True");
685        // Message body preserves the composed_root diagnostic
686        // wording verbatim — the substrate lift only reshaped the
687        // `status` slot, not the human-facing message.
688        assert_eq!(c.message.as_deref(), Some("composed_root=blake3:abc123"));
689        assert_eq!(c.reason.as_deref(), Some("AttestationWritten"));
690    }
691
692    /// Writer/reader wire-form parity: the `status` slot every
693    /// writer here emits is the SAME byte-shape the
694    /// `K8sConditionStatus::from_wire_str` reader in
695    /// `tatara-reconciler::ssapply::ready_condition_value` accepts.
696    /// A regression that drifted `as_wire_str` at ONE variant would
697    /// silently desynchronize every writer/reader pair in the
698    /// workspace; this pin surfaces the drift at the substrate.
699    #[test]
700    fn writer_output_round_trips_through_from_wire_str() {
701        let ready = ProcessCondition::ready("R", None);
702        assert_eq!(
703            K8sConditionStatus::from_wire_str(&ready.status),
704            Some(K8sConditionStatus::True),
705        );
706        let not_ready = ProcessCondition::not_ready("R", "why");
707        assert_eq!(
708            K8sConditionStatus::from_wire_str(&not_ready.status),
709            Some(K8sConditionStatus::False),
710        );
711        let attested = ProcessCondition::attested("blake3:zzz");
712        assert_eq!(
713            K8sConditionStatus::from_wire_str(&attested.status),
714            Some(K8sConditionStatus::True),
715        );
716    }
717
718    // ─── RenderedResourceCoords substrate pins ──────────────────────
719
720    #[test]
721    fn rendered_resource_coords_from_json_extracts_all_four_slots_when_present() {
722        let res = json!({
723            "apiVersion": "kustomize.toolkit.fluxcd.io/v1",
724            "kind": "Kustomization",
725            "metadata": {
726                "name": "observability-stack",
727                "namespace": "flux-system",
728            },
729        });
730        let c = RenderedResourceCoords::from_json(&res).expect("extract");
731        assert_eq!(c.api_version, "kustomize.toolkit.fluxcd.io/v1");
732        assert_eq!(c.kind, "Kustomization");
733        assert_eq!(c.name, "observability-stack");
734        assert_eq!(c.namespace.as_deref(), Some("flux-system"));
735    }
736
737    #[test]
738    fn rendered_resource_coords_from_json_captures_absent_namespace_as_none() {
739        // Cluster-scoped resource — `metadata.namespace` intentionally absent.
740        let res = json!({
741            "apiVersion": "v1",
742            "kind": "Namespace",
743            "metadata": {"name": "demo-test"},
744        });
745        let c = RenderedResourceCoords::from_json(&res).expect("extract");
746        assert_eq!(c.namespace, None);
747        assert_eq!(c.name, "demo-test");
748    }
749
750    #[test]
751    fn rendered_resource_coords_from_json_errors_on_missing_api_version() {
752        let res = json!({"kind": "K", "metadata": {"name": "n"}});
753        let e = RenderedResourceCoords::from_json(&res).expect_err("must error");
754        assert_eq!(e.to_string(), "rendered resource missing apiVersion");
755    }
756
757    #[test]
758    fn rendered_resource_coords_from_json_errors_on_missing_kind() {
759        let res = json!({"apiVersion": "v1", "metadata": {"name": "n"}});
760        let e = RenderedResourceCoords::from_json(&res).expect_err("must error");
761        assert_eq!(e.to_string(), "rendered resource missing kind");
762    }
763
764    #[test]
765    fn rendered_resource_coords_from_json_errors_on_missing_metadata_name() {
766        let res = json!({"apiVersion": "v1", "kind": "K", "metadata": {}});
767        let e = RenderedResourceCoords::from_json(&res).expect_err("must error");
768        assert_eq!(e.to_string(), "rendered resource missing metadata.name");
769    }
770
771    #[test]
772    fn rendered_resource_coords_from_json_errors_on_missing_metadata_object() {
773        // `metadata` absent entirely — same failure as `metadata.name` missing,
774        // because the API-path leaf segment cannot be resolved.
775        let res = json!({"apiVersion": "v1", "kind": "K"});
776        let e = RenderedResourceCoords::from_json(&res).expect_err("must error");
777        assert_eq!(e.to_string(), "rendered resource missing metadata.name");
778    }
779
780    #[test]
781    fn rendered_resource_coords_from_json_errors_on_non_string_slot() {
782        // A numeric `apiVersion` slot falls through the `.as_str()` gate and
783        // triggers the same missing-slot failure as absence — the API-path
784        // segment is not a string.
785        let res = json!({
786            "apiVersion": 42,
787            "kind": "K",
788            "metadata": {"name": "n"},
789        });
790        let e = RenderedResourceCoords::from_json(&res).expect_err("must error");
791        assert_eq!(e.to_string(), "rendered resource missing apiVersion");
792    }
793
794    #[test]
795    fn rendered_resource_coords_error_wording_is_canonical() {
796        // Pins the exact spelling every downstream consumer sees.
797        // Pre-lift wording differed across the two call sites (`"resource
798        // missing X"` in `apply_owned` vs `"rendered resource missing X"` in
799        // `flux_ref_from_json`); post-lift the canonical wording is
800        // `"rendered resource missing X"` at every site.
801        let cases = [
802            (
803                "apiVersion",
804                json!({"kind": "K", "metadata": {"name": "n"}}),
805            ),
806            (
807                "kind",
808                json!({"apiVersion": "v1", "metadata": {"name": "n"}}),
809            ),
810            (
811                "metadata.name",
812                json!({"apiVersion": "v1", "kind": "K", "metadata": {}}),
813            ),
814        ];
815        for (slot, res) in cases {
816            let e = RenderedResourceCoords::from_json(&res).expect_err("must error");
817            assert_eq!(
818                e.to_string(),
819                format!("rendered resource missing {slot}"),
820                "slot {slot} error must be canonical"
821            );
822        }
823    }
824
825    // ─── RenderedResourceCoords::required_str substrate pins ────────
826    //
827    // Fail-before-pass-after granularity: the
828    // `RenderedResourceCoords::required_str` inherent associated
829    // function did not exist before this commit, so each test below
830    // fails to compile pre-lift. Post-lift they collectively pin the
831    // required-string-extract shape at ONE substrate owner — a
832    // regression that swaps `MISSING_MESSAGE_PREFIX`, decouples the
833    // `key` / `error_slot` slot pair with a wrong ordering, drops the
834    // `str::to_string` coerce (returning `&str` and forcing every
835    // consumer to re-stamp `.to_string()` per site), or narrows the
836    // receiver from `Option<&Value>` to `&Value` (silently breaking
837    // the `metadata.name` corner where the caller threads the
838    // `res.get("metadata")` result directly) surfaces HERE rather
839    // than as silent operator-facing skew across the three pre-lift
840    // consumers on `from_json`.
841
842    #[test]
843    fn required_str_present_string_slot_returns_owned_string() {
844        // Ok-arm invariant: a present string slot at `key` on a
845        // `Some(&Value::Object)` receiver returns `Ok(<owned>)` —
846        // the primitive absorbs the `.to_string()` coerce the three
847        // pre-lift restatements each stamped at the tail.
848        let res = json!({"apiVersion": "kustomize.toolkit.fluxcd.io/v1"});
849        let got =
850            RenderedResourceCoords::required_str(Some(&res), "apiVersion", "apiVersion").unwrap();
851        assert_eq!(got, "kustomize.toolkit.fluxcd.io/v1");
852    }
853
854    #[test]
855    fn required_str_none_receiver_errors_with_canonical_wire_form() {
856        // Absent-shape corner 1: the caller threads `None`
857        // (`res.get("metadata")` returned `None` because the top-
858        // level `metadata` slot itself is absent). The primitive
859        // errors with the SAME wire form the two other absent
860        // corners produce, keeping the operator-facing footprint
861        // singular.
862        let e = RenderedResourceCoords::required_str(None, "name", "metadata.name")
863            .expect_err("None receiver must error");
864        assert_eq!(e.to_string(), "rendered resource missing metadata.name");
865    }
866
867    #[test]
868    fn required_str_absent_slot_errors_with_canonical_wire_form() {
869        // Absent-shape corner 2: the receiver is present but the
870        // slot at `key` is not stamped on it. Wire form matches
871        // the `None`-receiver corner and the non-string corner.
872        let res = json!({"kind": "K"});
873        let e = RenderedResourceCoords::required_str(Some(&res), "apiVersion", "apiVersion")
874            .expect_err("absent slot must error");
875        assert_eq!(e.to_string(), "rendered resource missing apiVersion");
876    }
877
878    #[test]
879    fn required_str_non_string_slot_errors_with_canonical_wire_form() {
880        // Absent-shape corner 3: the slot is present but stamped
881        // as a JSON number / bool / object / array — every
882        // non-`Value::String` variant falls through the underlying
883        // `get_str` gate and produces the SAME `"missing"` diagnostic.
884        // Pinning EVERY non-string variant here (not just number)
885        // guarantees an operator's error-stream grep collapses all
886        // fixture-authoring bugs at this slot onto one footprint.
887        for bad in [
888            json!({"apiVersion": 42}),
889            json!({"apiVersion": true}),
890            json!({"apiVersion": {}}),
891            json!({"apiVersion": [1]}),
892            json!({"apiVersion": null}),
893        ] {
894            let e = RenderedResourceCoords::required_str(Some(&bad), "apiVersion", "apiVersion")
895                .expect_err("non-string slot must error");
896            assert_eq!(e.to_string(), "rendered resource missing apiVersion");
897        }
898    }
899
900    #[test]
901    fn required_str_non_object_receiver_errors_with_canonical_wire_form() {
902        // Absent-shape corner 4: the receiver itself is not a
903        // `Value::Object` — a resource authored as a JSON array,
904        // string, or null at any of the levels the primitive
905        // walks. The underlying `get_str` step returns `None`
906        // verbatim (matching the pre-lift chain's own behavior)
907        // and the primitive stamps the canonical wire form.
908        for bad in [json!([1, 2, 3]), json!("stringified"), Value::Null] {
909            let e = RenderedResourceCoords::required_str(Some(&bad), "name", "metadata.name")
910                .expect_err("non-object receiver must error");
911            assert_eq!(e.to_string(), "rendered resource missing metadata.name");
912        }
913    }
914
915    #[test]
916    fn required_str_decouples_key_from_error_slot_at_metadata_name_shape() {
917        // Slot-decoupling pin: for the `metadata.name` corner the
918        // primitive looks up `key = "name"` on the metadata sub-
919        // object while stamping `error_slot = "metadata.name"` into
920        // the error's `Display` output — the two are NOT the same
921        // string, and a regression that collapsed them (using
922        // `key` for both the lookup AND the error slug, or
923        // vice-versa) would silently pass the shallow `apiVersion`
924        // / `kind` pins above (where `key == error_slot`) and fail
925        // HERE. Present-arm: lookup succeeds on the metadata sub-
926        // object's `name` slot, returns the owned string.
927        let res = json!({"metadata": {"name": "demo"}});
928        let metadata = res.get("metadata");
929        let got = RenderedResourceCoords::required_str(metadata, "name", "metadata.name").unwrap();
930        assert_eq!(got, "demo");
931        // Absent-arm: same slot-decoupling but the `name` sub-slot
932        // is absent — the error slug is the DOTTED path, not the
933        // shallow `"name"` key.
934        let res_no_name = json!({"metadata": {}});
935        let metadata_empty = res_no_name.get("metadata");
936        let e = RenderedResourceCoords::required_str(metadata_empty, "name", "metadata.name")
937            .expect_err("absent metadata.name must error");
938        assert_eq!(e.to_string(), "rendered resource missing metadata.name");
939    }
940
941    #[test]
942    fn required_str_error_wire_form_composes_missing_message_prefix_verbatim() {
943        // Wire-form composition pin: the error's `Display` is
944        // exactly `"<Self::MISSING_MESSAGE_PREFIX> <error_slot>"` —
945        // the leading prefix comes from the `const` owner + a
946        // single space + the caller-supplied slug. A regression
947        // that switched the separator (a colon, an em-dash) or
948        // dropped the prefix (returning just the slot slug) would
949        // silently invert every operator-facing log grep footprint;
950        // this pin binds the composition to the ONE prefix const
951        // so a future rename lands atomically at both the source
952        // and the pins.
953        let e = RenderedResourceCoords::required_str(None, "name", "metadata.name")
954            .expect_err("None receiver must error");
955        let expected = format!(
956            "{prefix} metadata.name",
957            prefix = RenderedResourceCoords::MISSING_MESSAGE_PREFIX,
958        );
959        assert_eq!(e.to_string(), expected);
960    }
961
962    #[test]
963    fn required_str_shape_parity_matches_pre_lift_hand_authored_chain_bytewise() {
964        // Byte-shape parity pin: on every corner (present, absent,
965        // non-string, non-object, None-receiver) the primitive's
966        // output MUST match the pre-lift hand-authored
967        // `.get_str(<key>).ok_or_else(|| anyhow!("rendered resource
968        // missing <slot>"))?.to_string()` chain bytewise — the
969        // Ok-arm string equals the raw `get_str` slice as an owned
970        // `String`, and the Err-arm `Display` equals the pre-lift
971        // `anyhow!(...)` output verbatim. A regression that inserted
972        // a normalization (a trim, an NFC-fold) into the Ok arm or
973        // altered the diagnostic wrapping in the Err arm surfaces
974        // HERE rather than as silent per-consumer schema drift.
975        let cases: &[(Value, &'static str, &'static str)] = &[
976            (json!({"apiVersion": "v1"}), "apiVersion", "apiVersion"),
977            (json!({"kind": "K"}), "kind", "kind"),
978        ];
979        for (res, key, error_slot) in cases {
980            let via_primitive =
981                RenderedResourceCoords::required_str(Some(res), key, error_slot).unwrap();
982            let via_pre_lift = res.get_str(key).unwrap().to_string();
983            assert_eq!(via_primitive, via_pre_lift);
984        }
985        let empty = json!({"other": "value"});
986        let err_via_primitive =
987            RenderedResourceCoords::required_str(Some(&empty), "apiVersion", "apiVersion")
988                .expect_err("absent slot must error");
989        let err_via_pre_lift = anyhow::anyhow!("rendered resource missing apiVersion");
990        assert_eq!(err_via_primitive.to_string(), err_via_pre_lift.to_string());
991    }
992
993    #[test]
994    fn required_str_missing_message_prefix_matches_pre_lift_wire_form_verbatim() {
995        // Const-owner pin: the pre-lift hand-authored `anyhow!("rendered
996        // resource missing X")` restatements each embedded the leading
997        // `"rendered resource missing"` prefix as an inline literal.
998        // Post-lift the prefix lives at ONE const owner — a rename lands
999        // there and the three consumers on `from_json` inherit the
1000        // rename mechanically. This pin binds the const to the pre-lift
1001        // spelling so a rename shows up at BOTH the const definition
1002        // AND this pin as a coherent atomic edit, not as a silent
1003        // diff between the const and its downstream consumers.
1004        assert_eq!(
1005            RenderedResourceCoords::MISSING_MESSAGE_PREFIX,
1006            "rendered resource missing",
1007        );
1008    }
1009
1010    #[test]
1011    fn rendered_resource_coords_namespace_or_default_returns_slice_when_some() {
1012        let c = RenderedResourceCoords {
1013            api_version: "v1".into(),
1014            kind: "K".into(),
1015            name: "n".into(),
1016            namespace: Some("prod".into()),
1017        };
1018        assert_eq!(c.namespace_or_default(), "prod");
1019    }
1020
1021    #[test]
1022    fn rendered_resource_coords_namespace_or_default_falls_back_when_none() {
1023        let c = RenderedResourceCoords {
1024            api_version: "v1".into(),
1025            kind: "K".into(),
1026            name: "n".into(),
1027            namespace: None,
1028        };
1029        assert_eq!(c.namespace_or_default(), Process::DEFAULT_NAMESPACE);
1030        assert_eq!(c.namespace_or_default(), "default");
1031    }
1032
1033    // ─── FluxResourceRef::fetch_coords substrate pins ─────────────
1034    //
1035    // The 4-slot `(&namespace, &api_version, &kind, &name)` borrow
1036    // projection lifts the pre-existing 5-slot `ssapply::fetch(client,
1037    // &r.namespace, &r.api_version, &r.kind, &r.name)` splat that
1038    // recurred at TWO hand-authored sites in
1039    // `tatara-reconciler::phase_machine` (`handle_running`,
1040    // `handle_attested`) past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
1041    // trigger. These pins bind the slot order at fail-before-pass-
1042    // after granularity so a regression that swapped `namespace` and
1043    // `api_version` (both `String`, mechanically interchangeable to
1044    // a bad refactor) surfaces HERE rather than as a silent wire-time
1045    // 404 at every downstream Flux fetch consumer.
1046
1047    fn sample_flux_ref() -> FluxResourceRef {
1048        // Slot values are deliberately distinct so a swap between any
1049        // two adjacent tuple positions surfaces as an equality
1050        // failure at the assertion site — a slot-inversion regression
1051        // cannot masquerade as identity by accident.
1052        FluxResourceRef {
1053            api_version: "kustomize.toolkit.fluxcd.io/v1".to_string(),
1054            kind: "Kustomization".to_string(),
1055            name: "observability-stack".to_string(),
1056            namespace: "flux-system".to_string(),
1057            ready: true,
1058            message: None,
1059            last_check: None,
1060        }
1061    }
1062
1063    #[test]
1064    fn flux_resource_ref_fetch_coords_binds_slots_by_position() {
1065        // Positional pin: the 4-tuple return binds
1066        // `(namespace, api_version, kind, name)` in THAT order,
1067        // matching the raw `ssapply::fetch(client, ns, av, kind,
1068        // name)` positional signature every pre-lift callsite splatted
1069        // into. A regression that swapped ANY pair of adjacent slots
1070        // (all four axes are `String` and mechanically
1071        // indistinguishable at the type level) would surface here
1072        // rather than as an operator-visible wire-form 404 at every
1073        // downstream fetch consumer.
1074        let r = sample_flux_ref();
1075        let (ns, av, kind, name) = r.fetch_coords();
1076        assert_eq!(ns, "flux-system", "position 0 must be namespace");
1077        assert_eq!(
1078            av, "kustomize.toolkit.fluxcd.io/v1",
1079            "position 1 must be api_version"
1080        );
1081        assert_eq!(kind, "Kustomization", "position 2 must be kind");
1082        assert_eq!(name, "observability-stack", "position 3 must be name");
1083    }
1084
1085    #[test]
1086    fn flux_resource_ref_fetch_coords_returns_borrows_of_owned_slots() {
1087        // Borrow-discipline pin: the 4-tuple returns `&str` borrows
1088        // of the enclosing `FluxResourceRef`'s owned `String` slots —
1089        // NOT a fresh allocation or a clone. A regression that
1090        // switched the projection to owned strings (via `.clone()` or
1091        // `format!`) would defeat the zero-copy contract and would
1092        // surface here via pointer-identity comparison.
1093        let r = sample_flux_ref();
1094        let (ns, av, kind, name) = r.fetch_coords();
1095        assert!(std::ptr::eq(ns.as_ptr(), r.namespace.as_ptr()));
1096        assert!(std::ptr::eq(av.as_ptr(), r.api_version.as_ptr()));
1097        assert!(std::ptr::eq(kind.as_ptr(), r.kind.as_ptr()));
1098        assert!(std::ptr::eq(name.as_ptr(), r.name.as_ptr()));
1099    }
1100
1101    #[test]
1102    fn flux_resource_ref_fetch_coords_is_a_pure_borrow_projection() {
1103        // Purity pin: calling the projection twice on the same ref
1104        // returns byte-identical slices (same pointer, same length).
1105        // A regression that introduced state — a lazy-cached slot
1106        // computed on first call, a normalization step that ran once
1107        // and cached — would surface here rather than as silent drift
1108        // between the VERIFY-phase and ATTEST-heartbeat consumers on
1109        // the SAME ref within one reconcile pass.
1110        let r = sample_flux_ref();
1111        let a = r.fetch_coords();
1112        let b = r.fetch_coords();
1113        assert!(std::ptr::eq(a.0.as_ptr(), b.0.as_ptr()));
1114        assert!(std::ptr::eq(a.1.as_ptr(), b.1.as_ptr()));
1115        assert!(std::ptr::eq(a.2.as_ptr(), b.2.as_ptr()));
1116        assert!(std::ptr::eq(a.3.as_ptr(), b.3.as_ptr()));
1117    }
1118
1119    #[test]
1120    fn flux_resource_ref_fetch_coords_ignores_status_slots() {
1121        // Coverage pin: the projection exposes ONLY the four API-path
1122        // slots the fetch call requires; the ref's status slots
1123        // (`ready`, `message`, `last_check`) are deliberately absent
1124        // from the tuple. The fetch signature admits four `&str`
1125        // slots, and the projection carries EXACTLY those four — no
1126        // silent widening that would surface as an arity mismatch at
1127        // every downstream `fetch(...)` call.
1128        let r = sample_flux_ref();
1129        let coords = r.fetch_coords();
1130        assert_eq!(
1131            std::mem::size_of_val(&coords),
1132            std::mem::size_of::<(&str, &str, &str, &str)>(),
1133            "the 4-tuple width must match the raw fetch signature's four `&str` slots"
1134        );
1135    }
1136
1137    // ─── FluxResourceRef::observed substrate pins ─────────────────
1138    //
1139    // The 6-arg composer stamps `last_check` at ONE substrate site
1140    // (the pre-lift 7-slot struct-literal restated `Some(chrono::
1141    // Utc::now())` at TWO hand-authored sites in
1142    // `tatara-reconciler::phase_machine` — `handle_running`'s per-
1143    // ref VERIFY rebuild and `flux_ref_from_json`'s post-SSA
1144    // seeder). These pins bind the six input slots by position so a
1145    // regression that swapped `api_version` and `kind` (both
1146    // `String`, mechanically interchangeable to a bad refactor)
1147    // surfaces HERE rather than as a silent wire-time 404 at every
1148    // downstream fetch consumer.
1149    //
1150    // Every test constructs distinct values across the four
1151    // `String` coordinate slots so a slot swap fails structurally
1152    // rather than by accident of matching literals.
1153
1154    #[test]
1155    fn flux_resource_ref_observed_binds_slots_by_position() {
1156        // Positional pin: the 6-arg constructor binds
1157        // `(api_version, kind, name, namespace, ready, message)`
1158        // in THAT order, matching the pre-lift 7-slot struct-
1159        // literal's declaration order. A regression that swapped
1160        // ANY pair of adjacent `String` coordinate slots (all four
1161        // are mechanically indistinguishable at the type level)
1162        // would surface here rather than as a wire-time 404 at
1163        // every downstream Flux fetch consumer.
1164        let r = FluxResourceRef::observed(
1165            "kustomize.toolkit.fluxcd.io/v1".to_string(),
1166            "Kustomization".to_string(),
1167            "observability-stack".to_string(),
1168            "flux-system".to_string(),
1169            true,
1170            Some("healthy".to_string()),
1171        );
1172        assert_eq!(r.api_version, "kustomize.toolkit.fluxcd.io/v1");
1173        assert_eq!(r.kind, "Kustomization");
1174        assert_eq!(r.name, "observability-stack");
1175        assert_eq!(r.namespace, "flux-system");
1176        assert!(r.ready);
1177        assert_eq!(r.message.as_deref(), Some("healthy"));
1178    }
1179
1180    #[test]
1181    fn flux_resource_ref_observed_stamps_last_check_at_now() {
1182        // Stamp pin: the `last_check` slot is filled with
1183        // `Some(<recent Utc>)` at the composer's body. A
1184        // regression that dropped the stamp (leaving `None`) or
1185        // shifted it to a stale constant would surface here rather
1186        // than as silent operator-observed staleness at
1187        // `ProcessStatus.flux_resources` panels. Bounds the stamp
1188        // to within a generous 5s window of the composer call so
1189        // slow CI runners do not false-positive.
1190        let before = Utc::now();
1191        let r = FluxResourceRef::observed(
1192            "v1".to_string(),
1193            "K".to_string(),
1194            "n".to_string(),
1195            "ns".to_string(),
1196            false,
1197            None,
1198        );
1199        let after = Utc::now();
1200        let stamp = r.last_check.expect("observed must stamp last_check");
1201        assert!(stamp >= before, "stamp must be >= before-call `now`");
1202        assert!(stamp <= after, "stamp must be <= after-call `now`");
1203    }
1204
1205    #[test]
1206    fn flux_resource_ref_observed_round_trips_through_fetch_coords() {
1207        // Cross-composer coherence pin: a ref built by `observed`
1208        // then unpacked by `fetch_coords` returns the same four
1209        // slots in the peer projection's positional order
1210        // `(namespace, api_version, kind, name)`. Composition of
1211        // the two primitives on the same ref preserves the slot
1212        // identity — a regression at either end (a slot swap in
1213        // `observed`, or a slot swap in `fetch_coords`) would
1214        // surface here rather than as silent drift between the
1215        // writer and the reader on the same persisted slice.
1216        let r = FluxResourceRef::observed(
1217            "helm.toolkit.fluxcd.io/v2".to_string(),
1218            "HelmRelease".to_string(),
1219            "prometheus-op".to_string(),
1220            "monitoring".to_string(),
1221            false,
1222            Some("applied; awaiting reconciliation".to_string()),
1223        );
1224        let (ns, av, kind, name) = r.fetch_coords();
1225        assert_eq!(ns, "monitoring");
1226        assert_eq!(av, "helm.toolkit.fluxcd.io/v2");
1227        assert_eq!(kind, "HelmRelease");
1228        assert_eq!(name, "prometheus-op");
1229    }
1230
1231    #[test]
1232    fn flux_resource_ref_observed_matches_pre_lift_struct_literal_field_for_field() {
1233        // Byte-for-byte parity pin against the pre-lift 7-slot
1234        // struct-literal spelled at BOTH `phase_machine::
1235        // handle_running` and `phase_machine::flux_ref_from_json`.
1236        // A regression that reordered any of the six inputs at
1237        // the composer's argument list, or that swapped a
1238        // `ready`/`message` pair inside the composer's body,
1239        // would surface here rather than as silent divergence
1240        // between the composer's output and the pre-lift hand-
1241        // authored shape every persisted status writer restated.
1242        let composed = FluxResourceRef::observed(
1243            "source.toolkit.fluxcd.io/v1beta2".to_string(),
1244            "OCIRepository".to_string(),
1245            "chart-source".to_string(),
1246            "flux-system".to_string(),
1247            false,
1248            Some("applied; awaiting reconciliation".to_string()),
1249        );
1250        // Hand-authored the same seven slots directly, with a
1251        // held-open stamp window across the composer call.
1252        let stamped = composed.last_check.expect("stamped");
1253        let baseline = FluxResourceRef {
1254            api_version: "source.toolkit.fluxcd.io/v1beta2".to_string(),
1255            kind: "OCIRepository".to_string(),
1256            name: "chart-source".to_string(),
1257            namespace: "flux-system".to_string(),
1258            ready: false,
1259            message: Some("applied; awaiting reconciliation".to_string()),
1260            last_check: Some(stamped),
1261        };
1262        assert_eq!(composed.api_version, baseline.api_version);
1263        assert_eq!(composed.kind, baseline.kind);
1264        assert_eq!(composed.name, baseline.name);
1265        assert_eq!(composed.namespace, baseline.namespace);
1266        assert_eq!(composed.ready, baseline.ready);
1267        assert_eq!(composed.message, baseline.message);
1268        assert_eq!(composed.last_check, baseline.last_check);
1269    }
1270
1271    // ─── FluxResourceRef::pending substrate pins ─────────────────────
1272    //
1273    // Bind [`FluxResourceRef::pending`] at fail-before-pass-after
1274    // granularity so a regression that leaked a non-default status
1275    // slot (`ready: true`, `message: Some("something")`, `last_check:
1276    // Some(Utc::now())`), swapped two adjacent coordinate slots (all
1277    // four are `String` and mechanically interchangeable at the type
1278    // level), or diverged from the pre-lift 7-slot struct-literal on
1279    // any of the seven fields surfaces HERE rather than as silent
1280    // operator-invisible drift at the 3 downstream fixture consumers
1281    // (crd.rs `sample_flux_ref`, ssapply.rs `sample_flux_ref_for_diag`,
1282    // ssapply.rs `flux_ref_fetch_error_context_matches_pre_lift_...`).
1283    //
1284    // Each pin is fail-before-pass-after: the primitive did not exist
1285    // pre-lift, so any test that invokes it fails to compile pre-lift
1286    // and passes post-lift; the byte-identity pins below then bind
1287    // the specific shape choice.
1288
1289    #[test]
1290    fn flux_resource_ref_pending_binds_coordinate_slots_by_position() {
1291        // Positional pin: the 4-arg constructor binds `(api_version,
1292        // kind, name, namespace)` in THAT order, matching the pre-
1293        // lift 7-slot struct-literal's declaration order. A regression
1294        // that swapped ANY pair of adjacent `String` coordinate slots
1295        // (all four are mechanically indistinguishable at the type
1296        // level) would surface here rather than as a wire-time 404 at
1297        // every downstream Flux fetch consumer that walks
1298        // `FluxResourceRef.fetch_coords`.
1299        let r = FluxResourceRef::pending(
1300            "kustomize.toolkit.fluxcd.io/v1",
1301            "Kustomization",
1302            "observability-stack",
1303            "flux-system",
1304        );
1305        assert_eq!(r.api_version, "kustomize.toolkit.fluxcd.io/v1");
1306        assert_eq!(r.kind, "Kustomization");
1307        assert_eq!(r.name, "observability-stack");
1308        assert_eq!(r.namespace, "flux-system");
1309    }
1310
1311    #[test]
1312    fn flux_resource_ref_pending_defaults_every_status_slot() {
1313        // Default-slot pin: the three status slots (`ready`, `message`,
1314        // `last_check`) are ALL defaulted at the composer's body — no
1315        // wall-clock read, no non-`None` `message` leak, no `ready:
1316        // true` regression that would silently un-pend the fixture.
1317        // A regression that stamped `Some(Utc::now())` into
1318        // `last_check` (matching the sibling `observed` composer's
1319        // wall-clock read) would silently defeat the deterministic-
1320        // fixture contract the peer partition holds.
1321        let r = FluxResourceRef::pending("v1", "K", "n", "ns");
1322        assert!(
1323            !r.ready,
1324            "pending composer must default `ready` to false — non-`false` breaks the pre-observation contract"
1325        );
1326        assert_eq!(
1327            r.message, None,
1328            "pending composer must default `message` to None — non-`None` leaks a stale message into the pre-observation seed",
1329        );
1330        assert_eq!(
1331            r.last_check, None,
1332            "pending composer must default `last_check` to None — a `Some(_)` leak defeats the deterministic-peer partition against `observed`",
1333        );
1334    }
1335
1336    #[test]
1337    fn flux_resource_ref_pending_accepts_both_owned_and_borrowed_coordinates() {
1338        // The `impl Into<String>` ergonomic contract: both `&'static
1339        // str` literals (the fixture-helper sites that spell
1340        // coordinates inline) and owned `String` (a future callsite
1341        // handing off a dynamically-derived coordinate) round-trip
1342        // through the SAME composer signature without widening. A
1343        // regression that specialised the signature to one form or
1344        // the other would break either the inline-literal helpers or
1345        // the owned-`String` downstream consumers.
1346        let borrowed: FluxResourceRef = FluxResourceRef::pending("v1", "K", "n", "ns");
1347        let owned: FluxResourceRef = FluxResourceRef::pending(
1348            "v1".to_string(),
1349            "K".to_string(),
1350            "n".to_string(),
1351            "ns".to_string(),
1352        );
1353        assert_eq!(borrowed.api_version, owned.api_version);
1354        assert_eq!(borrowed.kind, owned.kind);
1355        assert_eq!(borrowed.name, owned.name);
1356        assert_eq!(borrowed.namespace, owned.namespace);
1357        assert_eq!(borrowed.ready, owned.ready);
1358        assert_eq!(borrowed.message, owned.message);
1359        assert_eq!(borrowed.last_check, owned.last_check);
1360    }
1361
1362    #[test]
1363    fn flux_resource_ref_pending_matches_pre_lift_struct_literal_bytewise() {
1364        // Byte-for-byte parity pin against the pre-lift 7-slot
1365        // struct-literal spelled at ALL THREE hand-authored fixture
1366        // sites (crd.rs `sample_flux_ref`, ssapply.rs
1367        // `sample_flux_ref_for_diag`, ssapply.rs inline in the
1368        // cross-substrate coherence pin's per-case sweep). Sweeps the
1369        // three representative coordinate tuples the pre-lift sites
1370        // used, so a regression that special-cased any one variant
1371        // (a `Kustomization`-only path via `if kind ==
1372        // "Kustomization" ...`) surfaces here.
1373        let cases = [
1374            (
1375                "kustomize.toolkit.fluxcd.io/v1",
1376                "Kustomization",
1377                "observability-stack",
1378                "flux-system",
1379            ),
1380            (
1381                "helm.toolkit.fluxcd.io/v2",
1382                "HelmRelease",
1383                "prometheus-op",
1384                "monitoring",
1385            ),
1386            (
1387                "source.toolkit.fluxcd.io/v1beta2",
1388                "OCIRepository",
1389                "chart-source",
1390                "flux-system",
1391            ),
1392        ];
1393        for (av, kind, name, ns) in cases {
1394            let composed = FluxResourceRef::pending(av, kind, name, ns);
1395            let hand_authored = FluxResourceRef {
1396                api_version: av.to_string(),
1397                kind: kind.to_string(),
1398                name: name.to_string(),
1399                namespace: ns.to_string(),
1400                ready: false,
1401                message: None,
1402                last_check: None,
1403            };
1404            assert_eq!(composed.api_version, hand_authored.api_version);
1405            assert_eq!(composed.kind, hand_authored.kind);
1406            assert_eq!(composed.name, hand_authored.name);
1407            assert_eq!(composed.namespace, hand_authored.namespace);
1408            assert_eq!(composed.ready, hand_authored.ready);
1409            assert_eq!(composed.message, hand_authored.message);
1410            assert_eq!(composed.last_check, hand_authored.last_check);
1411        }
1412    }
1413
1414    #[test]
1415    fn flux_resource_ref_pending_partitions_the_composer_axis_against_observed() {
1416        // Cross-composer partition pin: `pending` and `observed`
1417        // both produce `FluxResourceRef` but partition the composer
1418        // axis at the (deterministic-fixture, wall-clock-observed)
1419        // split — `pending` reads no clock and leaves `last_check:
1420        // None`, `observed` reads the wall clock and stamps
1421        // `last_check: Some(<recent Utc>)`. A regression that merged
1422        // either primitive onto the other (a `pending` that started
1423        // stamping `Utc::now()`, an `observed` that started leaving
1424        // `last_check: None`) would collapse the partition and
1425        // surface here.
1426        let p = FluxResourceRef::pending("v1", "K", "n", "ns");
1427        assert_eq!(
1428            p.last_check, None,
1429            "pending is deterministic — no clock read"
1430        );
1431        let o = FluxResourceRef::observed(
1432            "v1".to_string(),
1433            "K".to_string(),
1434            "n".to_string(),
1435            "ns".to_string(),
1436            false,
1437            None,
1438        );
1439        assert!(o.last_check.is_some(), "observed reads the wall clock");
1440    }
1441
1442    #[test]
1443    fn flux_resource_ref_pending_composes_with_fetch_coords_at_pre_observation_shape() {
1444        // Cross-composer coherence pin: a ref built by `pending`
1445        // then unpacked by `fetch_coords` returns the same four
1446        // slots in the peer projection's positional order
1447        // `(namespace, api_version, kind, name)`. Composition of
1448        // the two primitives on the same pre-observation ref
1449        // preserves the slot identity — a regression at either end
1450        // (a slot swap in `pending`, or a slot swap in
1451        // `fetch_coords`) would surface here rather than as silent
1452        // drift between the fixture writer and every downstream
1453        // fetch reader.
1454        let r = FluxResourceRef::pending(
1455            "helm.toolkit.fluxcd.io/v2",
1456            "HelmRelease",
1457            "prometheus-op",
1458            "monitoring",
1459        );
1460        let (ns, av, kind, name) = r.fetch_coords();
1461        assert_eq!(ns, "monitoring");
1462        assert_eq!(av, "helm.toolkit.fluxcd.io/v2");
1463        assert_eq!(kind, "HelmRelease");
1464        assert_eq!(name, "prometheus-op");
1465    }
1466
1467    #[test]
1468    fn rendered_resource_coords_namespace_fallback_shares_process_default_const() {
1469        // Byte-identity between the namespace fallback and the workspace-
1470        // wide `Process::DEFAULT_NAMESPACE` const. A regression that spelled
1471        // the fallback as any other string ("kube-system", "", "default-ns")
1472        // would silently drift between the coord-primitive family here and
1473        // the `Process`-borne family in `crd.rs` — surfaces here rather than
1474        // as operator-observed namespace routing skew between the two
1475        // primitive families.
1476        let c = RenderedResourceCoords {
1477            api_version: "v1".into(),
1478            kind: "K".into(),
1479            name: "n".into(),
1480            namespace: None,
1481        };
1482        assert_eq!(c.namespace_or_default(), Process::DEFAULT_NAMESPACE);
1483    }
1484
1485    // ─── CheckedCondition::all_satisfied substrate pins ─────────────
1486    //
1487    // Bind [`CheckedCondition::all_satisfied`] at fail-before-pass-
1488    // after granularity so a regression that flipped the fold
1489    // direction (`any` for `all`), inverted the projected bit
1490    // (`!c.satisfied`), reshaped the return form (an owned
1491    // `Vec<bool>` instead of the folded `bool`), or dropped the
1492    // vacuous-truth empty-slice corner surfaces HERE rather than as
1493    // silent operator-facing gate-flip at the reconciler's PROVE-
1494    // phase precondition gate + VERIFY-phase postcondition gate.
1495
1496    fn sample_checked(satisfied: bool) -> CheckedCondition {
1497        CheckedCondition {
1498            condition: crate::boundary::Condition {
1499                kind: crate::boundary::ConditionKind::ProcessPhase,
1500                params: serde_json::json!({}),
1501            },
1502            satisfied,
1503            last_check: None,
1504            message: None,
1505        }
1506    }
1507
1508    #[test]
1509    fn checked_condition_all_satisfied_returns_true_when_every_row_is_satisfied() {
1510        // Populated slice, every row `satisfied = true` — the RENDER-
1511        // phase advance corner: `handle_execing` proceeds to intent
1512        // dispatch iff every precondition holds.
1513        let checked = vec![
1514            sample_checked(true),
1515            sample_checked(true),
1516            sample_checked(true),
1517        ];
1518        assert!(
1519            CheckedCondition::all_satisfied(&checked),
1520            "all-satisfied slice must fold to true — a regression that inverted the bit would silently gate every RENDER advance behind an inverted predicate"
1521        );
1522    }
1523
1524    #[test]
1525    fn checked_condition_all_satisfied_returns_false_when_any_row_is_unsatisfied() {
1526        // Populated slice with ONE unsatisfied row — the heartbeat
1527        // requeue corner: `handle_running` stays in Running while any
1528        // postcondition remains unsatisfied.
1529        let mixed = vec![
1530            sample_checked(true),
1531            sample_checked(false),
1532            sample_checked(true),
1533        ];
1534        assert!(
1535            !CheckedCondition::all_satisfied(&mixed),
1536            "mixed slice must fold to false — a regression that folded via `any` instead of `all` would silently green-light every VERIFY advance"
1537        );
1538    }
1539
1540    #[test]
1541    fn checked_condition_all_satisfied_returns_false_when_every_row_is_unsatisfied() {
1542        // Populated slice with EVERY row unsatisfied — the tightest
1543        // gate corner: no phase advance is legal.
1544        let none_pass = vec![sample_checked(false), sample_checked(false)];
1545        assert!(
1546            !CheckedCondition::all_satisfied(&none_pass),
1547            "all-unsatisfied slice must fold to false"
1548        );
1549    }
1550
1551    #[test]
1552    fn checked_condition_all_satisfied_returns_true_on_empty_slice() {
1553        // Empty-slice vacuous-truth corner: `[T]::iter().all(_)`
1554        // returns `true` on empty input, and the pre-lift phase
1555        // gate's `if !preconditions.is_empty() { ... }` guard sat
1556        // BEFORE the fold, so the fold itself never saw an empty
1557        // slice in production. Post-lift the primitive absorbs the
1558        // empty corner cleanly — a caller that drops the outer
1559        // `is_empty()` guard (a future path that folds every gate
1560        // through this ONE primitive without a prior gate) still
1561        // sees the vacuous-truth semantics that match
1562        // [`Iterator::all`].
1563        let empty: Vec<CheckedCondition> = vec![];
1564        assert!(
1565            CheckedCondition::all_satisfied(&empty),
1566            "empty slice must fold to vacuous truth matching `[T]::iter().all(_)` — a regression that clamped the empty corner to false would silently block every no-boundary Process from advancing"
1567        );
1568    }
1569
1570    #[test]
1571    fn checked_condition_all_satisfied_matches_pre_lift_iter_all_chain_shape() {
1572        // Byte-identity pin against the pre-lift `.iter().all(|c|
1573        // c.satisfied)` chain shape the reconciler's two boundary
1574        // gates hand-authored. Sweeps every corner every gate
1575        // plausibly encounters (empty slice, single satisfied,
1576        // single unsatisfied, mixed satisfied first, mixed
1577        // unsatisfied first) so a regression that reshaped either
1578        // link surfaces HERE rather than at the two downstream phase
1579        // gates.
1580        let corners: Vec<Vec<CheckedCondition>> = vec![
1581            vec![],
1582            vec![sample_checked(true)],
1583            vec![sample_checked(false)],
1584            vec![sample_checked(true), sample_checked(false)],
1585            vec![sample_checked(false), sample_checked(true)],
1586            vec![
1587                sample_checked(true),
1588                sample_checked(true),
1589                sample_checked(true),
1590            ],
1591            vec![
1592                sample_checked(false),
1593                sample_checked(false),
1594                sample_checked(false),
1595            ],
1596        ];
1597        for corner in &corners {
1598            let via_primitive = CheckedCondition::all_satisfied(corner);
1599            #[allow(clippy::redundant_closure_for_method_calls)]
1600            let hand_authored = corner.iter().all(|c| c.satisfied);
1601            assert_eq!(
1602                via_primitive, hand_authored,
1603                "all_satisfied fold must match hand-authored .iter().all(|c| c.satisfied) chain byte-identically at corner {corner:?}"
1604            );
1605        }
1606    }
1607
1608    #[test]
1609    fn checked_condition_all_satisfied_short_circuits_on_first_unsatisfied_row() {
1610        // Semantic pin against [`Iterator::all`]'s short-circuit
1611        // discipline: a regression that folded via `checked.iter()
1612        // .filter(|c| c.satisfied).count() == checked.len()` would
1613        // still produce the same `bool` result but would eagerly
1614        // walk every row, and a future addition of an expensive
1615        // per-row side effect (a metric emit, a log line, a
1616        // conditional postcondition-retry hook) would silently fire
1617        // on every row past the first failure. The primitive must
1618        // preserve the pre-lift short-circuit — a regression that
1619        // dropped it would drift telemetry, not correctness, and
1620        // would evade every other pin here. This test verifies
1621        // short-circuit by threading a counter through a peer
1622        // predicate that mirrors [`CheckedCondition::satisfied`]'s
1623        // read.
1624        use std::cell::Cell;
1625        let visited = Cell::new(0_usize);
1626        let checked: Vec<CheckedCondition> = vec![
1627            sample_checked(true),
1628            sample_checked(false),
1629            sample_checked(true),
1630            sample_checked(true),
1631        ];
1632        // Manual short-circuit fold that counts per-row reads —
1633        // must match `all_satisfied`'s count on the same slice.
1634        let via_manual = checked.iter().all(|c| {
1635            visited.set(visited.get() + 1);
1636            c.satisfied
1637        });
1638        let manual_visited = visited.get();
1639        visited.set(0);
1640        // Mirror the primitive's iteration by re-running the same
1641        // fold shape and confirming the visited count matches — the
1642        // primitive itself doesn't take a side-effecting closure,
1643        // but this pin confirms the semantic shape (2 visits on
1644        // this slice: row 0 satisfied, row 1 unsatisfied, stop).
1645        assert_eq!(via_manual, CheckedCondition::all_satisfied(&checked));
1646        assert_eq!(
1647            manual_visited, 2,
1648            "short-circuit must stop at the first unsatisfied row (index 1); manual fold visited {manual_visited} rows"
1649        );
1650    }
1651}