Skip to main content

tatara_process/
intent.rs

1//! Intent — where the rendered artifacts come from.
2//!
3//! Exactly one field on `Intent` must be set. The reconciler's RENDER phase
4//! selects a driver based on which variant is present:
5//!   - `nix`:        tatara-engine `nix_eval` → resources
6//!   - `flux`:       pass through an existing `GitRepository`
7//!   - `lisp`:       tatara-lisp reader + macroexpander → resources
8//!   - `container`:  emit Deployment/StatefulSet/etc directly (no Helm)
9//!   - `aplicacao`:  emit a FluxCD `HelmRelease` for a pleme-io typed
10//!                   Aplicacao chart (e.g. `lareira-demo-app`).
11//!                   This is the canonical handoff from caixa-shaped
12//!                   declarations to in-cluster reconciliation.
13//!   - `guest`:      tatara-hospedeiro supervises a Linux VM or WASM
14//!                   component. See `tatara/docs/declarative-guests.md`.
15//!                   The GuestSpec itself is type-erased here (JSON value)
16//!                   so tatara-process stays decoupled from tatara-vm;
17//!                   hospedeiro re-parses the value as GuestSpec on boot.
18
19use schemars::JsonSchema;
20use serde::{Deserialize, Serialize};
21use std::collections::BTreeMap;
22
23/// Intent — exactly one variant should be populated.
24#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
25#[serde(rename_all = "camelCase")]
26pub struct Intent {
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub nix: Option<NixIntent>,
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub flux: Option<FluxIntent>,
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub lisp: Option<LispIntent>,
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub container: Option<ContainerIntent>,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub aplicacao: Option<AplicacaoIntent>,
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub guest: Option<GuestIntent>,
39}
40
41/// Enum view over the populated variant — convenience for the reconciler.
42#[derive(Clone, Debug)]
43pub enum IntentVariant<'a> {
44    Nix(&'a NixIntent),
45    Flux(&'a FluxIntent),
46    Lisp(&'a LispIntent),
47    Container(&'a ContainerIntent),
48    Aplicacao(&'a AplicacaoIntent),
49    Guest(&'a GuestIntent),
50}
51
52impl IntentVariant<'_> {
53    /// Reverse projection — every borrowed variant knows its
54    /// `IntentKind` discriminator. Pairs with `IntentKind::select`
55    /// so `IntentKind::select(intent).map(|v| v.kind())` round-trips
56    /// the closed set; pinned by the substrate testkit
57    /// [`crate::tagged_union::assert_variant_round_trip`] shared
58    /// across every `<T: TaggedUnion>` implementor. The inherent
59    /// method stays load-bearing (the `.kind()` calling convention
60    /// pre-dates the trait lift; no consumer needs `use
61    /// crate::tagged_union::VariantKind` to reach the reverse
62    /// projection) while the trait impl below delegates to this body
63    /// as the ground-truth arm-to-Kind mapping.
64    pub fn kind(&self) -> IntentKind {
65        match self {
66            Self::Nix(_) => IntentKind::Nix,
67            Self::Flux(_) => IntentKind::Flux,
68            Self::Lisp(_) => IntentKind::Lisp,
69            Self::Container(_) => IntentKind::Container,
70            Self::Aplicacao(_) => IntentKind::Aplicacao,
71            Self::Guest(_) => IntentKind::Guest,
72        }
73    }
74
75    /// Canonical attestation-pillar bytes for the populated variant —
76    /// the pre-lift `serde_json::to_vec(<inner>).unwrap_or_default()`
77    /// shape every arm restated by hand now rides through the ONE
78    /// substrate primitive [`crate::three_pillar::pillar_bytes`],
79    /// peer of the four workload-render sites +
80    /// `phase_machine::compute_intent_hash` + `identity::content_hash`
81    /// consumers post-lift. Each arm names its inner payload ONCE;
82    /// the fallback rule lives at the substrate owner. Adding a 7th
83    /// intent variant requires only the arm here + one `pillar_bytes`
84    /// delegation, not a per-arm fallback restatement.
85    pub fn canonical_bytes(&self) -> Vec<u8> {
86        match self {
87            Self::Nix(n) => crate::three_pillar::pillar_bytes(n),
88            Self::Flux(f) => crate::three_pillar::pillar_bytes(f),
89            Self::Lisp(l) => crate::three_pillar::pillar_bytes(l),
90            Self::Container(c) => crate::three_pillar::pillar_bytes(c),
91            Self::Aplicacao(a) => crate::three_pillar::pillar_bytes(a),
92            Self::Guest(g) => crate::three_pillar::pillar_bytes(g),
93        }
94    }
95}
96
97impl crate::tagged_union::VariantKind<IntentKind> for IntentVariant<'_> {
98    fn variant_kind(&self) -> IntentKind {
99        self.kind()
100    }
101}
102
103/// Closed-set discriminator over `Intent`'s six tagged-union slots.
104/// Single source of truth that drives `Intent::variant`'s ambiguity
105/// + emptiness resolver, the `IntentError::Empty` message, and the
106/// reverse `IntentVariant::kind` projection. Adding a 7th intent
107/// variant lands at one `ALL` entry + one `as_str` arm + one
108/// `select` arm + one `IntentVariant::kind` arm — exhaustively
109/// checked by the compiler.
110#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
111#[closed_set(via = "as_str", generate_unknown, display)]
112pub enum IntentKind {
113    Nix,
114    Flux,
115    Lisp,
116    Container,
117    Aplicacao,
118    Guest,
119}
120
121impl IntentKind {
122    /// The closed set of intent kinds — single source of truth that
123    /// drives `Intent::variant`'s sweep so a variant added without
124    /// an `ALL` entry never reaches the resolver.
125    pub const ALL: [Self; 6] = [
126        Self::Nix,
127        Self::Flux,
128        Self::Lisp,
129        Self::Container,
130        Self::Aplicacao,
131        Self::Guest,
132    ];
133
134    /// Canonical lower-case wire-format key — matches the serde
135    /// `rename_all = "camelCase"` field name on `Intent`. The
136    /// `IntentError::Empty` message composes the human-readable
137    /// list from this projection so a new variant lands in the
138    /// operator-facing diagnostic automatically via the `ALL`
139    /// sweep, not via hand-maintained error-string drift.
140    pub const fn as_str(self) -> &'static str {
141        match self {
142            Self::Nix => "nix",
143            Self::Flux => "flux",
144            Self::Lisp => "lisp",
145            Self::Container => "container",
146            Self::Aplicacao => "aplicacao",
147            Self::Guest => "guest",
148        }
149    }
150
151    /// Project an `Intent` borrow into the optional typed variant
152    /// view for this kind. Returns `None` iff the matching slot is
153    /// `None`. Composes the closed-set sweep `Intent::variant`
154    /// loops over.
155    pub fn select<'a>(self, intent: &'a Intent) -> Option<IntentVariant<'a>> {
156        match self {
157            Self::Nix => intent.nix.as_ref().map(IntentVariant::Nix),
158            Self::Flux => intent.flux.as_ref().map(IntentVariant::Flux),
159            Self::Lisp => intent.lisp.as_ref().map(IntentVariant::Lisp),
160            Self::Container => intent.container.as_ref().map(IntentVariant::Container),
161            Self::Aplicacao => intent.aplicacao.as_ref().map(IntentVariant::Aplicacao),
162            Self::Guest => intent.guest.as_ref().map(IntentVariant::Guest),
163        }
164    }
165}
166
167crate::declare_tagged_union_error! {
168    pub IntentError,
169    empty = "intent has no variant set (one of {0} required)",
170    ambiguous = "intent has multiple variants set; exactly one required",
171}
172
173/// Slash-joined list of every `IntentKind::as_str()` — composed once
174/// at compile time so `IntentError::Empty`'s diagnostic carries the
175/// closed-set summary without per-variant string drift. Pinned against
176/// the canonical [`tatara_lisp::ClosedSet::labels_joined`] projection
177/// by `intent_error_empty_lists_every_kind_in_canonical_order`, so a
178/// regression that drifts this `&'static str` constant from the
179/// `IntentKind::ALL × as_str` composition fails-loudly at the test
180/// site without per-variant inline materialization.
181pub(crate) const INTENT_KIND_LIST: &str = "nix/flux/lisp/container/aplicacao/guest";
182
183// `impl FromStr for IntentKind` +
184// `impl tatara_lisp::ClosedSet for IntentKind` +
185// `impl fmt::Display for IntentKind` +
186// `pub struct UnknownIntentKind(pub String)` are all generated by
187// `#[derive(tatara_closed_set::DeriveClosedSet)]` +
188// `#[closed_set(via = "as_str", generate_unknown, display)]` on the
189// enum declaration above. `label` delegates to the inherent
190// `IntentKind::as_str` — the camelCase wire-vocabulary projection
191// stays load-bearing (matches the serde `rename_all = "camelCase"`
192// field names on `Intent` AND the `IntentVariant::canonical_bytes`
193// per-variant arm), while generic `T: ClosedSet` consumers reach the
194// STABLE workspace-wide name (`label`). The auto-derived carrier
195// label "intent kind" matches the substrate-wide
196// `#[error("unknown intent kind: {0}")]` shape every sibling
197// closed-set carrier across `tatara-process` renders verbatim.
198// Symmetric to [`crate::intent::WorkloadKind`] (the workload-axis
199// sibling on the same `ProcessSpec` slice) and every other
200// `#[derive(DeriveClosedSet)]` implementor across the crate.
201
202crate::declare_tagged_union_impls! {
203    parent = Intent,
204    kind = IntentKind,
205    variant = IntentVariant,
206    error = IntentError,
207    kind_list = INTENT_KIND_LIST,
208}
209
210/// Nix-sourced intent — tatara-engine's nix_eval driver produces resources.
211#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
212#[serde(rename_all = "camelCase")]
213pub struct NixIntent {
214    /// Flake reference, e.g., `github:pleme-io/k8s?dir=shared/infrastructure`.
215    pub flake_ref: String,
216    /// Attribute path within the flake (e.g., `observability`).
217    pub attribute: String,
218    /// Target system. Defaults to the controller host's system.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub system: Option<String>,
221    /// Attic cache to push the resulting store path into.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub attic_cache: Option<String>,
224    /// Additional `nix build` arguments (e.g., `["--impure"]`).
225    #[serde(default)]
226    pub extra_args: Vec<String>,
227    /// Delegate the actual build to a sibling NixBuild CRD
228    /// (bridges to tatara-operator NATS bare-metal builder path).
229    #[serde(default)]
230    pub delegate_to_nix_build: bool,
231}
232
233/// FluxCD passthrough intent — reuse an existing GitRepository.
234#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
235#[serde(rename_all = "camelCase")]
236pub struct FluxIntent {
237    /// Name of an existing `GitRepository` (typically in `flux-system`).
238    pub git_repository: String,
239    /// Path inside the repository that the Kustomization will apply.
240    pub path: String,
241    /// Optional namespace of the GitRepository CR (defaults to `flux-system`).
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub git_repository_namespace: Option<String>,
244    /// Optional target namespace for the emitted Kustomization.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub target_namespace: Option<String>,
247    /// SOPS decryption — defaults to true to match pleme-io conventions.
248    #[serde(default = "crate::serde_defaults::default_true")]
249    pub decrypt_sops: bool,
250    /// If set, additionally emit a HelmRelease for this chart.
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub helm_chart: Option<String>,
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub helm_values: Option<BTreeMap<String, serde_json::Value>>,
255}
256
257/// Lisp-sourced intent — tatara-lisp reader + macroexpander produces resources.
258#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
259#[serde(rename_all = "camelCase")]
260pub struct LispIntent {
261    /// Raw S-expression source, OR `include:<path>` / `configmap:<name>/<key>` pointer.
262    pub source: String,
263    /// Reader dialect / version tag.
264    #[serde(default = "default_reader")]
265    pub reader: String,
266    /// Macro form version.
267    #[serde(default = "default_version")]
268    pub version: String,
269    /// Symbols injected into the reader env (e.g., `cluster`, `region`).
270    #[serde(default)]
271    pub bindings: BTreeMap<String, serde_json::Value>,
272}
273
274fn default_reader() -> String {
275    "tatara-lisp".to_string()
276}
277fn default_version() -> String {
278    "v1".to_string()
279}
280
281/// Aplicacao intent — emit a FluxCD `HelmRelease` for a pleme-io
282/// typed Aplicacao chart. The chart owns its own sub-chart DAG;
283/// the reconciler only watches `HelmRelease.status.conditions[type=Ready]`.
284///
285/// This is the canonical handoff from caixa `(defaplicacao …)` declarations
286/// (which the typescape renders to this Intent) into in-cluster
287/// reconciliation. Closed-loop ephemeral test environments use this
288/// variant with `:lifetime :ephemeral` on the surrounding ProcessSpec.
289///
290/// Example (Lisp):
291/// ```lisp
292/// :intent (:aplicacao
293///           (:chart-ref "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
294///            :version "0.5.5"
295///            :profile "all-in-one"
296///            :values-overlay (:cluster (:name "ephemeral-test-01")
297///                             :persistence false
298///                             :compliance (:overlays []))))
299/// ```
300#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
301#[serde(rename_all = "camelCase")]
302pub struct AplicacaoIntent {
303    /// Helm chart reference. OCI (`oci://…`) or repo-relative (`pleme-io/lareira-demo-app`).
304    pub chart_ref: String,
305    /// Chart version (Helm semver constraint; `">=0.5.5"` allowed).
306    pub version: String,
307    /// Architecture profile from the chart's `values/*.yaml` family
308    /// (e.g. `all-in-one`, `saas-internal`).
309    /// Leave empty to use chart defaults.
310    #[serde(default, skip_serializing_if = "String::is_empty")]
311    pub profile: String,
312    /// Typed values overlay merged on top of the profile.
313    /// Free-form JSON to keep tatara-process decoupled from chart schemas.
314    #[serde(default)]
315    #[schemars(schema_with = "crate::schema_helpers::preserve_unknown_object")]
316    pub values_overlay: serde_json::Value,
317    /// HelmRelease name override. Defaults to the Process's PID-derived name.
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    pub release_name: Option<String>,
320    /// Target namespace for the chart. Defaults to the Process's namespace.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub target_namespace: Option<String>,
323    /// Install timeout (`humantime` duration). Empty = chart-controller default.
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub install_timeout: Option<String>,
326}
327
328/// Workspace-wide default for the `timeout` slot on a Flux
329/// `HelmRelease.spec.{install,upgrade}` block, applied when the
330/// operator did not populate [`AplicacaoIntent::install_timeout`].
331/// Load-bearing on the reconciler's Helm-driven RENDER surface —
332/// [`AplicacaoIntent::helm_lifecycle_policy`] substitutes this exact
333/// string, and the reconciler's `render_aplicacao` byte-installs
334/// the resulting policy into both install AND upgrade slots.
335pub const HELM_LIFECYCLE_DEFAULT_TIMEOUT: &str = "25m";
336
337/// Workspace-wide default for the `remediation.retries` slot on a
338/// Flux `HelmRelease.spec.{install,upgrade}` block. Constant across
339/// both slots today; a future two-slot split (e.g. distinct retry
340/// budgets for a first install vs a rolling upgrade) lands as two
341/// consts here + a two-slot [`HelmLifecyclePolicy`] shape, not at
342/// the render callsite.
343pub const HELM_LIFECYCLE_DEFAULT_RETRIES: u8 = 3;
344
345/// Workspace-wide default for the reconcile-loop cadence on both Flux
346/// resources a Helm-driven `AplicacaoIntent` publishes today: the
347/// `OCIRepository.spec.interval` on the source side (how often the
348/// source-controller re-pulls the chart from OCI) and the
349/// `HelmRelease.spec.interval` on the release side (how often the
350/// helm-controller re-reconciles the release against the chart).
351/// The fleet convention ties both cadences to the same `5m` string
352/// today, so the substrate exposes ONE named const rather than two
353/// literals sprayed across `render_aplicacao`.
354///
355/// Peer to [`HELM_LIFECYCLE_DEFAULT_TIMEOUT`] on the same
356/// AplicacaoIntent-facing "workspace-wide Flux default" axis. A
357/// future per-slot divergence (`SOURCE_INTERVAL` vs `RELEASE_INTERVAL`
358/// as two consts, or a two-slot method returning a
359/// `FluxReconcileIntervals { source, release }` shape) lands here,
360/// NOT at the two render callsites.
361///
362/// Load-bearing wire-format string: the byte-exact `5m` shape is
363/// what the Flux source- and helm-controllers parse via `humantime`;
364/// a regression that renamed it to any other duration would silently
365/// throttle or hammer every Helm-driven Process's reconciliation
366/// loop. Pinned at
367/// [`tests::flux_helm_default_interval_is_pinned_to_5m`].
368pub const FLUX_HELM_DEFAULT_INTERVAL: &str = "5m";
369
370/// Typed shape of one Flux `HelmRelease.spec.{install,upgrade}` slot
371/// — the substrate's projection of the "how long may Helm take, and
372/// how many retries after a failed run" contract every Helm-driven
373/// Process publishes on both slots. Pre-lift the reconciler's
374/// `render_aplicacao` hand-authored the shape via TWO adjacent
375/// identical `json!({"timeout": …, "remediation": {"retries": …}})`
376/// blocks past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold
377/// — one for install, one for upgrade, each restating the same
378/// three-slot literal with the same `Option::unwrap_or_else` fallback
379/// on the timeout. Post-lift the shape lives at ONE named typed
380/// struct here whose serde projection matches Flux HelmRelease v2's
381/// `install` / `upgrade` block schema byte-identically, and the
382/// reconciler composes both slots off ONE
383/// [`AplicacaoIntent::helm_lifecycle_policy`] call.
384///
385/// A future addition — a `wait: bool` slot, a `crds:
386/// CreateReplace` slot, a `disableOpenAPIValidation: bool` slot,
387/// a two-slot split that lets install carry a longer timeout than
388/// upgrade — lands at ONE struct here and every downstream
389/// consumer (the render surface, snapshot tests, an operator-
390/// facing dashboard column, a future validating webhook) inherits
391/// the upgrade mechanically.
392#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
393pub struct HelmLifecyclePolicy {
394    /// Chart-controller timeout (`humantime` duration). Set from
395    /// [`AplicacaoIntent::install_timeout`] when present; otherwise
396    /// [`HELM_LIFECYCLE_DEFAULT_TIMEOUT`].
397    pub timeout: String,
398    /// Retry budget for the slot.
399    pub remediation: HelmRemediationPolicy,
400}
401
402/// Typed shape of one `HelmLifecyclePolicy::remediation` slot.
403/// A named struct rather than an inline `{retries: u8}` map so
404/// downstream consumers can talk about "one Helm remediation
405/// policy" as a nameable handle rather than an unnamed nested
406/// object.
407#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
408pub struct HelmRemediationPolicy {
409    /// Number of times Flux's helm-controller retries a failed
410    /// install / upgrade before surfacing the failure to the parent
411    /// Process's boundary evaluator.
412    pub retries: u8,
413}
414
415impl HelmLifecyclePolicy {
416    /// The workspace-wide default policy — used when the operator
417    /// omitted [`AplicacaoIntent::install_timeout`]. Named projection
418    /// of the two `HELM_LIFECYCLE_DEFAULT_*` consts so a future
419    /// consumer wanting "the substrate's fresh-out-of-the-box Helm
420    /// lifecycle policy" pulls the pair through ONE call rather than
421    /// composing the struct by hand at every callsite.
422    pub fn workspace_default() -> Self {
423        Self {
424            timeout: HELM_LIFECYCLE_DEFAULT_TIMEOUT.to_string(),
425            remediation: HelmRemediationPolicy {
426                retries: HELM_LIFECYCLE_DEFAULT_RETRIES,
427            },
428        }
429    }
430}
431
432impl AplicacaoIntent {
433    /// Chart-pointer-only composer — the canonical minimal
434    /// `AplicacaoIntent` every fixture and default-shape callsite
435    /// restated pre-lift by binding only `(chart_ref, version)` and
436    /// leaving every remaining slot at its K8s-schema-default value
437    /// (`profile = ""`, `values_overlay = Value::Null`,
438    /// `release_name = target_namespace = install_timeout = None`).
439    ///
440    /// Pre-lift the 7-slot struct-literal was hand-authored at 14
441    /// workspace-wide sites past the ★★ PRIME-DIRECTIVE ≥ 2
442    /// duplication threshold, each restating the SAME 5-slot default
443    /// tail after a caller-varying `(chart_ref, version)` pair:
444    ///
445    /// * `tatara-process` — 10 sites across `lib.rs` (3× `empty_template`
446    ///   in the ephemeral-spec / matrix / observer test blocks),
447    ///   `lifetime_clock.rs` (2× the ephemeral / permanent Process
448    ///   composer helpers), `tagged_union.rs` (1× the
449    ///   `IntentKind::Aplicacao` sample-intent arm), `pool.rs` (1×
450    ///   `empty_template`), and `intent.rs` (3× the `helm_intent`
451    ///   helper + the `aplicacao_plus_flux_is_ambiguous` fixture + the
452    ///   `IntentKind::Aplicacao` sample-intent-for arm).
453    /// * `tatara-pool-reconciler` — 4 sites across `router.rs`,
454    ///   `pool_decide.rs`, `desired.rs`, `allocation_decide.rs`
455    ///   (all `empty_template` fixtures seeding the pool + allocation
456    ///   convergence-decision test batteries).
457    /// * `tatara-reconciler` — 1 site in `render.rs`
458    ///   (`helmrepository_chartref_for_non_oci` production-shape
459    ///   fixture stamping the non-OCI chart-ref render path).
460    ///
461    /// All 14 sites walked the SAME 5-slot default tail — differing
462    /// only in the caller-varying `chart_ref` / `version` values
463    /// (`"oci://x"` / `"1"` on the majority test-fixture slice,
464    /// `"oci://ghcr.io/x"` / `"0.1.0"` on the `IntentKind` sample,
465    /// `"pleme-io/lareira-demo-app"` / `"0.5.5"` on the non-OCI
466    /// render pin). Post-lift each callsite reads
467    /// `AplicacaoIntent::chart_only(chart, version)` and the 5-slot
468    /// default tail lives at ONE substrate owner.
469    ///
470    /// The `impl Into<String>` argument form matches the pre-lift
471    /// call shape — every site that spelled `"oci://x".into()` +
472    /// `"1".into()` in the struct-literal continues to compile
473    /// unchanged, and callers with a live `String` (e.g. reading
474    /// from a caller-supplied fixture parameter) pass it through
475    /// without a `.to_string()` re-wrap.
476    ///
477    /// Return-form axis: `AplicacaoIntent` — the owned typed value
478    /// every consumer's downstream `Intent { aplicacao: Some(...), ..
479    /// }` / `EphemeralSpec { aplicacao: ..., .. }` binding stamps
480    /// verbatim, matching the pre-lift 7-slot struct-literal's return
481    /// shape exactly. The five default-tail slots reify the K8s
482    /// schema's own defaults (`profile` empty ⇒ chart profile default;
483    /// `values_overlay = Null` ⇒ pass-through; three `None` slots ⇒
484    /// server / chart-computed) so no consumer inherits a semantic
485    /// change from the lift.
486    ///
487    /// A future normalization of the "minimal AplicacaoIntent" default
488    /// — an added struct field with its own K8s-schema default, a
489    /// tightening of a `None` slot to a substrate-owned default value,
490    /// a per-workspace-default `install_timeout` override — lands at
491    /// THIS ONE substrate primitive and every downstream fixture /
492    /// default-shape consumer inherits the upgrade mechanically — no
493    /// per-site edit at any of the 14 listed callers or at future
494    /// consumers (a new pool-shard-flavor fixture, a new intent-axis
495    /// convergence probe, a per-tenant AplicacaoIntent minimal seed).
496    ///
497    /// Peer to [`Self::helm_lifecycle_policy`] +
498    /// [`Self::flux_reconcile_interval`] on the (COMPOSE, DERIVE)
499    /// axis: `chart_only` is the WRITE-side composer (stamp a minimal
500    /// `AplicacaoIntent`); the lifecycle + interval methods are the
501    /// READ-side derivers (project a substrate-default Flux policy /
502    /// cadence off an `AplicacaoIntent`). The three primitives
503    /// partition the `AplicacaoIntent` compose × derive surface at
504    /// the substrate.
505    ///
506    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
507    /// the 5-slot default tail recurred at 14 hand-authored sites
508    /// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, spanning
509    /// three workspace crates, and is lifted onto the ONE workspace-
510    /// wide substrate owner here). THEORY.md §II.1 invariant 5
511    /// (composition preserves proofs — the pin block below binds the
512    /// primitive at fail-before-pass-after granularity so a
513    /// regression that drifted any of the five default-tail slots
514    /// surfaces at THESE pins rather than as silent fixture skew
515    /// across the 14 downstream consumers).
516    #[must_use]
517    pub fn chart_only(chart_ref: impl Into<String>, version: impl Into<String>) -> Self {
518        Self {
519            chart_ref: chart_ref.into(),
520            version: version.into(),
521            profile: String::new(),
522            values_overlay: serde_json::Value::Null,
523            release_name: None,
524            target_namespace: None,
525            install_timeout: None,
526        }
527    }
528
529    /// Effective HelmRelease name — the operator-supplied
530    /// [`Self::release_name`] override when set, else the caller-
531    /// supplied fallback (canonically the Process's PID-derived name
532    /// at the reconciler's `render_aplicacao` site, and the enclosing
533    /// matrix env's `NamedEphemeral.name` at the matrix
534    /// `breathe_bands` site — both are the Process's own `name`).
535    ///
536    /// Pre-lift the pattern was hand-authored at 2 workspace-wide
537    /// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold,
538    /// each restating the SAME `Option::clone().unwrap_or_else(||
539    /// fallback.into())` chain differing only in the caller-varying
540    /// fallback slot:
541    ///
542    /// * `tatara-reconciler::render::render_aplicacao` — the
543    ///   `HelmRelease.spec.releaseName` slot on the Flux-owned
544    ///   release the reconciler emits per Helm-driven Process.
545    /// * `tatara-process::matrix::EnvMatrixSpec::breathe_bands` —
546    ///   the `spec.targetRef.name` slot on the breathe Band CRs the
547    ///   matrix sweep emits per generated env × dimension.
548    ///
549    /// Post-lift both sites read `a.release_name_or(fallback)` and
550    /// the fallback-composition shape lives at ONE substrate owner.
551    /// A future tightening — a workspace-wide default seeded off the
552    /// PID, a fallback shape derived off `Self::chart_ref`, a
553    /// validation that the fallback is a DNS-1123 label — lands at
554    /// THIS ONE primitive.
555    ///
556    /// Peer to [`Self::target_namespace_or`] on the same (release,
557    /// namespace) axis: both project one operator-optional
558    /// override-or-fallback slot the reconciler + matrix consume in
559    /// lock-step.
560    #[must_use]
561    pub fn release_name_or(&self, fallback: &str) -> String {
562        self.release_name.clone().unwrap_or_else(|| fallback.into())
563    }
564
565    /// Effective HelmRelease target namespace — the operator-supplied
566    /// [`Self::target_namespace`] override when set, else the caller-
567    /// supplied fallback (canonically the Process's own namespace at
568    /// the reconciler's `render_aplicacao` site, and the enclosing
569    /// matrix env's `NamedEphemeral.name` at the matrix
570    /// `breathe_bands` site).
571    ///
572    /// Peer to [`Self::release_name_or`] — same substrate-owner
573    /// motivation, same 2-site collapse. Post-lift both consumers
574    /// read `a.target_namespace_or(fallback)` and the
575    /// `Option::clone().unwrap_or_else(|| fallback.into())` shape
576    /// lives at ONE primitive here.
577    #[must_use]
578    pub fn target_namespace_or(&self, fallback: &str) -> String {
579        self.target_namespace
580            .clone()
581            .unwrap_or_else(|| fallback.into())
582    }
583
584    /// Derive the Flux `HelmRelease.spec.{install,upgrade}` policy
585    /// this intent publishes on BOTH slots. Pre-lift the reconciler's
586    /// `render_aplicacao` restated the shape by hand via two adjacent
587    /// identical `json!` blocks (install and upgrade); post-lift both
588    /// slots ride through this ONE composer. A future two-slot split
589    /// (distinct install vs upgrade policies) lands as a two-method
590    /// pair here, not at the render callsite.
591    pub fn helm_lifecycle_policy(&self) -> HelmLifecyclePolicy {
592        HelmLifecyclePolicy {
593            timeout: self
594                .install_timeout
595                .clone()
596                .unwrap_or_else(|| HELM_LIFECYCLE_DEFAULT_TIMEOUT.to_string()),
597            remediation: HelmRemediationPolicy {
598                retries: HELM_LIFECYCLE_DEFAULT_RETRIES,
599            },
600        }
601    }
602
603    /// Derive the Flux reconcile-loop cadence this intent publishes on
604    /// BOTH `OCIRepository.spec.interval` (source-controller poll) and
605    /// `HelmRelease.spec.interval` (helm-controller re-reconcile).
606    /// Pre-lift the reconciler's `render_aplicacao` restated the value
607    /// via two adjacent hand-authored `"5m"` string literals past the
608    /// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold; post-lift both
609    /// slots ride through this ONE composer. A future divergence
610    /// (distinct per-slot cadences, a per-intent override field, a
611    /// two-slot method returning a `FluxReconcileIntervals` shape)
612    /// lands at ONE method here, not at the render callsites.
613    ///
614    /// Sibling composer to [`Self::helm_lifecycle_policy`]: both
615    /// return the substrate-default shape a Helm-driven Process
616    /// publishes on the Flux resources `render_aplicacao` emits,
617    /// keyed off the same `AplicacaoIntent`.
618    pub fn flux_reconcile_interval(&self) -> String {
619        FLUX_HELM_DEFAULT_INTERVAL.to_string()
620    }
621}
622
623/// Container intent — direct Deployment/StatefulSet/etc, no Helm.
624#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
625#[serde(rename_all = "camelCase")]
626pub struct ContainerIntent {
627    pub image: String,
628    #[serde(default, skip_serializing_if = "Option::is_none")]
629    pub replicas: Option<i32>,
630    #[serde(default)]
631    pub command: Vec<String>,
632    #[serde(default)]
633    pub args: Vec<String>,
634    #[serde(default)]
635    pub env: BTreeMap<String, String>,
636    #[serde(default)]
637    pub workload_kind: WorkloadKind,
638}
639
640/// K8s workload kind the `container` intent renders into. PascalCase
641/// values match the K8s `kind:` field on the emitted manifest verbatim,
642/// so `as_str` doubles as the canonical `kind:` projection at render time.
643#[derive(
644    Clone,
645    Copy,
646    Debug,
647    PartialEq,
648    Eq,
649    Hash,
650    Serialize,
651    Deserialize,
652    JsonSchema,
653    Default,
654    tatara_closed_set::DeriveClosedSet,
655)]
656#[serde(rename_all = "PascalCase")]
657#[closed_set(via = "as_str", generate_unknown, display)]
658pub enum WorkloadKind {
659    #[default]
660    Deployment,
661    StatefulSet,
662    DaemonSet,
663    Job,
664    CronJob,
665}
666
667impl WorkloadKind {
668    /// The closed set of workload kinds — single source of truth that
669    /// drives the `as_str` / Display / `FromStr` triad and the typed
670    /// `api_version` / `is_batch` projections. Adding a sixth variant
671    /// lands at one `ALL` entry + one `as_str` arm + one arm in each
672    /// projection — exhaustively checked by the compiler (the `[Self; 5]`
673    /// array literal forces the arity).
674    ///
675    /// Sibling closed-set lifts on the same `ProcessSpec` axis:
676    /// [`crate::encapsulates::EncapsulationMode::ALL`],
677    /// [`crate::export::ExportTrigger::ALL`],
678    /// [`crate::export::ReportFormat::ALL`],
679    /// [`crate::lifetime::TeardownPolicy::ALL`],
680    /// [`crate::intent::IntentKind::ALL`],
681    /// [`crate::lifetime::LifetimeKind::ALL`],
682    /// [`crate::boundary::ConditionKind::ALL`],
683    /// [`crate::phase::ProcessPhase::ALL`],
684    /// [`crate::signal::ProcessSignal::ALL`].
685    pub const ALL: [Self; 5] = [
686        Self::Deployment,
687        Self::StatefulSet,
688        Self::DaemonSet,
689        Self::Job,
690        Self::CronJob,
691    ];
692
693    /// Canonical PascalCase wire-format projection — matches the serde
694    /// `rename_all = "PascalCase"` output verbatim AND the K8s manifest
695    /// `kind:` field the `container` intent's future renderer will emit.
696    /// Used by Display (single source of truth), by `FromStr` to identify
697    /// the variant from its annotation / status-field representation, and
698    /// by operator-facing reason strings without reaching for `{:?}` Debug
699    /// formatting. Pinned by `workload_kind_as_str_matches_serde`.
700    pub const fn as_str(self) -> &'static str {
701        match self {
702            Self::Deployment => "Deployment",
703            Self::StatefulSet => "StatefulSet",
704            Self::DaemonSet => "DaemonSet",
705            Self::Job => "Job",
706            Self::CronJob => "CronJob",
707        }
708    }
709
710    /// Canonical K8s `apiVersion:` projection — `apps/v1` for the
711    /// long-running workload trio, `batch/v1` for the batch pair.
712    /// Single source of truth for the apiVersion the `container` intent
713    /// renderer will stamp on the emitted manifest; pinned by
714    /// `workload_kind_projection_truth_table` so a future variant lands
715    /// at one arm here, not at every render site that previously
716    /// hand-rolled `match kind { Job | CronJob => "batch/v1", _ => … }`.
717    ///
718    /// Closed-set match (not `matches!`) so adding a sixth variant
719    /// triggers the compiler's exhaustiveness check at this site
720    /// rather than silently defaulting to either group.
721    pub const fn api_version(self) -> &'static str {
722        match self {
723            Self::Deployment | Self::StatefulSet | Self::DaemonSet => "apps/v1",
724            Self::Job | Self::CronJob => "batch/v1",
725        }
726    }
727
728    /// True iff the workload kind is a batch (terminating) workload —
729    /// `Job` or `CronJob`. Drives the future container renderer's
730    /// decision between persistent / one-shot retry semantics and lets
731    /// the lifetime clock distinguish "naturally terminates" from "runs
732    /// until SIGTERM" without re-deriving the partition from
733    /// `api_version() == "batch/v1"`.
734    ///
735    /// Closed-set match (not `matches!`) so adding a sixth variant
736    /// triggers the compiler's exhaustiveness check at this site.
737    pub const fn is_batch(self) -> bool {
738        match self {
739            Self::Job | Self::CronJob => true,
740            Self::Deployment | Self::StatefulSet | Self::DaemonSet => false,
741        }
742    }
743}
744
745// `impl FromStr for WorkloadKind` +
746// `impl tatara_lisp::ClosedSet for WorkloadKind` +
747// `impl fmt::Display for WorkloadKind` +
748// `pub struct UnknownWorkloadKind(pub String)` are all generated by
749// `#[derive(tatara_closed_set::DeriveClosedSet)]` +
750// `#[closed_set(via = "as_str", generate_unknown, display)]` on the
751// enum declaration above. `label` delegates to the inherent
752// `WorkloadKind::as_str` — the PascalCase wire-vocabulary projection
753// stays load-bearing (matches the serde `rename_all = "PascalCase"`
754// output AND the K8s manifest `kind:` field verbatim), while generic
755// `T: ClosedSet` consumers reach the STABLE workspace-wide name
756// (`label`). The auto-derived carrier label "workload kind" matches
757// the prior hand-rolled `#[error("unknown workload kind: {0}")]`
758// annotation byte-for-byte. Symmetric to every other
759// `#[derive(DeriveClosedSet)]` implementor across the crate.
760
761/// Guest intent — the Process is a Linux VM or WASM component supervised
762/// by `tatara-hospedeiro`. See `tatara/docs/declarative-guests.md`.
763///
764/// The actual `GuestSpec` is stored as a serde JSON value to keep
765/// `tatara-process` decoupled from `tatara-vm`. Hospedeiro re-parses
766/// the value as the concrete `tatara_vm::GuestSpec` at boot time; a
767/// round-trip test on the tatara-vm side guarantees the shape.
768#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
769#[serde(rename_all = "camelCase")]
770pub struct GuestIntent {
771    /// The (defguest …) spec as JSON. Shape matches `tatara_vm::GuestSpec`.
772    #[schemars(schema_with = "crate::schema_helpers::preserve_unknown_object")]
773    pub spec: serde_json::Value,
774
775    /// Where to write per-guest state on the host (logs, socket, PID file).
776    /// Defaults to `~/.local/state/tatara/guests/<name>/`.
777    #[serde(default, skip_serializing_if = "Option::is_none")]
778    pub state_dir: Option<String>,
779
780    /// Whether hospedeiro is allowed to pull guest artifacts from a remote
781    /// transport (Attic, ssh-ng) if not already present locally. The
782    /// default is taken from the GuestSpec's `buildOn` field; setting
783    /// this explicitly overrides at the intent layer.
784    #[serde(default, skip_serializing_if = "Option::is_none")]
785    pub allow_remote_build: Option<bool>,
786}
787
788#[cfg(test)]
789mod tests {
790    use super::*;
791
792    #[test]
793    fn empty_intent_errors() {
794        let i = Intent::default();
795        match i.variant().unwrap_err() {
796            IntentError::Empty(list) => assert_eq!(list, INTENT_KIND_LIST),
797            other => panic!("expected Empty, got {other:?}"),
798        }
799    }
800
801    #[test]
802    fn exactly_one_ok() {
803        let i = Intent {
804            nix: Some(NixIntent {
805                flake_ref: "github:a/b".into(),
806                attribute: "x".into(),
807                system: None,
808                attic_cache: None,
809                extra_args: vec![],
810                delegate_to_nix_build: false,
811            }),
812            ..Intent::default()
813        };
814        assert!(matches!(i.variant().unwrap(), IntentVariant::Nix(_)));
815    }
816
817    /// AMBIGUOUS-PATH CONTRACT: when two slots are populated the
818    /// resolver yields `Ambiguous`, exhaustively across every pair in
819    /// `ALL × ALL` (excluding the diagonal). Routes through the
820    /// substrate primitive
821    /// [`crate::tagged_union::assert_two_slots_ambiguous`] shared with
822    /// the sibling
823    /// `encapsulation_kind_two_slots_is_ambiguous_across_every_pair`
824    /// / `artifact_source_two_slots_is_ambiguous_across_every_pair`
825    /// / `vector_channel_two_slots_is_ambiguous_across_every_pair`
826    /// sites. Subsumes the pre-lift hand-authored two-pair probes
827    /// (`nix + flux`, `nix + guest`) with exhaustive `6 × 5 = 30`
828    /// coverage — every off-diagonal pair on `IntentKind` is pinned.
829    #[test]
830    fn intent_two_slots_is_ambiguous_across_every_pair() {
831        crate::tagged_union::assert_two_slots_ambiguous::<Intent, _>(two_slot_intent);
832    }
833
834    #[test]
835    fn guest_intent_selects_its_variant() {
836        let i = Intent {
837            guest: Some(GuestIntent {
838                spec: serde_json::json!({
839                    "name": "fast-fn",
840                    "kind": { "kind": "wasm", "runtime": "wasmtime",
841                              "wasiPreview": "p2",
842                              "component": { "kind": "flake",
843                                             "value": {"url":"github:x/y","attr":"wasi"} },
844                              "features": { "simd": true } },
845                    "cmdline": []
846                }),
847                state_dir: None,
848                allow_remote_build: Some(true),
849            }),
850            ..Intent::default()
851        };
852        match i.variant().unwrap() {
853            IntentVariant::Guest(g) => {
854                assert_eq!(g.spec["name"], "fast-fn");
855                assert_eq!(g.allow_remote_build, Some(true));
856            }
857            other => panic!("expected Guest, got {other:?}"),
858        }
859    }
860
861    #[test]
862    fn aplicacao_intent_selects_its_variant() {
863        let i = Intent {
864            aplicacao: Some(AplicacaoIntent {
865                chart_ref: "oci://ghcr.io/pleme-io/charts/lareira-demo-app".into(),
866                version: "0.5.5".into(),
867                profile: "all-in-one".into(),
868                values_overlay: serde_json::json!({ "cluster": { "name": "test-01" } }),
869                release_name: None,
870                target_namespace: None,
871                install_timeout: Some("25m".into()),
872            }),
873            ..Intent::default()
874        };
875        match i.variant().unwrap() {
876            IntentVariant::Aplicacao(a) => {
877                assert_eq!(a.profile, "all-in-one");
878                assert_eq!(a.version, "0.5.5");
879                assert_eq!(a.install_timeout.as_deref(), Some("25m"));
880            }
881            other => panic!("expected Aplicacao, got {other:?}"),
882        }
883    }
884
885    /// Structural well-formedness of [`IntentKind`] as a
886    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
887    /// testkit lift that pins all structural invariants (`ALL` is
888    /// non-empty, every variant round-trips through `label ↔
889    /// parse_label`, labels are pairwise distinct, `""` is outside
890    /// the closed set, the `UnknownIntentKind` carrier's Display
891    /// renders the substrate-wide `"unknown intent kind: <input>"`
892    /// shape, `labels()` equals the natural `ALL × label` projection,
893    /// `parse_label_with_hint` composes `parse_label` +
894    /// `suggest_closest` verbatim) at ONE call site. Replaces the
895    /// hand-derived `intent_kind_all_is_unique_and_complete` —
896    /// clause (1)+(3) of the testkit subsume the uniqueness +
897    /// non-emptiness sweep that test pinned independently.
898    #[test]
899    fn intent_kind_is_well_formed_closed_set() {
900        tatara_closed_set::assert_closed_set_well_formed::<IntentKind>();
901    }
902
903    /// The Display impl IS `as_str` — pinning this lets future callers
904    /// reach for either projection without drift. Symmetric to the
905    /// sibling `workload_kind_display_matches_as_str` invariant; if a
906    /// reviewer accidentally re-introduces an inline match in Display,
907    /// this test would fail the moment a variant rename touches one
908    /// site but not the other.
909    ///
910    /// Routes through the substrate primitive
911    /// [`crate::tagged_union::assert_display_matches_label`], which
912    /// composes `<T as ClosedSet>::label` against `T::to_string`
913    /// byte-identically for every `<T: ClosedSet + Display>`
914    /// implementor — the Display-alignment testkit shared with every
915    /// sibling `X_display_matches_as_str` site across the crate.
916    /// Pre-lift the 27 bodies each restated the same
917    /// `for k in K::ALL { assert_eq!(k.to_string(), k.as_str()) }`
918    /// two-line probe at the test surface; post-lift the projection
919    /// lives at ONE substrate primitive and every site binds through
920    /// a single call.
921    #[test]
922    fn intent_kind_display_matches_as_str() {
923        crate::tagged_union::assert_display_matches_label::<IntentKind>();
924    }
925
926    /// CANONICAL-KEY CONTRACT: each variant's `as_str()` matches the
927    /// camelCase serde field name on `Intent`. A future rename of
928    /// any field lands here at one site — and the `Empty` diagnostic
929    /// composed from `INTENT_KIND_LIST` stays coherent with the
930    /// wire format.
931    ///
932    /// Routes through the substrate primitive
933    /// [`crate::tagged_union::assert_single_slot_key_matches_label`],
934    /// which pins the exactly-one-key + name-equality projection
935    /// byte-identically for every `<T: TaggedUnion + Serialize>`
936    /// implementor — the wire-alignment testkit shared with the sibling
937    /// `encapsulation_target_as_str_matches_field_name` /
938    /// `artifact_kind_as_str_matches_field_name` /
939    /// `channel_kind_as_str_matches_field_name` sites. Pre-lift the
940    /// four bodies each restated the same serialize-and-inspect sweep
941    /// at the test surface (three through a weaker YAML-substring
942    /// check; this site alone through the strong JSON-object exactly-
943    /// one form); post-lift the projection lives at ONE substrate
944    /// primitive and every site binds through a single call — the
945    /// three YAML sites simultaneously upgrade to the strong exactly-
946    /// one form.
947    #[test]
948    fn intent_kind_as_str_matches_intent_field_name() {
949        crate::tagged_union::assert_single_slot_key_matches_label::<Intent, _>(single_slot_intent);
950    }
951
952    /// ROUND-TRIP CONTRACT: `IntentKind::select(intent).map(|v|
953    /// v.kind()) == Some(kind)`. The reverse `IntentVariant::kind`
954    /// projection composes the closed set in both directions — a
955    /// regression that misroutes a select arm (e.g. `Self::Nix =>
956    /// intent.flux.as_ref()...`) fails loudly here.
957    ///
958    /// Routes through the substrate primitive
959    /// [`crate::tagged_union::assert_variant_round_trip`], which
960    /// composes [`crate::tagged_union::VariantSelector::select`]
961    /// (forward) with [`crate::tagged_union::VariantKind::variant_kind`]
962    /// (reverse) byte-identically for every `<T: TaggedUnion>`
963    /// implementor — the round-trip testkit shared with the sibling
964    /// `artifact_kind_round_trips_through_variant_kind` /
965    /// `channel_kind_round_trips_through_variant_kind` /
966    /// `encapsulation_target_round_trips_through_variant_target`
967    /// sites. Pre-lift the four bodies each restated the same
968    /// two-arm round-trip probe at the test surface; post-lift the
969    /// projection lives at ONE substrate primitive and every site
970    /// binds through a single call.
971    #[test]
972    fn intent_kind_round_trips_through_variant_kind() {
973        crate::tagged_union::assert_variant_round_trip::<Intent, _>(single_slot_intent);
974    }
975
976    /// PRESENCE-PROBE WIRE CONTRACT: the `intent-<kind>` require-tag
977    /// dispatcher in `tatara-check` (`bin/tatara-check.rs`) parses
978    /// each suffix via `IntentKind::from_str` and dispatches through
979    /// the substrate primitive `Intent::has` (a one-line inherent
980    /// forwarder over [`crate::tagged_union::TaggedUnion::has`]).
981    /// Pre-lift the dispatcher restated five hand-authored
982    /// `spec.intent.<field>.is_some()` arms whose per-field addressing
983    /// drifted from `IntentKind::ALL` (the sixth variant `Guest` had
984    /// no `intent-guest` arm at all); post-lift adding a seventh
985    /// variant to `IntentKind` lands the corresponding `intent-<kind>`
986    /// tag automatically — the sweep here pins that every
987    /// `IntentKind` roundtrips through the `intent-{as_str}` wire
988    /// key, and that `Intent::has(k)` fires exactly on the populated
989    /// slot addressed by `k`.
990    #[test]
991    fn intent_has_dispatches_through_wire_key_across_every_kind() {
992        for populated in IntentKind::ALL {
993            let intent = single_slot_intent(populated);
994            for probed in IntentKind::ALL {
995                let wire_key = format!("intent-{}", probed.as_str());
996                let parsed: IntentKind = wire_key
997                    .strip_prefix("intent-")
998                    .expect("wire key composes as intent-<as_str>")
999                    .parse()
1000                    .expect("as_str→from_str round trip pinned by DeriveClosedSet");
1001                assert_eq!(parsed, probed);
1002                let expected = probed == populated;
1003                assert_eq!(
1004                    intent.has(probed),
1005                    expected,
1006                    "Intent::has drift — populated={populated:?} probed={probed:?}",
1007                );
1008            }
1009        }
1010    }
1011
1012    /// EMPTY-DIAGNOSTIC CONTRACT: the closed-set kind list embedded
1013    /// in `IntentError::Empty` echoes the canonical join of every
1014    /// `IntentKind::as_str()` projection. A variant added without
1015    /// updating `INTENT_KIND_LIST` (or a renamed variant) shows up
1016    /// here as a mismatch.
1017    ///
1018    /// Routes through the substrate primitive
1019    /// [`crate::tagged_union::assert_kind_list_matches_closed_set`],
1020    /// which composes `<T::Kind as ClosedSet>::labels_joined("/")`
1021    /// against `<T as TaggedUnion>::KIND_LIST` byte-identically for
1022    /// every implementor — the diagnostic-stability testkit shared
1023    /// with the sibling `artifact_error_empty_lists_every_kind_in_canonical_order`
1024    /// / `channel_error_empty_lists_every_kind_in_canonical_order`
1025    /// / `encapsulation_kind_error_empty_lists_every_target_in_canonical_order`
1026    /// sites. Pre-lift the four bodies each restated the same
1027    /// two-argument `assert_eq!(<XxxKind as ClosedSet>::labels_joined("/"),
1028    /// XXX_KIND_LIST)` comparison at the test surface; post-lift
1029    /// the projection lives at ONE substrate primitive and every
1030    /// site binds through a single call.
1031    #[test]
1032    fn intent_error_empty_lists_every_kind_in_canonical_order() {
1033        crate::tagged_union::assert_kind_list_matches_closed_set::<Intent>();
1034    }
1035
1036    /// CANONICAL-BYTES CONTRACT: every populated variant yields the
1037    /// SAME bytes as `serde_json::to_vec` on the inner reference.
1038    /// Pins the lift of the parallel observe-mode match in
1039    /// `tatara-reconciler::render` to this single method.
1040    #[test]
1041    fn intent_variant_canonical_bytes_matches_inner_serialize() {
1042        for kind in IntentKind::ALL {
1043            let i = single_slot_intent(kind);
1044            let v = i.variant().expect("exactly-one variant");
1045            let via_method = v.canonical_bytes();
1046            let expected: Vec<u8> = match &v {
1047                IntentVariant::Nix(n) => serde_json::to_vec(n).unwrap_or_default(),
1048                IntentVariant::Flux(f) => serde_json::to_vec(f).unwrap_or_default(),
1049                IntentVariant::Lisp(l) => serde_json::to_vec(l).unwrap_or_default(),
1050                IntentVariant::Container(c) => serde_json::to_vec(c).unwrap_or_default(),
1051                IntentVariant::Aplicacao(a) => serde_json::to_vec(a).unwrap_or_default(),
1052                IntentVariant::Guest(g) => serde_json::to_vec(g).unwrap_or_default(),
1053            };
1054            assert_eq!(
1055                via_method, expected,
1056                "canonical_bytes mismatch for {kind:?}"
1057            );
1058            assert!(!via_method.is_empty(), "{kind:?} produced empty bytes");
1059        }
1060    }
1061
1062    /// Construct an `Intent` with two slots populated — drives the
1063    /// pairwise `Ambiguous` sweep through the substrate primitive
1064    /// [`crate::tagged_union::assert_two_slots_ambiguous`]. Composes
1065    /// the single-slot constructor on top of itself per-field so ONE
1066    /// source of truth for per-variant inner payloads is preserved.
1067    /// Mirrors `two_slot_source` / `two_slot_channel` / `two_slot_kind`
1068    /// in shape across `ProcessSpec`'s tagged-union axis.
1069    fn two_slot_intent(a: IntentKind, b: IntentKind) -> Intent {
1070        let ia = single_slot_intent(a);
1071        let ib = single_slot_intent(b);
1072        Intent {
1073            nix: ia.nix.or(ib.nix),
1074            flux: ia.flux.or(ib.flux),
1075            lisp: ia.lisp.or(ib.lisp),
1076            container: ia.container.or(ib.container),
1077            aplicacao: ia.aplicacao.or(ib.aplicacao),
1078            guest: ia.guest.or(ib.guest),
1079        }
1080    }
1081
1082    /// Construct an `Intent` with exactly the given kind's slot
1083    /// populated by a minimal valid inner spec. Shared across the
1084    /// closed-set property tests so they each cover every variant
1085    /// without restating the construction table.
1086    fn single_slot_intent(kind: IntentKind) -> Intent {
1087        match kind {
1088            IntentKind::Nix => Intent {
1089                nix: Some(NixIntent {
1090                    flake_ref: "github:a/b".into(),
1091                    attribute: "x".into(),
1092                    system: None,
1093                    attic_cache: None,
1094                    extra_args: vec![],
1095                    delegate_to_nix_build: false,
1096                }),
1097                ..Intent::default()
1098            },
1099            IntentKind::Flux => Intent {
1100                flux: Some(FluxIntent {
1101                    git_repository: "g".into(),
1102                    path: "p".into(),
1103                    git_repository_namespace: None,
1104                    target_namespace: None,
1105                    decrypt_sops: true,
1106                    helm_chart: None,
1107                    helm_values: None,
1108                }),
1109                ..Intent::default()
1110            },
1111            IntentKind::Lisp => Intent {
1112                lisp: Some(LispIntent {
1113                    source: "()".into(),
1114                    reader: "tatara-lisp".into(),
1115                    version: "v1".into(),
1116                    bindings: BTreeMap::new(),
1117                }),
1118                ..Intent::default()
1119            },
1120            IntentKind::Container => Intent {
1121                container: Some(ContainerIntent {
1122                    image: "ghcr.io/x:1".into(),
1123                    replicas: Some(1),
1124                    command: vec![],
1125                    args: vec![],
1126                    env: BTreeMap::new(),
1127                    workload_kind: WorkloadKind::default(),
1128                }),
1129                ..Intent::default()
1130            },
1131            IntentKind::Aplicacao => Intent {
1132                aplicacao: Some(AplicacaoIntent::chart_only("oci://ghcr.io/x", "0.1.0")),
1133                ..Intent::default()
1134            },
1135            IntentKind::Guest => Intent {
1136                guest: Some(GuestIntent {
1137                    spec: serde_json::json!({"name": "guest-1"}),
1138                    state_dir: None,
1139                    allow_remote_build: None,
1140                }),
1141                ..Intent::default()
1142            },
1143        }
1144    }
1145
1146    // ── closed-set algebra for WorkloadKind (ALL × as_str × Display ×
1147    //    FromStr × api_version × is_batch) ─────────────────────────────
1148
1149    /// Structural well-formedness of [`WorkloadKind`] as a
1150    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
1151    /// testkit lift that pins all three structural invariants (`ALL`
1152    /// is non-empty, every variant round-trips through `label ↔
1153    /// parse_label`, labels are pairwise distinct, `""` is outside the
1154    /// closed set) at ONE call site. Replaces the hand-derived
1155    /// `workload_kind_all_is_unique_and_complete` +
1156    /// `workload_kind_roundtrip_via_as_str` + the empty-input arm of
1157    /// `unknown_workload_kind_errors`. `FromStr` delegates to
1158    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
1159    /// exercises the same code path the reconciler hits when parsing a
1160    /// K8s `kind:`-shaped value back to the typed workload kind.
1161    #[test]
1162    fn workload_kind_is_well_formed_closed_set() {
1163        tatara_closed_set::assert_closed_set_well_formed::<WorkloadKind>();
1164    }
1165
1166    /// CANONICAL-KEY CONTRACT: every variant's `as_str()` matches serde's
1167    /// PascalCase output verbatim. A future variant rename (or an
1168    /// `as_str` arm typo) lands at one site, instead of drifting
1169    /// between the typed surface, the K8s `kind:` manifest field, and
1170    /// the YAML wire format the reconciler / operator both read.
1171    #[test]
1172    fn workload_kind_as_str_matches_serde() {
1173        crate::tagged_union::assert_label_matches_serde_serialization::<WorkloadKind>();
1174    }
1175
1176    /// The Display impl IS `as_str` — pinning this lets future callers
1177    /// reach for either projection without drift. If a reviewer
1178    /// accidentally re-introduces an inline match in Display, this
1179    /// test would fail the moment a variant rename touches one site
1180    /// but not the other.
1181    #[test]
1182    fn workload_kind_display_matches_as_str() {
1183        crate::tagged_union::assert_display_matches_label::<WorkloadKind>();
1184    }
1185
1186    /// `FromStr` rejects strings that aren't in the canonical
1187    /// projection — lowercased / typo / unrelated — and the error
1188    /// echoes the input verbatim so the operator-facing diagnostic
1189    /// carries the offending value, not a normalized form. The
1190    /// empty-input arm is pinned by
1191    /// [`workload_kind_is_well_formed_closed_set`] via the
1192    /// `tatara_lisp::ClosedSet` testkit; the cases here pin the
1193    /// verbatim-echo contract on the [`UnknownWorkloadKind`]
1194    /// newtype, which the trait's `make_unknown` can't see.
1195    #[test]
1196    fn unknown_workload_kind_errors() {
1197        use std::str::FromStr;
1198        for bad in ["deployment", "JOB", "ReplicaSet", "Pod"] {
1199            let err = WorkloadKind::from_str(bad).unwrap_err();
1200            assert_eq!(err.0, bad, "error payload should echo input verbatim");
1201        }
1202    }
1203
1204    #[test]
1205    fn workload_kind_default_is_deployment() {
1206        assert_eq!(WorkloadKind::default(), WorkloadKind::Deployment);
1207    }
1208
1209    /// TRUTH-TABLE CONTRACT: `api_version` / `is_batch` agree with the
1210    /// documented (kind) -> (apiVersion, is_batch) table for every
1211    /// variant. A new variant in `WorkloadKind` without extending
1212    /// either projection's match is caught by the compiler (closed-set
1213    /// match in each method); adding a variant without extending its
1214    /// truth row is caught here. Also pins the invariant
1215    /// `is_batch <=> api_version == "batch/v1"`, so a future renderer
1216    /// can route on either projection without re-deriving the partition.
1217    #[test]
1218    fn workload_kind_projection_truth_table() {
1219        let table: &[(WorkloadKind, &str, bool)] = &[
1220            // (kind, api_version, is_batch)
1221            (WorkloadKind::Deployment, "apps/v1", false),
1222            (WorkloadKind::StatefulSet, "apps/v1", false),
1223            (WorkloadKind::DaemonSet, "apps/v1", false),
1224            (WorkloadKind::Job, "batch/v1", true),
1225            (WorkloadKind::CronJob, "batch/v1", true),
1226        ];
1227        assert_eq!(table.len(), WorkloadKind::ALL.len());
1228        for (kind, api, batch) in table {
1229            assert_eq!(kind.api_version(), *api, "api_version drift for {kind:?}");
1230            assert_eq!(kind.is_batch(), *batch, "is_batch drift for {kind:?}");
1231            assert_eq!(
1232                kind.is_batch(),
1233                kind.api_version() == "batch/v1",
1234                "is_batch / api_version partition disagrees for {kind:?}"
1235            );
1236        }
1237    }
1238
1239    #[test]
1240    fn aplicacao_plus_flux_is_ambiguous() {
1241        let i = Intent {
1242            aplicacao: Some(AplicacaoIntent::chart_only("x", "1")),
1243            flux: Some(FluxIntent {
1244                git_repository: "g".into(),
1245                path: "p".into(),
1246                git_repository_namespace: None,
1247                target_namespace: None,
1248                decrypt_sops: true,
1249                helm_chart: None,
1250                helm_values: None,
1251            }),
1252            ..Intent::default()
1253        };
1254        assert_eq!(i.variant().unwrap_err(), IntentError::Ambiguous);
1255    }
1256
1257    // ── Helm lifecycle policy — install / upgrade slot substrate ────
1258
1259    fn helm_intent(install_timeout: Option<&str>) -> AplicacaoIntent {
1260        AplicacaoIntent {
1261            install_timeout: install_timeout.map(str::to_string),
1262            ..AplicacaoIntent::chart_only("oci://ghcr.io/pleme-io/charts/lareira-demo-app", "0.5.5")
1263        }
1264    }
1265
1266    /// The workspace-wide default timeout const is pinned to `25m`.
1267    /// A regression that renamed it to any other duration would
1268    /// silently misroute every Helm-driven Process's default retry
1269    /// budget, so pin the byte-exact spelling here rather than at
1270    /// every consumer's own callsite.
1271    #[test]
1272    fn helm_lifecycle_default_timeout_is_pinned_to_25m() {
1273        assert_eq!(HELM_LIFECYCLE_DEFAULT_TIMEOUT, "25m");
1274    }
1275
1276    /// The workspace-wide default retries const is pinned to `3`.
1277    /// Peer to the `_timeout` pin; same rationale.
1278    #[test]
1279    fn helm_lifecycle_default_retries_is_pinned_to_three() {
1280        assert_eq!(HELM_LIFECYCLE_DEFAULT_RETRIES, 3);
1281    }
1282
1283    /// Fallback branch of the primitive: an intent that omitted
1284    /// `install_timeout` picks up the workspace-wide default
1285    /// (`25m` + retries `3`). Pin binds the "no override" shape
1286    /// every render / snapshot / dashboard consumer sees today.
1287    #[test]
1288    fn helm_lifecycle_policy_defaults_when_install_timeout_is_none() {
1289        let policy = helm_intent(None).helm_lifecycle_policy();
1290        assert_eq!(policy.timeout, HELM_LIFECYCLE_DEFAULT_TIMEOUT);
1291        assert_eq!(policy.remediation.retries, HELM_LIFECYCLE_DEFAULT_RETRIES);
1292    }
1293
1294    /// Override branch of the primitive: when the operator populated
1295    /// `install_timeout`, the primitive substitutes that string
1296    /// verbatim (no normalization, no trimming) — the reconciler
1297    /// hands the exact `humantime` shape to Flux, and any parse
1298    /// error surfaces from the chart-controller, not from here.
1299    #[test]
1300    fn helm_lifecycle_policy_uses_install_timeout_when_present() {
1301        for shape in ["10m", "1h30m", "5s", "25m", "0s"] {
1302            let policy = helm_intent(Some(shape)).helm_lifecycle_policy();
1303            assert_eq!(
1304                policy.timeout, shape,
1305                "override shape {shape} not substituted verbatim"
1306            );
1307            // Retries stay at the workspace default regardless of timeout.
1308            assert_eq!(policy.remediation.retries, HELM_LIFECYCLE_DEFAULT_RETRIES);
1309        }
1310    }
1311
1312    /// Coherence axis: the retries slot is invariant across every
1313    /// timeout shape the operator might publish — a regression that
1314    /// coupled the two slots (e.g. "when timeout is short, retry
1315    /// more") surfaces here rather than at every consumer.
1316    #[test]
1317    fn helm_lifecycle_policy_retries_are_invariant_across_timeout_shapes() {
1318        let seen: std::collections::BTreeSet<u8> = [None, Some("1m"), Some("25m"), Some("2h")]
1319            .into_iter()
1320            .map(|t| helm_intent(t).helm_lifecycle_policy().remediation.retries)
1321            .collect();
1322        assert_eq!(
1323            seen.len(),
1324            1,
1325            "retries should be constant across timeout shapes"
1326        );
1327        assert_eq!(
1328            seen.into_iter().next(),
1329            Some(HELM_LIFECYCLE_DEFAULT_RETRIES)
1330        );
1331    }
1332
1333    /// Wire-shape pin: the serde projection matches Flux
1334    /// `HelmRelease.spec.{install,upgrade}` v2 byte-identically —
1335    /// `{"timeout": <string>, "remediation": {"retries": <int>}}`
1336    /// with no extra keys, no field renames, no camelCase surprises.
1337    /// A regression that added a slot to `HelmLifecyclePolicy` or
1338    /// renamed one would fail here rather than as a Flux CR
1339    /// rejection at every deployment.
1340    #[test]
1341    fn helm_lifecycle_policy_serializes_to_flux_hr_v2_install_upgrade_shape() {
1342        let policy = helm_intent(Some("10m")).helm_lifecycle_policy();
1343        let json = serde_json::to_value(&policy).unwrap();
1344        assert_eq!(
1345            json,
1346            serde_json::json!({
1347                "timeout": "10m",
1348                "remediation": { "retries": 3 },
1349            }),
1350        );
1351    }
1352
1353    /// Coherence axis: `HelmLifecyclePolicy::workspace_default()`
1354    /// composes byte-identically to the intent-derived policy of an
1355    /// intent with `install_timeout: None` — the two paths to the
1356    /// substrate default (via the `Aplicacao` intent's own resolver
1357    /// vs the standalone workspace-default constructor) yield the
1358    /// same shape. Binds the "workspace_default IS the fallback"
1359    /// invariant so a future divergence (e.g. workspace_default
1360    /// changes but the intent resolver's inline fallback does not)
1361    /// surfaces here rather than as a silent drift at every render
1362    /// callsite.
1363    #[test]
1364    fn helm_lifecycle_policy_workspace_default_matches_intent_fallback_branch() {
1365        let default_policy = HelmLifecyclePolicy::workspace_default();
1366        let intent_policy = helm_intent(None).helm_lifecycle_policy();
1367        assert_eq!(default_policy, intent_policy);
1368    }
1369
1370    // ── Flux reconcile interval — OCIRepository + HelmRelease shared ─
1371
1372    /// The workspace-wide default Flux reconcile-interval const is
1373    /// pinned to `5m`. A regression that renamed it would silently
1374    /// throttle or hammer every Helm-driven Process's OCIRepository
1375    /// pull cadence AND its HelmRelease reconcile cadence, so pin
1376    /// the byte-exact spelling here rather than at the two render
1377    /// callsites the primitive owns.
1378    #[test]
1379    fn flux_helm_default_interval_is_pinned_to_5m() {
1380        assert_eq!(FLUX_HELM_DEFAULT_INTERVAL, "5m");
1381    }
1382
1383    /// The intent-side composer returns the workspace-wide default
1384    /// verbatim today. A regression that hand-authored some other
1385    /// string here (or that stopped routing through the const)
1386    /// would surface at this pin.
1387    #[test]
1388    fn flux_reconcile_interval_returns_workspace_default() {
1389        assert_eq!(
1390            helm_intent(None).flux_reconcile_interval(),
1391            FLUX_HELM_DEFAULT_INTERVAL,
1392        );
1393    }
1394
1395    /// Coherence axis: the reconcile interval is invariant across
1396    /// every `install_timeout` shape the operator publishes today.
1397    /// Pre-lift the two slots were siblings hand-authored with the
1398    /// same `"5m"` value regardless of any other AplicacaoIntent
1399    /// shape; post-lift the same invariance holds through the
1400    /// composer. A future coupling (e.g. "when timeout is short,
1401    /// reconcile more often") lands at the composer's shape, not
1402    /// silently at any render callsite.
1403    #[test]
1404    fn flux_reconcile_interval_is_invariant_across_install_timeout_shapes() {
1405        let seen: std::collections::BTreeSet<String> =
1406            [None, Some("10m"), Some("1h30m"), Some("25m"), Some("2h")]
1407                .into_iter()
1408                .map(|t| helm_intent(t).flux_reconcile_interval())
1409                .collect();
1410        assert_eq!(
1411            seen.len(),
1412            1,
1413            "reconcile interval should be constant across install_timeout shapes"
1414        );
1415        assert_eq!(
1416            seen.into_iter().next().as_deref(),
1417            Some(FLUX_HELM_DEFAULT_INTERVAL),
1418        );
1419    }
1420
1421    // ─── AplicacaoIntent::chart_only substrate pins ─────────────────
1422    //
1423    // Bind the chart-pointer-only composer at fail-before-pass-after
1424    // granularity so a regression that drifted any of the five
1425    // default-tail slots (profile → non-empty, values_overlay → non-
1426    // `Null`, any of the three `Option<String>` slots → `Some`),
1427    // reshaped the two-argument surface, or swapped the positional
1428    // slot order surfaces HERE rather than as silent fixture skew at
1429    // the 14 downstream consumers.
1430
1431    #[test]
1432    fn chart_only_binds_two_caller_slots_and_defaults_the_other_five() {
1433        // Primary shape asserted end-to-end: the returned value
1434        // carries the caller-supplied `(chart_ref, version)` and the
1435        // K8s-schema-default `("", Null, None, None, None)` tail. A
1436        // regression that swapped the two positional slots would
1437        // land `"1"` in `chart_ref` and `"oci://x"` in `version`;
1438        // the byte-equality pin below catches that.
1439        let a = AplicacaoIntent::chart_only("oci://x", "1");
1440        assert_eq!(a.chart_ref, "oci://x");
1441        assert_eq!(a.version, "1");
1442        assert_eq!(a.profile, "");
1443        assert_eq!(a.values_overlay, serde_json::Value::Null);
1444        assert!(a.release_name.is_none());
1445        assert!(a.target_namespace.is_none());
1446        assert!(a.install_timeout.is_none());
1447    }
1448
1449    #[test]
1450    fn chart_only_matches_hand_authored_pre_lift_struct_literal_shape() {
1451        // Byte-identical parity with the pre-lift 7-slot struct-
1452        // literal every one of the 14 hand-authored sites restated.
1453        // A regression that drifted the composer would surface HERE
1454        // rather than as silent fixture skew at every downstream
1455        // `empty_template` / `sample_intent_for` / `helm_intent`
1456        // consumer. Swept across the three representative
1457        // `(chart_ref, version)` shape families the pre-lift sites
1458        // used (fixture stub `oci://x`/`1`; sample `oci://ghcr.io/x`
1459        // / `0.1.0`; production non-OCI `pleme-io/lareira-demo-app`
1460        // / `0.5.5`).
1461        for (chart_ref, version) in [
1462            ("oci://x", "1"),
1463            ("oci://ghcr.io/x", "0.1.0"),
1464            ("pleme-io/lareira-demo-app", "0.5.5"),
1465            ("x", "1"),
1466        ] {
1467            let composed = AplicacaoIntent::chart_only(chart_ref, version);
1468            let hand_authored = AplicacaoIntent {
1469                chart_ref: chart_ref.into(),
1470                version: version.into(),
1471                profile: String::new(),
1472                values_overlay: serde_json::Value::Null,
1473                release_name: None,
1474                target_namespace: None,
1475                install_timeout: None,
1476            };
1477            assert_eq!(
1478                serde_json::to_value(&composed).unwrap(),
1479                serde_json::to_value(&hand_authored).unwrap(),
1480                "composed and hand-authored must agree for ({chart_ref}, {version})"
1481            );
1482        }
1483    }
1484
1485    #[test]
1486    fn chart_only_accepts_string_and_str_uniformly() {
1487        // The `impl Into<String>` argument form matches both the
1488        // pre-lift `"literal".into()` shape AND callers with a live
1489        // `String` (e.g. a fixture parameter). A regression that
1490        // narrowed the argument type to `&str` or `String` would
1491        // break one of the two shapes; this pin binds both.
1492        let owned_chart = String::from("oci://y");
1493        let owned_version = String::from("2");
1494        let via_string = AplicacaoIntent::chart_only(owned_chart.clone(), owned_version.clone());
1495        let via_str = AplicacaoIntent::chart_only("oci://y", "2");
1496        assert_eq!(
1497            serde_json::to_value(&via_string).unwrap(),
1498            serde_json::to_value(&via_str).unwrap(),
1499        );
1500    }
1501
1502    // ── AplicacaoIntent::{release_name,target_namespace}_or pins ───
1503    //
1504    // Bind the (override, fallback) fallback-composer pair at
1505    // fail-before-pass-after granularity so a regression that flipped
1506    // the branch order (fallback wins when override is Some), dropped
1507    // the `.clone()` on the override, dropped the lazy branch on the
1508    // fallback, or swapped the two field slots surfaces HERE rather
1509    // than as silent drift at the two production consumers
1510    // (`tatara-reconciler::render::render_aplicacao` and
1511    // `tatara-process::matrix::EnvMatrixSpec::breathe_bands`).
1512
1513    #[test]
1514    fn release_name_or_returns_override_when_set() {
1515        let mut a = AplicacaoIntent::chart_only("oci://x", "1");
1516        a.release_name = Some("operator-picked".into());
1517        assert_eq!(a.release_name_or("fallback-pid"), "operator-picked");
1518    }
1519
1520    #[test]
1521    fn release_name_or_returns_fallback_when_unset() {
1522        let a = AplicacaoIntent::chart_only("oci://x", "1");
1523        assert!(a.release_name.is_none());
1524        assert_eq!(a.release_name_or("fallback-pid"), "fallback-pid");
1525    }
1526
1527    #[test]
1528    fn target_namespace_or_returns_override_when_set() {
1529        let mut a = AplicacaoIntent::chart_only("oci://x", "1");
1530        a.target_namespace = Some("operator-picked".into());
1531        assert_eq!(a.target_namespace_or("fallback-ns"), "operator-picked");
1532    }
1533
1534    #[test]
1535    fn target_namespace_or_returns_fallback_when_unset() {
1536        let a = AplicacaoIntent::chart_only("oci://x", "1");
1537        assert!(a.target_namespace.is_none());
1538        assert_eq!(a.target_namespace_or("fallback-ns"), "fallback-ns");
1539    }
1540
1541    #[test]
1542    fn release_name_and_target_namespace_or_are_independent_across_all_four_shapes() {
1543        // Coherence axis: the two fallback slots are independent —
1544        // any of the four (release_name, target_namespace) ∈
1545        // {None, Some} shapes projects the expected pair with no
1546        // cross-slot bleed. A regression that keyed one field off
1547        // the other's `Option` state would surface HERE.
1548        for (rn, tn) in [
1549            (None, None),
1550            (Some("r".to_string()), None),
1551            (None, Some("t".to_string())),
1552            (Some("r".to_string()), Some("t".to_string())),
1553        ] {
1554            let mut a = AplicacaoIntent::chart_only("oci://x", "1");
1555            a.release_name = rn.clone();
1556            a.target_namespace = tn.clone();
1557            let got_rn = a.release_name_or("rn-fb");
1558            let got_tn = a.target_namespace_or("tn-fb");
1559            let want_rn = rn.clone().unwrap_or_else(|| "rn-fb".into());
1560            let want_tn = tn.clone().unwrap_or_else(|| "tn-fb".into());
1561            assert_eq!(got_rn, want_rn, "release_name_or for ({rn:?}, {tn:?})");
1562            assert_eq!(got_tn, want_tn, "target_namespace_or for ({rn:?}, {tn:?})");
1563        }
1564    }
1565
1566    #[test]
1567    fn release_name_or_matches_hand_authored_pre_lift_option_clone_unwrap_or_else_shape() {
1568        // Byte-identical parity with the two pre-lift call shapes.
1569        // A regression that drifted the composer would surface HERE
1570        // rather than as silent skew at either production site.
1571        for override_ in [None, Some("op".to_string())] {
1572            let mut a = AplicacaoIntent::chart_only("oci://x", "1");
1573            a.release_name = override_.clone();
1574            let via_primitive = a.release_name_or("fb");
1575            let hand_authored = a.release_name.clone().unwrap_or_else(|| "fb".into());
1576            assert_eq!(via_primitive, hand_authored);
1577        }
1578        for override_ in [None, Some("op".to_string())] {
1579            let mut a = AplicacaoIntent::chart_only("oci://x", "1");
1580            a.target_namespace = override_.clone();
1581            let via_primitive = a.target_namespace_or("fb");
1582            let hand_authored = a.target_namespace.clone().unwrap_or_else(|| "fb".into());
1583            assert_eq!(via_primitive, hand_authored);
1584        }
1585    }
1586
1587    #[test]
1588    fn chart_only_composes_downstream_through_helm_lifecycle_policy_default_branch() {
1589        // Cross-primitive coherence pin: an `AplicacaoIntent` built
1590        // through `chart_only` has `install_timeout = None` and
1591        // therefore rides the workspace-default branch of
1592        // `helm_lifecycle_policy`. A regression that flipped
1593        // `install_timeout` to `Some(_)` at the composer would
1594        // silently un-default every downstream Helm policy; this
1595        // pin binds the default-branch composition end-to-end.
1596        let a = AplicacaoIntent::chart_only("oci://x", "1");
1597        let policy = a.helm_lifecycle_policy();
1598        assert_eq!(policy.timeout, HELM_LIFECYCLE_DEFAULT_TIMEOUT);
1599        assert_eq!(policy.remediation.retries, HELM_LIFECYCLE_DEFAULT_RETRIES);
1600    }
1601}