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