Skip to main content

workload_spec/
validate.rs

1//! Shape validators for [`WorkloadSpec`].
2//!
3//! Called by clients (desktop, agent, CLI) before sending a spec over RPC.
4//! Sync, no I/O. Returns `Ok(warnings)` on pass or `Err(ShapeError)` on the
5//! first hard constraint violation.
6//!
7//! Layers: shape (this file, no I/O) → semantic (yubaba-side, R090-F3) →
8//! environment (deploy-time, R090-F4).
9
10use std::fmt;
11use std::sync::OnceLock;
12
13use regex::Regex;
14use thiserror::Error;
15
16use crate::{
17    EnvValue, EnvVar, ImageRef, LifecycleArchetype, MachineId, MeshIdent, MeshLookup,
18    RestartPolicy, SecretRef, SecretTarget, StaticAssetWorkload, Supply, VolumeSource,
19    WorkloadSpec, DURABILITY_SUBJECTS_ANNOTATION, DURABILITY_TIER_ANNOTATION,
20};
21
22// ── Field paths ───────────────────────────────────────────────────────────────
23
24/// Identifies the field that caused a shape error or warning.
25///
26/// Structured as an enum so promoting to all-errors mode (collecting into
27/// `Vec<FieldError>` instead of returning on the first hit) is mechanical.
28#[derive(Debug, Clone, PartialEq)]
29pub enum FieldPath {
30    Name,
31    MeshIdentity,
32    TailscaleTag,
33    Replicas,
34    ImageTag,
35    Tier,
36    /// `volumes[index].<sub>` — e.g. `Volume(0, "source")`.
37    Volume(usize, &'static str),
38    /// Public port not found in `expose.mesh.ports`.
39    ExposeMeshPort(u16),
40    /// `expose.mesh.ports[index]` — a malformed port declaration (R844-F17):
41    /// an empty entry, a bad name, or a name/number repeated within the list.
42    MeshPort(usize),
43    /// `secrets[index].<sub>` — e.g. `Secret(0, "target.path")`.
44    Secret(usize, &'static str),
45    /// `healthcheck.<sub>`.
46    Healthcheck(&'static str),
47    RestartPolicy,
48    /// `image` — registry says the image/tag is unknown.
49    Image,
50    /// `depends_on[index]` — mesh ident is not a known deployed workload.
51    DependsOn(usize),
52    /// `requires[index]` — a malformed requirement (R860-T1): a `supply` /
53    /// `provides` mismatch, a provider whose spec names a different identity,
54    /// a nested `self` supply, or a repeated / self-naming ident.
55    Requires(usize),
56    /// `expose.public.hostname` — hostname is not in an owned CF zone.
57    Hostname,
58    /// `resources` — machine lacks sufficient capacity.
59    Resources,
60    /// `aliases[key]` — alias target filename is not in the `[[asset]]` catalog.
61    AssetAlias(String),
62    /// `asset[index].<sub>` — e.g. `Asset(0, "source")` for the XOR rule.
63    Asset(usize, &'static str),
64    /// `annotations["<key>"]` — a declaration carried as an annotation rather
65    /// than a field, because `WorkloadSpec` crosses a positional postcard wire
66    /// (R590-B3). `yah.durability.tier` is the first.
67    Annotation(&'static str),
68}
69
70impl fmt::Display for FieldPath {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self {
73            FieldPath::Name => write!(f, "name"),
74            FieldPath::MeshIdentity => write!(f, "expose.mesh.identity"),
75            FieldPath::TailscaleTag => write!(f, "expose.operator.tailscale_tag"),
76            FieldPath::Replicas => write!(f, "replicas"),
77            FieldPath::ImageTag => write!(f, "image.tag"),
78            FieldPath::Tier => write!(f, "tier"),
79            FieldPath::Volume(i, sub) => write!(f, "volumes[{i}].{sub}"),
80            FieldPath::ExposeMeshPort(port) => write!(f, "expose.public.port ({port})"),
81            FieldPath::MeshPort(i) => write!(f, "expose.mesh.ports[{i}]"),
82            FieldPath::Secret(i, sub) => write!(f, "secrets[{i}].{sub}"),
83            FieldPath::Healthcheck(sub) => write!(f, "healthcheck.{sub}"),
84            FieldPath::RestartPolicy => write!(f, "restart_policy"),
85            FieldPath::Image => write!(f, "image"),
86            FieldPath::DependsOn(i) => write!(f, "depends_on[{i}]"),
87            FieldPath::Requires(i) => write!(f, "requires[{i}]"),
88            FieldPath::Hostname => write!(f, "expose.public.hostname"),
89            FieldPath::Resources => write!(f, "resources"),
90            FieldPath::AssetAlias(key) => write!(f, "aliases[{key}]"),
91            FieldPath::Asset(i, sub) => write!(f, "asset[{i}].{sub}"),
92            FieldPath::Annotation(key) => write!(f, "annotations[\"{key}\"]"),
93        }
94    }
95}
96
97// ── Hard errors ───────────────────────────────────────────────────────────────
98
99/// A hard constraint violation that makes a spec impossible to deploy.
100///
101/// V1 surfaces the first error found. When the UI needs per-field
102/// highlighting, wrap in `Vec<ShapeError>` and collect instead of returning
103/// early — the `FieldPath` enum is already the common currency.
104#[derive(Debug, Error, PartialEq)]
105pub enum ShapeError {
106    #[error("field {path}: {reason}")]
107    Field { path: FieldPath, reason: String },
108}
109
110// ── Soft warnings ─────────────────────────────────────────────────────────────
111
112/// A soft check that passed but may indicate misconfiguration.
113#[derive(Debug, Clone, PartialEq)]
114pub struct ShapeWarning {
115    pub path: FieldPath,
116    pub message: String,
117}
118
119impl fmt::Display for ShapeWarning {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        write!(f, "warning at {}: {}", self.path, self.message)
122    }
123}
124
125// ── Internal helpers ──────────────────────────────────────────────────────────
126
127/// V1 known tier values. Unknown tiers produce a warning, not an error
128/// (cluster config may add custom tiers).
129const KNOWN_TIERS: &[&str] = &["public", "tenant", "private", "infra"];
130
131fn dns_label_re() -> &'static Regex {
132    static RE: OnceLock<Regex> = OnceLock::new();
133    RE.get_or_init(|| Regex::new(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$").unwrap())
134}
135
136fn env_name_re() -> &'static Regex {
137    static RE: OnceLock<Regex> = OnceLock::new();
138    RE.get_or_init(|| Regex::new(r"^[A-Z_][A-Z0-9_]*$").unwrap())
139}
140
141/// Validates a single DNS label: `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`, ≤ 63 chars.
142fn check_dns_label(value: &str, path: FieldPath) -> Result<(), ShapeError> {
143    if value.len() > 63 {
144        return Err(ShapeError::Field {
145            path,
146            reason: format!("length {} exceeds maximum 63", value.len()),
147        });
148    }
149    if !dns_label_re().is_match(value) {
150        return Err(ShapeError::Field {
151            path,
152            reason: format!(
153                "{:?} must match ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",
154                value
155            ),
156        });
157    }
158    Ok(())
159}
160
161/// Validates a dot-separated mesh identity where each segment is a DNS label.
162/// Total length ≤ 63. Example valid value: `"noisetable-api.pdx"`.
163fn check_mesh_ident(value: &str, path: FieldPath) -> Result<(), ShapeError> {
164    if value.len() > 63 {
165        return Err(ShapeError::Field {
166            path,
167            reason: format!("length {} exceeds maximum 63", value.len()),
168        });
169    }
170    for segment in value.split('.') {
171        if !dns_label_re().is_match(segment) {
172            return Err(ShapeError::Field {
173                path,
174                reason: format!(
175                    "segment {:?} in {:?} must match ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",
176                    segment, value
177                ),
178            });
179        }
180    }
181    Ok(())
182}
183
184/// The longest a port name may be. Matches IANA's service-name limit, which is
185/// what Kubernetes uses for the same field and what any tool that has to render
186/// a port name in a fixed column already assumes.
187const MESH_PORT_NAME_MAX: usize = 15;
188
189/// Validates `expose.mesh.ports` (R844-F17): every entry states something, every
190/// name is a DNS label short enough to be a service name, and nothing is
191/// declared twice.
192///
193/// The uniqueness rules are the load-bearing half. A repeated *name* would make
194/// `name -> port` ambiguous at exactly the moment a consumer asks for it —
195/// `ServiceRecord::port("http")` and the `PORT_HTTP` variable both resolve
196/// through that map — and a repeated *number* is a workload asking to bind one
197/// socket twice. Both are caught here rather than at bring-up because the
198/// author can still see the manifest.
199fn check_mesh_ports(
200    mesh: &crate::MeshExpose,
201    warnings: &mut Vec<ShapeWarning>,
202) -> Result<(), ShapeError> {
203    let mut seen_names: Vec<&str> = Vec::new();
204    let mut seen_numbers: Vec<u16> = Vec::new();
205
206    for (i, port) in mesh.ports.iter().enumerate() {
207        let path = FieldPath::MeshPort(i);
208
209        if port.name.is_none() && port.number.is_none() {
210            return Err(ShapeError::Field {
211                path,
212                reason: "declares neither a name nor a number — write a number \
213                         (8080), a name (\"http\"), or both \
214                         ({ name = \"http\", port = 8080 })"
215                    .to_string(),
216            });
217        }
218
219        if let Some(name) = port.name.as_deref() {
220            if name.len() > MESH_PORT_NAME_MAX {
221                return Err(ShapeError::Field {
222                    path,
223                    reason: format!(
224                        "port name {name:?} is {} characters; the maximum is \
225                         {MESH_PORT_NAME_MAX}",
226                        name.len()
227                    ),
228                });
229            }
230            if !dns_label_re().is_match(name) {
231                return Err(ShapeError::Field {
232                    path,
233                    reason: format!(
234                        "port name {name:?} must match \
235                         ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$"
236                    ),
237                });
238            }
239            if seen_names.contains(&name) {
240                return Err(ShapeError::Field {
241                    path,
242                    reason: format!(
243                        "port name {name:?} is declared twice; a name is how a \
244                         consumer selects one port, so it has to pick out \
245                         exactly one"
246                    ),
247                });
248            }
249            seen_names.push(name);
250        }
251
252        match port.number {
253            Some(number) => {
254                if seen_numbers.contains(&number) {
255                    return Err(ShapeError::Field {
256                        path,
257                        reason: format!(
258                            "port {number} is declared twice; a workload cannot \
259                             bind the same port on two listeners"
260                        ),
261                    });
262                }
263                seen_numbers.push(number);
264            }
265            // Still a warning rather than an error, but R844-F21 changed what
266            // it has to say. A name-only port IS allocated now — on the native
267            // backend, which owns the workload's network namespace: kamaji
268            // picks the number, remembers it per `(ident, name)` across a
269            // restart, and hands it to the process as `PORT_<NAME>`.
270            //
271            // It is still unbindable on a container backend, where the ports
272            // are the image's and both backends refuse the spelling outright
273            // (`kamaji::reject_unresolved_ports`). Shape validation cannot tell
274            // which backend a spec will land on — placement decides that later
275            // — so naming the split is the most this layer can honestly say,
276            // and it is why an error here would be wrong.
277            None => warnings.push(ShapeWarning {
278                path,
279                message: format!(
280                    "port {:?} declares no number: the native backend allocates \
281                     one and tells the process via PORT_{}, but a container \
282                     backend refuses it — a container's ports are its image's. \
283                     State the number ({{ name = {:?}, port = <n> }}) if this \
284                     workload runs as a container.",
285                    port.name.as_deref().unwrap_or_default(),
286                    port.name
287                        .as_deref()
288                        .unwrap_or_default()
289                        .to_uppercase()
290                        .replace(|c: char| !c.is_ascii_alphanumeric(), "_"),
291                    port.name.as_deref().unwrap_or_default(),
292                ),
293            }),
294        }
295    }
296
297    Ok(())
298}
299
300/// Validates `requires` (R860-T1 / W338): the `supply` / `provides` pairing,
301/// the identity a self-provisioned provider claims, the depth bound on the
302/// recursion, and ident uniqueness.
303///
304/// The depth bound is the load-bearing rule. `Requirement::provides` makes
305/// `WorkloadSpec` recursive, and a provider that may itself self-provision
306/// turns "a workload plus its sidecars" into an unbounded tree that placement
307/// would have to flatten before it could schedule anything. One level is what
308/// the design asks for, so one level is what is representable.
309fn check_requires(spec: &WorkloadSpec) -> Result<(), ShapeError> {
310    let mut seen: Vec<&str> = Vec::new();
311
312    for (i, req) in spec.requires.iter().enumerate() {
313        let path = || FieldPath::Requires(i);
314        let ident = req.ident.0.as_str();
315
316        if ident == spec.expose.mesh.identity.0 {
317            return Err(ShapeError::Field {
318                path: path(),
319                reason: format!(
320                    "requires its own identity {ident:?}; a workload cannot be \
321                     its own provider"
322                ),
323            });
324        }
325        if seen.contains(&ident) {
326            return Err(ShapeError::Field {
327                path: path(),
328                reason: format!(
329                    "ident {ident:?} is declared twice; one requirement per \
330                     provider, since a second entry could only contradict the \
331                     first's locality or supply"
332                ),
333            });
334        }
335        seen.push(ident);
336
337        match (req.supply, &req.provides) {
338            (Supply::SelfProvision, None) => {
339                return Err(ShapeError::Field {
340                    path: path(),
341                    reason: format!(
342                        "supply = \"self\" on {ident:?} but no `provides` spec; \
343                         a self-provisioned requirement is the one that carries \
344                         its provider, so there is nothing to stand up"
345                    ),
346                });
347            }
348            (Supply::Wait, Some(_)) => {
349                return Err(ShapeError::Field {
350                    path: path(),
351                    reason: format!(
352                        "supply = \"wait\" on {ident:?} but a `provides` spec is \
353                         present; a waiting requirement names a provider someone \
354                         else declares, so this spec would have no owner — set \
355                         supply = \"self\" to deploy it here"
356                    ),
357                });
358            }
359            (Supply::Wait, None) => {}
360            (Supply::SelfProvision, Some(provided)) => {
361                if provided.expose.mesh.identity.0 != ident {
362                    return Err(ShapeError::Field {
363                        path: path(),
364                        reason: format!(
365                            "`provides` declares expose.mesh.identity {:?} but the \
366                             requirement names {ident:?}; the provider keeps its \
367                             own mesh identity and it has to be the one this \
368                             requirement asks for (its `name` is {:?})",
369                            provided.expose.mesh.identity.0, provided.name
370                        ),
371                    });
372                }
373                if let Some(nested) = provided
374                    .requires
375                    .iter()
376                    .find(|r| matches!(r.supply, Supply::SelfProvision))
377                {
378                    return Err(ShapeError::Field {
379                        path: path(),
380                        reason: format!(
381                            "`provides` spec {ident:?} itself requires {:?} with \
382                             supply = \"self\"; composition is bounded at one \
383                             level, so a provider may only wait on things it \
384                             does not deploy — hoist that requirement up to this \
385                             spec's own `requires`",
386                            nested.ident.0
387                        ),
388                    });
389                }
390            }
391        }
392    }
393
394    Ok(())
395}
396
397// ── Public API ────────────────────────────────────────────────────────────────
398
399/// Run shape validation — sync, no I/O.
400///
401/// Returns `Ok(warnings)` when all hard constraints pass; the `Vec` is empty
402/// for a clean spec. Returns `Err` on the first hard constraint violation.
403/// Callers that only need hard errors can discard the Ok value with
404/// `.map(|_| ())`.
405///
406/// Hard constraints checked:
407/// - `name`, `expose.mesh.identity`: DNS-label format, ≤ 63 chars.
408/// - `expose.operator.tailscale_tag`: `"tag:<dns-label>"`, ≤ 63 chars.
409/// - `replicas`: 0–100.
410/// - `image.tag`: non-empty when `digest` is `None`.
411/// - `volumes[*].source = Bind`: only allowed when `tier = "infra"`.
412/// - `expose.mesh.ports[*]`: each entry states a name and/or a number; names are
413///   DNS labels ≤ 15 chars; no name and no number is declared twice (R844-F17).
414/// - `expose.public.port`: must appear in `expose.mesh.ports`.
415/// - `secrets[*].target`: file paths must be absolute; env-var names must
416///   match `^[A-Z_][A-Z0-9_]*$`.
417/// - `requires[*]`: `supply = "self"` carries a `provides` spec and
418///   `supply = "wait"` does not; a `provides` spec declares the identity its
419///   requirement names; a `provides` spec carries no `self` supply of its own
420///   (depth 1); idents are unique and none is the spec's own (R860-T1).
421///
422/// Soft checks (produce warnings, not errors):
423/// - `expose.mesh.ports[*]`: a name with no number — nothing allocates from the
424///   manifest yet, so nothing binds it (R844-F17).
425/// - Unknown tier value.
426/// - `RestartPolicy::Never` without `annotations["yah.forge"] = "true"`.
427/// - `healthcheck.initial_delay < stop_policy.grace_period * 2`.
428pub fn shape(spec: &WorkloadSpec) -> Result<Vec<ShapeWarning>, ShapeError> {
429    let mut warnings: Vec<ShapeWarning> = Vec::new();
430
431    // name: single DNS label, ≤ 63 chars
432    check_dns_label(&spec.name, FieldPath::Name)?;
433
434    // expose.mesh.identity: dot-separated DNS name, ≤ 63 total
435    check_mesh_ident(&spec.expose.mesh.identity.0, FieldPath::MeshIdentity)?;
436
437    // expose.operator.tailscale_tag: "tag:<dns-label>", ≤ 63 chars (optional)
438    if let Some(op) = &spec.expose.operator {
439        let tag = &op.tailscale_tag;
440        if tag.len() > 63 {
441            return Err(ShapeError::Field {
442                path: FieldPath::TailscaleTag,
443                reason: format!("length {} exceeds maximum 63", tag.len()),
444            });
445        }
446        let rest = tag.strip_prefix("tag:").ok_or_else(|| ShapeError::Field {
447            path: FieldPath::TailscaleTag,
448            reason: format!("{:?} must start with \"tag:\"", tag),
449        })?;
450        if !dns_label_re().is_match(rest) {
451            return Err(ShapeError::Field {
452                path: FieldPath::TailscaleTag,
453                reason: format!(
454                    "the part after \"tag:\" in {:?} must match \
455                     ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",
456                    tag
457                ),
458            });
459        }
460    }
461
462    // replicas: 0..=100
463    if spec.replicas > 100 {
464        return Err(ShapeError::Field {
465            path: FieldPath::Replicas,
466            reason: format!("{} exceeds maximum 100", spec.replicas),
467        });
468    }
469
470    // image.tag: non-empty (informational identifier; digest is the source of
471    // truth and is structurally required at the type level).
472    if spec.image.tag.is_empty() {
473        return Err(ShapeError::Field {
474            path: FieldPath::ImageTag,
475            reason: "tag is empty; provide a human-readable tag alongside the digest".into(),
476        });
477    }
478
479    // tier: warn on unknown (cluster config may add custom tiers)
480    if !KNOWN_TIERS.contains(&spec.tier.0.as_str()) {
481        warnings.push(ShapeWarning {
482            path: FieldPath::Tier,
483            message: format!(
484                "\"{}\" is not in the known tier set (public/tenant/private/infra); \
485                 yubaba may reject it if the cluster config does not include this tier",
486                spec.tier.0
487            ),
488        });
489    }
490
491    // volumes[*]: Bind rejected unless tier = "infra"
492    for (i, vol) in spec.volumes.iter().enumerate() {
493        if matches!(&vol.source, VolumeSource::Bind { .. }) && spec.tier.0 != "infra" {
494            return Err(ShapeError::Field {
495                path: FieldPath::Volume(i, "source"),
496                reason: format!(
497                    "Bind mounts are only allowed when tier = \"infra\" \
498                     (current tier: {:?})",
499                    spec.tier.0
500                ),
501            });
502        }
503    }
504
505    // expose.mesh.ports[*]: names well-formed, nothing declared twice (R844-F17)
506    check_mesh_ports(&spec.expose.mesh, &mut warnings)?;
507
508    // requires[*]: supply/provides pairing, provider identity, depth bound,
509    // ident uniqueness (R860-T1)
510    check_requires(spec)?;
511
512    // expose.public.port must appear in expose.mesh.ports
513    if let Some(public) = &spec.expose.public {
514        if !spec.expose.mesh.declares_number(public.port) {
515            return Err(ShapeError::Field {
516                path: FieldPath::ExposeMeshPort(public.port),
517                reason: format!(
518                    "port {} must appear in expose.mesh.ports {:?} \
519                     before it can be exposed publicly",
520                    public.port,
521                    spec.expose.mesh.numbers()
522                ),
523            });
524        }
525    }
526
527    // secrets[*]: target paths absolute; env-var names valid identifiers
528    for (i, secret) in spec.secrets.iter().enumerate() {
529        match &secret.target {
530            SecretTarget::File { path, .. } => {
531                if !path.is_absolute() {
532                    return Err(ShapeError::Field {
533                        path: FieldPath::Secret(i, "target.path"),
534                        reason: format!("{:?} is not an absolute path", path),
535                    });
536                }
537            }
538            SecretTarget::EnvVar { name } => {
539                if !env_name_re().is_match(name) {
540                    return Err(ShapeError::Field {
541                        path: FieldPath::Secret(i, "target.name"),
542                        reason: format!(
543                            "{:?} is not a valid env-var identifier (^[A-Z_][A-Z0-9_]*$)",
544                            name
545                        ),
546                    });
547                }
548            }
549        }
550    }
551
552    // soft: RestartPolicy::Never without yah.forge=true annotation
553    if matches!(spec.restart_policy, RestartPolicy::Never) {
554        let is_forge = spec
555            .annotations
556            .get("yah.forge")
557            .map(|v| v == "true")
558            .unwrap_or(false);
559        if !is_forge {
560            warnings.push(ShapeWarning {
561                path: FieldPath::RestartPolicy,
562                message: "restart_policy=Never is intended for forge runs; \
563                          add annotation yah.forge=true to suppress this warning"
564                    .into(),
565            });
566        }
567    }
568
569    // yah.durability.*: a malformed declaration is hard, and a stateful
570    // workload with no declaration at all is soft (R850-P4).
571    //
572    // The asymmetry is deliberate. Refusing every undeclared appliance would
573    // fail every spec in the tree on the day the annotation shipped; reading a
574    // *malformed* one as "undeclared" would let `tier = "streem"` mean "no
575    // backups" silently, which is the failure this whole surface exists to
576    // stop. See `WorkloadSpec::durability`.
577    let durability = spec
578        .durability()
579        .map_err(|e| ShapeError::Field {
580            path: FieldPath::Annotation(DURABILITY_TIER_ANNOTATION),
581            reason: e.to_string(),
582        })?;
583    // R850-F1: a bytes-shipping tier's subjects are volume-relative, so there
584    // has to be exactly one volume for them to be relative *to*. Zero means the
585    // declaration names files that will never exist; two or more means the
586    // hydrate helper would have to guess which host directory to restore into,
587    // and a wrong guess writes somebody's database over somebody else's.
588    //
589    // A **bind** counts, not only a yubaba-managed named volume. The rule was
590    // named-only until R858-F17 named the case it excluded: headscale keeps its
591    // state at `/var/lib/yah-cloud/headscale/`, is a native-exec appliance, and
592    // has no named volume and never will — so the narrow rule made the one
593    // workload whose loss took this camp's mesh down for 37 hours the one
594    // workload that could not declare durability. A bind is already restricted
595    // to `tier = "infra"` below, which is exactly the class this applies to.
596    if let Some(d) = durability.as_ref().filter(|d| d.tier.ships_bytes()) {
597        let roots: Vec<String> = spec
598            .volumes
599            .iter()
600            .filter_map(|v| match &v.source {
601                VolumeSource::Named { name } => Some(name.clone()),
602                VolumeSource::Bind { host_path } => Some(host_path.display().to_string()),
603                // Tmpfs is deliberately not a candidate: it is the declaration
604                // that this data does not survive the process, so counting it
605                // would let a spec claim durable state on a ramdisk.
606                VolumeSource::Tmpfs { .. } => None,
607            })
608            .collect();
609        if roots.len() != 1 {
610            return Err(ShapeError::Field {
611                path: FieldPath::Annotation(DURABILITY_SUBJECTS_ANNOTATION),
612                reason: format!(
613                    "{DURABILITY_TIER_ANNOTATION} = \"{}\" declares subjects {:?}, which are \
614                     relative to one volume, but this spec declares {} named-or-bind volumes{}; \
615                     a tier that ships bytes needs exactly one (tmpfs does not count — it is a \
616                     declaration that the data does not survive)",
617                    d.tier,
618                    d.subjects,
619                    roots.len(),
620                    if roots.is_empty() {
621                        String::new()
622                    } else {
623                        format!(" ({})", roots.join(", "))
624                    }
625                ),
626            });
627        }
628    }
629
630    if durability.is_none()
631        && spec.effective_archetype() == LifecycleArchetype::Appliance
632        && spec
633            .volumes
634            .iter()
635            .any(|v| matches!(v.source, VolumeSource::Named { .. }))
636    {
637        warnings.push(ShapeWarning {
638            path: FieldPath::Annotation(DURABILITY_TIER_ANNOTATION),
639            message: format!(
640                "appliance with a yubaba-managed named volume declares no durability \
641                 tier, so that volume is the only copy of its state and losing the node \
642                 loses it; declare {DURABILITY_TIER_ANNOTATION} = \"none\" if that is \
643                 intended, or a real tier if it is not"
644            ),
645        });
646    }
647
648    // soft: healthcheck.initial_delay >= stop_policy.grace_period * 2
649    if let Some(hc) = &spec.healthcheck {
650        let min_recommended = spec.stop_policy.grace_period.as_ms().saturating_mul(2);
651        if hc.initial_delay.as_ms() < min_recommended {
652            warnings.push(ShapeWarning {
653                path: FieldPath::Healthcheck("initial_delay"),
654                message: format!(
655                    "initial_delay ({}ms) is less than stop_policy.grace_period * 2 ({}ms); \
656                     a SIGTERM during startup may catch a still-initialising container",
657                    hc.initial_delay.as_ms(),
658                    min_recommended
659                ),
660            });
661        }
662    }
663
664    Ok(warnings)
665}
666
667// ── StaticAsset validator ─────────────────────────────────────────────────────
668
669/// Shape-validate a `kind = "static-asset"` workload.
670///
671/// Enforces the closed-catalog invariant: every value in `[aliases]` must be a
672/// `filename` present in `[[asset]]`. A mirror's `[asset_aliases]` overrides
673/// are bound by the same rule and are validated separately at sync time when
674/// both the workload and mirror are loaded together.
675pub fn shape_static_asset(workload: &StaticAssetWorkload) -> Result<(), ShapeError> {
676    // XOR rule (W164 / R438-T2): every [[asset]] row must set exactly one of
677    // `source` (legacy local bytes) or `derive` (fetch + optional transform).
678    // Both-set is ambiguous (which one wins?); neither-set leaves the
679    // reconciler with no bytes to upload.
680    for (i, entry) in workload.assets.iter().enumerate() {
681        match (entry.source.is_some(), entry.derive.is_some()) {
682            (true, true) => {
683                return Err(ShapeError::Field {
684                    path: FieldPath::Asset(i, "source"),
685                    reason: format!(
686                        "asset {:?}: both `source` and `derive` are set; pick exactly one",
687                        entry.filename
688                    ),
689                });
690            }
691            (false, false) => {
692                return Err(ShapeError::Field {
693                    path: FieldPath::Asset(i, "source"),
694                    reason: format!(
695                        "asset {:?}: neither `source` nor `derive` is set; pick exactly one",
696                        entry.filename
697                    ),
698                });
699            }
700            _ => {}
701        }
702    }
703
704    let filenames: std::collections::HashSet<&str> =
705        workload.assets.iter().map(|a| a.filename.as_str()).collect();
706
707    for (alias_key, alias_target) in &workload.aliases {
708        if !filenames.contains(alias_target.as_str()) {
709            return Err(ShapeError::Field {
710                path: FieldPath::AssetAlias(alias_key.clone()),
711                reason: format!(
712                    "alias target {:?} is not present in the [[asset]] catalog; \
713                     add a matching [[asset]] row or correct the filename",
714                    alias_target
715                ),
716            });
717        }
718    }
719
720    Ok(())
721}
722
723// ── Semantic layer ────────────────────────────────────────────────────────────
724
725/// Transient error from a [`ValidationContext`] lookup.
726///
727/// Distinct from a semantic "resource not found" failure. `ContextError` means
728/// the lookup itself could not complete (network timeout, auth failure, etc.),
729/// not that the resource is definitively absent.
730#[derive(Debug, Error, Clone, PartialEq)]
731#[error("context lookup failed: {0}")]
732pub struct ContextError(pub String);
733
734/// A semantic constraint violation: the spec references a resource that is not
735/// known to the cluster at validation time.
736#[derive(Debug, Error, PartialEq)]
737pub enum SemanticError {
738    #[error("field {path}: {reason}")]
739    Unknown { path: FieldPath, reason: String },
740}
741
742/// Top-level validation error spanning both shape and semantic layers.
743///
744/// `Shape` always wins: if the spec is structurally invalid, semantic checks
745/// never run.
746#[derive(Debug, Error, PartialEq)]
747pub enum WorkloadValidationError {
748    /// Hard shape constraint failed — spec is structurally invalid.
749    #[error("shape: {0}")]
750    Shape(ShapeError),
751
752    /// Semantic check failed — spec references an unknown cluster resource.
753    #[error("semantic: {0}")]
754    Semantic(SemanticError),
755
756    /// Transient ValidationContext lookup failure — the check itself failed.
757    #[error("context: {0}")]
758    Context(ContextError),
759}
760
761impl From<ShapeError> for WorkloadValidationError {
762    fn from(e: ShapeError) -> Self { WorkloadValidationError::Shape(e) }
763}
764
765impl From<ContextError> for WorkloadValidationError {
766    fn from(e: ContextError) -> Self { WorkloadValidationError::Context(e) }
767}
768
769/// Read-only view of yubaba state used for semantic validation.
770///
771/// Defined here so clients (desktop, CLI, agents) can run semantic checks
772/// without depending on the yubaba crate. Yubaba implements this trait.
773///
774/// Each method returns `Result<bool, ContextError>` so transient failures are
775/// distinguishable from definitive "not found" answers.
776pub trait ValidationContext {
777    /// True when the registry confirms the image exists.
778    fn image_exists(&self, image: &ImageRef) -> Result<bool, ContextError>;
779
780    /// True when the named secret exists in the yubaba secret store.
781    fn secret_exists(&self, secret: &SecretRef) -> Result<bool, ContextError>;
782
783    /// True when `ident` is a known deployed workload OR appears in `batch`
784    /// (the set of specs co-deployed in the same request — allows forward
785    /// references within a single deployment batch).
786    fn mesh_ident_known(&self, ident: &MeshIdent, batch: &[MeshIdent]) -> Result<bool, ContextError>;
787
788    /// True when `hostname` falls under a Cloudflare zone owned by this cluster.
789    fn cf_zone_owned(&self, hostname: &str) -> Result<bool, ContextError>;
790
791    /// True when `tag` (e.g. `"tag:noisetable-ops"`) is in the cluster's
792    /// Tailscale ACL tag list.
793    fn tailscale_tag_known(&self, tag: &str) -> Result<bool, ContextError>;
794
795    /// True when `machine_id` has sufficient remaining capacity to host the
796    /// given spec's resource requirements.
797    ///
798    /// Implementors: read memory via [`WorkloadSpec::memory_request_mb`], not
799    /// `spec.resources.memory_mb`. The latter is a cgroup ceiling, and using
800    /// it as a capacity floor is what made every build-worker smaller than
801    /// `for_forge`'s 32 GiB ceiling unschedulable in `admit_workload`. Only a
802    /// test implementation of this trait exists today, so the bug is not live
803    /// here — this note is to keep it from arriving with the first real one.
804    fn capacity_for(&self, spec: &WorkloadSpec, machine_id: &MachineId) -> Result<bool, ContextError>;
805}
806
807/// Run semantic validation — requires yubaba state via [`ValidationContext`].
808///
809/// Shape validation is NOT run here. Callers MUST run [`shape`] first; use
810/// [`all`] to enforce this automatically.
811///
812/// `machine_id` is the target machine for admission-control capacity checks.
813/// `batch` is the set of mesh idents being co-deployed (pass `&[]` for
814/// single-spec deployment); these count as "known" for `depends_on` resolution.
815pub fn semantic(
816    spec: &WorkloadSpec,
817    ctx: &dyn ValidationContext,
818    machine_id: &MachineId,
819    batch: &[MeshIdent],
820) -> Result<(), WorkloadValidationError> {
821    if !ctx.image_exists(&spec.image)? {
822        return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
823            path: FieldPath::Image,
824            reason: format!(
825                "image {}/{}:{} not found in registry",
826                spec.image.registry, spec.image.repository, spec.image.tag
827            ),
828        }));
829    }
830
831    for (i, secret) in spec.secrets.iter().enumerate() {
832        if !ctx.secret_exists(&secret.source)? {
833            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
834                path: FieldPath::Secret(i, "source"),
835                reason: format!("secret source at index {i} not found in yubaba secret store"),
836            }));
837        }
838    }
839
840    for (i, dep) in spec.depends_on.iter().enumerate() {
841        if !ctx.mesh_ident_known(dep, batch)? {
842            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
843                path: FieldPath::DependsOn(i),
844                reason: format!("mesh ident {:?} is not a known deployed workload", dep.0),
845            }));
846        }
847    }
848
849    if let Some(public) = &spec.expose.public {
850        if !ctx.cf_zone_owned(&public.hostname)? {
851            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
852                path: FieldPath::Hostname,
853                reason: format!(
854                    "hostname {:?} is not under a Cloudflare zone owned by this cluster",
855                    public.hostname
856                ),
857            }));
858        }
859    }
860
861    if let Some(op) = &spec.expose.operator {
862        if !ctx.tailscale_tag_known(&op.tailscale_tag)? {
863            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
864                path: FieldPath::TailscaleTag,
865                reason: format!(
866                    "tailscale tag {:?} is not in the cluster's ACL tag list",
867                    op.tailscale_tag
868                ),
869            }));
870        }
871    }
872
873    if !ctx.capacity_for(spec, machine_id)? {
874        return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
875            path: FieldPath::Resources,
876            reason: format!(
877                "machine {:?} lacks capacity (memory={}MB cpu_millis={} ephemeral={}MB)",
878                machine_id.0,
879                spec.resources.memory_mb,
880                spec.resources.cpu_millis,
881                spec.resources.ephemeral_storage_mb
882            ),
883        }));
884    }
885
886    Ok(())
887}
888
889// ── Mesh resolution layer ─────────────────────────────────────────────────────
890
891/// Failure surface for [`MeshResolver`] lookups.
892///
893/// `NotDeployed` means the dependency hasn't been observed in mesh state yet
894/// (yubaba's deploy step waits on this — see [`crate::EnvValue::FromMesh`]).
895/// `NoPorts` means the dependency is deployed but its `MeshExpose.ports`
896/// list is empty, so a port-based lookup can't render a value. `Lookup`
897/// covers transient failures from the underlying state read.
898#[derive(Debug, Error, Clone, PartialEq)]
899pub enum MeshError {
900    #[error("mesh ident {ident:?} is not yet deployed")]
901    NotDeployed { ident: String },
902
903    #[error(
904        "mesh ident {ident:?} exposes no ports; {lookup:?} requires at least one"
905    )]
906    NoPorts { ident: String, lookup: MeshLookup },
907
908    /// The peer exposes several ports and the lookup did not say which
909    /// (R844-B22). Deliberately an error rather than a pick — see
910    /// [`MeshLookup`]'s docs.
911    #[error(
912        "mesh ident {ident:?} exposes {} ports ({}) and none is named \"http\", \
913         so {lookup:?} cannot say which one to use. Name the port in the \
914         lookup (kind = \"port_named\", name = \"…\"), or name one of the \
915         peer's ports \"http\" in its expose.mesh.ports.",
916        .names.len(),
917        .names.join(", ")
918    )]
919    AmbiguousPort {
920        ident: String,
921        lookup: MeshLookup,
922        names: Vec<String>,
923    },
924
925    /// The lookup named a port the peer does not expose (R844-B22).
926    #[error(
927        "mesh ident {ident:?} exposes no port named {name:?}; it has {}",
928        if .available.is_empty() { "none".to_string() } else { .available.join(", ") }
929    )]
930    NoSuchPort {
931        ident: String,
932        name: String,
933        available: Vec<String>,
934    },
935
936    #[error("mesh state lookup failed: {0}")]
937    Lookup(String),
938}
939
940/// The port name a peer's sole/default listener carries. Agrees with
941/// `kamaji::DEFAULT_PORT_NAME` by convention rather than by import: kamaji sits
942/// *above* workload-spec in the publish DAG (`yah-base <- {qed,kamaji} <-
943/// yubaba`), so depending on it here would invert the graph. The two are pinned
944/// together by `default_port_name_agrees_with_the_supervisor` in this file's
945/// tests.
946pub const DEFAULT_PORT_NAME: &str = "http";
947
948/// Pick the port a [`MeshLookup`] refers to out of a peer's `name -> port` map
949/// (R844-B22) — the one place the rule lives, so every resolver answers the
950/// same way.
951///
952/// - A **named** lookup takes that port, or errors naming what the peer does
953///   have. No fallback: a lookup that asked for `wss` and silently got `http`
954///   would be the positional guess wearing a name.
955/// - An **unnamed** lookup takes the sole port when there is one, else the port
956///   named [`DEFAULT_PORT_NAME`], else errors. It never takes "the first",
957///   which is what this function exists to stop.
958pub fn select_mesh_port(
959    ident: &str,
960    ports: &std::collections::BTreeMap<String, u16>,
961    lookup: &MeshLookup,
962) -> Result<u16, MeshError> {
963    if let Some(name) = lookup.port_name() {
964        return ports.get(name).copied().ok_or_else(|| MeshError::NoSuchPort {
965            ident: ident.to_string(),
966            name: name.to_string(),
967            available: ports.keys().cloned().collect(),
968        });
969    }
970
971    let mut entries = ports.iter();
972    match (entries.next(), entries.next()) {
973        (None, _) => Err(MeshError::NoPorts {
974            ident: ident.to_string(),
975            lookup: lookup.clone(),
976        }),
977        (Some((_, &only)), None) => Ok(only),
978        _ => ports
979            .get(DEFAULT_PORT_NAME)
980            .copied()
981            .ok_or_else(|| MeshError::AmbiguousPort {
982                ident: ident.to_string(),
983                lookup: lookup.clone(),
984                names: ports.keys().cloned().collect(),
985            }),
986    }
987}
988
989/// Resolve [`crate::EnvValue::FromMesh`] references to literal env values.
990///
991/// Defined in workload-spec so clients (agents, desktop, CLI) can render
992/// specs against fake mesh state without depending on the yubaba crate.
993/// Yubaba's production implementation (in `yubaba::deploy::mesh_resolve`)
994/// reads from raft state.
995///
996/// **Resolution rules** (R844-B22 replaced the positional ones):
997/// - [`MeshLookup::Host`] — the bare DNS-ish identifier as authored (e.g.
998///   `"noisetable-db.pdx"`). Needs no port and resolves for a portless peer.
999/// - [`MeshLookup::Url`] — `"http://<ident>:<port>"`.
1000/// - [`MeshLookup::Port`] — that port stringified, e.g. `"5432"`.
1001/// - [`MeshLookup::UrlNamed`] / [`MeshLookup::PortNamed`] — the same, at the
1002///   peer's port of that name.
1003///
1004/// **Which port** is [`select_mesh_port`]'s decision, and implementations must
1005/// route through it rather than re-deriving: a sole port, else the one named
1006/// [`DEFAULT_PORT_NAME`], else an error. It is emphatically *not* "the first
1007/// entry", which is what this trait's doc used to promise — declaration order
1008/// is not a statement about which listener a dependent should dial, and acting
1009/// as if it were is how a workload gets handed a metrics port as its API URL.
1010///
1011/// Because the rule is name-based rather than positional, a `Url` and a `Port`
1012/// resolved in the same deploy agree by construction; the old doc had to ask
1013/// implementations to make the lookup atomic to get that.
1014pub trait MeshResolver {
1015    fn resolve(&self, ident: &MeshIdent, kind: MeshLookup) -> Result<String, MeshError>;
1016}
1017
1018/// Render every [`EnvValue::FromMesh`] entry in `env` to a [`EnvValue::Literal`]
1019/// using `resolver`; pass through `Literal` and `FromSecret` values unchanged.
1020///
1021/// Returns the first resolution error encountered. Callers should run this
1022/// after yubaba's stage-3 mesh peering completes (see
1023/// `yubaba::deploy::env_validate::run` doc), at containerd-spec assembly.
1024///
1025/// `FromSecret` values are deliberately untouched here — secret resolution
1026/// is the secrets layer's job (R090-F5), not the mesh resolver's.
1027///
1028/// @yah:ticket(R844-B22, "MeshLookup::Url and ::Port resolve &quot;the first entry in expose.mesh.ports&quot; — the positional guess this relay abolishes, in the env-injection path")
1029/// @yah:status(review)
1030/// @yah:at(2026-09-04T14:10:34Z)
1031/// @yah:assignee(agent:bundle-anthropic-ashguard)
1032/// @yah:parent(R844)
1033/// @yah:severity(medium)
1034/// @yah:gotcha("THE CLAIM IS IN THE TRAIT'S OWN DOC, so this is confirmed rather than inferred. `MeshResolver` (oss/yah-base/crates/workload-spec/src/validate.rs, \\\"Resolution rules\\\") states: `MeshLookup::Url` resolves to `\\\"http://&lt;ident&gt;:&lt;port&gt;\\\"` where port is \\\"the first entry in the referenced workload's `MeshExpose.ports`\\\", and `MeshLookup::Port` is \\\"the first port stringified\\\". That is precisely the index-guess `kamaji::name_anonymous_ports` refuses to make and that R844-F15's `ServiceRecordFanout::port_for` was rewritten to stop making — an ingress rule resolved off declaration order can publish a hostname at a metrics listener, and this path can hand a DEPENDENT WORKLOAD the same wrong number in its environment. Nothing has hit it because no fronted or depended-on workload declares two ports yet; that is the same reason F15 gave for the passway gap it left, and it stops being true the moment someone uses R844-F17's new spelling.")
1035/// @yah:next("THIS IS NOW FIXABLE, WHICH IS WHY IT IS FILED — before R844-F17 a manifest could not name a port, so \\\"first\\\" was the only selector available and the doc was describing a limitation rather than a bug. `MeshExpose::named_numbers()` and `kamaji::declared_port_names()` now give a name-keyed answer.")
1036/// @yah:next("SHAPE: add a named variant to `MeshLookup` (e.g. `Port { name: String }` / `Url { name: String }`) and make the unnamed forms resolve through the `http` rule instead of index 0 — i.e. one port resolves as today, several resolve to `http` if one is named that, and NONE otherwise. Returning an error when several ports are unnamed is the whole point: it sends the author to the manifest rather than handing a dependent a plausible wrong number. MIND THE WIRE: `MeshLookup` rides `EnvValue::FromMesh` inside `WorkloadSpec`, which crosses the postcard kamaji UDS — see the V6/V7 stanza in oss/kamaji/crates/kamaji-proto/src/version.rs. Adding a field to an existing variant is a bump; appending a whole new variant is not.")
1037/// @yah:handoff("FIXED — the positional guess is gone from the env-injection path. `MeshLookup` gained `UrlNamed { name }` / `PortNamed { name }`, APPENDED rather than added as fields on `Url`/`Port` exactly as the ticket instructed, so every existing postcard encoding stays byte-identical (an enum is encoded by variant index) and NO ProtocolVersion bump was needed — verified by the kamaji-proto codec suite passing untouched. The unnamed forms no longer mean \"index 0\": they resolve through `workload_spec::validate::select_mesh_port`, which takes the sole port when there is one, else the port named `http`, else RETURNS AN ERROR. `MeshLookup` also lost `Copy` (it now owns a String); the one call site that relied on it is `resolve_env_from_mesh`, now cloning.")
1038/// @yah:handoff("THE RULE LIVES IN ONE PLACE, which is the actual repair — the bug was not that a rule was wrong, it was that the rule was RE-DERIVED at every site, so all of them agreed about something false. `select_mesh_port(ident, &BTreeMap<String,u16>, &MeshLookup)` in workload-spec is now the only implementation; yubaba `StateMeshResolver` calls it, the workload-spec test fake calls it (it had been carrying its OWN copy of \"the first entry\", which is why the test suite confirmed the bug rather than catching it), and the `MeshResolver` trait doc now REQUIRES implementations to route through it instead of describing the rule for them to copy. A named lookup deliberately does NOT fall back to `http`: that would be the positional guess wearing a name.")
1039/// @yah:handoff("REQUIRED A TYPE CHANGE THE TICKET DID NOT NAME, and it is where the names were actually being lost: `yubaba::deploy::mesh_resolve::MeshAddress.ports` was a `Vec<u16>`. A bare number list CANNOT answer \"which of these is the API port\", so positional resolution was not a shortcut in that file — it was the only thing the type permitted, and the trait doc had written that limitation down as a rule. It is now the same `BTreeMap<String,u16>` that `kamaji::WorkloadState::ports` and `ServiceRecord::resolved_ports` already carry, so a name survives from manifest to dependent environment. Cheap to change: `MeshAddress` is constructed in exactly one file and only by tests.")
1040/// @yah:handoff("ONE CROSS-CRATE CONSTANT, pinned rather than duplicated silently. `select_mesh_port` needs the default port name and CANNOT import `kamaji::DEFAULT_PORT_NAME` — kamaji sits above workload-spec in the publish DAG (`yah-base <- {qed,kamaji} <- yubaba`), so the dep would invert the graph. So `workload_spec::validate::DEFAULT_PORT_NAME` states it, and `kamaji::tests::default_port_name_agrees_with_the_mesh_resolver` asserts all three spellings (kamaji DEFAULT_PORT_NAME, ports::HTTP, the validate const) are one string. Without that pin a future rename would make a dependent `FromMesh` URL and its own `PORT` env disagree about which listener is the default, silently.")
1041/// @yah:verify("cargo test --manifest-path oss/yah-base/Cargo.toml -p yah-workload-spec = 146/0 + 94/0 (87 before, so +7). The behaviour change is pinned by name: `several_unnamed_ports_is_an_error_not_the_first_one` (the case that previously rendered 5432 out of [5432,9100] and had a test LOCKING THAT IN), `several_ports_resolve_through_http_when_one_is_named_that`, `a_named_lookup_selects_that_port_and_nothing_else`, `a_named_lookup_for_an_absent_port_errors_rather_than_falling_back`, `a_sole_port_resolves_whatever_it_is_called` (sole beats the http rule on purpose — no ambiguity exists with one listener), `an_empty_port_map_is_no_ports_not_ambiguous`, `host_resolves_for_a_portless_peer`.")
1042/// @yah:verify("cargo test --manifest-path oss/yubaba/Cargo.toml -p yubaba --lib = 634 passed / 0 failed (632 before). Two new cases run the PRODUCTION resolver, not the fake: `several_unnamed_ports_error_rather_than_resolving_to_the_first` and `a_named_lookup_selects_that_port_through_the_state_resolver`. THREE PRE-EXISTING TESTS ASSERTED THE BUG and were rewritten rather than worked around — `url_renders_first_port_with_http_prefix` / `port_renders_first_port_as_string` (both crates) took a two-port peer and asserted the first one came back; their fixtures are now single-port and the multi-port case is its own explicitly-named test.")
1043/// @yah:verify("WHOLE-TREE on a settled tree: cargo test --manifest-path oss/kamaji/Cargo.toml --workspace --all-features = every target ok (kamaji lib 185/0, kamaji-bin 278/0, kamaji-proto codec suite untouched and green — the no-wire-bump evidence); yah-cloud --lib 1019/0/4 ignored; yah-local-driver --lib 99/0; cargo test -p yah --lib 1364 passed / 0 failed / 1 ignored; cargo check --workspace --all-targets = ZERO errors. R844 PURITY CANARY HELD: cargo test -p xtask --test main mirror_ingress = 11 passed / 0 failed.")
1044/// @yah:gotcha("MEASURED SCOPE, so nobody over- or under-reads this fix: THE FromMesh ENV PATH HAS NO PRODUCTION CALLER TODAY. `resolve_env_from_mesh` is called only from workload-spec own tests; `StateMeshResolver` is constructed only in its own module tests; and kamaji-bin `resolve_env` (native.rs:208) REFUSES an unresolved `EnvValue::FromMesh` outright with \"Yubaba must resolve mesh refs before dispatching to Kamaji\" — but nothing in yubaba calls the resolver on the deploy path. So the wrong rule had not yet handed a real workload a wrong number; it was a loaded gun, not a fired one. That is also why the fix was cheap (no call sites to migrate) and why it was worth doing NOW rather than after the path is wired.")
1045/// @yah:gotcha("GENERATED ARTIFACTS REGENERATED, and they carry MORE than this ticket. `.yah/schema/workload.toml.schema.json` and `packages/yah/workload-spec/index.ts` are generated from these Rust types and the pre-commit regen was disabled 2026-08-15, so they had gone stale at R844-F17 — the TS binding still said `ports: Array<number>` weeks after `MeshExpose.ports` became `Vec<MeshPort>`. Running `cargo run -p xtask -- emit-schemas` and the workload-spec `export-ts` bin swept BOTH F17 drift and this ticket. Diff is confined to the two expected surfaces (`MeshExpose.ports`, `MeshLookup`) and nothing else. Flagging per the shared-tree rule that a derived file is nobody property: whoever owns R844-F17 should know their type change is now reflected in the bindings.")
1046pub fn resolve_env_from_mesh(
1047    env: &[EnvVar],
1048    resolver: &dyn MeshResolver,
1049) -> Result<Vec<EnvVar>, MeshError> {
1050    env.iter()
1051        .map(|var| match &var.value {
1052            EnvValue::FromMesh { ident, kind } => {
1053                let value = resolver.resolve(ident, kind.clone())?;
1054                Ok(EnvVar {
1055                    name: var.name.clone(),
1056                    value: EnvValue::Literal { value },
1057                })
1058            }
1059            _ => Ok(var.clone()),
1060        })
1061        .collect()
1062}
1063
1064/// Run shape then semantic validation in the correct order.
1065///
1066/// Shape always runs first. If shape fails, `WorkloadValidationError::Shape`
1067/// is returned and semantic checks are skipped — callers never see a
1068/// `Semantic` error for a structurally invalid spec.
1069///
1070/// `machine_id` is forwarded to the capacity admission-control check.
1071/// `batch` is the set of co-deployed mesh idents for forward-reference
1072/// resolution; pass `&[]` for single-spec deployment.
1073pub fn all(
1074    spec: &WorkloadSpec,
1075    ctx: &dyn ValidationContext,
1076    machine_id: &MachineId,
1077    batch: &[MeshIdent],
1078) -> Result<(), WorkloadValidationError> {
1079    shape(spec)?;
1080    semantic(spec, ctx, machine_id, batch)
1081}