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    /// `serde_json::to_vec` on the inner reference, with an empty
77    /// fallback that matches the pre-lift Observe-mode shape in
78    /// `tatara-reconciler::render`. ONE site owns the per-variant
79    /// serialization so adding a 7th variant requires only the
80    /// arm here, not the parallel match the pre-lift Observe arm
81    /// carried.
82    pub fn canonical_bytes(&self) -> Vec<u8> {
83        match self {
84            Self::Nix(n) => serde_json::to_vec(n).unwrap_or_default(),
85            Self::Flux(f) => serde_json::to_vec(f).unwrap_or_default(),
86            Self::Lisp(l) => serde_json::to_vec(l).unwrap_or_default(),
87            Self::Container(c) => serde_json::to_vec(c).unwrap_or_default(),
88            Self::Aplicacao(a) => serde_json::to_vec(a).unwrap_or_default(),
89            Self::Guest(g) => serde_json::to_vec(g).unwrap_or_default(),
90        }
91    }
92}
93
94impl crate::tagged_union::VariantKind<IntentKind> for IntentVariant<'_> {
95    fn variant_kind(&self) -> IntentKind {
96        self.kind()
97    }
98}
99
100/// Closed-set discriminator over `Intent`'s six tagged-union slots.
101/// Single source of truth that drives `Intent::variant`'s ambiguity
102/// + emptiness resolver, the `IntentError::Empty` message, and the
103/// reverse `IntentVariant::kind` projection. Adding a 7th intent
104/// variant lands at one `ALL` entry + one `as_str` arm + one
105/// `select` arm + one `IntentVariant::kind` arm — exhaustively
106/// checked by the compiler.
107#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
108#[closed_set(via = "as_str", generate_unknown, display)]
109pub enum IntentKind {
110    Nix,
111    Flux,
112    Lisp,
113    Container,
114    Aplicacao,
115    Guest,
116}
117
118impl IntentKind {
119    /// The closed set of intent kinds — single source of truth that
120    /// drives `Intent::variant`'s sweep so a variant added without
121    /// an `ALL` entry never reaches the resolver.
122    pub const ALL: [Self; 6] = [
123        Self::Nix,
124        Self::Flux,
125        Self::Lisp,
126        Self::Container,
127        Self::Aplicacao,
128        Self::Guest,
129    ];
130
131    /// Canonical lower-case wire-format key — matches the serde
132    /// `rename_all = "camelCase"` field name on `Intent`. The
133    /// `IntentError::Empty` message composes the human-readable
134    /// list from this projection so a new variant lands in the
135    /// operator-facing diagnostic automatically via the `ALL`
136    /// sweep, not via hand-maintained error-string drift.
137    pub const fn as_str(self) -> &'static str {
138        match self {
139            Self::Nix => "nix",
140            Self::Flux => "flux",
141            Self::Lisp => "lisp",
142            Self::Container => "container",
143            Self::Aplicacao => "aplicacao",
144            Self::Guest => "guest",
145        }
146    }
147
148    /// Project an `Intent` borrow into the optional typed variant
149    /// view for this kind. Returns `None` iff the matching slot is
150    /// `None`. Composes the closed-set sweep `Intent::variant`
151    /// loops over.
152    pub fn select<'a>(self, intent: &'a Intent) -> Option<IntentVariant<'a>> {
153        match self {
154            Self::Nix => intent.nix.as_ref().map(IntentVariant::Nix),
155            Self::Flux => intent.flux.as_ref().map(IntentVariant::Flux),
156            Self::Lisp => intent.lisp.as_ref().map(IntentVariant::Lisp),
157            Self::Container => intent.container.as_ref().map(IntentVariant::Container),
158            Self::Aplicacao => intent.aplicacao.as_ref().map(IntentVariant::Aplicacao),
159            Self::Guest => intent.guest.as_ref().map(IntentVariant::Guest),
160        }
161    }
162}
163
164crate::declare_tagged_union_error! {
165    pub IntentError,
166    empty = "intent has no variant set (one of {0} required)",
167    ambiguous = "intent has multiple variants set; exactly one required",
168}
169
170/// Slash-joined list of every `IntentKind::as_str()` — composed once
171/// at compile time so `IntentError::Empty`'s diagnostic carries the
172/// closed-set summary without per-variant string drift. Pinned against
173/// the canonical [`tatara_lisp::ClosedSet::labels_joined`] projection
174/// by `intent_error_empty_lists_every_kind_in_canonical_order`, so a
175/// regression that drifts this `&'static str` constant from the
176/// `IntentKind::ALL × as_str` composition fails-loudly at the test
177/// site without per-variant inline materialization.
178pub(crate) const INTENT_KIND_LIST: &str = "nix/flux/lisp/container/aplicacao/guest";
179
180// `impl FromStr for IntentKind` +
181// `impl tatara_lisp::ClosedSet for IntentKind` +
182// `impl fmt::Display for IntentKind` +
183// `pub struct UnknownIntentKind(pub String)` are all generated by
184// `#[derive(tatara_closed_set::DeriveClosedSet)]` +
185// `#[closed_set(via = "as_str", generate_unknown, display)]` on the
186// enum declaration above. `label` delegates to the inherent
187// `IntentKind::as_str` — the camelCase wire-vocabulary projection
188// stays load-bearing (matches the serde `rename_all = "camelCase"`
189// field names on `Intent` AND the `IntentVariant::canonical_bytes`
190// per-variant arm), while generic `T: ClosedSet` consumers reach the
191// STABLE workspace-wide name (`label`). The auto-derived carrier
192// label "intent kind" matches the substrate-wide
193// `#[error("unknown intent kind: {0}")]` shape every sibling
194// closed-set carrier across `tatara-process` renders verbatim.
195// Symmetric to [`crate::intent::WorkloadKind`] (the workload-axis
196// sibling on the same `ProcessSpec` slice) and every other
197// `#[derive(DeriveClosedSet)]` implementor across the crate.
198
199crate::declare_tagged_union_impls! {
200    parent = Intent,
201    kind = IntentKind,
202    variant = IntentVariant,
203    error = IntentError,
204    kind_list = INTENT_KIND_LIST,
205}
206
207/// Nix-sourced intent — tatara-engine's nix_eval driver produces resources.
208#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
209#[serde(rename_all = "camelCase")]
210pub struct NixIntent {
211    /// Flake reference, e.g., `github:pleme-io/k8s?dir=shared/infrastructure`.
212    pub flake_ref: String,
213    /// Attribute path within the flake (e.g., `observability`).
214    pub attribute: String,
215    /// Target system. Defaults to the controller host's system.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub system: Option<String>,
218    /// Attic cache to push the resulting store path into.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub attic_cache: Option<String>,
221    /// Additional `nix build` arguments (e.g., `["--impure"]`).
222    #[serde(default)]
223    pub extra_args: Vec<String>,
224    /// Delegate the actual build to a sibling NixBuild CRD
225    /// (bridges to tatara-operator NATS bare-metal builder path).
226    #[serde(default)]
227    pub delegate_to_nix_build: bool,
228}
229
230/// FluxCD passthrough intent — reuse an existing GitRepository.
231#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
232#[serde(rename_all = "camelCase")]
233pub struct FluxIntent {
234    /// Name of an existing `GitRepository` (typically in `flux-system`).
235    pub git_repository: String,
236    /// Path inside the repository that the Kustomization will apply.
237    pub path: String,
238    /// Optional namespace of the GitRepository CR (defaults to `flux-system`).
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub git_repository_namespace: Option<String>,
241    /// Optional target namespace for the emitted Kustomization.
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub target_namespace: Option<String>,
244    /// SOPS decryption — defaults to true to match pleme-io conventions.
245    #[serde(default = "default_true")]
246    pub decrypt_sops: bool,
247    /// If set, additionally emit a HelmRelease for this chart.
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub helm_chart: Option<String>,
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub helm_values: Option<BTreeMap<String, serde_json::Value>>,
252}
253
254fn default_true() -> bool {
255    true
256}
257
258/// Lisp-sourced intent — tatara-lisp reader + macroexpander produces resources.
259#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
260#[serde(rename_all = "camelCase")]
261pub struct LispIntent {
262    /// Raw S-expression source, OR `include:<path>` / `configmap:<name>/<key>` pointer.
263    pub source: String,
264    /// Reader dialect / version tag.
265    #[serde(default = "default_reader")]
266    pub reader: String,
267    /// Macro form version.
268    #[serde(default = "default_version")]
269    pub version: String,
270    /// Symbols injected into the reader env (e.g., `cluster`, `region`).
271    #[serde(default)]
272    pub bindings: BTreeMap<String, serde_json::Value>,
273}
274
275fn default_reader() -> String {
276    "tatara-lisp".to_string()
277}
278fn default_version() -> String {
279    "v1".to_string()
280}
281
282/// Aplicacao intent — emit a FluxCD `HelmRelease` for a pleme-io
283/// typed Aplicacao chart. The chart owns its own sub-chart DAG;
284/// the reconciler only watches `HelmRelease.status.conditions[type=Ready]`.
285///
286/// This is the canonical handoff from caixa `(defaplicacao …)` declarations
287/// (which the typescape renders to this Intent) into in-cluster
288/// reconciliation. Closed-loop ephemeral test environments use this
289/// variant with `:lifetime :ephemeral` on the surrounding ProcessSpec.
290///
291/// Example (Lisp):
292/// ```lisp
293/// :intent (:aplicacao
294///           (:chart-ref "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
295///            :version "0.5.5"
296///            :profile "all-in-one"
297///            :values-overlay (:cluster (:name "ephemeral-test-01")
298///                             :persistence false
299///                             :compliance (:overlays []))))
300/// ```
301#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
302#[serde(rename_all = "camelCase")]
303pub struct AplicacaoIntent {
304    /// Helm chart reference. OCI (`oci://…`) or repo-relative (`pleme-io/lareira-demo-app`).
305    pub chart_ref: String,
306    /// Chart version (Helm semver constraint; `">=0.5.5"` allowed).
307    pub version: String,
308    /// Architecture profile from the chart's `values/*.yaml` family
309    /// (e.g. `all-in-one`, `saas-internal`).
310    /// Leave empty to use chart defaults.
311    #[serde(default, skip_serializing_if = "String::is_empty")]
312    pub profile: String,
313    /// Typed values overlay merged on top of the profile.
314    /// Free-form JSON to keep tatara-process decoupled from chart schemas.
315    #[serde(default)]
316    #[schemars(schema_with = "crate::schema_helpers::preserve_unknown_object")]
317    pub values_overlay: serde_json::Value,
318    /// HelmRelease name override. Defaults to the Process's PID-derived name.
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub release_name: Option<String>,
321    /// Target namespace for the chart. Defaults to the Process's namespace.
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub target_namespace: Option<String>,
324    /// Install timeout (`humantime` duration). Empty = chart-controller default.
325    #[serde(default, skip_serializing_if = "Option::is_none")]
326    pub install_timeout: Option<String>,
327}
328
329/// Workspace-wide default for the `timeout` slot on a Flux
330/// `HelmRelease.spec.{install,upgrade}` block, applied when the
331/// operator did not populate [`AplicacaoIntent::install_timeout`].
332/// Load-bearing on the reconciler's Helm-driven RENDER surface —
333/// [`AplicacaoIntent::helm_lifecycle_policy`] substitutes this exact
334/// string, and the reconciler's `render_aplicacao` byte-installs
335/// the resulting policy into both install AND upgrade slots.
336pub const HELM_LIFECYCLE_DEFAULT_TIMEOUT: &str = "25m";
337
338/// Workspace-wide default for the `remediation.retries` slot on a
339/// Flux `HelmRelease.spec.{install,upgrade}` block. Constant across
340/// both slots today; a future two-slot split (e.g. distinct retry
341/// budgets for a first install vs a rolling upgrade) lands as two
342/// consts here + a two-slot [`HelmLifecyclePolicy`] shape, not at
343/// the render callsite.
344pub const HELM_LIFECYCLE_DEFAULT_RETRIES: u8 = 3;
345
346/// Workspace-wide default for the reconcile-loop cadence on both Flux
347/// resources a Helm-driven `AplicacaoIntent` publishes today: the
348/// `OCIRepository.spec.interval` on the source side (how often the
349/// source-controller re-pulls the chart from OCI) and the
350/// `HelmRelease.spec.interval` on the release side (how often the
351/// helm-controller re-reconciles the release against the chart).
352/// The fleet convention ties both cadences to the same `5m` string
353/// today, so the substrate exposes ONE named const rather than two
354/// literals sprayed across `render_aplicacao`.
355///
356/// Peer to [`HELM_LIFECYCLE_DEFAULT_TIMEOUT`] on the same
357/// AplicacaoIntent-facing "workspace-wide Flux default" axis. A
358/// future per-slot divergence (`SOURCE_INTERVAL` vs `RELEASE_INTERVAL`
359/// as two consts, or a two-slot method returning a
360/// `FluxReconcileIntervals { source, release }` shape) lands here,
361/// NOT at the two render callsites.
362///
363/// Load-bearing wire-format string: the byte-exact `5m` shape is
364/// what the Flux source- and helm-controllers parse via `humantime`;
365/// a regression that renamed it to any other duration would silently
366/// throttle or hammer every Helm-driven Process's reconciliation
367/// loop. Pinned at
368/// [`tests::flux_helm_default_interval_is_pinned_to_5m`].
369pub const FLUX_HELM_DEFAULT_INTERVAL: &str = "5m";
370
371/// Typed shape of one Flux `HelmRelease.spec.{install,upgrade}` slot
372/// — the substrate's projection of the "how long may Helm take, and
373/// how many retries after a failed run" contract every Helm-driven
374/// Process publishes on both slots. Pre-lift the reconciler's
375/// `render_aplicacao` hand-authored the shape via TWO adjacent
376/// identical `json!({"timeout": …, "remediation": {"retries": …}})`
377/// blocks past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold
378/// — one for install, one for upgrade, each restating the same
379/// three-slot literal with the same `Option::unwrap_or_else` fallback
380/// on the timeout. Post-lift the shape lives at ONE named typed
381/// struct here whose serde projection matches Flux HelmRelease v2's
382/// `install` / `upgrade` block schema byte-identically, and the
383/// reconciler composes both slots off ONE
384/// [`AplicacaoIntent::helm_lifecycle_policy`] call.
385///
386/// A future addition — a `wait: bool` slot, a `crds:
387/// CreateReplace` slot, a `disableOpenAPIValidation: bool` slot,
388/// a two-slot split that lets install carry a longer timeout than
389/// upgrade — lands at ONE struct here and every downstream
390/// consumer (the render surface, snapshot tests, an operator-
391/// facing dashboard column, a future validating webhook) inherits
392/// the upgrade mechanically.
393#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
394pub struct HelmLifecyclePolicy {
395    /// Chart-controller timeout (`humantime` duration). Set from
396    /// [`AplicacaoIntent::install_timeout`] when present; otherwise
397    /// [`HELM_LIFECYCLE_DEFAULT_TIMEOUT`].
398    pub timeout: String,
399    /// Retry budget for the slot.
400    pub remediation: HelmRemediationPolicy,
401}
402
403/// Typed shape of one `HelmLifecyclePolicy::remediation` slot.
404/// A named struct rather than an inline `{retries: u8}` map so
405/// downstream consumers can talk about "one Helm remediation
406/// policy" as a nameable handle rather than an unnamed nested
407/// object.
408#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
409pub struct HelmRemediationPolicy {
410    /// Number of times Flux's helm-controller retries a failed
411    /// install / upgrade before surfacing the failure to the parent
412    /// Process's boundary evaluator.
413    pub retries: u8,
414}
415
416impl HelmLifecyclePolicy {
417    /// The workspace-wide default policy — used when the operator
418    /// omitted [`AplicacaoIntent::install_timeout`]. Named projection
419    /// of the two `HELM_LIFECYCLE_DEFAULT_*` consts so a future
420    /// consumer wanting "the substrate's fresh-out-of-the-box Helm
421    /// lifecycle policy" pulls the pair through ONE call rather than
422    /// composing the struct by hand at every callsite.
423    pub fn workspace_default() -> Self {
424        Self {
425            timeout: HELM_LIFECYCLE_DEFAULT_TIMEOUT.to_string(),
426            remediation: HelmRemediationPolicy {
427                retries: HELM_LIFECYCLE_DEFAULT_RETRIES,
428            },
429        }
430    }
431}
432
433impl AplicacaoIntent {
434    /// Derive the Flux `HelmRelease.spec.{install,upgrade}` policy
435    /// this intent publishes on BOTH slots. Pre-lift the reconciler's
436    /// `render_aplicacao` restated the shape by hand via two adjacent
437    /// identical `json!` blocks (install and upgrade); post-lift both
438    /// slots ride through this ONE composer. A future two-slot split
439    /// (distinct install vs upgrade policies) lands as a two-method
440    /// pair here, not at the render callsite.
441    pub fn helm_lifecycle_policy(&self) -> HelmLifecyclePolicy {
442        HelmLifecyclePolicy {
443            timeout: self
444                .install_timeout
445                .clone()
446                .unwrap_or_else(|| HELM_LIFECYCLE_DEFAULT_TIMEOUT.to_string()),
447            remediation: HelmRemediationPolicy {
448                retries: HELM_LIFECYCLE_DEFAULT_RETRIES,
449            },
450        }
451    }
452
453    /// Derive the Flux reconcile-loop cadence this intent publishes on
454    /// BOTH `OCIRepository.spec.interval` (source-controller poll) and
455    /// `HelmRelease.spec.interval` (helm-controller re-reconcile).
456    /// Pre-lift the reconciler's `render_aplicacao` restated the value
457    /// via two adjacent hand-authored `"5m"` string literals past the
458    /// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold; post-lift both
459    /// slots ride through this ONE composer. A future divergence
460    /// (distinct per-slot cadences, a per-intent override field, a
461    /// two-slot method returning a `FluxReconcileIntervals` shape)
462    /// lands at ONE method here, not at the render callsites.
463    ///
464    /// Sibling composer to [`Self::helm_lifecycle_policy`]: both
465    /// return the substrate-default shape a Helm-driven Process
466    /// publishes on the Flux resources `render_aplicacao` emits,
467    /// keyed off the same `AplicacaoIntent`.
468    pub fn flux_reconcile_interval(&self) -> String {
469        FLUX_HELM_DEFAULT_INTERVAL.to_string()
470    }
471}
472
473/// Container intent — direct Deployment/StatefulSet/etc, no Helm.
474#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
475#[serde(rename_all = "camelCase")]
476pub struct ContainerIntent {
477    pub image: String,
478    #[serde(default, skip_serializing_if = "Option::is_none")]
479    pub replicas: Option<i32>,
480    #[serde(default)]
481    pub command: Vec<String>,
482    #[serde(default)]
483    pub args: Vec<String>,
484    #[serde(default)]
485    pub env: BTreeMap<String, String>,
486    #[serde(default)]
487    pub workload_kind: WorkloadKind,
488}
489
490/// K8s workload kind the `container` intent renders into. PascalCase
491/// values match the K8s `kind:` field on the emitted manifest verbatim,
492/// so `as_str` doubles as the canonical `kind:` projection at render time.
493#[derive(
494    Clone,
495    Copy,
496    Debug,
497    PartialEq,
498    Eq,
499    Hash,
500    Serialize,
501    Deserialize,
502    JsonSchema,
503    Default,
504    tatara_closed_set::DeriveClosedSet,
505)]
506#[serde(rename_all = "PascalCase")]
507#[closed_set(via = "as_str", generate_unknown, display)]
508pub enum WorkloadKind {
509    #[default]
510    Deployment,
511    StatefulSet,
512    DaemonSet,
513    Job,
514    CronJob,
515}
516
517impl WorkloadKind {
518    /// The closed set of workload kinds — single source of truth that
519    /// drives the `as_str` / Display / `FromStr` triad and the typed
520    /// `api_version` / `is_batch` projections. Adding a sixth variant
521    /// lands at one `ALL` entry + one `as_str` arm + one arm in each
522    /// projection — exhaustively checked by the compiler (the `[Self; 5]`
523    /// array literal forces the arity).
524    ///
525    /// Sibling closed-set lifts on the same `ProcessSpec` axis:
526    /// [`crate::encapsulates::EncapsulationMode::ALL`],
527    /// [`crate::export::ExportTrigger::ALL`],
528    /// [`crate::export::ReportFormat::ALL`],
529    /// [`crate::lifetime::TeardownPolicy::ALL`],
530    /// [`crate::intent::IntentKind::ALL`],
531    /// [`crate::lifetime::LifetimeKind::ALL`],
532    /// [`crate::boundary::ConditionKind::ALL`],
533    /// [`crate::phase::ProcessPhase::ALL`],
534    /// [`crate::signal::ProcessSignal::ALL`].
535    pub const ALL: [Self; 5] = [
536        Self::Deployment,
537        Self::StatefulSet,
538        Self::DaemonSet,
539        Self::Job,
540        Self::CronJob,
541    ];
542
543    /// Canonical PascalCase wire-format projection — matches the serde
544    /// `rename_all = "PascalCase"` output verbatim AND the K8s manifest
545    /// `kind:` field the `container` intent's future renderer will emit.
546    /// Used by Display (single source of truth), by `FromStr` to identify
547    /// the variant from its annotation / status-field representation, and
548    /// by operator-facing reason strings without reaching for `{:?}` Debug
549    /// formatting. Pinned by `workload_kind_as_str_matches_serde`.
550    pub const fn as_str(self) -> &'static str {
551        match self {
552            Self::Deployment => "Deployment",
553            Self::StatefulSet => "StatefulSet",
554            Self::DaemonSet => "DaemonSet",
555            Self::Job => "Job",
556            Self::CronJob => "CronJob",
557        }
558    }
559
560    /// Canonical K8s `apiVersion:` projection — `apps/v1` for the
561    /// long-running workload trio, `batch/v1` for the batch pair.
562    /// Single source of truth for the apiVersion the `container` intent
563    /// renderer will stamp on the emitted manifest; pinned by
564    /// `workload_kind_projection_truth_table` so a future variant lands
565    /// at one arm here, not at every render site that previously
566    /// hand-rolled `match kind { Job | CronJob => "batch/v1", _ => … }`.
567    ///
568    /// Closed-set match (not `matches!`) so adding a sixth variant
569    /// triggers the compiler's exhaustiveness check at this site
570    /// rather than silently defaulting to either group.
571    pub const fn api_version(self) -> &'static str {
572        match self {
573            Self::Deployment | Self::StatefulSet | Self::DaemonSet => "apps/v1",
574            Self::Job | Self::CronJob => "batch/v1",
575        }
576    }
577
578    /// True iff the workload kind is a batch (terminating) workload —
579    /// `Job` or `CronJob`. Drives the future container renderer's
580    /// decision between persistent / one-shot retry semantics and lets
581    /// the lifetime clock distinguish "naturally terminates" from "runs
582    /// until SIGTERM" without re-deriving the partition from
583    /// `api_version() == "batch/v1"`.
584    ///
585    /// Closed-set match (not `matches!`) so adding a sixth variant
586    /// triggers the compiler's exhaustiveness check at this site.
587    pub const fn is_batch(self) -> bool {
588        match self {
589            Self::Job | Self::CronJob => true,
590            Self::Deployment | Self::StatefulSet | Self::DaemonSet => false,
591        }
592    }
593}
594
595// `impl FromStr for WorkloadKind` +
596// `impl tatara_lisp::ClosedSet for WorkloadKind` +
597// `impl fmt::Display for WorkloadKind` +
598// `pub struct UnknownWorkloadKind(pub String)` are all generated by
599// `#[derive(tatara_closed_set::DeriveClosedSet)]` +
600// `#[closed_set(via = "as_str", generate_unknown, display)]` on the
601// enum declaration above. `label` delegates to the inherent
602// `WorkloadKind::as_str` — the PascalCase wire-vocabulary projection
603// stays load-bearing (matches the serde `rename_all = "PascalCase"`
604// output AND the K8s manifest `kind:` field verbatim), while generic
605// `T: ClosedSet` consumers reach the STABLE workspace-wide name
606// (`label`). The auto-derived carrier label "workload kind" matches
607// the prior hand-rolled `#[error("unknown workload kind: {0}")]`
608// annotation byte-for-byte. Symmetric to every other
609// `#[derive(DeriveClosedSet)]` implementor across the crate.
610
611/// Guest intent — the Process is a Linux VM or WASM component supervised
612/// by `tatara-hospedeiro`. See `tatara/docs/declarative-guests.md`.
613///
614/// The actual `GuestSpec` is stored as a serde JSON value to keep
615/// `tatara-process` decoupled from `tatara-vm`. Hospedeiro re-parses
616/// the value as the concrete `tatara_vm::GuestSpec` at boot time; a
617/// round-trip test on the tatara-vm side guarantees the shape.
618#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
619#[serde(rename_all = "camelCase")]
620pub struct GuestIntent {
621    /// The (defguest …) spec as JSON. Shape matches `tatara_vm::GuestSpec`.
622    #[schemars(schema_with = "crate::schema_helpers::preserve_unknown_object")]
623    pub spec: serde_json::Value,
624
625    /// Where to write per-guest state on the host (logs, socket, PID file).
626    /// Defaults to `~/.local/state/tatara/guests/<name>/`.
627    #[serde(default, skip_serializing_if = "Option::is_none")]
628    pub state_dir: Option<String>,
629
630    /// Whether hospedeiro is allowed to pull guest artifacts from a remote
631    /// transport (Attic, ssh-ng) if not already present locally. The
632    /// default is taken from the GuestSpec's `buildOn` field; setting
633    /// this explicitly overrides at the intent layer.
634    #[serde(default, skip_serializing_if = "Option::is_none")]
635    pub allow_remote_build: Option<bool>,
636}
637
638#[cfg(test)]
639mod tests {
640    use super::*;
641
642    #[test]
643    fn empty_intent_errors() {
644        let i = Intent::default();
645        match i.variant().unwrap_err() {
646            IntentError::Empty(list) => assert_eq!(list, INTENT_KIND_LIST),
647            other => panic!("expected Empty, got {other:?}"),
648        }
649    }
650
651    #[test]
652    fn exactly_one_ok() {
653        let i = Intent {
654            nix: Some(NixIntent {
655                flake_ref: "github:a/b".into(),
656                attribute: "x".into(),
657                system: None,
658                attic_cache: None,
659                extra_args: vec![],
660                delegate_to_nix_build: false,
661            }),
662            ..Intent::default()
663        };
664        assert!(matches!(i.variant().unwrap(), IntentVariant::Nix(_)));
665    }
666
667    /// AMBIGUOUS-PATH CONTRACT: when two slots are populated the
668    /// resolver yields `Ambiguous`, exhaustively across every pair in
669    /// `ALL × ALL` (excluding the diagonal). Routes through the
670    /// substrate primitive
671    /// [`crate::tagged_union::assert_two_slots_ambiguous`] shared with
672    /// the sibling
673    /// `encapsulation_kind_two_slots_is_ambiguous_across_every_pair`
674    /// / `artifact_source_two_slots_is_ambiguous_across_every_pair`
675    /// / `vector_channel_two_slots_is_ambiguous_across_every_pair`
676    /// sites. Subsumes the pre-lift hand-authored two-pair probes
677    /// (`nix + flux`, `nix + guest`) with exhaustive `6 × 5 = 30`
678    /// coverage — every off-diagonal pair on `IntentKind` is pinned.
679    #[test]
680    fn intent_two_slots_is_ambiguous_across_every_pair() {
681        crate::tagged_union::assert_two_slots_ambiguous::<Intent, _>(two_slot_intent);
682    }
683
684    #[test]
685    fn guest_intent_selects_its_variant() {
686        let i = Intent {
687            guest: Some(GuestIntent {
688                spec: serde_json::json!({
689                    "name": "fast-fn",
690                    "kind": { "kind": "wasm", "runtime": "wasmtime",
691                              "wasiPreview": "p2",
692                              "component": { "kind": "flake",
693                                             "value": {"url":"github:x/y","attr":"wasi"} },
694                              "features": { "simd": true } },
695                    "cmdline": []
696                }),
697                state_dir: None,
698                allow_remote_build: Some(true),
699            }),
700            ..Intent::default()
701        };
702        match i.variant().unwrap() {
703            IntentVariant::Guest(g) => {
704                assert_eq!(g.spec["name"], "fast-fn");
705                assert_eq!(g.allow_remote_build, Some(true));
706            }
707            other => panic!("expected Guest, got {other:?}"),
708        }
709    }
710
711    #[test]
712    fn aplicacao_intent_selects_its_variant() {
713        let i = Intent {
714            aplicacao: Some(AplicacaoIntent {
715                chart_ref: "oci://ghcr.io/pleme-io/charts/lareira-demo-app".into(),
716                version: "0.5.5".into(),
717                profile: "all-in-one".into(),
718                values_overlay: serde_json::json!({ "cluster": { "name": "test-01" } }),
719                release_name: None,
720                target_namespace: None,
721                install_timeout: Some("25m".into()),
722            }),
723            ..Intent::default()
724        };
725        match i.variant().unwrap() {
726            IntentVariant::Aplicacao(a) => {
727                assert_eq!(a.profile, "all-in-one");
728                assert_eq!(a.version, "0.5.5");
729                assert_eq!(a.install_timeout.as_deref(), Some("25m"));
730            }
731            other => panic!("expected Aplicacao, got {other:?}"),
732        }
733    }
734
735    /// Structural well-formedness of [`IntentKind`] as a
736    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
737    /// testkit lift that pins all structural invariants (`ALL` is
738    /// non-empty, every variant round-trips through `label ↔
739    /// parse_label`, labels are pairwise distinct, `""` is outside
740    /// the closed set, the `UnknownIntentKind` carrier's Display
741    /// renders the substrate-wide `"unknown intent kind: <input>"`
742    /// shape, `labels()` equals the natural `ALL × label` projection,
743    /// `parse_label_with_hint` composes `parse_label` +
744    /// `suggest_closest` verbatim) at ONE call site. Replaces the
745    /// hand-derived `intent_kind_all_is_unique_and_complete` —
746    /// clause (1)+(3) of the testkit subsume the uniqueness +
747    /// non-emptiness sweep that test pinned independently.
748    #[test]
749    fn intent_kind_is_well_formed_closed_set() {
750        tatara_closed_set::assert_closed_set_well_formed::<IntentKind>();
751    }
752
753    /// The Display impl IS `as_str` — pinning this lets future callers
754    /// reach for either projection without drift. Symmetric to the
755    /// sibling `workload_kind_display_matches_as_str` invariant; if a
756    /// reviewer accidentally re-introduces an inline match in Display,
757    /// this test would fail the moment a variant rename touches one
758    /// site but not the other.
759    ///
760    /// Routes through the substrate primitive
761    /// [`crate::tagged_union::assert_display_matches_label`], which
762    /// composes `<T as ClosedSet>::label` against `T::to_string`
763    /// byte-identically for every `<T: ClosedSet + Display>`
764    /// implementor — the Display-alignment testkit shared with every
765    /// sibling `X_display_matches_as_str` site across the crate.
766    /// Pre-lift the 27 bodies each restated the same
767    /// `for k in K::ALL { assert_eq!(k.to_string(), k.as_str()) }`
768    /// two-line probe at the test surface; post-lift the projection
769    /// lives at ONE substrate primitive and every site binds through
770    /// a single call.
771    #[test]
772    fn intent_kind_display_matches_as_str() {
773        crate::tagged_union::assert_display_matches_label::<IntentKind>();
774    }
775
776    /// CANONICAL-KEY CONTRACT: each variant's `as_str()` matches the
777    /// camelCase serde field name on `Intent`. A future rename of
778    /// any field lands here at one site — and the `Empty` diagnostic
779    /// composed from `INTENT_KIND_LIST` stays coherent with the
780    /// wire format.
781    ///
782    /// Routes through the substrate primitive
783    /// [`crate::tagged_union::assert_single_slot_key_matches_label`],
784    /// which pins the exactly-one-key + name-equality projection
785    /// byte-identically for every `<T: TaggedUnion + Serialize>`
786    /// implementor — the wire-alignment testkit shared with the sibling
787    /// `encapsulation_target_as_str_matches_field_name` /
788    /// `artifact_kind_as_str_matches_field_name` /
789    /// `channel_kind_as_str_matches_field_name` sites. Pre-lift the
790    /// four bodies each restated the same serialize-and-inspect sweep
791    /// at the test surface (three through a weaker YAML-substring
792    /// check; this site alone through the strong JSON-object exactly-
793    /// one form); post-lift the projection lives at ONE substrate
794    /// primitive and every site binds through a single call — the
795    /// three YAML sites simultaneously upgrade to the strong exactly-
796    /// one form.
797    #[test]
798    fn intent_kind_as_str_matches_intent_field_name() {
799        crate::tagged_union::assert_single_slot_key_matches_label::<Intent, _>(single_slot_intent);
800    }
801
802    /// ROUND-TRIP CONTRACT: `IntentKind::select(intent).map(|v|
803    /// v.kind()) == Some(kind)`. The reverse `IntentVariant::kind`
804    /// projection composes the closed set in both directions — a
805    /// regression that misroutes a select arm (e.g. `Self::Nix =>
806    /// intent.flux.as_ref()...`) fails loudly here.
807    ///
808    /// Routes through the substrate primitive
809    /// [`crate::tagged_union::assert_variant_round_trip`], which
810    /// composes [`crate::tagged_union::VariantSelector::select`]
811    /// (forward) with [`crate::tagged_union::VariantKind::variant_kind`]
812    /// (reverse) byte-identically for every `<T: TaggedUnion>`
813    /// implementor — the round-trip testkit shared with the sibling
814    /// `artifact_kind_round_trips_through_variant_kind` /
815    /// `channel_kind_round_trips_through_variant_kind` /
816    /// `encapsulation_target_round_trips_through_variant_target`
817    /// sites. Pre-lift the four bodies each restated the same
818    /// two-arm round-trip probe at the test surface; post-lift the
819    /// projection lives at ONE substrate primitive and every site
820    /// binds through a single call.
821    #[test]
822    fn intent_kind_round_trips_through_variant_kind() {
823        crate::tagged_union::assert_variant_round_trip::<Intent, _>(single_slot_intent);
824    }
825
826    /// PRESENCE-PROBE WIRE CONTRACT: the `intent-<kind>` require-tag
827    /// dispatcher in `tatara-check` (`bin/tatara-check.rs`) parses
828    /// each suffix via `IntentKind::from_str` and dispatches through
829    /// the substrate primitive `Intent::has` (a one-line inherent
830    /// forwarder over [`crate::tagged_union::TaggedUnion::has`]).
831    /// Pre-lift the dispatcher restated five hand-authored
832    /// `spec.intent.<field>.is_some()` arms whose per-field addressing
833    /// drifted from `IntentKind::ALL` (the sixth variant `Guest` had
834    /// no `intent-guest` arm at all); post-lift adding a seventh
835    /// variant to `IntentKind` lands the corresponding `intent-<kind>`
836    /// tag automatically — the sweep here pins that every
837    /// `IntentKind` roundtrips through the `intent-{as_str}` wire
838    /// key, and that `Intent::has(k)` fires exactly on the populated
839    /// slot addressed by `k`.
840    #[test]
841    fn intent_has_dispatches_through_wire_key_across_every_kind() {
842        for populated in IntentKind::ALL {
843            let intent = single_slot_intent(populated);
844            for probed in IntentKind::ALL {
845                let wire_key = format!("intent-{}", probed.as_str());
846                let parsed: IntentKind = wire_key
847                    .strip_prefix("intent-")
848                    .expect("wire key composes as intent-<as_str>")
849                    .parse()
850                    .expect("as_str→from_str round trip pinned by DeriveClosedSet");
851                assert_eq!(parsed, probed);
852                let expected = probed == populated;
853                assert_eq!(
854                    intent.has(probed),
855                    expected,
856                    "Intent::has drift — populated={populated:?} probed={probed:?}",
857                );
858            }
859        }
860    }
861
862    /// EMPTY-DIAGNOSTIC CONTRACT: the closed-set kind list embedded
863    /// in `IntentError::Empty` echoes the canonical join of every
864    /// `IntentKind::as_str()` projection. A variant added without
865    /// updating `INTENT_KIND_LIST` (or a renamed variant) shows up
866    /// here as a mismatch.
867    ///
868    /// Routes through the substrate primitive
869    /// [`crate::tagged_union::assert_kind_list_matches_closed_set`],
870    /// which composes `<T::Kind as ClosedSet>::labels_joined("/")`
871    /// against `<T as TaggedUnion>::KIND_LIST` byte-identically for
872    /// every implementor — the diagnostic-stability testkit shared
873    /// with the sibling `artifact_error_empty_lists_every_kind_in_canonical_order`
874    /// / `channel_error_empty_lists_every_kind_in_canonical_order`
875    /// / `encapsulation_kind_error_empty_lists_every_target_in_canonical_order`
876    /// sites. Pre-lift the four bodies each restated the same
877    /// two-argument `assert_eq!(<XxxKind as ClosedSet>::labels_joined("/"),
878    /// XXX_KIND_LIST)` comparison at the test surface; post-lift
879    /// the projection lives at ONE substrate primitive and every
880    /// site binds through a single call.
881    #[test]
882    fn intent_error_empty_lists_every_kind_in_canonical_order() {
883        crate::tagged_union::assert_kind_list_matches_closed_set::<Intent>();
884    }
885
886    /// CANONICAL-BYTES CONTRACT: every populated variant yields the
887    /// SAME bytes as `serde_json::to_vec` on the inner reference.
888    /// Pins the lift of the parallel observe-mode match in
889    /// `tatara-reconciler::render` to this single method.
890    #[test]
891    fn intent_variant_canonical_bytes_matches_inner_serialize() {
892        for kind in IntentKind::ALL {
893            let i = single_slot_intent(kind);
894            let v = i.variant().expect("exactly-one variant");
895            let via_method = v.canonical_bytes();
896            let expected: Vec<u8> = match &v {
897                IntentVariant::Nix(n) => serde_json::to_vec(n).unwrap_or_default(),
898                IntentVariant::Flux(f) => serde_json::to_vec(f).unwrap_or_default(),
899                IntentVariant::Lisp(l) => serde_json::to_vec(l).unwrap_or_default(),
900                IntentVariant::Container(c) => serde_json::to_vec(c).unwrap_or_default(),
901                IntentVariant::Aplicacao(a) => serde_json::to_vec(a).unwrap_or_default(),
902                IntentVariant::Guest(g) => serde_json::to_vec(g).unwrap_or_default(),
903            };
904            assert_eq!(
905                via_method, expected,
906                "canonical_bytes mismatch for {kind:?}"
907            );
908            assert!(!via_method.is_empty(), "{kind:?} produced empty bytes");
909        }
910    }
911
912    /// Construct an `Intent` with two slots populated — drives the
913    /// pairwise `Ambiguous` sweep through the substrate primitive
914    /// [`crate::tagged_union::assert_two_slots_ambiguous`]. Composes
915    /// the single-slot constructor on top of itself per-field so ONE
916    /// source of truth for per-variant inner payloads is preserved.
917    /// Mirrors `two_slot_source` / `two_slot_channel` / `two_slot_kind`
918    /// in shape across `ProcessSpec`'s tagged-union axis.
919    fn two_slot_intent(a: IntentKind, b: IntentKind) -> Intent {
920        let ia = single_slot_intent(a);
921        let ib = single_slot_intent(b);
922        Intent {
923            nix: ia.nix.or(ib.nix),
924            flux: ia.flux.or(ib.flux),
925            lisp: ia.lisp.or(ib.lisp),
926            container: ia.container.or(ib.container),
927            aplicacao: ia.aplicacao.or(ib.aplicacao),
928            guest: ia.guest.or(ib.guest),
929        }
930    }
931
932    /// Construct an `Intent` with exactly the given kind's slot
933    /// populated by a minimal valid inner spec. Shared across the
934    /// closed-set property tests so they each cover every variant
935    /// without restating the construction table.
936    fn single_slot_intent(kind: IntentKind) -> Intent {
937        match kind {
938            IntentKind::Nix => Intent {
939                nix: Some(NixIntent {
940                    flake_ref: "github:a/b".into(),
941                    attribute: "x".into(),
942                    system: None,
943                    attic_cache: None,
944                    extra_args: vec![],
945                    delegate_to_nix_build: false,
946                }),
947                ..Intent::default()
948            },
949            IntentKind::Flux => Intent {
950                flux: Some(FluxIntent {
951                    git_repository: "g".into(),
952                    path: "p".into(),
953                    git_repository_namespace: None,
954                    target_namespace: None,
955                    decrypt_sops: true,
956                    helm_chart: None,
957                    helm_values: None,
958                }),
959                ..Intent::default()
960            },
961            IntentKind::Lisp => Intent {
962                lisp: Some(LispIntent {
963                    source: "()".into(),
964                    reader: "tatara-lisp".into(),
965                    version: "v1".into(),
966                    bindings: BTreeMap::new(),
967                }),
968                ..Intent::default()
969            },
970            IntentKind::Container => Intent {
971                container: Some(ContainerIntent {
972                    image: "ghcr.io/x:1".into(),
973                    replicas: Some(1),
974                    command: vec![],
975                    args: vec![],
976                    env: BTreeMap::new(),
977                    workload_kind: WorkloadKind::default(),
978                }),
979                ..Intent::default()
980            },
981            IntentKind::Aplicacao => Intent {
982                aplicacao: Some(AplicacaoIntent {
983                    chart_ref: "oci://ghcr.io/x".into(),
984                    version: "0.1.0".into(),
985                    profile: String::new(),
986                    values_overlay: serde_json::Value::Null,
987                    release_name: None,
988                    target_namespace: None,
989                    install_timeout: None,
990                }),
991                ..Intent::default()
992            },
993            IntentKind::Guest => Intent {
994                guest: Some(GuestIntent {
995                    spec: serde_json::json!({"name": "guest-1"}),
996                    state_dir: None,
997                    allow_remote_build: None,
998                }),
999                ..Intent::default()
1000            },
1001        }
1002    }
1003
1004    // ── closed-set algebra for WorkloadKind (ALL × as_str × Display ×
1005    //    FromStr × api_version × is_batch) ─────────────────────────────
1006
1007    /// Structural well-formedness of [`WorkloadKind`] as a
1008    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
1009    /// testkit lift that pins all three structural invariants (`ALL`
1010    /// is non-empty, every variant round-trips through `label ↔
1011    /// parse_label`, labels are pairwise distinct, `""` is outside the
1012    /// closed set) at ONE call site. Replaces the hand-derived
1013    /// `workload_kind_all_is_unique_and_complete` +
1014    /// `workload_kind_roundtrip_via_as_str` + the empty-input arm of
1015    /// `unknown_workload_kind_errors`. `FromStr` delegates to
1016    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
1017    /// exercises the same code path the reconciler hits when parsing a
1018    /// K8s `kind:`-shaped value back to the typed workload kind.
1019    #[test]
1020    fn workload_kind_is_well_formed_closed_set() {
1021        tatara_closed_set::assert_closed_set_well_formed::<WorkloadKind>();
1022    }
1023
1024    /// CANONICAL-KEY CONTRACT: every variant's `as_str()` matches serde's
1025    /// PascalCase output verbatim. A future variant rename (or an
1026    /// `as_str` arm typo) lands at one site, instead of drifting
1027    /// between the typed surface, the K8s `kind:` manifest field, and
1028    /// the YAML wire format the reconciler / operator both read.
1029    #[test]
1030    fn workload_kind_as_str_matches_serde() {
1031        crate::tagged_union::assert_label_matches_serde_serialization::<WorkloadKind>();
1032    }
1033
1034    /// The Display impl IS `as_str` — pinning this lets future callers
1035    /// reach for either projection without drift. If a reviewer
1036    /// accidentally re-introduces an inline match in Display, this
1037    /// test would fail the moment a variant rename touches one site
1038    /// but not the other.
1039    #[test]
1040    fn workload_kind_display_matches_as_str() {
1041        crate::tagged_union::assert_display_matches_label::<WorkloadKind>();
1042    }
1043
1044    /// `FromStr` rejects strings that aren't in the canonical
1045    /// projection — lowercased / typo / unrelated — and the error
1046    /// echoes the input verbatim so the operator-facing diagnostic
1047    /// carries the offending value, not a normalized form. The
1048    /// empty-input arm is pinned by
1049    /// [`workload_kind_is_well_formed_closed_set`] via the
1050    /// `tatara_lisp::ClosedSet` testkit; the cases here pin the
1051    /// verbatim-echo contract on the [`UnknownWorkloadKind`]
1052    /// newtype, which the trait's `make_unknown` can't see.
1053    #[test]
1054    fn unknown_workload_kind_errors() {
1055        use std::str::FromStr;
1056        for bad in ["deployment", "JOB", "ReplicaSet", "Pod"] {
1057            let err = WorkloadKind::from_str(bad).unwrap_err();
1058            assert_eq!(err.0, bad, "error payload should echo input verbatim");
1059        }
1060    }
1061
1062    #[test]
1063    fn workload_kind_default_is_deployment() {
1064        assert_eq!(WorkloadKind::default(), WorkloadKind::Deployment);
1065    }
1066
1067    /// TRUTH-TABLE CONTRACT: `api_version` / `is_batch` agree with the
1068    /// documented (kind) -> (apiVersion, is_batch) table for every
1069    /// variant. A new variant in `WorkloadKind` without extending
1070    /// either projection's match is caught by the compiler (closed-set
1071    /// match in each method); adding a variant without extending its
1072    /// truth row is caught here. Also pins the invariant
1073    /// `is_batch <=> api_version == "batch/v1"`, so a future renderer
1074    /// can route on either projection without re-deriving the partition.
1075    #[test]
1076    fn workload_kind_projection_truth_table() {
1077        let table: &[(WorkloadKind, &str, bool)] = &[
1078            // (kind, api_version, is_batch)
1079            (WorkloadKind::Deployment, "apps/v1", false),
1080            (WorkloadKind::StatefulSet, "apps/v1", false),
1081            (WorkloadKind::DaemonSet, "apps/v1", false),
1082            (WorkloadKind::Job, "batch/v1", true),
1083            (WorkloadKind::CronJob, "batch/v1", true),
1084        ];
1085        assert_eq!(table.len(), WorkloadKind::ALL.len());
1086        for (kind, api, batch) in table {
1087            assert_eq!(kind.api_version(), *api, "api_version drift for {kind:?}");
1088            assert_eq!(kind.is_batch(), *batch, "is_batch drift for {kind:?}");
1089            assert_eq!(
1090                kind.is_batch(),
1091                kind.api_version() == "batch/v1",
1092                "is_batch / api_version partition disagrees for {kind:?}"
1093            );
1094        }
1095    }
1096
1097    #[test]
1098    fn aplicacao_plus_flux_is_ambiguous() {
1099        let i = Intent {
1100            aplicacao: Some(AplicacaoIntent {
1101                chart_ref: "x".into(),
1102                version: "1".into(),
1103                profile: String::new(),
1104                values_overlay: serde_json::Value::Null,
1105                release_name: None,
1106                target_namespace: None,
1107                install_timeout: None,
1108            }),
1109            flux: Some(FluxIntent {
1110                git_repository: "g".into(),
1111                path: "p".into(),
1112                git_repository_namespace: None,
1113                target_namespace: None,
1114                decrypt_sops: true,
1115                helm_chart: None,
1116                helm_values: None,
1117            }),
1118            ..Intent::default()
1119        };
1120        assert_eq!(i.variant().unwrap_err(), IntentError::Ambiguous);
1121    }
1122
1123    // ── Helm lifecycle policy — install / upgrade slot substrate ────
1124
1125    fn helm_intent(install_timeout: Option<&str>) -> AplicacaoIntent {
1126        AplicacaoIntent {
1127            chart_ref: "oci://ghcr.io/pleme-io/charts/lareira-demo-app".into(),
1128            version: "0.5.5".into(),
1129            profile: String::new(),
1130            values_overlay: serde_json::Value::Null,
1131            release_name: None,
1132            target_namespace: None,
1133            install_timeout: install_timeout.map(str::to_string),
1134        }
1135    }
1136
1137    /// The workspace-wide default timeout const is pinned to `25m`.
1138    /// A regression that renamed it to any other duration would
1139    /// silently misroute every Helm-driven Process's default retry
1140    /// budget, so pin the byte-exact spelling here rather than at
1141    /// every consumer's own callsite.
1142    #[test]
1143    fn helm_lifecycle_default_timeout_is_pinned_to_25m() {
1144        assert_eq!(HELM_LIFECYCLE_DEFAULT_TIMEOUT, "25m");
1145    }
1146
1147    /// The workspace-wide default retries const is pinned to `3`.
1148    /// Peer to the `_timeout` pin; same rationale.
1149    #[test]
1150    fn helm_lifecycle_default_retries_is_pinned_to_three() {
1151        assert_eq!(HELM_LIFECYCLE_DEFAULT_RETRIES, 3);
1152    }
1153
1154    /// Fallback branch of the primitive: an intent that omitted
1155    /// `install_timeout` picks up the workspace-wide default
1156    /// (`25m` + retries `3`). Pin binds the "no override" shape
1157    /// every render / snapshot / dashboard consumer sees today.
1158    #[test]
1159    fn helm_lifecycle_policy_defaults_when_install_timeout_is_none() {
1160        let policy = helm_intent(None).helm_lifecycle_policy();
1161        assert_eq!(policy.timeout, HELM_LIFECYCLE_DEFAULT_TIMEOUT);
1162        assert_eq!(policy.remediation.retries, HELM_LIFECYCLE_DEFAULT_RETRIES);
1163    }
1164
1165    /// Override branch of the primitive: when the operator populated
1166    /// `install_timeout`, the primitive substitutes that string
1167    /// verbatim (no normalization, no trimming) — the reconciler
1168    /// hands the exact `humantime` shape to Flux, and any parse
1169    /// error surfaces from the chart-controller, not from here.
1170    #[test]
1171    fn helm_lifecycle_policy_uses_install_timeout_when_present() {
1172        for shape in ["10m", "1h30m", "5s", "25m", "0s"] {
1173            let policy = helm_intent(Some(shape)).helm_lifecycle_policy();
1174            assert_eq!(
1175                policy.timeout, shape,
1176                "override shape {shape} not substituted verbatim"
1177            );
1178            // Retries stay at the workspace default regardless of timeout.
1179            assert_eq!(policy.remediation.retries, HELM_LIFECYCLE_DEFAULT_RETRIES);
1180        }
1181    }
1182
1183    /// Coherence axis: the retries slot is invariant across every
1184    /// timeout shape the operator might publish — a regression that
1185    /// coupled the two slots (e.g. "when timeout is short, retry
1186    /// more") surfaces here rather than at every consumer.
1187    #[test]
1188    fn helm_lifecycle_policy_retries_are_invariant_across_timeout_shapes() {
1189        let seen: std::collections::BTreeSet<u8> = [None, Some("1m"), Some("25m"), Some("2h")]
1190            .into_iter()
1191            .map(|t| helm_intent(t).helm_lifecycle_policy().remediation.retries)
1192            .collect();
1193        assert_eq!(
1194            seen.len(),
1195            1,
1196            "retries should be constant across timeout shapes"
1197        );
1198        assert_eq!(
1199            seen.into_iter().next(),
1200            Some(HELM_LIFECYCLE_DEFAULT_RETRIES)
1201        );
1202    }
1203
1204    /// Wire-shape pin: the serde projection matches Flux
1205    /// `HelmRelease.spec.{install,upgrade}` v2 byte-identically —
1206    /// `{"timeout": <string>, "remediation": {"retries": <int>}}`
1207    /// with no extra keys, no field renames, no camelCase surprises.
1208    /// A regression that added a slot to `HelmLifecyclePolicy` or
1209    /// renamed one would fail here rather than as a Flux CR
1210    /// rejection at every deployment.
1211    #[test]
1212    fn helm_lifecycle_policy_serializes_to_flux_hr_v2_install_upgrade_shape() {
1213        let policy = helm_intent(Some("10m")).helm_lifecycle_policy();
1214        let json = serde_json::to_value(&policy).unwrap();
1215        assert_eq!(
1216            json,
1217            serde_json::json!({
1218                "timeout": "10m",
1219                "remediation": { "retries": 3 },
1220            }),
1221        );
1222    }
1223
1224    /// Coherence axis: `HelmLifecyclePolicy::workspace_default()`
1225    /// composes byte-identically to the intent-derived policy of an
1226    /// intent with `install_timeout: None` — the two paths to the
1227    /// substrate default (via the `Aplicacao` intent's own resolver
1228    /// vs the standalone workspace-default constructor) yield the
1229    /// same shape. Binds the "workspace_default IS the fallback"
1230    /// invariant so a future divergence (e.g. workspace_default
1231    /// changes but the intent resolver's inline fallback does not)
1232    /// surfaces here rather than as a silent drift at every render
1233    /// callsite.
1234    #[test]
1235    fn helm_lifecycle_policy_workspace_default_matches_intent_fallback_branch() {
1236        let default_policy = HelmLifecyclePolicy::workspace_default();
1237        let intent_policy = helm_intent(None).helm_lifecycle_policy();
1238        assert_eq!(default_policy, intent_policy);
1239    }
1240
1241    // ── Flux reconcile interval — OCIRepository + HelmRelease shared ─
1242
1243    /// The workspace-wide default Flux reconcile-interval const is
1244    /// pinned to `5m`. A regression that renamed it would silently
1245    /// throttle or hammer every Helm-driven Process's OCIRepository
1246    /// pull cadence AND its HelmRelease reconcile cadence, so pin
1247    /// the byte-exact spelling here rather than at the two render
1248    /// callsites the primitive owns.
1249    #[test]
1250    fn flux_helm_default_interval_is_pinned_to_5m() {
1251        assert_eq!(FLUX_HELM_DEFAULT_INTERVAL, "5m");
1252    }
1253
1254    /// The intent-side composer returns the workspace-wide default
1255    /// verbatim today. A regression that hand-authored some other
1256    /// string here (or that stopped routing through the const)
1257    /// would surface at this pin.
1258    #[test]
1259    fn flux_reconcile_interval_returns_workspace_default() {
1260        assert_eq!(
1261            helm_intent(None).flux_reconcile_interval(),
1262            FLUX_HELM_DEFAULT_INTERVAL,
1263        );
1264    }
1265
1266    /// Coherence axis: the reconcile interval is invariant across
1267    /// every `install_timeout` shape the operator publishes today.
1268    /// Pre-lift the two slots were siblings hand-authored with the
1269    /// same `"5m"` value regardless of any other AplicacaoIntent
1270    /// shape; post-lift the same invariance holds through the
1271    /// composer. A future coupling (e.g. "when timeout is short,
1272    /// reconcile more often") lands at the composer's shape, not
1273    /// silently at any render callsite.
1274    #[test]
1275    fn flux_reconcile_interval_is_invariant_across_install_timeout_shapes() {
1276        let seen: std::collections::BTreeSet<String> =
1277            [None, Some("10m"), Some("1h30m"), Some("25m"), Some("2h")]
1278                .into_iter()
1279                .map(|t| helm_intent(t).flux_reconcile_interval())
1280                .collect();
1281        assert_eq!(
1282            seen.len(),
1283            1,
1284            "reconcile interval should be constant across install_timeout shapes"
1285        );
1286        assert_eq!(
1287            seen.into_iter().next().as_deref(),
1288            Some(FLUX_HELM_DEFAULT_INTERVAL),
1289        );
1290    }
1291}