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    if let Some(d) = durability.as_ref().filter(|d| d.tier.ships_bytes()) {
589        let named: Vec<&str> = spec
590            .volumes
591            .iter()
592            .filter_map(|v| match &v.source {
593                VolumeSource::Named { name } => Some(name.as_str()),
594                _ => None,
595            })
596            .collect();
597        if named.len() != 1 {
598            return Err(ShapeError::Field {
599                path: FieldPath::Annotation(DURABILITY_SUBJECTS_ANNOTATION),
600                reason: format!(
601                    "{DURABILITY_TIER_ANNOTATION} = \"{}\" declares subjects {:?}, which are \
602                     relative to a named volume, but this spec declares {} named volumes{}; \
603                     a tier that ships bytes needs exactly one",
604                    d.tier,
605                    d.subjects,
606                    named.len(),
607                    if named.is_empty() {
608                        String::new()
609                    } else {
610                        format!(" ({})", named.join(", "))
611                    }
612                ),
613            });
614        }
615    }
616
617    if durability.is_none()
618        && spec.effective_archetype() == LifecycleArchetype::Appliance
619        && spec
620            .volumes
621            .iter()
622            .any(|v| matches!(v.source, VolumeSource::Named { .. }))
623    {
624        warnings.push(ShapeWarning {
625            path: FieldPath::Annotation(DURABILITY_TIER_ANNOTATION),
626            message: format!(
627                "appliance with a yubaba-managed named volume declares no durability \
628                 tier, so that volume is the only copy of its state and losing the node \
629                 loses it; declare {DURABILITY_TIER_ANNOTATION} = \"none\" if that is \
630                 intended, or a real tier if it is not"
631            ),
632        });
633    }
634
635    // soft: healthcheck.initial_delay >= stop_policy.grace_period * 2
636    if let Some(hc) = &spec.healthcheck {
637        let min_recommended = spec.stop_policy.grace_period.as_ms().saturating_mul(2);
638        if hc.initial_delay.as_ms() < min_recommended {
639            warnings.push(ShapeWarning {
640                path: FieldPath::Healthcheck("initial_delay"),
641                message: format!(
642                    "initial_delay ({}ms) is less than stop_policy.grace_period * 2 ({}ms); \
643                     a SIGTERM during startup may catch a still-initialising container",
644                    hc.initial_delay.as_ms(),
645                    min_recommended
646                ),
647            });
648        }
649    }
650
651    Ok(warnings)
652}
653
654// ── StaticAsset validator ─────────────────────────────────────────────────────
655
656/// Shape-validate a `kind = "static-asset"` workload.
657///
658/// Enforces the closed-catalog invariant: every value in `[aliases]` must be a
659/// `filename` present in `[[asset]]`. A mirror's `[asset_aliases]` overrides
660/// are bound by the same rule and are validated separately at sync time when
661/// both the workload and mirror are loaded together.
662pub fn shape_static_asset(workload: &StaticAssetWorkload) -> Result<(), ShapeError> {
663    // XOR rule (W164 / R438-T2): every [[asset]] row must set exactly one of
664    // `source` (legacy local bytes) or `derive` (fetch + optional transform).
665    // Both-set is ambiguous (which one wins?); neither-set leaves the
666    // reconciler with no bytes to upload.
667    for (i, entry) in workload.assets.iter().enumerate() {
668        match (entry.source.is_some(), entry.derive.is_some()) {
669            (true, true) => {
670                return Err(ShapeError::Field {
671                    path: FieldPath::Asset(i, "source"),
672                    reason: format!(
673                        "asset {:?}: both `source` and `derive` are set; pick exactly one",
674                        entry.filename
675                    ),
676                });
677            }
678            (false, false) => {
679                return Err(ShapeError::Field {
680                    path: FieldPath::Asset(i, "source"),
681                    reason: format!(
682                        "asset {:?}: neither `source` nor `derive` is set; pick exactly one",
683                        entry.filename
684                    ),
685                });
686            }
687            _ => {}
688        }
689    }
690
691    let filenames: std::collections::HashSet<&str> =
692        workload.assets.iter().map(|a| a.filename.as_str()).collect();
693
694    for (alias_key, alias_target) in &workload.aliases {
695        if !filenames.contains(alias_target.as_str()) {
696            return Err(ShapeError::Field {
697                path: FieldPath::AssetAlias(alias_key.clone()),
698                reason: format!(
699                    "alias target {:?} is not present in the [[asset]] catalog; \
700                     add a matching [[asset]] row or correct the filename",
701                    alias_target
702                ),
703            });
704        }
705    }
706
707    Ok(())
708}
709
710// ── Semantic layer ────────────────────────────────────────────────────────────
711
712/// Transient error from a [`ValidationContext`] lookup.
713///
714/// Distinct from a semantic "resource not found" failure. `ContextError` means
715/// the lookup itself could not complete (network timeout, auth failure, etc.),
716/// not that the resource is definitively absent.
717#[derive(Debug, Error, Clone, PartialEq)]
718#[error("context lookup failed: {0}")]
719pub struct ContextError(pub String);
720
721/// A semantic constraint violation: the spec references a resource that is not
722/// known to the cluster at validation time.
723#[derive(Debug, Error, PartialEq)]
724pub enum SemanticError {
725    #[error("field {path}: {reason}")]
726    Unknown { path: FieldPath, reason: String },
727}
728
729/// Top-level validation error spanning both shape and semantic layers.
730///
731/// `Shape` always wins: if the spec is structurally invalid, semantic checks
732/// never run.
733#[derive(Debug, Error, PartialEq)]
734pub enum WorkloadValidationError {
735    /// Hard shape constraint failed — spec is structurally invalid.
736    #[error("shape: {0}")]
737    Shape(ShapeError),
738
739    /// Semantic check failed — spec references an unknown cluster resource.
740    #[error("semantic: {0}")]
741    Semantic(SemanticError),
742
743    /// Transient ValidationContext lookup failure — the check itself failed.
744    #[error("context: {0}")]
745    Context(ContextError),
746}
747
748impl From<ShapeError> for WorkloadValidationError {
749    fn from(e: ShapeError) -> Self { WorkloadValidationError::Shape(e) }
750}
751
752impl From<ContextError> for WorkloadValidationError {
753    fn from(e: ContextError) -> Self { WorkloadValidationError::Context(e) }
754}
755
756/// Read-only view of yubaba state used for semantic validation.
757///
758/// Defined here so clients (desktop, CLI, agents) can run semantic checks
759/// without depending on the yubaba crate. Yubaba implements this trait.
760///
761/// Each method returns `Result<bool, ContextError>` so transient failures are
762/// distinguishable from definitive "not found" answers.
763pub trait ValidationContext {
764    /// True when the registry confirms the image exists.
765    fn image_exists(&self, image: &ImageRef) -> Result<bool, ContextError>;
766
767    /// True when the named secret exists in the yubaba secret store.
768    fn secret_exists(&self, secret: &SecretRef) -> Result<bool, ContextError>;
769
770    /// True when `ident` is a known deployed workload OR appears in `batch`
771    /// (the set of specs co-deployed in the same request — allows forward
772    /// references within a single deployment batch).
773    fn mesh_ident_known(&self, ident: &MeshIdent, batch: &[MeshIdent]) -> Result<bool, ContextError>;
774
775    /// True when `hostname` falls under a Cloudflare zone owned by this cluster.
776    fn cf_zone_owned(&self, hostname: &str) -> Result<bool, ContextError>;
777
778    /// True when `tag` (e.g. `"tag:noisetable-ops"`) is in the cluster's
779    /// Tailscale ACL tag list.
780    fn tailscale_tag_known(&self, tag: &str) -> Result<bool, ContextError>;
781
782    /// True when `machine_id` has sufficient remaining capacity to host the
783    /// given spec's resource requirements.
784    ///
785    /// Implementors: read memory via [`WorkloadSpec::memory_request_mb`], not
786    /// `spec.resources.memory_mb`. The latter is a cgroup ceiling, and using
787    /// it as a capacity floor is what made every build-worker smaller than
788    /// `for_forge`'s 32 GiB ceiling unschedulable in `admit_workload`. Only a
789    /// test implementation of this trait exists today, so the bug is not live
790    /// here — this note is to keep it from arriving with the first real one.
791    fn capacity_for(&self, spec: &WorkloadSpec, machine_id: &MachineId) -> Result<bool, ContextError>;
792}
793
794/// Run semantic validation — requires yubaba state via [`ValidationContext`].
795///
796/// Shape validation is NOT run here. Callers MUST run [`shape`] first; use
797/// [`all`] to enforce this automatically.
798///
799/// `machine_id` is the target machine for admission-control capacity checks.
800/// `batch` is the set of mesh idents being co-deployed (pass `&[]` for
801/// single-spec deployment); these count as "known" for `depends_on` resolution.
802pub fn semantic(
803    spec: &WorkloadSpec,
804    ctx: &dyn ValidationContext,
805    machine_id: &MachineId,
806    batch: &[MeshIdent],
807) -> Result<(), WorkloadValidationError> {
808    if !ctx.image_exists(&spec.image)? {
809        return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
810            path: FieldPath::Image,
811            reason: format!(
812                "image {}/{}:{} not found in registry",
813                spec.image.registry, spec.image.repository, spec.image.tag
814            ),
815        }));
816    }
817
818    for (i, secret) in spec.secrets.iter().enumerate() {
819        if !ctx.secret_exists(&secret.source)? {
820            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
821                path: FieldPath::Secret(i, "source"),
822                reason: format!("secret source at index {i} not found in yubaba secret store"),
823            }));
824        }
825    }
826
827    for (i, dep) in spec.depends_on.iter().enumerate() {
828        if !ctx.mesh_ident_known(dep, batch)? {
829            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
830                path: FieldPath::DependsOn(i),
831                reason: format!("mesh ident {:?} is not a known deployed workload", dep.0),
832            }));
833        }
834    }
835
836    if let Some(public) = &spec.expose.public {
837        if !ctx.cf_zone_owned(&public.hostname)? {
838            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
839                path: FieldPath::Hostname,
840                reason: format!(
841                    "hostname {:?} is not under a Cloudflare zone owned by this cluster",
842                    public.hostname
843                ),
844            }));
845        }
846    }
847
848    if let Some(op) = &spec.expose.operator {
849        if !ctx.tailscale_tag_known(&op.tailscale_tag)? {
850            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
851                path: FieldPath::TailscaleTag,
852                reason: format!(
853                    "tailscale tag {:?} is not in the cluster's ACL tag list",
854                    op.tailscale_tag
855                ),
856            }));
857        }
858    }
859
860    if !ctx.capacity_for(spec, machine_id)? {
861        return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
862            path: FieldPath::Resources,
863            reason: format!(
864                "machine {:?} lacks capacity (memory={}MB cpu_millis={} ephemeral={}MB)",
865                machine_id.0,
866                spec.resources.memory_mb,
867                spec.resources.cpu_millis,
868                spec.resources.ephemeral_storage_mb
869            ),
870        }));
871    }
872
873    Ok(())
874}
875
876// ── Mesh resolution layer ─────────────────────────────────────────────────────
877
878/// Failure surface for [`MeshResolver`] lookups.
879///
880/// `NotDeployed` means the dependency hasn't been observed in mesh state yet
881/// (yubaba's deploy step waits on this — see [`crate::EnvValue::FromMesh`]).
882/// `NoPorts` means the dependency is deployed but its `MeshExpose.ports`
883/// list is empty, so a port-based lookup can't render a value. `Lookup`
884/// covers transient failures from the underlying state read.
885#[derive(Debug, Error, Clone, PartialEq)]
886pub enum MeshError {
887    #[error("mesh ident {ident:?} is not yet deployed")]
888    NotDeployed { ident: String },
889
890    #[error(
891        "mesh ident {ident:?} exposes no ports; {lookup:?} requires at least one"
892    )]
893    NoPorts { ident: String, lookup: MeshLookup },
894
895    /// The peer exposes several ports and the lookup did not say which
896    /// (R844-B22). Deliberately an error rather than a pick — see
897    /// [`MeshLookup`]'s docs.
898    #[error(
899        "mesh ident {ident:?} exposes {} ports ({}) and none is named \"http\", \
900         so {lookup:?} cannot say which one to use. Name the port in the \
901         lookup (kind = \"port_named\", name = \"…\"), or name one of the \
902         peer's ports \"http\" in its expose.mesh.ports.",
903        .names.len(),
904        .names.join(", ")
905    )]
906    AmbiguousPort {
907        ident: String,
908        lookup: MeshLookup,
909        names: Vec<String>,
910    },
911
912    /// The lookup named a port the peer does not expose (R844-B22).
913    #[error(
914        "mesh ident {ident:?} exposes no port named {name:?}; it has {}",
915        if .available.is_empty() { "none".to_string() } else { .available.join(", ") }
916    )]
917    NoSuchPort {
918        ident: String,
919        name: String,
920        available: Vec<String>,
921    },
922
923    #[error("mesh state lookup failed: {0}")]
924    Lookup(String),
925}
926
927/// The port name a peer's sole/default listener carries. Agrees with
928/// `kamaji::DEFAULT_PORT_NAME` by convention rather than by import: kamaji sits
929/// *above* workload-spec in the publish DAG (`yah-base <- {qed,kamaji} <-
930/// yubaba`), so depending on it here would invert the graph. The two are pinned
931/// together by `default_port_name_agrees_with_the_supervisor` in this file's
932/// tests.
933pub const DEFAULT_PORT_NAME: &str = "http";
934
935/// Pick the port a [`MeshLookup`] refers to out of a peer's `name -> port` map
936/// (R844-B22) — the one place the rule lives, so every resolver answers the
937/// same way.
938///
939/// - A **named** lookup takes that port, or errors naming what the peer does
940///   have. No fallback: a lookup that asked for `wss` and silently got `http`
941///   would be the positional guess wearing a name.
942/// - An **unnamed** lookup takes the sole port when there is one, else the port
943///   named [`DEFAULT_PORT_NAME`], else errors. It never takes "the first",
944///   which is what this function exists to stop.
945pub fn select_mesh_port(
946    ident: &str,
947    ports: &std::collections::BTreeMap<String, u16>,
948    lookup: &MeshLookup,
949) -> Result<u16, MeshError> {
950    if let Some(name) = lookup.port_name() {
951        return ports.get(name).copied().ok_or_else(|| MeshError::NoSuchPort {
952            ident: ident.to_string(),
953            name: name.to_string(),
954            available: ports.keys().cloned().collect(),
955        });
956    }
957
958    let mut entries = ports.iter();
959    match (entries.next(), entries.next()) {
960        (None, _) => Err(MeshError::NoPorts {
961            ident: ident.to_string(),
962            lookup: lookup.clone(),
963        }),
964        (Some((_, &only)), None) => Ok(only),
965        _ => ports
966            .get(DEFAULT_PORT_NAME)
967            .copied()
968            .ok_or_else(|| MeshError::AmbiguousPort {
969                ident: ident.to_string(),
970                lookup: lookup.clone(),
971                names: ports.keys().cloned().collect(),
972            }),
973    }
974}
975
976/// Resolve [`crate::EnvValue::FromMesh`] references to literal env values.
977///
978/// Defined in workload-spec so clients (agents, desktop, CLI) can render
979/// specs against fake mesh state without depending on the yubaba crate.
980/// Yubaba's production implementation (in `yubaba::deploy::mesh_resolve`)
981/// reads from raft state.
982///
983/// **Resolution rules** (R844-B22 replaced the positional ones):
984/// - [`MeshLookup::Host`] — the bare DNS-ish identifier as authored (e.g.
985///   `"noisetable-db.pdx"`). Needs no port and resolves for a portless peer.
986/// - [`MeshLookup::Url`] — `"http://<ident>:<port>"`.
987/// - [`MeshLookup::Port`] — that port stringified, e.g. `"5432"`.
988/// - [`MeshLookup::UrlNamed`] / [`MeshLookup::PortNamed`] — the same, at the
989///   peer's port of that name.
990///
991/// **Which port** is [`select_mesh_port`]'s decision, and implementations must
992/// route through it rather than re-deriving: a sole port, else the one named
993/// [`DEFAULT_PORT_NAME`], else an error. It is emphatically *not* "the first
994/// entry", which is what this trait's doc used to promise — declaration order
995/// is not a statement about which listener a dependent should dial, and acting
996/// as if it were is how a workload gets handed a metrics port as its API URL.
997///
998/// Because the rule is name-based rather than positional, a `Url` and a `Port`
999/// resolved in the same deploy agree by construction; the old doc had to ask
1000/// implementations to make the lookup atomic to get that.
1001pub trait MeshResolver {
1002    fn resolve(&self, ident: &MeshIdent, kind: MeshLookup) -> Result<String, MeshError>;
1003}
1004
1005/// Render every [`EnvValue::FromMesh`] entry in `env` to a [`EnvValue::Literal`]
1006/// using `resolver`; pass through `Literal` and `FromSecret` values unchanged.
1007///
1008/// Returns the first resolution error encountered. Callers should run this
1009/// after yubaba's stage-3 mesh peering completes (see
1010/// `yubaba::deploy::env_validate::run` doc), at containerd-spec assembly.
1011///
1012/// `FromSecret` values are deliberately untouched here — secret resolution
1013/// is the secrets layer's job (R090-F5), not the mesh resolver's.
1014///
1015/// @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")
1016/// @yah:status(review)
1017/// @yah:at(2026-09-04T14:10:34Z)
1018/// @yah:assignee(agent:bundle-anthropic-ashguard)
1019/// @yah:parent(R844)
1020/// @yah:severity(medium)
1021/// @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.")
1022/// @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.")
1023/// @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.")
1024/// @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.")
1025/// @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.")
1026/// @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.")
1027/// @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.")
1028/// @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`.")
1029/// @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.")
1030/// @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.")
1031/// @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.")
1032/// @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.")
1033pub fn resolve_env_from_mesh(
1034    env: &[EnvVar],
1035    resolver: &dyn MeshResolver,
1036) -> Result<Vec<EnvVar>, MeshError> {
1037    env.iter()
1038        .map(|var| match &var.value {
1039            EnvValue::FromMesh { ident, kind } => {
1040                let value = resolver.resolve(ident, kind.clone())?;
1041                Ok(EnvVar {
1042                    name: var.name.clone(),
1043                    value: EnvValue::Literal { value },
1044                })
1045            }
1046            _ => Ok(var.clone()),
1047        })
1048        .collect()
1049}
1050
1051/// Run shape then semantic validation in the correct order.
1052///
1053/// Shape always runs first. If shape fails, `WorkloadValidationError::Shape`
1054/// is returned and semantic checks are skipped — callers never see a
1055/// `Semantic` error for a structurally invalid spec.
1056///
1057/// `machine_id` is forwarded to the capacity admission-control check.
1058/// `batch` is the set of co-deployed mesh idents for forward-reference
1059/// resolution; pass `&[]` for single-spec deployment.
1060pub fn all(
1061    spec: &WorkloadSpec,
1062    ctx: &dyn ValidationContext,
1063    machine_id: &MachineId,
1064    batch: &[MeshIdent],
1065) -> Result<(), WorkloadValidationError> {
1066    shape(spec)?;
1067    semantic(spec, ctx, machine_id, batch)
1068}