Skip to main content

tatara_process/
lib.rs

1//! Process CRD — the K8s-as-Unix-processes wire format.
2//!
3//! A `Process` is one element of the tatara convergence lattice.
4//! Clusters, HelmReleases, migrations, tests — all are Processes.
5//! The reconciliation loop *is* Unix: fork → exec → wait → exit → reap.
6
7pub mod allocation;
8pub mod anyhow_flatten;
9pub mod api;
10pub mod attestation;
11pub mod boundary;
12pub mod classification;
13pub mod compliance;
14pub mod condition_type;
15pub mod configmap;
16pub mod crd;
17pub mod create;
18pub mod delete;
19pub mod encapsulates;
20pub mod env;
21pub mod ephemeral;
22pub mod err_ctx;
23pub mod export;
24pub mod finalizers;
25pub mod flux_resource;
26pub mod hash;
27pub mod hostname;
28pub mod identity;
29pub mod intent;
30pub mod json_object;
31pub mod k8s_builtin_resource;
32pub mod k8s_condition;
33pub mod k8s_object_ref;
34pub mod k8s_wire_identity;
35pub mod kube_error;
36pub mod lifetime;
37pub mod lifetime_clock;
38pub mod list;
39pub mod matrix;
40pub mod patch;
41pub mod phase;
42pub mod pool;
43pub mod process_api;
44pub mod receipt;
45pub mod requeue;
46pub mod routing;
47pub mod routing_edge_resource;
48pub mod secret_env;
49pub mod serde_defaults;
50pub mod signal;
51pub mod spec;
52pub mod status;
53pub mod string_map;
54pub mod table;
55pub mod tagged_union;
56pub mod three_pillar;
57pub mod time;
58
59pub mod prelude {
60    pub use crate::allocation::{
61        AllocationCondition, AllocationPhase, AllocationSpec, AllocationStatus,
62        EphemeralAllocation, Requestor,
63    };
64    pub use crate::anyhow_flatten::FlattenCtxExt;
65    pub use crate::attestation::ProcessAttestation;
66    pub use crate::boundary::{Boundary, Condition, ConditionKind, UnknownConditionKind};
67    pub use crate::classification::{
68        Arity, CalmClassification, Classification, ConvergencePointType, DataClassification,
69        Horizon, HorizonKind, OptimizationDirection, SubstrateType, UnknownCalmClassification,
70        UnknownConvergencePointType, UnknownDataClassification, UnknownHorizonKind,
71        UnknownOptimizationDirection, UnknownSubstrateType,
72    };
73    pub use crate::compliance::{
74        ComplianceBinding, ComplianceSpec, UnknownVerificationPhase, VerificationPhase,
75    };
76    pub use crate::crd::{Process, ProcessSpec, ProcessStatus};
77    pub use crate::encapsulates::{
78        BareWorkload, EncapsulatesSpec, EncapsulationKind, EncapsulationKindError,
79        EncapsulationKindVariant, EncapsulationMode, EncapsulationTarget, ExistingHelmRelease,
80        ExistingKustomization, UnknownEncapsulationMode, UnknownEncapsulationTarget,
81    };
82    pub use crate::ephemeral::{compile_ephemeral_source, EphemeralSpec};
83    pub use crate::err_ctx::ErrCtxExt;
84    pub use crate::export::{
85        ArtifactError, ArtifactKind, ArtifactSource, ArtifactVariant, ChannelError, ChannelKind,
86        ChannelVariant, ExportSpec, ExportTrigger, HttpEventChannel, NatsSubjectChannel,
87        ProcessSnapshotSource, ReceiptsSource, ReportFormat, ReportPayloadShape, RunMarkerSource,
88        StdoutChannel, TestReportSource, UnknownArtifactKind, UnknownChannelKind,
89        UnknownExportTrigger, UnknownReportFormat, VectorChannel, DEFAULT_NATS_URL,
90        DEFAULT_VECTOR_INGEST,
91    };
92    pub use crate::flux_resource::FluxResource;
93    pub use crate::hash::hex_blake3;
94    pub use crate::hostname::{
95        ephemeral_id_from_spec, fmt_fqdn, fmt_fqdn_stable, resolve_ephemeral_id, HostnameError,
96        HostnameResultExt, EPHEMERAL_ID_HASH_LEN,
97    };
98    pub use crate::identity::{
99        content_hash, derive_identity, format_process_address, join_pid_segment, Identity,
100        PID_PATH_SEPARATOR,
101    };
102    pub use crate::intent::{
103        AplicacaoIntent, ContainerIntent, FluxIntent, GuestIntent, HelmLifecyclePolicy,
104        HelmRemediationPolicy, Intent, IntentError, IntentKind, IntentVariant, LispIntent,
105        NixIntent, UnknownWorkloadKind, WorkloadKind, FLUX_HELM_DEFAULT_INTERVAL,
106        HELM_LIFECYCLE_DEFAULT_RETRIES, HELM_LIFECYCLE_DEFAULT_TIMEOUT,
107    };
108    pub use crate::k8s_builtin_resource::K8sBuiltinResource;
109    pub use crate::k8s_condition::K8sConditionStatus;
110    pub use crate::k8s_object_ref::K8sObjectRef;
111    pub use crate::k8s_wire_identity::K8sWireIdentity;
112    pub use crate::lifetime::{
113        EphemeralLifetime, Lifetime, LifetimeError, LifetimeKind, LifetimeVariant,
114        PermanentLifetime, TeardownPolicy, UnknownTeardownPolicy,
115    };
116    pub use crate::lifetime_clock::{
117        evaluate as lifetime_clock_evaluate, AutoTerminate, AutoTerminateKind, TerminateReason,
118        TerminateReasonKind, UnknownAutoTerminateKind, UnknownTerminateReasonKind,
119    };
120    pub use crate::matrix::{
121        compile_env_matrix_source, EnvMatrixSpec, MatrixAxis, MatrixBudget, NamedEphemeral,
122        SelectStrategy, SelectStrategyKind, UnknownSelectStrategyKind,
123    };
124    pub use crate::phase::{ProcessPhase, UnknownPhase};
125    pub use crate::pool::{
126        AllocationRef, EphemeralPool, MatchKey, MemberState, PoolCondition, PoolMember, PoolPhase,
127        PoolSelector, PoolSpec, PoolStatus, ReplacementPolicy, ReturnPolicy, UnknownMemberState,
128        UnknownPoolPhase, UnknownReplacementPolicy,
129    };
130    pub use crate::receipt::{
131        default_receipt_config_map_name, extract_receipt_payload_json,
132        resolve_receipt_config_map_name, ReceiptEnvelope, ReceiptError, ReceiptKind,
133        ReceiptWireForm, RECEIPT_CM_KEYS, RECEIPT_CM_MISSING_KEY_MSG, RECEIPT_CM_SUFFIX,
134        RECEIPT_JSON_KEY, RECEIPT_VERSION, RECEIPT_YAML_KEY,
135    };
136    pub use crate::requeue::after_secs as requeue_after_secs;
137    pub use crate::routing::{RoutingBackend, RoutingForm, RoutingHostname, RoutingSpec};
138    pub use crate::routing_edge_resource::RoutingEdgeResource;
139    pub use crate::signal::{ProcessSignal, SighupStrategy, UnknownSighupStrategy};
140    pub use crate::spec::{
141        DependsOn, IdentitySpec, MustReachPhase, SignalPolicy, UnknownMustReachPhase,
142    };
143    pub use crate::status::{
144        BoundaryStatus, CheckedCondition, ComplianceStatus, FluxResourceRef, ProcessCondition,
145        RenderedResourceCoords,
146    };
147    pub use crate::table::{
148        ClaimRecord, ProcessEntry, ProcessTable, ProcessTableSpec, ProcessTableStatus,
149    };
150    pub use crate::time::{elapsed_since, seconds_ago, tombstone_at, tombstone_now};
151    pub use crate::{qualified_error_ctx, qualified_process_ref};
152    pub use crate::{Annotated, DeletionTombstoned, NamespacedApiCoordinates, PlacedInNamespace};
153}
154
155/// CRD API group for every tatara CRD.
156pub const GROUP: &str = "tatara.pleme.io";
157/// CRD version for this module.
158pub const VERSION: &str = "v1alpha1";
159
160/// Reverse-DNS group prefix — the `<GROUP>/` byte-shape every
161/// tatara-owned `tatara.pleme.io/*` wire-form key (annotation,
162/// finalizer, label, signal) rides through, and the string every
163/// downstream `.starts_with(...)` group-membership filter compares
164/// against.
165///
166/// Peer to [`GROUP`] + [`VERSION`] + [`API_VERSION`] on the CRD-
167/// group×version axis: where [`GROUP`] owns the bare reverse-DNS
168/// segment (`"tatara.pleme.io"`), [`VERSION`] owns the version
169/// segment, and [`API_VERSION`] owns the two-segment compose product
170/// (`"tatara.pleme.io/v1alpha1"`), this const owns the ONE-segment
171/// `<GROUP>/` product every tatara wire-form key uses as its
172/// namespace prefix (`"tatara.pleme.io/"`). Pre-lift the prefix was
173/// spelled inline as a bare `"tatara.pleme.io/"` literal at TWO
174/// substrate-owner sites — [`annotations::GROUP_PREFIX`] +
175/// [`finalizers::GROUP_PREFIX`] — pinned equal to each other by
176/// [`annotations_family_tests::group_prefix_matches_finalizers_group_prefix`]
177/// but with no shared owner binding them to [`GROUP`] itself. A
178/// future rename that shifted the group segment (a
179/// `"tatara.pleme.io/v2/"` migration under a group-segment bump, a
180/// per-fleet override, an alias table) would silently unbind the two
181/// peer families from the CRD [`GROUP`] itself unless every one of
182/// the three inline literals was updated coherently.
183///
184/// Post-lift the prefix lives at ONE substrate owner here; both
185/// [`annotations::GROUP_PREFIX`] and [`finalizers::GROUP_PREFIX`]
186/// route through this const as compile-time aliases
187/// (`pub const GROUP_PREFIX: &str = crate::GROUP_PREFIX;`), so a
188/// rename of the reverse-DNS root lands at ONE `pub const` here + at
189/// [`GROUP`] with the byte-shape pin
190/// [`owner_reference_tests::group_prefix_const_composes_group_slash_bytewise`]
191/// binding the two consts, rather than at three independent per-
192/// module string literals whose coherence relied on convention.
193///
194/// Byte-shape pinned against `format!("{GROUP}/")` by
195/// [`owner_reference_tests::group_prefix_const_composes_group_slash_bytewise`]
196/// (sibling to `api_version_const_composes_group_and_version_bytewise`
197/// on the same GROUP-composition axis) so a rename of [`GROUP`] that
198/// missed this const surfaces HERE rather than as silent skew between
199/// [`GROUP`] (which the [`api_url_prefix`] composer feeds) and every
200/// downstream `<key>.starts_with(GROUP_PREFIX)` gate on the peer
201/// [`annotations::ALL`] / [`finalizers::ALL`] families.
202pub const GROUP_PREFIX: &str = "tatara.pleme.io/";
203/// Kind spelling of the tatara Process CRD as it appears in a K8s
204/// [`OwnerReference.kind`][ownref] field. Peer to [`GROUP`] +
205/// [`VERSION`] — centralizes the ONE literal every SSA-time
206/// re-injection helper pre-lift restated by hand across
207/// `tatara-reconciler` (`render.rs`, `edges.rs`, `ssapply.rs`).
208///
209/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
210pub const PROCESS_KIND: &str = "Process";
211
212/// Canonical `<GROUP>/<VERSION>` `apiVersion` string as a compile-time
213/// `&'static str` — the ONE typed wire-form binding every tatara CRD
214/// stamps on its own `apiVersion` slot.
215///
216/// Peer to [`GROUP`] + [`VERSION`] on the CRD-group×version axis:
217/// where those two consts own the group segment + the version segment
218/// separately (each addressable in its own right — the [`api_url_prefix`]
219/// composer weaves them into the REST-URL envelope, `#[kube(group = ...,
220/// version = ...)]` derive slots on every tatara CRD struct address
221/// them individually), this const owns the two-segment compose product
222/// every wire-form emit — every K8s `apiVersion:` slot the reconciler
223/// stamps + every [`PROCESS_WIRE_IDENTITY`] projection — routes
224/// through.
225///
226/// Byte-shape pinned against `format!("{GROUP}/{VERSION}")` by
227/// [`owner_reference_tests::api_version_const_composes_group_and_version_bytewise`]
228/// so a rename of [`GROUP`] or a version bump on [`VERSION`] that
229/// missed the const surfaces HERE rather than as silent SSA-apply
230/// skew at every downstream OwnerReference / apiVersion-slot emit
231/// site.
232///
233/// Sibling to the runtime [`api_version`] fn — [`API_VERSION`] is the
234/// `&'static str` typed form (const-callable, feeds
235/// [`PROCESS_WIRE_IDENTITY`]); [`api_version`] returns
236/// [`API_VERSION`]`.to_string()` for owned-String call sites (SSA
237/// re-injection helpers that thread the `apiVersion` slot through a
238/// per-site cloned map).
239pub const API_VERSION: &str = "tatara.pleme.io/v1alpha1";
240
241/// Typed K8s wire-form identity of the tatara `Process` CRD — the
242/// [`k8s_wire_identity::K8sWireIdentity`] projection carrying
243/// `(apiVersion, kind) = (API_VERSION, PROCESS_KIND)` at ONE
244/// compile-time `const`.
245///
246/// Peer on the K8s-wire-form-identity axis-family to the three
247/// pre-existing closed-set `.wire_identity()` projections:
248///
249/// * [`k8s_builtin_resource::K8sBuiltinResource::wire_identity`] owns
250///   the K8s built-in axis (`Job` / `ConfigMap`) — the resources the
251///   reconciler fetches from Kubernetes itself.
252/// * [`flux_resource::FluxResource::wire_identity`] owns the
253///   FluxCD-controller axis (`Kustomization` / `HelmRelease` /
254///   `OCIRepository`).
255/// * [`routing_edge_resource::RoutingEdgeResource::wire_identity`]
256///   owns the routing-edge axis (`Ingress` / `DNSEndpoint`).
257/// * [`PROCESS_WIRE_IDENTITY`] (this const) owns the tatara `Process`
258///   CRD's own wire-form identity — pre-lift the fourth arm was the
259///   open corner every peer closed-set called out in its own docs as
260///   "the tatara `Process` CRD's `(apiVersion, kind)` pair" but which
261///   itself lived only as two disjoint consts + a runtime
262///   [`api_version`] fn threaded through the [`owner_reference_json`]
263///   composer's hand-inlined `json!` slots.
264///
265/// Together the four owners partition every K8s wire-form identity
266/// the workspace's reconcilers reach at run time; the pin
267/// [`owner_reference_tests::process_wire_identity_is_disjoint_from_every_peer_wire_form_axis`]
268/// binds the four axes pairwise-distinct at fail-before-pass-after
269/// granularity so a future variant addition on any peer that
270/// accidentally overlapped this pair (a hypothetical
271/// `K8sBuiltinResource::Process` copy-paste, a Flux-side `Process`
272/// naming collision) surfaces at that pin rather than as silent
273/// cross-axis ambiguity at every reconciler dispatch.
274///
275/// Consumed by [`owner_reference_json`] via
276/// [`k8s_wire_identity::K8sWireIdentity::resource_json`] — pre-lift
277/// the OwnerReference composer hand-inlined the (apiVersion, kind)
278/// pair as two adjacent `json!` slots referencing [`api_version`] +
279/// [`PROCESS_KIND`] separately, leaving a silent-drift path where a
280/// copy-paste that dropped ONE reference (an `apiVersion` bump that
281/// missed the sibling `kind`, a rename of one const that didn't
282/// touch the other) would emit an OwnerReference no K8s controller
283/// recognizes (a 404 at wire time diagnosed as a broken CRD). Post-
284/// lift the emit routes through the ONE typed pair, and the drift
285/// trap is unrepresentable — a caller cannot skew the two slots
286/// because the composer takes the identity as a single struct.
287///
288/// A future consumer of the tatara `Process` wire-form identity — a
289/// second OwnerReference emit site (P3 kenshi-runner's
290/// `TestSuiteBinding` owner-ref, a P1 caixa-tatara-emitted
291/// `HelmRelease`'s parent-Process reference), a future admission-
292/// webhook that filters on the CRD's `(apiVersion, kind)` pair, a
293/// fleet-wide audit walker enumerating every tatara-owned resource —
294/// reads through this ONE const rather than re-composing the pair
295/// from [`API_VERSION`] + [`PROCESS_KIND`] separately.
296///
297/// Theory grounding: THEORY.md §II.1 invariant 5 — composition
298/// preserves proofs. The two-slot (apiVersion, kind) composition
299/// lives at ONE typed algebra projection here; a regression that
300/// drifted either slot surfaces at this module's pins rather than as
301/// silent operator-visible OwnerReference skew. THEORY.md §III —
302/// typescape. The typed [`k8s_wire_identity::K8sWireIdentity`] pair
303/// bounds the axis of variation at the type level — a callsite that
304/// receives a `K8sWireIdentity` cannot skew the two slots at compose
305/// time.
306pub const PROCESS_WIRE_IDENTITY: k8s_wire_identity::K8sWireIdentity =
307    k8s_wire_identity::K8sWireIdentity::new(API_VERSION, PROCESS_KIND);
308
309/// Canonical `<GROUP>/<VERSION>` as an owned `String` — the ONE
310/// K8s `apiVersion` shape every tatara CRD stamps. Delegates to the
311/// compile-time [`API_VERSION`] const so a bump of [`GROUP`] or
312/// [`VERSION`] that missed the const surfaces at
313/// [`owner_reference_tests::api_version_const_composes_group_and_version_bytewise`]
314/// rather than as silent skew between the runtime fn and the typed
315/// [`PROCESS_WIRE_IDENTITY`] const that shares the same wire form.
316///
317/// Pre-lift, two `tatara-reconciler` sites hand-wrote
318/// `format!("{}/{}", tatara_process::GROUP, tatara_process::VERSION)`
319/// while a third inlined the literal `"tatara.pleme.io/v1alpha1"`,
320/// opening a silent drift path if [`VERSION`] ever advances past
321/// `v1alpha1`; both are covered by the ONE substrate owner here.
322pub fn api_version() -> String {
323    API_VERSION.to_string()
324}
325
326/// Canonical `/apis/<GROUP>/<VERSION>/` prefix as an owned `String` —
327/// the ONE K8s REST-path shape every typed `Api::namespaced` /
328/// `Api::all` primitive built off a tatara CRD kind (`Process`,
329/// `ProcessTable`, `EphemeralPool`, `EphemeralAllocation`) emits at
330/// [`kube::Api::resource_url`]. Peer to [`api_version`] — composed
331/// from the SAME [`GROUP`] + [`VERSION`] pair, wrapped in the fixed
332/// `/apis/{…}/` HTTP-path envelope that the K8s API server exposes
333/// every custom-resource group under.
334///
335/// Pre-lift the wire-form literal `"/apis/tatara.pleme.io/v1alpha1/"`
336/// recurred at ELEVEN hand-authored sites across three separate test
337/// modules — six across `tatara-reconciler::context` (`process_api`,
338/// `process_table_api`, `processes_all_api` scope pins), four across
339/// `tatara-pool-reconciler::context` (`pool_api`, `allocation_api`,
340/// `pools_all_api`, `allocations_all_api` scope pins), and one at
341/// `tatara-github-watcher::handler` (`allocation_api` scope pin) —
342/// each restating the same URL prefix a bump of `GROUP` or `VERSION`
343/// would silently miss at every one. Post-lift each of the eleven
344/// sites composes the prefix through this substrate function, so a
345/// future group rename or `v1alpha1` → `v1beta1` bump lands at ONE
346/// composer and the eleven downstream scope guards inherit the shape
347/// mechanically.
348///
349/// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
350/// proofs. A regression that drifted the URL prefix at ONE site (a
351/// group typo, a `/apis/` → `/api/` mis-spelling, a stale `v1alpha1`
352/// left behind after a workspace-wide `VERSION` bump) surfaces at the
353/// [`api_url_prefix_tests`] pins below rather than as silent
354/// scope-guard drift between the three reconciler + watcher test
355/// suites (which pre-lift already disagreed with each other on
356/// nothing but were free to drift independently).
357#[must_use]
358pub fn api_url_prefix() -> String {
359    format!("/apis/{GROUP}/{VERSION}/")
360}
361
362/// Substrate-primitive composer for the canonical
363/// **namespace-qualified process reference** — the `<ns>/<name>`
364/// string every consumer that grepped, keyed, or annotated a
365/// Process by "which cluster location owns it" hand-authored as
366/// `format!("{ns}/{name}")` at scattered sites across the workspace.
367/// Lifted onto `tatara-process` (from its prior home at
368/// `tatara_reconciler::ssapply::qualified_process_ref`) so callers
369/// BELOW the reconciler layer — `tatara-export-worker` (which does
370/// NOT depend on `tatara-reconciler`) and `tatara-pool-reconciler` —
371/// reach the SAME composer the reconciler-side sites do, closing
372/// the previously-open substrate corner where a downstream consumer
373/// re-authored the shape by hand rather than routing through the
374/// ONE primitive.
375///
376/// The `<ns>/<name>` shape is the workspace-wide convention for
377/// "how to name a namespaced K8s resource in a single string" — the
378/// same shape the K8s API server itself uses in
379/// [`OwnerReference`][ownref] pretty-printing, in the `holder` slot of
380/// [`crate::table::ClaimRecord`], and in the `tatara.pleme.io/process`
381/// annotation every reconciler-emitted resource carries. Callers
382/// with a live [`crate::prelude::Process`] compose through
383/// [`crate::prelude::Process::coordinates_or_defaults`] +
384/// [`Self`] (this function); callers with bare
385/// `(ns: &str, name: &str)` params (CLI-arg driven binaries,
386/// `metadata`-agnostic composers) call this directly.
387///
388/// The 2-arg signature encodes the invariant "the qualified
389/// reference is EXACTLY `<ns>/<name>`, in that order, joined by a
390/// single `/` separator" at the type level — a caller cannot
391/// accidentally swap the two axes (which would produce `<name>/<ns>`
392/// and silently break every downstream grep) nor omit either half,
393/// the way a pre-lift hand-authored `format!("{name}/{ns}")` or
394/// `format!("{ns}-{name}")` typo would.
395///
396/// A future change to the reference shape — a `<ns>/<name>@<gen>`
397/// multi-generation variant for attestation grepping, a
398/// `<cluster>/<ns>/<name>` cross-cluster form, a normalization
399/// (case-fold, unicode-safe collation) that must apply everywhere —
400/// lands at ONE substrate function here and every downstream
401/// composer (annotation seed, ProcessTable claim key, label
402/// selector, owner metadata, export-worker run-id fallback,
403/// receipt-owner filter) inherits the upgrade mechanically.
404///
405/// Theory anchor: THEORY.md §VI.1 (generation over composition —
406/// the `<ns>/<name>` shape recurred at hand-authored sites past the
407/// ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted onto
408/// the ONE workspace-wide owner here). THEORY.md §II.1 invariant 5
409/// (composition preserves proofs — a regression that swapped the
410/// two axes or the separator at ONE site surfaces at
411/// [`qualified_process_ref_tests::qualified_process_ref_joins_ns_and_name_with_slash`]
412/// rather than as silent drift at every downstream annotation seed
413/// / claim key / label selector / run-id / receipt-owner filter).
414///
415/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
416#[must_use]
417pub fn qualified_process_ref(ns: &str, name: &str) -> String {
418    format!("{ns}/{name}")
419}
420
421/// Substrate-primitive composer for the workspace-canonical
422/// **`<verb> <Kind> <ns>/<name>`** diagnostic-body head every
423/// per-Kind [`error_ctx`][crate::configmap::error_ctx] peer wraps
424/// around a wire-verb failure against a namespaced K8s resource
425/// (through [`crate::kube_error::KubeResultExt::kube_ctx_with`] on
426/// the reconciler-boundary consumers or through
427/// [`anyhow::Context::with_context`] on the export-worker
428/// consumers).
429///
430/// Owns the fixed 4-slot shape at ONE substrate site, routing the
431/// `<ns>/<name>` join through the workspace-wide
432/// [`qualified_process_ref`] composer so a future normalization of
433/// the qualified-ref shape (case-fold, unicode collation, IDN) lands
434/// at ONE site and every per-Kind diagnostic body picks it up
435/// mechanically.
436///
437/// Pre-lift the 4-slot shape recurred at TWO peer per-Kind
438/// composers in this crate past the ★★ PRIME-DIRECTIVE ≥ 2
439/// duplication threshold, each restating the SAME
440/// `format!("{verb} <Kind> {}", qualified_process_ref(ns, name))`
441/// incantation with only the fixed `<Kind>` literal differing:
442///
443/// * [`crate::configmap::error_ctx`] — the ConfigMap-axis per-Kind
444///   composer (`<Kind> = "ConfigMap"`), routing the closed-loop
445///   probe's receipt-CM writer + the export-worker's SSA-side
446///   ConfigMap writer through ONE substrate slug.
447/// * [`crate::process_api::error_ctx`] — the tatara-CRD
448///   Process-axis per-Kind composer (`<Kind> = "Process"`), routing
449///   the reconciler-boundary ProcessPhase evaluator + the
450///   export-worker's ProcessSnapshotSource reader through ONE
451///   substrate slug.
452///
453/// Both peers walked the SAME 4-slot shape — take a verb, a fixed
454/// `&'static str` per-Kind literal (`"ConfigMap"` / `"Process"`),
455/// and the target resource's namespace + name — and produced the
456/// SAME `"<verb> <Kind> <ns>/<name>"` diagnostic head. Post-lift
457/// each per-Kind composer reads
458/// `crate::qualified_error_ctx(<verb>, "<Kind>", ns, name)` as a
459/// one-line delegate, and the shared 4-slot shape lives at ONE
460/// substrate owner here. A future third + fourth per-Kind composer
461/// (a `crate::secret::error_ctx` for the K8s `Secret` axis, a
462/// `crate::job::error_ctx` for the `batch/v1::Job` axis a future
463/// `ConditionKind::JobAttested` companion reader might open, a
464/// `crate::helm_release::error_ctx` for the FluxCD `HelmRelease`
465/// axis the P2 reconciler already emits) inherits the 4-slot shape
466/// through THIS composer, pinning only its own `&'static str` Kind
467/// literal.
468///
469/// ### Naming — `qualified_error_ctx`, not `error_ctx`
470///
471/// The bare `error_ctx` name is already taken at each per-Kind
472/// composer's module ([`crate::configmap::error_ctx`],
473/// [`crate::process_api::error_ctx`], [`crate::list::error_ctx`]),
474/// each closing its own per-Kind or per-verb axis. This composer's
475/// `qualified_error_ctx` name is deliberately distinct so a caller
476/// with any of the per-Kind modules in scope cannot resolve to the
477/// wrong composer by accident (which would silently drop the
478/// per-Kind literal at the callsite). The `qualified_` prefix names
479/// the routing invariant: the `<ns>/<name>` join at the composer's
480/// tail rides through [`qualified_process_ref`], the SAME workspace-
481/// wide substrate every per-Kind peer already routes through.
482///
483/// ### 4-slot shape, not 3
484///
485/// The `kind` slot is required — the pre-lift per-Kind composers
486/// hard-coded their Kind literal as a `&'static str` at each
487/// `format!` chain, and post-lift the composer keeps that Kind
488/// literal at the caller so the K8s-canonical TitleCase spelling
489/// stays visible in the callsite's grep footprint. A future
490/// caller with a dynamically-composed Kind slot (a CRD-family
491/// walker that renders errors for every `ProcessTable` /
492/// `EphemeralPool` / `EphemeralAllocation` variant at one call)
493/// still reaches through this same 4-slot signature — the `&str`
494/// bound on `kind` accepts both `&'static str` literals (the
495/// per-Kind peer shape) and runtime-composed `&str` slices (the
496/// dynamic-Kind walker shape).
497///
498/// ### `#[must_use]`
499///
500/// The returned `String` is consumed by [`crate::kube_error::
501/// KubeResultExt::kube_ctx_with`], by
502/// [`anyhow::Context::with_context`]'s owned-`String`-returning
503/// closure form, or by the sibling [`crate::err_ctx::ErrCtxExt::
504/// err_ctx_with`] owned-string escape hatch. Dropping the return
505/// silently drops the diagnostic head entirely, which is never the
506/// intended semantic at any pre-lift or post-lift consumer.
507///
508/// Theory anchor: THEORY.md §VI.1 (generation over composition —
509/// the 4-slot `<verb> <Kind> <ns>/<name>` shape recurred at 2 peer
510/// per-Kind composers past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
511/// trigger, and is lifted onto the ONE workspace-wide substrate
512/// owner here). THEORY.md §II.1 invariant 5 (composition preserves
513/// proofs — a regression that reordered the head slots, dropped
514/// the fixed `<Kind>` word, or routed the `<ns>/<name>` join
515/// through a bare inline `format!` — bypassing
516/// [`qualified_process_ref`] — surfaces at
517/// [`qualified_error_ctx_tests`] rather than as silent drift across
518/// every per-Kind diagnostic body and every future per-Kind peer
519/// that opens on this composer).
520#[must_use]
521pub fn qualified_error_ctx(verb: &str, kind: &str, ns: &str, name: &str) -> String {
522    format!("{verb} {kind} {}", qualified_process_ref(ns, name))
523}
524
525/// Build a Kubernetes [`OwnerReference`][ownref] JSON blob pointing
526/// at a Process (`kind = `[`PROCESS_KIND`], `apiVersion = `
527/// [`api_version`]) with `controller: true` +
528/// `blockOwnerDeletion: true` — the exact 6-slot shape every SSA
529/// re-injection site pre-lift restated three times across
530/// `tatara-reconciler` (`render.rs::owner_refs` for export-Job
531/// owners, `edges.rs::build_owner_refs` for Ingress + DNSEndpoint
532/// owners, `ssapply.rs::build_owner_reference` for the injected
533/// owner-ref stamped on every applied `DynamicObject`). Callers
534/// with a live `Process` value read `metadata.{name,uid}` and pass
535/// them through as `&str`.
536///
537/// The 6-slot shape is fixed (`controller` + `blockOwnerDeletion`
538/// both `true`); a Process-owned resource that wants a non-
539/// controller reference doesn't belong on this owner and can build
540/// its own `json!` inline — this primitive is the composer for the
541/// canonical "Process controls this resource, cascade-delete on
542/// GC" shape, not a general OwnerReference builder.
543///
544/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
545pub fn owner_reference_json(name: &str, uid: &str) -> serde_json::Value {
546    // Route the (apiVersion, kind) pair through the ONE typed
547    // wire-identity const [`PROCESS_WIRE_IDENTITY`] via
548    // [`k8s_wire_identity::K8sWireIdentity::resource_json`] — the
549    // composer stamps the identity slots on top of the caller's
550    // 4-slot extras map (name / uid / controller / blockOwnerDeletion)
551    // and the identity slots win over any accidental extras collision
552    // by construction. Pre-lift the two identity slots were hand-
553    // inlined as adjacent `json!` slots referencing `api_version()` +
554    // `PROCESS_KIND` separately, so a copy-paste that dropped one
555    // reference (or drifted one const under a group rename) would
556    // silently emit an OwnerReference no K8s controller recognizes.
557    // Post-lift the wire-form pair binds structurally at ONE typed
558    // [`PROCESS_WIRE_IDENTITY`] const and the drift trap is
559    // unrepresentable.
560    PROCESS_WIRE_IDENTITY.resource_json(serde_json::json!({
561        "name": name,
562        "uid": uid,
563        "controller": true,
564        "blockOwnerDeletion": true,
565    }))
566}
567
568/// Substrate-primitive builder for a Process-owned resource's
569/// **`metadata.ownerReferences` array** — the empty-uid-gated,
570/// single-entry `Vec<Value>` every emit site that lacks a fully
571/// materialized [`crate::prelude::Process`] (i.e. every site that
572/// works from a bare `(name, uid)` pair rather than routing through
573/// [`ssapply::build_owner_reference`](../tatara_reconciler/ssapply/fn.build_owner_reference.html)'s
574/// anyhow-guarded unwrap) hand-composed by wrapping
575/// [`owner_reference_json`] in a `Vec::new()` + `is_empty` gate on
576/// the `uid` slot.
577///
578/// The `uid.is_empty()` gate encodes the invariant every caller
579/// already enforced: a Process pre-metadata (fixtured in tests, or
580/// caught mid-Forking before the API server has stamped a `uid`) has
581/// no admissible owner reference to point at, so the emit site
582/// stamps `metadata.ownerReferences: []` rather than an
583/// owner-referenceless resource pointing at a placeholder uid the K8s
584/// GC would silently ignore. Post-lift the gate lives at ONE
585/// primitive so a regression that inlined an owner reference for
586/// an empty uid — which the API server accepts and quietly detaches
587/// from cascade-delete — surfaces at THIS primitive's pin rather
588/// than as an operator-visible ownerless resource after apply.
589///
590/// Pre-lift the 3-line `let mut owner_refs = vec![]; if
591/// !uid.is_empty() { owner_refs.push(owner_reference_json(name,
592/// uid)); }` incantation was hand-authored at TWO sites past the
593/// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
594/// `tatara-reconciler`, each restating the same gated composition:
595/// * `edges::build_owner_refs` — the shared owner-refs builder both
596///   `IngressEdge` + `DnsEndpointEdge` route through, sourcing
597///   `(process_name, process_uid)` from the [`crate::edges::EdgeContext`].
598/// * `render::one_export_job` — the export Job's owner-refs seed,
599///   sourcing `(name, uid)` from the [`crate::prelude::Process`]
600///   `render_export_jobs` threaded in.
601///
602/// Post-lift both callsites read `owner_references_json(name, uid)`.
603/// A future addition — e.g. a second owner-reference slot naming a
604/// controlling ProcessTable entry, a policy that stamps a stale-uid
605/// warning annotation before returning empty, or a normalization
606/// that strips a cluster-prefix off the uid — lands at ONE
607/// substrate function here and every emit site inherits the upgrade
608/// mechanically. The [`ssapply::build_owner_reference`] path (which
609/// works from a materialized [`crate::prelude::Process`] and errors
610/// on absent `metadata.uid`) is a peer, not a lift candidate: its
611/// contract is "the K8s API server assigned a uid, so refuse to
612/// SSA-apply resources whose owner cannot be materialized", while
613/// this primitive's contract is "the caller has an optional-uid
614/// posture; emit `[]` when the uid is absent". The two shapes
615/// partition the input space at the "is the enclosing scope
616/// obligated to produce a materialized Process reference" axis.
617///
618/// The 2-arg `(&str, &str)` signature accepts both the
619/// `EdgeContext`-sourced `(&str, &str)` slice shape and the
620/// `render_export_jobs`-owned `(name: &str, uid: &str)` local shape
621/// without widening — matches every current callsite.
622pub fn owner_references_json(name: &str, uid: &str) -> Vec<serde_json::Value> {
623    if uid.is_empty() {
624        vec![]
625    } else {
626        vec![owner_reference_json(name, uid)]
627    }
628}
629
630/// Substrate-primitive trait for the **`Api::namespaced`-shaped
631/// coordinate extraction** every tatara-CRD reconciler restated by
632/// hand at its top-level `reconcile` dispatcher: pull owned `String`
633/// forms of `metadata.namespace` and `metadata.name` and refuse to
634/// substitute a workspace-wide default for either slot, because the
635/// caller is about to feed the pair positionally into
636/// `Api::namespaced(client, &ns)` + `Api::patch(&name, …)` and the
637/// K8s API server refuses an empty-string name / namespace path
638/// segment.
639///
640/// Pre-lift the 5-line `.metadata.<slot>.clone().ok_or_else(||
641/// anyhow!("<Kind> has no metadata.<slot>"))?` chain (paired at both
642/// slots inside every controller's `reconcile_inner`) was hand-
643/// authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
644/// threshold in `tatara-pool-reconciler`, each restating the SAME
645/// (`namespace` errors, then `name` errors, both owned `String`)
646/// contract on a different CRD:
647/// * `controller_pool::reconcile_inner` — the pool reconciler's
648///   top-level `Pool has no metadata.{namespace,name}` gate,
649///   funneling every subsequent `Api::namespaced` + `Api::patch` call
650///   through the extracted `(ns, name)` pair.
651/// * `controller_allocation::reconcile_inner` — the allocation
652///   reconciler's peer gate on `EphemeralAllocation`, funneling the
653///   `Api::namespaced` + `Api::patch_status` calls that follow.
654///
655/// Both sites walked the SAME 5-line paired chain and both wanted the
656/// `(String, String)` form the primitive returns — because the
657/// produced `ns` outlives the source-object borrow (it feeds
658/// `Api::namespaced(client, &ns)` and later log-line interpolations
659/// across a stretch of `.await` points) and the `name` similarly
660/// threads through `Api::patch(&name, …)` calls downstream. Post-lift
661/// each callsite reads `pool.owned_coordinates_required()?` /
662/// `alloc.owned_coordinates_required()?` and the produced tuple
663/// destructures into the same downstream slots unchanged.
664///
665/// The blanket impl over `kube::Resource<DynamicType = ()>` (which
666/// every `#[derive(CustomResource)]`-generated tatara CRD satisfies)
667/// closes the substrate corner ONCE for the entire workspace: adding
668/// a third or fourth CRD in a peer crate — a routing-edge object, a
669/// receipt registry — inherits the extractor for free at its own
670/// `reconcile_inner` dispatcher with zero per-CRD lift work. This is
671/// the direction the CSE Compounding Directive names by
672/// "solve once, load-bearing fixes only": the primitive lands once
673/// and every downstream controller pattern-matches into it without
674/// re-authoring the chain.
675///
676/// Peer to [`crate::prelude::Process::owned_coordinates_or_err`] on
677/// the (`Process`-specific × namespace-required) axis pair — the two
678/// primitives partition the workspace's owned-form coordinate
679/// extraction on the `namespace-required` axis and cover the
680/// per-CRD needs they were opened for:
681///
682/// * ns-defaulted, name-required, `Process`-inherent →
683///   [`crate::prelude::Process::owned_coordinates_or_err`]
684///   (`tatara-reconciler`'s `phase_machine` / `signals` callers —
685///   consumers whose downstream tolerates the workspace's
686///   [`crate::prelude::Process::DEFAULT_NAMESPACE`] substitute for a
687///   `Process` fixtured pre-namespace-defaulting).
688/// * ns-required + name-required, blanket over every CRD → **this
689///   method** (`tatara-pool-reconciler`'s pool + allocation reconciler
690///   callers — consumers whose downstream refuses BOTH substitutions
691///   because the `Api::namespaced` dispatcher expects a real path
692///   segment on each axis and the enclosing controller is not
693///   authored to run against a namespace-less pool / allocation).
694///
695/// The error strings are shaped as `"{Kind} has no metadata.{slot}"`
696/// with `{Kind}` pulled positionally from `Self::kind(&())` (the
697/// kube-rs canonical CRD kind — `"EphemeralPool"` / `"EphemeralAllocation"`
698/// — which matches `kubectl get ephemeralpools|ephemeralallocations`
699/// output verbatim rather than the pre-lift `"Pool"` / `"Allocation"`
700/// short-forms every callsite hard-coded by hand). Routing the type
701/// name through `Self::kind` closes the drift path where a future
702/// CRD rename or a copy-paste consumer inherited the wrong short-
703/// form; the K8s-kind spelling is the ONE canonical name every
704/// operator-facing surface (kubectl output, RBAC subject strings,
705/// audit-log entries) already uses, so a log-line consumer greppping
706/// for either kind hits the primitive's canonical spelling directly.
707///
708/// A future normalization step (a per-CRD namespace canonicalization
709/// pass — case-fold, unicode-safe path-segment validation, a shared
710/// [`crate::prelude::Process::DEFAULT_NAMESPACE`]-aware fallback
711/// mode gated by an argument) lands at ONE substrate trait method
712/// here and every downstream reconciler picks up the upgrade
713/// mechanically — no per-callsite hand-edit at `controller_pool` /
714/// `controller_allocation` / any future CRD's `reconcile_inner`.
715///
716/// Theory anchor: THEORY.md §VI.1 (generation over composition —
717/// the paired 5-line `.metadata.<slot>.clone().ok_or_else` chain
718/// recurred at two hand-authored sites past the ★★ PRIME-DIRECTIVE
719/// ≥ 2 duplication trigger, and is lifted onto ONE trait method
720/// here). THEORY.md §II.1 invariant 5 (composition preserves
721/// proofs — the pins bind the missing-namespace corner, the
722/// missing-name corner, the missing-both corner (namespace error
723/// wins), the both-slots-present happy path, AND the
724/// `Self::kind`-driven error-string spelling per CRD, so a
725/// regression that reordered the two `ok_or_else` gates or drifted
726/// the error prefix surfaces at `tests::owned_coordinates_required_*`
727/// rather than as silent operator-facing skew between the two
728/// reconcilers' top-level error-message shapes).
729pub trait NamespacedApiCoordinates: kube::Resource<DynamicType = ()> {
730    /// Extract the K8s API path coordinates as owned `String`s,
731    /// erroring with a `Self::kind`-prefixed message when either
732    /// slot is absent. See the trait-level docs for the axis-family
733    /// context, peer primitives, and future-normalization anchor.
734    fn owned_coordinates_required(&self) -> anyhow::Result<(String, String)> {
735        let meta = self.meta();
736        let ns = meta
737            .namespace
738            .clone()
739            .ok_or_else(|| anyhow::anyhow!("{} has no metadata.namespace", Self::kind(&())))?;
740        let name = meta
741            .name
742            .clone()
743            .ok_or_else(|| anyhow::anyhow!("{} has no metadata.name", Self::kind(&())))?;
744        Ok((ns, name))
745    }
746}
747
748impl<T> NamespacedApiCoordinates for T where T: kube::Resource<DynamicType = ()> {}
749
750/// Substrate-primitive trait for the **deletion-tombstone presence
751/// probe** every tatara CRD reconciler restated as
752/// `.metadata.deletion_timestamp.is_some()` on the K8s-API-server-
753/// stamped `metadata.deletionTimestamp` slot: a `true` reading means
754/// the API server has accepted a DELETE and finalizers are draining
755/// (the object is still live but the controller must move into its
756/// SIGTERM cascade / DELETE-skip branch), while a `false` reading
757/// means no delete is in flight.
758///
759/// Pre-lift the ONE-line `.metadata.deletion_timestamp.is_some()`
760/// chain was hand-authored across every tatara-process CRD in
761/// consumer crates and independently re-authored as byte-identical
762/// inherent methods on [`crate::prelude::Process`] +
763/// [`crate::prelude::EphemeralPool`], with the sister CRD
764/// [`crate::prelude::EphemeralAllocation`] still on the raw chain in
765/// `tatara-pool-reconciler::allocation_decide::AllocationConvergenceCtx::observe`.
766/// That's TWO byte-identical inherent implementations past the ★★
767/// PRIME-DIRECTIVE ≥ 2 duplication threshold on the substrate side
768/// PLUS the hand-authored chain on the third CRD — three surfaces
769/// spelling the SAME projection, each with the same drift risk (a
770/// stale-tombstone grace-period gate, a paused-controller
771/// canonicalization, a cross-cluster clock-skew guard would have to
772/// land at every surface plus stay coherent).
773///
774/// Post-lift the substrate owns the probe at ONE trait method with a
775/// blanket impl over every `kube::Resource<DynamicType = ()>`, so:
776/// * [`crate::prelude::EphemeralAllocation`] inherits the probe for
777///   free — its `allocation_decide.rs` hand-authored chain routes
778///   through `alloc.is_being_deleted()` post-lift, closing the
779///   third-CRD gap noted in the [`crate::prelude::EphemeralPool::is_being_deleted`]
780///   commit body (`7f8f104`).
781/// * Any future tatara CRD (a routing-edge object, a receipt
782///   registry, a fleet-wide claim registry) inherits the probe at
783///   its own `reconcile_inner` dispatcher with zero per-CRD lift
784///   work — the same solve-once discipline
785///   [`NamespacedApiCoordinates`] established for the paired
786///   coordinate extractor.
787///
788/// The two existing inherent methods
789/// ([`crate::prelude::Process::is_being_deleted`] +
790/// [`crate::prelude::EphemeralPool::is_being_deleted`]) are peers
791/// rather than lift casualties: Rust method resolution prefers the
792/// inherent over the trait's blanket, so every existing callsite
793/// keeps hitting the same code path. The trait's blanket impl
794/// closes the substrate corner for CRDs WITHOUT the inherent — the
795/// coherence tests pin that the trait and the two inherents produce
796/// byte-identical results across every corner of the (missing,
797/// present) input matrix, so a future rewrite that consolidates
798/// onto the trait doesn't skew any consumer.
799///
800/// Return-form axis: `bool` matches the copy-form discipline of the
801/// two inherent peers and of [`crate::prelude::Process::observed_phase`]
802/// — the underlying wire-format slot is an `Option<Time>` carrying
803/// only presence information at this axis (the RFC-3339 timestamp
804/// payload itself is not what the callers read; all just probe
805/// presence to detect the tombstone-stamped state).
806///
807/// A future normalization step (a per-tombstone staleness gate
808/// returning `false` for a tombstone older than the reconciler's
809/// grace-period budget, a paused-controller tombstone
810/// canonicalization, a cross-cluster tombstone-observation clock
811/// skew guard) lands at ONE substrate trait method here — the two
812/// inherent forwarders inherit the upgrade mechanically if they are
813/// rewired to `<Self as DeletionTombstoned>::is_being_deleted(self)`
814/// as a follow-up sweep, and every downstream consumer that already
815/// routes through this trait picks it up without a per-callsite
816/// hand-edit.
817///
818/// Theory anchor: THEORY.md §VI.1 (generation over composition —
819/// the `.metadata.deletion_timestamp.is_some()` projection recurred
820/// as TWO byte-identical inherent implementations on
821/// [`crate::prelude::Process`] + [`crate::prelude::EphemeralPool`]
822/// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger and is
823/// lifted onto ONE trait method here). THEORY.md §II.1 invariant 5
824/// (composition preserves proofs — the pins bind the missing-
825/// tombstone corner + the present-tombstone corner + the copy-form
826/// `bool` return + the byte-identical parity with the pre-lift
827/// `.is_some()` chain + cross-CRD coherence with both inherent
828/// forwarders on the SAME `Process` / `EphemeralPool` value, so a
829/// regression that skewed either surface surfaces at
830/// `deletion_tombstoned_tests::*` rather than as silent operator-
831/// facing skew between the top-level dispatcher's SIGTERM preempt,
832/// the SIGTERM cascade's child-fan-out DELETE-skip, the pool
833/// reconciler's Drain gate, and the allocation reconciler's release
834/// short-circuit on three sibling CRDs.
835pub trait DeletionTombstoned: kube::Resource<DynamicType = ()> {
836    /// True iff the K8s API server has stamped `metadata.deletionTimestamp`
837    /// on this resource — a DELETE is in flight and finalizers are
838    /// draining. See the trait-level docs for the axis-family context,
839    /// peer inherent methods, and future-normalization anchor.
840    fn is_being_deleted(&self) -> bool {
841        self.meta().deletion_timestamp.is_some()
842    }
843}
844
845impl<T> DeletionTombstoned for T where T: kube::Resource<DynamicType = ()> {}
846
847/// Substrate-primitive trait for the ONE **borrow-form annotation
848/// lookup** every tatara CRD reconciler restated as the 3-line
849/// `.metadata.annotations.as_ref().and_then(|m| m.get(key)).map(String::as_str)`
850/// chain (or a `.cloned()` / `.cloned().unwrap_or_default()` variant
851/// of the same shape) on the K8s `metadata.annotations` map: returns
852/// `Some(&str)` iff the annotations block is present AND the key is
853/// present inside it; both missing corners collapse to `None`.
854///
855/// Peer to [`DeletionTombstoned`] + [`NamespacedApiCoordinates`] on
856/// the substrate-primitive-trait axis (kube-Resource blanket impls
857/// over `DynamicType = ()`), and peer to the pre-existing
858/// [`crate::prelude::Process::annotation`] inherent forwarder on the
859/// axis of "one annotation-lookup shape shared across every kube
860/// resource, tatara CRD or K8s built-in". The inherent stays as a
861/// peer — Rust method resolution prefers an inherent over a trait's
862/// blanket impl, so the three consumers already routed through
863/// `Process::annotation`
864/// (`tatara-reconciler::signals::ingest`,
865/// `tatara-reconciler::phase_machine::released_from_annotation`,
866/// `tatara-pool-reconciler::controller_pool::process_belongs_to_pool`)
867/// keep hitting the byte-identical code path — and the trait's
868/// blanket impl closes the substrate corner for kube resources
869/// WITHOUT the inherent: post-lift the hand-authored
870/// `.metadata.annotations.as_ref().and_then(|m| m.get(KEY))...` chain
871/// in `tatara-export-worker::main` (on `k8s_openapi`'s `ConfigMap`,
872/// which has no tatara-owned inherent) routes through the trait at
873/// `cm.annotation(KEY)`, and any future `EphemeralPool` /
874/// `EphemeralAllocation` (or new tatara CRD) consumer that needs an
875/// annotation lookup inherits the primitive for free — the same
876/// solve-once discipline the two peer traits already established.
877///
878/// Return-form axis: `Option<&str>` matches the borrow-first
879/// discipline of the peer metadata primitives
880/// ([`crate::prelude::Process::namespace_or_default`],
881/// [`crate::prelude::Process::name_or_placeholder`],
882/// [`crate::prelude::Process::coordinates_or_none`], and the inherent
883/// [`crate::prelude::Process::annotation`] this trait mirrors). The
884/// two corners the pre-lift chain swallowed (missing `annotations`
885/// map, missing key inside the map) BOTH collapse to `None` so
886/// `.is_some()` / `if let Some(_)` / `Option::map` behave identically
887/// on a resource whose annotations block is `None` and on one whose
888/// annotations block is populated but omits the key — matching what
889/// the pre-lift `.and_then(...)` chain produced.
890///
891/// A future normalization step (a key-canonicalization pass, a
892/// case-fold lookup, a per-key alias table for renamed annotations
893/// across API versions, a per-namespace override substrate) lands at
894/// ONE trait method here and every downstream consumer — the four
895/// current sites plus every future CRD reconciler that inherits the
896/// blanket impl — picks up the upgrade mechanically. If the inherent
897/// is ever rewired to `<Self as Annotated>::annotation(self, key)`
898/// as a follow-up sweep, the three inherent-preferred callsites
899/// automatically inherit any trait-level upgrade too.
900///
901/// Theory anchor: THEORY.md §VI.1 (generation over composition —
902/// the annotation-lookup shape recurred as ONE inherent forwarder on
903/// `Process` PLUS a hand-authored chain on `ConfigMap` past the
904/// ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted onto
905/// ONE trait method here). THEORY.md §II.1 invariant 5 (composition
906/// preserves proofs — the pins bind the missing-annotations corner +
907/// the missing-key corner + the borrow-form `&str` lifetime + the
908/// byte-identical parity with the pre-lift 3-line chain + the
909/// cross-primitive coherence with `Process::annotation` on the SAME
910/// `Process` value, so a regression that skewed either surface
911/// surfaces at `annotated_tests::*` rather than as silent operator-
912/// facing skew between the SIGNAL / RELEASED_FROM / POOL annotation
913/// readers on Process and the receipts-owner filter on ConfigMap).
914pub trait Annotated: kube::Resource<DynamicType = ()> {
915    /// Borrow one key from `metadata.annotations`. See the trait-level
916    /// docs for the axis-family context, peer inherent method, and
917    /// future-normalization anchor.
918    fn annotation(&self, key: &str) -> Option<&str> {
919        self.meta()
920            .annotations
921            .as_ref()
922            .and_then(|m| m.get(key))
923            .map(String::as_str)
924    }
925}
926
927impl<T> Annotated for T where T: kube::Resource<DynamicType = ()> {}
928
929/// Substrate-primitive trait for the **place-in-namespace** fluent
930/// builder every consumer of a `kube::Resource` restated as
931/// `let mut cr = <CRD>::new(name, spec); cr.meta_mut().namespace = Some(ns.into()); cr`
932/// on the freshly-minted resource whose derive-supplied
933/// `::new(name, spec)` constructor stamps `metadata.name` alone and
934/// leaves `metadata.namespace` at `None`.
935///
936/// Pre-lift the pattern was hand-authored across THREE tatara-owned
937/// axes past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold:
938///
939/// * `tatara-reconciler::render::tests::render_through_top_level_intent_dispatch`
940///   — the ONE remaining hand-authored site on the `Process` CRD
941///   (the sibling `Process::new_in` was not opened in the prior
942///   pool/allocation sweep because no `Process`-side pool fixture
943///   restated the pattern at ≥ 2 sites in isolation).
944/// * [`crate::pool::EphemeralPool::new_in`] — a per-CRD inherent
945///   composer opened in commit `a5dbb26` that inlined the identical
946///   `Self::new(name, spec); metadata.namespace = Some(namespace.into())`
947///   body on the `EphemeralPool` axis.
948/// * [`crate::allocation::EphemeralAllocation::new_in`] — the sister
949///   inherent composer opened in the same commit on the
950///   `EphemeralAllocation` axis with the byte-identical body.
951///
952/// Post-lift the substrate owns the `metadata.namespace` stamp at
953/// ONE trait method with a blanket impl over every
954/// `kube::Resource<DynamicType = ()>`, so:
955///
956/// * The two per-CRD `new_in` composers forward through
957///   `Self::new(name, spec).in_namespace(namespace)` — three
958///   substrate copies of the mutation collapse to one. The
959///   composers keep their ergonomic per-CRD signatures so existing
960///   callers stay unchanged; only the body threads through here.
961/// * The `tatara-reconciler::render` fixture routes through
962///   `Process::new(...).in_namespace(...)` on the SAME trait method,
963///   closing the last hand-authored site on the tatara CRD trio.
964/// * Any future tatara CRD (a routing-edge object, a receipt
965///   registry, a fleet-wide claim registry) inherits the builder at
966///   its own operator-facing factory + its own test-fixture site
967///   with zero per-CRD lift work — the same solve-once discipline
968///   [`NamespacedApiCoordinates`] established for the paired
969///   coordinate extractor and [`DeletionTombstoned`] established
970///   for the deletion-tombstone probe.
971/// * Any K8s built-in CRD (`ConfigMap`, `Job`, `Ingress`) inherits
972///   the builder too — the sibling [`Annotated`] blanket already
973///   covers the same category on the annotation-read axis, so an
974///   emitter that composes a `ConfigMap` in a specific namespace can
975///   now write `<owner-composer>().in_namespace(ns)` on the SAME
976///   finished value.
977///
978/// Return-form axis: `Self` (owned, by-value) — the builder
979/// consumes `self` and returns the mutated value so chained
980/// composers read left-to-right as `<CRD>::new(name, spec)
981/// .in_namespace(ns)` in the ONE natural composition order operators
982/// reach for. Peer to the borrow-form observer
983/// [`Annotated::annotation`] on the (mutation direction ×
984/// ObjectMeta-slot family) axis pair; both traits close their
985/// respective ObjectMeta-slot corners at ONE trait method with a
986/// blanket impl over the SAME `kube::Resource<DynamicType = ()>`
987/// bound so a future consumer that alternates between reading an
988/// annotation and stamping a namespace never sees two different
989/// trait-import spellings.
990///
991/// A future normalization step (a per-fleet virtual-cluster prefix
992/// rewrite on the `namespace` slot, a per-cluster canonical
993/// case-fold pass, an operator-scoped default namespace for
994/// cluster-local test rigs, a promotion to a typed `Namespace`
995/// newtype that carries K8s DNS-1123 validation as a phantom-type
996/// guard) lands at ONE substrate trait method here — every
997/// downstream consumer routed through `.in_namespace(...)` picks up
998/// the upgrade mechanically, and the two per-CRD `new_in` composers
999/// inherit it for free through their one-line forwarders.
1000///
1001/// Theory anchor: THEORY.md §II.1 invariant 5 (composition preserves
1002/// proofs — the pins bind `<CRD>::new(name, spec).in_namespace(ns)
1003/// .metadata.namespace == Some(ns.to_string())` on every corner of
1004/// the (CRD ∈ {`Process`, `EphemeralPool`, `EphemeralAllocation`,
1005/// `ConfigMap`} × input form ∈ {`&str`, `String`}) input matrix
1006/// PLUS the overwrite corner where `.in_namespace(a).in_namespace(b)`
1007/// binds `b`, so a regression that skewed either surface surfaces
1008/// at `placed_in_namespace_tests::*` rather than as silent
1009/// operator-facing skew between the tatara-reconciler render
1010/// fixture, the two per-CRD `new_in` composers, and any future
1011/// CRD-adjacent namespace-stamping consumer). THEORY.md §VI.1
1012/// (generation over composition — the mutation recurred as three
1013/// substrate copies past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
1014/// trigger).
1015pub trait PlacedInNamespace: kube::Resource<DynamicType = ()> + Sized {
1016    /// Stamp `namespace` onto `self.metadata.namespace` and return
1017    /// the mutated value by-value. See the trait-level docs for the
1018    /// axis-family context, peer trait, and future-normalization
1019    /// anchor.
1020    #[must_use]
1021    fn in_namespace(mut self, namespace: impl Into<String>) -> Self {
1022        self.meta_mut().namespace = Some(namespace.into());
1023        self
1024    }
1025}
1026
1027impl<T> PlacedInNamespace for T where T: kube::Resource<DynamicType = ()> {}
1028
1029/// Annotation keys the reconciler reads/writes on owned FluxCD resources.
1030pub mod annotations {
1031    pub const MANAGED_BY: &str = "tatara.pleme.io/managed-by";
1032    pub const PROCESS: &str = "tatara.pleme.io/process";
1033    pub const PID: &str = "tatara.pleme.io/pid";
1034    pub const CONTENT_HASH: &str = "tatara.pleme.io/content-hash";
1035    pub const ATTESTATION_ROOT: &str = "tatara.pleme.io/attestation-root";
1036    pub const GENERATION: &str = "tatara.pleme.io/generation";
1037    pub const SIGNAL: &str = "tatara.pleme.io/signal";
1038    /// Stamped by the reconciler when transitioning into `Releasing`
1039    /// — records which terminal-reached gate the Process came from
1040    /// (`Attested` or `Failed`) so `handle_releasing` can pick the
1041    /// matching `ExportTrigger` set + the correct post-Releasing
1042    /// destination (`Exiting` from Attested, `Zombie` from Failed).
1043    pub const RELEASED_FROM: &str = "tatara.pleme.io/released-from";
1044    /// Labels the export-worker Jobs the reconciler emits during
1045    /// `Releasing`. Selector: `tatara.pleme.io/role=export`.
1046    pub const ROLE: &str = "tatara.pleme.io/role";
1047    /// Index of an export inside `lifetime.ephemeral.exports`.
1048    /// Stamped on the corresponding tatara-export-worker Job + its
1049    /// receipt ConfigMap so the reconciler can correlate them
1050    /// without re-parsing the spec JSON.
1051    pub const EXPORT_INDEX: &str = "tatara.pleme.io/export-index";
1052    /// Label / annotation key stamping which
1053    /// `RoutingSpec.hostnames` entry a routing edge (Ingress /
1054    /// DNSEndpoint) belongs to. Value is the entry's `app` slot;
1055    /// a `label`-selector on this key slices every emitted edge
1056    /// for a given `app` regardless of hostname form. Peer to
1057    /// [`ROUTING_FORM`] on the routing-axis pair.
1058    pub const APP: &str = "tatara.pleme.io/app";
1059    /// Label / annotation key stamping the routing form
1060    /// (`"stable"` | `"instance"`) on every emitted routing edge.
1061    /// Value is a [`crate::routing::RoutingForm`] wire-form string;
1062    /// consumers filtering the two forms compare to
1063    /// [`RoutingForm::as_str`][crate::routing::RoutingForm::as_str],
1064    /// never to a bare literal.
1065    pub const ROUTING_FORM: &str = "tatara.pleme.io/routing-form";
1066    /// Stamped by `tatara-pool-reconciler::controller_allocation::
1067    /// reconcile` on the member `Process` at the moment an
1068    /// `EphemeralAllocation` transitions Queued → Bound. Value is
1069    /// the requestor Allocation's `<ns>/<name>` qualified reference
1070    /// (composed through the same `<ns>/<name>` shape every peer
1071    /// substrate composer routes through — see
1072    /// [`crate::qualified_process_ref`]). Downstream consumers
1073    /// (operator dashboards, admission webhooks, audit-trail
1074    /// scrapers) grep for this key to answer "which allocator drove
1075    /// this member Process into its ephemeral overlay".
1076    pub const REQUESTOR: &str = "tatara.pleme.io/requestor";
1077    /// Peer to [`REQUESTOR`] on the same allocator-bind axis: the
1078    /// bare Allocation name (no namespace prefix), stamped alongside
1079    /// so downstream consumers that key on the Allocation identity
1080    /// alone (a single-namespace UI, an in-cluster label selector
1081    /// that already carries the namespace) don't need to re-split
1082    /// [`REQUESTOR`]'s composed reference.
1083    pub const ALLOCATION: &str = "tatara.pleme.io/allocation";
1084    /// Peer to [`REQUESTOR`] + [`ALLOCATION`] on the same
1085    /// allocator-bind axis: mirrors
1086    /// [`crate::allocation::RequestorRef.kind`] verbatim onto the
1087    /// bound member Process so consumers that dispatch on the
1088    /// requestor-kind axis (a GitHub-PR-scoped webhook, a
1089    /// scheduler-window scoped fairness gate, a per-kind quota
1090    /// enforcer) never have to fetch the Allocation object again.
1091    pub const REQUESTOR_KIND: &str = "tatara.pleme.io/requestor-kind";
1092    /// Stamped by `tatara-pool-reconciler::controller_pool::
1093    /// build_member_process` on every Process the pool controller
1094    /// materializes into a pool slot. Value is the owning
1095    /// [`crate::pool::EphemeralPool`]'s `metadata.name`; the pool
1096    /// controller's `process_belongs_to_pool` membership gate reads
1097    /// this key back through the substrate primitive
1098    /// [`crate::prelude::Process::annotation`] to filter its owned
1099    /// members out of the cluster-wide Process listing. Peer to
1100    /// [`POOL_SLOT`] on the same pool-membership axis; the two keys
1101    /// travel together at every write site so any future rename (a
1102    /// `tatara.pleme.io/v2/pool` migration, an alias table for
1103    /// cross-cluster pool identity, a per-cluster ownership prefix)
1104    /// lands at ONE `pub const` in the substrate and every
1105    /// downstream consumer (the pool reconciler's membership gate,
1106    /// any future observability label emitter, a cross-namespace
1107    /// pool-topology walker) inherits the upgrade mechanically.
1108    pub const POOL: &str = "tatara.pleme.io/pool";
1109    /// Peer to [`POOL`] on the same pool-membership axis: the
1110    /// zero-based slot index the pool controller assigned to the
1111    /// member Process, stamped alongside so downstream consumers
1112    /// that need per-slot identity (a UI grid layout, a per-slot
1113    /// affinity gate, a slot-scoped audit-trail scraper) can
1114    /// dispatch on it without re-scanning the pool controller's
1115    /// naming scheme. Value is the slot's `u32` rendered through
1116    /// `.to_string()`.
1117    pub const POOL_SLOT: &str = "tatara.pleme.io/pool-slot";
1118    /// Stamped by `tatara-pool-reconciler::controller_allocation::
1119    /// reconcile` on the bound member `Process` at the moment an
1120    /// `EphemeralAllocation` transitions Bound → Released, to nudge
1121    /// the pool reconciler into taking the return path (flip back
1122    /// to `Lifetime::Permanent` on the pool's [`crate::pool::ReturnPolicy::
1123    /// Keep`] arm, or delete the Process outright on the
1124    /// [`crate::pool::ReturnPolicy::Replace`] arm). Value is the wire-
1125    /// form string `"true"` — merge-patch semantics treat a bare
1126    /// `Value::Null` as strip, so the pool reconciler's future strip
1127    /// arm will stamp `Value::Null` under the same key through the
1128    /// same substrate [`crate::patch::annotation_body`] composer. Peer
1129    /// to [`SIGNAL`] (asynchronous signal-annotation ingest by
1130    /// `tatara-reconciler::signals::ingest`) and [`RELEASED_FROM`]
1131    /// (Releasing-gate stamp by `tatara-reconciler::phase_machine::
1132    /// transition_to_releasing`) on the "single-annotation trigger
1133    /// for the next reconcile pass" axis-family; all three keys ride
1134    /// through the same `annotation_body(<key>, <value>)` composer at
1135    /// their stamp sites.
1136    ///
1137    /// Peer to [`POOL`] + [`POOL_SLOT`] on the pool-membership axis:
1138    /// where those two keys travel together at pool-controller
1139    /// creation to identify a Process as a pool member, this key
1140    /// travels alone at the allocator's Release arm to fire the
1141    /// return path. A future rename that shifted the return-trigger
1142    /// wire-form (a `tatara.pleme.io/v2/return-trigger` migration, a
1143    /// per-fleet override, a collapse into a compound
1144    /// `tatara.pleme.io/allocator-trigger` key carrying the
1145    /// (bind|release) discriminator) lands at ONE `pub const` in the
1146    /// substrate and every downstream consumer inherits the upgrade
1147    /// mechanically.
1148    pub const RETURN_TRIGGER: &str = "tatara.pleme.io/return-trigger";
1149    /// Stamped by
1150    /// `tatara-reconciler::render::mark_resources_as_adopting` on every
1151    /// emitted resource of a Process whose
1152    /// [`crate::encapsulates::EncapsulatesSpec.mode`] gates the Adopt
1153    /// arm. Value is the wire-form spelling of the corresponding
1154    /// [`crate::encapsulates::EncapsulationMode`] variant
1155    /// (`"Adopt"` today; future modes ride through the same closed set),
1156    /// so downstream consumers (operator dashboards, admission webhooks,
1157    /// audit-trail scrapers) can filter which owned resources were
1158    /// stamped for adoption vs greenfield management vs pure observation
1159    /// without re-deriving the mode from the parent Process spec. Peer
1160    /// to [`ADOPTED_RELEASE`] on the same encapsulation-diagnostic
1161    /// axis-family; both keys travel together at the same emit site so
1162    /// a future rename (a `tatara.pleme.io/v2/encapsulation-mode`
1163    /// migration, a per-fleet override, a collapse into a compound
1164    /// `tatara.pleme.io/encapsulation` payload key) lands at ONE
1165    /// `pub const` in the substrate and every downstream consumer
1166    /// inherits the upgrade mechanically.
1167    pub const ENCAPSULATION_MODE: &str = "tatara.pleme.io/encapsulation-mode";
1168    /// Peer to [`ENCAPSULATION_MODE`] on the encapsulation-diagnostic
1169    /// axis-family: stamped by
1170    /// `tatara-reconciler::render::mark_resources_as_adopting` on every
1171    /// emitted resource of a Process whose
1172    /// [`crate::encapsulates::EncapsulationKind`] gates the
1173    /// [`crate::encapsulates::ExistingHelmRelease`] arm. Value is the
1174    /// `<ns>/<release>` qualified reference of the pre-existing
1175    /// HelmRelease the Process is adopting, composed through the
1176    /// workspace-wide [`crate::qualified_process_ref`] `<ns>/<name>`
1177    /// substrate composer (never as a hand-authored `format!("{}/{}",
1178    /// ns, release)` chain). Downstream consumers (operator dashboards,
1179    /// audit-trail scrapers, cross-namespace release-lineage walkers)
1180    /// grep for this key to answer "which pre-existing release did this
1181    /// Process take over".
1182    pub const ADOPTED_RELEASE: &str = "tatara.pleme.io/adopted-release";
1183    /// Label key stamped on every receipt [`ConfigMap`] that carries a
1184    /// typed [`crate::receipt::ReceiptEnvelope`] payload, so operators
1185    /// can `kubectl get cm -l tatara.pleme.io/receipt=tatara-receipt/v1`
1186    /// to enumerate every receipt of a given version on a cluster
1187    /// without pre-parsing each CM's embedded JSON/YAML.
1188    ///
1189    /// Value is [`crate::receipt::RECEIPT_VERSION`] — the wire-format
1190    /// version string every parser gates on. A future bump to
1191    /// `tatara-receipt/v2` lands at ONE const declaration on
1192    /// [`crate::receipt::RECEIPT_VERSION`] and every consumer that
1193    /// stamps this label picks up the upgrade mechanically.
1194    ///
1195    /// Load-bearing at TWO production write-sites past the ★★
1196    /// PRIME-DIRECTIVE ≥ 2 duplication threshold:
1197    /// - `tatara-closed-loop-probe::write_receipt_cm`'s
1198    ///   `BTreeMap::from([...])` label seed — the closed-loop auth
1199    ///   probe's receipt-CM label writer.
1200    /// - `tatara_process::configmap::with_data`'s byte-shape parity
1201    ///   witness test that mirrors the closed-loop-probe callsite.
1202    ///
1203    /// The `tatara-export-worker` receipt-CM writer intentionally
1204    /// stamps NO labels (its consumer keys on the CM name the
1205    /// ExportSpec channel already carries), so it is not a consumer of
1206    /// this const; the two production label-stamp sites above are the
1207    /// complete workspace consumer set today.
1208    ///
1209    /// Peer to [`ROLE`] + [`EXPORT_INDEX`] on the "annotation / label
1210    /// key stamped on a receipt-emitting resource other than the
1211    /// Process itself" axis-family: those two keys ride on the
1212    /// export-worker Job the reconciler emits (Job-side), this key
1213    /// rides on the receipt ConfigMap the probe binary writes
1214    /// (ConfigMap-side); all three share the [`GROUP_PREFIX`]
1215    /// reverse-DNS namespace. A future rename of this key (a
1216    /// `tatara.pleme.io/v2/receipt` migration, a per-fleet override, a
1217    /// collapse into a compound `tatara.pleme.io/receipt-envelope`
1218    /// key) lands at ONE `pub const` in the substrate and every
1219    /// downstream consumer inherits the upgrade mechanically.
1220    pub const RECEIPT: &str = "tatara.pleme.io/receipt";
1221
1222    /// Shared reverse-DNS namespace prefix every substrate-owned
1223    /// annotation key in this module carries — the same
1224    /// `tatara.pleme.io/` group segment every tatara-owned CRD
1225    /// annotation + finalizer key rides through, matching the
1226    /// `#[kube(group = "tatara.pleme.io", …)]` derive slot on every
1227    /// tatara CRD struct.
1228    ///
1229    /// Compile-time alias of the crate-wide substrate owner
1230    /// [`crate::GROUP_PREFIX`] — the ONE `pub const &'static str` that
1231    /// owns the `<GROUP>/` byte-shape every tatara wire-form key uses
1232    /// as its reverse-DNS prefix. Pre-lift this const restated the
1233    /// literal `"tatara.pleme.io/"` inline as a byte-parity mirror of
1234    /// the sibling [`crate::finalizers::GROUP_PREFIX`] (pinned equal
1235    /// by
1236    /// [`crate::annotations_family_tests::group_prefix_matches_finalizers_group_prefix`]);
1237    /// post-lift both peer consts route through
1238    /// [`crate::GROUP_PREFIX`] so byte equality holds by construction
1239    /// (the same `&'static str` address), and a future rename of the
1240    /// reverse-DNS root (a `"tatara.pleme.io/v2/"` migration under a
1241    /// group-segment bump, a per-fleet override, an alias table for
1242    /// cross-cluster ownership) lands at the ONE crate-root const with
1243    /// every peer wire-form consumer inheriting the shift mechanically
1244    /// rather than at three independent per-module string literals.
1245    ///
1246    /// Pinned across every arm of [`ALL`] by
1247    /// [`crate::annotations_family_tests::all_share_group_prefix`] so a
1248    /// future addition to the annotation family that drifted the prefix
1249    /// (a `tatara.io/` copy-paste that silently escaped the K8s-side
1250    /// reverse-DNS convention, a group-segment shift on ONE key that
1251    /// missed the ALL slice) surfaces at compile-time / test-time rather
1252    /// than as silent operator-facing skew.
1253    pub const GROUP_PREFIX: &str = crate::GROUP_PREFIX;
1254
1255    /// Closed family of every substrate-owned annotation key in this
1256    /// module, in stable declaration order matching the `pub const`
1257    /// definitions above.
1258    ///
1259    /// Peer to [`crate::finalizers::ALL`] on the "closed slice over a
1260    /// family of tatara-owned wire-form keys sharing the
1261    /// [`GROUP_PREFIX`] reverse-DNS namespace" axis-pair: the
1262    /// [`crate::finalizers`] module owns the same shape over its three
1263    /// finalizer keys; this const opens the mirror over the 20
1264    /// annotation keys in this module.
1265    ///
1266    /// Downstream sweeps that pre-lift the ALL owner had to hand-list
1267    /// every substrate-owned annotation key to iterate them — a
1268    /// fleet-wide annotation-audit binary dumping every
1269    /// `tatara.pleme.io/*` key on a cluster, a per-key coverage report
1270    /// answering "which annotations does the reconciler write vs read",
1271    /// a cross-cluster rename planner, the existing intra-module
1272    /// pairwise-disjointness tests (see the "peer list" arrays in
1273    /// [`crate::annotations_pins`] which hand-list up to 18 sibling
1274    /// keys to prove one axis is disjoint from every other) — iterate
1275    /// through ONE substrate slice post-lift. A future addition to the
1276    /// annotation family that landed a new `pub const` above but forgot
1277    /// this slice surfaces at
1278    /// [`crate::annotations_family_tests::all_matches_declared_length`]
1279    /// rather than by silently escaping every downstream iteration
1280    /// consumer.
1281    ///
1282    /// Pinned to length 21 by
1283    /// [`crate::annotations_family_tests::all_matches_declared_length`],
1284    /// to shared [`GROUP_PREFIX`] membership by
1285    /// [`crate::annotations_family_tests::all_share_group_prefix`],
1286    /// and to pairwise-uniqueness by
1287    /// [`crate::annotations_family_tests::all_are_pairwise_unique`] so
1288    /// a copy-paste that duplicated one arm's wire form at another arm
1289    /// (silently double-booking the K8s metadata slot the two keys
1290    /// share) surfaces at the family pin rather than as silent
1291    /// annotation-writer collision at whichever downstream site
1292    /// stamped the copy-paste'd key.
1293    pub const ALL: &[&str] = &[
1294        MANAGED_BY,
1295        PROCESS,
1296        PID,
1297        CONTENT_HASH,
1298        ATTESTATION_ROOT,
1299        GENERATION,
1300        SIGNAL,
1301        RELEASED_FROM,
1302        ROLE,
1303        EXPORT_INDEX,
1304        APP,
1305        ROUTING_FORM,
1306        REQUESTOR,
1307        ALLOCATION,
1308        REQUESTOR_KIND,
1309        POOL,
1310        POOL_SLOT,
1311        RETURN_TRIGGER,
1312        ENCAPSULATION_MODE,
1313        ADOPTED_RELEASE,
1314        RECEIPT,
1315    ];
1316}
1317
1318/// Standard finalizer for the Process reconciler.
1319///
1320/// Re-export of [`finalizers::PROCESS`] — the substrate-owner
1321/// per-CRD finalizer family lives at [`crate::finalizers`]; this
1322/// top-level const stays put for downstream consumers that predate
1323/// the module, and is coherence-pinned against
1324/// [`finalizers::PROCESS`] by
1325/// [`finalizers::tests::process_finalizer_top_level_reexport_routes_through_finalizers_process`].
1326pub const PROCESS_FINALIZER: &str = finalizers::PROCESS;
1327
1328/// Shared schemars helpers — emit OpenAPI schemas Kubernetes accepts.
1329/// Free-form `serde_json::Value` fields default to an *empty* schema
1330/// in schemars, which the K8s API server rejects with "type: Required
1331/// value: must not be empty for specified object fields". The typed
1332/// workaround is to emit `{type: object, x-kubernetes-preserve-unknown-
1333/// fields: true}` — same shape kube-rs's own helpers produce.
1334pub mod schema_helpers {
1335    use schemars::{gen::SchemaGenerator, schema::Schema};
1336    /// Schema for a free-form JSON object field. Apply via
1337    /// `#[schemars(schema_with = "tatara_process::schema_helpers::preserve_unknown_object")]`
1338    /// on any `serde_json::Value` / `BTreeMap<String, serde_json::Value>`
1339    /// field exposed through a CRD.
1340    pub fn preserve_unknown_object(_g: &mut SchemaGenerator) -> Schema {
1341        serde_json::from_value(serde_json::json!({
1342            "type": "object",
1343            "x-kubernetes-preserve-unknown-fields": true
1344        }))
1345        .expect("static JSON literal parses as Schema")
1346    }
1347}
1348
1349#[cfg(test)]
1350mod owner_reference_tests {
1351    //! Pin the `owner_reference_json` composer at fail-before-pass-
1352    //! after granularity. Every shape a pre-lift caller hand-authored
1353    //! is re-asserted here so a regression that inlined any of the
1354    //! six slots at a call site (breaking the primitive's role as
1355    //! the ONE source of truth) fails HERE at the composer's shipped-
1356    //! shape pin rather than as silent drift between the pre-lift
1357    //! `render.rs` / `edges.rs` / `ssapply.rs` sites (which pre-lift
1358    //! already carried TWO different `apiVersion` spellings — a
1359    //! composed `format!("{}/{}", GROUP, VERSION)` at two sites and
1360    //! the frozen literal `"tatara.pleme.io/v1alpha1"` at the third).
1361    use super::{
1362        api_version, owner_reference_json, owner_references_json, API_VERSION, GROUP, GROUP_PREFIX,
1363        PROCESS_KIND, PROCESS_WIRE_IDENTITY, VERSION,
1364    };
1365    use crate::flux_resource::FluxResource;
1366    use crate::k8s_builtin_resource::K8sBuiltinResource;
1367    use crate::k8s_wire_identity::K8sWireIdentity;
1368    use crate::routing_edge_resource::RoutingEdgeResource;
1369    use serde_json::json;
1370
1371    #[test]
1372    fn api_version_composes_group_and_version() {
1373        // Any bump of GROUP or VERSION lands at ONE composer.
1374        assert_eq!(api_version(), format!("{GROUP}/{VERSION}"));
1375    }
1376
1377    // ─── API_VERSION const substrate pins ───────────────────────────
1378    //
1379    // The compile-time `&'static str` [`API_VERSION`] const feeds the
1380    // typed [`PROCESS_WIRE_IDENTITY`] const and delegates the runtime
1381    // [`api_version`] fn — these pins bind the const at fail-before-
1382    // pass-after granularity so a regression that drifted the const
1383    // (a rename that touched [`GROUP`] but not the const's baked
1384    // literal, a VERSION bump that only updated [`VERSION`]) surfaces
1385    // HERE rather than as silent operator-facing skew between the
1386    // typed-const consumers and the fn-based consumers on the same
1387    // wire-form axis.
1388
1389    #[test]
1390    fn api_version_const_composes_group_and_version_bytewise() {
1391        // Cross-const coherence pin: the compile-time [`API_VERSION`]
1392        // must be byte-identical to the runtime `format!("{GROUP}/
1393        // {VERSION}")` composition. A regression that drifted either
1394        // the const or the two segment consts would surface HERE
1395        // rather than as silent skew between [`PROCESS_WIRE_IDENTITY`]
1396        // (which composes over the const) and [`api_url_prefix`]
1397        // (which composes over the two segment consts at runtime).
1398        assert_eq!(API_VERSION, format!("{GROUP}/{VERSION}"));
1399    }
1400
1401    #[test]
1402    fn api_version_const_byte_matches_wire_form_pre_lift() {
1403        // Byte-identity pin: the frozen wire-form literal is the SAME
1404        // string every downstream consumer (the typed
1405        // [`PROCESS_WIRE_IDENTITY`] const, the runtime [`api_version`]
1406        // fn, every K8s `apiVersion:` slot the reconciler stamps)
1407        // must emit. Peer of the pre-existing runtime pin
1408        // [`api_version_byte_matches_wire_form_pre_lift`]; both close
1409        // the axis at the SAME wire form.
1410        assert_eq!(API_VERSION, "tatara.pleme.io/v1alpha1");
1411    }
1412
1413    #[test]
1414    fn api_version_fn_delegates_through_const_owner() {
1415        // Routing pin: the runtime `api_version()` fn returns
1416        // [`API_VERSION`]`.to_string()` — the ONE substrate owner of
1417        // the wire-form literal. A regression that re-open-coded the
1418        // fn's body (restoring the pre-lift `format!("{GROUP}/
1419        // {VERSION}")` composition, or inlining a stale literal) would
1420        // surface HERE rather than as silent skew between the two
1421        // sibling emit paths (typed-const vs owned-String).
1422        assert_eq!(api_version(), API_VERSION);
1423    }
1424
1425    #[test]
1426    fn api_version_const_is_reachable_at_compile_time() {
1427        // Compile-time reachability pin: [`API_VERSION`] is a `const
1428        // &'static str` so a caller can bind it into a `const` slot —
1429        // exactly what [`PROCESS_WIRE_IDENTITY`] does through
1430        // [`K8sWireIdentity::new`]'s `const fn`. A regression that
1431        // widened the const to an owned `String` or a `Lazy<String>`
1432        // would fail-loudly at this coercion rather than at the
1433        // silent runtime-vs-const composition boundary at
1434        // [`PROCESS_WIRE_IDENTITY`].
1435        const AV: &str = API_VERSION;
1436        assert_eq!(AV, "tatara.pleme.io/v1alpha1");
1437    }
1438
1439    // ─── GROUP_PREFIX const substrate pins ──────────────────────────
1440    //
1441    // The compile-time `&'static str` [`GROUP_PREFIX`] const owns the
1442    // `<GROUP>/` reverse-DNS prefix every tatara-owned wire-form key
1443    // (annotation, finalizer, label, signal) uses as its namespace
1444    // prefix, and every downstream `.starts_with(...)` group-membership
1445    // gate compares against. Pre-lift the prefix was spelled inline as
1446    // a bare `"tatara.pleme.io/"` literal at TWO substrate-owner sites
1447    // ([`crate::annotations::GROUP_PREFIX`] +
1448    // [`crate::finalizers::GROUP_PREFIX`]) pinned byte-equal to each
1449    // other but with no shared owner binding them to [`GROUP`] itself.
1450    // Post-lift both peer consts route through this ONE crate-root
1451    // owner as compile-time aliases so byte equality holds by
1452    // construction. These pins bind the const at fail-before-pass-after
1453    // granularity so a regression that drifted it (a rename that
1454    // touched [`GROUP`] but not the const's baked literal, a partial
1455    // edit that unbound the two peer aliases from the ONE owner) would
1456    // surface HERE rather than as silent operator-facing skew between
1457    // the [`GROUP`] const the [`api_url_prefix`] composer feeds and the
1458    // [`GROUP_PREFIX`] const every downstream annotation / finalizer
1459    // family gate consumes.
1460
1461    #[test]
1462    fn group_prefix_const_composes_group_slash_bytewise() {
1463        // Cross-const coherence pin: the compile-time [`GROUP_PREFIX`]
1464        // must be byte-identical to the runtime `format!("{GROUP}/")`
1465        // composition. A regression that drifted either the const or
1466        // the [`GROUP`] segment would surface HERE rather than as
1467        // silent skew between [`GROUP`] (which
1468        // [`api_url_prefix`] + [`api_version`] compose over) and
1469        // [`GROUP_PREFIX`] (which every downstream annotation /
1470        // finalizer family gate consumes as its reverse-DNS prefix).
1471        assert_eq!(GROUP_PREFIX, format!("{GROUP}/"));
1472    }
1473
1474    #[test]
1475    fn group_prefix_const_byte_matches_wire_form_pre_lift() {
1476        // Byte-identity pin: the frozen wire-form literal is the SAME
1477        // string every downstream consumer (the peer aliases
1478        // [`crate::annotations::GROUP_PREFIX`] +
1479        // [`crate::finalizers::GROUP_PREFIX`], every
1480        // `<key>.starts_with(GROUP_PREFIX)` gate on the peer
1481        // [`crate::annotations::ALL`] / [`crate::finalizers::ALL`]
1482        // families) must compare against. Peer of the pre-existing
1483        // wire-form pin
1484        // [`api_version_const_byte_matches_wire_form_pre_lift`]; both
1485        // close the axis at the SAME reverse-DNS root.
1486        assert_eq!(GROUP_PREFIX, "tatara.pleme.io/");
1487    }
1488
1489    #[test]
1490    fn group_prefix_const_is_reachable_at_compile_time() {
1491        // Compile-time reachability pin: [`GROUP_PREFIX`] is a `const
1492        // &'static str` so callers can bind it into a `const` slot —
1493        // exactly what [`crate::annotations::GROUP_PREFIX`] +
1494        // [`crate::finalizers::GROUP_PREFIX`] do as compile-time
1495        // aliases. A regression that widened the const to an owned
1496        // `String` or a `Lazy<String>` would fail-loudly at this
1497        // coercion rather than at the silent alias-coercion boundary
1498        // at the two peer consts.
1499        const GP: &str = GROUP_PREFIX;
1500        assert_eq!(GP, "tatara.pleme.io/");
1501    }
1502
1503    #[test]
1504    fn annotations_group_prefix_routes_through_crate_root_owner() {
1505        // Routing pin: [`crate::annotations::GROUP_PREFIX`] is a
1506        // compile-time alias of [`GROUP_PREFIX`] — the ONE substrate
1507        // owner of the reverse-DNS prefix wire form. A regression that
1508        // re-open-coded the annotation-family const (restoring the
1509        // pre-lift inline `"tatara.pleme.io/"` literal, inlining a
1510        // stale byte string) would surface HERE rather than as silent
1511        // skew between the two sibling substrate owners (annotation vs
1512        // finalizer families) on the SAME reverse-DNS prefix.
1513        assert_eq!(crate::annotations::GROUP_PREFIX, GROUP_PREFIX);
1514    }
1515
1516    #[test]
1517    fn finalizers_group_prefix_routes_through_crate_root_owner() {
1518        // Routing pin: [`crate::finalizers::GROUP_PREFIX`] is a
1519        // compile-time alias of [`GROUP_PREFIX`] — the ONE substrate
1520        // owner of the reverse-DNS prefix wire form. A regression that
1521        // re-open-coded the finalizer-family const (restoring the
1522        // pre-lift inline `"tatara.pleme.io/"` literal, inlining a
1523        // stale byte string) would surface HERE rather than as silent
1524        // skew between the two sibling substrate owners (finalizer vs
1525        // annotation families) on the SAME reverse-DNS prefix.
1526        assert_eq!(crate::finalizers::GROUP_PREFIX, GROUP_PREFIX);
1527    }
1528
1529    // ─── PROCESS_WIRE_IDENTITY substrate pins ───────────────────────
1530    //
1531    // The typed [`PROCESS_WIRE_IDENTITY`] const closes the fourth arm
1532    // of the K8s-wire-form-identity axis-family (peer to
1533    // [`K8sBuiltinResource::wire_identity`],
1534    // [`FluxResource::wire_identity`],
1535    // [`RoutingEdgeResource::wire_identity`]). These pins bind the
1536    // const at fail-before-pass-after granularity so a regression that
1537    // drifted either slot (an `apiVersion` slot that stopped routing
1538    // through [`API_VERSION`], a `kind` slot that stopped routing
1539    // through [`PROCESS_KIND`]) surfaces HERE rather than as silent
1540    // OwnerReference-emit skew at every downstream consumer.
1541
1542    #[test]
1543    fn process_wire_identity_pairs_api_version_and_kind_through_substrate_owners() {
1544        // Slot-routing pin: both slots MUST route through the ONE
1545        // substrate owner per slot ([`API_VERSION`] for the
1546        // `apiVersion` slot, [`PROCESS_KIND`] for the `kind` slot).
1547        // A regression that re-inlined either slot's literal at the
1548        // const declaration would surface HERE rather than as silent
1549        // skew between the wire-identity const and its slot owners.
1550        assert_eq!(PROCESS_WIRE_IDENTITY.api_version, API_VERSION);
1551        assert_eq!(PROCESS_WIRE_IDENTITY.kind, PROCESS_KIND);
1552    }
1553
1554    #[test]
1555    fn process_wire_identity_byte_matches_wire_form_pre_lift() {
1556        // Byte-identity pin: the const's `(apiVersion, kind)` pair
1557        // must equal the two frozen wire-form strings every pre-lift
1558        // consumer hand-authored — a regression that drifted either
1559        // slot would surface HERE rather than as a wire-time 404 the
1560        // K8s API server would misdiagnose as a broken CRD.
1561        assert_eq!(
1562            PROCESS_WIRE_IDENTITY.api_version,
1563            "tatara.pleme.io/v1alpha1"
1564        );
1565        assert_eq!(PROCESS_WIRE_IDENTITY.kind, "Process");
1566    }
1567
1568    #[test]
1569    fn process_wire_identity_is_const_reachable() {
1570        // Compile-time reachability pin: [`PROCESS_WIRE_IDENTITY`] is
1571        // a compile-time `const K8sWireIdentity` so a caller can bind
1572        // it into a `const` slot. A regression that dropped the
1573        // `const fn` qualifier on [`K8sWireIdentity::new`] or widened
1574        // [`API_VERSION`] off the `&'static str` axis would fail-loudly
1575        // HERE rather than as a runtime dispatch at every OwnerReference
1576        // emit site.
1577        const ID: K8sWireIdentity = PROCESS_WIRE_IDENTITY;
1578        assert_eq!(ID.api_version, "tatara.pleme.io/v1alpha1");
1579        assert_eq!(ID.kind, "Process");
1580    }
1581
1582    #[test]
1583    fn process_wire_identity_is_disjoint_from_every_peer_wire_form_axis() {
1584        // Cross-substrate coherence pin: the tatara `Process` CRD's
1585        // typed `(apiVersion, kind)` pair MUST NOT collide with any
1586        // variant of the three peer closed-set axes on the K8s wire-
1587        // form-identity axis-family
1588        // ([`K8sBuiltinResource`] / [`FluxResource`] /
1589        // [`RoutingEdgeResource`]) — a hypothetical variant addition
1590        // on any peer that copy-pasted the tatara `Process` pair
1591        // (a `FluxResource::Process` renaming collision, a
1592        // `K8sBuiltinResource::Process` typo) would silently let a
1593        // reconciler dispatch reach through the wrong closed set. Pin
1594        // the disjointness so every future addition to any peer axis
1595        // that would collide with this const surfaces HERE.
1596        for k in K8sBuiltinResource::ALL {
1597            assert_ne!(
1598                (
1599                    PROCESS_WIRE_IDENTITY.api_version,
1600                    PROCESS_WIRE_IDENTITY.kind
1601                ),
1602                (k.api_version(), k.kind()),
1603                "PROCESS_WIRE_IDENTITY must not share a wire-form pair with K8sBuiltinResource {k:?}"
1604            );
1605        }
1606        for f in FluxResource::ALL {
1607            assert_ne!(
1608                (
1609                    PROCESS_WIRE_IDENTITY.api_version,
1610                    PROCESS_WIRE_IDENTITY.kind
1611                ),
1612                (f.api_version(), f.kind()),
1613                "PROCESS_WIRE_IDENTITY must not share a wire-form pair with FluxResource {f:?}"
1614            );
1615        }
1616        for r in RoutingEdgeResource::ALL {
1617            assert_ne!(
1618                (
1619                    PROCESS_WIRE_IDENTITY.api_version,
1620                    PROCESS_WIRE_IDENTITY.kind
1621                ),
1622                (r.api_version(), r.kind()),
1623                "PROCESS_WIRE_IDENTITY must not share a wire-form pair with RoutingEdgeResource {r:?}"
1624            );
1625        }
1626    }
1627
1628    #[test]
1629    fn owner_reference_json_routes_apiversion_and_kind_through_process_wire_identity() {
1630        // Routing pin: the `owner_reference_json` composer's
1631        // `(apiVersion, kind)` pair MUST match the typed
1632        // [`PROCESS_WIRE_IDENTITY`] const's `(api_version, kind)`
1633        // fields byte-for-byte. Post-lift the composer routes through
1634        // [`K8sWireIdentity::resource_json`], so this equality holds
1635        // by construction; a regression that re-open-coded the two
1636        // slots at the composer body (restoring the pre-lift `json!`
1637        // inline reference to `api_version()` + `PROCESS_KIND`
1638        // separately) would surface HERE rather than as silent skew
1639        // between the OwnerReference emit and the typed const owner.
1640        let v = owner_reference_json("p", "u");
1641        assert_eq!(v["apiVersion"], PROCESS_WIRE_IDENTITY.api_version);
1642        assert_eq!(v["kind"], PROCESS_WIRE_IDENTITY.kind);
1643    }
1644
1645    #[test]
1646    fn api_version_byte_matches_wire_form_pre_lift() {
1647        // Byte-identity pin: the frozen wire-form literal
1648        // `"tatara.pleme.io/v1alpha1"` that `ssapply.rs::
1649        // build_owner_reference` hand-wrote pre-lift must equal the
1650        // composed shape now sourced through the ONE owner. A
1651        // future VERSION bump that missed this test would land as
1652        // an operator-visible reference-mismatch after apply.
1653        assert_eq!(api_version(), "tatara.pleme.io/v1alpha1");
1654    }
1655
1656    #[test]
1657    fn api_url_prefix_composes_apis_group_version_slash() {
1658        // Composition pin: any bump of GROUP or VERSION lands at
1659        // ONE composer.
1660        assert_eq!(super::api_url_prefix(), format!("/apis/{GROUP}/{VERSION}/"));
1661    }
1662
1663    #[test]
1664    fn api_url_prefix_byte_matches_wire_form_pre_lift() {
1665        // Byte-identity pin: the frozen wire-form literal
1666        // `"/apis/tatara.pleme.io/v1alpha1/"` that eleven
1667        // hand-authored scope guards across `tatara-reconciler::
1668        // context`, `tatara-pool-reconciler::context`, and
1669        // `tatara-github-watcher::handler` restated pre-lift must
1670        // equal the composed shape now sourced through the ONE
1671        // owner. A future group rename or VERSION bump that missed
1672        // this pin would land as a silent scope-guard mismatch at
1673        // every downstream Api-primitive test.
1674        assert_eq!(super::api_url_prefix(), "/apis/tatara.pleme.io/v1alpha1/");
1675    }
1676
1677    #[test]
1678    fn api_url_prefix_carries_api_version_between_apis_and_trailing_slash() {
1679        // Cross-primitive pin: the URL prefix and the `apiVersion`
1680        // wire form share the SAME `<GROUP>/<VERSION>` shape,
1681        // wrapped by the fixed `/apis/…/` HTTP-path envelope. A
1682        // regression that drifted the two composers apart (a bump
1683        // that missed one of the two owners) surfaces here rather
1684        // than as an operator-visible mismatch between an emitted
1685        // ownerReference's `apiVersion` and the REST url every typed
1686        // `Api` primitive routes through.
1687        let prefix = super::api_url_prefix();
1688        let version = api_version();
1689        assert!(
1690            prefix.starts_with("/apis/") && prefix.ends_with('/'),
1691            "prefix must be wrapped as `/apis/…/`; got {prefix}"
1692        );
1693        let inner = &prefix["/apis/".len()..prefix.len() - 1];
1694        assert_eq!(
1695            inner, version,
1696            "prefix inner slot must equal api_version(); got inner={inner:?} version={version:?}"
1697        );
1698    }
1699
1700    #[test]
1701    fn process_kind_is_process_literal() {
1702        // Symbol-vs-string pin: any consumer that hand-wrote `"Process"`
1703        // pre-lift routes through this const post-lift.
1704        assert_eq!(PROCESS_KIND, "Process");
1705    }
1706
1707    #[test]
1708    fn owner_reference_json_has_all_six_slots_present() {
1709        let v = owner_reference_json("my-process", "abc-uid");
1710        let obj = v.as_object().expect("owner reference is a JSON object");
1711        for k in [
1712            "apiVersion",
1713            "kind",
1714            "name",
1715            "uid",
1716            "controller",
1717            "blockOwnerDeletion",
1718        ] {
1719            assert!(obj.contains_key(k), "missing owner-reference slot: {k}");
1720        }
1721        assert_eq!(obj.len(), 6, "owner reference must have exactly 6 slots");
1722    }
1723
1724    #[test]
1725    fn owner_reference_json_apiversion_routes_through_api_version_owner() {
1726        let v = owner_reference_json("x", "y");
1727        assert_eq!(v["apiVersion"], api_version());
1728    }
1729
1730    #[test]
1731    fn owner_reference_json_kind_routes_through_process_kind_const() {
1732        let v = owner_reference_json("x", "y");
1733        assert_eq!(v["kind"], PROCESS_KIND);
1734    }
1735
1736    #[test]
1737    fn owner_reference_json_stamps_supplied_name_and_uid() {
1738        let v = owner_reference_json("some-name", "some-uid");
1739        assert_eq!(v["name"], "some-name");
1740        assert_eq!(v["uid"], "some-uid");
1741    }
1742
1743    #[test]
1744    fn owner_reference_json_controller_and_block_owner_deletion_are_true() {
1745        // These are structural — a Process-owned resource always
1746        // has a controlling reference that cascade-deletes with
1747        // the owner. A regression that flipped either boolean
1748        // would silently detach every emitted resource.
1749        let v = owner_reference_json("x", "y");
1750        assert_eq!(v["controller"], true);
1751        assert_eq!(v["blockOwnerDeletion"], true);
1752    }
1753
1754    #[test]
1755    fn owner_reference_json_matches_hand_authored_shape_pre_lift() {
1756        // Byte-shape pin against the exact `json!({…})` incantation
1757        // every pre-lift call site restated. A regression that
1758        // reordered a slot, dropped one, or added a seventh here
1759        // surfaces at THIS pin rather than as a subtle SSA-apply
1760        // failure downstream when the K8s API server rejects the
1761        // OwnerReference on schema mismatch.
1762        let via_owner = owner_reference_json("p", "u");
1763        let hand_authored = json!({
1764            "apiVersion": "tatara.pleme.io/v1alpha1",
1765            "kind": "Process",
1766            "name": "p",
1767            "uid": "u",
1768            "controller": true,
1769            "blockOwnerDeletion": true,
1770        });
1771        assert_eq!(via_owner, hand_authored);
1772    }
1773
1774    #[test]
1775    fn owner_reference_json_preserves_empty_name_and_uid_bytewise() {
1776        // The primitive does not guard against empty inputs — its
1777        // callers pre-lift did the empty-check upstream (both the
1778        // `edges.rs::build_owner_refs` and `render.rs::one_export_job`
1779        // sites gated on `!uid.is_empty()` before calling this composer,
1780        // and both now route through `owner_references_json` below;
1781        // `ssapply.rs::build_owner_reference` unwraps a required
1782        // `metadata.uid` via anyhow). The scalar composer owns
1783        // shape composition, not admission control; a downstream
1784        // rename that wants strict input validation lands as a
1785        // peer, not a change to the composer's contract.
1786        let v = owner_reference_json("", "");
1787        assert_eq!(v["name"], "");
1788        assert_eq!(v["uid"], "");
1789    }
1790
1791    // ─── owner_references_json substrate pins ────────────────────────
1792    //
1793    // The 3-line `let mut owner_refs = vec![]; if !uid.is_empty()
1794    // { owner_refs.push(owner_reference_json(name, uid)); }` gate was
1795    // hand-authored at TWO sites in `tatara-reconciler`
1796    // (`edges::build_owner_refs` + `render::one_export_job`) before
1797    // this primitive existed, each restating the same optional-uid
1798    // posture that emits `[]` when the caller lacks a K8s-assigned
1799    // uid to point owners at. These pins bind the primitive at
1800    // fail-before-pass-after granularity so a regression that
1801    // inlined an owner reference for an empty uid — silently
1802    // detaching the resource from cascade-delete — surfaces HERE
1803    // rather than as an operator-visible ownerless resource after
1804    // apply, and a regression that added an owner reference of the
1805    // wrong SHAPE (a peer of `owner_reference_json` that swapped a
1806    // slot) surfaces via the composed-shape pin below rather than
1807    // as silent drift at every downstream emit site.
1808
1809    #[test]
1810    fn owner_references_json_emits_single_entry_when_uid_present() {
1811        // The primary shape: a caller with a materialized uid gets
1812        // exactly one owner reference back — the pre-lift 3-line
1813        // `vec![]` + `push` gate collapses to this ONE call, and
1814        // the returned array is a direct-drop `ownerReferences`
1815        // slot value at every callsite.
1816        let refs = owner_references_json("demo-app", "abc-uid");
1817        assert_eq!(refs.len(), 1);
1818        assert_eq!(refs[0]["kind"], PROCESS_KIND);
1819        assert_eq!(refs[0]["name"], "demo-app");
1820        assert_eq!(refs[0]["uid"], "abc-uid");
1821        // controller + blockOwnerDeletion routed through the scalar
1822        // composer — a regression that hand-composed the vec entry
1823        // rather than delegating would flip one of these booleans.
1824        assert_eq!(refs[0]["controller"], true);
1825        assert_eq!(refs[0]["blockOwnerDeletion"], true);
1826    }
1827
1828    #[test]
1829    fn owner_references_json_emits_empty_when_uid_empty() {
1830        // The load-bearing gate — a pre-metadata Process (fixtured in
1831        // tests, or caught mid-Forking) has no admissible owner
1832        // reference to point at. Post-lift the gate lives at ONE
1833        // primitive so every emit site stamps `[]` uniformly rather
1834        // than one site accidentally emitting a placeholder-uid
1835        // owner reference the K8s GC would quietly detach from
1836        // cascade-delete.
1837        let refs = owner_references_json("demo-app", "");
1838        assert!(
1839            refs.is_empty(),
1840            "empty uid must produce zero owner references, not a placeholder-uid entry"
1841        );
1842    }
1843
1844    #[test]
1845    fn owner_references_json_gates_on_uid_not_name() {
1846        // The gate axis is `uid`, not `name` — a Process with a
1847        // non-empty name but no uid still emits `[]` (the pre-metadata
1848        // shape), while a Process with a non-empty uid emits ONE
1849        // entry even when the name slot is empty (matching the
1850        // scalar composer's admission-control-free contract). Pin
1851        // both cross-diagonal combinations so a regression that
1852        // swapped the gate axis surfaces HERE rather than at every
1853        // downstream owner-refs consumer.
1854        assert!(
1855            owner_references_json("has-name", "").is_empty(),
1856            "empty uid gates to []; name presence is irrelevant"
1857        );
1858        let refs = owner_references_json("", "has-uid");
1859        assert_eq!(
1860            refs.len(),
1861            1,
1862            "empty name but present uid still emits one entry (name is not the gate)"
1863        );
1864        assert_eq!(refs[0]["name"], "");
1865        assert_eq!(refs[0]["uid"], "has-uid");
1866    }
1867
1868    #[test]
1869    fn owner_references_json_matches_hand_authored_pre_lift_bytewise() {
1870        // Byte-identical parity with the exact pre-lift 3-line
1871        // `let mut owner_refs = vec![]; if !uid.is_empty() {
1872        // owner_refs.push(owner_reference_json(name, uid)); }` gate
1873        // across the two axis combinations every callsite plausibly
1874        // encounters. A regression that reordered the two branches,
1875        // dropped the gate, or reshaped the vec composition surfaces
1876        // HERE rather than at every downstream `ownerReferences`
1877        // slot pinned across `edges.rs` + `render.rs` tests.
1878        for (name, uid) in [
1879            ("demo-app", "uid-abc"),
1880            ("demo-app", ""),
1881            ("", "uid-abc"),
1882            ("", ""),
1883        ] {
1884            let via_primitive = owner_references_json(name, uid);
1885
1886            // The pre-lift 3-line block, byte-for-byte.
1887            let mut hand_authored: Vec<serde_json::Value> = vec![];
1888            if !uid.is_empty() {
1889                hand_authored.push(owner_reference_json(name, uid));
1890            }
1891
1892            assert_eq!(
1893                via_primitive, hand_authored,
1894                "owner_references_json must be byte-identical to the pre-lift 3-line gate on ({name:?}, {uid:?})"
1895            );
1896        }
1897    }
1898
1899    #[test]
1900    fn owner_references_json_interpolates_cleanly_as_owner_refs_slot() {
1901        // Both callsites drop the returned vec directly under a
1902        // `"ownerReferences"` key inside a `json!({...})` block. Pin
1903        // the interop shape: a JSON-macro-wrapped Value carries the
1904        // primitive's output as a JSON array with the exact 6-slot
1905        // entries at each index. A regression that returned a
1906        // non-array (e.g. a single Value on the one-entry path,
1907        // requiring per-site vec-wrapping) surfaces HERE rather than
1908        // as a broken `metadata.ownerReferences` slot on every
1909        // emitted Ingress / DNSEndpoint / export Job.
1910        let refs = owner_references_json("demo-app", "abc-uid");
1911        let wrapped = json!({
1912            "metadata": {
1913                "name": "resource",
1914                "ownerReferences": refs,
1915            },
1916        });
1917        let owner_refs = &wrapped["metadata"]["ownerReferences"];
1918        assert!(
1919            owner_refs.is_array(),
1920            "ownerReferences must land as a JSON array"
1921        );
1922        assert_eq!(owner_refs.as_array().unwrap().len(), 1);
1923        assert_eq!(owner_refs[0]["kind"], PROCESS_KIND);
1924
1925        // And the empty-uid path lands as an EMPTY array, not a
1926        // missing key or a null — matches the K8s API server's
1927        // expectation that the slot is either an array of entries
1928        // or absent, never a null.
1929        let empty_refs = owner_references_json("demo-app", "");
1930        let wrapped_empty = json!({
1931            "metadata": {
1932                "name": "resource",
1933                "ownerReferences": empty_refs,
1934            },
1935        });
1936        let owner_refs_empty = &wrapped_empty["metadata"]["ownerReferences"];
1937        assert!(owner_refs_empty.is_array());
1938        assert!(owner_refs_empty.as_array().unwrap().is_empty());
1939    }
1940}
1941
1942#[cfg(test)]
1943mod qualified_process_ref_tests {
1944    //! Pin the [`qualified_process_ref`] composer at fail-before-
1945    //! pass-after granularity. The `<ns>/<name>` shape is the
1946    //! workspace-wide convention for a namespaced K8s resource
1947    //! reference — every downstream grep (the reconciler's
1948    //! `tatara.pleme.io/process` annotation reader, the
1949    //! [`crate::table::ClaimRecord.holder`] slot, the
1950    //! export-worker's receipt-owner filter, the reconciler's
1951    //! `PROCESS=<ref>` label-selector composer) depends on the
1952    //! two axes landing in `(ns, name)` order joined by a single
1953    //! `/` separator. A regression that swapped the axes, dropped
1954    //! either half, or renormalized the input surfaces HERE rather
1955    //! than as silent operator-facing drift at every downstream
1956    //! consumer.
1957    use super::qualified_process_ref;
1958
1959    #[test]
1960    fn qualified_process_ref_joins_ns_and_name_with_slash() {
1961        // The invariant every downstream consumer composes against:
1962        // the qualified reference is EXACTLY `<ns>/<name>`, in that
1963        // order, joined by a single `/`.
1964        assert_eq!(
1965            qualified_process_ref("demo-ns", "ephemeral-demo"),
1966            "demo-ns/ephemeral-demo",
1967        );
1968    }
1969
1970    #[test]
1971    fn qualified_process_ref_binds_positional_slots_by_axis_order() {
1972        // Positional pin — a copy-paste that swapped the two `&str`
1973        // arguments (both mechanically interchangeable at the type
1974        // level) would silently produce `<name>/<ns>` and break every
1975        // downstream grep keyed on the reference shape. Distinct
1976        // input slot values so a swap surfaces as an equality
1977        // failure rather than accidental identity.
1978        let out = qualified_process_ref("first-slot-ns", "second-slot-name");
1979        assert!(
1980            out.starts_with("first-slot-ns/"),
1981            "position 0 must be the namespace slot: got {out}"
1982        );
1983        assert!(
1984            out.ends_with("/second-slot-name"),
1985            "position 1 must be the name slot: got {out}"
1986        );
1987    }
1988
1989    #[test]
1990    fn qualified_process_ref_accepts_string_deref_and_str_slice_shapes() {
1991        // Consumers split across two callsite shapes: owned
1992        // `String` locals (via deref coercion), bare `&str` slices,
1993        // and mixed provenance. Every shape must ride cleanly
1994        // through the same 2-arg signature — matches every current
1995        // pre-lift caller in `tatara-export-worker` (CLI-arg driven
1996        // owned strings + `&str` from a struct field) and in
1997        // `tatara-reconciler` (owned locals + function-param
1998        // slices).
1999        let owned_ns = String::from("owned-ns");
2000        let owned_name = String::from("owned-app");
2001        let borrowed_ns: &str = "borrowed-ns";
2002        let borrowed_name: &str = "borrowed-app";
2003        assert_eq!(
2004            qualified_process_ref(&owned_ns, &owned_name),
2005            "owned-ns/owned-app",
2006        );
2007        assert_eq!(
2008            qualified_process_ref(borrowed_ns, borrowed_name),
2009            "borrowed-ns/borrowed-app",
2010        );
2011        assert_eq!(
2012            qualified_process_ref(&owned_ns, borrowed_name),
2013            "owned-ns/borrowed-app",
2014        );
2015    }
2016
2017    #[test]
2018    fn qualified_process_ref_rides_edge_case_axis_shapes() {
2019        // The composer shapes the two axes as arbitrary strings —
2020        // no length/character validation happens at the composer,
2021        // so any shape a Process's `metadata.namespace` /
2022        // `metadata.name` can hold rides through unchanged. Pin
2023        // the empty-string cases (unnamed process pre-metadata,
2024        // cluster-scoped `namespace = ""` fallback), and the
2025        // whitespace-and-slash-in-name pathological case (a
2026        // regression that URL-escaped or path-normalized the input
2027        // at this primitive would silently break every downstream
2028        // grep).
2029        assert_eq!(qualified_process_ref("", ""), "/");
2030        assert_eq!(qualified_process_ref("default", ""), "default/");
2031        assert_eq!(qualified_process_ref("", "orphan"), "/orphan");
2032        assert_eq!(
2033            qualified_process_ref("weird ns", "with/slash"),
2034            "weird ns/with/slash",
2035        );
2036    }
2037
2038    #[test]
2039    fn qualified_process_ref_composes_from_process_coordinates_or_defaults() {
2040        // The primary Process-driven callsite: a live
2041        // [`crate::prelude::Process`] with populated metadata
2042        // composes through
2043        // [`crate::prelude::Process::coordinates_or_defaults`] +
2044        // [`qualified_process_ref`]. Pin the composition so a
2045        // regression in either primitive that broke the `(ns,
2046        // name)` positional contract surfaces HERE rather than as
2047        // silent drift at every downstream reconciler / export-
2048        // worker / pool-reconciler consumer.
2049        use crate::crd::{Process, ProcessSpec};
2050        // Routes through the ONE substrate composer
2051        // `ProcessSpec::gate_compute_defaults` — pre-lift this was a
2052        // 12-line inline struct-literal restated verbatim inside this
2053        // pin body.
2054        let spec = ProcessSpec::gate_compute_defaults();
2055        let mut p = Process::new("ephemeral-demo", spec);
2056        p.metadata.namespace = Some("demo-ns".into());
2057        let (ns, name) = p.coordinates_or_defaults();
2058        assert_eq!(
2059            qualified_process_ref(ns, name),
2060            "demo-ns/ephemeral-demo",
2061            "coordinates_or_defaults + qualified_process_ref must \
2062             compose to the canonical <ns>/<name> shape"
2063        );
2064    }
2065
2066    #[test]
2067    fn qualified_process_ref_matches_hand_authored_pre_lift_bytewise() {
2068        // Byte-identical parity with the exact pre-lift
2069        // `format!("{ns}/{name}")` incantation. A regression that
2070        // reshaped the separator, reordered the axes, or dropped
2071        // either half surfaces HERE rather than at every downstream
2072        // annotation / claim-key / run-id consumer. Sweeps every
2073        // shape combination the pre-lift callers plausibly
2074        // encountered.
2075        for (ns, name) in [
2076            ("demo-ns", "ephemeral-demo"),
2077            ("", ""),
2078            ("default", ""),
2079            ("", "orphan"),
2080        ] {
2081            let via_primitive = qualified_process_ref(ns, name);
2082            let hand_authored = format!("{ns}/{name}");
2083            assert_eq!(
2084                via_primitive, hand_authored,
2085                "qualified_process_ref must be byte-identical to \
2086                 the pre-lift `format!(\"{{ns}}/{{name}}\")` \
2087                 hand-authored shape on ({ns:?}, {name:?})"
2088            );
2089        }
2090    }
2091}
2092
2093#[cfg(test)]
2094mod qualified_error_ctx_tests {
2095    //! Pin the [`qualified_error_ctx`] composer at fail-before-
2096    //! pass-after granularity across the shape it factored out of
2097    //! the two peer per-Kind composers
2098    //! ([`crate::configmap::error_ctx`],
2099    //! [`crate::process_api::error_ctx`]). Every observable slot
2100    //! (verb-first, fixed-Kind literal in the middle, `<ns>/<name>`
2101    //! join at the tail routed through
2102    //! [`qualified_process_ref`]) is bound here so a regression
2103    //! that reordered the head slots, dropped the fixed `<Kind>`
2104    //! word, drifted the qualified-ref join off the substrate axis,
2105    //! or narrowed any input slot to a closed set (would silently
2106    //! reject a future per-Kind peer that composes a fresh verb or
2107    //! Kind literal) surfaces HERE rather than as silent operator-
2108    //! facing skew at the two consumer peers.
2109    use super::qualified_error_ctx;
2110
2111    #[test]
2112    fn qualified_error_ctx_signature_binds_borrowed_slots_returning_owned_string() {
2113        // Signature pin: `verb: &str` + `kind: &str` + `ns: &str` +
2114        // `name: &str` on the input side (both pre-lift per-Kind
2115        // peers pass a `&'static str` verb + `&'static str` fixed-
2116        // Kind literal + borrowed `&str` ns/name fields). Return
2117        // `String` matches the downstream `kube_ctx_with(context:
2118        // String)` sink verbatim on the reconciler-boundary
2119        // consumers AND the `with_context(|| String)` closure form
2120        // on the export-worker consumers.
2121        //
2122        // A regression that widened any input slot to `String`
2123        // (forcing the caller to `.to_string()` at the boundary — a
2124        // per-site perf regression that also fights the
2125        // `&str`-fields-in-args idiom the callers thread) or
2126        // narrowed the return to `&'static str` (which would prevent
2127        // the runtime-composed ns/name slots the two peer composers
2128        // pass) fails at compile time.
2129        let _witness: fn(&str, &str, &str, &str) -> String = qualified_error_ctx;
2130    }
2131
2132    #[test]
2133    fn qualified_error_ctx_composes_verb_kind_qualified_ref_head_verbatim() {
2134        // Byte-shape parity witness on the primary shape both peer
2135        // composers depend on: the composed slug MUST be exactly
2136        // `"<verb> <Kind> <ns>/<name>"` in that order. A regression
2137        // that reordered the head slots (verb after Kind, Kind
2138        // after the qualified ref) would silently break every
2139        // operator-facing grep every downstream diagnostic body
2140        // riding through the sibling per-Kind peers uses.
2141        assert_eq!(
2142            qualified_error_ctx("fetch", "Process", "default", "api"),
2143            "fetch Process default/api",
2144        );
2145        assert_eq!(
2146            qualified_error_ctx("patch", "ConfigMap", "demo-ns", "receipt-cm"),
2147            "patch ConfigMap demo-ns/receipt-cm",
2148        );
2149    }
2150
2151    #[test]
2152    fn qualified_error_ctx_routes_ns_name_join_through_qualified_process_ref_substrate() {
2153        // Routing pin — the `<ns>/<name>` join at the composer's
2154        // tail rides through the workspace-wide
2155        // [`qualified_process_ref`] primitive rather than a bare
2156        // inline `format!("{ns}/{name}")`. A future normalization
2157        // of the qualified-ref shape (case-fold, unicode collation,
2158        // IDN) lands at ONE [`qualified_process_ref`] site and
2159        // every per-Kind diagnostic body picks it up mechanically;
2160        // this pin binds THIS composer to that substrate so a
2161        // regression that inlined the join (drifting the primitive
2162        // off the substrate axis this commit opens) surfaces HERE
2163        // rather than as silent qualified-ref drift between the
2164        // two peer per-Kind composers and every other qualified-
2165        // ref consumer across the workspace.
2166        for (verb, kind, ns, name) in [
2167            ("fetch", "Process", "default", "api"),
2168            ("get", "Process", "tatara-system", "reconciler-canary"),
2169            ("patch", "ConfigMap", "demo-ns", "receipt-cm"),
2170            ("create", "ConfigMap", "ns-1", "cm.dotted.name"),
2171        ] {
2172            let via_composer = qualified_error_ctx(verb, kind, ns, name);
2173            let via_qualified = format!("{verb} {kind} {}", super::qualified_process_ref(ns, name));
2174            assert_eq!(
2175                via_composer, via_qualified,
2176                "qualified_error_ctx must route the (ns, name) join through \
2177                 qualified_process_ref for ({verb:?}, {kind:?}, {ns:?}, {name:?})",
2178            );
2179        }
2180    }
2181
2182    #[test]
2183    fn qualified_error_ctx_is_symbolic_over_the_kind_slot() {
2184        // Symbolic pin: the `kind` slot is threaded verbatim into
2185        // the produced slug — no case-fold, no allow-list narrowing
2186        // to the two shipped Kinds (`"ConfigMap"`, `"Process"`), no
2187        // per-Kind canonicalization. A regression that hardcoded
2188        // an allow-list (a `match kind { "ConfigMap" | "Process" =>
2189        // …, _ => … }` closed set that would silently reject future
2190        // per-Kind peers) surfaces HERE.
2191        //
2192        // Future third + fourth per-Kind peers (a `Secret` axis
2193        // reader, a `batch/v1::Job` axis reader for the
2194        // ConditionKind::JobAttested companion, a FluxCD
2195        // `HelmRelease` axis reader for the P2 reconciler's
2196        // emit-side) inherit the primitive at their own peer
2197        // composers and pass their own Kind literals verbatim
2198        // without the composer widening.
2199        for kind in [
2200            "ConfigMap",
2201            "Process",
2202            "Secret",
2203            "Job",
2204            "HelmRelease",
2205            "OCIRepository",
2206            "Deployment",
2207            "StatefulSet",
2208        ] {
2209            let got = qualified_error_ctx("fetch", kind, "default", "api");
2210            let expected = format!("fetch {kind} default/api");
2211            assert_eq!(
2212                got, expected,
2213                "kind-slot substitution must be verbatim for {kind:?}"
2214            );
2215        }
2216    }
2217
2218    #[test]
2219    fn qualified_error_ctx_is_symbolic_over_the_verb_slot() {
2220        // Symbolic pin: the `verb` slot is threaded verbatim — same
2221        // discipline as the sibling verb-slot pins on the two peer
2222        // per-Kind composers ([`crate::configmap::tests::
2223        // error_ctx_is_symbolic_over_the_verb_slot`] via absence,
2224        // [`crate::process_api::tests::
2225        // error_ctx_is_symbolic_over_the_verb_slot`]). Post-lift
2226        // both peers route through this composer so this pin binds
2227        // the shared symbolic contract at ONE substrate owner rather
2228        // than as two parallel pins that could drift.
2229        for verb in [
2230            "fetch", "get", "reap", "resolve", "watch", "patch", "delete", "create",
2231        ] {
2232            let got = qualified_error_ctx(verb, "Process", "default", "api");
2233            let expected = format!("{verb} Process default/api");
2234            assert_eq!(
2235                got, expected,
2236                "verb-slot substitution must be verbatim for {verb:?}"
2237            );
2238        }
2239    }
2240
2241    #[test]
2242    fn qualified_error_ctx_matches_configmap_peer_bytewise() {
2243        // Post-lift peer coherence pin: the composer's output at
2244        // `<Kind> = "ConfigMap"` MUST be byte-identical to the
2245        // [`crate::configmap::error_ctx`] peer's output at the SAME
2246        // (verb, ns, name) triple. The peer is now a one-line
2247        // delegate through this composer, so a regression that
2248        // dropped or drifted the delegation would surface HERE.
2249        for (verb, ns, name) in [
2250            ("patch", "default", "receipt-cm"),
2251            ("create", "demo-ns", "cm-01"),
2252            ("get", "ns-1", "receipt.dotted.name"),
2253        ] {
2254            let via_composer = qualified_error_ctx(verb, "ConfigMap", ns, name);
2255            let via_peer = crate::configmap::error_ctx(verb, ns, name);
2256            assert_eq!(
2257                via_composer, via_peer,
2258                "configmap::error_ctx must route through qualified_error_ctx \
2259                 for ({verb:?}, {ns:?}, {name:?})"
2260            );
2261        }
2262    }
2263
2264    #[test]
2265    fn qualified_error_ctx_matches_process_api_peer_bytewise() {
2266        // Post-lift peer coherence pin: the composer's output at
2267        // `<Kind> = "Process"` MUST be byte-identical to the
2268        // [`crate::process_api::error_ctx`] peer's output at the
2269        // SAME (verb, ns, name) triple. Peer to the ConfigMap
2270        // coherence pin above — both peers now delegate through the
2271        // SAME 4-slot composer, so a regression that drifted either
2272        // delegation surfaces at exactly ONE of the two
2273        // fail-before-pass-after pins.
2274        for (verb, ns, name) in [
2275            ("fetch", "default", "api"),
2276            ("get", "demo-ns", "demo"),
2277            ("watch", "tatara-system", "reconciler-canary"),
2278        ] {
2279            let via_composer = qualified_error_ctx(verb, "Process", ns, name);
2280            let via_peer = crate::process_api::error_ctx(verb, ns, name);
2281            assert_eq!(
2282                via_composer, via_peer,
2283                "process_api::error_ctx must route through qualified_error_ctx \
2284                 for ({verb:?}, {ns:?}, {name:?})"
2285            );
2286        }
2287    }
2288
2289    #[test]
2290    fn qualified_error_ctx_rides_edge_case_axis_shapes() {
2291        // Edge-case pin: the composer performs NO validation on the
2292        // four slots — an empty verb / empty Kind / empty ns / empty
2293        // name / slash-in-name pathological input rides through
2294        // unchanged. Matches the pre-lift per-Kind peers' semantics
2295        // (both were unconditional `format!(…)` chains). A
2296        // regression that added a normalization step (URL-escaping
2297        // the slot values, path-normalizing the qualified-ref tail,
2298        // trimming empty slots) at this primitive would silently
2299        // break every downstream grep operators run to bisect an
2300        // authoring bug in the pre-lift consumers' input surface.
2301        assert_eq!(qualified_error_ctx("", "", "", ""), "  /");
2302        assert_eq!(
2303            qualified_error_ctx("fetch", "Process", "", ""),
2304            "fetch Process /",
2305        );
2306        assert_eq!(
2307            qualified_error_ctx("fetch", "Process", "default", ""),
2308            "fetch Process default/",
2309        );
2310        assert_eq!(
2311            qualified_error_ctx("get", "Process", "ns", "with/slash"),
2312            "get Process ns/with/slash",
2313        );
2314    }
2315}
2316
2317#[cfg(test)]
2318mod namespaced_api_coordinates_tests {
2319    //! Pin the [`NamespacedApiCoordinates`] trait's
2320    //! `owned_coordinates_required` extractor at fail-before-pass-
2321    //! after granularity across every corner of the (namespace slot,
2322    //! name slot) × (present, absent) input matrix, on BOTH CRDs the
2323    //! trait's blanket impl covers today (`EphemeralPool` +
2324    //! `EphemeralAllocation`). A regression that reordered the two
2325    //! `ok_or_else` gates, dropped the `Self::kind` prefix, or drifted
2326    //! the error-string spelling surfaces HERE rather than as silent
2327    //! operator-facing skew between the two reconcilers' top-level
2328    //! error messages.
2329    use super::NamespacedApiCoordinates;
2330    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
2331    use crate::ephemeral::EphemeralSpec;
2332    use crate::intent::AplicacaoIntent;
2333    use crate::lifetime::TeardownPolicy;
2334    use crate::pool::{EphemeralPool, PoolSpec};
2335
2336    fn empty_template() -> EphemeralSpec {
2337        // Mirror `tatara-pool-reconciler::router::tests::empty_template`
2338        // — the workspace-wide minimal `EphemeralSpec` fixture the sister
2339        // reconciler tests already use for pool wiring exercised here.
2340        EphemeralSpec {
2341            aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
2342            ttl: "1h".into(),
2343            teardown: TeardownPolicy::Always,
2344            max_concurrent: 0,
2345            postconditions: vec![],
2346            preconditions: vec![],
2347            verify_timeout: None,
2348            classification: None,
2349            parent: None,
2350            exports: vec![],
2351            routing: None,
2352        }
2353    }
2354
2355    fn pool_fixture(name: &str, ns: Option<&str>) -> EphemeralPool {
2356        // Every non-template slot rides the ONE substrate composer
2357        // [`PoolSpec::with_template`]; pre-lift this fixture spelled the
2358        // full 11-slot struct-literal verbatim as one of eight cross-
2359        // crate hand-authored copies. See the primitive's doc-comment
2360        // for the full migration rationale.
2361        let spec = PoolSpec {
2362            desired_size: 1,
2363            ..PoolSpec::with_template(empty_template())
2364        };
2365        let mut p = EphemeralPool::new(name, spec);
2366        p.metadata.namespace = ns.map(str::to_string);
2367        p
2368    }
2369
2370    fn alloc_fixture(name: &str, ns: Option<&str>) -> EphemeralAllocation {
2371        // AllocationSpec rides through the ONE substrate composer
2372        // `AllocationSpec::requestor_only`; the inner Requestor rides
2373        // through the peer composer `Requestor::kind_only`. Nine
2374        // pre-lift exact-match sites past the ★★ PRIME-DIRECTIVE ≥ 2
2375        // threshold collapse onto this ONE substrate owner.
2376        let spec = AllocationSpec::requestor_only(Requestor::kind_only("github-pr"));
2377        let mut a = EphemeralAllocation::new(name, spec);
2378        a.metadata.namespace = ns.map(str::to_string);
2379        a
2380    }
2381
2382    fn nameless_pool(ns: Option<&str>) -> EphemeralPool {
2383        let mut p = pool_fixture("placeholder", ns);
2384        p.metadata.name = None;
2385        p
2386    }
2387
2388    fn nameless_alloc(ns: Option<&str>) -> EphemeralAllocation {
2389        let mut a = alloc_fixture("placeholder", ns);
2390        a.metadata.name = None;
2391        a
2392    }
2393
2394    // ── Happy path: both slots present ─────────────────────────────
2395
2396    #[test]
2397    fn owned_coordinates_required_returns_owned_strings_on_ephemeral_pool_when_both_slots_present()
2398    {
2399        let p = pool_fixture("attest-pool", Some("ephemeral-pools"));
2400        let (ns, name) = p.owned_coordinates_required().unwrap();
2401        assert_eq!(ns, "ephemeral-pools");
2402        assert_eq!(name, "attest-pool");
2403    }
2404
2405    #[test]
2406    fn owned_coordinates_required_returns_owned_strings_on_ephemeral_allocation_when_both_slots_present(
2407    ) {
2408        let a = alloc_fixture("pr-42-demo", Some("ephemeral-pools"));
2409        let (ns, name) = a.owned_coordinates_required().unwrap();
2410        assert_eq!(ns, "ephemeral-pools");
2411        assert_eq!(name, "pr-42-demo");
2412    }
2413
2414    // ── Missing namespace ─────────────────────────────────────────
2415
2416    #[test]
2417    fn owned_coordinates_required_errors_on_ephemeral_pool_missing_namespace() {
2418        let p = pool_fixture("attest-pool", None);
2419        let err = p.owned_coordinates_required().unwrap_err();
2420        assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
2421    }
2422
2423    #[test]
2424    fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_namespace() {
2425        let a = alloc_fixture("pr-42-demo", None);
2426        let err = a.owned_coordinates_required().unwrap_err();
2427        assert_eq!(
2428            err.to_string(),
2429            "EphemeralAllocation has no metadata.namespace"
2430        );
2431    }
2432
2433    // ── Missing name ──────────────────────────────────────────────
2434
2435    #[test]
2436    fn owned_coordinates_required_errors_on_ephemeral_pool_missing_name_when_namespace_present() {
2437        let p = nameless_pool(Some("ephemeral-pools"));
2438        let err = p.owned_coordinates_required().unwrap_err();
2439        assert_eq!(err.to_string(), "EphemeralPool has no metadata.name");
2440    }
2441
2442    #[test]
2443    fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_name_when_namespace_present(
2444    ) {
2445        let a = nameless_alloc(Some("ephemeral-pools"));
2446        let err = a.owned_coordinates_required().unwrap_err();
2447        assert_eq!(err.to_string(), "EphemeralAllocation has no metadata.name");
2448    }
2449
2450    // ── Missing both slots: namespace error wins (pre-lift ordering) ──
2451
2452    #[test]
2453    fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_pool()
2454    {
2455        // Pre-lift both reconcilers spelled the paired chain as the
2456        // namespace ok_or_else THEN the name ok_or_else, so the
2457        // reported error on a fixture missing both slots was always
2458        // the namespace one. Pin that ordering post-lift so a
2459        // regression that swapped the two `ok_or_else` blocks
2460        // surfaces HERE rather than at operator-facing log-line
2461        // grep drift between the two reconcilers.
2462        let p = nameless_pool(None);
2463        let err = p.owned_coordinates_required().unwrap_err();
2464        assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
2465    }
2466
2467    #[test]
2468    fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_allocation(
2469    ) {
2470        let a = nameless_alloc(None);
2471        let err = a.owned_coordinates_required().unwrap_err();
2472        assert_eq!(
2473            err.to_string(),
2474            "EphemeralAllocation has no metadata.namespace"
2475        );
2476    }
2477
2478    // ── Byte-identical parity with the pre-lift 5-line chain ──────
2479
2480    #[test]
2481    fn owned_coordinates_required_matches_pre_lift_pool_reconciler_chain_shape() {
2482        // Byte-identical parity pin: the primitive produces the SAME
2483        // `Result<(String, String), anyhow::Error>` shape a pre-lift
2484        // `.metadata.<slot>.clone().ok_or_else(|| anyhow!("<Kind> has
2485        // no metadata.<slot>"))?` chain produced at
2486        // `tatara-pool-reconciler::controller_pool::reconcile_inner`
2487        // pre-lift, on both the happy and the missing-slot corners.
2488        // A regression that changed the error prefix, reordered the
2489        // two gates, or returned a non-`(String, String)` tuple
2490        // surfaces HERE rather than at every consumer downstream.
2491        let cases = [
2492            (Some("prod"), Some("api")),
2493            (Some("prod"), None),
2494            (None, Some("orphan")),
2495            (None, None),
2496        ];
2497        for (ns_slot, name_slot) in cases {
2498            let mut p = pool_fixture("placeholder", ns_slot);
2499            if let Some(nm) = name_slot {
2500                p.metadata.name = Some(nm.into());
2501            } else {
2502                p.metadata.name = None;
2503            }
2504
2505            // Pre-lift 5-line paired chain (with the reconciler's
2506            // hand-authored short-form `"Pool"` prefix updated to the
2507            // canonical kube kind `"EphemeralPool"`, matching the
2508            // primitive's `Self::kind`-driven spelling — the drift
2509            // is intentional per the trait's docs).
2510            let pre_lift: anyhow::Result<(String, String)> = (|| {
2511                let ns =
2512                    p.metadata.namespace.clone().ok_or_else(|| {
2513                        anyhow::anyhow!("EphemeralPool has no metadata.namespace")
2514                    })?;
2515                let name = p
2516                    .metadata
2517                    .name
2518                    .clone()
2519                    .ok_or_else(|| anyhow::anyhow!("EphemeralPool has no metadata.name"))?;
2520                Ok((ns, name))
2521            })();
2522
2523            let via_primitive = p.owned_coordinates_required();
2524
2525            // Compare on both the Ok tuple + the error string
2526            // spelling — anyhow::Error does not derive PartialEq so
2527            // pattern-match on the Result axis rather than a direct
2528            // `assert_eq!` on the whole Result.
2529            match (via_primitive, pre_lift) {
2530                (Ok(a), Ok(b)) => assert_eq!(a, b),
2531                (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
2532                (a, b) => panic!(
2533                    "primitive vs pre-lift chain disagree on Ok/Err axis for \
2534                     (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
2535                ),
2536            }
2537        }
2538    }
2539
2540    #[test]
2541    fn owned_coordinates_required_matches_pre_lift_allocation_reconciler_chain_shape() {
2542        // Peer to the pool-side pin above — pin the same byte-
2543        // identity contract on the allocation reconciler's chain,
2544        // where the pre-lift error spelling used the short-form
2545        // `"Allocation"` prefix that the primitive now emits as the
2546        // canonical kube-kind `"EphemeralAllocation"`.
2547        let cases = [
2548            (Some("ephemeral-pools"), Some("pr-42-demo")),
2549            (Some("ephemeral-pools"), None),
2550            (None, Some("orphan")),
2551            (None, None),
2552        ];
2553        for (ns_slot, name_slot) in cases {
2554            let mut a = alloc_fixture("placeholder", ns_slot);
2555            if let Some(nm) = name_slot {
2556                a.metadata.name = Some(nm.into());
2557            } else {
2558                a.metadata.name = None;
2559            }
2560
2561            let pre_lift: anyhow::Result<(String, String)> = (|| {
2562                let ns = a.metadata.namespace.clone().ok_or_else(|| {
2563                    anyhow::anyhow!("EphemeralAllocation has no metadata.namespace")
2564                })?;
2565                let name =
2566                    a.metadata.name.clone().ok_or_else(|| {
2567                        anyhow::anyhow!("EphemeralAllocation has no metadata.name")
2568                    })?;
2569                Ok((ns, name))
2570            })();
2571
2572            let via_primitive = a.owned_coordinates_required();
2573
2574            match (via_primitive, pre_lift) {
2575                (Ok(a), Ok(b)) => assert_eq!(a, b),
2576                (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
2577                (a, b) => panic!(
2578                    "primitive vs pre-lift chain disagree on Ok/Err axis for \
2579                     (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
2580                ),
2581            }
2582        }
2583    }
2584
2585    // ── Cross-CRD symmetry: kube kind drives the error prefix ─────
2586
2587    #[test]
2588    fn owned_coordinates_required_error_prefix_matches_kube_kind_on_each_crd() {
2589        // The error prefix is sourced positionally from `Self::kind`
2590        // so the two CRDs emit distinct kube-canonical spellings
2591        // without either callsite hard-coding a per-CRD literal.
2592        // Regressions that hard-coded a shared prefix (e.g. a
2593        // copy-paste that pasted the pool's error string into the
2594        // allocation callsite) surface HERE.
2595        use kube::Resource;
2596        let p = pool_fixture("p", None);
2597        let a = alloc_fixture("a", None);
2598        assert_eq!(
2599            p.owned_coordinates_required().unwrap_err().to_string(),
2600            format!("{} has no metadata.namespace", EphemeralPool::kind(&()))
2601        );
2602        assert_eq!(
2603            a.owned_coordinates_required().unwrap_err().to_string(),
2604            format!(
2605                "{} has no metadata.namespace",
2606                EphemeralAllocation::kind(&())
2607            )
2608        );
2609        // Belt-and-suspenders: the two kinds are distinct spellings,
2610        // so the error strings are distinct too.
2611        assert_ne!(
2612            p.owned_coordinates_required().unwrap_err().to_string(),
2613            a.owned_coordinates_required().unwrap_err().to_string(),
2614        );
2615    }
2616}
2617
2618#[cfg(test)]
2619mod deletion_tombstoned_tests {
2620    //! Pin the [`DeletionTombstoned`] trait's `is_being_deleted` probe
2621    //! at fail-before-pass-after granularity across every corner of
2622    //! the (tombstone present, tombstone absent) input matrix, on
2623    //! ALL THREE tatara-process CRDs the trait's blanket impl covers
2624    //! today (`Process`, `EphemeralPool`, `EphemeralAllocation`), plus
2625    //! the cross-CRD coherence with the two pre-existing inherent
2626    //! forwarders. A regression that skewed the trait's default,
2627    //! promoted a distinct-payload tombstone to a false negative, or
2628    //! diverged the trait from either inherent forwarder surfaces
2629    //! HERE rather than as silent operator-facing skew between the
2630    //! four consumer sites the primitive owns (the top-level
2631    //! dispatcher's SIGTERM preempt, the SIGTERM cascade's child-
2632    //! fan-out DELETE-skip, the pool reconciler's Drain gate, and
2633    //! the allocation reconciler's release short-circuit) on three
2634    //! sibling CRDs.
2635    use super::DeletionTombstoned;
2636    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
2637    use crate::crd::{Process, ProcessSpec};
2638    use crate::ephemeral::EphemeralSpec;
2639    use crate::intent::AplicacaoIntent;
2640    use crate::lifetime::TeardownPolicy;
2641    use crate::pool::{EphemeralPool, PoolSpec};
2642    use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
2643
2644    fn empty_template() -> EphemeralSpec {
2645        EphemeralSpec {
2646            aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
2647            ttl: "1h".into(),
2648            teardown: TeardownPolicy::Always,
2649            max_concurrent: 0,
2650            postconditions: vec![],
2651            preconditions: vec![],
2652            verify_timeout: None,
2653            classification: None,
2654            parent: None,
2655            exports: vec![],
2656            routing: None,
2657        }
2658    }
2659
2660    fn empty_pool_spec() -> PoolSpec {
2661        // Every non-template slot rides the ONE substrate composer
2662        // [`PoolSpec::with_template`]; see the primitive's doc-comment
2663        // for the full migration rationale.
2664        PoolSpec {
2665            desired_size: 1,
2666            ..PoolSpec::with_template(empty_template())
2667        }
2668    }
2669
2670    fn empty_alloc_spec() -> AllocationSpec {
2671        // AllocationSpec rides through the ONE substrate composer
2672        // `AllocationSpec::requestor_only`; the inner Requestor rides
2673        // through `Requestor::kind_only`. Nine pre-lift exact-match
2674        // fixture sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold
2675        // collapse onto this ONE substrate owner.
2676        AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
2677    }
2678
2679    fn empty_process_spec() -> ProcessSpec {
2680        // Routes through the ONE substrate composer
2681        // `ProcessSpec::gate_compute_defaults` — the minimal
2682        // `ProcessSpec` used across every substrate metadata-projection
2683        // pin. Pre-lift this was the 12-line struct-literal restated
2684        // verbatim at every fixture in this pin family.
2685        ProcessSpec::gate_compute_defaults()
2686    }
2687
2688    // ── Missing tombstone (default fixture) — trait returns false ─────
2689
2690    #[test]
2691    fn is_being_deleted_on_process_missing_tombstone_returns_false_via_trait() {
2692        let p = Process::new("api", empty_process_spec());
2693        assert!(!DeletionTombstoned::is_being_deleted(&p));
2694    }
2695
2696    #[test]
2697    fn is_being_deleted_on_ephemeral_pool_missing_tombstone_returns_false_via_trait() {
2698        let p = EphemeralPool::new("attest-pool", empty_pool_spec());
2699        assert!(!DeletionTombstoned::is_being_deleted(&p));
2700    }
2701
2702    #[test]
2703    fn is_being_deleted_on_ephemeral_allocation_missing_tombstone_returns_false_via_trait() {
2704        // The load-bearing corner: EphemeralAllocation had NO inherent
2705        // is_being_deleted pre-lift — the trait's blanket impl is
2706        // what closes the substrate gap for the allocation reconciler's
2707        // hand-authored `.metadata.deletion_timestamp.is_some()` chain.
2708        let a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2709        assert!(!DeletionTombstoned::is_being_deleted(&a));
2710    }
2711
2712    // ── Present tombstone — trait returns true ────────────────────────
2713
2714    #[test]
2715    fn is_being_deleted_on_process_present_tombstone_returns_true_via_trait() {
2716        let mut p = Process::new("api", empty_process_spec());
2717        // Routes through the ONE substrate composer
2718        // `tatara_process::time::tombstone_now` — one of 12 pre-lift
2719        // exact-match sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold
2720        // for the `Some(Time(Utc::now()))` wire shape.
2721        p.metadata.deletion_timestamp = crate::time::tombstone_now();
2722        assert!(DeletionTombstoned::is_being_deleted(&p));
2723    }
2724
2725    #[test]
2726    fn is_being_deleted_on_ephemeral_pool_present_tombstone_returns_true_via_trait() {
2727        let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
2728        p.metadata.deletion_timestamp = crate::time::tombstone_now();
2729        assert!(DeletionTombstoned::is_being_deleted(&p));
2730    }
2731
2732    #[test]
2733    fn is_being_deleted_on_ephemeral_allocation_present_tombstone_returns_true_via_trait() {
2734        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2735        a.metadata.deletion_timestamp = crate::time::tombstone_now();
2736        assert!(DeletionTombstoned::is_being_deleted(&a));
2737    }
2738
2739    // ── Byte-identical parity with the pre-lift `.is_some()` chain ────
2740
2741    #[test]
2742    fn is_being_deleted_matches_pre_lift_deletion_timestamp_is_some_chain_on_ephemeral_allocation()
2743    {
2744        // Byte-identical parity pin: the trait's default produces the
2745        // SAME `bool` a pre-lift `.metadata.deletion_timestamp.is_some()`
2746        // chain produced at `tatara-pool-reconciler::allocation_decide::
2747        // AllocationConvergenceCtx::observe` pre-lift, across every
2748        // corner of the (absent, present-at-now, present-at-past)
2749        // input matrix. A regression that inserted a normalization
2750        // step the pre-lift chain does NOT apply — or vice versa —
2751        // surfaces here rather than as silent drift between the
2752        // substrate owner and the pre-lift consumer.
2753        // Routes through the ONE substrate composer family
2754        // `tatara_process::time::{tombstone_now,tombstone_at}` — the
2755        // present-at-now corner rides `tombstone_now`, the present-at-
2756        // past corner composes `tombstone_at(seconds_ago(3600))` per
2757        // the composer's canonical stale-fixture shape.
2758        let mut cases: Vec<Option<Time>> = vec![None];
2759        cases.push(crate::time::tombstone_now());
2760        cases.push(crate::time::tombstone_at(crate::time::seconds_ago(3600)));
2761
2762        for ts in cases {
2763            let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2764            a.metadata.deletion_timestamp = ts.clone();
2765
2766            let pre_lift = a.metadata.deletion_timestamp.is_some();
2767            let via_trait = DeletionTombstoned::is_being_deleted(&a);
2768
2769            assert_eq!(
2770                pre_lift, via_trait,
2771                "trait probe must be byte-identical to pre-lift .metadata.deletion_timestamp.is_some() on tombstone={ts:?}",
2772            );
2773        }
2774    }
2775
2776    // ── Cross-CRD coherence with the two inherent forwarders ──────────
2777
2778    #[test]
2779    fn trait_probe_coheres_with_process_inherent_is_being_deleted_on_both_corners() {
2780        // Cross-primitive coherence pin: the trait's default and the
2781        // pre-existing `Process::is_being_deleted` inherent forwarder
2782        // return the SAME `bool` on the SAME `Process` value — a
2783        // future consolidation of the inherent onto the trait's default
2784        // (or vice versa) cannot land any drift between the two
2785        // surfaces because this pin binds them at every corner of the
2786        // (missing, present) input matrix.
2787        // Routes the tombstone-present corner through the ONE
2788        // substrate composer `tatara_process::time::tombstone_now`.
2789        for ts in [None, crate::time::tombstone_now()] {
2790            let mut p = Process::new("api", empty_process_spec());
2791            p.metadata.deletion_timestamp = ts.clone();
2792            assert_eq!(
2793                p.is_being_deleted(),
2794                DeletionTombstoned::is_being_deleted(&p),
2795                "Process trait probe must match inherent on tombstone={ts:?}",
2796            );
2797        }
2798    }
2799
2800    #[test]
2801    fn trait_probe_coheres_with_ephemeral_pool_inherent_is_being_deleted_on_both_corners() {
2802        // Peer coherence pin on the sister CRD.
2803        for ts in [None, crate::time::tombstone_now()] {
2804            let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
2805            p.metadata.deletion_timestamp = ts.clone();
2806            assert_eq!(
2807                p.is_being_deleted(),
2808                DeletionTombstoned::is_being_deleted(&p),
2809                "EphemeralPool trait probe must match inherent on tombstone={ts:?}",
2810            );
2811        }
2812    }
2813
2814    // ── Inherent-preferred method resolution on Process + EphemeralPool ──
2815
2816    #[test]
2817    fn dot_call_on_process_resolves_to_inherent_when_trait_in_scope() {
2818        // Rust method resolution prefers an inherent over a trait's
2819        // blanket impl, so `process.is_being_deleted()` with the trait
2820        // in scope still routes through the inherent — and both
2821        // return the same `bool` (verified in
2822        // `trait_probe_coheres_with_process_inherent_is_being_deleted_on_both_corners`).
2823        // This pin guards against a future refactor that removes the
2824        // inherent but leaves consumers assuming inherent-preferred
2825        // resolution — the observable output is identical either way,
2826        // so the pin locks the invariant that BOTH paths agree.
2827        let mut p = Process::new("api", empty_process_spec());
2828        // Routes through `tatara_process::time::tombstone_now`.
2829        p.metadata.deletion_timestamp = crate::time::tombstone_now();
2830        assert!(p.is_being_deleted());
2831    }
2832
2833    #[test]
2834    fn dot_call_on_ephemeral_allocation_resolves_to_trait_blanket_impl() {
2835        // The load-bearing corner: `alloc.is_being_deleted()` with
2836        // the trait in scope routes to the trait's blanket impl
2837        // (there is no inherent on `EphemeralAllocation`) and
2838        // produces the expected `bool`. This is what the swept
2839        // allocation-reconciler callsite depends on post-lift.
2840        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2841        assert!(!a.is_being_deleted());
2842        a.metadata.deletion_timestamp = crate::time::tombstone_now();
2843        assert!(a.is_being_deleted());
2844    }
2845}
2846
2847#[cfg(test)]
2848mod annotated_tests {
2849    //! Pin the [`Annotated`] trait's `annotation` lookup at fail-
2850    //! before-pass-after granularity across every corner of the
2851    //! (annotations map: absent / present-empty / present-with-key /
2852    //! present-without-key) × (value form: normal / empty-string)
2853    //! input matrix, on the three tatara-process CRDs the trait's
2854    //! blanket impl covers today (`Process`, `EphemeralPool`,
2855    //! `EphemeralAllocation`) PLUS a K8s built-in (`ConfigMap`) — the
2856    //! load-bearing fourth surface that `tatara-export-worker::main`
2857    //! consumes post-lift where no tatara-owned inherent forwarder
2858    //! exists. Also pin cross-primitive coherence with the pre-existing
2859    //! `Process::annotation` inherent so a future consolidation onto
2860    //! the trait's default cannot silently skew the three consumers
2861    //! already routed through the inherent
2862    //! (`signals::ingest`,
2863    //! `phase_machine::released_from_annotation`,
2864    //! `controller_pool::process_belongs_to_pool`).
2865    use super::Annotated;
2866    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
2867    use crate::crd::{Process, ProcessSpec};
2868    use crate::ephemeral::EphemeralSpec;
2869    use crate::intent::AplicacaoIntent;
2870    use crate::lifetime::TeardownPolicy;
2871    use crate::pool::{EphemeralPool, PoolSpec};
2872    use k8s_openapi::api::core::v1::ConfigMap;
2873    use std::collections::BTreeMap;
2874
2875    fn empty_template() -> EphemeralSpec {
2876        EphemeralSpec {
2877            aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
2878            ttl: "1h".into(),
2879            teardown: TeardownPolicy::Always,
2880            max_concurrent: 0,
2881            postconditions: vec![],
2882            preconditions: vec![],
2883            verify_timeout: None,
2884            classification: None,
2885            parent: None,
2886            exports: vec![],
2887            routing: None,
2888        }
2889    }
2890
2891    fn empty_pool_spec() -> PoolSpec {
2892        // Every non-template slot rides the ONE substrate composer
2893        // [`PoolSpec::with_template`]; see the primitive's doc-comment
2894        // for the full migration rationale.
2895        PoolSpec {
2896            desired_size: 1,
2897            ..PoolSpec::with_template(empty_template())
2898        }
2899    }
2900
2901    fn empty_alloc_spec() -> AllocationSpec {
2902        // AllocationSpec rides through `AllocationSpec::requestor_only`;
2903        // the inner Requestor rides through `Requestor::kind_only` —
2904        // sibling to the peer `empty_alloc_spec` fixture in the
2905        // DeletionTombstoned pin module above.
2906        AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
2907    }
2908
2909    fn empty_process_spec() -> ProcessSpec {
2910        // Routes through the ONE substrate composer
2911        // `ProcessSpec::gate_compute_defaults` — sibling to the
2912        // `empty_process_spec` fixture in the DeletionTombstoned pin
2913        // module above and to `empty_spec` in `crd.rs::tests`.
2914        ProcessSpec::gate_compute_defaults()
2915    }
2916
2917    fn one_annotation(key: &str, value: &str) -> BTreeMap<String, String> {
2918        let mut m = BTreeMap::new();
2919        m.insert(key.into(), value.into());
2920        m
2921    }
2922
2923    // ── Missing annotations map — trait returns None on every key ─────
2924
2925    #[test]
2926    fn annotation_on_process_missing_annotations_returns_none_via_trait() {
2927        let mut p = Process::new("api", empty_process_spec());
2928        p.metadata.annotations = None;
2929        assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/signal"), None);
2930        assert_eq!(Annotated::annotation(&p, ""), None);
2931    }
2932
2933    #[test]
2934    fn annotation_on_ephemeral_pool_missing_annotations_returns_none_via_trait() {
2935        let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
2936        p.metadata.annotations = None;
2937        assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/pool"), None);
2938    }
2939
2940    #[test]
2941    fn annotation_on_ephemeral_allocation_missing_annotations_returns_none_via_trait() {
2942        // The peer load-bearing corner: EphemeralAllocation has NO
2943        // inherent `annotation()` pre-lift — the trait's blanket impl
2944        // is what closes the substrate gap here, exactly as the
2945        // sibling `DeletionTombstoned` trait already did on the
2946        // tombstone axis for the SAME third CRD.
2947        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2948        a.metadata.annotations = None;
2949        assert_eq!(
2950            Annotated::annotation(&a, "tatara.pleme.io/requestor-kind"),
2951            None,
2952        );
2953    }
2954
2955    #[test]
2956    fn annotation_on_config_map_missing_annotations_returns_none_via_trait() {
2957        // The load-bearing corner the export-worker's post-lift call
2958        // depends on: `ConfigMap` is a K8s built-in with no tatara-
2959        // owned inherent forwarder, and the receipts-owner filter
2960        // needs to route through the trait's blanket impl at
2961        // `cm.annotation(KEY)`.
2962        let cm = ConfigMap::default();
2963        // `Default::default()` produces an object with an empty
2964        // ObjectMeta whose `annotations` slot is `None` — the exact
2965        // missing-annotations corner the trait must collapse to
2966        // `None` at every key lookup, matching what the pre-lift
2967        // `cm.metadata.annotations.as_ref().and_then(...)` chain
2968        // produced.
2969        assert_eq!(Annotated::annotation(&cm, "tatara.pleme.io/process"), None,);
2970    }
2971
2972    // ── Missing key inside populated map — trait returns None ─────────
2973
2974    #[test]
2975    fn annotation_on_process_missing_key_returns_none_via_trait() {
2976        let mut p = Process::new("api", empty_process_spec());
2977        p.metadata.annotations = Some(one_annotation("other/key", "irrelevant"));
2978        assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/signal"), None);
2979        assert_eq!(Annotated::annotation(&p, ""), None);
2980    }
2981
2982    #[test]
2983    fn annotation_on_config_map_missing_key_returns_none_via_trait() {
2984        let mut cm = ConfigMap::default();
2985        cm.metadata.annotations = Some(one_annotation("unrelated", "yes"));
2986        assert_eq!(Annotated::annotation(&cm, "tatara.pleme.io/process"), None,);
2987    }
2988
2989    // ── Present key — trait returns borrowed slice ────────────────────
2990
2991    #[test]
2992    fn annotation_on_process_present_key_returns_borrowed_slice_via_trait() {
2993        let mut p = Process::new("api", empty_process_spec());
2994        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", "SIGHUP"));
2995        assert_eq!(
2996            Annotated::annotation(&p, "tatara.pleme.io/signal"),
2997            Some("SIGHUP"),
2998        );
2999    }
3000
3001    #[test]
3002    fn annotation_on_ephemeral_pool_present_key_returns_borrowed_slice_via_trait() {
3003        let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
3004        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/pool", "demo-pool"));
3005        assert_eq!(
3006            Annotated::annotation(&p, "tatara.pleme.io/pool"),
3007            Some("demo-pool"),
3008        );
3009    }
3010
3011    #[test]
3012    fn annotation_on_ephemeral_allocation_present_key_returns_borrowed_slice_via_trait() {
3013        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
3014        a.metadata.annotations = Some(one_annotation(
3015            "tatara.pleme.io/requestor-kind",
3016            "github-pr",
3017        ));
3018        assert_eq!(
3019            Annotated::annotation(&a, "tatara.pleme.io/requestor-kind"),
3020            Some("github-pr"),
3021        );
3022    }
3023
3024    #[test]
3025    fn annotation_on_config_map_present_key_returns_borrowed_slice_via_trait() {
3026        // The exact receipts-owner filter shape from
3027        // `tatara-export-worker::main`: a ConfigMap carrying the
3028        // `tatara.pleme.io/process` annotation set to the qualified
3029        // process reference `<ns>/<name>`. Pin that the trait produces
3030        // the exact borrowed slice the equality comparison against the
3031        // caller's `want.as_str()` sentinel consumes.
3032        let mut cm = ConfigMap::default();
3033        cm.metadata.annotations = Some(one_annotation(
3034            "tatara.pleme.io/process",
3035            "demo-ns/demo-app",
3036        ));
3037        assert_eq!(
3038            Annotated::annotation(&cm, "tatara.pleme.io/process"),
3039            Some("demo-ns/demo-app"),
3040        );
3041    }
3042
3043    // ── Empty-value contract: `Some("")` — the pre-lift chain never
3044    //    swallowed empty values into `None`, so the trait must not
3045    //    either. Pinned separately from the missing-slot corners.
3046
3047    #[test]
3048    fn annotation_present_key_with_empty_value_returns_some_empty_slice_via_trait() {
3049        let mut p = Process::new("api", empty_process_spec());
3050        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", ""));
3051        assert_eq!(
3052            Annotated::annotation(&p, "tatara.pleme.io/signal"),
3053            Some("")
3054        );
3055    }
3056
3057    // ── Byte-identical parity with the pre-lift 3-line chain ──────────
3058
3059    #[test]
3060    fn annotation_matches_pre_lift_annotations_lookup_chain_on_config_map() {
3061        // The four-corner input matrix the pre-lift
3062        // `cm.metadata.annotations.as_ref().and_then(|m| m.get(KEY))
3063        // .map(String::as_str)` chain traversed in
3064        // `tatara-export-worker::main` pre-lift. A regression that
3065        // inserted a normalization step the pre-lift chain does NOT
3066        // apply — or vice versa — surfaces here rather than as silent
3067        // drift between the substrate owner and the pre-lift consumer.
3068        const KEY: &str = "tatara.pleme.io/process";
3069        let cases: Vec<(Option<BTreeMap<String, String>>, Option<&str>)> = vec![
3070            (None, None),
3071            (Some(BTreeMap::new()), None),
3072            (Some(one_annotation("unrelated", "yes")), None),
3073            (
3074                Some(one_annotation(KEY, "demo-ns/demo-app")),
3075                Some("demo-ns/demo-app"),
3076            ),
3077            (Some(one_annotation(KEY, "")), Some("")),
3078        ];
3079        for (anns, expected) in cases {
3080            let mut cm = ConfigMap::default();
3081            cm.metadata.annotations = anns.clone();
3082
3083            let pre_lift: Option<&str> = cm
3084                .metadata
3085                .annotations
3086                .as_ref()
3087                .and_then(|m| m.get(KEY))
3088                .map(String::as_str);
3089            let via_trait = Annotated::annotation(&cm, KEY);
3090
3091            assert_eq!(
3092                pre_lift, expected,
3093                "pre-lift chain must return {expected:?} for annotations={anns:?}",
3094            );
3095            assert_eq!(
3096                via_trait, pre_lift,
3097                "trait probe must be byte-identical to pre-lift chain for annotations={anns:?}",
3098            );
3099        }
3100    }
3101
3102    // ── Cross-primitive coherence with Process's inherent forwarder ───
3103
3104    #[test]
3105    fn trait_probe_coheres_with_process_inherent_annotation_on_every_corner() {
3106        // Cross-primitive coherence pin: the trait's default and the
3107        // pre-existing `Process::annotation` inherent forwarder return
3108        // the SAME `Option<&str>` on the SAME `Process` value — a
3109        // future consolidation of the inherent onto the trait's
3110        // default cannot land any drift because this pin binds them
3111        // at every corner of the (absent, present-missing-key,
3112        // present-with-key, present-with-empty-value) input matrix.
3113        const KEY: &str = "tatara.pleme.io/signal";
3114        let cases: Vec<Option<BTreeMap<String, String>>> = vec![
3115            None,
3116            Some(BTreeMap::new()),
3117            Some(one_annotation("other/key", "irrelevant")),
3118            Some(one_annotation(KEY, "SIGHUP")),
3119            Some(one_annotation(KEY, "")),
3120        ];
3121        for anns in cases {
3122            let mut p = Process::new("api", empty_process_spec());
3123            p.metadata.annotations = anns.clone();
3124            let via_inherent = p.annotation(KEY);
3125            let via_trait = Annotated::annotation(&p, KEY);
3126            assert_eq!(
3127                via_inherent, via_trait,
3128                "Process inherent + Annotated trait must agree on annotations={anns:?}",
3129            );
3130        }
3131    }
3132
3133    // ── Inherent-preferred method resolution on Process ───────────────
3134
3135    #[test]
3136    fn dot_call_on_process_resolves_to_inherent_when_trait_in_scope() {
3137        // Rust method resolution prefers an inherent over a trait's
3138        // blanket impl, so `process.annotation(key)` with the trait in
3139        // scope still routes through the inherent — and both return
3140        // the same `Option<&str>` (verified in
3141        // `trait_probe_coheres_with_process_inherent_annotation_on_every_corner`).
3142        // This pin guards against a future refactor that removes the
3143        // inherent but leaves consumers assuming inherent-preferred
3144        // resolution — the observable output is identical either way,
3145        // so the pin locks the invariant that BOTH paths agree.
3146        let mut p = Process::new("api", empty_process_spec());
3147        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", "SIGHUP"));
3148        assert_eq!(p.annotation("tatara.pleme.io/signal"), Some("SIGHUP"));
3149    }
3150
3151    #[test]
3152    fn dot_call_on_ephemeral_allocation_resolves_to_trait_blanket_impl() {
3153        // The peer load-bearing corner: `alloc.annotation(key)` with
3154        // the trait in scope routes to the trait's blanket impl —
3155        // there is no inherent on `EphemeralAllocation` — and produces
3156        // the expected `Option<&str>`. The same discipline the sibling
3157        // `DeletionTombstoned` trait already established on the
3158        // tombstone axis for the SAME third CRD.
3159        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
3160        assert_eq!(a.annotation("tatara.pleme.io/requestor-kind"), None);
3161        a.metadata.annotations = Some(one_annotation(
3162            "tatara.pleme.io/requestor-kind",
3163            "github-pr",
3164        ));
3165        assert_eq!(
3166            a.annotation("tatara.pleme.io/requestor-kind"),
3167            Some("github-pr"),
3168        );
3169    }
3170
3171    #[test]
3172    fn dot_call_on_config_map_resolves_to_trait_blanket_impl() {
3173        // The load-bearing corner the export-worker's post-lift call
3174        // exercises: `cm.annotation(KEY)` with the trait in scope
3175        // routes to the blanket impl (ConfigMap is a K8s built-in
3176        // with no tatara-owned inherent) and produces the same
3177        // `Option<&str>` the pre-lift 3-line chain did.
3178        let mut cm = ConfigMap::default();
3179        assert_eq!(cm.annotation("tatara.pleme.io/process"), None);
3180        cm.metadata.annotations = Some(one_annotation(
3181            "tatara.pleme.io/process",
3182            "demo-ns/demo-app",
3183        ));
3184        assert_eq!(
3185            cm.annotation("tatara.pleme.io/process"),
3186            Some("demo-ns/demo-app"),
3187        );
3188    }
3189}
3190
3191#[cfg(test)]
3192mod annotations_pins {
3193    //! Pin the three newly-lifted allocator-bind annotation keys
3194    //! ([`crate::annotations::REQUESTOR`],
3195    //! [`crate::annotations::ALLOCATION`],
3196    //! [`crate::annotations::REQUESTOR_KIND`]) at their canonical
3197    //! wire-form byte-values, and pin the coherence between each
3198    //! constant and the pre-lift string literal the sibling writer +
3199    //! reader test-sites still spell verbatim.
3200    //!
3201    //! Pre-lift each of the three keys was a bare `"tatara.pleme.io/…"`
3202    //! string literal at both the writer (`tatara-pool-reconciler::
3203    //! controller_allocation::reconcile_inner`'s Bind arm) AND the
3204    //! reader-side test sites in `annotated_tests` above — six
3205    //! restatements of `REQUESTOR_KIND` alone past the ★★
3206    //! PRIME-DIRECTIVE ≥ 2 duplication threshold. Post-lift the writer
3207    //! keys on the substrate constant; these pins bind the constant's
3208    //! byte-shape so a future edit that drifted the constant (a
3209    //! typo'd suffix, an accidental `tatara.pleme.io/v2/…` migration
3210    //! landing at only the writer, an incoming rename that swapped
3211    //! two of the three keys) surfaces here rather than as silent
3212    //! operator-facing skew between the writer and the tatara-process
3213    //! reader tests that still spell the literal.
3214    //!
3215    //! Theory anchor: THEORY.md §II.1 invariant 5 (composition
3216    //! preserves proofs — the wire-form value each downstream reader
3217    //! depends on now has a compile-time pin at the substrate).
3218    use crate::annotations;
3219
3220    #[test]
3221    fn requestor_matches_pre_lift_wire_string() {
3222        assert_eq!(annotations::REQUESTOR, "tatara.pleme.io/requestor");
3223    }
3224
3225    #[test]
3226    fn allocation_matches_pre_lift_wire_string() {
3227        assert_eq!(annotations::ALLOCATION, "tatara.pleme.io/allocation");
3228    }
3229
3230    #[test]
3231    fn requestor_kind_matches_pre_lift_wire_string() {
3232        assert_eq!(
3233            annotations::REQUESTOR_KIND,
3234            "tatara.pleme.io/requestor-kind",
3235        );
3236    }
3237
3238    #[test]
3239    fn allocator_bind_axis_keys_are_distinct() {
3240        // A copy-paste that duplicated one key's value across two
3241        // slots (an oversight during the initial lift or a future
3242        // rename that merged two keys by mistake) collapses BOTH
3243        // downstream readers onto the same wire string and silently
3244        // loses one of the three axes. Pin the closed set is
3245        // partition-distinct.
3246        assert_ne!(annotations::REQUESTOR, annotations::ALLOCATION);
3247        assert_ne!(annotations::REQUESTOR, annotations::REQUESTOR_KIND);
3248        assert_ne!(annotations::ALLOCATION, annotations::REQUESTOR_KIND);
3249    }
3250
3251    #[test]
3252    fn allocator_bind_axis_keys_share_tatara_namespace() {
3253        // Every substrate-owned annotation key inhabits the
3254        // `tatara.pleme.io/` reverse-DNS namespace; a future rename
3255        // that dropped the prefix (a bare `"requestor"` key, a
3256        // typo'd `pleme.io/requestor`) would collide with an
3257        // arbitrary third-party operator's annotations on the same
3258        // Process and silently corrupt cross-consumer reads.
3259        for key in [
3260            annotations::REQUESTOR,
3261            annotations::ALLOCATION,
3262            annotations::REQUESTOR_KIND,
3263        ] {
3264            assert!(
3265                key.starts_with("tatara.pleme.io/"),
3266                "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
3267            );
3268        }
3269    }
3270
3271    // ── Pool-membership axis pins ────────────────────────────────────
3272    //
3273    // Pins the two newly-lifted pool-membership annotation keys
3274    // ([`crate::annotations::POOL`], [`crate::annotations::POOL_SLOT`])
3275    // at their canonical wire-form byte-values. Pre-lift each key was
3276    // a file-scope `const ANNOTATION_POOL / ANNOTATION_SLOT` in
3277    // `tatara-pool-reconciler::controller_pool` PLUS bare
3278    // `"tatara.pleme.io/pool"` string literals at four reader-side
3279    // test sites in this crate (in the sibling `annotated_tests` above
3280    // and in `crd.rs`'s
3281    // `annotation_composes_borrow_equality_tail_matching_pre_lift_pool`
3282    // + `annotation_returns_none_when_metadata_annotations_is_none`).
3283    // Post-lift the writer routes through the substrate constant; a
3284    // future edit that drifted the constant (a typo'd suffix, an
3285    // accidental `tatara.pleme.io/v2/pool` migration landing at only
3286    // the writer, an incoming rename that swapped POOL and POOL_SLOT)
3287    // surfaces here rather than as silent operator-facing skew
3288    // between the pool controller's writer and its own membership-
3289    // gate reader.
3290
3291    #[test]
3292    fn pool_matches_pre_lift_wire_string() {
3293        assert_eq!(annotations::POOL, "tatara.pleme.io/pool");
3294    }
3295
3296    #[test]
3297    fn pool_slot_matches_pre_lift_wire_string() {
3298        assert_eq!(annotations::POOL_SLOT, "tatara.pleme.io/pool-slot");
3299    }
3300
3301    #[test]
3302    fn pool_membership_axis_keys_are_distinct() {
3303        // A copy-paste that duplicated one key's value across both
3304        // slots (an oversight during the initial lift, or a future
3305        // rename that merged the two keys by mistake) collapses
3306        // BOTH downstream readers onto the same wire string and
3307        // silently loses the slot-index axis — the pool controller
3308        // would still find its own members via POOL but every per-
3309        // slot dispatch consumer would read the pool name where the
3310        // slot index used to sit. Pin the closed set is partition-
3311        // distinct.
3312        assert_ne!(annotations::POOL, annotations::POOL_SLOT);
3313    }
3314
3315    #[test]
3316    fn pool_membership_axis_keys_share_tatara_namespace() {
3317        // Same reverse-DNS namespace invariant the allocator-bind
3318        // axis-family enforces above — a rename that dropped the
3319        // prefix on either POOL or POOL_SLOT would collide with an
3320        // arbitrary third-party operator's annotations on the same
3321        // Process and silently corrupt every pool-membership read.
3322        for key in [annotations::POOL, annotations::POOL_SLOT] {
3323            assert!(
3324                key.starts_with("tatara.pleme.io/"),
3325                "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
3326            );
3327        }
3328    }
3329
3330    #[test]
3331    fn pool_membership_axis_keys_partition_distinct_from_allocator_bind_axis() {
3332        // Cross-family distinctness pin — the pool-membership axis
3333        // (POOL, POOL_SLOT) and the allocator-bind axis (REQUESTOR,
3334        // ALLOCATION, REQUESTOR_KIND) travel on the SAME member
3335        // Process at the SAME time (the pool controller writes POOL
3336        // + POOL_SLOT at creation; the allocator later merges
3337        // REQUESTOR / ALLOCATION / REQUESTOR_KIND onto the same
3338        // Process at Bind). A copy-paste that collapsed any axis
3339        // pair (e.g. POOL and REQUESTOR onto the same wire string)
3340        // would let one write silently overwrite the other. Pin
3341        // that every substrate-owned annotation key is unique
3342        // across the two axis-families.
3343        let pool_axis = [annotations::POOL, annotations::POOL_SLOT];
3344        let bind_axis = [
3345            annotations::REQUESTOR,
3346            annotations::ALLOCATION,
3347            annotations::REQUESTOR_KIND,
3348        ];
3349        for p in pool_axis {
3350            for b in bind_axis {
3351                assert_ne!(
3352                    p, b,
3353                    "pool-membership key {p:?} collides with allocator-bind key {b:?}",
3354                );
3355            }
3356        }
3357    }
3358
3359    // ── Release-return axis pins ─────────────────────────────────────
3360    //
3361    // Pins the newly-lifted release-return annotation key
3362    // ([`crate::annotations::RETURN_TRIGGER`]) at its canonical
3363    // wire-form byte-value. Pre-lift the key was a bare
3364    // `"tatara.pleme.io/return-trigger"` string literal at the
3365    // pool-reconciler's Release-arm stamp (`tatara-pool-reconciler::
3366    // controller_allocation::reconcile_inner`) — the ONE remaining
3367    // hand-authored annotation-key literal in the workspace's active
3368    // controllers after every sibling single-annotation key on the
3369    // same axis-family (`SIGNAL`, `RELEASED_FROM`, `POOL`, `POOL_SLOT`,
3370    // `REQUESTOR`, `ALLOCATION`, `REQUESTOR_KIND`) already routed
3371    // through a `pub const` in the substrate. Post-lift the writer
3372    // routes through the substrate constant; these pins bind the
3373    // constant's byte-shape + tatara-namespace membership + partition-
3374    // distinctness against every peer key so a future edit that
3375    // drifted the constant (a typo'd suffix, an incoming rename that
3376    // collapsed RETURN_TRIGGER onto a peer key, a `tatara.pleme.io/v2/
3377    // return-trigger` migration landing at only the writer) surfaces
3378    // HERE rather than as silent operator-facing skew between the
3379    // allocator's Release-arm stamp and every downstream reader (an
3380    // audit-trail scraper, a future pool-reconciler return-path arm,
3381    // an admission-webhook gate on the return trigger).
3382
3383    #[test]
3384    fn return_trigger_matches_pre_lift_wire_string() {
3385        assert_eq!(
3386            annotations::RETURN_TRIGGER,
3387            "tatara.pleme.io/return-trigger",
3388        );
3389    }
3390
3391    #[test]
3392    fn return_trigger_inhabits_tatara_namespace() {
3393        // Same reverse-DNS namespace invariant every sibling key on
3394        // the axis-family enforces above — a rename that dropped the
3395        // prefix on RETURN_TRIGGER would collide with an arbitrary
3396        // third-party operator's annotations on the same Process and
3397        // silently corrupt the allocator's Release-arm write.
3398        assert!(
3399            annotations::RETURN_TRIGGER.starts_with("tatara.pleme.io/"),
3400            "annotation key {:?} must inhabit tatara.pleme.io/ namespace",
3401            annotations::RETURN_TRIGGER,
3402        );
3403    }
3404
3405    #[test]
3406    fn return_trigger_is_distinct_from_every_peer_annotation_key() {
3407        // Cross-family distinctness pin — RETURN_TRIGGER travels on
3408        // the SAME member Process (at Release) that already carries
3409        // the pool-membership axis (POOL, POOL_SLOT, stamped at
3410        // creation), the allocator-bind axis (REQUESTOR, ALLOCATION,
3411        // REQUESTOR_KIND, stamped at Bind), and the
3412        // "single-annotation trigger for the next reconcile pass"
3413        // axis-family (SIGNAL, RELEASED_FROM). A copy-paste that
3414        // collapsed RETURN_TRIGGER onto any peer would let one write
3415        // silently overwrite the other. Pin the key against every
3416        // sibling substrate-owned annotation key on the workspace.
3417        for peer in [
3418            annotations::SIGNAL,
3419            annotations::RELEASED_FROM,
3420            annotations::POOL,
3421            annotations::POOL_SLOT,
3422            annotations::REQUESTOR,
3423            annotations::ALLOCATION,
3424            annotations::REQUESTOR_KIND,
3425            annotations::MANAGED_BY,
3426            annotations::PROCESS,
3427            annotations::PID,
3428            annotations::CONTENT_HASH,
3429            annotations::ATTESTATION_ROOT,
3430            annotations::GENERATION,
3431            annotations::ROLE,
3432            annotations::EXPORT_INDEX,
3433            annotations::APP,
3434            annotations::ROUTING_FORM,
3435        ] {
3436            assert_ne!(
3437                annotations::RETURN_TRIGGER,
3438                peer,
3439                "RETURN_TRIGGER key {:?} collides with peer annotation key {peer:?}",
3440                annotations::RETURN_TRIGGER,
3441            );
3442        }
3443    }
3444
3445    #[test]
3446    fn return_trigger_composes_at_annotation_body_key_slot() {
3447        // End-to-end composability pin: the substrate composer
3448        // [`crate::patch::annotation_body`] takes a `key: &str`; the
3449        // pre-lift Release-arm callsite fed a bare `"tatara.pleme.io/
3450        // return-trigger"` literal and the post-lift callsite feeds
3451        // `annotations::RETURN_TRIGGER`. Both shapes produce a JSON
3452        // merge-body whose `metadata.annotations.<KEY>` slot equals
3453        // `"true"`; pin that the substrate constant threads through
3454        // the composer verbatim so a regression that reshaped the
3455        // `annotation_body` key-slot (a case-fold pass, an unexpected
3456        // trim, a prefix-normalization step) surfaces HERE rather
3457        // than at every downstream consumer.
3458        let body = crate::patch::annotation_body(annotations::RETURN_TRIGGER, "true");
3459        assert_eq!(
3460            body["metadata"]["annotations"][annotations::RETURN_TRIGGER],
3461            "true",
3462            "annotation_body must stamp RETURN_TRIGGER verbatim at the metadata.annotations slot",
3463        );
3464        assert_eq!(
3465            body["metadata"]["annotations"]["tatara.pleme.io/return-trigger"],
3466            "true",
3467            "byte-shape parity — the pre-lift hand-authored key spelling routes through the constant to the same nested slot",
3468        );
3469    }
3470
3471    // ── Encapsulation-diagnostic axis pins ──────────────────────────
3472    //
3473    // Pins the two newly-lifted encapsulation-diagnostic annotation
3474    // keys ([`crate::annotations::ENCAPSULATION_MODE`],
3475    // [`crate::annotations::ADOPTED_RELEASE`]) at their canonical
3476    // wire-form byte-values. Pre-lift the two keys were bare
3477    // `"tatara.pleme.io/encapsulation-mode"` /
3478    // `"tatara.pleme.io/adopted-release"` string literals inline at
3479    // `tatara-reconciler::render::mark_resources_as_adopting`'s two
3480    // `anns_obj.insert_str(...)` writer sites — the ONE remaining
3481    // hand-authored annotation-key pair in the workspace's active
3482    // reconciler after every sibling annotation key already routed
3483    // through a `pub const` in the substrate. Post-lift the writer
3484    // routes through the substrate constants; these pins bind each
3485    // constant's byte-shape + tatara-namespace membership + partition-
3486    // distinctness against every peer key so a future edit that
3487    // drifted the constants (a typo'd suffix, an incoming rename that
3488    // collapsed the pair onto a peer key, a
3489    // `tatara.pleme.io/v2/encapsulation-mode` migration landing at
3490    // only the writer, a collapse into a compound
3491    // `tatara.pleme.io/encapsulation` payload key) surfaces HERE
3492    // rather than as silent operator-facing skew between the render
3493    // emitter and every downstream reader (an operator dashboard
3494    // filtering adopted resources, an admission-webhook gate on the
3495    // encapsulation mode, an audit-trail scraper following the
3496    // `<ns>/<release>` adoption lineage).
3497
3498    #[test]
3499    fn encapsulation_mode_matches_pre_lift_wire_string() {
3500        assert_eq!(
3501            annotations::ENCAPSULATION_MODE,
3502            "tatara.pleme.io/encapsulation-mode",
3503        );
3504    }
3505
3506    #[test]
3507    fn adopted_release_matches_pre_lift_wire_string() {
3508        assert_eq!(
3509            annotations::ADOPTED_RELEASE,
3510            "tatara.pleme.io/adopted-release",
3511        );
3512    }
3513
3514    #[test]
3515    fn encapsulation_diagnostic_axis_keys_are_distinct() {
3516        // A copy-paste that duplicated one key's value across the pair
3517        // (an oversight during the initial lift, or a future rename
3518        // that merged the two keys by mistake) collapses BOTH
3519        // downstream readers onto the same wire string and silently
3520        // loses one of the two axes — an operator dashboard would
3521        // still see the mode via ENCAPSULATION_MODE but every
3522        // `<ns>/<release>` back-reference consumer would read the
3523        // mode literal where the qualified reference used to sit.
3524        // Pin the closed set is partition-distinct.
3525        assert_ne!(
3526            annotations::ENCAPSULATION_MODE,
3527            annotations::ADOPTED_RELEASE
3528        );
3529    }
3530
3531    #[test]
3532    fn encapsulation_diagnostic_axis_keys_share_tatara_namespace() {
3533        // Same reverse-DNS namespace invariant every sibling
3534        // annotation key on the workspace enforces above — a rename
3535        // that dropped the prefix on either constant would collide
3536        // with an arbitrary third-party operator's annotations on the
3537        // same emitted resource (a HelmRelease, a Kustomization, an
3538        // adopted secondary) and silently corrupt every
3539        // encapsulation-diagnostic read.
3540        for key in [
3541            annotations::ENCAPSULATION_MODE,
3542            annotations::ADOPTED_RELEASE,
3543        ] {
3544            assert!(
3545                key.starts_with("tatara.pleme.io/"),
3546                "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
3547            );
3548        }
3549    }
3550
3551    #[test]
3552    fn encapsulation_diagnostic_axis_keys_partition_distinct_from_every_peer() {
3553        // Cross-family distinctness pin — the encapsulation-diagnostic
3554        // axis (ENCAPSULATION_MODE, ADOPTED_RELEASE) is stamped on
3555        // every RESOURCE the reconciler emits for an Adopt-mode
3556        // Process, whereas every peer annotation key on the workspace
3557        // is stamped on the PROCESS itself (SIGNAL, RELEASED_FROM,
3558        // POOL, POOL_SLOT, REQUESTOR, ALLOCATION, REQUESTOR_KIND,
3559        // RETURN_TRIGGER) OR on emitted routing edges (APP,
3560        // ROUTING_FORM) OR on export-worker Jobs (ROLE, EXPORT_INDEX).
3561        // A copy-paste that collapsed the pair onto any peer would
3562        // let one write silently overwrite the other. Pin that both
3563        // constants are unique across every substrate-owned peer.
3564        let diag_axis = [
3565            annotations::ENCAPSULATION_MODE,
3566            annotations::ADOPTED_RELEASE,
3567        ];
3568        let peers = [
3569            annotations::MANAGED_BY,
3570            annotations::PROCESS,
3571            annotations::PID,
3572            annotations::CONTENT_HASH,
3573            annotations::ATTESTATION_ROOT,
3574            annotations::GENERATION,
3575            annotations::SIGNAL,
3576            annotations::RELEASED_FROM,
3577            annotations::ROLE,
3578            annotations::EXPORT_INDEX,
3579            annotations::APP,
3580            annotations::ROUTING_FORM,
3581            annotations::REQUESTOR,
3582            annotations::ALLOCATION,
3583            annotations::REQUESTOR_KIND,
3584            annotations::POOL,
3585            annotations::POOL_SLOT,
3586            annotations::RETURN_TRIGGER,
3587        ];
3588        for d in diag_axis {
3589            for p in peers {
3590                assert_ne!(
3591                    d, p,
3592                    "encapsulation-diagnostic key {d:?} collides with peer annotation key {p:?}",
3593                );
3594            }
3595        }
3596    }
3597
3598    // ── Receipt-CM-label axis pins ──────────────────────────────────
3599    //
3600    // Pins the newly-lifted receipt-CM label KEY
3601    // ([`crate::annotations::RECEIPT`]) at its canonical wire-form
3602    // byte-value. Pre-lift the key was a bare
3603    // `"tatara.pleme.io/receipt"` string literal inline at
3604    // `tatara-closed-loop-probe::write_receipt_cm`'s
3605    // `BTreeMap::from([...])` label seed AND at the byte-shape parity
3606    // witness in `tatara_process::configmap::with_data`'s
3607    // `with_data_preserves_passed_labels_map_verbatim_when_some` test —
3608    // TWO restatements past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
3609    // threshold. Post-lift both callsites route through the substrate
3610    // constant; these pins bind the constant's byte-shape +
3611    // tatara-namespace membership + partition-distinctness against
3612    // every peer key so a future edit that drifted the constant (a
3613    // typo'd suffix, an incoming rename that collapsed RECEIPT onto a
3614    // peer key, a `tatara.pleme.io/v2/receipt` migration landing at
3615    // only the writer, a collapse into a compound
3616    // `tatara.pleme.io/receipt-envelope` payload key) surfaces HERE
3617    // rather than as silent operator-facing kubectl-selector skew
3618    // between the probe's receipt-CM writer and every downstream
3619    // consumer (a receipt-collection walker, an admission-webhook gate
3620    // on receipt version, an audit-trail scraper enumerating every
3621    // `tatara-receipt/v1` payload on a cluster).
3622
3623    #[test]
3624    fn receipt_matches_pre_lift_wire_string() {
3625        assert_eq!(annotations::RECEIPT, "tatara.pleme.io/receipt");
3626    }
3627
3628    #[test]
3629    fn receipt_inhabits_tatara_namespace() {
3630        // Same reverse-DNS namespace invariant every sibling key on
3631        // the workspace enforces above — a rename that dropped the
3632        // prefix on RECEIPT would collide with an arbitrary
3633        // third-party operator's labels on the same ConfigMap and
3634        // silently corrupt every downstream kubectl-selector that
3635        // enumerates receipt CMs of a given version on a cluster.
3636        assert!(
3637            annotations::RECEIPT.starts_with(annotations::GROUP_PREFIX),
3638            "annotation key {:?} must inhabit {:?} namespace",
3639            annotations::RECEIPT,
3640            annotations::GROUP_PREFIX,
3641        );
3642    }
3643
3644    #[test]
3645    fn receipt_is_distinct_from_every_peer_annotation_key() {
3646        // Cross-family distinctness pin — RECEIPT rides on the
3647        // receipt ConfigMap the probe binary writes (a peer resource
3648        // of the Process itself), whereas every peer annotation key on
3649        // the workspace is stamped on the PROCESS (SIGNAL,
3650        // RELEASED_FROM, POOL, POOL_SLOT, REQUESTOR, ALLOCATION,
3651        // REQUESTOR_KIND, RETURN_TRIGGER) OR on emitted routing edges
3652        // (APP, ROUTING_FORM) OR on export-worker Jobs (ROLE,
3653        // EXPORT_INDEX) OR on encapsulation-diagnostic side-resources
3654        // (ENCAPSULATION_MODE, ADOPTED_RELEASE). A copy-paste that
3655        // collapsed RECEIPT onto any peer would let one write silently
3656        // overwrite the other. Pin the key against every sibling
3657        // substrate-owned annotation key on the workspace.
3658        for peer in [
3659            annotations::MANAGED_BY,
3660            annotations::PROCESS,
3661            annotations::PID,
3662            annotations::CONTENT_HASH,
3663            annotations::ATTESTATION_ROOT,
3664            annotations::GENERATION,
3665            annotations::SIGNAL,
3666            annotations::RELEASED_FROM,
3667            annotations::ROLE,
3668            annotations::EXPORT_INDEX,
3669            annotations::APP,
3670            annotations::ROUTING_FORM,
3671            annotations::REQUESTOR,
3672            annotations::ALLOCATION,
3673            annotations::REQUESTOR_KIND,
3674            annotations::POOL,
3675            annotations::POOL_SLOT,
3676            annotations::RETURN_TRIGGER,
3677            annotations::ENCAPSULATION_MODE,
3678            annotations::ADOPTED_RELEASE,
3679        ] {
3680            assert_ne!(
3681                annotations::RECEIPT,
3682                peer,
3683                "RECEIPT key {:?} collides with peer annotation key {peer:?}",
3684                annotations::RECEIPT,
3685            );
3686        }
3687    }
3688
3689    #[test]
3690    fn receipt_value_slot_routes_through_receipt_version_const() {
3691        // Value-side coherence pin — the SUBSTRATE convention is that
3692        // every ConfigMap labeled `RECEIPT` carries a payload whose
3693        // envelope `version` slot equals [`crate::receipt::RECEIPT_VERSION`],
3694        // so a kubectl `-l tatara.pleme.io/receipt=tatara-receipt/v1`
3695        // selector matches exactly the CMs whose payloads pass the
3696        // `RECEIPT_VERSION` gate. Pin that the label VALUE the probe
3697        // stamps IS `RECEIPT_VERSION` (routed through the const, not a
3698        // parallel `"tatara-receipt/v1"` literal): a future bump to
3699        // `tatara-receipt/v2` at the version const propagates
3700        // MECHANICALLY to the label value without touching any writer.
3701        assert_eq!(
3702            crate::receipt::RECEIPT_VERSION,
3703            "tatara-receipt/v1",
3704            "RECEIPT_VERSION wire-form pin — a bump surfaces here",
3705        );
3706    }
3707
3708    #[test]
3709    fn encapsulation_mode_value_slot_routes_through_encapsulation_mode_closed_set() {
3710        // Value-side pin — the render emitter's `ENCAPSULATION_MODE`
3711        // slot writes the wire-form spelling of an
3712        // [`crate::encapsulates::EncapsulationMode`] variant. Pre-lift
3713        // the site hand-authored the fixed `"Adopt"` literal;
3714        // post-lift the writer feeds
3715        // `EncapsulationMode::Adopt.as_str()` — the SAME closed-set
3716        // owner every peer consumer (the reconciler's status-condition
3717        // reason string, the operator dashboard's per-mode filter, the
3718        // admission webhook's Adopt/Manage/Observe dispatch) routes
3719        // through. A regression that drifted the closed-set wire form
3720        // (a lowercase `"adopt"`, a `"Adoption"` typo) surfaces at
3721        // `EncapsulationMode::as_str`'s own pin AND here at the value
3722        // slot the render emitter stamps.
3723        assert_eq!(
3724            crate::encapsulates::EncapsulationMode::Adopt.as_str(),
3725            "Adopt",
3726            "the render emitter's ENCAPSULATION_MODE value slot must byte-match the closed-set wire form",
3727        );
3728    }
3729}
3730
3731// ── Lisp → ProcessSpec compile bridge ──────────────────────────────────
3732//
3733// `(defpoint NAME :k v …)` compiles to a `NamedDefinition<ProcessSpec>`.
3734// The derive on ProcessSpec handles every field via the serde Deserialize
3735// fallthrough — no hand-rolled keyword parsing needed.
3736
3737/// A named ProcessSpec as produced by `compile_source`.
3738pub type Definition = tatara_lisp::NamedDefinition<crate::crd::ProcessSpec>;
3739
3740/// Compile a Lisp source string into a list of named ProcessSpecs.
3741/// Each top-level `(defpoint NAME …)` form becomes one `Definition`.
3742pub fn compile_source(src: &str) -> tatara_lisp::Result<Vec<Definition>> {
3743    tatara_lisp::compile_named::<crate::crd::ProcessSpec>(src)
3744}
3745
3746/// Register every domain owned by this crate with the global Lisp
3747/// dispatcher. Call once per binary, typically near the top of `main`.
3748/// After this call, `tatara_lisp::domain::lookup("defpoint")` and
3749/// `lookup("defephemeral")` both resolve to the right typed compiler.
3750///
3751/// Idempotent — registering the same type twice is a no-op.
3752pub fn register_all() {
3753    tatara_lisp::domain::register::<crate::crd::ProcessSpec>();
3754    tatara_lisp::domain::register::<crate::ephemeral::EphemeralSpec>();
3755}
3756
3757#[cfg(test)]
3758mod compile_tests {
3759    use super::compile_source;
3760    use crate::classification::{ConvergencePointType, SubstrateType};
3761    use crate::compliance::VerificationPhase;
3762    use crate::spec::MustReachPhase;
3763
3764    /// The full derive-powered pipeline — no hand-rolled parsing anywhere.
3765    /// Every field travels: Lisp → Sexp → serde_json → typed ProcessSpec.
3766    #[test]
3767    fn full_processspec_round_trip_via_derive() {
3768        let src = r#"
3769            (defpoint observability-stack
3770              :identity       (:parent "seph.1")
3771              :classification (:point-type Gate
3772                               :substrate Observability
3773                               :horizon (:kind Bounded)
3774                               :calm Monotone
3775                               :data-classification Internal)
3776              :intent         (:nix (:flake-ref "github:pleme-io/k8s"
3777                                     :attribute "observability"
3778                                     :attic-cache "main"))
3779              :boundary       (:postconditions
3780                                 ((:kind KustomizationHealthy
3781                                   :params (:name "observability-stack"
3782                                            :namespace "flux-system"))
3783                                  (:kind PromQL
3784                                   :params (:query "up == 1")))
3785                               :timeout "15m")
3786              :compliance     (:baseline "fedramp-moderate"
3787                               :bindings ((:framework "nist-800-53"
3788                                           :control-id "SC-7"
3789                                           :phase AtBoundary)))
3790              :depends-on     ((:name "secret-injection" :must-reach Attested))
3791              :signals        (:sigterm-grace-seconds 480
3792                               :sighup-strategy Reconverge))
3793        "#;
3794        let defs = compile_source(src).expect("compile");
3795        assert_eq!(defs.len(), 1);
3796        let d = &defs[0];
3797        assert_eq!(d.name, "observability-stack");
3798
3799        // identity
3800        assert_eq!(d.spec.identity.parent.as_deref(), Some("seph.1"));
3801
3802        // classification (enums deserialized via symbol → string)
3803        assert_eq!(d.spec.classification.point_type, ConvergencePointType::Gate);
3804        assert_eq!(
3805            d.spec.classification.substrate,
3806            SubstrateType::Observability
3807        );
3808
3809        // intent (tagged-union with one of four options)
3810        let nix = d.spec.intent.nix.as_ref().expect("nix intent");
3811        assert_eq!(nix.flake_ref, "github:pleme-io/k8s");
3812        assert_eq!(nix.attribute, "observability");
3813        assert_eq!(nix.attic_cache.as_deref(), Some("main"));
3814
3815        // boundary (Vec<nested struct with params object>)
3816        assert_eq!(d.spec.boundary.postconditions.len(), 2);
3817        assert_eq!(d.spec.boundary.timeout.as_deref(), Some("15m"));
3818
3819        // compliance (Vec<binding with enum phase>)
3820        assert_eq!(
3821            d.spec.compliance.baseline.as_deref(),
3822            Some("fedramp-moderate")
3823        );
3824        assert_eq!(d.spec.compliance.bindings.len(), 1);
3825        assert_eq!(
3826            d.spec.compliance.bindings[0].phase,
3827            VerificationPhase::AtBoundary
3828        );
3829
3830        // depends_on (Vec<struct with enum>)
3831        assert_eq!(d.spec.depends_on.len(), 1);
3832        assert_eq!(d.spec.depends_on[0].must_reach, MustReachPhase::Attested);
3833
3834        // signals (numeric + enum defaults)
3835        assert_eq!(d.spec.signals.sigterm_grace_seconds, 480);
3836    }
3837
3838    #[test]
3839    fn missing_required_field_errors() {
3840        // `:classification` has no #[serde(default)] — omit it and compile must fail.
3841        let src = r#"(defpoint x :intent (:nix (:flake-ref "f" :attribute "a")))"#;
3842        assert!(compile_source(src).is_err());
3843    }
3844
3845    #[test]
3846    fn serde_default_fields_are_optional() {
3847        // Omit every #[serde(default)] field — compile must succeed because
3848        // the derive honors serde defaults.
3849        let src = r#"
3850            (defpoint x
3851              :classification (:point-type Transform :substrate Compute)
3852              :intent (:flux (:git-repository "g" :path ".")))
3853        "#;
3854        let defs = compile_source(src).expect("compile");
3855        assert_eq!(defs.len(), 1);
3856        let d = &defs[0];
3857        assert!(d.spec.depends_on.is_empty());
3858        assert!(d.spec.boundary.postconditions.is_empty());
3859        assert!(d.spec.compliance.bindings.is_empty());
3860        assert!(!d.spec.suspended);
3861        // Lifetime defaults to Permanent (no variant set, resolver still works).
3862        assert!(d.spec.lifetime.is_default());
3863        assert!(!d.spec.lifetime.is_ephemeral());
3864    }
3865
3866    /// Registering all process-owned domains is idempotent and resolves
3867    /// both `defpoint` (ProcessSpec) and `defephemeral` (EphemeralSpec).
3868    #[test]
3869    fn register_all_resolves_defpoint_and_defephemeral() {
3870        use tatara_lisp::domain::lookup;
3871        super::register_all();
3872        super::register_all(); // idempotent
3873        assert!(lookup("defpoint").is_some(), "defpoint must resolve");
3874        assert!(
3875            lookup("defephemeral").is_some(),
3876            "defephemeral must resolve"
3877        );
3878    }
3879
3880    /// End-to-end: a `(defpoint …)` form may carry the full ephemeral
3881    /// shape directly — `:intent (:aplicacao …)` + `:lifetime (:ephemeral …)`.
3882    /// This is what the `(defephemeral …)` sugar lowers to via `From`.
3883    #[test]
3884    fn defpoint_with_aplicacao_intent_and_ephemeral_lifetime() {
3885        use crate::intent::IntentVariant;
3886        use crate::lifetime::{LifetimeVariant, TeardownPolicy};
3887        let src = r#"
3888            (defpoint closed-loop-attest
3889              :classification (:point-type Gate :substrate Compute)
3890              :intent (:aplicacao
3891                        (:chart-ref "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
3892                         :version "0.5.5"
3893                         :profile "all-in-one"
3894                         :values-overlay (:cluster (:name "ephemeral-test-01"))
3895                         :target-namespace "demo-test"))
3896              :boundary (:postconditions
3897                          ((:kind HelmReleaseReleased
3898                            :params (:name "demo-app-consolidated"
3899                                     :namespace "demo-test"))
3900                           (:kind ClosedLoopAuth
3901                            :params (:issuer (:service "demo-app-issuer" :port 8080)
3902                                     :consumer (:service "demo-app-gateway" :port 8000)
3903                                     :probeImage "ghcr.io/pleme-io/closed-loop-probe:0.1.0"))))
3904              :lifetime (:ephemeral (:ttl "1h"
3905                                     :teardown-policy OnAttested
3906                                     :max-concurrent 1)))
3907        "#;
3908        let defs = compile_source(src).expect("compile");
3909        assert_eq!(defs.len(), 1);
3910        let d = &defs[0];
3911
3912        // Aplicacao intent landed.
3913        match d.spec.intent.variant().unwrap() {
3914            IntentVariant::Aplicacao(a) => {
3915                assert_eq!(a.profile, "all-in-one");
3916                assert_eq!(a.version, "0.5.5");
3917                assert_eq!(a.target_namespace.as_deref(), Some("demo-test"));
3918                assert_eq!(a.values_overlay["cluster"]["name"], "ephemeral-test-01");
3919            }
3920            other => panic!("expected Aplicacao, got {other:?}"),
3921        }
3922
3923        // Ephemeral lifetime landed with the right teardown policy.
3924        match d.spec.lifetime.variant().unwrap() {
3925            LifetimeVariant::Ephemeral(e) => {
3926                assert_eq!(e.ttl, "1h");
3927                assert_eq!(e.teardown_policy, TeardownPolicy::OnAttested);
3928                assert_eq!(e.max_concurrent, 1);
3929            }
3930            other => panic!("expected ephemeral, got {other:?}"),
3931        }
3932
3933        // Two typed postconditions including ClosedLoopAuth.
3934        assert_eq!(d.spec.boundary.postconditions.len(), 2);
3935        assert_eq!(
3936            d.spec.boundary.postconditions[1].kind,
3937            crate::boundary::ConditionKind::ClosedLoopAuth
3938        );
3939    }
3940}
3941
3942#[cfg(test)]
3943mod placed_in_namespace_tests {
3944    //! Pin the [`PlacedInNamespace`] trait's `in_namespace` builder at
3945    //! fail-before-pass-after granularity across every corner of the
3946    //! (CRD ∈ {`Process`, `EphemeralPool`, `EphemeralAllocation`,
3947    //! `ConfigMap`}) × (input form ∈ {`&str`, `String`, `&String`})
3948    //! matrix — the three tatara-owned CRDs the trait's blanket impl
3949    //! covers today PLUS one K8s built-in (`ConfigMap`) whose sibling
3950    //! [`Annotated`] blanket already covers the same category on the
3951    //! annotation-read axis. Also pin (a) the overwrite corner where
3952    //! `.in_namespace(a).in_namespace(b)` binds `b`, so a future
3953    //! consumer that chains two stamps in one composition never sees
3954    //! stale semantics, and (b) the byte-identical parity corner with
3955    //! the pre-lift 3-line body of the per-CRD `EphemeralPool::new_in`
3956    //! and `EphemeralAllocation::new_in` composers post-forwarding —
3957    //! `<CRD>::new_in(name, ns, spec)` must yield a value structurally
3958    //! identical to `<CRD>::new(name, spec).in_namespace(ns)` on every
3959    //! metadata slot the derive stamps.
3960    use super::PlacedInNamespace;
3961    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
3962    use crate::crd::{Process, ProcessSpec};
3963    use crate::pool::{EphemeralPool, PoolSpec};
3964    use k8s_openapi::api::core::v1::ConfigMap;
3965    use kube::api::ObjectMeta;
3966
3967    fn empty_process_spec() -> ProcessSpec {
3968        ProcessSpec::gate_compute_defaults()
3969    }
3970
3971    fn empty_pool_spec() -> PoolSpec {
3972        PoolSpec {
3973            desired_size: 1,
3974            ..PoolSpec::with_template(crate::ephemeral::EphemeralSpec {
3975                aplicacao: crate::intent::AplicacaoIntent::chart_only("oci://x", "1"),
3976                ttl: "1h".into(),
3977                teardown: crate::lifetime::TeardownPolicy::Always,
3978                max_concurrent: 0,
3979                postconditions: vec![],
3980                preconditions: vec![],
3981                verify_timeout: None,
3982                classification: None,
3983                parent: None,
3984                exports: vec![],
3985                routing: None,
3986            })
3987        }
3988    }
3989
3990    fn empty_alloc_spec() -> AllocationSpec {
3991        AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
3992    }
3993
3994    #[test]
3995    fn in_namespace_on_process_stamps_borrowed_str() {
3996        let p = Process::new("api", empty_process_spec()).in_namespace("prod");
3997        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
3998    }
3999
4000    #[test]
4001    fn in_namespace_on_process_stamps_owned_string() {
4002        let ns: String = "prod".into();
4003        let p = Process::new("api", empty_process_spec()).in_namespace(ns);
4004        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
4005    }
4006
4007    #[test]
4008    fn in_namespace_on_process_stamps_string_ref() {
4009        let ns: String = "prod".into();
4010        let p = Process::new("api", empty_process_spec()).in_namespace(&ns);
4011        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
4012    }
4013
4014    #[test]
4015    fn in_namespace_on_ephemeral_pool_stamps_borrowed_str() {
4016        let p = EphemeralPool::new("pool-1", empty_pool_spec()).in_namespace("pools");
4017        assert_eq!(p.metadata.namespace.as_deref(), Some("pools"));
4018    }
4019
4020    #[test]
4021    fn in_namespace_on_ephemeral_allocation_stamps_borrowed_str() {
4022        let a = EphemeralAllocation::new("alloc-1", empty_alloc_spec()).in_namespace("pools");
4023        assert_eq!(a.metadata.namespace.as_deref(), Some("pools"));
4024    }
4025
4026    #[test]
4027    fn in_namespace_on_configmap_via_blanket_stamps_ns() {
4028        let cm = ConfigMap {
4029            metadata: ObjectMeta {
4030                name: Some("cm-1".into()),
4031                ..Default::default()
4032            },
4033            ..Default::default()
4034        };
4035        let cm = cm.in_namespace("demo");
4036        assert_eq!(cm.metadata.namespace.as_deref(), Some("demo"));
4037    }
4038
4039    #[test]
4040    fn in_namespace_second_call_overwrites_first() {
4041        let p = Process::new("api", empty_process_spec())
4042            .in_namespace("staging")
4043            .in_namespace("prod");
4044        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
4045    }
4046
4047    #[test]
4048    fn in_namespace_preserves_name_and_spec_untouched() {
4049        // Byte-identical parity with the pre-lift two-line pattern:
4050        // only `metadata.namespace` moves; `metadata.name` + `spec`
4051        // stay at the values the derive-supplied `::new` stamped.
4052        // Serialize both `spec` sides through serde_json so we can
4053        // pin equality without requiring `PartialEq` on `ProcessSpec`.
4054        let p = Process::new("api", empty_process_spec()).in_namespace("prod");
4055        assert_eq!(p.metadata.name.as_deref(), Some("api"));
4056        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
4057        let expected = serde_json::to_value(empty_process_spec()).unwrap();
4058        let actual = serde_json::to_value(&p.spec).unwrap();
4059        assert_eq!(actual, expected);
4060    }
4061
4062    #[test]
4063    fn pool_new_in_forwarder_matches_trait_form() {
4064        // Cross-composer coherence witness — the per-CRD
4065        // `EphemeralPool::new_in` forwarder must produce a value
4066        // structurally identical to what `Process::new(...).in_namespace(...)`
4067        // does on the same axis. Serialize both sides through
4068        // serde_json so any drift between the forwarding form and a
4069        // direct trait-call materializes at this pin.
4070        let via_new_in = EphemeralPool::new_in("pool-x", "pools", empty_pool_spec());
4071        let via_trait = EphemeralPool::new("pool-x", empty_pool_spec()).in_namespace("pools");
4072        assert_eq!(
4073            serde_json::to_value(&via_new_in).unwrap(),
4074            serde_json::to_value(&via_trait).unwrap(),
4075        );
4076    }
4077
4078    #[test]
4079    fn allocation_new_in_forwarder_matches_trait_form() {
4080        let via_new_in = EphemeralAllocation::new_in("alloc-x", "pools", empty_alloc_spec());
4081        let via_trait =
4082            EphemeralAllocation::new("alloc-x", empty_alloc_spec()).in_namespace("pools");
4083        assert_eq!(
4084            serde_json::to_value(&via_new_in).unwrap(),
4085            serde_json::to_value(&via_trait).unwrap(),
4086        );
4087    }
4088}
4089
4090#[cfg(test)]
4091mod annotations_family_tests {
4092    //! Family-invariant pins for the substrate-owned annotation-key
4093    //! family that the [`crate::annotations`] module owns.
4094    //!
4095    //! Mirror of the sibling [`crate::finalizers::tests`] family-
4096    //! invariant block on the peer-family axis: the [`crate::finalizers`]
4097    //! module already carries the same closed-family + shared-prefix
4098    //! + pairwise-uniqueness discipline over its three finalizer keys;
4099    //! this block extends the same solve-once discipline to the 21-key
4100    //! annotation family.
4101    //!
4102    //! Each pin binds ONE invariant at fail-before-pass-after
4103    //! granularity so a future addition to the annotation family that
4104    //! violated the invariant (a new `pub const` that missed the
4105    //! [`crate::annotations::ALL`] slice, a prefix drift that dropped
4106    //! the shared [`crate::annotations::GROUP_PREFIX`] on ONE arm, a
4107    //! copy-paste that duplicated one arm's wire form at another)
4108    //! surfaces HERE rather than at some downstream sweep binary or
4109    //! silent K8s-API-server-side skew whichever consumer hit the
4110    //! broken invariant first.
4111    use crate::{annotations, finalizers};
4112
4113    #[test]
4114    fn group_prefix_matches_tatara_reverse_dns() {
4115        // Byte-shape pin — the shared prefix is the same
4116        // reverse-DNS namespace every tatara-owned wire-form key
4117        // (annotation, finalizer, CRD group) rides through.
4118        assert_eq!(annotations::GROUP_PREFIX, "tatara.pleme.io/");
4119    }
4120
4121    #[test]
4122    fn group_prefix_matches_finalizers_group_prefix() {
4123        // Cross-peer-family coherence pin — the annotation family +
4124        // the finalizer family MUST share the same reverse-DNS
4125        // namespace prefix at the substrate level. A future rename
4126        // that shifted ONE module's prefix (a group-segment migration
4127        // that landed at the annotation family but forgot the
4128        // finalizer family, or vice-versa) would silently unbind the
4129        // two peer families and let one CRD's finalizers escape the
4130        // reverse-DNS convention every annotation key on the same CRD
4131        // still carried. Pin the two consts equal at the ONE
4132        // substrate-level coherence witness.
4133        assert_eq!(annotations::GROUP_PREFIX, finalizers::GROUP_PREFIX);
4134    }
4135
4136    #[test]
4137    fn all_matches_declared_length() {
4138        // A regression that added a 22nd `pub const` above the ALL
4139        // slice without appending it to ALL (or shrank the family
4140        // without pruning the slice) would surface here. The
4141        // 21-arm listing pins the declaration order every downstream
4142        // audit sweep iterates through.
4143        assert_eq!(annotations::ALL.len(), 21);
4144    }
4145
4146    #[test]
4147    fn all_share_group_prefix() {
4148        // Every arm of the family MUST start with the shared
4149        // [`crate::annotations::GROUP_PREFIX`] reverse-DNS namespace
4150        // — matching the `#[kube(group = "tatara.pleme.io", …)]`
4151        // slot on every CRD struct. A future rename that drifted ONE
4152        // arm's prefix (a `tatara.io/` copy-paste that silently
4153        // escaped the K8s-side convention) would silently corrupt
4154        // every downstream annotation read on that key; the pin
4155        // surfaces the drift here rather than at operator-visible
4156        // annotation-read skew.
4157        for key in annotations::ALL {
4158            assert!(
4159                key.starts_with(annotations::GROUP_PREFIX),
4160                "annotation key {key:?} must start with {:?}",
4161                annotations::GROUP_PREFIX,
4162            );
4163        }
4164    }
4165
4166    #[test]
4167    fn all_are_pairwise_unique() {
4168        // No two arms of the family may share the same wire form —
4169        // a copy-paste regression that duplicated one arm's wire
4170        // form at another arm (e.g. a `POOL_SLOT` const that got
4171        // copy-pasted to the `RETURN_TRIGGER` const's value) would
4172        // silently double-book the K8s metadata slot the two keys
4173        // share, letting one write overwrite the other at whichever
4174        // downstream stamp site fired second.
4175        let mut seen: Vec<&str> = Vec::new();
4176        for key in annotations::ALL {
4177            assert!(
4178                !seen.contains(key),
4179                "duplicate annotation key in ALL: {key:?}",
4180            );
4181            seen.push(key);
4182        }
4183        assert_eq!(seen.len(), annotations::ALL.len());
4184    }
4185
4186    #[test]
4187    fn all_contains_every_declared_const() {
4188        // Coherence pin — a regression that added a new `pub const`
4189        // above the ALL slice but forgot to append it here surfaces
4190        // by name at this pin. Every currently-declared const in
4191        // [`crate::annotations`] MUST appear at least once in the
4192        // [`crate::annotations::ALL`] slice; if a future editor
4193        // adds a 22nd const above but omits it below, this pin +
4194        // [`all_matches_declared_length`] together catch both the
4195        // slice-length drift and the omitted-const case.
4196        for key in [
4197            annotations::MANAGED_BY,
4198            annotations::PROCESS,
4199            annotations::PID,
4200            annotations::CONTENT_HASH,
4201            annotations::ATTESTATION_ROOT,
4202            annotations::GENERATION,
4203            annotations::SIGNAL,
4204            annotations::RELEASED_FROM,
4205            annotations::ROLE,
4206            annotations::EXPORT_INDEX,
4207            annotations::APP,
4208            annotations::ROUTING_FORM,
4209            annotations::REQUESTOR,
4210            annotations::ALLOCATION,
4211            annotations::REQUESTOR_KIND,
4212            annotations::POOL,
4213            annotations::POOL_SLOT,
4214            annotations::RETURN_TRIGGER,
4215            annotations::ENCAPSULATION_MODE,
4216            annotations::ADOPTED_RELEASE,
4217            annotations::RECEIPT,
4218        ] {
4219            assert!(
4220                annotations::ALL.contains(&key),
4221                "annotation key {key:?} missing from ALL slice",
4222            );
4223        }
4224    }
4225
4226    #[test]
4227    fn all_disjoint_from_finalizer_family() {
4228        // Cross-peer-family disjointness pin — the annotation +
4229        // finalizer families share the reverse-DNS namespace
4230        // [`crate::annotations::GROUP_PREFIX`] but MUST NOT share
4231        // any specific wire-form key. A copy-paste that landed a
4232        // finalizer key (`tatara.pleme.io/<owner>-finalizer`) in
4233        // the annotation family, or an annotation key on the
4234        // finalizer family, would let a metadata-list writer
4235        // silently double-book the K8s garbage-collection slot on
4236        // the SAME resource the annotation reader consumes.
4237        for ann in annotations::ALL {
4238            for fin in finalizers::ALL {
4239                assert_ne!(
4240                    ann, fin,
4241                    "annotation key {ann:?} collides with finalizer key {fin:?}",
4242                );
4243            }
4244        }
4245    }
4246}