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