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
1091/// Process status — every field optional until the reconciler writes it.
1092#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
1093#[serde(rename_all = "camelCase")]
1094pub struct ProcessStatus {
1095    /// Hierarchical PID path — e.g., `"seph.1.7"`.
1096    #[serde(default, skip_serializing_if = "Option::is_none")]
1097    pub pid: Option<String>,
1098
1099    /// Parent PID path (mirror of `spec.identity.parent`, resolved at fork).
1100    #[serde(default, skip_serializing_if = "Option::is_none")]
1101    pub parent: Option<String>,
1102
1103    /// Direct children's PID paths.
1104    #[serde(default)]
1105    pub children: Vec<String>,
1106
1107    /// Resolved identity (name + content hash).
1108    #[serde(default, skip_serializing_if = "Option::is_none")]
1109    pub identity: Option<Identity>,
1110
1111    /// Current phase.
1112    #[serde(default)]
1113    pub phase: ProcessPhase,
1114
1115    /// When the process entered the current phase.
1116    #[serde(default, skip_serializing_if = "Option::is_none")]
1117    pub phase_since: Option<DateTime<Utc>>,
1118
1119    /// Three-pillar attestation (written at end of every successful cycle).
1120    #[serde(default, skip_serializing_if = "Option::is_none")]
1121    pub attestation: Option<ProcessAttestation>,
1122
1123    /// FluxCD resources currently owned by this Process.
1124    #[serde(default)]
1125    pub flux_resources: Vec<FluxResourceRef>,
1126
1127    /// Boundary verification state.
1128    #[serde(default)]
1129    pub boundary: BoundaryStatus,
1130
1131    /// Compliance summary at the latest attestation.
1132    #[serde(default)]
1133    pub compliance: ComplianceStatus,
1134
1135    /// Pending signals (delivered, not yet handled).
1136    #[serde(default)]
1137    pub signal_queue: Vec<ProcessSignal>,
1138
1139    /// Standard K8s Conditions.
1140    #[serde(default)]
1141    pub conditions: Vec<ProcessCondition>,
1142
1143    /// Human-readable last status message.
1144    #[serde(default, skip_serializing_if = "Option::is_none")]
1145    pub message: Option<String>,
1146
1147    /// Exit code (only set on Failed / Reaped).
1148    #[serde(default, skip_serializing_if = "Option::is_none")]
1149    pub exit_code: Option<i32>,
1150}
1151
1152#[cfg(test)]
1153mod tests {
1154    use super::*;
1155    use crate::classification::{ConvergencePointType, SubstrateType};
1156    use crate::intent::NixIntent;
1157
1158    #[test]
1159    fn minimal_spec_serializes() {
1160        let spec = ProcessSpec {
1161            identity: IdentitySpec::default(),
1162            classification: Classification {
1163                point_type: ConvergencePointType::Gate,
1164                substrate: SubstrateType::Observability,
1165                horizon: Default::default(),
1166                calm: Default::default(),
1167                data_classification: Default::default(),
1168            },
1169            intent: Intent {
1170                nix: Some(NixIntent {
1171                    flake_ref: "github:pleme-io/k8s".into(),
1172                    attribute: "obs".into(),
1173                    system: None,
1174                    attic_cache: None,
1175                    extra_args: vec![],
1176                    delegate_to_nix_build: false,
1177                }),
1178                ..Intent::default()
1179            },
1180            boundary: Default::default(),
1181            compliance: Default::default(),
1182            depends_on: vec![],
1183            signals: Default::default(),
1184            lifetime: Default::default(),
1185            routing: None,
1186            encapsulates: None,
1187            suspended: false,
1188        };
1189        let yaml = serde_yaml::to_string(&spec).unwrap();
1190        assert!(yaml.contains("pointType: Gate"));
1191        assert!(yaml.contains("substrate: Observability"));
1192        assert!(yaml.contains("flakeRef: github:pleme-io/k8s"));
1193    }
1194
1195    // ─── Process::coordinates_or_defaults substrate pins ────────────────
1196    //
1197    // Pins the (namespace, name) coordinate-primitive family on the
1198    // (metadata slot × fallback shape) axis. Fail-before-pass-after
1199    // granularity: a regression that flipped either fallback string,
1200    // swapped the return-tuple axis order, or dropped the
1201    // `Option::as_deref` unwrap surfaces here rather than as silent
1202    // drift at every downstream annotation writer / claim-arbiter row
1203    // builder / render owner-metadata seed.
1204
1205    fn empty_spec() -> ProcessSpec {
1206        ProcessSpec {
1207            identity: IdentitySpec::default(),
1208            classification: Classification {
1209                point_type: ConvergencePointType::Gate,
1210                substrate: SubstrateType::Compute,
1211                horizon: Default::default(),
1212                calm: Default::default(),
1213                data_classification: Default::default(),
1214            },
1215            intent: Intent::default(),
1216            boundary: Default::default(),
1217            compliance: Default::default(),
1218            depends_on: vec![],
1219            signals: Default::default(),
1220            lifetime: Default::default(),
1221            routing: None,
1222            encapsulates: None,
1223            suspended: false,
1224        }
1225    }
1226
1227    #[test]
1228    fn default_namespace_constant_is_k8s_canonical_default() {
1229        // Pins the load-bearing convention that this primitive's
1230        // namespace fallback matches K8s's own implicit-namespace
1231        // spelling. A regression that renamed this to "kube-system"
1232        // or any other K8s-reserved name would silently misroute
1233        // every downstream namespaced-Api call on a Process without
1234        // a metadata.namespace.
1235        assert_eq!(Process::DEFAULT_NAMESPACE, "default");
1236    }
1237
1238    #[test]
1239    fn unnamed_placeholder_constant_matches_prior_annotation_writer_fallback() {
1240        // Pins the load-bearing convention that this primitive's name
1241        // fallback matches the exact spelling every annotation writer
1242        // (tatara-reconciler::ssapply::inject_annotations,
1243        // tatara-reconciler::render::render, and
1244        // tatara-reconciler::table_controller's claim-row builder)
1245        // was hand-authoring pre-lift ("unnamed", NOT "<unnamed>" or
1246        // ""). A regression that renamed this would break the
1247        // annotation-writer / claim-arbiter grep contract silently.
1248        assert_eq!(Process::UNNAMED_PLACEHOLDER, "unnamed");
1249    }
1250
1251    #[test]
1252    fn namespace_or_default_falls_back_when_metadata_namespace_is_none() {
1253        let mut p = Process::new("some-proc", empty_spec());
1254        p.metadata.namespace = None;
1255        assert_eq!(p.namespace_or_default(), Process::DEFAULT_NAMESPACE);
1256    }
1257
1258    #[test]
1259    fn namespace_or_default_returns_metadata_slice_when_some() {
1260        let mut p = Process::new("some-proc", empty_spec());
1261        p.metadata.namespace = Some("prod-app".into());
1262        assert_eq!(p.namespace_or_default(), "prod-app");
1263    }
1264
1265    #[test]
1266    fn name_or_placeholder_falls_back_when_metadata_name_is_none() {
1267        let mut p = Process::new("real-name", empty_spec());
1268        p.metadata.name = None;
1269        assert_eq!(p.name_or_placeholder(), Process::UNNAMED_PLACEHOLDER);
1270    }
1271
1272    #[test]
1273    fn name_or_placeholder_returns_metadata_slice_when_some() {
1274        let p = Process::new("api-gateway", empty_spec());
1275        assert_eq!(p.name_or_placeholder(), "api-gateway");
1276    }
1277
1278    #[test]
1279    fn coordinates_or_defaults_composes_both_halves() {
1280        // Both slots present — returns metadata slices in
1281        // (namespace, name) axis order.
1282        let mut p = Process::new("api", empty_spec());
1283        p.metadata.namespace = Some("staging".into());
1284        assert_eq!(p.coordinates_or_defaults(), ("staging", "api"));
1285    }
1286
1287    #[test]
1288    fn coordinates_or_defaults_falls_back_on_both_slots() {
1289        // Both slots None — returns (DEFAULT_NAMESPACE,
1290        // UNNAMED_PLACEHOLDER) in axis order.
1291        let mut p = Process::new("scratch", empty_spec());
1292        p.metadata.name = None;
1293        p.metadata.namespace = None;
1294        assert_eq!(
1295            p.coordinates_or_defaults(),
1296            (Process::DEFAULT_NAMESPACE, Process::UNNAMED_PLACEHOLDER)
1297        );
1298    }
1299
1300    #[test]
1301    fn coordinates_or_defaults_mixes_slotted_and_fallback_halves() {
1302        // Namespace set, name missing — the (namespace, name) tuple
1303        // pins each half independently. A regression that returned
1304        // BOTH fallbacks when EITHER metadata slot was None would
1305        // surface here rather than at every downstream reader.
1306        let mut p = Process::new("kept-name", empty_spec());
1307        p.metadata.namespace = Some("prod".into());
1308        assert_eq!(p.coordinates_or_defaults(), ("prod", "kept-name"));
1309
1310        // Name set, namespace missing — the peer corner.
1311        let mut q = Process::new("api", empty_spec());
1312        q.metadata.namespace = None;
1313        assert_eq!(
1314            q.coordinates_or_defaults(),
1315            (Process::DEFAULT_NAMESPACE, "api")
1316        );
1317    }
1318
1319    // ─── Process::owned_coordinates_or_err substrate pins ──────────────
1320    //
1321    // Pins the owned + name-required peer of the coordinate-primitive
1322    // family on the (return-form × name gate) axis pair. Fail-before-
1323    // pass-after granularity: a regression that flipped the namespace
1324    // fallback string, dropped the `Option::clone` unwrap, changed the
1325    // return-tuple axis order, or altered the "Process has no
1326    // metadata.name" error wording surfaces here rather than as silent
1327    // drift at every pre-lift caller (10 sites in
1328    // `tatara-reconciler::phase_machine` + 2 sites in
1329    // `tatara-reconciler::signals` pre-lift).
1330
1331    #[test]
1332    fn owned_coordinates_or_err_returns_owned_strings_when_both_slots_present() {
1333        // Happy path — both slots populated, method returns owned
1334        // Strings in (namespace, name) axis order.
1335        let mut p = Process::new("api-gateway", empty_spec());
1336        p.metadata.namespace = Some("prod-app".into());
1337        let (ns, name) = p.owned_coordinates_or_err().unwrap();
1338        assert_eq!(ns, "prod-app");
1339        assert_eq!(name, "api-gateway");
1340        // Ownership pin: type inference above binds ns/name as
1341        // owned Strings — a regression that returned &str would
1342        // fail to compile at the following .push() call. This
1343        // holds the "owned" half of the primitive's contract.
1344        let mut owned_ns = ns;
1345        owned_ns.push_str("-mutated");
1346        assert_eq!(owned_ns, "prod-app-mutated");
1347    }
1348
1349    #[test]
1350    fn owned_coordinates_or_err_falls_back_on_namespace_but_returns_owned_name() {
1351        // Namespace absent → DEFAULT_NAMESPACE. Name present → owned.
1352        let p = Process::new("api", empty_spec());
1353        // Process::new leaves metadata.namespace = None by default.
1354        let (ns, name) = p.owned_coordinates_or_err().unwrap();
1355        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
1356        assert_eq!(name, "api");
1357    }
1358
1359    #[test]
1360    fn owned_coordinates_or_err_errors_when_metadata_name_absent_regardless_of_namespace() {
1361        // Name absent → Err, REGARDLESS of whether the namespace is
1362        // populated. The name gate is strictly on `metadata.name` and
1363        // does NOT fall back to `Self::UNNAMED_PLACEHOLDER` (that
1364        // fallback is on the peer `coordinates_or_defaults`, which
1365        // exists precisely for consumers that can tolerate a
1366        // display placeholder).
1367        for ns_slot in [None, Some("prod".to_string())] {
1368            let mut p = Process::new("scratch", empty_spec());
1369            p.metadata.name = None;
1370            p.metadata.namespace = ns_slot.clone();
1371            let err = p.owned_coordinates_or_err().unwrap_err();
1372            assert!(
1373                err.to_string().contains("metadata.name"),
1374                "err on missing name (ns={ns_slot:?}) should mention metadata.name; got {err}"
1375            );
1376        }
1377    }
1378
1379    #[test]
1380    fn owned_coordinates_or_err_error_message_matches_pre_lift_reconciler_wording() {
1381        // Load-bearing wording pin — every pre-lift `tatara-reconciler`
1382        // helper (`phase_machine::namespace_and_name`,
1383        // `signals::ingest`, `signals::consume_effect`) errored with
1384        // EXACTLY this wording. Post-lift the substrate owner produces
1385        // the same wording so log-line / test greps that anchored on
1386        // it keep matching, and no operator-visible message drift
1387        // lands as a side effect of the substrate move.
1388        let mut p = Process::new("scratch", empty_spec());
1389        p.metadata.name = None;
1390        let err = p.owned_coordinates_or_err().unwrap_err();
1391        assert_eq!(err.to_string(), "Process has no metadata.name");
1392    }
1393
1394    #[test]
1395    fn owned_coordinates_or_err_namespace_fallback_matches_default_namespace_const() {
1396        // Byte-identity pin between the owned form's namespace
1397        // fallback and the workspace-wide `DEFAULT_NAMESPACE` const.
1398        // A regression that spelled this fallback as any other
1399        // string ("kube-system", "", "default-ns") would silently
1400        // misroute every downstream namespaced-Api call on a
1401        // Process without a metadata.namespace — surfaces here
1402        // rather than at every kube-rs API caller.
1403        let mut p = Process::new("api", empty_spec());
1404        p.metadata.namespace = None;
1405        let (ns, _) = p.owned_coordinates_or_err().unwrap();
1406        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
1407    }
1408
1409    #[test]
1410    fn owned_coordinates_or_err_matches_pre_lift_reconciler_helper_shape() {
1411        // Byte-identical parity pin between the owned + name-required
1412        // primitive here and the pre-lift `tatara-reconciler` helper
1413        // shape — the exact 2-slot unwrap chain each pre-lift caller
1414        // spelled by hand:
1415        //
1416        //   let ns = p.metadata.namespace.clone().unwrap_or_else(|| "default".into());
1417        //   let name = p.metadata.name.clone().ok_or_else(|| anyhow!(...))?;
1418        //   Ok((ns, name))
1419        //
1420        // Sweeps every corner every callsite plausibly encounters
1421        // (both slots present, namespace absent, name absent, both
1422        // absent). A regression that inserted a normalization step
1423        // at the primitive that the pre-lift chain does NOT apply —
1424        // or vice versa — surfaces here rather than as silent drift
1425        // between the 12 pre-lift consumer callsites and the ONE
1426        // substrate owner they now route through.
1427        fn pre_lift(p: &Process) -> anyhow::Result<(String, String)> {
1428            let ns = p
1429                .metadata
1430                .namespace
1431                .clone()
1432                .unwrap_or_else(|| "default".into());
1433            let name = p
1434                .metadata
1435                .name
1436                .clone()
1437                .ok_or_else(|| anyhow::anyhow!("Process has no metadata.name"))?;
1438            Ok((ns, name))
1439        }
1440        // Both present.
1441        let mut p = Process::new("api", empty_spec());
1442        p.metadata.namespace = Some("prod".into());
1443        assert_eq!(p.owned_coordinates_or_err().unwrap(), pre_lift(&p).unwrap());
1444        // Namespace absent.
1445        let p = Process::new("api", empty_spec());
1446        assert_eq!(p.owned_coordinates_or_err().unwrap(), pre_lift(&p).unwrap());
1447        // Name absent → both variants error with the same wording.
1448        let mut p = Process::new("api", empty_spec());
1449        p.metadata.name = None;
1450        p.metadata.namespace = Some("prod".into());
1451        assert_eq!(
1452            p.owned_coordinates_or_err().unwrap_err().to_string(),
1453            pre_lift(&p).unwrap_err().to_string(),
1454        );
1455        // Both absent → still errors on the name gate.
1456        let mut p = Process::new("api", empty_spec());
1457        p.metadata.name = None;
1458        p.metadata.namespace = None;
1459        assert_eq!(
1460            p.owned_coordinates_or_err().unwrap_err().to_string(),
1461            pre_lift(&p).unwrap_err().to_string(),
1462        );
1463    }
1464
1465    #[test]
1466    fn owned_coordinates_or_err_axis_order_matches_coordinates_or_defaults() {
1467        // Cross-primitive coherence pin between the owned + name-
1468        // required form and the borrow + name-defaulted peer:
1469        // (namespace, name) axis order is IDENTICAL across both
1470        // return-forms. A regression that swapped the tuple slots on
1471        // only ONE of the two primitives would silently misroute
1472        // every consumer that picked between the two forms based on
1473        // its callsite's ownership needs. The pin re-reads both
1474        // primitives at test time so the equality holds iff both
1475        // live paths are the current implementation.
1476        let mut p = Process::new("app", empty_spec());
1477        p.metadata.namespace = Some("infra".into());
1478        let (borrow_ns, borrow_name) = p.coordinates_or_defaults();
1479        let (owned_ns, owned_name) = p.owned_coordinates_or_err().unwrap();
1480        assert_eq!(owned_ns, borrow_ns);
1481        assert_eq!(owned_name, borrow_name);
1482        // Explicit slot labels — pins the (namespace, name) axis
1483        // order as opposed to (name, namespace).
1484        assert_eq!(owned_ns, "infra"); // NOT "app"
1485        assert_eq!(owned_name, "app"); // NOT "infra"
1486    }
1487
1488    // ─── Process::coordinates_or_none substrate pins ──────────────────
1489    //
1490    // Pins the borrow + name-required peer of the coordinate-primitive
1491    // family on the (return-form × name-gate) axis pair. Closes the
1492    // corner previously left open (borrow + name-required) so the
1493    // three consumer shapes (child-Process delete-fan-out at
1494    // `phase_machine::handle_exiting`, claim-arbiter probe at
1495    // `phase_machine::process_holds_any_claim`, any future non-fatal
1496    // skip site) route through ONE primitive rather than three hand-
1497    // authored empty-string / `unwrap_or_default()` sentinel chains.
1498    // Fail-before-pass-after granularity: a regression that flipped
1499    // the namespace fallback, swapped the return-tuple axis order,
1500    // returned an owned form, or promoted a missing name to an error
1501    // rather than `None` surfaces here rather than as silent drift at
1502    // every borrow + name-required consumer.
1503
1504    #[test]
1505    fn coordinates_or_none_returns_slices_when_both_slots_present() {
1506        // Happy path — both slots populated, method returns borrowed
1507        // (&str, &str) in (namespace, name) axis order wrapped in
1508        // `Some`.
1509        let mut p = Process::new("api-gateway", empty_spec());
1510        p.metadata.namespace = Some("prod-app".into());
1511        let (ns, name) = p.coordinates_or_none().expect("Some when name set");
1512        assert_eq!(ns, "prod-app");
1513        assert_eq!(name, "api-gateway");
1514    }
1515
1516    #[test]
1517    fn coordinates_or_none_falls_back_on_namespace_but_returns_name_slice() {
1518        // Namespace absent → DEFAULT_NAMESPACE (shared with the peer
1519        // `coordinates_or_defaults` + `namespace_or_default`). Name
1520        // present → the metadata slice, wrapped in `Some`.
1521        let mut p = Process::new("api", empty_spec());
1522        p.metadata.namespace = None;
1523        let (ns, name) = p.coordinates_or_none().expect("Some when name set");
1524        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
1525        assert_eq!(name, "api");
1526    }
1527
1528    #[test]
1529    fn coordinates_or_none_returns_none_when_metadata_name_absent_regardless_of_namespace() {
1530        // Name absent → `None`, REGARDLESS of whether the namespace
1531        // slot is populated. The name gate is strictly on
1532        // `metadata.name` and does NOT fall back to
1533        // `Self::UNNAMED_PLACEHOLDER` (that fallback is on the peer
1534        // `coordinates_or_defaults`, which exists precisely for
1535        // consumers that tolerate a display placeholder). Peer to
1536        // `owned_coordinates_or_err_errors_when_metadata_name_absent_regardless_of_namespace`
1537        // on the sibling primitive; a regression that widened THIS
1538        // form to substitute the placeholder while leaving the owned
1539        // form strict would silently drift the two borrow-form
1540        // primitives out of the coherence the family carries.
1541        for ns_slot in [None, Some("prod".to_string())] {
1542            let mut p = Process::new("scratch", empty_spec());
1543            p.metadata.name = None;
1544            p.metadata.namespace = ns_slot.clone();
1545            assert!(
1546                p.coordinates_or_none().is_none(),
1547                "coordinates_or_none must be None on missing name (ns={ns_slot:?})",
1548            );
1549        }
1550    }
1551
1552    #[test]
1553    fn coordinates_or_none_namespace_fallback_matches_default_namespace_const() {
1554        // Byte-identity pin between the borrow + name-required form's
1555        // namespace fallback and the workspace-wide `DEFAULT_NAMESPACE`
1556        // const. Sibling to
1557        // `owned_coordinates_or_err_namespace_fallback_matches_default_namespace_const`
1558        // on the peer primitive — the two forms MUST substitute the
1559        // same fallback string, else a consumer that switches between
1560        // them based on its ownership need silently observes a
1561        // different namespace-fallback shape as a side effect.
1562        let mut p = Process::new("api", empty_spec());
1563        p.metadata.namespace = None;
1564        let (ns, _) = p.coordinates_or_none().unwrap();
1565        assert_eq!(ns, Process::DEFAULT_NAMESPACE);
1566    }
1567
1568    #[test]
1569    fn coordinates_or_none_axis_order_matches_coordinates_or_defaults_when_name_present() {
1570        // Cross-primitive coherence pin between the two borrow-form
1571        // primitives: when the name is present, the (namespace, name)
1572        // return-tuple axis order is IDENTICAL across the two forms,
1573        // and the returned slices are the SAME `&str` view onto the
1574        // same metadata slots. A regression that swapped the tuple
1575        // slots on ONE form would silently misroute every consumer
1576        // that picked between the two forms based on its name-gate
1577        // need. The pin re-reads both primitives at test time so the
1578        // equality holds iff both live paths are the current
1579        // implementation.
1580        let mut p = Process::new("app", empty_spec());
1581        p.metadata.namespace = Some("infra".into());
1582        let (defaulted_ns, defaulted_name) = p.coordinates_or_defaults();
1583        let (required_ns, required_name) = p.coordinates_or_none().unwrap();
1584        assert_eq!(defaulted_ns, required_ns);
1585        assert_eq!(defaulted_name, required_name);
1586        // Explicit slot labels — pins the (namespace, name) axis order
1587        // as opposed to (name, namespace).
1588        assert_eq!(required_ns, "infra"); // NOT "app"
1589        assert_eq!(required_name, "app"); // NOT "infra"
1590    }
1591
1592    #[test]
1593    fn coordinates_or_none_axis_pair_diverges_from_coordinates_or_defaults_on_missing_name() {
1594        // Divergence pin between the two borrow-form primitives when
1595        // the name gate fires: `coordinates_or_defaults` substitutes
1596        // the display placeholder AND still returns a tuple;
1597        // `coordinates_or_none` returns `None`. A regression that
1598        // collapsed the two behaviors (either by dropping the gate
1599        // from the required form or by adding a `None` corner to the
1600        // defaulted form) would blur the axis pair's whole reason to
1601        // exist as two peer primitives.
1602        let mut p = Process::new("scratch", empty_spec());
1603        p.metadata.name = None;
1604        p.metadata.namespace = Some("prod".into());
1605        // Defaulted form: substitutes placeholder, no gate.
1606        assert_eq!(
1607            p.coordinates_or_defaults(),
1608            ("prod", Process::UNNAMED_PLACEHOLDER)
1609        );
1610        // Required form: gate fires, `None`.
1611        assert!(p.coordinates_or_none().is_none());
1612    }
1613
1614    #[test]
1615    fn coordinates_or_none_matches_pre_lift_reconciler_helper_shape() {
1616        // Byte-identical parity pin between the borrow + name-required
1617        // primitive here and the pre-lift `tatara-reconciler` helper
1618        // shapes — the exact 2-slot unwrap + gate chains each pre-lift
1619        // caller spelled by hand (`phase_machine::process_holds_any_claim`
1620        // spelled it as `unwrap_or("")` + `is_empty` early-return;
1621        // `phase_machine::handle_exiting`'s child-fan-out spelled it
1622        // as `unwrap_or_default()` + implicit no-op delete on the
1623        // empty API-path). Sweeps every corner every callsite plausibly
1624        // encounters (both slots present, namespace absent, name
1625        // absent + ns present, both absent). A regression that
1626        // inserted a normalization step at the primitive the pre-lift
1627        // chain does NOT apply — or vice versa — surfaces here rather
1628        // than as silent drift between the pre-lift consumer sites
1629        // and the ONE substrate owner they now route through.
1630        fn pre_lift_holds_any_claim(p: &Process) -> Option<(&str, &str)> {
1631            let ns = p.metadata.namespace.as_deref().unwrap_or("default");
1632            let name = p.metadata.name.as_deref().unwrap_or("");
1633            if name.is_empty() {
1634                return None;
1635            }
1636            Some((ns, name))
1637        }
1638        // Both present.
1639        let mut p = Process::new("api", empty_spec());
1640        p.metadata.namespace = Some("prod".into());
1641        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
1642        // Namespace absent.
1643        let p = Process::new("api", empty_spec());
1644        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
1645        // Name absent → both variants return `None` regardless of ns.
1646        let mut p = Process::new("api", empty_spec());
1647        p.metadata.name = None;
1648        p.metadata.namespace = Some("prod".into());
1649        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
1650        // Both absent → still `None` on the name gate.
1651        let mut p = Process::new("api", empty_spec());
1652        p.metadata.name = None;
1653        p.metadata.namespace = None;
1654        assert_eq!(p.coordinates_or_none(), pre_lift_holds_any_claim(&p));
1655    }
1656
1657    #[test]
1658    fn coordinates_or_none_axis_order_matches_owned_coordinates_or_err_on_happy_path() {
1659        // Cross-primitive coherence pin at the sibling corner: when
1660        // BOTH slots are present, the borrow + name-required form
1661        // (this method) and the owned + name-required peer
1662        // (`owned_coordinates_or_err`) return the SAME `(ns, name)`
1663        // pair — the axis order is IDENTICAL and neither primitive
1664        // silently applies a normalization the other omits. A
1665        // regression that skewed one form's normalization would
1666        // surface here rather than as silent drift between the two
1667        // name-required corners of the primitive family.
1668        let mut p = Process::new("app", empty_spec());
1669        p.metadata.namespace = Some("infra".into());
1670        let (borrow_ns, borrow_name) = p.coordinates_or_none().unwrap();
1671        let (owned_ns, owned_name) = p.owned_coordinates_or_err().unwrap();
1672        assert_eq!(borrow_ns, owned_ns.as_str());
1673        assert_eq!(borrow_name, owned_name.as_str());
1674    }
1675
1676    #[test]
1677    fn coordinates_or_defaults_axis_order_matches_qualified_process_ref() {
1678        // Pins the load-bearing convention that the return-tuple
1679        // axis order is (namespace, name) — the exact positional
1680        // argument order the substrate's paired-composer primitive
1681        // `tatara_reconciler::ssapply::qualified_process_ref(ns,
1682        // name)` consumes. A regression that swapped the tuple
1683        // slots would silently misroute every annotation writer /
1684        // claim-arbiter row / owner-metadata seed built by feeding
1685        // this pair into the composer — every downstream `<ns>/
1686        // <name>` grep would suddenly see `<name>/<ns>`. The test
1687        // verifies the tuple's first slot is what a hand-authored
1688        // `.metadata.namespace.as_deref()...` produced pre-lift, and
1689        // the second slot is what `.metadata.name.as_deref()...`
1690        // produced.
1691        let mut p = Process::new("app", empty_spec());
1692        p.metadata.namespace = Some("infra".into());
1693        let (ns, name) = p.coordinates_or_defaults();
1694        assert_eq!(ns, "infra"); // NOT "app"
1695        assert_eq!(name, "app"); // NOT "infra"
1696    }
1697
1698    // ─── Process::annotation substrate pins ────────────────────────────
1699    //
1700    // Pins the borrow-form annotation-lookup primitive that owns the
1701    // 3-line `.metadata.annotations.as_ref().and_then(|m| m.get(KEY))`
1702    // chain three hand-authored sites restated by hand pre-lift:
1703    // `tatara-reconciler::signals::ingest` (SIGNAL),
1704    // `tatara-reconciler::phase_machine::released_from_annotation`
1705    // (RELEASED_FROM), and
1706    // `tatara-pool-reconciler::controller_pool::process_belongs_to_pool`
1707    // (POOL). Fail-before-pass-after granularity: a regression that
1708    // widened the missing-`annotations` corner (returning `Some("")`
1709    // instead of `None`), promoted a missing key to an error, dropped
1710    // the borrow-form return, or changed the two swallowed corners'
1711    // shared collapse to `None` surfaces here rather than as silent
1712    // drift at the three consumer sites.
1713    fn process_with_annotation(key: &str, value: &str) -> Process {
1714        let mut p = Process::new("some-proc", empty_spec());
1715        let mut anns = std::collections::BTreeMap::new();
1716        anns.insert(key.to_string(), value.to_string());
1717        p.metadata.annotations = Some(anns);
1718        p
1719    }
1720
1721    #[test]
1722    fn annotation_returns_none_when_metadata_annotations_is_none() {
1723        // Missing-`annotations` corner: a Process with no annotations
1724        // block at all returns `None` for every key. Peer to
1725        // `observed_flux_resources_returns_empty_slice_when_status_is_none`
1726        // on the status-projection axis; both primitives collapse the
1727        // outer `Option` corner rather than requiring each consumer
1728        // to spell the guard by hand.
1729        let mut p = Process::new("scratch", empty_spec());
1730        p.metadata.annotations = None;
1731        assert!(p.annotation("tatara.pleme.io/signal").is_none());
1732        assert!(p.annotation("tatara.pleme.io/pool").is_none());
1733        assert!(p.annotation("").is_none());
1734    }
1735
1736    #[test]
1737    fn annotation_returns_none_when_key_absent_from_populated_map() {
1738        // Missing-key corner: annotations block populated with OTHER
1739        // keys returns `None` for the queried key. Symmetric with the
1740        // missing-`annotations` corner — both corners collapse to the
1741        // same `None`, matching the pre-lift `.and_then(...)`
1742        // behavior every consumer relied on.
1743        let p = process_with_annotation("tatara.pleme.io/other", "value");
1744        assert!(p.annotation("tatara.pleme.io/signal").is_none());
1745        assert!(p.annotation("").is_none());
1746    }
1747
1748    #[test]
1749    fn annotation_returns_borrowed_slice_when_key_present() {
1750        // Happy path: annotations block populated + key present →
1751        // `Some(&str)` borrowed from the underlying `String` in the
1752        // map. A regression that returned an owned `String` (defeating
1753        // the primitive's role as a zero-copy projection) would
1754        // surface at the lifetime of the returned reference — the
1755        // `&str` outlives the borrow of `&p` here.
1756        let p = process_with_annotation("tatara.pleme.io/signal", "SIGHUP");
1757        assert_eq!(p.annotation("tatara.pleme.io/signal"), Some("SIGHUP"));
1758    }
1759
1760    #[test]
1761    fn annotation_returns_borrowed_empty_string_slice_when_value_is_empty() {
1762        // Edge corner between the missing-key `None` and the present-
1763        // key `Some("")` — a Process whose annotation is EXPLICITLY
1764        // set to an empty string returns `Some("")`, NOT `None`. A
1765        // regression that normalized the empty-string value to `None`
1766        // (a plausible "defensive" simplification) would silently
1767        // reshape the corner every callsite pre-lift kept distinct via
1768        // `.cloned().unwrap_or_default()` (which collapses BOTH to
1769        // `""`) or `.map(String::as_str)` (which keeps them distinct
1770        // as `None` vs `Some("")`).
1771        let p = process_with_annotation("tatara.pleme.io/signal", "");
1772        assert_eq!(p.annotation("tatara.pleme.io/signal"), Some(""));
1773    }
1774
1775    #[test]
1776    fn annotation_is_a_pure_projection() {
1777        // Purity pin — repeated calls return equal results and the
1778        // primitive does not mutate `self`. Peer to
1779        // `observed_flux_resources_is_a_pure_projection` on the
1780        // status-projection axis.
1781        let p = process_with_annotation("tatara.pleme.io/released-from", "Attested");
1782        let a = p.annotation("tatara.pleme.io/released-from");
1783        let b = p.annotation("tatara.pleme.io/released-from");
1784        assert_eq!(a, b);
1785        assert_eq!(a, Some("Attested"));
1786    }
1787
1788    #[test]
1789    fn annotation_matches_pre_lift_reconciler_chain_shape() {
1790        // Byte-identical parity pin between the borrow-form primitive
1791        // here and the pre-lift `tatara-reconciler` / `tatara-pool-
1792        // reconciler` chain shape — the exact 3-line
1793        // `.metadata.annotations.as_ref().and_then(|m| m.get(KEY))
1794        // .map(String::as_str)` incantation each pre-lift caller
1795        // spelled by hand (three variants of tail collapsed onto ONE
1796        // borrow-form primitive here; each caller reapplies its own
1797        // tail at its own site). Sweeps every corner (missing
1798        // annotations map, missing key, present key with value,
1799        // present key with empty value) so a regression that inserted
1800        // a normalization at the primitive the pre-lift chain does
1801        // NOT apply — or vice versa — surfaces here rather than as
1802        // silent drift between the ONE substrate owner and the three
1803        // consumer sites.
1804        fn pre_lift<'a>(p: &'a Process, key: &str) -> Option<&'a str> {
1805            p.metadata
1806                .annotations
1807                .as_ref()
1808                .and_then(|m| m.get(key))
1809                .map(String::as_str)
1810        }
1811        // Missing annotations map.
1812        let mut p = Process::new("x", empty_spec());
1813        p.metadata.annotations = None;
1814        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
1815        // Missing key in populated map.
1816        let p = process_with_annotation("other", "v");
1817        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
1818        // Present key with non-empty value.
1819        let p = process_with_annotation("k", "v");
1820        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
1821        // Present key with explicitly-empty value — the corner
1822        // `.cloned().unwrap_or_default()` collapses to `""` post-tail
1823        // but the primitive-level shape stays `Some("")`.
1824        let p = process_with_annotation("k", "");
1825        assert_eq!(p.annotation("k"), pre_lift(&p, "k"));
1826    }
1827
1828    #[test]
1829    fn annotation_composes_owned_tail_matching_pre_lift_signals_ingest() {
1830        // Pins the exact tail shape `tatara-reconciler::signals::
1831        // ingest` composed pre-lift: an `Option<String>` for the
1832        // downstream `let Some(raw) = raw else { ... }` guard.
1833        // Post-lift the callsite composes `.map(str::to_string)` at
1834        // its own site; this test pins the composition matches the
1835        // pre-lift `.cloned()` tail byte-for-byte on both corners the
1836        // consumer's downstream distinguishes (annotation present →
1837        // `Some(String)`; absent → `None`).
1838        let p = process_with_annotation("tatara.pleme.io/signal", "SIGUSR1");
1839        assert_eq!(
1840            p.annotation("tatara.pleme.io/signal").map(str::to_string),
1841            Some("SIGUSR1".to_string())
1842        );
1843        let mut q = Process::new("y", empty_spec());
1844        q.metadata.annotations = None;
1845        assert_eq!(
1846            q.annotation("tatara.pleme.io/signal").map(str::to_string),
1847            None
1848        );
1849    }
1850
1851    #[test]
1852    fn annotation_composes_default_tail_matching_pre_lift_released_from() {
1853        // Pins the exact tail shape
1854        // `tatara-reconciler::phase_machine::released_from_annotation`
1855        // composed pre-lift: a bare `String` via `.cloned()
1856        // .unwrap_or_default()` for the downstream
1857        // `match v.as_str()` dispatch. Post-lift the callsite matches
1858        // directly on `Option<&str>` (Some("Failed") vs _); this test
1859        // pins that the borrow-form primitive plus the `.unwrap_or("")`
1860        // fallback reproduces the pre-lift bare-string shape on both
1861        // corners.
1862        let p = process_with_annotation("tatara.pleme.io/released-from", "Failed");
1863        assert_eq!(
1864            p.annotation("tatara.pleme.io/released-from").unwrap_or(""),
1865            "Failed"
1866        );
1867        let mut q = Process::new("y", empty_spec());
1868        q.metadata.annotations = None;
1869        assert_eq!(
1870            q.annotation("tatara.pleme.io/released-from").unwrap_or(""),
1871            ""
1872        );
1873    }
1874
1875    #[test]
1876    fn annotation_composes_borrow_equality_tail_matching_pre_lift_pool() {
1877        // Pins the exact tail shape `tatara-pool-reconciler::
1878        // controller_pool::process_belongs_to_pool` composed pre-lift:
1879        // an `Option<&str>` compared with `== Some(pool_name)` for the
1880        // membership gate. Post-lift the callsite composes
1881        // `p.annotation(POOL) == Some(pool_name)` verbatim; this test
1882        // pins that the borrow-form primitive returns exactly the
1883        // shape the equality gate expects.
1884        let p = process_with_annotation("tatara.pleme.io/pool", "demo-pool");
1885        assert_eq!(
1886            p.annotation("tatara.pleme.io/pool") == Some("demo-pool"),
1887            true
1888        );
1889        assert_eq!(p.annotation("tatara.pleme.io/pool") == Some("other"), false);
1890    }
1891
1892    // ─── Process::uid_or_empty substrate pins ──────────────────────────
1893    //
1894    // Pins the borrow-form metadata-projection primitive on the
1895    // `metadata.uid` axis that owns the `.metadata.uid.as_deref()
1896    // .unwrap_or("")` chain the two hand-authored
1897    // `tatara-reconciler::render` sites (`render_routing` +
1898    // `render_export_jobs`) restated by hand pre-lift. Peer to the
1899    // sibling `namespace_or_default_*` + `name_or_placeholder_*` pin
1900    // families on the metadata-slot × fallback-shape axis; all three
1901    // primitives return borrows of an owned-metadata slot with a slot-
1902    // specific fallback baked in (`"default"` for namespace, `"unnamed"`
1903    // for name, `""` for uid — the load-bearing gate value for
1904    // `owner_references_json`'s `is_empty` check). Fail-before-pass-
1905    // after granularity: `uid_or_empty` did not exist pre-lift, so any
1906    // test invoking it fails to compile pre-lift and passes post-lift.
1907
1908    #[test]
1909    fn uid_or_empty_returns_empty_string_when_metadata_uid_is_none() {
1910        // Empty-slot corner pin: the primitive collapses the no-uid
1911        // case to `""`, matching the pre-lift `.as_deref().unwrap_or("")`
1912        // chain's `""` byte-identically at both render consumer sites.
1913        // Semantically corresponds to a Process pre-metadata (fixtured
1914        // in tests, or caught mid-Forking before the API server has
1915        // stamped a `uid`); the downstream `owner_references_json`
1916        // composer gates on this exact `""` sentinel to stamp
1917        // `metadata.ownerReferences: []` rather than emit an owner-ref
1918        // pointing at a placeholder uid.
1919        let mut p = Process::new("scratch", empty_spec());
1920        p.metadata.uid = None;
1921        assert_eq!(p.uid_or_empty(), "");
1922    }
1923
1924    #[test]
1925    fn uid_or_empty_returns_borrowed_str_when_slot_is_populated() {
1926        // Happy-path pin: with a populated `metadata.uid` slot, the
1927        // primitive returns a borrowed `&str` whose contents match the
1928        // persisted `String`. A regression that reshaped / normalized
1929        // / cross-cluster-stripped the uid without touching this pin
1930        // would surface here rather than as silent skew at the two
1931        // `owner_references_json(name, uid)` emitters on the SAME
1932        // Process.
1933        let mut p = Process::new("owned-proc", empty_spec());
1934        p.metadata.uid = Some("uid-abc-123".into());
1935        assert_eq!(p.uid_or_empty(), "uid-abc-123");
1936    }
1937
1938    #[test]
1939    fn uid_or_empty_returns_empty_string_when_slot_is_explicitly_empty_string() {
1940        // Corner between the missing-slot `None` and the explicitly-
1941        // empty-string `Some("")` — both collapse to `""` at the
1942        // primitive because the downstream gate at
1943        // `owner_references_json` treats `.is_empty()` uniformly (the
1944        // empty-slot posture is what the whole primitive family
1945        // encodes: "no admissible owner reference, stamp `[]`"). A
1946        // regression that discriminated the two corners (returning a
1947        // sentinel `"<none>"` for the missing slot but `""` for the
1948        // explicit slot) would break the composition with
1949        // `owner_references_json` at the exactly-two-corner gate.
1950        let mut p = Process::new("owned-proc", empty_spec());
1951        p.metadata.uid = Some(String::new());
1952        assert_eq!(p.uid_or_empty(), "");
1953    }
1954
1955    #[test]
1956    fn uid_or_empty_is_a_zero_copy_borrow_projection() {
1957        // Borrow-discipline pin: the returned `&str` borrows the
1958        // persisted `String`'s underlying byte buffer in place — NOT
1959        // a fresh allocation or a clone. A regression that switched
1960        // the projection to an owned `String` (via `.clone()` or a
1961        // `format!` wrap) would defeat the zero-copy contract the
1962        // lift's primary strict-widening delivers, and would surface
1963        // here via pointer-identity comparison.
1964        let mut p = Process::new("owned-proc", empty_spec());
1965        p.metadata.uid = Some("uid-borrow-pin".into());
1966        let slice = p.uid_or_empty();
1967        assert!(std::ptr::eq(
1968            slice.as_ptr(),
1969            p.metadata.uid.as_ref().unwrap().as_ptr()
1970        ));
1971    }
1972
1973    #[test]
1974    fn uid_or_empty_is_a_pure_projection() {
1975        // Purity pin — repeated calls return byte-identical slices
1976        // (same pointer, same length). A regression that introduced
1977        // state (a lazy-cached normalized slot, a first-call
1978        // canonicalization pass) would surface here rather than as
1979        // silent drift between the two render consumer sites on the
1980        // SAME Process within one render pass.
1981        let mut p = Process::new("owned-proc", empty_spec());
1982        p.metadata.uid = Some("uid-pure".into());
1983        let a = p.uid_or_empty();
1984        let b = p.uid_or_empty();
1985        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
1986        assert_eq!(a.len(), b.len());
1987    }
1988
1989    #[test]
1990    fn uid_or_empty_matches_pre_lift_render_chain_shape() {
1991        // Byte-identical parity pin between the borrow-form primitive
1992        // here and the pre-lift `tatara-reconciler::render` chain shape
1993        // — the exact `.metadata.uid.as_deref().unwrap_or("")`
1994        // incantation both `render_routing` (line 514) and
1995        // `render_export_jobs` (line 653) spelled by hand pre-lift.
1996        // Sweeps every corner (missing uid slot, populated uid slot,
1997        // explicitly-empty uid slot) so a regression that inserted a
1998        // normalization the pre-lift chain does NOT apply — or vice
1999        // versa — surfaces here rather than as silent drift between
2000        // the ONE substrate owner and the two consumer sites.
2001        fn pre_lift(p: &Process) -> &str {
2002            p.metadata.uid.as_deref().unwrap_or("")
2003        }
2004        // Missing slot.
2005        let mut p = Process::new("x", empty_spec());
2006        p.metadata.uid = None;
2007        assert_eq!(p.uid_or_empty(), pre_lift(&p));
2008        // Populated slot.
2009        let mut p = Process::new("x", empty_spec());
2010        p.metadata.uid = Some("uid-42".into());
2011        assert_eq!(p.uid_or_empty(), pre_lift(&p));
2012        // Explicitly-empty slot.
2013        let mut p = Process::new("x", empty_spec());
2014        p.metadata.uid = Some(String::new());
2015        assert_eq!(p.uid_or_empty(), pre_lift(&p));
2016    }
2017
2018    #[test]
2019    fn uid_or_empty_composes_with_owner_references_json_empty_gate() {
2020        // Cross-primitive composition pin — the empty-string sentinel
2021        // this primitive returns for the missing-uid corner is EXACTLY
2022        // the sentinel the sibling substrate composer
2023        // `owner_references_json(name, uid)` gates on to stamp
2024        // `metadata.ownerReferences: []`. A regression that changed
2025        // the sentinel at either end (this primitive returning
2026        // `"<none>"`, `owner_references_json` gating on `uid == "0"`
2027        // instead of `uid.is_empty()`) would break the composition
2028        // and surface here rather than as an operator-observed
2029        // orphan resource after apply.
2030        let mut p = Process::new("x", empty_spec());
2031        p.metadata.uid = None;
2032        let refs = crate::owner_references_json("some-name", p.uid_or_empty());
2033        assert!(
2034            refs.is_empty(),
2035            "empty-uid corner must produce empty owner-refs array"
2036        );
2037
2038        p.metadata.uid = Some("real-uid".into());
2039        let refs = crate::owner_references_json("some-name", p.uid_or_empty());
2040        assert_eq!(
2041            refs.len(),
2042            1,
2043            "populated-uid corner must produce one owner-ref entry"
2044        );
2045    }
2046
2047    // ─── Process::declared_parent_pid substrate pins ─────────────────
2048    //
2049    // Pins the borrow-form spec-projection primitive on the declared
2050    // parent-PID axis that owns the `.spec.identity.parent.as_deref()`
2051    // chain the two hand-authored `tatara-reconciler::phase_machine`
2052    // sites (`handle_forking` ALLOCATE-PID composer + `handle_exiting`
2053    // SIGTERM-cascade child-fan-out filter) restated by hand pre-lift.
2054    // Peer to the sibling `observed_pid_*` pin family on the (spec-
2055    // declared × status-observed) axis pair; both compose the same
2056    // borrow-form `Option<&str>` return-shape skeleton on distinct
2057    // slots (`spec.identity.parent` vs. `status.pid`). Fail-before-
2058    // pass-after granularity: `declared_parent_pid` did not exist
2059    // pre-lift, so any test invoking it fails to compile pre-lift and
2060    // passes post-lift.
2061    fn process_with_declared_parent(parent: Option<&str>) -> Process {
2062        let mut spec = empty_spec();
2063        spec.identity.parent = parent.map(str::to_string);
2064        Process::new("child-proc", spec)
2065    }
2066
2067    #[test]
2068    fn declared_parent_pid_returns_none_when_slot_is_none() {
2069        // Empty-slot corner pin: the primitive collapses the no-
2070        // parent case to `None`, matching the pre-lift `.as_deref()`
2071        // chain's `None` byte-identically at both reconciler consumer
2072        // sites. Semantically corresponds to a Process authored at
2073        // cluster init (PID 1) with no upstream parent — the
2074        // ALLOCATE-PID composer feeds `None` into `pid::allocate_pid`
2075        // to signal "no prefix", and the SIGTERM cascade's filter
2076        // never matches such a Process because a child's declared
2077        // parent can never equal `Some(pid)` when the slot is `None`.
2078        let p = process_with_declared_parent(None);
2079        assert!(p.declared_parent_pid().is_none());
2080    }
2081
2082    #[test]
2083    fn declared_parent_pid_returns_borrowed_str_when_slot_is_populated() {
2084        // Happy-path pin: with a populated `spec.identity.parent`
2085        // slot, the primitive returns a borrowed `&str` whose
2086        // contents match the persisted `String`. A regression that
2087        // filtered / reshaped / canonicalized the string would
2088        // surface here rather than as silent skew at the child-fan-
2089        // out filter's `.declared_parent_pid() == Some(pid)`
2090        // equality check on the SAME parent-child pair.
2091        let p = process_with_declared_parent(Some("seph.1"));
2092        assert_eq!(p.declared_parent_pid(), Some("seph.1"));
2093    }
2094
2095    #[test]
2096    fn declared_parent_pid_is_a_zero_copy_borrow_projection() {
2097        // Borrow-discipline pin: the returned `&str` borrows the
2098        // persisted `String`'s underlying byte buffer in place —
2099        // NOT a fresh allocation or a clone. A regression that
2100        // switched the projection to an owned `String` (via
2101        // `.clone()` or `.to_owned()`) would defeat the zero-copy
2102        // contract the lift's primary strict-widening delivers.
2103        // The `handle_exiting` cascade filter runs per candidate
2104        // child across the cluster-wide Process list; a per-row
2105        // `String::clone` would allocate one heap block per non-
2106        // matching row, so the borrow-form primitive is load-
2107        // bearing for large clusters. Peer to the sibling
2108        // `observed_pid_is_a_zero_copy_borrow_projection` pin on
2109        // the status-observed side of the axis pair.
2110        let p = process_with_declared_parent(Some("seph.1"));
2111        let borrowed = p.declared_parent_pid().expect("populated slot");
2112        let persisted = p.spec.identity.parent.as_ref().unwrap();
2113        assert!(std::ptr::eq(borrowed.as_ptr(), persisted.as_ptr()));
2114    }
2115
2116    #[test]
2117    fn declared_parent_pid_is_a_pure_projection() {
2118        // Purity pin: calling the projection twice on the same
2119        // `Process` returns byte-identical `&str`s (same pointer,
2120        // same length). A regression that introduced state — a
2121        // lazy-cached slice materialized on first call, a
2122        // normalization step that ran once and cached — would
2123        // surface here rather than as silent drift between the
2124        // ALLOCATE-PID composer and the SIGTERM cascade's child-
2125        // fan-out filter within one reconcile pass.
2126        let p = process_with_declared_parent(Some("seph.1.3"));
2127        let a = p.declared_parent_pid().expect("populated slot");
2128        let b = p.declared_parent_pid().expect("populated slot");
2129        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
2130        assert_eq!(a.len(), b.len());
2131    }
2132
2133    #[test]
2134    fn declared_parent_pid_matches_pre_lift_reconciler_chain_shape() {
2135        // Byte-identical parity pin between the borrow-form primitive
2136        // here and the pre-lift `tatara-reconciler::phase_machine`
2137        // `.spec.identity.parent.as_deref()` chain shape. Sweeps
2138        // every corner every callsite plausibly encounters (empty
2139        // slot, populated with a hierarchical PID). A regression
2140        // that inserted a normalization step at the primitive the
2141        // pre-lift chain does NOT apply — or vice versa — surfaces
2142        // here rather than as silent drift between the pre-lift
2143        // consumer sites and the ONE substrate owner they now route
2144        // through. Peer to
2145        // `observed_pid_matches_pre_lift_reconciler_chain_shape` on
2146        // the sibling axis's borrow-form primitive.
2147        fn pre_lift(p: &Process) -> Option<&str> {
2148            p.spec.identity.parent.as_deref()
2149        }
2150        // Empty slot.
2151        let p = process_with_declared_parent(None);
2152        assert_eq!(p.declared_parent_pid(), pre_lift(&p));
2153        // Populated with a hierarchical PID.
2154        let p = process_with_declared_parent(Some("seph.1"));
2155        assert_eq!(p.declared_parent_pid(), pre_lift(&p));
2156        // Populated with a deeper hierarchical PID.
2157        let p = process_with_declared_parent(Some("seph.1.7.42"));
2158        assert_eq!(p.declared_parent_pid(), pre_lift(&p));
2159    }
2160
2161    #[test]
2162    fn declared_parent_pid_preserves_hierarchical_pid_format() {
2163        // Format-preservation pin: the hierarchical PID path
2164        // (dotted-segment form `seph.1.7`, matching the ported
2165        // `convergence-controller/src/identity.rs` scheme) reaches
2166        // the caller with segments and separators byte-identical
2167        // to the persisted `String`. A regression that inserted a
2168        // canonicalization pass (a segment-count validator, a
2169        // separator swap `.` → `/`, a leading/trailing whitespace
2170        // trim) would silently misroute the SIGTERM cascade's
2171        // `declared_parent_pid() == Some(pid)` comparator against
2172        // children whose `parent` field was authored in the ported
2173        // scheme's exact form — the SAME children the observed_pid
2174        // primitive is pinned to match on the other side of the
2175        // axis pair.
2176        for parent in ["seph", "seph.1", "seph.1.7", "seph.1.7.42"] {
2177            let p = process_with_declared_parent(Some(parent));
2178            assert_eq!(p.declared_parent_pid(), Some(parent));
2179        }
2180    }
2181
2182    #[test]
2183    fn declared_parent_pid_composes_with_observed_pid_for_child_fanout_filter() {
2184        // Cross-axis coherence pin against the sibling
2185        // [`Self::observed_pid`] on the (spec-declared × status-
2186        // observed) axis pair: a child's `.declared_parent_pid()`
2187        // and its parent's `.observed_pid()` compose through the
2188        // SAME borrow-form `Option<&str>` skeleton so the
2189        // `handle_exiting` cascade filter's equality gate holds
2190        // structurally. A regression that skewed EITHER primitive's
2191        // return-form (return-shape, borrow discipline, empty-slot
2192        // collapse) would silently misroute every SIGTERM cascade
2193        // on the parent-child pair. This pin re-reads both primitives
2194        // at test time so the composition holds iff both live paths
2195        // are the current implementation.
2196        // Parent Process: has an observed PID.
2197        let mut parent = Process::new("parent-proc", empty_spec());
2198        parent.status = Some(ProcessStatus {
2199            pid: Some("seph.1".to_string()),
2200            ..Default::default()
2201        });
2202        // Child Process: declared parent matches parent's observed PID.
2203        let child = process_with_declared_parent(Some("seph.1"));
2204        // The `handle_exiting` filter's equality gate:
2205        // `child.declared_parent_pid() == Some(parent.observed_pid()?)`.
2206        let parent_pid = parent.observed_pid().expect("parent has PID");
2207        assert_eq!(child.declared_parent_pid(), Some(parent_pid));
2208        // Sibling Process with an unrelated declared parent must NOT
2209        // match the same parent — pins that the filter's SKIP branch
2210        // holds on the other side of the axis pair.
2211        let sibling = process_with_declared_parent(Some("seph.2"));
2212        assert_ne!(sibling.declared_parent_pid(), Some(parent_pid));
2213    }
2214
2215    // ─── Process::declared_name_override substrate pins ──────────────
2216    //
2217    // Pins the borrow-form spec-projection primitive on the declared
2218    // name-override sub-axis of the declared-identity axis that owns
2219    // the `.spec.identity.name_override.as_deref()` chain the two
2220    // hand-authored `tatara-reconciler::phase_machine` sites
2221    // (`handle_pending` DECLARE composer + `handle_forking` ALLOCATE-
2222    // PID rehydration branch) restated by hand pre-lift. Peer to the
2223    // sibling `declared_parent_pid_*` pin family on the (parent ×
2224    // name-override) sub-axis pair; both compose the same borrow-form
2225    // `Option<&str>` return-shape skeleton on distinct slots
2226    // (`spec.identity.name_override` vs `spec.identity.parent`).
2227    // Fail-before-pass-after granularity: `declared_name_override`
2228    // did not exist pre-lift, so any test invoking it fails to
2229    // compile pre-lift and passes post-lift.
2230    fn process_with_declared_name_override(name_override: Option<&str>) -> Process {
2231        let mut spec = empty_spec();
2232        spec.identity.name_override = name_override.map(str::to_string);
2233        Process::new("some-proc", spec)
2234    }
2235
2236    #[test]
2237    fn declared_name_override_returns_none_when_slot_is_none() {
2238        // Empty-slot corner pin: the primitive collapses the no-
2239        // override case to `None`, matching the pre-lift `.as_deref()`
2240        // chain's `None` byte-identically at both reconciler consumer
2241        // sites. Semantically corresponds to a Process authored
2242        // WITHOUT the human-name-override escape hatch — the default;
2243        // `derive_identity` then computes the name from the content
2244        // hash and stamps `name_override: false` on the resulting
2245        // [`Identity`].
2246        let p = process_with_declared_name_override(None);
2247        assert!(p.declared_name_override().is_none());
2248    }
2249
2250    #[test]
2251    fn declared_name_override_returns_borrowed_str_when_slot_is_populated() {
2252        // Happy-path pin: with a populated `spec.identity
2253        // .name_override` slot, the primitive returns a borrowed
2254        // `&str` whose contents match the persisted `String`. A
2255        // regression that filtered / reshaped / canonicalized the
2256        // string at the primitive (as opposed to inside
2257        // `derive_identity`, where the trim/empty-filter lives today)
2258        // would surface here rather than as silent skew between the
2259        // DECLARE composer and the ALLOCATE-PID rehydration branch on
2260        // the SAME Process spec.
2261        let p = process_with_declared_name_override(Some("observability-stack"));
2262        assert_eq!(p.declared_name_override(), Some("observability-stack"));
2263    }
2264
2265    #[test]
2266    fn declared_name_override_is_a_zero_copy_borrow_projection() {
2267        // Borrow-discipline pin: the returned `&str` borrows the
2268        // persisted `String`'s underlying byte buffer in place —
2269        // NOT a fresh allocation or a clone. Peer to the sibling
2270        // `declared_parent_pid_is_a_zero_copy_borrow_projection` pin
2271        // on the other side of the (parent × name-override) sub-axis
2272        // pair; the borrow discipline holds structurally on BOTH
2273        // sub-axes so a future `declared_identity` composite that
2274        // returns both halves together can compose them without
2275        // dropping into an owning form.
2276        let p = process_with_declared_name_override(Some("observability-stack"));
2277        let borrowed = p.declared_name_override().expect("populated slot");
2278        let persisted = p.spec.identity.name_override.as_ref().unwrap();
2279        assert!(std::ptr::eq(borrowed.as_ptr(), persisted.as_ptr()));
2280    }
2281
2282    #[test]
2283    fn declared_name_override_is_a_pure_projection() {
2284        // Purity pin: calling the projection twice on the same
2285        // `Process` returns byte-identical `&str`s (same pointer,
2286        // same length). A regression that introduced state — a
2287        // lazy-cached slice materialized on first call, a
2288        // normalization step that ran once and cached — would
2289        // surface here rather than as silent drift between the
2290        // DECLARE composer and the ALLOCATE-PID rehydration branch
2291        // within one reconcile pass.
2292        let p = process_with_declared_name_override(Some("gateway-primary"));
2293        let a = p.declared_name_override().expect("populated slot");
2294        let b = p.declared_name_override().expect("populated slot");
2295        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
2296        assert_eq!(a.len(), b.len());
2297    }
2298
2299    #[test]
2300    fn declared_name_override_matches_pre_lift_reconciler_chain_shape() {
2301        // Byte-identical parity pin between the borrow-form primitive
2302        // here and the pre-lift `tatara-reconciler::phase_machine`
2303        // `.spec.identity.name_override.as_deref()` chain shape.
2304        // Sweeps every corner every callsite plausibly encounters
2305        // (empty slot, populated with a bare name, populated with a
2306        // whitespace-containing name that `derive_identity`'s
2307        // internal trim would collapse, populated with an explicitly
2308        // empty string that `derive_identity`'s internal
2309        // `!s.is_empty()` filter would reject). A regression that
2310        // inserted a normalization step at the primitive the pre-
2311        // lift chain does NOT apply — or vice versa — surfaces here
2312        // rather than as silent drift between the pre-lift consumer
2313        // sites and the ONE substrate owner they now route through.
2314        // Peer to
2315        // `declared_parent_pid_matches_pre_lift_reconciler_chain_shape`
2316        // on the sibling sub-axis's borrow-form primitive.
2317        fn pre_lift(p: &Process) -> Option<&str> {
2318            p.spec.identity.name_override.as_deref()
2319        }
2320        // Empty slot.
2321        let p = process_with_declared_name_override(None);
2322        assert_eq!(p.declared_name_override(), pre_lift(&p));
2323        // Populated with a bare name.
2324        let p = process_with_declared_name_override(Some("observability-stack"));
2325        assert_eq!(p.declared_name_override(), pre_lift(&p));
2326        // Populated with a whitespace-containing name.
2327        let p = process_with_declared_name_override(Some("  observability-stack  "));
2328        assert_eq!(p.declared_name_override(), pre_lift(&p));
2329        // Populated with an explicitly empty string. Distinct from
2330        // the missing-slot `None` corner both at the primitive here
2331        // and at the pre-lift chain (the trim/filter that collapses
2332        // these two into the same `false`-branched
2333        // `Identity { name_override: false, .. }` lives INSIDE
2334        // `derive_identity`, NOT at the borrow site) — the primitive
2335        // MUST preserve the distinction so a future lift of the trim/
2336        // filter OUT of `derive_identity` INTO the primitive is a
2337        // conscious substrate change, not a silent one.
2338        let p = process_with_declared_name_override(Some(""));
2339        assert_eq!(p.declared_name_override(), pre_lift(&p));
2340    }
2341
2342    #[test]
2343    fn declared_name_override_preserves_raw_slot_verbatim() {
2344        // Invariance-under-`derive_identity`-normalization pin: the
2345        // primitive returns the slot's raw byte contents verbatim —
2346        // no trim, no empty-string filter, no case fold, no
2347        // normalization of any kind. `derive_identity` internally
2348        // applies `.map(str::trim).filter(|s| !s.is_empty())` before
2349        // dispatching on `Some(non_empty)` vs `None | Some(empty |
2350        // whitespace)`, but that transform lives IN `derive_identity`,
2351        // NOT at the borrow site. A regression that pulled the trim/
2352        // filter forward INTO the primitive would silently collapse
2353        // three currently-distinct corners at the borrow site (bare
2354        // populated → `Some(name)`; whitespace-only → `Some("   ")`;
2355        // empty → `Some("")`) into two (bare → `Some(name)`; the
2356        // other two → `None`). That collapse might be an intentional
2357        // substrate change some future run wants to make; if so, it
2358        // lands as a conscious edit here (with this pin updated in
2359        // the same commit) rather than as silent behavior drift.
2360        for value in ["bare", "  padded  ", "\ttabs\t", "   ", ""] {
2361            let p = process_with_declared_name_override(Some(value));
2362            assert_eq!(
2363                p.declared_name_override(),
2364                Some(value),
2365                "declared_name_override must preserve raw slot verbatim for value {value:?}"
2366            );
2367        }
2368    }
2369
2370    #[test]
2371    fn declared_name_override_composes_with_derive_identity_call_shape() {
2372        // Cross-primitive coherence pin against the [`derive_identity`]
2373        // consumer: the two live `tatara-reconciler::phase_machine`
2374        // callsites feed `p.declared_name_override()` as the second
2375        // positional argument to `derive_identity(&p.spec, …)`. This
2376        // pin exercises that exact call shape at test time so a
2377        // regression that skewed the primitive's return-form (return-
2378        // shape, borrow discipline, empty-slot collapse) surfaces
2379        // here as a shape mismatch at the [`derive_identity`] call
2380        // site rather than as silent operator-facing skew between the
2381        // DECLARE composer and the ALLOCATE-PID rehydration branch.
2382        // Populated with a bare non-empty name: `derive_identity`
2383        // dispatches on `Some(non_empty)` and stamps
2384        // `name_override: true` on the resulting [`Identity`], with
2385        // the resulting `.name` equal to the raw slot value.
2386        let p = process_with_declared_name_override(Some("gateway-primary"));
2387        let id = crate::identity::derive_identity(&p.spec, p.declared_name_override());
2388        assert!(id.name_override);
2389        assert_eq!(id.name, "gateway-primary");
2390        // Empty slot: `derive_identity` dispatches on `None` and
2391        // stamps `name_override: false` on the resulting [`Identity`],
2392        // with the resulting `.name` derived from the content hash
2393        // (NOT equal to any operator-authored slot value).
2394        let p = process_with_declared_name_override(None);
2395        let id = crate::identity::derive_identity(&p.spec, p.declared_name_override());
2396        assert!(!id.name_override);
2397    }
2398
2399    // ─── Process::observed_flux_resources substrate pins ───────────────
2400    //
2401    // Pins the borrow-form status-projection primitive that owns the
2402    // 5-line `.status.as_ref().map(|s| s.flux_resources.clone())
2403    // .unwrap_or_default()` chain the two hand-authored
2404    // `tatara-reconciler::phase_machine` sites (`handle_running` +
2405    // `handle_attested`) restated by hand pre-lift. Fail-before-pass-
2406    // after granularity: a regression that widened the missing-`status`
2407    // corner, dropped the slot, or drifted the borrow discipline
2408    // surfaces here rather than as silent operator-facing skew between
2409    // the VERIFY-phase readiness probe and the ATTEST-heartbeat drift
2410    // detector.
2411
2412    fn sample_flux_ref(name: &str) -> FluxResourceRef {
2413        // Distinct slot values so a swap between adjacent tuple
2414        // positions surfaces as an equality failure at the assertion
2415        // site — a slot-inversion regression cannot masquerade as
2416        // identity by accident. Peer to the sibling
2417        // `tatara_process::status::tests::sample_flux_ref` discipline
2418        // on the fetch-coords axis.
2419        FluxResourceRef {
2420            api_version: "kustomize.toolkit.fluxcd.io/v1".to_string(),
2421            kind: "Kustomization".to_string(),
2422            name: name.to_string(),
2423            namespace: "flux-system".to_string(),
2424            ready: false,
2425            message: None,
2426            last_check: None,
2427        }
2428    }
2429
2430    fn process_with_flux_resources(refs: Vec<FluxResourceRef>) -> Process {
2431        let mut p = Process::new("api-gateway", empty_spec());
2432        p.metadata.namespace = Some("prod".into());
2433        let mut status = ProcessStatus::default();
2434        status.flux_resources = refs;
2435        p.status = Some(status);
2436        p
2437    }
2438
2439    #[test]
2440    fn observed_flux_resources_returns_empty_slice_when_status_is_none() {
2441        // Missing-`status` corner pin: the primitive collapses the
2442        // no-status case to `&[]` so downstream `.is_empty()` /
2443        // `.len()` / iteration behave identically on a `Process`
2444        // whose status field is `None` and on one whose status
2445        // carries an empty `flux_resources` slot. Matches the
2446        // pre-lift `.unwrap_or_default()`'s empty-`Vec` corner
2447        // byte-identically at every reconciler consumer's downstream
2448        // shape.
2449        let mut p = Process::new("api", empty_spec());
2450        p.status = None;
2451        assert!(p.observed_flux_resources().is_empty());
2452        assert_eq!(p.observed_flux_resources().len(), 0);
2453    }
2454
2455    #[test]
2456    fn observed_flux_resources_returns_empty_slice_when_flux_resources_is_empty() {
2457        // Zero-refs-under-populated-status corner pin: the primitive
2458        // returns an empty slice, matching the missing-`status`
2459        // corner byte-identically. A regression that treated the two
2460        // corners differently (a `None`-vs-empty signal that
2461        // downstream consumers could grep on) would silently promote
2462        // an internal representation detail (whether the reconciler
2463        // has ever written a status subresource) into observable
2464        // behavior.
2465        let p = process_with_flux_resources(vec![]);
2466        assert!(p.observed_flux_resources().is_empty());
2467        assert_eq!(p.observed_flux_resources().len(), 0);
2468    }
2469
2470    #[test]
2471    fn observed_flux_resources_returns_slice_of_persisted_vec() {
2472        // Happy-path pin: with a populated `status.flux_resources`
2473        // slot, the primitive returns a borrowed slice whose length
2474        // and per-element identity match the persisted vector. A
2475        // regression that filtered / reshaped / deduplicated the
2476        // slice would surface here rather than as silent skew at the
2477        // downstream fetch consumers.
2478        let refs = vec![
2479            sample_flux_ref("observability-stack"),
2480            sample_flux_ref("gateway"),
2481        ];
2482        let p = process_with_flux_resources(refs.clone());
2483        let observed = p.observed_flux_resources();
2484        assert_eq!(observed.len(), 2);
2485        assert_eq!(observed[0].name, "observability-stack");
2486        assert_eq!(observed[1].name, "gateway");
2487    }
2488
2489    #[test]
2490    fn observed_flux_resources_is_a_zero_copy_borrow_projection() {
2491        // Borrow-discipline pin: the returned slice borrows the
2492        // persisted `Vec<FluxResourceRef>` in place — NOT a fresh
2493        // allocation or a clone. A regression that switched the
2494        // projection to owned refs (via `.clone()` or `.to_vec()`)
2495        // would defeat the zero-copy contract the lift's primary
2496        // strict-widening delivers (the pre-lift 5-line chain
2497        // eagerly cloned the whole vector per reconcile pass; the
2498        // post-lift primitive borrows). Peer to the sibling
2499        // `flux_resource_ref_fetch_coords_returns_borrows_of_owned_slots`
2500        // pin on the per-ref borrow-projection axis.
2501        let refs = vec![sample_flux_ref("observability-stack")];
2502        let p = process_with_flux_resources(refs);
2503        let observed = p.observed_flux_resources();
2504        let persisted = &p.status.as_ref().unwrap().flux_resources;
2505        assert!(std::ptr::eq(observed.as_ptr(), persisted.as_ptr()));
2506    }
2507
2508    #[test]
2509    fn observed_flux_resources_is_a_pure_projection() {
2510        // Purity pin: calling the projection twice on the same
2511        // `Process` returns byte-identical slices (same pointer,
2512        // same length). A regression that introduced state — a
2513        // lazy-cached slice materialized on first call, a
2514        // normalization step that ran once and cached — would
2515        // surface here rather than as silent drift between the
2516        // VERIFY-phase and ATTEST-heartbeat consumers on the SAME
2517        // `Process` within one reconcile pass.
2518        let refs = vec![sample_flux_ref("observability-stack")];
2519        let p = process_with_flux_resources(refs);
2520        let a = p.observed_flux_resources();
2521        let b = p.observed_flux_resources();
2522        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
2523        assert_eq!(a.len(), b.len());
2524    }
2525
2526    #[test]
2527    fn observed_flux_resources_matches_pre_lift_reconciler_chain_shape() {
2528        // Byte-identical parity pin between the borrow-form primitive
2529        // here and the pre-lift `tatara-reconciler::phase_machine`
2530        // 5-line chain shape. Sweeps every corner every callsite
2531        // plausibly encounters (missing status, empty flux_resources,
2532        // populated flux_resources with one ref, populated with
2533        // multiple refs). A regression that inserted a normalization
2534        // step at the primitive the pre-lift chain does NOT apply —
2535        // or vice versa — surfaces here rather than as silent drift
2536        // between the pre-lift consumer sites and the ONE substrate
2537        // owner they now route through. Peer to
2538        // `coordinates_or_none_matches_pre_lift_reconciler_helper_shape`
2539        // on the metadata axis's borrow-form primitive.
2540        // `FluxResourceRef` does not derive `PartialEq` — the parity
2541        // check walks the per-ref fetch-coords tuple (the same 4-slot
2542        // borrow projection every downstream fetch consumer routes
2543        // through) so a regression that reshaped ANY slot at ANY
2544        // index surfaces here through the sibling
2545        // `FluxResourceRef::fetch_coords` typed projection.
2546        fn pre_lift(p: &Process) -> Vec<FluxResourceRef> {
2547            p.status
2548                .as_ref()
2549                .map(|s| s.flux_resources.clone())
2550                .unwrap_or_default()
2551        }
2552        fn coord_shape(refs: &[FluxResourceRef]) -> Vec<(String, String, String, String)> {
2553            refs.iter()
2554                .map(|r| {
2555                    let (ns, av, kind, name) = r.fetch_coords();
2556                    (
2557                        ns.to_string(),
2558                        av.to_string(),
2559                        kind.to_string(),
2560                        name.to_string(),
2561                    )
2562                })
2563                .collect()
2564        }
2565        // Missing status.
2566        let mut p = Process::new("api", empty_spec());
2567        p.status = None;
2568        assert_eq!(
2569            coord_shape(p.observed_flux_resources()),
2570            coord_shape(&pre_lift(&p))
2571        );
2572        // Populated status, empty slot.
2573        let p = process_with_flux_resources(vec![]);
2574        assert_eq!(
2575            coord_shape(p.observed_flux_resources()),
2576            coord_shape(&pre_lift(&p))
2577        );
2578        // Populated status, one ref.
2579        let p = process_with_flux_resources(vec![sample_flux_ref("obs")]);
2580        assert_eq!(
2581            coord_shape(p.observed_flux_resources()),
2582            coord_shape(&pre_lift(&p))
2583        );
2584        // Populated status, multiple refs.
2585        let p = process_with_flux_resources(vec![
2586            sample_flux_ref("obs"),
2587            sample_flux_ref("gw"),
2588            sample_flux_ref("api"),
2589        ]);
2590        assert_eq!(
2591            coord_shape(p.observed_flux_resources()),
2592            coord_shape(&pre_lift(&p))
2593        );
2594    }
2595
2596    #[test]
2597    fn observed_flux_resources_missing_status_and_empty_slot_collapse_to_the_same_slice_shape() {
2598        // Cross-corner coherence pin: the missing-`status` corner and
2599        // the populated-empty-slot corner return slices whose
2600        // `.is_empty()` / `.len()` observations are IDENTICAL. A
2601        // regression that promoted the missing-`status` corner to
2602        // returning `None` (via a signature change) — or that widened
2603        // the empty-slot corner to a synthetic single-element slice
2604        // — would surface here rather than as silent operator-facing
2605        // divergence between a never-status-written Process and a
2606        // status-emptied Process.
2607        let mut p_no_status = Process::new("api", empty_spec());
2608        p_no_status.status = None;
2609        let p_empty_status = process_with_flux_resources(vec![]);
2610        assert_eq!(
2611            p_no_status.observed_flux_resources().len(),
2612            p_empty_status.observed_flux_resources().len()
2613        );
2614        assert_eq!(
2615            p_no_status.observed_flux_resources().is_empty(),
2616            p_empty_status.observed_flux_resources().is_empty()
2617        );
2618    }
2619
2620    #[test]
2621    fn observed_flux_resources_slice_preserves_persisted_ordering() {
2622        // Ordering-preservation pin: the borrowed slice preserves
2623        // the exact insertion order of the persisted vector — no
2624        // sort, no dedup, no reshape. A regression that inserted a
2625        // sort or reordering would silently misroute per-ref
2626        // observations at the downstream VERIFY-phase / ATTEST-
2627        // heartbeat consumers, both of which walk the slice
2628        // positionally and correlate the position to the observed
2629        // readiness.
2630        let refs = vec![
2631            sample_flux_ref("z-last"),
2632            sample_flux_ref("a-first"),
2633            sample_flux_ref("m-middle"),
2634        ];
2635        let p = process_with_flux_resources(refs);
2636        let observed = p.observed_flux_resources();
2637        assert_eq!(observed[0].name, "z-last");
2638        assert_eq!(observed[1].name, "a-first");
2639        assert_eq!(observed[2].name, "m-middle");
2640    }
2641
2642    // ─── Process::observed_pid substrate pins ─────────────────────────
2643    //
2644    // Pins the borrow-form status-projection primitive on the PID axis
2645    // that owns the 3-line `.status.as_ref().and_then(|s| s.pid.clone())`
2646    // chain the two hand-authored `tatara-reconciler::phase_machine`
2647    // sites (`handle_forking` ALLOCATE-PID gate + `handle_exiting`
2648    // SIGTERM cascade) restated by hand pre-lift. Peer to the sibling
2649    // `observed_flux_resources_*` pin family on the flux-resources
2650    // axis; both compose the missing-`status` fallback + borrow-form
2651    // return-shape skeleton on distinct `ProcessStatus` slots. Fail-
2652    // before-pass-after granularity: `observed_pid` did not exist
2653    // pre-lift, so any test invoking it fails to compile pre-lift and
2654    // passes post-lift.
2655
2656    fn process_with_pid(pid: Option<&str>) -> Process {
2657        let mut p = Process::new("api-gateway", empty_spec());
2658        p.metadata.namespace = Some("prod".into());
2659        let mut status = ProcessStatus::default();
2660        status.pid = pid.map(str::to_string);
2661        p.status = Some(status);
2662        p
2663    }
2664
2665    #[test]
2666    fn observed_pid_returns_none_when_status_is_none() {
2667        // Missing-`status` corner pin: the primitive collapses the
2668        // no-status case to `None` so downstream `.is_some()` /
2669        // `if let Some(_)` / `.map(...)` behave identically on a
2670        // `Process` whose status field is `None` and on one whose
2671        // status carries an unpopulated `pid` slot. Matches the
2672        // pre-lift `.and_then(...)` chain's `None` byte-identically
2673        // at every reconciler consumer's downstream shape.
2674        let mut p = Process::new("api", empty_spec());
2675        p.status = None;
2676        assert!(p.observed_pid().is_none());
2677    }
2678
2679    #[test]
2680    fn observed_pid_returns_none_when_pid_slot_is_none() {
2681        // Empty-slot-under-populated-status corner pin: the
2682        // primitive returns `None`, matching the missing-`status`
2683        // corner byte-identically. A regression that treated the
2684        // two corners differently (a `None`-vs-`Some("")` signal
2685        // that downstream consumers could grep on) would silently
2686        // promote an internal representation detail (whether the
2687        // reconciler has ever written a status subresource) into
2688        // observable behavior at the ALLOCATE-PID gate.
2689        let p = process_with_pid(None);
2690        assert!(p.observed_pid().is_none());
2691    }
2692
2693    #[test]
2694    fn observed_pid_returns_borrowed_str_when_pid_slot_is_populated() {
2695        // Happy-path pin: with a populated `status.pid` slot, the
2696        // primitive returns a borrowed `&str` whose contents match
2697        // the persisted `String`. A regression that filtered /
2698        // reshaped / canonicalized the string would surface here
2699        // rather than as silent skew at the downstream cascade
2700        // comparator's `.as_deref() == Some(...)` equality check.
2701        let p = process_with_pid(Some("seph.1.7"));
2702        assert_eq!(p.observed_pid(), Some("seph.1.7"));
2703    }
2704
2705    #[test]
2706    fn observed_pid_is_a_zero_copy_borrow_projection() {
2707        // Borrow-discipline pin: the returned `&str` borrows the
2708        // persisted `String`'s underlying byte buffer in place —
2709        // NOT a fresh allocation or a clone. A regression that
2710        // switched the projection to an owned `String` (via
2711        // `.clone()` or `.to_owned()`) would defeat the zero-copy
2712        // contract the lift's primary strict-widening delivers
2713        // (the pre-lift 3-line chain eagerly cloned the `String`
2714        // per reconcile pass at BOTH call sites even though the
2715        // ALLOCATE-PID gate immediately dropped the clone and the
2716        // SIGTERM cascade only re-borrowed it via `.as_str()`; the
2717        // post-lift primitive borrows). Peer to the sibling
2718        // `observed_flux_resources_is_a_zero_copy_borrow_projection`
2719        // pin on the flux-resources borrow-projection axis.
2720        let p = process_with_pid(Some("seph.1.7"));
2721        let observed = p.observed_pid().expect("populated slot");
2722        let persisted = p.status.as_ref().unwrap().pid.as_ref().unwrap();
2723        assert!(std::ptr::eq(observed.as_ptr(), persisted.as_ptr()));
2724    }
2725
2726    #[test]
2727    fn observed_pid_is_a_pure_projection() {
2728        // Purity pin: calling the projection twice on the same
2729        // `Process` returns byte-identical `&str`s (same pointer,
2730        // same length). A regression that introduced state — a
2731        // lazy-cached slice materialized on first call, a
2732        // normalization step that ran once and cached — would
2733        // surface here rather than as silent drift between the
2734        // ALLOCATE-PID gate and the SIGTERM cascade on the SAME
2735        // `Process` within one reconcile pass.
2736        let p = process_with_pid(Some("seph.1.7"));
2737        let a = p.observed_pid().expect("populated slot");
2738        let b = p.observed_pid().expect("populated slot");
2739        assert!(std::ptr::eq(a.as_ptr(), b.as_ptr()));
2740        assert_eq!(a.len(), b.len());
2741    }
2742
2743    #[test]
2744    fn observed_pid_matches_pre_lift_reconciler_chain_shape() {
2745        // Byte-identical parity pin between the borrow-form
2746        // primitive here and the pre-lift `tatara-reconciler
2747        // ::phase_machine` 3-line chain shape. Sweeps every corner
2748        // every callsite plausibly encounters (missing status,
2749        // empty pid slot, populated pid slot). A regression that
2750        // inserted a normalization step at the primitive the pre-
2751        // lift chain does NOT apply — or vice versa — surfaces
2752        // here rather than as silent drift between the pre-lift
2753        // consumer sites and the ONE substrate owner they now
2754        // route through. Peer to
2755        // `observed_flux_resources_matches_pre_lift_reconciler_chain_shape`
2756        // on the flux-resources axis's borrow-form primitive.
2757        fn pre_lift(p: &Process) -> Option<String> {
2758            p.status.as_ref().and_then(|s| s.pid.clone())
2759        }
2760        // Missing status.
2761        let mut p = Process::new("api", empty_spec());
2762        p.status = None;
2763        assert_eq!(p.observed_pid().map(str::to_string), pre_lift(&p));
2764        // Populated status, empty pid slot.
2765        let p = process_with_pid(None);
2766        assert_eq!(p.observed_pid().map(str::to_string), pre_lift(&p));
2767        // Populated status, populated pid slot.
2768        let p = process_with_pid(Some("seph.1.7"));
2769        assert_eq!(p.observed_pid().map(str::to_string), pre_lift(&p));
2770    }
2771
2772    #[test]
2773    fn observed_pid_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
2774        // Cross-corner coherence pin: the missing-`status` corner
2775        // and the populated-empty-slot corner return `Option`s whose
2776        // `.is_none()` observations are IDENTICAL. A regression
2777        // that promoted the missing-`status` corner to returning a
2778        // typed error (via a signature change to `Result<_, _>`) —
2779        // or that widened the empty-slot corner to a synthetic
2780        // `Some("")` — would surface here rather than as silent
2781        // operator-facing divergence between a never-status-
2782        // written Process and a status-emptied Process on the
2783        // ALLOCATE-PID gate.
2784        let mut p_no_status = Process::new("api", empty_spec());
2785        p_no_status.status = None;
2786        let p_empty_slot = process_with_pid(None);
2787        assert_eq!(
2788            p_no_status.observed_pid().is_none(),
2789            p_empty_slot.observed_pid().is_none()
2790        );
2791        assert_eq!(
2792            p_no_status.observed_pid().is_some(),
2793            p_empty_slot.observed_pid().is_some()
2794        );
2795    }
2796
2797    #[test]
2798    fn observed_pid_preserves_hierarchical_pid_format() {
2799        // Format-preservation pin: the hierarchical PID path
2800        // (dotted-segment form `seph.1.7`, matching the ported
2801        // `convergence-controller/src/identity.rs` scheme) reaches
2802        // the caller with segments and separators byte-identical
2803        // to the persisted `String`. A regression that inserted a
2804        // canonicalization pass (a segment-count validator, a
2805        // separator swap `.` → `/`, a leading/trailing whitespace
2806        // trim) would silently misroute the SIGTERM cascade's
2807        // `spec.identity.parent == Some(pid)` comparator against
2808        // children whose `parent` field was authored in the ported
2809        // scheme's exact form.
2810        for pid in ["seph", "seph.1", "seph.1.7", "seph.1.7.42"] {
2811            let p = process_with_pid(Some(pid));
2812            assert_eq!(p.observed_pid(), Some(pid));
2813        }
2814    }
2815
2816    // ─── Process::observed_attestation substrate pins ─────────────────
2817    //
2818    // Pins the borrow-form status-projection primitive on the
2819    // attestation-chain axis that owns the 3-line
2820    // `.status.as_ref().and_then(|s| s.attestation.as_ref())` chain
2821    // the two hand-authored `tatara-reconciler` sites
2822    // (`phase_machine::advance_to_attested` ATTEST composer +
2823    // `render::render_export_jobs` export-Job builder) restated by
2824    // hand pre-lift. Peer to the sibling `observed_pid_*` +
2825    // `observed_flux_resources_*` pin families; all three compose
2826    // the missing-`status` fallback + borrow-form return-shape
2827    // skeleton on distinct `ProcessStatus` slots. Fail-before-pass-
2828    // after granularity: `observed_attestation` did not exist
2829    // pre-lift, so any test invoking it fails to compile pre-lift
2830    // and passes post-lift.
2831
2832    fn sample_attestation(artifact: &str, intent: &str) -> ProcessAttestation {
2833        // Distinct pillar strings so a regression that swapped the
2834        // artifact / intent pillars silently surfaces as an
2835        // equality failure at the composed-root parity pin.
2836        ProcessAttestation::initial(artifact.to_string(), None, intent.to_string())
2837    }
2838
2839    fn process_with_attestation(attestation: Option<ProcessAttestation>) -> Process {
2840        let mut p = Process::new("api-gateway", empty_spec());
2841        p.metadata.namespace = Some("prod".into());
2842        let mut status = ProcessStatus::default();
2843        status.attestation = attestation;
2844        p.status = Some(status);
2845        p
2846    }
2847
2848    #[test]
2849    fn observed_attestation_returns_none_when_status_is_none() {
2850        // Missing-`status` corner pin: the primitive collapses the
2851        // no-status case to `None` so downstream `.is_some()` /
2852        // `if let Some(_)` / `.map(...)` behave identically on a
2853        // `Process` whose status field is `None` and on one whose
2854        // status carries an unpopulated `attestation` slot.
2855        // Matches the pre-lift `.and_then(...)` chain's `None`
2856        // byte-identically at every reconciler consumer's
2857        // downstream shape.
2858        let mut p = Process::new("api", empty_spec());
2859        p.status = None;
2860        assert!(p.observed_attestation().is_none());
2861    }
2862
2863    #[test]
2864    fn observed_attestation_returns_none_when_attestation_slot_is_none() {
2865        // Empty-slot-under-populated-status corner pin: the
2866        // primitive returns `None`, matching the missing-`status`
2867        // corner byte-identically. A regression that treated the
2868        // two corners differently (a `None`-vs-`Some(_)` signal
2869        // that downstream consumers could grep on) would silently
2870        // promote an internal representation detail (whether the
2871        // reconciler has ever written a status subresource) into
2872        // observable behavior at the ATTEST composer's
2873        // seed-vs-chain branch.
2874        let p = process_with_attestation(None);
2875        assert!(p.observed_attestation().is_none());
2876    }
2877
2878    #[test]
2879    fn observed_attestation_returns_borrow_when_slot_is_populated() {
2880        // Happy-path pin: with a populated `status.attestation`
2881        // slot, the primitive returns a borrowed
2882        // `&ProcessAttestation` whose fields match the persisted
2883        // record. A regression that filtered / reshaped /
2884        // canonicalized the record would surface here rather than
2885        // as silent skew at the downstream `prior.next(pillars)`
2886        // chain composer + the ephemeral-export receipt's
2887        // `previous_root` linker.
2888        let att = sample_attestation("art-1", "int-1");
2889        let composed_root = att.composed_root.clone();
2890        let p = process_with_attestation(Some(att));
2891        let observed = p.observed_attestation().expect("populated slot");
2892        assert_eq!(observed.artifact_hash, "art-1");
2893        assert_eq!(observed.intent_hash, "int-1");
2894        assert_eq!(observed.composed_root, composed_root);
2895        assert_eq!(observed.generation, 0);
2896        assert!(observed.previous_root.is_none());
2897    }
2898
2899    #[test]
2900    fn observed_attestation_is_a_zero_copy_borrow_projection() {
2901        // Borrow-discipline pin: the returned reference points at
2902        // the persisted `ProcessAttestation` in place — NOT a fresh
2903        // allocation or a clone. A regression that switched the
2904        // projection to an owned `ProcessAttestation` (via
2905        // `.clone()`) would defeat the zero-copy contract the
2906        // lift's primary strict-widening delivers (the pre-lift
2907        // 3-line chain returned a borrow, but the export-Job
2908        // builder then cloned `composed_root` off it; the post-
2909        // lift primitive preserves the borrow all the way to the
2910        // consumer's own cloning choice). Peer to the sibling
2911        // `observed_pid_is_a_zero_copy_borrow_projection` +
2912        // `observed_flux_resources_is_a_zero_copy_borrow_projection`
2913        // pins on the PID + flux-resources borrow-projection axes.
2914        let att = sample_attestation("art-1", "int-1");
2915        let p = process_with_attestation(Some(att));
2916        let observed = p.observed_attestation().expect("populated slot") as *const _;
2917        let persisted = p.status.as_ref().unwrap().attestation.as_ref().unwrap() as *const _;
2918        assert!(std::ptr::eq(observed, persisted));
2919    }
2920
2921    #[test]
2922    fn observed_attestation_is_a_pure_projection() {
2923        // Purity pin: calling the projection twice on the same
2924        // `Process` returns byte-identical borrows (same pointer).
2925        // A regression that introduced state — a lazy-cached
2926        // reference materialized on first call, a normalization
2927        // step that ran once and cached — would surface here
2928        // rather than as silent drift between the ATTEST composer
2929        // and the ephemeral-export receipt chain on the SAME
2930        // `Process` within one reconcile pass.
2931        let att = sample_attestation("art-1", "int-1");
2932        let p = process_with_attestation(Some(att));
2933        let a = p.observed_attestation().expect("populated slot") as *const _;
2934        let b = p.observed_attestation().expect("populated slot") as *const _;
2935        assert!(std::ptr::eq(a, b));
2936    }
2937
2938    #[test]
2939    fn observed_attestation_matches_pre_lift_reconciler_chain_shape() {
2940        // Byte-identical parity pin between the borrow-form
2941        // primitive here and the pre-lift `tatara-reconciler`
2942        // 3-line chain shape. Sweeps every corner every callsite
2943        // plausibly encounters (missing status, empty attestation
2944        // slot, populated attestation slot). A regression that
2945        // inserted a normalization step at the primitive the pre-
2946        // lift chain does NOT apply — or vice versa — surfaces
2947        // here rather than as silent drift between the pre-lift
2948        // consumer sites and the ONE substrate owner they now
2949        // route through. Peer to
2950        // `observed_pid_matches_pre_lift_reconciler_chain_shape` +
2951        // `observed_flux_resources_matches_pre_lift_reconciler_chain_shape`
2952        // on the PID + flux-resources axes.
2953        // `ProcessAttestation` does not derive `PartialEq` — the
2954        // parity check walks the `composed_root` field (the
2955        // byte-string every downstream consumer keys off) so a
2956        // regression that reshaped the record without touching
2957        // the composed-root observation surfaces here through
2958        // the receipt-chain projection.
2959        fn pre_lift(p: &Process) -> Option<String> {
2960            p.status
2961                .as_ref()
2962                .and_then(|s| s.attestation.as_ref())
2963                .map(|a| a.composed_root.clone())
2964        }
2965        // Missing status.
2966        let mut p = Process::new("api", empty_spec());
2967        p.status = None;
2968        assert_eq!(
2969            p.observed_attestation().map(|a| a.composed_root.clone()),
2970            pre_lift(&p)
2971        );
2972        // Populated status, empty attestation slot.
2973        let p = process_with_attestation(None);
2974        assert_eq!(
2975            p.observed_attestation().map(|a| a.composed_root.clone()),
2976            pre_lift(&p)
2977        );
2978        // Populated status, populated attestation slot.
2979        let p = process_with_attestation(Some(sample_attestation("art-1", "int-1")));
2980        assert_eq!(
2981            p.observed_attestation().map(|a| a.composed_root.clone()),
2982            pre_lift(&p)
2983        );
2984    }
2985
2986    #[test]
2987    fn observed_attestation_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
2988        // Cross-corner coherence pin: the missing-`status` corner
2989        // and the populated-empty-slot corner return `Option`s
2990        // whose `.is_none()` observations are IDENTICAL. A
2991        // regression that promoted the missing-`status` corner to
2992        // returning a typed error (via a signature change to
2993        // `Result<_, _>`) — or that widened the empty-slot corner
2994        // to a synthetic `Some(default_attestation)` — would
2995        // surface here rather than as silent operator-facing
2996        // divergence between a never-status-written Process and
2997        // an attestation-emptied Process on the ATTEST composer's
2998        // seed-vs-chain branch.
2999        let mut p_no_status = Process::new("api", empty_spec());
3000        p_no_status.status = None;
3001        let p_empty_slot = process_with_attestation(None);
3002        assert_eq!(
3003            p_no_status.observed_attestation().is_none(),
3004            p_empty_slot.observed_attestation().is_none()
3005        );
3006        assert_eq!(
3007            p_no_status.observed_attestation().is_some(),
3008            p_empty_slot.observed_attestation().is_some()
3009        );
3010    }
3011
3012    #[test]
3013    fn observed_attestation_preserves_chain_generation_field() {
3014        // Generation-preservation pin: a chained attestation
3015        // (`prior.next(...)` at generation N ≥ 1 with a
3016        // `previous_root` linked to `prior.composed_root`) reaches
3017        // the caller with its `generation` counter + `previous_root`
3018        // link byte-identical to the persisted record. The pre-lift
3019        // ATTEST composer discriminated exactly on this borrow's
3020        // `Some(prior)` vs `None` arm; a regression that dropped
3021        // the chain's `generation` counter (say, by folding
3022        // `next(...)` into a fresh `initial(...)` on every
3023        // reconcile pass) would silently reset every chain and
3024        // orphan every downstream `previous_root` link, but that
3025        // drift is invisible to a Process CRD reader who only
3026        // observes the LATEST composed_root.
3027        let prior = sample_attestation("art-0", "int-0");
3028        let chained = prior.next("art-1".to_string(), None, "int-1".to_string());
3029        let expected_generation = chained.generation;
3030        let expected_previous = chained.previous_root.clone();
3031        let p = process_with_attestation(Some(chained));
3032        let observed = p.observed_attestation().expect("populated slot");
3033        assert_eq!(observed.generation, expected_generation);
3034        assert_eq!(observed.generation, 1);
3035        assert_eq!(observed.previous_root, expected_previous);
3036        assert_eq!(
3037            observed.previous_root.as_deref(),
3038            Some(prior.composed_root.as_str())
3039        );
3040    }
3041
3042    // ─── Process::observed_identity substrate pins ────────────────────
3043    //
3044    // The borrow-form status-projection primitive on the resolved-
3045    // identity axis. Collapses the paired 3-line `.status.as_ref()
3046    // .and_then(|s| s.identity.<clone|as_ref>())` chain every
3047    // consumer in `tatara-reconciler` restated by hand pre-lift at
3048    // TWO sites (`phase_machine::handle_forking` seed +
3049    // `ssapply::inject_annotations` content-hash annotation
3050    // composer). Peer to the sibling `observed_pid_*` +
3051    // `observed_attestation_*` + `observed_flux_resources_*` pin
3052    // families; all four compose the same missing-`status` fallback
3053    // + borrow-form return-shape skeleton on distinct
3054    // `ProcessStatus` slots. Each pin fails-before-pass-after
3055    // granularity: `observed_identity` did not exist pre-lift, so
3056    // any test invoking it fails to compile pre-lift and passes
3057    // post-lift.
3058
3059    fn sample_identity(name: &str) -> Identity {
3060        // Distinct name + content_hash + override flag so a
3061        // regression that reshaped one slot surfaces at the
3062        // populated-slot pin's field-equality check without
3063        // aliasing the sibling slots.
3064        Identity {
3065            name: name.to_string(),
3066            content_hash: "a".repeat(26),
3067            name_override: true,
3068        }
3069    }
3070
3071    fn process_with_identity(identity: Option<Identity>) -> Process {
3072        let mut p = Process::new("api-gateway", empty_spec());
3073        p.metadata.namespace = Some("prod".into());
3074        let mut status = ProcessStatus::default();
3075        status.identity = identity;
3076        p.status = Some(status);
3077        p
3078    }
3079
3080    #[test]
3081    fn observed_identity_returns_none_when_status_is_none() {
3082        // Missing-`status` corner pin: the primitive collapses the
3083        // no-status case to `None` so downstream `.is_some()` /
3084        // `if let Some(_)` / `.cloned().unwrap_or_else(...)` behave
3085        // identically on a `Process` whose status field is `None`
3086        // and on one whose status carries an unpopulated `identity`
3087        // slot. Matches the pre-lift `.and_then(...)` chain's `None`
3088        // byte-identically at every reconciler consumer's
3089        // downstream shape.
3090        let mut p = Process::new("api", empty_spec());
3091        p.status = None;
3092        assert!(p.observed_identity().is_none());
3093    }
3094
3095    #[test]
3096    fn observed_identity_returns_none_when_identity_slot_is_none() {
3097        // Empty-slot-under-populated-status corner pin: the
3098        // primitive returns `None`, matching the missing-`status`
3099        // corner byte-identically. A regression that treated the
3100        // two corners differently (a `None`-vs-`Some(_)` signal
3101        // that downstream consumers could grep on) would silently
3102        // promote an internal representation detail (whether the
3103        // reconciler has ever written a status subresource) into
3104        // observable behavior at the FORK-time `derive_identity`
3105        // fallback branch.
3106        let p = process_with_identity(None);
3107        assert!(p.observed_identity().is_none());
3108    }
3109
3110    #[test]
3111    fn observed_identity_returns_borrow_when_slot_is_populated() {
3112        // Happy-path pin: with a populated `status.identity` slot,
3113        // the primitive returns a borrowed `&Identity` whose fields
3114        // match the persisted record. A regression that filtered /
3115        // reshaped / canonicalized the record would surface here
3116        // rather than as silent skew at the FORK-time seed's
3117        // `.cloned().unwrap_or_else(derive_identity)` composition
3118        // + the SSA-time content-hash annotation stamp on the SAME
3119        // Process.
3120        let id = sample_identity("seph");
3121        let expected = id.clone();
3122        let p = process_with_identity(Some(id));
3123        let observed = p.observed_identity().expect("populated slot");
3124        assert_eq!(observed, &expected);
3125        assert_eq!(observed.name, "seph");
3126        assert_eq!(observed.content_hash, "a".repeat(26));
3127        assert!(observed.name_override);
3128    }
3129
3130    #[test]
3131    fn observed_identity_is_a_zero_copy_borrow_projection() {
3132        // Borrow-discipline pin: the returned reference points at
3133        // the persisted `Identity` in place — NOT a fresh
3134        // allocation or a clone. A regression that switched the
3135        // projection to an owned `Identity` (via `.clone()`) would
3136        // defeat the zero-copy contract the lift's primary strict-
3137        // widening delivers (the SSA-time consumer never clones the
3138        // whole `Identity`, only the `content_hash` field it stamps
3139        // onto the annotation map, so the borrow-form return
3140        // shape's happy-path allocation count is exactly ZERO).
3141        // Peer to the sibling
3142        // `observed_attestation_is_a_zero_copy_borrow_projection`
3143        // + `observed_pid_is_a_zero_copy_borrow_projection` +
3144        // `observed_flux_resources_is_a_zero_copy_borrow_projection`
3145        // pins on the attestation-chain + PID + flux-resources
3146        // borrow-projection axes.
3147        let id = sample_identity("seph");
3148        let p = process_with_identity(Some(id));
3149        let observed = p.observed_identity().expect("populated slot") as *const _;
3150        let persisted = p.status.as_ref().unwrap().identity.as_ref().unwrap() as *const _;
3151        assert!(std::ptr::eq(observed, persisted));
3152    }
3153
3154    #[test]
3155    fn observed_identity_is_a_pure_projection() {
3156        // Purity pin: calling the projection twice on the same
3157        // `Process` returns byte-identical borrows (same pointer).
3158        // A regression that introduced state — a lazy-cached
3159        // reference materialized on first call, a normalization
3160        // step that ran once and cached — would surface here
3161        // rather than as silent drift between the FORK-time
3162        // identity seed and the SSA-time content-hash annotation
3163        // stamp on the SAME `Process` within one reconcile pass.
3164        let p = process_with_identity(Some(sample_identity("seph")));
3165        let a = p.observed_identity().expect("populated slot") as *const _;
3166        let b = p.observed_identity().expect("populated slot") as *const _;
3167        assert!(std::ptr::eq(a, b));
3168    }
3169
3170    #[test]
3171    fn observed_identity_matches_pre_lift_reconciler_chain_shape() {
3172        // Byte-identical parity pin between the borrow-form
3173        // primitive here and the pre-lift `tatara-reconciler`
3174        // 3-line chain shape. Sweeps every corner every callsite
3175        // plausibly encounters (missing status, empty identity
3176        // slot, populated identity slot). A regression that
3177        // inserted a normalization step at the primitive the pre-
3178        // lift chain does NOT apply — or vice versa — surfaces
3179        // here rather than as silent drift between the pre-lift
3180        // consumer sites and the ONE substrate owner they now
3181        // route through. Peer to
3182        // `observed_attestation_matches_pre_lift_reconciler_chain_shape`
3183        // + `observed_pid_matches_pre_lift_reconciler_chain_shape`
3184        // + `observed_flux_resources_matches_pre_lift_reconciler_chain_shape`
3185        // on the attestation-chain + PID + flux-resources axes.
3186        fn pre_lift(p: &Process) -> Option<Identity> {
3187            p.status.as_ref().and_then(|s| s.identity.clone())
3188        }
3189        // Missing status.
3190        let mut p = Process::new("api", empty_spec());
3191        p.status = None;
3192        assert_eq!(p.observed_identity().cloned(), pre_lift(&p));
3193        // Populated status, empty identity slot.
3194        let p = process_with_identity(None);
3195        assert_eq!(p.observed_identity().cloned(), pre_lift(&p));
3196        // Populated status, populated identity slot.
3197        let p = process_with_identity(Some(sample_identity("seph")));
3198        assert_eq!(p.observed_identity().cloned(), pre_lift(&p));
3199    }
3200
3201    #[test]
3202    fn observed_identity_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
3203        // Cross-corner coherence pin: the missing-`status` corner
3204        // and the populated-empty-slot corner return `Option`s
3205        // whose `.is_none()` observations are IDENTICAL. A
3206        // regression that promoted the missing-`status` corner to
3207        // returning a typed error (via a signature change to
3208        // `Result<_, _>`) — or that widened the empty-slot corner
3209        // to a synthetic `Some(derive_identity(default_spec))` —
3210        // would surface here rather than as silent operator-facing
3211        // divergence between a never-status-written Process and an
3212        // identity-cleared Process on the FORK-time seed branch.
3213        let mut p_no_status = Process::new("api", empty_spec());
3214        p_no_status.status = None;
3215        let p_empty_slot = process_with_identity(None);
3216        assert_eq!(
3217            p_no_status.observed_identity().is_none(),
3218            p_empty_slot.observed_identity().is_none()
3219        );
3220        assert_eq!(
3221            p_no_status.observed_identity().is_some(),
3222            p_empty_slot.observed_identity().is_some()
3223        );
3224    }
3225
3226    #[test]
3227    fn observed_identity_cloned_composes_with_derive_identity_fallback() {
3228        // Cross-primitive composition pin: the borrow-form
3229        // primitive threaded through `.cloned().unwrap_or_else(||
3230        // derive_identity(...))` reproduces the pre-lift FORK-time
3231        // seed's owned-`Identity` shape at every corner. Binds the
3232        // exact composition the `phase_machine::handle_forking`
3233        // consumer performs: on the populated-slot corner the
3234        // reconciler-persisted `Identity` is returned verbatim (the
3235        // fallback never fires), and on both empty corners
3236        // (missing-status + empty-slot) the fallback fires
3237        // producing a fresh `derive_identity(&spec,
3238        // name_override)`. A regression that (a) swapped the
3239        // fallback direction, (b) made `.cloned()` re-derive
3240        // instead of clone, or (c) made the empty-slot corner
3241        // return a synthetic `Some(default_identity)` collides
3242        // with the fallback surfaces here rather than as silent
3243        // FORK-time PID allocator skew.
3244        let spec = empty_spec();
3245        let fallback_expected = crate::identity::derive_identity(&spec, None);
3246        // Populated-slot corner: the seed returns the persisted
3247        // identity, NOT the derive fallback.
3248        let persisted = sample_identity("seph");
3249        let p = process_with_identity(Some(persisted.clone()));
3250        let seed = p.observed_identity().cloned().unwrap_or_else(|| {
3251            crate::identity::derive_identity(&p.spec, p.declared_name_override())
3252        });
3253        assert_eq!(seed, persisted);
3254        assert_ne!(seed, fallback_expected);
3255        // Empty-slot corner: the seed fires the derive fallback.
3256        let p = process_with_identity(None);
3257        let seed = p.observed_identity().cloned().unwrap_or_else(|| {
3258            crate::identity::derive_identity(&p.spec, p.declared_name_override())
3259        });
3260        assert_eq!(seed, fallback_expected);
3261        // Missing-status corner: the seed fires the derive
3262        // fallback, byte-identical to the empty-slot corner.
3263        let mut p = Process::new("api-gateway", empty_spec());
3264        p.metadata.namespace = Some("prod".into());
3265        p.status = None;
3266        let seed = p.observed_identity().cloned().unwrap_or_else(|| {
3267            crate::identity::derive_identity(&p.spec, p.declared_name_override())
3268        });
3269        assert_eq!(seed, fallback_expected);
3270    }
3271
3272    // ─── Process::observed_phase substrate pins ───────────────────────
3273    //
3274    // The copy-form status-projection primitive on the phase axis.
3275    // Collapses the paired 3-line `.status.as_ref().map(|s| s.phase)`
3276    // chain every consumer in `tatara-reconciler` restated by hand
3277    // pre-lift at FIVE sites. Peer to the borrow-form
3278    // `observed_pid_*` + `observed_flux_resources_*` +
3279    // `observed_attestation_*` pin families; all four compose the
3280    // same missing-`status` fallback skeleton on distinct
3281    // `ProcessStatus` slots, with the phase-axis form returning
3282    // `Option<ProcessPhase>` (copy of a `Copy` scalar) rather than
3283    // `Option<&T>` (borrow) because the underlying slot is a bare
3284    // `ProcessPhase` — no allocation to borrow past, and the enum
3285    // is one byte on the wire. Each pin fails-before-pass-after
3286    // granularity: `observed_phase` did not exist pre-lift, so any
3287    // test invoking it fails to compile pre-lift and passes
3288    // post-lift.
3289
3290    fn process_with_phase(phase: Option<ProcessPhase>) -> Process {
3291        let mut p = Process::new("api-gateway", empty_spec());
3292        p.metadata.namespace = Some("prod".into());
3293        if let Some(ph) = phase {
3294            let mut status = ProcessStatus::default();
3295            status.phase = ph;
3296            p.status = Some(status);
3297        }
3298        p
3299    }
3300
3301    #[test]
3302    fn observed_phase_returns_none_when_status_is_none() {
3303        // Missing-`status` corner pin: the primitive collapses the
3304        // no-status case to `None` so downstream `.unwrap_or(...)`
3305        // at every reconciler consumer chooses the default
3306        // deliberately (`Pending` for the top-level dispatch seed
3307        // + boundary evaluator + routing groupby; `Attested` for
3308        // the released-from annotation composer). Matches the
3309        // pre-lift `.map(|s| s.phase)` chain's `None`
3310        // byte-identically at every consumer's downstream shape.
3311        let mut p = Process::new("api", empty_spec());
3312        p.status = None;
3313        assert!(p.observed_phase().is_none());
3314    }
3315
3316    #[test]
3317    fn observed_phase_returns_some_default_when_status_is_populated_with_default_phase() {
3318        // Populated-status corner pin: the primitive returns
3319        // `Some(ProcessPhase::default())` — a `ProcessStatus`
3320        // constructed via `default()` carries `phase: Pending`
3321        // because the phase field is a bare `ProcessPhase` (not
3322        // `Option<ProcessPhase>`), so there is NO "empty slot"
3323        // corner peer to the borrow-form projections' empty-slot
3324        // pins. A regression that reshaped the return type to
3325        // filter out `Pending` (treating it as "unset") would
3326        // surface here and silently break the top-level
3327        // dispatcher's Pending → Forking transition on a Process
3328        // freshly written by the reconciler.
3329        let p = process_with_phase(Some(ProcessPhase::default()));
3330        assert_eq!(p.observed_phase(), Some(ProcessPhase::Pending));
3331        assert_eq!(p.observed_phase(), Some(ProcessPhase::default()));
3332    }
3333
3334    #[test]
3335    fn observed_phase_returns_persisted_phase_when_status_is_populated() {
3336        // Happy-path pin: with a populated `status.phase` slot,
3337        // the primitive returns the persisted `ProcessPhase`.
3338        // A regression that filtered / reshaped / canonicalized
3339        // the phase would surface here rather than as silent
3340        // skew at the top-level dispatcher's phase handler
3341        // dispatch on the SAME Process.
3342        let p = process_with_phase(Some(ProcessPhase::Running));
3343        assert_eq!(p.observed_phase(), Some(ProcessPhase::Running));
3344    }
3345
3346    #[test]
3347    fn observed_phase_is_a_pure_projection() {
3348        // Purity pin: two consecutive calls return byte-identical
3349        // `Option<ProcessPhase>` values (no lazy materialization,
3350        // no interior mutation of `self`). Peer to the sibling
3351        // `observed_pid_is_a_pure_projection` +
3352        // `observed_flux_resources_is_a_pure_projection` +
3353        // `observed_attestation_is_a_pure_projection` pins; all
3354        // four bind the pure-projection discipline on the ONE
3355        // substrate accessor per status slot.
3356        let p = process_with_phase(Some(ProcessPhase::Attested));
3357        let a = p.observed_phase();
3358        let b = p.observed_phase();
3359        assert_eq!(a, b);
3360        assert_eq!(a, Some(ProcessPhase::Attested));
3361    }
3362
3363    #[test]
3364    fn observed_phase_matches_pre_lift_reconciler_chain_shape() {
3365        // Parity pin: sweeps the two corners every pre-lift
3366        // consumer plausibly encountered (missing status,
3367        // populated status with a particular phase) and compares
3368        // the substrate call against a hand-authored pre-lift
3369        // chain byte-identically. A regression that reshaped ANY
3370        // of the two corners would surface here rather than as
3371        // silent operator-facing skew between the top-level
3372        // dispatcher and any of the four other reconciler
3373        // consumers on the SAME `Process`.
3374        fn pre_lift(p: &Process) -> Option<ProcessPhase> {
3375            p.status.as_ref().map(|s| s.phase)
3376        }
3377        let mut p = Process::new("api", empty_spec());
3378        p.status = None;
3379        assert_eq!(p.observed_phase(), pre_lift(&p));
3380        let p = process_with_phase(Some(ProcessPhase::Running));
3381        assert_eq!(p.observed_phase(), pre_lift(&p));
3382        let p = process_with_phase(Some(ProcessPhase::Attested));
3383        assert_eq!(p.observed_phase(), pre_lift(&p));
3384        let p = process_with_phase(Some(ProcessPhase::Failed));
3385        assert_eq!(p.observed_phase(), pre_lift(&p));
3386    }
3387
3388    #[test]
3389    fn observed_phase_default_unwrap_matches_pre_lift_pending_default() {
3390        // Callsite-shape pin: three of the FIVE pre-lift consumers
3391        // (`controller::reconcile`, `boundary::evaluate_process_phase`,
3392        // `table_controller::stable_name_group_key`) closed the
3393        // 3-line chain with `.unwrap_or(ProcessPhase::Pending)`
3394        // (identical to `.unwrap_or_default()`). This pin binds
3395        // that call-site shape: `observed_phase().unwrap_or
3396        // (Pending)` returns `Pending` on missing status and the
3397        // persisted phase otherwise. A regression that swapped
3398        // the `None` sentinel's downstream default would surface
3399        // here rather than as silent skew at three of the five
3400        // consumer sites.
3401        let mut p = Process::new("api", empty_spec());
3402        p.status = None;
3403        assert_eq!(
3404            p.observed_phase().unwrap_or(ProcessPhase::Pending),
3405            ProcessPhase::Pending
3406        );
3407        let p = process_with_phase(Some(ProcessPhase::Running));
3408        assert_eq!(
3409            p.observed_phase().unwrap_or(ProcessPhase::Pending),
3410            ProcessPhase::Running
3411        );
3412    }
3413
3414    #[test]
3415    fn observed_phase_attested_unwrap_matches_pre_lift_released_from_default() {
3416        // Callsite-shape pin: the ONE pre-lift consumer
3417        // (`phase_machine::p_current_phase_str` — the
3418        // released-from annotation composer) closed the 3-line
3419        // chain with `.unwrap_or(ProcessPhase::Attested)` rather
3420        // than the `Default` (`Pending`). This pin binds that
3421        // call-site shape: `observed_phase().unwrap_or(Attested)`
3422        // returns `Attested` on missing status and the persisted
3423        // phase otherwise. A regression that folded the
3424        // `Attested`-default consumer into the `Pending`-default
3425        // majority would break the SIGSTOP/SIGCONT release gate's
3426        // "which annotation label to emit" branch — the pin binds
3427        // the primitive at the raw `Option<ProcessPhase>` form so
3428        // this default choice stays local at the callsite.
3429        let mut p = Process::new("api", empty_spec());
3430        p.status = None;
3431        assert_eq!(
3432            p.observed_phase().unwrap_or(ProcessPhase::Attested),
3433            ProcessPhase::Attested
3434        );
3435        let p = process_with_phase(Some(ProcessPhase::Failed));
3436        assert_eq!(
3437            p.observed_phase().unwrap_or(ProcessPhase::Attested),
3438            ProcessPhase::Failed
3439        );
3440    }
3441
3442    #[test]
3443    fn observed_phase_preserves_every_process_phase_variant() {
3444        // Round-trip pin: every `ProcessPhase` variant round-
3445        // trips through the primitive unchanged. Peer to the
3446        // sibling `observed_pid_preserves_hierarchical_pid_format`
3447        // pin's dotted-segment sweep; this pin sweeps the closed
3448        // set of `ProcessPhase` variants directly so a
3449        // canonicalization pass that dropped or reshaped one
3450        // (e.g. folded `Reconverging` back into `Execing`, or
3451        // remapped `Zombie` to `Reaped`) surfaces here rather
3452        // than as silent skew at the SIGSTOP/SIGCONT release
3453        // gate's phase-name annotation branch. Covers every
3454        // variant the `ProcessPhase::DeriveClosedSet` enumerates
3455        // so a future variant addition surfaces via the closed-
3456        // set macro rather than at a silent partial sweep.
3457        for phase in [
3458            ProcessPhase::Pending,
3459            ProcessPhase::Forking,
3460            ProcessPhase::Execing,
3461            ProcessPhase::Running,
3462            ProcessPhase::Attested,
3463            ProcessPhase::Reconverging,
3464            ProcessPhase::Releasing,
3465            ProcessPhase::Exiting,
3466            ProcessPhase::Failed,
3467            ProcessPhase::Zombie,
3468            ProcessPhase::Reaped,
3469        ] {
3470            let p = process_with_phase(Some(phase));
3471            assert_eq!(
3472                p.observed_phase(),
3473                Some(phase),
3474                "phase variant {phase:?} did not round-trip"
3475            );
3476        }
3477    }
3478}