Skip to main content

tatara_process/
crd.rs

1//! The `Process` CRD — `tatara.pleme.io/v1alpha1`.
2
3use chrono::{DateTime, Utc};
4use kube::CustomResource;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use tatara_lisp::DeriveTataraDomain;
8
9use crate::attestation::ProcessAttestation;
10use crate::boundary::Boundary;
11use crate::classification::Classification;
12use crate::compliance::ComplianceSpec;
13use crate::encapsulates::EncapsulatesSpec;
14use crate::identity::Identity;
15use crate::intent::Intent;
16use crate::lifetime::{EphemeralLifetime, Lifetime};
17use crate::phase::ProcessPhase;
18use crate::routing::RoutingSpec;
19use crate::signal::ProcessSignal;
20use crate::spec::{DependsOn, IdentitySpec, SignalPolicy};
21use crate::status::{BoundaryStatus, ComplianceStatus, FluxResourceRef, ProcessCondition};
22
23/// Process — one element of the tatara convergence lattice, reconciled as a Unix process.
24///
25/// ```yaml
26/// apiVersion: tatara.pleme.io/v1alpha1
27/// kind: Process
28/// metadata:
29///   name: observability-stack
30///   namespace: seph
31/// spec:
32///   identity:
33///     parent: seph.1
34///   classification:
35///     pointType: Gate
36///     substrate: Observability
37///   intent:
38///     nix:
39///       flakeRef: github:pleme-io/k8s?dir=shared/infrastructure
40///       attribute: observability
41///   compliance:
42///     baseline: fedramp-moderate
43///     bindings:
44///       - framework: nist-800-53
45///         controlId: SC-7
46///         phase: AtBoundary
47///   dependsOn:
48///     - name: secret-injection
49/// ```
50#[derive(CustomResource, DeriveTataraDomain, Clone, Debug, Deserialize, Serialize, JsonSchema)]
51#[kube(
52    group = "tatara.pleme.io",
53    version = "v1alpha1",
54    kind = "Process",
55    plural = "processes",
56    shortname = "proc",
57    namespaced,
58    status = "ProcessStatus",
59    printcolumn = r#"{"name":"PID","type":"string","jsonPath":".status.pid"}"#,
60    printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"#,
61    printcolumn = r#"{"name":"Type","type":"string","jsonPath":".spec.classification.pointType"}"#,
62    printcolumn = r#"{"name":"Substrate","type":"string","jsonPath":".spec.classification.substrate"}"#,
63    printcolumn = r#"{"name":"Gen","type":"integer","jsonPath":".status.attestation.generation"}"#,
64    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
65)]
66#[serde(rename_all = "camelCase")]
67#[tatara(keyword = "defpoint")]
68pub struct ProcessSpec {
69    /// Identity (parent, name override).
70    #[serde(default)]
71    pub identity: IdentitySpec,
72
73    /// Lattice position (6 dimensions).
74    pub classification: Classification,
75
76    /// Where rendered artifacts come from. Exactly one variant must be set.
77    pub intent: Intent,
78
79    /// Boundary predicates (preconditions / postconditions).
80    #[serde(default)]
81    pub boundary: Boundary,
82
83    /// Compliance bindings + baseline.
84    #[serde(default)]
85    pub compliance: ComplianceSpec,
86
87    /// Lattice dependencies — must reach phase before we proceed.
88    #[serde(default)]
89    pub depends_on: Vec<DependsOn>,
90
91    /// Signal policy (grace, SIGHUP strategy, start-suspended).
92    #[serde(default)]
93    pub signals: SignalPolicy,
94
95    /// Lifetime — `Permanent` (default, re-converging) or `Ephemeral`
96    /// (auto-SIGTERM per `teardown_policy` + TTL clock).
97    #[serde(default, skip_serializing_if = "Lifetime::is_default")]
98    pub lifetime: Lifetime,
99
100    /// External edges — DNS + Ingress. When `None`, the Process is
101    /// internal-only (matches today's default). See
102    /// [`crate::routing`] for the full shape.
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub routing: Option<RoutingSpec>,
105
106    /// Pre-existing in-cluster state this Process wraps. When `None`,
107    /// the Process is greenfield (Manage mode implicitly applied to
108    /// nothing pre-existing). See [`crate::encapsulates`] for the
109    /// three modes (Manage / Adopt / Observe).
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub encapsulates: Option<EncapsulatesSpec>,
112
113    /// Soft-suspend marker — reconciler treats as SIGSTOP.
114    /// Same effect as delivering SIGSTOP, but persistent across restarts.
115    #[serde(default)]
116    pub suspended: bool,
117}
118
119// Coordinate primitives — the `(namespace, name)` pair every downstream
120// composer (annotation writers, claim arbiter, boundary evaluator,
121// render owner-metadata seed) pulled by hand from `Process.metadata`
122// pre-lift, each restating the same two `Option<String>`-to-`&str`
123// unwrap incantations with the same two workspace-wide fallback
124// strings sprayed inline. Post-lift the pair lives at ONE substrate
125// primitive on `Process` — a future normalization (case-fold,
126// unicode-safe collation, cross-cluster prefix, a rename of either
127// fallback) lands here and every downstream composer inherits the
128// upgrade mechanically. Peer to `qualified_process_ref` in
129// `tatara-reconciler::ssapply`, whose two `&str` arguments are
130// exactly the pair `Process::coordinates_or_defaults` returns.
131impl Process {
132    /// The K8s canonical default namespace — the fallback every
133    /// consumer of a `Process` whose `metadata.namespace` is `None`
134    /// substitutes. Matches the string K8s itself substitutes on
135    /// namespaced resource writes with no explicit namespace.
136    pub const DEFAULT_NAMESPACE: &'static str = "default";
137
138    /// Workspace-wide fallback for a `Process`'s `metadata.name` when
139    /// it is `None` — the sentinel every annotation writer, claim
140    /// arbiter, and owner-metadata seed substitutes so downstream
141    /// grepping / label-selecting sees a stable spelling rather than
142    /// a per-callsite ad-hoc placeholder (`""`, `"<unnamed>"`, or the
143    /// empty `unwrap_or_default()` fallback). A Process authored
144    /// through the reconciler's fork path always has a name; this
145    /// constant covers the surface where an untyped `Process` value
146    /// (test fixture, dynamic API response, adopted resource pre-
147    /// name-resolution) surfaces without one.
148    pub const UNNAMED_PLACEHOLDER: &'static str = "unnamed";
149
150    /// Namespace slice with the [`Self::DEFAULT_NAMESPACE`] fallback
151    /// applied — the ONE-line collapse of the `metadata.namespace
152    /// .as_deref().unwrap_or("default")` incantation every consumer
153    /// spelled by hand pre-lift.
154    ///
155    /// Peer to [`Self::name_or_placeholder`] on the (metadata slot ×
156    /// fallback shape) axis; both compose through
157    /// [`Self::coordinates_or_defaults`] when a consumer needs the
158    /// pair together (annotation writers, claim-arbiter row builders,
159    /// render owner-metadata seed).
160    pub fn namespace_or_default(&self) -> &str {
161        self.metadata
162            .namespace
163            .as_deref()
164            .unwrap_or(Self::DEFAULT_NAMESPACE)
165    }
166
167    /// Name slice with the [`Self::UNNAMED_PLACEHOLDER`] fallback
168    /// applied — the ONE-line collapse of the `metadata.name.as_deref
169    /// ().unwrap_or("unnamed")` incantation every consumer spelled by
170    /// hand pre-lift.
171    ///
172    /// Peer to [`Self::namespace_or_default`] on the (metadata slot ×
173    /// fallback shape) axis; both compose through
174    /// [`Self::coordinates_or_defaults`] when a consumer needs the
175    /// pair together.
176    pub fn name_or_placeholder(&self) -> &str {
177        self.metadata
178            .name
179            .as_deref()
180            .unwrap_or(Self::UNNAMED_PLACEHOLDER)
181    }
182
183    /// `(namespace, name)` coordinates with the workspace-wide default
184    /// fallbacks applied — the ONE-line collapse of the paired
185    /// `metadata.namespace.as_deref().unwrap_or("default")` +
186    /// `metadata.name.as_deref().unwrap_or("unnamed")` extraction
187    /// every downstream composer restated by hand pre-lift.
188    ///
189    /// Return-tuple order matches the axis order of the substrate's
190    /// paired-composer primitive
191    /// `tatara_reconciler::ssapply::qualified_process_ref(ns, name)`:
192    /// the (namespace, name) pair this method returns feeds that
193    /// primitive positionally without an axis-swap step.
194    pub fn coordinates_or_defaults(&self) -> (&str, &str) {
195        (self.namespace_or_default(), self.name_or_placeholder())
196    }
197
198    /// `(namespace, name)` coordinates as owned `String`s, with the
199    /// namespace half fallback-defaulted to [`Self::DEFAULT_NAMESPACE`]
200    /// but the name half REQUIRED — an [`anyhow::Error`] is returned
201    /// when `metadata.name` is absent, because "unnamed" is a display
202    /// placeholder, not a valid K8s API path segment. Fed straight into
203    /// kube-rs API calls (`Api::patch`, `Api::delete`, `Api::get`) that
204    /// take owned `String` arguments; the [`Self::DEFAULT_NAMESPACE`]
205    /// fallback matches what K8s itself substitutes on namespaced
206    /// resource writes with no explicit namespace, so the surface is
207    /// safe against a `Process` whose `metadata.namespace` slot is
208    /// absent (test fixture, dynamic API response pre-defaulting) but
209    /// refuses to guess a name.
210    ///
211    /// Peer to [`Self::coordinates_or_defaults`] on the (return-form ×
212    /// name gate) axis pair:
213    /// * borrow + name-defaulted → `coordinates_or_defaults` (display,
214    ///   annotation writers, ownership-tag composers — every consumer
215    ///   whose downstream drops `"unnamed"` in place of a missing name
216    ///   without an operator-visible failure);
217    /// * owned + name-required → this method (kube-rs API calls —
218    ///   every consumer whose downstream must NOT silently substitute
219    ///   a placeholder for the API call target, because the caller is
220    ///   about to `patch`/`delete`/`get` at `metadata.name`).
221    ///
222    /// The error wording is pinned by
223    /// [`tests::owned_coordinates_or_err_error_message_matches_pre_lift_reconciler_wording`]
224    /// to match the exact spelling every pre-lift `tatara-reconciler`
225    /// helper produced (`"Process has no metadata.name"`) so log-line
226    /// / test greps that anchored on that wording keep matching post-
227    /// lift, and no operator-visible message drift lands as a side
228    /// effect of the substrate move.
229    pub fn owned_coordinates_or_err(&self) -> anyhow::Result<(String, String)> {
230        let ns = self
231            .metadata
232            .namespace
233            .clone()
234            .unwrap_or_else(|| Self::DEFAULT_NAMESPACE.into());
235        let name = self
236            .metadata
237            .name
238            .clone()
239            .ok_or_else(|| anyhow::anyhow!("Process has no metadata.name"))?;
240        Ok((ns, name))
241    }
242
243    /// `(namespace, name)` coordinates in the BORROW + NAME-REQUIRED
244    /// corner of the primitive family — namespace half falls back to
245    /// [`Self::DEFAULT_NAMESPACE`], but the name half is REQUIRED
246    /// (`None` on a `Process` whose `metadata.name` is absent, so the
247    /// caller stops with an `else { continue; }` / `else { return
248    /// …; }` guard rather than proceeding with the empty-string
249    /// sentinel every pre-lift consumer had to spell inline).
250    ///
251    /// Peer to [`Self::coordinates_or_defaults`] +
252    /// [`Self::owned_coordinates_or_err`] on the (return-form ×
253    /// name-gate) axis pair — closes the corner the family previously
254    /// left open:
255    ///
256    /// * borrow + name-defaulted → [`Self::coordinates_or_defaults`]
257    ///   (annotation writers, render owner-metadata seed — consumers
258    ///   whose downstream tolerates the `"unnamed"` display placeholder
259    ///   without operator-visible failure);
260    /// * borrow + name-required → **this method** (claim-arbiter
261    ///   probes, child-Process delete-fan-out — consumers that need a
262    ///   real API-path leaf and cleanly SKIP the row when the name is
263    ///   absent rather than issuing a K8s call with an empty-string
264    ///   name argument);
265    /// * owned + name-required → [`Self::owned_coordinates_or_err`]
266    ///   (kube-rs API-path calls — consumers whose downstream requires
267    ///   owned `String` arguments and rejects the missing-name corner
268    ///   with a load-bearing error message).
269    ///
270    /// The primitive family's `None`-on-missing-name semantics
271    /// intentionally differs from [`Self::owned_coordinates_or_err`]'s
272    /// error-on-missing-name semantics: the caller sites for this form
273    /// (child-Process fan-out, claim-arbiter row probes) are non-fatal
274    /// SKIPS rather than reportable failures — an `Option::None` at
275    /// the primitive lets the caller thread that "skip" through a
276    /// let-else without stringifying / logging an anyhow chain per
277    /// missing-name occurrence.
278    ///
279    /// The namespace fallback matches [`Self::coordinates_or_defaults`]
280    /// (via [`Self::namespace_or_default`]), so a consumer that
281    /// switches between the two borrow-form primitives based on its
282    /// name-gate need never sees a different namespace-fallback string
283    /// as a side effect.
284    pub fn coordinates_or_none(&self) -> Option<(&str, &str)> {
285        let name = self.metadata.name.as_deref()?;
286        Some((self.namespace_or_default(), name))
287    }
288
289    /// Canonical `<ns>/<name>` **namespace-qualified process reference**
290    /// composed straight off the live [`Process`] — the ONE-liner
291    /// collapse of the paired
292    /// `let (ns, name) = process.coordinates_or_defaults(); let r =
293    /// qualified_process_ref(ns, name);` incantation every consumer
294    /// whose downstream keys a Process by "which cluster location owns
295    /// it" hand-authored at scattered sites across `tatara-reconciler`.
296    ///
297    /// Pre-lift the 2-step `coordinates_or_defaults() →
298    /// qualified_process_ref(ns, name)` composition was hand-authored
299    /// at THREE sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
300    /// threshold in `tatara-reconciler`, each restating the SAME
301    /// paired projection + `<ns>/<name>` shape:
302    /// * `render::render_routing` — routing-graph `PROCESS=<ref>`
303    ///   annotation seed on every emitted Ingress / DNSEndpoint,
304    ///   feeding [`crate::status::FluxResourceRef`] downstream.
305    /// * `render::render_export_jobs` — export-Job `PROCESS=<ref>`
306    ///   annotation seed on every emitted export `batch/v1` Job.
307    /// * `table_controller::reconcile` — claim-arbiter row-key +
308    ///   `Candidate.process_ref` seed on the stable-name claim
309    ///   registry (the reference lands verbatim in
310    ///   [`crate::table::ClaimRecord.holder`], where every downstream
311    ///   claim query greps it).
312    ///
313    /// All THREE sites walked the SAME 2-step chain — pull the
314    /// `(ns, name)` pair through [`Self::coordinates_or_defaults`],
315    /// then feed the pair positionally into
316    /// [`crate::qualified_process_ref`]. Post-lift each caller reads
317    /// `process.qualified_ref()` — the paired projection + shape
318    /// composer now sit at ONE substrate owner, so a rename of either
319    /// workspace-wide fallback (`"default"` / `"unnamed"`), a swap of
320    /// the `<ns>/<name>` separator, a normalization pass inserted
321    /// between the paired projection and the shape composer, or a
322    /// future `<ns>/<name>@<gen>` / `<cluster>/<ns>/<name>` cross-
323    /// cluster extension lands here exactly once and every consumer
324    /// (annotation seed, claim-row key, holder-slot writer, export-
325    /// Job seed, `Candidate` composer) inherits the upgrade
326    /// mechanically.
327    ///
328    /// Peer to [`Self::coordinates_or_defaults`] on the (return-form ×
329    /// composition-depth) axis pair:
330    /// * pair + defaulted → [`Self::coordinates_or_defaults`]
331    ///   (consumers that thread each half into a separate positional
332    ///   slot — `Api::namespaced(client, &ns) + Api::patch(&name, …)`,
333    ///   `one_export_job(ns, name, …)`, `EdgeContext { process_name,
334    ///   process_namespace, … }`);
335    /// * shape + defaulted → **this method** (consumers that key on
336    ///   the composed `<ns>/<name>` reference directly — the
337    ///   `PROCESS=<ref>` annotation seed, the `ClaimRecord.holder`
338    ///   slot, the label-selector composer).
339    ///
340    /// The namespace-fallback discipline matches
341    /// [`Self::coordinates_or_defaults`] (via
342    /// [`Self::namespace_or_default`]) and the name-fallback discipline
343    /// matches [`Self::name_or_placeholder`], so a consumer that
344    /// switches between the pair-returning primitive and this shape-
345    /// composing primitive never sees a different fallback string as
346    /// a side effect. The composed reference is byte-identical to the
347    /// pre-lift hand-authored `format!("{ns}/{name}")` with `ns` /
348    /// `name` supplied by the pair-returning primitive, so downstream
349    /// greps keyed on the reference shape (`PROCESS=<ref>` on emitted
350    /// resources, `holder = <ref>` on claim-registry queries) match
351    /// bytewise post-lift.
352    ///
353    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
354    /// the 2-step paired-projection + shape-composer chain recurred at
355    /// three hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
356    /// duplication trigger, and is lifted onto ONE workspace-wide
357    /// owner here). THEORY.md §II.1 invariant 5 (composition preserves
358    /// proofs — a regression that inserted a normalization step at
359    /// only two of three sites, or that drifted the fallback strings
360    /// between the paired projection and the shape composer, surfaces
361    /// at [`tests::qualified_ref_*`] rather than as silent operator-
362    /// visible skew across the three annotation / claim-key /
363    /// export-Job seed writers).
364    #[must_use]
365    pub fn qualified_ref(&self) -> String {
366        let (ns, name) = self.coordinates_or_defaults();
367        crate::qualified_process_ref(ns, name)
368    }
369
370    /// Borrowed lookup of ONE key in `metadata.annotations`, with
371    /// BOTH the missing-`annotations` corner AND the missing-key
372    /// corner collapsed to `None` — the ONE-liner collapse of the
373    /// paired `self.metadata.annotations.as_ref().and_then(|m|
374    /// m.get(key)).map(String::as_str)` incantation every consumer
375    /// restated by hand pre-lift.
376    ///
377    /// Pre-lift the 3-line `.metadata.annotations.as_ref().and_then
378    /// (|m| m.get(KEY))` chain (in three tail variants — `.cloned()`,
379    /// `.cloned().unwrap_or_default()`, `.map(String::as_str)`) was
380    /// hand-authored at THREE sites past the ★★ PRIME-DIRECTIVE ≥ 2
381    /// duplication threshold across the workspace:
382    /// * `tatara-reconciler::signals::ingest` — SIGNAL annotation
383    ///   lookup (pre-lift `.cloned()` for owned parsing).
384    /// * `tatara-reconciler::phase_machine::released_from_annotation`
385    ///   — RELEASED_FROM annotation lookup (pre-lift `.cloned()
386    ///   .unwrap_or_default()` for `match v.as_str()`).
387    /// * `tatara-pool-reconciler::controller_pool::process_belongs_to_pool`
388    ///   — POOL annotation lookup (pre-lift `.map(String::as_str)`
389    ///   for `== Some(pool_name)`).
390    ///
391    /// All THREE sites walked the SAME 3-line chain — read the
392    /// annotations map, gate on presence, index by key — differing
393    /// only in the tail that shaped the result. Post-lift each
394    /// caller routes through the ONE substrate primitive here and
395    /// applies its own tail at its own site (`.map(str::to_string)`
396    /// / bare match / `==`).
397    ///
398    /// Return-form axis: `Option<&str>` mirrors the existing borrow-
399    /// first discipline of the peer metadata primitives
400    /// [`Self::namespace_or_default`], [`Self::name_or_placeholder`],
401    /// [`Self::coordinates_or_none`]. The two corners the chain
402    /// swallowed pre-lift (missing `metadata.annotations` map,
403    /// missing key inside the map) BOTH collapse to `None` so
404    /// `.is_some()` / `if let Some(_)` / `Option::map` behave
405    /// identically on a `Process` whose annotations block is `None`
406    /// and on one whose annotations block is populated but omits the
407    /// key — matching what the pre-lift `.and_then(...)` chain
408    /// produced.
409    ///
410    /// A future normalization step (a key-canonicalization pass,
411    /// a case-fold lookup, a per-key alias table for renamed
412    /// annotations across API versions, a per-namespace override
413    /// substrate) lands at ONE substrate method here and all three
414    /// downstream consumers pick up the upgrade mechanically — no
415    /// per-callsite hand-edit at `ingest` / `released_from_annotation`
416    /// / `process_belongs_to_pool`.
417    ///
418    /// Sibling to the peer metadata primitives
419    /// ([`Self::namespace_or_default`], [`Self::name_or_placeholder`],
420    /// [`Self::coordinates_or_defaults`], [`Self::coordinates_or_none`],
421    /// [`Self::owned_coordinates_or_err`]) on the metadata axis;
422    /// this method opens the borrow-form peer on the ANNOTATION
423    /// axis. Future annotation projections (a paired
424    /// `label(&str) -> Option<&str>` on `metadata.labels`, a
425    /// `has_annotation(&str) -> bool` boolean gate for presence-
426    /// only consumers) land as peer methods on this same axis.
427    ///
428    /// Theory anchor: THEORY.md §VI.1 (generation over composition
429    /// — the 3-line annotation-lookup chain recurred at three
430    /// hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
431    /// duplication trigger, and is lifted to ONE owner here).
432    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
433    /// the pins bind the missing-`annotations` corner + the
434    /// missing-key corner + the borrow-form `&str` lifetime + the
435    /// byte-identical parity with the pre-lift 3-line chain, so a
436    /// regression that drifted any surface at
437    /// `tests::annotation_*` rather than as silent operator-facing
438    /// skew between the SIGNAL / RELEASED_FROM / POOL annotation
439    /// readers).
440    pub fn annotation(&self, key: &str) -> Option<&str> {
441        self.metadata
442            .annotations
443            .as_ref()
444            .and_then(|m| m.get(key))
445            .map(String::as_str)
446    }
447
448    /// Borrow-form metadata-projection primitive on the `metadata.uid`
449    /// axis: returns the K8s-API-server-assigned uid as a `&str`, with
450    /// the missing-uid corner collapsed to the load-bearing empty-string
451    /// sentinel — the ONE-liner collapse of the paired
452    /// `self.metadata.uid.as_deref().unwrap_or("")` incantation every
453    /// owner-reference-emitting consumer restated by hand pre-lift.
454    ///
455    /// The empty-string fallback is NOT arbitrary — it is the exact
456    /// sentinel value the sibling substrate composer
457    /// [`crate::owner_references_json`] gates on (`if uid.is_empty()
458    /// { vec![] } else { vec![owner_reference_json(name, uid)] }`) to
459    /// stamp `metadata.ownerReferences: []` on a resource whose owning
460    /// Process pre-dates the API server's `metadata.uid` assignment
461    /// (test fixture, mid-Forking snapshot before the first `patch`
462    /// round-trip, dynamic API response pre-uid-resolution). Pre-lift
463    /// each consumer spelled the fallback as `.unwrap_or("")` at its
464    /// callsite; the two literals in two files could drift silently to
465    /// `.unwrap_or_default()`, `.unwrap_or("<unknown>")`, or an
466    /// `if let Some(u) = &process.metadata.uid` gate that returned a
467    /// different owner-refs shape for the missing-uid corner. Post-lift
468    /// the sentinel value is composed at ONE substrate site so the
469    /// empty-uid gate at `owner_references_json` and its per-callsite
470    /// producers share the SAME `""` byte-string, and a rename of the
471    /// sentinel would land at ONE substrate site rather than at every
472    /// downstream `owner_references_json(name, uid)` call.
473    ///
474    /// Peer to [`Self::namespace_or_default`] +
475    /// [`Self::name_or_placeholder`] on the metadata-slot × fallback-
476    /// shape axis: `namespace_or_default` returns the K8s-canonical
477    /// `"default"` fallback (matching what the API server substitutes
478    /// on namespaced writes with no explicit namespace);
479    /// `name_or_placeholder` returns the workspace-wide `"unnamed"`
480    /// sentinel (a display placeholder for downstream grepping /
481    /// label-selecting); this method returns the empty-string sentinel
482    /// (a load-bearing gate value that composes with
483    /// [`crate::owner_references_json`]'s `is_empty` check). The three
484    /// primitives partition the metadata-slot family by whether the
485    /// consumer wants a K8s-canonical fallback (namespace), a display
486    /// placeholder (name), or a gate sentinel (uid).
487    ///
488    /// Pre-lift the `.metadata.uid.as_deref().unwrap_or("")` chain was
489    /// hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
490    /// duplication threshold in `tatara-reconciler::render`, both
491    /// feeding a downstream owner-reference emitter:
492    /// * `render_routing` — the routing-edge seed that binds
493    ///   `process_uid` into every routing-form `EdgeContext` (Ingress +
494    ///   DNSEndpoint) built inside the fanout loop over
495    ///   `RoutingSpec::hostnames`; each `Edge::render` impl then walks
496    ///   its `EdgeContext` through `build_owner_refs` →
497    ///   [`crate::owner_references_json`] to stamp
498    ///   `metadata.ownerReferences` on the emitted resource.
499    /// * `render_export_jobs` — the ephemeral-export Job builder that
500    ///   passes the same uid slice to `tatara_process::
501    ///   owner_references_json(name, uid)` per rendered Job, stamping
502    ///   the export-Job's `metadata.ownerReferences` back at the
503    ///   owning Process.
504    ///
505    /// Both sites walked the SAME `.as_deref().unwrap_or("")` chain and
506    /// both wanted the `&str` form the primitive returns — as the
507    /// second positional argument to `owner_references_json(name, uid)`
508    /// on the ownership-tag axis. Post-lift each callsite reads
509    /// `let uid = process.uid_or_empty();` and the produced slice feeds
510    /// the same downstream composer unchanged.
511    ///
512    /// Return-form axis: `&str` mirrors the existing borrow-first
513    /// discipline of the peer metadata-fallback primitives
514    /// ([`Self::namespace_or_default`], [`Self::name_or_placeholder`]);
515    /// all three return owned-metadata borrows with a slot-specific
516    /// fallback baked in so downstream consumers compose the slice
517    /// directly into their next call without re-spelling the fallback.
518    ///
519    /// A future normalization step (a canonicalization pass that
520    /// rejects a malformed uid before the owner-ref stamp, a cross-
521    /// cluster uid rewrite for multi-tenant control planes, a stale-
522    /// uid warning annotation for a Process whose uid changed under
523    /// the reconciler mid-generation) lands at ONE substrate method
524    /// here and both downstream `owner_references_json` consumers
525    /// pick up the upgrade mechanically — no per-callsite hand-edit
526    /// at `render_routing` / `render_export_jobs`.
527    ///
528    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
529    /// the `.metadata.uid.as_deref().unwrap_or("")` chain recurred at
530    /// two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
531    /// duplication trigger, and is lifted to ONE owner here).
532    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
533    /// the pins bind the missing-uid corner + the empty-string
534    /// sentinel byte-shape + the borrow-form `&str` lifetime + the
535    /// byte-identical parity with the pre-lift chain + the composition
536    /// coherence with [`crate::owner_references_json`]'s `is_empty`
537    /// gate, so a regression that drifted any surface at
538    /// `tests::uid_or_empty_*` rather than as silent operator-facing
539    /// skew between the two owner-reference emitters on the SAME
540    /// Process).
541    pub fn uid_or_empty(&self) -> &str {
542        self.metadata.uid.as_deref().unwrap_or("")
543    }
544
545    /// Owned-form metadata-projection primitive on the `metadata.name`
546    /// axis: returns an owned `String` copy of the K8s object name, with
547    /// the missing-name corner collapsed to the load-bearing empty-string
548    /// sentinel — the ONE-liner collapse of the paired
549    /// `self.metadata.name.clone().unwrap_or_default()` incantation every
550    /// keying / row-builder consumer restated by hand pre-lift.
551    ///
552    /// Pre-lift the `.metadata.name.clone().unwrap_or_default()` chain
553    /// was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
554    /// duplication threshold in `tatara-pool-reconciler::controller_pool`,
555    /// both stamping the `PoolMember` / `PoolMemberSnapshot`
556    /// `process_name: String` slot inside a struct-literal fanout over
557    /// pool-owned `Process`es:
558    /// * `reconcile_pool`'s pool-member seed (annotation-matched Process
559    ///   list → `PoolMember { process_name, state, entered_state_at, .. }`)
560    ///   — the row every operator sees on the pool's status page.
561    /// * `reconcile_pool`'s desired-count snapshot seed
562    ///   (`PoolMemberSnapshot { process_name, phase, created_at }`)
563    ///   — the row fed into `decide_pool_convergence`.
564    ///
565    /// Both sites walked the SAME `.clone().unwrap_or_default()` chain
566    /// and both wanted the `String` form the primitive returns — as the
567    /// owned-form `process_name: String` slot on a struct literal
568    /// composed inside a `.iter().map(...)` fanout over the same
569    /// pool-owned `Process` list. Post-lift each callsite reads
570    /// `process_name: p.owned_name_or_empty()` and the produced value
571    /// feeds the same struct-literal slot unchanged.
572    ///
573    /// The empty-string fallback is the SAME sentinel the sibling
574    /// borrow-form primitive [`Self::uid_or_empty`] returns — the two
575    /// primitives partition the owned-form × borrow-form corner of the
576    /// metadata-slot family on identical fallback semantics (empty
577    /// string means "the slot is unset"), so a consumer that switches
578    /// between them based on downstream ownership requirements never
579    /// sees a different missing-slot spelling as a side effect.
580    ///
581    /// Peer to [`Self::name_or_placeholder`] on the (return-form ×
582    /// fallback-value) axis pair — closes the corner the family
583    /// previously left open:
584    ///
585    /// * borrow + display placeholder → [`Self::name_or_placeholder`]
586    ///   (log lines, annotation writers, ownership-tag composers —
587    ///   consumers whose downstream drops `"unnamed"` in place of a
588    ///   missing name without operator-visible failure);
589    /// * owned + empty sentinel → **this method** (row-builder /
590    ///   HashMap-key / struct-literal fanout consumers whose downstream
591    ///   fills a `String` field with the load-bearing `""` sentinel to
592    ///   flag "no name to key by" rather than substituting a display
593    ///   placeholder that would misalign a downstream lookup);
594    /// * owned + name-required → [`Self::owned_coordinates_or_err`] (kube-rs
595    ///   API-path calls — consumers whose downstream must NOT silently
596    ///   substitute a placeholder for the API call target).
597    ///
598    /// The primitive family's `""`-on-missing-name semantics
599    /// intentionally differs from [`Self::name_or_placeholder`]'s
600    /// `"unnamed"` semantics: the caller sites for this form (pool
601    /// membership row seeds, HashMap keys) are load-bearing keys — a
602    /// display placeholder like `"unnamed"` would silently alias every
603    /// missing-name Process to the same key, collapsing distinct rows
604    /// in the pool's member list. The empty-string sentinel keeps the
605    /// pre-lift byte-shape and lets downstream consumers gate on
606    /// `String::is_empty` if they need to filter the missing-name
607    /// corner explicitly.
608    ///
609    /// A future normalization step (a name-canonicalization pass, a
610    /// case-fold key builder, a per-pool alias table for renamed
611    /// Processes across generations) lands at ONE substrate method
612    /// here and both downstream `PoolMember` / `PoolMemberSnapshot`
613    /// seeds pick up the upgrade mechanically — no per-callsite hand-
614    /// edit at `reconcile_pool`.
615    ///
616    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
617    /// the `.metadata.name.clone().unwrap_or_default()` chain recurred
618    /// at two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
619    /// duplication trigger, and is lifted to ONE owner here).
620    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
621    /// the pins bind the missing-name corner + the empty-string
622    /// sentinel byte-shape + the owned-form `String` return type +
623    /// the byte-identical parity with the pre-lift chain + the
624    /// fallback-value coherence with the sibling [`Self::uid_or_empty`]
625    /// on the metadata-slot × empty-sentinel axis, so a regression
626    /// that drifted any surface at `tests::owned_name_or_empty_*`
627    /// rather than as silent operator-facing skew between the pool-
628    /// member seed and the desired-count snapshot seed on the SAME
629    /// pool).
630    pub fn owned_name_or_empty(&self) -> String {
631        self.metadata.name.clone().unwrap_or_default()
632    }
633
634    /// Borrow-form spec-projection primitive on the declared parent-PID
635    /// axis: returns the hierarchical PID path (e.g. `"seph.1"`) the
636    /// author declared at `spec.identity.parent`, with the empty-slot
637    /// corner collapsed to `None` — the ONE-liner collapse of the
638    /// paired `self.spec.identity.parent.as_deref()` incantation every
639    /// consumer restated by hand pre-lift.
640    ///
641    /// Pre-lift the `.spec.identity.parent.as_deref()` chain was hand-
642    /// authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
643    /// duplication threshold in `tatara-reconciler::phase_machine`:
644    /// * `handle_forking` — the ALLOCATE-PID composer that threads the
645    ///   declared parent PID into [`pid::allocate_pid`] and also into
646    ///   the status patch payload (`{ "pid": new_pid, "parent":
647    ///   parent_pid }`), so the reconciler-observed
648    ///   [`ProcessStatus::parent`] slot mirrors the author-declared
649    ///   [`IdentitySpec::parent`] at fork time. The `info!` tracing
650    ///   span also reads the same slice as the `parent` field on the
651    ///   PID-assigned log line.
652    /// * `handle_exiting` — the SIGTERM cascade's child-fan-out filter
653    ///   that enumerates every Process cluster-wide and picks children
654    ///   whose `spec.identity.parent` equals this Process's currently-
655    ///   observed PID (`.filter(|c| c.spec.identity.parent.as_deref()
656    ///   == Some(pid))`). The filter runs per candidate child, so the
657    ///   borrow-form projection avoids allocating one `String` clone
658    ///   per non-matching row in the cluster-wide list.
659    ///
660    /// Both sites walked the SAME `.as_deref()` chain and both wanted
661    /// the `Option<&str>` form the primitive returns — the
662    /// `handle_forking` site to feed positionally into
663    /// `pid::allocate_pid(&identity, parent_pid, next_seq)` and the
664    /// tracing span's `parent = ?parent_pid` debug print + the JSON
665    /// payload's `"parent": parent_pid` slot; the `handle_exiting`
666    /// filter to compare directly against `Some(pid)` where `pid:
667    /// &str` came off the borrow-form peer [`Self::observed_pid`].
668    ///
669    /// Return-form axis: `Option<&str>` mirrors the borrow-first
670    /// discipline of every peer primitive on the metadata / status
671    /// slot family ([`Self::namespace_or_default`],
672    /// [`Self::name_or_placeholder`], [`Self::observed_pid`],
673    /// [`Self::annotation`]). The empty-slot corner
674    /// (`spec.identity.parent = None`, matching `init` / PID 1 with
675    /// no parent) collapses to `None` so `.is_some()` / `if let
676    /// Some(_)` / `.map(...)` behave identically on a `Process`
677    /// authored at cluster init (PID 1, parent absent) and on any
678    /// PID-N child (parent present) — matching the pre-lift
679    /// `.as_deref()` chain's `None` byte-identically.
680    ///
681    /// Peer to [`Self::observed_pid`] on the (spec-declared ×
682    /// status-observed) axis pair: `observed_pid` returns the PID
683    /// path this Process currently OWNS (the reconciler-persisted
684    /// child position in the hierarchy), while `declared_parent_pid`
685    /// returns the PID path this Process's parent OWNS (the author-
686    /// declared upstream position). The SIGTERM cascade at
687    /// `handle_exiting` composes both: it reads its own
688    /// [`Self::observed_pid`] and matches each candidate child's
689    /// [`Self::declared_parent_pid`] against that value — the child-
690    /// fan-out relation IS the spec-declared × status-observed axis
691    /// pair collapsed to a single comparator, both sides routed
692    /// through the same borrow-form skeleton.
693    ///
694    /// A future normalization step (a per-slot canonicalization pass
695    /// that rejects malformed hierarchical PIDs, a case-fold lookup
696    /// against a table of renamed identities, a cross-cluster prefix
697    /// stripper, an alias-table lookup that maps a legacy PID to its
698    /// current spelling) lands at ONE substrate method here and both
699    /// downstream consumers pick up the upgrade mechanically — no
700    /// per-callsite hand-edit at `handle_forking` / `handle_exiting`.
701    ///
702    /// Sibling to the peer metadata-projection primitives
703    /// ([`Self::namespace_or_default`], [`Self::name_or_placeholder`],
704    /// [`Self::coordinates_or_defaults`], [`Self::coordinates_or_none`],
705    /// [`Self::owned_coordinates_or_err`], [`Self::annotation`]) on the
706    /// metadata axis; this method opens the borrow-form peer on the
707    /// declared-identity axis. Future identity projections
708    /// (`declared_name_override` on the `spec.identity.name_override`
709    /// axis, a paired `declared_identity` composite that returns both
710    /// halves) land as peer methods on this same axis.
711    ///
712    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
713    /// the `.spec.identity.parent.as_deref()` chain recurred at two
714    /// hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
715    /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
716    /// invariant 5 (composition preserves proofs — the pins bind the
717    /// empty-slot corner + the borrow-form `&str` lifetime + the
718    /// byte-identical parity with the pre-lift `.as_deref()` chain,
719    /// so a regression that drifted any surface at
720    /// `tests::declared_parent_pid_*` rather than as silent operator-
721    /// facing skew between the ALLOCATE-PID composer and the SIGTERM
722    /// cascade's child-fan-out filter on the SAME parent-child pair).
723    pub fn declared_parent_pid(&self) -> Option<&str> {
724        self.spec.identity.parent.as_deref()
725    }
726
727    /// Borrow-form spec-projection primitive on the declared
728    /// name-override axis: returns the human name the author declared
729    /// at `spec.identity.name_override` (used verbatim instead of the
730    /// content-hash-derived name in [`derive_identity`]), with the
731    /// empty-slot corner collapsed to `None` — the ONE-liner collapse
732    /// of the paired `self.spec.identity.name_override.as_deref()`
733    /// incantation every consumer restated by hand pre-lift.
734    ///
735    /// Pre-lift the `.spec.identity.name_override.as_deref()` chain
736    /// was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
737    /// duplication threshold in `tatara-reconciler::phase_machine`,
738    /// both feeding the second positional argument of
739    /// [`derive_identity`]:
740    /// * `handle_pending` — the DECLARE composer that computes the
741    ///   Process's [`Identity`] on entry to the state machine (before
742    ///   `patch::phase_status` writes it into `status.identity`).
743    /// * `handle_forking` — the ALLOCATE-PID composer that recomputes
744    ///   the same [`Identity`] on a rehydration path (status may
745    ///   already carry an identity from a prior reconcile, in which
746    ///   case the `.and_then(|s| s.identity.clone())` short-circuit
747    ///   takes it; otherwise this `.unwrap_or_else` branch fires and
748    ///   recomputes the identity fresh from the spec) so `pid::
749    ///   allocate_pid` sees the SAME [`Identity`] the DECLARE phase
750    ///   produced.
751    ///
752    /// Both sites walked the SAME `.as_deref()` chain and both wanted
753    /// the `Option<&str>` form the primitive returns — as the second
754    /// positional argument to `derive_identity(&self.spec, …)`, which
755    /// internally trims + filters empty strings + dispatches on
756    /// `Some(non_empty)` (verbatim name, `name_override: true`) vs
757    /// `None | Some(empty | whitespace)` (content-hash-derived name,
758    /// `name_override: false`). The primitive itself preserves the
759    /// raw slot byte-identically (the trim happens IN
760    /// `derive_identity`, not at the borrow site), so the two live
761    /// paths compose through the SAME borrow-form skeleton.
762    ///
763    /// Return-form axis: `Option<&str>` mirrors the borrow-first
764    /// discipline of every peer primitive on the metadata / status /
765    /// spec-identity slot family ([`Self::namespace_or_default`],
766    /// [`Self::name_or_placeholder`], [`Self::observed_pid`],
767    /// [`Self::annotation`], [`Self::declared_parent_pid`]). The
768    /// empty-slot corner (`spec.identity.name_override = None`,
769    /// matching a Process authored WITHOUT the human-name-override
770    /// escape hatch — the default; `derive_identity` then computes
771    /// the name from the content hash) collapses to `None` so
772    /// `.is_some()` / `if let Some(_)` / `.map(...)` behave
773    /// identically on the two Process shapes an operator can author.
774    ///
775    /// Peer to [`Self::declared_parent_pid`] on the (parent × name-
776    /// override) sub-axis of the declared-identity axis: both
777    /// primitives project a `Option<String>` slot on `IdentitySpec`
778    /// through the SAME borrow-form skeleton, so a future
779    /// `declared_identity` composite that returns both halves
780    /// together (e.g. as a `(Option<&str>, Option<&str>)` tuple or a
781    /// borrow-form `DeclaredIdentityView<'_>` newtype) lands as ONE
782    /// method that COMPOSES the two peer primitives, not as three
783    /// hand-authored `.as_deref()` chains restated at each callsite.
784    ///
785    /// A future normalization step (a per-slot canonicalization pass
786    /// that rejects malformed names, a case-fold lookup against a
787    /// table of renamed identities, an alias-table lookup that maps
788    /// a legacy name-override to its current spelling, a whitespace-
789    /// trim lift OUT of `derive_identity` INTO the primitive so both
790    /// consumers see the trimmed form) lands at ONE substrate method
791    /// here and both downstream consumers pick up the upgrade
792    /// mechanically — no per-callsite hand-edit at `handle_pending` /
793    /// `handle_forking`.
794    ///
795    /// Sibling to the peer spec-identity projection
796    /// [`Self::declared_parent_pid`] on the declared-identity axis;
797    /// this method opens the borrow-form peer on the name-override
798    /// sub-axis of the same closed set (`IdentitySpec { parent,
799    /// name_override }`). Future identity projections (a paired
800    /// `declared_identity` composite that returns both halves
801    /// together) land as peer methods on this same axis.
802    ///
803    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
804    /// the `.spec.identity.name_override.as_deref()` chain recurred
805    /// at two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
806    /// duplication trigger, and is lifted to ONE owner here).
807    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
808    /// the pins bind the empty-slot corner + the borrow-form `&str`
809    /// lifetime + the byte-identical parity with the pre-lift
810    /// `.as_deref()` chain + the invariance under
811    /// [`derive_identity`]'s internal trim/filter step, so a
812    /// regression that drifted any surface at
813    /// `tests::declared_name_override_*` rather than as silent
814    /// operator-facing skew between the DECLARE composer and the
815    /// ALLOCATE-PID rehydration branch on the SAME Process spec).
816    pub fn declared_name_override(&self) -> Option<&str> {
817        self.spec.identity.name_override.as_deref()
818    }
819
820    /// Borrowed slice of the FluxCD resources this Process's status
821    /// currently persists at `status.flux_resources`, with the
822    /// missing-`status` corner collapsed to an empty slice — the ONE-
823    /// line collapse of the paired `self.status.as_ref().map(|s|
824    /// s.flux_resources.clone()).unwrap_or_default()` incantation
825    /// every VERIFY-phase / ATTEST-heartbeat consumer restated by hand
826    /// pre-lift.
827    ///
828    /// Pre-lift the 5-line `.status.as_ref().map(|s| s.flux_resources
829    /// .clone()).unwrap_or_default()` chain was hand-authored at TWO
830    /// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
831    /// `tatara-reconciler::phase_machine`:
832    /// * `handle_running` — the VERIFY-phase per-ref readiness probe
833    ///   seed that walks every ref through
834    ///   [`crate::status::FluxResourceRef::fetch_coords`] via
835    ///   `ssapply::fetch_flux_ref` and rebuilds an updated
836    ///   `Vec<FluxResourceRef>` with `ready` + `message` + `last_check`
837    ///   observed at reconcile time.
838    /// * `handle_attested` — the ATTEST-heartbeat drift detector that
839    ///   short-circuits on the first non-Ready ref via
840    ///   `ssapply::fetch_flux_ref` + `ssapply::ready_condition`.
841    ///
842    /// Both sites walked the SAME 5-line chain — clone the vector
843    /// eagerly for the length of the reconcile pass, then iterate it
844    /// by reference — even though neither site ever mutates the vector
845    /// nor keeps it alive past the enclosing async fn. Post-lift both
846    /// callers borrow the slice directly from `self.status`; the two
847    /// pre-lift `.clone()` calls disappear because the slice lives for
848    /// the borrow of `&self`, and both call sites' subsequent
849    /// downstream calls (`ssapply::fetch_flux_ref` / the
850    /// `patch::patch_process_status` write) do not touch the borrowed
851    /// `p: &Process`, so the borrow lifetime holds.
852    ///
853    /// Return-form axis: `&[FluxResourceRef]` mirrors the existing
854    /// borrow-first discipline every pre-lift consumer already
855    /// iterated by reference (`for r in &refs`), and the shape of
856    /// [`crate::status::FluxResourceRef::fetch_coords`]'s per-ref
857    /// borrow projection extends mechanically to the slice-level
858    /// projection here. The missing-`status` corner collapses to the
859    /// empty slice `&[]` so `.is_empty()` / `.len()` / iteration all
860    /// behave identically on a `Process` whose status is `None` and
861    /// on one whose status carries an empty `flux_resources` slot —
862    /// matching what the pre-lift `.unwrap_or_default()` produced
863    /// (an empty `Vec`).
864    ///
865    /// A future normalization step (a per-ref canonicalization pass
866    /// that skips duplicated refs, an owner-filter that returns only
867    /// refs stamped with the CURRENT `metadata.generation`, a
868    /// staleness gate that drops refs whose `last_check` predates a
869    /// reconcile deadline) lands at ONE substrate method here and
870    /// both downstream consumers pick up the upgrade mechanically —
871    /// no per-callsite hand-edit at `handle_running` /
872    /// `handle_attested`.
873    ///
874    /// Sibling to the [`Self::coordinates_or_none`] borrow-first
875    /// primitive on the metadata axis; this method opens the
876    /// analogous borrow-first primitive on the status-projection
877    /// axis. Future status projections (`observed_attestation` on
878    /// the attestation-chain axis, `observed_pid` on the PID axis,
879    /// `observed_children` on the child-fan-out axis) land as peer
880    /// methods on this same axis.
881    ///
882    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
883    /// the 5-line status-projection chain recurred at two hand-
884    /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
885    /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
886    /// invariant 5 (composition preserves proofs — the pins bind the
887    /// missing-`status` corner + the slice-lifetime borrow discipline
888    /// + the byte-identical parity with the pre-lift 5-line chain, so
889    /// a regression that drifted any of the three surfaces at
890    /// `tests::observed_flux_resources_*` rather than as silent
891    /// operator-facing skew between the VERIFY-phase and ATTEST-
892    /// heartbeat consumers).
893    pub fn observed_flux_resources(&self) -> &[FluxResourceRef] {
894        self.status
895            .as_ref()
896            .map(|s| s.flux_resources.as_slice())
897            .unwrap_or(&[])
898    }
899
900    /// The borrow-form status-projection primitive on the PID axis:
901    /// returns the hierarchical PID path (e.g. `"seph.1.7"`) the
902    /// reconciler currently persists at `status.pid`, with BOTH the
903    /// missing-`status` corner AND the empty-slot corner collapsed
904    /// to `None` — the ONE-liner collapse of the paired
905    /// `self.status.as_ref().and_then(|s| s.pid.clone())` incantation
906    /// every consumer restated by hand pre-lift.
907    ///
908    /// Pre-lift the 3-line `.status.as_ref().and_then(|s| s.pid
909    /// .clone())` chain was hand-authored at TWO sites past the ★★
910    /// PRIME-DIRECTIVE ≥ 2 duplication threshold in
911    /// `tatara-reconciler::phase_machine`:
912    /// * `handle_forking` — the ALLOCATE-PID gate that short-
913    ///   circuits the PID allocator when the reconciler already
914    ///   assigned a PID on a prior reconcile pass (pre-lift the
915    ///   chain composed with `.is_some()` and threw the clone away
916    ///   without ever reading the string).
917    /// * `handle_exiting` — the SIGTERM cascade that enumerates
918    ///   child Processes and terminates them by matching each
919    ///   child's `spec.identity.parent` against the PID this Process
920    ///   currently owns (pre-lift the chain bound an owned
921    ///   `Option<String>` and threaded `pid.as_str()` into the
922    ///   downstream `.as_deref() == Some(...)` comparator).
923    ///
924    /// Both sites walked the SAME 3-line chain — clone the `String`
925    /// eagerly, then either drop it (the `handle_forking` gate) or
926    /// re-borrow it through `.as_str()` (the `handle_exiting`
927    /// comparator) — even though neither site ever mutates the PID
928    /// nor keeps it alive past the enclosing async fn. Post-lift
929    /// both callers borrow the PID directly from `self.status`; the
930    /// pre-lift `.clone()` at both sites disappears because the
931    /// `&str` lives for the borrow of `&self`, and both call sites'
932    /// subsequent downstream calls (the K8s API list/patch, the
933    /// child-Process comparator) do not touch the borrowed
934    /// `p: &Process`, so the borrow lifetime holds.
935    ///
936    /// Return-form axis: `Option<&str>` mirrors the existing
937    /// borrow-first discipline every pre-lift consumer already
938    /// re-borrowed through `.as_str()` before use, and the shape of
939    /// [`Self::coordinates_or_none`]'s `Option<(&str, &str)>`
940    /// projection extends mechanically to the single-slot
941    /// projection here. The missing-`status` corner AND the
942    /// populated-status-with-`pid=None` corner BOTH collapse to
943    /// `None` so `.is_some()` / `if let Some(_)` / `.map(...)`
944    /// behave identically on a `Process` whose status is `None`
945    /// and on one whose status carries an unpopulated `pid` slot —
946    /// matching what the pre-lift `.and_then(...)` chain produced.
947    ///
948    /// A future normalization step (a per-slot canonicalization
949    /// pass that rejects malformed hierarchical PIDs, a
950    /// generation-filter that returns `None` for a PID stamped
951    /// with a stale `metadata.generation`, a staleness gate that
952    /// drops a PID whose observing `phase_since` predates a
953    /// reconcile deadline) lands at ONE substrate method here and
954    /// both downstream consumers pick up the upgrade mechanically
955    /// — no per-callsite hand-edit at `handle_forking` /
956    /// `handle_exiting`.
957    ///
958    /// Sibling to the peer [`Self::observed_flux_resources`]
959    /// borrow-first primitive on the flux-resources axis; both
960    /// methods compose the same missing-`status` fallback +
961    /// borrow-form return-shape skeleton on distinct
962    /// `ProcessStatus` slots. Future status projections
963    /// (`observed_parent` on the parent-pointer axis,
964    /// `observed_message` on the human-readable-status axis,
965    /// `observed_attestation` on the attestation-chain axis) land
966    /// as peer methods on this same axis.
967    ///
968    /// Theory anchor: THEORY.md §VI.1 (generation over
969    /// composition — the 3-line status-projection chain recurred
970    /// at two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
971    /// duplication trigger, and is lifted to ONE owner here).
972    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
973    /// the pins bind the missing-`status` corner + the empty-slot
974    /// corner + the borrow-form `&str` lifetime + the
975    /// byte-identical parity with the pre-lift 3-line chain, so a
976    /// regression that drifted any surface at
977    /// `tests::observed_pid_*` rather than as silent operator-
978    /// facing skew between the ALLOCATE-PID gate and the SIGTERM
979    /// cascade on the SAME `Process`).
980    pub fn observed_pid(&self) -> Option<&str> {
981        self.status.as_ref().and_then(|s| s.pid.as_deref())
982    }
983
984    /// The borrow-form status-projection primitive on the
985    /// attestation-chain axis: returns the last
986    /// [`ProcessAttestation`] the reconciler persisted at
987    /// `status.attestation`, with the missing-`status` corner AND the
988    /// empty-slot corner BOTH collapsed to `None` — the ONE-liner
989    /// collapse of the paired `self.status.as_ref().and_then(|s|
990    /// s.attestation.as_ref())` incantation every consumer restated
991    /// by hand pre-lift.
992    ///
993    /// Pre-lift the 3-line `.status.as_ref().and_then(|s| s
994    /// .attestation.as_ref())` chain was hand-authored at TWO sites
995    /// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
996    /// `tatara-reconciler`:
997    /// * `phase_machine::advance_to_attested` — the ATTEST composer
998    ///   that chains `prior.next(pillars)` when a prior attestation
999    ///   is persisted and seeds with `ProcessAttestation::initial`
1000    ///   otherwise.
1001    /// * `render::render_export_jobs` — the ephemeral-export Job
1002    ///   builder that pulls the prior `composed_root` off the last
1003    ///   persisted attestation and threads it into every rendered
1004    ///   Job's `previousRoot` env var, so the export receipt chains
1005    ///   into the Process's BLAKE3 attestation tree at the correct
1006    ///   generation boundary.
1007    ///
1008    /// Both sites walked the SAME 3-line chain — the borrow-form
1009    /// `Option<&ProcessAttestation>` shape both consumers wanted
1010    /// already — even though neither site ever mutated the
1011    /// attestation nor kept it alive past the enclosing async fn.
1012    /// Post-lift both callers borrow the attestation directly from
1013    /// `self.status`; the pre-lift 3-line chain shrinks to a single
1014    /// method call at both sites, and both consumers' subsequent
1015    /// downstream calls (`ProcessAttestation::next` for the ATTEST
1016    /// composer, `.composed_root.clone()` for the export Job builder)
1017    /// do not touch the borrowed `p: &Process`, so the borrow
1018    /// lifetime holds.
1019    ///
1020    /// Return-form axis: `Option<&ProcessAttestation>` mirrors the
1021    /// existing borrow-first discipline every pre-lift consumer
1022    /// already re-borrowed through `.as_ref()`, and the shape of the
1023    /// peer [`Self::observed_pid`] projection extends mechanically
1024    /// to the whole-attestation-record projection here. The missing-
1025    /// `status` corner AND the populated-status-with-`attestation
1026    /// =None` corner BOTH collapse to `None` so `.is_some()` / `if
1027    /// let Some(_)` / `.map(...)` behave identically on a `Process`
1028    /// whose status is `None` and on one whose status carries an
1029    /// unpopulated `attestation` slot — matching what the pre-lift
1030    /// `.and_then(...)` chain produced.
1031    ///
1032    /// A future normalization step (a per-slot canonicalization pass
1033    /// that rejects a persisted attestation whose `composed_root`
1034    /// fails `verify`, a generation-filter that returns `None` for
1035    /// an attestation stamped with a stale `metadata.generation`, a
1036    /// staleness gate that drops an attestation whose `attested_at`
1037    /// predates a reconcile deadline) lands at ONE substrate method
1038    /// here and both downstream consumers pick up the upgrade
1039    /// mechanically — no per-callsite hand-edit at
1040    /// `advance_to_attested` / `render_export_jobs`.
1041    ///
1042    /// Sibling to the peer [`Self::observed_pid`] +
1043    /// [`Self::observed_flux_resources`] borrow-first primitives on
1044    /// the PID + flux-resources axes; all three methods compose the
1045    /// same missing-`status` fallback + borrow-form return-shape
1046    /// skeleton on distinct `ProcessStatus` slots. Future status
1047    /// projections (`observed_parent` on the parent-pointer axis,
1048    /// `observed_message` on the human-readable-status axis) land
1049    /// as peer methods on this same axis.
1050    ///
1051    /// Theory anchor: THEORY.md §VI.1 (generation over composition
1052    /// — the 3-line status-projection chain recurred at two hand-
1053    /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
1054    /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
1055    /// invariant 5 (composition preserves proofs — the pins bind
1056    /// the missing-`status` corner + the empty-slot corner + the
1057    /// borrow-form `&ProcessAttestation` lifetime + the byte-
1058    /// identical parity with the pre-lift 3-line chain, so a
1059    /// regression that drifted any surface at
1060    /// `tests::observed_attestation_*` rather than as silent
1061    /// operator-facing skew between the ATTEST composer and the
1062    /// ephemeral-export receipt chain on the SAME `Process`).
1063    pub fn observed_attestation(&self) -> Option<&ProcessAttestation> {
1064        self.status.as_ref().and_then(|s| s.attestation.as_ref())
1065    }
1066
1067    /// The borrow-form status-projection primitive on the resolved-
1068    /// identity axis: returns the [`Identity`] the reconciler
1069    /// currently persists at `status.identity` (name + content hash +
1070    /// override flag), with the missing-`status` corner AND the
1071    /// empty-slot corner BOTH collapsed to `None` — the ONE-liner
1072    /// collapse of the paired `self.status.as_ref().and_then(|s|
1073    /// s.identity.as_ref())` incantation every consumer restated by
1074    /// hand pre-lift.
1075    ///
1076    /// Pre-lift the paired `.status.as_ref().and_then(|s|
1077    /// s.identity.<clone|as_ref>())` chain was hand-authored at TWO
1078    /// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold
1079    /// in `tatara-reconciler`:
1080    /// * `phase_machine::handle_forking` — the FORK-time identity
1081    ///   seed that reuses the reconciler-persisted `Identity` if
1082    ///   present and falls back to a fresh `derive_identity(&spec,
1083    ///   name_override)` otherwise. Pre-lift the site cloned the
1084    ///   whole `Identity` off the borrow before threading it through
1085    ///   `.unwrap_or_else(...)` even though the fallback path
1086    ///   allocates its own owned `Identity` — the pre-lift clone
1087    ///   allocated a fresh `Identity` on the happy path just so the
1088    ///   `Option`'s shape matched the fallback's `Identity` return
1089    ///   type.
1090    /// * `ssapply::inject_annotations` — the SSA-time annotation
1091    ///   composer that stamps the content-hash annotation onto every
1092    ///   owned resource. Pre-lift the site nested the identity
1093    ///   borrow-form check inside a manual `if let Some(status) =
1094    ///   &process.status { … }` guard alongside sibling `status.pid`
1095    ///   and `status.attestation` accesses — three siblings the peer
1096    ///   primitives [`Self::observed_pid`] and
1097    ///   [`Self::observed_attestation`] already own, so the outer
1098    ///   status guard was the last hand-authored `.status.as_ref()`
1099    ///   destructure at this composer.
1100    ///
1101    /// Both sites walked the SAME 3-line chain (one via `.clone()`,
1102    /// one via `.as_ref()`) — the borrow-form
1103    /// `Option<&Identity>` shape both consumers wanted already, even
1104    /// though the FORK-time seed then had to `.clone()` off the
1105    /// borrow to compose with the owned-`Identity` fallback. Post-
1106    /// lift the seed calls `.observed_identity().cloned()` at the
1107    /// exact composition point where the owned value is required
1108    /// (the empty-borrow corner clones nothing, since
1109    /// `Option::cloned` on `None` is `None`), and the SSA-time
1110    /// consumer drops the outer status guard entirely — the
1111    /// three-sibling primitive family (pid + identity + attestation)
1112    /// now peers through `observed_pid` +
1113    /// `observed_identity` + `observed_attestation` at ONE call each
1114    /// with no shared status destructure between them.
1115    ///
1116    /// Return-form axis: `Option<&Identity>` mirrors the
1117    /// existing borrow-first discipline every pre-lift consumer
1118    /// already re-borrowed through `.as_ref()` / re-cloned through
1119    /// `.clone()`, and the shape of the peer
1120    /// [`Self::observed_attestation`] projection extends
1121    /// mechanically to the whole-`Identity`-record projection here.
1122    /// The missing-`status` corner AND the populated-status-with-
1123    /// `identity=None` corner BOTH collapse to `None` so
1124    /// `.is_some()` / `if let Some(_)` / `.map(...)` behave
1125    /// identically on a `Process` whose status is `None` and on one
1126    /// whose status carries an unpopulated `identity` slot —
1127    /// matching what the pre-lift `.and_then(...)` chain produced.
1128    ///
1129    /// A future normalization step (a per-slot canonicalization
1130    /// pass that rejects an `Identity` whose `content_hash` fails
1131    /// re-derivation against the current spec, a generation-filter
1132    /// that returns `None` for an identity stamped with a stale
1133    /// `metadata.generation`, a staleness gate that drops an
1134    /// identity whose observing `phase_since` predates a reconcile
1135    /// deadline) lands at ONE substrate method here and both
1136    /// downstream consumers pick up the upgrade mechanically — no
1137    /// per-callsite hand-edit at `handle_forking` /
1138    /// `inject_annotations`.
1139    ///
1140    /// Sibling to the peer [`Self::observed_pid`] +
1141    /// [`Self::observed_attestation`] +
1142    /// [`Self::observed_flux_resources`] borrow-first primitives on
1143    /// the PID + attestation-chain + flux-resources axes; all four
1144    /// methods compose the same missing-`status` fallback +
1145    /// borrow-form return-shape skeleton on distinct `ProcessStatus`
1146    /// slots. Future status projections (`observed_parent` on the
1147    /// parent-pointer axis, `observed_message` on the human-
1148    /// readable-status axis) land as peer methods on this same
1149    /// axis.
1150    ///
1151    /// Theory anchor: THEORY.md §VI.1 (generation over composition
1152    /// — the 3-line status-projection chain recurred at two hand-
1153    /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
1154    /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
1155    /// invariant 5 (composition preserves proofs — the pins bind
1156    /// the missing-`status` corner + the empty-slot corner + the
1157    /// borrow-form `&Identity` lifetime + the byte-identical parity
1158    /// with the pre-lift 3-line chain, so a regression that drifted
1159    /// any surface at `tests::observed_identity_*` rather than as
1160    /// silent operator-facing skew between the FORK-time identity
1161    /// seed and the SSA-time content-hash annotation stamp on the
1162    /// SAME `Process`).
1163    pub fn observed_identity(&self) -> Option<&Identity> {
1164        self.status.as_ref().and_then(|s| s.identity.as_ref())
1165    }
1166
1167    /// The copy-form status-projection primitive on the phase axis:
1168    /// returns the [`ProcessPhase`] the reconciler currently persists
1169    /// at `status.phase`, wrapped in an `Option` so the missing-
1170    /// `status` corner collapses to `None` — the ONE-liner collapse
1171    /// of the paired `self.status.as_ref().map(|s| s.phase)`
1172    /// incantation every consumer restated by hand pre-lift.
1173    ///
1174    /// Peer to the borrow-form projections
1175    /// [`Self::observed_pid`] (PID axis, `Option<&str>`),
1176    /// [`Self::observed_flux_resources`] (flux-resources axis,
1177    /// `&[FluxResourceRef]`), and [`Self::observed_attestation`]
1178    /// (attestation-chain axis, `Option<&ProcessAttestation>`); this
1179    /// method opens the copy-form peer for `ProcessPhase` — a
1180    /// `Copy` scalar with a `Default` impl (`Pending`), so the
1181    /// return is `Option<ProcessPhase>` rather than
1182    /// `Option<&ProcessPhase>` (borrow would give the caller
1183    /// nothing over the copy for a 1-byte enum) and neither the
1184    /// missing-`status` corner nor a "empty slot" corner is
1185    /// meaningful — the underlying slot is a bare `ProcessPhase`,
1186    /// not `Option<ProcessPhase>`, so the primitive returns `None`
1187    /// iff `status: None`.
1188    ///
1189    /// Pre-lift the 3-line `.status.as_ref().map(|s| s.phase)`
1190    /// chain was hand-authored at FIVE sites past the ★★
1191    /// PRIME-DIRECTIVE ≥ 2 duplication threshold in
1192    /// `tatara-reconciler`:
1193    /// * `controller::reconcile` — the top-level dispatcher's
1194    ///   `current_phase` seed that feeds the deletion-preempt +
1195    ///   signal-ingestion gates + the per-phase handler dispatch.
1196    ///   Pre-lift `.unwrap_or(ProcessPhase::Pending)`.
1197    /// * `boundary::evaluate_process_phase` — the boundary
1198    ///   evaluator's `ProcessPhase` condition (a peer-Process
1199    ///   `phase`-reached postcondition). Pre-lift
1200    ///   `.unwrap_or(ProcessPhase::Pending)`.
1201    /// * `boundary::check_depends_on` — the `depends_on`
1202    ///   pre-condition audit that stashes the observed phase into
1203    ///   the `UnmetDependency::actual: Option<ProcessPhase>` slot
1204    ///   (keeps the `Option` form). Pre-lift the raw
1205    ///   `.map(|s| s.phase)` shape.
1206    /// * `phase_machine::p_current_phase_str` — the released-from
1207    ///   annotation composer that emits `"Attested"` for every
1208    ///   non-`Failed` phase (SIGSTOP/SIGCONT release gate).
1209    ///   Pre-lift `.unwrap_or(ProcessPhase::Attested)` — the ONE
1210    ///   site whose default is not `Pending`; the primitive
1211    ///   returns the raw `Option` so the caller's `.unwrap_or`
1212    ///   default choice stays local rather than baked in.
1213    /// * `table_controller::stable_name_group_key` — the routing-
1214    ///   groupby seed that pairs the phase with the PID + creation
1215    ///   timestamp when partitioning Processes claiming the same
1216    ///   stable name. Pre-lift `.unwrap_or(ProcessPhase::Pending)`.
1217    ///
1218    /// All FIVE sites walked the SAME 3-line `.status.as_ref()
1219    /// .map(|s| s.phase)` chain — three closed with `unwrap_or
1220    /// (ProcessPhase::Pending)` (the `Default`), one closed with
1221    /// `unwrap_or(ProcessPhase::Attested)`, one kept the raw
1222    /// `Option<ProcessPhase>` — so the ONE substrate accessor
1223    /// returns the raw `Option<ProcessPhase>` and each consumer
1224    /// keeps its `.unwrap_or(...)` default choice at its own site.
1225    ///
1226    /// A future normalization step (a generation-filter that
1227    /// returns `None` for a phase stamped with a stale
1228    /// `metadata.generation`, a staleness gate that drops a phase
1229    /// whose observing `phase_since` predates a reconcile
1230    /// deadline, a canonicalization pass that maps a phase that
1231    /// no longer belongs to the CRD's closed set to `None`) lands
1232    /// at ONE substrate method here and all five consumers pick
1233    /// up the upgrade mechanically — no per-callsite hand-edit at
1234    /// `reconcile` / `evaluate_process_phase` / `check_depends_on`
1235    /// / `p_current_phase_str` / `stable_name_group_key`.
1236    ///
1237    /// Future status projections (`observed_parent` on the
1238    /// parent-pointer axis, `observed_message` on the human-
1239    /// readable-status axis, `observed_children` on the child
1240    /// fan-out axis, `observed_exit_code` on the terminal-exit
1241    /// axis) land as peer methods on this same axis.
1242    ///
1243    /// Theory anchor: THEORY.md §VI.1 (generation over
1244    /// composition — the 3-line status-projection chain recurred
1245    /// at FIVE hand-authored sites past the ★★ PRIME-DIRECTIVE
1246    /// ≥ 2 duplication trigger, and is lifted to ONE owner here).
1247    /// THEORY.md §II.1 invariant 5 (composition preserves proofs
1248    /// — the pins bind the missing-`status` corner + the
1249    /// per-variant enum round-trip + the byte-identical parity
1250    /// with the pre-lift 3-line chain, so a regression that
1251    /// drifted any surface at `tests::observed_phase_*` rather
1252    /// than as silent operator-facing skew between the
1253    /// controller's dispatch seed and the boundary evaluator's
1254    /// depends-on audit on the SAME `Process` within one
1255    /// reconcile pass).
1256    pub fn observed_phase(&self) -> Option<ProcessPhase> {
1257        self.status.as_ref().map(|s| s.phase)
1258    }
1259
1260    /// The copy-form status-projection primitive on the phase axis
1261    /// with the `Pending` sink applied — the ONE-liner collapse of
1262    /// the paired `self.observed_phase().unwrap_or(ProcessPhase::
1263    /// Pending)` incantation every reconciler consumer restated by
1264    /// hand at the `Option`-flattening tail of the `observed_phase`
1265    /// call. Sibling to [`Self::observed_phase`] on the (return-form
1266    /// × fallback shape) axis pair — the raw-`Option` corner stays
1267    /// as `observed_phase`, this method opens the `Pending`-defaulted
1268    /// corner that four of the five hand-authored `observed_phase`
1269    /// consumers chose (the fifth chose `Attested`; it keeps the raw
1270    /// `Option` accessor because a `Pending` sink would silently drop
1271    /// its released-from-annotation branch into the wrong label).
1272    ///
1273    /// The primitive returns [`ProcessPhase::Pending`] on any missing
1274    /// `status` slot — the same sentinel [`ProcessPhase::default`]
1275    /// returns, and the same fallback all four pre-lift consumers
1276    /// wrote by hand. `ProcessPhase::Pending` is load-bearing as the
1277    /// "not yet observed" default because the top-level dispatcher's
1278    /// `Pending → Forking` transition, the boundary evaluator's
1279    /// per-Process phase-reached postcondition, the routing groupby's
1280    /// stable-name claim-arbiter row seed, and the pool controller's
1281    /// desired-count snapshot all read a freshly-forked Process (no
1282    /// `status` yet stamped by the reconciler) as being at the
1283    /// entrypoint phase of the closed lifecycle. A caller with a
1284    /// different default choice (currently only the SIGSTOP/SIGCONT
1285    /// release gate's `Attested` fallback in
1286    /// `phase_machine::p_current_phase_str`) keeps the raw
1287    /// [`Self::observed_phase`] accessor at its own site.
1288    ///
1289    /// Pre-lift the two-link `.observed_phase().unwrap_or
1290    /// (ProcessPhase::Pending)` chain was hand-authored at FOUR
1291    /// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold
1292    /// across the workspace:
1293    /// * `tatara-reconciler::controller::reconcile` — the top-level
1294    ///   dispatcher's `current_phase` seed that feeds the
1295    ///   deletion-preempt + signal-ingestion gates + the per-phase
1296    ///   handler dispatch.
1297    /// * `tatara-reconciler::boundary::evaluate_process_phase` — the
1298    ///   boundary evaluator's [`ConditionKind::ProcessPhase`]
1299    ///   evaluator that compares a peer-Process's observed phase
1300    ///   against the operator-declared `phase`-reached postcondition.
1301    /// * `tatara-reconciler::table_controller::stable_name_group_key`
1302    ///   — the routing-groupby seed that pairs the phase with the
1303    ///   PID + creation timestamp when partitioning Processes
1304    ///   claiming the same stable name.
1305    /// * `tatara-pool-reconciler::controller_pool::reconcile_pool` —
1306    ///   the desired-count loop's per-member snapshot seed that feeds
1307    ///   `decide_pool_convergence` with each owned Process's
1308    ///   `(phase, created_at)` pair.
1309    ///
1310    /// All FOUR sites walked the SAME two-link chain and all four
1311    /// closed with `ProcessPhase::Pending` as the sink; post-lift
1312    /// each callsite reads `process.observed_phase_or_pending()` and
1313    /// the produced `ProcessPhase` feeds the same downstream branch
1314    /// (dispatch on the `current_phase` value, comparison against a
1315    /// declared threshold, groupby-key composition, member-state
1316    /// snapshot construction) unchanged.
1317    ///
1318    /// Return-form axis: `ProcessPhase` matches the copy discipline
1319    /// of [`Self::observed_phase`] (a `Copy` scalar one byte wide),
1320    /// with the [`Option`] wrapper collapsed at the primitive rather
1321    /// than at every consumer. A caller that needs the missing-`status`
1322    /// corner as a distinguishable value keeps the raw
1323    /// [`Self::observed_phase`] accessor.
1324    ///
1325    /// A future normalization step (a generation-filter that
1326    /// treats a phase stamped with a stale `metadata.generation` as
1327    /// unobserved and therefore `Pending`, a staleness gate that
1328    /// drops a phase whose observing `phase_since` predates a
1329    /// reconcile deadline, a canonicalization pass that maps a phase
1330    /// that no longer belongs to the CRD's closed set to `Pending`)
1331    /// lands at ONE substrate method here — because this primitive
1332    /// composes on top of [`Self::observed_phase`], the normalization
1333    /// applies to both the raw-`Option` and the `Pending`-sinked
1334    /// return through the SAME upstream body — and all four
1335    /// downstream consumers pick up the upgrade mechanically.
1336    ///
1337    /// Peer to the sibling defaulted-fallback primitive family
1338    /// [`Self::namespace_or_default`] +
1339    /// [`Self::name_or_placeholder`] + [`Self::uid_or_empty`] on the
1340    /// (return-shape × fallback-value) axis — those three open the
1341    /// borrow-form defaulted corner for the metadata slots; this
1342    /// method opens the copy-form defaulted corner for the phase
1343    /// slot on `status`. Future defaulted-fallback status
1344    /// projections (an `observed_pid_or_empty` on the PID axis, an
1345    /// `observed_exit_code_or_zero` on the terminal-exit axis) land
1346    /// as peer methods on this same axis.
1347    ///
1348    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1349    /// the two-link `.observed_phase().unwrap_or(Pending)` chain
1350    /// recurred at four hand-authored sites past the ★★
1351    /// PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE
1352    /// owner here). THEORY.md §II.1 invariant 5 (composition
1353    /// preserves proofs — the pins bind the missing-`status` sink to
1354    /// `Pending` + populated-status pass-through + every
1355    /// `ProcessPhase` variant round-trip + byte-identical parity
1356    /// with the pre-lift two-link chain, so a regression that
1357    /// drifted any surface at `tests::observed_phase_or_pending_*`
1358    /// rather than as silent operator-facing skew between the
1359    /// top-level dispatcher's `Pending → Forking` seed and the
1360    /// boundary evaluator's per-Process phase-reached postcondition
1361    /// on the SAME `Process` within one reconcile pass).
1362    pub fn observed_phase_or_pending(&self) -> ProcessPhase {
1363        self.observed_phase().unwrap_or(ProcessPhase::Pending)
1364    }
1365
1366    /// The copy-form status-projection primitive on the
1367    /// `status.phase_since` axis: returns the [`DateTime<Utc>`] the
1368    /// reconciler stamped when this Process last transitioned into its
1369    /// current [`ProcessPhase`], wrapped in an `Option` so BOTH the
1370    /// missing-`status` corner AND the empty-slot corner
1371    /// (`ProcessStatus.phase_since == None` — a freshly-forked Process
1372    /// whose reconciler has not yet stamped a first transition) collapse
1373    /// to `None` — the ONE-liner collapse of the paired
1374    /// `self.status.as_ref().and_then(|s| s.phase_since)` incantation
1375    /// the pool reconciler's per-owned-Process member-seed builder
1376    /// restated by hand pre-lift.
1377    ///
1378    /// Pre-lift the 5-line
1379    /// ```rust,ignore
1380    /// p.status
1381    ///     .as_ref()
1382    ///     .and_then(|s| s.phase_since)
1383    ///     .unwrap_or_else(Utc::now)
1384    /// ```
1385    /// chain was hand-authored at
1386    /// `tatara-pool-reconciler::controller_pool::reconcile_inner`'s
1387    /// per-owned-Process `PoolMember { entered_state_at: … }` seed —
1388    /// the row-builder that feeds `pool_phase_from_members` +
1389    /// `apply_pool_reconcile_decision` with each owned Process's
1390    /// last-observed transition instant. Post-lift the callsite reads
1391    /// `p.observed_phase_since().unwrap_or_else(Utc::now)`, a
1392    /// one-liner symmetric to the peer `p.created_at()
1393    /// .unwrap_or_else(Utc::now)` chain the sibling
1394    /// [`PoolMemberSnapshot`] `created_at` seed two branches below
1395    /// already routes through — closing the last raw
1396    /// `.status.as_ref()` chain on `Process` at that reconciler site.
1397    ///
1398    /// Return-form axis: `Option<DateTime<Utc>>` matches the copy-form
1399    /// discipline of the sibling metadata-projection primitive
1400    /// [`Self::created_at`] (both return `Option<DateTime<Utc>>` and
1401    /// hide the wire-format wrapper — `ProcessStatus` on the status
1402    /// side, `k8s_openapi::…::v1::Time` on the metadata side) so the
1403    /// two timestamp-projection primitives compose byte-uniformly at
1404    /// the pool reconciler's `PoolMember` / `PoolMemberSnapshot`
1405    /// seeds. Returning owned `DateTime<Utc>` with a
1406    /// substrate-injected `Utc::now()` fallback would fold an impure
1407    /// wall-clock read into the primitive, breaking the pure-
1408    /// projection discipline every peer `observed_*` accessor
1409    /// follows; the sink stays at the callsite where it composes with
1410    /// [`Self::created_at`]'s identical `.unwrap_or_else(Utc::now)`
1411    /// tail.
1412    ///
1413    /// Peer to the copy-form status-projection primitive
1414    /// [`Self::observed_phase`] on the (return-shape × status-slot)
1415    /// axis pair — both walk the paired `.status.as_ref().<map|and_then>
1416    /// (|s| s.<slot>)` chain and both project a `Copy` inner from a
1417    /// wire slot whose "not yet observed" corner collapses to `None`.
1418    /// [`Self::observed_phase`] projects the `phase` slot (a bare
1419    /// [`ProcessPhase`] with a `Default` sentinel — collapses only on
1420    /// missing `status`); this method projects the `phase_since` slot
1421    /// (an `Option<DateTime<Utc>>` with no sentinel — collapses on
1422    /// missing `status` OR on empty slot). The paired
1423    /// `.map` vs `.and_then` choice tracks the difference: the raw
1424    /// slot is `Option<DateTime<Utc>>` here so the closure returns an
1425    /// `Option` and the outer combinator flattens through `.and_then`,
1426    /// where `observed_phase`'s raw slot is a bare `ProcessPhase` so
1427    /// the closure returns a bare value and the outer combinator maps
1428    /// through `.map`. Future status-timestamp projections (an
1429    /// `observed_last_boundary_check` on
1430    /// [`crate::status::BoundaryStatus.last_check`], an
1431    /// `observed_last_export_receipt` on a future receipt-observation
1432    /// slot) land as peer methods on this same axis.
1433    ///
1434    /// A future normalization step (a per-cluster clock-skew guard
1435    /// that offsets the returned timestamp by the observing controller's
1436    /// measured skew, a canonicalization pass that maps a suspiciously-
1437    /// zero `phase_since` to `None` so consumers' `.unwrap_or_else
1438    /// (Utc::now)` tails synthesize a fresh anchor, a staleness gate
1439    /// that drops a `phase_since` predating a reconcile deadline) lands
1440    /// at ONE substrate method here and every downstream consumer
1441    /// picks up the upgrade mechanically — no per-callsite hand-edit
1442    /// at `reconcile_inner`'s member-seed builder.
1443    ///
1444    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1445    /// the paired `.status.as_ref().and_then(|s| s.phase_since)` chain
1446    /// closes the last raw `.status.as_ref()` chain in
1447    /// `tatara-pool-reconciler`'s production reconciler code on
1448    /// `Process`, and is lifted to ONE substrate owner here alongside
1449    /// the sibling `observed_phase` / `observed_phase_or_pending` /
1450    /// `observed_identity` / `observed_pid` / `observed_attestation` /
1451    /// `observed_flux_resources` primitives that closed their axes
1452    /// previously). THEORY.md §II.1 invariant 5 (composition preserves
1453    /// proofs — the pins bind the missing-`status` corner + the empty-
1454    /// slot corner + the populated-slot pass-through + the pure-
1455    /// projection discipline + the byte-identical parity with the pre-
1456    /// lift `.status.as_ref().and_then(|s| s.phase_since)` chain + the
1457    /// composition-shape agreement with [`Self::created_at`]'s
1458    /// identical `.unwrap_or_else(Utc::now)` tail at the peer
1459    /// pool-reconciler seed, so a regression that drifted any surface
1460    /// at `tests::observed_phase_since_*` rather than as silent
1461    /// operator-facing skew between the `PoolMember` row's observed-
1462    /// transition anchor and the `PoolMemberSnapshot`'s creation-
1463    /// timestamp anchor on the SAME owned `Process` within one
1464    /// reconcile pass).
1465    #[must_use]
1466    pub fn observed_phase_since(&self) -> Option<DateTime<Utc>> {
1467        self.status.as_ref().and_then(|s| s.phase_since)
1468    }
1469
1470    /// Copy-form metadata-projection primitive on the deletion-tombstone
1471    /// axis: returns `true` iff the K8s API server has stamped a
1472    /// `metadata.deletionTimestamp` on this Process (the moment the
1473    /// object entered the "being deleted" corner of its lifecycle,
1474    /// after which further mutating writes are refused and finalizers
1475    /// are drained before the object is actually removed) — the ONE-
1476    /// liner collapse of the paired `self.metadata.deletion_timestamp
1477    /// .is_some()` incantation every consumer restated by hand
1478    /// pre-lift.
1479    ///
1480    /// Pre-lift the `.metadata.deletion_timestamp.is_some()` chain
1481    /// was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE
1482    /// ≥ 2 duplication threshold in `tatara-reconciler`, both
1483    /// projecting the SAME tombstone-presence predicate on a
1484    /// `Process` value:
1485    /// * `controller::reconcile` — the top-level dispatcher's
1486    ///   deletion-preempt gate that forces the SIGTERM cascade
1487    ///   (`→ Exiting`) as soon as the API server stamps the
1488    ///   tombstone, before the phase handler for the current
1489    ///   [`ProcessPhase`] gets a chance to run. Composed with
1490    ///   [`ProcessPhase::is_alive`] so the preempt only fires on a
1491    ///   Process still in an alive phase — a Process already in
1492    ///   `Zombie` / `Reaped` / `Failed` runs its normal handler.
1493    /// * `phase_machine::handle_exiting` — the SIGTERM cascade's
1494    ///   child-fan-out loop that enumerates every child Process and
1495    ///   skips ones the API server has already tombstoned (so the
1496    ///   reconciler does not re-issue a `DELETE` against a child
1497    ///   whose deletion the API server is already draining through
1498    ///   its own finalizer). The skip composes with
1499    ///   [`Self::coordinates_or_none`]'s name-required probe so a
1500    ///   child missing either its tombstone-absent gate or its
1501    ///   `metadata.name` slot is a clean `continue` rather than an
1502    ///   attempted `child_api.delete("")` no-op.
1503    ///
1504    /// Both sites walked the SAME `.metadata.deletion_timestamp
1505    /// .is_some()` chain and both wanted the `bool` form the
1506    /// primitive returns — the `controller::reconcile` site to gate
1507    /// the SIGTERM preempt with `&& current_phase.is_alive()` and
1508    /// the `handle_exiting` site to gate the DELETE-skip with a
1509    /// bare `if child.is_being_deleted() { continue; }`. Post-lift
1510    /// each callsite reads `process.is_being_deleted()` and the
1511    /// produced `bool` feeds the same downstream gate unchanged.
1512    ///
1513    /// Return-form axis: `bool` matches the copy-form discipline of
1514    /// [`Self::observed_phase`] (an `Option<Copy>` scalar) — the
1515    /// underlying slot is a wire-format `Option<Time>` that carries
1516    /// only presence information at this axis (the RFC-3339 timestamp
1517    /// payload itself is not what the two consumers read; both only
1518    /// probe presence to detect the tombstone-stamped state).
1519    /// Returning the raw `Option<&Time>` would push the `.is_some()`
1520    /// probe back to every callsite, restating the pre-lift chain
1521    /// one link shorter without collapsing the primitive.
1522    ///
1523    /// Peer to the metadata-fallback primitives
1524    /// [`Self::namespace_or_default`], [`Self::name_or_placeholder`],
1525    /// [`Self::uid_or_empty`], [`Self::coordinates_or_defaults`],
1526    /// [`Self::coordinates_or_none`], [`Self::owned_coordinates_or_err`],
1527    /// [`Self::annotation`] on the metadata axis; this method opens
1528    /// the copy-form peer for the presence-probe corner. Future
1529    /// metadata-presence projections (an `is_being_finalized`
1530    /// projection on `metadata.finalizers.is_empty()`'s negation,
1531    /// a `has_owner` projection on `metadata.owner_references.is_empty()`'s
1532    /// negation) land as peer methods on this same axis.
1533    ///
1534    /// A future normalization step (a per-tombstone staleness gate
1535    /// that returns `false` for a tombstone older than the reconciler's
1536    /// grace-period budget, a canonicalization pass that treats a
1537    /// tombstone from a paused controller as absent, a cross-cluster
1538    /// tombstone-observation clock skew guard) lands at ONE substrate
1539    /// method here and both downstream consumers pick up the upgrade
1540    /// mechanically — no per-callsite hand-edit at
1541    /// `controller::reconcile` / `phase_machine::handle_exiting`.
1542    ///
1543    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1544    /// the `.metadata.deletion_timestamp.is_some()` chain recurred at
1545    /// two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
1546    /// duplication trigger, and is lifted to ONE owner here).
1547    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
1548    /// the pins bind the missing-tombstone corner + the present-
1549    /// tombstone corner + the copy-form `bool` return + the byte-
1550    /// identical parity with the pre-lift `.is_some()` chain, so a
1551    /// regression that drifted any surface at
1552    /// `tests::is_being_deleted_*` rather than as silent operator-
1553    /// facing skew between the top-level dispatcher's SIGTERM
1554    /// preempt and the SIGTERM cascade's child-fan-out DELETE-skip
1555    /// on the SAME `Process` within one reconcile pass).
1556    pub fn is_being_deleted(&self) -> bool {
1557        self.metadata.deletion_timestamp.is_some()
1558    }
1559
1560    /// Copy-form metadata-projection primitive on the
1561    /// `metadata.creationTimestamp` axis: returns the K8s-API-server-
1562    /// assigned creation moment as a `DateTime<Utc>`, hiding the wire-
1563    /// format `k8s_openapi::apimachinery::pkg::apis::meta::v1::Time`
1564    /// newtype behind an inherent projection — the ONE-liner collapse
1565    /// of the paired `self.metadata.creation_timestamp.as_ref().map(|t|
1566    /// t.0)` incantation every timestamp-driven consumer restated by
1567    /// hand pre-lift.
1568    ///
1569    /// Pre-lift the paired `.metadata.creation_timestamp.as_ref()` +
1570    /// `t.0` unwrap chain was hand-authored at THREE sites past the
1571    /// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold across the
1572    /// workspace, all projecting the SAME creation-moment `DateTime<Utc>`
1573    /// on a `Process`:
1574    /// * `tatara-process::lifetime_clock::evaluate` — TTL-expiry gate
1575    ///   in the ephemeral-lifetime decision (`elapsed = now
1576    ///   .signed_duration_since(creation.0)`), inside the non-terminal-
1577    ///   phase guard that fires the `AutoTerminate::Now { TtlExpired }`
1578    ///   branch. Pre-lift the site read `if let Some(creation) = process
1579    ///   .metadata.creation_timestamp.as_ref() { ... creation.0 ... }`.
1580    /// * `tatara-process::lifetime_clock::requeue_with_ttl` — sleep-
1581    ///   budget picker for the reconciler's next requeue, choosing the
1582    ///   smaller of HEARTBEAT and TTL-remaining so the reconciler
1583    ///   doesn't oversleep past a TTL boundary. Pre-lift the site read
1584    ///   `let Some(creation) = process.metadata.creation_timestamp
1585    ///   .as_ref() else { return default; };` + `creation.0`.
1586    /// * `tatara-reconciler::table_controller::reconcile_process_table`
1587    ///   — stable-name claim-arbiter row builder, seeding each
1588    ///   candidate row's `created_at` for the tie-break ordering
1589    ///   (oldest wins). Pre-lift the site read `p.metadata
1590    ///   .creation_timestamp.as_ref().map(|t| t.0).unwrap_or_else(Utc
1591    ///   ::now)`.
1592    ///
1593    /// All THREE sites walked the SAME two-link chain — read the
1594    /// `Option<Time>` slot as a borrow, then unwrap the `Time` newtype
1595    /// to its inner `DateTime<Utc>` — differing only in the tail
1596    /// (`if-let-Some` guard, `let-else` short-circuit, `Utc::now`
1597    /// fallback). Post-lift each callsite reads
1598    /// `process.created_at()` and applies its own tail at its own site
1599    /// (`if let Some(creation) = ...`, `let Some(creation) = ... else`,
1600    /// `.unwrap_or_else(Utc::now)`).
1601    ///
1602    /// Return-form axis: `Option<DateTime<Utc>>` matches the copy-form
1603    /// discipline of the sibling status-projection primitive
1604    /// [`Self::observed_phase`] — both return `Option<T>` where `T:
1605    /// Copy` and hide the wire-format wrapper (`ProcessStatus` on the
1606    /// status side; `Time` on the metadata side). Returning the raw
1607    /// `Option<&Time>` would push the `.0` unwrap back to every
1608    /// callsite, restating the pre-lift chain one link shorter without
1609    /// collapsing the primitive; returning owned `Option<Time>` would
1610    /// force a `Time` import at every consumer for a projection every
1611    /// consumer immediately discards past `.0`.
1612    ///
1613    /// Peer to the metadata-fallback + presence-probe primitives
1614    /// [`Self::namespace_or_default`], [`Self::name_or_placeholder`],
1615    /// [`Self::uid_or_empty`], [`Self::coordinates_or_defaults`],
1616    /// [`Self::coordinates_or_none`], [`Self::owned_coordinates_or_err`],
1617    /// [`Self::annotation`], [`Self::is_being_deleted`] on the metadata
1618    /// axis; this method opens the copy-form timestamp corner. Future
1619    /// metadata-timestamp projections (a
1620    /// `deletion_at() -> Option<DateTime<Utc>>` peer on the
1621    /// tombstone-payload axis for staleness gates that need the
1622    /// timestamp value alongside the presence bit) land as peer
1623    /// methods on this same axis.
1624    ///
1625    /// A future normalization step (a per-cluster clock-skew guard
1626    /// that offsets the returned timestamp by the observing controller's
1627    /// measured skew, a canonicalization pass that maps a suspiciously-
1628    /// zero creation moment to `None`, a per-namespace override that
1629    /// substitutes a `spec.identity`-declared creation anchor for the
1630    /// metadata slot on adopted resources) lands at ONE substrate
1631    /// method here and all three downstream consumers pick up the
1632    /// upgrade mechanically — no per-callsite hand-edit at `evaluate`
1633    /// / `requeue_with_ttl` / `reconcile_process_table`.
1634    ///
1635    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1636    /// the `.metadata.creation_timestamp.as_ref().map(|t| t.0)` chain
1637    /// recurred at three hand-authored sites past the ★★
1638    /// PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE
1639    /// owner here). THEORY.md §II.1 invariant 5 (composition preserves
1640    /// proofs — the pins bind the missing-timestamp corner + the
1641    /// present-timestamp corner + the copy-form `DateTime<Utc>` return
1642    /// + the byte-identical parity with the pre-lift `.as_ref().map(|t|
1643    /// t.0)` chain, so a regression that drifted any surface at
1644    /// `tests::created_at_*` rather than as silent operator-facing
1645    /// skew between the TTL-expiry gate, the requeue-budget picker,
1646    /// and the stable-name claim-arbiter tie-break on the SAME
1647    /// `Process` within one reconcile pass).
1648    pub fn created_at(&self) -> Option<DateTime<Utc>> {
1649        self.metadata.creation_timestamp.as_ref().map(|t| t.0)
1650    }
1651
1652    /// Pure composer over [`Self::created_at`] that folds the paired
1653    /// `.unwrap_or(fallback)` sink into ONE substrate owner — the
1654    /// ONE-liner collapse of the paired
1655    /// `p.created_at().unwrap_or_else(Utc::now)` incantation the two
1656    /// production consumers restated by hand pre-lift, with the
1657    /// wall-clock read kept at the callsite (as `Utc::now()` passed in
1658    /// positionally) so the primitive itself stays pure — matching the
1659    /// discipline every peer `observed_*` / `created_at` copy-form
1660    /// projection follows and the explicit warning against a
1661    /// substrate-injected `Utc::now()` fallback that
1662    /// [`Self::observed_phase_since`]'s doc already spelled out.
1663    ///
1664    /// Pre-lift the paired 2-step
1665    /// `.created_at().unwrap_or_else(Utc::now)` chain was hand-authored
1666    /// at TWO production sites past the ★★ PRIME-DIRECTIVE ≥ 2
1667    /// duplication threshold, both stamping the SAME wall-clock
1668    /// fallback on the same missing-timestamp corner:
1669    /// * `tatara-reconciler::table_controller::reconcile_process_table` —
1670    ///   the per-Process claim-row's `created_at` anchor that feeds
1671    ///   the stable-name group's tie-break comparator; a freshly-forked
1672    ///   Process whose API server has not yet stamped
1673    ///   `metadata.creationTimestamp` gets `Utc::now()` synthesized so
1674    ///   the tie-break sorts by "just-created" order rather than
1675    ///   short-circuiting on the missing slot.
1676    /// * `tatara-pool-reconciler::controller_pool::reconcile_inner`'s
1677    ///   desired-count `PoolMemberSnapshot { created_at, .. }` seed —
1678    ///   the per-owned-Process snapshot fed to
1679    ///   `decide_pool_convergence`, whose stability arithmetic
1680    ///   subtracts the anchor from `now` to compute the observed dwell
1681    ///   time; the same "just-created" fallback keeps a freshly-spawned
1682    ///   pool member from being reaped as if it were a stale zombie.
1683    ///
1684    /// Both sites walked the SAME `.unwrap_or_else(Utc::now)` tail on
1685    /// the SAME [`Self::created_at`] pure projection and both wanted
1686    /// the resolved `DateTime<Utc>` the composer returns. Post-lift
1687    /// each callsite reads `p.created_at_or(Utc::now())` and the
1688    /// produced value feeds the same downstream slot unchanged.
1689    ///
1690    /// The `fallback: DateTime<Utc>` parameter (rather than a
1691    /// substrate-injected `Utc::now()`) keeps the composer pure — a
1692    /// test with a fixed-clock harness passes its own frozen anchor, a
1693    /// production consumer passes `Utc::now()`, both go through the
1694    /// same primitive without the composer itself reaching for the
1695    /// wall clock. This resolves the tension the sibling
1696    /// [`Self::observed_phase_since`]'s doc spelled out (a buried
1697    /// `Utc::now()` fallback "would fold an impure wall-clock read
1698    /// into the primitive, breaking the pure-projection discipline
1699    /// every peer `observed_*` accessor follows") by lifting the
1700    /// composition shape, not the wall-clock read.
1701    ///
1702    /// Return-form axis: `DateTime<Utc>` matches the `unwrap_or`-style
1703    /// composer discipline of `Option::unwrap_or` in std — takes the
1704    /// pure projection, an owned fallback, returns the resolved owned
1705    /// value. Peer to the substrate composers
1706    /// [`Self::observed_phase_or_pending`] on the status-phase axis and
1707    /// [`Self::coordinates_or_defaults`] on the metadata-coordinate
1708    /// axis; all three lift a `.unwrap_or(<fallback>)` tail into ONE
1709    /// substrate site so the fallback-shape decision lives at ONE
1710    /// owner per axis.
1711    ///
1712    /// A future normalization step (a per-cluster clock-skew guard
1713    /// that offsets the returned timestamp by the observing
1714    /// controller's measured skew before applying the fallback, a
1715    /// canonicalization pass that folds a suspiciously-zero
1716    /// `creationTimestamp` to the fallback rather than accepting it,
1717    /// a per-namespace override that substitutes a `spec.identity`-
1718    /// declared creation anchor for the metadata slot on adopted
1719    /// resources) lands at ONE substrate method here and both
1720    /// downstream consumers pick up the upgrade mechanically — no
1721    /// per-callsite hand-edit at `reconcile_process_table` /
1722    /// `reconcile_inner`.
1723    ///
1724    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1725    /// the paired `.created_at().unwrap_or_else(Utc::now)` chain
1726    /// recurred at two hand-authored sites past the ★★
1727    /// PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE
1728    /// owner here). THEORY.md §II.1 invariant 5 (composition
1729    /// preserves proofs — the pins bind the missing-slot fallback
1730    /// corner + the populated-slot pass-through + the pure-composer
1731    /// discipline + the byte-identical parity with the pre-lift
1732    /// `.unwrap_or(fallback)` chain, so a regression that drifted
1733    /// any surface at `tests::created_at_or_*` rather than as
1734    /// silent operator-facing skew between the claim-arbiter's
1735    /// tie-break anchor and the pool convergence snapshot's dwell-time
1736    /// anchor on the SAME `Process` within one reconcile pass).
1737    #[must_use]
1738    pub fn created_at_or(&self, fallback: DateTime<Utc>) -> DateTime<Utc> {
1739        self.created_at().unwrap_or(fallback)
1740    }
1741
1742    /// Compound spec-projection primitive on the `spec.lifetime` axis:
1743    /// returns `Some(&e)` iff the resolver unambiguously picks the
1744    /// `Ephemeral` slot, `None` otherwise — the ONE-liner collapse of
1745    /// the 4-step `self.spec.lifetime.resolved_ephemeral()` chain the
1746    /// two `lifetime_clock` consumers previously reached through and
1747    /// the coherence-tightening lift of the naked
1748    /// `self.spec.lifetime.ephemeral.as_ref()` raw-field access
1749    /// `tatara_reconciler::render::render_export_jobs` previously
1750    /// walked past.
1751    ///
1752    /// Pre-lift THREE consumer sites past the ★★ PRIME-DIRECTIVE ≥ 2
1753    /// duplication threshold reached the ephemeral inner through TWO
1754    /// different chains that disagreed on the ambiguous corner:
1755    /// * `tatara_process::lifetime_clock::evaluate` — ambiguity-aware:
1756    ///   `process.spec.lifetime.resolved_ephemeral()` collapses BOTH-
1757    ///   slots-set to `None`, matching the "no ephemeral action"
1758    ///   outcome (`AutoTerminate::Skip`) the ambiguous case must yield.
1759    /// * `tatara_process::lifetime_clock::requeue_with_ttl` —
1760    ///   ambiguity-aware peer of `evaluate`; both share the SAME
1761    ///   `resolved_ephemeral()` gate and MUST agree on the ambiguous
1762    ///   corner or the reconciler's teardown decision and requeue-
1763    ///   budget picker drift apart on the SAME `Process` within one
1764    ///   reconcile pass.
1765    /// * `tatara_reconciler::render::render_export_jobs` — RAW field
1766    ///   access: `process.spec.lifetime.ephemeral.as_ref()` returned
1767    ///   `Some(&e)` on the ambiguous corner, so an operator-authored
1768    ///   `Process` with BOTH `permanent:` AND `ephemeral:` slots
1769    ///   populated would emit export Jobs whose teardown-triggered
1770    ///   fire semantics `lifetime_clock` refused to honor. The two
1771    ///   consumers drifted at the mis-configuration corner.
1772    ///
1773    /// Post-lift ALL THREE consumers reach through ONE `Process` method
1774    /// that composes `self.spec.lifetime.resolved_ephemeral()` — the
1775    /// ambiguity-aware `variant().ok() + as_ephemeral` chain
1776    /// [`crate::lifetime::Lifetime::resolved_ephemeral`] owns — and
1777    /// the drift between the reconciler's export-render arm and the
1778    /// lifetime clock's teardown/TTL arm CLOSES at ONE substrate site.
1779    ///
1780    /// Return-form axis: `Option<&EphemeralLifetime>` matches the
1781    /// borrow-form discipline of the underlying
1782    /// [`crate::lifetime::Lifetime::resolved_ephemeral`] projection so
1783    /// the borrow carries the `'_self` lifetime through directly
1784    /// without a temporary `LifetimeVariant` binding. Peer to the
1785    /// borrow-form status-projection primitives
1786    /// [`Self::observed_attestation`], [`Self::observed_identity`] and
1787    /// the borrow-form metadata-projection primitive
1788    /// [`Self::uid_or_empty`] — all four hide a wrapping `Option`-
1789    /// carrying wire slot behind an inherent projection.
1790    ///
1791    /// A future normalization step (a canonicalization pass that maps
1792    /// a suspiciously-zero `ttl` to a per-cluster default, a per-
1793    /// namespace override that substitutes an operator-declared
1794    /// teardown policy on adopted resources, a wire-schema migration
1795    /// that renames `spec.lifetime.ephemeral` to `spec.lifetime.timed`
1796    /// with a bridging `From` shim) lands at ONE substrate method here
1797    /// and all three downstream consumers pick up the upgrade
1798    /// mechanically — no per-callsite hand-edit at `evaluate` /
1799    /// `requeue_with_ttl` / `render_export_jobs`.
1800    ///
1801    /// Theory anchor: THEORY.md §II.1 invariant 5 (composition
1802    /// preserves proofs — the pins bind the Permanent-only corner, the
1803    /// Ephemeral-only corner, the Both-set-ambiguous corner, the
1804    /// empty-default corner, and the byte-identity parity with the
1805    /// underlying `self.spec.lifetime.resolved_ephemeral()` delegate,
1806    /// so a regression that silently swapped the projection back to
1807    /// the raw `.ephemeral.as_ref()` field would surface here rather
1808    /// than as operator-facing drift between the export-render arm
1809    /// and the teardown/TTL arm on the SAME `Process`). THEORY.md
1810    /// §VI.1 (generation over composition — the ambiguity-aware
1811    /// projection recurred at three hand-authored sites past the ★★
1812    /// PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE
1813    /// owner here).
1814    pub fn resolved_ephemeral(&self) -> Option<&EphemeralLifetime> {
1815        self.spec.lifetime.resolved_ephemeral()
1816    }
1817}
1818
1819/// Process status — every field optional until the reconciler writes it.
1820#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
1821#[serde(rename_all = "camelCase")]
1822pub struct ProcessStatus {
1823    /// Hierarchical PID path — e.g., `"seph.1.7"`.
1824    #[serde(default, skip_serializing_if = "Option::is_none")]
1825    pub pid: Option<String>,
1826
1827    /// Parent PID path (mirror of `spec.identity.parent`, resolved at fork).
1828    #[serde(default, skip_serializing_if = "Option::is_none")]
1829    pub parent: Option<String>,
1830
1831    /// Direct children's PID paths.
1832    #[serde(default)]
1833    pub children: Vec<String>,
1834
1835    /// Resolved identity (name + content hash).
1836    #[serde(default, skip_serializing_if = "Option::is_none")]
1837    pub identity: Option<Identity>,
1838
1839    /// Current phase.
1840    #[serde(default)]
1841    pub phase: ProcessPhase,
1842
1843    /// When the process entered the current phase.
1844    #[serde(default, skip_serializing_if = "Option::is_none")]
1845    pub phase_since: Option<DateTime<Utc>>,
1846
1847    /// Three-pillar attestation (written at end of every successful cycle).
1848    #[serde(default, skip_serializing_if = "Option::is_none")]
1849    pub attestation: Option<ProcessAttestation>,
1850
1851    /// FluxCD resources currently owned by this Process.
1852    #[serde(default)]
1853    pub flux_resources: Vec<FluxResourceRef>,
1854
1855    /// Boundary verification state.
1856    #[serde(default)]
1857    pub boundary: BoundaryStatus,
1858
1859    /// Compliance summary at the latest attestation.
1860    #[serde(default)]
1861    pub compliance: ComplianceStatus,
1862
1863    /// Pending signals (delivered, not yet handled).
1864    #[serde(default)]
1865    pub signal_queue: Vec<ProcessSignal>,
1866
1867    /// Standard K8s Conditions.
1868    #[serde(default)]
1869    pub conditions: Vec<ProcessCondition>,
1870
1871    /// Human-readable last status message.
1872    #[serde(default, skip_serializing_if = "Option::is_none")]
1873    pub message: Option<String>,
1874
1875    /// Exit code (only set on Failed / Reaped).
1876    #[serde(default, skip_serializing_if = "Option::is_none")]
1877    pub exit_code: Option<i32>,
1878}
1879
1880#[cfg(test)]
1881mod tests {
1882    use super::*;
1883    use crate::classification::{ConvergencePointType, SubstrateType};
1884    use crate::intent::NixIntent;
1885
1886    #[test]
1887    fn minimal_spec_serializes() {
1888        let spec = ProcessSpec {
1889            identity: IdentitySpec::default(),
1890            classification: Classification {
1891                point_type: ConvergencePointType::Gate,
1892                substrate: SubstrateType::Observability,
1893                horizon: Default::default(),
1894                calm: Default::default(),
1895                data_classification: Default::default(),
1896            },
1897            intent: Intent {
1898                nix: Some(NixIntent {
1899                    flake_ref: "github:pleme-io/k8s".into(),
1900                    attribute: "obs".into(),
1901                    system: None,
1902                    attic_cache: None,
1903                    extra_args: vec![],
1904                    delegate_to_nix_build: false,
1905                }),
1906                ..Intent::default()
1907            },
1908            boundary: Default::default(),
1909            compliance: Default::default(),
1910            depends_on: vec![],
1911            signals: Default::default(),
1912            lifetime: Default::default(),
1913            routing: None,
1914            encapsulates: None,
1915            suspended: false,
1916        };
1917        let yaml = serde_yaml::to_string(&spec).unwrap();
1918        assert!(yaml.contains("pointType: Gate"));
1919        assert!(yaml.contains("substrate: Observability"));
1920        assert!(yaml.contains("flakeRef: github:pleme-io/k8s"));
1921    }
1922
1923    // ─── Process::coordinates_or_defaults substrate pins ────────────────
1924    //
1925    // Pins the (namespace, name) coordinate-primitive family on the
1926    // (metadata slot × fallback shape) axis. Fail-before-pass-after
1927    // granularity: a regression that flipped either fallback string,
1928    // swapped the return-tuple axis order, or dropped the
1929    // `Option::as_deref` unwrap surfaces here rather than as silent
1930    // drift at every downstream annotation writer / claim-arbiter row
1931    // builder / render owner-metadata seed.
1932
1933    fn empty_spec() -> ProcessSpec {
1934        ProcessSpec {
1935            identity: IdentitySpec::default(),
1936            classification: Classification::gate_compute(),
1937            intent: Intent::default(),
1938            boundary: Default::default(),
1939            compliance: Default::default(),
1940            depends_on: vec![],
1941            signals: Default::default(),
1942            lifetime: Default::default(),
1943            routing: None,
1944            encapsulates: None,
1945            suspended: false,
1946        }
1947    }
1948
1949    #[test]
1950    fn default_namespace_constant_is_k8s_canonical_default() {
1951        // Pins the load-bearing convention that this primitive's
1952        // namespace fallback matches K8s's own implicit-namespace
1953        // spelling. A regression that renamed this to "kube-system"
1954        // or any other K8s-reserved name would silently misroute
1955        // every downstream namespaced-Api call on a Process without
1956        // a metadata.namespace.
1957        assert_eq!(Process::DEFAULT_NAMESPACE, "default");
1958    }
1959
1960    #[test]
1961    fn unnamed_placeholder_constant_matches_prior_annotation_writer_fallback() {
1962        // Pins the load-bearing convention that this primitive's name
1963        // fallback matches the exact spelling every annotation writer
1964        // (tatara-reconciler::ssapply::inject_annotations,
1965        // tatara-reconciler::render::render, and
1966        // tatara-reconciler::table_controller's claim-row builder)
1967        // was hand-authoring pre-lift ("unnamed", NOT "<unnamed>" or
1968        // ""). A regression that renamed this would break the
1969        // annotation-writer / claim-arbiter grep contract silently.
1970        assert_eq!(Process::UNNAMED_PLACEHOLDER, "unnamed");
1971    }
1972
1973    #[test]
1974    fn namespace_or_default_falls_back_when_metadata_namespace_is_none() {
1975        let mut p = Process::new("some-proc", empty_spec());
1976        p.metadata.namespace = None;
1977        assert_eq!(p.namespace_or_default(), Process::DEFAULT_NAMESPACE);
1978    }
1979
1980    #[test]
1981    fn namespace_or_default_returns_metadata_slice_when_some() {
1982        let mut p = Process::new("some-proc", empty_spec());
1983        p.metadata.namespace = Some("prod-app".into());
1984        assert_eq!(p.namespace_or_default(), "prod-app");
1985    }
1986
1987    #[test]
1988    fn name_or_placeholder_falls_back_when_metadata_name_is_none() {
1989        let mut p = Process::new("real-name", empty_spec());
1990        p.metadata.name = None;
1991        assert_eq!(p.name_or_placeholder(), Process::UNNAMED_PLACEHOLDER);
1992    }
1993
1994    #[test]
1995    fn name_or_placeholder_returns_metadata_slice_when_some() {
1996        let p = Process::new("api-gateway", empty_spec());
1997        assert_eq!(p.name_or_placeholder(), "api-gateway");
1998    }
1999
2000    #[test]
2001    fn coordinates_or_defaults_composes_both_halves() {
2002        // Both slots present — returns metadata slices in
2003        // (namespace, name) axis order.
2004        let mut p = Process::new("api", empty_spec());
2005        p.metadata.namespace = Some("staging".into());
2006        assert_eq!(p.coordinates_or_defaults(), ("staging", "api"));
2007    }
2008
2009    #[test]
2010    fn coordinates_or_defaults_falls_back_on_both_slots() {
2011        // Both slots None — returns (DEFAULT_NAMESPACE,
2012        // UNNAMED_PLACEHOLDER) in axis order.
2013        let mut p = Process::new("scratch", empty_spec());
2014        p.metadata.name = None;
2015        p.metadata.namespace = None;
2016        assert_eq!(
2017            p.coordinates_or_defaults(),
2018            (Process::DEFAULT_NAMESPACE, Process::UNNAMED_PLACEHOLDER)
2019        );
2020    }
2021
2022    #[test]
2023    fn coordinates_or_defaults_mixes_slotted_and_fallback_halves() {
2024        // Namespace set, name missing — the (namespace, name) tuple
2025        // pins each half independently. A regression that returned
2026        // BOTH fallbacks when EITHER metadata slot was None would
2027        // surface here rather than at every downstream reader.
2028        let mut p = Process::new("kept-name", empty_spec());
2029        p.metadata.namespace = Some("prod".into());
2030        assert_eq!(p.coordinates_or_defaults(), ("prod", "kept-name"));
2031
2032        // Name set, namespace missing — the peer corner.
2033        let mut q = Process::new("api", empty_spec());
2034        q.metadata.namespace = None;
2035        assert_eq!(
2036            q.coordinates_or_defaults(),
2037            (Process::DEFAULT_NAMESPACE, "api")
2038        );
2039    }
2040
2041    // ─── Process::qualified_ref substrate pins ─────────────────────────
2042    //
2043    // Pins the paired-projection + shape-composer chain
2044    // `coordinates_or_defaults() → qualified_process_ref(ns, name)` on
2045    // the (return-form × composition-depth) axis pair. Fail-before-
2046    // pass-after granularity: a regression that swapped the `<ns>/<name>`
2047    // axis order, dropped either half, drifted the fallback strings
2048    // between the paired-projection primitive and the shape composer, or
2049    // inserted a normalization step at only the composed site and not
2050    // the pair-returning primitive (or vice versa) surfaces here rather
2051    // than as silent operator-visible skew across the three pre-lift
2052    // `tatara-reconciler` sites (`render::render_routing`,
2053    // `render::render_export_jobs`, `table_controller::reconcile`)
2054    // whose downstream greps the reference shape verbatim (the
2055    // `PROCESS=<ref>` annotation seed on every emitted Ingress /
2056    // DNSEndpoint / export Job, the `ClaimRecord.holder` slot on the
2057    // stable-name claim registry).
2058
2059    #[test]
2060    fn qualified_ref_composes_ns_and_name_with_slash_when_both_slots_present() {
2061        // Happy path — both metadata slots populated. The composed
2062        // reference is EXACTLY `<ns>/<name>`, in that order, joined by
2063        // a single `/`. A regression that swapped the two axes at
2064        // this primitive would silently break every downstream
2065        // `PROCESS=<ref>` annotation grep + claim-registry lookup.
2066        let mut p = Process::new("api-gateway", empty_spec());
2067        p.metadata.namespace = Some("prod-app".into());
2068        assert_eq!(p.qualified_ref(), "prod-app/api-gateway");
2069    }
2070
2071    #[test]
2072    fn qualified_ref_falls_back_to_default_namespace_when_metadata_namespace_is_none() {
2073        // Namespace-fallback pin: an absent `metadata.namespace` rides
2074        // through `namespace_or_default()` → `DEFAULT_NAMESPACE`, so
2075        // the composed reference lands as `default/<name>`. Matches
2076        // what a pre-lift `qualified_process_ref(process.
2077        // coordinates_or_defaults())` composition produced.
2078        let mut p = Process::new("api-gateway", empty_spec());
2079        p.metadata.namespace = None;
2080        assert_eq!(p.qualified_ref(), "default/api-gateway");
2081    }
2082
2083    #[test]
2084    fn qualified_ref_falls_back_to_unnamed_placeholder_when_metadata_name_is_none() {
2085        // Name-fallback pin: an absent `metadata.name` rides through
2086        // `name_or_placeholder()` → `UNNAMED_PLACEHOLDER`, so the
2087        // composed reference lands as `<ns>/unnamed`. A pre-lift
2088        // consumer whose paired projection returned the placeholder
2089        // (annotation writer, render owner-metadata seed) sees the
2090        // exact same `<ns>/unnamed` shape post-lift, so downstream
2091        // greps keyed on the pre-metadata Process's reference match
2092        // bytewise.
2093        let mut p = Process::new("ignored", empty_spec());
2094        p.metadata.namespace = Some("staging".into());
2095        p.metadata.name = None;
2096        assert_eq!(p.qualified_ref(), "staging/unnamed");
2097    }
2098
2099    #[test]
2100    fn qualified_ref_falls_back_on_both_slots_when_both_metadata_are_none() {
2101        // Both slots absent → both fallbacks land in the composed
2102        // reference. The `default/unnamed` shape is what every pre-
2103        // lift caller produced when a Process fixture (test or
2104        // dynamic API response) surfaced without populated metadata;
2105        // pinning it here holds the primitive's contract against a
2106        // regression that dropped either fallback at only the
2107        // composed site.
2108        let mut p = Process::new("ignored", empty_spec());
2109        p.metadata.namespace = None;
2110        p.metadata.name = None;
2111        assert_eq!(
2112            p.qualified_ref(),
2113            format!(
2114                "{}/{}",
2115                Process::DEFAULT_NAMESPACE,
2116                Process::UNNAMED_PLACEHOLDER
2117            )
2118        );
2119    }
2120
2121    #[test]
2122    fn qualified_ref_matches_pre_lift_paired_composition_bytewise() {
2123        // Byte-identical parity with the exact pre-lift 2-step
2124        // composition every `tatara-reconciler` site hand-authored:
2125        // `let (ns, name) = process.coordinates_or_defaults(); let r
2126        // = qualified_process_ref(ns, name);`. Sweeps every metadata-
2127        // slot combination the three pre-lift consumers plausibly
2128        // encountered — both slots populated (steady state), one
2129        // slot absent (Process mid-fork before API-server metadata
2130        // stamp), both slots absent (dynamic API response / test
2131        // fixture) — so a regression that reshaped the composition at
2132        // the substrate primitive would surface here rather than as
2133        // silent drift at the three consumer sites.
2134        let fixtures: [(Option<&str>, Option<&str>); 4] = [
2135            (Some("prod-app"), Some("api-gateway")),
2136            (None, Some("api-gateway")),
2137            (Some("staging"), None),
2138            (None, None),
2139        ];
2140        for (ns_slot, name_slot) in fixtures {
2141            let mut p = Process::new(name_slot.unwrap_or("seed"), empty_spec());
2142            p.metadata.namespace = ns_slot.map(str::to_string);
2143            p.metadata.name = name_slot.map(str::to_string);
2144            let via_primitive = p.qualified_ref();
2145            let (ns, name) = p.coordinates_or_defaults();
2146            let via_paired = crate::qualified_process_ref(ns, name);
2147            assert_eq!(
2148                via_primitive, via_paired,
2149                "qualified_ref must be byte-identical to the pre-lift \
2150                 paired composition on (ns={ns_slot:?}, name={name_slot:?})"
2151            );
2152        }
2153    }
2154
2155    #[test]
2156    fn qualified_ref_composes_from_the_shared_coordinates_or_defaults_owner() {
2157        // Composition invariant: the composed reference decomposes at
2158        // the single `/` separator into EXACTLY the (ns, name) pair
2159        // `coordinates_or_defaults` returns. A regression that
2160        // introduced a per-callsite normalization at the shape
2161        // composer (URL-escape, case-fold, path-normalize) or that
2162        // pulled the pair from a different metadata source than the
2163        // paired-projection primitive would surface here rather than
2164        // at every downstream reference-shape grep.
2165        let mut p = Process::new("api-gateway", empty_spec());
2166        p.metadata.namespace = Some("prod-app".into());
2167        let composed = p.qualified_ref();
2168        let (ns, name) = p.coordinates_or_defaults();
2169        let (composed_ns, composed_name) = composed.split_once('/').unwrap();
2170        assert_eq!(composed_ns, ns);
2171        assert_eq!(composed_name, name);
2172    }
2173
2174    // ─── Process::owned_coordinates_or_err substrate pins ──────────────
2175    //
2176    // Pins the owned + name-required peer of the coordinate-primitive
2177    // family on the (return-form × name gate) axis pair. Fail-before-
2178    // pass-after granularity: a regression that flipped the namespace
2179    // fallback string, dropped the `Option::clone` unwrap, changed the
2180    // return-tuple axis order, or altered the "Process has no
2181    // metadata.name" error wording surfaces here rather than as silent
2182    // drift at every pre-lift caller (10 sites in
2183    // `tatara-reconciler::phase_machine` + 2 sites in
2184    // `tatara-reconciler::signals` pre-lift).
2185
2186    #[test]
2187    fn owned_coordinates_or_err_returns_owned_strings_when_both_slots_present() {
2188        // Happy path — both slots populated, method returns owned
2189        // Strings in (namespace, name) axis order.
2190        let mut p = Process::new("api-gateway", empty_spec());
2191        p.metadata.namespace = Some("prod-app".into());
2192        let (ns, name) = p.owned_coordinates_or_err().unwrap();
2193        assert_eq!(ns, "prod-app");
2194        assert_eq!(name, "api-gateway");
2195        // Ownership pin: type inference above binds ns/name as
2196        // owned Strings — a regression that returned &str would
2197        // fail to compile at the following .push() call. This
2198        // holds the "owned" half of the primitive's contract.
2199        let mut owned_ns = ns;
2200        owned_ns.push_str("-mutated");
2201        assert_eq!(owned_ns, "prod-app-mutated");
2202    }
2203
2204    #[test]
2205    fn owned_coordinates_or_err_falls_back_on_namespace_but_returns_owned_name() {
2206        // Namespace absent → DEFAULT_NAMESPACE. Name present → owned.
2207        let p = Process::new("api", empty_spec());
2208        // Process::new leaves metadata.namespace = None by default.
2209        let (ns, name) = p.owned_coordinates_or_err().unwrap();
2210        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
2211        assert_eq!(name, "api");
2212    }
2213
2214    #[test]
2215    fn owned_coordinates_or_err_errors_when_metadata_name_absent_regardless_of_namespace() {
2216        // Name absent → Err, REGARDLESS of whether the namespace is
2217        // populated. The name gate is strictly on `metadata.name` and
2218        // does NOT fall back to `Self::UNNAMED_PLACEHOLDER` (that
2219        // fallback is on the peer `coordinates_or_defaults`, which
2220        // exists precisely for consumers that can tolerate a
2221        // display placeholder).
2222        for ns_slot in [None, Some("prod".to_string())] {
2223            let mut p = Process::new("scratch", empty_spec());
2224            p.metadata.name = None;
2225            p.metadata.namespace = ns_slot.clone();
2226            let err = p.owned_coordinates_or_err().unwrap_err();
2227            assert!(
2228                err.to_string().contains("metadata.name"),
2229                "err on missing name (ns={ns_slot:?}) should mention metadata.name; got {err}"
2230            );
2231        }
2232    }
2233
2234    #[test]
2235    fn owned_coordinates_or_err_error_message_matches_pre_lift_reconciler_wording() {
2236        // Load-bearing wording pin — every pre-lift `tatara-reconciler`
2237        // helper (`phase_machine::namespace_and_name`,
2238        // `signals::ingest`, `signals::consume_effect`) errored with
2239        // EXACTLY this wording. Post-lift the substrate owner produces
2240        // the same wording so log-line / test greps that anchored on
2241        // it keep matching, and no operator-visible message drift
2242        // lands as a side effect of the substrate move.
2243        let mut p = Process::new("scratch", empty_spec());
2244        p.metadata.name = None;
2245        let err = p.owned_coordinates_or_err().unwrap_err();
2246        assert_eq!(err.to_string(), "Process has no metadata.name");
2247    }
2248
2249    #[test]
2250    fn owned_coordinates_or_err_namespace_fallback_matches_default_namespace_const() {
2251        // Byte-identity pin between the owned form's namespace
2252        // fallback and the workspace-wide `DEFAULT_NAMESPACE` const.
2253        // A regression that spelled this fallback as any other
2254        // string ("kube-system", "", "default-ns") would silently
2255        // misroute every downstream namespaced-Api call on a
2256        // Process without a metadata.namespace — surfaces here
2257        // rather than at every kube-rs API caller.
2258        let mut p = Process::new("api", empty_spec());
2259        p.metadata.namespace = None;
2260        let (ns, _) = p.owned_coordinates_or_err().unwrap();
2261        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
2262    }
2263
2264    #[test]
2265    fn owned_coordinates_or_err_matches_pre_lift_reconciler_helper_shape() {
2266        // Byte-identical parity pin between the owned + name-required
2267        // primitive here and the pre-lift `tatara-reconciler` helper
2268        // shape — the exact 2-slot unwrap chain each pre-lift caller
2269        // spelled by hand:
2270        //
2271        //   let ns = p.metadata.namespace.clone().unwrap_or_else(|| "default".into());
2272        //   let name = p.metadata.name.clone().ok_or_else(|| anyhow!(...))?;
2273        //   Ok((ns, name))
2274        //
2275        // Sweeps every corner every callsite plausibly encounters
2276        // (both slots present, namespace absent, name absent, both
2277        // absent). A regression that inserted a normalization step
2278        // at the primitive that the pre-lift chain does NOT apply —
2279        // or vice versa — surfaces here rather than as silent drift
2280        // between the 12 pre-lift consumer callsites and the ONE
2281        // substrate owner they now route through.
2282        fn pre_lift(p: &Process) -> anyhow::Result<(String, String)> {
2283            let ns = p
2284                .metadata
2285                .namespace
2286                .clone()
2287                .unwrap_or_else(|| "default".into());
2288            let name = p
2289                .metadata
2290                .name
2291                .clone()
2292                .ok_or_else(|| anyhow::anyhow!("Process has no metadata.name"))?;
2293            Ok((ns, name))
2294        }
2295        // Both present.
2296        let mut p = Process::new("api", empty_spec());
2297        p.metadata.namespace = Some("prod".into());
2298        assert_eq!(p.owned_coordinates_or_err().unwrap(), pre_lift(&p).unwrap());
2299        // Namespace absent.
2300        let p = Process::new("api", empty_spec());
2301        assert_eq!(p.owned_coordinates_or_err().unwrap(), pre_lift(&p).unwrap());
2302        // Name absent → both variants error with the same wording.
2303        let mut p = Process::new("api", empty_spec());
2304        p.metadata.name = None;
2305        p.metadata.namespace = Some("prod".into());
2306        assert_eq!(
2307            p.owned_coordinates_or_err().unwrap_err().to_string(),
2308            pre_lift(&p).unwrap_err().to_string(),
2309        );
2310        // Both absent → still errors on the name gate.
2311        let mut p = Process::new("api", empty_spec());
2312        p.metadata.name = None;
2313        p.metadata.namespace = None;
2314        assert_eq!(
2315            p.owned_coordinates_or_err().unwrap_err().to_string(),
2316            pre_lift(&p).unwrap_err().to_string(),
2317        );
2318    }
2319
2320    #[test]
2321    fn owned_coordinates_or_err_axis_order_matches_coordinates_or_defaults() {
2322        // Cross-primitive coherence pin between the owned + name-
2323        // required form and the borrow + name-defaulted peer:
2324        // (namespace, name) axis order is IDENTICAL across both
2325        // return-forms. A regression that swapped the tuple slots on
2326        // only ONE of the two primitives would silently misroute
2327        // every consumer that picked between the two forms based on
2328        // its callsite's ownership needs. The pin re-reads both
2329        // primitives at test time so the equality holds iff both
2330        // live paths are the current implementation.
2331        let mut p = Process::new("app", empty_spec());
2332        p.metadata.namespace = Some("infra".into());
2333        let (borrow_ns, borrow_name) = p.coordinates_or_defaults();
2334        let (owned_ns, owned_name) = p.owned_coordinates_or_err().unwrap();
2335        assert_eq!(owned_ns, borrow_ns);
2336        assert_eq!(owned_name, borrow_name);
2337        // Explicit slot labels — pins the (namespace, name) axis
2338        // order as opposed to (name, namespace).
2339        assert_eq!(owned_ns, "infra"); // NOT "app"
2340        assert_eq!(owned_name, "app"); // NOT "infra"
2341    }
2342
2343    // ─── Process::coordinates_or_none substrate pins ──────────────────
2344    //
2345    // Pins the borrow + name-required peer of the coordinate-primitive
2346    // family on the (return-form × name-gate) axis pair. Closes the
2347    // corner previously left open (borrow + name-required) so the
2348    // three consumer shapes (child-Process delete-fan-out at
2349    // `phase_machine::handle_exiting`, claim-arbiter probe at
2350    // `phase_machine::process_holds_any_claim`, any future non-fatal
2351    // skip site) route through ONE primitive rather than three hand-
2352    // authored empty-string / `unwrap_or_default()` sentinel chains.
2353    // Fail-before-pass-after granularity: a regression that flipped
2354    // the namespace fallback, swapped the return-tuple axis order,
2355    // returned an owned form, or promoted a missing name to an error
2356    // rather than `None` surfaces here rather than as silent drift at
2357    // every borrow + name-required consumer.
2358
2359    #[test]
2360    fn coordinates_or_none_returns_slices_when_both_slots_present() {
2361        // Happy path — both slots populated, method returns borrowed
2362        // (&str, &str) in (namespace, name) axis order wrapped in
2363        // `Some`.
2364        let mut p = Process::new("api-gateway", empty_spec());
2365        p.metadata.namespace = Some("prod-app".into());
2366        let (ns, name) = p.coordinates_or_none().expect("Some when name set");
2367        assert_eq!(ns, "prod-app");
2368        assert_eq!(name, "api-gateway");
2369    }
2370
2371    #[test]
2372    fn coordinates_or_none_falls_back_on_namespace_but_returns_name_slice() {
2373        // Namespace absent → DEFAULT_NAMESPACE (shared with the peer
2374        // `coordinates_or_defaults` + `namespace_or_default`). Name
2375        // present → the metadata slice, wrapped in `Some`.
2376        let mut p = Process::new("api", empty_spec());
2377        p.metadata.namespace = None;
2378        let (ns, name) = p.coordinates_or_none().expect("Some when name set");
2379        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
2380        assert_eq!(name, "api");
2381    }
2382
2383    #[test]
2384    fn coordinates_or_none_returns_none_when_metadata_name_absent_regardless_of_namespace() {
2385        // Name absent → `None`, REGARDLESS of whether the namespace
2386        // slot is populated. The name gate is strictly on
2387        // `metadata.name` and does NOT fall back to
2388        // `Self::UNNAMED_PLACEHOLDER` (that fallback is on the peer
2389        // `coordinates_or_defaults`, which exists precisely for
2390        // consumers that tolerate a display placeholder). Peer to
2391        // `owned_coordinates_or_err_errors_when_metadata_name_absent_regardless_of_namespace`
2392        // on the sibling primitive; a regression that widened THIS
2393        // form to substitute the placeholder while leaving the owned
2394        // form strict would silently drift the two borrow-form
2395        // primitives out of the coherence the family carries.
2396        for ns_slot in [None, Some("prod".to_string())] {
2397            let mut p = Process::new("scratch", empty_spec());
2398            p.metadata.name = None;
2399            p.metadata.namespace = ns_slot.clone();
2400            assert!(
2401                p.coordinates_or_none().is_none(),
2402                "coordinates_or_none must be None on missing name (ns={ns_slot:?})",
2403            );
2404        }
2405    }
2406
2407    #[test]
2408    fn coordinates_or_none_namespace_fallback_matches_default_namespace_const() {
2409        // Byte-identity pin between the borrow + name-required form's
2410        // namespace fallback and the workspace-wide `DEFAULT_NAMESPACE`
2411        // const. Sibling to
2412        // `owned_coordinates_or_err_namespace_fallback_matches_default_namespace_const`
2413        // on the peer primitive — the two forms MUST substitute the
2414        // same fallback string, else a consumer that switches between
2415        // them based on its ownership need silently observes a
2416        // different namespace-fallback shape as a side effect.
2417        let mut p = Process::new("api", empty_spec());
2418        p.metadata.namespace = None;
2419        let (ns, _) = p.coordinates_or_none().unwrap();
2420        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
2421    }
2422
2423    #[test]
2424    fn coordinates_or_none_axis_order_matches_coordinates_or_defaults_when_name_present() {
2425        // Cross-primitive coherence pin between the two borrow-form
2426        // primitives: when the name is present, the (namespace, name)
2427        // return-tuple axis order is IDENTICAL across the two forms,
2428        // and the returned slices are the SAME `&str` view onto the
2429        // same metadata slots. A regression that swapped the tuple
2430        // slots on ONE form would silently misroute every consumer
2431        // that picked between the two forms based on its name-gate
2432        // need. The pin re-reads both primitives at test time so the
2433        // equality holds iff both live paths are the current
2434        // implementation.
2435        let mut p = Process::new("app", empty_spec());
2436        p.metadata.namespace = Some("infra".into());
2437        let (defaulted_ns, defaulted_name) = p.coordinates_or_defaults();
2438        let (required_ns, required_name) = p.coordinates_or_none().unwrap();
2439        assert_eq!(defaulted_ns, required_ns);
2440        assert_eq!(defaulted_name, required_name);
2441        // Explicit slot labels — pins the (namespace, name) axis order
2442        // as opposed to (name, namespace).
2443        assert_eq!(required_ns, "infra"); // NOT "app"
2444        assert_eq!(required_name, "app"); // NOT "infra"
2445    }
2446
2447    #[test]
2448    fn coordinates_or_none_axis_pair_diverges_from_coordinates_or_defaults_on_missing_name() {
2449        // Divergence pin between the two borrow-form primitives when
2450        // the name gate fires: `coordinates_or_defaults` substitutes
2451        // the display placeholder AND still returns a tuple;
2452        // `coordinates_or_none` returns `None`. A regression that
2453        // collapsed the two behaviors (either by dropping the gate
2454        // from the required form or by adding a `None` corner to the
2455        // defaulted form) would blur the axis pair's whole reason to
2456        // exist as two peer primitives.
2457        let mut p = Process::new("scratch", empty_spec());
2458        p.metadata.name = None;
2459        p.metadata.namespace = Some("prod".into());
2460        // Defaulted form: substitutes placeholder, no gate.
2461        assert_eq!(
2462            p.coordinates_or_defaults(),
2463            ("prod", Process::UNNAMED_PLACEHOLDER)
2464        );
2465        // Required form: gate fires, `None`.
2466        assert!(p.coordinates_or_none().is_none());
2467    }
2468
2469    #[test]
2470    fn coordinates_or_none_matches_pre_lift_reconciler_helper_shape() {
2471        // Byte-identical parity pin between the borrow + name-required
2472        // primitive here and the pre-lift `tatara-reconciler` helper
2473        // shapes — the exact 2-slot unwrap + gate chains each pre-lift
2474        // caller spelled by hand (`phase_machine::process_holds_any_claim`
2475        // spelled it as `unwrap_or("")` + `is_empty` early-return;
2476        // `phase_machine::handle_exiting`'s child-fan-out spelled it
2477        // as `unwrap_or_default()` + implicit no-op delete on the
2478        // empty API-path). Sweeps every corner every callsite plausibly
2479        // encounters (both slots present, namespace absent, name
2480        // absent + ns present, both absent). A regression that
2481        // inserted a normalization step at the primitive the pre-lift
2482        // chain does NOT apply — or vice versa — surfaces here rather
2483        // than as silent drift between the pre-lift consumer sites
2484        // and the ONE substrate owner they now route through.
2485        fn pre_lift_holds_any_claim(p: &Process) -> Option<(&str, &str)> {
2486            let ns = p.metadata.namespace.as_deref().unwrap_or("default");
2487            let name = p.metadata.name.as_deref().unwrap_or("");
2488            if name.is_empty() {
2489                return None;
2490            }
2491            Some((ns, name))
2492        }
2493        // Both present.
2494        let mut p = Process::new("api", empty_spec());
2495        p.metadata.namespace = Some("prod".into());
2496        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
2497        // Namespace absent.
2498        let p = Process::new("api", empty_spec());
2499        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
2500        // Name absent → both variants return `None` regardless of ns.
2501        let mut p = Process::new("api", empty_spec());
2502        p.metadata.name = None;
2503        p.metadata.namespace = Some("prod".into());
2504        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
2505        // Both absent → still `None` on the name gate.
2506        let mut p = Process::new("api", empty_spec());
2507        p.metadata.name = None;
2508        p.metadata.namespace = None;
2509        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
2510    }
2511
2512    #[test]
2513    fn coordinates_or_none_axis_order_matches_owned_coordinates_or_err_on_happy_path() {
2514        // Cross-primitive coherence pin at the sibling corner: when
2515        // BOTH slots are present, the borrow + name-required form
2516        // (this method) and the owned + name-required peer
2517        // (`owned_coordinates_or_err`) return the SAME `(ns, name)`
2518        // pair — the axis order is IDENTICAL and neither primitive
2519        // silently applies a normalization the other omits. A
2520        // regression that skewed one form's normalization would
2521        // surface here rather than as silent drift between the two
2522        // name-required corners of the primitive family.
2523        let mut p = Process::new("app", empty_spec());
2524        p.metadata.namespace = Some("infra".into());
2525        let (borrow_ns, borrow_name) = p.coordinates_or_none().unwrap();
2526        let (owned_ns, owned_name) = p.owned_coordinates_or_err().unwrap();
2527        assert_eq!(borrow_ns, owned_ns.as_str());
2528        assert_eq!(borrow_name, owned_name.as_str());
2529    }
2530
2531    #[test]
2532    fn coordinates_or_defaults_axis_order_matches_qualified_process_ref() {
2533        // Pins the load-bearing convention that the return-tuple
2534        // axis order is (namespace, name) — the exact positional
2535        // argument order the substrate's paired-composer primitive
2536        // `tatara_reconciler::ssapply::qualified_process_ref(ns,
2537        // name)` consumes. A regression that swapped the tuple
2538        // slots would silently misroute every annotation writer /
2539        // claim-arbiter row / owner-metadata seed built by feeding
2540        // this pair into the composer — every downstream `<ns>/
2541        // <name>` grep would suddenly see `<name>/<ns>`. The test
2542        // verifies the tuple's first slot is what a hand-authored
2543        // `.metadata.namespace.as_deref()...` produced pre-lift, and
2544        // the second slot is what `.metadata.name.as_deref()...`
2545        // produced.
2546        let mut p = Process::new("app", empty_spec());
2547        p.metadata.namespace = Some("infra".into());
2548        let (ns, name) = p.coordinates_or_defaults();
2549        assert_eq!(ns, "infra"); // NOT "app"
2550        assert_eq!(name, "app"); // NOT "infra"
2551    }
2552
2553    // ─── Process::annotation substrate pins ────────────────────────────
2554    //
2555    // Pins the borrow-form annotation-lookup primitive that owns the
2556    // 3-line `.metadata.annotations.as_ref().and_then(|m| m.get(KEY))`
2557    // chain three hand-authored sites restated by hand pre-lift:
2558    // `tatara-reconciler::signals::ingest` (SIGNAL),
2559    // `tatara-reconciler::phase_machine::released_from_annotation`
2560    // (RELEASED_FROM), and
2561    // `tatara-pool-reconciler::controller_pool::process_belongs_to_pool`
2562    // (POOL). Fail-before-pass-after granularity: a regression that
2563    // widened the missing-`annotations` corner (returning `Some("")`
2564    // instead of `None`), promoted a missing key to an error, dropped
2565    // the borrow-form return, or changed the two swallowed corners'
2566    // shared collapse to `None` surfaces here rather than as silent
2567    // drift at the three consumer sites.
2568    fn process_with_annotation(key: &str, value: &str) -> Process {
2569        let mut p = Process::new("some-proc", empty_spec());
2570        let mut anns = std::collections::BTreeMap::new();
2571        anns.insert(key.to_string(), value.to_string());
2572        p.metadata.annotations = Some(anns);
2573        p
2574    }
2575
2576    #[test]
2577    fn annotation_returns_none_when_metadata_annotations_is_none() {
2578        // Missing-`annotations` corner: a Process with no annotations
2579        // block at all returns `None` for every key. Peer to
2580        // `observed_flux_resources_returns_empty_slice_when_status_is_none`
2581        // on the status-projection axis; both primitives collapse the
2582        // outer `Option` corner rather than requiring each consumer
2583        // to spell the guard by hand.
2584        let mut p = Process::new("scratch", empty_spec());
2585        p.metadata.annotations = None;
2586        assert!(p.annotation("tatara.pleme.io/signal").is_none());
2587        assert!(p.annotation("tatara.pleme.io/pool").is_none());
2588        assert!(p.annotation("").is_none());
2589    }
2590
2591    #[test]
2592    fn annotation_returns_none_when_key_absent_from_populated_map() {
2593        // Missing-key corner: annotations block populated with OTHER
2594        // keys returns `None` for the queried key. Symmetric with the
2595        // missing-`annotations` corner — both corners collapse to the
2596        // same `None`, matching the pre-lift `.and_then(...)`
2597        // behavior every consumer relied on.
2598        let p = process_with_annotation("tatara.pleme.io/other", "value");
2599        assert!(p.annotation("tatara.pleme.io/signal").is_none());
2600        assert!(p.annotation("").is_none());
2601    }
2602
2603    #[test]
2604    fn annotation_returns_borrowed_slice_when_key_present() {
2605        // Happy path: annotations block populated + key present →
2606        // `Some(&str)` borrowed from the underlying `String` in the
2607        // map. A regression that returned an owned `String` (defeating
2608        // the primitive's role as a zero-copy projection) would
2609        // surface at the lifetime of the returned reference — the
2610        // `&str` outlives the borrow of `&p` here.
2611        let p = process_with_annotation("tatara.pleme.io/signal", "SIGHUP");
2612        assert_eq!(p.annotation("tatara.pleme.io/signal"), Some("SIGHUP"));
2613    }
2614
2615    #[test]
2616    fn annotation_returns_borrowed_empty_string_slice_when_value_is_empty() {
2617        // Edge corner between the missing-key `None` and the present-
2618        // key `Some("")` — a Process whose annotation is EXPLICITLY
2619        // set to an empty string returns `Some("")`, NOT `None`. A
2620        // regression that normalized the empty-string value to `None`
2621        // (a plausible "defensive" simplification) would silently
2622        // reshape the corner every callsite pre-lift kept distinct via
2623        // `.cloned().unwrap_or_default()` (which collapses BOTH to
2624        // `""`) or `.map(String::as_str)` (which keeps them distinct
2625        // as `None` vs `Some("")`).
2626        let p = process_with_annotation("tatara.pleme.io/signal", "");
2627        assert_eq!(p.annotation("tatara.pleme.io/signal"), Some(""));
2628    }
2629
2630    #[test]
2631    fn annotation_is_a_pure_projection() {
2632        // Purity pin — repeated calls return equal results and the
2633        // primitive does not mutate `self`. Peer to
2634        // `observed_flux_resources_is_a_pure_projection` on the
2635        // status-projection axis.
2636        let p = process_with_annotation("tatara.pleme.io/released-from", "Attested");
2637        let a = p.annotation("tatara.pleme.io/released-from");
2638        let b = p.annotation("tatara.pleme.io/released-from");
2639        assert_eq!(a, b);
2640        assert_eq!(a, Some("Attested"));
2641    }
2642
2643    #[test]
2644    fn annotation_matches_pre_lift_reconciler_chain_shape() {
2645        // Byte-identical parity pin between the borrow-form primitive
2646        // here and the pre-lift `tatara-reconciler` / `tatara-pool-
2647        // reconciler` chain shape — the exact 3-line
2648        // `.metadata.annotations.as_ref().and_then(|m| m.get(KEY))
2649        // .map(String::as_str)` incantation each pre-lift caller
2650        // spelled by hand (three variants of tail collapsed onto ONE
2651        // borrow-form primitive here; each caller reapplies its own
2652        // tail at its own site). Sweeps every corner (missing
2653        // annotations map, missing key, present key with value,
2654        // present key with empty value) so a regression that inserted
2655        // a normalization at the primitive the pre-lift chain does
2656        // NOT apply — or vice versa — surfaces here rather than as
2657        // silent drift between the ONE substrate owner and the three
2658        // consumer sites.
2659        fn pre_lift<'a>(p: &'a Process, key: &str) -> Option<&'a str> {
2660            p.metadata
2661                .annotations
2662                .as_ref()
2663                .and_then(|m| m.get(key))
2664                .map(String::as_str)
2665        }
2666        // Missing annotations map.
2667        let mut p = Process::new("x", empty_spec());
2668        p.metadata.annotations = None;
2669        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
2670        // Missing key in populated map.
2671        let p = process_with_annotation("other", "v");
2672        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
2673        // Present key with non-empty value.
2674        let p = process_with_annotation("k", "v");
2675        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
2676        // Present key with explicitly-empty value — the corner
2677        // `.cloned().unwrap_or_default()` collapses to `""` post-tail
2678        // but the primitive-level shape stays `Some("")`.
2679        let p = process_with_annotation("k", "");
2680        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
2681    }
2682
2683    #[test]
2684    fn annotation_composes_owned_tail_matching_pre_lift_signals_ingest() {
2685        // Pins the exact tail shape `tatara-reconciler::signals::
2686        // ingest` composed pre-lift: an `Option<String>` for the
2687        // downstream `let Some(raw) = raw else { ... }` guard.
2688        // Post-lift the callsite composes `.map(str::to_string)` at
2689        // its own site; this test pins the composition matches the
2690        // pre-lift `.cloned()` tail byte-for-byte on both corners the
2691        // consumer's downstream distinguishes (annotation present →
2692        // `Some(String)`; absent → `None`).
2693        let p = process_with_annotation("tatara.pleme.io/signal", "SIGUSR1");
2694        assert_eq!(
2695            p.annotation("tatara.pleme.io/signal").map(str::to_string),
2696            Some("SIGUSR1".to_string())
2697        );
2698        let mut q = Process::new("y", empty_spec());
2699        q.metadata.annotations = None;
2700        assert_eq!(
2701            q.annotation("tatara.pleme.io/signal").map(str::to_string),
2702            None
2703        );
2704    }
2705
2706    #[test]
2707    fn annotation_composes_default_tail_matching_pre_lift_released_from() {
2708        // Pins the exact tail shape
2709        // `tatara-reconciler::phase_machine::released_from_annotation`
2710        // composed pre-lift: a bare `String` via `.cloned()
2711        // .unwrap_or_default()` for the downstream
2712        // `match v.as_str()` dispatch. Post-lift the callsite matches
2713        // directly on `Option<&str>` (Some("Failed") vs _); this test
2714        // pins that the borrow-form primitive plus the `.unwrap_or("")`
2715        // fallback reproduces the pre-lift bare-string shape on both
2716        // corners.
2717        let p = process_with_annotation("tatara.pleme.io/released-from", "Failed");
2718        assert_eq!(
2719            p.annotation("tatara.pleme.io/released-from").unwrap_or(""),
2720            "Failed"
2721        );
2722        let mut q = Process::new("y", empty_spec());
2723        q.metadata.annotations = None;
2724        assert_eq!(
2725            q.annotation("tatara.pleme.io/released-from").unwrap_or(""),
2726            ""
2727        );
2728    }
2729
2730    #[test]
2731    fn annotation_composes_borrow_equality_tail_matching_pre_lift_pool() {
2732        // Pins the exact tail shape `tatara-pool-reconciler::
2733        // controller_pool::process_belongs_to_pool` composed pre-lift:
2734        // an `Option<&str>` compared with `== Some(pool_name)` for the
2735        // membership gate. Post-lift the callsite composes
2736        // `p.annotation(POOL) == Some(pool_name)` verbatim; this test
2737        // pins that the borrow-form primitive returns exactly the
2738        // shape the equality gate expects.
2739        let p = process_with_annotation("tatara.pleme.io/pool", "demo-pool");
2740        assert_eq!(
2741            p.annotation("tatara.pleme.io/pool") == Some("demo-pool"),
2742            true
2743        );
2744        assert_eq!(p.annotation("tatara.pleme.io/pool") == Some("other"), false);
2745    }
2746
2747    // ─── Process::uid_or_empty substrate pins ──────────────────────────
2748    //
2749    // Pins the borrow-form metadata-projection primitive on the
2750    // `metadata.uid` axis that owns the `.metadata.uid.as_deref()
2751    // .unwrap_or("")` chain the two hand-authored
2752    // `tatara-reconciler::render` sites (`render_routing` +
2753    // `render_export_jobs`) restated by hand pre-lift. Peer to the
2754    // sibling `namespace_or_default_*` + `name_or_placeholder_*` pin
2755    // families on the metadata-slot × fallback-shape axis; all three
2756    // primitives return borrows of an owned-metadata slot with a slot-
2757    // specific fallback baked in (`"default"` for namespace, `"unnamed"`
2758    // for name, `""` for uid — the load-bearing gate value for
2759    // `owner_references_json`'s `is_empty` check). Fail-before-pass-
2760    // after granularity: `uid_or_empty` did not exist pre-lift, so any
2761    // test invoking it fails to compile pre-lift and passes post-lift.
2762
2763    #[test]
2764    fn uid_or_empty_returns_empty_string_when_metadata_uid_is_none() {
2765        // Empty-slot corner pin: the primitive collapses the no-uid
2766        // case to `""`, matching the pre-lift `.as_deref().unwrap_or("")`
2767        // chain's `""` byte-identically at both render consumer sites.
2768        // Semantically corresponds to a Process pre-metadata (fixtured
2769        // in tests, or caught mid-Forking before the API server has
2770        // stamped a `uid`); the downstream `owner_references_json`
2771        // composer gates on this exact `""` sentinel to stamp
2772        // `metadata.ownerReferences: []` rather than emit an owner-ref
2773        // pointing at a placeholder uid.
2774        let mut p = Process::new("scratch", empty_spec());
2775        p.metadata.uid = None;
2776        assert_eq!(p.uid_or_empty(), "");
2777    }
2778
2779    #[test]
2780    fn uid_or_empty_returns_borrowed_str_when_slot_is_populated() {
2781        // Happy-path pin: with a populated `metadata.uid` slot, the
2782        // primitive returns a borrowed `&str` whose contents match the
2783        // persisted `String`. A regression that reshaped / normalized
2784        // / cross-cluster-stripped the uid without touching this pin
2785        // would surface here rather than as silent skew at the two
2786        // `owner_references_json(name, uid)` emitters on the SAME
2787        // Process.
2788        let mut p = Process::new("owned-proc", empty_spec());
2789        p.metadata.uid = Some("uid-abc-123".into());
2790        assert_eq!(p.uid_or_empty(), "uid-abc-123");
2791    }
2792
2793    #[test]
2794    fn uid_or_empty_returns_empty_string_when_slot_is_explicitly_empty_string() {
2795        // Corner between the missing-slot `None` and the explicitly-
2796        // empty-string `Some("")` — both collapse to `""` at the
2797        // primitive because the downstream gate at
2798        // `owner_references_json` treats `.is_empty()` uniformly (the
2799        // empty-slot posture is what the whole primitive family
2800        // encodes: "no admissible owner reference, stamp `[]`"). A
2801        // regression that discriminated the two corners (returning a
2802        // sentinel `"<none>"` for the missing slot but `""` for the
2803        // explicit slot) would break the composition with
2804        // `owner_references_json` at the exactly-two-corner gate.
2805        let mut p = Process::new("owned-proc", empty_spec());
2806        p.metadata.uid = Some(String::new());
2807        assert_eq!(p.uid_or_empty(), "");
2808    }
2809
2810    #[test]
2811    fn uid_or_empty_is_a_zero_copy_borrow_projection() {
2812        // Borrow-discipline pin: the returned `&str` borrows the
2813        // persisted `String`'s underlying byte buffer in place — NOT
2814        // a fresh allocation or a clone. A regression that switched
2815        // the projection to an owned `String` (via `.clone()` or a
2816        // `format!` wrap) would defeat the zero-copy contract the
2817        // lift's primary strict-widening delivers, and would surface
2818        // here via pointer-identity comparison.
2819        let mut p = Process::new("owned-proc", empty_spec());
2820        p.metadata.uid = Some("uid-borrow-pin".into());
2821        let slice = p.uid_or_empty();
2822        assert!(std::ptr::eq(
2823            slice.as_ptr(),
2824            p.metadata.uid.as_ref().unwrap().as_ptr()
2825        ));
2826    }
2827
2828    #[test]
2829    fn uid_or_empty_is_a_pure_projection() {
2830        // Purity pin — repeated calls return byte-identical slices
2831        // (same pointer, same length). A regression that introduced
2832        // state (a lazy-cached normalized slot, a first-call
2833        // canonicalization pass) would surface here rather than as
2834        // silent drift between the two render consumer sites on the
2835        // SAME Process within one render pass.
2836        let mut p = Process::new("owned-proc", empty_spec());
2837        p.metadata.uid = Some("uid-pure".into());
2838        let a = p.uid_or_empty();
2839        let b = p.uid_or_empty();
2840        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
2841        assert_eq!(a.len(), b.len());
2842    }
2843
2844    #[test]
2845    fn uid_or_empty_matches_pre_lift_render_chain_shape() {
2846        // Byte-identical parity pin between the borrow-form primitive
2847        // here and the pre-lift `tatara-reconciler::render` chain shape
2848        // — the exact `.metadata.uid.as_deref().unwrap_or("")`
2849        // incantation both `render_routing` (line 514) and
2850        // `render_export_jobs` (line 653) spelled by hand pre-lift.
2851        // Sweeps every corner (missing uid slot, populated uid slot,
2852        // explicitly-empty uid slot) so a regression that inserted a
2853        // normalization the pre-lift chain does NOT apply — or vice
2854        // versa — surfaces here rather than as silent drift between
2855        // the ONE substrate owner and the two consumer sites.
2856        fn pre_lift(p: &Process) -> &str {
2857            p.metadata.uid.as_deref().unwrap_or("")
2858        }
2859        // Missing slot.
2860        let mut p = Process::new("x", empty_spec());
2861        p.metadata.uid = None;
2862        assert_eq!(p.uid_or_empty(), pre_lift(&p));
2863        // Populated slot.
2864        let mut p = Process::new("x", empty_spec());
2865        p.metadata.uid = Some("uid-42".into());
2866        assert_eq!(p.uid_or_empty(), pre_lift(&p));
2867        // Explicitly-empty slot.
2868        let mut p = Process::new("x", empty_spec());
2869        p.metadata.uid = Some(String::new());
2870        assert_eq!(p.uid_or_empty(), pre_lift(&p));
2871    }
2872
2873    #[test]
2874    fn uid_or_empty_composes_with_owner_references_json_empty_gate() {
2875        // Cross-primitive composition pin — the empty-string sentinel
2876        // this primitive returns for the missing-uid corner is EXACTLY
2877        // the sentinel the sibling substrate composer
2878        // `owner_references_json(name, uid)` gates on to stamp
2879        // `metadata.ownerReferences: []`. A regression that changed
2880        // the sentinel at either end (this primitive returning
2881        // `"<none>"`, `owner_references_json` gating on `uid == "0"`
2882        // instead of `uid.is_empty()`) would break the composition
2883        // and surface here rather than as an operator-observed
2884        // orphan resource after apply.
2885        let mut p = Process::new("x", empty_spec());
2886        p.metadata.uid = None;
2887        let refs = crate::owner_references_json("some-name", p.uid_or_empty());
2888        assert!(
2889            refs.is_empty(),
2890            "empty-uid corner must produce empty owner-refs array"
2891        );
2892
2893        p.metadata.uid = Some("real-uid".into());
2894        let refs = crate::owner_references_json("some-name", p.uid_or_empty());
2895        assert_eq!(
2896            refs.len(),
2897            1,
2898            "populated-uid corner must produce one owner-ref entry"
2899        );
2900    }
2901
2902    // ─── Process::owned_name_or_empty substrate pins ─────────────────
2903    //
2904    // Pins the owned-form metadata-projection primitive on the
2905    // `metadata.name` axis that owns the
2906    // `.metadata.name.clone().unwrap_or_default()` chain the two hand-
2907    // authored `tatara-pool-reconciler::controller_pool` sites (the
2908    // `PoolMember` seed at line 68 + the `PoolMemberSnapshot` desired-
2909    // count seed at line 108) restated by hand pre-lift. Peer to the
2910    // sibling `uid_or_empty` pin family on the (return-form × fallback-
2911    // value) axis pair — `uid_or_empty` owns the BORROW + empty-sentinel
2912    // corner (`&str` for owner-ref emitters gating on `.is_empty()`);
2913    // this method owns the OWNED + empty-sentinel corner (`String` for
2914    // struct-literal / HashMap-key row-builder consumers whose
2915    // downstream fills a `String` field with the load-bearing `""`
2916    // sentinel). Fail-before-pass-after granularity: `owned_name_or_empty`
2917    // did not exist pre-lift, so any test invoking it fails to compile
2918    // pre-lift and passes post-lift.
2919
2920    #[test]
2921    fn owned_name_or_empty_returns_empty_string_when_metadata_name_is_none() {
2922        // Empty-slot corner pin: the primitive collapses the no-name
2923        // case to `String::new()`, matching the pre-lift
2924        // `.clone().unwrap_or_default()` chain's empty `String` byte-
2925        // identically at both pool-reconciler consumer sites.
2926        // Semantically corresponds to a Process pre-metadata-name (test
2927        // fixture, dynamic API response pre-name-resolution); the
2928        // downstream `PoolMember { process_name, .. }` slot then holds
2929        // `""` as a stable "no name to key by" signal rather than a
2930        // display placeholder that would silently alias distinct rows.
2931        let mut p = Process::new("scratch", empty_spec());
2932        p.metadata.name = None;
2933        assert_eq!(p.owned_name_or_empty(), String::new());
2934    }
2935
2936    #[test]
2937    fn owned_name_or_empty_returns_owned_string_when_slot_is_populated() {
2938        // Happy-path pin: with a populated `metadata.name` slot, the
2939        // primitive returns an owned `String` whose contents match the
2940        // persisted `String`. A regression that reshaped / normalized
2941        // / case-folded the name without touching this pin would surface
2942        // here rather than as silent skew between the two pool-member
2943        // seeds keying on the SAME Process's name.
2944        let p = Process::new("api", empty_spec());
2945        assert_eq!(p.owned_name_or_empty(), "api");
2946    }
2947
2948    #[test]
2949    fn owned_name_or_empty_returns_empty_string_when_slot_is_explicitly_empty_string() {
2950        // Corner between the missing-slot `None` and the explicitly-
2951        // empty-string `Some(String::new())` — both collapse to `""` at
2952        // the primitive because the downstream pool-member consumers
2953        // treat both corners uniformly (no name, no key). A regression
2954        // that discriminated the two corners (returning a sentinel
2955        // `"<none>"` for the missing slot but `""` for the explicit
2956        // slot) would break `String::is_empty` gating at the row-builder
2957        // callsites without moving this pin.
2958        let mut p = Process::new("scratch", empty_spec());
2959        p.metadata.name = Some(String::new());
2960        assert_eq!(p.owned_name_or_empty(), String::new());
2961        assert!(p.owned_name_or_empty().is_empty());
2962    }
2963
2964    #[test]
2965    fn owned_name_or_empty_is_a_pure_projection() {
2966        // Purity pin — repeated calls return byte-identical `String`
2967        // values. A regression that introduced state (a lazy-cached
2968        // normalized slot, a first-call canonicalization pass) would
2969        // surface here rather than as silent drift between the pool-
2970        // member seed and the desired-count snapshot seed on the SAME
2971        // Process within one reconcile pass.
2972        let p = Process::new("stable-name", empty_spec());
2973        assert_eq!(p.owned_name_or_empty(), p.owned_name_or_empty());
2974    }
2975
2976    #[test]
2977    fn owned_name_or_empty_returns_independent_owned_string() {
2978        // Owned-discipline pin: the returned `String` is an independent
2979        // allocation the caller may consume, `.push_str` into, or move
2980        // into a struct-literal `process_name: String` slot — NOT a
2981        // shared reference into `metadata.name`. A regression that
2982        // switched the projection to a `Cow`-shaped variant or a slice-
2983        // form projection would defeat the owned-form contract the two
2984        // pool-reconciler struct-literal consumers depend on (a slice
2985        // cannot land in a `process_name: String` slot without a re-
2986        // clone), and would surface here at compile time via the mutate-
2987        // in-place test below.
2988        let p = Process::new("owned-proc", empty_spec());
2989        let mut owned = p.owned_name_or_empty();
2990        owned.push_str("-mutated");
2991        assert_eq!(owned, "owned-proc-mutated");
2992        // The Process's own slot is unchanged — the returned String
2993        // owns its own byte buffer, disjoint from `metadata.name`.
2994        assert_eq!(p.metadata.name.as_deref(), Some("owned-proc"));
2995    }
2996
2997    #[test]
2998    fn owned_name_or_empty_matches_pre_lift_controller_pool_chain_shape() {
2999        // Byte-identical parity pin between the owned-form primitive
3000        // here and the pre-lift `tatara-pool-reconciler::controller_pool`
3001        // chain shape — the exact `.metadata.name.clone().unwrap_or_default()`
3002        // incantation both `PoolMember` seed (line 68) and
3003        // `PoolMemberSnapshot` seed (line 108) spelled by hand pre-lift.
3004        // Sweeps every corner (missing name slot, populated name slot,
3005        // explicitly-empty name slot) so a regression that inserted a
3006        // normalization the pre-lift chain does NOT apply — or vice
3007        // versa — surfaces here rather than as silent drift between
3008        // the ONE substrate owner and the two consumer sites.
3009        fn pre_lift(p: &Process) -> String {
3010            p.metadata.name.clone().unwrap_or_default()
3011        }
3012        // Missing slot.
3013        let mut p = Process::new("x", empty_spec());
3014        p.metadata.name = None;
3015        assert_eq!(p.owned_name_or_empty(), pre_lift(&p));
3016        // Populated slot.
3017        let p = Process::new("real-name", empty_spec());
3018        assert_eq!(p.owned_name_or_empty(), pre_lift(&p));
3019        // Explicitly-empty slot.
3020        let mut p = Process::new("x", empty_spec());
3021        p.metadata.name = Some(String::new());
3022        assert_eq!(p.owned_name_or_empty(), pre_lift(&p));
3023    }
3024
3025    #[test]
3026    fn owned_name_or_empty_shares_empty_sentinel_with_uid_or_empty() {
3027        // Cross-primitive coherence pin — the empty-string fallback this
3028        // primitive returns for the missing-name corner is the SAME
3029        // sentinel the sibling borrow-form primitive `uid_or_empty`
3030        // returns for the missing-uid corner. Both partition the OWNED
3031        // × BORROW corner of the metadata-slot family on identical
3032        // fallback semantics ("the slot is unset"), so a consumer that
3033        // switches between them based on downstream ownership
3034        // requirements never sees a different missing-slot spelling as
3035        // a side effect. A regression that drifted either sentinel
3036        // (this primitive returning `"<unnamed>"`, `uid_or_empty`
3037        // returning `"<none>"`) would break the partition and surface
3038        // here rather than as silent shape drift across the family.
3039        let mut p = Process::new("scratch", empty_spec());
3040        p.metadata.name = None;
3041        p.metadata.uid = None;
3042        assert_eq!(p.owned_name_or_empty(), p.uid_or_empty());
3043        assert!(p.owned_name_or_empty().is_empty());
3044        assert!(p.uid_or_empty().is_empty());
3045    }
3046
3047    #[test]
3048    fn owned_name_or_empty_returns_distinct_fallback_from_name_or_placeholder() {
3049        // Axis-partition pin — the owned + empty-sentinel primitive here
3050        // and the borrow + display-placeholder primitive
3051        // [`Self::name_or_placeholder`] MUST return distinct fallback
3052        // values on the missing-name corner. The distinction is load-
3053        // bearing: `owned_name_or_empty` is for HashMap-key / row-builder
3054        // consumers that need distinct keys for missing-name Processes
3055        // (empty string collides only with other missing-name rows,
3056        // never with a real "unnamed" Process); `name_or_placeholder`
3057        // is for log-line / display consumers that render the
3058        // `"unnamed"` word to operators. A regression that unified the
3059        // two fallbacks (either primitive returning the other's
3060        // sentinel) would silently collapse missing-name pool members
3061        // into a display-string key or expose the empty sentinel to
3062        // operator log lines. This pin catches either drift.
3063        let mut p = Process::new("scratch", empty_spec());
3064        p.metadata.name = None;
3065        assert_eq!(p.owned_name_or_empty(), "");
3066        assert_eq!(p.name_or_placeholder(), Process::UNNAMED_PLACEHOLDER);
3067        assert_ne!(p.owned_name_or_empty(), p.name_or_placeholder());
3068    }
3069
3070    // ─── Process::declared_parent_pid substrate pins ─────────────────
3071    //
3072    // Pins the borrow-form spec-projection primitive on the declared
3073    // parent-PID axis that owns the `.spec.identity.parent.as_deref()`
3074    // chain the two hand-authored `tatara-reconciler::phase_machine`
3075    // sites (`handle_forking` ALLOCATE-PID composer + `handle_exiting`
3076    // SIGTERM-cascade child-fan-out filter) restated by hand pre-lift.
3077    // Peer to the sibling `observed_pid_*` pin family on the (spec-
3078    // declared × status-observed) axis pair; both compose the same
3079    // borrow-form `Option<&str>` return-shape skeleton on distinct
3080    // slots (`spec.identity.parent` vs. `status.pid`). Fail-before-
3081    // pass-after granularity: `declared_parent_pid` did not exist
3082    // pre-lift, so any test invoking it fails to compile pre-lift and
3083    // passes post-lift.
3084    fn process_with_declared_parent(parent: Option<&str>) -> Process {
3085        let mut spec = empty_spec();
3086        spec.identity.parent = parent.map(str::to_string);
3087        Process::new("child-proc", spec)
3088    }
3089
3090    #[test]
3091    fn declared_parent_pid_returns_none_when_slot_is_none() {
3092        // Empty-slot corner pin: the primitive collapses the no-
3093        // parent case to `None`, matching the pre-lift `.as_deref()`
3094        // chain's `None` byte-identically at both reconciler consumer
3095        // sites. Semantically corresponds to a Process authored at
3096        // cluster init (PID 1) with no upstream parent — the
3097        // ALLOCATE-PID composer feeds `None` into `pid::allocate_pid`
3098        // to signal "no prefix", and the SIGTERM cascade's filter
3099        // never matches such a Process because a child's declared
3100        // parent can never equal `Some(pid)` when the slot is `None`.
3101        let p = process_with_declared_parent(None);
3102        assert!(p.declared_parent_pid().is_none());
3103    }
3104
3105    #[test]
3106    fn declared_parent_pid_returns_borrowed_str_when_slot_is_populated() {
3107        // Happy-path pin: with a populated `spec.identity.parent`
3108        // slot, the primitive returns a borrowed `&str` whose
3109        // contents match the persisted `String`. A regression that
3110        // filtered / reshaped / canonicalized the string would
3111        // surface here rather than as silent skew at the child-fan-
3112        // out filter's `.declared_parent_pid() == Some(pid)`
3113        // equality check on the SAME parent-child pair.
3114        let p = process_with_declared_parent(Some("seph.1"));
3115        assert_eq!(p.declared_parent_pid(), Some("seph.1"));
3116    }
3117
3118    #[test]
3119    fn declared_parent_pid_is_a_zero_copy_borrow_projection() {
3120        // Borrow-discipline pin: the returned `&str` borrows the
3121        // persisted `String`'s underlying byte buffer in place —
3122        // NOT a fresh allocation or a clone. A regression that
3123        // switched the projection to an owned `String` (via
3124        // `.clone()` or `.to_owned()`) would defeat the zero-copy
3125        // contract the lift's primary strict-widening delivers.
3126        // The `handle_exiting` cascade filter runs per candidate
3127        // child across the cluster-wide Process list; a per-row
3128        // `String::clone` would allocate one heap block per non-
3129        // matching row, so the borrow-form primitive is load-
3130        // bearing for large clusters. Peer to the sibling
3131        // `observed_pid_is_a_zero_copy_borrow_projection` pin on
3132        // the status-observed side of the axis pair.
3133        let p = process_with_declared_parent(Some("seph.1"));
3134        let borrowed = p.declared_parent_pid().expect("populated slot");
3135        let persisted = p.spec.identity.parent.as_ref().unwrap();
3136        assert!(std::ptr::eq(borrowed.as_ptr(), persisted.as_ptr()));
3137    }
3138
3139    #[test]
3140    fn declared_parent_pid_is_a_pure_projection() {
3141        // Purity pin: calling the projection twice on the same
3142        // `Process` returns byte-identical `&str`s (same pointer,
3143        // same length). A regression that introduced state — a
3144        // lazy-cached slice materialized on first call, a
3145        // normalization step that ran once and cached — would
3146        // surface here rather than as silent drift between the
3147        // ALLOCATE-PID composer and the SIGTERM cascade's child-
3148        // fan-out filter within one reconcile pass.
3149        let p = process_with_declared_parent(Some("seph.1.3"));
3150        let a = p.declared_parent_pid().expect("populated slot");
3151        let b = p.declared_parent_pid().expect("populated slot");
3152        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
3153        assert_eq!(a.len(), b.len());
3154    }
3155
3156    #[test]
3157    fn declared_parent_pid_matches_pre_lift_reconciler_chain_shape() {
3158        // Byte-identical parity pin between the borrow-form primitive
3159        // here and the pre-lift `tatara-reconciler::phase_machine`
3160        // `.spec.identity.parent.as_deref()` chain shape. Sweeps
3161        // every corner every callsite plausibly encounters (empty
3162        // slot, populated with a hierarchical PID). A regression
3163        // that inserted a normalization step at the primitive the
3164        // pre-lift chain does NOT apply — or vice versa — surfaces
3165        // here rather than as silent drift between the pre-lift
3166        // consumer sites and the ONE substrate owner they now route
3167        // through. Peer to
3168        // `observed_pid_matches_pre_lift_reconciler_chain_shape` on
3169        // the sibling axis's borrow-form primitive.
3170        fn pre_lift(p: &Process) -> Option<&str> {
3171            p.spec.identity.parent.as_deref()
3172        }
3173        // Empty slot.
3174        let p = process_with_declared_parent(None);
3175        assert_eq!(p.declared_parent_pid(), pre_lift(&p));
3176        // Populated with a hierarchical PID.
3177        let p = process_with_declared_parent(Some("seph.1"));
3178        assert_eq!(p.declared_parent_pid(), pre_lift(&p));
3179        // Populated with a deeper hierarchical PID.
3180        let p = process_with_declared_parent(Some("seph.1.7.42"));
3181        assert_eq!(p.declared_parent_pid(), pre_lift(&p));
3182    }
3183
3184    #[test]
3185    fn declared_parent_pid_preserves_hierarchical_pid_format() {
3186        // Format-preservation pin: the hierarchical PID path
3187        // (dotted-segment form `seph.1.7`, matching the ported
3188        // `convergence-controller/src/identity.rs` scheme) reaches
3189        // the caller with segments and separators byte-identical
3190        // to the persisted `String`. A regression that inserted a
3191        // canonicalization pass (a segment-count validator, a
3192        // separator swap `.` → `/`, a leading/trailing whitespace
3193        // trim) would silently misroute the SIGTERM cascade's
3194        // `declared_parent_pid() == Some(pid)` comparator against
3195        // children whose `parent` field was authored in the ported
3196        // scheme's exact form — the SAME children the observed_pid
3197        // primitive is pinned to match on the other side of the
3198        // axis pair.
3199        for parent in ["seph", "seph.1", "seph.1.7", "seph.1.7.42"] {
3200            let p = process_with_declared_parent(Some(parent));
3201            assert_eq!(p.declared_parent_pid(), Some(parent));
3202        }
3203    }
3204
3205    #[test]
3206    fn declared_parent_pid_composes_with_observed_pid_for_child_fanout_filter() {
3207        // Cross-axis coherence pin against the sibling
3208        // [`Self::observed_pid`] on the (spec-declared × status-
3209        // observed) axis pair: a child's `.declared_parent_pid()`
3210        // and its parent's `.observed_pid()` compose through the
3211        // SAME borrow-form `Option<&str>` skeleton so the
3212        // `handle_exiting` cascade filter's equality gate holds
3213        // structurally. A regression that skewed EITHER primitive's
3214        // return-form (return-shape, borrow discipline, empty-slot
3215        // collapse) would silently misroute every SIGTERM cascade
3216        // on the parent-child pair. This pin re-reads both primitives
3217        // at test time so the composition holds iff both live paths
3218        // are the current implementation.
3219        // Parent Process: has an observed PID.
3220        let mut parent = Process::new("parent-proc", empty_spec());
3221        parent.status = Some(ProcessStatus {
3222            pid: Some("seph.1".to_string()),
3223            ..Default::default()
3224        });
3225        // Child Process: declared parent matches parent's observed PID.
3226        let child = process_with_declared_parent(Some("seph.1"));
3227        // The `handle_exiting` filter's equality gate:
3228        // `child.declared_parent_pid() == Some(parent.observed_pid()?)`.
3229        let parent_pid = parent.observed_pid().expect("parent has PID");
3230        assert_eq!(child.declared_parent_pid(), Some(parent_pid));
3231        // Sibling Process with an unrelated declared parent must NOT
3232        // match the same parent — pins that the filter's SKIP branch
3233        // holds on the other side of the axis pair.
3234        let sibling = process_with_declared_parent(Some("seph.2"));
3235        assert_ne!(sibling.declared_parent_pid(), Some(parent_pid));
3236    }
3237
3238    // ─── Process::declared_name_override substrate pins ──────────────
3239    //
3240    // Pins the borrow-form spec-projection primitive on the declared
3241    // name-override sub-axis of the declared-identity axis that owns
3242    // the `.spec.identity.name_override.as_deref()` chain the two
3243    // hand-authored `tatara-reconciler::phase_machine` sites
3244    // (`handle_pending` DECLARE composer + `handle_forking` ALLOCATE-
3245    // PID rehydration branch) restated by hand pre-lift. Peer to the
3246    // sibling `declared_parent_pid_*` pin family on the (parent ×
3247    // name-override) sub-axis pair; both compose the same borrow-form
3248    // `Option<&str>` return-shape skeleton on distinct slots
3249    // (`spec.identity.name_override` vs `spec.identity.parent`).
3250    // Fail-before-pass-after granularity: `declared_name_override`
3251    // did not exist pre-lift, so any test invoking it fails to
3252    // compile pre-lift and passes post-lift.
3253    fn process_with_declared_name_override(name_override: Option<&str>) -> Process {
3254        let mut spec = empty_spec();
3255        spec.identity.name_override = name_override.map(str::to_string);
3256        Process::new("some-proc", spec)
3257    }
3258
3259    #[test]
3260    fn declared_name_override_returns_none_when_slot_is_none() {
3261        // Empty-slot corner pin: the primitive collapses the no-
3262        // override case to `None`, matching the pre-lift `.as_deref()`
3263        // chain's `None` byte-identically at both reconciler consumer
3264        // sites. Semantically corresponds to a Process authored
3265        // WITHOUT the human-name-override escape hatch — the default;
3266        // `derive_identity` then computes the name from the content
3267        // hash and stamps `name_override: false` on the resulting
3268        // [`Identity`].
3269        let p = process_with_declared_name_override(None);
3270        assert!(p.declared_name_override().is_none());
3271    }
3272
3273    #[test]
3274    fn declared_name_override_returns_borrowed_str_when_slot_is_populated() {
3275        // Happy-path pin: with a populated `spec.identity
3276        // .name_override` slot, the primitive returns a borrowed
3277        // `&str` whose contents match the persisted `String`. A
3278        // regression that filtered / reshaped / canonicalized the
3279        // string at the primitive (as opposed to inside
3280        // `derive_identity`, where the trim/empty-filter lives today)
3281        // would surface here rather than as silent skew between the
3282        // DECLARE composer and the ALLOCATE-PID rehydration branch on
3283        // the SAME Process spec.
3284        let p = process_with_declared_name_override(Some("observability-stack"));
3285        assert_eq!(p.declared_name_override(), Some("observability-stack"));
3286    }
3287
3288    #[test]
3289    fn declared_name_override_is_a_zero_copy_borrow_projection() {
3290        // Borrow-discipline pin: the returned `&str` borrows the
3291        // persisted `String`'s underlying byte buffer in place —
3292        // NOT a fresh allocation or a clone. Peer to the sibling
3293        // `declared_parent_pid_is_a_zero_copy_borrow_projection` pin
3294        // on the other side of the (parent × name-override) sub-axis
3295        // pair; the borrow discipline holds structurally on BOTH
3296        // sub-axes so a future `declared_identity` composite that
3297        // returns both halves together can compose them without
3298        // dropping into an owning form.
3299        let p = process_with_declared_name_override(Some("observability-stack"));
3300        let borrowed = p.declared_name_override().expect("populated slot");
3301        let persisted = p.spec.identity.name_override.as_ref().unwrap();
3302        assert!(std::ptr::eq(borrowed.as_ptr(), persisted.as_ptr()));
3303    }
3304
3305    #[test]
3306    fn declared_name_override_is_a_pure_projection() {
3307        // Purity pin: calling the projection twice on the same
3308        // `Process` returns byte-identical `&str`s (same pointer,
3309        // same length). A regression that introduced state — a
3310        // lazy-cached slice materialized on first call, a
3311        // normalization step that ran once and cached — would
3312        // surface here rather than as silent drift between the
3313        // DECLARE composer and the ALLOCATE-PID rehydration branch
3314        // within one reconcile pass.
3315        let p = process_with_declared_name_override(Some("gateway-primary"));
3316        let a = p.declared_name_override().expect("populated slot");
3317        let b = p.declared_name_override().expect("populated slot");
3318        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
3319        assert_eq!(a.len(), b.len());
3320    }
3321
3322    #[test]
3323    fn declared_name_override_matches_pre_lift_reconciler_chain_shape() {
3324        // Byte-identical parity pin between the borrow-form primitive
3325        // here and the pre-lift `tatara-reconciler::phase_machine`
3326        // `.spec.identity.name_override.as_deref()` chain shape.
3327        // Sweeps every corner every callsite plausibly encounters
3328        // (empty slot, populated with a bare name, populated with a
3329        // whitespace-containing name that `derive_identity`'s
3330        // internal trim would collapse, populated with an explicitly
3331        // empty string that `derive_identity`'s internal
3332        // `!s.is_empty()` filter would reject). A regression that
3333        // inserted a normalization step at the primitive the pre-
3334        // lift chain does NOT apply — or vice versa — surfaces here
3335        // rather than as silent drift between the pre-lift consumer
3336        // sites and the ONE substrate owner they now route through.
3337        // Peer to
3338        // `declared_parent_pid_matches_pre_lift_reconciler_chain_shape`
3339        // on the sibling sub-axis's borrow-form primitive.
3340        fn pre_lift(p: &Process) -> Option<&str> {
3341            p.spec.identity.name_override.as_deref()
3342        }
3343        // Empty slot.
3344        let p = process_with_declared_name_override(None);
3345        assert_eq!(p.declared_name_override(), pre_lift(&p));
3346        // Populated with a bare name.
3347        let p = process_with_declared_name_override(Some("observability-stack"));
3348        assert_eq!(p.declared_name_override(), pre_lift(&p));
3349        // Populated with a whitespace-containing name.
3350        let p = process_with_declared_name_override(Some("  observability-stack  "));
3351        assert_eq!(p.declared_name_override(), pre_lift(&p));
3352        // Populated with an explicitly empty string. Distinct from
3353        // the missing-slot `None` corner both at the primitive here
3354        // and at the pre-lift chain (the trim/filter that collapses
3355        // these two into the same `false`-branched
3356        // `Identity { name_override: false, .. }` lives INSIDE
3357        // `derive_identity`, NOT at the borrow site) — the primitive
3358        // MUST preserve the distinction so a future lift of the trim/
3359        // filter OUT of `derive_identity` INTO the primitive is a
3360        // conscious substrate change, not a silent one.
3361        let p = process_with_declared_name_override(Some(""));
3362        assert_eq!(p.declared_name_override(), pre_lift(&p));
3363    }
3364
3365    #[test]
3366    fn declared_name_override_preserves_raw_slot_verbatim() {
3367        // Invariance-under-`derive_identity`-normalization pin: the
3368        // primitive returns the slot's raw byte contents verbatim —
3369        // no trim, no empty-string filter, no case fold, no
3370        // normalization of any kind. `derive_identity` internally
3371        // applies `.map(str::trim).filter(|s| !s.is_empty())` before
3372        // dispatching on `Some(non_empty)` vs `None | Some(empty |
3373        // whitespace)`, but that transform lives IN `derive_identity`,
3374        // NOT at the borrow site. A regression that pulled the trim/
3375        // filter forward INTO the primitive would silently collapse
3376        // three currently-distinct corners at the borrow site (bare
3377        // populated → `Some(name)`; whitespace-only → `Some("   ")`;
3378        // empty → `Some("")`) into two (bare → `Some(name)`; the
3379        // other two → `None`). That collapse might be an intentional
3380        // substrate change some future run wants to make; if so, it
3381        // lands as a conscious edit here (with this pin updated in
3382        // the same commit) rather than as silent behavior drift.
3383        for value in ["bare", "  padded  ", "\ttabs\t", "   ", ""] {
3384            let p = process_with_declared_name_override(Some(value));
3385            assert_eq!(
3386                p.declared_name_override(),
3387                Some(value),
3388                "declared_name_override must preserve raw slot verbatim for value {value:?}"
3389            );
3390        }
3391    }
3392
3393    #[test]
3394    fn declared_name_override_composes_with_derive_identity_call_shape() {
3395        // Cross-primitive coherence pin against the [`derive_identity`]
3396        // consumer: the two live `tatara-reconciler::phase_machine`
3397        // callsites feed `p.declared_name_override()` as the second
3398        // positional argument to `derive_identity(&p.spec, …)`. This
3399        // pin exercises that exact call shape at test time so a
3400        // regression that skewed the primitive's return-form (return-
3401        // shape, borrow discipline, empty-slot collapse) surfaces
3402        // here as a shape mismatch at the [`derive_identity`] call
3403        // site rather than as silent operator-facing skew between the
3404        // DECLARE composer and the ALLOCATE-PID rehydration branch.
3405        // Populated with a bare non-empty name: `derive_identity`
3406        // dispatches on `Some(non_empty)` and stamps
3407        // `name_override: true` on the resulting [`Identity`], with
3408        // the resulting `.name` equal to the raw slot value.
3409        let p = process_with_declared_name_override(Some("gateway-primary"));
3410        let id = crate::identity::derive_identity(&p.spec, p.declared_name_override());
3411        assert!(id.name_override);
3412        assert_eq!(id.name, "gateway-primary");
3413        // Empty slot: `derive_identity` dispatches on `None` and
3414        // stamps `name_override: false` on the resulting [`Identity`],
3415        // with the resulting `.name` derived from the content hash
3416        // (NOT equal to any operator-authored slot value).
3417        let p = process_with_declared_name_override(None);
3418        let id = crate::identity::derive_identity(&p.spec, p.declared_name_override());
3419        assert!(!id.name_override);
3420    }
3421
3422    // ─── Process::observed_flux_resources substrate pins ───────────────
3423    //
3424    // Pins the borrow-form status-projection primitive that owns the
3425    // 5-line `.status.as_ref().map(|s| s.flux_resources.clone())
3426    // .unwrap_or_default()` chain the two hand-authored
3427    // `tatara-reconciler::phase_machine` sites (`handle_running` +
3428    // `handle_attested`) restated by hand pre-lift. Fail-before-pass-
3429    // after granularity: a regression that widened the missing-`status`
3430    // corner, dropped the slot, or drifted the borrow discipline
3431    // surfaces here rather than as silent operator-facing skew between
3432    // the VERIFY-phase readiness probe and the ATTEST-heartbeat drift
3433    // detector.
3434
3435    fn sample_flux_ref(name: &str) -> FluxResourceRef {
3436        // Distinct slot values so a swap between adjacent tuple
3437        // positions surfaces as an equality failure at the assertion
3438        // site — a slot-inversion regression cannot masquerade as
3439        // identity by accident. Peer to the sibling
3440        // `tatara_process::status::tests::sample_flux_ref` discipline
3441        // on the fetch-coords axis.
3442        FluxResourceRef {
3443            api_version: "kustomize.toolkit.fluxcd.io/v1".to_string(),
3444            kind: "Kustomization".to_string(),
3445            name: name.to_string(),
3446            namespace: "flux-system".to_string(),
3447            ready: false,
3448            message: None,
3449            last_check: None,
3450        }
3451    }
3452
3453    fn process_with_flux_resources(refs: Vec<FluxResourceRef>) -> Process {
3454        let mut p = Process::new("api-gateway", empty_spec());
3455        p.metadata.namespace = Some("prod".into());
3456        let mut status = ProcessStatus::default();
3457        status.flux_resources = refs;
3458        p.status = Some(status);
3459        p
3460    }
3461
3462    #[test]
3463    fn observed_flux_resources_returns_empty_slice_when_status_is_none() {
3464        // Missing-`status` corner pin: the primitive collapses the
3465        // no-status case to `&[]` so downstream `.is_empty()` /
3466        // `.len()` / iteration behave identically on a `Process`
3467        // whose status field is `None` and on one whose status
3468        // carries an empty `flux_resources` slot. Matches the
3469        // pre-lift `.unwrap_or_default()`'s empty-`Vec` corner
3470        // byte-identically at every reconciler consumer's downstream
3471        // shape.
3472        let mut p = Process::new("api", empty_spec());
3473        p.status = None;
3474        assert!(p.observed_flux_resources().is_empty());
3475        assert_eq!(p.observed_flux_resources().len(), 0);
3476    }
3477
3478    #[test]
3479    fn observed_flux_resources_returns_empty_slice_when_flux_resources_is_empty() {
3480        // Zero-refs-under-populated-status corner pin: the primitive
3481        // returns an empty slice, matching the missing-`status`
3482        // corner byte-identically. A regression that treated the two
3483        // corners differently (a `None`-vs-empty signal that
3484        // downstream consumers could grep on) would silently promote
3485        // an internal representation detail (whether the reconciler
3486        // has ever written a status subresource) into observable
3487        // behavior.
3488        let p = process_with_flux_resources(vec![]);
3489        assert!(p.observed_flux_resources().is_empty());
3490        assert_eq!(p.observed_flux_resources().len(), 0);
3491    }
3492
3493    #[test]
3494    fn observed_flux_resources_returns_slice_of_persisted_vec() {
3495        // Happy-path pin: with a populated `status.flux_resources`
3496        // slot, the primitive returns a borrowed slice whose length
3497        // and per-element identity match the persisted vector. A
3498        // regression that filtered / reshaped / deduplicated the
3499        // slice would surface here rather than as silent skew at the
3500        // downstream fetch consumers.
3501        let refs = vec![
3502            sample_flux_ref("observability-stack"),
3503            sample_flux_ref("gateway"),
3504        ];
3505        let p = process_with_flux_resources(refs.clone());
3506        let observed = p.observed_flux_resources();
3507        assert_eq!(observed.len(), 2);
3508        assert_eq!(observed[0].name, "observability-stack");
3509        assert_eq!(observed[1].name, "gateway");
3510    }
3511
3512    #[test]
3513    fn observed_flux_resources_is_a_zero_copy_borrow_projection() {
3514        // Borrow-discipline pin: the returned slice borrows the
3515        // persisted `Vec<FluxResourceRef>` in place — NOT a fresh
3516        // allocation or a clone. A regression that switched the
3517        // projection to owned refs (via `.clone()` or `.to_vec()`)
3518        // would defeat the zero-copy contract the lift's primary
3519        // strict-widening delivers (the pre-lift 5-line chain
3520        // eagerly cloned the whole vector per reconcile pass; the
3521        // post-lift primitive borrows). Peer to the sibling
3522        // `flux_resource_ref_fetch_coords_returns_borrows_of_owned_slots`
3523        // pin on the per-ref borrow-projection axis.
3524        let refs = vec![sample_flux_ref("observability-stack")];
3525        let p = process_with_flux_resources(refs);
3526        let observed = p.observed_flux_resources();
3527        let persisted = &p.status.as_ref().unwrap().flux_resources;
3528        assert!(std::ptr::eq(observed.as_ptr(), persisted.as_ptr()));
3529    }
3530
3531    #[test]
3532    fn observed_flux_resources_is_a_pure_projection() {
3533        // Purity pin: calling the projection twice on the same
3534        // `Process` returns byte-identical slices (same pointer,
3535        // same length). A regression that introduced state — a
3536        // lazy-cached slice materialized on first call, a
3537        // normalization step that ran once and cached — would
3538        // surface here rather than as silent drift between the
3539        // VERIFY-phase and ATTEST-heartbeat consumers on the SAME
3540        // `Process` within one reconcile pass.
3541        let refs = vec![sample_flux_ref("observability-stack")];
3542        let p = process_with_flux_resources(refs);
3543        let a = p.observed_flux_resources();
3544        let b = p.observed_flux_resources();
3545        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
3546        assert_eq!(a.len(), b.len());
3547    }
3548
3549    #[test]
3550    fn observed_flux_resources_matches_pre_lift_reconciler_chain_shape() {
3551        // Byte-identical parity pin between the borrow-form primitive
3552        // here and the pre-lift `tatara-reconciler::phase_machine`
3553        // 5-line chain shape. Sweeps every corner every callsite
3554        // plausibly encounters (missing status, empty flux_resources,
3555        // populated flux_resources with one ref, populated with
3556        // multiple refs). A regression that inserted a normalization
3557        // step at the primitive the pre-lift chain does NOT apply —
3558        // or vice versa — surfaces here rather than as silent drift
3559        // between the pre-lift consumer sites and the ONE substrate
3560        // owner they now route through. Peer to
3561        // `coordinates_or_none_matches_pre_lift_reconciler_helper_shape`
3562        // on the metadata axis's borrow-form primitive.
3563        // `FluxResourceRef` does not derive `PartialEq` — the parity
3564        // check walks the per-ref fetch-coords tuple (the same 4-slot
3565        // borrow projection every downstream fetch consumer routes
3566        // through) so a regression that reshaped ANY slot at ANY
3567        // index surfaces here through the sibling
3568        // `FluxResourceRef::fetch_coords` typed projection.
3569        fn pre_lift(p: &Process) -> Vec<FluxResourceRef> {
3570            p.status
3571                .as_ref()
3572                .map(|s| s.flux_resources.clone())
3573                .unwrap_or_default()
3574        }
3575        fn coord_shape(refs: &[FluxResourceRef]) -> Vec<(String, String, String, String)> {
3576            refs.iter()
3577                .map(|r| {
3578                    let (ns, av, kind, name) = r.fetch_coords();
3579                    (
3580                        ns.to_string(),
3581                        av.to_string(),
3582                        kind.to_string(),
3583                        name.to_string(),
3584                    )
3585                })
3586                .collect()
3587        }
3588        // Missing status.
3589        let mut p = Process::new("api", empty_spec());
3590        p.status = None;
3591        assert_eq!(
3592            coord_shape(p.observed_flux_resources()),
3593            coord_shape(&pre_lift(&p))
3594        );
3595        // Populated status, empty slot.
3596        let p = process_with_flux_resources(vec![]);
3597        assert_eq!(
3598            coord_shape(p.observed_flux_resources()),
3599            coord_shape(&pre_lift(&p))
3600        );
3601        // Populated status, one ref.
3602        let p = process_with_flux_resources(vec![sample_flux_ref("obs")]);
3603        assert_eq!(
3604            coord_shape(p.observed_flux_resources()),
3605            coord_shape(&pre_lift(&p))
3606        );
3607        // Populated status, multiple refs.
3608        let p = process_with_flux_resources(vec![
3609            sample_flux_ref("obs"),
3610            sample_flux_ref("gw"),
3611            sample_flux_ref("api"),
3612        ]);
3613        assert_eq!(
3614            coord_shape(p.observed_flux_resources()),
3615            coord_shape(&pre_lift(&p))
3616        );
3617    }
3618
3619    #[test]
3620    fn observed_flux_resources_missing_status_and_empty_slot_collapse_to_the_same_slice_shape() {
3621        // Cross-corner coherence pin: the missing-`status` corner and
3622        // the populated-empty-slot corner return slices whose
3623        // `.is_empty()` / `.len()` observations are IDENTICAL. A
3624        // regression that promoted the missing-`status` corner to
3625        // returning `None` (via a signature change) — or that widened
3626        // the empty-slot corner to a synthetic single-element slice
3627        // — would surface here rather than as silent operator-facing
3628        // divergence between a never-status-written Process and a
3629        // status-emptied Process.
3630        let mut p_no_status = Process::new("api", empty_spec());
3631        p_no_status.status = None;
3632        let p_empty_status = process_with_flux_resources(vec![]);
3633        assert_eq!(
3634            p_no_status.observed_flux_resources().len(),
3635            p_empty_status.observed_flux_resources().len()
3636        );
3637        assert_eq!(
3638            p_no_status.observed_flux_resources().is_empty(),
3639            p_empty_status.observed_flux_resources().is_empty()
3640        );
3641    }
3642
3643    #[test]
3644    fn observed_flux_resources_slice_preserves_persisted_ordering() {
3645        // Ordering-preservation pin: the borrowed slice preserves
3646        // the exact insertion order of the persisted vector — no
3647        // sort, no dedup, no reshape. A regression that inserted a
3648        // sort or reordering would silently misroute per-ref
3649        // observations at the downstream VERIFY-phase / ATTEST-
3650        // heartbeat consumers, both of which walk the slice
3651        // positionally and correlate the position to the observed
3652        // readiness.
3653        let refs = vec![
3654            sample_flux_ref("z-last"),
3655            sample_flux_ref("a-first"),
3656            sample_flux_ref("m-middle"),
3657        ];
3658        let p = process_with_flux_resources(refs);
3659        let observed = p.observed_flux_resources();
3660        assert_eq!(observed[0].name, "z-last");
3661        assert_eq!(observed[1].name, "a-first");
3662        assert_eq!(observed[2].name, "m-middle");
3663    }
3664
3665    // ─── Process::observed_pid substrate pins ─────────────────────────
3666    //
3667    // Pins the borrow-form status-projection primitive on the PID axis
3668    // that owns the 3-line `.status.as_ref().and_then(|s| s.pid.clone())`
3669    // chain the two hand-authored `tatara-reconciler::phase_machine`
3670    // sites (`handle_forking` ALLOCATE-PID gate + `handle_exiting`
3671    // SIGTERM cascade) restated by hand pre-lift. Peer to the sibling
3672    // `observed_flux_resources_*` pin family on the flux-resources
3673    // axis; both compose the missing-`status` fallback + borrow-form
3674    // return-shape skeleton on distinct `ProcessStatus` slots. Fail-
3675    // before-pass-after granularity: `observed_pid` did not exist
3676    // pre-lift, so any test invoking it fails to compile pre-lift and
3677    // passes post-lift.
3678
3679    fn process_with_pid(pid: Option<&str>) -> Process {
3680        let mut p = Process::new("api-gateway", empty_spec());
3681        p.metadata.namespace = Some("prod".into());
3682        let mut status = ProcessStatus::default();
3683        status.pid = pid.map(str::to_string);
3684        p.status = Some(status);
3685        p
3686    }
3687
3688    #[test]
3689    fn observed_pid_returns_none_when_status_is_none() {
3690        // Missing-`status` corner pin: the primitive collapses the
3691        // no-status case to `None` so downstream `.is_some()` /
3692        // `if let Some(_)` / `.map(...)` behave identically on a
3693        // `Process` whose status field is `None` and on one whose
3694        // status carries an unpopulated `pid` slot. Matches the
3695        // pre-lift `.and_then(...)` chain's `None` byte-identically
3696        // at every reconciler consumer's downstream shape.
3697        let mut p = Process::new("api", empty_spec());
3698        p.status = None;
3699        assert!(p.observed_pid().is_none());
3700    }
3701
3702    #[test]
3703    fn observed_pid_returns_none_when_pid_slot_is_none() {
3704        // Empty-slot-under-populated-status corner pin: the
3705        // primitive returns `None`, matching the missing-`status`
3706        // corner byte-identically. A regression that treated the
3707        // two corners differently (a `None`-vs-`Some("")` signal
3708        // that downstream consumers could grep on) would silently
3709        // promote an internal representation detail (whether the
3710        // reconciler has ever written a status subresource) into
3711        // observable behavior at the ALLOCATE-PID gate.
3712        let p = process_with_pid(None);
3713        assert!(p.observed_pid().is_none());
3714    }
3715
3716    #[test]
3717    fn observed_pid_returns_borrowed_str_when_pid_slot_is_populated() {
3718        // Happy-path pin: with a populated `status.pid` slot, the
3719        // primitive returns a borrowed `&str` whose contents match
3720        // the persisted `String`. A regression that filtered /
3721        // reshaped / canonicalized the string would surface here
3722        // rather than as silent skew at the downstream cascade
3723        // comparator's `.as_deref() == Some(...)` equality check.
3724        let p = process_with_pid(Some("seph.1.7"));
3725        assert_eq!(p.observed_pid(), Some("seph.1.7"));
3726    }
3727
3728    #[test]
3729    fn observed_pid_is_a_zero_copy_borrow_projection() {
3730        // Borrow-discipline pin: the returned `&str` borrows the
3731        // persisted `String`'s underlying byte buffer in place —
3732        // NOT a fresh allocation or a clone. A regression that
3733        // switched the projection to an owned `String` (via
3734        // `.clone()` or `.to_owned()`) would defeat the zero-copy
3735        // contract the lift's primary strict-widening delivers
3736        // (the pre-lift 3-line chain eagerly cloned the `String`
3737        // per reconcile pass at BOTH call sites even though the
3738        // ALLOCATE-PID gate immediately dropped the clone and the
3739        // SIGTERM cascade only re-borrowed it via `.as_str()`; the
3740        // post-lift primitive borrows). Peer to the sibling
3741        // `observed_flux_resources_is_a_zero_copy_borrow_projection`
3742        // pin on the flux-resources borrow-projection axis.
3743        let p = process_with_pid(Some("seph.1.7"));
3744        let observed = p.observed_pid().expect("populated slot");
3745        let persisted = p.status.as_ref().unwrap().pid.as_ref().unwrap();
3746        assert!(std::ptr::eq(observed.as_ptr(), persisted.as_ptr()));
3747    }
3748
3749    #[test]
3750    fn observed_pid_is_a_pure_projection() {
3751        // Purity pin: calling the projection twice on the same
3752        // `Process` returns byte-identical `&str`s (same pointer,
3753        // same length). A regression that introduced state — a
3754        // lazy-cached slice materialized on first call, a
3755        // normalization step that ran once and cached — would
3756        // surface here rather than as silent drift between the
3757        // ALLOCATE-PID gate and the SIGTERM cascade on the SAME
3758        // `Process` within one reconcile pass.
3759        let p = process_with_pid(Some("seph.1.7"));
3760        let a = p.observed_pid().expect("populated slot");
3761        let b = p.observed_pid().expect("populated slot");
3762        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
3763        assert_eq!(a.len(), b.len());
3764    }
3765
3766    #[test]
3767    fn observed_pid_matches_pre_lift_reconciler_chain_shape() {
3768        // Byte-identical parity pin between the borrow-form
3769        // primitive here and the pre-lift `tatara-reconciler
3770        // ::phase_machine` 3-line chain shape. Sweeps every corner
3771        // every callsite plausibly encounters (missing status,
3772        // empty pid slot, populated pid slot). A regression that
3773        // inserted a normalization step at the primitive the pre-
3774        // lift chain does NOT apply — or vice versa — surfaces
3775        // here rather than as silent drift between the pre-lift
3776        // consumer sites and the ONE substrate owner they now
3777        // route through. Peer to
3778        // `observed_flux_resources_matches_pre_lift_reconciler_chain_shape`
3779        // on the flux-resources axis's borrow-form primitive.
3780        fn pre_lift(p: &Process) -> Option<String> {
3781            p.status.as_ref().and_then(|s| s.pid.clone())
3782        }
3783        // Missing status.
3784        let mut p = Process::new("api", empty_spec());
3785        p.status = None;
3786        assert_eq!(p.observed_pid().map(str::to_string), pre_lift(&p));
3787        // Populated status, empty pid slot.
3788        let p = process_with_pid(None);
3789        assert_eq!(p.observed_pid().map(str::to_string), pre_lift(&p));
3790        // Populated status, populated pid slot.
3791        let p = process_with_pid(Some("seph.1.7"));
3792        assert_eq!(p.observed_pid().map(str::to_string), pre_lift(&p));
3793    }
3794
3795    #[test]
3796    fn observed_pid_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
3797        // Cross-corner coherence pin: the missing-`status` corner
3798        // and the populated-empty-slot corner return `Option`s whose
3799        // `.is_none()` observations are IDENTICAL. A regression
3800        // that promoted the missing-`status` corner to returning a
3801        // typed error (via a signature change to `Result<_, _>`) —
3802        // or that widened the empty-slot corner to a synthetic
3803        // `Some("")` — would surface here rather than as silent
3804        // operator-facing divergence between a never-status-
3805        // written Process and a status-emptied Process on the
3806        // ALLOCATE-PID gate.
3807        let mut p_no_status = Process::new("api", empty_spec());
3808        p_no_status.status = None;
3809        let p_empty_slot = process_with_pid(None);
3810        assert_eq!(
3811            p_no_status.observed_pid().is_none(),
3812            p_empty_slot.observed_pid().is_none()
3813        );
3814        assert_eq!(
3815            p_no_status.observed_pid().is_some(),
3816            p_empty_slot.observed_pid().is_some()
3817        );
3818    }
3819
3820    #[test]
3821    fn observed_pid_preserves_hierarchical_pid_format() {
3822        // Format-preservation pin: the hierarchical PID path
3823        // (dotted-segment form `seph.1.7`, matching the ported
3824        // `convergence-controller/src/identity.rs` scheme) reaches
3825        // the caller with segments and separators byte-identical
3826        // to the persisted `String`. A regression that inserted a
3827        // canonicalization pass (a segment-count validator, a
3828        // separator swap `.` → `/`, a leading/trailing whitespace
3829        // trim) would silently misroute the SIGTERM cascade's
3830        // `spec.identity.parent == Some(pid)` comparator against
3831        // children whose `parent` field was authored in the ported
3832        // scheme's exact form.
3833        for pid in ["seph", "seph.1", "seph.1.7", "seph.1.7.42"] {
3834            let p = process_with_pid(Some(pid));
3835            assert_eq!(p.observed_pid(), Some(pid));
3836        }
3837    }
3838
3839    // ─── Process::observed_attestation substrate pins ─────────────────
3840    //
3841    // Pins the borrow-form status-projection primitive on the
3842    // attestation-chain axis that owns the 3-line
3843    // `.status.as_ref().and_then(|s| s.attestation.as_ref())` chain
3844    // the two hand-authored `tatara-reconciler` sites
3845    // (`phase_machine::advance_to_attested` ATTEST composer +
3846    // `render::render_export_jobs` export-Job builder) restated by
3847    // hand pre-lift. Peer to the sibling `observed_pid_*` +
3848    // `observed_flux_resources_*` pin families; all three compose
3849    // the missing-`status` fallback + borrow-form return-shape
3850    // skeleton on distinct `ProcessStatus` slots. Fail-before-pass-
3851    // after granularity: `observed_attestation` did not exist
3852    // pre-lift, so any test invoking it fails to compile pre-lift
3853    // and passes post-lift.
3854
3855    fn sample_attestation(artifact: &str, intent: &str) -> ProcessAttestation {
3856        // Distinct pillar strings so a regression that swapped the
3857        // artifact / intent pillars silently surfaces as an
3858        // equality failure at the composed-root parity pin.
3859        ProcessAttestation::initial(artifact.to_string(), None, intent.to_string())
3860    }
3861
3862    fn process_with_attestation(attestation: Option<ProcessAttestation>) -> Process {
3863        let mut p = Process::new("api-gateway", empty_spec());
3864        p.metadata.namespace = Some("prod".into());
3865        let mut status = ProcessStatus::default();
3866        status.attestation = attestation;
3867        p.status = Some(status);
3868        p
3869    }
3870
3871    #[test]
3872    fn observed_attestation_returns_none_when_status_is_none() {
3873        // Missing-`status` corner pin: the primitive collapses the
3874        // no-status case to `None` so downstream `.is_some()` /
3875        // `if let Some(_)` / `.map(...)` behave identically on a
3876        // `Process` whose status field is `None` and on one whose
3877        // status carries an unpopulated `attestation` slot.
3878        // Matches the pre-lift `.and_then(...)` chain's `None`
3879        // byte-identically at every reconciler consumer's
3880        // downstream shape.
3881        let mut p = Process::new("api", empty_spec());
3882        p.status = None;
3883        assert!(p.observed_attestation().is_none());
3884    }
3885
3886    #[test]
3887    fn observed_attestation_returns_none_when_attestation_slot_is_none() {
3888        // Empty-slot-under-populated-status corner pin: the
3889        // primitive returns `None`, matching the missing-`status`
3890        // corner byte-identically. A regression that treated the
3891        // two corners differently (a `None`-vs-`Some(_)` signal
3892        // that downstream consumers could grep on) would silently
3893        // promote an internal representation detail (whether the
3894        // reconciler has ever written a status subresource) into
3895        // observable behavior at the ATTEST composer's
3896        // seed-vs-chain branch.
3897        let p = process_with_attestation(None);
3898        assert!(p.observed_attestation().is_none());
3899    }
3900
3901    #[test]
3902    fn observed_attestation_returns_borrow_when_slot_is_populated() {
3903        // Happy-path pin: with a populated `status.attestation`
3904        // slot, the primitive returns a borrowed
3905        // `&ProcessAttestation` whose fields match the persisted
3906        // record. A regression that filtered / reshaped /
3907        // canonicalized the record would surface here rather than
3908        // as silent skew at the downstream `prior.next(pillars)`
3909        // chain composer + the ephemeral-export receipt's
3910        // `previous_root` linker.
3911        let att = sample_attestation("art-1", "int-1");
3912        let composed_root = att.composed_root.clone();
3913        let p = process_with_attestation(Some(att));
3914        let observed = p.observed_attestation().expect("populated slot");
3915        assert_eq!(observed.artifact_hash, "art-1");
3916        assert_eq!(observed.intent_hash, "int-1");
3917        assert_eq!(observed.composed_root, composed_root);
3918        assert_eq!(observed.generation, 0);
3919        assert!(observed.previous_root.is_none());
3920    }
3921
3922    #[test]
3923    fn observed_attestation_is_a_zero_copy_borrow_projection() {
3924        // Borrow-discipline pin: the returned reference points at
3925        // the persisted `ProcessAttestation` in place — NOT a fresh
3926        // allocation or a clone. A regression that switched the
3927        // projection to an owned `ProcessAttestation` (via
3928        // `.clone()`) would defeat the zero-copy contract the
3929        // lift's primary strict-widening delivers (the pre-lift
3930        // 3-line chain returned a borrow, but the export-Job
3931        // builder then cloned `composed_root` off it; the post-
3932        // lift primitive preserves the borrow all the way to the
3933        // consumer's own cloning choice). Peer to the sibling
3934        // `observed_pid_is_a_zero_copy_borrow_projection` +
3935        // `observed_flux_resources_is_a_zero_copy_borrow_projection`
3936        // pins on the PID + flux-resources borrow-projection axes.
3937        let att = sample_attestation("art-1", "int-1");
3938        let p = process_with_attestation(Some(att));
3939        let observed = p.observed_attestation().expect("populated slot") as *const _;
3940        let persisted = p.status.as_ref().unwrap().attestation.as_ref().unwrap() as *const _;
3941        assert!(std::ptr::eq(observed, persisted));
3942    }
3943
3944    #[test]
3945    fn observed_attestation_is_a_pure_projection() {
3946        // Purity pin: calling the projection twice on the same
3947        // `Process` returns byte-identical borrows (same pointer).
3948        // A regression that introduced state — a lazy-cached
3949        // reference materialized on first call, a normalization
3950        // step that ran once and cached — would surface here
3951        // rather than as silent drift between the ATTEST composer
3952        // and the ephemeral-export receipt chain on the SAME
3953        // `Process` within one reconcile pass.
3954        let att = sample_attestation("art-1", "int-1");
3955        let p = process_with_attestation(Some(att));
3956        let a = p.observed_attestation().expect("populated slot") as *const _;
3957        let b = p.observed_attestation().expect("populated slot") as *const _;
3958        assert!(std::ptr::eq(a, b));
3959    }
3960
3961    #[test]
3962    fn observed_attestation_matches_pre_lift_reconciler_chain_shape() {
3963        // Byte-identical parity pin between the borrow-form
3964        // primitive here and the pre-lift `tatara-reconciler`
3965        // 3-line chain shape. Sweeps every corner every callsite
3966        // plausibly encounters (missing status, empty attestation
3967        // slot, populated attestation slot). A regression that
3968        // inserted a normalization step at the primitive the pre-
3969        // lift chain does NOT apply — or vice versa — surfaces
3970        // here rather than as silent drift between the pre-lift
3971        // consumer sites and the ONE substrate owner they now
3972        // route through. Peer to
3973        // `observed_pid_matches_pre_lift_reconciler_chain_shape` +
3974        // `observed_flux_resources_matches_pre_lift_reconciler_chain_shape`
3975        // on the PID + flux-resources axes.
3976        // `ProcessAttestation` does not derive `PartialEq` — the
3977        // parity check walks the `composed_root` field (the
3978        // byte-string every downstream consumer keys off) so a
3979        // regression that reshaped the record without touching
3980        // the composed-root observation surfaces here through
3981        // the receipt-chain projection.
3982        fn pre_lift(p: &Process) -> Option<String> {
3983            p.status
3984                .as_ref()
3985                .and_then(|s| s.attestation.as_ref())
3986                .map(|a| a.composed_root.clone())
3987        }
3988        // Missing status.
3989        let mut p = Process::new("api", empty_spec());
3990        p.status = None;
3991        assert_eq!(
3992            p.observed_attestation().map(|a| a.composed_root.clone()),
3993            pre_lift(&p)
3994        );
3995        // Populated status, empty attestation slot.
3996        let p = process_with_attestation(None);
3997        assert_eq!(
3998            p.observed_attestation().map(|a| a.composed_root.clone()),
3999            pre_lift(&p)
4000        );
4001        // Populated status, populated attestation slot.
4002        let p = process_with_attestation(Some(sample_attestation("art-1", "int-1")));
4003        assert_eq!(
4004            p.observed_attestation().map(|a| a.composed_root.clone()),
4005            pre_lift(&p)
4006        );
4007    }
4008
4009    #[test]
4010    fn observed_attestation_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
4011        // Cross-corner coherence pin: the missing-`status` corner
4012        // and the populated-empty-slot corner return `Option`s
4013        // whose `.is_none()` observations are IDENTICAL. A
4014        // regression that promoted the missing-`status` corner to
4015        // returning a typed error (via a signature change to
4016        // `Result<_, _>`) — or that widened the empty-slot corner
4017        // to a synthetic `Some(default_attestation)` — would
4018        // surface here rather than as silent operator-facing
4019        // divergence between a never-status-written Process and
4020        // an attestation-emptied Process on the ATTEST composer's
4021        // seed-vs-chain branch.
4022        let mut p_no_status = Process::new("api", empty_spec());
4023        p_no_status.status = None;
4024        let p_empty_slot = process_with_attestation(None);
4025        assert_eq!(
4026            p_no_status.observed_attestation().is_none(),
4027            p_empty_slot.observed_attestation().is_none()
4028        );
4029        assert_eq!(
4030            p_no_status.observed_attestation().is_some(),
4031            p_empty_slot.observed_attestation().is_some()
4032        );
4033    }
4034
4035    #[test]
4036    fn observed_attestation_preserves_chain_generation_field() {
4037        // Generation-preservation pin: a chained attestation
4038        // (`prior.next(...)` at generation N ≥ 1 with a
4039        // `previous_root` linked to `prior.composed_root`) reaches
4040        // the caller with its `generation` counter + `previous_root`
4041        // link byte-identical to the persisted record. The pre-lift
4042        // ATTEST composer discriminated exactly on this borrow's
4043        // `Some(prior)` vs `None` arm; a regression that dropped
4044        // the chain's `generation` counter (say, by folding
4045        // `next(...)` into a fresh `initial(...)` on every
4046        // reconcile pass) would silently reset every chain and
4047        // orphan every downstream `previous_root` link, but that
4048        // drift is invisible to a Process CRD reader who only
4049        // observes the LATEST composed_root.
4050        let prior = sample_attestation("art-0", "int-0");
4051        let chained = prior.next("art-1".to_string(), None, "int-1".to_string());
4052        let expected_generation = chained.generation;
4053        let expected_previous = chained.previous_root.clone();
4054        let p = process_with_attestation(Some(chained));
4055        let observed = p.observed_attestation().expect("populated slot");
4056        assert_eq!(observed.generation, expected_generation);
4057        assert_eq!(observed.generation, 1);
4058        assert_eq!(observed.previous_root, expected_previous);
4059        assert_eq!(
4060            observed.previous_root.as_deref(),
4061            Some(prior.composed_root.as_str())
4062        );
4063    }
4064
4065    // ─── Process::observed_identity substrate pins ────────────────────
4066    //
4067    // The borrow-form status-projection primitive on the resolved-
4068    // identity axis. Collapses the paired 3-line `.status.as_ref()
4069    // .and_then(|s| s.identity.<clone|as_ref>())` chain every
4070    // consumer in `tatara-reconciler` restated by hand pre-lift at
4071    // TWO sites (`phase_machine::handle_forking` seed +
4072    // `ssapply::inject_annotations` content-hash annotation
4073    // composer). Peer to the sibling `observed_pid_*` +
4074    // `observed_attestation_*` + `observed_flux_resources_*` pin
4075    // families; all four compose the same missing-`status` fallback
4076    // + borrow-form return-shape skeleton on distinct
4077    // `ProcessStatus` slots. Each pin fails-before-pass-after
4078    // granularity: `observed_identity` did not exist pre-lift, so
4079    // any test invoking it fails to compile pre-lift and passes
4080    // post-lift.
4081
4082    fn sample_identity(name: &str) -> Identity {
4083        // Distinct name + content_hash + override flag so a
4084        // regression that reshaped one slot surfaces at the
4085        // populated-slot pin's field-equality check without
4086        // aliasing the sibling slots.
4087        Identity {
4088            name: name.to_string(),
4089            content_hash: "a".repeat(26),
4090            name_override: true,
4091        }
4092    }
4093
4094    fn process_with_identity(identity: Option<Identity>) -> Process {
4095        let mut p = Process::new("api-gateway", empty_spec());
4096        p.metadata.namespace = Some("prod".into());
4097        let mut status = ProcessStatus::default();
4098        status.identity = identity;
4099        p.status = Some(status);
4100        p
4101    }
4102
4103    #[test]
4104    fn observed_identity_returns_none_when_status_is_none() {
4105        // Missing-`status` corner pin: the primitive collapses the
4106        // no-status case to `None` so downstream `.is_some()` /
4107        // `if let Some(_)` / `.cloned().unwrap_or_else(...)` behave
4108        // identically on a `Process` whose status field is `None`
4109        // and on one whose status carries an unpopulated `identity`
4110        // slot. Matches the pre-lift `.and_then(...)` chain's `None`
4111        // byte-identically at every reconciler consumer's
4112        // downstream shape.
4113        let mut p = Process::new("api", empty_spec());
4114        p.status = None;
4115        assert!(p.observed_identity().is_none());
4116    }
4117
4118    #[test]
4119    fn observed_identity_returns_none_when_identity_slot_is_none() {
4120        // Empty-slot-under-populated-status corner pin: the
4121        // primitive returns `None`, matching the missing-`status`
4122        // corner byte-identically. A regression that treated the
4123        // two corners differently (a `None`-vs-`Some(_)` signal
4124        // that downstream consumers could grep on) would silently
4125        // promote an internal representation detail (whether the
4126        // reconciler has ever written a status subresource) into
4127        // observable behavior at the FORK-time `derive_identity`
4128        // fallback branch.
4129        let p = process_with_identity(None);
4130        assert!(p.observed_identity().is_none());
4131    }
4132
4133    #[test]
4134    fn observed_identity_returns_borrow_when_slot_is_populated() {
4135        // Happy-path pin: with a populated `status.identity` slot,
4136        // the primitive returns a borrowed `&Identity` whose fields
4137        // match the persisted record. A regression that filtered /
4138        // reshaped / canonicalized the record would surface here
4139        // rather than as silent skew at the FORK-time seed's
4140        // `.cloned().unwrap_or_else(derive_identity)` composition
4141        // + the SSA-time content-hash annotation stamp on the SAME
4142        // Process.
4143        let id = sample_identity("seph");
4144        let expected = id.clone();
4145        let p = process_with_identity(Some(id));
4146        let observed = p.observed_identity().expect("populated slot");
4147        assert_eq!(observed, &expected);
4148        assert_eq!(observed.name, "seph");
4149        assert_eq!(observed.content_hash, "a".repeat(26));
4150        assert!(observed.name_override);
4151    }
4152
4153    #[test]
4154    fn observed_identity_is_a_zero_copy_borrow_projection() {
4155        // Borrow-discipline pin: the returned reference points at
4156        // the persisted `Identity` in place — NOT a fresh
4157        // allocation or a clone. A regression that switched the
4158        // projection to an owned `Identity` (via `.clone()`) would
4159        // defeat the zero-copy contract the lift's primary strict-
4160        // widening delivers (the SSA-time consumer never clones the
4161        // whole `Identity`, only the `content_hash` field it stamps
4162        // onto the annotation map, so the borrow-form return
4163        // shape's happy-path allocation count is exactly ZERO).
4164        // Peer to the sibling
4165        // `observed_attestation_is_a_zero_copy_borrow_projection`
4166        // + `observed_pid_is_a_zero_copy_borrow_projection` +
4167        // `observed_flux_resources_is_a_zero_copy_borrow_projection`
4168        // pins on the attestation-chain + PID + flux-resources
4169        // borrow-projection axes.
4170        let id = sample_identity("seph");
4171        let p = process_with_identity(Some(id));
4172        let observed = p.observed_identity().expect("populated slot") as *const _;
4173        let persisted = p.status.as_ref().unwrap().identity.as_ref().unwrap() as *const _;
4174        assert!(std::ptr::eq(observed, persisted));
4175    }
4176
4177    #[test]
4178    fn observed_identity_is_a_pure_projection() {
4179        // Purity pin: calling the projection twice on the same
4180        // `Process` returns byte-identical borrows (same pointer).
4181        // A regression that introduced state — a lazy-cached
4182        // reference materialized on first call, a normalization
4183        // step that ran once and cached — would surface here
4184        // rather than as silent drift between the FORK-time
4185        // identity seed and the SSA-time content-hash annotation
4186        // stamp on the SAME `Process` within one reconcile pass.
4187        let p = process_with_identity(Some(sample_identity("seph")));
4188        let a = p.observed_identity().expect("populated slot") as *const _;
4189        let b = p.observed_identity().expect("populated slot") as *const _;
4190        assert!(std::ptr::eq(a, b));
4191    }
4192
4193    #[test]
4194    fn observed_identity_matches_pre_lift_reconciler_chain_shape() {
4195        // Byte-identical parity pin between the borrow-form
4196        // primitive here and the pre-lift `tatara-reconciler`
4197        // 3-line chain shape. Sweeps every corner every callsite
4198        // plausibly encounters (missing status, empty identity
4199        // slot, populated identity slot). A regression that
4200        // inserted a normalization step at the primitive the pre-
4201        // lift chain does NOT apply — or vice versa — surfaces
4202        // here rather than as silent drift between the pre-lift
4203        // consumer sites and the ONE substrate owner they now
4204        // route through. Peer to
4205        // `observed_attestation_matches_pre_lift_reconciler_chain_shape`
4206        // + `observed_pid_matches_pre_lift_reconciler_chain_shape`
4207        // + `observed_flux_resources_matches_pre_lift_reconciler_chain_shape`
4208        // on the attestation-chain + PID + flux-resources axes.
4209        fn pre_lift(p: &Process) -> Option<Identity> {
4210            p.status.as_ref().and_then(|s| s.identity.clone())
4211        }
4212        // Missing status.
4213        let mut p = Process::new("api", empty_spec());
4214        p.status = None;
4215        assert_eq!(p.observed_identity().cloned(), pre_lift(&p));
4216        // Populated status, empty identity slot.
4217        let p = process_with_identity(None);
4218        assert_eq!(p.observed_identity().cloned(), pre_lift(&p));
4219        // Populated status, populated identity slot.
4220        let p = process_with_identity(Some(sample_identity("seph")));
4221        assert_eq!(p.observed_identity().cloned(), pre_lift(&p));
4222    }
4223
4224    #[test]
4225    fn observed_identity_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
4226        // Cross-corner coherence pin: the missing-`status` corner
4227        // and the populated-empty-slot corner return `Option`s
4228        // whose `.is_none()` observations are IDENTICAL. A
4229        // regression that promoted the missing-`status` corner to
4230        // returning a typed error (via a signature change to
4231        // `Result<_, _>`) — or that widened the empty-slot corner
4232        // to a synthetic `Some(derive_identity(default_spec))` —
4233        // would surface here rather than as silent operator-facing
4234        // divergence between a never-status-written Process and an
4235        // identity-cleared Process on the FORK-time seed branch.
4236        let mut p_no_status = Process::new("api", empty_spec());
4237        p_no_status.status = None;
4238        let p_empty_slot = process_with_identity(None);
4239        assert_eq!(
4240            p_no_status.observed_identity().is_none(),
4241            p_empty_slot.observed_identity().is_none()
4242        );
4243        assert_eq!(
4244            p_no_status.observed_identity().is_some(),
4245            p_empty_slot.observed_identity().is_some()
4246        );
4247    }
4248
4249    #[test]
4250    fn observed_identity_cloned_composes_with_derive_identity_fallback() {
4251        // Cross-primitive composition pin: the borrow-form
4252        // primitive threaded through `.cloned().unwrap_or_else(||
4253        // derive_identity(...))` reproduces the pre-lift FORK-time
4254        // seed's owned-`Identity` shape at every corner. Binds the
4255        // exact composition the `phase_machine::handle_forking`
4256        // consumer performs: on the populated-slot corner the
4257        // reconciler-persisted `Identity` is returned verbatim (the
4258        // fallback never fires), and on both empty corners
4259        // (missing-status + empty-slot) the fallback fires
4260        // producing a fresh `derive_identity(&spec,
4261        // name_override)`. A regression that (a) swapped the
4262        // fallback direction, (b) made `.cloned()` re-derive
4263        // instead of clone, or (c) made the empty-slot corner
4264        // return a synthetic `Some(default_identity)` collides
4265        // with the fallback surfaces here rather than as silent
4266        // FORK-time PID allocator skew.
4267        let spec = empty_spec();
4268        let fallback_expected = crate::identity::derive_identity(&spec, None);
4269        // Populated-slot corner: the seed returns the persisted
4270        // identity, NOT the derive fallback.
4271        let persisted = sample_identity("seph");
4272        let p = process_with_identity(Some(persisted.clone()));
4273        let seed = p.observed_identity().cloned().unwrap_or_else(|| {
4274            crate::identity::derive_identity(&p.spec, p.declared_name_override())
4275        });
4276        assert_eq!(seed, persisted);
4277        assert_ne!(seed, fallback_expected);
4278        // Empty-slot corner: the seed fires the derive fallback.
4279        let p = process_with_identity(None);
4280        let seed = p.observed_identity().cloned().unwrap_or_else(|| {
4281            crate::identity::derive_identity(&p.spec, p.declared_name_override())
4282        });
4283        assert_eq!(seed, fallback_expected);
4284        // Missing-status corner: the seed fires the derive
4285        // fallback, byte-identical to the empty-slot corner.
4286        let mut p = Process::new("api-gateway", empty_spec());
4287        p.metadata.namespace = Some("prod".into());
4288        p.status = None;
4289        let seed = p.observed_identity().cloned().unwrap_or_else(|| {
4290            crate::identity::derive_identity(&p.spec, p.declared_name_override())
4291        });
4292        assert_eq!(seed, fallback_expected);
4293    }
4294
4295    // ─── Process::observed_phase substrate pins ───────────────────────
4296    //
4297    // The copy-form status-projection primitive on the phase axis.
4298    // Collapses the paired 3-line `.status.as_ref().map(|s| s.phase)`
4299    // chain every consumer in `tatara-reconciler` restated by hand
4300    // pre-lift at FIVE sites. Peer to the borrow-form
4301    // `observed_pid_*` + `observed_flux_resources_*` +
4302    // `observed_attestation_*` pin families; all four compose the
4303    // same missing-`status` fallback skeleton on distinct
4304    // `ProcessStatus` slots, with the phase-axis form returning
4305    // `Option<ProcessPhase>` (copy of a `Copy` scalar) rather than
4306    // `Option<&T>` (borrow) because the underlying slot is a bare
4307    // `ProcessPhase` — no allocation to borrow past, and the enum
4308    // is one byte on the wire. Each pin fails-before-pass-after
4309    // granularity: `observed_phase` did not exist pre-lift, so any
4310    // test invoking it fails to compile pre-lift and passes
4311    // post-lift.
4312
4313    fn process_with_phase(phase: Option<ProcessPhase>) -> Process {
4314        let mut p = Process::new("api-gateway", empty_spec());
4315        p.metadata.namespace = Some("prod".into());
4316        if let Some(ph) = phase {
4317            let mut status = ProcessStatus::default();
4318            status.phase = ph;
4319            p.status = Some(status);
4320        }
4321        p
4322    }
4323
4324    #[test]
4325    fn observed_phase_returns_none_when_status_is_none() {
4326        // Missing-`status` corner pin: the primitive collapses the
4327        // no-status case to `None` so downstream `.unwrap_or(...)`
4328        // at every reconciler consumer chooses the default
4329        // deliberately (`Pending` for the top-level dispatch seed
4330        // + boundary evaluator + routing groupby; `Attested` for
4331        // the released-from annotation composer). Matches the
4332        // pre-lift `.map(|s| s.phase)` chain's `None`
4333        // byte-identically at every consumer's downstream shape.
4334        let mut p = Process::new("api", empty_spec());
4335        p.status = None;
4336        assert!(p.observed_phase().is_none());
4337    }
4338
4339    #[test]
4340    fn observed_phase_returns_some_default_when_status_is_populated_with_default_phase() {
4341        // Populated-status corner pin: the primitive returns
4342        // `Some(ProcessPhase::default())` — a `ProcessStatus`
4343        // constructed via `default()` carries `phase: Pending`
4344        // because the phase field is a bare `ProcessPhase` (not
4345        // `Option<ProcessPhase>`), so there is NO "empty slot"
4346        // corner peer to the borrow-form projections' empty-slot
4347        // pins. A regression that reshaped the return type to
4348        // filter out `Pending` (treating it as "unset") would
4349        // surface here and silently break the top-level
4350        // dispatcher's Pending → Forking transition on a Process
4351        // freshly written by the reconciler.
4352        let p = process_with_phase(Some(ProcessPhase::default()));
4353        assert_eq!(p.observed_phase(), Some(ProcessPhase::Pending));
4354        assert_eq!(p.observed_phase(), Some(ProcessPhase::default()));
4355    }
4356
4357    #[test]
4358    fn observed_phase_returns_persisted_phase_when_status_is_populated() {
4359        // Happy-path pin: with a populated `status.phase` slot,
4360        // the primitive returns the persisted `ProcessPhase`.
4361        // A regression that filtered / reshaped / canonicalized
4362        // the phase would surface here rather than as silent
4363        // skew at the top-level dispatcher's phase handler
4364        // dispatch on the SAME Process.
4365        let p = process_with_phase(Some(ProcessPhase::Running));
4366        assert_eq!(p.observed_phase(), Some(ProcessPhase::Running));
4367    }
4368
4369    #[test]
4370    fn observed_phase_is_a_pure_projection() {
4371        // Purity pin: two consecutive calls return byte-identical
4372        // `Option<ProcessPhase>` values (no lazy materialization,
4373        // no interior mutation of `self`). Peer to the sibling
4374        // `observed_pid_is_a_pure_projection` +
4375        // `observed_flux_resources_is_a_pure_projection` +
4376        // `observed_attestation_is_a_pure_projection` pins; all
4377        // four bind the pure-projection discipline on the ONE
4378        // substrate accessor per status slot.
4379        let p = process_with_phase(Some(ProcessPhase::Attested));
4380        let a = p.observed_phase();
4381        let b = p.observed_phase();
4382        assert_eq!(a, b);
4383        assert_eq!(a, Some(ProcessPhase::Attested));
4384    }
4385
4386    #[test]
4387    fn observed_phase_matches_pre_lift_reconciler_chain_shape() {
4388        // Parity pin: sweeps the two corners every pre-lift
4389        // consumer plausibly encountered (missing status,
4390        // populated status with a particular phase) and compares
4391        // the substrate call against a hand-authored pre-lift
4392        // chain byte-identically. A regression that reshaped ANY
4393        // of the two corners would surface here rather than as
4394        // silent operator-facing skew between the top-level
4395        // dispatcher and any of the four other reconciler
4396        // consumers on the SAME `Process`.
4397        fn pre_lift(p: &Process) -> Option<ProcessPhase> {
4398            p.status.as_ref().map(|s| s.phase)
4399        }
4400        let mut p = Process::new("api", empty_spec());
4401        p.status = None;
4402        assert_eq!(p.observed_phase(), pre_lift(&p));
4403        let p = process_with_phase(Some(ProcessPhase::Running));
4404        assert_eq!(p.observed_phase(), pre_lift(&p));
4405        let p = process_with_phase(Some(ProcessPhase::Attested));
4406        assert_eq!(p.observed_phase(), pre_lift(&p));
4407        let p = process_with_phase(Some(ProcessPhase::Failed));
4408        assert_eq!(p.observed_phase(), pre_lift(&p));
4409    }
4410
4411    #[test]
4412    fn observed_phase_default_unwrap_matches_pre_lift_pending_default() {
4413        // Callsite-shape pin: three of the FIVE pre-lift consumers
4414        // (`controller::reconcile`, `boundary::evaluate_process_phase`,
4415        // `table_controller::stable_name_group_key`) closed the
4416        // 3-line chain with `.unwrap_or(ProcessPhase::Pending)`
4417        // (identical to `.unwrap_or_default()`). This pin binds
4418        // that call-site shape: `observed_phase().unwrap_or
4419        // (Pending)` returns `Pending` on missing status and the
4420        // persisted phase otherwise. A regression that swapped
4421        // the `None` sentinel's downstream default would surface
4422        // here rather than as silent skew at three of the five
4423        // consumer sites.
4424        let mut p = Process::new("api", empty_spec());
4425        p.status = None;
4426        assert_eq!(
4427            p.observed_phase().unwrap_or(ProcessPhase::Pending),
4428            ProcessPhase::Pending
4429        );
4430        let p = process_with_phase(Some(ProcessPhase::Running));
4431        assert_eq!(
4432            p.observed_phase().unwrap_or(ProcessPhase::Pending),
4433            ProcessPhase::Running
4434        );
4435    }
4436
4437    #[test]
4438    fn observed_phase_attested_unwrap_matches_pre_lift_released_from_default() {
4439        // Callsite-shape pin: the ONE pre-lift consumer
4440        // (`phase_machine::p_current_phase_str` — the
4441        // released-from annotation composer) closed the 3-line
4442        // chain with `.unwrap_or(ProcessPhase::Attested)` rather
4443        // than the `Default` (`Pending`). This pin binds that
4444        // call-site shape: `observed_phase().unwrap_or(Attested)`
4445        // returns `Attested` on missing status and the persisted
4446        // phase otherwise. A regression that folded the
4447        // `Attested`-default consumer into the `Pending`-default
4448        // majority would break the SIGSTOP/SIGCONT release gate's
4449        // "which annotation label to emit" branch — the pin binds
4450        // the primitive at the raw `Option<ProcessPhase>` form so
4451        // this default choice stays local at the callsite.
4452        let mut p = Process::new("api", empty_spec());
4453        p.status = None;
4454        assert_eq!(
4455            p.observed_phase().unwrap_or(ProcessPhase::Attested),
4456            ProcessPhase::Attested
4457        );
4458        let p = process_with_phase(Some(ProcessPhase::Failed));
4459        assert_eq!(
4460            p.observed_phase().unwrap_or(ProcessPhase::Attested),
4461            ProcessPhase::Failed
4462        );
4463    }
4464
4465    #[test]
4466    fn observed_phase_preserves_every_process_phase_variant() {
4467        // Round-trip pin: every `ProcessPhase` variant round-
4468        // trips through the primitive unchanged. Peer to the
4469        // sibling `observed_pid_preserves_hierarchical_pid_format`
4470        // pin's dotted-segment sweep; this pin sweeps the closed
4471        // set of `ProcessPhase` variants directly so a
4472        // canonicalization pass that dropped or reshaped one
4473        // (e.g. folded `Reconverging` back into `Execing`, or
4474        // remapped `Zombie` to `Reaped`) surfaces here rather
4475        // than as silent skew at the SIGSTOP/SIGCONT release
4476        // gate's phase-name annotation branch. Covers every
4477        // variant the `ProcessPhase::DeriveClosedSet` enumerates
4478        // so a future variant addition surfaces via the closed-
4479        // set macro rather than at a silent partial sweep.
4480        for phase in [
4481            ProcessPhase::Pending,
4482            ProcessPhase::Forking,
4483            ProcessPhase::Execing,
4484            ProcessPhase::Running,
4485            ProcessPhase::Attested,
4486            ProcessPhase::Reconverging,
4487            ProcessPhase::Releasing,
4488            ProcessPhase::Exiting,
4489            ProcessPhase::Failed,
4490            ProcessPhase::Zombie,
4491            ProcessPhase::Reaped,
4492        ] {
4493            let p = process_with_phase(Some(phase));
4494            assert_eq!(
4495                p.observed_phase(),
4496                Some(phase),
4497                "phase variant {phase:?} did not round-trip"
4498            );
4499        }
4500    }
4501
4502    // ─── Process::observed_phase_or_pending substrate pins ─────────────
4503    //
4504    // Pins the copy-form status-projection primitive on the phase
4505    // axis with the `Pending` sink applied. Sibling to the raw
4506    // `observed_phase_*` pin family on the (return-form × fallback
4507    // shape) axis pair — the raw-`Option` corner stays with the
4508    // sibling family; this pin family opens the `Pending`-defaulted
4509    // corner that four of the five pre-lift `observed_phase`
4510    // consumers wrote by hand. Fail-before-pass-after granularity:
4511    // `observed_phase_or_pending` did not exist pre-lift, so any
4512    // test invoking it fails to compile pre-lift and passes
4513    // post-lift.
4514
4515    #[test]
4516    fn observed_phase_or_pending_returns_pending_when_status_is_none() {
4517        // Missing-`status` corner pin: the primitive collapses the
4518        // no-status case to `Pending` — the sink four of the five
4519        // pre-lift `observed_phase` consumers wrote by hand
4520        // (`controller::reconcile` / `boundary::
4521        // evaluate_process_phase` / `table_controller::
4522        // stable_name_group_key` / `controller_pool::reconcile_pool`)
4523        // and the sentinel `ProcessPhase::default()` returns. A
4524        // regression that folded the `None` sink to any other phase
4525        // (e.g. `Forking` — treating "not yet observed" as "already
4526        // dispatched") would silently mis-seed the top-level
4527        // dispatcher's `Pending → Forking` transition and surface as
4528        // operator-visible reconcile-cycle skew on a freshly-forked
4529        // Process rather than at this pin.
4530        let mut p = Process::new("api", empty_spec());
4531        p.status = None;
4532        assert_eq!(p.observed_phase_or_pending(), ProcessPhase::Pending);
4533    }
4534
4535    #[test]
4536    fn observed_phase_or_pending_returns_persisted_phase_when_status_is_populated() {
4537        // Populated-status corner pin: the primitive passes through
4538        // the persisted `ProcessPhase` unchanged — the sink only
4539        // fires on missing `status`, not on a populated one carrying
4540        // a `Pending`-adjacent variant. Two variants pinned to
4541        // separate the "pass through the persisted phase" arm from
4542        // the "sink fires" arm: `Running` (mid-lifecycle) and
4543        // `Attested` (post-verify) both round-trip unchanged where
4544        // a regression that always returned `Pending` (dropped the
4545        // pass-through arm entirely) would surface here rather than
4546        // as silent skew at every reconciler's per-phase branch.
4547        let p = process_with_phase(Some(ProcessPhase::Running));
4548        assert_eq!(p.observed_phase_or_pending(), ProcessPhase::Running);
4549        let p = process_with_phase(Some(ProcessPhase::Attested));
4550        assert_eq!(p.observed_phase_or_pending(), ProcessPhase::Attested);
4551    }
4552
4553    #[test]
4554    fn observed_phase_or_pending_matches_pre_lift_unwrap_or_pending_chain_shape() {
4555        // Byte-identical parity pin: the primitive's return equals
4556        // the pre-lift two-link `.observed_phase().unwrap_or
4557        // (ProcessPhase::Pending)` chain at every one of the four
4558        // corner values (missing `status` → `Pending`, populated
4559        // with `Pending` → `Pending`, populated with a mid-lifecycle
4560        // variant → pass-through, populated with a terminal variant
4561        // → pass-through). A regression that swapped the sink to
4562        // `ProcessPhase::default()` (currently equivalent to
4563        // `Pending`) would keep this pin green until the enum's
4564        // `Default` impl drifted — the explicit `Pending` spelling
4565        // in the pin binds the operator-visible label rather than
4566        // the derived `Default`, so a future rename or reordering
4567        // of `ProcessPhase` variants that shifted `Default` off
4568        // `Pending` would surface here rather than as silent skew
4569        // at the four downstream consumer sites.
4570        let pre_lift = |p: &Process| p.observed_phase().unwrap_or(ProcessPhase::Pending);
4571        let mut p = Process::new("api", empty_spec());
4572        p.status = None;
4573        assert_eq!(p.observed_phase_or_pending(), pre_lift(&p));
4574        let p = process_with_phase(Some(ProcessPhase::Pending));
4575        assert_eq!(p.observed_phase_or_pending(), pre_lift(&p));
4576        let p = process_with_phase(Some(ProcessPhase::Running));
4577        assert_eq!(p.observed_phase_or_pending(), pre_lift(&p));
4578        let p = process_with_phase(Some(ProcessPhase::Reaped));
4579        assert_eq!(p.observed_phase_or_pending(), pre_lift(&p));
4580    }
4581
4582    #[test]
4583    fn observed_phase_or_pending_is_a_pure_projection() {
4584        // Purity pin: two back-to-back calls on the same `Process`
4585        // return the same `ProcessPhase` — the primitive stamps no
4586        // side effect (no clock read, no metadata write, no
4587        // `status` mutation) despite the sibling `observed_phase`
4588        // taking `&self` too. Peer to the sibling `observed_phase`
4589        // purity pin; a regression that folded a clock read (e.g.
4590        // "if the sink fired, stamp `phase_since = Utc::now()`")
4591        // into the primitive would surface here rather than at the
4592        // consumer sites' downstream reconcile-cycle behavior.
4593        let p = process_with_phase(Some(ProcessPhase::Running));
4594        let a = p.observed_phase_or_pending();
4595        let b = p.observed_phase_or_pending();
4596        assert_eq!(a, b);
4597    }
4598
4599    #[test]
4600    fn observed_phase_or_pending_preserves_every_process_phase_variant() {
4601        // Round-trip pin: every `ProcessPhase` variant round-trips
4602        // through the primitive unchanged when the `status` slot is
4603        // populated. Peer to the sibling `observed_phase_preserves
4604        // _every_process_phase_variant` sweep; this pin sweeps the
4605        // closed set through the `Pending`-sinked accessor rather
4606        // than the raw-`Option` accessor so a canonicalization pass
4607        // that dropped or reshaped one variant (e.g. folded
4608        // `Reconverging` back into `Execing`, remapped `Zombie` to
4609        // `Reaped`) surfaces at BOTH primitives' pin sets rather
4610        // than as silent skew at a subset of the reconciler
4611        // consumers. Covers every variant the
4612        // `ProcessPhase::DeriveClosedSet` enumerates so a future
4613        // variant addition surfaces via the closed-set macro rather
4614        // than at a silent partial sweep.
4615        for phase in [
4616            ProcessPhase::Pending,
4617            ProcessPhase::Forking,
4618            ProcessPhase::Execing,
4619            ProcessPhase::Running,
4620            ProcessPhase::Attested,
4621            ProcessPhase::Reconverging,
4622            ProcessPhase::Releasing,
4623            ProcessPhase::Exiting,
4624            ProcessPhase::Failed,
4625            ProcessPhase::Zombie,
4626            ProcessPhase::Reaped,
4627        ] {
4628            let p = process_with_phase(Some(phase));
4629            assert_eq!(
4630                p.observed_phase_or_pending(),
4631                phase,
4632                "phase variant {phase:?} did not round-trip through observed_phase_or_pending"
4633            );
4634        }
4635    }
4636
4637    // ─── Process::observed_phase_since substrate pins ──────────────────
4638    //
4639    // Pins the copy-form status-projection primitive on the
4640    // `status.phase_since` axis that owns the paired 5-line
4641    // `.status.as_ref().and_then(|s| s.phase_since).unwrap_or_else
4642    // (Utc::now)` chain the pool reconciler's per-owned-Process
4643    // `PoolMember { entered_state_at: … }` seed restated by hand pre-
4644    // lift. Peer to the sibling `observed_phase_*` +
4645    // `observed_identity_*` + `observed_attestation_*` +
4646    // `observed_flux_resources_*` + `observed_pid_*` + `created_at_*`
4647    // pin families — all six / seven primitives project a wire-format
4648    // `Option<T>` slot into a `Copy`-or-borrow inner value at ONE
4649    // owner. Fail-before-pass-after granularity: `observed_phase_since`
4650    // did not exist pre-lift, so any test invoking it fails to
4651    // compile pre-lift and passes post-lift.
4652
4653    fn process_with_phase_since(phase_since: Option<DateTime<Utc>>) -> Process {
4654        let mut p = Process::new("api-gateway", empty_spec());
4655        p.metadata.namespace = Some("prod".into());
4656        let mut status = ProcessStatus::default();
4657        status.phase_since = phase_since;
4658        p.status = Some(status);
4659        p
4660    }
4661
4662    #[test]
4663    fn observed_phase_since_returns_none_when_status_is_none() {
4664        // Missing-`status` corner pin: the primitive collapses the
4665        // no-status case to `None` so the pool reconciler's `PoolMember
4666        // { entered_state_at: p.observed_phase_since().unwrap_or_else
4667        // (Utc::now), .. }` seed synthesizes a "just entered" anchor
4668        // at its own tail rather than materializing a stale timestamp
4669        // at the substrate. Matches the pre-lift `.and_then(|s| s
4670        // .phase_since)` chain's `None` byte-identically at the
4671        // consumer's downstream tail.
4672        let mut p = Process::new("api", empty_spec());
4673        p.status = None;
4674        assert!(p.observed_phase_since().is_none());
4675    }
4676
4677    #[test]
4678    fn observed_phase_since_returns_none_when_slot_is_empty() {
4679        // Populated-status + empty-slot corner pin: a `ProcessStatus`
4680        // whose `phase_since` slot is `None` (a freshly-forked
4681        // Process whose reconciler has not yet stamped a first
4682        // transition) collapses to `None` at the primitive. The
4683        // paired-corner collapse with the missing-`status` corner
4684        // (both → `None`) matches what `.and_then` produces
4685        // structurally — one `None` cannot recover into a `Some` at
4686        // the flat outer wrapper. A regression that swapped the outer
4687        // combinator to `.map(|s| s.phase_since)` would flatten to
4688        // `Option<Option<_>>` and the compiler would reject the
4689        // signature, but a regression that "synthesized" a default
4690        // anchor at the substrate (e.g. `Utc::now()` on the empty
4691        // slot) would silently break the callsite's own
4692        // `.unwrap_or_else(Utc::now)` tail's semantics — the sink
4693        // fires ONCE at the callsite, not twice.
4694        let p = process_with_phase_since(None);
4695        assert!(p.observed_phase_since().is_none());
4696    }
4697
4698    #[test]
4699    fn observed_phase_since_returns_populated_timestamp_verbatim() {
4700        // Populated-slot corner pin: with a populated `status
4701        // .phase_since` slot, the primitive returns the persisted
4702        // `DateTime<Utc>` verbatim — no rounding, no timezone
4703        // stripping, no `Time` wrapper leaked. A regression that
4704        // canonicalized the timestamp (e.g. truncated to the second,
4705        // stripped the timezone marker) would surface here rather
4706        // than as silent skew at the pool reconciler's per-member
4707        // entered-state-at seed comparison against `Utc::now()`
4708        // downstream at `pool_phase_from_members`.
4709        let anchor = Utc::now() - chrono::Duration::seconds(720);
4710        let p = process_with_phase_since(Some(anchor));
4711        assert_eq!(p.observed_phase_since(), Some(anchor));
4712    }
4713
4714    #[test]
4715    fn observed_phase_since_is_a_pure_projection() {
4716        // Purity pin: two consecutive calls return byte-identical
4717        // `Option<DateTime<Utc>>` values (no lazy materialization,
4718        // no interior mutation of `self`, no wall-clock read on the
4719        // empty corner). Peer to the sibling
4720        // `is_being_deleted_is_a_pure_projection` +
4721        // `created_at_is_a_pure_projection` +
4722        // `observed_phase_is_a_pure_projection` +
4723        // `observed_phase_or_pending_is_a_pure_projection` pins; all
4724        // five bind the pure-projection discipline on the ONE
4725        // substrate accessor per metadata / status slot. A
4726        // regression that folded the impure `Utc::now()` sink into
4727        // this primitive (rather than keeping it at the callsite's
4728        // `.unwrap_or_else(Utc::now)` tail alongside the sibling
4729        // `created_at` seed) would surface here as two consecutive
4730        // calls that returned distinct `Some(now_1)` /
4731        // `Some(now_2)` values.
4732        let anchor = Utc::now() - chrono::Duration::seconds(5);
4733        let p = process_with_phase_since(Some(anchor));
4734        let a = p.observed_phase_since();
4735        let b = p.observed_phase_since();
4736        assert_eq!(a, b);
4737        assert_eq!(a, Some(anchor));
4738        // Empty-slot corner: pure `None`, not a fresh `Utc::now()`.
4739        let p_empty = process_with_phase_since(None);
4740        let a = p_empty.observed_phase_since();
4741        let b = p_empty.observed_phase_since();
4742        assert_eq!(a, b);
4743        assert!(a.is_none());
4744    }
4745
4746    #[test]
4747    fn observed_phase_since_matches_pre_lift_pool_reconciler_chain_shape() {
4748        // Byte-identical parity pin between the copy-form primitive
4749        // here and the pre-lift `tatara-pool-reconciler::
4750        // controller_pool::reconcile_inner` 5-line chain shape
4751        // (without the callsite's `.unwrap_or_else(Utc::now)` tail —
4752        // that tail stays at the callsite). Sweeps every corner
4753        // every pre-lift callsite plausibly encountered: missing
4754        // `status`, populated `status` + empty `phase_since` slot,
4755        // populated `status` + populated `phase_since` slot. A
4756        // regression that inserted a normalization step at the
4757        // primitive the pre-lift chain does NOT apply — or vice
4758        // versa — surfaces here rather than as silent drift between
4759        // the pre-lift consumer site and the ONE substrate owner it
4760        // now routes through.
4761        fn pre_lift(p: &Process) -> Option<DateTime<Utc>> {
4762            p.status.as_ref().and_then(|s| s.phase_since)
4763        }
4764        // Missing status.
4765        let mut p = Process::new("x", empty_spec());
4766        p.status = None;
4767        assert_eq!(p.observed_phase_since(), pre_lift(&p));
4768        // Populated status, empty slot.
4769        let p = process_with_phase_since(None);
4770        assert_eq!(p.observed_phase_since(), pre_lift(&p));
4771        // Populated status, populated slot.
4772        let anchor = Utc::now() - chrono::Duration::seconds(90);
4773        let p = process_with_phase_since(Some(anchor));
4774        assert_eq!(p.observed_phase_since(), pre_lift(&p));
4775    }
4776
4777    #[test]
4778    fn observed_phase_since_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
4779        // Cross-corner coherence pin: the missing-`status` corner
4780        // AND the populated-empty-slot corner return `Option`s
4781        // whose `.is_none()` observations are IDENTICAL — a
4782        // shape peer to `observed_identity_missing_status_and_empty
4783        // _slot_collapse_to_the_same_option_shape`. A regression
4784        // that promoted the missing-`status` corner to returning a
4785        // typed error (via a signature change to `Result<_, _>`) —
4786        // or that widened the empty-slot corner to a synthetic
4787        // `Some(Utc::now())` at the substrate — would surface here
4788        // rather than as silent operator-facing divergence between
4789        // a never-status-written Process and a phase-since-cleared
4790        // Process at the pool reconciler's per-member row builder.
4791        let mut p_no_status = Process::new("api", empty_spec());
4792        p_no_status.status = None;
4793        let p_empty_slot = process_with_phase_since(None);
4794        assert_eq!(
4795            p_no_status.observed_phase_since().is_none(),
4796            p_empty_slot.observed_phase_since().is_none()
4797        );
4798        assert_eq!(
4799            p_no_status.observed_phase_since().is_some(),
4800            p_empty_slot.observed_phase_since().is_some()
4801        );
4802    }
4803
4804    #[test]
4805    fn observed_phase_since_composes_with_unwrap_or_else_utc_now_tail_at_pool_seed() {
4806        // Call-site-shape pin: the `tatara-pool-reconciler::
4807        // controller_pool::reconcile_inner` per-owned-Process
4808        // `PoolMember { entered_state_at: … }` seed composes
4809        // `p.observed_phase_since().unwrap_or_else(Utc::now)`. A
4810        // regression that returned `Some(Utc::now())` on the empty
4811        // corner (folding the sink into the primitive) would break
4812        // the observable contract that a caller with a distinct
4813        // now-source (e.g. an injected `time_source: impl Fn() ->
4814        // DateTime<Utc>`, or a test-time frozen clock) could
4815        // substitute at the tail — this pin binds the empty-corner
4816        // shape by observing that the substrate returns `None` (so
4817        // the `.unwrap_or_else` runs at the callsite) and that the
4818        // populated-corner shape is byte-identical between the
4819        // substrate `Some(anchor)` and the composed
4820        // `Some(anchor).unwrap_or_else(...)` (the fallback never
4821        // fires when the corner is populated). Peer to
4822        // `created_at_composes_with_signed_duration_since_at_ttl_gate`
4823        // on the metadata-timestamp side — both bind the
4824        // composition shape at the callsite so a substrate-side
4825        // refactor cannot silently break the tail semantics.
4826        let anchor = Utc::now() - chrono::Duration::seconds(30);
4827        // Populated corner: substrate returns `Some(anchor)` and
4828        // the composed tail returns `anchor` (fallback silent).
4829        let p = process_with_phase_since(Some(anchor));
4830        let composed = p.observed_phase_since().unwrap_or_else(Utc::now);
4831        assert_eq!(composed, anchor);
4832        // Empty corner: substrate returns `None` and the composed
4833        // tail fires `Utc::now()` at the callsite (observed as a
4834        // timestamp >= a `before` sample AND close to now).
4835        let before = Utc::now();
4836        let p = process_with_phase_since(None);
4837        assert!(p.observed_phase_since().is_none());
4838        let composed = p.observed_phase_since().unwrap_or_else(Utc::now);
4839        assert!(composed >= before);
4840        assert!(composed <= Utc::now() + chrono::Duration::seconds(1));
4841    }
4842
4843    // ─── Process::is_being_deleted substrate pins ───────────────────────
4844    //
4845    // Pins the copy-form metadata-projection primitive on the
4846    // deletion-tombstone axis. Peer to the borrow-form + copy-form
4847    // metadata-fallback family (`namespace_or_default`,
4848    // `name_or_placeholder`, `uid_or_empty`, `coordinates_or_defaults`,
4849    // `coordinates_or_none`, `owned_coordinates_or_err`, `annotation`);
4850    // this one opens the presence-probe corner for the tombstone slot.
4851    // Fail-before-pass-after granularity: `is_being_deleted` did not
4852    // exist pre-lift, so any test invoking it fails to compile pre-
4853    // lift and passes post-lift.
4854
4855    fn tombstoned_process() -> Process {
4856        let mut p = Process::new("api-gateway", empty_spec());
4857        p.metadata.namespace = Some("prod".into());
4858        p.metadata.deletion_timestamp = Some(k8s_openapi::apimachinery::pkg::apis::meta::v1::Time(
4859            Utc::now(),
4860        ));
4861        p
4862    }
4863
4864    #[test]
4865    fn is_being_deleted_returns_false_when_deletion_timestamp_is_absent() {
4866        // Missing-tombstone corner pin: the primitive collapses the
4867        // no-tombstone case to `false` so the SIGTERM preempt at
4868        // `controller::reconcile` skips the `→ Exiting` forcing
4869        // branch and the DELETE-skip at `handle_exiting`'s child
4870        // fan-out does NOT `continue` past a child that is still
4871        // healthy. Matches the pre-lift `.is_some()` chain's `false`
4872        // byte-identically at every consumer's downstream gate.
4873        let mut p = Process::new("api", empty_spec());
4874        p.metadata.deletion_timestamp = None;
4875        assert!(!p.is_being_deleted());
4876    }
4877
4878    #[test]
4879    fn is_being_deleted_returns_true_when_deletion_timestamp_is_present() {
4880        // Present-tombstone corner pin: the primitive returns
4881        // `true` on any populated `metadata.deletionTimestamp`
4882        // slot regardless of the timestamp payload — the two
4883        // consumers only read the tombstone's PRESENCE, never
4884        // its RFC-3339 timestamp value. A regression that gated
4885        // the `true` return on the timestamp being non-epoch, or
4886        // parsed the timestamp before returning, would surface
4887        // here rather than as silent skew at the SIGTERM preempt
4888        // or child-fan-out DELETE-skip on the SAME `Process`.
4889        let p = tombstoned_process();
4890        assert!(p.is_being_deleted());
4891    }
4892
4893    #[test]
4894    fn is_being_deleted_is_a_pure_projection() {
4895        // Purity pin: two consecutive calls return byte-identical
4896        // `bool` values (no lazy materialization, no interior
4897        // mutation of `self`). Peer to the sibling
4898        // `observed_phase_is_a_pure_projection` +
4899        // `observed_pid_is_a_pure_projection` +
4900        // `observed_flux_resources_is_a_pure_projection` +
4901        // `observed_attestation_is_a_pure_projection` pins; all
4902        // five bind the pure-projection discipline on the ONE
4903        // substrate accessor per metadata / status slot.
4904        let p = tombstoned_process();
4905        let a = p.is_being_deleted();
4906        let b = p.is_being_deleted();
4907        assert_eq!(a, b);
4908        assert!(a);
4909    }
4910
4911    #[test]
4912    fn is_being_deleted_matches_pre_lift_reconciler_chain_shape() {
4913        // Parity pin: sweeps the two corners every pre-lift
4914        // consumer plausibly encountered (missing tombstone,
4915        // present tombstone) and compares the substrate call
4916        // against a hand-authored pre-lift chain byte-identically.
4917        // A regression that reshaped either corner would surface
4918        // here rather than as silent operator-facing skew between
4919        // the top-level dispatcher's SIGTERM preempt and the
4920        // SIGTERM cascade's child-fan-out DELETE-skip on the
4921        // SAME `Process` within one reconcile pass.
4922        fn pre_lift(p: &Process) -> bool {
4923            p.metadata.deletion_timestamp.is_some()
4924        }
4925        let mut p = Process::new("api", empty_spec());
4926        p.metadata.deletion_timestamp = None;
4927        assert_eq!(p.is_being_deleted(), pre_lift(&p));
4928        let p = tombstoned_process();
4929        assert_eq!(p.is_being_deleted(), pre_lift(&p));
4930    }
4931
4932    #[test]
4933    fn is_being_deleted_composes_with_process_phase_is_alive_at_reconcile_preempt() {
4934        // Call-site-shape pin: the `controller::reconcile` SIGTERM
4935        // preempt composes `is_being_deleted() && current_phase
4936        // .is_alive()` — the tombstone-presence probe AND the
4937        // alive-phase gate must BOTH hold to force `→ Exiting`.
4938        // A dead-phase (`Zombie` / `Reaped` / `Failed`) Process
4939        // that carries a tombstone still runs its normal handler,
4940        // not the preempt. This pin binds that composition shape
4941        // at the primitive so a regression that flipped either
4942        // half of the `&&` (or that broadened the tombstone probe
4943        // to include the `is_alive` half implicitly) surfaces
4944        // here rather than as silent skew at the top-level
4945        // dispatch on the SAME `Process`.
4946        let mut p = tombstoned_process();
4947        // Alive + tombstoned → preempt fires.
4948        let mut alive = ProcessStatus::default();
4949        alive.phase = ProcessPhase::Running;
4950        p.status = Some(alive);
4951        assert!(p.is_being_deleted());
4952        assert!(p.observed_phase().unwrap_or_default().is_alive());
4953        // Dead + tombstoned → preempt does NOT fire (composition
4954        // with `is_alive` returns false).
4955        let mut dead = ProcessStatus::default();
4956        dead.phase = ProcessPhase::Reaped;
4957        p.status = Some(dead);
4958        assert!(p.is_being_deleted());
4959        assert!(!p.observed_phase().unwrap_or_default().is_alive());
4960    }
4961
4962    // ─── Process::created_at substrate pins ─────────────────────────
4963    //
4964    // Pins the copy-form metadata-projection primitive on the
4965    // `metadata.creationTimestamp` axis that owns the
4966    // `.metadata.creation_timestamp.as_ref().map(|t| t.0)` chain the
4967    // three hand-authored sites (`lifetime_clock::evaluate`,
4968    // `lifetime_clock::requeue_with_ttl`,
4969    // `tatara-reconciler::table_controller`) restated by hand pre-lift.
4970    // Peer to the sibling `is_being_deleted_*` +
4971    // `observed_phase_*` pin families — all three primitives project a
4972    // wire-format `Option<T>` slot into a `Copy` inner value at ONE
4973    // owner. Fail-before-pass-after granularity: `created_at` did not
4974    // exist pre-lift, so any test invoking it fails to compile pre-lift
4975    // and passes post-lift.
4976
4977    fn creation_stamped_process(t: DateTime<Utc>) -> Process {
4978        let mut p = Process::new("age-anchor", empty_spec());
4979        p.metadata.namespace = Some("prod".into());
4980        p.metadata.creation_timestamp =
4981            Some(k8s_openapi::apimachinery::pkg::apis::meta::v1::Time(t));
4982        p
4983    }
4984
4985    #[test]
4986    fn created_at_returns_none_when_creation_timestamp_is_absent() {
4987        // Missing-slot corner pin: the primitive collapses the
4988        // no-creation-timestamp case to `None` so the TTL-expiry gate
4989        // at `lifetime_clock::evaluate` short-circuits its inner
4990        // `if let Some(...)` branch (no elapsed computation), the
4991        // requeue-budget picker returns its default sleep, and the
4992        // stable-name arbiter's `.unwrap_or_else(Utc::now)` tail
4993        // synthesizes a "just created" anchor at its own site. Matches
4994        // the pre-lift `.as_ref().map(|t| t.0)` chain's `None`
4995        // byte-identically at every consumer's downstream tail.
4996        let mut p = Process::new("api", empty_spec());
4997        p.metadata.creation_timestamp = None;
4998        assert!(p.created_at().is_none());
4999    }
5000
5001    #[test]
5002    fn created_at_returns_some_datetime_when_slot_is_populated() {
5003        // Populated-slot corner pin: with a populated
5004        // `metadata.creationTimestamp` slot, the primitive unwraps the
5005        // wire-format `Time` newtype to its inner `DateTime<Utc>` and
5006        // returns it as `Some(datetime)` — hiding the `.0` field-access
5007        // every pre-lift consumer restated to reach the underlying
5008        // instant.
5009        let anchor = Utc::now() - chrono::Duration::seconds(300);
5010        let p = creation_stamped_process(anchor);
5011        assert_eq!(p.created_at(), Some(anchor));
5012    }
5013
5014    #[test]
5015    fn created_at_is_a_pure_projection() {
5016        // Purity pin: two consecutive calls return byte-identical
5017        // `Option<DateTime<Utc>>` values (no lazy materialization, no
5018        // interior mutation of `self`). Peer to the sibling
5019        // `is_being_deleted_is_a_pure_projection` +
5020        // `observed_phase_is_a_pure_projection` pins; all three bind
5021        // the pure-projection discipline on the ONE substrate accessor
5022        // per metadata / status slot.
5023        let anchor = Utc::now();
5024        let p = creation_stamped_process(anchor);
5025        let a = p.created_at();
5026        let b = p.created_at();
5027        assert_eq!(a, b);
5028        assert_eq!(a, Some(anchor));
5029    }
5030
5031    #[test]
5032    fn created_at_matches_pre_lift_creation_timestamp_chain_shape() {
5033        // Parity pin: sweeps the two corners every pre-lift consumer
5034        // plausibly encountered (missing slot, populated slot) and
5035        // compares the substrate call against a hand-authored pre-lift
5036        // chain byte-identically. A regression that reshaped either
5037        // corner (returning `Some(Utc::now())` on the missing slot,
5038        // returning a rounded / truncated timestamp on the populated
5039        // slot) would surface here rather than as silent operator-
5040        // facing skew between the TTL-expiry gate, the requeue-budget
5041        // picker, and the stable-name claim-arbiter tie-break on the
5042        // SAME `Process` within one reconcile pass.
5043        fn pre_lift(p: &Process) -> Option<DateTime<Utc>> {
5044            p.metadata.creation_timestamp.as_ref().map(|t| t.0)
5045        }
5046        // Missing slot.
5047        let mut p = Process::new("x", empty_spec());
5048        p.metadata.creation_timestamp = None;
5049        assert_eq!(p.created_at(), pre_lift(&p));
5050        // Populated slot.
5051        let anchor = Utc::now() - chrono::Duration::seconds(42);
5052        let p = creation_stamped_process(anchor);
5053        assert_eq!(p.created_at(), pre_lift(&p));
5054    }
5055
5056    #[test]
5057    fn created_at_composes_with_signed_duration_since_at_ttl_gate() {
5058        // Call-site-shape pin: the `lifetime_clock::evaluate` TTL-
5059        // expiry gate composes `now.signed_duration_since(creation)`
5060        // where `creation` is the `DateTime<Utc>` returned by this
5061        // primitive's `Some` corner. A regression that returned a
5062        // per-callsite `Local` timezone (or that stripped the timezone
5063        // marker) would break the arithmetic silently. This pin
5064        // computes the elapsed duration byte-identically against the
5065        // pre-lift `.map(|t| t.0)` chain so a timezone drift surfaces
5066        // here rather than as silent skew at the TTL-expiry decision
5067        // on the SAME `Process` within one reconcile pass.
5068        let now = Utc::now();
5069        let anchor = now - chrono::Duration::seconds(120);
5070        let p = creation_stamped_process(anchor);
5071        let via_primitive = p.created_at().expect("populated slot");
5072        let via_pre_lift = p
5073            .metadata
5074            .creation_timestamp
5075            .as_ref()
5076            .map(|t| t.0)
5077            .expect("populated slot");
5078        assert_eq!(
5079            now.signed_duration_since(via_primitive),
5080            now.signed_duration_since(via_pre_lift)
5081        );
5082    }
5083
5084    // ─── Process::created_at_or substrate pins ──────────────────────
5085    //
5086    // Pins the pure composer over `Process::created_at` that owns the
5087    // paired `.created_at().unwrap_or_else(Utc::now)` chain the two
5088    // production consumers restated by hand pre-lift
5089    // (`tatara-reconciler::table_controller::reconcile_process_table`
5090    // + `tatara-pool-reconciler::controller_pool::reconcile_inner`).
5091    // Fail-before-pass-after granularity: `created_at_or` did not
5092    // exist pre-lift, so any test invoking it fails to compile
5093    // pre-lift and passes post-lift.
5094
5095    #[test]
5096    fn created_at_or_returns_fallback_when_creation_timestamp_is_absent() {
5097        // Missing-slot corner pin: the composer collapses the
5098        // no-creation-timestamp case to the caller's fallback anchor
5099        // byte-identically to the pre-lift `.unwrap_or(fallback)`
5100        // tail. A freshly-forked Process whose API server has not yet
5101        // stamped `metadata.creationTimestamp` gets the caller's
5102        // wall-clock read (or a test's frozen anchor) synthesized so
5103        // downstream dwell-time / tie-break arithmetic proceeds
5104        // without a special-case branch at each consumer.
5105        let mut p = Process::new("api", empty_spec());
5106        p.metadata.creation_timestamp = None;
5107        let fallback = Utc::now() - chrono::Duration::seconds(42);
5108        assert_eq!(p.created_at_or(fallback), fallback);
5109    }
5110
5111    #[test]
5112    fn created_at_or_returns_anchor_when_slot_is_populated() {
5113        // Populated-slot corner pin: with a populated
5114        // `metadata.creationTimestamp` slot, the composer ignores the
5115        // caller's fallback and returns the observed anchor
5116        // byte-identically to the pre-lift `.unwrap_or(fallback)`
5117        // pass-through. Sibling to `created_at_returns_some_datetime_
5118        // when_slot_is_populated` — that pin binds the pure projection,
5119        // this pin binds the composer's pass-through on the same
5120        // populated corner.
5121        let anchor = Utc::now() - chrono::Duration::seconds(300);
5122        let p = creation_stamped_process(anchor);
5123        let unrelated_fallback = Utc::now() + chrono::Duration::seconds(9_999);
5124        assert_eq!(p.created_at_or(unrelated_fallback), anchor);
5125    }
5126
5127    #[test]
5128    fn created_at_or_is_pure_over_the_fallback_argument() {
5129        // Purity pin: the composer itself never reads the wall clock —
5130        // two consecutive calls with the SAME fallback return
5131        // byte-identical `DateTime<Utc>` values on both the missing-
5132        // slot corner (both calls return the caller's fallback) and
5133        // the populated-slot corner (both calls return the observed
5134        // anchor). Peer to the sibling
5135        // `created_at_is_a_pure_projection` pin; both bind the pure-
5136        // projection / pure-composer discipline on the ONE substrate
5137        // accessor per axis.
5138        let fallback = Utc::now() - chrono::Duration::seconds(7);
5139        // Missing slot.
5140        let mut p = Process::new("x", empty_spec());
5141        p.metadata.creation_timestamp = None;
5142        assert_eq!(p.created_at_or(fallback), p.created_at_or(fallback));
5143        // Populated slot.
5144        let anchor = Utc::now() - chrono::Duration::seconds(120);
5145        let p = creation_stamped_process(anchor);
5146        assert_eq!(p.created_at_or(fallback), p.created_at_or(fallback));
5147    }
5148
5149    #[test]
5150    fn created_at_or_matches_pre_lift_unwrap_or_chain_shape() {
5151        // Parity pin: sweeps the two corners every pre-lift consumer
5152        // encountered (missing slot, populated slot) and compares the
5153        // substrate call against the hand-authored pre-lift
5154        // `.created_at().unwrap_or(fallback)` chain byte-identically.
5155        // A regression that reshaped either corner (returning the
5156        // fallback on a populated slot, returning `Utc::now()` on the
5157        // missing slot regardless of the caller's fallback) would
5158        // surface here rather than as silent operator-facing skew
5159        // between the claim-arbiter's tie-break anchor and the pool
5160        // convergence snapshot's dwell-time anchor on the SAME
5161        // `Process` within one reconcile pass.
5162        fn pre_lift(p: &Process, fallback: DateTime<Utc>) -> DateTime<Utc> {
5163            p.created_at().unwrap_or(fallback)
5164        }
5165        let fallback = Utc::now() - chrono::Duration::seconds(13);
5166        // Missing slot.
5167        let mut p = Process::new("x", empty_spec());
5168        p.metadata.creation_timestamp = None;
5169        assert_eq!(p.created_at_or(fallback), pre_lift(&p, fallback));
5170        // Populated slot.
5171        let anchor = Utc::now() - chrono::Duration::seconds(42);
5172        let p = creation_stamped_process(anchor);
5173        assert_eq!(p.created_at_or(fallback), pre_lift(&p, fallback));
5174    }
5175
5176    #[test]
5177    fn created_at_or_composes_with_utc_now_at_reconciler_callsites() {
5178        // Call-site-shape pin: the two production consumers
5179        // (`table_controller::reconcile_process_table` +
5180        // `controller_pool::reconcile_inner`) both call
5181        // `p.created_at_or(Utc::now())`. On the populated corner the
5182        // wall-clock fallback is irrelevant (the observed anchor
5183        // wins); on the missing corner the fallback becomes the
5184        // resolved value within the sub-second window between the
5185        // caller's `Utc::now()` read and the assertion below. This
5186        // pin binds that the callsite composition returns the
5187        // observed anchor exactly on the populated corner (the
5188        // stable, drift-free assertion) and a "recent" wall-clock
5189        // read on the missing corner (bounded within a two-second
5190        // window to absorb scheduler jitter). A regression that
5191        // silently substituted a different fallback (`DateTime::MIN`,
5192        // a per-cluster prefix offset, a hardcoded epoch) would
5193        // surface at the second half of this pin.
5194        // Populated corner: byte-identical to the observed anchor.
5195        let anchor = Utc::now() - chrono::Duration::seconds(600);
5196        let p = creation_stamped_process(anchor);
5197        assert_eq!(p.created_at_or(Utc::now()), anchor);
5198        // Missing corner: within a two-second wall-clock window.
5199        let mut p = Process::new("x", empty_spec());
5200        p.metadata.creation_timestamp = None;
5201        let before = Utc::now();
5202        let resolved = p.created_at_or(Utc::now());
5203        let after = Utc::now();
5204        assert!(
5205            resolved >= before - chrono::Duration::seconds(2),
5206            "resolved {resolved} is before window start {before}"
5207        );
5208        assert!(
5209            resolved <= after + chrono::Duration::seconds(2),
5210            "resolved {resolved} is after window end {after}"
5211        );
5212    }
5213
5214    // ─── Process::resolved_ephemeral substrate pins ─────────────────
5215    //
5216    // Pins the compound spec-projection primitive on the
5217    // `spec.lifetime` axis that owns the ambiguity-aware
5218    // `resolved_ephemeral` chain the three hand-authored sites
5219    // (`lifetime_clock::evaluate`, `lifetime_clock::requeue_with_ttl`,
5220    // `tatara-reconciler::render::render_export_jobs`) restated by
5221    // hand pre-lift through TWO different chains that disagreed on
5222    // the ambiguous corner. Fail-before-pass-after granularity:
5223    // `resolved_ephemeral` did not exist pre-lift on `impl Process`,
5224    // so any test invoking it fails to compile pre-lift and passes
5225    // post-lift.
5226
5227    fn permanent_only_process() -> Process {
5228        let mut spec = empty_spec();
5229        spec.lifetime = crate::lifetime::Lifetime {
5230            permanent: Some(crate::lifetime::PermanentLifetime {}),
5231            ..crate::lifetime::Lifetime::default()
5232        };
5233        Process::new("perm", spec)
5234    }
5235
5236    fn ephemeral_only_process(ttl: &str) -> Process {
5237        let mut spec = empty_spec();
5238        spec.lifetime = crate::lifetime::Lifetime {
5239            ephemeral: Some(EphemeralLifetime {
5240                ttl: ttl.into(),
5241                teardown_policy: crate::lifetime::TeardownPolicy::OnAttested,
5242                max_concurrent: 3,
5243                exports: vec![],
5244            }),
5245            ..crate::lifetime::Lifetime::default()
5246        };
5247        Process::new("eph", spec)
5248    }
5249
5250    fn ambiguous_lifetime_process() -> Process {
5251        let mut spec = empty_spec();
5252        spec.lifetime = crate::lifetime::Lifetime {
5253            permanent: Some(crate::lifetime::PermanentLifetime {}),
5254            ephemeral: Some(EphemeralLifetime::default()),
5255        };
5256        Process::new("both", spec)
5257    }
5258
5259    #[test]
5260    fn resolved_ephemeral_returns_none_when_lifetime_is_default_empty() {
5261        // Empty-default corner pin: neither slot populated. The
5262        // resolver collapses to `Permanent(&DEFAULT_PERMANENT)` and
5263        // the compound projection sees no ephemeral inner. Matches
5264        // the pre-lift `lifetime_clock::evaluate` early-return to
5265        // `AutoTerminate::Skip` byte-identically.
5266        let p = Process::new("empty-lifetime", empty_spec());
5267        assert!(p.resolved_ephemeral().is_none());
5268    }
5269
5270    #[test]
5271    fn resolved_ephemeral_returns_none_for_permanent_only_process() {
5272        // Permanent-only corner pin: the `permanent:` slot is
5273        // populated, `ephemeral:` is not. Matches the pre-lift
5274        // `lifetime_clock::evaluate` outcome — the teardown/TTL
5275        // branch is never reached on a Permanent Process, and the
5276        // export-render arm now agrees at this call site (was
5277        // previously reached through the raw `.ephemeral.as_ref()`
5278        // that also returned `None` on this same corner — no drift
5279        // here; the drift is at the ambiguous corner below).
5280        let p = permanent_only_process();
5281        assert!(p.resolved_ephemeral().is_none());
5282    }
5283
5284    #[test]
5285    fn resolved_ephemeral_returns_some_for_ephemeral_only_process() {
5286        // Ephemeral-only corner pin: the ONE arm that projects. The
5287        // returned borrow carries the operator-authored `ttl` /
5288        // `teardown_policy` / `max_concurrent` verbatim. A
5289        // regression that swapped the projection to the sibling
5290        // `permanent:` slot would surface here as a type mismatch on
5291        // the `EphemeralLifetime` fields rather than as silent
5292        // operator-facing no-op teardown at the reconciler.
5293        let p = ephemeral_only_process("42m");
5294        let e = p
5295            .resolved_ephemeral()
5296            .expect("ephemeral-only Process must project");
5297        assert_eq!(e.ttl, "42m");
5298        assert_eq!(
5299            e.teardown_policy,
5300            crate::lifetime::TeardownPolicy::OnAttested
5301        );
5302        assert_eq!(e.max_concurrent, 3);
5303    }
5304
5305    #[test]
5306    fn resolved_ephemeral_returns_none_for_ambiguous_lifetime() {
5307        // DRIFT-CLOSING CONTRACT: BOTH `permanent:` AND `ephemeral:`
5308        // slots populated is an operator-authored mis-configuration.
5309        // Pre-lift, `lifetime_clock::evaluate` (via
5310        // `resolved_ephemeral()` on `Lifetime`) collapsed this
5311        // corner to `None` and yielded `AutoTerminate::Skip`, while
5312        // `tatara-reconciler::render::render_export_jobs` walked
5313        // the naked `.spec.lifetime.ephemeral.as_ref()` chain and
5314        // returned `Some(&e)` — so the reconciler would emit export
5315        // Jobs on a Process whose teardown-triggered fire semantics
5316        // the lifetime clock refused to honor. Post-lift this
5317        // primitive collapses ambiguity to `None` at ONE site so
5318        // BOTH consumers agree. A regression that broadened the
5319        // projection back to the raw field (or that silently
5320        // "preferred ephemeral" in the ambiguous case) surfaces
5321        // here rather than as export-Job noise on a mis-configured
5322        // ephemeral.
5323        let p = ambiguous_lifetime_process();
5324        assert!(p.resolved_ephemeral().is_none());
5325        // The raw field IS populated at this corner — pins the
5326        // pre-lift `.spec.lifetime.ephemeral.as_ref()` shape that
5327        // returned `Some` here.
5328        assert!(p.spec.lifetime.ephemeral.is_some());
5329    }
5330
5331    #[test]
5332    fn resolved_ephemeral_matches_spec_lifetime_forwarder() {
5333        // Byte-identity pin: the `Process` projection delegates
5334        // through the underlying `Lifetime::resolved_ephemeral`
5335        // primitive at every corner (empty, permanent-only,
5336        // ephemeral-only, ambiguous). A regression that silently
5337        // reintroduced the raw `.ephemeral.as_ref()` shortcut, or
5338        // that decided the ambiguous case by "prefer ephemeral"
5339        // at the Process layer instead of delegating, surfaces
5340        // here.
5341        for p in [
5342            Process::new("empty", empty_spec()),
5343            permanent_only_process(),
5344            ephemeral_only_process("1h"),
5345            ambiguous_lifetime_process(),
5346        ] {
5347            let via_process = p.resolved_ephemeral();
5348            let via_lifetime = p.spec.lifetime.resolved_ephemeral();
5349            // Both borrows point into the SAME `EphemeralLifetime`
5350            // slot when present — a regression that materialized a
5351            // per-call clone at the Process layer would fail the
5352            // pointer-equality gate.
5353            match (via_process, via_lifetime) {
5354                (Some(a), Some(b)) => assert!(
5355                    std::ptr::eq(a, b),
5356                    "Process::resolved_ephemeral must borrow the same slot as Lifetime::resolved_ephemeral"
5357                ),
5358                (None, None) => {}
5359                (a, b) => panic!(
5360                    "resolved_ephemeral shape drift: process={:?}, lifetime={:?}",
5361                    a.is_some(),
5362                    b.is_some()
5363                ),
5364            }
5365        }
5366    }
5367
5368    #[test]
5369    fn resolved_ephemeral_is_a_pure_projection() {
5370        // Purity pin: two consecutive calls return borrows into the
5371        // same underlying slot (no lazy materialization, no interior
5372        // mutation of `self`). Peer to the sibling
5373        // `is_being_deleted_is_a_pure_projection` +
5374        // `observed_attestation_is_a_pure_projection` pins; all
5375        // three bind the pure-projection discipline on the ONE
5376        // substrate accessor per spec / metadata / status slot.
5377        let p = ephemeral_only_process("5m");
5378        let a = p.resolved_ephemeral();
5379        let b = p.resolved_ephemeral();
5380        match (a, b) {
5381            (Some(x), Some(y)) => assert!(std::ptr::eq(x, y)),
5382            other => panic!("expected two Some borrows into the same slot, got {other:?}"),
5383        }
5384    }
5385}