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 /// EMPTY-DIAGNOSTIC CONTRACT: the closed-set kind list embedded
827 /// in `IntentError::Empty` echoes the canonical join of every
828 /// `IntentKind::as_str()` projection. A variant added without
829 /// updating `INTENT_KIND_LIST` (or a renamed variant) shows up
830 /// here as a mismatch.
831 ///
832 /// Routes through the substrate primitive
833 /// [`crate::tagged_union::assert_kind_list_matches_closed_set`],
834 /// which composes `<T::Kind as ClosedSet>::labels_joined("/")`
835 /// against `<T as TaggedUnion>::KIND_LIST` byte-identically for
836 /// every implementor — the diagnostic-stability testkit shared
837 /// with the sibling `artifact_error_empty_lists_every_kind_in_canonical_order`
838 /// / `channel_error_empty_lists_every_kind_in_canonical_order`
839 /// / `encapsulation_kind_error_empty_lists_every_target_in_canonical_order`
840 /// sites. Pre-lift the four bodies each restated the same
841 /// two-argument `assert_eq!(<XxxKind as ClosedSet>::labels_joined("/"),
842 /// XXX_KIND_LIST)` comparison at the test surface; post-lift
843 /// the projection lives at ONE substrate primitive and every
844 /// site binds through a single call.
845 #[test]
846 fn intent_error_empty_lists_every_kind_in_canonical_order() {
847 crate::tagged_union::assert_kind_list_matches_closed_set::<Intent>();
848 }
849
850 /// CANONICAL-BYTES CONTRACT: every populated variant yields the
851 /// SAME bytes as `serde_json::to_vec` on the inner reference.
852 /// Pins the lift of the parallel observe-mode match in
853 /// `tatara-reconciler::render` to this single method.
854 #[test]
855 fn intent_variant_canonical_bytes_matches_inner_serialize() {
856 for kind in IntentKind::ALL {
857 let i = single_slot_intent(kind);
858 let v = i.variant().expect("exactly-one variant");
859 let via_method = v.canonical_bytes();
860 let expected: Vec<u8> = match &v {
861 IntentVariant::Nix(n) => serde_json::to_vec(n).unwrap_or_default(),
862 IntentVariant::Flux(f) => serde_json::to_vec(f).unwrap_or_default(),
863 IntentVariant::Lisp(l) => serde_json::to_vec(l).unwrap_or_default(),
864 IntentVariant::Container(c) => serde_json::to_vec(c).unwrap_or_default(),
865 IntentVariant::Aplicacao(a) => serde_json::to_vec(a).unwrap_or_default(),
866 IntentVariant::Guest(g) => serde_json::to_vec(g).unwrap_or_default(),
867 };
868 assert_eq!(
869 via_method, expected,
870 "canonical_bytes mismatch for {kind:?}"
871 );
872 assert!(!via_method.is_empty(), "{kind:?} produced empty bytes");
873 }
874 }
875
876 /// Construct an `Intent` with two slots populated — drives the
877 /// pairwise `Ambiguous` sweep through the substrate primitive
878 /// [`crate::tagged_union::assert_two_slots_ambiguous`]. Composes
879 /// the single-slot constructor on top of itself per-field so ONE
880 /// source of truth for per-variant inner payloads is preserved.
881 /// Mirrors `two_slot_source` / `two_slot_channel` / `two_slot_kind`
882 /// in shape across `ProcessSpec`'s tagged-union axis.
883 fn two_slot_intent(a: IntentKind, b: IntentKind) -> Intent {
884 let ia = single_slot_intent(a);
885 let ib = single_slot_intent(b);
886 Intent {
887 nix: ia.nix.or(ib.nix),
888 flux: ia.flux.or(ib.flux),
889 lisp: ia.lisp.or(ib.lisp),
890 container: ia.container.or(ib.container),
891 aplicacao: ia.aplicacao.or(ib.aplicacao),
892 guest: ia.guest.or(ib.guest),
893 }
894 }
895
896 /// Construct an `Intent` with exactly the given kind's slot
897 /// populated by a minimal valid inner spec. Shared across the
898 /// closed-set property tests so they each cover every variant
899 /// without restating the construction table.
900 fn single_slot_intent(kind: IntentKind) -> Intent {
901 match kind {
902 IntentKind::Nix => Intent {
903 nix: Some(NixIntent {
904 flake_ref: "github:a/b".into(),
905 attribute: "x".into(),
906 system: None,
907 attic_cache: None,
908 extra_args: vec![],
909 delegate_to_nix_build: false,
910 }),
911 ..Intent::default()
912 },
913 IntentKind::Flux => Intent {
914 flux: Some(FluxIntent {
915 git_repository: "g".into(),
916 path: "p".into(),
917 git_repository_namespace: None,
918 target_namespace: None,
919 decrypt_sops: true,
920 helm_chart: None,
921 helm_values: None,
922 }),
923 ..Intent::default()
924 },
925 IntentKind::Lisp => Intent {
926 lisp: Some(LispIntent {
927 source: "()".into(),
928 reader: "tatara-lisp".into(),
929 version: "v1".into(),
930 bindings: BTreeMap::new(),
931 }),
932 ..Intent::default()
933 },
934 IntentKind::Container => Intent {
935 container: Some(ContainerIntent {
936 image: "ghcr.io/x:1".into(),
937 replicas: Some(1),
938 command: vec![],
939 args: vec![],
940 env: BTreeMap::new(),
941 workload_kind: WorkloadKind::default(),
942 }),
943 ..Intent::default()
944 },
945 IntentKind::Aplicacao => Intent {
946 aplicacao: Some(AplicacaoIntent {
947 chart_ref: "oci://ghcr.io/x".into(),
948 version: "0.1.0".into(),
949 profile: String::new(),
950 values_overlay: serde_json::Value::Null,
951 release_name: None,
952 target_namespace: None,
953 install_timeout: None,
954 }),
955 ..Intent::default()
956 },
957 IntentKind::Guest => Intent {
958 guest: Some(GuestIntent {
959 spec: serde_json::json!({"name": "guest-1"}),
960 state_dir: None,
961 allow_remote_build: None,
962 }),
963 ..Intent::default()
964 },
965 }
966 }
967
968 // ── closed-set algebra for WorkloadKind (ALL × as_str × Display ×
969 // FromStr × api_version × is_batch) ─────────────────────────────
970
971 /// Structural well-formedness of [`WorkloadKind`] as a
972 /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
973 /// testkit lift that pins all three structural invariants (`ALL`
974 /// is non-empty, every variant round-trips through `label ↔
975 /// parse_label`, labels are pairwise distinct, `""` is outside the
976 /// closed set) at ONE call site. Replaces the hand-derived
977 /// `workload_kind_all_is_unique_and_complete` +
978 /// `workload_kind_roundtrip_via_as_str` + the empty-input arm of
979 /// `unknown_workload_kind_errors`. `FromStr` delegates to
980 /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
981 /// exercises the same code path the reconciler hits when parsing a
982 /// K8s `kind:`-shaped value back to the typed workload kind.
983 #[test]
984 fn workload_kind_is_well_formed_closed_set() {
985 tatara_closed_set::assert_closed_set_well_formed::<WorkloadKind>();
986 }
987
988 /// CANONICAL-KEY CONTRACT: every variant's `as_str()` matches serde's
989 /// PascalCase output verbatim. A future variant rename (or an
990 /// `as_str` arm typo) lands at one site, instead of drifting
991 /// between the typed surface, the K8s `kind:` manifest field, and
992 /// the YAML wire format the reconciler / operator both read.
993 #[test]
994 fn workload_kind_as_str_matches_serde() {
995 crate::tagged_union::assert_label_matches_serde_serialization::<WorkloadKind>();
996 }
997
998 /// The Display impl IS `as_str` — pinning this lets future callers
999 /// reach for either projection without drift. If a reviewer
1000 /// accidentally re-introduces an inline match in Display, this
1001 /// test would fail the moment a variant rename touches one site
1002 /// but not the other.
1003 #[test]
1004 fn workload_kind_display_matches_as_str() {
1005 crate::tagged_union::assert_display_matches_label::<WorkloadKind>();
1006 }
1007
1008 /// `FromStr` rejects strings that aren't in the canonical
1009 /// projection — lowercased / typo / unrelated — and the error
1010 /// echoes the input verbatim so the operator-facing diagnostic
1011 /// carries the offending value, not a normalized form. The
1012 /// empty-input arm is pinned by
1013 /// [`workload_kind_is_well_formed_closed_set`] via the
1014 /// `tatara_lisp::ClosedSet` testkit; the cases here pin the
1015 /// verbatim-echo contract on the [`UnknownWorkloadKind`]
1016 /// newtype, which the trait's `make_unknown` can't see.
1017 #[test]
1018 fn unknown_workload_kind_errors() {
1019 use std::str::FromStr;
1020 for bad in ["deployment", "JOB", "ReplicaSet", "Pod"] {
1021 let err = WorkloadKind::from_str(bad).unwrap_err();
1022 assert_eq!(err.0, bad, "error payload should echo input verbatim");
1023 }
1024 }
1025
1026 #[test]
1027 fn workload_kind_default_is_deployment() {
1028 assert_eq!(WorkloadKind::default(), WorkloadKind::Deployment);
1029 }
1030
1031 /// TRUTH-TABLE CONTRACT: `api_version` / `is_batch` agree with the
1032 /// documented (kind) -> (apiVersion, is_batch) table for every
1033 /// variant. A new variant in `WorkloadKind` without extending
1034 /// either projection's match is caught by the compiler (closed-set
1035 /// match in each method); adding a variant without extending its
1036 /// truth row is caught here. Also pins the invariant
1037 /// `is_batch <=> api_version == "batch/v1"`, so a future renderer
1038 /// can route on either projection without re-deriving the partition.
1039 #[test]
1040 fn workload_kind_projection_truth_table() {
1041 let table: &[(WorkloadKind, &str, bool)] = &[
1042 // (kind, api_version, is_batch)
1043 (WorkloadKind::Deployment, "apps/v1", false),
1044 (WorkloadKind::StatefulSet, "apps/v1", false),
1045 (WorkloadKind::DaemonSet, "apps/v1", false),
1046 (WorkloadKind::Job, "batch/v1", true),
1047 (WorkloadKind::CronJob, "batch/v1", true),
1048 ];
1049 assert_eq!(table.len(), WorkloadKind::ALL.len());
1050 for (kind, api, batch) in table {
1051 assert_eq!(kind.api_version(), *api, "api_version drift for {kind:?}");
1052 assert_eq!(kind.is_batch(), *batch, "is_batch drift for {kind:?}");
1053 assert_eq!(
1054 kind.is_batch(),
1055 kind.api_version() == "batch/v1",
1056 "is_batch / api_version partition disagrees for {kind:?}"
1057 );
1058 }
1059 }
1060
1061 #[test]
1062 fn aplicacao_plus_flux_is_ambiguous() {
1063 let i = Intent {
1064 aplicacao: Some(AplicacaoIntent {
1065 chart_ref: "x".into(),
1066 version: "1".into(),
1067 profile: String::new(),
1068 values_overlay: serde_json::Value::Null,
1069 release_name: None,
1070 target_namespace: None,
1071 install_timeout: None,
1072 }),
1073 flux: Some(FluxIntent {
1074 git_repository: "g".into(),
1075 path: "p".into(),
1076 git_repository_namespace: None,
1077 target_namespace: None,
1078 decrypt_sops: true,
1079 helm_chart: None,
1080 helm_values: None,
1081 }),
1082 ..Intent::default()
1083 };
1084 assert_eq!(i.variant().unwrap_err(), IntentError::Ambiguous);
1085 }
1086
1087 // ── Helm lifecycle policy — install / upgrade slot substrate ────
1088
1089 fn helm_intent(install_timeout: Option<&str>) -> AplicacaoIntent {
1090 AplicacaoIntent {
1091 chart_ref: "oci://ghcr.io/pleme-io/charts/lareira-demo-app".into(),
1092 version: "0.5.5".into(),
1093 profile: String::new(),
1094 values_overlay: serde_json::Value::Null,
1095 release_name: None,
1096 target_namespace: None,
1097 install_timeout: install_timeout.map(str::to_string),
1098 }
1099 }
1100
1101 /// The workspace-wide default timeout const is pinned to `25m`.
1102 /// A regression that renamed it to any other duration would
1103 /// silently misroute every Helm-driven Process's default retry
1104 /// budget, so pin the byte-exact spelling here rather than at
1105 /// every consumer's own callsite.
1106 #[test]
1107 fn helm_lifecycle_default_timeout_is_pinned_to_25m() {
1108 assert_eq!(HELM_LIFECYCLE_DEFAULT_TIMEOUT, "25m");
1109 }
1110
1111 /// The workspace-wide default retries const is pinned to `3`.
1112 /// Peer to the `_timeout` pin; same rationale.
1113 #[test]
1114 fn helm_lifecycle_default_retries_is_pinned_to_three() {
1115 assert_eq!(HELM_LIFECYCLE_DEFAULT_RETRIES, 3);
1116 }
1117
1118 /// Fallback branch of the primitive: an intent that omitted
1119 /// `install_timeout` picks up the workspace-wide default
1120 /// (`25m` + retries `3`). Pin binds the "no override" shape
1121 /// every render / snapshot / dashboard consumer sees today.
1122 #[test]
1123 fn helm_lifecycle_policy_defaults_when_install_timeout_is_none() {
1124 let policy = helm_intent(None).helm_lifecycle_policy();
1125 assert_eq!(policy.timeout, HELM_LIFECYCLE_DEFAULT_TIMEOUT);
1126 assert_eq!(policy.remediation.retries, HELM_LIFECYCLE_DEFAULT_RETRIES);
1127 }
1128
1129 /// Override branch of the primitive: when the operator populated
1130 /// `install_timeout`, the primitive substitutes that string
1131 /// verbatim (no normalization, no trimming) — the reconciler
1132 /// hands the exact `humantime` shape to Flux, and any parse
1133 /// error surfaces from the chart-controller, not from here.
1134 #[test]
1135 fn helm_lifecycle_policy_uses_install_timeout_when_present() {
1136 for shape in ["10m", "1h30m", "5s", "25m", "0s"] {
1137 let policy = helm_intent(Some(shape)).helm_lifecycle_policy();
1138 assert_eq!(
1139 policy.timeout, shape,
1140 "override shape {shape} not substituted verbatim"
1141 );
1142 // Retries stay at the workspace default regardless of timeout.
1143 assert_eq!(policy.remediation.retries, HELM_LIFECYCLE_DEFAULT_RETRIES);
1144 }
1145 }
1146
1147 /// Coherence axis: the retries slot is invariant across every
1148 /// timeout shape the operator might publish — a regression that
1149 /// coupled the two slots (e.g. "when timeout is short, retry
1150 /// more") surfaces here rather than at every consumer.
1151 #[test]
1152 fn helm_lifecycle_policy_retries_are_invariant_across_timeout_shapes() {
1153 let seen: std::collections::BTreeSet<u8> = [None, Some("1m"), Some("25m"), Some("2h")]
1154 .into_iter()
1155 .map(|t| helm_intent(t).helm_lifecycle_policy().remediation.retries)
1156 .collect();
1157 assert_eq!(
1158 seen.len(),
1159 1,
1160 "retries should be constant across timeout shapes"
1161 );
1162 assert_eq!(
1163 seen.into_iter().next(),
1164 Some(HELM_LIFECYCLE_DEFAULT_RETRIES)
1165 );
1166 }
1167
1168 /// Wire-shape pin: the serde projection matches Flux
1169 /// `HelmRelease.spec.{install,upgrade}` v2 byte-identically —
1170 /// `{"timeout": <string>, "remediation": {"retries": <int>}}`
1171 /// with no extra keys, no field renames, no camelCase surprises.
1172 /// A regression that added a slot to `HelmLifecyclePolicy` or
1173 /// renamed one would fail here rather than as a Flux CR
1174 /// rejection at every deployment.
1175 #[test]
1176 fn helm_lifecycle_policy_serializes_to_flux_hr_v2_install_upgrade_shape() {
1177 let policy = helm_intent(Some("10m")).helm_lifecycle_policy();
1178 let json = serde_json::to_value(&policy).unwrap();
1179 assert_eq!(
1180 json,
1181 serde_json::json!({
1182 "timeout": "10m",
1183 "remediation": { "retries": 3 },
1184 }),
1185 );
1186 }
1187
1188 /// Coherence axis: `HelmLifecyclePolicy::workspace_default()`
1189 /// composes byte-identically to the intent-derived policy of an
1190 /// intent with `install_timeout: None` — the two paths to the
1191 /// substrate default (via the `Aplicacao` intent's own resolver
1192 /// vs the standalone workspace-default constructor) yield the
1193 /// same shape. Binds the "workspace_default IS the fallback"
1194 /// invariant so a future divergence (e.g. workspace_default
1195 /// changes but the intent resolver's inline fallback does not)
1196 /// surfaces here rather than as a silent drift at every render
1197 /// callsite.
1198 #[test]
1199 fn helm_lifecycle_policy_workspace_default_matches_intent_fallback_branch() {
1200 let default_policy = HelmLifecyclePolicy::workspace_default();
1201 let intent_policy = helm_intent(None).helm_lifecycle_policy();
1202 assert_eq!(default_policy, intent_policy);
1203 }
1204
1205 // ── Flux reconcile interval — OCIRepository + HelmRelease shared ─
1206
1207 /// The workspace-wide default Flux reconcile-interval const is
1208 /// pinned to `5m`. A regression that renamed it would silently
1209 /// throttle or hammer every Helm-driven Process's OCIRepository
1210 /// pull cadence AND its HelmRelease reconcile cadence, so pin
1211 /// the byte-exact spelling here rather than at the two render
1212 /// callsites the primitive owns.
1213 #[test]
1214 fn flux_helm_default_interval_is_pinned_to_5m() {
1215 assert_eq!(FLUX_HELM_DEFAULT_INTERVAL, "5m");
1216 }
1217
1218 /// The intent-side composer returns the workspace-wide default
1219 /// verbatim today. A regression that hand-authored some other
1220 /// string here (or that stopped routing through the const)
1221 /// would surface at this pin.
1222 #[test]
1223 fn flux_reconcile_interval_returns_workspace_default() {
1224 assert_eq!(
1225 helm_intent(None).flux_reconcile_interval(),
1226 FLUX_HELM_DEFAULT_INTERVAL,
1227 );
1228 }
1229
1230 /// Coherence axis: the reconcile interval is invariant across
1231 /// every `install_timeout` shape the operator publishes today.
1232 /// Pre-lift the two slots were siblings hand-authored with the
1233 /// same `"5m"` value regardless of any other AplicacaoIntent
1234 /// shape; post-lift the same invariance holds through the
1235 /// composer. A future coupling (e.g. "when timeout is short,
1236 /// reconcile more often") lands at the composer's shape, not
1237 /// silently at any render callsite.
1238 #[test]
1239 fn flux_reconcile_interval_is_invariant_across_install_timeout_shapes() {
1240 let seen: std::collections::BTreeSet<String> =
1241 [None, Some("10m"), Some("1h30m"), Some("25m"), Some("2h")]
1242 .into_iter()
1243 .map(|t| helm_intent(t).flux_reconcile_interval())
1244 .collect();
1245 assert_eq!(
1246 seen.len(),
1247 1,
1248 "reconcile interval should be constant across install_timeout shapes"
1249 );
1250 assert_eq!(
1251 seen.into_iter().next().as_deref(),
1252 Some(FLUX_HELM_DEFAULT_INTERVAL),
1253 );
1254 }
1255}