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::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    /// Borrowed lookup of ONE key in `metadata.annotations`, with
290    /// BOTH the missing-`annotations` corner AND the missing-key
291    /// corner collapsed to `None` — the ONE-liner collapse of the
292    /// paired `self.metadata.annotations.as_ref().and_then(|m|
293    /// m.get(key)).map(String::as_str)` incantation every consumer
294    /// restated by hand pre-lift.
295    ///
296    /// Pre-lift the 3-line `.metadata.annotations.as_ref().and_then
297    /// (|m| m.get(KEY))` chain (in three tail variants — `.cloned()`,
298    /// `.cloned().unwrap_or_default()`, `.map(String::as_str)`) was
299    /// hand-authored at THREE sites past the ★★ PRIME-DIRECTIVE ≥ 2
300    /// duplication threshold across the workspace:
301    /// * `tatara-reconciler::signals::ingest` — SIGNAL annotation
302    ///   lookup (pre-lift `.cloned()` for owned parsing).
303    /// * `tatara-reconciler::phase_machine::released_from_annotation`
304    ///   — RELEASED_FROM annotation lookup (pre-lift `.cloned()
305    ///   .unwrap_or_default()` for `match v.as_str()`).
306    /// * `tatara-pool-reconciler::controller_pool::process_belongs_to_pool`
307    ///   — POOL annotation lookup (pre-lift `.map(String::as_str)`
308    ///   for `== Some(pool_name)`).
309    ///
310    /// All THREE sites walked the SAME 3-line chain — read the
311    /// annotations map, gate on presence, index by key — differing
312    /// only in the tail that shaped the result. Post-lift each
313    /// caller routes through the ONE substrate primitive here and
314    /// applies its own tail at its own site (`.map(str::to_string)`
315    /// / bare match / `==`).
316    ///
317    /// Return-form axis: `Option<&str>` mirrors the existing borrow-
318    /// first discipline of the peer metadata primitives
319    /// [`Self::namespace_or_default`], [`Self::name_or_placeholder`],
320    /// [`Self::coordinates_or_none`]. The two corners the chain
321    /// swallowed pre-lift (missing `metadata.annotations` map,
322    /// missing key inside the map) BOTH collapse to `None` so
323    /// `.is_some()` / `if let Some(_)` / `Option::map` behave
324    /// identically on a `Process` whose annotations block is `None`
325    /// and on one whose annotations block is populated but omits the
326    /// key — matching what the pre-lift `.and_then(...)` chain
327    /// produced.
328    ///
329    /// A future normalization step (a key-canonicalization pass,
330    /// a case-fold lookup, a per-key alias table for renamed
331    /// annotations across API versions, a per-namespace override
332    /// substrate) lands at ONE substrate method here and all three
333    /// downstream consumers pick up the upgrade mechanically — no
334    /// per-callsite hand-edit at `ingest` / `released_from_annotation`
335    /// / `process_belongs_to_pool`.
336    ///
337    /// Sibling to the peer metadata primitives
338    /// ([`Self::namespace_or_default`], [`Self::name_or_placeholder`],
339    /// [`Self::coordinates_or_defaults`], [`Self::coordinates_or_none`],
340    /// [`Self::owned_coordinates_or_err`]) on the metadata axis;
341    /// this method opens the borrow-form peer on the ANNOTATION
342    /// axis. Future annotation projections (a paired
343    /// `label(&str) -> Option<&str>` on `metadata.labels`, a
344    /// `has_annotation(&str) -> bool` boolean gate for presence-
345    /// only consumers) land as peer methods on this same axis.
346    ///
347    /// Theory anchor: THEORY.md §VI.1 (generation over composition
348    /// — the 3-line annotation-lookup chain recurred at three
349    /// hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
350    /// duplication trigger, and is lifted to ONE owner here).
351    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
352    /// the pins bind the missing-`annotations` corner + the
353    /// missing-key corner + the borrow-form `&str` lifetime + the
354    /// byte-identical parity with the pre-lift 3-line chain, so a
355    /// regression that drifted any surface at
356    /// `tests::annotation_*` rather than as silent operator-facing
357    /// skew between the SIGNAL / RELEASED_FROM / POOL annotation
358    /// readers).
359    pub fn annotation(&self, key: &str) -> Option<&str> {
360        self.metadata
361            .annotations
362            .as_ref()
363            .and_then(|m| m.get(key))
364            .map(String::as_str)
365    }
366
367    /// Borrow-form metadata-projection primitive on the `metadata.uid`
368    /// axis: returns the K8s-API-server-assigned uid as a `&str`, with
369    /// the missing-uid corner collapsed to the load-bearing empty-string
370    /// sentinel — the ONE-liner collapse of the paired
371    /// `self.metadata.uid.as_deref().unwrap_or("")` incantation every
372    /// owner-reference-emitting consumer restated by hand pre-lift.
373    ///
374    /// The empty-string fallback is NOT arbitrary — it is the exact
375    /// sentinel value the sibling substrate composer
376    /// [`crate::owner_references_json`] gates on (`if uid.is_empty()
377    /// { vec![] } else { vec![owner_reference_json(name, uid)] }`) to
378    /// stamp `metadata.ownerReferences: []` on a resource whose owning
379    /// Process pre-dates the API server's `metadata.uid` assignment
380    /// (test fixture, mid-Forking snapshot before the first `patch`
381    /// round-trip, dynamic API response pre-uid-resolution). Pre-lift
382    /// each consumer spelled the fallback as `.unwrap_or("")` at its
383    /// callsite; the two literals in two files could drift silently to
384    /// `.unwrap_or_default()`, `.unwrap_or("<unknown>")`, or an
385    /// `if let Some(u) = &process.metadata.uid` gate that returned a
386    /// different owner-refs shape for the missing-uid corner. Post-lift
387    /// the sentinel value is composed at ONE substrate site so the
388    /// empty-uid gate at `owner_references_json` and its per-callsite
389    /// producers share the SAME `""` byte-string, and a rename of the
390    /// sentinel would land at ONE substrate site rather than at every
391    /// downstream `owner_references_json(name, uid)` call.
392    ///
393    /// Peer to [`Self::namespace_or_default`] +
394    /// [`Self::name_or_placeholder`] on the metadata-slot × fallback-
395    /// shape axis: `namespace_or_default` returns the K8s-canonical
396    /// `"default"` fallback (matching what the API server substitutes
397    /// on namespaced writes with no explicit namespace);
398    /// `name_or_placeholder` returns the workspace-wide `"unnamed"`
399    /// sentinel (a display placeholder for downstream grepping /
400    /// label-selecting); this method returns the empty-string sentinel
401    /// (a load-bearing gate value that composes with
402    /// [`crate::owner_references_json`]'s `is_empty` check). The three
403    /// primitives partition the metadata-slot family by whether the
404    /// consumer wants a K8s-canonical fallback (namespace), a display
405    /// placeholder (name), or a gate sentinel (uid).
406    ///
407    /// Pre-lift the `.metadata.uid.as_deref().unwrap_or("")` chain was
408    /// hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
409    /// duplication threshold in `tatara-reconciler::render`, both
410    /// feeding a downstream owner-reference emitter:
411    /// * `render_routing` — the routing-edge seed that binds
412    ///   `process_uid` into every routing-form `EdgeContext` (Ingress +
413    ///   DNSEndpoint) built inside the fanout loop over
414    ///   `RoutingSpec::hostnames`; each `Edge::render` impl then walks
415    ///   its `EdgeContext` through `build_owner_refs` →
416    ///   [`crate::owner_references_json`] to stamp
417    ///   `metadata.ownerReferences` on the emitted resource.
418    /// * `render_export_jobs` — the ephemeral-export Job builder that
419    ///   passes the same uid slice to `tatara_process::
420    ///   owner_references_json(name, uid)` per rendered Job, stamping
421    ///   the export-Job's `metadata.ownerReferences` back at the
422    ///   owning Process.
423    ///
424    /// Both sites walked the SAME `.as_deref().unwrap_or("")` chain and
425    /// both wanted the `&str` form the primitive returns — as the
426    /// second positional argument to `owner_references_json(name, uid)`
427    /// on the ownership-tag axis. Post-lift each callsite reads
428    /// `let uid = process.uid_or_empty();` and the produced slice feeds
429    /// the same downstream composer unchanged.
430    ///
431    /// Return-form axis: `&str` mirrors the existing borrow-first
432    /// discipline of the peer metadata-fallback primitives
433    /// ([`Self::namespace_or_default`], [`Self::name_or_placeholder`]);
434    /// all three return owned-metadata borrows with a slot-specific
435    /// fallback baked in so downstream consumers compose the slice
436    /// directly into their next call without re-spelling the fallback.
437    ///
438    /// A future normalization step (a canonicalization pass that
439    /// rejects a malformed uid before the owner-ref stamp, a cross-
440    /// cluster uid rewrite for multi-tenant control planes, a stale-
441    /// uid warning annotation for a Process whose uid changed under
442    /// the reconciler mid-generation) lands at ONE substrate method
443    /// here and both downstream `owner_references_json` consumers
444    /// pick up the upgrade mechanically — no per-callsite hand-edit
445    /// at `render_routing` / `render_export_jobs`.
446    ///
447    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
448    /// the `.metadata.uid.as_deref().unwrap_or("")` chain recurred at
449    /// two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
450    /// duplication trigger, and is lifted to ONE owner here).
451    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
452    /// the pins bind the missing-uid corner + the empty-string
453    /// sentinel byte-shape + the borrow-form `&str` lifetime + the
454    /// byte-identical parity with the pre-lift chain + the composition
455    /// coherence with [`crate::owner_references_json`]'s `is_empty`
456    /// gate, so a regression that drifted any surface at
457    /// `tests::uid_or_empty_*` rather than as silent operator-facing
458    /// skew between the two owner-reference emitters on the SAME
459    /// Process).
460    pub fn uid_or_empty(&self) -> &str {
461        self.metadata.uid.as_deref().unwrap_or("")
462    }
463
464    /// Borrow-form spec-projection primitive on the declared parent-PID
465    /// axis: returns the hierarchical PID path (e.g. `"seph.1"`) the
466    /// author declared at `spec.identity.parent`, with the empty-slot
467    /// corner collapsed to `None` — the ONE-liner collapse of the
468    /// paired `self.spec.identity.parent.as_deref()` incantation every
469    /// consumer restated by hand pre-lift.
470    ///
471    /// Pre-lift the `.spec.identity.parent.as_deref()` chain was hand-
472    /// authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
473    /// duplication threshold in `tatara-reconciler::phase_machine`:
474    /// * `handle_forking` — the ALLOCATE-PID composer that threads the
475    ///   declared parent PID into [`pid::allocate_pid`] and also into
476    ///   the status patch payload (`{ "pid": new_pid, "parent":
477    ///   parent_pid }`), so the reconciler-observed
478    ///   [`ProcessStatus::parent`] slot mirrors the author-declared
479    ///   [`IdentitySpec::parent`] at fork time. The `info!` tracing
480    ///   span also reads the same slice as the `parent` field on the
481    ///   PID-assigned log line.
482    /// * `handle_exiting` — the SIGTERM cascade's child-fan-out filter
483    ///   that enumerates every Process cluster-wide and picks children
484    ///   whose `spec.identity.parent` equals this Process's currently-
485    ///   observed PID (`.filter(|c| c.spec.identity.parent.as_deref()
486    ///   == Some(pid))`). The filter runs per candidate child, so the
487    ///   borrow-form projection avoids allocating one `String` clone
488    ///   per non-matching row in the cluster-wide list.
489    ///
490    /// Both sites walked the SAME `.as_deref()` chain and both wanted
491    /// the `Option<&str>` form the primitive returns — the
492    /// `handle_forking` site to feed positionally into
493    /// `pid::allocate_pid(&identity, parent_pid, next_seq)` and the
494    /// tracing span's `parent = ?parent_pid` debug print + the JSON
495    /// payload's `"parent": parent_pid` slot; the `handle_exiting`
496    /// filter to compare directly against `Some(pid)` where `pid:
497    /// &str` came off the borrow-form peer [`Self::observed_pid`].
498    ///
499    /// Return-form axis: `Option<&str>` mirrors the borrow-first
500    /// discipline of every peer primitive on the metadata / status
501    /// slot family ([`Self::namespace_or_default`],
502    /// [`Self::name_or_placeholder`], [`Self::observed_pid`],
503    /// [`Self::annotation`]). The empty-slot corner
504    /// (`spec.identity.parent = None`, matching `init` / PID 1 with
505    /// no parent) collapses to `None` so `.is_some()` / `if let
506    /// Some(_)` / `.map(...)` behave identically on a `Process`
507    /// authored at cluster init (PID 1, parent absent) and on any
508    /// PID-N child (parent present) — matching the pre-lift
509    /// `.as_deref()` chain's `None` byte-identically.
510    ///
511    /// Peer to [`Self::observed_pid`] on the (spec-declared ×
512    /// status-observed) axis pair: `observed_pid` returns the PID
513    /// path this Process currently OWNS (the reconciler-persisted
514    /// child position in the hierarchy), while `declared_parent_pid`
515    /// returns the PID path this Process's parent OWNS (the author-
516    /// declared upstream position). The SIGTERM cascade at
517    /// `handle_exiting` composes both: it reads its own
518    /// [`Self::observed_pid`] and matches each candidate child's
519    /// [`Self::declared_parent_pid`] against that value — the child-
520    /// fan-out relation IS the spec-declared × status-observed axis
521    /// pair collapsed to a single comparator, both sides routed
522    /// through the same borrow-form skeleton.
523    ///
524    /// A future normalization step (a per-slot canonicalization pass
525    /// that rejects malformed hierarchical PIDs, a case-fold lookup
526    /// against a table of renamed identities, a cross-cluster prefix
527    /// stripper, an alias-table lookup that maps a legacy PID to its
528    /// current spelling) lands at ONE substrate method here and both
529    /// downstream consumers pick up the upgrade mechanically — no
530    /// per-callsite hand-edit at `handle_forking` / `handle_exiting`.
531    ///
532    /// Sibling to the peer metadata-projection primitives
533    /// ([`Self::namespace_or_default`], [`Self::name_or_placeholder`],
534    /// [`Self::coordinates_or_defaults`], [`Self::coordinates_or_none`],
535    /// [`Self::owned_coordinates_or_err`], [`Self::annotation`]) on the
536    /// metadata axis; this method opens the borrow-form peer on the
537    /// declared-identity axis. Future identity projections
538    /// (`declared_name_override` on the `spec.identity.name_override`
539    /// axis, a paired `declared_identity` composite that returns both
540    /// halves) land as peer methods on this same axis.
541    ///
542    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
543    /// the `.spec.identity.parent.as_deref()` chain recurred at two
544    /// hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
545    /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
546    /// invariant 5 (composition preserves proofs — the pins bind the
547    /// empty-slot corner + the borrow-form `&str` lifetime + the
548    /// byte-identical parity with the pre-lift `.as_deref()` chain,
549    /// so a regression that drifted any surface at
550    /// `tests::declared_parent_pid_*` rather than as silent operator-
551    /// facing skew between the ALLOCATE-PID composer and the SIGTERM
552    /// cascade's child-fan-out filter on the SAME parent-child pair).
553    pub fn declared_parent_pid(&self) -> Option<&str> {
554        self.spec.identity.parent.as_deref()
555    }
556
557    /// Borrow-form spec-projection primitive on the declared
558    /// name-override axis: returns the human name the author declared
559    /// at `spec.identity.name_override` (used verbatim instead of the
560    /// content-hash-derived name in [`derive_identity`]), with the
561    /// empty-slot corner collapsed to `None` — the ONE-liner collapse
562    /// of the paired `self.spec.identity.name_override.as_deref()`
563    /// incantation every consumer restated by hand pre-lift.
564    ///
565    /// Pre-lift the `.spec.identity.name_override.as_deref()` chain
566    /// was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
567    /// duplication threshold in `tatara-reconciler::phase_machine`,
568    /// both feeding the second positional argument of
569    /// [`derive_identity`]:
570    /// * `handle_pending` — the DECLARE composer that computes the
571    ///   Process's [`Identity`] on entry to the state machine (before
572    ///   `patch::phase_status` writes it into `status.identity`).
573    /// * `handle_forking` — the ALLOCATE-PID composer that recomputes
574    ///   the same [`Identity`] on a rehydration path (status may
575    ///   already carry an identity from a prior reconcile, in which
576    ///   case the `.and_then(|s| s.identity.clone())` short-circuit
577    ///   takes it; otherwise this `.unwrap_or_else` branch fires and
578    ///   recomputes the identity fresh from the spec) so `pid::
579    ///   allocate_pid` sees the SAME [`Identity`] the DECLARE phase
580    ///   produced.
581    ///
582    /// Both sites walked the SAME `.as_deref()` chain and both wanted
583    /// the `Option<&str>` form the primitive returns — as the second
584    /// positional argument to `derive_identity(&self.spec, …)`, which
585    /// internally trims + filters empty strings + dispatches on
586    /// `Some(non_empty)` (verbatim name, `name_override: true`) vs
587    /// `None | Some(empty | whitespace)` (content-hash-derived name,
588    /// `name_override: false`). The primitive itself preserves the
589    /// raw slot byte-identically (the trim happens IN
590    /// `derive_identity`, not at the borrow site), so the two live
591    /// paths compose through the SAME borrow-form skeleton.
592    ///
593    /// Return-form axis: `Option<&str>` mirrors the borrow-first
594    /// discipline of every peer primitive on the metadata / status /
595    /// spec-identity slot family ([`Self::namespace_or_default`],
596    /// [`Self::name_or_placeholder`], [`Self::observed_pid`],
597    /// [`Self::annotation`], [`Self::declared_parent_pid`]). The
598    /// empty-slot corner (`spec.identity.name_override = None`,
599    /// matching a Process authored WITHOUT the human-name-override
600    /// escape hatch — the default; `derive_identity` then computes
601    /// the name from the content hash) collapses to `None` so
602    /// `.is_some()` / `if let Some(_)` / `.map(...)` behave
603    /// identically on the two Process shapes an operator can author.
604    ///
605    /// Peer to [`Self::declared_parent_pid`] on the (parent × name-
606    /// override) sub-axis of the declared-identity axis: both
607    /// primitives project a `Option<String>` slot on `IdentitySpec`
608    /// through the SAME borrow-form skeleton, so a future
609    /// `declared_identity` composite that returns both halves
610    /// together (e.g. as a `(Option<&str>, Option<&str>)` tuple or a
611    /// borrow-form `DeclaredIdentityView<'_>` newtype) lands as ONE
612    /// method that COMPOSES the two peer primitives, not as three
613    /// hand-authored `.as_deref()` chains restated at each callsite.
614    ///
615    /// A future normalization step (a per-slot canonicalization pass
616    /// that rejects malformed names, a case-fold lookup against a
617    /// table of renamed identities, an alias-table lookup that maps
618    /// a legacy name-override to its current spelling, a whitespace-
619    /// trim lift OUT of `derive_identity` INTO the primitive so both
620    /// consumers see the trimmed form) lands at ONE substrate method
621    /// here and both downstream consumers pick up the upgrade
622    /// mechanically — no per-callsite hand-edit at `handle_pending` /
623    /// `handle_forking`.
624    ///
625    /// Sibling to the peer spec-identity projection
626    /// [`Self::declared_parent_pid`] on the declared-identity axis;
627    /// this method opens the borrow-form peer on the name-override
628    /// sub-axis of the same closed set (`IdentitySpec { parent,
629    /// name_override }`). Future identity projections (a paired
630    /// `declared_identity` composite that returns both halves
631    /// together) land as peer methods on this same axis.
632    ///
633    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
634    /// the `.spec.identity.name_override.as_deref()` chain recurred
635    /// at two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
636    /// duplication trigger, and is lifted to ONE owner here).
637    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
638    /// the pins bind the empty-slot corner + the borrow-form `&str`
639    /// lifetime + the byte-identical parity with the pre-lift
640    /// `.as_deref()` chain + the invariance under
641    /// [`derive_identity`]'s internal trim/filter step, so a
642    /// regression that drifted any surface at
643    /// `tests::declared_name_override_*` rather than as silent
644    /// operator-facing skew between the DECLARE composer and the
645    /// ALLOCATE-PID rehydration branch on the SAME Process spec).
646    pub fn declared_name_override(&self) -> Option<&str> {
647        self.spec.identity.name_override.as_deref()
648    }
649
650    /// Borrowed slice of the FluxCD resources this Process's status
651    /// currently persists at `status.flux_resources`, with the
652    /// missing-`status` corner collapsed to an empty slice — the ONE-
653    /// line collapse of the paired `self.status.as_ref().map(|s|
654    /// s.flux_resources.clone()).unwrap_or_default()` incantation
655    /// every VERIFY-phase / ATTEST-heartbeat consumer restated by hand
656    /// pre-lift.
657    ///
658    /// Pre-lift the 5-line `.status.as_ref().map(|s| s.flux_resources
659    /// .clone()).unwrap_or_default()` chain was hand-authored at TWO
660    /// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
661    /// `tatara-reconciler::phase_machine`:
662    /// * `handle_running` — the VERIFY-phase per-ref readiness probe
663    ///   seed that walks every ref through
664    ///   [`crate::status::FluxResourceRef::fetch_coords`] via
665    ///   `ssapply::fetch_flux_ref` and rebuilds an updated
666    ///   `Vec<FluxResourceRef>` with `ready` + `message` + `last_check`
667    ///   observed at reconcile time.
668    /// * `handle_attested` — the ATTEST-heartbeat drift detector that
669    ///   short-circuits on the first non-Ready ref via
670    ///   `ssapply::fetch_flux_ref` + `ssapply::ready_condition`.
671    ///
672    /// Both sites walked the SAME 5-line chain — clone the vector
673    /// eagerly for the length of the reconcile pass, then iterate it
674    /// by reference — even though neither site ever mutates the vector
675    /// nor keeps it alive past the enclosing async fn. Post-lift both
676    /// callers borrow the slice directly from `self.status`; the two
677    /// pre-lift `.clone()` calls disappear because the slice lives for
678    /// the borrow of `&self`, and both call sites' subsequent
679    /// downstream calls (`ssapply::fetch_flux_ref` / the
680    /// `patch::patch_process_status` write) do not touch the borrowed
681    /// `p: &Process`, so the borrow lifetime holds.
682    ///
683    /// Return-form axis: `&[FluxResourceRef]` mirrors the existing
684    /// borrow-first discipline every pre-lift consumer already
685    /// iterated by reference (`for r in &refs`), and the shape of
686    /// [`crate::status::FluxResourceRef::fetch_coords`]'s per-ref
687    /// borrow projection extends mechanically to the slice-level
688    /// projection here. The missing-`status` corner collapses to the
689    /// empty slice `&[]` so `.is_empty()` / `.len()` / iteration all
690    /// behave identically on a `Process` whose status is `None` and
691    /// on one whose status carries an empty `flux_resources` slot —
692    /// matching what the pre-lift `.unwrap_or_default()` produced
693    /// (an empty `Vec`).
694    ///
695    /// A future normalization step (a per-ref canonicalization pass
696    /// that skips duplicated refs, an owner-filter that returns only
697    /// refs stamped with the CURRENT `metadata.generation`, a
698    /// staleness gate that drops refs whose `last_check` predates a
699    /// reconcile deadline) lands at ONE substrate method here and
700    /// both downstream consumers pick up the upgrade mechanically —
701    /// no per-callsite hand-edit at `handle_running` /
702    /// `handle_attested`.
703    ///
704    /// Sibling to the [`Self::coordinates_or_none`] borrow-first
705    /// primitive on the metadata axis; this method opens the
706    /// analogous borrow-first primitive on the status-projection
707    /// axis. Future status projections (`observed_attestation` on
708    /// the attestation-chain axis, `observed_pid` on the PID axis,
709    /// `observed_children` on the child-fan-out axis) land as peer
710    /// methods on this same axis.
711    ///
712    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
713    /// the 5-line status-projection chain recurred at two hand-
714    /// 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    /// missing-`status` corner + the slice-lifetime borrow discipline
718    /// + the byte-identical parity with the pre-lift 5-line chain, so
719    /// a regression that drifted any of the three surfaces at
720    /// `tests::observed_flux_resources_*` rather than as silent
721    /// operator-facing skew between the VERIFY-phase and ATTEST-
722    /// heartbeat consumers).
723    pub fn observed_flux_resources(&self) -> &[FluxResourceRef] {
724        self.status
725            .as_ref()
726            .map(|s| s.flux_resources.as_slice())
727            .unwrap_or(&[])
728    }
729
730    /// The borrow-form status-projection primitive on the PID axis:
731    /// returns the hierarchical PID path (e.g. `"seph.1.7"`) the
732    /// reconciler currently persists at `status.pid`, with BOTH the
733    /// missing-`status` corner AND the empty-slot corner collapsed
734    /// to `None` — the ONE-liner collapse of the paired
735    /// `self.status.as_ref().and_then(|s| s.pid.clone())` incantation
736    /// every consumer restated by hand pre-lift.
737    ///
738    /// Pre-lift the 3-line `.status.as_ref().and_then(|s| s.pid
739    /// .clone())` chain was hand-authored at TWO sites past the ★★
740    /// PRIME-DIRECTIVE ≥ 2 duplication threshold in
741    /// `tatara-reconciler::phase_machine`:
742    /// * `handle_forking` — the ALLOCATE-PID gate that short-
743    ///   circuits the PID allocator when the reconciler already
744    ///   assigned a PID on a prior reconcile pass (pre-lift the
745    ///   chain composed with `.is_some()` and threw the clone away
746    ///   without ever reading the string).
747    /// * `handle_exiting` — the SIGTERM cascade that enumerates
748    ///   child Processes and terminates them by matching each
749    ///   child's `spec.identity.parent` against the PID this Process
750    ///   currently owns (pre-lift the chain bound an owned
751    ///   `Option<String>` and threaded `pid.as_str()` into the
752    ///   downstream `.as_deref() == Some(...)` comparator).
753    ///
754    /// Both sites walked the SAME 3-line chain — clone the `String`
755    /// eagerly, then either drop it (the `handle_forking` gate) or
756    /// re-borrow it through `.as_str()` (the `handle_exiting`
757    /// comparator) — even though neither site ever mutates the PID
758    /// nor keeps it alive past the enclosing async fn. Post-lift
759    /// both callers borrow the PID directly from `self.status`; the
760    /// pre-lift `.clone()` at both sites disappears because the
761    /// `&str` lives for the borrow of `&self`, and both call sites'
762    /// subsequent downstream calls (the K8s API list/patch, the
763    /// child-Process comparator) do not touch the borrowed
764    /// `p: &Process`, so the borrow lifetime holds.
765    ///
766    /// Return-form axis: `Option<&str>` mirrors the existing
767    /// borrow-first discipline every pre-lift consumer already
768    /// re-borrowed through `.as_str()` before use, and the shape of
769    /// [`Self::coordinates_or_none`]'s `Option<(&str, &str)>`
770    /// projection extends mechanically to the single-slot
771    /// projection here. The missing-`status` corner AND the
772    /// populated-status-with-`pid=None` corner BOTH collapse to
773    /// `None` so `.is_some()` / `if let Some(_)` / `.map(...)`
774    /// behave identically on a `Process` whose status is `None`
775    /// and on one whose status carries an unpopulated `pid` slot —
776    /// matching what the pre-lift `.and_then(...)` chain produced.
777    ///
778    /// A future normalization step (a per-slot canonicalization
779    /// pass that rejects malformed hierarchical PIDs, a
780    /// generation-filter that returns `None` for a PID stamped
781    /// with a stale `metadata.generation`, a staleness gate that
782    /// drops a PID whose observing `phase_since` predates a
783    /// reconcile deadline) lands at ONE substrate method here and
784    /// both downstream consumers pick up the upgrade mechanically
785    /// — no per-callsite hand-edit at `handle_forking` /
786    /// `handle_exiting`.
787    ///
788    /// Sibling to the peer [`Self::observed_flux_resources`]
789    /// borrow-first primitive on the flux-resources axis; both
790    /// methods compose the same missing-`status` fallback +
791    /// borrow-form return-shape skeleton on distinct
792    /// `ProcessStatus` slots. Future status projections
793    /// (`observed_parent` on the parent-pointer axis,
794    /// `observed_message` on the human-readable-status axis,
795    /// `observed_attestation` on the attestation-chain axis) land
796    /// as peer methods on this same axis.
797    ///
798    /// Theory anchor: THEORY.md §VI.1 (generation over
799    /// composition — the 3-line status-projection chain recurred
800    /// at two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
801    /// duplication trigger, and is lifted to ONE owner here).
802    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
803    /// the pins bind the missing-`status` corner + the empty-slot
804    /// corner + the borrow-form `&str` lifetime + the
805    /// byte-identical parity with the pre-lift 3-line chain, so a
806    /// regression that drifted any surface at
807    /// `tests::observed_pid_*` rather than as silent operator-
808    /// facing skew between the ALLOCATE-PID gate and the SIGTERM
809    /// cascade on the SAME `Process`).
810    pub fn observed_pid(&self) -> Option<&str> {
811        self.status.as_ref().and_then(|s| s.pid.as_deref())
812    }
813
814    /// The borrow-form status-projection primitive on the
815    /// attestation-chain axis: returns the last
816    /// [`ProcessAttestation`] the reconciler persisted at
817    /// `status.attestation`, with the missing-`status` corner AND the
818    /// empty-slot corner BOTH collapsed to `None` — the ONE-liner
819    /// collapse of the paired `self.status.as_ref().and_then(|s|
820    /// s.attestation.as_ref())` incantation every consumer restated
821    /// by hand pre-lift.
822    ///
823    /// Pre-lift the 3-line `.status.as_ref().and_then(|s| s
824    /// .attestation.as_ref())` chain was hand-authored at TWO sites
825    /// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
826    /// `tatara-reconciler`:
827    /// * `phase_machine::advance_to_attested` — the ATTEST composer
828    ///   that chains `prior.next(pillars)` when a prior attestation
829    ///   is persisted and seeds with `ProcessAttestation::initial`
830    ///   otherwise.
831    /// * `render::render_export_jobs` — the ephemeral-export Job
832    ///   builder that pulls the prior `composed_root` off the last
833    ///   persisted attestation and threads it into every rendered
834    ///   Job's `previousRoot` env var, so the export receipt chains
835    ///   into the Process's BLAKE3 attestation tree at the correct
836    ///   generation boundary.
837    ///
838    /// Both sites walked the SAME 3-line chain — the borrow-form
839    /// `Option<&ProcessAttestation>` shape both consumers wanted
840    /// already — even though neither site ever mutated the
841    /// attestation nor kept it alive past the enclosing async fn.
842    /// Post-lift both callers borrow the attestation directly from
843    /// `self.status`; the pre-lift 3-line chain shrinks to a single
844    /// method call at both sites, and both consumers' subsequent
845    /// downstream calls (`ProcessAttestation::next` for the ATTEST
846    /// composer, `.composed_root.clone()` for the export Job builder)
847    /// do not touch the borrowed `p: &Process`, so the borrow
848    /// lifetime holds.
849    ///
850    /// Return-form axis: `Option<&ProcessAttestation>` mirrors the
851    /// existing borrow-first discipline every pre-lift consumer
852    /// already re-borrowed through `.as_ref()`, and the shape of the
853    /// peer [`Self::observed_pid`] projection extends mechanically
854    /// to the whole-attestation-record projection here. The missing-
855    /// `status` corner AND the populated-status-with-`attestation
856    /// =None` corner BOTH collapse to `None` so `.is_some()` / `if
857    /// let Some(_)` / `.map(...)` behave identically on a `Process`
858    /// whose status is `None` and on one whose status carries an
859    /// unpopulated `attestation` slot — matching what the pre-lift
860    /// `.and_then(...)` chain produced.
861    ///
862    /// A future normalization step (a per-slot canonicalization pass
863    /// that rejects a persisted attestation whose `composed_root`
864    /// fails `verify`, a generation-filter that returns `None` for
865    /// an attestation stamped with a stale `metadata.generation`, a
866    /// staleness gate that drops an attestation whose `attested_at`
867    /// predates a reconcile deadline) lands at ONE substrate method
868    /// here and both downstream consumers pick up the upgrade
869    /// mechanically — no per-callsite hand-edit at
870    /// `advance_to_attested` / `render_export_jobs`.
871    ///
872    /// Sibling to the peer [`Self::observed_pid`] +
873    /// [`Self::observed_flux_resources`] borrow-first primitives on
874    /// the PID + flux-resources axes; all three methods compose the
875    /// same missing-`status` fallback + borrow-form return-shape
876    /// skeleton on distinct `ProcessStatus` slots. Future status
877    /// projections (`observed_parent` on the parent-pointer axis,
878    /// `observed_message` on the human-readable-status axis) land
879    /// as peer methods on this same axis.
880    ///
881    /// Theory anchor: THEORY.md §VI.1 (generation over composition
882    /// — the 3-line status-projection chain recurred at two hand-
883    /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
884    /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
885    /// invariant 5 (composition preserves proofs — the pins bind
886    /// the missing-`status` corner + the empty-slot corner + the
887    /// borrow-form `&ProcessAttestation` lifetime + the byte-
888    /// identical parity with the pre-lift 3-line chain, so a
889    /// regression that drifted any surface at
890    /// `tests::observed_attestation_*` rather than as silent
891    /// operator-facing skew between the ATTEST composer and the
892    /// ephemeral-export receipt chain on the SAME `Process`).
893    pub fn observed_attestation(&self) -> Option<&ProcessAttestation> {
894        self.status.as_ref().and_then(|s| s.attestation.as_ref())
895    }
896
897    /// The borrow-form status-projection primitive on the resolved-
898    /// identity axis: returns the [`Identity`] the reconciler
899    /// currently persists at `status.identity` (name + content hash +
900    /// override flag), with the missing-`status` corner AND the
901    /// empty-slot corner BOTH collapsed to `None` — the ONE-liner
902    /// collapse of the paired `self.status.as_ref().and_then(|s|
903    /// s.identity.as_ref())` incantation every consumer restated by
904    /// hand pre-lift.
905    ///
906    /// Pre-lift the paired `.status.as_ref().and_then(|s|
907    /// s.identity.<clone|as_ref>())` chain was hand-authored at TWO
908    /// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold
909    /// in `tatara-reconciler`:
910    /// * `phase_machine::handle_forking` — the FORK-time identity
911    ///   seed that reuses the reconciler-persisted `Identity` if
912    ///   present and falls back to a fresh `derive_identity(&spec,
913    ///   name_override)` otherwise. Pre-lift the site cloned the
914    ///   whole `Identity` off the borrow before threading it through
915    ///   `.unwrap_or_else(...)` even though the fallback path
916    ///   allocates its own owned `Identity` — the pre-lift clone
917    ///   allocated a fresh `Identity` on the happy path just so the
918    ///   `Option`'s shape matched the fallback's `Identity` return
919    ///   type.
920    /// * `ssapply::inject_annotations` — the SSA-time annotation
921    ///   composer that stamps the content-hash annotation onto every
922    ///   owned resource. Pre-lift the site nested the identity
923    ///   borrow-form check inside a manual `if let Some(status) =
924    ///   &process.status { … }` guard alongside sibling `status.pid`
925    ///   and `status.attestation` accesses — three siblings the peer
926    ///   primitives [`Self::observed_pid`] and
927    ///   [`Self::observed_attestation`] already own, so the outer
928    ///   status guard was the last hand-authored `.status.as_ref()`
929    ///   destructure at this composer.
930    ///
931    /// Both sites walked the SAME 3-line chain (one via `.clone()`,
932    /// one via `.as_ref()`) — the borrow-form
933    /// `Option<&Identity>` shape both consumers wanted already, even
934    /// though the FORK-time seed then had to `.clone()` off the
935    /// borrow to compose with the owned-`Identity` fallback. Post-
936    /// lift the seed calls `.observed_identity().cloned()` at the
937    /// exact composition point where the owned value is required
938    /// (the empty-borrow corner clones nothing, since
939    /// `Option::cloned` on `None` is `None`), and the SSA-time
940    /// consumer drops the outer status guard entirely — the
941    /// three-sibling primitive family (pid + identity + attestation)
942    /// now peers through `observed_pid` +
943    /// `observed_identity` + `observed_attestation` at ONE call each
944    /// with no shared status destructure between them.
945    ///
946    /// Return-form axis: `Option<&Identity>` mirrors the
947    /// existing borrow-first discipline every pre-lift consumer
948    /// already re-borrowed through `.as_ref()` / re-cloned through
949    /// `.clone()`, and the shape of the peer
950    /// [`Self::observed_attestation`] projection extends
951    /// mechanically to the whole-`Identity`-record projection here.
952    /// The missing-`status` corner AND the populated-status-with-
953    /// `identity=None` corner BOTH collapse to `None` so
954    /// `.is_some()` / `if let Some(_)` / `.map(...)` behave
955    /// identically on a `Process` whose status is `None` and on one
956    /// whose status carries an unpopulated `identity` slot —
957    /// matching what the pre-lift `.and_then(...)` chain produced.
958    ///
959    /// A future normalization step (a per-slot canonicalization
960    /// pass that rejects an `Identity` whose `content_hash` fails
961    /// re-derivation against the current spec, a generation-filter
962    /// that returns `None` for an identity stamped with a stale
963    /// `metadata.generation`, a staleness gate that drops an
964    /// identity whose observing `phase_since` predates a reconcile
965    /// deadline) lands at ONE substrate method here and both
966    /// downstream consumers pick up the upgrade mechanically — no
967    /// per-callsite hand-edit at `handle_forking` /
968    /// `inject_annotations`.
969    ///
970    /// Sibling to the peer [`Self::observed_pid`] +
971    /// [`Self::observed_attestation`] +
972    /// [`Self::observed_flux_resources`] borrow-first primitives on
973    /// the PID + attestation-chain + flux-resources axes; all four
974    /// methods compose the same missing-`status` fallback +
975    /// borrow-form return-shape skeleton on distinct `ProcessStatus`
976    /// slots. Future status projections (`observed_parent` on the
977    /// parent-pointer axis, `observed_message` on the human-
978    /// readable-status axis) land as peer methods on this same
979    /// axis.
980    ///
981    /// Theory anchor: THEORY.md §VI.1 (generation over composition
982    /// — the 3-line status-projection chain recurred at two hand-
983    /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
984    /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
985    /// invariant 5 (composition preserves proofs — the pins bind
986    /// the missing-`status` corner + the empty-slot corner + the
987    /// borrow-form `&Identity` lifetime + the byte-identical parity
988    /// with the pre-lift 3-line chain, so a regression that drifted
989    /// any surface at `tests::observed_identity_*` rather than as
990    /// silent operator-facing skew between the FORK-time identity
991    /// seed and the SSA-time content-hash annotation stamp on the
992    /// SAME `Process`).
993    pub fn observed_identity(&self) -> Option<&Identity> {
994        self.status.as_ref().and_then(|s| s.identity.as_ref())
995    }
996
997    /// The copy-form status-projection primitive on the phase axis:
998    /// returns the [`ProcessPhase`] the reconciler currently persists
999    /// at `status.phase`, wrapped in an `Option` so the missing-
1000    /// `status` corner collapses to `None` — the ONE-liner collapse
1001    /// of the paired `self.status.as_ref().map(|s| s.phase)`
1002    /// incantation every consumer restated by hand pre-lift.
1003    ///
1004    /// Peer to the borrow-form projections
1005    /// [`Self::observed_pid`] (PID axis, `Option<&str>`),
1006    /// [`Self::observed_flux_resources`] (flux-resources axis,
1007    /// `&[FluxResourceRef]`), and [`Self::observed_attestation`]
1008    /// (attestation-chain axis, `Option<&ProcessAttestation>`); this
1009    /// method opens the copy-form peer for `ProcessPhase` — a
1010    /// `Copy` scalar with a `Default` impl (`Pending`), so the
1011    /// return is `Option<ProcessPhase>` rather than
1012    /// `Option<&ProcessPhase>` (borrow would give the caller
1013    /// nothing over the copy for a 1-byte enum) and neither the
1014    /// missing-`status` corner nor a "empty slot" corner is
1015    /// meaningful — the underlying slot is a bare `ProcessPhase`,
1016    /// not `Option<ProcessPhase>`, so the primitive returns `None`
1017    /// iff `status: None`.
1018    ///
1019    /// Pre-lift the 3-line `.status.as_ref().map(|s| s.phase)`
1020    /// chain was hand-authored at FIVE sites past the ★★
1021    /// PRIME-DIRECTIVE ≥ 2 duplication threshold in
1022    /// `tatara-reconciler`:
1023    /// * `controller::reconcile` — the top-level dispatcher's
1024    ///   `current_phase` seed that feeds the deletion-preempt +
1025    ///   signal-ingestion gates + the per-phase handler dispatch.
1026    ///   Pre-lift `.unwrap_or(ProcessPhase::Pending)`.
1027    /// * `boundary::evaluate_process_phase` — the boundary
1028    ///   evaluator's `ProcessPhase` condition (a peer-Process
1029    ///   `phase`-reached postcondition). Pre-lift
1030    ///   `.unwrap_or(ProcessPhase::Pending)`.
1031    /// * `boundary::check_depends_on` — the `depends_on`
1032    ///   pre-condition audit that stashes the observed phase into
1033    ///   the `UnmetDependency::actual: Option<ProcessPhase>` slot
1034    ///   (keeps the `Option` form). Pre-lift the raw
1035    ///   `.map(|s| s.phase)` shape.
1036    /// * `phase_machine::p_current_phase_str` — the released-from
1037    ///   annotation composer that emits `"Attested"` for every
1038    ///   non-`Failed` phase (SIGSTOP/SIGCONT release gate).
1039    ///   Pre-lift `.unwrap_or(ProcessPhase::Attested)` — the ONE
1040    ///   site whose default is not `Pending`; the primitive
1041    ///   returns the raw `Option` so the caller's `.unwrap_or`
1042    ///   default choice stays local rather than baked in.
1043    /// * `table_controller::stable_name_group_key` — the routing-
1044    ///   groupby seed that pairs the phase with the PID + creation
1045    ///   timestamp when partitioning Processes claiming the same
1046    ///   stable name. Pre-lift `.unwrap_or(ProcessPhase::Pending)`.
1047    ///
1048    /// All FIVE sites walked the SAME 3-line `.status.as_ref()
1049    /// .map(|s| s.phase)` chain — three closed with `unwrap_or
1050    /// (ProcessPhase::Pending)` (the `Default`), one closed with
1051    /// `unwrap_or(ProcessPhase::Attested)`, one kept the raw
1052    /// `Option<ProcessPhase>` — so the ONE substrate accessor
1053    /// returns the raw `Option<ProcessPhase>` and each consumer
1054    /// keeps its `.unwrap_or(...)` default choice at its own site.
1055    ///
1056    /// A future normalization step (a generation-filter that
1057    /// returns `None` for a phase stamped with a stale
1058    /// `metadata.generation`, a staleness gate that drops a phase
1059    /// whose observing `phase_since` predates a reconcile
1060    /// deadline, a canonicalization pass that maps a phase that
1061    /// no longer belongs to the CRD's closed set to `None`) lands
1062    /// at ONE substrate method here and all five consumers pick
1063    /// up the upgrade mechanically — no per-callsite hand-edit at
1064    /// `reconcile` / `evaluate_process_phase` / `check_depends_on`
1065    /// / `p_current_phase_str` / `stable_name_group_key`.
1066    ///
1067    /// Future status projections (`observed_parent` on the
1068    /// parent-pointer axis, `observed_message` on the human-
1069    /// readable-status axis, `observed_children` on the child
1070    /// fan-out axis, `observed_exit_code` on the terminal-exit
1071    /// axis) land as peer methods on this same axis.
1072    ///
1073    /// Theory anchor: THEORY.md §VI.1 (generation over
1074    /// composition — the 3-line status-projection chain recurred
1075    /// at FIVE hand-authored sites past the ★★ PRIME-DIRECTIVE
1076    /// ≥ 2 duplication trigger, and is lifted to ONE owner here).
1077    /// THEORY.md §II.1 invariant 5 (composition preserves proofs
1078    /// — the pins bind the missing-`status` corner + the
1079    /// per-variant enum round-trip + the byte-identical parity
1080    /// with the pre-lift 3-line chain, so a regression that
1081    /// drifted any surface at `tests::observed_phase_*` rather
1082    /// than as silent operator-facing skew between the
1083    /// controller's dispatch seed and the boundary evaluator's
1084    /// depends-on audit on the SAME `Process` within one
1085    /// reconcile pass).
1086    pub fn observed_phase(&self) -> Option<ProcessPhase> {
1087        self.status.as_ref().map(|s| s.phase)
1088    }
1089
1090    /// The copy-form status-projection primitive on the phase axis
1091    /// with the `Pending` sink applied — the ONE-liner collapse of
1092    /// the paired `self.observed_phase().unwrap_or(ProcessPhase::
1093    /// Pending)` incantation every reconciler consumer restated by
1094    /// hand at the `Option`-flattening tail of the `observed_phase`
1095    /// call. Sibling to [`Self::observed_phase`] on the (return-form
1096    /// × fallback shape) axis pair — the raw-`Option` corner stays
1097    /// as `observed_phase`, this method opens the `Pending`-defaulted
1098    /// corner that four of the five hand-authored `observed_phase`
1099    /// consumers chose (the fifth chose `Attested`; it keeps the raw
1100    /// `Option` accessor because a `Pending` sink would silently drop
1101    /// its released-from-annotation branch into the wrong label).
1102    ///
1103    /// The primitive returns [`ProcessPhase::Pending`] on any missing
1104    /// `status` slot — the same sentinel [`ProcessPhase::default`]
1105    /// returns, and the same fallback all four pre-lift consumers
1106    /// wrote by hand. `ProcessPhase::Pending` is load-bearing as the
1107    /// "not yet observed" default because the top-level dispatcher's
1108    /// `Pending → Forking` transition, the boundary evaluator's
1109    /// per-Process phase-reached postcondition, the routing groupby's
1110    /// stable-name claim-arbiter row seed, and the pool controller's
1111    /// desired-count snapshot all read a freshly-forked Process (no
1112    /// `status` yet stamped by the reconciler) as being at the
1113    /// entrypoint phase of the closed lifecycle. A caller with a
1114    /// different default choice (currently only the SIGSTOP/SIGCONT
1115    /// release gate's `Attested` fallback in
1116    /// `phase_machine::p_current_phase_str`) keeps the raw
1117    /// [`Self::observed_phase`] accessor at its own site.
1118    ///
1119    /// Pre-lift the two-link `.observed_phase().unwrap_or
1120    /// (ProcessPhase::Pending)` chain was hand-authored at FOUR
1121    /// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold
1122    /// across the workspace:
1123    /// * `tatara-reconciler::controller::reconcile` — the top-level
1124    ///   dispatcher's `current_phase` seed that feeds the
1125    ///   deletion-preempt + signal-ingestion gates + the per-phase
1126    ///   handler dispatch.
1127    /// * `tatara-reconciler::boundary::evaluate_process_phase` — the
1128    ///   boundary evaluator's [`ConditionKind::ProcessPhase`]
1129    ///   evaluator that compares a peer-Process's observed phase
1130    ///   against the operator-declared `phase`-reached postcondition.
1131    /// * `tatara-reconciler::table_controller::stable_name_group_key`
1132    ///   — the routing-groupby seed that pairs the phase with the
1133    ///   PID + creation timestamp when partitioning Processes
1134    ///   claiming the same stable name.
1135    /// * `tatara-pool-reconciler::controller_pool::reconcile_pool` —
1136    ///   the desired-count loop's per-member snapshot seed that feeds
1137    ///   `decide_pool_convergence` with each owned Process's
1138    ///   `(phase, created_at)` pair.
1139    ///
1140    /// All FOUR sites walked the SAME two-link chain and all four
1141    /// closed with `ProcessPhase::Pending` as the sink; post-lift
1142    /// each callsite reads `process.observed_phase_or_pending()` and
1143    /// the produced `ProcessPhase` feeds the same downstream branch
1144    /// (dispatch on the `current_phase` value, comparison against a
1145    /// declared threshold, groupby-key composition, member-state
1146    /// snapshot construction) unchanged.
1147    ///
1148    /// Return-form axis: `ProcessPhase` matches the copy discipline
1149    /// of [`Self::observed_phase`] (a `Copy` scalar one byte wide),
1150    /// with the [`Option`] wrapper collapsed at the primitive rather
1151    /// than at every consumer. A caller that needs the missing-`status`
1152    /// corner as a distinguishable value keeps the raw
1153    /// [`Self::observed_phase`] accessor.
1154    ///
1155    /// A future normalization step (a generation-filter that
1156    /// treats a phase stamped with a stale `metadata.generation` as
1157    /// unobserved and therefore `Pending`, a staleness gate that
1158    /// drops a phase whose observing `phase_since` predates a
1159    /// reconcile deadline, a canonicalization pass that maps a phase
1160    /// that no longer belongs to the CRD's closed set to `Pending`)
1161    /// lands at ONE substrate method here — because this primitive
1162    /// composes on top of [`Self::observed_phase`], the normalization
1163    /// applies to both the raw-`Option` and the `Pending`-sinked
1164    /// return through the SAME upstream body — and all four
1165    /// downstream consumers pick up the upgrade mechanically.
1166    ///
1167    /// Peer to the sibling defaulted-fallback primitive family
1168    /// [`Self::namespace_or_default`] +
1169    /// [`Self::name_or_placeholder`] + [`Self::uid_or_empty`] on the
1170    /// (return-shape × fallback-value) axis — those three open the
1171    /// borrow-form defaulted corner for the metadata slots; this
1172    /// method opens the copy-form defaulted corner for the phase
1173    /// slot on `status`. Future defaulted-fallback status
1174    /// projections (an `observed_pid_or_empty` on the PID axis, an
1175    /// `observed_exit_code_or_zero` on the terminal-exit axis) land
1176    /// as peer methods on this same axis.
1177    ///
1178    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1179    /// the two-link `.observed_phase().unwrap_or(Pending)` chain
1180    /// recurred at four hand-authored sites past the ★★
1181    /// PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE
1182    /// owner here). THEORY.md §II.1 invariant 5 (composition
1183    /// preserves proofs — the pins bind the missing-`status` sink to
1184    /// `Pending` + populated-status pass-through + every
1185    /// `ProcessPhase` variant round-trip + byte-identical parity
1186    /// with the pre-lift two-link chain, so a regression that
1187    /// drifted any surface at `tests::observed_phase_or_pending_*`
1188    /// rather than as silent operator-facing skew between the
1189    /// top-level dispatcher's `Pending → Forking` seed and the
1190    /// boundary evaluator's per-Process phase-reached postcondition
1191    /// on the SAME `Process` within one reconcile pass).
1192    pub fn observed_phase_or_pending(&self) -> ProcessPhase {
1193        self.observed_phase().unwrap_or(ProcessPhase::Pending)
1194    }
1195
1196    /// Copy-form metadata-projection primitive on the deletion-tombstone
1197    /// axis: returns `true` iff the K8s API server has stamped a
1198    /// `metadata.deletionTimestamp` on this Process (the moment the
1199    /// object entered the "being deleted" corner of its lifecycle,
1200    /// after which further mutating writes are refused and finalizers
1201    /// are drained before the object is actually removed) — the ONE-
1202    /// liner collapse of the paired `self.metadata.deletion_timestamp
1203    /// .is_some()` incantation every consumer restated by hand
1204    /// pre-lift.
1205    ///
1206    /// Pre-lift the `.metadata.deletion_timestamp.is_some()` chain
1207    /// was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE
1208    /// ≥ 2 duplication threshold in `tatara-reconciler`, both
1209    /// projecting the SAME tombstone-presence predicate on a
1210    /// `Process` value:
1211    /// * `controller::reconcile` — the top-level dispatcher's
1212    ///   deletion-preempt gate that forces the SIGTERM cascade
1213    ///   (`→ Exiting`) as soon as the API server stamps the
1214    ///   tombstone, before the phase handler for the current
1215    ///   [`ProcessPhase`] gets a chance to run. Composed with
1216    ///   [`ProcessPhase::is_alive`] so the preempt only fires on a
1217    ///   Process still in an alive phase — a Process already in
1218    ///   `Zombie` / `Reaped` / `Failed` runs its normal handler.
1219    /// * `phase_machine::handle_exiting` — the SIGTERM cascade's
1220    ///   child-fan-out loop that enumerates every child Process and
1221    ///   skips ones the API server has already tombstoned (so the
1222    ///   reconciler does not re-issue a `DELETE` against a child
1223    ///   whose deletion the API server is already draining through
1224    ///   its own finalizer). The skip composes with
1225    ///   [`Self::coordinates_or_none`]'s name-required probe so a
1226    ///   child missing either its tombstone-absent gate or its
1227    ///   `metadata.name` slot is a clean `continue` rather than an
1228    ///   attempted `child_api.delete("")` no-op.
1229    ///
1230    /// Both sites walked the SAME `.metadata.deletion_timestamp
1231    /// .is_some()` chain and both wanted the `bool` form the
1232    /// primitive returns — the `controller::reconcile` site to gate
1233    /// the SIGTERM preempt with `&& current_phase.is_alive()` and
1234    /// the `handle_exiting` site to gate the DELETE-skip with a
1235    /// bare `if child.is_being_deleted() { continue; }`. Post-lift
1236    /// each callsite reads `process.is_being_deleted()` and the
1237    /// produced `bool` feeds the same downstream gate unchanged.
1238    ///
1239    /// Return-form axis: `bool` matches the copy-form discipline of
1240    /// [`Self::observed_phase`] (an `Option<Copy>` scalar) — the
1241    /// underlying slot is a wire-format `Option<Time>` that carries
1242    /// only presence information at this axis (the RFC-3339 timestamp
1243    /// payload itself is not what the two consumers read; both only
1244    /// probe presence to detect the tombstone-stamped state).
1245    /// Returning the raw `Option<&Time>` would push the `.is_some()`
1246    /// probe back to every callsite, restating the pre-lift chain
1247    /// one link shorter without collapsing the primitive.
1248    ///
1249    /// Peer to the metadata-fallback primitives
1250    /// [`Self::namespace_or_default`], [`Self::name_or_placeholder`],
1251    /// [`Self::uid_or_empty`], [`Self::coordinates_or_defaults`],
1252    /// [`Self::coordinates_or_none`], [`Self::owned_coordinates_or_err`],
1253    /// [`Self::annotation`] on the metadata axis; this method opens
1254    /// the copy-form peer for the presence-probe corner. Future
1255    /// metadata-presence projections (an `is_being_finalized`
1256    /// projection on `metadata.finalizers.is_empty()`'s negation,
1257    /// a `has_owner` projection on `metadata.owner_references.is_empty()`'s
1258    /// negation) land as peer methods on this same axis.
1259    ///
1260    /// A future normalization step (a per-tombstone staleness gate
1261    /// that returns `false` for a tombstone older than the reconciler's
1262    /// grace-period budget, a canonicalization pass that treats a
1263    /// tombstone from a paused controller as absent, a cross-cluster
1264    /// tombstone-observation clock skew guard) lands at ONE substrate
1265    /// method here and both downstream consumers pick up the upgrade
1266    /// mechanically — no per-callsite hand-edit at
1267    /// `controller::reconcile` / `phase_machine::handle_exiting`.
1268    ///
1269    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1270    /// the `.metadata.deletion_timestamp.is_some()` chain recurred at
1271    /// two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
1272    /// duplication trigger, and is lifted to ONE owner here).
1273    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
1274    /// the pins bind the missing-tombstone corner + the present-
1275    /// tombstone corner + the copy-form `bool` return + the byte-
1276    /// identical parity with the pre-lift `.is_some()` chain, so a
1277    /// regression that drifted any surface at
1278    /// `tests::is_being_deleted_*` rather than as silent operator-
1279    /// facing skew between the top-level dispatcher's SIGTERM
1280    /// preempt and the SIGTERM cascade's child-fan-out DELETE-skip
1281    /// on the SAME `Process` within one reconcile pass).
1282    pub fn is_being_deleted(&self) -> bool {
1283        self.metadata.deletion_timestamp.is_some()
1284    }
1285
1286    /// Copy-form metadata-projection primitive on the
1287    /// `metadata.creationTimestamp` axis: returns the K8s-API-server-
1288    /// assigned creation moment as a `DateTime<Utc>`, hiding the wire-
1289    /// format `k8s_openapi::apimachinery::pkg::apis::meta::v1::Time`
1290    /// newtype behind an inherent projection — the ONE-liner collapse
1291    /// of the paired `self.metadata.creation_timestamp.as_ref().map(|t|
1292    /// t.0)` incantation every timestamp-driven consumer restated by
1293    /// hand pre-lift.
1294    ///
1295    /// Pre-lift the paired `.metadata.creation_timestamp.as_ref()` +
1296    /// `t.0` unwrap chain was hand-authored at THREE sites past the
1297    /// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold across the
1298    /// workspace, all projecting the SAME creation-moment `DateTime<Utc>`
1299    /// on a `Process`:
1300    /// * `tatara-process::lifetime_clock::evaluate` — TTL-expiry gate
1301    ///   in the ephemeral-lifetime decision (`elapsed = now
1302    ///   .signed_duration_since(creation.0)`), inside the non-terminal-
1303    ///   phase guard that fires the `AutoTerminate::Now { TtlExpired }`
1304    ///   branch. Pre-lift the site read `if let Some(creation) = process
1305    ///   .metadata.creation_timestamp.as_ref() { ... creation.0 ... }`.
1306    /// * `tatara-process::lifetime_clock::requeue_with_ttl` — sleep-
1307    ///   budget picker for the reconciler's next requeue, choosing the
1308    ///   smaller of HEARTBEAT and TTL-remaining so the reconciler
1309    ///   doesn't oversleep past a TTL boundary. Pre-lift the site read
1310    ///   `let Some(creation) = process.metadata.creation_timestamp
1311    ///   .as_ref() else { return default; };` + `creation.0`.
1312    /// * `tatara-reconciler::table_controller::reconcile_process_table`
1313    ///   — stable-name claim-arbiter row builder, seeding each
1314    ///   candidate row's `created_at` for the tie-break ordering
1315    ///   (oldest wins). Pre-lift the site read `p.metadata
1316    ///   .creation_timestamp.as_ref().map(|t| t.0).unwrap_or_else(Utc
1317    ///   ::now)`.
1318    ///
1319    /// All THREE sites walked the SAME two-link chain — read the
1320    /// `Option<Time>` slot as a borrow, then unwrap the `Time` newtype
1321    /// to its inner `DateTime<Utc>` — differing only in the tail
1322    /// (`if-let-Some` guard, `let-else` short-circuit, `Utc::now`
1323    /// fallback). Post-lift each callsite reads
1324    /// `process.created_at()` and applies its own tail at its own site
1325    /// (`if let Some(creation) = ...`, `let Some(creation) = ... else`,
1326    /// `.unwrap_or_else(Utc::now)`).
1327    ///
1328    /// Return-form axis: `Option<DateTime<Utc>>` matches the copy-form
1329    /// discipline of the sibling status-projection primitive
1330    /// [`Self::observed_phase`] — both return `Option<T>` where `T:
1331    /// Copy` and hide the wire-format wrapper (`ProcessStatus` on the
1332    /// status side; `Time` on the metadata side). Returning the raw
1333    /// `Option<&Time>` would push the `.0` unwrap back to every
1334    /// callsite, restating the pre-lift chain one link shorter without
1335    /// collapsing the primitive; returning owned `Option<Time>` would
1336    /// force a `Time` import at every consumer for a projection every
1337    /// consumer immediately discards past `.0`.
1338    ///
1339    /// Peer to the metadata-fallback + presence-probe primitives
1340    /// [`Self::namespace_or_default`], [`Self::name_or_placeholder`],
1341    /// [`Self::uid_or_empty`], [`Self::coordinates_or_defaults`],
1342    /// [`Self::coordinates_or_none`], [`Self::owned_coordinates_or_err`],
1343    /// [`Self::annotation`], [`Self::is_being_deleted`] on the metadata
1344    /// axis; this method opens the copy-form timestamp corner. Future
1345    /// metadata-timestamp projections (a
1346    /// `deletion_at() -> Option<DateTime<Utc>>` peer on the
1347    /// tombstone-payload axis for staleness gates that need the
1348    /// timestamp value alongside the presence bit) land as peer
1349    /// methods on this same axis.
1350    ///
1351    /// A future normalization step (a per-cluster clock-skew guard
1352    /// that offsets the returned timestamp by the observing controller's
1353    /// measured skew, a canonicalization pass that maps a suspiciously-
1354    /// zero creation moment to `None`, a per-namespace override that
1355    /// substitutes a `spec.identity`-declared creation anchor for the
1356    /// metadata slot on adopted resources) lands at ONE substrate
1357    /// method here and all three downstream consumers pick up the
1358    /// upgrade mechanically — no per-callsite hand-edit at `evaluate`
1359    /// / `requeue_with_ttl` / `reconcile_process_table`.
1360    ///
1361    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1362    /// the `.metadata.creation_timestamp.as_ref().map(|t| t.0)` chain
1363    /// recurred at three hand-authored sites past the ★★
1364    /// PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE
1365    /// owner here). THEORY.md §II.1 invariant 5 (composition preserves
1366    /// proofs — the pins bind the missing-timestamp corner + the
1367    /// present-timestamp corner + the copy-form `DateTime<Utc>` return
1368    /// + the byte-identical parity with the pre-lift `.as_ref().map(|t|
1369    /// t.0)` chain, so a regression that drifted any surface at
1370    /// `tests::created_at_*` rather than as silent operator-facing
1371    /// skew between the TTL-expiry gate, the requeue-budget picker,
1372    /// and the stable-name claim-arbiter tie-break on the SAME
1373    /// `Process` within one reconcile pass).
1374    pub fn created_at(&self) -> Option<DateTime<Utc>> {
1375        self.metadata.creation_timestamp.as_ref().map(|t| t.0)
1376    }
1377}
1378
1379/// Process status — every field optional until the reconciler writes it.
1380#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
1381#[serde(rename_all = "camelCase")]
1382pub struct ProcessStatus {
1383    /// Hierarchical PID path — e.g., `"seph.1.7"`.
1384    #[serde(default, skip_serializing_if = "Option::is_none")]
1385    pub pid: Option<String>,
1386
1387    /// Parent PID path (mirror of `spec.identity.parent`, resolved at fork).
1388    #[serde(default, skip_serializing_if = "Option::is_none")]
1389    pub parent: Option<String>,
1390
1391    /// Direct children's PID paths.
1392    #[serde(default)]
1393    pub children: Vec<String>,
1394
1395    /// Resolved identity (name + content hash).
1396    #[serde(default, skip_serializing_if = "Option::is_none")]
1397    pub identity: Option<Identity>,
1398
1399    /// Current phase.
1400    #[serde(default)]
1401    pub phase: ProcessPhase,
1402
1403    /// When the process entered the current phase.
1404    #[serde(default, skip_serializing_if = "Option::is_none")]
1405    pub phase_since: Option<DateTime<Utc>>,
1406
1407    /// Three-pillar attestation (written at end of every successful cycle).
1408    #[serde(default, skip_serializing_if = "Option::is_none")]
1409    pub attestation: Option<ProcessAttestation>,
1410
1411    /// FluxCD resources currently owned by this Process.
1412    #[serde(default)]
1413    pub flux_resources: Vec<FluxResourceRef>,
1414
1415    /// Boundary verification state.
1416    #[serde(default)]
1417    pub boundary: BoundaryStatus,
1418
1419    /// Compliance summary at the latest attestation.
1420    #[serde(default)]
1421    pub compliance: ComplianceStatus,
1422
1423    /// Pending signals (delivered, not yet handled).
1424    #[serde(default)]
1425    pub signal_queue: Vec<ProcessSignal>,
1426
1427    /// Standard K8s Conditions.
1428    #[serde(default)]
1429    pub conditions: Vec<ProcessCondition>,
1430
1431    /// Human-readable last status message.
1432    #[serde(default, skip_serializing_if = "Option::is_none")]
1433    pub message: Option<String>,
1434
1435    /// Exit code (only set on Failed / Reaped).
1436    #[serde(default, skip_serializing_if = "Option::is_none")]
1437    pub exit_code: Option<i32>,
1438}
1439
1440#[cfg(test)]
1441mod tests {
1442    use super::*;
1443    use crate::classification::{ConvergencePointType, SubstrateType};
1444    use crate::intent::NixIntent;
1445
1446    #[test]
1447    fn minimal_spec_serializes() {
1448        let spec = ProcessSpec {
1449            identity: IdentitySpec::default(),
1450            classification: Classification {
1451                point_type: ConvergencePointType::Gate,
1452                substrate: SubstrateType::Observability,
1453                horizon: Default::default(),
1454                calm: Default::default(),
1455                data_classification: Default::default(),
1456            },
1457            intent: Intent {
1458                nix: Some(NixIntent {
1459                    flake_ref: "github:pleme-io/k8s".into(),
1460                    attribute: "obs".into(),
1461                    system: None,
1462                    attic_cache: None,
1463                    extra_args: vec![],
1464                    delegate_to_nix_build: false,
1465                }),
1466                ..Intent::default()
1467            },
1468            boundary: Default::default(),
1469            compliance: Default::default(),
1470            depends_on: vec![],
1471            signals: Default::default(),
1472            lifetime: Default::default(),
1473            routing: None,
1474            encapsulates: None,
1475            suspended: false,
1476        };
1477        let yaml = serde_yaml::to_string(&spec).unwrap();
1478        assert!(yaml.contains("pointType: Gate"));
1479        assert!(yaml.contains("substrate: Observability"));
1480        assert!(yaml.contains("flakeRef: github:pleme-io/k8s"));
1481    }
1482
1483    // ─── Process::coordinates_or_defaults substrate pins ────────────────
1484    //
1485    // Pins the (namespace, name) coordinate-primitive family on the
1486    // (metadata slot × fallback shape) axis. Fail-before-pass-after
1487    // granularity: a regression that flipped either fallback string,
1488    // swapped the return-tuple axis order, or dropped the
1489    // `Option::as_deref` unwrap surfaces here rather than as silent
1490    // drift at every downstream annotation writer / claim-arbiter row
1491    // builder / render owner-metadata seed.
1492
1493    fn empty_spec() -> ProcessSpec {
1494        ProcessSpec {
1495            identity: IdentitySpec::default(),
1496            classification: Classification {
1497                point_type: ConvergencePointType::Gate,
1498                substrate: SubstrateType::Compute,
1499                horizon: Default::default(),
1500                calm: Default::default(),
1501                data_classification: Default::default(),
1502            },
1503            intent: Intent::default(),
1504            boundary: Default::default(),
1505            compliance: Default::default(),
1506            depends_on: vec![],
1507            signals: Default::default(),
1508            lifetime: Default::default(),
1509            routing: None,
1510            encapsulates: None,
1511            suspended: false,
1512        }
1513    }
1514
1515    #[test]
1516    fn default_namespace_constant_is_k8s_canonical_default() {
1517        // Pins the load-bearing convention that this primitive's
1518        // namespace fallback matches K8s's own implicit-namespace
1519        // spelling. A regression that renamed this to "kube-system"
1520        // or any other K8s-reserved name would silently misroute
1521        // every downstream namespaced-Api call on a Process without
1522        // a metadata.namespace.
1523        assert_eq!(Process::DEFAULT_NAMESPACE, "default");
1524    }
1525
1526    #[test]
1527    fn unnamed_placeholder_constant_matches_prior_annotation_writer_fallback() {
1528        // Pins the load-bearing convention that this primitive's name
1529        // fallback matches the exact spelling every annotation writer
1530        // (tatara-reconciler::ssapply::inject_annotations,
1531        // tatara-reconciler::render::render, and
1532        // tatara-reconciler::table_controller's claim-row builder)
1533        // was hand-authoring pre-lift ("unnamed", NOT "<unnamed>" or
1534        // ""). A regression that renamed this would break the
1535        // annotation-writer / claim-arbiter grep contract silently.
1536        assert_eq!(Process::UNNAMED_PLACEHOLDER, "unnamed");
1537    }
1538
1539    #[test]
1540    fn namespace_or_default_falls_back_when_metadata_namespace_is_none() {
1541        let mut p = Process::new("some-proc", empty_spec());
1542        p.metadata.namespace = None;
1543        assert_eq!(p.namespace_or_default(), Process::DEFAULT_NAMESPACE);
1544    }
1545
1546    #[test]
1547    fn namespace_or_default_returns_metadata_slice_when_some() {
1548        let mut p = Process::new("some-proc", empty_spec());
1549        p.metadata.namespace = Some("prod-app".into());
1550        assert_eq!(p.namespace_or_default(), "prod-app");
1551    }
1552
1553    #[test]
1554    fn name_or_placeholder_falls_back_when_metadata_name_is_none() {
1555        let mut p = Process::new("real-name", empty_spec());
1556        p.metadata.name = None;
1557        assert_eq!(p.name_or_placeholder(), Process::UNNAMED_PLACEHOLDER);
1558    }
1559
1560    #[test]
1561    fn name_or_placeholder_returns_metadata_slice_when_some() {
1562        let p = Process::new("api-gateway", empty_spec());
1563        assert_eq!(p.name_or_placeholder(), "api-gateway");
1564    }
1565
1566    #[test]
1567    fn coordinates_or_defaults_composes_both_halves() {
1568        // Both slots present — returns metadata slices in
1569        // (namespace, name) axis order.
1570        let mut p = Process::new("api", empty_spec());
1571        p.metadata.namespace = Some("staging".into());
1572        assert_eq!(p.coordinates_or_defaults(), ("staging", "api"));
1573    }
1574
1575    #[test]
1576    fn coordinates_or_defaults_falls_back_on_both_slots() {
1577        // Both slots None — returns (DEFAULT_NAMESPACE,
1578        // UNNAMED_PLACEHOLDER) in axis order.
1579        let mut p = Process::new("scratch", empty_spec());
1580        p.metadata.name = None;
1581        p.metadata.namespace = None;
1582        assert_eq!(
1583            p.coordinates_or_defaults(),
1584            (Process::DEFAULT_NAMESPACE, Process::UNNAMED_PLACEHOLDER)
1585        );
1586    }
1587
1588    #[test]
1589    fn coordinates_or_defaults_mixes_slotted_and_fallback_halves() {
1590        // Namespace set, name missing — the (namespace, name) tuple
1591        // pins each half independently. A regression that returned
1592        // BOTH fallbacks when EITHER metadata slot was None would
1593        // surface here rather than at every downstream reader.
1594        let mut p = Process::new("kept-name", empty_spec());
1595        p.metadata.namespace = Some("prod".into());
1596        assert_eq!(p.coordinates_or_defaults(), ("prod", "kept-name"));
1597
1598        // Name set, namespace missing — the peer corner.
1599        let mut q = Process::new("api", empty_spec());
1600        q.metadata.namespace = None;
1601        assert_eq!(
1602            q.coordinates_or_defaults(),
1603            (Process::DEFAULT_NAMESPACE, "api")
1604        );
1605    }
1606
1607    // ─── Process::owned_coordinates_or_err substrate pins ──────────────
1608    //
1609    // Pins the owned + name-required peer of the coordinate-primitive
1610    // family on the (return-form × name gate) axis pair. Fail-before-
1611    // pass-after granularity: a regression that flipped the namespace
1612    // fallback string, dropped the `Option::clone` unwrap, changed the
1613    // return-tuple axis order, or altered the "Process has no
1614    // metadata.name" error wording surfaces here rather than as silent
1615    // drift at every pre-lift caller (10 sites in
1616    // `tatara-reconciler::phase_machine` + 2 sites in
1617    // `tatara-reconciler::signals` pre-lift).
1618
1619    #[test]
1620    fn owned_coordinates_or_err_returns_owned_strings_when_both_slots_present() {
1621        // Happy path — both slots populated, method returns owned
1622        // Strings in (namespace, name) axis order.
1623        let mut p = Process::new("api-gateway", empty_spec());
1624        p.metadata.namespace = Some("prod-app".into());
1625        let (ns, name) = p.owned_coordinates_or_err().unwrap();
1626        assert_eq!(ns, "prod-app");
1627        assert_eq!(name, "api-gateway");
1628        // Ownership pin: type inference above binds ns/name as
1629        // owned Strings — a regression that returned &str would
1630        // fail to compile at the following .push() call. This
1631        // holds the "owned" half of the primitive's contract.
1632        let mut owned_ns = ns;
1633        owned_ns.push_str("-mutated");
1634        assert_eq!(owned_ns, "prod-app-mutated");
1635    }
1636
1637    #[test]
1638    fn owned_coordinates_or_err_falls_back_on_namespace_but_returns_owned_name() {
1639        // Namespace absent → DEFAULT_NAMESPACE. Name present → owned.
1640        let p = Process::new("api", empty_spec());
1641        // Process::new leaves metadata.namespace = None by default.
1642        let (ns, name) = p.owned_coordinates_or_err().unwrap();
1643        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
1644        assert_eq!(name, "api");
1645    }
1646
1647    #[test]
1648    fn owned_coordinates_or_err_errors_when_metadata_name_absent_regardless_of_namespace() {
1649        // Name absent → Err, REGARDLESS of whether the namespace is
1650        // populated. The name gate is strictly on `metadata.name` and
1651        // does NOT fall back to `Self::UNNAMED_PLACEHOLDER` (that
1652        // fallback is on the peer `coordinates_or_defaults`, which
1653        // exists precisely for consumers that can tolerate a
1654        // display placeholder).
1655        for ns_slot in [None, Some("prod".to_string())] {
1656            let mut p = Process::new("scratch", empty_spec());
1657            p.metadata.name = None;
1658            p.metadata.namespace = ns_slot.clone();
1659            let err = p.owned_coordinates_or_err().unwrap_err();
1660            assert!(
1661                err.to_string().contains("metadata.name"),
1662                "err on missing name (ns={ns_slot:?}) should mention metadata.name; got {err}"
1663            );
1664        }
1665    }
1666
1667    #[test]
1668    fn owned_coordinates_or_err_error_message_matches_pre_lift_reconciler_wording() {
1669        // Load-bearing wording pin — every pre-lift `tatara-reconciler`
1670        // helper (`phase_machine::namespace_and_name`,
1671        // `signals::ingest`, `signals::consume_effect`) errored with
1672        // EXACTLY this wording. Post-lift the substrate owner produces
1673        // the same wording so log-line / test greps that anchored on
1674        // it keep matching, and no operator-visible message drift
1675        // lands as a side effect of the substrate move.
1676        let mut p = Process::new("scratch", empty_spec());
1677        p.metadata.name = None;
1678        let err = p.owned_coordinates_or_err().unwrap_err();
1679        assert_eq!(err.to_string(), "Process has no metadata.name");
1680    }
1681
1682    #[test]
1683    fn owned_coordinates_or_err_namespace_fallback_matches_default_namespace_const() {
1684        // Byte-identity pin between the owned form's namespace
1685        // fallback and the workspace-wide `DEFAULT_NAMESPACE` const.
1686        // A regression that spelled this fallback as any other
1687        // string ("kube-system", "", "default-ns") would silently
1688        // misroute every downstream namespaced-Api call on a
1689        // Process without a metadata.namespace — surfaces here
1690        // rather than at every kube-rs API caller.
1691        let mut p = Process::new("api", empty_spec());
1692        p.metadata.namespace = None;
1693        let (ns, _) = p.owned_coordinates_or_err().unwrap();
1694        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
1695    }
1696
1697    #[test]
1698    fn owned_coordinates_or_err_matches_pre_lift_reconciler_helper_shape() {
1699        // Byte-identical parity pin between the owned + name-required
1700        // primitive here and the pre-lift `tatara-reconciler` helper
1701        // shape — the exact 2-slot unwrap chain each pre-lift caller
1702        // spelled by hand:
1703        //
1704        //   let ns = p.metadata.namespace.clone().unwrap_or_else(|| "default".into());
1705        //   let name = p.metadata.name.clone().ok_or_else(|| anyhow!(...))?;
1706        //   Ok((ns, name))
1707        //
1708        // Sweeps every corner every callsite plausibly encounters
1709        // (both slots present, namespace absent, name absent, both
1710        // absent). A regression that inserted a normalization step
1711        // at the primitive that the pre-lift chain does NOT apply —
1712        // or vice versa — surfaces here rather than as silent drift
1713        // between the 12 pre-lift consumer callsites and the ONE
1714        // substrate owner they now route through.
1715        fn pre_lift(p: &Process) -> anyhow::Result<(String, String)> {
1716            let ns = p
1717                .metadata
1718                .namespace
1719                .clone()
1720                .unwrap_or_else(|| "default".into());
1721            let name = p
1722                .metadata
1723                .name
1724                .clone()
1725                .ok_or_else(|| anyhow::anyhow!("Process has no metadata.name"))?;
1726            Ok((ns, name))
1727        }
1728        // Both present.
1729        let mut p = Process::new("api", empty_spec());
1730        p.metadata.namespace = Some("prod".into());
1731        assert_eq!(p.owned_coordinates_or_err().unwrap(), pre_lift(&p).unwrap());
1732        // Namespace absent.
1733        let p = Process::new("api", empty_spec());
1734        assert_eq!(p.owned_coordinates_or_err().unwrap(), pre_lift(&p).unwrap());
1735        // Name absent → both variants error with the same wording.
1736        let mut p = Process::new("api", empty_spec());
1737        p.metadata.name = None;
1738        p.metadata.namespace = Some("prod".into());
1739        assert_eq!(
1740            p.owned_coordinates_or_err().unwrap_err().to_string(),
1741            pre_lift(&p).unwrap_err().to_string(),
1742        );
1743        // Both absent → still errors on the name gate.
1744        let mut p = Process::new("api", empty_spec());
1745        p.metadata.name = None;
1746        p.metadata.namespace = None;
1747        assert_eq!(
1748            p.owned_coordinates_or_err().unwrap_err().to_string(),
1749            pre_lift(&p).unwrap_err().to_string(),
1750        );
1751    }
1752
1753    #[test]
1754    fn owned_coordinates_or_err_axis_order_matches_coordinates_or_defaults() {
1755        // Cross-primitive coherence pin between the owned + name-
1756        // required form and the borrow + name-defaulted peer:
1757        // (namespace, name) axis order is IDENTICAL across both
1758        // return-forms. A regression that swapped the tuple slots on
1759        // only ONE of the two primitives would silently misroute
1760        // every consumer that picked between the two forms based on
1761        // its callsite's ownership needs. The pin re-reads both
1762        // primitives at test time so the equality holds iff both
1763        // live paths are the current implementation.
1764        let mut p = Process::new("app", empty_spec());
1765        p.metadata.namespace = Some("infra".into());
1766        let (borrow_ns, borrow_name) = p.coordinates_or_defaults();
1767        let (owned_ns, owned_name) = p.owned_coordinates_or_err().unwrap();
1768        assert_eq!(owned_ns, borrow_ns);
1769        assert_eq!(owned_name, borrow_name);
1770        // Explicit slot labels — pins the (namespace, name) axis
1771        // order as opposed to (name, namespace).
1772        assert_eq!(owned_ns, "infra"); // NOT "app"
1773        assert_eq!(owned_name, "app"); // NOT "infra"
1774    }
1775
1776    // ─── Process::coordinates_or_none substrate pins ──────────────────
1777    //
1778    // Pins the borrow + name-required peer of the coordinate-primitive
1779    // family on the (return-form × name-gate) axis pair. Closes the
1780    // corner previously left open (borrow + name-required) so the
1781    // three consumer shapes (child-Process delete-fan-out at
1782    // `phase_machine::handle_exiting`, claim-arbiter probe at
1783    // `phase_machine::process_holds_any_claim`, any future non-fatal
1784    // skip site) route through ONE primitive rather than three hand-
1785    // authored empty-string / `unwrap_or_default()` sentinel chains.
1786    // Fail-before-pass-after granularity: a regression that flipped
1787    // the namespace fallback, swapped the return-tuple axis order,
1788    // returned an owned form, or promoted a missing name to an error
1789    // rather than `None` surfaces here rather than as silent drift at
1790    // every borrow + name-required consumer.
1791
1792    #[test]
1793    fn coordinates_or_none_returns_slices_when_both_slots_present() {
1794        // Happy path — both slots populated, method returns borrowed
1795        // (&str, &str) in (namespace, name) axis order wrapped in
1796        // `Some`.
1797        let mut p = Process::new("api-gateway", empty_spec());
1798        p.metadata.namespace = Some("prod-app".into());
1799        let (ns, name) = p.coordinates_or_none().expect("Some when name set");
1800        assert_eq!(ns, "prod-app");
1801        assert_eq!(name, "api-gateway");
1802    }
1803
1804    #[test]
1805    fn coordinates_or_none_falls_back_on_namespace_but_returns_name_slice() {
1806        // Namespace absent → DEFAULT_NAMESPACE (shared with the peer
1807        // `coordinates_or_defaults` + `namespace_or_default`). Name
1808        // present → the metadata slice, wrapped in `Some`.
1809        let mut p = Process::new("api", empty_spec());
1810        p.metadata.namespace = None;
1811        let (ns, name) = p.coordinates_or_none().expect("Some when name set");
1812        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
1813        assert_eq!(name, "api");
1814    }
1815
1816    #[test]
1817    fn coordinates_or_none_returns_none_when_metadata_name_absent_regardless_of_namespace() {
1818        // Name absent → `None`, REGARDLESS of whether the namespace
1819        // slot is populated. The name gate is strictly on
1820        // `metadata.name` and does NOT fall back to
1821        // `Self::UNNAMED_PLACEHOLDER` (that fallback is on the peer
1822        // `coordinates_or_defaults`, which exists precisely for
1823        // consumers that tolerate a display placeholder). Peer to
1824        // `owned_coordinates_or_err_errors_when_metadata_name_absent_regardless_of_namespace`
1825        // on the sibling primitive; a regression that widened THIS
1826        // form to substitute the placeholder while leaving the owned
1827        // form strict would silently drift the two borrow-form
1828        // primitives out of the coherence the family carries.
1829        for ns_slot in [None, Some("prod".to_string())] {
1830            let mut p = Process::new("scratch", empty_spec());
1831            p.metadata.name = None;
1832            p.metadata.namespace = ns_slot.clone();
1833            assert!(
1834                p.coordinates_or_none().is_none(),
1835                "coordinates_or_none must be None on missing name (ns={ns_slot:?})",
1836            );
1837        }
1838    }
1839
1840    #[test]
1841    fn coordinates_or_none_namespace_fallback_matches_default_namespace_const() {
1842        // Byte-identity pin between the borrow + name-required form's
1843        // namespace fallback and the workspace-wide `DEFAULT_NAMESPACE`
1844        // const. Sibling to
1845        // `owned_coordinates_or_err_namespace_fallback_matches_default_namespace_const`
1846        // on the peer primitive — the two forms MUST substitute the
1847        // same fallback string, else a consumer that switches between
1848        // them based on its ownership need silently observes a
1849        // different namespace-fallback shape as a side effect.
1850        let mut p = Process::new("api", empty_spec());
1851        p.metadata.namespace = None;
1852        let (ns, _) = p.coordinates_or_none().unwrap();
1853        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
1854    }
1855
1856    #[test]
1857    fn coordinates_or_none_axis_order_matches_coordinates_or_defaults_when_name_present() {
1858        // Cross-primitive coherence pin between the two borrow-form
1859        // primitives: when the name is present, the (namespace, name)
1860        // return-tuple axis order is IDENTICAL across the two forms,
1861        // and the returned slices are the SAME `&str` view onto the
1862        // same metadata slots. A regression that swapped the tuple
1863        // slots on ONE form would silently misroute every consumer
1864        // that picked between the two forms based on its name-gate
1865        // need. The pin re-reads both primitives at test time so the
1866        // equality holds iff both live paths are the current
1867        // implementation.
1868        let mut p = Process::new("app", empty_spec());
1869        p.metadata.namespace = Some("infra".into());
1870        let (defaulted_ns, defaulted_name) = p.coordinates_or_defaults();
1871        let (required_ns, required_name) = p.coordinates_or_none().unwrap();
1872        assert_eq!(defaulted_ns, required_ns);
1873        assert_eq!(defaulted_name, required_name);
1874        // Explicit slot labels — pins the (namespace, name) axis order
1875        // as opposed to (name, namespace).
1876        assert_eq!(required_ns, "infra"); // NOT "app"
1877        assert_eq!(required_name, "app"); // NOT "infra"
1878    }
1879
1880    #[test]
1881    fn coordinates_or_none_axis_pair_diverges_from_coordinates_or_defaults_on_missing_name() {
1882        // Divergence pin between the two borrow-form primitives when
1883        // the name gate fires: `coordinates_or_defaults` substitutes
1884        // the display placeholder AND still returns a tuple;
1885        // `coordinates_or_none` returns `None`. A regression that
1886        // collapsed the two behaviors (either by dropping the gate
1887        // from the required form or by adding a `None` corner to the
1888        // defaulted form) would blur the axis pair's whole reason to
1889        // exist as two peer primitives.
1890        let mut p = Process::new("scratch", empty_spec());
1891        p.metadata.name = None;
1892        p.metadata.namespace = Some("prod".into());
1893        // Defaulted form: substitutes placeholder, no gate.
1894        assert_eq!(
1895            p.coordinates_or_defaults(),
1896            ("prod", Process::UNNAMED_PLACEHOLDER)
1897        );
1898        // Required form: gate fires, `None`.
1899        assert!(p.coordinates_or_none().is_none());
1900    }
1901
1902    #[test]
1903    fn coordinates_or_none_matches_pre_lift_reconciler_helper_shape() {
1904        // Byte-identical parity pin between the borrow + name-required
1905        // primitive here and the pre-lift `tatara-reconciler` helper
1906        // shapes — the exact 2-slot unwrap + gate chains each pre-lift
1907        // caller spelled by hand (`phase_machine::process_holds_any_claim`
1908        // spelled it as `unwrap_or("")` + `is_empty` early-return;
1909        // `phase_machine::handle_exiting`'s child-fan-out spelled it
1910        // as `unwrap_or_default()` + implicit no-op delete on the
1911        // empty API-path). Sweeps every corner every callsite plausibly
1912        // encounters (both slots present, namespace absent, name
1913        // absent + ns present, both absent). A regression that
1914        // inserted a normalization step at the primitive the pre-lift
1915        // chain does NOT apply — or vice versa — surfaces here rather
1916        // than as silent drift between the pre-lift consumer sites
1917        // and the ONE substrate owner they now route through.
1918        fn pre_lift_holds_any_claim(p: &Process) -> Option<(&str, &str)> {
1919            let ns = p.metadata.namespace.as_deref().unwrap_or("default");
1920            let name = p.metadata.name.as_deref().unwrap_or("");
1921            if name.is_empty() {
1922                return None;
1923            }
1924            Some((ns, name))
1925        }
1926        // Both present.
1927        let mut p = Process::new("api", empty_spec());
1928        p.metadata.namespace = Some("prod".into());
1929        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
1930        // Namespace absent.
1931        let p = Process::new("api", empty_spec());
1932        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
1933        // Name absent → both variants return `None` regardless of ns.
1934        let mut p = Process::new("api", empty_spec());
1935        p.metadata.name = None;
1936        p.metadata.namespace = Some("prod".into());
1937        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
1938        // Both absent → still `None` on the name gate.
1939        let mut p = Process::new("api", empty_spec());
1940        p.metadata.name = None;
1941        p.metadata.namespace = None;
1942        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
1943    }
1944
1945    #[test]
1946    fn coordinates_or_none_axis_order_matches_owned_coordinates_or_err_on_happy_path() {
1947        // Cross-primitive coherence pin at the sibling corner: when
1948        // BOTH slots are present, the borrow + name-required form
1949        // (this method) and the owned + name-required peer
1950        // (`owned_coordinates_or_err`) return the SAME `(ns, name)`
1951        // pair — the axis order is IDENTICAL and neither primitive
1952        // silently applies a normalization the other omits. A
1953        // regression that skewed one form's normalization would
1954        // surface here rather than as silent drift between the two
1955        // name-required corners of the primitive family.
1956        let mut p = Process::new("app", empty_spec());
1957        p.metadata.namespace = Some("infra".into());
1958        let (borrow_ns, borrow_name) = p.coordinates_or_none().unwrap();
1959        let (owned_ns, owned_name) = p.owned_coordinates_or_err().unwrap();
1960        assert_eq!(borrow_ns, owned_ns.as_str());
1961        assert_eq!(borrow_name, owned_name.as_str());
1962    }
1963
1964    #[test]
1965    fn coordinates_or_defaults_axis_order_matches_qualified_process_ref() {
1966        // Pins the load-bearing convention that the return-tuple
1967        // axis order is (namespace, name) — the exact positional
1968        // argument order the substrate's paired-composer primitive
1969        // `tatara_reconciler::ssapply::qualified_process_ref(ns,
1970        // name)` consumes. A regression that swapped the tuple
1971        // slots would silently misroute every annotation writer /
1972        // claim-arbiter row / owner-metadata seed built by feeding
1973        // this pair into the composer — every downstream `<ns>/
1974        // <name>` grep would suddenly see `<name>/<ns>`. The test
1975        // verifies the tuple's first slot is what a hand-authored
1976        // `.metadata.namespace.as_deref()...` produced pre-lift, and
1977        // the second slot is what `.metadata.name.as_deref()...`
1978        // produced.
1979        let mut p = Process::new("app", empty_spec());
1980        p.metadata.namespace = Some("infra".into());
1981        let (ns, name) = p.coordinates_or_defaults();
1982        assert_eq!(ns, "infra"); // NOT "app"
1983        assert_eq!(name, "app"); // NOT "infra"
1984    }
1985
1986    // ─── Process::annotation substrate pins ────────────────────────────
1987    //
1988    // Pins the borrow-form annotation-lookup primitive that owns the
1989    // 3-line `.metadata.annotations.as_ref().and_then(|m| m.get(KEY))`
1990    // chain three hand-authored sites restated by hand pre-lift:
1991    // `tatara-reconciler::signals::ingest` (SIGNAL),
1992    // `tatara-reconciler::phase_machine::released_from_annotation`
1993    // (RELEASED_FROM), and
1994    // `tatara-pool-reconciler::controller_pool::process_belongs_to_pool`
1995    // (POOL). Fail-before-pass-after granularity: a regression that
1996    // widened the missing-`annotations` corner (returning `Some("")`
1997    // instead of `None`), promoted a missing key to an error, dropped
1998    // the borrow-form return, or changed the two swallowed corners'
1999    // shared collapse to `None` surfaces here rather than as silent
2000    // drift at the three consumer sites.
2001    fn process_with_annotation(key: &str, value: &str) -> Process {
2002        let mut p = Process::new("some-proc", empty_spec());
2003        let mut anns = std::collections::BTreeMap::new();
2004        anns.insert(key.to_string(), value.to_string());
2005        p.metadata.annotations = Some(anns);
2006        p
2007    }
2008
2009    #[test]
2010    fn annotation_returns_none_when_metadata_annotations_is_none() {
2011        // Missing-`annotations` corner: a Process with no annotations
2012        // block at all returns `None` for every key. Peer to
2013        // `observed_flux_resources_returns_empty_slice_when_status_is_none`
2014        // on the status-projection axis; both primitives collapse the
2015        // outer `Option` corner rather than requiring each consumer
2016        // to spell the guard by hand.
2017        let mut p = Process::new("scratch", empty_spec());
2018        p.metadata.annotations = None;
2019        assert!(p.annotation("tatara.pleme.io/signal").is_none());
2020        assert!(p.annotation("tatara.pleme.io/pool").is_none());
2021        assert!(p.annotation("").is_none());
2022    }
2023
2024    #[test]
2025    fn annotation_returns_none_when_key_absent_from_populated_map() {
2026        // Missing-key corner: annotations block populated with OTHER
2027        // keys returns `None` for the queried key. Symmetric with the
2028        // missing-`annotations` corner — both corners collapse to the
2029        // same `None`, matching the pre-lift `.and_then(...)`
2030        // behavior every consumer relied on.
2031        let p = process_with_annotation("tatara.pleme.io/other", "value");
2032        assert!(p.annotation("tatara.pleme.io/signal").is_none());
2033        assert!(p.annotation("").is_none());
2034    }
2035
2036    #[test]
2037    fn annotation_returns_borrowed_slice_when_key_present() {
2038        // Happy path: annotations block populated + key present →
2039        // `Some(&str)` borrowed from the underlying `String` in the
2040        // map. A regression that returned an owned `String` (defeating
2041        // the primitive's role as a zero-copy projection) would
2042        // surface at the lifetime of the returned reference — the
2043        // `&str` outlives the borrow of `&p` here.
2044        let p = process_with_annotation("tatara.pleme.io/signal", "SIGHUP");
2045        assert_eq!(p.annotation("tatara.pleme.io/signal"), Some("SIGHUP"));
2046    }
2047
2048    #[test]
2049    fn annotation_returns_borrowed_empty_string_slice_when_value_is_empty() {
2050        // Edge corner between the missing-key `None` and the present-
2051        // key `Some("")` — a Process whose annotation is EXPLICITLY
2052        // set to an empty string returns `Some("")`, NOT `None`. A
2053        // regression that normalized the empty-string value to `None`
2054        // (a plausible "defensive" simplification) would silently
2055        // reshape the corner every callsite pre-lift kept distinct via
2056        // `.cloned().unwrap_or_default()` (which collapses BOTH to
2057        // `""`) or `.map(String::as_str)` (which keeps them distinct
2058        // as `None` vs `Some("")`).
2059        let p = process_with_annotation("tatara.pleme.io/signal", "");
2060        assert_eq!(p.annotation("tatara.pleme.io/signal"), Some(""));
2061    }
2062
2063    #[test]
2064    fn annotation_is_a_pure_projection() {
2065        // Purity pin — repeated calls return equal results and the
2066        // primitive does not mutate `self`. Peer to
2067        // `observed_flux_resources_is_a_pure_projection` on the
2068        // status-projection axis.
2069        let p = process_with_annotation("tatara.pleme.io/released-from", "Attested");
2070        let a = p.annotation("tatara.pleme.io/released-from");
2071        let b = p.annotation("tatara.pleme.io/released-from");
2072        assert_eq!(a, b);
2073        assert_eq!(a, Some("Attested"));
2074    }
2075
2076    #[test]
2077    fn annotation_matches_pre_lift_reconciler_chain_shape() {
2078        // Byte-identical parity pin between the borrow-form primitive
2079        // here and the pre-lift `tatara-reconciler` / `tatara-pool-
2080        // reconciler` chain shape — the exact 3-line
2081        // `.metadata.annotations.as_ref().and_then(|m| m.get(KEY))
2082        // .map(String::as_str)` incantation each pre-lift caller
2083        // spelled by hand (three variants of tail collapsed onto ONE
2084        // borrow-form primitive here; each caller reapplies its own
2085        // tail at its own site). Sweeps every corner (missing
2086        // annotations map, missing key, present key with value,
2087        // present key with empty value) so a regression that inserted
2088        // a normalization at the primitive the pre-lift chain does
2089        // NOT apply — or vice versa — surfaces here rather than as
2090        // silent drift between the ONE substrate owner and the three
2091        // consumer sites.
2092        fn pre_lift<'a>(p: &'a Process, key: &str) -> Option<&'a str> {
2093            p.metadata
2094                .annotations
2095                .as_ref()
2096                .and_then(|m| m.get(key))
2097                .map(String::as_str)
2098        }
2099        // Missing annotations map.
2100        let mut p = Process::new("x", empty_spec());
2101        p.metadata.annotations = None;
2102        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
2103        // Missing key in populated map.
2104        let p = process_with_annotation("other", "v");
2105        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
2106        // Present key with non-empty value.
2107        let p = process_with_annotation("k", "v");
2108        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
2109        // Present key with explicitly-empty value — the corner
2110        // `.cloned().unwrap_or_default()` collapses to `""` post-tail
2111        // but the primitive-level shape stays `Some("")`.
2112        let p = process_with_annotation("k", "");
2113        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
2114    }
2115
2116    #[test]
2117    fn annotation_composes_owned_tail_matching_pre_lift_signals_ingest() {
2118        // Pins the exact tail shape `tatara-reconciler::signals::
2119        // ingest` composed pre-lift: an `Option<String>` for the
2120        // downstream `let Some(raw) = raw else { ... }` guard.
2121        // Post-lift the callsite composes `.map(str::to_string)` at
2122        // its own site; this test pins the composition matches the
2123        // pre-lift `.cloned()` tail byte-for-byte on both corners the
2124        // consumer's downstream distinguishes (annotation present →
2125        // `Some(String)`; absent → `None`).
2126        let p = process_with_annotation("tatara.pleme.io/signal", "SIGUSR1");
2127        assert_eq!(
2128            p.annotation("tatara.pleme.io/signal").map(str::to_string),
2129            Some("SIGUSR1".to_string())
2130        );
2131        let mut q = Process::new("y", empty_spec());
2132        q.metadata.annotations = None;
2133        assert_eq!(
2134            q.annotation("tatara.pleme.io/signal").map(str::to_string),
2135            None
2136        );
2137    }
2138
2139    #[test]
2140    fn annotation_composes_default_tail_matching_pre_lift_released_from() {
2141        // Pins the exact tail shape
2142        // `tatara-reconciler::phase_machine::released_from_annotation`
2143        // composed pre-lift: a bare `String` via `.cloned()
2144        // .unwrap_or_default()` for the downstream
2145        // `match v.as_str()` dispatch. Post-lift the callsite matches
2146        // directly on `Option<&str>` (Some("Failed") vs _); this test
2147        // pins that the borrow-form primitive plus the `.unwrap_or("")`
2148        // fallback reproduces the pre-lift bare-string shape on both
2149        // corners.
2150        let p = process_with_annotation("tatara.pleme.io/released-from", "Failed");
2151        assert_eq!(
2152            p.annotation("tatara.pleme.io/released-from").unwrap_or(""),
2153            "Failed"
2154        );
2155        let mut q = Process::new("y", empty_spec());
2156        q.metadata.annotations = None;
2157        assert_eq!(
2158            q.annotation("tatara.pleme.io/released-from").unwrap_or(""),
2159            ""
2160        );
2161    }
2162
2163    #[test]
2164    fn annotation_composes_borrow_equality_tail_matching_pre_lift_pool() {
2165        // Pins the exact tail shape `tatara-pool-reconciler::
2166        // controller_pool::process_belongs_to_pool` composed pre-lift:
2167        // an `Option<&str>` compared with `== Some(pool_name)` for the
2168        // membership gate. Post-lift the callsite composes
2169        // `p.annotation(POOL) == Some(pool_name)` verbatim; this test
2170        // pins that the borrow-form primitive returns exactly the
2171        // shape the equality gate expects.
2172        let p = process_with_annotation("tatara.pleme.io/pool", "demo-pool");
2173        assert_eq!(
2174            p.annotation("tatara.pleme.io/pool") == Some("demo-pool"),
2175            true
2176        );
2177        assert_eq!(p.annotation("tatara.pleme.io/pool") == Some("other"), false);
2178    }
2179
2180    // ─── Process::uid_or_empty substrate pins ──────────────────────────
2181    //
2182    // Pins the borrow-form metadata-projection primitive on the
2183    // `metadata.uid` axis that owns the `.metadata.uid.as_deref()
2184    // .unwrap_or("")` chain the two hand-authored
2185    // `tatara-reconciler::render` sites (`render_routing` +
2186    // `render_export_jobs`) restated by hand pre-lift. Peer to the
2187    // sibling `namespace_or_default_*` + `name_or_placeholder_*` pin
2188    // families on the metadata-slot × fallback-shape axis; all three
2189    // primitives return borrows of an owned-metadata slot with a slot-
2190    // specific fallback baked in (`"default"` for namespace, `"unnamed"`
2191    // for name, `""` for uid — the load-bearing gate value for
2192    // `owner_references_json`'s `is_empty` check). Fail-before-pass-
2193    // after granularity: `uid_or_empty` did not exist pre-lift, so any
2194    // test invoking it fails to compile pre-lift and passes post-lift.
2195
2196    #[test]
2197    fn uid_or_empty_returns_empty_string_when_metadata_uid_is_none() {
2198        // Empty-slot corner pin: the primitive collapses the no-uid
2199        // case to `""`, matching the pre-lift `.as_deref().unwrap_or("")`
2200        // chain's `""` byte-identically at both render consumer sites.
2201        // Semantically corresponds to a Process pre-metadata (fixtured
2202        // in tests, or caught mid-Forking before the API server has
2203        // stamped a `uid`); the downstream `owner_references_json`
2204        // composer gates on this exact `""` sentinel to stamp
2205        // `metadata.ownerReferences: []` rather than emit an owner-ref
2206        // pointing at a placeholder uid.
2207        let mut p = Process::new("scratch", empty_spec());
2208        p.metadata.uid = None;
2209        assert_eq!(p.uid_or_empty(), "");
2210    }
2211
2212    #[test]
2213    fn uid_or_empty_returns_borrowed_str_when_slot_is_populated() {
2214        // Happy-path pin: with a populated `metadata.uid` slot, the
2215        // primitive returns a borrowed `&str` whose contents match the
2216        // persisted `String`. A regression that reshaped / normalized
2217        // / cross-cluster-stripped the uid without touching this pin
2218        // would surface here rather than as silent skew at the two
2219        // `owner_references_json(name, uid)` emitters on the SAME
2220        // Process.
2221        let mut p = Process::new("owned-proc", empty_spec());
2222        p.metadata.uid = Some("uid-abc-123".into());
2223        assert_eq!(p.uid_or_empty(), "uid-abc-123");
2224    }
2225
2226    #[test]
2227    fn uid_or_empty_returns_empty_string_when_slot_is_explicitly_empty_string() {
2228        // Corner between the missing-slot `None` and the explicitly-
2229        // empty-string `Some("")` — both collapse to `""` at the
2230        // primitive because the downstream gate at
2231        // `owner_references_json` treats `.is_empty()` uniformly (the
2232        // empty-slot posture is what the whole primitive family
2233        // encodes: "no admissible owner reference, stamp `[]`"). A
2234        // regression that discriminated the two corners (returning a
2235        // sentinel `"<none>"` for the missing slot but `""` for the
2236        // explicit slot) would break the composition with
2237        // `owner_references_json` at the exactly-two-corner gate.
2238        let mut p = Process::new("owned-proc", empty_spec());
2239        p.metadata.uid = Some(String::new());
2240        assert_eq!(p.uid_or_empty(), "");
2241    }
2242
2243    #[test]
2244    fn uid_or_empty_is_a_zero_copy_borrow_projection() {
2245        // Borrow-discipline pin: the returned `&str` borrows the
2246        // persisted `String`'s underlying byte buffer in place — NOT
2247        // a fresh allocation or a clone. A regression that switched
2248        // the projection to an owned `String` (via `.clone()` or a
2249        // `format!` wrap) would defeat the zero-copy contract the
2250        // lift's primary strict-widening delivers, and would surface
2251        // here via pointer-identity comparison.
2252        let mut p = Process::new("owned-proc", empty_spec());
2253        p.metadata.uid = Some("uid-borrow-pin".into());
2254        let slice = p.uid_or_empty();
2255        assert!(std::ptr::eq(
2256            slice.as_ptr(),
2257            p.metadata.uid.as_ref().unwrap().as_ptr()
2258        ));
2259    }
2260
2261    #[test]
2262    fn uid_or_empty_is_a_pure_projection() {
2263        // Purity pin — repeated calls return byte-identical slices
2264        // (same pointer, same length). A regression that introduced
2265        // state (a lazy-cached normalized slot, a first-call
2266        // canonicalization pass) would surface here rather than as
2267        // silent drift between the two render consumer sites on the
2268        // SAME Process within one render pass.
2269        let mut p = Process::new("owned-proc", empty_spec());
2270        p.metadata.uid = Some("uid-pure".into());
2271        let a = p.uid_or_empty();
2272        let b = p.uid_or_empty();
2273        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
2274        assert_eq!(a.len(), b.len());
2275    }
2276
2277    #[test]
2278    fn uid_or_empty_matches_pre_lift_render_chain_shape() {
2279        // Byte-identical parity pin between the borrow-form primitive
2280        // here and the pre-lift `tatara-reconciler::render` chain shape
2281        // — the exact `.metadata.uid.as_deref().unwrap_or("")`
2282        // incantation both `render_routing` (line 514) and
2283        // `render_export_jobs` (line 653) spelled by hand pre-lift.
2284        // Sweeps every corner (missing uid slot, populated uid slot,
2285        // explicitly-empty uid slot) so a regression that inserted a
2286        // normalization the pre-lift chain does NOT apply — or vice
2287        // versa — surfaces here rather than as silent drift between
2288        // the ONE substrate owner and the two consumer sites.
2289        fn pre_lift(p: &Process) -> &str {
2290            p.metadata.uid.as_deref().unwrap_or("")
2291        }
2292        // Missing slot.
2293        let mut p = Process::new("x", empty_spec());
2294        p.metadata.uid = None;
2295        assert_eq!(p.uid_or_empty(), pre_lift(&p));
2296        // Populated slot.
2297        let mut p = Process::new("x", empty_spec());
2298        p.metadata.uid = Some("uid-42".into());
2299        assert_eq!(p.uid_or_empty(), pre_lift(&p));
2300        // Explicitly-empty slot.
2301        let mut p = Process::new("x", empty_spec());
2302        p.metadata.uid = Some(String::new());
2303        assert_eq!(p.uid_or_empty(), pre_lift(&p));
2304    }
2305
2306    #[test]
2307    fn uid_or_empty_composes_with_owner_references_json_empty_gate() {
2308        // Cross-primitive composition pin — the empty-string sentinel
2309        // this primitive returns for the missing-uid corner is EXACTLY
2310        // the sentinel the sibling substrate composer
2311        // `owner_references_json(name, uid)` gates on to stamp
2312        // `metadata.ownerReferences: []`. A regression that changed
2313        // the sentinel at either end (this primitive returning
2314        // `"<none>"`, `owner_references_json` gating on `uid == "0"`
2315        // instead of `uid.is_empty()`) would break the composition
2316        // and surface here rather than as an operator-observed
2317        // orphan resource after apply.
2318        let mut p = Process::new("x", empty_spec());
2319        p.metadata.uid = None;
2320        let refs = crate::owner_references_json("some-name", p.uid_or_empty());
2321        assert!(
2322            refs.is_empty(),
2323            "empty-uid corner must produce empty owner-refs array"
2324        );
2325
2326        p.metadata.uid = Some("real-uid".into());
2327        let refs = crate::owner_references_json("some-name", p.uid_or_empty());
2328        assert_eq!(
2329            refs.len(),
2330            1,
2331            "populated-uid corner must produce one owner-ref entry"
2332        );
2333    }
2334
2335    // ─── Process::declared_parent_pid substrate pins ─────────────────
2336    //
2337    // Pins the borrow-form spec-projection primitive on the declared
2338    // parent-PID axis that owns the `.spec.identity.parent.as_deref()`
2339    // chain the two hand-authored `tatara-reconciler::phase_machine`
2340    // sites (`handle_forking` ALLOCATE-PID composer + `handle_exiting`
2341    // SIGTERM-cascade child-fan-out filter) restated by hand pre-lift.
2342    // Peer to the sibling `observed_pid_*` pin family on the (spec-
2343    // declared × status-observed) axis pair; both compose the same
2344    // borrow-form `Option<&str>` return-shape skeleton on distinct
2345    // slots (`spec.identity.parent` vs. `status.pid`). Fail-before-
2346    // pass-after granularity: `declared_parent_pid` did not exist
2347    // pre-lift, so any test invoking it fails to compile pre-lift and
2348    // passes post-lift.
2349    fn process_with_declared_parent(parent: Option<&str>) -> Process {
2350        let mut spec = empty_spec();
2351        spec.identity.parent = parent.map(str::to_string);
2352        Process::new("child-proc", spec)
2353    }
2354
2355    #[test]
2356    fn declared_parent_pid_returns_none_when_slot_is_none() {
2357        // Empty-slot corner pin: the primitive collapses the no-
2358        // parent case to `None`, matching the pre-lift `.as_deref()`
2359        // chain's `None` byte-identically at both reconciler consumer
2360        // sites. Semantically corresponds to a Process authored at
2361        // cluster init (PID 1) with no upstream parent — the
2362        // ALLOCATE-PID composer feeds `None` into `pid::allocate_pid`
2363        // to signal "no prefix", and the SIGTERM cascade's filter
2364        // never matches such a Process because a child's declared
2365        // parent can never equal `Some(pid)` when the slot is `None`.
2366        let p = process_with_declared_parent(None);
2367        assert!(p.declared_parent_pid().is_none());
2368    }
2369
2370    #[test]
2371    fn declared_parent_pid_returns_borrowed_str_when_slot_is_populated() {
2372        // Happy-path pin: with a populated `spec.identity.parent`
2373        // slot, the primitive returns a borrowed `&str` whose
2374        // contents match the persisted `String`. A regression that
2375        // filtered / reshaped / canonicalized the string would
2376        // surface here rather than as silent skew at the child-fan-
2377        // out filter's `.declared_parent_pid() == Some(pid)`
2378        // equality check on the SAME parent-child pair.
2379        let p = process_with_declared_parent(Some("seph.1"));
2380        assert_eq!(p.declared_parent_pid(), Some("seph.1"));
2381    }
2382
2383    #[test]
2384    fn declared_parent_pid_is_a_zero_copy_borrow_projection() {
2385        // Borrow-discipline pin: the returned `&str` borrows the
2386        // persisted `String`'s underlying byte buffer in place —
2387        // NOT a fresh allocation or a clone. A regression that
2388        // switched the projection to an owned `String` (via
2389        // `.clone()` or `.to_owned()`) would defeat the zero-copy
2390        // contract the lift's primary strict-widening delivers.
2391        // The `handle_exiting` cascade filter runs per candidate
2392        // child across the cluster-wide Process list; a per-row
2393        // `String::clone` would allocate one heap block per non-
2394        // matching row, so the borrow-form primitive is load-
2395        // bearing for large clusters. Peer to the sibling
2396        // `observed_pid_is_a_zero_copy_borrow_projection` pin on
2397        // the status-observed side of the axis pair.
2398        let p = process_with_declared_parent(Some("seph.1"));
2399        let borrowed = p.declared_parent_pid().expect("populated slot");
2400        let persisted = p.spec.identity.parent.as_ref().unwrap();
2401        assert!(std::ptr::eq(borrowed.as_ptr(), persisted.as_ptr()));
2402    }
2403
2404    #[test]
2405    fn declared_parent_pid_is_a_pure_projection() {
2406        // Purity pin: calling the projection twice on the same
2407        // `Process` returns byte-identical `&str`s (same pointer,
2408        // same length). A regression that introduced state — a
2409        // lazy-cached slice materialized on first call, a
2410        // normalization step that ran once and cached — would
2411        // surface here rather than as silent drift between the
2412        // ALLOCATE-PID composer and the SIGTERM cascade's child-
2413        // fan-out filter within one reconcile pass.
2414        let p = process_with_declared_parent(Some("seph.1.3"));
2415        let a = p.declared_parent_pid().expect("populated slot");
2416        let b = p.declared_parent_pid().expect("populated slot");
2417        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
2418        assert_eq!(a.len(), b.len());
2419    }
2420
2421    #[test]
2422    fn declared_parent_pid_matches_pre_lift_reconciler_chain_shape() {
2423        // Byte-identical parity pin between the borrow-form primitive
2424        // here and the pre-lift `tatara-reconciler::phase_machine`
2425        // `.spec.identity.parent.as_deref()` chain shape. Sweeps
2426        // every corner every callsite plausibly encounters (empty
2427        // slot, populated with a hierarchical PID). A regression
2428        // that inserted a normalization step at the primitive the
2429        // pre-lift chain does NOT apply — or vice versa — surfaces
2430        // here rather than as silent drift between the pre-lift
2431        // consumer sites and the ONE substrate owner they now route
2432        // through. Peer to
2433        // `observed_pid_matches_pre_lift_reconciler_chain_shape` on
2434        // the sibling axis's borrow-form primitive.
2435        fn pre_lift(p: &Process) -> Option<&str> {
2436            p.spec.identity.parent.as_deref()
2437        }
2438        // Empty slot.
2439        let p = process_with_declared_parent(None);
2440        assert_eq!(p.declared_parent_pid(), pre_lift(&p));
2441        // Populated with a hierarchical PID.
2442        let p = process_with_declared_parent(Some("seph.1"));
2443        assert_eq!(p.declared_parent_pid(), pre_lift(&p));
2444        // Populated with a deeper hierarchical PID.
2445        let p = process_with_declared_parent(Some("seph.1.7.42"));
2446        assert_eq!(p.declared_parent_pid(), pre_lift(&p));
2447    }
2448
2449    #[test]
2450    fn declared_parent_pid_preserves_hierarchical_pid_format() {
2451        // Format-preservation pin: the hierarchical PID path
2452        // (dotted-segment form `seph.1.7`, matching the ported
2453        // `convergence-controller/src/identity.rs` scheme) reaches
2454        // the caller with segments and separators byte-identical
2455        // to the persisted `String`. A regression that inserted a
2456        // canonicalization pass (a segment-count validator, a
2457        // separator swap `.` → `/`, a leading/trailing whitespace
2458        // trim) would silently misroute the SIGTERM cascade's
2459        // `declared_parent_pid() == Some(pid)` comparator against
2460        // children whose `parent` field was authored in the ported
2461        // scheme's exact form — the SAME children the observed_pid
2462        // primitive is pinned to match on the other side of the
2463        // axis pair.
2464        for parent in ["seph", "seph.1", "seph.1.7", "seph.1.7.42"] {
2465            let p = process_with_declared_parent(Some(parent));
2466            assert_eq!(p.declared_parent_pid(), Some(parent));
2467        }
2468    }
2469
2470    #[test]
2471    fn declared_parent_pid_composes_with_observed_pid_for_child_fanout_filter() {
2472        // Cross-axis coherence pin against the sibling
2473        // [`Self::observed_pid`] on the (spec-declared × status-
2474        // observed) axis pair: a child's `.declared_parent_pid()`
2475        // and its parent's `.observed_pid()` compose through the
2476        // SAME borrow-form `Option<&str>` skeleton so the
2477        // `handle_exiting` cascade filter's equality gate holds
2478        // structurally. A regression that skewed EITHER primitive's
2479        // return-form (return-shape, borrow discipline, empty-slot
2480        // collapse) would silently misroute every SIGTERM cascade
2481        // on the parent-child pair. This pin re-reads both primitives
2482        // at test time so the composition holds iff both live paths
2483        // are the current implementation.
2484        // Parent Process: has an observed PID.
2485        let mut parent = Process::new("parent-proc", empty_spec());
2486        parent.status = Some(ProcessStatus {
2487            pid: Some("seph.1".to_string()),
2488            ..Default::default()
2489        });
2490        // Child Process: declared parent matches parent's observed PID.
2491        let child = process_with_declared_parent(Some("seph.1"));
2492        // The `handle_exiting` filter's equality gate:
2493        // `child.declared_parent_pid() == Some(parent.observed_pid()?)`.
2494        let parent_pid = parent.observed_pid().expect("parent has PID");
2495        assert_eq!(child.declared_parent_pid(), Some(parent_pid));
2496        // Sibling Process with an unrelated declared parent must NOT
2497        // match the same parent — pins that the filter's SKIP branch
2498        // holds on the other side of the axis pair.
2499        let sibling = process_with_declared_parent(Some("seph.2"));
2500        assert_ne!(sibling.declared_parent_pid(), Some(parent_pid));
2501    }
2502
2503    // ─── Process::declared_name_override substrate pins ──────────────
2504    //
2505    // Pins the borrow-form spec-projection primitive on the declared
2506    // name-override sub-axis of the declared-identity axis that owns
2507    // the `.spec.identity.name_override.as_deref()` chain the two
2508    // hand-authored `tatara-reconciler::phase_machine` sites
2509    // (`handle_pending` DECLARE composer + `handle_forking` ALLOCATE-
2510    // PID rehydration branch) restated by hand pre-lift. Peer to the
2511    // sibling `declared_parent_pid_*` pin family on the (parent ×
2512    // name-override) sub-axis pair; both compose the same borrow-form
2513    // `Option<&str>` return-shape skeleton on distinct slots
2514    // (`spec.identity.name_override` vs `spec.identity.parent`).
2515    // Fail-before-pass-after granularity: `declared_name_override`
2516    // did not exist pre-lift, so any test invoking it fails to
2517    // compile pre-lift and passes post-lift.
2518    fn process_with_declared_name_override(name_override: Option<&str>) -> Process {
2519        let mut spec = empty_spec();
2520        spec.identity.name_override = name_override.map(str::to_string);
2521        Process::new("some-proc", spec)
2522    }
2523
2524    #[test]
2525    fn declared_name_override_returns_none_when_slot_is_none() {
2526        // Empty-slot corner pin: the primitive collapses the no-
2527        // override case to `None`, matching the pre-lift `.as_deref()`
2528        // chain's `None` byte-identically at both reconciler consumer
2529        // sites. Semantically corresponds to a Process authored
2530        // WITHOUT the human-name-override escape hatch — the default;
2531        // `derive_identity` then computes the name from the content
2532        // hash and stamps `name_override: false` on the resulting
2533        // [`Identity`].
2534        let p = process_with_declared_name_override(None);
2535        assert!(p.declared_name_override().is_none());
2536    }
2537
2538    #[test]
2539    fn declared_name_override_returns_borrowed_str_when_slot_is_populated() {
2540        // Happy-path pin: with a populated `spec.identity
2541        // .name_override` slot, the primitive returns a borrowed
2542        // `&str` whose contents match the persisted `String`. A
2543        // regression that filtered / reshaped / canonicalized the
2544        // string at the primitive (as opposed to inside
2545        // `derive_identity`, where the trim/empty-filter lives today)
2546        // would surface here rather than as silent skew between the
2547        // DECLARE composer and the ALLOCATE-PID rehydration branch on
2548        // the SAME Process spec.
2549        let p = process_with_declared_name_override(Some("observability-stack"));
2550        assert_eq!(p.declared_name_override(), Some("observability-stack"));
2551    }
2552
2553    #[test]
2554    fn declared_name_override_is_a_zero_copy_borrow_projection() {
2555        // Borrow-discipline pin: the returned `&str` borrows the
2556        // persisted `String`'s underlying byte buffer in place —
2557        // NOT a fresh allocation or a clone. Peer to the sibling
2558        // `declared_parent_pid_is_a_zero_copy_borrow_projection` pin
2559        // on the other side of the (parent × name-override) sub-axis
2560        // pair; the borrow discipline holds structurally on BOTH
2561        // sub-axes so a future `declared_identity` composite that
2562        // returns both halves together can compose them without
2563        // dropping into an owning form.
2564        let p = process_with_declared_name_override(Some("observability-stack"));
2565        let borrowed = p.declared_name_override().expect("populated slot");
2566        let persisted = p.spec.identity.name_override.as_ref().unwrap();
2567        assert!(std::ptr::eq(borrowed.as_ptr(), persisted.as_ptr()));
2568    }
2569
2570    #[test]
2571    fn declared_name_override_is_a_pure_projection() {
2572        // Purity pin: calling the projection twice on the same
2573        // `Process` returns byte-identical `&str`s (same pointer,
2574        // same length). A regression that introduced state — a
2575        // lazy-cached slice materialized on first call, a
2576        // normalization step that ran once and cached — would
2577        // surface here rather than as silent drift between the
2578        // DECLARE composer and the ALLOCATE-PID rehydration branch
2579        // within one reconcile pass.
2580        let p = process_with_declared_name_override(Some("gateway-primary"));
2581        let a = p.declared_name_override().expect("populated slot");
2582        let b = p.declared_name_override().expect("populated slot");
2583        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
2584        assert_eq!(a.len(), b.len());
2585    }
2586
2587    #[test]
2588    fn declared_name_override_matches_pre_lift_reconciler_chain_shape() {
2589        // Byte-identical parity pin between the borrow-form primitive
2590        // here and the pre-lift `tatara-reconciler::phase_machine`
2591        // `.spec.identity.name_override.as_deref()` chain shape.
2592        // Sweeps every corner every callsite plausibly encounters
2593        // (empty slot, populated with a bare name, populated with a
2594        // whitespace-containing name that `derive_identity`'s
2595        // internal trim would collapse, populated with an explicitly
2596        // empty string that `derive_identity`'s internal
2597        // `!s.is_empty()` filter would reject). A regression that
2598        // inserted a normalization step at the primitive the pre-
2599        // lift chain does NOT apply — or vice versa — surfaces here
2600        // rather than as silent drift between the pre-lift consumer
2601        // sites and the ONE substrate owner they now route through.
2602        // Peer to
2603        // `declared_parent_pid_matches_pre_lift_reconciler_chain_shape`
2604        // on the sibling sub-axis's borrow-form primitive.
2605        fn pre_lift(p: &Process) -> Option<&str> {
2606            p.spec.identity.name_override.as_deref()
2607        }
2608        // Empty slot.
2609        let p = process_with_declared_name_override(None);
2610        assert_eq!(p.declared_name_override(), pre_lift(&p));
2611        // Populated with a bare name.
2612        let p = process_with_declared_name_override(Some("observability-stack"));
2613        assert_eq!(p.declared_name_override(), pre_lift(&p));
2614        // Populated with a whitespace-containing name.
2615        let p = process_with_declared_name_override(Some("  observability-stack  "));
2616        assert_eq!(p.declared_name_override(), pre_lift(&p));
2617        // Populated with an explicitly empty string. Distinct from
2618        // the missing-slot `None` corner both at the primitive here
2619        // and at the pre-lift chain (the trim/filter that collapses
2620        // these two into the same `false`-branched
2621        // `Identity { name_override: false, .. }` lives INSIDE
2622        // `derive_identity`, NOT at the borrow site) — the primitive
2623        // MUST preserve the distinction so a future lift of the trim/
2624        // filter OUT of `derive_identity` INTO the primitive is a
2625        // conscious substrate change, not a silent one.
2626        let p = process_with_declared_name_override(Some(""));
2627        assert_eq!(p.declared_name_override(), pre_lift(&p));
2628    }
2629
2630    #[test]
2631    fn declared_name_override_preserves_raw_slot_verbatim() {
2632        // Invariance-under-`derive_identity`-normalization pin: the
2633        // primitive returns the slot's raw byte contents verbatim —
2634        // no trim, no empty-string filter, no case fold, no
2635        // normalization of any kind. `derive_identity` internally
2636        // applies `.map(str::trim).filter(|s| !s.is_empty())` before
2637        // dispatching on `Some(non_empty)` vs `None | Some(empty |
2638        // whitespace)`, but that transform lives IN `derive_identity`,
2639        // NOT at the borrow site. A regression that pulled the trim/
2640        // filter forward INTO the primitive would silently collapse
2641        // three currently-distinct corners at the borrow site (bare
2642        // populated → `Some(name)`; whitespace-only → `Some("   ")`;
2643        // empty → `Some("")`) into two (bare → `Some(name)`; the
2644        // other two → `None`). That collapse might be an intentional
2645        // substrate change some future run wants to make; if so, it
2646        // lands as a conscious edit here (with this pin updated in
2647        // the same commit) rather than as silent behavior drift.
2648        for value in ["bare", "  padded  ", "\ttabs\t", "   ", ""] {
2649            let p = process_with_declared_name_override(Some(value));
2650            assert_eq!(
2651                p.declared_name_override(),
2652                Some(value),
2653                "declared_name_override must preserve raw slot verbatim for value {value:?}"
2654            );
2655        }
2656    }
2657
2658    #[test]
2659    fn declared_name_override_composes_with_derive_identity_call_shape() {
2660        // Cross-primitive coherence pin against the [`derive_identity`]
2661        // consumer: the two live `tatara-reconciler::phase_machine`
2662        // callsites feed `p.declared_name_override()` as the second
2663        // positional argument to `derive_identity(&p.spec, …)`. This
2664        // pin exercises that exact call shape at test time so a
2665        // regression that skewed the primitive's return-form (return-
2666        // shape, borrow discipline, empty-slot collapse) surfaces
2667        // here as a shape mismatch at the [`derive_identity`] call
2668        // site rather than as silent operator-facing skew between the
2669        // DECLARE composer and the ALLOCATE-PID rehydration branch.
2670        // Populated with a bare non-empty name: `derive_identity`
2671        // dispatches on `Some(non_empty)` and stamps
2672        // `name_override: true` on the resulting [`Identity`], with
2673        // the resulting `.name` equal to the raw slot value.
2674        let p = process_with_declared_name_override(Some("gateway-primary"));
2675        let id = crate::identity::derive_identity(&p.spec, p.declared_name_override());
2676        assert!(id.name_override);
2677        assert_eq!(id.name, "gateway-primary");
2678        // Empty slot: `derive_identity` dispatches on `None` and
2679        // stamps `name_override: false` on the resulting [`Identity`],
2680        // with the resulting `.name` derived from the content hash
2681        // (NOT equal to any operator-authored slot value).
2682        let p = process_with_declared_name_override(None);
2683        let id = crate::identity::derive_identity(&p.spec, p.declared_name_override());
2684        assert!(!id.name_override);
2685    }
2686
2687    // ─── Process::observed_flux_resources substrate pins ───────────────
2688    //
2689    // Pins the borrow-form status-projection primitive that owns the
2690    // 5-line `.status.as_ref().map(|s| s.flux_resources.clone())
2691    // .unwrap_or_default()` chain the two hand-authored
2692    // `tatara-reconciler::phase_machine` sites (`handle_running` +
2693    // `handle_attested`) restated by hand pre-lift. Fail-before-pass-
2694    // after granularity: a regression that widened the missing-`status`
2695    // corner, dropped the slot, or drifted the borrow discipline
2696    // surfaces here rather than as silent operator-facing skew between
2697    // the VERIFY-phase readiness probe and the ATTEST-heartbeat drift
2698    // detector.
2699
2700    fn sample_flux_ref(name: &str) -> FluxResourceRef {
2701        // Distinct slot values so a swap between adjacent tuple
2702        // positions surfaces as an equality failure at the assertion
2703        // site — a slot-inversion regression cannot masquerade as
2704        // identity by accident. Peer to the sibling
2705        // `tatara_process::status::tests::sample_flux_ref` discipline
2706        // on the fetch-coords axis.
2707        FluxResourceRef {
2708            api_version: "kustomize.toolkit.fluxcd.io/v1".to_string(),
2709            kind: "Kustomization".to_string(),
2710            name: name.to_string(),
2711            namespace: "flux-system".to_string(),
2712            ready: false,
2713            message: None,
2714            last_check: None,
2715        }
2716    }
2717
2718    fn process_with_flux_resources(refs: Vec<FluxResourceRef>) -> Process {
2719        let mut p = Process::new("api-gateway", empty_spec());
2720        p.metadata.namespace = Some("prod".into());
2721        let mut status = ProcessStatus::default();
2722        status.flux_resources = refs;
2723        p.status = Some(status);
2724        p
2725    }
2726
2727    #[test]
2728    fn observed_flux_resources_returns_empty_slice_when_status_is_none() {
2729        // Missing-`status` corner pin: the primitive collapses the
2730        // no-status case to `&[]` so downstream `.is_empty()` /
2731        // `.len()` / iteration behave identically on a `Process`
2732        // whose status field is `None` and on one whose status
2733        // carries an empty `flux_resources` slot. Matches the
2734        // pre-lift `.unwrap_or_default()`'s empty-`Vec` corner
2735        // byte-identically at every reconciler consumer's downstream
2736        // shape.
2737        let mut p = Process::new("api", empty_spec());
2738        p.status = None;
2739        assert!(p.observed_flux_resources().is_empty());
2740        assert_eq!(p.observed_flux_resources().len(), 0);
2741    }
2742
2743    #[test]
2744    fn observed_flux_resources_returns_empty_slice_when_flux_resources_is_empty() {
2745        // Zero-refs-under-populated-status corner pin: the primitive
2746        // returns an empty slice, matching the missing-`status`
2747        // corner byte-identically. A regression that treated the two
2748        // corners differently (a `None`-vs-empty signal that
2749        // downstream consumers could grep on) would silently promote
2750        // an internal representation detail (whether the reconciler
2751        // has ever written a status subresource) into observable
2752        // behavior.
2753        let p = process_with_flux_resources(vec![]);
2754        assert!(p.observed_flux_resources().is_empty());
2755        assert_eq!(p.observed_flux_resources().len(), 0);
2756    }
2757
2758    #[test]
2759    fn observed_flux_resources_returns_slice_of_persisted_vec() {
2760        // Happy-path pin: with a populated `status.flux_resources`
2761        // slot, the primitive returns a borrowed slice whose length
2762        // and per-element identity match the persisted vector. A
2763        // regression that filtered / reshaped / deduplicated the
2764        // slice would surface here rather than as silent skew at the
2765        // downstream fetch consumers.
2766        let refs = vec![
2767            sample_flux_ref("observability-stack"),
2768            sample_flux_ref("gateway"),
2769        ];
2770        let p = process_with_flux_resources(refs.clone());
2771        let observed = p.observed_flux_resources();
2772        assert_eq!(observed.len(), 2);
2773        assert_eq!(observed[0].name, "observability-stack");
2774        assert_eq!(observed[1].name, "gateway");
2775    }
2776
2777    #[test]
2778    fn observed_flux_resources_is_a_zero_copy_borrow_projection() {
2779        // Borrow-discipline pin: the returned slice borrows the
2780        // persisted `Vec<FluxResourceRef>` in place — NOT a fresh
2781        // allocation or a clone. A regression that switched the
2782        // projection to owned refs (via `.clone()` or `.to_vec()`)
2783        // would defeat the zero-copy contract the lift's primary
2784        // strict-widening delivers (the pre-lift 5-line chain
2785        // eagerly cloned the whole vector per reconcile pass; the
2786        // post-lift primitive borrows). Peer to the sibling
2787        // `flux_resource_ref_fetch_coords_returns_borrows_of_owned_slots`
2788        // pin on the per-ref borrow-projection axis.
2789        let refs = vec![sample_flux_ref("observability-stack")];
2790        let p = process_with_flux_resources(refs);
2791        let observed = p.observed_flux_resources();
2792        let persisted = &p.status.as_ref().unwrap().flux_resources;
2793        assert!(std::ptr::eq(observed.as_ptr(), persisted.as_ptr()));
2794    }
2795
2796    #[test]
2797    fn observed_flux_resources_is_a_pure_projection() {
2798        // Purity pin: calling the projection twice on the same
2799        // `Process` returns byte-identical slices (same pointer,
2800        // same length). A regression that introduced state — a
2801        // lazy-cached slice materialized on first call, a
2802        // normalization step that ran once and cached — would
2803        // surface here rather than as silent drift between the
2804        // VERIFY-phase and ATTEST-heartbeat consumers on the SAME
2805        // `Process` within one reconcile pass.
2806        let refs = vec![sample_flux_ref("observability-stack")];
2807        let p = process_with_flux_resources(refs);
2808        let a = p.observed_flux_resources();
2809        let b = p.observed_flux_resources();
2810        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
2811        assert_eq!(a.len(), b.len());
2812    }
2813
2814    #[test]
2815    fn observed_flux_resources_matches_pre_lift_reconciler_chain_shape() {
2816        // Byte-identical parity pin between the borrow-form primitive
2817        // here and the pre-lift `tatara-reconciler::phase_machine`
2818        // 5-line chain shape. Sweeps every corner every callsite
2819        // plausibly encounters (missing status, empty flux_resources,
2820        // populated flux_resources with one ref, populated with
2821        // multiple refs). A regression that inserted a normalization
2822        // step at the primitive the pre-lift chain does NOT apply —
2823        // or vice versa — surfaces here rather than as silent drift
2824        // between the pre-lift consumer sites and the ONE substrate
2825        // owner they now route through. Peer to
2826        // `coordinates_or_none_matches_pre_lift_reconciler_helper_shape`
2827        // on the metadata axis's borrow-form primitive.
2828        // `FluxResourceRef` does not derive `PartialEq` — the parity
2829        // check walks the per-ref fetch-coords tuple (the same 4-slot
2830        // borrow projection every downstream fetch consumer routes
2831        // through) so a regression that reshaped ANY slot at ANY
2832        // index surfaces here through the sibling
2833        // `FluxResourceRef::fetch_coords` typed projection.
2834        fn pre_lift(p: &Process) -> Vec<FluxResourceRef> {
2835            p.status
2836                .as_ref()
2837                .map(|s| s.flux_resources.clone())
2838                .unwrap_or_default()
2839        }
2840        fn coord_shape(refs: &[FluxResourceRef]) -> Vec<(String, String, String, String)> {
2841            refs.iter()
2842                .map(|r| {
2843                    let (ns, av, kind, name) = r.fetch_coords();
2844                    (
2845                        ns.to_string(),
2846                        av.to_string(),
2847                        kind.to_string(),
2848                        name.to_string(),
2849                    )
2850                })
2851                .collect()
2852        }
2853        // Missing status.
2854        let mut p = Process::new("api", empty_spec());
2855        p.status = None;
2856        assert_eq!(
2857            coord_shape(p.observed_flux_resources()),
2858            coord_shape(&pre_lift(&p))
2859        );
2860        // Populated status, empty slot.
2861        let p = process_with_flux_resources(vec![]);
2862        assert_eq!(
2863            coord_shape(p.observed_flux_resources()),
2864            coord_shape(&pre_lift(&p))
2865        );
2866        // Populated status, one ref.
2867        let p = process_with_flux_resources(vec![sample_flux_ref("obs")]);
2868        assert_eq!(
2869            coord_shape(p.observed_flux_resources()),
2870            coord_shape(&pre_lift(&p))
2871        );
2872        // Populated status, multiple refs.
2873        let p = process_with_flux_resources(vec![
2874            sample_flux_ref("obs"),
2875            sample_flux_ref("gw"),
2876            sample_flux_ref("api"),
2877        ]);
2878        assert_eq!(
2879            coord_shape(p.observed_flux_resources()),
2880            coord_shape(&pre_lift(&p))
2881        );
2882    }
2883
2884    #[test]
2885    fn observed_flux_resources_missing_status_and_empty_slot_collapse_to_the_same_slice_shape() {
2886        // Cross-corner coherence pin: the missing-`status` corner and
2887        // the populated-empty-slot corner return slices whose
2888        // `.is_empty()` / `.len()` observations are IDENTICAL. A
2889        // regression that promoted the missing-`status` corner to
2890        // returning `None` (via a signature change) — or that widened
2891        // the empty-slot corner to a synthetic single-element slice
2892        // — would surface here rather than as silent operator-facing
2893        // divergence between a never-status-written Process and a
2894        // status-emptied Process.
2895        let mut p_no_status = Process::new("api", empty_spec());
2896        p_no_status.status = None;
2897        let p_empty_status = process_with_flux_resources(vec![]);
2898        assert_eq!(
2899            p_no_status.observed_flux_resources().len(),
2900            p_empty_status.observed_flux_resources().len()
2901        );
2902        assert_eq!(
2903            p_no_status.observed_flux_resources().is_empty(),
2904            p_empty_status.observed_flux_resources().is_empty()
2905        );
2906    }
2907
2908    #[test]
2909    fn observed_flux_resources_slice_preserves_persisted_ordering() {
2910        // Ordering-preservation pin: the borrowed slice preserves
2911        // the exact insertion order of the persisted vector — no
2912        // sort, no dedup, no reshape. A regression that inserted a
2913        // sort or reordering would silently misroute per-ref
2914        // observations at the downstream VERIFY-phase / ATTEST-
2915        // heartbeat consumers, both of which walk the slice
2916        // positionally and correlate the position to the observed
2917        // readiness.
2918        let refs = vec![
2919            sample_flux_ref("z-last"),
2920            sample_flux_ref("a-first"),
2921            sample_flux_ref("m-middle"),
2922        ];
2923        let p = process_with_flux_resources(refs);
2924        let observed = p.observed_flux_resources();
2925        assert_eq!(observed[0].name, "z-last");
2926        assert_eq!(observed[1].name, "a-first");
2927        assert_eq!(observed[2].name, "m-middle");
2928    }
2929
2930    // ─── Process::observed_pid substrate pins ─────────────────────────
2931    //
2932    // Pins the borrow-form status-projection primitive on the PID axis
2933    // that owns the 3-line `.status.as_ref().and_then(|s| s.pid.clone())`
2934    // chain the two hand-authored `tatara-reconciler::phase_machine`
2935    // sites (`handle_forking` ALLOCATE-PID gate + `handle_exiting`
2936    // SIGTERM cascade) restated by hand pre-lift. Peer to the sibling
2937    // `observed_flux_resources_*` pin family on the flux-resources
2938    // axis; both compose the missing-`status` fallback + borrow-form
2939    // return-shape skeleton on distinct `ProcessStatus` slots. Fail-
2940    // before-pass-after granularity: `observed_pid` did not exist
2941    // pre-lift, so any test invoking it fails to compile pre-lift and
2942    // passes post-lift.
2943
2944    fn process_with_pid(pid: Option<&str>) -> Process {
2945        let mut p = Process::new("api-gateway", empty_spec());
2946        p.metadata.namespace = Some("prod".into());
2947        let mut status = ProcessStatus::default();
2948        status.pid = pid.map(str::to_string);
2949        p.status = Some(status);
2950        p
2951    }
2952
2953    #[test]
2954    fn observed_pid_returns_none_when_status_is_none() {
2955        // Missing-`status` corner pin: the primitive collapses the
2956        // no-status case to `None` so downstream `.is_some()` /
2957        // `if let Some(_)` / `.map(...)` behave identically on a
2958        // `Process` whose status field is `None` and on one whose
2959        // status carries an unpopulated `pid` slot. Matches the
2960        // pre-lift `.and_then(...)` chain's `None` byte-identically
2961        // at every reconciler consumer's downstream shape.
2962        let mut p = Process::new("api", empty_spec());
2963        p.status = None;
2964        assert!(p.observed_pid().is_none());
2965    }
2966
2967    #[test]
2968    fn observed_pid_returns_none_when_pid_slot_is_none() {
2969        // Empty-slot-under-populated-status corner pin: the
2970        // primitive returns `None`, matching the missing-`status`
2971        // corner byte-identically. A regression that treated the
2972        // two corners differently (a `None`-vs-`Some("")` signal
2973        // that downstream consumers could grep on) would silently
2974        // promote an internal representation detail (whether the
2975        // reconciler has ever written a status subresource) into
2976        // observable behavior at the ALLOCATE-PID gate.
2977        let p = process_with_pid(None);
2978        assert!(p.observed_pid().is_none());
2979    }
2980
2981    #[test]
2982    fn observed_pid_returns_borrowed_str_when_pid_slot_is_populated() {
2983        // Happy-path pin: with a populated `status.pid` slot, the
2984        // primitive returns a borrowed `&str` whose contents match
2985        // the persisted `String`. A regression that filtered /
2986        // reshaped / canonicalized the string would surface here
2987        // rather than as silent skew at the downstream cascade
2988        // comparator's `.as_deref() == Some(...)` equality check.
2989        let p = process_with_pid(Some("seph.1.7"));
2990        assert_eq!(p.observed_pid(), Some("seph.1.7"));
2991    }
2992
2993    #[test]
2994    fn observed_pid_is_a_zero_copy_borrow_projection() {
2995        // Borrow-discipline pin: the returned `&str` borrows the
2996        // persisted `String`'s underlying byte buffer in place —
2997        // NOT a fresh allocation or a clone. A regression that
2998        // switched the projection to an owned `String` (via
2999        // `.clone()` or `.to_owned()`) would defeat the zero-copy
3000        // contract the lift's primary strict-widening delivers
3001        // (the pre-lift 3-line chain eagerly cloned the `String`
3002        // per reconcile pass at BOTH call sites even though the
3003        // ALLOCATE-PID gate immediately dropped the clone and the
3004        // SIGTERM cascade only re-borrowed it via `.as_str()`; the
3005        // post-lift primitive borrows). Peer to the sibling
3006        // `observed_flux_resources_is_a_zero_copy_borrow_projection`
3007        // pin on the flux-resources borrow-projection axis.
3008        let p = process_with_pid(Some("seph.1.7"));
3009        let observed = p.observed_pid().expect("populated slot");
3010        let persisted = p.status.as_ref().unwrap().pid.as_ref().unwrap();
3011        assert!(std::ptr::eq(observed.as_ptr(), persisted.as_ptr()));
3012    }
3013
3014    #[test]
3015    fn observed_pid_is_a_pure_projection() {
3016        // Purity pin: calling the projection twice on the same
3017        // `Process` returns byte-identical `&str`s (same pointer,
3018        // same length). A regression that introduced state — a
3019        // lazy-cached slice materialized on first call, a
3020        // normalization step that ran once and cached — would
3021        // surface here rather than as silent drift between the
3022        // ALLOCATE-PID gate and the SIGTERM cascade on the SAME
3023        // `Process` within one reconcile pass.
3024        let p = process_with_pid(Some("seph.1.7"));
3025        let a = p.observed_pid().expect("populated slot");
3026        let b = p.observed_pid().expect("populated slot");
3027        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
3028        assert_eq!(a.len(), b.len());
3029    }
3030
3031    #[test]
3032    fn observed_pid_matches_pre_lift_reconciler_chain_shape() {
3033        // Byte-identical parity pin between the borrow-form
3034        // primitive here and the pre-lift `tatara-reconciler
3035        // ::phase_machine` 3-line chain shape. Sweeps every corner
3036        // every callsite plausibly encounters (missing status,
3037        // empty pid slot, populated pid slot). A regression that
3038        // inserted a normalization step at the primitive the pre-
3039        // lift chain does NOT apply — or vice versa — surfaces
3040        // here rather than as silent drift between the pre-lift
3041        // consumer sites and the ONE substrate owner they now
3042        // route through. Peer to
3043        // `observed_flux_resources_matches_pre_lift_reconciler_chain_shape`
3044        // on the flux-resources axis's borrow-form primitive.
3045        fn pre_lift(p: &Process) -> Option<String> {
3046            p.status.as_ref().and_then(|s| s.pid.clone())
3047        }
3048        // Missing status.
3049        let mut p = Process::new("api", empty_spec());
3050        p.status = None;
3051        assert_eq!(p.observed_pid().map(str::to_string), pre_lift(&p));
3052        // Populated status, empty pid slot.
3053        let p = process_with_pid(None);
3054        assert_eq!(p.observed_pid().map(str::to_string), pre_lift(&p));
3055        // Populated status, populated pid slot.
3056        let p = process_with_pid(Some("seph.1.7"));
3057        assert_eq!(p.observed_pid().map(str::to_string), pre_lift(&p));
3058    }
3059
3060    #[test]
3061    fn observed_pid_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
3062        // Cross-corner coherence pin: the missing-`status` corner
3063        // and the populated-empty-slot corner return `Option`s whose
3064        // `.is_none()` observations are IDENTICAL. A regression
3065        // that promoted the missing-`status` corner to returning a
3066        // typed error (via a signature change to `Result<_, _>`) —
3067        // or that widened the empty-slot corner to a synthetic
3068        // `Some("")` — would surface here rather than as silent
3069        // operator-facing divergence between a never-status-
3070        // written Process and a status-emptied Process on the
3071        // ALLOCATE-PID gate.
3072        let mut p_no_status = Process::new("api", empty_spec());
3073        p_no_status.status = None;
3074        let p_empty_slot = process_with_pid(None);
3075        assert_eq!(
3076            p_no_status.observed_pid().is_none(),
3077            p_empty_slot.observed_pid().is_none()
3078        );
3079        assert_eq!(
3080            p_no_status.observed_pid().is_some(),
3081            p_empty_slot.observed_pid().is_some()
3082        );
3083    }
3084
3085    #[test]
3086    fn observed_pid_preserves_hierarchical_pid_format() {
3087        // Format-preservation pin: the hierarchical PID path
3088        // (dotted-segment form `seph.1.7`, matching the ported
3089        // `convergence-controller/src/identity.rs` scheme) reaches
3090        // the caller with segments and separators byte-identical
3091        // to the persisted `String`. A regression that inserted a
3092        // canonicalization pass (a segment-count validator, a
3093        // separator swap `.` → `/`, a leading/trailing whitespace
3094        // trim) would silently misroute the SIGTERM cascade's
3095        // `spec.identity.parent == Some(pid)` comparator against
3096        // children whose `parent` field was authored in the ported
3097        // scheme's exact form.
3098        for pid in ["seph", "seph.1", "seph.1.7", "seph.1.7.42"] {
3099            let p = process_with_pid(Some(pid));
3100            assert_eq!(p.observed_pid(), Some(pid));
3101        }
3102    }
3103
3104    // ─── Process::observed_attestation substrate pins ─────────────────
3105    //
3106    // Pins the borrow-form status-projection primitive on the
3107    // attestation-chain axis that owns the 3-line
3108    // `.status.as_ref().and_then(|s| s.attestation.as_ref())` chain
3109    // the two hand-authored `tatara-reconciler` sites
3110    // (`phase_machine::advance_to_attested` ATTEST composer +
3111    // `render::render_export_jobs` export-Job builder) restated by
3112    // hand pre-lift. Peer to the sibling `observed_pid_*` +
3113    // `observed_flux_resources_*` pin families; all three compose
3114    // the missing-`status` fallback + borrow-form return-shape
3115    // skeleton on distinct `ProcessStatus` slots. Fail-before-pass-
3116    // after granularity: `observed_attestation` did not exist
3117    // pre-lift, so any test invoking it fails to compile pre-lift
3118    // and passes post-lift.
3119
3120    fn sample_attestation(artifact: &str, intent: &str) -> ProcessAttestation {
3121        // Distinct pillar strings so a regression that swapped the
3122        // artifact / intent pillars silently surfaces as an
3123        // equality failure at the composed-root parity pin.
3124        ProcessAttestation::initial(artifact.to_string(), None, intent.to_string())
3125    }
3126
3127    fn process_with_attestation(attestation: Option<ProcessAttestation>) -> Process {
3128        let mut p = Process::new("api-gateway", empty_spec());
3129        p.metadata.namespace = Some("prod".into());
3130        let mut status = ProcessStatus::default();
3131        status.attestation = attestation;
3132        p.status = Some(status);
3133        p
3134    }
3135
3136    #[test]
3137    fn observed_attestation_returns_none_when_status_is_none() {
3138        // Missing-`status` corner pin: the primitive collapses the
3139        // no-status case to `None` so downstream `.is_some()` /
3140        // `if let Some(_)` / `.map(...)` behave identically on a
3141        // `Process` whose status field is `None` and on one whose
3142        // status carries an unpopulated `attestation` slot.
3143        // Matches the pre-lift `.and_then(...)` chain's `None`
3144        // byte-identically at every reconciler consumer's
3145        // downstream shape.
3146        let mut p = Process::new("api", empty_spec());
3147        p.status = None;
3148        assert!(p.observed_attestation().is_none());
3149    }
3150
3151    #[test]
3152    fn observed_attestation_returns_none_when_attestation_slot_is_none() {
3153        // Empty-slot-under-populated-status corner pin: the
3154        // primitive returns `None`, matching the missing-`status`
3155        // corner byte-identically. A regression that treated the
3156        // two corners differently (a `None`-vs-`Some(_)` signal
3157        // that downstream consumers could grep on) would silently
3158        // promote an internal representation detail (whether the
3159        // reconciler has ever written a status subresource) into
3160        // observable behavior at the ATTEST composer's
3161        // seed-vs-chain branch.
3162        let p = process_with_attestation(None);
3163        assert!(p.observed_attestation().is_none());
3164    }
3165
3166    #[test]
3167    fn observed_attestation_returns_borrow_when_slot_is_populated() {
3168        // Happy-path pin: with a populated `status.attestation`
3169        // slot, the primitive returns a borrowed
3170        // `&ProcessAttestation` whose fields match the persisted
3171        // record. A regression that filtered / reshaped /
3172        // canonicalized the record would surface here rather than
3173        // as silent skew at the downstream `prior.next(pillars)`
3174        // chain composer + the ephemeral-export receipt's
3175        // `previous_root` linker.
3176        let att = sample_attestation("art-1", "int-1");
3177        let composed_root = att.composed_root.clone();
3178        let p = process_with_attestation(Some(att));
3179        let observed = p.observed_attestation().expect("populated slot");
3180        assert_eq!(observed.artifact_hash, "art-1");
3181        assert_eq!(observed.intent_hash, "int-1");
3182        assert_eq!(observed.composed_root, composed_root);
3183        assert_eq!(observed.generation, 0);
3184        assert!(observed.previous_root.is_none());
3185    }
3186
3187    #[test]
3188    fn observed_attestation_is_a_zero_copy_borrow_projection() {
3189        // Borrow-discipline pin: the returned reference points at
3190        // the persisted `ProcessAttestation` in place — NOT a fresh
3191        // allocation or a clone. A regression that switched the
3192        // projection to an owned `ProcessAttestation` (via
3193        // `.clone()`) would defeat the zero-copy contract the
3194        // lift's primary strict-widening delivers (the pre-lift
3195        // 3-line chain returned a borrow, but the export-Job
3196        // builder then cloned `composed_root` off it; the post-
3197        // lift primitive preserves the borrow all the way to the
3198        // consumer's own cloning choice). Peer to the sibling
3199        // `observed_pid_is_a_zero_copy_borrow_projection` +
3200        // `observed_flux_resources_is_a_zero_copy_borrow_projection`
3201        // pins on the PID + flux-resources borrow-projection axes.
3202        let att = sample_attestation("art-1", "int-1");
3203        let p = process_with_attestation(Some(att));
3204        let observed = p.observed_attestation().expect("populated slot") as *const _;
3205        let persisted = p.status.as_ref().unwrap().attestation.as_ref().unwrap() as *const _;
3206        assert!(std::ptr::eq(observed, persisted));
3207    }
3208
3209    #[test]
3210    fn observed_attestation_is_a_pure_projection() {
3211        // Purity pin: calling the projection twice on the same
3212        // `Process` returns byte-identical borrows (same pointer).
3213        // A regression that introduced state — a lazy-cached
3214        // reference materialized on first call, a normalization
3215        // step that ran once and cached — would surface here
3216        // rather than as silent drift between the ATTEST composer
3217        // and the ephemeral-export receipt chain on the SAME
3218        // `Process` within one reconcile pass.
3219        let att = sample_attestation("art-1", "int-1");
3220        let p = process_with_attestation(Some(att));
3221        let a = p.observed_attestation().expect("populated slot") as *const _;
3222        let b = p.observed_attestation().expect("populated slot") as *const _;
3223        assert!(std::ptr::eq(a, b));
3224    }
3225
3226    #[test]
3227    fn observed_attestation_matches_pre_lift_reconciler_chain_shape() {
3228        // Byte-identical parity pin between the borrow-form
3229        // primitive here and the pre-lift `tatara-reconciler`
3230        // 3-line chain shape. Sweeps every corner every callsite
3231        // plausibly encounters (missing status, empty attestation
3232        // slot, populated attestation slot). A regression that
3233        // inserted a normalization step at the primitive the pre-
3234        // lift chain does NOT apply — or vice versa — surfaces
3235        // here rather than as silent drift between the pre-lift
3236        // consumer sites and the ONE substrate owner they now
3237        // route through. Peer to
3238        // `observed_pid_matches_pre_lift_reconciler_chain_shape` +
3239        // `observed_flux_resources_matches_pre_lift_reconciler_chain_shape`
3240        // on the PID + flux-resources axes.
3241        // `ProcessAttestation` does not derive `PartialEq` — the
3242        // parity check walks the `composed_root` field (the
3243        // byte-string every downstream consumer keys off) so a
3244        // regression that reshaped the record without touching
3245        // the composed-root observation surfaces here through
3246        // the receipt-chain projection.
3247        fn pre_lift(p: &Process) -> Option<String> {
3248            p.status
3249                .as_ref()
3250                .and_then(|s| s.attestation.as_ref())
3251                .map(|a| a.composed_root.clone())
3252        }
3253        // Missing status.
3254        let mut p = Process::new("api", empty_spec());
3255        p.status = None;
3256        assert_eq!(
3257            p.observed_attestation().map(|a| a.composed_root.clone()),
3258            pre_lift(&p)
3259        );
3260        // Populated status, empty attestation slot.
3261        let p = process_with_attestation(None);
3262        assert_eq!(
3263            p.observed_attestation().map(|a| a.composed_root.clone()),
3264            pre_lift(&p)
3265        );
3266        // Populated status, populated attestation slot.
3267        let p = process_with_attestation(Some(sample_attestation("art-1", "int-1")));
3268        assert_eq!(
3269            p.observed_attestation().map(|a| a.composed_root.clone()),
3270            pre_lift(&p)
3271        );
3272    }
3273
3274    #[test]
3275    fn observed_attestation_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
3276        // Cross-corner coherence pin: the missing-`status` corner
3277        // and the populated-empty-slot corner return `Option`s
3278        // whose `.is_none()` observations are IDENTICAL. A
3279        // regression that promoted the missing-`status` corner to
3280        // returning a typed error (via a signature change to
3281        // `Result<_, _>`) — or that widened the empty-slot corner
3282        // to a synthetic `Some(default_attestation)` — would
3283        // surface here rather than as silent operator-facing
3284        // divergence between a never-status-written Process and
3285        // an attestation-emptied Process on the ATTEST composer's
3286        // seed-vs-chain branch.
3287        let mut p_no_status = Process::new("api", empty_spec());
3288        p_no_status.status = None;
3289        let p_empty_slot = process_with_attestation(None);
3290        assert_eq!(
3291            p_no_status.observed_attestation().is_none(),
3292            p_empty_slot.observed_attestation().is_none()
3293        );
3294        assert_eq!(
3295            p_no_status.observed_attestation().is_some(),
3296            p_empty_slot.observed_attestation().is_some()
3297        );
3298    }
3299
3300    #[test]
3301    fn observed_attestation_preserves_chain_generation_field() {
3302        // Generation-preservation pin: a chained attestation
3303        // (`prior.next(...)` at generation N ≥ 1 with a
3304        // `previous_root` linked to `prior.composed_root`) reaches
3305        // the caller with its `generation` counter + `previous_root`
3306        // link byte-identical to the persisted record. The pre-lift
3307        // ATTEST composer discriminated exactly on this borrow's
3308        // `Some(prior)` vs `None` arm; a regression that dropped
3309        // the chain's `generation` counter (say, by folding
3310        // `next(...)` into a fresh `initial(...)` on every
3311        // reconcile pass) would silently reset every chain and
3312        // orphan every downstream `previous_root` link, but that
3313        // drift is invisible to a Process CRD reader who only
3314        // observes the LATEST composed_root.
3315        let prior = sample_attestation("art-0", "int-0");
3316        let chained = prior.next("art-1".to_string(), None, "int-1".to_string());
3317        let expected_generation = chained.generation;
3318        let expected_previous = chained.previous_root.clone();
3319        let p = process_with_attestation(Some(chained));
3320        let observed = p.observed_attestation().expect("populated slot");
3321        assert_eq!(observed.generation, expected_generation);
3322        assert_eq!(observed.generation, 1);
3323        assert_eq!(observed.previous_root, expected_previous);
3324        assert_eq!(
3325            observed.previous_root.as_deref(),
3326            Some(prior.composed_root.as_str())
3327        );
3328    }
3329
3330    // ─── Process::observed_identity substrate pins ────────────────────
3331    //
3332    // The borrow-form status-projection primitive on the resolved-
3333    // identity axis. Collapses the paired 3-line `.status.as_ref()
3334    // .and_then(|s| s.identity.<clone|as_ref>())` chain every
3335    // consumer in `tatara-reconciler` restated by hand pre-lift at
3336    // TWO sites (`phase_machine::handle_forking` seed +
3337    // `ssapply::inject_annotations` content-hash annotation
3338    // composer). Peer to the sibling `observed_pid_*` +
3339    // `observed_attestation_*` + `observed_flux_resources_*` pin
3340    // families; all four compose the same missing-`status` fallback
3341    // + borrow-form return-shape skeleton on distinct
3342    // `ProcessStatus` slots. Each pin fails-before-pass-after
3343    // granularity: `observed_identity` did not exist pre-lift, so
3344    // any test invoking it fails to compile pre-lift and passes
3345    // post-lift.
3346
3347    fn sample_identity(name: &str) -> Identity {
3348        // Distinct name + content_hash + override flag so a
3349        // regression that reshaped one slot surfaces at the
3350        // populated-slot pin's field-equality check without
3351        // aliasing the sibling slots.
3352        Identity {
3353            name: name.to_string(),
3354            content_hash: "a".repeat(26),
3355            name_override: true,
3356        }
3357    }
3358
3359    fn process_with_identity(identity: Option<Identity>) -> Process {
3360        let mut p = Process::new("api-gateway", empty_spec());
3361        p.metadata.namespace = Some("prod".into());
3362        let mut status = ProcessStatus::default();
3363        status.identity = identity;
3364        p.status = Some(status);
3365        p
3366    }
3367
3368    #[test]
3369    fn observed_identity_returns_none_when_status_is_none() {
3370        // Missing-`status` corner pin: the primitive collapses the
3371        // no-status case to `None` so downstream `.is_some()` /
3372        // `if let Some(_)` / `.cloned().unwrap_or_else(...)` behave
3373        // identically on a `Process` whose status field is `None`
3374        // and on one whose status carries an unpopulated `identity`
3375        // slot. Matches the pre-lift `.and_then(...)` chain's `None`
3376        // byte-identically at every reconciler consumer's
3377        // downstream shape.
3378        let mut p = Process::new("api", empty_spec());
3379        p.status = None;
3380        assert!(p.observed_identity().is_none());
3381    }
3382
3383    #[test]
3384    fn observed_identity_returns_none_when_identity_slot_is_none() {
3385        // Empty-slot-under-populated-status corner pin: the
3386        // primitive returns `None`, matching the missing-`status`
3387        // corner byte-identically. A regression that treated the
3388        // two corners differently (a `None`-vs-`Some(_)` signal
3389        // that downstream consumers could grep on) would silently
3390        // promote an internal representation detail (whether the
3391        // reconciler has ever written a status subresource) into
3392        // observable behavior at the FORK-time `derive_identity`
3393        // fallback branch.
3394        let p = process_with_identity(None);
3395        assert!(p.observed_identity().is_none());
3396    }
3397
3398    #[test]
3399    fn observed_identity_returns_borrow_when_slot_is_populated() {
3400        // Happy-path pin: with a populated `status.identity` slot,
3401        // the primitive returns a borrowed `&Identity` whose fields
3402        // match the persisted record. A regression that filtered /
3403        // reshaped / canonicalized the record would surface here
3404        // rather than as silent skew at the FORK-time seed's
3405        // `.cloned().unwrap_or_else(derive_identity)` composition
3406        // + the SSA-time content-hash annotation stamp on the SAME
3407        // Process.
3408        let id = sample_identity("seph");
3409        let expected = id.clone();
3410        let p = process_with_identity(Some(id));
3411        let observed = p.observed_identity().expect("populated slot");
3412        assert_eq!(observed, &expected);
3413        assert_eq!(observed.name, "seph");
3414        assert_eq!(observed.content_hash, "a".repeat(26));
3415        assert!(observed.name_override);
3416    }
3417
3418    #[test]
3419    fn observed_identity_is_a_zero_copy_borrow_projection() {
3420        // Borrow-discipline pin: the returned reference points at
3421        // the persisted `Identity` in place — NOT a fresh
3422        // allocation or a clone. A regression that switched the
3423        // projection to an owned `Identity` (via `.clone()`) would
3424        // defeat the zero-copy contract the lift's primary strict-
3425        // widening delivers (the SSA-time consumer never clones the
3426        // whole `Identity`, only the `content_hash` field it stamps
3427        // onto the annotation map, so the borrow-form return
3428        // shape's happy-path allocation count is exactly ZERO).
3429        // Peer to the sibling
3430        // `observed_attestation_is_a_zero_copy_borrow_projection`
3431        // + `observed_pid_is_a_zero_copy_borrow_projection` +
3432        // `observed_flux_resources_is_a_zero_copy_borrow_projection`
3433        // pins on the attestation-chain + PID + flux-resources
3434        // borrow-projection axes.
3435        let id = sample_identity("seph");
3436        let p = process_with_identity(Some(id));
3437        let observed = p.observed_identity().expect("populated slot") as *const _;
3438        let persisted = p.status.as_ref().unwrap().identity.as_ref().unwrap() as *const _;
3439        assert!(std::ptr::eq(observed, persisted));
3440    }
3441
3442    #[test]
3443    fn observed_identity_is_a_pure_projection() {
3444        // Purity pin: calling the projection twice on the same
3445        // `Process` returns byte-identical borrows (same pointer).
3446        // A regression that introduced state — a lazy-cached
3447        // reference materialized on first call, a normalization
3448        // step that ran once and cached — would surface here
3449        // rather than as silent drift between the FORK-time
3450        // identity seed and the SSA-time content-hash annotation
3451        // stamp on the SAME `Process` within one reconcile pass.
3452        let p = process_with_identity(Some(sample_identity("seph")));
3453        let a = p.observed_identity().expect("populated slot") as *const _;
3454        let b = p.observed_identity().expect("populated slot") as *const _;
3455        assert!(std::ptr::eq(a, b));
3456    }
3457
3458    #[test]
3459    fn observed_identity_matches_pre_lift_reconciler_chain_shape() {
3460        // Byte-identical parity pin between the borrow-form
3461        // primitive here and the pre-lift `tatara-reconciler`
3462        // 3-line chain shape. Sweeps every corner every callsite
3463        // plausibly encounters (missing status, empty identity
3464        // slot, populated identity slot). A regression that
3465        // inserted a normalization step at the primitive the pre-
3466        // lift chain does NOT apply — or vice versa — surfaces
3467        // here rather than as silent drift between the pre-lift
3468        // consumer sites and the ONE substrate owner they now
3469        // route through. Peer to
3470        // `observed_attestation_matches_pre_lift_reconciler_chain_shape`
3471        // + `observed_pid_matches_pre_lift_reconciler_chain_shape`
3472        // + `observed_flux_resources_matches_pre_lift_reconciler_chain_shape`
3473        // on the attestation-chain + PID + flux-resources axes.
3474        fn pre_lift(p: &Process) -> Option<Identity> {
3475            p.status.as_ref().and_then(|s| s.identity.clone())
3476        }
3477        // Missing status.
3478        let mut p = Process::new("api", empty_spec());
3479        p.status = None;
3480        assert_eq!(p.observed_identity().cloned(), pre_lift(&p));
3481        // Populated status, empty identity slot.
3482        let p = process_with_identity(None);
3483        assert_eq!(p.observed_identity().cloned(), pre_lift(&p));
3484        // Populated status, populated identity slot.
3485        let p = process_with_identity(Some(sample_identity("seph")));
3486        assert_eq!(p.observed_identity().cloned(), pre_lift(&p));
3487    }
3488
3489    #[test]
3490    fn observed_identity_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
3491        // Cross-corner coherence pin: the missing-`status` corner
3492        // and the populated-empty-slot corner return `Option`s
3493        // whose `.is_none()` observations are IDENTICAL. A
3494        // regression that promoted the missing-`status` corner to
3495        // returning a typed error (via a signature change to
3496        // `Result<_, _>`) — or that widened the empty-slot corner
3497        // to a synthetic `Some(derive_identity(default_spec))` —
3498        // would surface here rather than as silent operator-facing
3499        // divergence between a never-status-written Process and an
3500        // identity-cleared Process on the FORK-time seed branch.
3501        let mut p_no_status = Process::new("api", empty_spec());
3502        p_no_status.status = None;
3503        let p_empty_slot = process_with_identity(None);
3504        assert_eq!(
3505            p_no_status.observed_identity().is_none(),
3506            p_empty_slot.observed_identity().is_none()
3507        );
3508        assert_eq!(
3509            p_no_status.observed_identity().is_some(),
3510            p_empty_slot.observed_identity().is_some()
3511        );
3512    }
3513
3514    #[test]
3515    fn observed_identity_cloned_composes_with_derive_identity_fallback() {
3516        // Cross-primitive composition pin: the borrow-form
3517        // primitive threaded through `.cloned().unwrap_or_else(||
3518        // derive_identity(...))` reproduces the pre-lift FORK-time
3519        // seed's owned-`Identity` shape at every corner. Binds the
3520        // exact composition the `phase_machine::handle_forking`
3521        // consumer performs: on the populated-slot corner the
3522        // reconciler-persisted `Identity` is returned verbatim (the
3523        // fallback never fires), and on both empty corners
3524        // (missing-status + empty-slot) the fallback fires
3525        // producing a fresh `derive_identity(&spec,
3526        // name_override)`. A regression that (a) swapped the
3527        // fallback direction, (b) made `.cloned()` re-derive
3528        // instead of clone, or (c) made the empty-slot corner
3529        // return a synthetic `Some(default_identity)` collides
3530        // with the fallback surfaces here rather than as silent
3531        // FORK-time PID allocator skew.
3532        let spec = empty_spec();
3533        let fallback_expected = crate::identity::derive_identity(&spec, None);
3534        // Populated-slot corner: the seed returns the persisted
3535        // identity, NOT the derive fallback.
3536        let persisted = sample_identity("seph");
3537        let p = process_with_identity(Some(persisted.clone()));
3538        let seed = p.observed_identity().cloned().unwrap_or_else(|| {
3539            crate::identity::derive_identity(&p.spec, p.declared_name_override())
3540        });
3541        assert_eq!(seed, persisted);
3542        assert_ne!(seed, fallback_expected);
3543        // Empty-slot corner: the seed fires the derive fallback.
3544        let p = process_with_identity(None);
3545        let seed = p.observed_identity().cloned().unwrap_or_else(|| {
3546            crate::identity::derive_identity(&p.spec, p.declared_name_override())
3547        });
3548        assert_eq!(seed, fallback_expected);
3549        // Missing-status corner: the seed fires the derive
3550        // fallback, byte-identical to the empty-slot corner.
3551        let mut p = Process::new("api-gateway", empty_spec());
3552        p.metadata.namespace = Some("prod".into());
3553        p.status = None;
3554        let seed = p.observed_identity().cloned().unwrap_or_else(|| {
3555            crate::identity::derive_identity(&p.spec, p.declared_name_override())
3556        });
3557        assert_eq!(seed, fallback_expected);
3558    }
3559
3560    // ─── Process::observed_phase substrate pins ───────────────────────
3561    //
3562    // The copy-form status-projection primitive on the phase axis.
3563    // Collapses the paired 3-line `.status.as_ref().map(|s| s.phase)`
3564    // chain every consumer in `tatara-reconciler` restated by hand
3565    // pre-lift at FIVE sites. Peer to the borrow-form
3566    // `observed_pid_*` + `observed_flux_resources_*` +
3567    // `observed_attestation_*` pin families; all four compose the
3568    // same missing-`status` fallback skeleton on distinct
3569    // `ProcessStatus` slots, with the phase-axis form returning
3570    // `Option<ProcessPhase>` (copy of a `Copy` scalar) rather than
3571    // `Option<&T>` (borrow) because the underlying slot is a bare
3572    // `ProcessPhase` — no allocation to borrow past, and the enum
3573    // is one byte on the wire. Each pin fails-before-pass-after
3574    // granularity: `observed_phase` did not exist pre-lift, so any
3575    // test invoking it fails to compile pre-lift and passes
3576    // post-lift.
3577
3578    fn process_with_phase(phase: Option<ProcessPhase>) -> Process {
3579        let mut p = Process::new("api-gateway", empty_spec());
3580        p.metadata.namespace = Some("prod".into());
3581        if let Some(ph) = phase {
3582            let mut status = ProcessStatus::default();
3583            status.phase = ph;
3584            p.status = Some(status);
3585        }
3586        p
3587    }
3588
3589    #[test]
3590    fn observed_phase_returns_none_when_status_is_none() {
3591        // Missing-`status` corner pin: the primitive collapses the
3592        // no-status case to `None` so downstream `.unwrap_or(...)`
3593        // at every reconciler consumer chooses the default
3594        // deliberately (`Pending` for the top-level dispatch seed
3595        // + boundary evaluator + routing groupby; `Attested` for
3596        // the released-from annotation composer). Matches the
3597        // pre-lift `.map(|s| s.phase)` chain's `None`
3598        // byte-identically at every consumer's downstream shape.
3599        let mut p = Process::new("api", empty_spec());
3600        p.status = None;
3601        assert!(p.observed_phase().is_none());
3602    }
3603
3604    #[test]
3605    fn observed_phase_returns_some_default_when_status_is_populated_with_default_phase() {
3606        // Populated-status corner pin: the primitive returns
3607        // `Some(ProcessPhase::default())` — a `ProcessStatus`
3608        // constructed via `default()` carries `phase: Pending`
3609        // because the phase field is a bare `ProcessPhase` (not
3610        // `Option<ProcessPhase>`), so there is NO "empty slot"
3611        // corner peer to the borrow-form projections' empty-slot
3612        // pins. A regression that reshaped the return type to
3613        // filter out `Pending` (treating it as "unset") would
3614        // surface here and silently break the top-level
3615        // dispatcher's Pending → Forking transition on a Process
3616        // freshly written by the reconciler.
3617        let p = process_with_phase(Some(ProcessPhase::default()));
3618        assert_eq!(p.observed_phase(), Some(ProcessPhase::Pending));
3619        assert_eq!(p.observed_phase(), Some(ProcessPhase::default()));
3620    }
3621
3622    #[test]
3623    fn observed_phase_returns_persisted_phase_when_status_is_populated() {
3624        // Happy-path pin: with a populated `status.phase` slot,
3625        // the primitive returns the persisted `ProcessPhase`.
3626        // A regression that filtered / reshaped / canonicalized
3627        // the phase would surface here rather than as silent
3628        // skew at the top-level dispatcher's phase handler
3629        // dispatch on the SAME Process.
3630        let p = process_with_phase(Some(ProcessPhase::Running));
3631        assert_eq!(p.observed_phase(), Some(ProcessPhase::Running));
3632    }
3633
3634    #[test]
3635    fn observed_phase_is_a_pure_projection() {
3636        // Purity pin: two consecutive calls return byte-identical
3637        // `Option<ProcessPhase>` values (no lazy materialization,
3638        // no interior mutation of `self`). Peer to the sibling
3639        // `observed_pid_is_a_pure_projection` +
3640        // `observed_flux_resources_is_a_pure_projection` +
3641        // `observed_attestation_is_a_pure_projection` pins; all
3642        // four bind the pure-projection discipline on the ONE
3643        // substrate accessor per status slot.
3644        let p = process_with_phase(Some(ProcessPhase::Attested));
3645        let a = p.observed_phase();
3646        let b = p.observed_phase();
3647        assert_eq!(a, b);
3648        assert_eq!(a, Some(ProcessPhase::Attested));
3649    }
3650
3651    #[test]
3652    fn observed_phase_matches_pre_lift_reconciler_chain_shape() {
3653        // Parity pin: sweeps the two corners every pre-lift
3654        // consumer plausibly encountered (missing status,
3655        // populated status with a particular phase) and compares
3656        // the substrate call against a hand-authored pre-lift
3657        // chain byte-identically. A regression that reshaped ANY
3658        // of the two corners would surface here rather than as
3659        // silent operator-facing skew between the top-level
3660        // dispatcher and any of the four other reconciler
3661        // consumers on the SAME `Process`.
3662        fn pre_lift(p: &Process) -> Option<ProcessPhase> {
3663            p.status.as_ref().map(|s| s.phase)
3664        }
3665        let mut p = Process::new("api", empty_spec());
3666        p.status = None;
3667        assert_eq!(p.observed_phase(), pre_lift(&p));
3668        let p = process_with_phase(Some(ProcessPhase::Running));
3669        assert_eq!(p.observed_phase(), pre_lift(&p));
3670        let p = process_with_phase(Some(ProcessPhase::Attested));
3671        assert_eq!(p.observed_phase(), pre_lift(&p));
3672        let p = process_with_phase(Some(ProcessPhase::Failed));
3673        assert_eq!(p.observed_phase(), pre_lift(&p));
3674    }
3675
3676    #[test]
3677    fn observed_phase_default_unwrap_matches_pre_lift_pending_default() {
3678        // Callsite-shape pin: three of the FIVE pre-lift consumers
3679        // (`controller::reconcile`, `boundary::evaluate_process_phase`,
3680        // `table_controller::stable_name_group_key`) closed the
3681        // 3-line chain with `.unwrap_or(ProcessPhase::Pending)`
3682        // (identical to `.unwrap_or_default()`). This pin binds
3683        // that call-site shape: `observed_phase().unwrap_or
3684        // (Pending)` returns `Pending` on missing status and the
3685        // persisted phase otherwise. A regression that swapped
3686        // the `None` sentinel's downstream default would surface
3687        // here rather than as silent skew at three of the five
3688        // consumer sites.
3689        let mut p = Process::new("api", empty_spec());
3690        p.status = None;
3691        assert_eq!(
3692            p.observed_phase().unwrap_or(ProcessPhase::Pending),
3693            ProcessPhase::Pending
3694        );
3695        let p = process_with_phase(Some(ProcessPhase::Running));
3696        assert_eq!(
3697            p.observed_phase().unwrap_or(ProcessPhase::Pending),
3698            ProcessPhase::Running
3699        );
3700    }
3701
3702    #[test]
3703    fn observed_phase_attested_unwrap_matches_pre_lift_released_from_default() {
3704        // Callsite-shape pin: the ONE pre-lift consumer
3705        // (`phase_machine::p_current_phase_str` — the
3706        // released-from annotation composer) closed the 3-line
3707        // chain with `.unwrap_or(ProcessPhase::Attested)` rather
3708        // than the `Default` (`Pending`). This pin binds that
3709        // call-site shape: `observed_phase().unwrap_or(Attested)`
3710        // returns `Attested` on missing status and the persisted
3711        // phase otherwise. A regression that folded the
3712        // `Attested`-default consumer into the `Pending`-default
3713        // majority would break the SIGSTOP/SIGCONT release gate's
3714        // "which annotation label to emit" branch — the pin binds
3715        // the primitive at the raw `Option<ProcessPhase>` form so
3716        // this default choice stays local at the callsite.
3717        let mut p = Process::new("api", empty_spec());
3718        p.status = None;
3719        assert_eq!(
3720            p.observed_phase().unwrap_or(ProcessPhase::Attested),
3721            ProcessPhase::Attested
3722        );
3723        let p = process_with_phase(Some(ProcessPhase::Failed));
3724        assert_eq!(
3725            p.observed_phase().unwrap_or(ProcessPhase::Attested),
3726            ProcessPhase::Failed
3727        );
3728    }
3729
3730    #[test]
3731    fn observed_phase_preserves_every_process_phase_variant() {
3732        // Round-trip pin: every `ProcessPhase` variant round-
3733        // trips through the primitive unchanged. Peer to the
3734        // sibling `observed_pid_preserves_hierarchical_pid_format`
3735        // pin's dotted-segment sweep; this pin sweeps the closed
3736        // set of `ProcessPhase` variants directly so a
3737        // canonicalization pass that dropped or reshaped one
3738        // (e.g. folded `Reconverging` back into `Execing`, or
3739        // remapped `Zombie` to `Reaped`) surfaces here rather
3740        // than as silent skew at the SIGSTOP/SIGCONT release
3741        // gate's phase-name annotation branch. Covers every
3742        // variant the `ProcessPhase::DeriveClosedSet` enumerates
3743        // so a future variant addition surfaces via the closed-
3744        // set macro rather than at a silent partial sweep.
3745        for phase in [
3746            ProcessPhase::Pending,
3747            ProcessPhase::Forking,
3748            ProcessPhase::Execing,
3749            ProcessPhase::Running,
3750            ProcessPhase::Attested,
3751            ProcessPhase::Reconverging,
3752            ProcessPhase::Releasing,
3753            ProcessPhase::Exiting,
3754            ProcessPhase::Failed,
3755            ProcessPhase::Zombie,
3756            ProcessPhase::Reaped,
3757        ] {
3758            let p = process_with_phase(Some(phase));
3759            assert_eq!(
3760                p.observed_phase(),
3761                Some(phase),
3762                "phase variant {phase:?} did not round-trip"
3763            );
3764        }
3765    }
3766
3767    // ─── Process::observed_phase_or_pending substrate pins ─────────────
3768    //
3769    // Pins the copy-form status-projection primitive on the phase
3770    // axis with the `Pending` sink applied. Sibling to the raw
3771    // `observed_phase_*` pin family on the (return-form × fallback
3772    // shape) axis pair — the raw-`Option` corner stays with the
3773    // sibling family; this pin family opens the `Pending`-defaulted
3774    // corner that four of the five pre-lift `observed_phase`
3775    // consumers wrote by hand. Fail-before-pass-after granularity:
3776    // `observed_phase_or_pending` did not exist pre-lift, so any
3777    // test invoking it fails to compile pre-lift and passes
3778    // post-lift.
3779
3780    #[test]
3781    fn observed_phase_or_pending_returns_pending_when_status_is_none() {
3782        // Missing-`status` corner pin: the primitive collapses the
3783        // no-status case to `Pending` — the sink four of the five
3784        // pre-lift `observed_phase` consumers wrote by hand
3785        // (`controller::reconcile` / `boundary::
3786        // evaluate_process_phase` / `table_controller::
3787        // stable_name_group_key` / `controller_pool::reconcile_pool`)
3788        // and the sentinel `ProcessPhase::default()` returns. A
3789        // regression that folded the `None` sink to any other phase
3790        // (e.g. `Forking` — treating "not yet observed" as "already
3791        // dispatched") would silently mis-seed the top-level
3792        // dispatcher's `Pending → Forking` transition and surface as
3793        // operator-visible reconcile-cycle skew on a freshly-forked
3794        // Process rather than at this pin.
3795        let mut p = Process::new("api", empty_spec());
3796        p.status = None;
3797        assert_eq!(p.observed_phase_or_pending(), ProcessPhase::Pending);
3798    }
3799
3800    #[test]
3801    fn observed_phase_or_pending_returns_persisted_phase_when_status_is_populated() {
3802        // Populated-status corner pin: the primitive passes through
3803        // the persisted `ProcessPhase` unchanged — the sink only
3804        // fires on missing `status`, not on a populated one carrying
3805        // a `Pending`-adjacent variant. Two variants pinned to
3806        // separate the "pass through the persisted phase" arm from
3807        // the "sink fires" arm: `Running` (mid-lifecycle) and
3808        // `Attested` (post-verify) both round-trip unchanged where
3809        // a regression that always returned `Pending` (dropped the
3810        // pass-through arm entirely) would surface here rather than
3811        // as silent skew at every reconciler's per-phase branch.
3812        let p = process_with_phase(Some(ProcessPhase::Running));
3813        assert_eq!(p.observed_phase_or_pending(), ProcessPhase::Running);
3814        let p = process_with_phase(Some(ProcessPhase::Attested));
3815        assert_eq!(p.observed_phase_or_pending(), ProcessPhase::Attested);
3816    }
3817
3818    #[test]
3819    fn observed_phase_or_pending_matches_pre_lift_unwrap_or_pending_chain_shape() {
3820        // Byte-identical parity pin: the primitive's return equals
3821        // the pre-lift two-link `.observed_phase().unwrap_or
3822        // (ProcessPhase::Pending)` chain at every one of the four
3823        // corner values (missing `status` → `Pending`, populated
3824        // with `Pending` → `Pending`, populated with a mid-lifecycle
3825        // variant → pass-through, populated with a terminal variant
3826        // → pass-through). A regression that swapped the sink to
3827        // `ProcessPhase::default()` (currently equivalent to
3828        // `Pending`) would keep this pin green until the enum's
3829        // `Default` impl drifted — the explicit `Pending` spelling
3830        // in the pin binds the operator-visible label rather than
3831        // the derived `Default`, so a future rename or reordering
3832        // of `ProcessPhase` variants that shifted `Default` off
3833        // `Pending` would surface here rather than as silent skew
3834        // at the four downstream consumer sites.
3835        let pre_lift = |p: &Process| p.observed_phase().unwrap_or(ProcessPhase::Pending);
3836        let mut p = Process::new("api", empty_spec());
3837        p.status = None;
3838        assert_eq!(p.observed_phase_or_pending(), pre_lift(&p));
3839        let p = process_with_phase(Some(ProcessPhase::Pending));
3840        assert_eq!(p.observed_phase_or_pending(), pre_lift(&p));
3841        let p = process_with_phase(Some(ProcessPhase::Running));
3842        assert_eq!(p.observed_phase_or_pending(), pre_lift(&p));
3843        let p = process_with_phase(Some(ProcessPhase::Reaped));
3844        assert_eq!(p.observed_phase_or_pending(), pre_lift(&p));
3845    }
3846
3847    #[test]
3848    fn observed_phase_or_pending_is_a_pure_projection() {
3849        // Purity pin: two back-to-back calls on the same `Process`
3850        // return the same `ProcessPhase` — the primitive stamps no
3851        // side effect (no clock read, no metadata write, no
3852        // `status` mutation) despite the sibling `observed_phase`
3853        // taking `&self` too. Peer to the sibling `observed_phase`
3854        // purity pin; a regression that folded a clock read (e.g.
3855        // "if the sink fired, stamp `phase_since = Utc::now()`")
3856        // into the primitive would surface here rather than at the
3857        // consumer sites' downstream reconcile-cycle behavior.
3858        let p = process_with_phase(Some(ProcessPhase::Running));
3859        let a = p.observed_phase_or_pending();
3860        let b = p.observed_phase_or_pending();
3861        assert_eq!(a, b);
3862    }
3863
3864    #[test]
3865    fn observed_phase_or_pending_preserves_every_process_phase_variant() {
3866        // Round-trip pin: every `ProcessPhase` variant round-trips
3867        // through the primitive unchanged when the `status` slot is
3868        // populated. Peer to the sibling `observed_phase_preserves
3869        // _every_process_phase_variant` sweep; this pin sweeps the
3870        // closed set through the `Pending`-sinked accessor rather
3871        // than the raw-`Option` accessor so a canonicalization pass
3872        // that dropped or reshaped one variant (e.g. folded
3873        // `Reconverging` back into `Execing`, remapped `Zombie` to
3874        // `Reaped`) surfaces at BOTH primitives' pin sets rather
3875        // than as silent skew at a subset of the reconciler
3876        // consumers. Covers every variant the
3877        // `ProcessPhase::DeriveClosedSet` enumerates so a future
3878        // variant addition surfaces via the closed-set macro rather
3879        // than at a silent partial sweep.
3880        for phase in [
3881            ProcessPhase::Pending,
3882            ProcessPhase::Forking,
3883            ProcessPhase::Execing,
3884            ProcessPhase::Running,
3885            ProcessPhase::Attested,
3886            ProcessPhase::Reconverging,
3887            ProcessPhase::Releasing,
3888            ProcessPhase::Exiting,
3889            ProcessPhase::Failed,
3890            ProcessPhase::Zombie,
3891            ProcessPhase::Reaped,
3892        ] {
3893            let p = process_with_phase(Some(phase));
3894            assert_eq!(
3895                p.observed_phase_or_pending(),
3896                phase,
3897                "phase variant {phase:?} did not round-trip through observed_phase_or_pending"
3898            );
3899        }
3900    }
3901
3902    // ─── Process::is_being_deleted substrate pins ───────────────────────
3903    //
3904    // Pins the copy-form metadata-projection primitive on the
3905    // deletion-tombstone axis. Peer to the borrow-form + copy-form
3906    // metadata-fallback family (`namespace_or_default`,
3907    // `name_or_placeholder`, `uid_or_empty`, `coordinates_or_defaults`,
3908    // `coordinates_or_none`, `owned_coordinates_or_err`, `annotation`);
3909    // this one opens the presence-probe corner for the tombstone slot.
3910    // Fail-before-pass-after granularity: `is_being_deleted` did not
3911    // exist pre-lift, so any test invoking it fails to compile pre-
3912    // lift and passes post-lift.
3913
3914    fn tombstoned_process() -> Process {
3915        let mut p = Process::new("api-gateway", empty_spec());
3916        p.metadata.namespace = Some("prod".into());
3917        p.metadata.deletion_timestamp = Some(k8s_openapi::apimachinery::pkg::apis::meta::v1::Time(
3918            Utc::now(),
3919        ));
3920        p
3921    }
3922
3923    #[test]
3924    fn is_being_deleted_returns_false_when_deletion_timestamp_is_absent() {
3925        // Missing-tombstone corner pin: the primitive collapses the
3926        // no-tombstone case to `false` so the SIGTERM preempt at
3927        // `controller::reconcile` skips the `→ Exiting` forcing
3928        // branch and the DELETE-skip at `handle_exiting`'s child
3929        // fan-out does NOT `continue` past a child that is still
3930        // healthy. Matches the pre-lift `.is_some()` chain's `false`
3931        // byte-identically at every consumer's downstream gate.
3932        let mut p = Process::new("api", empty_spec());
3933        p.metadata.deletion_timestamp = None;
3934        assert!(!p.is_being_deleted());
3935    }
3936
3937    #[test]
3938    fn is_being_deleted_returns_true_when_deletion_timestamp_is_present() {
3939        // Present-tombstone corner pin: the primitive returns
3940        // `true` on any populated `metadata.deletionTimestamp`
3941        // slot regardless of the timestamp payload — the two
3942        // consumers only read the tombstone's PRESENCE, never
3943        // its RFC-3339 timestamp value. A regression that gated
3944        // the `true` return on the timestamp being non-epoch, or
3945        // parsed the timestamp before returning, would surface
3946        // here rather than as silent skew at the SIGTERM preempt
3947        // or child-fan-out DELETE-skip on the SAME `Process`.
3948        let p = tombstoned_process();
3949        assert!(p.is_being_deleted());
3950    }
3951
3952    #[test]
3953    fn is_being_deleted_is_a_pure_projection() {
3954        // Purity pin: two consecutive calls return byte-identical
3955        // `bool` values (no lazy materialization, no interior
3956        // mutation of `self`). Peer to the sibling
3957        // `observed_phase_is_a_pure_projection` +
3958        // `observed_pid_is_a_pure_projection` +
3959        // `observed_flux_resources_is_a_pure_projection` +
3960        // `observed_attestation_is_a_pure_projection` pins; all
3961        // five bind the pure-projection discipline on the ONE
3962        // substrate accessor per metadata / status slot.
3963        let p = tombstoned_process();
3964        let a = p.is_being_deleted();
3965        let b = p.is_being_deleted();
3966        assert_eq!(a, b);
3967        assert!(a);
3968    }
3969
3970    #[test]
3971    fn is_being_deleted_matches_pre_lift_reconciler_chain_shape() {
3972        // Parity pin: sweeps the two corners every pre-lift
3973        // consumer plausibly encountered (missing tombstone,
3974        // present tombstone) and compares the substrate call
3975        // against a hand-authored pre-lift chain byte-identically.
3976        // A regression that reshaped either corner would surface
3977        // here rather than as silent operator-facing skew between
3978        // the top-level dispatcher's SIGTERM preempt and the
3979        // SIGTERM cascade's child-fan-out DELETE-skip on the
3980        // SAME `Process` within one reconcile pass.
3981        fn pre_lift(p: &Process) -> bool {
3982            p.metadata.deletion_timestamp.is_some()
3983        }
3984        let mut p = Process::new("api", empty_spec());
3985        p.metadata.deletion_timestamp = None;
3986        assert_eq!(p.is_being_deleted(), pre_lift(&p));
3987        let p = tombstoned_process();
3988        assert_eq!(p.is_being_deleted(), pre_lift(&p));
3989    }
3990
3991    #[test]
3992    fn is_being_deleted_composes_with_process_phase_is_alive_at_reconcile_preempt() {
3993        // Call-site-shape pin: the `controller::reconcile` SIGTERM
3994        // preempt composes `is_being_deleted() && current_phase
3995        // .is_alive()` — the tombstone-presence probe AND the
3996        // alive-phase gate must BOTH hold to force `→ Exiting`.
3997        // A dead-phase (`Zombie` / `Reaped` / `Failed`) Process
3998        // that carries a tombstone still runs its normal handler,
3999        // not the preempt. This pin binds that composition shape
4000        // at the primitive so a regression that flipped either
4001        // half of the `&&` (or that broadened the tombstone probe
4002        // to include the `is_alive` half implicitly) surfaces
4003        // here rather than as silent skew at the top-level
4004        // dispatch on the SAME `Process`.
4005        let mut p = tombstoned_process();
4006        // Alive + tombstoned → preempt fires.
4007        let mut alive = ProcessStatus::default();
4008        alive.phase = ProcessPhase::Running;
4009        p.status = Some(alive);
4010        assert!(p.is_being_deleted());
4011        assert!(p.observed_phase().unwrap_or_default().is_alive());
4012        // Dead + tombstoned → preempt does NOT fire (composition
4013        // with `is_alive` returns false).
4014        let mut dead = ProcessStatus::default();
4015        dead.phase = ProcessPhase::Reaped;
4016        p.status = Some(dead);
4017        assert!(p.is_being_deleted());
4018        assert!(!p.observed_phase().unwrap_or_default().is_alive());
4019    }
4020
4021    // ─── Process::created_at substrate pins ─────────────────────────
4022    //
4023    // Pins the copy-form metadata-projection primitive on the
4024    // `metadata.creationTimestamp` axis that owns the
4025    // `.metadata.creation_timestamp.as_ref().map(|t| t.0)` chain the
4026    // three hand-authored sites (`lifetime_clock::evaluate`,
4027    // `lifetime_clock::requeue_with_ttl`,
4028    // `tatara-reconciler::table_controller`) restated by hand pre-lift.
4029    // Peer to the sibling `is_being_deleted_*` +
4030    // `observed_phase_*` pin families — all three primitives project a
4031    // wire-format `Option<T>` slot into a `Copy` inner value at ONE
4032    // owner. Fail-before-pass-after granularity: `created_at` did not
4033    // exist pre-lift, so any test invoking it fails to compile pre-lift
4034    // and passes post-lift.
4035
4036    fn creation_stamped_process(t: DateTime<Utc>) -> Process {
4037        let mut p = Process::new("age-anchor", empty_spec());
4038        p.metadata.namespace = Some("prod".into());
4039        p.metadata.creation_timestamp =
4040            Some(k8s_openapi::apimachinery::pkg::apis::meta::v1::Time(t));
4041        p
4042    }
4043
4044    #[test]
4045    fn created_at_returns_none_when_creation_timestamp_is_absent() {
4046        // Missing-slot corner pin: the primitive collapses the
4047        // no-creation-timestamp case to `None` so the TTL-expiry gate
4048        // at `lifetime_clock::evaluate` short-circuits its inner
4049        // `if let Some(...)` branch (no elapsed computation), the
4050        // requeue-budget picker returns its default sleep, and the
4051        // stable-name arbiter's `.unwrap_or_else(Utc::now)` tail
4052        // synthesizes a "just created" anchor at its own site. Matches
4053        // the pre-lift `.as_ref().map(|t| t.0)` chain's `None`
4054        // byte-identically at every consumer's downstream tail.
4055        let mut p = Process::new("api", empty_spec());
4056        p.metadata.creation_timestamp = None;
4057        assert!(p.created_at().is_none());
4058    }
4059
4060    #[test]
4061    fn created_at_returns_some_datetime_when_slot_is_populated() {
4062        // Populated-slot corner pin: with a populated
4063        // `metadata.creationTimestamp` slot, the primitive unwraps the
4064        // wire-format `Time` newtype to its inner `DateTime<Utc>` and
4065        // returns it as `Some(datetime)` — hiding the `.0` field-access
4066        // every pre-lift consumer restated to reach the underlying
4067        // instant.
4068        let anchor = Utc::now() - chrono::Duration::seconds(300);
4069        let p = creation_stamped_process(anchor);
4070        assert_eq!(p.created_at(), Some(anchor));
4071    }
4072
4073    #[test]
4074    fn created_at_is_a_pure_projection() {
4075        // Purity pin: two consecutive calls return byte-identical
4076        // `Option<DateTime<Utc>>` values (no lazy materialization, no
4077        // interior mutation of `self`). Peer to the sibling
4078        // `is_being_deleted_is_a_pure_projection` +
4079        // `observed_phase_is_a_pure_projection` pins; all three bind
4080        // the pure-projection discipline on the ONE substrate accessor
4081        // per metadata / status slot.
4082        let anchor = Utc::now();
4083        let p = creation_stamped_process(anchor);
4084        let a = p.created_at();
4085        let b = p.created_at();
4086        assert_eq!(a, b);
4087        assert_eq!(a, Some(anchor));
4088    }
4089
4090    #[test]
4091    fn created_at_matches_pre_lift_creation_timestamp_chain_shape() {
4092        // Parity pin: sweeps the two corners every pre-lift consumer
4093        // plausibly encountered (missing slot, populated slot) and
4094        // compares the substrate call against a hand-authored pre-lift
4095        // chain byte-identically. A regression that reshaped either
4096        // corner (returning `Some(Utc::now())` on the missing slot,
4097        // returning a rounded / truncated timestamp on the populated
4098        // slot) would surface here rather than as silent operator-
4099        // facing skew between the TTL-expiry gate, the requeue-budget
4100        // picker, and the stable-name claim-arbiter tie-break on the
4101        // SAME `Process` within one reconcile pass.
4102        fn pre_lift(p: &Process) -> Option<DateTime<Utc>> {
4103            p.metadata.creation_timestamp.as_ref().map(|t| t.0)
4104        }
4105        // Missing slot.
4106        let mut p = Process::new("x", empty_spec());
4107        p.metadata.creation_timestamp = None;
4108        assert_eq!(p.created_at(), pre_lift(&p));
4109        // Populated slot.
4110        let anchor = Utc::now() - chrono::Duration::seconds(42);
4111        let p = creation_stamped_process(anchor);
4112        assert_eq!(p.created_at(), pre_lift(&p));
4113    }
4114
4115    #[test]
4116    fn created_at_composes_with_signed_duration_since_at_ttl_gate() {
4117        // Call-site-shape pin: the `lifetime_clock::evaluate` TTL-
4118        // expiry gate composes `now.signed_duration_since(creation)`
4119        // where `creation` is the `DateTime<Utc>` returned by this
4120        // primitive's `Some` corner. A regression that returned a
4121        // per-callsite `Local` timezone (or that stripped the timezone
4122        // marker) would break the arithmetic silently. This pin
4123        // computes the elapsed duration byte-identically against the
4124        // pre-lift `.map(|t| t.0)` chain so a timezone drift surfaces
4125        // here rather than as silent skew at the TTL-expiry decision
4126        // on the SAME `Process` within one reconcile pass.
4127        let now = Utc::now();
4128        let anchor = now - chrono::Duration::seconds(120);
4129        let p = creation_stamped_process(anchor);
4130        let via_primitive = p.created_at().expect("populated slot");
4131        let via_pre_lift = p
4132            .metadata
4133            .creation_timestamp
4134            .as_ref()
4135            .map(|t| t.0)
4136            .expect("populated slot");
4137        assert_eq!(
4138            now.signed_duration_since(via_primitive),
4139            now.signed_duration_since(via_pre_lift)
4140        );
4141    }
4142}