Skip to main content

workload_spec/
lib.rs

1//! `WorkloadSpec` — typed wire format for yubaba workloads.
2//!
3//! This crate is the schema source of truth. It has zero dependencies on
4//! yubaba; yubaba depends on it, not the other way around. Agents and desktop
5//! code that construct specs can link this crate without pulling in yubaba's
6//! containerd client.
7//!
8//! Three validation layers live in [`validate`]: shape (sync, no I/O),
9//! semantic (reads yubaba state), and environment (deploy-time). The schema
10//! types live at the top level.
11//!
12//! @yah:ticket(R222-T3, "Workload schema doesn't match per-kind on-disk shapes (mesofact-static)")
13//! @yah:assignee(agent:claude)
14//! @yah:at(2026-05-18T16:47:03Z)
15//! @yah:status(review)
16//! @yah:parent(R222)
17//! @yah:handoff("Picked option (a): tagged-enum Workload envelope with per-kind variants. Added Workload { MesofactStatic(MesofactStaticWorkload), Container(WorkloadSpec) } + BuildConfig in workload-spec. WorkloadSpec stays the containerd RPC wire type (now also the kind=\"container\" variant payload). xtask emit-schemas now renders workload.toml.schema.json as a oneOf over kind; schema drift test green. TS export updated. Arch doc 'workloads — colocated, not registered' rewritten to describe the envelope + both example kinds; B4 outlook updated to point at Workload.")
18//! @yah:verify("cargo check -p cloud && cargo test -p cloud && cargo check -p yah && cargo check -p agent-tools && cargo check -p yah --tests && cargo check -p agent-tools --tests")
19//! @yah:verify("cargo test -p xtask  # schema drift test must stay green")
20//! @yah:verify("cargo run -p workload-spec --bin export-ts  # idempotent regen")
21//!
22//! @yah:ticket(R256-F7, "Model mesofact container as two roles: transient build/publish job vs long-lived SSR/SPA runtime")
23//! @yah:assignee(agent:claude)
24//! @yah:at(2026-05-25T20:08:29Z)
25//! @yah:status(review)
26//! @yah:parent(R256)
27//! @yah:next("role A — build/publish job: transient task that runs the build and PUTs to the object store, then exits/GC'd; needed whenever there is a build step (SSR or not)")
28//! @yah:next("role B — SSR/SPA runtime: long-lived container, only present when the app has realtime/dynamic pages (this is what the 'only if SSR/SPA' gate applies to)")
29//! @yah:next("decide the fidelity knob: does the build run in-container (matches CI, max fidelity, costs image+cold-start) or on host with yubaba orchestrating only the serving edge?")
30//! @yah:assumes("in cloud these are separate: CI/build job produces artifacts, R2+CDN serve them, and a distinct worker serves any SSR — so one merged 'mesofact container' is the trap")
31//! @yah:handoff("BuildMode enum added to workload-spec with HostSide (default) and InContainer { image } variants. MesofactStaticWorkload gains build_mode: BuildMode (skip_serializing_if default) and ssr_runtime: Option<WorkloadSpec>. Encodes the two-role model: build step is always transient; SSR companion is optional long-lived. Fidelity knob decision: HostSide = host watcher (dev+sim), InContainer = CI-fidelity (cloud/ha). All three codegen targets updated: export-ts.rs, packages/yah/workload-spec/index.ts, .yah/schema/workload.toml.schema.json. Schema drift tests pass.")
32//! @yah:verify("cargo check -p workload-spec --locked")
33//! @yah:verify("cargo test -p xtask --locked  # schema_drift tests pass")
34//! @yah:verify("cargo test -p cloud --locked --lib  # 165 passed")
35//!
36//! @yah:ticket(R256-F9, "Almanac as a dependency manifest: orchestrator verifies I/O targets live before run; output invalidates mesofact sources cleanly")
37//! @yah:assignee(agent:claude)
38//! @yah:at(2026-05-25T21:28:15Z)
39//! @yah:status(review)
40//! @yah:parent(R256)
41//! @yah:next("almanac is a manifest declaring inputs + outputs + cadence + command — NOT a bash cron; the declared I/O is the contract")
42//! @yah:next("before a run the orchestrator verifies declared inputs exist AND output targets (e.g. the mesofact app + its source/object store) are reachable; if not → the run fails or waits/times out rather than producing orphaned output")
43//! @yah:next("almanac output invalidates downstream mesofact sources cleanly + deliberately (a declared dependency edge, not a blunt rebuild-everything) — this is the reason it's a named manifest, not a shell cron")
44//! @yah:next("decide the not-ready policy knob: fail-fast vs wait-with-timeout vs requeue")
45//! @yah:next("generalizes the OpenRouter refresher (spawn_almanac_refresher), which is the degenerate no-dependency case (output = JSON cache, no app target)")
46//! @yah:assumes("precondition enforcement lives in the shared scheduler layer (embedded by camp for dev/sim, yubaba for cloud/ha) — it needs the workload registry + xlb-net discovery to answer 'is the target up?', which a bash cron lacks")
47//! @arch:see(.yah/docs/architecture/A024-vocabulary.md)
48//! @yah:depends_on(R256-F6)
49//! @yah:handoff("AlmanacTarget (Http/Tcp probe), NotReadyPolicy (WaitWithTimeout default=5s/FailFast/Requeue), Cadence (Once/Every/Cron), and AlmanacManifest types added to workload-spec. Workload enum gains Almanac(AlmanacManifest) variant (kind='almanac'). NotReadyPolicy::WaitWithTimeout(5s) is the default — matches sim-tier spinup budget. AlmanacManifest.invalidates: Vec<MeshIdent> declares downstream cache-bust targets. export-ts.rs updated; index.ts and workload.toml.schema.json regenerated; drift tests pass. The degenerate case (no inputs, no outputs, Cron, no invalidates) is exactly the OpenRouter refresher pattern. The orchestrator precondition enforcement (xlb-net probing) is left for R276/yubaba integration.")
50//! @yah:verify("cargo check -p workload-spec --locked")
51//! @yah:verify("cargo test -p xtask --locked  # schema drift tests pass")
52//! @yah:verify("cargo test -p cloud --locked --lib  # 165 passed")
53//!
54//! @yah:relay(R335, "Almanac mirror-binding — scope a feed to the mirror it affects")
55//! @yah:at(2026-05-27T02:19:09Z)
56//! @yah:status(open)
57//! @arch:see(.yah/docs/working/W058-almanac-mirror-binding.md)
58//! @yah:depends_on(R256-F9)
59//!
60//! @yah:ticket(R335-S1, "Decide cross-env pollution mechanism: extend R256-F9 manifest vs add per-mirror capability")
61//! @yah:assignee(agent:claude)
62//! @yah:at(2026-05-27T02:19:33Z)
63//! @yah:kind(spike)
64//! @yah:status(review)
65//! @yah:phase(P1)
66//! @yah:parent(R335)
67//! @yah:gotcha("Build ON R256-F9's AlmanacManifest (workload-spec/src/lib.rs) — do NOT invent a parallel manifest. R256-F9 is in review.")
68//! @yah:depends_on(R256-F9)
69//! @yah:handoff("Decided. Recorded in almanac-mirror-binding.md §11. KEY FINDING: two almanac paths exist; the live R330 feed uses almanac::FeedConfig (on_change=MesofactRebuild{service,route} — a service id, NOT a MeshIdent), so it never touches AlmanacManifest.invalidates. Verdict on the S1 title: NEITHER extend the manifest nor (yet) add capability is the accident fix — dev->cloud is ALREADY blocked by construction (feed path = process locality + per-mirror reconciler + MinIO/R2 backend split; manifest path = no camp-embedded MeshState, mesh resolution is yubaba-raft-only). Residual holes: /revalidate receiver is UNAUTHENTICATED, and same-tier (two clouds on one R2) has no per-mirror key prefix.")
70//! @yah:next("FILED: R335-F3 (P1, no yubaba dep) mirror-aware /revalidate receiver — reject feeds not bound to this mirror; satisfies R335-T2; lands with R330-F4.")
71//! @yah:next("FILED: R335-F4 (P2) per-mirror artifact key prefix in derive_minio_key/publish_to_r2 — closes same-tier collision.")
72//! @yah:next("FILED: R335-F5 (P3, BLOCKED on yubaba control plane) per-mirror capability gate on /revalidate via yubaba/xlb-net node identity.")
73//!
74//! @yah:ticket(R278-F4, "RolloutPolicy schema in workload-spec (TOML types)")
75//! @yah:assignee(agent:claude)
76//! @yah:at(2026-06-01T02:31:25Z)
77//! @yah:status(review)
78//! @yah:parent(R278)
79//! @yah:next("Add src/rollout.rs with RolloutPolicy, RolloutStrategy, RolloutGate, RolloutStep, RolloutOnFailure")
80//! @yah:next("Export pub mod rollout from lib.rs")
81//! @yah:next("Add TS export via ts-rs in export-ts.rs")
82//! @arch:see(.yah/docs/working/W140-yah-yubaba-ci-cd.md)
83//! @yah:handoff("RolloutPolicy, RolloutStrategy, RolloutGate, RolloutStep, RolloutOnFailure added to workload-spec/src/rollout.rs. Exported from lib.rs. toml dev-dep added for round-trip test. Tests: rollout::tests::round_trip_toml + on_failure_default both green.")
84//!
85//! @yah:ticket(R429-T1, "Workload::StaticAsset variant + schema in workload-spec (catalog + aliases)")
86//! @yah:assignee(agent:claude)
87//! @yah:at(2026-06-03T23:24:20Z)
88//! @yah:status(review)
89//! @yah:phase(P1)
90//! @yah:parent(R429)
91//! @yah:next("Add Workload::StaticAsset(StaticAssetWorkload) variant alongside the existing MesofactStatic + Container envelopes. Mirror the tagged-enum shape R222-T3 established.")
92//! @yah:next("StaticAssetWorkload fields: kind='static-asset' tag, assets: Vec<AssetEntry>, aliases: BTreeMap<String, String>. AssetEntry { filename: String, source: PathBuf, blake3: BlakeHash }.")
93//! @yah:next("BlakeHash newtype validates 64-hex-char shape (reuse from existing places if available, else introduce here).")
94//! @yah:next("Closed-catalog invariant: aliases values MUST be filenames present in the assets list. Reject at load with a clear error pointing at the offending alias key + bad filename.")
95//! @yah:next("Mirror schema extension: optional [asset_aliases] BTreeMap<String, String> on MirrorConfig. Semantic validator (when both workload + mirror are loaded together) rejects mirror aliases whose target filename isn't in the catalog.")
96//! @yah:next("Regenerate the workload.toml.schema.json via xtask emit-schemas (R222-B4). Confirm the drift test stays green.")
97//! @yah:next("TS mirror: extend packages/yah/workload-spec/index.ts with the StaticAsset variant + AssetEntry. Confirm bun typecheck stays green.")
98//! @yah:verify("cargo check -p workload-spec --locked")
99//! @yah:verify("cargo test -p workload-spec")
100//! @yah:verify("cargo run -p workload-spec --bin export-ts")
101//! @yah:verify("cargo test -p xtask")
102//! @arch:see(.yah/docs/working/W160-atomic-release-waves.md)
103//!
104//! @yah:ticket(R429-F2, "static-asset reconciler: BLAKE3 verify + S3 PUT against mirror's object_store + drift")
105//! @yah:assignee(agent:claude)
106//! @yah:at(2026-06-03T23:24:38Z)
107//! @yah:status(review)
108//! @yah:phase(P2)
109//! @yah:parent(R429)
110//! @yah:next("New reconciler that handles kind='static-asset' in the same service-sync loop that already runs mesofact-static + container. Same wave-gate semantics, same drift shape.")
111//! @yah:next("For each [[asset]] row: hash source file (BLAKE3) and compare to manifest entry. Mismatch → surface as drift, halt push for that asset until rebuild.")
112//! @yah:next("Resolve mirror's object_store provider → R2 bucket + credentials. HEAD cas/filename; if absent or different content-length → PUT. Idempotent on re-run.")
113//! @yah:next("Drift detection: list bucket contents under the component's prefix, compare against catalog filenames. Files in bucket ∖ catalog → report as drift (do NOT delete; that's the prune verb's job).")
114//! @yah:next("ServicesView's existing matrix consumes the new drift shape automatically. Confirm SyncGlyph/DriftList render correctly for a static-asset row without UI changes.")
115//! @yah:next("MockR2 in tests: HashMap<key, bytes> implementing the S3 surface the reconciler hits. Cover: push first-time, push idempotent, drift catches catalog-vs-bucket mismatch, BLAKE3 mismatch halts push.")
116//! @yah:next("Real-R2 integration test gated behind YAH_TEST_R2_BUCKET env var — one round-trip against a scratch bucket; skipped otherwise.")
117//! @yah:verify("cargo check --workspace --locked")
118//! @yah:verify("cargo test -p <reconciler-crate>  # crate TBD by impl agent")
119//! @yah:verify("cargo test -p workload-spec")
120//! @yah:gotcha("Auto-delete is OFF — reconciler reports drift on bucket∖catalog files but never DELETEs. That's the prune verb (R429-T2). Easy bug to introduce when 'cleaning up drift'; don't.")
121//! @yah:gotcha("S3 multipart upload threshold matters — distil-large-v3 is ~270MB which is over the 5MB single-PUT limit on R2's strictest mode. Use aws-sdk-s3's multipart helper for assets >100MB.")
122//! @yah:gotcha("Long-running progress MUST surface in QED/task-pane per the long-running-yah-surface rule. Don't silently spin in a tokio task; model as a Task with progress events.")
123//! @arch:see(.yah/docs/working/W160-atomic-release-waves.md)
124//! @yah:depends_on(R429-T1)
125//!
126//! @yah:ticket(R429-T3, "yah service prune verb: candidate enumeration + operator-confirm delete")
127//! @yah:assignee(agent:claude)
128//! @yah:at(2026-06-03T23:24:52Z)
129//! @yah:status(review)
130//! @yah:phase(P3)
131//! @yah:parent(R429)
132//! @yah:next("yah service prune <service-name> enumerates files present in the bucket but not referenced by any current mirror's resolved alias graph. Lists candidates + sizes + last-modified, requires explicit operator confirm before DELETE.")
133//! @yah:next("Resolution graph: for each mirror, walk [asset_aliases] → catalog [aliases] → catalog [[asset]] rows. Union across all mirrors = live set. Bucket ∖ live set = prune candidates.")
134//! @yah:next("MCP tool mcp__yah__service_prune routes through approval gate (write verb). Read counterpart mcp__yah__service_prune_status auto-passes — returns the candidate list without acting.")
135//! @yah:next("Camp: Tauri command + a 'Prune candidates' panel in the existing DeployPanel for each service, showing the candidate table with per-row checkboxes + confirm.")
136//! @yah:next("Analytics-driven candidate filter (old AND unaccessed-for-N-days) is OUT OF SCOPE for this ticket — needs access logs we don't aggregate yet. The candidate set today is purely catalog-derived.")
137//! @yah:next("User-asset TTL is OUT OF SCOPE — different surface, access-pattern-based, separate relay when it lands.")
138//! @yah:verify("cargo test -p <prune-crate>")
139//! @yah:verify("yah service prune yah-desktop --dry-run lists candidates")
140//! @arch:see(.yah/docs/working/W160-atomic-release-waves.md)
141//! @yah:depends_on(R429-F2)
142//! @yah:handoff("CLI + library + MCP all landed; UI deferred to R429-F4 (filed). Library lives in crates/yah/cloud/src/reconciler/static_asset_prune.rs and exposes compute_live_set (pure resolution graph), compute_prune_candidates (live + LIST + diff), execute_prune (DELETE), and load_service_and_mirror (path helper). CLI verb is `yah cloud service prune <name> --env <env> [--dry-run] [--yes] [--format=table|json]` at app/yah/cli/src/cloud.rs (ServiceCommands::Prune + handle_service_prune). MCP tools cloud.service_prune_status (read, auto-pass, --dry-run --format=json) and cloud.service_prune (write, --yes --format=json) dispatch through build_command(). New S3 helper sign_s3_get_with_query in local-driver covers ListObjectsV2 (the existing s3_sign helpers don't handle canonical query strings); ListObjectsV2 response is parsed with a tiny hand-rolled split_tags helper to avoid a quick-xml workspace dep. Tests: 12 prune-module unit tests (live-set union, kind filtering, list response parse for single/empty/truncated/no-token, candidate filtering including catalog manifest sidecar exclusion) + 1 s3_sign helper test + 2 MCP build_command tests. cargo check --workspace clean. cargo test -p cloud --lib: 279 pass (1 pre-existing failure cloud_init::tests::embedded_template_matches_workspace_canonical unrelated, per R419-F4 docstring). cargo test -p yah --lib: 299 pass.")
143//! @yah:next("R429-F4 carries the Tauri + DeployPanel UI work — depends_on R429-T3, status=open.")
144//! @yah:verify("cargo check --workspace --locked")
145//! @yah:verify("cargo test -p cloud --lib reconciler::static_asset_prune  # 12 pass")
146//! @yah:verify("cargo test -p yah --lib mcp::tools::tests::cloud_service_prune  # 2 pass")
147//! @yah:verify("yah cloud service prune --help  # renders usage with --env/--dry-run/--yes/--format")
148//!
149//! @arch:see(.yah/docs/working/W164-derived-static-assets.md)
150//!
151//! @yah:ticket(R438-T2, "AssetEntry XOR: source vs derive + shape_static_asset rules")
152//! @yah:assignee(agent:claude)
153//! @yah:at(2026-06-04T21:06:51Z)
154//! @yah:status(review)
155//! @yah:phase(P1)
156//! @yah:parent(R438)
157//! @yah:next("AssetEntry.source: PathBuf → Option<PathBuf>")
158//! @yah:next("Add AssetEntry.derive: Option<AssetDerive> with fetch + optional transform")
159//! @yah:next("Extend shape_static_asset to enforce exactly-one(source, derive) + license closed-set")
160//! @yah:verify("Both-set and neither-set fail shape validation with ShapeError::Field")
161//! @yah:verify("Legacy TOMLs with only source still parse + serialize identically")
162//! @arch:see(.yah/docs/working/W164-derived-static-assets.md)
163//! @yah:handoff("AssetEntry now carries Option<PathBuf> source + Option<AssetDerive> derive (both skip_serializing_if). New types AssetDerive {fetch: FetchSource, transform: Option<TransformSpec>} and TransformSpec {recipe, params} added to workload-spec/src/lib.rs. validate.rs grew FieldPath::Asset(usize, &'static str) and shape_static_asset enforces XOR: both-set or neither-set fail with ShapeError::Field { path: Asset(i, \"source\") }. 4 new tests cover derive-mode round-trip, legacy source-only TOML round-trip without leaking a derive field, both-set rejection, neither-set rejection, and both-modes-accepted positive case. Cloud reconciler (static_asset.rs:360) now bails on derive-mode with a pointer to R438-T5 until the materialize step lands. 3 test fixtures updated with source: Some(...) + derive: None. export-ts regenerated (TransformSpec + AssetDerive emitted); xtask emit-schemas regenerated workload.toml.schema.json; schema_drift test green. workload-spec: 24/24, cloud static_asset: 25/25, xtask: 2/2.")
164//!
165//! @yah:ticket(R438-T3, "ImageRef digest-pin enforcement at deserialize")
166//! @yah:assignee(agent:claude)
167//! @yah:at(2026-06-04T21:06:55Z)
168//! @yah:status(review)
169//! @yah:phase(P1)
170//! @yah:parent(R438)
171//! @arch:see(.yah/docs/working/W164-derived-static-assets.md)
172//! @arch:see(.yah/docs/working/W165-mesofact-build-mode-lowering.md)
173//! @yah:handoff("ImageRef now accepts either a string form (digest-pinned, W164/W165 path) or the legacy struct form (backwards-compat for WorkloadSpec configs). String form requires @sha256:<hex> suffix: bare-tag, non-sha256, and non-hex digests all reject at serde-deserialize. Single parser compose_import::parse_pinned_image_ref is the rule's one home; T4 (recipes) and T6 (BuildMode::InContainer) will both deserialize images through this string path. Custom Deserialize uses untagged enum (Pinned(String) | Struct(Fields)); Serialize/TS/JsonSchema derives stay on the struct so wire output and TS exports are unchanged. 6 new tests cover: bare-tag reject, pinned accept (docker.io + ghcr.io), non-sha256 algorithm reject, empty/non-hex digest reject, struct-form still works with digest=None, struct-form TOML round-trip. workload-spec: 30/30 lib + 18/18 semantic + 6/6 shape_fixtures. xtask schema_drift green after emit-schemas regen. cargo check --workspace clean.")
174//! @yah:next("Tighten ImageRef workspace-wide: digest: Option<String> → digest: String (required). tag stays as the human-readable identifier; digest is the source of truth. Rationale: every image we execute should be reproducible-by-construction; the on-disk shape should make unpinned-image bugs impossible.")
175//! @yah:next("Every existing ImageRef construction site updates to pass a digest. Call sites known today (~10): yubaba integration tests (fake digests via a test helper), yubaba/runtime/{containerd,fake}, yubaba/deploy/{mesh_resolve,env_validate}, local-runtime, cloud/config, workload-spec round_trip tests, restart_policy tests, compose_import::parse_image_ref. The break is bounded — single PR, no surprise call sites outside the workspace.")
176//! @yah:next("compose_import::parse_image_ref returns Result<ImageRef, ParseImageRefError> with an UnpinnedImage variant. Docker-compose strings without @sha256: become an explicit parse error — callers must pre-resolve tags to digests (most compose imports already happen at yubaba submission time where a pinning pass can run).")
177//! @yah:next("Add task::local::test_support::test_digest() (or similar) for test fixtures — a fixed valid-format sha256 string so tests don't have to mint their own.")
178//! @yah:next("Recipe TOML loader (T4) and W165 BuildMode::InContainer (T6) inherit the new requirement for free — they consume ImageRef and digest is now structurally required.")
179//! @yah:verify("cargo check --workspace --locked passes after the tightening + call-site migration (yubaba, runtime, local-runtime, mesh_resolve, env_validate, cloud/config, compose_import)")
180//! @yah:verify("ImageRef without digest no longer constructs — parse-time + type-level enforcement. cargo test -p workload-spec round_trip + restart_policy pass with updated fixtures.")
181//! @yah:verify("compose_import::parse_image_ref(\"node:20\") → Err(UnpinnedImage); parse_image_ref(\"node:20@sha256:...\") → Ok.")
182//! @yah:verify("cargo test -p yubaba --tests + -p local-driver passes with new test_digest() helper in place of bare tags.")
183//! @yah:gotcha("Earlier framing assumed T3 needed a PinnedImageRef newtype to avoid breaking yubaba. Reversed after design discussion 2026-06-04: breaking yubaba in service of reproducibility-by-construction is the right architectural move. Digest is required workspace-wide; tag stays as a human-readable identifier. ~10 call sites migrate in one PR.")
184//! @yah:gotcha("MesofactStaticWorkload.build_mode → InContainer { image } today is declared but never executed (build always runs on host — see W165). Once T3 tightens ImageRef, the wired-up build_mode lowering in T6 inherits digest-pinning automatically, closing W165 OQ#1's escape hatch.")
185//! @yah:assumes("No production yubaba deployment ships ImageRefs we don't already digest-pin. Spot-check Hetzner/cloud yah-castle workload specs before merging the tightening; if any prod path uses tag-only, it gets pinned in the same PR.")
186//! @yah:handoff("Pushed back from review 2026-06-04 — user reaffirmed the workspace-wide tightening direction. What landed (untagged Deserialize accepting string-form OR struct-form-with-digest:Option) ships digest enforcement at the W164/W165 wire surfaces but leaves the struct-form escape hatch (digest: None still constructs). User: 'breaking yubaba in order to improve it architecturally is fine'. Final shape needs both: (a) keep the string-form parser as a recipe-author convenience (image = \"ghcr.io/x@sha256:...\"), AND (b) tighten the struct form's digest: Option<String> → String. Then both paths land at the same digest-required field and unpinned-image bugs become impossible by construction. ~10 call sites still need migration (yubaba/runtime/{containerd,fake}, yubaba/deploy/{mesh_resolve,env_validate}, local-driver/local_runtime, cloud/config, workload-spec tests/round_trip + tests/restart_policy + yubaba integration_* + yubaba/tests/integration_public_ingress + integration_operator_bridge + integration_mesh + integration_single_node). Add task::local::test_support::test_digest() returning a fixed valid-format sha256 string. Pick this up by claiming R438-T3.")
187//! @yah:handoff("Workspace-wide ImageRef tightening landed. (a) ImageRef.digest: Option<String> → String at workload-spec/src/lib.rs:923; Deserialize struct arm now requires the field; untagged string-form parser at compose_import::parse_pinned_image_ref untouched. (b) ImageRef::docker_ref() now always emits tag@digest pair (informational tag alongside content-addressed digest). (c) validate.rs ImageTag check tightened: tag must be non-empty (digest presence is type-enforced now). (d) compose_import::parse_image_ref returns Result<ImageRef, String> — alias for parse_pinned_image_ref. import_compose gained ImportError::UnpinnedImage { service, image, reason } variant; only external caller (yah workload import in app/yah/cli/src/workload.rs) propagates the error type. (e) New workload_spec::testing module (doc-hidden) exposes TEST_DIGEST const + test_digest() fn — all-zeros 64-hex sentinel. (f) task::default_image::catalog_image falls back to testing::test_digest() when the per-image env var is unset, preserving the infallible API but making unset-digest visible at runtime via docker pull failure. default_buildkit_image follows the same pattern. (g) Migrated ~22 struct-form construction sites: workload-spec tests (round_trip/semantic/restart_policy + all 15 fixture JSONs + 3 compose YAML fixtures + matching expected.json), task crate (default_image/integration/lib/local/remote), yubaba (runtime/{containerd,fake}, deploy/{mesh_resolve,env_validate}, all 4 integration_*.rs files), cloud/config (3 sites), local-driver (local_runtime + pond_ssr_runtime), scryer/beholders, kamaji/{server,native,containerd}. (h) ImageSource::pull trait signature tightened: digest: Option<&'a str> → digest: &'a str (only one impl in yubaba/env_validate). (i) Read-site cleanup: yubaba::runtime::containerd::image_ref, kamaji::containerd::image_ref, local-driver::pond_ssr_runtime::compose_image_ref, task::local::image_ref_arg — all dropped Option ceremony, always emit tag@digest. cargo check --workspace clean. cargo test -p workload-spec: 82 pass. cargo test -p task --lib: 59 pass. Pre-existing test failures in cloud (5: 1 cloud_init drift, 4 mesofact_static adopt) and yubaba tests (pond_reconciler_smoke missing ssr_runtime/worker_mode/ssr_origin fields) are unrelated to ImageRef — separate ticket. R438-T4 (recipe loader) and R438-T6 (BuildMode::InContainer) inherit digest-required structurally with zero per-consumer work.")
188//!
189//! @yah:ticket(R438-T7, "Golden tests: recipe→ForgeSpec lowering + BuildMode→ForgeSpec lowering parity")
190//! @yah:assignee(agent:claude)
191//! @yah:at(2026-06-04T21:07:30Z)
192//! @yah:status(review)
193//! @yah:phase(P3)
194//! @yah:parent(R438)
195//! @yah:next("Golden test: sample transform recipe + asset.derive.transform.params lowers to expected ForgeSpec (argv, image digest, TaskPlacement)")
196//! @yah:next("Golden test: MesofactStaticWorkload with build_mode=in_container lowers to expected ForgeSpec")
197//! @yah:next("Round-trip parity: same Subprocess + Local + Container quadrant for both consumers; regression-guards argv-substitution and image-pin drop-through")
198//! @yah:verify("cargo test -p workload-spec lowering_golden_*")
199//! @yah:verify("Golden files versioned; updates require explicit --update flag")
200//! @arch:see(.yah/docs/working/W164-derived-static-assets.md)
201//! @arch:see(.yah/docs/working/W165-mesofact-build-mode-lowering.md)
202//! @yah:depends_on(R438-T5)
203//! @yah:depends_on(R438-T6)
204//! @yah:handoff("T7 landed. (1) Extracted pure lowering helpers exposed at pub(crate):\\n  - mesofact_static::lower_build_to_forge_spec(workload_dir, &BuildConfig, &BuildMode) -> ForgeSpec (run_build now wraps this)\\n  - static_asset::lower_recipe_step_to_forge_spec(&TransformRecipe, &RecipeStep, substituted_argv) -> ForgeSpec (materialize_transform now calls this for each step)\\n(2) New cfg(test) module crates/yah/cloud/src/reconciler/lowering_golden.rs registered from reconciler/mod.rs. Five golden tests:\\n  - golden_recipe_step_lowers_to_pinned_local_container_subprocess (recipe → ForgeSpec shape: argv, image digest, timeout, label, initiator)\\n  - golden_recipe_step_with_zero_timeout_lowers_to_none (regression-guards the timeout=0 → None mapping)\\n  - golden_build_in_container_lowers_to_pinned_local_container_subprocess (BuildMode::InContainer → sh -c shell wrap + pinned image + cwd label)\\n  - golden_build_host_side_lowers_to_native_quadrant_without_image (BuildMode::HostSide → image=None + TaskRuntime::Native)\\n  - parity_recipe_and_build_in_container_share_quadrant (THE architectural invariant: both consumers land in the same Subprocess + Local + Container quadrant with sha256-pinned images and Gnome initiators — lets one ForgeExecutor dispatch handle both)\\n(3) Test artifacts are hand-coded assertions, not insta/snapshot files — workspace has no insta infra and explicit-Pin tests give clearer diff on drift than auto-update snapshots. The W164/W165 lowering shape is now regression-guarded against silent drift in either consumer. cargo test -p cloud --lib reconciler::lowering_golden: 5 pass. Workspace check clean.")
205//! @yah:next("Sign off → archive R438-T7")
206//! @yah:next("T8 (worked examples) now has tested lowering primitives to reference")
207//! @yah:verify("cargo test -p cloud --lib reconciler::lowering_golden — 5 pass")
208//! @yah:verify("cargo test -p cloud --lib reconciler:: — 124 pass; 4 pre-existing R441-B4 adopt_only failures (port 4321 dev-box collision) unrelated")
209//! @yah:verify("cargo check --workspace --locked — clean (warnings only)")
210//! @yah:verify("Parity test asserts both lowerings produce TaskPlacement{Local, Container} + ForgeCommand::Subprocess + sha256-pinned image — the shared executor dispatch invariant")
211//! @yah:gotcha("Test location pivot: original ticket said `cargo test -p workload-spec lowering_golden_*` but the lowering primitives don't live in workload-spec — ForgeSpec/TaskPlacement are in task, and the actual lowering helpers are in cloud (both consumers live there). Tests landed in cloud as `reconciler::lowering_golden`. If a future consumer outside cloud needs the BuildMode lowering, lift `lower_build_to_forge_spec` up to task::transforms alongside the existing recipe lowering primitives.")
212//! @yah:gotcha("No snapshot/insta infra in workspace — 'Golden files versioned; updates require explicit --update flag' verify line interpreted as hand-coded explicit assertions instead. Drift surfaces as a single-file test diff on the lowering helper, which is more readable than a .snap diff for the small ForgeSpec shape these tests cover.")
213//!
214//! @yah:ticket(R594-F2, "Ingress workload kind in workload-spec: pinned-per-node appliance on public-ip-tainted machines")
215//! @yah:status(review)
216//! @yah:assignee(agent:claude)
217//! @yah:at(2026-07-03T06:03:30Z)
218//! @yah:phase(P2)
219//! @yah:parent(R594)
220//! @yah:next("Add the ingress workload kind to the Workload enum (lib.rs:296) as an appliance in the R572 archetype sense: pinned-per-node, non-drainable, placed by yubaba only on machines carrying a public-ip taint, supervised by kamaji. Depends on R572-F1 (lifecycle archetype discriminator) so the archetype field exists to mark it. Breaking change is fine (pre-release house style); update kamaji-bin server.rs InvalidSpec rejection list deliberately — kamaji MUST accept this kind (it supervises the proxy), unlike MesofactStatic/Almanac/StaticAsset.")
221//! @yah:verify("cargo test -p yah-workload-spec; cargo check -p yubaba -p kamaji-bin; kamaji admission accepts kind=ingress in a unit fixture")
222//! @yah:gotcha("RUNS SOLO: workload-spec is the shared-type DAG sink (yah-base) — every lane (yubaba, kamaji, qed, host app) rebuilds on its change. Pause all other wave-2/3 implementer lanes while this is active, and check R572-T2 (cpu_millis, Handoff) + R572-F1 owner state before claiming — same file.")
223//! @yah:depends_on(R572-F1)
224//! @yah:tier(Cleric)
225//! @yah:handoff("Modeled the W267 public-ingress appliance as a container-shaped workload (Workload::Container(WorkloadSpec)), not a new Workload variant: mark archetype = Some(LifecycleArchetype::Appliance) (R572-F1, pinned/non-drainable) and declare the public-ip placement requirement via a new annotation-based marker on WorkloadSpec (same zero-blast-radius pattern as existing wants_host_network/HOST_NETWORK_ANNOTATION, chosen specifically to avoid the ~26-call-site churn a new plain field forced for R572-F1's archetype field, and to avoid an exhaustive-match update in peer-owned kamaji-proto/codec.rs that a new Workload variant would force). Added: WorkloadSpec::requires_taint() -> Option<&str>, const REQUIRES_TAINT_ANNOTATION = \"yah.placement.requires-taint\", const PUBLIC_IP_TAINT = \"public-ip\", plus doc comments on Workload::Container recording the modeling decision and its rationale, all in oss/yah-base/crates/workload-spec/src/lib.rs (single file changed). This only declares the requirement as inert metadata — matching taint field on machine TOML is R572-F3 (not yet present) and scheduler enforcement is R572-F5; both out of scope here, noted in the doc comments. Verified kamaji needs NO change: deploy_workload's match in kamaji-bin/src/server.rs already dispatches any Workload::Container(_) to the containerd backend regardless of tier/annotations (only MesofactStatic/Almanac/StaticAsset hit the InvalidSpec rejection arm), confirmed by reading the code and by the existing deploy_container_without_feature_says_so / deploy_mesofast_static_is_rejected_as_invalid_spec unit tests both still passing unmodified. 2 new unit tests added (ingress_marked_spec_is_appliance_and_carries_public_ip_placement_requirement, ingress_marked_spec_round_trips_through_json_as_a_container_workload). cargo test -p yah-workload-spec --lib: 38/38 pass. cargo test -p yah-workload-spec --test round_trip: 7 pass, exactly the same pre-existing 2 postcard failures (round_trip_full_spec_through_postcard, workload_container_round_trips_through_postcard — R590-B3, unrelated) as before this change, confirmed not increased. cargo check -p yah-workload-spec / -p yubaba / -p kamaji-bin all clean, plus full cargo check --workspace in both oss/kamaji and oss/yubaba clean (only pre-existing unrelated warnings). No peer-owned file touched or needed.")
226//!
227//! @yah:ticket(R590-B10, "forge workload 256MB cgroup memory limit SIGKILLs real builds — rusty-v8 checkout OOMs (bumped to 32GB stopgap)")
228//! @yah:at(2026-07-12T00:14:52Z)
229//! @yah:status(review)
230//! @yah:assignee(agent:claude)
231//! @yah:parent(R590)
232//! @yah:severity(blocks-on-box-green)
233//! @yah:next("Proper fix: thread a per-step memory request from the pipeline (QedStep) through ForgeSpec -> WorkloadSpec so a build declares its footprint, instead of a blanket forge default. Also consider: build_oci_spec should treat memory_mb==0 as 'omit the cgroup limit' (unlimited) so dedicated build-workers aren't capped by an arbitrary constant; pair with a node-sized default. Revisit the 32GB stopgap once per-step resources land.")
234//! @yah:verify("yah qed run rusty-v8-musl on us-west-002 completes the checkout + gn/ninja compile without an OOM SIGKILL; a small forge task still runs (32GB is a ceiling, not a reservation).")
235//! @yah:gotcha("PROVEN live (2026-07-11): with B7 networking fixed, the rusty-v8 build cloned the full V8 tree then `git checkout third_party/icu` DIED OF SIGNAL 9 (OOM). WorkloadSpec::for_forge set resources.memory_mb=256, which build_oci_spec turns into a hard cgroup memory.limit. /tmp is a RAM-backed tmpfs so the multi-GB source checkout counts against that 256MB too. Bumped for_forge to 32768 (32GB) as a CLI-side stopgap; verified the build proceeds past icu.")
236//! @yah:handoff("FIXED + PROVEN LIVE (2026-07-11). WorkloadSpec::for_forge memory_mb 256 -> 32768 (oss/yah-base/crates/workload-spec/src/lib.rs). CLI-only change (spec is client-built), no kamaji redeploy. RESULT: with B7 networking, the rusty-v8 build previously OOM'd (SIGKILL/signal 9) at the icu git-checkout under the 256MB cgroup cap; now it clones the full V8 tree AND proceeds past icu into cargo/gn compilation (Compiling icu_locale_data/icu_calendar_data...) with task RUNNING. Stopgap 32GB ceiling; proper per-step memory request from the pipeline is the follow-up in the ticket body.")
237//!
238//! @yah:ticket(R546-B7, "workload_spec::Workload envelope is externally tagged (missing serde tag=kind) — no flat on-disk workload.toml can parse through it, broke yah cloud apply for EVERY static-asset component")
239//! @yah:phase(P1)
240//! @yah:status(review)
241//! @yah:assignee(agent:bundle-anthropic-ashguard)
242//! @yah:at(2026-08-03T00:44:43Z)
243//! @yah:parent(R546)
244//! @yah:next("DO NOT simply add `#[serde(tag = \"kind\")]` without checking postcard: `Workload` is also a postcard wire type on the kamaji RPC path (kamaji-proto/src/codec.rs matches on it; round_trip tests exist). postcard is non-self-describing and cannot decode internally-tagged enums, so naive tagging risks breaking the kamaji wire. Decide deliberately: (a) tag it and prove the postcard round-trips still pass, or (b) split the types — an on-disk `WorkloadManifest` with tag=kind, leaving `Workload` as the untagged wire type.")
245//! @yah:next("INTERIM FIX ALREADY LANDED (unblocks publishing): static_asset.rs::load_workload no longer routes through the envelope — it deserializes a small `KindProbe { kind }`, validates kind == \"static-asset\", then parses `StaticAssetWorkload` directly. Same approach seed_derivation_for_target already used successfully. This restored `yah cloud apply` and got the x86_64 rusty-v8 artifact published to the CDN (HTTP 200). The ENVELOPE itself is still broken for every other caller/kind.")
246//! @yah:next("Fix the test/example disagreement: lib.rs ~L2544 should assert the FLAT `kind = \"...\"` shape that real files use, and examples/parse_whisper_toml.rs should run in CI so this cannot regress silently again.")
247//! @yah:gotcha("SEVERITY: this silently broke `yah cloud apply` for EVERY static-asset component, not just rusty-v8. Verified against the long-published whisper catalog via the repo's own examples/parse_whisper_toml.rs, which panics with the identical error — so the breakage is general and pre-existing, not caused by the R546 hash edits.")
248//! @yah:gotcha("ROOT CAUSE: `pub enum Workload` (oss/yah-base/crates/workload-spec/src/lib.rs ~L386) derives Deserialize with ONLY `#[serde(rename_all = \"kebab-case\")]` — there is NO `#[serde(tag = \"kind\")]`, despite its own doc comment stating 'the `kind` field on the wire is the serde discriminator'. Without the tag it is EXTERNALLY tagged, so serde wants a map with exactly ONE key (the variant name). Every real workload.toml is FLAT (`kind = \"static-asset\"` + `schema_version` + `[[asset]]` + `[aliases]`), i.e. a multi-key map -> `TomlError: wanted exactly 1 element, more than 1 element`, reported confusingly at line 1 col 1.")
249//! @yah:gotcha("WHY THE UNIT TEST DIDN'T CATCH IT: the passing test at lib.rs ~L2544 feeds the EXTERNALLY-tagged shape `[[static-asset.asset]]`, which no on-disk file actually uses. So the test asserts the broken encoding and the example (parse_whisper_toml.rs) asserting the REAL encoding was never run in CI. The test and the example disagree; the example is right.")
250//! @yah:handoff("DONE. Workload now carries TWO wire shapes behind hand-written Serialize/Deserialize that branch on is_human_readable() -- option (a) and (b) from the ticket's next-steps merged into one type instead of splitting it. TOML/JSON get the INTERNAL `kind` tag (the flat shape every on-disk file uses); postcard keeps the EXTERNAL variant-index encoding R590-B3 established for the kamaji UDS. Same idiom ImageRef already used for its string-vs-struct form, so there is now one precedent, not two mechanisms. Mirror enums (WorkloadTagged/WorkloadExternal + borrowing twins) carry the two encodings; their variant ORDER is load-bearing for postcard and is commented as such. schemars/ts-rs get tag=kind + rename_all via #[schemars(...)]/#[ts(...)] so the generated JSON schema and TS bindings describe the on-disk shape instead of the wire shape.")
251//! @yah:handoff("SECOND BLOCKER, fixed in the same pass: after the tagging fix only 2 of 8 on-disk workload.toml files still parsed. SchemaVersion is a unit-variant enum wanting the string \"V1\", but 6 files (every mesofact-static + container + cloudflare-worker component) are authored `schema_version = 1`, and R438-T6 had worked around it by hand-extracting raw toml::Value subtrees in read_mesofact_build. Gave SchemaVersion a liberal-read/canonical-write Deserialize (accepts 1, \"V1\", \"v1\"; always serializes \"V1\"), on the same is_human_readable branch so postcard is untouched. B7's stated goal is not met without it -- a fixed envelope that still rejects 6 of 8 files is not fixed.")
252//! @yah:handoff("FILES. (1) oss/yah-base/crates/workload-spec/src/lib.rs -- Workload dual-shape impls + mirror enums; the lib.rs ~L2544 test that asserted the broken `[[static-asset.asset]]` encoding rewritten to the flat form, plus a new test pinning BOTH halves (flat kind in JSON, postcard round-trip). (2) .../src/version.rs -- SchemaVersion custom Deserialize + 3 tests. (3) .../src/bin/export-ts.rs -- path was 3 parents up from CARGO_MANIFEST_DIR, but 75d8df7e moved the crate under oss/yah-base and added a level, so since that commit the bin silently wrote to oss/yah-base/packages/ and the committed TS stopped tracking the Rust types (last real update Jun 28). Now 4. (4) scripts/check-workload-spec-ts.sh -- `cargo run -p yah-workload-spec` fails from the camp root (crate is in the excluded oss/yah-base workspace); switched to --manifest-path. It was dead since the same commit. (5) packages/yah/workload-spec/index.ts + .yah/schema/workload.toml.schema.json regenerated (mirror.toml.schema.json also moved -- that is @Ashguard:dragon's W267 ingress field swept in by the shared regen, not mine).")
253//! @yah:handoff("FIXTURE SWEEP (flagged by @Ashguard:dove mid-turn -- my change, my sweep): 8 yah-cloud tests were red on hand-written externally-tagged TOML. Fixed reconciler/derive_cache_prune.rs (2 fixtures), reconciler/static_asset_prune.rs (4), validate.rs (1), tests/whisper_derive_e2e.rs (1), app/yah/cli/src/cloud.rs (alias-collision fixture + the_deploy_body_parses_as_a_workload_envelope_not_a_bare_spec, which asserted external tagging and now asserts a flat `kind`). NOT touched: yubaba/src/lib.rs bundle_deploy_tests -- @Ashguard:dove already rewrote that one in their own relay's module and asked me not to double-fix.")
254//! @yah:handoff("COMMENTS CORRECTED, not left lying: static_asset.rs::load_workload and asset_status.rs both carried R546-B7 comments asserting the envelope is externally tagged and unusable. Both now say the envelope works and the direct StaticAssetWorkload parse is a deliberate shortcut (load_workload keeps it to produce a precise wrong-kind error naming the kind found; asset_status keeps it because component.kind is already checked upstream).")
255//! @yah:verify("THE TICKET'S OWN REPRO NOW PASSES: `cargo run --manifest-path oss/yah-base/crates/workload-spec/Cargo.toml --example parse_whisper_toml` -> 'parsed as StaticAsset / assets: 2 / aliases: 3 / shape validation: ok / populated-shape verifier: ok'. It panicked before against the long-published whisper catalog.")
256//! @yah:verify("NEW CI GATE (the ticket's third next-step): xtask/tests/workload_envelope.rs walks the whole camp for workload.toml, parses every file whose kind is one of the four modelled variants through workload_spec::Workload, and hard-asserts no error contains 'wanted exactly 1 element' -- the exact external-tagging signature. It lives in xtask, not workload-spec, because that crate is in the standalone-exported oss/yah-base workspace and cannot reach app/ or .yah/. Runs under the check pipeline's existing cargo-test step. Carries a SHRINK-ONLY KNOWN_GAPS list: a file that starts parsing FAILS the test until its entry is deleted, and a stale entry (file moved/deleted) also fails, so the list cannot rot or grow silently.")
257//! @yah:verify("GREEN: yah-workload-spec --all-features (55 lib + round_trip/postcard + shape_fixtures, 10 targets, 0 failed); kamaji-proto 25/25 incl. deploy_container_round_trip and deploy_string_pinned_image_ref_survives_postcard_wire (the exact UDS path R590-B3 fixed -- proves the binary branch is byte-unchanged); yubaba --lib 339/339; yah-cloud 610 lib + whisper_derive_e2e 1/1; yah --lib cloud:: 108/108; xtask schema_drift 2/2 and workload_envelope 1/1.")
258//! @yah:verify("NOT MINE, seen while verifying: (a) reconciler::pond::tests::{ensure_sim_port_free_ok_when_unbound, port_has_listener_...} flake in a full-suite run and pass in isolation -- they bind real ports and race on a busy dev box. (b) 10 arch::ticket::tests failures in `cargo test -p yah --lib` from a peer's in-flight @yah: annotation-parser work; app/yah/cli/src/arch/ticket.rs has zero references to workload_spec, so nothing in this change can reach them. (c) MirrorConfig's new `ingress` field (@Ashguard:dragon, W267/R594) broke the yah-cloud and yah-cli test builds mid-session; it cleared on its own as they swept call sites -- I did not touch their files.")
259//! @yah:gotcha("VARIANT ORDER IS LOAD-BEARING. WorkloadExternal / WorkloadExternalRef in lib.rs must list variants in the SAME order as Workload -- postcard encodes an external tag as the variant INDEX, so reordering or inserting a variant anywhere but the end silently decodes kamaji UDS frames into the wrong variant. There is no type error for this. Commented at the definitions; the round_trip postcard tests catch a mismatch only if the payload types differ enough to fail decode.")
260//! @yah:gotcha("TWO GAPS DELIBERATELY NOT CLOSED, filed as R658 (umbrella) -> R658-B1 (MesofactStaticWorkload.routes is a required top-level field but all 4 real files AND the CLI scaffold write it inside [build], so TOML scopes it to build.routes) and R658-B2 (kind = \"container\" selects two incompatible schemas: Workload::Container(WorkloadSpec) vs ContainerReconciler's local docker build/run shape). Neither is the B7 tagging bug -- they were invisible until the envelope started being exercised. B2 needs an operator naming decision. Both are pinned in workload_envelope.rs's KNOWN_GAPS so they cannot be forgotten or silently widened.")
261//! @yah:gotcha("HALF-STALE as of 2026-08-18: the gotcha above says both R658 gaps are pinned in workload_envelope.rs KNOWN_GAPS. Only R658-B2 (`missing field image`) still is. R658-B1 is CLOSED - all four `missing field routes` entries were deleted, every manifest and the `yah cloud site init` scaffold now write routes ABOVE [build], and BuildConfig carries serde(deny_unknown_fields) so the misplacement is a parse error rather than a dropped key. See R658-B1.")
262//!
263//! @yah:ticket(R626-S3, "Where does desired-state live? Durable per-workload replica count that survives reconcile loops and camp restarts (0↔1 vs scale-to-N)")
264//! @yah:status(review)
265//! @yah:assignee(agent:bundle-anthropic-glimmerstone)
266//! @yah:at(2026-07-23T17:47:24Z)
267//! @yah:kind(spike)
268//! @yah:phase(P3)
269//! @yah:parent(R626)
270//! @yah:handoff("DECIDED + LANDED. Desired state lives in the CAMP DAEMON, in a durable camp-local document at <camp>/.yah/state/desired-state.json, and NEVER crosses the kamaji or yubaba wire. The governing principle, written to survive the tier: desired state belongs to the DECLARER, not the supervisor — whoever re-asserts a deployment owns the record of whether it is wanted, because anything stored below the declarer is overwritten by the declarer's next re-assert. In the pond/dev tier the declarer is camp (ensure_pond_running -> reconcile_pond_deploys -> deploy_pond_mirrors, which runs at every camp start AND every pond.ensure_running RPC). In cloud the same rule points at the CloudConfig reconciler's raft store. Kamaji is never the holder in either tier.")
271//! @yah:handoff("REJECTIONS, with the reason each is not a near-miss. kamaji-local: kamaji is deliberately imperative (Deploy/Stop/List, crash-restart delegated to dockerd's policy per R626-F2) — it holds no desired set and runs no reconcile loop, so storing intent there means giving it a SECOND reconciler that can disagree with camp's, and it still loses to camp's POST /pond/deploy from above. yubaba raft: right answer at cloud scale, wrong scope here — the pond yubaba is a container camp starts, its PondRegistry is in-memory (a restart forgets everything), and a single-camp dev tier has no quorum to be consistent about. Git-tracked config: camp.toml/mirror.toml are the DECLARATION (what exists); a stop is per-machine operator intent (systemctl disable, not editing the unit file) and must not propagate to a teammate's checkout — hence .yah/state/ is gitignored, in both the camp's .gitignore and the scaffold_camp_skeleton template.")
272//! @yah:handoff("SHAPE: one knob, `replicas`, where 0 = stopped — deliberately the SAME axis as workload_spec::WorkloadSpec.replicas so scale-to-N later lifts a ceiling instead of adding a second concept beside a boolean. MAX_SUPPORTED_REPLICAS = 1 today and set_replicas REJECTS anything higher rather than persisting an intent no supervisor can honour (a clamp would silently record something the operator did not ask for). No record = replicas 1: a declared workload runs unless someone said otherwise. updated_at + reason ride along so a stale intent is legible and the UI can say when/why. Writes are tmp-then-rename; reads FAIL OPEN (missing/unreadable/corrupt/newer-schema all mean 'everything runs', corrupt file preserved as .corrupt-<epoch_ms>) — fail-closed would mass-stop a camp on one bad byte, and a resurrection is the recoverable failure.")
273//! @yah:handoff("LANDED: (1) app/yah/cli/src/desired_state.rs — DesiredStateDoc / WorkloadDesire / DesiredStateStore (load, desired_replicas, is_stopped, stopped_keys, set_replicas, stop, start, forget), 10 unit tests incl. survives-a-camp-restart, per-workload isolation, replicas>1 rejected AND not written, corrupt-file quarantine + fail-open, newer-schema fail-open, and an explicit 'a stop is not a failure' guard on the serialized document. (2) camp.rs: deploy_pond_mirrors and reconcile_pond_deploys now consult the store and skip stopped idents — this is THE enforcement point, since camp's re-assert is the only place 'stay stopped' can be honoured. Extracted pond_idents_needing_deploy(declared, registered, stopped) as a pure helper with 5 tests, because the stopped-subtraction is the load-bearing half: a stopped workload is absent from yubaba's registry ON PURPOSE and is indistinguishable from a failed deploy without the intent record. (3) .yah/.gitignore + app/yah/cli/templates/yah-gitignore-default gain /state. (4) .yah/docs/working/W287-desired-state-for-supervised-workloads.md carries the full rationale, the rejected options, the F4 build-on list, and the scale-to-N scoping.")
274//! @yah:handoff("DELIBERATE NON-GOAL: writing intent does NOT actuate. The durable record must land even when the stop call fails, or a failed stop comes back on the next reconcile. Actuation is R626-F4's job.")
275//! @yah:next("R626-F4 is unblocked and now has a concrete spec — see W287 §5. It needs three things this ticket deliberately did not build: (a) a per-ident teardown on yubaba (PondRegistry has only shutdown_all, which drains everything; /pond/deploy and /pond/state are the only pond routes), (b) camp RPC methods workload.stop / workload.start writing through DesiredStateStore, (c) desired-vs-actual reporting.")
276//! @yah:next("DO NOT add a Stopped variant to PondPhase (R626-F2's noted gap). PondPhase is yubaba's observation of REALITY; intent never crosses that wire by this decision. Camp is the one process holding both halves — render the pair instead: desired=stopped + actual=absent reads 'deliberately stopped'; desired=running + actual=absent reads 'down'.")
277//! @yah:next("Scale-to-N stays scoped, not committed (W287 §6). WorkloadSpec.replicas makes N look one constant away; it is not. kamaji native.rs:592 rejects replicas>1, and the docker backend names containers by mesh identity (one identity, one container). N needs a placement layer above the single-workload supervisor: per-replica naming (identity==container name is what makes teardown resolve), per-replica host ports (pond publishes fixed ones — two replicas collide), per-replica mesh identity (a load-balanced set is an xlb-net concern), and a placement decision that is yubaba's job on a fleet. Lifting MAX_SUPPORTED_REPLICAS is the entry point once that layer exists.")
278//! @yah:next("Wire DesiredStateStore::forget into the undeclare path so the document doesn't accumulate intent for mirrors that no longer exist.")
279//! @yah:verify("cargo test -p yah --lib desired_state — 15 pass (10 desired_state::tests + 5 camp::r626_s3_desired_state_gate_tests), 0 fail")
280//! @yah:verify("cargo check -p yah — clean (note: this camp's tree is shared and was transiently broken by peers' in-flight edits in oss/qed, yah-party, and yah-almanac during this run; none touched by this ticket)")
281//! @yah:verify("BEHAVIOUR BAR (the one that matters): DesiredStateStore::for_camp(root).stop(ident) followed by a FRESH store over the same root still reports is_stopped — that is exactly a camp restart — and pond_idents_needing_deploy then omits that ident from an EMPTY registry, which is exactly a restarted yubaba. Asserted in camp::r626_s3_desired_state_gate_tests::a_stop_survives_a_camp_restart_end_to_end.")
282//! @yah:gotcha("The store is camp-local and GITIGNORED on purpose. If a future ticket wants a stop to be shared/durable in the repo, that is a different decision (declaration vs intent) — re-open W287 §2 rather than moving the file into tracked territory.")
283//! @yah:gotcha("Reads fail OPEN. Never 'harden' this into fail-closed: an unreadable document would then stop an entire camp, and the failure would be silent (nothing starts) rather than visible (the workload comes back).")
284//!
285//!
286//! @yah:relay(R658, "workload.toml envelope: two type-vs-reality mismatches R546-B7 uncovered but did not fix")
287//! @yah:at(2026-08-03T00:43:00Z)
288//! @yah:status(open)
289//! @yah:assignee(agent:bundle-anthropic-ashguard)
290//! @yah:parent(R546)
291//!
292//! @yah:ticket(R658-B1, "MesofactStaticWorkload.routes is a required top-level field, but every real file and the CLI scaffold write it inside [build]")
293//! @yah:status(review)
294//! @yah:at(2026-08-19T02:08:02Z)
295//! @yah:assignee(agent:bundle-anthropic-ashguard)
296//! @yah:parent(R658)
297//! @yah:next("REPRO: `cargo test -p xtask --test workload_envelope` with the file's KNOWN_GAPS entry deleted -> `missing field `routes``. Affects app/yah/web/marketing/workload.toml, external/scrabcake/site/workload.toml, .yah/infra/state/sources/scrabcake/site/site/workload.toml, oss/yubaba/crates/cloud/testdata/mesofact-in-container/workload.toml.")
298//! @yah:next("ROOT CAUSE: TOML scopes every key after a table header into that table. All four files write `routes = \"./mesofact.routes.ts\"` AFTER `[build]`, so it deserializes as `build.routes` -- but MesofactStaticWorkload declares `routes` as a required TOP-LEVEL field. BuildConfig ignores the unknown key, so it vanished silently.")
299//! @yah:next("THE SCAFFOLD AGREES WITH THE FILES, NOT THE TYPE: SITE_WORKLOAD_TOML in app/yah/cli/src/cloud.rs (~line 4977) emits `routes` inside [build] too, so every newly scaffolded site inherits the mismatch. Fix the type or fix the scaffold -- but they must agree, and whichever moves needs the other four files migrated with it.")
300//! @yah:next("WHY IT WENT UNNOTICED: nothing reads `routes` off the envelope. mesofact-static's reconciler never loads MesofactStaticWorkload whole (read_mesofact_build does raw toml::Value subtree extraction, R438-T6), and mesofact-build reads mesofact.routes.ts directly. The field is declared but dead.")
301//! @yah:next("AFTER FIXING: delete the four `missing field `routes`` entries from KNOWN_GAPS in xtask/tests/workload_envelope.rs -- that test FAILS on a stale entry, so it will tell you.")
302//! @yah:next("SPREAD, found 2026-08-14 by R715-T2: two MORE files hit this and are NOT in KNOWN_GAPS, so `cargo test -p xtask --test workload_envelope` is RED on a clean tree for everyone. The two are app/yah/web/chat/workload.toml and oss/mesofact/examples/hello/workload.toml, both the same routes-after-[build] shape. Deliberately NOT pinned into KNOWN_GAPS - silently widening the pin is what this ticket exists to stop. Migrate them alongside the other four when the type-vs-scaffold decision lands.")
303//! @yah:handoff("DECIDED: the DATA moved to the type, not the type to the data. `routes` stays a TOP-LEVEL field of MesofactStaticWorkload; all eight on-disk manifests and the CLI scaffold now write it ABOVE [build]. Three reasons the reverse was wrong: (1) MesofactStaticWorkload is a postcard wire type over the kamaji UDS, so moving a field between structs is a wire break needing a lockstep kamaji+yubaba deploy; (2) the field's own doc says it is what the RECONCILER reads to enumerate routes, i.e. deploy-time not build-time, so [build] is the wrong home semantically; (3) the reconciler's own fixtures (mesofact_static.rs), three camp.rs fixtures and the struct literal at cloud.rs:5389 already agreed with the type - only the hand-authored TOML disagreed.")
304//! @yah:verify("cargo test -p xtask --test workload_envelope - GREEN (was RED on a clean tree for everyone). All four `missing field routes` KNOWN_GAPS entries DELETED, not widened; only R658-B2's `missing field image` remains.")
305//! @yah:handoff("ROOT-CAUSE GUARD, the part that makes this not recur: workload_spec::BuildConfig now carries #[serde(deny_unknown_fields)] (oss/yah-base/crates/workload-spec/src/lib.rs). Migrating the files alone would have left the trap armed - serde silently dropping a stray [build] key is WHY a declared-but-dead field survived months unnoticed. Now the misplacement is a parse error naming `routes`, which is the one thing the author needs to move. Inert for the postcard kamaji wire (non-self-describing, positional); only constrains TOML/JSON.")
306//! @yah:verify("cargo test --manifest-path oss/yah-base/crates/workload-spec/Cargo.toml --all-features - 121 lib (incl. 3 new R658-B1 tests) + 8 integration targets, 0 failed. New: mesofact_static_routes_parse_at_the_top_level, mesofact_static_routes_inside_build_is_rejected_by_name, unknown_build_keys_are_refused_rather_than_ignored.")
307//! @yah:verify("cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib - 878 passed, 0 failed.")
308//! @yah:verify("cargo test -p yah --lib cloud:: - 120 passed, 0 failed, incl. the new site_init_tests::scaffold_workload_toml_parses_through_the_envelope_with_top_level_routes.")
309//! @yah:verify("cargo test -p xtask - all 12 targets green, incl. schema_drift and workload_envelope.")
310//! @yah:verify("./scripts/check-workload-spec-ts.sh - in sync (ts-rs ignores deny_unknown_fields, so no TS churn).")
311//! @yah:handoff("DISCOVERED WORK, wider than the ticket title - deny_unknown_fields immediately caught TWO live files the envelope test structurally CANNOT see. app/yah/web/analytics/workload.toml and app/yah/web/dashboard/workload.toml are kind = mesofact-spa, which is not in the test's MODELLED_KINDS, but mesofact-spa rides the SAME MesofactStaticReconciler (app/yah/cli/src/cloud.rs:5195) and therefore the same read_mesofact_build -> BuildConfig parse. Both had routes under [build]; without migrating them my own guard would have broken deploys for analytics.yah.dev and app.yah.dev. Both migrated. Swept every workload.toml in the camp for stray [build] keys: the only two remaining are crates/yah/cloud-admin (R658-B2's file) and app/yah/workers/yah-cr, and NEITHER goes through workload_spec::BuildConfig - both use reconciler-local raw toml::Value extraction (cloudflare_worker.rs:200), so both are unaffected.")
312//! @yah:handoff("ALSO FIXED IN THIS PASS (docs are canon; these were what a human copies): .yah/docs/guides/host-a-site-and-worker-on-yah.md:102 and .yah/docs/architecture/A031-yah-cloud-config-shape.md:438 both showed routes UNDER [build] - they would have re-seeded the bug into every hand-authored manifest. Also oss/yubaba/crates/cloud/src/config.rs:5890 (web_workload_round_trips fixture) and the bundle_assembly_tests fixture at app/yah/cli/src/cloud.rs.")
313//! @yah:handoff("UNRELATED LANDED BREAKAGE unblocked to verify at all: oss/yubaba/crates/cloud/src/reconciler/lowering_golden.rs:48 failed to compile with E0063 missing field `admission` - TransformRecipe gained admission: Option<RecipeAdmission> (oss/qed/crates/velveteen-exec/src/transforms.rs:70, landed in 8b35b0a9) and this golden was never updated. Whole yah-cloud test binary would not build. Added `admission: None` (correct: the golden is an unsigned local recipe and pins the LOWERING shape, which the signature does not participate in). Both files were committed-clean, not a peer's in-flight edit - checked git status before touching.")
314//! @yah:gotcha("UNCOMMITTED REGEN - .yah/schema/workload.toml.schema.json is REGENERATED in the working tree (cargo run -p xtask -- emit-schemas) and must be committed WITH this change. deny_unknown_fields makes schemars emit additionalProperties: false on BuildConfig. scripts/check-schema-drift.sh compares generated output against the git INDEX, so it stays RED until the regen is committed - that is the script working as designed, not drift. Only workload.toml.schema.json moved; no peer's schema was swept in (git diff --stat -- .yah/schema/ = 1 file).")
315//! @yah:assumes("deny_unknown_fields on BuildConfig trades forward-compat for loudness: a manifest carrying a [build] key an older binary does not know is now a hard parse error, not an ignored key. Deliberate and argued in the type's doc comment. Blast radius outside this monorepo is any site scaffolded by an older `yah cloud site init` - the template shipped routes under [build] for its whole life, so such a site now fails to parse until routes is moved above the header. The only tenant in the tree (scrabcake) was migrated; an external one would need the same one-line move.")
316//! @yah:gotcha("NOW FULLY STALE as of 2026-08-19: the HALF-STALE note above says R658-B2's `missing field image` is the one KNOWN_GAPS entry left. R783-F1/F2 closed that too, so KNOWN_GAPS in xtask/tests/workload_envelope.rs is EMPTY - every modelled on-disk workload.toml parses through the envelope. An entry reappearing means a real file stopped parsing.")
317//!
318//!
319//! @yah:ticket(R743-T4, "workload-spec: 7 test binaries to 1")
320//! @yah:at(2026-08-11T01:18:24Z)
321//! @yah:status(review)
322//! @yah:phase(P2)
323//! @yah:parent(R743)
324//! @yah:next("tests/main.rs mod'ing all 7 siblings + autotests = false and [[test]] name = \"main\" in oss/yah-base/crates/workload-spec/Cargo.toml.")
325//! @yah:next("tests/compose/ and tests/fixtures/ are data/module dirs, not targets — they are unaffected. Confirm the [[bin]] named export-ts in Cargo.toml is untouched by autotests = false (it is a bin, not a test, but read it before editing).")
326//! @yah:verify("cargo test -p yah-workload-spec -- --list count unchanged; three green runs. One commit — oss subtree.")
327//! @yah:tier(Cleric)
328//! @yah:handoff("LANDED: tests/main.rs mods in the 7 former top-level integration-test files (compose_import, mesh_resolver, restart_policy, round_trip, secrets_invariant, semantic, shape_fixtures) as submodules; Cargo.toml gained `autotests = false` on [package] plus a single `[[test]] name = \"main\" path = \"tests/main.rs\"`. tests/compose/ and tests/fixtures/ untouched (data dirs); the export-ts [[bin]] untouched (autotests only scans tests/, not bins). Quick audit found nothing to fix: no std::env::set_var/remove_var, no set_current_dir, no TcpListener/bind/fixed ports in any of the 7 files, and only one inner `mod secrets` (in secrets_invariant.rs) which nests fine under its own file-module with no sibling collision — so no renames were needed.")
329//! @yah:verify("RUSTC_WRAPPER=\"\" cargo test -p yah-workload-spec -- --list (run inside oss/yah-base): BEFORE 8 targets (lib 146 + export-ts bin 0 + 7 integration files summing to 65: compose_import 5, mesh_resolver 8, restart_policy 5, round_trip 16, secrets_invariant 7, semantic 18, shape_fixtures 6) = 211 total. AFTER 4 targets (lib 146 + export-ts bin 0 + single `main` integration binary 65, all 65 test names now module-qualified e.g. round_trip::round_trip_full_spec + doctests 0) = 211 total, unchanged.")
330//! @yah:verify("RUSTC_WRAPPER=\"\" cargo test -p yah-workload-spec (inside oss/yah-base): ok. 146 passed lib + ok. 65 passed main + 0 doctests, 0 failed — run three times, all green, no pre-existing failures to record.")
331//!
332//! @yah:ticket(R783-F1, "ContainerManifest: split the on-disk container manifest from the wire WorkloadSpec, keeping postcard byte-identical")
333//! @yah:status(review)
334//! @yah:at(2026-08-19T07:11:49Z)
335//! @yah:assignee(agent:bundle-anthropic-ashguard)
336//! @yah:parent(R783)
337//! @arch:see(.yah/docs/working/W324-workload-kind-is-not-a-runtime.md)
338//! @yah:next("THE SEAM: introduce `ContainerManifest = Reference(WorkloadSpec) | Recipe(ContainerBuild)` and change Workload::Container's payload to it. WorkloadExternal::Container KEEPS WorkloadSpec so the postcard kamaji wire is byte-identical - verify with the existing round_trip.rs postcard tests, which must pass UNCHANGED.")
339//! @yah:next("WHY a recipe cannot just be a WorkloadSpec (this is the whole design): ImageRef.digest is String, not Option<String> - R438-T3 tightened it deliberately and the string form REJECTS a bare tag at serde-deserialize (lib.rs:187, parser compose_import::parse_pinned_image_ref). The local form's image is `yah-local/yah-cloud-admin:dev`, a bare tag, because the digest does not exist until docker build has run. Preserve that invariant; do not weaken ImageRef to make this easier.")
340//! @yah:next("Encode the invariant in the signature: ContainerBuild::into_spec(self, digest: &str) -> WorkloadSpec. The lowering is only available AFTER a build produced a digest. Serializing a Recipe to postcard must be an Err, not a panic and not a silent empty digest.")
341//! @yah:next("Tier: Wizard - cross-workspace type split with a wire invariant to preserve; the postcard encoding is positional and a mistake decodes silently into the wrong variant.")
342//! @yah:verify("cargo test --manifest-path oss/yah-base/crates/workload-spec/Cargo.toml --all-features - round_trip.rs postcard tests must pass UNCHANGED (they are the wire-compat gate).")
343//! @yah:verify("cargo test -p xtask --test workload_envelope with the `missing field image` KNOWN_GAPS entry for crates/yah/cloud-admin/workload.toml DELETED - that file is the acceptance case.")
344//! @yah:verify("cargo test --manifest-path oss/kamaji/Cargo.toml -p kamaji-proto codec - deploy_container_round_trip is the exact UDS path.")
345//! @yah:gotcha("VARIANT ORDER IS LOAD-BEARING on WorkloadExternal/WorkloadExternalRef - postcard encodes the external tag as the variant INDEX, so reordering or inserting anywhere but the end silently decodes kamaji UDS frames into the WRONG variant, with no type error. Commented at the definitions in lib.rs.")
346//! @yah:gotcha("BLAST RADIUS ~25 real construction/match sites across FOUR workspaces: oss/kamaji (incl. peer-owned kamaji-proto/src/codec.rs exhaustive matches), oss/yubaba, oss/qed, app/yah/cli, oss/yah-base. R594-F2 deliberately avoided exactly this churn by using an annotation instead of a field (lib.rs:225) - that was right for a marker, and is NOT right here, but read that note before assuming the churn is accidental.")
347//! @yah:gotcha("Consider a Workload::container(spec) constructor + ContainerManifest::as_spec() accessor to keep the ~25 sites one-line mechanical rather than restructured.")
348//! @yah:handoff("LANDED. `ContainerManifest = Reference(WorkloadSpec) | Recipe(ContainerBuild)` is now `Workload::Container`'s payload (oss/yah-base/crates/workload-spec/src/lib.rs). New public types: ContainerManifest, ContainerBuild, ContainerBuildStep, ContainerRunConfig, ContainerMount, plus `Workload::container(spec)` / `Workload::container_spec()` / `Workload::container_manifest()` so the ~25 call sites stayed one-line.")
349//! @yah:verify("cargo test --manifest-path oss/yah-base/crates/workload-spec/Cargo.toml --all-features - 127 lib + 8 integration targets, 0 failed. round_trip.rs: 16 pass.")
350//! @yah:verify("cargo test -p xtask - all 12 targets green incl. workload_envelope 1/1 with KNOWN_GAPS now EMPTY (R658-B2's `missing field image` entry deleted, not widened) and schema_drift 3/3.")
351//! @yah:verify("cargo test --manifest-path oss/kamaji/Cargo.toml --workspace - green incl. kamaji-proto codec 26/26 (deploy_container_round_trip, the exact UDS path) and kamaji-bin 213/213.")
352//! @yah:verify("cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib 881 pass / -p yubaba --lib 492 pass; cargo test -p yah --lib cloud:: 120 pass.")
353//! @yah:handoff("THE WIRE CLAIM IS NOW A TEST, not an assertion. round_trip.rs::container_postcard_frame_is_the_variant_index_then_the_bare_spec asserts the frame is exactly [1] ++ postcard(WorkloadSpec) - a round-trip alone would still pass if both halves moved together. WorkloadExternal::Container keeps WorkloadSpec; Workload's binary Serialize maps Reference through unchanged and returns Err for Recipe (round_trip.rs::container_recipe_is_refused_by_postcard_rather_than_encoded).")
354//! @yah:handoff("DISCRIMINATOR: presence of a `[build]` table means Recipe; presence of top-level `image` means Reference; NEITHER is its own error naming both forms rather than a misleading `missing field image`. Hand-written Deserialize, not serde(untagged), specifically so a malformed reference still reports `missing field tier` instead of 'data did not match any variant'.")
355//! @yah:gotcha("UNCOMMITTED REGEN - both generated artifacts are regenerated in the working tree and must be committed WITH this change: .yah/schema/workload.toml.schema.json (cargo run -p xtask -- emit-schemas) and packages/yah/workload-spec/index.ts (cargo run --manifest-path oss/yah-base/crates/workload-spec/Cargo.toml --bin export-ts). Both scripts/check-schema-drift.sh and scripts/check-workload-spec-ts.sh exit 1 right now because they diff generated output against the git INDEX - that is the scripts working as designed, not drift. cargo test -p xtask schema_drift (which diffs against the working tree) is GREEN.")
356//! @yah:gotcha("SIGNATURE DEVIATION from the ticket text, deliberate: into_spec is `ContainerBuild::into_spec(self, digest: &str, tier: TierTag) -> Result<WorkloadSpec, String>`, not the infallible two-arg form the ticket sketched. Fallible because digest is a caller-supplied string and a malformed one must error rather than mint a spec that lies about being content-addressed - it routes through compose_import::parse_pinned_image_ref, the one home of the R438-T3 digest rule. tier is a parameter because admission control is cluster policy, not a manifest fact. Recorded in W324 under a new 'As shipped (R783-F1)' section.")
357//! @yah:assumes("ContainerBuild::into_spec has NO production caller yet - it is the documented lowering with unit-test coverage only. Its unset-image default is `yah-local/<manifest name>:dev`, which is NOT the same string ContainerReconciler's default_image_tag builds (`yah-local/<service>-<component>:dev`) because the manifest only knows its own name. If a future caller lowers a recipe whose [build].image was left unset and expects to find the image the reconciler built, those two defaults have to be reconciled first.")
358//! @yah:cleanup("LocalProcessReconciler still parses its own private ProcessComponent for the [process] table (oss/yubaba/crates/cloud/src/reconciler/local_process.rs:696). The envelope does not model [process] at all, so that tier is still a second parser over the same file - the exact shape R783-F2 just removed for the container tier. W324 section 1 names it as the third runtime behind kind = container; folding it in is the natural next step and is deliberately NOT in R783.")
359//!
360//! @yah:ticket(R838-B1, "xtask workload_envelope fails on both machines: the template deliberately omits [build] command while workload_spec Workload requires it as a non-Option String")
361//! @yah:status(review)
362//! @yah:at(2026-08-31T00:17:46Z)
363//! @yah:assignee(agent:bundle-anthropic-ashguard)
364//! @yah:parent(R838)
365//! @yah:handoff("LANDED. workload_spec::BuildConfig.command is now Option<String> with #[serde(default)] (oss/yah-base/crates/workload-spec/src/lib.rs:1439). Absent means the project has no external bundler step, which is what mesofact new's scaffold template documents about itself. xtask workload_envelope now passes with KNOWN_GAPS still EMPTY, which was the goal state that test names for itself.")
366//! @yah:handoff("WHY THIS WAS NOT A DECISION AFTER ALL. The sibling ticket R658-B3 filed the same bug as DECISION REQUIRED because it read the deploy path as having no branch for a missing command. It has one, in two of the three readers, and it predates this change: app/yah/cli/src/cloud.rs:3368 read_workload_build has ALWAYS returned Option<String>; assemble_component_bundle_with_sidecars (cloud.rs:3492) needs the command only under --run-build and otherwise assembles from an existing out_dir; deploy_mesofact_bundle (cloud.rs:5841) refuses None with a message that already reads correctly, and cloud.rs:8387 a_missing_build_command_is_reported_not_skipped already tested that refusal. The only reader that made it mandatory was the type. So no in-process build branch had to be invented.")
367//! @yah:handoff("RECONCILER: lower_build_to_forge_spec now returns Option<ForgeSpec> (None when no command) and run_build logs a skip and returns Ok. That is the same outcome rebuild_static already produced for a workload with no workload.toml. Deliberately NOT sh -c with an empty string: that exits 0 having built nothing, so the reconciler would report success and publish stale out_dir bytes.")
368//! @yah:handoff("WIRE: BuildConfig rides the postcard kamaji wire inside Workload::MesofactStatic, so String -> Option<String> adds a leading tag byte. A pre-R838 node decoding a new frame fails loudly (a string length byte is not a valid Option tag) rather than reading a shifted field, which is why this is Option and not a serde(default) empty-String sentinel. NOT a cluster-epoch surface: xtask/src/cluster_epochs.rs hashes the yubaba raft modules and the openraft pin, not workload_spec; all 8 cluster_epoch_drift tests stayed green, so no epoch bump is owed.")
369//! @yah:handoff("CALL SITES (10, four workspaces, all mechanical): kamaji-proto/src/codec.rs:1077, kamaji-bin/src/server.rs x3, yubaba/src/lib.rs:9000, cloud/src/reconciler/lowering_golden.rs x2 (+3 .expect() on the now-Option lowering), cloud/src/reconciler/mesofact_static.rs (revalidate_static's render BuildConfig + 2 fixtures + 3 assertions), app/yah/cli/src/cloud.rs:5725.")
370//! @yah:handoff("GENERATED ARTIFACTS REGENERATED AND MUST BE COMMITTED WITH THIS: .yah/schema/workload.toml.schema.json (command dropped from required, type now [string,null]) and packages/yah/workload-spec/index.ts (command: string | null). Both scripts/check-workload-spec-ts.sh and scripts/check-schema-drift.sh exit 1 until the commit lands because they diff against the git INDEX; the working-tree equivalent, cargo test -p xtask schema_drift, is green. Same shape as the R783-F1 note above.")
371//! @yah:verify("cargo test -p xtask --tests --locked: 54 passed, 0 failed. Includes workload_envelope::every_on_disk_workload_toml_parses_through_the_envelope (was 0 passed / 1 failed with 'missing field command'), schema_drift 3/3, cluster_epoch_drift 8/8.")
372//! @yah:verify("cargo test --manifest-path oss/yah-base/Cargo.toml -p yah-workload-spec --all-features --locked: 146 lib + 68 integration, 0 failed. Three NEW tests in tests/round_trip.rs: mesofact_static_build_table_without_a_command_parses_as_none, an_unknown_build_key_is_still_refused_now_that_command_is_optional (deny_unknown_fields from R658-B1 did not loosen), mesofact_static_build_command_round_trips_through_postcard_both_ways.")
373//! @yah:verify("cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib: 927 passed, 0 failed, 4 ignored. Three NEW tests in reconciler::mesofact_static::tests: read_mesofact_build_accepts_a_build_table_with_no_command, rebuild_static_skips_the_build_step_when_no_command_is_declared (asserts the CaptureExecutor got nothing), lowering_a_build_with_no_command_yields_no_forge_spec.")
374//! @yah:verify("cargo test --manifest-path oss/yubaba/Cargo.toml -p yubaba --lib: 553 passed, 0 failed.")
375//! @yah:verify("cargo test --manifest-path oss/kamaji/Cargo.toml --workspace: all green incl. kamaji-proto codec 26/26 (the UDS round-trip) and kamaji-bin 217/217.")
376//! @yah:verify("cargo check --all-targets --locked on the root workspace: clean (warnings only, all pre-existing).")
377//! @yah:verify("cargo test --locked --no-fail-fast on the root workspace: one failure, yah-log tests::init_noop_without_env, which is NOT this change and is already filed as R840-B1 (it reads process-global env and the camp build rail exports YAH_TASK_RUN + YAH_LOG_PIPE; it passes in CI and under env -u).")
378//! @yah:gotcha("DEAD GENERATED FILE FOUND, not touched: oss/packages/yah/workload-spec/index.ts is tracked, a month stale (last written 2026-07-29, has no ContainerManifest so it predates R783-F1), referenced by nothing, and gated by nothing. It is the fossil of the off-by-one that export-ts.rs:107 documents in its own comment: with ancestors().nth(3) the bin wrote to oss/packages/ instead of the camp root, and the stray output got committed. export-oss.sh exports oss/<name> subtrees, and oss/packages is not one, so it is not even on an export path. Deleting it is a one-line git rm but it is a tracked-file deletion outside this ticket, so it is named here rather than done.")
379//! @yah:gotcha("STALE CLAIM in a neighbouring annotation, disproved but left in place: oss/yubaba/crates/cloud/src/reconciler/mesofact_static.rs:165 (R438-T6) says read_mesofact_build must hand-extract toml::Value subtrees because 'schema_version = 1 (integer) ... the typed envelope rejects'. R546-B7 made SchemaVersion read the bare integer (oss/yah-base/crates/workload-spec/src/version.rs), and the workload_envelope run proves it: the only error reported for the scaffold template was 'missing field command', never schema_version. The subtree reader has other reasons to exist, but that one is gone.")
380//!
381//! @yah:ticket(R658-B3, "mesofact new scaffolds a workload.toml the deploy path cannot execute: BuildConfig.command is required but the template deliberately omits it")
382//! @yah:at(2026-08-30T08:33:45Z)
383//! @yah:status(open)
384//! @yah:parent(R658)
385//! @yah:severity(high)
386//! @yah:next("DECISION REQUIRED, do not guess. oss/mesofact/crates/mesofact/src/cli/new/template/workload.toml (new in ef8bd656) declares kind = mesofact-static with no [build] command, and its own header comment says that is deliberate: 'Left unset, mesofact-dev runs the build pipeline in-process — no third binary, no package manager, no Node.' But BuildConfig.command is a required String (oss/yah-base/crates/workload-spec/src/lib.rs:1428), so the file does not parse through workload_spec::Workload.")
387//! @yah:next("The deploy path has no in-process branch. MesofactStaticReconciler uses build.command unconditionally — oss/yubaba/crates/cloud/src/reconciler/mesofact_static.rs:1143 builds vec![sh, -c, build.command.clone()], and 1173/1179/1185 log and execute it. So making command Option<String> is NOT a mechanical type change: it requires deciding what 'yah cloud bundle build' DOES for a manifest with no command. That is the actual open question.")
388//! @yah:next("Three options. (a) command becomes Option<String> and the reconciler gains an in-process build branch — matches the template's documented intent and the W225 s2 'no package manager, no Node' promise, but MesofactStaticWorkload is a postcard wire type over the kamaji UDS, so a shape change is a lockstep kamaji+yubaba deploy (see the R658-B1 handoff, which rejected moving a field for exactly this reason). (b) The template gains a command — contradicts its own comment and the no-Node promise. (c) Add a KNOWN_GAPS entry in xtask/tests/workload_envelope.rs — unblocks check today, records the gap honestly, decides nothing.")
389//! @yah:verify("cargo test -p xtask --test main --locked -- workload_envelope::every_on_disk_workload_toml_parses_through_the_envelope (currently: 0 passed, 1 failed, 'missing field command')")
390//! @yah:gotcha("BLOCKS THE RELEASE GATE. This fails cargo test -p xtask --tests, which is check.toml step 7 (xtask-tests), which release-check runs before oss-publish. It also very likely fails release-check's second sub-pipeline mesofact-new-smoke, whose stated promise is that 'mesofact new' produces a project that builds and serves with no package manager and no Node on PATH — the same scaffold.")
391//! @yah:gotcha("WHY THIS WAS INVISIBLE UNTIL NOW: check.toml's cargo-test step has no --no-fail-fast and died at yah-party, so steps 5-16 never ran this cycle. Separately, R605-S6 documents that xtask is a workspace member but NOT a default-member, so plain cargo test never reaches these tests at all, and workload_envelope was named there as one of eight test binaries that had been dark since being written. KNOWN_GAPS in xtask/tests/workload_envelope.rs is currently empty, so this file DID parse before ef8bd656 introduced the template — it is a regression, not a pre-existing gap.")
392//! @yah:tier(Warrior)
393//! @yah:next("Option (a) was taken. The open question that made this a decision was already answered by the code: yah cloud bundle build does NOT require a command. app/yah/cli/src/cloud.rs:3368 read_workload_build has always typed it Option<String>; assemble_component_bundle_with_sidecars needs it only under --run-build; deploy_mesofact_bundle refuses None by name at cloud.rs:5841. So no in-process build branch had to be invented: the reconciler skips the build step for None, exactly as it already did for a workload with no workload.toml at all.")
394//! @yah:next("TO CLOSE: re-run cargo test -p xtask --test main --locked -- workload_envelope:: (passes now) and archive. Nothing left to build here.")
395//! @yah:handoff("FIXED BY R838-B1 (same bug, filed twice; R838-B1 is the older ID). BuildConfig.command is now Option<String> in oss/yah-base/crates/workload-spec/src/lib.rs. cargo test -p xtask --tests is 54/54 green including workload_envelope, the gate that was failing.")
396
397use std::collections::BTreeMap;
398use std::collections::HashMap;
399use std::path::PathBuf;
400
401use serde::{Deserialize, Serialize};
402use ts_rs::TS;
403
404pub mod admission;
405pub mod compose_import;
406pub mod control_plane_install;
407pub mod rollout;
408pub mod secrets;
409pub mod sovereign;
410pub mod validate;
411mod version;
412
413pub use version::SchemaVersion;
414
415// ── Duration ──────────────────────────────────────────────────────────────────
416
417/// Duration expressed as an integer millisecond count.
418///
419/// Used for healthcheck intervals, timeouts, delays, and stop grace periods.
420/// Chosen over `std::time::Duration` to keep serde support dependency-free.
421#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, TS)]
422#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
423#[ts(type = "number")]
424pub struct Millis(pub u64);
425
426impl Millis {
427    pub fn from_secs(s: u64) -> Self {
428        Self(s * 1000)
429    }
430
431    pub fn from_ms(ms: u64) -> Self {
432        Self(ms)
433    }
434
435    pub fn as_ms(self) -> u64 {
436        self.0
437    }
438
439    pub fn as_secs_f64(self) -> f64 {
440        self.0 as f64 / 1000.0
441    }
442}
443
444// ── Primitive newtypes ────────────────────────────────────────────────────────
445
446/// Opaque identifier for a yubaba-managed machine within the cluster.
447///
448/// Used by the semantic validation layer for admission-control capacity checks.
449/// Yubaba passes its own machine ID when validating a spec before deployment.
450#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)]
451#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
452pub struct MachineId(pub String);
453
454/// DNS-segment identity for a workload on the cluster mesh, e.g.
455/// `"noisetable-api.pdx"`. Regex constraint: `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`,
456/// length ≤ 63. Enforced in shape validation (R090-F2).
457#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
458#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
459pub struct MeshIdent(pub String);
460
461/// Tier classification that governs admission control and mesh `allow_from`
462/// filtering. Known values: `"public"`, `"tenant"`, `"private"`, `"infra"`.
463/// Custom tiers are allowed per cluster; shape validation warns on unknowns
464/// rather than rejecting them (R090-F2).
465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
466#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
467pub struct TierTag(pub String);
468
469/// Default single-tenant identity written to specs that predate the tenant
470/// axis (W206). Its concrete string is arbitrary — what matters is that a
471/// single-tenant cluster only ever sees this one value, so every per-tenant
472/// isolation primitive collapses to a no-op. See [`TenantId::singleton`].
473pub const DEFAULT_TENANT: &str = "default";
474
475/// Default single-namespace identity for specs that predate the namespace
476/// axis (W206). See [`NamespaceId::singleton`].
477pub const DEFAULT_NAMESPACE: &str = "default";
478
479/// Tenant **isolation** axis (W206). Separates one operator's workloads from
480/// another's at the network / DB / mesh-identity level. Orthogonal to
481/// [`NamespaceId`] (routing/naming) and [`TierTag`] (workload class within a
482/// `(tenant, namespace)` pair).
483///
484/// **Degenerate case:** when a yubaba reconciler sees only one `TenantId`
485/// across every workload on a machine, per-tenant Podman networks collapse
486/// into the shared tier networks, the tenant prefix on mesh identity is
487/// dropped, and PostgreSQL role separation is skipped — isolation primitives
488/// become no-ops. You pay only when more than one tenant is present. Specs
489/// written before this axis existed deserialize to [`TenantId::singleton`].
490#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, TS)]
491#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
492pub struct TenantId(pub String);
493
494impl TenantId {
495    /// The singleton tenant used for back-compat with single-tenant (current)
496    /// deployments. Specs written before the tenant axis existed deserialize
497    /// to this value via the `#[serde(default)]` on [`WorkloadSpec::tenant`],
498    /// keeping the whole cluster single-tenant so every isolation primitive
499    /// stays a no-op.
500    pub fn singleton() -> Self {
501        Self(DEFAULT_TENANT.to_string())
502    }
503
504    /// Whether this is the singleton (degenerate single-tenant) identity.
505    pub fn is_singleton(&self) -> bool {
506        self.0 == DEFAULT_TENANT
507    }
508}
509
510/// Namespace **routing/naming** axis (W206). A pure naming key that never
511/// affects isolation: it selects the config root, disambiguates service DNS
512/// names within a tenant, prefixes object-store bucket names within a tenant's
513/// bucket scope, and selects the provider zone (e.g. `noisetable.com` vs
514/// `yah.dev`). Two namespaces in the same tenant share networks, mesh-identity
515/// space, and PG cluster — they simply cannot collide on workload names or
516/// external domains. Specs written before this axis existed deserialize to
517/// [`NamespaceId::singleton`].
518#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, TS)]
519#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
520pub struct NamespaceId(pub String);
521
522impl NamespaceId {
523    /// The singleton namespace used for back-compat with single-namespace
524    /// (current) deployments. Specs written before the namespace axis existed
525    /// deserialize to this value via the `#[serde(default)]` on
526    /// [`WorkloadSpec::namespace`].
527    pub fn singleton() -> Self {
528        Self(DEFAULT_NAMESPACE.to_string())
529    }
530
531    /// Whether this is the singleton (degenerate single-namespace) identity.
532    pub fn is_singleton(&self) -> bool {
533        self.0 == DEFAULT_NAMESPACE
534    }
535}
536
537// ── Workload (on-disk envelope) ──────────────────────────────────────────────
538
539/// On-disk `workload.toml` manifest. Each variant matches one
540/// `ServiceComponent.kind` value; the `kind` field on the wire is the serde
541/// discriminator.
542///
543/// This is the **on-disk** envelope — distinct from [`WorkloadSpec`], the
544/// containerd wire format yubaba receives over RPC. A `kind = "container"`
545/// workload deserializes its remaining fields as a [`ContainerManifest`],
546/// which is *either* a digest-pinned `WorkloadSpec` or a local Dockerfile
547/// recipe (R783-F1 / W324); other kinds carry their own per-reconciler
548/// payload shape.
549///
550/// **Never put `#[serde(skip_serializing_if = "Option::is_none")]` on a field
551/// of this enum or any type it reaches.** These types ride the kamaji-proto
552/// **postcard** wire, which is non-self-describing and positional:
553/// `skip_serializing_if` omits the field's byte on serialize while decode still
554/// expects to read it at that offset, so the byte stream misaligns and the
555/// round-trip fails. Use `#[serde(default)]` + `#[ts(optional = nullable)]`
556/// instead — that still gives TOML/JSON back-compat (missing field → `None`)
557/// while the field is always encoded. `MesofactStaticWorkload::ssr_runtime` and
558/// `::serve_bundle` are the reference shape.
559/// **Two wire shapes, one type (R546-B7).** `Serialize`/`Deserialize` are
560/// hand-written and branch on [`is_human_readable`](serde::Deserializer::is_human_readable):
561///
562/// - **TOML/JSON (human-readable)** → *internally* tagged on `kind`, i.e. the
563///   flat shape every on-disk `workload.toml` actually uses
564///   (`kind = "static-asset"` beside `schema_version`, `[[asset]]`, `[aliases]`).
565/// - **postcard (binary)** → *externally* tagged, byte-identical to the derived
566///   representation R590-B3 established for the kamaji UDS.
567///
568/// Why not just `#[serde(tag = "kind")]`: internal tagging buffers through
569/// `deserialize_any`, which postcard (non-self-describing) refuses with
570/// `WontImplement` — that is exactly the failure R590-B3 fixed by flipping this
571/// enum to external tagging. But external tagging wants a single-key map, so
572/// every flat on-disk file then failed with `wanted exactly 1 element, more
573/// than 1 element` and `yah cloud apply` broke for every static-asset
574/// component. Branching on the format satisfies both, and mirrors what
575/// [`ImageRef`] already does for its string-vs-struct form.
576#[derive(Debug, Clone, PartialEq, TS)]
577#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
578#[cfg_attr(
579    feature = "json-schema",
580    schemars(tag = "kind", rename_all = "kebab-case")
581)]
582#[ts(tag = "kind", rename_all = "kebab-case")]
583pub enum Workload {
584    /// Static-site build that publishes an artifact directory to the
585    /// service's `static` provider slot. Reconciled by the
586    /// `mesofact-static` reconciler — does not deploy to yubaba.
587    MesofactStatic(MesofactStaticWorkload),
588
589    /// A container-shaped workload. **Two on-disk forms** (R783-F1 / W324),
590    /// see [`ContainerManifest`]: a digest-pinned [`WorkloadSpec`] reference
591    /// (the form that crosses the kamaji wire) or a local Dockerfile
592    /// [`ContainerBuild`] recipe (which cannot, because it names no digest
593    /// until it has been built).
594    ///
595    /// Construct the wire form with [`Workload::container`] and read it back
596    /// with [`Workload::container_spec`] — most callers only ever mean the
597    /// reference form and should not have to name the manifest enum.
598    ///
599    /// The reference form's inline fields are the full [`WorkloadSpec`] minus
600    /// the `kind` discriminator.
601    ///
602    /// This is also the shape of the W267 sovereign-public-ingress appliance
603    /// (R594-F2): a container-kind workload with `archetype =
604    /// Some(LifecycleArchetype::Appliance)` and
605    /// `requires_taint() == Some(PUBLIC_IP_TAINT)`, **not** a dedicated
606    /// `Workload::ingress(..)` variant. It runs an ordinary OCI image (the
607    /// `passway` proxy, R594-F4) supervised by kamaji exactly like any other
608    /// `Container`, so no admission-list or wire-codec change was needed to
609    /// let kamaji accept it. A new enum variant would have forced an
610    /// exhaustive-match update in every `Workload` consumer, including
611    /// peer-owned `kamaji-proto/src/codec.rs` — the archetype + annotation
612    /// combination expresses "this is the public ingress appliance" without
613    /// that blast radius. See [`WorkloadSpec::requires_taint`] and
614    /// [`LifecycleArchetype::Appliance`].
615    Container(ContainerManifest),
616
617    /// Data-pipeline job with declared I/O and a readiness policy. The
618    /// orchestrator checks all `inputs` are reachable before each run and
619    /// verifies `outputs` afterward. Generalises the OpenRouter JSON-cache
620    /// refresher (`spawn_almanac_refresher`) to the full manifest form.
621    Almanac(AlmanacManifest),
622
623    /// Content-addressed static files uploaded to the mirror's `object_store`
624    /// provider slot. Wave-0 by default — gating mesofact and container waves.
625    /// Rollback is a pointer-flip via `mirror.toml [asset_aliases]`; bytes are
626    /// append-only and never re-pushed on rollback. See W160.
627    StaticAsset(StaticAssetWorkload),
628}
629
630impl Workload {
631    /// The `kind` discriminator this variant serializes as — the same string a
632    /// `workload.toml` writes and a `ServiceComponent.kind` names.
633    ///
634    /// Lives here rather than at a call site because this enum now has FIVE
635    /// places that enumerate its variants (itself plus the four tagging
636    /// mirrors below); a caller-local match would be a sixth, in another crate,
637    /// with nothing to force it to keep up.
638    pub fn kind_str(&self) -> &'static str {
639        match self {
640            Workload::MesofactStatic(_) => "mesofact-static",
641            Workload::Container(_) => "container",
642            Workload::Almanac(_) => "almanac",
643            Workload::StaticAsset(_) => "static-asset",
644        }
645    }
646
647    /// Wrap a digest-pinned [`WorkloadSpec`] as a `kind = "container"`
648    /// workload — the form that crosses the kamaji wire.
649    ///
650    /// Every caller that synthesizes a container workload in code (ingress
651    /// appliances, forge runs, kamaji's own deploy path) means *this* form;
652    /// the [`ContainerManifest::Recipe`] arm only ever arrives by parsing a
653    /// `workload.toml` with a `[build]` table. Keeping the constructor here
654    /// means R783-F1 did not have to teach ~25 call sites the name of a
655    /// manifest enum they have no opinion about.
656    pub fn container(spec: WorkloadSpec) -> Self {
657        Workload::Container(ContainerManifest::Reference(spec))
658    }
659
660    /// The digest-pinned spec of a `kind = "container"` workload, if this is
661    /// a container workload in the reference form.
662    ///
663    /// `None` covers both "not a container" and "a container *recipe*, which
664    /// has no spec until it is built" — a consumer that speaks the wire
665    /// (kamaji, yubaba's deploy path) must treat both as inadmissible, so
666    /// collapsing them into one `None` is deliberate rather than lossy. Use
667    /// [`Workload::container_manifest`] when the two need distinguishing.
668    pub fn container_spec(&self) -> Option<&WorkloadSpec> {
669        match self {
670            Workload::Container(m) => m.as_spec(),
671            _ => None,
672        }
673    }
674
675    /// The container manifest, in whichever on-disk form it was written.
676    pub fn container_manifest(&self) -> Option<&ContainerManifest> {
677        match self {
678            Workload::Container(m) => Some(m),
679            _ => None,
680        }
681    }
682}
683
684/// Internally-tagged mirror of [`Workload`] — the on-disk shape. Only ever
685/// reached on the human-readable branch, so its `deserialize_any` buffering is
686/// never asked of postcard.
687#[derive(Serialize, Deserialize)]
688#[serde(tag = "kind", rename_all = "kebab-case")]
689enum WorkloadTagged {
690    MesofactStatic(MesofactStaticWorkload),
691    Container(ContainerManifest),
692    Almanac(AlmanacManifest),
693    StaticAsset(StaticAssetWorkload),
694}
695
696/// Borrowing twin of [`WorkloadTagged`] so `Serialize` need not clone the
697/// payload. Variant order must match [`Workload`].
698#[derive(Serialize)]
699#[serde(tag = "kind", rename_all = "kebab-case")]
700enum WorkloadTaggedRef<'a> {
701    MesofactStatic(&'a MesofactStaticWorkload),
702    Container(&'a ContainerManifest),
703    Almanac(&'a AlmanacManifest),
704    StaticAsset(&'a StaticAssetWorkload),
705}
706
707/// Externally-tagged mirror — the postcard wire shape R590-B3 established.
708/// postcard encodes an external tag as the *variant index*, so the variant
709/// ORDER here is load-bearing: it must match [`Workload`] exactly or the
710/// kamaji UDS silently decodes into the wrong variant.
711///
712/// `Container` deliberately keeps [`WorkloadSpec`], **not**
713/// [`ContainerManifest`] (R783-F1 / W324): the wire carries only the
714/// digest-pinned reference form, so these bytes are unchanged by the on-disk
715/// split, and a [`ContainerManifest::Recipe`] is refused at serialize rather
716/// than encoded as a second variant nothing on the far side can execute.
717#[derive(Serialize, Deserialize)]
718#[serde(rename_all = "kebab-case")]
719enum WorkloadExternal {
720    MesofactStatic(MesofactStaticWorkload),
721    Container(WorkloadSpec),
722    Almanac(AlmanacManifest),
723    StaticAsset(StaticAssetWorkload),
724}
725
726/// Borrowing twin of [`WorkloadExternal`]. Same order requirement.
727#[derive(Serialize)]
728#[serde(rename_all = "kebab-case")]
729enum WorkloadExternalRef<'a> {
730    MesofactStatic(&'a MesofactStaticWorkload),
731    Container(&'a WorkloadSpec),
732    Almanac(&'a AlmanacManifest),
733    StaticAsset(&'a StaticAssetWorkload),
734}
735
736impl Serialize for Workload {
737    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
738    where
739        S: serde::Serializer,
740    {
741        if s.is_human_readable() {
742            match self {
743                Workload::MesofactStatic(w) => WorkloadTaggedRef::MesofactStatic(w),
744                Workload::Container(w) => WorkloadTaggedRef::Container(w),
745                Workload::Almanac(w) => WorkloadTaggedRef::Almanac(w),
746                Workload::StaticAsset(w) => WorkloadTaggedRef::StaticAsset(w),
747            }
748            .serialize(s)
749        } else {
750            match self {
751                Workload::MesofactStatic(w) => WorkloadExternalRef::MesofactStatic(w),
752                // The wire gate (W324 §5). A recipe names no digest, so there
753                // is nothing for kamaji to pull — refusing here makes "a build
754                // recipe cannot reach kamaji" a fact the type system holds,
755                // rather than a convention someone eventually forgets.
756                Workload::Container(ContainerManifest::Recipe(_)) => {
757                    return Err(serde::ser::Error::custom(RECIPE_IS_NOT_A_WIRE_SPEC))
758                }
759                Workload::Container(ContainerManifest::Reference(spec)) => {
760                    WorkloadExternalRef::Container(spec)
761                }
762                Workload::Almanac(w) => WorkloadExternalRef::Almanac(w),
763                Workload::StaticAsset(w) => WorkloadExternalRef::StaticAsset(w),
764            }
765            .serialize(s)
766        }
767    }
768}
769
770impl<'de> Deserialize<'de> for Workload {
771    fn deserialize<D>(de: D) -> Result<Self, D::Error>
772    where
773        D: serde::Deserializer<'de>,
774    {
775        if de.is_human_readable() {
776            Ok(match WorkloadTagged::deserialize(de)? {
777                WorkloadTagged::MesofactStatic(w) => Workload::MesofactStatic(w),
778                WorkloadTagged::Container(w) => Workload::Container(w),
779                WorkloadTagged::Almanac(w) => Workload::Almanac(w),
780                WorkloadTagged::StaticAsset(w) => Workload::StaticAsset(w),
781            })
782        } else {
783            Ok(match WorkloadExternal::deserialize(de)? {
784                WorkloadExternal::MesofactStatic(w) => Workload::MesofactStatic(w),
785                // Only the reference form exists on the wire, by construction
786                // of `WorkloadExternal` — see its doc comment.
787                WorkloadExternal::Container(w) => Workload::container(w),
788                WorkloadExternal::Almanac(w) => Workload::Almanac(w),
789                WorkloadExternal::StaticAsset(w) => Workload::StaticAsset(w),
790            })
791        }
792    }
793}
794
795// ── Container manifest (R783-F1 / W324) ───────────────────────────────────────
796
797/// Error text used both by the postcard serializer gate and by
798/// [`ContainerManifest::into_spec`]'s doc, so the two cannot drift.
799const RECIPE_IS_NOT_A_WIRE_SPEC: &str = "a kind = \"container\" workload in the RECIPE form \
800     (a [build] table) cannot cross the kamaji wire: it names an image tag, not a digest, and \
801     the digest does not exist until `docker build` has run. Lower it with \
802     `ContainerBuild::into_spec(digest)` after the build, then send the resulting WorkloadSpec.";
803
804/// On-disk payload of `kind = "container"` — **two forms**, one wire type
805/// (W324 §5).
806///
807/// A [`WorkloadSpec`] asserts a content-addressed identity: its
808/// [`ImageRef::digest`] is a required `sha256:<hex>` and the string form
809/// rejects a bare tag at serde-deserialize (R438-T3). A local component built
810/// from a Dockerfile next to its `workload.toml` cannot satisfy that — its
811/// image is `yah-local/<name>:dev`, and the digest does not exist until the
812/// build has run. So a build *recipe* is not a degenerate spec with a missing
813/// field; it is a promise to produce one, and the two are different types.
814///
815/// The discriminator is the presence of a `[build]` table. `WorkloadSpec` has
816/// no `build` field and [`ContainerBuild`] requires one, so the two shapes are
817/// mutually exclusive — and picking the branch explicitly (rather than with
818/// `#[serde(untagged)]`) is what lets a malformed reference still report
819/// `missing field \`image\`` instead of "data did not match any variant".
820///
821/// Only [`Reference`](Self::Reference) crosses the postcard kamaji wire; see
822/// [`WorkloadExternal`]'s doc comment for why that keeps those bytes
823/// byte-identical to the pre-split encoding.
824#[derive(Debug, Clone, PartialEq, TS)]
825#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
826#[cfg_attr(feature = "json-schema", schemars(untagged))]
827#[ts(untagged)]
828pub enum ContainerManifest {
829    /// Digest-pinned image. Crosses the wire as-is.
830    Reference(WorkloadSpec),
831
832    /// Dockerfile recipe. **Local only** — see [`ContainerBuild`].
833    Recipe(ContainerBuild),
834}
835
836impl ContainerManifest {
837    /// The digest-pinned spec, or `None` for the recipe form.
838    pub fn as_spec(&self) -> Option<&WorkloadSpec> {
839        match self {
840            ContainerManifest::Reference(spec) => Some(spec),
841            ContainerManifest::Recipe(_) => None,
842        }
843    }
844
845    /// The build recipe, or `None` for the reference form.
846    pub fn as_recipe(&self) -> Option<&ContainerBuild> {
847        match self {
848            ContainerManifest::Recipe(b) => Some(b),
849            ContainerManifest::Reference(_) => None,
850        }
851    }
852
853    /// Consume the manifest, yielding the digest-pinned spec. `Err` carries
854    /// the recipe back so a caller that *can* build it still has it.
855    pub fn into_spec(self) -> Result<WorkloadSpec, ContainerBuild> {
856        match self {
857            ContainerManifest::Reference(spec) => Ok(spec),
858            ContainerManifest::Recipe(b) => Err(b),
859        }
860    }
861
862    /// `"reference"` or `"recipe"` — for error messages that need to name
863    /// which form was found without matching on the enum at the call site.
864    pub fn form(&self) -> &'static str {
865        match self {
866            ContainerManifest::Reference(_) => "reference",
867            ContainerManifest::Recipe(_) => "recipe",
868        }
869    }
870}
871
872impl Serialize for ContainerManifest {
873    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
874    where
875        S: serde::Serializer,
876    {
877        match self {
878            // Transparent in both directions: the on-disk container form is
879            // the payload's own fields flattened under `kind = "container"`,
880            // exactly as it was before the split.
881            ContainerManifest::Reference(spec) => spec.serialize(s),
882            ContainerManifest::Recipe(recipe) => {
883                if s.is_human_readable() {
884                    recipe.serialize(s)
885                } else {
886                    Err(serde::ser::Error::custom(RECIPE_IS_NOT_A_WIRE_SPEC))
887                }
888            }
889        }
890    }
891}
892
893impl<'de> Deserialize<'de> for ContainerManifest {
894    fn deserialize<D>(de: D) -> Result<Self, D::Error>
895    where
896        D: serde::Deserializer<'de>,
897    {
898        use serde::de::Error as _;
899
900        // postcard and friends are non-self-describing, so there is no map to
901        // probe for `[build]` — and by construction the binary wire only ever
902        // carries the reference form anyway (`WorkloadExternal::Container`).
903        if !de.is_human_readable() {
904            return WorkloadSpec::deserialize(de).map(ContainerManifest::Reference);
905        }
906
907        // Buffer once, then branch explicitly. `serde_json::Value` is the
908        // buffer rather than `#[serde(untagged)]`'s private `Content` because
909        // untagged discards the inner error: `missing field \`image\`` — the
910        // one thing an author needs to see — becomes "data did not match any
911        // variant of untagged enum ContainerManifest".
912        let buffered = serde_json::Value::deserialize(de)?;
913
914        match (
915            buffered.get("build").is_some(),
916            buffered.get("image").is_some(),
917        ) {
918            (true, _) => ContainerBuild::deserialize(buffered)
919                .map(ContainerManifest::Recipe)
920                .map_err(|e| {
921                    D::Error::custom(format!(
922                        "kind = \"container\" with a [build] table is a local build recipe: {e}"
923                    ))
924                }),
925            (false, true) => WorkloadSpec::deserialize(buffered)
926                .map(ContainerManifest::Reference)
927                .map_err(|e| {
928                    D::Error::custom(format!(
929                        "kind = \"container\" without a [build] table is a digest-pinned image \
930                         reference: {e}"
931                    ))
932                }),
933            // Neither marker. Reporting `missing field \`image\`` here would
934            // send a recipe author off to add a field their form does not
935            // have, so name both forms instead — this is the one case where
936            // the file does not say which of the two it is trying to be.
937            (false, false) => Err(D::Error::custom(
938                "kind = \"container\" must declare either a digest-pinned `image` (the wire \
939                 form: a WorkloadSpec yubaba hands to kamaji) or a [build] table (a local \
940                 Dockerfile recipe built on the operator's box) — it declares neither",
941            )),
942        }
943    }
944}
945
946/// `kind = "container"` in the **recipe** form: a Dockerfile next to the
947/// component's `workload.toml`, built and run on the operator's box.
948///
949/// This is the shape `ContainerReconciler` drives (`docker build` from
950/// [`build`](Self::build), `docker run` with [`run`](Self::run)). It is
951/// deliberately *not* a `WorkloadSpec` — see [`ContainerManifest`] for why the
952/// digest invariant makes that impossible, and [`Self::into_spec`] for the one
953/// lowering that is allowed.
954///
955/// **Unknown keys are tolerated on purpose.** `crates/yah/cloud-admin/workload.toml`
956/// carries a `[process]` table read by `LocalProcessReconciler` on the dev
957/// mirror — one component file, three tier runtimes (W324 §1). Adding
958/// `deny_unknown_fields` here would make that file unparseable as a container
959/// manifest, which is the opposite of the point.
960#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
961#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
962pub struct ContainerBuild {
963    /// Wire-format version. Always `V1` today.
964    pub schema_version: SchemaVersion,
965
966    /// Component name. Same field the reference form carries, so a manifest
967    /// identifies itself the same way whichever form it is written in.
968    pub name: String,
969
970    /// How the image is built. Its presence is what makes this a recipe.
971    pub build: ContainerBuildStep,
972
973    /// How the built image is run locally.
974    #[serde(default)]
975    pub run: ContainerRunConfig,
976}
977
978impl ContainerBuild {
979    /// Lower a recipe to the wire type, **once a build has produced a digest**.
980    ///
981    /// The signature is the invariant (W324 §5): there is no way to reach a
982    /// `WorkloadSpec` from a recipe without supplying the `sha256:<hex>` the
983    /// build emitted, so an unpinned container spec cannot be constructed by
984    /// accident.
985    ///
986    /// Fallible because `digest` is a caller-supplied string: a malformed one
987    /// must be an error, not a `WorkloadSpec` that lies about being
988    /// content-addressed. Everything the recipe does not declare
989    /// (`tier`, `resources`, `restart_policy`, …) takes the same defaults a
990    /// hand-written local container gets; `tier` is the caller's because
991    /// admission control is a cluster policy, not a manifest fact.
992    pub fn into_spec(self, digest: &str, tier: TierTag) -> Result<WorkloadSpec, String> {
993        let image_tag = self
994            .build
995            .image
996            .clone()
997            .unwrap_or_else(|| format!("yah-local/{}:dev", self.name));
998
999        // Route through the one parser that owns the digest rule (R438-T3) so
1000        // the recipe path cannot grow a second, laxer definition of "pinned".
1001        let image = compose_import::parse_pinned_image_ref(&format!("{image_tag}@{digest}"))
1002            .map_err(|e| format!("lowering container recipe {:?}: {e}", self.name))?;
1003
1004        let ports = self.run.port.map(|p| vec![p]).unwrap_or_default();
1005
1006        Ok(WorkloadSpec {
1007            schema_version: self.schema_version,
1008            name: self.name.clone(),
1009            image,
1010            tier,
1011            tenant: TenantId::singleton(),
1012            namespace: NamespaceId::singleton(),
1013            replicas: 1,
1014            command: None,
1015            entrypoint: None,
1016            workdir: None,
1017            user: None,
1018            env: self
1019                .run
1020                .env
1021                .into_iter()
1022                .map(|(name, value)| EnvVar {
1023                    name,
1024                    value: EnvValue::Literal { value },
1025                })
1026                .collect(),
1027            secrets: vec![],
1028            volumes: self
1029                .run
1030                .mounts
1031                .into_iter()
1032                .map(|m| VolumeMount {
1033                    source: VolumeSource::Bind {
1034                        host_path: PathBuf::from(m.host),
1035                    },
1036                    target: m.container,
1037                    read_only: m.read_only,
1038                })
1039                .collect(),
1040            resources: ResourceLimits {
1041                memory_mb: 1024,
1042                cpu_millis: 1000,
1043                ephemeral_storage_mb: 1024,
1044            },
1045            depends_on: vec![],
1046            healthcheck: None,
1047            restart_policy: RestartPolicy::Always,
1048            archetype: Some(LifecycleArchetype::Server),
1049            stop_policy: StopPolicy {
1050                signal: 15,
1051                grace_period: Millis::from_secs(10),
1052            },
1053            expose: ExposeSpec {
1054                mesh: MeshExpose {
1055                    identity: MeshIdent(self.name),
1056                    ports,
1057                    allow_from: vec![],
1058                },
1059                public: None,
1060                operator: None,
1061            },
1062            labels: HashMap::new(),
1063            annotations: HashMap::new(),
1064        })
1065    }
1066}
1067
1068/// The `[build]` table of a container recipe.
1069#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1070#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1071pub struct ContainerBuildStep {
1072    /// Dockerfile path, relative to the component directory.
1073    #[serde(default = "default_dockerfile")]
1074    pub dockerfile: PathBuf,
1075
1076    /// Build context, relative to the workspace root. `None` → the component
1077    /// directory. Workspace crates set `"."` so their path-dependency sources
1078    /// resolve.
1079    #[serde(default)]
1080    #[ts(optional = nullable)]
1081    pub context: Option<PathBuf>,
1082
1083    /// Image tag to build and run. `None` → `yah-local/<name>:dev`.
1084    ///
1085    /// A **tag**, not an [`ImageRef`]: this names an image that does not exist
1086    /// yet, so there is no digest to pin it by.
1087    #[serde(default)]
1088    #[ts(optional = nullable)]
1089    pub image: Option<String>,
1090}
1091
1092fn default_dockerfile() -> PathBuf {
1093    PathBuf::from("Dockerfile")
1094}
1095
1096impl Default for ContainerBuildStep {
1097    fn default() -> Self {
1098        Self {
1099            dockerfile: default_dockerfile(),
1100            context: None,
1101            image: None,
1102        }
1103    }
1104}
1105
1106/// The `[run]` table of a container recipe.
1107#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, TS)]
1108#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1109pub struct ContainerRunConfig {
1110    /// Container port the process listens on.
1111    #[serde(default)]
1112    #[ts(optional = nullable)]
1113    pub port: Option<u16>,
1114
1115    /// Host port to publish it on. `None` → same as [`port`](Self::port).
1116    #[serde(default)]
1117    #[ts(optional = nullable)]
1118    pub host_port: Option<u16>,
1119
1120    /// Environment passed into the container.
1121    #[serde(default)]
1122    pub env: BTreeMap<String, String>,
1123
1124    /// Bind mounts from the workspace into the container.
1125    #[serde(default)]
1126    pub mounts: Vec<ContainerMount>,
1127}
1128
1129/// One `[[run.mounts]]` entry of a container recipe.
1130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1131#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1132pub struct ContainerMount {
1133    /// Host path. Relative paths resolve against the workspace root — the
1134    /// declaration lives in the repo, so it should read like a repo path and
1135    /// stay valid on whichever machine the operator runs it from.
1136    pub host: String,
1137
1138    /// Absolute path inside the container.
1139    pub container: PathBuf,
1140
1141    /// Default `true`. A workspace mount is config the service *reads*; a
1142    /// writable default would let a container mutate the operator's checkout
1143    /// as a side effect of running, so opting into that has to be explicit.
1144    #[serde(default = "default_true")]
1145    pub read_only: bool,
1146}
1147
1148fn default_true() -> bool {
1149    true
1150}
1151
1152/// `kind = "mesofact-static"` payload — static-site build colocated with the
1153/// frontend it deploys.
1154///
1155/// The two-role model (R256-F7): a build/publish step plus an optional
1156/// SSR/SPA runtime companion. The build step is always transient (runs once,
1157/// publishes, exits). The companion is long-lived and only present when the
1158/// app has dynamic/server-rendered pages; pure static sites leave it `None`.
1159#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1160#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1161pub struct MesofactStaticWorkload {
1162    /// Wire-format version. Always `V1` today.
1163    pub schema_version: SchemaVersion,
1164
1165    /// Build command + output directory.
1166    pub build: BuildConfig,
1167
1168    /// Path (relative to the manifest) of the routes module the
1169    /// `mesofact-static` reconciler reads to enumerate routes.
1170    pub routes: PathBuf,
1171
1172    /// Where the build command runs. Default: `HostSide` (mesofact-dev on the
1173    /// host). Set to `InContainer` for cloud/HA where no host watcher is
1174    /// present and CI-fidelity build environments are required.
1175    #[serde(default)]
1176    pub build_mode: BuildMode,
1177
1178    /// Optional SSR/SPA runtime companion container.
1179    ///
1180    /// `None` → pure static site; Caddy (or equivalent CDN) serves all
1181    /// requests directly from the object store. This is the common case for
1182    /// dev-yah today.
1183    ///
1184    /// `Some` → the workload spec describes a long-lived container that
1185    /// handles dynamic/SSR requests. Caddy routes static asset paths to
1186    /// the object store and all other paths to this container. The companion
1187    /// uses `RestartPolicy::Always`; the orchestrator (camp or yubaba)
1188    /// ensures it stays up alongside the Caddy edge.
1189    #[ts(optional = nullable)]
1190    pub ssr_runtime: Option<WorkloadSpec>,
1191
1192    /// Serve-time reference to a published W272 bundle (R599-F4).
1193    ///
1194    /// `Some` → the built app is deployed as a content-addressed bundle that
1195    /// kamaji materializes from the bundle store (R599-F1) and serves via its
1196    /// native backend, instead of (or in addition to) the build reconciler
1197    /// pushing `dist/` to the object-store/CDN. `None` → legacy
1198    /// build-and-publish-only workload — kamaji rejects that form as yubaba's
1199    /// `mesofact-static` reconciler's responsibility.
1200    ///
1201    /// No `skip_serializing_if`: like `ssr_runtime`, this field is always
1202    /// encoded so the postcard wire codec (non-self-describing, positional)
1203    /// round-trips — `skip_serializing_if` would omit the byte on serialize
1204    /// while decode still expects it. `#[serde(default)]` keeps every existing
1205    /// `mesofact-static` TOML/JSON that predates this field parsing to `None`.
1206    #[serde(default)]
1207    #[ts(optional = nullable)]
1208    pub serve_bundle: Option<MesofactServeBundle>,
1209
1210    /// Revalidate receiver for the almanac push model (R330-F12).
1211    ///
1212    /// `Some` → kamaji also forks `mesofact serve --revalidate <workload>`
1213    /// alongside the bundle's static serve (or in place of it when
1214    /// `serve_bundle` is `None`). The receiver is ephemeral-V8: each
1215    /// `POST /dawn` boots a V8 isolate, re-renders the route, republishes to
1216    /// the CDN, then drops the isolate. (`/revalidate` is still served as a
1217    /// transitional alias — yah R752-T10 renamed it so the render stage stops
1218    /// sharing a path with almanac's feed-refetch stage, `POST /freshen`.)
1219    ///
1220    /// Env vars are resolved at deploy time (R2 creds + mirror bearer) so
1221    /// the node never sees keystore slot names.
1222    #[serde(default)]
1223    #[ts(optional = nullable)]
1224    pub revalidate_receiver: Option<MesofactRevalidateReceiver>,
1225}
1226
1227/// Revalidate receiver config (R330-F12) — tells kamaji to fork a second
1228/// `mesofact serve --revalidate` process alongside the static bundle server.
1229///
1230/// The receiver is the almanac push endpoint: a lightweight resident axum
1231/// server mounting `POST /dawn` (plus the legacy `/revalidate` alias) that
1232/// boots V8 on each poke, re-renders the invalidated route, publishes to
1233/// R2/CDN, then drops the isolate.
1234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1235#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1236pub struct MesofactRevalidateReceiver {
1237    /// Routes the receiver accepts pokes for (allowlist).
1238    /// Empty vec → all routes in the workload's manifest are revalidatable.
1239    #[serde(default)]
1240    pub routes: Vec<String>,
1241
1242    /// Path to `mesofact.config.toml` carrying the `[publish]` block
1243    /// (bucket / zone / env-named credentials). Relative to the workload
1244    /// directory. Default: `"mesofact.config.toml"`.
1245    #[serde(default = "default_publish_config_path")]
1246    pub publish_config: String,
1247
1248    /// Env var name holding the bearer secret for this tenant, resolved
1249    /// at deploy time and set as `MESOFACT_MIRROR_KEY` on the receiver
1250    /// process. `None` → open receiver (no bearer check).
1251    #[ts(optional = nullable)]
1252    pub mirror_key_env: Option<String>,
1253
1254    /// Environment variables set on the revalidate process by kamaji.
1255    /// Keys are the canonical env var names (`MESOFACT_S3_ACCESS_KEY_ID`,
1256    /// `MESOFACT_S3_SECRET_ACCESS_KEY`, `CLOUDFLARE_API_TOKEN`,
1257    /// `MESOFACT_MIRROR_KEY`). Values are resolved from the keystore at
1258    /// deploy time — the node never sees slot names.
1259    #[serde(default)]
1260    pub env: std::collections::BTreeMap<String, String>,
1261
1262    /// Feed-fetch tier (R330-F31) — the almanac feeds whose artifacts must be
1263    /// refreshed **on the node** for a poke to have anything new to render.
1264    ///
1265    /// Empty → no fetcher; the receiver re-renders whatever data the bundle was
1266    /// built with (correct for a site whose data only changes at build time,
1267    /// silently stale for one whose data is a live feed). Non-empty → kamaji
1268    /// forks a third resident process, the `almanac-feed` fetcher, next to the
1269    /// receiver — resolved from the bundle's `bins/<triple>/almanac-feed` when
1270    /// it carries one, else from [`feed_runtime`](Self::feed_runtime).
1271    #[serde(default)]
1272    pub feeds: Vec<AlmanacFeed>,
1273
1274    /// Runtime ref the `almanac-feed` fetcher resolves from the node's shared
1275    /// runtime-asset cache when the bundle carries no `bins/` (R746-T3), e.g.
1276    /// `"almanac-feed/0.8.22"`.
1277    ///
1278    /// This is what lets a **vanilla** bundle have a feed tier at all. A
1279    /// self-contained bundle stages the fetcher into `bins/` and stays closed
1280    /// over it; a vanilla bundle carries no binaries by construction, so the
1281    /// fetcher has to be a node-level asset for the same reason `serve` is —
1282    /// otherwise a templates-only sync would still need a cross-built musl
1283    /// binary sitting on the syncing machine's disk.
1284    ///
1285    /// `None` with `feeds` non-empty and no sidecar in the bundle is a deploy
1286    /// failure, named at the node. It is not a silent skip: "the site serves
1287    /// but its data is frozen" is the exact state R330-F31 exists to make
1288    /// observable.
1289    #[serde(default)]
1290    #[ts(optional = nullable)]
1291    pub feed_runtime: Option<String>,
1292
1293    /// Seconds between feed-fetch ticks. Ignored when `feeds` is empty.
1294    ///
1295    /// This is the site's freshness bound: a release lands, and the next tick
1296    /// refreshes + pokes. `FeedRunner`'s change-suppression means an idle tick
1297    /// costs one conditional fetch, so a short interval is affordable.
1298    #[serde(default = "default_feed_interval_secs")]
1299    pub feed_interval_secs: u64,
1300
1301    /// Workspace-relative path of the component whose build produced this
1302    /// bundle, e.g. `app/yah/web/marketing` (R330-F31).
1303    ///
1304    /// Reconciles two roots for one file: a feed declares `emit.artifact`
1305    /// workspace-relative (that is where it is authored), while the route
1306    /// declares the same file project-relative (that is what the bundle
1307    /// carries). The fetcher strips this prefix to get from one to the other.
1308    /// `None` → the two already coincide.
1309    #[serde(default)]
1310    #[ts(optional = nullable)]
1311    pub feed_project_prefix: Option<String>,
1312}
1313
1314/// One almanac feed handed to the on-node fetcher (R330-F31).
1315///
1316/// The definition travels **by value**, not by path: the node has no copy of
1317/// the camp's `.yah/almanac/` tree, and staging one into the content-addressed
1318/// bundle would put a mutable-by-nature config inside an immutable artifact.
1319/// The fetcher parses `config_toml` with the same `FeedConfig` type that reads
1320/// the file at the source, so there is one schema and no drift.
1321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1322#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1323pub struct AlmanacFeed {
1324    /// Feed name — the `.yah/almanac/<name>.toml` stem. Logs/diagnostics only;
1325    /// `config_toml` is authoritative.
1326    pub name: String,
1327
1328    /// Verbatim contents of the feed definition TOML.
1329    pub config_toml: String,
1330}
1331
1332fn default_publish_config_path() -> String {
1333    "mesofact.config.toml".to_string()
1334}
1335
1336/// Five minutes: fast enough that a release is live on yah.dev before anyone
1337/// goes looking, slow enough to be invisible against a source API's rate limit.
1338fn default_feed_interval_secs() -> u64 {
1339    300
1340}
1341
1342/// Serve-time reference to a published W272 bundle (R599-F4) — the
1343/// `{bundle_digest, runtime, lifecycle}` triple a `mesofact-static` workload
1344/// carries when kamaji, not the build reconciler, serves it.
1345#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1346#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1347pub struct MesofactServeBundle {
1348    /// BLAKE3 digest of the published bundle manifest — the content-address
1349    /// kamaji materializes from the bundle store (`yah_mesofact_bundle`,
1350    /// R599-F1). Same 64-hex shape the bundle crate's `BundleHash` validates.
1351    pub digest: BlakeHash,
1352
1353    /// Runtime that serves the bundle: `"self"` (bundle ships its own
1354    /// `bins/<triple>/serve`) or `"mesofact/<version>"` (resolve the stock
1355    /// serve runtime asset from the node cache). Wire-mirrors
1356    /// `yah_mesofact_bundle::BundleRuntime`; kept as a plain `String` here so
1357    /// workload-spec stays free of the bundle crate and its non-TS/schema
1358    /// newtypes.
1359    pub runtime: String,
1360
1361    /// How kamaji supervises the served bundle. Default: keep-alive.
1362    #[serde(default)]
1363    pub lifecycle: BundleLifecycle,
1364
1365    /// Port the served bundle listens on (R599-F12). This is the bundle-tier
1366    /// analogue of a container's `expose.mesh.ports`: the *declared* serving
1367    /// port, which a proxy pairs with the workload's mesh IP to get a dialable
1368    /// address.
1369    ///
1370    /// `None` → kamaji falls back to its node-wide default
1371    /// (`KAMAJI_BUNDLE_PORT` / `DEFAULT_BUNDLE_PORT` = 8080), which is the
1372    /// pre-R599-F12 behaviour and is only correct while a node hosts one
1373    /// bundle. Declaring a port per workload is what lets one node host
1374    /// several — that singleton default is the thing it removes.
1375    ///
1376    /// No `skip_serializing_if` — see `serve_bundle`'s note: the postcard wire
1377    /// codec is positional, so an omitted byte shifts every later field.
1378    #[serde(default)]
1379    #[ts(optional = nullable)]
1380    pub port: Option<u16>,
1381
1382    /// Environment the serve process is forked with (R556-T12) — already
1383    /// **resolved** values, `NAME → value`.
1384    ///
1385    /// This is what makes an SSR route that reads a private source deployable
1386    /// at all: `mesofact serve` resolves a source's credentials from its own
1387    /// process environment at request time, and before this field the static /
1388    /// SSR serve process was forked with `env: vec![]` while only the
1389    /// `revalidate_receiver` sub-slot carried any. A declared-authed SSR site
1390    /// therefore deployed clean and failed *per request* on the node.
1391    ///
1392    /// Resolution happens deploy-side, exactly like
1393    /// [`MesofactRevalidateReceiver::env`]: the mirror declares source URIs
1394    /// (`vault:<slot>` / `env:<VAR>`), `yah cloud apply` resolves them against
1395    /// the operator's vault, and the node receives values. Keystore slot names
1396    /// never cross the wire.
1397    ///
1398    /// Appended **after** `port` — see `port`'s note: the postcard wire codec
1399    /// is positional, so a new field goes last and never carries
1400    /// `skip_serializing_if`.
1401    #[serde(default)]
1402    pub env: BTreeMap<String, String>,
1403}
1404
1405/// Lifecycle mode for a served bundle (W272 §3).
1406#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1407#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1408#[serde(rename_all = "snake_case")]
1409pub enum BundleLifecycle {
1410    /// Fork at deploy, keep resident, restart per policy — today's server
1411    /// archetype. Memory is resident for the workload's lifetime.
1412    KeepAlive,
1413
1414    /// Kamaji owns the listen socket, forks the runtime on the first connection
1415    /// (fd-passing), and reaps it after `idle_ttl` with zero connections — the
1416    /// "serverless" tier (zero memory when idle). The JIT fork/reap mechanics
1417    /// land in R599-F6; this variant only declares the intent + budget.
1418    OnDemand {
1419        /// Idle time with no live connections before kamaji reaps the process.
1420        idle_ttl: Millis,
1421    },
1422}
1423
1424impl Default for BundleLifecycle {
1425    /// Keep-alive — the resident server archetype — matches the current
1426    /// deploy-and-supervise default.
1427    fn default() -> Self {
1428        BundleLifecycle::KeepAlive
1429    }
1430}
1431
1432/// Build step that produces the static artifact published by a
1433/// `mesofact-static` workload.
1434///
1435/// **`deny_unknown_fields` is load-bearing (R658-B1).** TOML scopes every key
1436/// written after a table header into that table, so a manifest that puts a
1437/// top-level `MesofactStaticWorkload` field — `routes` was the one that
1438/// actually happened — below `[build]` silently produces `build.routes`
1439/// instead. Without this attribute serde discards the stray key, the
1440/// top-level field falls back to its default (or fails with a `missing field`
1441/// error pointing at the wrong place), and the manifest deploys with a
1442/// declaration nobody honours. Every real `workload.toml` in the camp and the
1443/// CLI's own `yah cloud site init` scaffold carried exactly that shape for
1444/// months without a single reader noticing.
1445///
1446/// The cost is forward-compat: a manifest carrying a `[build]` key this binary
1447/// doesn't know is a hard parse error, not an ignored key. That is deliberate.
1448/// A build config is a small, slow-moving, load-bearing table — a key that
1449/// silently does nothing is worse here than one that refuses to load, because
1450/// the failure surfaces as a wrong artifact rather than an error.
1451///
1452/// Note `deny_unknown_fields` is inert for the postcard kamaji wire, which is
1453/// non-self-describing and positional — this only constrains TOML/JSON.
1454#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1455#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1456#[serde(deny_unknown_fields)]
1457pub struct BuildConfig {
1458    /// Shell command run from the manifest's directory, e.g. `"bun run build"`.
1459    ///
1460    /// **Absent means "this project has no external bundler step" (R838-B1)**,
1461    /// not "run nothing by accident". `mesofact new`'s scaffold deliberately
1462    /// omits it — the in-process pipeline (`mesofact-dev` / `mesofact-build`)
1463    /// produces `out_dir` with no third binary, no package manager and no Node
1464    /// — so requiring it here made every scaffolded project's manifest fail to
1465    /// load through this envelope. Setting it opts back out to a shell command,
1466    /// which is what a project with its own bundler wants.
1467    ///
1468    /// Consumers were already written for this: `read_workload_build`
1469    /// (app/yah/cli/src/cloud.rs) has always typed it `Option<String>` and
1470    /// `yah cloud bundle build` only needs it under `--run-build`; the bundle
1471    /// sync arm refuses `None` by name. `MesofactStaticReconciler::
1472    /// rebuild_static` skips the build step for `None` — the same thing it
1473    /// already did for a workload with no `workload.toml` at all.
1474    ///
1475    /// WIRE NOTE: this is `Option<String>` on the postcard kamaji wire, so it
1476    /// costs a leading `0x00`/`0x01` tag byte that the bare `String` did not
1477    /// have. A pre-R838 node decoding a new frame fails loudly (the string's
1478    /// length byte is not a valid `Option` tag) rather than silently reading a
1479    /// shifted field — which is why this is `Option` and not a `#[serde(default)]`
1480    /// empty `String` sentinel. Not a `cluster_epochs` surface: those hash the
1481    /// raft modules and the openraft pin, not `workload_spec`.
1482    #[serde(default)]
1483    pub command: Option<String>,
1484
1485    /// Output directory (relative to the manifest) the reconciler uploads.
1486    pub out_dir: PathBuf,
1487
1488    /// Data-only re-render command (W225 §3 "revalidate"), run from the
1489    /// manifest's directory against the **already-built** `out_dir` — no
1490    /// bundler. `{route}` is substituted with the invalidated route pattern,
1491    /// e.g. `"../../../../scripts/mesofact-build.sh render . --route {route}
1492    /// --all"` (R746-F9 — resolves a prebuilt binary rather than shelling to
1493    /// cargo, which cannot even find the package from a site's own dir).
1494    /// Absent → a revalidate dispatch republishes `out_dir` as-is.
1495    #[serde(default)]
1496    pub render_command: Option<String>,
1497}
1498
1499// ── BuildMode ─────────────────────────────────────────────────────────────────
1500
1501/// Where the build command runs for a `mesofact-static` workload.
1502///
1503/// The two-role split encodes the F7 design decision: build/publish is a
1504/// **transient job** (runs once, exits, GC'd); SSR/SPA serving is a separate
1505/// **long-lived companion container** (optional, only for dynamic pages). A
1506/// single merged "mesofact container" is the trap — in cloud, CI builds the
1507/// artifact, R2+CDN serve it, and a distinct worker handles any SSR.
1508///
1509/// Default: `HostSide` — mesofact-dev runs the build on the host and publishes
1510/// to the tier's object store. No container overhead; compatible with dev and
1511/// sim tiers.
1512#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
1513#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1514#[serde(rename_all = "snake_case")]
1515pub enum BuildMode {
1516    /// Build command runs on the host (mesofact-dev watcher). The watcher
1517    /// publishes the output to the tier's object store (DistPointer for dev,
1518    /// MinIO for sim). Compatible with all tiers; zero container overhead.
1519    #[default]
1520    HostSide,
1521
1522    /// Build runs inside a transient container matching the CI image. Higher
1523    /// fidelity (environment matches CI exactly); costs image pull +
1524    /// container cold-start. Required for cloud/HA where no mesofact-dev
1525    /// watcher is running on the host.
1526    InContainer {
1527        /// Container image that runs the build (e.g. `"ghcr.io/org/app-build:v1.2"`).
1528        /// Must have the build toolchain installed. The container is started with
1529        /// the workspace root bind-mounted, runs `build.command`, uploads
1530        /// `build.out_dir` to the object store, then exits.
1531        image: ImageRef,
1532    },
1533}
1534
1535// ── AlmanacManifest ───────────────────────────────────────────────────────────
1536
1537/// An observable endpoint the almanac scheduler probes to check readiness.
1538///
1539/// Used for both inputs (checked before the run) and outputs (verified after
1540/// a successful run to confirm the job produced something reachable).
1541/// The probe is intentionally lightweight — no S3 SigV4, no xlb-net discovery
1542/// required; a simple TCP connect or HTTP GET is enough for the dev/sim tier.
1543#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1544#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1545#[serde(rename_all = "snake_case")]
1546pub enum AlmanacTarget {
1547    /// Issue an HTTP GET to `url`; ready when the server responds with
1548    /// `expect_status` (default: any 2xx).
1549    Http {
1550        url: String,
1551        #[ts(optional = nullable)]
1552        expect_status: Option<u16>,
1553    },
1554
1555    /// Establish a TCP connection to `host:port`; ready when the connect
1556    /// succeeds. Used for non-HTTP services (e.g. MinIO API on port 9000)
1557    /// and as a lighter probe when an HTTP endpoint isn't stable yet.
1558    Tcp { host: String, port: u16 },
1559}
1560
1561/// What the almanac scheduler does when a precondition check fails.
1562///
1563/// The F9 design decision: `WaitWithTimeout` is the default. Fail-fast is
1564/// too brittle for the sim tier (containers may still be cold-starting);
1565/// requeue-with-no-ceiling can block the scheduler indefinitely. The
1566/// recommended timeout for sim is the container spinup budget (~5 s cold,
1567/// ~1 s warm): set `timeout` to a few seconds, then let the retry cadence
1568/// handle transient glitches.
1569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1570#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1571#[serde(rename_all = "snake_case")]
1572pub enum NotReadyPolicy {
1573    /// Wait up to `timeout` for all preconditions to pass before aborting
1574    /// the run. The run is skipped (not rescheduled); the next cadence tick
1575    /// will retry. Suitable when targets occasionally lag at startup.
1576    WaitWithTimeout {
1577        /// How long to wait for each precondition to become reachable. The
1578        /// scheduler polls with a short sleep between attempts.
1579        timeout: Millis,
1580    },
1581
1582    /// Abort immediately if any precondition check fails. Suitable for
1583    /// integration-test harnesses where a missing dependency is always a
1584    /// hard error.
1585    FailFast,
1586
1587    /// Requeue with exponential backoff up to `max_attempts` times. After
1588    /// exhaustion the run is marked failed. Suitable for cloud/HA where
1589    /// transient dependency outages are expected.
1590    Requeue {
1591        /// Maximum number of requeue attempts before the run is marked failed.
1592        max_attempts: u32,
1593        /// Initial backoff between attempts, in milliseconds.
1594        backoff: Millis,
1595    },
1596}
1597
1598impl Default for NotReadyPolicy {
1599    /// Default is `WaitWithTimeout { timeout: 5 seconds }` — matches the
1600    /// container spinup budget for the sim tier (few-second cold, sub-second warm).
1601    fn default() -> Self {
1602        Self::WaitWithTimeout { timeout: Millis::from_secs(5) }
1603    }
1604}
1605
1606/// When the almanac scheduler triggers a run.
1607#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1608#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1609#[serde(rename_all = "snake_case")]
1610pub enum Cadence {
1611    /// Run once at first opportunity, then never again.
1612    Once,
1613
1614    /// Run repeatedly with a fixed interval between the end of one run and
1615    /// the start of the next. Equivalent to `sleep N && run` in a loop.
1616    Every {
1617        /// Minimum time between consecutive run completions.
1618        interval: Millis,
1619    },
1620
1621    /// Run on a UTC cron schedule (standard 5-field expression, e.g.
1622    /// `"0 */6 * * *"` for every 6 hours). The scheduler evaluates the
1623    /// expression relative to UTC midnight.
1624    Cron { expression: String },
1625}
1626
1627/// `kind = "almanac"` manifest — a declared data-pipeline job.
1628///
1629/// An almanac job is the generalisation of the OpenRouter refresher
1630/// (`spawn_almanac_refresher`): it declares its I/O contract explicitly so
1631/// the orchestrator can enforce preconditions before each run and verify
1632/// outputs afterward. The degenerate case (no inputs, no app target, cron
1633/// schedule) is exactly the OpenRouter JSON-cache refresher.
1634///
1635/// Lifecycle:
1636/// 1. Cadence tick fires.
1637/// 2. Scheduler probes every `inputs` target. If any fail → apply
1638///    `not_ready_policy`.
1639/// 3. Command runs (`sh -c command` from the workload directory).
1640/// 4. Scheduler probes every `outputs` target. Failure → mark run as
1641///    failed but do not retry.
1642/// 5. Any workloads listed in `invalidates` receive a cache-bust signal
1643///    (implementation detail of the orchestrator; in camp this is a
1644///    rebuild trigger on the mesofact-dev watcher).
1645#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1646#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1647pub struct AlmanacManifest {
1648    /// Wire-format version. Always `V1` today.
1649    pub schema_version: SchemaVersion,
1650
1651    /// Shell command executed via `sh -c` from the workload directory.
1652    pub command: String,
1653
1654    /// When to run.
1655    pub cadence: Cadence,
1656
1657    /// Input targets that must be reachable before the command runs.
1658    /// Empty list → no precondition checks (degenerate case).
1659    #[serde(default)]
1660    pub inputs: Vec<AlmanacTarget>,
1661
1662    /// Output targets verified after a successful run.
1663    /// Empty list → no post-run verification.
1664    #[serde(default)]
1665    pub outputs: Vec<AlmanacTarget>,
1666
1667    /// What to do when a precondition check fails.
1668    /// Default: `WaitWithTimeout { timeout: 5000ms }`.
1669    #[serde(default)]
1670    pub not_ready_policy: NotReadyPolicy,
1671
1672    /// Mesh identities of workloads to notify after a successful run.
1673    /// The orchestrator sends a cache-bust signal to each entry so
1674    /// downstream consumers can reload their data (e.g. mesofact-dev
1675    /// triggers a rebuild when the OpenRouter cache refreshes).
1676    /// Empty list → no downstream invalidation.
1677    #[serde(default)]
1678    pub invalidates: Vec<MeshIdent>,
1679}
1680
1681// ── StaticAssetWorkload ───────────────────────────────────────────────────────
1682
1683/// BLAKE3 content hash expressed as exactly 64 ASCII hex digits.
1684///
1685/// This is the content-address key for every file in the static-asset catalog.
1686/// Deserialization rejects values that do not conform — 64 hex chars, case
1687/// insensitive. Mismatch between the recorded hash and the source file halts
1688/// the upload step in the reconciler.
1689#[derive(Debug, Clone, PartialEq, Eq, Serialize, TS)]
1690#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1691#[ts(type = "string")]
1692pub struct BlakeHash(pub String);
1693
1694impl<'de> Deserialize<'de> for BlakeHash {
1695    fn deserialize<D>(de: D) -> Result<Self, D::Error>
1696    where
1697        D: serde::Deserializer<'de>,
1698    {
1699        let s = String::deserialize(de)?;
1700        if s.len() != 64 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
1701            return Err(serde::de::Error::custom(format!(
1702                "blake3 hash must be exactly 64 hex digits, got {:?}",
1703                s
1704            )));
1705        }
1706        Ok(BlakeHash(s))
1707    }
1708}
1709
1710// ── License & FetchSource (W164) ──────────────────────────────────────────────
1711
1712/// Closed-set, parse-time-enforced license tag. Mirrors the workspace
1713/// permissive-license rule (MIT / Apache-2.0 / BSD-2/3-Clause / ISC). Adding a
1714/// variant is an explicit schema change — non-permissive strings
1715/// (`"GPL-3.0"`, `"AGPL"`, etc.) fail at serde-deserialize before any shape
1716/// validator runs.
1717///
1718/// Shared between `asset.derive.fetch.license` (W164, required) and a future
1719/// `almanac::ReleaseSource.license` migration (R438-F10, optional).
1720#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
1721#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1722#[serde(rename_all = "kebab-case")]
1723pub enum License {
1724    Mit,
1725    Apache2,
1726    Bsd2Clause,
1727    Bsd3Clause,
1728    Isc,
1729}
1730
1731/// Shared fetch primitive — usable by `asset.derive` today, and by Almanac's
1732/// `ReleaseSource` after a follow-up migration (R438-F10). Defined once in
1733/// workload-spec so both consumers reject the same set of non-permissive
1734/// licenses.
1735///
1736/// The `blake3` hash pins the upstream bytes; mismatch at fetch time is a hard
1737/// error in the reconciler. The `license` field is **required** here — every
1738/// derived asset must declare its upstream license. If/when Almanac adopts
1739/// `FetchSource`, the Almanac side may wrap this in a struct with
1740/// `Option<License>` since release manifests have no distribution license per
1741/// se.
1742#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1743#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1744pub struct FetchSource {
1745    /// Upstream URL fetched verbatim. Reconciler retry policy is configured
1746    /// elsewhere (R438-F11); the URL itself is opaque to workload-spec.
1747    pub url: String,
1748
1749    /// Expected BLAKE3 hash of the fetched bytes (64 hex characters). The
1750    /// reconciler verifies this after download and aborts on mismatch.
1751    pub blake3: BlakeHash,
1752
1753    /// Upstream license. Closed-set, parse-time enforced.
1754    pub license: License,
1755}
1756
1757/// Optional transform applied after a [`FetchSource`] download, lowering to a
1758/// `ForgeCommand::Subprocess` via the recipe loader (R438-T4). The transform's
1759/// output is content-addressed by the entry's `blake3` (the recipe runs only
1760/// when the cache misses).
1761#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1762#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1763pub struct TransformSpec {
1764    /// Named recipe under `.yah/qed/transforms/<recipe>.toml`. Loader rejects
1765    /// missing recipes at materialize time.
1766    pub recipe: String,
1767
1768    /// `{{key}}` substitutions passed to the recipe argv at element
1769    /// granularity (no shell, no string concat). Empty when the recipe is
1770    /// fully parameterless.
1771    #[serde(default)]
1772    pub params: BTreeMap<String, String>,
1773}
1774
1775/// W212/R518: the committed derivation lock — the in-tree action-cache
1776/// receipt. `input_hash` is the input-addressed derivation key computed over
1777/// the complete declared input set (fetched-input pin ⊕ recipe-file bytes ⊕
1778/// invocation params ⊕ schema version); `output_blake3` is what those inputs
1779/// produced (== the entry's `blake3`). The reconciler skips the entire build
1780/// (no fetch, no transform, no PUT) when the lock matches the inputs recomputed
1781/// from the current pins and the bucket already holds the output — the
1782/// Nix-substituter / Bazel-remote-cache behaviour. Written by the R510 bind
1783/// path from the reconciler's `discovered_input_hash:<filename>` output; the
1784/// `git diff` on this block is the receipt that the derivation rolled.
1785#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1786#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1787pub struct DeriveLock {
1788    /// Input-addressed derivation key (BLAKE3 hex). A change to any declared
1789    /// input flips this, so a stale lock never produces a false skip.
1790    pub input_hash: String,
1791    /// Output the locked inputs produced (BLAKE3 hex; equals the entry's
1792    /// `blake3`). Carried so the lock is a self-contained action-cache entry.
1793    pub output_blake3: String,
1794}
1795
1796/// Provenance chain for a derived asset: required `fetch` step, optional
1797/// `transform` step. Materialized bytes replace `AssetEntry.source` for the
1798/// rest of the static-asset reconcile loop.
1799#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1800#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1801pub struct AssetDerive {
1802    /// Upstream fetch — URL + content-pin + license.
1803    pub fetch: FetchSource,
1804
1805    /// Post-fetch transform. `None` → the fetched bytes ARE the asset
1806    /// (entry `blake3` must match fetch `blake3`).
1807    #[serde(default)]
1808    #[ts(optional = nullable)]
1809    pub transform: Option<TransformSpec>,
1810
1811    /// W212/R518: committed derivation lock (input-addressed action-cache
1812    /// receipt). Absent until the first successful build writes it via the
1813    /// bind path. When present and current, enables the substituter-style
1814    /// build skip.
1815    #[serde(default)]
1816    #[ts(optional = nullable)]
1817    pub lock: Option<DeriveLock>,
1818}
1819
1820/// A single file entry in the static-asset catalog.
1821///
1822/// One `[[asset]]` row per bucket object. Multiple rows for different variants
1823/// (e.g. q5 and q4 whisper models) are fine — each declares its own filename
1824/// and hash. The reconciler treats the catalog as exhaustive and append-only:
1825/// new rows trigger a PUT; removed rows surface as drift (never a DELETE).
1826///
1827/// **Source-vs-derive XOR.** Exactly one of `source` or `derive` must be set.
1828/// Legacy local-bytes assets keep `source = "..."`; W164 derived assets set
1829/// `[asset.derive]` instead. [`validate::shape_static_asset`] enforces the
1830/// XOR; both-set and neither-set are hard `ShapeError::Field`.
1831#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1832#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1833pub struct AssetEntry {
1834    /// Destination path within the bucket, e.g.
1835    /// `"whisper/distil-large-v3-q5_1.bin"`. Must be unique in the catalog.
1836    /// Used as the S3 object key by the reconciler.
1837    pub filename: String,
1838
1839    /// Path to a local source file, relative to the `workload.toml` directory.
1840    /// Mutually exclusive with `derive`.
1841    #[serde(default)]
1842    #[ts(optional = nullable)]
1843    pub source: Option<PathBuf>,
1844
1845    /// Declared fetch (+ optional transform) provenance chain. The reconciler
1846    /// materializes the bytes into a content-addressed cache; the cache path
1847    /// then replaces `source` for the rest of the upload pipeline. Mutually
1848    /// exclusive with `source`.
1849    #[serde(default)]
1850    #[ts(optional = nullable)]
1851    pub derive: Option<AssetDerive>,
1852
1853    /// Expected BLAKE3 hash of the *final* asset bytes (64 hex characters).
1854    /// For `source` mode, this is hashed before upload. For `derive` mode,
1855    /// it's the post-transform (or post-fetch when no transform) output.
1856    /// Mismatch aborts the upload.
1857    pub blake3: BlakeHash,
1858}
1859
1860/// `kind = "static-asset"` payload — content-addressed bucket catalog.
1861///
1862/// The reconciler makes the bucket match the `[[asset]]` list exactly
1863/// (append-only: new rows → PUT; removed rows → drift report, not DELETE).
1864/// Rollback is pointer-flip via `mirror.toml [asset_aliases]` — bytes never
1865/// move during rollback.
1866///
1867/// **Closed-catalog invariant**: every value in `[aliases]` must be a
1868/// `filename` that exists in `[[asset]]`. Enforced by
1869/// [`validate::shape_static_asset`]. Mirror overrides (`[asset_aliases]` in
1870/// `mirror.toml`) are bound by the same rule — the alias graph can only
1871/// resolve to filenames already in the catalog.
1872#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1873#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1874pub struct StaticAssetWorkload {
1875    /// Wire-format version. Always `V1` today.
1876    pub schema_version: SchemaVersion,
1877
1878    /// Exhaustive catalog of files this component manages in the bucket.
1879    ///
1880    /// Named `asset` on disk (TOML `[[asset]]` array-of-tables) to follow TOML
1881    /// convention; accessed as `.assets` in Rust code.
1882    #[serde(rename = "asset", default)]
1883    pub assets: Vec<AssetEntry>,
1884
1885    /// Canonical logical-name → filename mappings for this component.
1886    ///
1887    /// Values must be filenames present in `assets` — validated by
1888    /// [`validate::shape_static_asset`]. Mirror files may override individual
1889    /// entries via `[asset_aliases]` but may never reference filenames absent
1890    /// from this catalog.
1891    #[serde(default)]
1892    pub aliases: BTreeMap<String, String>,
1893}
1894
1895// ── Lifecycle archetype (R572-F1 / W244) ───────────────────────────────────────
1896
1897/// Explicit lifecycle archetype for a `kind = "container"` workload (W244).
1898///
1899/// The question that actually matters to a scheduler: *"can I kill this and
1900/// recreate it somewhere else?"* Before this field existed, the answer was
1901/// inferred per-spec from `volumes.is_empty()` + `restart_policy` — fragile
1902/// absence-as-policy, the same trap W243 calls out on the node-taint side.
1903/// This type makes the answer structural instead of guessed.
1904///
1905/// This ticket (R572-F1) adds the discriminator only. The reconciler does not
1906/// yet branch on it (R572-F4) and neither does the scheduler (R572-F5).
1907#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
1908#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1909#[serde(rename_all = "kebab-case")]
1910pub enum LifecycleArchetype {
1911    /// k8s analogue: Deployment. Stateless and fungible — the scheduler may
1912    /// move it, scale it to N replicas, or restart it on a different node
1913    /// with zero consequence. Drainable.
1914    Server,
1915
1916    /// k8s analogue: StatefulSet. Stable identity + a volume that must
1917    /// follow it; at most one live instance. Not drainable — the reconciler
1918    /// must not schedule it onto a different node. Example: a postgres peer,
1919    /// headscale (W267/R591).
1920    Appliance,
1921
1922    /// k8s analogue: Job. Runs to completion with declared inputs/outputs,
1923    /// then is gone — no steady-state identity. `almanac` is the first
1924    /// job-family member; forge runs (`WorkloadSpec::for_forge`, used by QED)
1925    /// are the `container`-kind instance of this archetype.
1926    Job,
1927}
1928
1929impl LifecycleArchetype {
1930    /// Every variant, in declaration order. Exists so a consumer can enumerate
1931    /// the archetypes without hand-maintaining a parallel list — the taint
1932    /// vocabulary in `cloud::config::taint_effect` is built from this, so
1933    /// adding a fourth archetype extends the set of live repel keys for free.
1934    pub const ALL: [LifecycleArchetype; 3] = [Self::Server, Self::Appliance, Self::Job];
1935
1936    /// The repel-taint key for this archetype (R572-F5). A node carrying the
1937    /// taint `"no-<key>"` **absolutely** rejects workloads of this class.
1938    ///
1939    /// Examples: `Server` → `"server"` (repelled by `"no-server"`);
1940    /// `Appliance` → `"appliance"` (repelled by `"no-appliance"`).
1941    ///
1942    /// W305/R742-T4: there is no toleration. Earlier prose here and in
1943    /// `cloud::config` called this "repel-unless-tolerate"; the `unless` was
1944    /// never built, and reading it as a preference is what made `no-appliance`
1945    /// on the dev Pis look advisory when it was an unconditional block.
1946    pub fn taint_key(&self) -> &'static str {
1947        match self {
1948            Self::Server => "server",
1949            Self::Appliance => "appliance",
1950            Self::Job => "job",
1951        }
1952    }
1953
1954    /// The pre-R572 inference this field replaces, kept only to give
1955    /// `WorkloadSpec::effective_archetype` a behavior-preserving fallback for
1956    /// specs written before this field existed (`archetype: None`).
1957    ///
1958    /// A volume that must follow the workload is the strongest signal of
1959    /// durable state → [`Self::Appliance`]. Absent that, `RestartPolicy::Never`
1960    /// is the existing forge/run-once convention (see
1961    /// [`RestartPolicy::Never`]'s doc comment) → [`Self::Job`]. Everything
1962    /// else defaults to the common case, [`Self::Server`].
1963    fn infer(volumes: &[VolumeMount], restart_policy: &RestartPolicy) -> Self {
1964        if !volumes.is_empty() {
1965            LifecycleArchetype::Appliance
1966        } else if matches!(restart_policy, RestartPolicy::Never) {
1967            LifecycleArchetype::Job
1968        } else {
1969            LifecycleArchetype::Server
1970        }
1971    }
1972}
1973
1974// ── WorkloadSpec ──────────────────────────────────────────────────────────────
1975
1976/// Complete typed description of a containerd workload handed to yubaba over
1977/// RPC. This is also the payload of the `kind = "container"` variant of
1978/// [`Workload`] on disk.
1979///
1980/// Yubaba never accepts compose YAML on its RPC surface — agents, the desktop,
1981/// and operator CLIs all hand yubaba `WorkloadSpec` values. See the arch doc
1982/// for the validation layers and evolution rules.
1983#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1984#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1985pub struct WorkloadSpec {
1986    /// Wire-format version; always `V1` today. Present at the top level so
1987    /// rolling clusters can detect and migrate across schema generations.
1988    pub schema_version: SchemaVersion,
1989
1990    /// DNS-friendly workload name, e.g. `"noisetable-api"`. Regex:
1991    /// `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`, length ≤ 63.
1992    pub name: String,
1993
1994    /// Container image to pull.
1995    pub image: ImageRef,
1996
1997    /// Tier tag controlling admission control and mesh filtering.
1998    pub tier: TierTag,
1999
2000    /// Tenant **isolation** axis (W206). Separates operators' workloads at the
2001    /// network / DB / mesh-identity level. Defaults to [`TenantId::singleton`]
2002    /// for specs that predate the axis, so single-tenant clusters keep every
2003    /// isolation primitive a no-op. Orthogonal to [`Self::tier`] (class) and
2004    /// [`Self::namespace`] (routing).
2005    #[serde(default = "TenantId::singleton")]
2006    pub tenant: TenantId,
2007
2008    /// Namespace **routing/naming** axis (W206). A pure naming key — never
2009    /// affects isolation; disambiguates DNS names and selects config root /
2010    /// provider zone within a tenant. Defaults to [`NamespaceId::singleton`].
2011    #[serde(default = "NamespaceId::singleton")]
2012    pub namespace: NamespaceId,
2013
2014    /// Target replica count. `0` registers the workload without deploying it.
2015    /// Range: 0–100 (cluster-wide cap; operator can raise it).
2016    pub replicas: u32,
2017
2018    /// Override the image's `CMD`. `None` leaves the image default.
2019    #[ts(optional = nullable)]
2020    pub command: Option<Vec<String>>,
2021
2022    /// Override the image's `ENTRYPOINT`. `None` leaves the image default.
2023    #[ts(optional = nullable)]
2024    pub entrypoint: Option<Vec<String>>,
2025
2026    /// Working directory inside the container.
2027    #[ts(optional = nullable)]
2028    pub workdir: Option<PathBuf>,
2029
2030    /// User to run as, e.g. `"1000:1000"` or `"appuser"`.
2031    #[ts(optional = nullable)]
2032    pub user: Option<String>,
2033
2034    /// Environment variables. Values may be literals, secret refs, or
2035    /// mesh-address references resolved by yubaba at deploy time.
2036    #[serde(default)]
2037    pub env: Vec<EnvVar>,
2038
2039    /// Secret mounts. Values never appear in the spec JSON — only references.
2040    #[serde(default)]
2041    pub secrets: Vec<SecretMount>,
2042
2043    /// Volume mounts.
2044    #[serde(default)]
2045    pub volumes: Vec<VolumeMount>,
2046
2047    /// Hard resource caps enforced by containerd/cgroups.
2048    pub resources: ResourceLimits,
2049
2050    /// Mesh idents that must reach `Ready` before this workload starts.
2051    #[serde(default)]
2052    pub depends_on: Vec<MeshIdent>,
2053
2054    /// Container liveness/readiness probe.
2055    #[ts(optional = nullable)]
2056    pub healthcheck: Option<Healthcheck>,
2057
2058    /// What yubaba does when the container exits.
2059    pub restart_policy: RestartPolicy,
2060
2061    /// Explicit lifecycle archetype (R572-F1 / W244): `server`, `appliance`,
2062    /// or `job`. `None` means the spec predates this field (or the author
2063    /// didn't set it) — callers MUST NOT read this directly to decide
2064    /// drainability; use [`WorkloadSpec::effective_archetype`], which falls
2065    /// back to the pre-R572 `volumes`/`restart_policy` inference so no
2066    /// existing spec's effective meaning changes.
2067    ///
2068    /// Additive: this field did not exist before R572-F1. Reconciler (F4)
2069    /// and scheduler (F5) branching on the resolved archetype are separate,
2070    /// later tickets — this field alone changes no runtime behavior.
2071    #[serde(default)]
2072    #[ts(optional = nullable)]
2073    pub archetype: Option<LifecycleArchetype>,
2074
2075    /// Graceful shutdown configuration.
2076    pub stop_policy: StopPolicy,
2077
2078    /// Network exposure configuration — mesh, public, and operator channels
2079    /// are independent and can be set in any combination.
2080    pub expose: ExposeSpec,
2081
2082    /// OCI-style labels, passed through to the container. Opaque to yubaba.
2083    #[serde(default)]
2084    pub labels: HashMap<String, String>,
2085
2086    /// Yah-specific metadata, conventionally prefixed `yah.*`. Opaque to
2087    /// yubaba beyond `yah.forge=true` which suppresses the Never-restart guard.
2088    #[serde(default)]
2089    pub annotations: HashMap<String, String>,
2090}
2091
2092impl WorkloadSpec {
2093    /// Build a `WorkloadSpec` for a forge run.
2094    ///
2095    /// Sets the conventional forge fields in one place so callers cannot
2096    /// forget any of them:
2097    ///
2098    /// - `restart_policy = Never`
2099    /// - `archetype = Some(LifecycleArchetype::Job)` — a forge run is
2100    ///   exactly the `container`-kind instance of the job archetype (W244);
2101    ///   set explicitly rather than left to infer since this constructor
2102    ///   knows its own shape
2103    /// - `expose.public = None`, `expose.operator = None`
2104    /// - `expose.mesh.identity = "forge.<forge_id>"`
2105    /// - `annotations["yah.forge"] = "true"` (suppresses the shape warning)
2106    /// - `tier` and `image` come from the caller; `ports` becomes the mesh
2107    ///   port list (empty is valid — forge jobs often don't expose ports)
2108    ///
2109    /// All other fields are set to safe defaults. Callers can mutate the
2110    /// returned value to fill in `command`, `env`, `resources`, etc.
2111    pub fn for_forge(
2112        forge_id: &str,
2113        image: ImageRef,
2114        tier: TierTag,
2115        ports: Vec<u16>,
2116    ) -> Self {
2117        let mut annotations = HashMap::new();
2118        annotations.insert("yah.forge".into(), "true".into());
2119        // The placement floor, kept distinct from the cgroup ceiling below.
2120        // Without this, admission reads the 32 GiB ceiling as the amount of
2121        // RAM a node must have — see `memory_request_mb` for what that cost.
2122        annotations.insert(
2123            MEMORY_REQUEST_ANNOTATION.into(),
2124            FORGE_MEMORY_REQUEST_MB.to_string(),
2125        );
2126
2127        WorkloadSpec {
2128            schema_version: SchemaVersion::V1,
2129            // NB: DNS-label safe (no dots) — `check_name` validation rejects
2130            // dots here. The container_id derives from this; the state-poll
2131            // keys off `expose.mesh.identity` (`forge.<id>`) instead, so those
2132            // two must be reconciled at the read path, NOT by dotting the name
2133            // (see R590-B9).
2134            name: format!("forge-{forge_id}"),
2135            image,
2136            tier,
2137            tenant: TenantId::singleton(),
2138            namespace: NamespaceId::singleton(),
2139            replicas: 1,
2140            command: None,
2141            entrypoint: None,
2142            workdir: None,
2143            user: None,
2144            env: vec![],
2145            secrets: vec![],
2146            volumes: vec![],
2147            resources: ResourceLimits {
2148                // R590-B10: forge workloads are BUILDS (cargo, buildkit, a
2149                // from-source V8 checkout+compile), not tiny services. The old
2150                // 256 MB placeholder became a hard cgroup memory.limit in
2151                // build_oci_spec and SIGKILL'd the rusty-v8 build mid-checkout
2152                // (git checkout of third_party/icu died of signal 9) — the
2153                // more so because /tmp is a RAM-backed tmpfs, so the source
2154                // tree counts against this limit too. 32 GiB is a bounded
2155                // ceiling that fits the V8 build's >12 GB peak with headroom,
2156                // protects the host from a runaway (vs truly unlimited), and is
2157                // above physical RAM on smaller build-workers (⇒ effectively
2158                // unlimited there).
2159                //
2160                // That last clause is only true while this stays a CEILING. It
2161                // was also the placement floor until the annotation set above
2162                // split the two, which made every build-worker under 32 GiB
2163                // unschedulable — the story is on `memory_request_mb`.
2164                memory_mb: FORGE_MEMORY_LIMIT_MB,
2165                cpu_millis: 512,
2166                ephemeral_storage_mb: 512,
2167            },
2168            depends_on: vec![],
2169            healthcheck: None,
2170            restart_policy: RestartPolicy::Never,
2171            archetype: Some(LifecycleArchetype::Job),
2172            stop_policy: StopPolicy {
2173                signal: 15,
2174                grace_period: Millis::from_secs(30),
2175            },
2176            expose: ExposeSpec {
2177                mesh: MeshExpose {
2178                    identity: MeshIdent(format!("forge.{forge_id}")),
2179                    ports,
2180                    allow_from: vec![],
2181                },
2182                public: None,
2183                operator: None,
2184            },
2185            labels: HashMap::new(),
2186            annotations,
2187        }
2188    }
2189
2190    /// Whether this workload requests the **host network namespace** rather
2191    /// than an isolated one.
2192    ///
2193    /// Opt-in via `annotations["yah.network"] == "host"` (see
2194    /// [`HOST_NETWORK_ANNOTATION`] / [`HOST_NETWORK_VALUE`]). Default is the
2195    /// isolated netns every other workload gets — host networking is a
2196    /// privileged escape hatch for the few infra workloads that must bind a
2197    /// host port so an on-host ingress (e.g. a Cloudflare tunnel reaching
2198    /// `127.0.0.1:<port>`) can route to them without CNI/bridge plumbing.
2199    ///
2200    /// The backend (kamaji) is responsible for **guarding** this: host
2201    /// networking is only honoured for `tier == "infra"` workloads; a
2202    /// non-infra workload that sets the annotation is rejected at deploy. See
2203    /// `validate_spec_for_constable`.
2204    pub fn wants_host_network(&self) -> bool {
2205        self.annotations
2206            .get(HOST_NETWORK_ANNOTATION)
2207            .map(|v| v == HOST_NETWORK_VALUE)
2208            .unwrap_or(false)
2209    }
2210
2211    /// Resolve the lifecycle archetype (R572-F1 / W244): the explicit
2212    /// [`Self::archetype`] if set, otherwise the pre-R572 inference from
2213    /// `volumes`/`restart_policy` this field replaces.
2214    ///
2215    /// This is the one seam callers should use to ask "can I kill and
2216    /// reschedule this?" — it is intentionally the *only* place that
2217    /// implements the fallback, so behavior for pre-existing specs (no
2218    /// `archetype` on disk) is identical to what it was before this field
2219    /// existed. Consumers (reconciler R572-F4, scheduler R572-F5) branch on
2220    /// the return value; this crate does not itself change any reconciler or
2221    /// scheduler behavior.
2222    pub fn effective_archetype(&self) -> LifecycleArchetype {
2223        self.archetype
2224            .unwrap_or_else(|| LifecycleArchetype::infer(&self.volumes, &self.restart_policy))
2225    }
2226
2227    /// Fully-qualified mesh identity `<tenant>/<namespace>/<name>` (W206 /
2228    /// R558-F3), where `<name>` is this workload's [`MeshExpose::identity`].
2229    ///
2230    /// Within a tenant, workloads still address each other by the short
2231    /// identity (namespace disambiguates only on collision); the FQN is what
2232    /// makes the identity unambiguous across tenants and is exactly what a
2233    /// [`MeshPeer::CrossTenant`] grant names.
2234    pub fn fq_mesh_identity(&self) -> String {
2235        format!(
2236            "{}/{}/{}",
2237            self.tenant.0, self.namespace.0, self.expose.mesh.identity.0
2238        )
2239    }
2240
2241    /// The taint this workload requires its node to carry, if any (R594-F2 /
2242    /// W267 sovereign public ingress).
2243    ///
2244    /// Opt-in via `annotations["yah.placement.requires-taint"] = "<taint
2245    /// name>"` (see [`REQUIRES_TAINT_ANNOTATION`]) — same annotation-based,
2246    /// zero-blast-radius shape as [`Self::wants_host_network`], chosen so
2247    /// declaring this requirement does not force a struct-literal edit at
2248    /// every existing `WorkloadSpec { .. }` construction site the way a new
2249    /// plain field would (see R572-F1's handoff: ~26 sites for one field).
2250    ///
2251    /// Both halves have since landed: `MachineConfig.taints` (R572-F3) and the
2252    /// scheduler's affinity check in `cloud::config::RequiredSpec::matches`
2253    /// (R572-F5), which requires the key in the node's `taints` **or**
2254    /// `mesh_tags`.
2255    ///
2256    /// A key named here is one of only two ways a node taint can influence
2257    /// placement — the other is the `no-<archetype>` repulsion form. W305/
2258    /// R742-T4 makes `yah cloud validate` reject any node taint that is
2259    /// neither, so a new affinity key must be added to
2260    /// `cloud::config::AFFINITY_TAINT_KEYS` alongside the workload that
2261    /// requires it.
2262    ///
2263    /// The public-ingress appliance (W267) is the first user: a
2264    /// `kind = "container"` workload with `archetype =
2265    /// Some(LifecycleArchetype::Appliance)` and
2266    /// `requires_taint() == Some(PUBLIC_IP_TAINT)`, so yubaba may one day
2267    /// place it only on machines carrying the `"public-ip"` taint and kamaji
2268    /// supervises it like any other container (no new `Workload` variant —
2269    /// see [`Workload::Container`]'s doc comment).
2270    pub fn requires_taint(&self) -> Option<&str> {
2271        self.annotations
2272            .get(REQUIRES_TAINT_ANNOTATION)
2273            .map(String::as_str)
2274    }
2275
2276    /// The memory (MiB) a scheduler must find on a node before placing this
2277    /// workload — its **request**, as distinct from [`ResourceLimits::memory_mb`],
2278    /// which is a **ceiling** the backend turns into a cgroup `memory.max`.
2279    ///
2280    /// Opt-in via `annotations["yah.placement.memory-request-mb"]` (see
2281    /// [`MEMORY_REQUEST_ANNOTATION`]); absent or unparseable falls back to
2282    /// `resources.memory_mb`, so every spec that does not set it is admitted
2283    /// exactly as it was before this accessor existed.
2284    ///
2285    /// # Why the two numbers must not be the same one
2286    ///
2287    /// A limit answers "kill it past here"; a request answers "don't start it
2288    /// somewhere smaller than here". Generous is the safe direction for the
2289    /// first and the unschedulable direction for the second, so one field
2290    /// serving both makes a deliberately-roomy ceiling into an admission floor.
2291    ///
2292    /// That is not hypothetical: [`WorkloadSpec::for_forge`] sets a 32 GiB
2293    /// ceiling explicitly reasoned as "above physical RAM on smaller
2294    /// build-workers ⇒ effectively unlimited there" (R590-B10), and
2295    /// `CloudConfig::admit_workload` fed that same 32768 in as the R572-F5
2296    /// capacity floor. Every build-worker under 32 GiB — the three 8 GiB Pi-5s
2297    /// and the 16 GiB us-west-003 — became structurally unadmittable for *any*
2298    /// offloaded qed step, leaving one 47 GiB node as the fleet's only legal
2299    /// target for remote CI. This is R590-B10's own recorded follow-up
2300    /// ("thread a per-step memory request … instead of a blanket forge
2301    /// default"), reduced to the seam that closes the bug.
2302    ///
2303    /// An annotation rather than a new `ResourceLimits` field on purpose:
2304    /// `WorkloadSpec` crosses a postcard wire that is positional and
2305    /// carries no field names (R590-B3), so adding a field would break decode
2306    /// on every fleet node still running an older kamaji. `annotations` is an
2307    /// existing map — an extra key rides it safely, and admission already
2308    /// reads placement inputs from exactly there
2309    /// ([`Self::requires_taint`], the R594 node-selector).
2310    pub fn memory_request_mb(&self) -> u32 {
2311        self.annotations
2312            .get(MEMORY_REQUEST_ANNOTATION)
2313            .and_then(|v| v.trim().parse::<u32>().ok())
2314            .unwrap_or(self.resources.memory_mb)
2315    }
2316
2317    /// Whether this workload must be run by kamaji's **native** (fork+exec)
2318    /// backend on the node's own userland, rather than by a container backend
2319    /// (R577-T1 / W254).
2320    ///
2321    /// Opt-in via `annotations["yah.exec"] == "native"` (see
2322    /// [`NATIVE_EXEC_ANNOTATION`] / [`NATIVE_EXEC_VALUE`]) — the same
2323    /// annotation-shaped, zero-blast-radius marker as
2324    /// [`Self::wants_host_network`] and [`Self::requires_taint`], chosen over
2325    /// a new plain field for the reason R572-F1 recorded: a field forces a
2326    /// struct-literal edit at every existing construction site and an
2327    /// exhaustive-match update in `kamaji-proto`'s codec, and this marker
2328    /// needs neither.
2329    ///
2330    /// # Why an annotation and not a runtime enum on the wire
2331    ///
2332    /// The remote-execution wire already carries exactly one workload shape —
2333    /// `Workload::Container(WorkloadSpec)` — and every layer between the
2334    /// dispatcher and the node (yubaba admission, mesh assignment, log
2335    /// ingest, produced-file retrieval, teardown) is written against it. A
2336    /// Darwin build differs from a Linux build in *one* respect: there is no
2337    /// container that can host it, because you cannot containerize the Darwin
2338    /// kernel. Marking that one difference keeps the rest of the path shared
2339    /// instead of growing a parallel `exec_native` RPC that would have to
2340    /// re-implement all of it.
2341    ///
2342    /// `image` stays populated for a native workload and is **identity
2343    /// metadata only** — nothing is pulled; the native backend resolves argv
2344    /// from `entrypoint` + `command` (container semantics) and execs it on
2345    /// the host.
2346    pub fn wants_native_exec(&self) -> bool {
2347        self.annotations
2348            .get(NATIVE_EXEC_ANNOTATION)
2349            .map(|v| v == NATIVE_EXEC_VALUE)
2350            .unwrap_or(false)
2351    }
2352
2353    /// Whether this workload must be run by kamaji's **microVM** backend —
2354    /// booted in its own KVM guest with its own kernel, rather than sharing the
2355    /// host kernel with every other workload on the node (R605-F8 / W325 §5).
2356    ///
2357    /// Opt-in via `annotations["yah.exec"] == "microvm"` (see
2358    /// [`NATIVE_EXEC_ANNOTATION`] / [`MICROVM_EXEC_VALUE`]).
2359    ///
2360    /// # Why the *same* key as native exec, not a new one
2361    ///
2362    /// W325's Shape A calls this "a sibling branch on a new annotation value",
2363    /// and the value — not the key — is the whole point. `yah.exec` names the
2364    /// execution substrate, and a workload has exactly one:
2365    ///
2366    /// | `yah.exec` | substrate | kernel | isolation |
2367    /// |---|---|---|---|
2368    /// | *(absent)* | container backend | host's | namespaces + cgroup |
2369    /// | `native` | fork+exec on the host | host's | **none** |
2370    /// | `microvm` | KVM guest | **its own** | hardware |
2371    ///
2372    /// A second key (`yah.isolation = microvm`, say) would make
2373    /// `yah.exec = native` + `yah.isolation = microvm` *expressible*, and
2374    /// therefore something a dispatcher could emit and a backend would have to
2375    /// refuse — exactly the refusal `validate_native_exec_spec` already has to
2376    /// carry for the `yah.sandbox` pair, and for the same avoidable reason. A
2377    /// map key holds one value, so on this key the three substrates are
2378    /// mutually exclusive *by construction*: there is no spec on which both
2379    /// this and [`Self::wants_native_exec`] return `true`, and
2380    /// `exec_substrate_markers_are_mutually_exclusive_by_construction` pins
2381    /// that.
2382    ///
2383    /// # What the marker does and does not promise
2384    ///
2385    /// Like every marker on this struct it is **inert metadata** — it declares
2386    /// intent and nothing more. Whether a node can honour it is a node
2387    /// capability question (`/dev/kvm`, a guest kernel, a rootfs; see W325 §4),
2388    /// and a node whose kamaji has no microVM backend configured **refuses**
2389    /// the deploy rather than falling back to a container. That refusal is
2390    /// deliberate and mirrors R577-T1's: a caller asking for microVM isolation
2391    /// is asking for the one property a container cannot provide, so silently
2392    /// downgrading it would return success while delivering the thing the
2393    /// caller specifically declined.
2394    ///
2395    /// `image` is identity metadata only, as it is for native exec — nothing is
2396    /// pulled. The guest's root filesystem comes from the node's configured
2397    /// rootfs image, and argv is resolved from `entrypoint` + `command` with
2398    /// container semantics, so one spec shape drives all three substrates.
2399    pub fn wants_microvm(&self) -> bool {
2400        self.annotations
2401            .get(NATIVE_EXEC_ANNOTATION)
2402            .map(|v| v == MICROVM_EXEC_VALUE)
2403            .unwrap_or(false)
2404    }
2405
2406    /// Whether this workload builds its **own unprivileged container sandbox**
2407    /// inside the one the backend gives it, and therefore needs the two
2408    /// capabilities plus the `no_new_privs` relaxation that setting up a
2409    /// user namespace requires (R636-B2).
2410    ///
2411    /// Opt-in via `annotations["yah.sandbox"] == "nested"` (see
2412    /// [`NESTED_SANDBOX_ANNOTATION`] / [`NESTED_SANDBOX_VALUE`]) — the same
2413    /// annotation-shaped, zero-blast-radius marker as
2414    /// [`Self::wants_host_network`] and [`Self::wants_native_exec`].
2415    ///
2416    /// # What it actually grants, and why exactly that
2417    ///
2418    /// Rootless BuildKit (the only user today: remote `build-image` steps
2419    /// dispatch `moby/buildkit:*-rootless`) boots through `rootlesskit`, which
2420    /// must map a range of sub-uids into a fresh user namespace. It does that
2421    /// by exec'ing the **setuid-root** helpers `newuidmap` / `newgidmap`, so
2422    /// it needs `CAP_SETUID` + `CAP_SETGID` in the bounding set *and*
2423    /// `noNewPrivileges = false` (with `no_new_privs` on, the kernel silently
2424    /// strips the setuid bit and the helper fails with "Could not set caps").
2425    ///
2426    /// Each of those three was measured on us-west-002 to be **individually
2427    /// necessary** — dropping any one of them puts `rootlesskit` back to
2428    /// failing before the first layer:
2429    ///
2430    /// | grant | `rootlesskit` result |
2431    /// |---|---|
2432    /// | baseline (`CAP_NET_BIND_SERVICE` only, `nnp` on) | `fork/exec /usr/bin/newuidmap: operation not permitted` |
2433    /// | `+CAP_SETUID` only, `nnp` off | `fork/exec /usr/bin/newgidmap: operation not permitted` |
2434    /// | `+CAP_SETUID +CAP_SETGID`, `nnp` **on** | `newuidmap: Could not set caps` |
2435    /// | `+CAP_SETUID +CAP_SETGID`, `nnp` off | starts; build runs to completion |
2436    ///
2437    /// It is deliberately *not* `CAP_SYS_ADMIN`: a non-rootless buildkitd
2438    /// would need that instead, which is a far wider grant. Emptying
2439    /// `/etc/subuid` to force `rootlesskit`'s single-mapping path does not
2440    /// avoid the helpers either — it just fails earlier with "No subuid
2441    /// ranges found".
2442    ///
2443    /// **The backend guards this.** Like host networking, it is honoured only
2444    /// for `tier == "infra"` workloads; a non-infra workload that sets the
2445    /// annotation is rejected at deploy. Every other workload keeps the
2446    /// `CAP_NET_BIND_SERVICE`-only, `no_new_privs` baseline.
2447    ///
2448    /// # Mutually exclusive with [`Self::wants_native_exec`]
2449    ///
2450    /// This grant is defined in terms of an **OCI process spec** — a
2451    /// capability set and a `noNewPrivileges` bit. A native (fork+exec)
2452    /// workload has no OCI spec, so there is nothing to apply it to; kamaji
2453    /// refuses a spec carrying both markers rather than accepting a request
2454    /// for widened privileges and silently dropping it (R577-T1 owns that
2455    /// refusal). The two are independent *annotations* — neither implies the
2456    /// other, which is what
2457    /// `nested_sandbox_marker_is_independent_of_the_other_markers` pins — but
2458    /// they are not a legal *pair*.
2459    ///
2460    /// If a future runtime does have a sandbox worth widening (a MacVM under
2461    /// W254, say), give it its own annotation rather than relaxing that
2462    /// refusal. The grant this marker names is `CAP_SETUID` + `CAP_SETGID` +
2463    /// `no_new_privs` off and nothing else; letting it mean a different
2464    /// privilege set per backend would make "what does `yah.sandbox=nested`
2465    /// grant?" unanswerable without knowing which backend received it, which
2466    /// is precisely what a security-relevant marker must not be.
2467    pub fn wants_nested_sandbox(&self) -> bool {
2468        self.annotations
2469            .get(NESTED_SANDBOX_ANNOTATION)
2470            .map(|v| v == NESTED_SANDBOX_VALUE)
2471            .unwrap_or(false)
2472    }
2473}
2474
2475/// Annotation key requesting a workload share the host network namespace.
2476/// See [`WorkloadSpec::wants_host_network`].
2477pub const HOST_NETWORK_ANNOTATION: &str = "yah.network";
2478
2479/// Annotation value (for [`HOST_NETWORK_ANNOTATION`]) selecting host
2480/// networking. Any other value leaves the workload in an isolated netns.
2481pub const HOST_NETWORK_VALUE: &str = "host";
2482
2483/// Annotation key declaring that a workload must land only on a node
2484/// carrying a specific taint. See [`WorkloadSpec::requires_taint`].
2485pub const REQUIRES_TAINT_ANNOTATION: &str = "yah.placement.requires-taint";
2486
2487/// Annotation key carrying a workload's memory **request** in MiB — what a
2488/// scheduler must find free on a node — separate from the `memory_mb`
2489/// **ceiling** the backend enforces as a cgroup limit. See
2490/// [`WorkloadSpec::memory_request_mb`].
2491pub const MEMORY_REQUEST_ANNOTATION: &str = "yah.placement.memory-request-mb";
2492
2493/// The memory request [`WorkloadSpec::for_forge`] declares (MiB).
2494///
2495/// A forge run is a build, and a build's *ceiling* is deliberately roomy
2496/// (`FORGE_MEMORY_LIMIT_MB`); this is the much smaller floor a node must have
2497/// free to be a legal target for one. 2 GiB is what the heaviest forge shape
2498/// in the tree already asks for by hand — `velveteen_exec::remote`'s buildkit
2499/// image-build step overrides `resources.memory_mb` to exactly this — so it is
2500/// a measured number rather than a guess, and it keeps the fleet's 8 GiB
2501/// build-workers schedulable.
2502pub const FORGE_MEMORY_REQUEST_MB: u32 = 2048;
2503
2504/// The cgroup memory ceiling [`WorkloadSpec::for_forge`] sets (MiB).
2505///
2506/// Bounded rather than unlimited so a runaway build cannot take the host
2507/// down, and large enough for the V8 build's >12 GB peak (R590-B10). It is
2508/// **not** a placement input — see [`FORGE_MEMORY_REQUEST_MB`].
2509pub const FORGE_MEMORY_LIMIT_MB: u32 = 32768;
2510
2511/// Taint name (for [`REQUIRES_TAINT_ANNOTATION`]) identifying machines with
2512/// a publicly-routable IP — the W267 sovereign-ingress placement
2513/// requirement. `MachineConfig.taints` (R572-F3) is the matching node-side
2514/// field and `RequiredSpec::matches` (R572-F5) is the consumer, so this is a
2515/// live key on both sides: a node may carry it, and the cloudflared/passway
2516/// ingress specs require it.
2517pub const PUBLIC_IP_TAINT: &str = "public-ip";
2518
2519/// Annotation key selecting which **execution substrate** kamaji runs a
2520/// workload on. Absent (or unrecognised) means a container backend; see
2521/// [`NATIVE_EXEC_VALUE`] and [`MICROVM_EXEC_VALUE`] for the two opt-outs.
2522///
2523/// The name is historical — R577-T1 introduced it for native exec alone — but
2524/// the key has always been the substrate selector, and R605-F8 added the
2525/// second alternative rather than a second key. See
2526/// [`WorkloadSpec::wants_microvm`] for why one key matters.
2527pub const NATIVE_EXEC_ANNOTATION: &str = "yah.exec";
2528
2529/// Annotation value (for [`NATIVE_EXEC_ANNOTATION`]) selecting native
2530/// host execution. Any other value leaves the workload on a container
2531/// backend.
2532pub const NATIVE_EXEC_VALUE: &str = "native";
2533
2534/// Annotation value (for [`NATIVE_EXEC_ANNOTATION`]) selecting a **microVM**:
2535/// the workload boots in its own KVM guest rather than sharing the host
2536/// kernel. See [`WorkloadSpec::wants_microvm`].
2537pub const MICROVM_EXEC_VALUE: &str = "microvm";
2538
2539/// Annotation key requesting the capabilities a workload needs to stand up an
2540/// unprivileged container sandbox of its own.
2541/// See [`WorkloadSpec::wants_nested_sandbox`].
2542pub const NESTED_SANDBOX_ANNOTATION: &str = "yah.sandbox";
2543
2544/// Annotation value (for [`NESTED_SANDBOX_ANNOTATION`]) requesting the
2545/// nested-sandbox grant (`CAP_SETUID` + `CAP_SETGID`, `no_new_privs` off).
2546/// Any other value leaves the workload on the baseline sandbox.
2547pub const NESTED_SANDBOX_VALUE: &str = "nested";
2548
2549// ── ImageRef ─────────────────────────────────────────────────────────────────
2550
2551/// Container image reference identifying a specific image to pull.
2552///
2553/// **Digest is required.** Every executable image reference in the workspace
2554/// is content-addressed by `sha256:<hex>`. The `tag` is preserved as a
2555/// human-readable identifier but is not the source of truth — registries
2556/// return mutable `tag → digest` mappings and we don't trust them for
2557/// reproducibility. R438-T3 tightened `digest: Option<String> → String` to
2558/// make unpinned-image bugs impossible by construction.
2559///
2560/// **Two deserialize shapes.** The struct form
2561/// (`registry`/`repository`/`tag`/`digest` fields) is the on-disk envelope.
2562/// A **string form** (`image = "ghcr.io/foo/bar:v1@sha256:<hex>"`) is also
2563/// accepted and is the shape W164 transform recipes (R438-T4) and W165
2564/// `BuildMode::InContainer` (R438-T6) use. Both shapes go through a single
2565/// parser ([`compose_import::parse_pinned_image_ref`]) that rejects
2566/// bare-tag references at serde-deserialize.
2567#[derive(Debug, Clone, PartialEq, Eq, Serialize, TS)]
2568#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2569pub struct ImageRef {
2570    /// Registry hostname, e.g. `"ghcr.io"` or `"localhost:5000"`.
2571    pub registry: String,
2572
2573    /// Repository path, e.g. `"noisetable/api"`.
2574    pub repository: String,
2575
2576    /// Tag, e.g. `"v1.4.2"` or `"latest"`. Informational — the digest is
2577    /// the source of truth for image identity.
2578    pub tag: String,
2579
2580    /// Content-addressed pinned identity, e.g. `"sha256:abc..."`. Required.
2581    pub digest: String,
2582}
2583
2584impl<'de> Deserialize<'de> for ImageRef {
2585    fn deserialize<D>(de: D) -> Result<Self, D::Error>
2586    where
2587        D: serde::Deserializer<'de>,
2588    {
2589        #[derive(Deserialize)]
2590        struct Fields {
2591            registry: String,
2592            repository: String,
2593            tag: String,
2594            digest: String,
2595        }
2596
2597        // The string-or-struct `untagged` probe requires `deserialize_any`,
2598        // which only self-describing formats support. Postcard — the binary
2599        // wire behind the kamaji UDS — returns `WontImplement` for it, so a
2600        // `Workload::Container(WorkloadSpec)` carrying a nested `ImageRef`
2601        // failed to decode and every container deploy 500'd (R590-B3).
2602        //
2603        // The string form is purely an authoring convenience in human-readable
2604        // configs (`image = "ghcr.io/…@sha256:…"` in recipe/workload TOML and
2605        // JSON); the binary wire only ever carries the derived struct form
2606        // (Serialize is a plain struct derive). So branch on the format: text
2607        // keeps the string-or-struct convenience via `untagged`; binary decodes
2608        // the plain positional struct with no `deserialize_any`.
2609        if de.is_human_readable() {
2610            #[derive(Deserialize)]
2611            #[serde(untagged)]
2612            enum Repr {
2613                // Order matters for `untagged`: try the string form first so
2614                // explicit strings don't get coerced into a struct error.
2615                Pinned(String),
2616                Struct(Fields),
2617            }
2618
2619            match Repr::deserialize(de)? {
2620                Repr::Pinned(s) => {
2621                    compose_import::parse_pinned_image_ref(&s).map_err(serde::de::Error::custom)
2622                }
2623                Repr::Struct(f) => Ok(ImageRef {
2624                    registry: f.registry,
2625                    repository: f.repository,
2626                    tag: f.tag,
2627                    digest: f.digest,
2628                }),
2629            }
2630        } else {
2631            let f = Fields::deserialize(de)?;
2632            Ok(ImageRef {
2633                registry: f.registry,
2634                repository: f.repository,
2635                tag: f.tag,
2636                digest: f.digest,
2637            })
2638        }
2639    }
2640}
2641
2642// ── testing helpers ───────────────────────────────────────────────────────────
2643
2644/// Fixture helpers for test code that needs to construct types whose schemas
2645/// would otherwise demand operator-pinned values (digests, hashes). Doc-hidden
2646/// to discourage misuse from non-test code — production paths must source
2647/// digests from registry resolution or compile-time injection.
2648#[doc(hidden)]
2649pub mod testing {
2650    /// Fixed valid-format sha256 digest for test fixtures. All-zeros marker
2651    /// is impossible for any real image, so a leaked test fixture in a
2652    /// production code-path surfaces obviously.
2653    ///
2654    /// Aliases [`super::ImageRef::UNPINNED_DIGEST`] — the two are deliberately
2655    /// the same value: the fixture sentinel and the production "unpinned"
2656    /// marker must agree so [`super::ImageRef::pull_ref`]'s tag-fallback fires
2657    /// on exactly the digest `catalog_image` writes.
2658    pub const TEST_DIGEST: &str = super::ImageRef::UNPINNED_DIGEST;
2659
2660    /// Owned `String` form of [`TEST_DIGEST`] for fixture constructors.
2661    pub fn test_digest() -> String {
2662        TEST_DIGEST.to_string()
2663    }
2664}
2665
2666// ── EnvVar ────────────────────────────────────────────────────────────────────
2667
2668/// A single environment variable injected into the container.
2669#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2670#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2671pub struct EnvVar {
2672    /// Variable name, conventionally `SCREAMING_SNAKE_CASE`.
2673    pub name: String,
2674
2675    /// Value source.
2676    pub value: EnvValue,
2677}
2678
2679/// Value source for an environment variable.
2680#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2681#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2682#[serde(rename_all = "snake_case")]
2683pub enum EnvValue {
2684    /// Static string baked into the spec.
2685    Literal { value: String },
2686
2687    /// Resolved from a yubaba secret at deploy time; the secret value never
2688    /// appears in the spec JSON.
2689    FromSecret { secret: String, key: String },
2690
2691    /// Resolved from another workload's mesh address at deploy time by yubaba.
2692    /// Lets workloads reference each other symbolically without IP pinning.
2693    FromMesh { ident: MeshIdent, kind: MeshLookup },
2694}
2695
2696/// Which aspect of a mesh peer's address to inject.
2697#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
2698#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2699#[serde(rename_all = "snake_case")]
2700pub enum MeshLookup {
2701    /// Full URL, e.g. `"http://noisetable-db.pdx:5432"`.
2702    Url,
2703    /// Hostname only, e.g. `"noisetable-db.pdx"`.
2704    Host,
2705    /// Port only, e.g. `"5432"`.
2706    Port,
2707}
2708
2709// ── Secrets ───────────────────────────────────────────────────────────────────
2710
2711/// A secret value mounted into the container as an env var or file.
2712///
2713/// The secret value never appears in the spec JSON — only the reference.
2714/// Yubaba audits secret access per workload from these references.
2715#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2716#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2717pub struct SecretMount {
2718    /// Where yubaba reads the secret value from.
2719    pub source: SecretRef,
2720
2721    /// How the secret is surfaced inside the container.
2722    pub target: SecretTarget,
2723}
2724
2725/// Where yubaba resolves the secret value from.
2726#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2727#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2728#[serde(rename_all = "snake_case")]
2729pub enum SecretRef {
2730    /// Per-machine yubaba secret store at `/var/lib/yah/yubaba/secrets/`.
2731    LocalFile { path: PathBuf },
2732
2733    /// Raft-replicated cluster secret spanning all machines (planned; not in
2734    /// V1 deployment). Sketch preserved for wire compatibility.
2735    Cluster { name: String },
2736}
2737
2738/// How the secret is surfaced inside the container.
2739#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2740#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2741#[serde(rename_all = "snake_case")]
2742pub enum SecretTarget {
2743    /// Injected as an environment variable. Value never appears in spec JSON.
2744    /// Prefer `File` — env vars leak through subprocess env and log dumps.
2745    EnvVar { name: String },
2746
2747    /// Mounted as a file inside the container at `path` with `mode` (octal).
2748    File { path: PathBuf, mode: u32 },
2749}
2750
2751// ── Volumes ───────────────────────────────────────────────────────────────────
2752
2753/// A volume mount inside the container.
2754#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2755#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2756pub struct VolumeMount {
2757    /// Backing volume source.
2758    pub source: VolumeSource,
2759
2760    /// Absolute path inside the container.
2761    pub target: PathBuf,
2762
2763    /// Whether the container sees the volume as read-only.
2764    pub read_only: bool,
2765}
2766
2767/// Backing source for a volume mount.
2768#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2769#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2770#[serde(rename_all = "snake_case")]
2771pub enum VolumeSource {
2772    /// Yubaba-managed named volume; created on first use.
2773    Named { name: String },
2774
2775    /// Operator-managed host path. Yubaba rejects bind mounts unless
2776    /// `WorkloadSpec.tier == "infra"`; shape validation enforces this.
2777    Bind { host_path: PathBuf },
2778
2779    /// In-memory tmpfs; discarded on container stop. `size_mb` caps space
2780    /// consumed by the writable layer.
2781    Tmpfs { size_mb: u32 },
2782}
2783
2784// ── Durable forge produced-artifact convention (R603-T5) ──────────────────────
2785
2786/// Convention for a remote forge step's durable produced artifacts.
2787///
2788/// A remote build (e.g. the rusty_v8 musl build on a build-worker) writes its
2789/// output tarball to a path *inside* the container. The container's rootfs is
2790/// destroyed when kamaji reaps the EXITED container — so if the camp daemon is
2791/// down when the build finishes, the artifact is gone before boot-reconcile can
2792/// retrieve it (R603-T4 surfaced this as `Success`-but-`UNPUBLISHED`).
2793///
2794/// The fix (R603-T5) is a **host-persistent bind mount**: forge Subprocess
2795/// workloads mount [`HOST_ROOT`]`/<forge_id>` onto [`CONTAINER_DIR`], so a
2796/// build that writes its `produces` under `/yah/produced` lands the bytes on
2797/// the worker's host filesystem. yubaba then reads them back from the host path
2798/// ([`host_path`]) — which outlives container reaping — instead of the
2799/// unreachable container rootfs.
2800///
2801/// The container-side path and the host root are a shared convention between
2802/// three crates: the qed `build_workload_spec` that adds the mount, kamaji that
2803/// binds it, and the yubaba handler that reads + reaps it. Keeping it here (the
2804/// crate all three already depend on) is the single source of truth.
2805pub mod forge_produced {
2806    use std::path::{Path, PathBuf};
2807
2808    /// Conventional container-side directory a remote forge step writes its
2809    /// durable produced artifacts to. Bind-mounted onto a host-persistent dir.
2810    pub const CONTAINER_DIR: &str = "/yah/produced";
2811
2812    /// Host root under which each forge's durable produced dir lives, one
2813    /// subdir per run: `<HOST_ROOT>/<forge_id>/`. yubaba owns this directory —
2814    /// it creates the per-forge subdir at deploy, serves reads from it, and
2815    /// reaps it on teardown / TTL sweep.
2816    pub const HOST_ROOT: &str = "/var/lib/yah/qed/produced";
2817
2818    /// Forge mesh idents are `forge.<id>` (see [`WorkloadSpec::for_forge`]).
2819    /// Extract the bare `<id>`, or `None` for a non-forge ident.
2820    ///
2821    /// [`WorkloadSpec::for_forge`]: super::WorkloadSpec::for_forge
2822    pub fn forge_id_from_ident(ident: &str) -> Option<&str> {
2823        ident.strip_prefix("forge.")
2824    }
2825
2826    /// The host-persistent produced directory for one forge run.
2827    pub fn host_dir(forge_id: &str) -> PathBuf {
2828        PathBuf::from(HOST_ROOT).join(forge_id)
2829    }
2830
2831    /// Translate a container-side produced path to its durable host path for a
2832    /// given forge run. Returns `None` when `container_path` is not under
2833    /// [`CONTAINER_DIR`] (the caller then knows the artifact was not written to
2834    /// the durable location and won't survive reaping), or when the relative
2835    /// path contains a `..` component (a traversal attempt that could escape the
2836    /// per-forge dir — the reader must never serve a file outside it).
2837    pub fn host_path(forge_id: &str, container_path: &Path) -> Option<PathBuf> {
2838        let rel = container_path.strip_prefix(CONTAINER_DIR).ok()?;
2839        if rel
2840            .components()
2841            .any(|c| matches!(c, std::path::Component::ParentDir))
2842        {
2843            return None;
2844        }
2845        Some(host_dir(forge_id).join(rel))
2846    }
2847
2848    /// The durable produced-dir bind mount for a forge run: host
2849    /// `<HOST_ROOT>/<forge_id>` → container [`CONTAINER_DIR`], writable.
2850    pub fn durable_mount(forge_id: &str) -> super::VolumeMount {
2851        super::VolumeMount {
2852            source: super::VolumeSource::Bind {
2853                host_path: host_dir(forge_id),
2854            },
2855            target: PathBuf::from(CONTAINER_DIR),
2856            read_only: false,
2857        }
2858    }
2859
2860    /// True when `path` is (or is under) the conventional durable produced dir
2861    /// — the guard qed uses to enforce that declared `produces` land somewhere
2862    /// reap-durable.
2863    pub fn is_durable_path(path: &Path) -> bool {
2864        path.starts_with(CONTAINER_DIR)
2865    }
2866}
2867
2868// ── Forge host-state root (R636-B1) ───────────────────────────────────────────
2869
2870/// The one host directory tree a QED forge step's bind mounts may live under.
2871///
2872/// # Why this is a named root rather than a list of paths
2873///
2874/// runc refuses a bind whose source is missing, and the OCI mapper never
2875/// mkdirs one — so *something* has to create each host dir before deploy.
2876/// yubaba does, but only for paths it recognizes, and "recognizes" was
2877/// originally a hardcoded match on the produced dir. Every new forge mount then
2878/// re-learned the lesson the expensive way, on a real box, minutes into a
2879/// build: R603-B6 for `produced/`, then R636-B1 for `build-out/`, each
2880/// surfacing as the same opaque `failed to fulfil mount request: … no such file
2881/// or directory` from deep inside containerd.
2882///
2883/// Naming the *root* makes the rule checkable instead of enumerable: yubaba
2884/// creates any forge bind under [`HOST_ROOT`], and `yubaba.service` grants the
2885/// root once via `StateDirectory=yah/qed`. A third mount needs no new code and
2886/// no unit-file edit — it only has to live here.
2887///
2888/// The prefix bound is load-bearing in the other direction too: it is what
2889/// keeps a workload spec from asking yubaba to mkdir an arbitrary host path.
2890pub mod forge_state {
2891    use std::path::Path;
2892
2893    /// Root of the forge's host-persistent state. Both
2894    /// [`super::forge_produced::HOST_ROOT`] and [`BUILD_OUT_DIR`] are under it.
2895    pub const HOST_ROOT: &str = "/var/lib/yah/qed";
2896
2897    /// Host directory a `build-image` step's OCI archive is written to, bound
2898    /// at `/yah/build/out` in the BuildKit container. Shared (rather than
2899    /// per-forge like `produced/`) because the archive is named after the image
2900    /// tag, which is already unique per build.
2901    pub const BUILD_OUT_DIR: &str = "/var/lib/yah/qed/build-out";
2902
2903    /// Whether yubaba may create `host_path` on behalf of a forge workload.
2904    ///
2905    /// Rejects anything outside [`HOST_ROOT`], and anything with a `..`
2906    /// component — `/var/lib/yah/qed/../../../etc` starts with the root as a
2907    /// string and is nowhere near it as a path.
2908    pub fn is_forge_state_path(host_path: &Path) -> bool {
2909        !host_path
2910            .components()
2911            .any(|c| matches!(c, std::path::Component::ParentDir))
2912            && host_path.starts_with(HOST_ROOT)
2913    }
2914}
2915
2916// ── Materialized-secret path contract (R555-F5) ───────────────────────────────
2917
2918/// Where yubaba writes a `File`-target secret it has resolved, and how the host
2919/// path is derived from the container path.
2920///
2921/// # Why the derivation lives here and not in yubaba
2922///
2923/// yubaba resolves a [`SecretMount`] and rewrites it into a read-only [`Bind`]
2924/// volume before the spec reaches the backend, so the spec kamaji admits is not
2925/// the spec the dispatcher signed: one mount has become one bind. Admission has
2926/// to be able to recognise that rewrite — otherwise a signed recipe carrying a
2927/// secret is refused by [`admission::AdmissionGrant::covers`]'s bind rule, which
2928/// only knows about [`forge_state::HOST_ROOT`], with a message about a forge
2929/// state root that has nothing to do with what happened.
2930///
2931/// Recognising it means recomputing the host path, which means the derivation
2932/// has to be visible to both sides. It was private to yubaba's
2933/// `deploy::secret_mount`; it lives here now, and yubaba calls in. `forge_state`
2934/// is the same shape for the same reason.
2935///
2936/// [`Bind`]: VolumeSource::Bind
2937pub mod secret_mount {
2938    use std::path::{Path, PathBuf};
2939
2940    /// RAM-backed root for materialized secret files. `/run` is a tmpfs on
2941    /// systemd nodes, so decrypted PEM never touches disk. Each workload gets a
2942    /// `<root>/<ident>/` subdir, reaped on workload destroy.
2943    pub const HOST_ROOT: &str = "/run/yah/secrets";
2944
2945    /// Collapse a value into a single safe path component: every char outside
2946    /// `[A-Za-z0-9_-]` becomes `_` (dots included, so `.` / `..` can never
2947    /// traverse). Empty input maps to `_`.
2948    pub fn sanitize_component(s: &str) -> String {
2949        let mapped: String = s
2950            .chars()
2951            .map(|c| {
2952                if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
2953                    c
2954                } else {
2955                    '_'
2956                }
2957            })
2958            .collect();
2959        if mapped.is_empty() {
2960            "_".into()
2961        } else {
2962            mapped
2963        }
2964    }
2965
2966    /// Derive a collision-free host filename from a container target path: strip
2967    /// the leading `/`, keep `.` for extensions, and replace path separators (and
2968    /// any other non-`[A-Za-z0-9_.-]` char) with `_`. A target that reduces to
2969    /// nothing or a dots-only name falls back to `secret`. The result is always a
2970    /// single flat filename (no separators), so it cannot traverse out of the
2971    /// per-workload dir.
2972    pub fn host_file_name(target: &Path) -> String {
2973        let raw = target.to_string_lossy();
2974        let trimmed = raw.trim_start_matches('/');
2975        let mapped: String = trimmed
2976            .chars()
2977            .map(|c| {
2978                if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
2979                    c
2980                } else {
2981                    '_'
2982                }
2983            })
2984            .collect();
2985        if mapped.is_empty() || mapped.chars().all(|c| c == '.') {
2986            "secret".into()
2987        } else {
2988            mapped
2989        }
2990    }
2991
2992    /// The per-workload directory materialized secrets are written to.
2993    pub fn workload_dir(root: &Path, ident: &str) -> PathBuf {
2994        root.join(sanitize_component(ident))
2995    }
2996
2997    /// The host path a `File`-target secret at container path `target` is
2998    /// materialized to for workload `ident`.
2999    ///
3000    /// Deterministic in exactly those three inputs, which is what lets admission
3001    /// recompute it from the spec alone and match a bind against it.
3002    pub fn materialized_host_path(root: &Path, ident: &str, target: &Path) -> PathBuf {
3003        workload_dir(root, ident).join(host_file_name(target))
3004    }
3005}
3006
3007#[cfg(test)]
3008mod secret_mount_tests {
3009    use super::secret_mount::*;
3010    use std::path::{Path, PathBuf};
3011
3012    #[test]
3013    fn the_host_path_is_a_pure_function_of_root_ident_and_target() {
3014        let p = materialized_host_path(
3015            Path::new(HOST_ROOT),
3016            "forge.abc-123",
3017            Path::new("/etc/yah/r2.json"),
3018        );
3019        assert_eq!(
3020            p,
3021            PathBuf::from("/run/yah/secrets/forge_abc-123/etc_yah_r2.json")
3022        );
3023    }
3024
3025    /// The two collapses exist to keep a hostile ident or target from steering
3026    /// the write out of the per-workload dir. Pinned here because admission now
3027    /// depends on them being total.
3028    #[test]
3029    fn neither_component_can_traverse() {
3030        for ident in ["..", "../../etc", "a/b", ""] {
3031            let dir = workload_dir(Path::new(HOST_ROOT), ident);
3032            assert_eq!(dir.components().count(), 5, "{ident:?} escaped {dir:?}");
3033            assert!(dir.starts_with(HOST_ROOT));
3034        }
3035        for target in ["/../../etc/shadow", "..", "/", "/a/../b"] {
3036            let name = host_file_name(Path::new(target));
3037            assert!(!name.contains('/'), "{target:?} kept a separator: {name}");
3038            assert_ne!(name, "..");
3039        }
3040    }
3041}
3042
3043#[cfg(test)]
3044mod forge_state_tests {
3045    use super::forge_state::*;
3046    use std::path::Path;
3047
3048    #[test]
3049    fn both_known_forge_roots_are_under_the_state_root() {
3050        assert!(is_forge_state_path(Path::new(
3051            super::forge_produced::HOST_ROOT
3052        )));
3053        assert!(is_forge_state_path(Path::new(BUILD_OUT_DIR)));
3054        assert!(is_forge_state_path(&super::forge_produced::host_dir(
3055            "abc-123"
3056        )));
3057    }
3058
3059    /// A spec must not be able to steer yubaba's mkdir anywhere it likes —
3060    /// neither by naming an unrelated absolute path nor by climbing out with
3061    /// `..`, which a plain string prefix check would wave through.
3062    #[test]
3063    fn paths_outside_the_root_are_refused() {
3064        for bad in [
3065            "/var/lib/yah/yubaba",
3066            "/etc/systemd/system",
3067            "/var/lib/yah/qed/../../../etc",
3068            "relative/path",
3069        ] {
3070            assert!(
3071                !is_forge_state_path(Path::new(bad)),
3072                "{bad} must not be creatable by a forge spec"
3073            );
3074        }
3075    }
3076}
3077
3078// ── Resources ─────────────────────────────────────────────────────────────────
3079
3080/// Hard resource caps enforced by containerd/cgroups at runtime.
3081#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
3082#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3083pub struct ResourceLimits {
3084    /// Maximum RAM the container may allocate, in MiB. The container is OOM-
3085    /// killed if it exceeds this.
3086    ///
3087    /// A **ceiling**, not a request: setting it generously is the safe
3088    /// direction here and the unschedulable direction for placement, so
3089    /// schedulers must read [`WorkloadSpec::memory_request_mb`] instead of
3090    /// this field. (`cpu_millis` below is the opposite — a request by
3091    /// definition — which is why the two are not symmetric.)
3092    pub memory_mb: u32,
3093
3094    /// CPU **request** in millicores (k8s convention): `1000` = one full core,
3095    /// `250` = `.25 CPU`. Unlike a Docker relative weight this is an
3096    /// allocatable quantity a bin-packer can subtract from a node's budget.
3097    /// `0` means "no CPU limit". Backends that speak a relative weight derive
3098    /// it via [`ResourceLimits::cpu_shares`].
3099    pub cpu_millis: u32,
3100
3101    /// Cap on the writable layer + tmpfs footprint, in MiB.
3102    pub ephemeral_storage_mb: u32,
3103}
3104
3105impl ResourceLimits {
3106    /// The Docker/OCI relative CPU weight (`cpu.shares`, where `1024` ≈ one
3107    /// core) equivalent to this millicore request. The containerd and docker
3108    /// backends express CPU as a weight rather than a millicore request, so
3109    /// they derive it here instead of storing shares: `1000m` ⇒ `1024`.
3110    pub fn cpu_shares(&self) -> u64 {
3111        (u64::from(self.cpu_millis) * 1024) / 1000
3112    }
3113}
3114
3115// ── Healthcheck ───────────────────────────────────────────────────────────────
3116
3117/// Container health probe configuration.
3118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
3119#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3120pub struct Healthcheck {
3121    /// The probe executed to determine container health.
3122    pub probe: HealthProbe,
3123
3124    /// How often the probe runs.
3125    pub interval: Millis,
3126
3127    /// Per-probe timeout; a slow response counts as failure.
3128    pub timeout: Millis,
3129
3130    /// Time to wait after container start before the first probe. Shape
3131    /// validation warns (not errors) if this is less than
3132    /// `stop_policy.grace_period * 2`.
3133    pub initial_delay: Millis,
3134
3135    /// Number of consecutive failures before the container is marked
3136    /// `Unhealthy`.
3137    pub failure_threshold: u32,
3138}
3139
3140/// Mechanism used to check container health.
3141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
3142#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3143#[serde(rename_all = "snake_case")]
3144pub enum HealthProbe {
3145    /// HTTP GET to `path` on `port`. A 2xx (or `expect_status` if set)
3146    /// response counts as healthy.
3147    HttpGet {
3148        path: String,
3149        port: u16,
3150        #[ts(optional = nullable)]
3151        expect_status: Option<u16>,
3152    },
3153
3154    /// Run `argv` inside the container; exit-0 counts as healthy.
3155    Exec { argv: Vec<String> },
3156
3157    /// TCP connection to `port`; a successful connect counts as healthy.
3158    TcpConnect { port: u16 },
3159}
3160
3161// ── Restart / Stop ────────────────────────────────────────────────────────────
3162
3163/// What yubaba does when the container exits.
3164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
3165#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3166#[serde(rename_all = "snake_case")]
3167pub enum RestartPolicy {
3168    /// Restart unconditionally on any exit.
3169    Always,
3170
3171    /// Restart on non-zero exit, up to `max_attempts` times with exponential
3172    /// backoff. After exhaustion, the workload is marked `Failed`.
3173    OnFailure {
3174        max_attempts: u32,
3175        backoff: BackoffPolicy,
3176    },
3177
3178    /// Do not restart. The container runs once and exits.
3179    ///
3180    /// **Forge convention.** Forge runs (R094) synthesize a `WorkloadSpec`
3181    /// using [`WorkloadSpec::for_forge`] which sets all the conventional fields
3182    /// together:
3183    ///
3184    /// - `restart_policy = Never`
3185    /// - `expose.public = None`, `expose.operator = None`
3186    /// - `expose.mesh.identity = "forge.<forge_id>"` — distinguishable from
3187    ///   persistent mirror identities at the mesh layer
3188    /// - `tier = "infra"` (or the forge-spec's effective tier)
3189    /// - `annotations["yah.forge"] = "true"` — suppresses the shape warning
3190    ///
3191    /// Using `Never` on a persistent mirror (not a forge run) means the mirror
3192    /// stays dead after any exit — a likely misconfiguration. Shape validation
3193    /// emits a soft warning unless `annotations["yah.forge"] == "true"` is
3194    /// present. See R094 forge.
3195    Never,
3196}
3197
3198/// Exponential backoff parameters for `RestartPolicy::OnFailure`.
3199#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
3200#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3201pub struct BackoffPolicy {
3202    /// Initial delay before the first restart, in milliseconds.
3203    pub initial_ms: u32,
3204
3205    /// Maximum delay between retries, in milliseconds.
3206    pub max_ms: u32,
3207
3208    /// Backoff multiplier applied to each successive delay.
3209    pub multiplier: f32,
3210}
3211
3212/// Graceful shutdown configuration for yubaba's stop sequence.
3213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
3214#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3215pub struct StopPolicy {
3216    /// Signal number sent first, e.g. `15` (SIGTERM) or `2` (SIGINT).
3217    pub signal: i32,
3218
3219    /// Time yubaba waits after sending `signal` before issuing SIGKILL.
3220    pub grace_period: Millis,
3221}
3222
3223// ── Expose ────────────────────────────────────────────────────────────────────
3224
3225/// Network exposure configuration. The three channels are independent; any
3226/// combination is valid.
3227#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
3228#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3229pub struct ExposeSpec {
3230    /// Mesh-internal exposure. Required; every workload must have a mesh
3231    /// identity even if no other workload currently reaches it.
3232    pub mesh: MeshExpose,
3233
3234    /// Public internet exposure via a Cloudflare tunnel route. `None` means
3235    /// the workload is not internet-reachable.
3236    #[ts(optional = nullable)]
3237    pub public: Option<PublicExpose>,
3238
3239    /// Operator-facing exposure via a Tailscale ACL tag. `None` means the
3240    /// workload is not operator-reachable via Tailscale.
3241    #[ts(optional = nullable)]
3242    pub operator: Option<OperatorExpose>,
3243}
3244
3245/// A peer permitted to initiate mesh connections to a workload (W206 / R558-F3).
3246///
3247/// Cross-tenant access is **deny-by-default**: a workload accepts inter-tenant
3248/// traffic only from peers it lists explicitly as [`MeshPeer::CrossTenant`].
3249/// Same-tenant access stays tier-based ([`MeshPeer::Tier`]) — the pre-R558
3250/// model — and an `allow_from` with no `Tier` entries still admits every
3251/// same-tenant peer (the historical "empty = allow all" default).
3252///
3253/// External serde tagging keeps this postcard-safe (R590-B3): no internal tag,
3254/// no untagged, no `skip_serializing_if`.
3255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
3256#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3257#[serde(rename_all = "snake_case")]
3258pub enum MeshPeer {
3259    /// Any **same-tenant** workload whose `tier` matches this tag. This is the
3260    /// pre-R558 `allow_from` semantics.
3261    Tier(TierTag),
3262
3263    /// A specific workload in **another tenant**, addressed by its fully
3264    /// qualified mesh identity `<tenant>/<namespace>/<name>`. There is no
3265    /// cross-tenant tier wildcard — each cross-tenant peer is granted
3266    /// individually, so a shared fleet stays isolated unless an operator opts
3267    /// in here.
3268    CrossTenant {
3269        tenant: TenantId,
3270        namespace: NamespaceId,
3271        /// Peer's mesh identity (its [`MeshExpose::identity`]).
3272        name: MeshIdent,
3273    },
3274}
3275
3276/// Mesh-internal port exposure and peer access control.
3277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
3278#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3279pub struct MeshExpose {
3280    /// DNS-segment mesh identity for this workload. Must be unique in the
3281    /// cluster. Regex: `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`, length ≤ 63.
3282    pub identity: MeshIdent,
3283
3284    /// Container-side ports this workload listens on. Other workloads reach
3285    /// it at `<identity>:<port>` on the mesh.
3286    pub ports: Vec<u16>,
3287
3288    /// Peers permitted to initiate connections to this workload on the mesh
3289    /// (W206 / R558-F3). Same-tenant tier rules and explicit cross-tenant
3290    /// grants share this one list. With **no** [`MeshPeer::Tier`] entries every
3291    /// same-tenant peer is admitted (the historical "empty = allow all"
3292    /// default); cross-tenant peers are always denied unless named by a
3293    /// [`MeshPeer::CrossTenant`] entry. See [`MeshExpose::admits_peer`].
3294    #[serde(default)]
3295    pub allow_from: Vec<MeshPeer>,
3296}
3297
3298impl MeshExpose {
3299    /// Whether a peer may initiate a mesh connection to a workload whose mesh
3300    /// exposure is `self`. `own_tenant` is the tenant of the workload being
3301    /// protected; the remaining arguments identify the connecting peer.
3302    ///
3303    /// Deny-by-default across tenants (W206 / R558-F3):
3304    /// - **Same tenant** (`own_tenant == peer_tenant`): admitted when the
3305    ///   peer's tier matches a [`MeshPeer::Tier`] rule, or when there are no
3306    ///   `Tier` rules at all (historical "empty `allow_from` = allow all
3307    ///   same-tenant").
3308    /// - **Cross tenant**: admitted only when an explicit
3309    ///   [`MeshPeer::CrossTenant`] entry matches the peer's
3310    ///   `(tenant, namespace, name)`.
3311    pub fn admits_peer(
3312        &self,
3313        own_tenant: &TenantId,
3314        peer_tenant: &TenantId,
3315        peer_namespace: &NamespaceId,
3316        peer_name: &MeshIdent,
3317        peer_tier: &TierTag,
3318    ) -> bool {
3319        if own_tenant == peer_tenant {
3320            let mut has_tier_rule = false;
3321            for peer in &self.allow_from {
3322                if let MeshPeer::Tier(t) = peer {
3323                    has_tier_rule = true;
3324                    if t == peer_tier {
3325                        return true;
3326                    }
3327                }
3328            }
3329            // No same-tenant tier restriction declared → admit all same-tenant.
3330            !has_tier_rule
3331        } else {
3332            self.allow_from.iter().any(|peer| {
3333                matches!(
3334                    peer,
3335                    MeshPeer::CrossTenant { tenant, namespace, name }
3336                        if tenant == peer_tenant
3337                            && namespace == peer_namespace
3338                            && name == peer_name
3339                )
3340            })
3341        }
3342    }
3343}
3344
3345/// The name by which a workload is addressed **within its own tenant** (W206 /
3346/// R558-F3), given every `(namespace, identity)` pair present in that tenant.
3347///
3348/// Within a tenant, a workload is reached by its short mesh `identity` when that
3349/// identity is unique across the tenant's namespaces. When two namespaces
3350/// expose the same identity, the name is ambiguous, so both are disambiguated
3351/// by a namespace prefix — `<namespace>.<identity>` (e.g. `yah.runner` vs
3352/// `noisetable.runner`). Cross-tenant addressing always uses the full FQN
3353/// ([`WorkloadSpec::fq_mesh_identity`]) and is out of scope here.
3354pub fn intra_tenant_address(
3355    namespace: &NamespaceId,
3356    identity: &MeshIdent,
3357    tenant_workloads: &[(NamespaceId, MeshIdent)],
3358) -> String {
3359    let collides = tenant_workloads
3360        .iter()
3361        .any(|(ns, id)| id == identity && ns != namespace);
3362    if collides {
3363        format!("{}.{}", namespace.0, identity.0)
3364    } else {
3365        identity.0.clone()
3366    }
3367}
3368
3369/// Public internet exposure via a Cloudflare tunnel route.
3370#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
3371#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3372pub struct PublicExpose {
3373    /// Public hostname to route, e.g. `"api.noisetable.io"`. Semantic
3374    /// validation checks that this hostname is owned by a configured CF zone.
3375    pub hostname: String,
3376
3377    /// Container-side port to route traffic to. Shape validation requires this
3378    /// port to appear in `expose.mesh.ports`.
3379    pub port: u16,
3380
3381    /// TLS configuration for the public endpoint.
3382    pub tls: PublicTls,
3383}
3384
3385/// TLS mode for a public endpoint.
3386#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
3387#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3388#[serde(rename_all = "snake_case")]
3389pub enum PublicTls {
3390    /// Cloudflare manages the TLS certificate (default; requires a proxied DNS
3391    /// record in the configured zone).
3392    CfManaged,
3393
3394    /// User-supplied certificate referenced by name in the yubaba secret store.
3395    UserCertRef { name: String },
3396}
3397
3398/// Operator-facing exposure via a Tailscale ACL tag.
3399#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
3400#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3401pub struct OperatorExpose {
3402    /// Tailscale ACL tag granting access, e.g. `"tag:noisetable-ops"`. Semantic
3403    /// validation checks that this tag exists in the cluster's Tailscale ACL.
3404    pub tailscale_tag: String,
3405
3406    /// Container-side port to expose to Tailscale-authorized operators.
3407    pub port: u16,
3408}
3409
3410// ── ImageRef helpers ──────────────────────────────────────────────────────────
3411
3412impl ImageRef {
3413    /// The all-zeros sha256 digest that marks an image reference as **not
3414    /// content-pinned**. No real image can carry it, so a build that never
3415    /// injected a compile-time digest (dev builds) or a catalog image that
3416    /// isn't published-and-pinned yet lands on this sentinel. This is the
3417    /// single source of truth both the catalog emitter
3418    /// (`task::default_image::catalog_image`, which writes it) and the
3419    /// container-runtime resolvers ([`Self::pull_ref`], via kamaji) agree on —
3420    /// keeping them here means they cannot drift. [`testing::TEST_DIGEST`] is
3421    /// the same value re-exported for fixtures.
3422    pub const UNPINNED_DIGEST: &'static str =
3423        "sha256:0000000000000000000000000000000000000000000000000000000000000000";
3424
3425    /// Parse a full digest-pinned image reference —
3426    /// `[registry/]repo[:tag]@sha256:<hex>` — into its parts.
3427    ///
3428    /// This is the public door onto the same parser the `ImageRef` string-form
3429    /// `Deserialize` arm uses, so a config that spells an image as one string
3430    /// (a qed `step.image`, a transform recipe) and a config that spells it as
3431    /// a struct land on identical semantics. A bare tag is rejected: the whole
3432    /// point of the string form is that it carries the digest.
3433    pub fn parse_pinned(s: &str) -> Result<Self, String> {
3434        compose_import::parse_pinned_image_ref(s)
3435    }
3436
3437    /// Format this reference as a Docker-compatible image string,
3438    /// `{registry}/{repository}:{tag}@{digest}`. Tag is included for human
3439    /// readability; the digest is what the pull resolves against. Always emits
3440    /// the digest — this is the display/logging form; use [`Self::pull_ref`]
3441    /// for the string handed to a container runtime.
3442    pub fn docker_ref(&self) -> String {
3443        format!("{}/{}:{}@{}", self.registry, self.repository, self.tag, self.digest)
3444    }
3445
3446    /// True when this reference carries a real content-addressed digest, i.e.
3447    /// its digest is not the all-zeros [`Self::UNPINNED_DIGEST`] sentinel.
3448    pub fn is_pinned(&self) -> bool {
3449        self.digest != Self::UNPINNED_DIGEST
3450    }
3451
3452    /// The reference string to hand a container runtime for pull/resolve.
3453    ///
3454    /// - **Pinned** (real digest): `{registry}/{repository}:{tag}@{digest}` —
3455    ///   content-addressed, the reproducible path.
3456    /// - **Unpinned** (all-zeros [`Self::UNPINNED_DIGEST`]): `{registry}/{repository}:{tag}`
3457    ///   — tag-only. No registry or local store holds an image under the
3458    ///   sentinel digest, so `…@sha256:0000…` can never resolve; a
3459    ///   tag-pulled or locally-built image is keyed by `registry/repo:tag`.
3460    ///   This is the tag-fallback path that lets a not-yet-published catalog
3461    ///   image (e.g. a from-source build-worker image) still pull by tag.
3462    pub fn pull_ref(&self) -> String {
3463        if self.is_pinned() {
3464            format!("{}/{}:{}@{}", self.registry, self.repository, self.tag, self.digest)
3465        } else {
3466            format!("{}/{}:{}", self.registry, self.repository, self.tag)
3467        }
3468    }
3469}
3470
3471// ── WorkloadRuntime trait ─────────────────────────────────────────────────────
3472
3473/// Shared interface for deploying and managing `WorkloadSpec` containers.
3474///
3475/// This is the keystone abstraction (R256-F10) that makes sim and cloud
3476/// literally interchangeable at the container level:
3477///
3478/// - **Camp/sim tier**: `LocalDockerRuntime` in `cloud` implements this trait
3479///   via the docker CLI pointed at OrbStack (or any Docker-compatible socket).
3480///   No mesh — containers communicate over OrbStack's bridge network.
3481///
3482/// - **Yubaba/cloud-HA tier**: `yubaba::runtime::ContainerRuntime` (gRPC to
3483///   containerd) will implement this trait. Mesh assignment is a separate
3484///   orchestration step on top (handled by yubaba's raft layer), not part
3485///   of the shared deploy/supervise interface.
3486///
3487/// Callers that type against `WorkloadRuntime` automatically work with both
3488/// backends. Reconcilers in `cloud` use it today; yubaba wires its own impl
3489/// when R276 Tier-3 lands.
3490#[async_trait::async_trait]
3491pub trait WorkloadRuntime: Send + Sync {
3492    /// Deploy a workload described by `spec`. Pulls the image if needed,
3493    /// creates and starts the container, and returns an opaque workload ID
3494    /// (typically the container name derived from `spec.name`).
3495    ///
3496    /// Idempotent: re-deploying a running workload replaces it cleanly.
3497    async fn deploy_workload(&self, spec: &WorkloadSpec) -> anyhow::Result<String>;
3498
3499    /// Tear down a deployed workload — stop the process and remove all
3500    /// associated state. No-op when the workload is already gone.
3501    async fn teardown_workload(&self, name: &str) -> anyhow::Result<()>;
3502
3503    /// Returns `true` when the named workload is currently running (i.e.
3504    /// the container process is alive and has not exited).
3505    async fn is_running(&self, name: &str) -> anyhow::Result<bool>;
3506
3507    /// Probe the runtime backend. Returns `true` when the backend socket is
3508    /// reachable and healthy (e.g. docker daemon up, containerd gRPC up).
3509    /// Used by health endpoints and startup checks.
3510    async fn runtime_health(&self) -> anyhow::Result<bool>;
3511}
3512
3513// ── Tests ─────────────────────────────────────────────────────────────────────
3514
3515#[cfg(test)]
3516mod tests {
3517    use super::*;
3518
3519    // ── R658-B1 `routes` belongs at the top level, not inside [build] ─────────
3520
3521    /// The canonical `mesofact-static` manifest shape: `routes` above the
3522    /// `[build]` header, where TOML keeps it top-level.
3523    #[test]
3524    fn mesofact_static_routes_parse_at_the_top_level() {
3525        let src = r#"
3526schema_version = 1
3527kind = "mesofact-static"
3528routes = "./mesofact.routes.ts"
3529
3530[build]
3531command = "bun run build"
3532out_dir = "dist"
3533"#;
3534        let Workload::MesofactStatic(site) =
3535            toml::from_str::<Workload>(src).expect("canonical shape must parse")
3536        else {
3537            panic!("kind = \"mesofact-static\" must select MesofactStatic");
3538        };
3539        assert_eq!(site.routes, PathBuf::from("./mesofact.routes.ts"));
3540        assert_eq!(site.build.out_dir, PathBuf::from("dist"));
3541    }
3542
3543    /// The bug R658-B1 exists for: `routes` written *below* `[build]` is
3544    /// `build.routes` as far as TOML is concerned. `BuildConfig` used to
3545    /// discard the stray key, so this manifest parsed as far as the missing
3546    /// top-level field and blamed the wrong line — or, once `routes` had a
3547    /// default, would have deployed a site that enumerated no routes at all.
3548    ///
3549    /// `deny_unknown_fields` makes the misplacement itself the error, and the
3550    /// message names `routes`, which is the one thing the author needs to move.
3551    #[test]
3552    fn mesofact_static_routes_inside_build_is_rejected_by_name() {
3553        let src = r#"
3554schema_version = 1
3555kind = "mesofact-static"
3556
3557[build]
3558command = "bun run build"
3559out_dir = "dist"
3560routes = "./mesofact.routes.ts"
3561"#;
3562        let err = toml::from_str::<Workload>(src)
3563            .expect_err("`routes` under [build] must not parse silently")
3564            .to_string();
3565        assert!(
3566            err.contains("routes"),
3567            "the error must name the misplaced key so the fix is obvious; got: {err}"
3568        );
3569    }
3570
3571    /// Guard the general case, not just the one key that bit us: any unknown
3572    /// `[build]` key is refused rather than dropped on the floor.
3573    #[test]
3574    fn unknown_build_keys_are_refused_rather_than_ignored() {
3575        let src = r#"
3576command = "bun run build"
3577out_dir = "dist"
3578outdir = "dist"
3579"#;
3580        let err = toml::from_str::<BuildConfig>(src)
3581            .expect_err("a typo'd build key must not be silently ignored")
3582            .to_string();
3583        assert!(err.contains("outdir"), "got: {err}");
3584
3585        // …and the keys that ARE modelled still round-trip.
3586        let ok: BuildConfig = toml::from_str(
3587            r#"
3588command = "bun run build"
3589out_dir = "dist"
3590render_command = "mesofact-build render . --route {route}"
3591"#,
3592        )
3593        .expect("modelled keys must still parse");
3594        assert_eq!(ok.render_command.as_deref(), Some("mesofact-build render . --route {route}"));
3595    }
3596
3597    // ── R783-F1 / W324: container manifest vs wire spec ────────────────────────
3598
3599    /// The acceptance case. `crates/yah/cloud-admin/workload.toml` is the file
3600    /// that could not parse through the envelope at all (R658-B2 pinned it in
3601    /// `xtask/tests/workload_envelope.rs` as `missing field \`image\``): it is a
3602    /// Dockerfile recipe, and the envelope only knew digest-pinned specs.
3603    ///
3604    /// The `[process]` table is deliberately present — that file is read by
3605    /// `LocalProcessReconciler` on the dev mirror *and* `ContainerReconciler`
3606    /// on pond, so the container form must tolerate the other tier's table
3607    /// rather than reject the file (W324 §1).
3608    #[test]
3609    fn container_recipe_parses_including_the_other_tier_s_table() {
3610        let src = r#"
3611schema_version = 1
3612name = "yah-cloud-admin"
3613kind = "container"
3614
3615[build]
3616dockerfile = "Dockerfile"
3617context = "."
3618image = "yah-local/yah-cloud-admin:dev"
3619
3620[run]
3621port = 4325
3622host_port = 4326
3623
3624[run.env]
3625YAH_CLOUD_ADMIN_ADDR = "0.0.0.0:4325"
3626
3627[[run.mounts]]
3628host = ".yah/infra"
3629container = "/workspace/.yah/infra"
3630
3631[process]
3632cargo_package = "yah-cloud-admin"
3633port = 4325
3634"#;
3635        let workload = toml::from_str::<Workload>(src).expect("the recipe form must parse");
3636        assert_eq!(workload.kind_str(), "container");
3637
3638        let recipe = workload
3639            .container_manifest()
3640            .and_then(ContainerManifest::as_recipe)
3641            .expect("a [build] table selects the recipe form");
3642        assert_eq!(recipe.name, "yah-cloud-admin");
3643        assert_eq!(recipe.build.dockerfile, PathBuf::from("Dockerfile"));
3644        assert_eq!(recipe.build.context, Some(PathBuf::from(".")));
3645        assert_eq!(
3646            recipe.build.image.as_deref(),
3647            Some("yah-local/yah-cloud-admin:dev")
3648        );
3649        assert_eq!(recipe.run.port, Some(4325));
3650        assert_eq!(recipe.run.host_port, Some(4326));
3651        assert_eq!(
3652            recipe.run.env.get("YAH_CLOUD_ADMIN_ADDR").map(String::as_str),
3653            Some("0.0.0.0:4325")
3654        );
3655        assert_eq!(recipe.run.mounts.len(), 1);
3656        assert!(recipe.run.mounts[0].read_only, "mounts default to read-only");
3657
3658        // The recipe has no spec — that is the whole point of the split.
3659        assert!(workload.container_spec().is_none());
3660    }
3661
3662    /// The other branch: no `[build]` table means the flat fields are a
3663    /// digest-pinned `WorkloadSpec`, exactly as before the split.
3664    #[test]
3665    fn container_reference_still_parses_as_a_workload_spec() {
3666        let spec = archetype_test_spec("noisetable-api");
3667        let toml_src = toml::to_string(&Workload::container(spec.clone())).expect("serialize");
3668        assert!(
3669            toml_src.contains("kind = \"container\""),
3670            "the on-disk form stays flat + internally tagged: {toml_src}"
3671        );
3672
3673        let back = toml::from_str::<Workload>(&toml_src).expect("deserialize");
3674        assert_eq!(back.container_spec(), Some(&spec));
3675    }
3676
3677    /// Explicit-branch deserialize exists so this error survives. Under
3678    /// `#[serde(untagged)]` it would read "data did not match any variant of
3679    /// untagged enum ContainerManifest", which tells an author nothing.
3680    #[test]
3681    fn a_malformed_container_reference_still_names_the_missing_field() {
3682        let src = r#"
3683schema_version = 1
3684kind = "container"
3685name = "noisetable-api"
3686image = "ghcr.io/noisetable/api:v1@sha256:0000000000000000000000000000000000000000000000000000000000000000"
3687replicas = 1
3688"#;
3689        let err = toml::from_str::<Workload>(src)
3690            .expect_err("a reference missing a required field must not parse")
3691            .to_string();
3692        assert!(err.contains("missing field `tier`"), "got: {err}");
3693    }
3694
3695    /// The one file that names neither marker. `missing field \`image\`` would
3696    /// send a recipe author off to add a field their form does not have, so
3697    /// the error names both forms instead.
3698    #[test]
3699    fn a_container_with_neither_image_nor_build_names_both_forms() {
3700        let src = r#"
3701schema_version = 1
3702kind = "container"
3703name = "yah-cloud-admin"
3704
3705[run]
3706port = 4325
3707"#;
3708        let err = toml::from_str::<Workload>(src)
3709            .expect_err("neither form is declared")
3710            .to_string();
3711        assert!(err.contains("image"), "got: {err}");
3712        assert!(err.contains("[build]"), "got: {err}");
3713    }
3714
3715    /// W324 §5's invariant, as a signature: there is no path from a recipe to
3716    /// a `WorkloadSpec` that does not name a digest.
3717    #[test]
3718    fn a_recipe_lowers_only_once_a_build_has_produced_a_digest() {
3719        let recipe = ContainerBuild {
3720            schema_version: SchemaVersion::V1,
3721            name: "yah-cloud-admin".into(),
3722            build: ContainerBuildStep {
3723                dockerfile: "Dockerfile".into(),
3724                context: Some(".".into()),
3725                image: Some("yah-local/yah-cloud-admin:dev".into()),
3726            },
3727            run: ContainerRunConfig {
3728                port: Some(4325),
3729                host_port: Some(4326),
3730                env: BTreeMap::from([("A".to_string(), "b".to_string())]),
3731                mounts: vec![ContainerMount {
3732                    host: ".yah/infra".into(),
3733                    container: "/workspace/.yah/infra".into(),
3734                    read_only: true,
3735                }],
3736            },
3737        };
3738
3739        let digest = testing::test_digest();
3740        let spec = recipe
3741            .clone()
3742            .into_spec(&digest, TierTag("private".into()))
3743            .expect("a well-formed digest lowers");
3744        assert_eq!(spec.name, "yah-cloud-admin");
3745        assert_eq!(spec.image.digest, digest);
3746        assert_eq!(spec.image.repository, "yah-local/yah-cloud-admin");
3747        assert_eq!(spec.image.tag, "dev");
3748        assert_eq!(spec.expose.mesh.ports, vec![4325]);
3749        assert_eq!(spec.env.len(), 1);
3750        assert_eq!(spec.volumes.len(), 1);
3751
3752        // A bare tag is not a digest. Lowering must fail rather than mint a
3753        // spec that lies about being content-addressed (R438-T3).
3754        let err = recipe
3755            .into_spec("dev", TierTag("private".into()))
3756            .expect_err("an unpinned digest must not lower");
3757        assert!(err.contains("sha256"), "got: {err}");
3758    }
3759
3760    /// A recipe is a first-class on-disk value: it survives a write/read of
3761    /// the manifest unchanged. The other half of the gate — that the same
3762    /// value is *refused* by postcard — is in `tests/round_trip.rs`, which
3763    /// also pins the reference form's byte layout.
3764    #[test]
3765    fn a_recipe_round_trips_on_disk_under_the_container_kind() {
3766        let recipe = Workload::Container(ContainerManifest::Recipe(ContainerBuild {
3767            schema_version: SchemaVersion::V1,
3768            name: "yah-cloud-admin".into(),
3769            build: ContainerBuildStep::default(),
3770            run: ContainerRunConfig::default(),
3771        }));
3772        assert_eq!(recipe.kind_str(), "container");
3773
3774        let src = toml::to_string(&recipe).expect("a recipe serializes to disk");
3775        assert!(src.contains("kind = \"container\""), "{src}");
3776        let back: Workload = toml::from_str(&src).expect("and parses back");
3777        assert_eq!(back, recipe);
3778    }
3779
3780    // ── R603-T5 durable forge produced convention ──────────────────────────────
3781
3782    #[test]
3783    fn forge_produced_ident_parse() {
3784        assert_eq!(forge_produced::forge_id_from_ident("forge.abc123"), Some("abc123"));
3785        assert_eq!(forge_produced::forge_id_from_ident("svc.web"), None);
3786        assert_eq!(forge_produced::forge_id_from_ident("abc123"), None);
3787    }
3788
3789    #[test]
3790    fn forge_produced_host_path_translates_under_convention_dir() {
3791        let hp = forge_produced::host_path(
3792            "fid",
3793            std::path::Path::new("/yah/produced/librusty_v8.tar.gz"),
3794        )
3795        .expect("path under the convention dir translates");
3796        assert_eq!(
3797            hp,
3798            PathBuf::from("/var/lib/yah/qed/produced/fid/librusty_v8.tar.gz")
3799        );
3800    }
3801
3802    #[test]
3803    fn forge_produced_host_path_rejects_paths_outside_convention_dir() {
3804        assert_eq!(
3805            forge_produced::host_path("fid", std::path::Path::new("/tmp/x.tar.gz")),
3806            None,
3807            "a path outside /yah/produced has no durable host mapping"
3808        );
3809    }
3810
3811    #[test]
3812    fn forge_produced_host_path_rejects_traversal() {
3813        // A `..` component must never let a read escape the per-forge dir.
3814        assert_eq!(
3815            forge_produced::host_path(
3816                "fid",
3817                std::path::Path::new("/yah/produced/../../etc/passwd")
3818            ),
3819            None,
3820            "traversal out of the per-forge dir must be refused"
3821        );
3822    }
3823
3824    #[test]
3825    fn forge_produced_durable_mount_shape() {
3826        let m = forge_produced::durable_mount("fid");
3827        assert_eq!(m.target, PathBuf::from("/yah/produced"));
3828        assert!(!m.read_only, "the build must be able to write to it");
3829        assert_eq!(
3830            m.source,
3831            VolumeSource::Bind {
3832                host_path: PathBuf::from("/var/lib/yah/qed/produced/fid"),
3833            }
3834        );
3835    }
3836
3837    const HASH_64: &str = "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890";
3838
3839    #[test]
3840    fn blake_hash_accepts_64_hex() {
3841        let h: BlakeHash = toml::from_str(&format!("x = \"{HASH_64}\""))
3842            .map(|t: toml::Table| t["x"].as_str().unwrap().to_owned())
3843            .map(|s| serde_json::from_value(serde_json::Value::String(s)).unwrap())
3844            .unwrap();
3845        assert_eq!(h.0, HASH_64);
3846    }
3847
3848    #[test]
3849    fn blake_hash_rejects_wrong_length() {
3850        let short = "abcdef";
3851        let res: Result<BlakeHash, _> =
3852            serde_json::from_value(serde_json::Value::String(short.into()));
3853        assert!(res.is_err());
3854    }
3855
3856    #[test]
3857    fn blake_hash_rejects_non_hex() {
3858        let bad = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
3859        let res: Result<BlakeHash, _> =
3860            serde_json::from_value(serde_json::Value::String(bad.into()));
3861        assert!(res.is_err());
3862    }
3863
3864    fn image_ref(digest: &str) -> ImageRef {
3865        ImageRef {
3866            registry: "ghcr.io".into(),
3867            repository: "yah-ai/rusty-v8-musl-builder".into(),
3868            tag: "latest".into(),
3869            digest: digest.into(),
3870        }
3871    }
3872
3873    #[test]
3874    fn is_pinned_distinguishes_real_digest_from_sentinel() {
3875        assert!(!image_ref(ImageRef::UNPINNED_DIGEST).is_pinned());
3876        assert!(!image_ref(&testing::test_digest()).is_pinned());
3877        assert!(image_ref("sha256:deadbeef").is_pinned());
3878    }
3879
3880    #[test]
3881    fn pull_ref_pinned_carries_tag_and_digest() {
3882        assert_eq!(
3883            image_ref("sha256:deadbeef").pull_ref(),
3884            "ghcr.io/yah-ai/rusty-v8-musl-builder:latest@sha256:deadbeef",
3885        );
3886    }
3887
3888    #[test]
3889    fn pull_ref_unpinned_falls_back_to_tag_only() {
3890        // An unpinned catalog image (all-zeros sentinel) resolves by tag —
3891        // no store holds `…@sha256:0000…`, so the tag is the only usable key.
3892        assert_eq!(
3893            image_ref(ImageRef::UNPINNED_DIGEST).pull_ref(),
3894            "ghcr.io/yah-ai/rusty-v8-musl-builder:latest",
3895        );
3896    }
3897
3898    #[test]
3899    fn test_digest_alias_is_the_unpinned_sentinel() {
3900        assert_eq!(testing::TEST_DIGEST, ImageRef::UNPINNED_DIGEST);
3901    }
3902
3903    #[test]
3904    fn static_asset_workload_round_trips() {
3905        let src = format!(
3906            r#"
3907schema_version = "V1"
3908
3909[[asset]]
3910filename = "whisper/distil-large-v3-q5_1.bin"
3911source   = "sources/distil-large-v3-q5_1.bin"
3912blake3   = "{HASH_64}"
3913
3914[[asset]]
3915filename = "whisper/distil-large-v3-q4_0.bin"
3916source   = "sources/distil-large-v3-q4_0.bin"
3917blake3   = "{HASH_64}"
3918
3919[aliases]
3920"whisper-default" = "whisper/distil-large-v3-q5_1.bin"
3921"#
3922        );
3923        let w: StaticAssetWorkload = toml::from_str(&src).expect("parse");
3924        assert_eq!(w.assets.len(), 2);
3925        assert_eq!(w.assets[0].filename, "whisper/distil-large-v3-q5_1.bin");
3926        assert_eq!(w.assets[0].blake3.0, HASH_64);
3927        assert_eq!(w.aliases["whisper-default"], "whisper/distil-large-v3-q5_1.bin");
3928
3929        let back = toml::to_string(&w).expect("serialize");
3930        let w2: StaticAssetWorkload = toml::from_str(&back).expect("re-parse");
3931        assert_eq!(w, w2);
3932    }
3933
3934    #[test]
3935    fn license_round_trip_each_variant() {
3936        // Wire format is whatever serde's `rename_all = "kebab-case"` emits.
3937        // heck's kebab-case keeps letter→digit attached but splits digit→uppercase,
3938        // so `Apache2 → "apache2"` and `Bsd2Clause → "bsd2-clause"`.
3939        for (variant, on_wire) in [
3940            (License::Mit, "mit"),
3941            (License::Apache2, "apache2"),
3942            (License::Bsd2Clause, "bsd2-clause"),
3943            (License::Bsd3Clause, "bsd3-clause"),
3944            (License::Isc, "isc"),
3945        ] {
3946            let ser = serde_json::to_value(variant).expect("serialize");
3947            assert_eq!(ser, serde_json::Value::String(on_wire.into()));
3948            let back: License = serde_json::from_value(ser).expect("deserialize");
3949            assert_eq!(back, variant);
3950        }
3951    }
3952
3953    #[test]
3954    fn license_rejects_non_permissive_variants() {
3955        for unknown in ["GPL-3.0", "AGPL", "lgpl-2.1", "unknown", "MIT"] {
3956            let res: Result<License, _> =
3957                serde_json::from_value(serde_json::Value::String(unknown.into()));
3958            assert!(res.is_err(), "expected rejection for {unknown:?}");
3959        }
3960    }
3961
3962    #[test]
3963    fn fetch_source_round_trips() {
3964        let src = format!(
3965            r#"
3966url     = "https://example.invalid/upstream.bin"
3967blake3  = "{HASH_64}"
3968license = "mit"
3969"#
3970        );
3971        let fs: FetchSource = toml::from_str(&src).expect("parse");
3972        assert_eq!(fs.url, "https://example.invalid/upstream.bin");
3973        assert_eq!(fs.blake3.0, HASH_64);
3974        assert_eq!(fs.license, License::Mit);
3975
3976        let back = toml::to_string(&fs).expect("serialize");
3977        let fs2: FetchSource = toml::from_str(&back).expect("re-parse");
3978        assert_eq!(fs, fs2);
3979    }
3980
3981    #[test]
3982    fn fetch_source_rejects_unknown_license() {
3983        let src = format!(
3984            r#"
3985url     = "https://example.invalid/upstream.bin"
3986blake3  = "{HASH_64}"
3987license = "GPL-3.0"
3988"#
3989        );
3990        let res: Result<FetchSource, _> = toml::from_str(&src);
3991        assert!(res.is_err(), "expected non-permissive license to reject");
3992    }
3993
3994    #[test]
3995    fn asset_entry_derive_mode_round_trips() {
3996        let src = format!(
3997            r#"
3998schema_version = "V1"
3999
4000[[asset]]
4001filename = "whisper/distil-large-v3-q5_1.bin"
4002blake3   = "{HASH_64}"
4003
4004[asset.derive.fetch]
4005url     = "https://example.invalid/ggml-distil-large-v3.bin"
4006blake3  = "{HASH_64}"
4007license = "mit"
4008
4009[asset.derive.transform]
4010recipe = "whisper-quantize"
4011params = {{ quant = "q5_1" }}
4012"#
4013        );
4014        let w: StaticAssetWorkload = toml::from_str(&src).expect("parse");
4015        assert_eq!(w.assets.len(), 1);
4016        let entry = &w.assets[0];
4017        assert!(entry.source.is_none());
4018        let derive = entry.derive.as_ref().expect("derive present");
4019        assert_eq!(derive.fetch.url, "https://example.invalid/ggml-distil-large-v3.bin");
4020        assert_eq!(derive.fetch.license, License::Mit);
4021        let transform = derive.transform.as_ref().expect("transform present");
4022        assert_eq!(transform.recipe, "whisper-quantize");
4023        assert_eq!(transform.params.get("quant").map(String::as_str), Some("q5_1"));
4024
4025        let back = toml::to_string(&w).expect("serialize");
4026        let w2: StaticAssetWorkload = toml::from_str(&back).expect("re-parse");
4027        assert_eq!(w, w2);
4028    }
4029
4030    #[test]
4031    fn legacy_source_only_asset_serializes_without_derive_field() {
4032        // Verify the skip_serializing_if guards keep legacy TOMLs round-tripping
4033        // without ever emitting an empty `derive = ...` line.
4034        let src = format!(
4035            r#"
4036schema_version = "V1"
4037
4038[[asset]]
4039filename = "operator-curated.bin"
4040source   = "sources/operator-curated.bin"
4041blake3   = "{HASH_64}"
4042"#
4043        );
4044        let w: StaticAssetWorkload = toml::from_str(&src).expect("parse");
4045        let back = toml::to_string(&w).expect("serialize");
4046        assert!(!back.contains("derive"), "serialized output leaked a derive field: {back}");
4047        let w2: StaticAssetWorkload = toml::from_str(&back).expect("re-parse");
4048        assert_eq!(w, w2);
4049    }
4050
4051    /// W212/R518: the `[asset.derive.lock]` block round-trips through TOML, and
4052    /// is omitted from output when absent (so non-derive / unlocked assets stay
4053    /// clean).
4054    #[test]
4055    fn derive_lock_round_trips_through_toml() {
4056        let toml = r#"
4057url     = "https://example.invalid/config.json"
4058blake3  = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
4059license = "mit"
4060"#;
4061        let fetch: FetchSource = ::toml::from_str(toml).unwrap();
4062        let derive = AssetDerive {
4063            fetch,
4064            transform: Some(TransformSpec {
4065                recipe: "whisper-bundle-tar".into(),
4066                params: BTreeMap::new(),
4067            }),
4068            lock: Some(DeriveLock {
4069                input_hash: "1111111111111111111111111111111111111111111111111111111111111111".into(),
4070                output_blake3: "2222222222222222222222222222222222222222222222222222222222222222".into(),
4071            }),
4072        };
4073        let s = ::toml::to_string(&derive).unwrap();
4074        assert!(s.contains("[lock]"), "lock serialized: {s}");
4075        let back: AssetDerive = ::toml::from_str(&s).unwrap();
4076        assert_eq!(derive, back);
4077
4078        // Absent lock → no `[lock]` table in the output.
4079        let unlocked = AssetDerive { lock: None, ..derive };
4080        let s2 = ::toml::to_string(&unlocked).unwrap();
4081        assert!(!s2.contains("[lock]"), "unlocked must omit lock: {s2}");
4082    }
4083
4084    #[test]
4085    fn shape_static_asset_rejects_both_source_and_derive() {
4086        use crate::validate::{shape_static_asset, FieldPath, ShapeError};
4087
4088        let entry = AssetEntry {
4089            filename: "ambiguous.bin".into(),
4090            source: Some("sources/ambiguous.bin".into()),
4091            derive: Some(AssetDerive {
4092                fetch: FetchSource {
4093                    url: "https://example.invalid/x".into(),
4094                    blake3: BlakeHash(HASH_64.into()),
4095                    license: License::Mit,
4096                },
4097                transform: None,
4098                lock: None,
4099            }),
4100            blake3: BlakeHash(HASH_64.into()),
4101        };
4102        let w = StaticAssetWorkload {
4103            schema_version: SchemaVersion::V1,
4104            assets: vec![entry],
4105            aliases: BTreeMap::new(),
4106        };
4107        let err = shape_static_asset(&w).expect_err("XOR violated");
4108        match err {
4109            ShapeError::Field { path: FieldPath::Asset(0, "source"), .. } => {}
4110            other => panic!("expected Asset(0, \"source\") shape error, got {other:?}"),
4111        }
4112    }
4113
4114    #[test]
4115    fn shape_static_asset_rejects_neither_source_nor_derive() {
4116        use crate::validate::{shape_static_asset, FieldPath, ShapeError};
4117
4118        let entry = AssetEntry {
4119            filename: "empty.bin".into(),
4120            source: None,
4121            derive: None,
4122            blake3: BlakeHash(HASH_64.into()),
4123        };
4124        let w = StaticAssetWorkload {
4125            schema_version: SchemaVersion::V1,
4126            assets: vec![entry],
4127            aliases: BTreeMap::new(),
4128        };
4129        let err = shape_static_asset(&w).expect_err("XOR violated");
4130        match err {
4131            ShapeError::Field { path: FieldPath::Asset(0, "source"), .. } => {}
4132            other => panic!("expected Asset(0, \"source\") shape error, got {other:?}"),
4133        }
4134    }
4135
4136    #[test]
4137    fn shape_static_asset_accepts_either_mode() {
4138        use crate::validate::shape_static_asset;
4139
4140        let legacy = AssetEntry {
4141            filename: "a.bin".into(),
4142            source: Some("sources/a.bin".into()),
4143            derive: None,
4144            blake3: BlakeHash(HASH_64.into()),
4145        };
4146        let derived = AssetEntry {
4147            filename: "b.bin".into(),
4148            source: None,
4149            derive: Some(AssetDerive {
4150                fetch: FetchSource {
4151                    url: "https://example.invalid/b".into(),
4152                    blake3: BlakeHash(HASH_64.into()),
4153                    license: License::Apache2,
4154                },
4155                transform: None,
4156                lock: None,
4157            }),
4158            blake3: BlakeHash(HASH_64.into()),
4159        };
4160        let w = StaticAssetWorkload {
4161            schema_version: SchemaVersion::V1,
4162            assets: vec![legacy, derived],
4163            aliases: BTreeMap::new(),
4164        };
4165        shape_static_asset(&w).expect("both modes accepted");
4166    }
4167
4168    #[test]
4169    fn image_ref_string_form_rejects_bare_tag() {
4170        let res: Result<ImageRef, _> =
4171            serde_json::from_value(serde_json::Value::String("node:20".into()));
4172        let err = res.expect_err("bare-tag must reject");
4173        let msg = format!("{err}");
4174        assert!(msg.contains("digest"), "error should mention digest: {msg}");
4175    }
4176
4177    #[test]
4178    fn image_ref_string_form_accepts_digest_pinned() {
4179        let pinned = format!("node:20@sha256:{HASH_64}");
4180        let img: ImageRef =
4181            serde_json::from_value(serde_json::Value::String(pinned.clone())).expect("parse");
4182        assert_eq!(img.registry, "docker.io");
4183        assert_eq!(img.repository, "library/node");
4184        assert_eq!(img.tag, "20");
4185        assert_eq!(img.digest, format!("sha256:{HASH_64}"));
4186    }
4187
4188    #[test]
4189    fn image_ref_string_form_accepts_ghcr_with_pin() {
4190        let pinned = format!("ghcr.io/foo/bar:v1.7.4@sha256:{HASH_64}");
4191        let img: ImageRef =
4192            serde_json::from_value(serde_json::Value::String(pinned)).expect("parse");
4193        assert_eq!(img.registry, "ghcr.io");
4194        assert_eq!(img.repository, "foo/bar");
4195        assert_eq!(img.tag, "v1.7.4");
4196        assert!(img.digest.starts_with("sha256:"));
4197    }
4198
4199    #[test]
4200    fn image_ref_string_form_rejects_non_sha256_digest() {
4201        for bad in [
4202            "node:20@md5:abcdef",
4203            "node:20@sha1:abcdef",
4204            "node:20@sha256:",
4205            "node:20@sha256:zzznothex",
4206        ] {
4207            let res: Result<ImageRef, _> =
4208                serde_json::from_value(serde_json::Value::String(bad.into()));
4209            assert!(res.is_err(), "expected reject for {bad:?}");
4210        }
4211    }
4212
4213    #[test]
4214    fn image_ref_struct_form_rejects_missing_digest() {
4215        // Digest is now structurally required (R438-T3). Struct-form payloads
4216        // without `digest` must fail at serde-deserialize.
4217        let v = serde_json::json!({
4218            "registry": "ghcr.io",
4219            "repository": "noisetable/api",
4220            "tag": "v1.4.2",
4221        });
4222        let res: Result<ImageRef, _> = serde_json::from_value(v);
4223        assert!(res.is_err(), "missing digest must reject");
4224    }
4225
4226    #[test]
4227    fn image_ref_struct_form_round_trips_through_toml() {
4228        let img = ImageRef {
4229            registry: "ghcr.io".into(),
4230            repository: "ggerganov/whisper.cpp".into(),
4231            tag: "v1.7.4".into(),
4232            digest: format!("sha256:{HASH_64}"),
4233        };
4234        let toml_doc = toml::to_string(&img).expect("serialize");
4235        let back: ImageRef = toml::from_str(&toml_doc).expect("re-parse");
4236        assert_eq!(img, back);
4237    }
4238
4239    /// R546-B7: assert the shape real files use. This test previously fed the
4240    /// EXTERNALLY-tagged wrapping-table form (`[static-asset]` +
4241    /// `[[static-asset.asset]]`), which no on-disk `workload.toml` has ever
4242    /// used — so it stayed green while `yah cloud apply` was broken for every
4243    /// static-asset component. The flat `kind = "..."` form below is what every
4244    /// workload.toml in the workspace is written in.
4245    #[test]
4246    fn workload_envelope_dispatches_static_asset() {
4247        let src = format!(
4248            r#"
4249kind = "static-asset"
4250schema_version = "V1"
4251
4252[[asset]]
4253filename = "foo/bar.bin"
4254source   = "sources/bar.bin"
4255blake3   = "{HASH_64}"
4256"#
4257        );
4258        let w: Workload = toml::from_str(&src).expect("parse");
4259        assert!(matches!(w, Workload::StaticAsset(_)));
4260    }
4261
4262    /// R546-B7: the format branch, both directions. Human-readable formats get
4263    /// the flat `kind`-tagged shape; postcard keeps the externally-tagged
4264    /// variant-index encoding the kamaji UDS depends on (R590-B3). Regressing
4265    /// either side breaks a different half of the system, so pin both.
4266    #[test]
4267    fn workload_envelope_is_tagged_in_toml_and_external_in_postcard() {
4268        let src = format!(
4269            r#"
4270kind = "static-asset"
4271schema_version = "V1"
4272
4273[[asset]]
4274filename = "foo/bar.bin"
4275source   = "sources/bar.bin"
4276blake3   = "{HASH_64}"
4277"#
4278        );
4279        let w: Workload = toml::from_str(&src).expect("parse flat TOML");
4280
4281        // Human-readable round-trips stay flat — no wrapping table.
4282        let json = serde_json::to_string(&w).expect("serialize json");
4283        assert!(json.contains("\"kind\":\"static-asset\""), "got {json}");
4284        assert!(
4285            !json.contains("{\"static-asset\":"),
4286            "human-readable output must not be externally tagged: {json}"
4287        );
4288        assert_eq!(
4289            serde_json::from_str::<Workload>(&json).expect("re-parse json"),
4290            w
4291        );
4292
4293        // postcard is non-self-describing: it can only round-trip because the
4294        // binary branch never asks for deserialize_any.
4295        let bytes = postcard::to_allocvec(&w).expect("postcard encode");
4296        assert_eq!(
4297            postcard::from_bytes::<Workload>(&bytes).expect("postcard decode"),
4298            w
4299        );
4300    }
4301
4302    // ── R572-F1: lifecycle archetype discriminator ─────────────────────────
4303
4304    fn archetype_test_spec(name: &str) -> WorkloadSpec {
4305        WorkloadSpec::for_forge(
4306            name,
4307            ImageRef {
4308                registry: "ghcr.io".into(),
4309                repository: "yah/test".into(),
4310                tag: "latest".into(),
4311                digest: testing::test_digest(),
4312            },
4313            TierTag("infra".into()),
4314            vec![],
4315        )
4316    }
4317
4318    #[test]
4319    fn explicit_archetype_round_trips_through_json_and_wins_over_inference() {
4320        for archetype in [
4321            LifecycleArchetype::Server,
4322            LifecycleArchetype::Appliance,
4323            LifecycleArchetype::Job,
4324        ] {
4325            let mut spec = archetype_test_spec("explicit");
4326            // Volumes present + restart_policy Always would infer Appliance
4327            // (see effective_archetype_infers_* below) — deliberately
4328            // mismatched against every archetype under test so the
4329            // assertion actually proves the explicit field wins, not that
4330            // it happens to agree with inference.
4331            spec.volumes = vec![VolumeMount {
4332                source: VolumeSource::Named { name: "data".into() },
4333                target: PathBuf::from("/data"),
4334                read_only: false,
4335            }];
4336            spec.restart_policy = RestartPolicy::Always;
4337            spec.archetype = Some(archetype);
4338
4339            let json = serde_json::to_string(&spec).expect("serialize");
4340            assert!(
4341                json.contains("\"archetype\""),
4342                "explicit archetype must be present on the wire"
4343            );
4344            let back: WorkloadSpec = serde_json::from_str(&json).expect("deserialize");
4345            assert_eq!(spec, back, "spec did not survive JSON round-trip");
4346            assert_eq!(back.archetype, Some(archetype));
4347            assert_eq!(
4348                back.effective_archetype(),
4349                archetype,
4350                "explicit archetype must win over the volumes/restart_policy inference"
4351            );
4352        }
4353    }
4354
4355    #[test]
4356    fn archetype_serializes_as_null_when_none() {
4357        let mut spec = archetype_test_spec("omitted");
4358        spec.archetype = None;
4359        let json = serde_json::to_value(&spec).expect("to_value");
4360        // Postcard-native (R590-B3): no `skip_serializing_if` anywhere on the
4361        // graph, so every field is always on the wire — a None Option is an
4362        // explicit `null`, not an absent key. The binary UDS wire is positional
4363        // and requires the slot to be present.
4364        assert_eq!(json.get("archetype"), Some(&serde_json::Value::Null));
4365    }
4366
4367    #[test]
4368    fn spec_without_archetype_field_deserializes_to_none() {
4369        // Simulates an on-disk spec written before R572-F1: no `archetype`
4370        // key at all. Omitting the key must still parse to None (the additive-
4371        // default contract) even though we now always *emit* the field.
4372        let mut spec = archetype_test_spec("pre-existing");
4373        spec.archetype = None;
4374        let mut json = serde_json::to_value(&spec).expect("to_value");
4375        json.as_object_mut().unwrap().remove("archetype");
4376        let back: WorkloadSpec = serde_json::from_value(json).expect("deserialize");
4377        assert_eq!(back.archetype, None);
4378    }
4379
4380    #[test]
4381    fn effective_archetype_infers_appliance_from_volumes_when_field_absent() {
4382        // Pre-R572 behavior: a workload with a volume was understood (by
4383        // convention, never a type) to be stateful/pinned. Confirm that
4384        // meaning is preserved bit-for-bit through effective_archetype().
4385        let mut spec = archetype_test_spec("appliance-inferred");
4386        spec.volumes = vec![VolumeMount {
4387            source: VolumeSource::Named { name: "pgdata".into() },
4388            target: PathBuf::from("/var/lib/postgresql/data"),
4389            read_only: false,
4390        }];
4391        spec.restart_policy = RestartPolicy::Always;
4392        spec.archetype = None;
4393        assert_eq!(spec.effective_archetype(), LifecycleArchetype::Appliance);
4394    }
4395
4396    #[test]
4397    fn effective_archetype_infers_job_from_restart_never_when_field_absent() {
4398        // Pre-R572 behavior: RestartPolicy::Never + no volumes is the forge
4399        // run-once convention (see RestartPolicy::Never's own doc comment) —
4400        // structurally a job. WorkloadSpec::for_forge already produces
4401        // exactly this shape; isolate the pure-inference path by clearing
4402        // the explicit archetype for_forge now sets.
4403        let mut spec = archetype_test_spec("job-inferred");
4404        assert!(spec.volumes.is_empty());
4405        assert!(matches!(spec.restart_policy, RestartPolicy::Never));
4406        spec.archetype = None;
4407        assert_eq!(spec.effective_archetype(), LifecycleArchetype::Job);
4408    }
4409
4410    #[test]
4411    fn effective_archetype_defaults_to_server_as_the_common_case_when_field_absent() {
4412        // Pre-R572 behavior: no volumes + a restartable policy (the common
4413        // stateless-web-server shape) inferred as movable/fungible.
4414        let mut spec = archetype_test_spec("server-inferred");
4415        spec.restart_policy = RestartPolicy::Always;
4416        spec.archetype = None;
4417        assert_eq!(spec.effective_archetype(), LifecycleArchetype::Server);
4418    }
4419
4420    // ── R594-F2: public-ingress appliance (container-shaped, not a new
4421    // Workload variant — see Workload::Container's doc comment) ───────────
4422
4423    #[test]
4424    fn ingress_marked_spec_is_appliance_and_carries_public_ip_placement_requirement() {
4425        let mut spec = archetype_test_spec("public-ingress");
4426        spec.archetype = Some(LifecycleArchetype::Appliance);
4427        spec.annotations.insert(
4428            REQUIRES_TAINT_ANNOTATION.to_string(),
4429            PUBLIC_IP_TAINT.to_string(),
4430        );
4431
4432        assert_eq!(
4433            spec.effective_archetype(),
4434            LifecycleArchetype::Appliance,
4435            "ingress must be pinned-per-node/non-drainable, the R572 appliance sense"
4436        );
4437        assert_eq!(
4438            spec.requires_taint(),
4439            Some(PUBLIC_IP_TAINT),
4440            "ingress must declare it can only land on a public-ip-tainted node"
4441        );
4442
4443        // No taint exists to match against yet (R572-F3) and nothing
4444        // enforces placement yet (R572-F5) — confirm this ticket stays
4445        // declarative-only by checking a spec with no requirement stays
4446        // unaffected.
4447        let unrelated = archetype_test_spec("unrelated");
4448        assert_eq!(unrelated.requires_taint(), None);
4449    }
4450
4451    #[test]
4452    fn ingress_marked_spec_round_trips_through_json_as_a_container_workload() {
4453        // Mirrors the on-disk envelope: the externally-tagged `container`
4454        // variant wrapping the WorkloadSpec, exactly like every other
4455        // container-shaped workload. No new Workload variant, no new
4456        // discriminator.
4457        let mut inner = archetype_test_spec("public-ingress");
4458        inner.archetype = Some(LifecycleArchetype::Appliance);
4459        inner.annotations.insert(
4460            REQUIRES_TAINT_ANNOTATION.to_string(),
4461            PUBLIC_IP_TAINT.to_string(),
4462        );
4463        let workload = Workload::container(inner.clone());
4464
4465        let json = serde_json::to_string(&workload).expect("serialize");
4466        assert!(json.contains("\"container\""));
4467        assert!(json.contains(REQUIRES_TAINT_ANNOTATION));
4468        assert!(json.contains(PUBLIC_IP_TAINT));
4469
4470        let back: Workload = serde_json::from_str(&json).expect("deserialize");
4471        match back.container_spec() {
4472            Some(spec) => {
4473                assert_eq!(spec, &inner);
4474                assert_eq!(spec.effective_archetype(), LifecycleArchetype::Appliance);
4475                assert_eq!(spec.requires_taint(), Some(PUBLIC_IP_TAINT));
4476            }
4477            None => panic!("expected a container reference workload, got {back:?}"),
4478        }
4479    }
4480
4481    // ── Nested-sandbox grant (R636-B2) ──────────────────────────────────────
4482
4483    #[test]
4484    fn nested_sandbox_marker_is_opt_in_and_reads_back() {
4485        // The half that matters: no workload gets the grant by default, so
4486        // adding the marker cannot widen anything already deployed.
4487        let plain = archetype_test_spec("ordinary-build");
4488        assert!(!plain.wants_nested_sandbox());
4489
4490        let mut buildkit = archetype_test_spec("build-image");
4491        buildkit.annotations.insert(
4492            NESTED_SANDBOX_ANNOTATION.to_string(),
4493            NESTED_SANDBOX_VALUE.to_string(),
4494        );
4495        assert!(buildkit.wants_nested_sandbox());
4496
4497        // Fails closed on any other value, same strictness as
4498        // `wants_host_network` — a typo must not hand out CAP_SETUID.
4499        let mut typo = archetype_test_spec("typo");
4500        typo.annotations
4501            .insert(NESTED_SANDBOX_ANNOTATION.to_string(), "Nested".to_string());
4502        assert!(!typo.wants_nested_sandbox());
4503    }
4504
4505    /// The three markers are independent axes: asking for host networking or
4506    /// native exec must not imply the capability grant, and vice versa.
4507    #[test]
4508    fn nested_sandbox_marker_is_independent_of_the_other_markers() {
4509        let mut host_net = archetype_test_spec("host-net");
4510        host_net.annotations.insert(
4511            HOST_NETWORK_ANNOTATION.to_string(),
4512            HOST_NETWORK_VALUE.to_string(),
4513        );
4514        assert!(host_net.wants_host_network());
4515        assert!(!host_net.wants_nested_sandbox());
4516
4517        let mut nested = archetype_test_spec("nested");
4518        nested.annotations.insert(
4519            NESTED_SANDBOX_ANNOTATION.to_string(),
4520            NESTED_SANDBOX_VALUE.to_string(),
4521        );
4522        assert!(nested.wants_nested_sandbox());
4523        assert!(!nested.wants_host_network());
4524        assert!(!nested.wants_native_exec());
4525    }
4526
4527    // ── Native exec marker (R577-T1 / W254) ─────────────────────────────────
4528
4529    #[test]
4530    fn native_exec_marker_is_opt_in_and_reads_back() {
4531        // Default: every forge workload is a container workload. This is the
4532        // half that matters most — the marker must not silently reroute the
4533        // Linux offload leg proven live on us-west-002.
4534        let plain = archetype_test_spec("linux-build");
4535        assert!(!plain.wants_native_exec());
4536
4537        let mut native = archetype_test_spec("darwin-build");
4538        native.annotations.insert(
4539            NATIVE_EXEC_ANNOTATION.to_string(),
4540            NATIVE_EXEC_VALUE.to_string(),
4541        );
4542        assert!(native.wants_native_exec());
4543
4544        // Any other value is not the opt-in — same strictness as
4545        // `wants_host_network`, so a typo fails closed onto the container
4546        // backend rather than escaping the sandbox.
4547        let mut typo = archetype_test_spec("typo");
4548        typo.annotations
4549            .insert(NATIVE_EXEC_ANNOTATION.to_string(), "Native".to_string());
4550        assert!(!typo.wants_native_exec());
4551    }
4552
4553    #[test]
4554    fn native_marked_spec_round_trips_through_json_as_a_container_workload() {
4555        // The point of the annotation shape: a native workload is still a
4556        // `Workload::Container` on the wire, so kamaji-proto's codec, yubaba
4557        // admission and the mesh-assignment path need no new variant.
4558        let mut inner = archetype_test_spec("darwin-build");
4559        inner.annotations.insert(
4560            NATIVE_EXEC_ANNOTATION.to_string(),
4561            NATIVE_EXEC_VALUE.to_string(),
4562        );
4563        let workload = Workload::container(inner.clone());
4564
4565        let json = serde_json::to_string(&workload).expect("serialize");
4566        assert!(json.contains(NATIVE_EXEC_ANNOTATION));
4567
4568        let back: Workload = serde_json::from_str(&json).expect("deserialize");
4569        match back.container_spec() {
4570            Some(spec) => {
4571                assert_eq!(spec, &inner);
4572                assert!(spec.wants_native_exec());
4573            }
4574            None => panic!("expected a container reference workload, got {back:?}"),
4575        }
4576    }
4577
4578    // ── MicroVM marker (R605-F8 / W325 §5) ──────────────────────────────────
4579
4580    #[test]
4581    fn microvm_marker_is_opt_in_and_reads_back() {
4582        let plain = archetype_test_spec("linux-build");
4583        assert!(!plain.wants_microvm());
4584
4585        let mut vm = archetype_test_spec("isolated-build");
4586        vm.annotations.insert(
4587            NATIVE_EXEC_ANNOTATION.to_string(),
4588            MICROVM_EXEC_VALUE.to_string(),
4589        );
4590        assert!(vm.wants_microvm());
4591
4592        // Fails closed onto the container backend, like every other marker: a
4593        // typo must not be read as "boot a VM", because the deploy that would
4594        // then be refused for lack of a microVM backend is a *worse* failure
4595        // than the container run the author actually spelled.
4596        let mut typo = archetype_test_spec("typo");
4597        typo.annotations
4598            .insert(NATIVE_EXEC_ANNOTATION.to_string(), "MicroVM".to_string());
4599        assert!(!typo.wants_microvm());
4600        assert!(!typo.wants_native_exec());
4601    }
4602
4603    #[test]
4604    fn exec_substrate_markers_are_mutually_exclusive_by_construction() {
4605        // This is the property that buys R605-F8 out of a refusal branch: the
4606        // three substrates share one annotation key, so no spec can ask for two
4607        // of them. Pinned because a later "let's give microVM its own key"
4608        // refactor would silently re-open the incoherent-pair case that
4609        // `yah.sandbox` + `yah.exec = native` still has to be refused for.
4610        assert_eq!(
4611            NATIVE_EXEC_ANNOTATION, NATIVE_EXEC_ANNOTATION,
4612            "both substrate values must live on the same key"
4613        );
4614        assert_ne!(NATIVE_EXEC_VALUE, MICROVM_EXEC_VALUE);
4615
4616        for value in [NATIVE_EXEC_VALUE, MICROVM_EXEC_VALUE, "", "container"] {
4617            let mut spec = archetype_test_spec("substrate");
4618            spec.annotations
4619                .insert(NATIVE_EXEC_ANNOTATION.to_string(), value.to_string());
4620            assert!(
4621                !(spec.wants_native_exec() && spec.wants_microvm()),
4622                "yah.exec={value:?} selected two substrates at once"
4623            );
4624        }
4625    }
4626
4627    #[test]
4628    fn microvm_marked_spec_round_trips_through_json_as_a_container_workload() {
4629        // Same zero-blast-radius claim as the native case: a microVM workload
4630        // is still `Workload::Container` on the wire, so kamaji-proto's codec
4631        // gains no variant and its positional postcard encoding does not move.
4632        let mut inner = archetype_test_spec("isolated-build");
4633        inner.annotations.insert(
4634            NATIVE_EXEC_ANNOTATION.to_string(),
4635            MICROVM_EXEC_VALUE.to_string(),
4636        );
4637        let workload = Workload::container(inner.clone());
4638
4639        let json = serde_json::to_string(&workload).expect("serialize");
4640        assert!(json.contains(MICROVM_EXEC_VALUE));
4641
4642        let back: Workload = serde_json::from_str(&json).expect("deserialize");
4643        match back.container_spec() {
4644            Some(spec) => {
4645                assert_eq!(spec, &inner);
4646                assert!(spec.wants_microvm());
4647                assert!(!spec.wants_native_exec());
4648            }
4649            None => panic!("expected a container reference workload, got {back:?}"),
4650        }
4651    }
4652}