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:at(2026-07-20T23:52:55Z)
240//! @yah:status(open)
241//! @yah:parent(R546)
242//! @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.")
243//! @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.")
244//! @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.")
245//! @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.")
246//! @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.")
247//! @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.")
248//!
249//! @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)")
250//! @yah:status(review)
251//! @yah:assignee(agent:bundle-anthropic-glimmerstone)
252//! @yah:at(2026-07-23T17:47:24Z)
253//! @yah:kind(spike)
254//! @yah:phase(P3)
255//! @yah:parent(R626)
256//! @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.")
257//! @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.")
258//! @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.")
259//! @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.")
260//! @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.")
261//! @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.")
262//! @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'.")
263//! @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.")
264//! @yah:next("Wire DesiredStateStore::forget into the undeclare path so the document doesn't accumulate intent for mirrors that no longer exist.")
265//! @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")
266//! @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)")
267//! @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.")
268//! @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.")
269//! @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).")
270//!
271
272use std::collections::BTreeMap;
273use std::collections::HashMap;
274use std::path::PathBuf;
275
276use serde::{Deserialize, Serialize};
277use ts_rs::TS;
278
279pub mod compose_import;
280pub mod control_plane_install;
281pub mod rollout;
282pub mod secrets;
283pub mod validate;
284mod version;
285
286pub use version::SchemaVersion;
287
288// ── Duration ──────────────────────────────────────────────────────────────────
289
290/// Duration expressed as an integer millisecond count.
291///
292/// Used for healthcheck intervals, timeouts, delays, and stop grace periods.
293/// Chosen over `std::time::Duration` to keep serde support dependency-free.
294#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, TS)]
295#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
296#[ts(type = "number")]
297pub struct Millis(pub u64);
298
299impl Millis {
300    pub fn from_secs(s: u64) -> Self {
301        Self(s * 1000)
302    }
303
304    pub fn from_ms(ms: u64) -> Self {
305        Self(ms)
306    }
307
308    pub fn as_ms(self) -> u64 {
309        self.0
310    }
311
312    pub fn as_secs_f64(self) -> f64 {
313        self.0 as f64 / 1000.0
314    }
315}
316
317// ── Primitive newtypes ────────────────────────────────────────────────────────
318
319/// Opaque identifier for a yubaba-managed machine within the cluster.
320///
321/// Used by the semantic validation layer for admission-control capacity checks.
322/// Yubaba passes its own machine ID when validating a spec before deployment.
323#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TS)]
324#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
325pub struct MachineId(pub String);
326
327/// DNS-segment identity for a workload on the cluster mesh, e.g.
328/// `"noisetable-api.pdx"`. Regex constraint: `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`,
329/// length ≤ 63. Enforced in shape validation (R090-F2).
330#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
331#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
332pub struct MeshIdent(pub String);
333
334/// Tier classification that governs admission control and mesh `allow_from`
335/// filtering. Known values: `"public"`, `"tenant"`, `"private"`, `"infra"`.
336/// Custom tiers are allowed per cluster; shape validation warns on unknowns
337/// rather than rejecting them (R090-F2).
338#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
339#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
340pub struct TierTag(pub String);
341
342/// Default single-tenant identity written to specs that predate the tenant
343/// axis (W206). Its concrete string is arbitrary — what matters is that a
344/// single-tenant cluster only ever sees this one value, so every per-tenant
345/// isolation primitive collapses to a no-op. See [`TenantId::singleton`].
346pub const DEFAULT_TENANT: &str = "default";
347
348/// Default single-namespace identity for specs that predate the namespace
349/// axis (W206). See [`NamespaceId::singleton`].
350pub const DEFAULT_NAMESPACE: &str = "default";
351
352/// Tenant **isolation** axis (W206). Separates one operator's workloads from
353/// another's at the network / DB / mesh-identity level. Orthogonal to
354/// [`NamespaceId`] (routing/naming) and [`TierTag`] (workload class within a
355/// `(tenant, namespace)` pair).
356///
357/// **Degenerate case:** when a yubaba reconciler sees only one `TenantId`
358/// across every workload on a machine, per-tenant Podman networks collapse
359/// into the shared tier networks, the tenant prefix on mesh identity is
360/// dropped, and PostgreSQL role separation is skipped — isolation primitives
361/// become no-ops. You pay only when more than one tenant is present. Specs
362/// written before this axis existed deserialize to [`TenantId::singleton`].
363#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, TS)]
364#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
365pub struct TenantId(pub String);
366
367impl TenantId {
368    /// The singleton tenant used for back-compat with single-tenant (current)
369    /// deployments. Specs written before the tenant axis existed deserialize
370    /// to this value via the `#[serde(default)]` on [`WorkloadSpec::tenant`],
371    /// keeping the whole cluster single-tenant so every isolation primitive
372    /// stays a no-op.
373    pub fn singleton() -> Self {
374        Self(DEFAULT_TENANT.to_string())
375    }
376
377    /// Whether this is the singleton (degenerate single-tenant) identity.
378    pub fn is_singleton(&self) -> bool {
379        self.0 == DEFAULT_TENANT
380    }
381}
382
383/// Namespace **routing/naming** axis (W206). A pure naming key that never
384/// affects isolation: it selects the config root, disambiguates service DNS
385/// names within a tenant, prefixes object-store bucket names within a tenant's
386/// bucket scope, and selects the provider zone (e.g. `noisetable.com` vs
387/// `yah.dev`). Two namespaces in the same tenant share networks, mesh-identity
388/// space, and PG cluster — they simply cannot collide on workload names or
389/// external domains. Specs written before this axis existed deserialize to
390/// [`NamespaceId::singleton`].
391#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, TS)]
392#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
393pub struct NamespaceId(pub String);
394
395impl NamespaceId {
396    /// The singleton namespace used for back-compat with single-namespace
397    /// (current) deployments. Specs written before the namespace axis existed
398    /// deserialize to this value via the `#[serde(default)]` on
399    /// [`WorkloadSpec::namespace`].
400    pub fn singleton() -> Self {
401        Self(DEFAULT_NAMESPACE.to_string())
402    }
403
404    /// Whether this is the singleton (degenerate single-namespace) identity.
405    pub fn is_singleton(&self) -> bool {
406        self.0 == DEFAULT_NAMESPACE
407    }
408}
409
410// ── Workload (on-disk envelope) ──────────────────────────────────────────────
411
412/// On-disk `workload.toml` manifest. Each variant matches one
413/// `ServiceComponent.kind` value; the `kind` field on the wire is the serde
414/// discriminator.
415///
416/// This is the **on-disk** envelope — distinct from [`WorkloadSpec`], the
417/// containerd wire format yubaba receives over RPC. A `kind = "container"`
418/// workload deserializes its remaining fields as a `WorkloadSpec`; other
419/// kinds carry their own per-reconciler payload shape.
420///
421/// **Never put `#[serde(skip_serializing_if = "Option::is_none")]` on a field
422/// of this enum or any type it reaches.** These types ride the kamaji-proto
423/// **postcard** wire, which is non-self-describing and positional:
424/// `skip_serializing_if` omits the field's byte on serialize while decode still
425/// expects to read it at that offset, so the byte stream misaligns and the
426/// round-trip fails. Use `#[serde(default)]` + `#[ts(optional = nullable)]`
427/// instead — that still gives TOML/JSON back-compat (missing field → `None`)
428/// while the field is always encoded. `MesofactStaticWorkload::ssr_runtime` and
429/// `::serve_bundle` are the reference shape.
430#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
431#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
432#[serde(rename_all = "kebab-case")]
433pub enum Workload {
434    /// Static-site build that publishes an artifact directory to the
435    /// service's `static` provider slot. Reconciled by the
436    /// `mesofact-static` reconciler — does not deploy to yubaba.
437    MesofactStatic(MesofactStaticWorkload),
438
439    /// Containerd workload handed to yubaba over RPC. The inline fields
440    /// are the full [`WorkloadSpec`] minus the `kind` discriminator.
441    ///
442    /// This is also the shape of the W267 sovereign-public-ingress appliance
443    /// (R594-F2): a container-kind workload with `archetype =
444    /// Some(LifecycleArchetype::Appliance)` and
445    /// `requires_taint() == Some(PUBLIC_IP_TAINT)`, **not** a dedicated
446    /// `Workload::ingress(..)` variant. It runs an ordinary OCI image (the
447    /// `passway` proxy, R594-F4) supervised by kamaji exactly like any other
448    /// `Container`, so no admission-list or wire-codec change was needed to
449    /// let kamaji accept it. A new enum variant would have forced an
450    /// exhaustive-match update in every `Workload` consumer, including
451    /// peer-owned `kamaji-proto/src/codec.rs` — the archetype + annotation
452    /// combination expresses "this is the public ingress appliance" without
453    /// that blast radius. See [`WorkloadSpec::requires_taint`] and
454    /// [`LifecycleArchetype::Appliance`].
455    Container(WorkloadSpec),
456
457    /// Data-pipeline job with declared I/O and a readiness policy. The
458    /// orchestrator checks all `inputs` are reachable before each run and
459    /// verifies `outputs` afterward. Generalises the OpenRouter JSON-cache
460    /// refresher (`spawn_almanac_refresher`) to the full manifest form.
461    Almanac(AlmanacManifest),
462
463    /// Content-addressed static files uploaded to the mirror's `object_store`
464    /// provider slot. Wave-0 by default — gating mesofact and container waves.
465    /// Rollback is a pointer-flip via `mirror.toml [asset_aliases]`; bytes are
466    /// append-only and never re-pushed on rollback. See W160.
467    StaticAsset(StaticAssetWorkload),
468}
469
470/// `kind = "mesofact-static"` payload — static-site build colocated with the
471/// frontend it deploys.
472///
473/// The two-role model (R256-F7): a build/publish step plus an optional
474/// SSR/SPA runtime companion. The build step is always transient (runs once,
475/// publishes, exits). The companion is long-lived and only present when the
476/// app has dynamic/server-rendered pages; pure static sites leave it `None`.
477#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
478#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
479pub struct MesofactStaticWorkload {
480    /// Wire-format version. Always `V1` today.
481    pub schema_version: SchemaVersion,
482
483    /// Build command + output directory.
484    pub build: BuildConfig,
485
486    /// Path (relative to the manifest) of the routes module the
487    /// `mesofact-static` reconciler reads to enumerate routes.
488    pub routes: PathBuf,
489
490    /// Where the build command runs. Default: `HostSide` (mesofact-dev on the
491    /// host). Set to `InContainer` for cloud/HA where no host watcher is
492    /// present and CI-fidelity build environments are required.
493    #[serde(default)]
494    pub build_mode: BuildMode,
495
496    /// Optional SSR/SPA runtime companion container.
497    ///
498    /// `None` → pure static site; Caddy (or equivalent CDN) serves all
499    /// requests directly from the object store. This is the common case for
500    /// dev-yah today.
501    ///
502    /// `Some` → the workload spec describes a long-lived container that
503    /// handles dynamic/SSR requests. Caddy routes static asset paths to
504    /// the object store and all other paths to this container. The companion
505    /// uses `RestartPolicy::Always`; the orchestrator (camp or yubaba)
506    /// ensures it stays up alongside the Caddy edge.
507    #[ts(optional = nullable)]
508    pub ssr_runtime: Option<WorkloadSpec>,
509
510    /// Serve-time reference to a published W272 bundle (R599-F4).
511    ///
512    /// `Some` → the built app is deployed as a content-addressed bundle that
513    /// kamaji materializes from the bundle store (R599-F1) and serves via its
514    /// native backend, instead of (or in addition to) the build reconciler
515    /// pushing `dist/` to the object-store/CDN. `None` → legacy
516    /// build-and-publish-only workload — kamaji rejects that form as yubaba's
517    /// `mesofact-static` reconciler's responsibility.
518    ///
519    /// No `skip_serializing_if`: like `ssr_runtime`, this field is always
520    /// encoded so the postcard wire codec (non-self-describing, positional)
521    /// round-trips — `skip_serializing_if` would omit the byte on serialize
522    /// while decode still expects it. `#[serde(default)]` keeps every existing
523    /// `mesofact-static` TOML/JSON that predates this field parsing to `None`.
524    #[serde(default)]
525    #[ts(optional = nullable)]
526    pub serve_bundle: Option<MesofactServeBundle>,
527}
528
529/// Serve-time reference to a published W272 bundle (R599-F4) — the
530/// `{bundle_digest, runtime, lifecycle}` triple a `mesofact-static` workload
531/// carries when kamaji, not the build reconciler, serves it.
532#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
533#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
534pub struct MesofactServeBundle {
535    /// BLAKE3 digest of the published bundle manifest — the content-address
536    /// kamaji materializes from the bundle store (`yah_mesofact_bundle`,
537    /// R599-F1). Same 64-hex shape the bundle crate's `BundleHash` validates.
538    pub digest: BlakeHash,
539
540    /// Runtime that serves the bundle: `"self"` (bundle ships its own
541    /// `bins/<triple>/serve`) or `"mesofact/<version>"` (resolve the stock
542    /// serve runtime asset from the node cache). Wire-mirrors
543    /// `yah_mesofact_bundle::BundleRuntime`; kept as a plain `String` here so
544    /// workload-spec stays free of the bundle crate and its non-TS/schema
545    /// newtypes.
546    pub runtime: String,
547
548    /// How kamaji supervises the served bundle. Default: keep-alive.
549    #[serde(default)]
550    pub lifecycle: BundleLifecycle,
551}
552
553/// Lifecycle mode for a served bundle (W272 §3).
554#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
555#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
556#[serde(rename_all = "snake_case")]
557pub enum BundleLifecycle {
558    /// Fork at deploy, keep resident, restart per policy — today's server
559    /// archetype. Memory is resident for the workload's lifetime.
560    KeepAlive,
561
562    /// Kamaji owns the listen socket, forks the runtime on the first connection
563    /// (fd-passing), and reaps it after `idle_ttl` with zero connections — the
564    /// "serverless" tier (zero memory when idle). The JIT fork/reap mechanics
565    /// land in R599-F6; this variant only declares the intent + budget.
566    OnDemand {
567        /// Idle time with no live connections before kamaji reaps the process.
568        idle_ttl: Millis,
569    },
570}
571
572impl Default for BundleLifecycle {
573    /// Keep-alive — the resident server archetype — matches the current
574    /// deploy-and-supervise default.
575    fn default() -> Self {
576        BundleLifecycle::KeepAlive
577    }
578}
579
580/// Build step that produces the static artifact published by a
581/// `mesofact-static` workload.
582#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
583#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
584pub struct BuildConfig {
585    /// Shell command run from the manifest's directory, e.g. `"bun run build"`.
586    pub command: String,
587
588    /// Output directory (relative to the manifest) the reconciler uploads.
589    pub out_dir: PathBuf,
590
591    /// Data-only re-render command (W225 §3 "revalidate"), run from the
592    /// manifest's directory against the **already-built** `out_dir` — no
593    /// bundler. `{route}` is substituted with the invalidated route pattern,
594    /// e.g. `"cargo run -p mesofact-build -- render . --route {route} --all"`.
595    /// Absent → a revalidate dispatch republishes `out_dir` as-is.
596    #[serde(default)]
597    pub render_command: Option<String>,
598}
599
600// ── BuildMode ─────────────────────────────────────────────────────────────────
601
602/// Where the build command runs for a `mesofact-static` workload.
603///
604/// The two-role split encodes the F7 design decision: build/publish is a
605/// **transient job** (runs once, exits, GC'd); SSR/SPA serving is a separate
606/// **long-lived companion container** (optional, only for dynamic pages). A
607/// single merged "mesofact container" is the trap — in cloud, CI builds the
608/// artifact, R2+CDN serve it, and a distinct worker handles any SSR.
609///
610/// Default: `HostSide` — mesofact-dev runs the build on the host and publishes
611/// to the tier's object store. No container overhead; compatible with dev and
612/// sim tiers.
613#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
614#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
615#[serde(rename_all = "snake_case")]
616pub enum BuildMode {
617    /// Build command runs on the host (mesofact-dev watcher). The watcher
618    /// publishes the output to the tier's object store (DistPointer for dev,
619    /// MinIO for sim). Compatible with all tiers; zero container overhead.
620    #[default]
621    HostSide,
622
623    /// Build runs inside a transient container matching the CI image. Higher
624    /// fidelity (environment matches CI exactly); costs image pull +
625    /// container cold-start. Required for cloud/HA where no mesofact-dev
626    /// watcher is running on the host.
627    InContainer {
628        /// Container image that runs the build (e.g. `"ghcr.io/org/app-build:v1.2"`).
629        /// Must have the build toolchain installed. The container is started with
630        /// the workspace root bind-mounted, runs `build.command`, uploads
631        /// `build.out_dir` to the object store, then exits.
632        image: ImageRef,
633    },
634}
635
636// ── AlmanacManifest ───────────────────────────────────────────────────────────
637
638/// An observable endpoint the almanac scheduler probes to check readiness.
639///
640/// Used for both inputs (checked before the run) and outputs (verified after
641/// a successful run to confirm the job produced something reachable).
642/// The probe is intentionally lightweight — no S3 SigV4, no xlb-net discovery
643/// required; a simple TCP connect or HTTP GET is enough for the dev/sim tier.
644#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
645#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
646#[serde(rename_all = "snake_case")]
647pub enum AlmanacTarget {
648    /// Issue an HTTP GET to `url`; ready when the server responds with
649    /// `expect_status` (default: any 2xx).
650    Http {
651        url: String,
652        #[ts(optional = nullable)]
653        expect_status: Option<u16>,
654    },
655
656    /// Establish a TCP connection to `host:port`; ready when the connect
657    /// succeeds. Used for non-HTTP services (e.g. MinIO API on port 9000)
658    /// and as a lighter probe when an HTTP endpoint isn't stable yet.
659    Tcp { host: String, port: u16 },
660}
661
662/// What the almanac scheduler does when a precondition check fails.
663///
664/// The F9 design decision: `WaitWithTimeout` is the default. Fail-fast is
665/// too brittle for the sim tier (containers may still be cold-starting);
666/// requeue-with-no-ceiling can block the scheduler indefinitely. The
667/// recommended timeout for sim is the container spinup budget (~5 s cold,
668/// ~1 s warm): set `timeout` to a few seconds, then let the retry cadence
669/// handle transient glitches.
670#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
671#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
672#[serde(rename_all = "snake_case")]
673pub enum NotReadyPolicy {
674    /// Wait up to `timeout` for all preconditions to pass before aborting
675    /// the run. The run is skipped (not rescheduled); the next cadence tick
676    /// will retry. Suitable when targets occasionally lag at startup.
677    WaitWithTimeout {
678        /// How long to wait for each precondition to become reachable. The
679        /// scheduler polls with a short sleep between attempts.
680        timeout: Millis,
681    },
682
683    /// Abort immediately if any precondition check fails. Suitable for
684    /// integration-test harnesses where a missing dependency is always a
685    /// hard error.
686    FailFast,
687
688    /// Requeue with exponential backoff up to `max_attempts` times. After
689    /// exhaustion the run is marked failed. Suitable for cloud/HA where
690    /// transient dependency outages are expected.
691    Requeue {
692        /// Maximum number of requeue attempts before the run is marked failed.
693        max_attempts: u32,
694        /// Initial backoff between attempts, in milliseconds.
695        backoff: Millis,
696    },
697}
698
699impl Default for NotReadyPolicy {
700    /// Default is `WaitWithTimeout { timeout: 5 seconds }` — matches the
701    /// container spinup budget for the sim tier (few-second cold, sub-second warm).
702    fn default() -> Self {
703        Self::WaitWithTimeout { timeout: Millis::from_secs(5) }
704    }
705}
706
707/// When the almanac scheduler triggers a run.
708#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
709#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
710#[serde(rename_all = "snake_case")]
711pub enum Cadence {
712    /// Run once at first opportunity, then never again.
713    Once,
714
715    /// Run repeatedly with a fixed interval between the end of one run and
716    /// the start of the next. Equivalent to `sleep N && run` in a loop.
717    Every {
718        /// Minimum time between consecutive run completions.
719        interval: Millis,
720    },
721
722    /// Run on a UTC cron schedule (standard 5-field expression, e.g.
723    /// `"0 */6 * * *"` for every 6 hours). The scheduler evaluates the
724    /// expression relative to UTC midnight.
725    Cron { expression: String },
726}
727
728/// `kind = "almanac"` manifest — a declared data-pipeline job.
729///
730/// An almanac job is the generalisation of the OpenRouter refresher
731/// (`spawn_almanac_refresher`): it declares its I/O contract explicitly so
732/// the orchestrator can enforce preconditions before each run and verify
733/// outputs afterward. The degenerate case (no inputs, no app target, cron
734/// schedule) is exactly the OpenRouter JSON-cache refresher.
735///
736/// Lifecycle:
737/// 1. Cadence tick fires.
738/// 2. Scheduler probes every `inputs` target. If any fail → apply
739///    `not_ready_policy`.
740/// 3. Command runs (`sh -c command` from the workload directory).
741/// 4. Scheduler probes every `outputs` target. Failure → mark run as
742///    failed but do not retry.
743/// 5. Any workloads listed in `invalidates` receive a cache-bust signal
744///    (implementation detail of the orchestrator; in camp this is a
745///    rebuild trigger on the mesofact-dev watcher).
746#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
747#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
748pub struct AlmanacManifest {
749    /// Wire-format version. Always `V1` today.
750    pub schema_version: SchemaVersion,
751
752    /// Shell command executed via `sh -c` from the workload directory.
753    pub command: String,
754
755    /// When to run.
756    pub cadence: Cadence,
757
758    /// Input targets that must be reachable before the command runs.
759    /// Empty list → no precondition checks (degenerate case).
760    #[serde(default)]
761    pub inputs: Vec<AlmanacTarget>,
762
763    /// Output targets verified after a successful run.
764    /// Empty list → no post-run verification.
765    #[serde(default)]
766    pub outputs: Vec<AlmanacTarget>,
767
768    /// What to do when a precondition check fails.
769    /// Default: `WaitWithTimeout { timeout: 5000ms }`.
770    #[serde(default)]
771    pub not_ready_policy: NotReadyPolicy,
772
773    /// Mesh identities of workloads to notify after a successful run.
774    /// The orchestrator sends a cache-bust signal to each entry so
775    /// downstream consumers can reload their data (e.g. mesofact-dev
776    /// triggers a rebuild when the OpenRouter cache refreshes).
777    /// Empty list → no downstream invalidation.
778    #[serde(default)]
779    pub invalidates: Vec<MeshIdent>,
780}
781
782// ── StaticAssetWorkload ───────────────────────────────────────────────────────
783
784/// BLAKE3 content hash expressed as exactly 64 ASCII hex digits.
785///
786/// This is the content-address key for every file in the static-asset catalog.
787/// Deserialization rejects values that do not conform — 64 hex chars, case
788/// insensitive. Mismatch between the recorded hash and the source file halts
789/// the upload step in the reconciler.
790#[derive(Debug, Clone, PartialEq, Eq, Serialize, TS)]
791#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
792#[ts(type = "string")]
793pub struct BlakeHash(pub String);
794
795impl<'de> Deserialize<'de> for BlakeHash {
796    fn deserialize<D>(de: D) -> Result<Self, D::Error>
797    where
798        D: serde::Deserializer<'de>,
799    {
800        let s = String::deserialize(de)?;
801        if s.len() != 64 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
802            return Err(serde::de::Error::custom(format!(
803                "blake3 hash must be exactly 64 hex digits, got {:?}",
804                s
805            )));
806        }
807        Ok(BlakeHash(s))
808    }
809}
810
811// ── License & FetchSource (W164) ──────────────────────────────────────────────
812
813/// Closed-set, parse-time-enforced license tag. Mirrors the workspace
814/// permissive-license rule (MIT / Apache-2.0 / BSD-2/3-Clause / ISC). Adding a
815/// variant is an explicit schema change — non-permissive strings
816/// (`"GPL-3.0"`, `"AGPL"`, etc.) fail at serde-deserialize before any shape
817/// validator runs.
818///
819/// Shared between `asset.derive.fetch.license` (W164, required) and a future
820/// `almanac::ReleaseSource.license` migration (R438-F10, optional).
821#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
822#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
823#[serde(rename_all = "kebab-case")]
824pub enum License {
825    Mit,
826    Apache2,
827    Bsd2Clause,
828    Bsd3Clause,
829    Isc,
830}
831
832/// Shared fetch primitive — usable by `asset.derive` today, and by Almanac's
833/// `ReleaseSource` after a follow-up migration (R438-F10). Defined once in
834/// workload-spec so both consumers reject the same set of non-permissive
835/// licenses.
836///
837/// The `blake3` hash pins the upstream bytes; mismatch at fetch time is a hard
838/// error in the reconciler. The `license` field is **required** here — every
839/// derived asset must declare its upstream license. If/when Almanac adopts
840/// `FetchSource`, the Almanac side may wrap this in a struct with
841/// `Option<License>` since release manifests have no distribution license per
842/// se.
843#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
844#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
845pub struct FetchSource {
846    /// Upstream URL fetched verbatim. Reconciler retry policy is configured
847    /// elsewhere (R438-F11); the URL itself is opaque to workload-spec.
848    pub url: String,
849
850    /// Expected BLAKE3 hash of the fetched bytes (64 hex characters). The
851    /// reconciler verifies this after download and aborts on mismatch.
852    pub blake3: BlakeHash,
853
854    /// Upstream license. Closed-set, parse-time enforced.
855    pub license: License,
856}
857
858/// Optional transform applied after a [`FetchSource`] download, lowering to a
859/// `ForgeCommand::Subprocess` via the recipe loader (R438-T4). The transform's
860/// output is content-addressed by the entry's `blake3` (the recipe runs only
861/// when the cache misses).
862#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
863#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
864pub struct TransformSpec {
865    /// Named recipe under `.yah/qed/transforms/<recipe>.toml`. Loader rejects
866    /// missing recipes at materialize time.
867    pub recipe: String,
868
869    /// `{{key}}` substitutions passed to the recipe argv at element
870    /// granularity (no shell, no string concat). Empty when the recipe is
871    /// fully parameterless.
872    #[serde(default)]
873    pub params: BTreeMap<String, String>,
874}
875
876/// W212/R518: the committed derivation lock — the in-tree action-cache
877/// receipt. `input_hash` is the input-addressed derivation key computed over
878/// the complete declared input set (fetched-input pin ⊕ recipe-file bytes ⊕
879/// invocation params ⊕ schema version); `output_blake3` is what those inputs
880/// produced (== the entry's `blake3`). The reconciler skips the entire build
881/// (no fetch, no transform, no PUT) when the lock matches the inputs recomputed
882/// from the current pins and the bucket already holds the output — the
883/// Nix-substituter / Bazel-remote-cache behaviour. Written by the R510 bind
884/// path from the reconciler's `discovered_input_hash:<filename>` output; the
885/// `git diff` on this block is the receipt that the derivation rolled.
886#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
887#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
888pub struct DeriveLock {
889    /// Input-addressed derivation key (BLAKE3 hex). A change to any declared
890    /// input flips this, so a stale lock never produces a false skip.
891    pub input_hash: String,
892    /// Output the locked inputs produced (BLAKE3 hex; equals the entry's
893    /// `blake3`). Carried so the lock is a self-contained action-cache entry.
894    pub output_blake3: String,
895}
896
897/// Provenance chain for a derived asset: required `fetch` step, optional
898/// `transform` step. Materialized bytes replace `AssetEntry.source` for the
899/// rest of the static-asset reconcile loop.
900#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
901#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
902pub struct AssetDerive {
903    /// Upstream fetch — URL + content-pin + license.
904    pub fetch: FetchSource,
905
906    /// Post-fetch transform. `None` → the fetched bytes ARE the asset
907    /// (entry `blake3` must match fetch `blake3`).
908    #[serde(default)]
909    #[ts(optional = nullable)]
910    pub transform: Option<TransformSpec>,
911
912    /// W212/R518: committed derivation lock (input-addressed action-cache
913    /// receipt). Absent until the first successful build writes it via the
914    /// bind path. When present and current, enables the substituter-style
915    /// build skip.
916    #[serde(default)]
917    #[ts(optional = nullable)]
918    pub lock: Option<DeriveLock>,
919}
920
921/// A single file entry in the static-asset catalog.
922///
923/// One `[[asset]]` row per bucket object. Multiple rows for different variants
924/// (e.g. q5 and q4 whisper models) are fine — each declares its own filename
925/// and hash. The reconciler treats the catalog as exhaustive and append-only:
926/// new rows trigger a PUT; removed rows surface as drift (never a DELETE).
927///
928/// **Source-vs-derive XOR.** Exactly one of `source` or `derive` must be set.
929/// Legacy local-bytes assets keep `source = "..."`; W164 derived assets set
930/// `[asset.derive]` instead. [`validate::shape_static_asset`] enforces the
931/// XOR; both-set and neither-set are hard `ShapeError::Field`.
932#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
933#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
934pub struct AssetEntry {
935    /// Destination path within the bucket, e.g.
936    /// `"whisper/distil-large-v3-q5_1.bin"`. Must be unique in the catalog.
937    /// Used as the S3 object key by the reconciler.
938    pub filename: String,
939
940    /// Path to a local source file, relative to the `workload.toml` directory.
941    /// Mutually exclusive with `derive`.
942    #[serde(default)]
943    #[ts(optional = nullable)]
944    pub source: Option<PathBuf>,
945
946    /// Declared fetch (+ optional transform) provenance chain. The reconciler
947    /// materializes the bytes into a content-addressed cache; the cache path
948    /// then replaces `source` for the rest of the upload pipeline. Mutually
949    /// exclusive with `source`.
950    #[serde(default)]
951    #[ts(optional = nullable)]
952    pub derive: Option<AssetDerive>,
953
954    /// Expected BLAKE3 hash of the *final* asset bytes (64 hex characters).
955    /// For `source` mode, this is hashed before upload. For `derive` mode,
956    /// it's the post-transform (or post-fetch when no transform) output.
957    /// Mismatch aborts the upload.
958    pub blake3: BlakeHash,
959}
960
961/// `kind = "static-asset"` payload — content-addressed bucket catalog.
962///
963/// The reconciler makes the bucket match the `[[asset]]` list exactly
964/// (append-only: new rows → PUT; removed rows → drift report, not DELETE).
965/// Rollback is pointer-flip via `mirror.toml [asset_aliases]` — bytes never
966/// move during rollback.
967///
968/// **Closed-catalog invariant**: every value in `[aliases]` must be a
969/// `filename` that exists in `[[asset]]`. Enforced by
970/// [`validate::shape_static_asset`]. Mirror overrides (`[asset_aliases]` in
971/// `mirror.toml`) are bound by the same rule — the alias graph can only
972/// resolve to filenames already in the catalog.
973#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
974#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
975pub struct StaticAssetWorkload {
976    /// Wire-format version. Always `V1` today.
977    pub schema_version: SchemaVersion,
978
979    /// Exhaustive catalog of files this component manages in the bucket.
980    ///
981    /// Named `asset` on disk (TOML `[[asset]]` array-of-tables) to follow TOML
982    /// convention; accessed as `.assets` in Rust code.
983    #[serde(rename = "asset", default)]
984    pub assets: Vec<AssetEntry>,
985
986    /// Canonical logical-name → filename mappings for this component.
987    ///
988    /// Values must be filenames present in `assets` — validated by
989    /// [`validate::shape_static_asset`]. Mirror files may override individual
990    /// entries via `[asset_aliases]` but may never reference filenames absent
991    /// from this catalog.
992    #[serde(default)]
993    pub aliases: BTreeMap<String, String>,
994}
995
996// ── Lifecycle archetype (R572-F1 / W244) ───────────────────────────────────────
997
998/// Explicit lifecycle archetype for a `kind = "container"` workload (W244).
999///
1000/// The question that actually matters to a scheduler: *"can I kill this and
1001/// recreate it somewhere else?"* Before this field existed, the answer was
1002/// inferred per-spec from `volumes.is_empty()` + `restart_policy` — fragile
1003/// absence-as-policy, the same trap W243 calls out on the node-taint side.
1004/// This type makes the answer structural instead of guessed.
1005///
1006/// This ticket (R572-F1) adds the discriminator only. The reconciler does not
1007/// yet branch on it (R572-F4) and neither does the scheduler (R572-F5).
1008#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
1009#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1010#[serde(rename_all = "kebab-case")]
1011pub enum LifecycleArchetype {
1012    /// k8s analogue: Deployment. Stateless and fungible — the scheduler may
1013    /// move it, scale it to N replicas, or restart it on a different node
1014    /// with zero consequence. Drainable.
1015    Server,
1016
1017    /// k8s analogue: StatefulSet. Stable identity + a volume that must
1018    /// follow it; at most one live instance. Not drainable — the reconciler
1019    /// must not schedule it onto a different node. Example: a postgres peer,
1020    /// headscale (W267/R591).
1021    Appliance,
1022
1023    /// k8s analogue: Job. Runs to completion with declared inputs/outputs,
1024    /// then is gone — no steady-state identity. `almanac` is the first
1025    /// job-family member; forge runs (`WorkloadSpec::for_forge`, used by QED)
1026    /// are the `container`-kind instance of this archetype.
1027    Job,
1028}
1029
1030impl LifecycleArchetype {
1031    /// The repel-taint key for this archetype (R572-F5). A node carrying the
1032    /// taint `"no-<key>"` repels workloads of this class unless they
1033    /// explicitly tolerate it.
1034    ///
1035    /// Examples: `Server` → `"server"` (repelled by `"no-server"`);
1036    /// `Appliance` → `"appliance"` (repelled by `"no-appliance"`).
1037    pub fn taint_key(&self) -> &'static str {
1038        match self {
1039            Self::Server => "server",
1040            Self::Appliance => "appliance",
1041            Self::Job => "job",
1042        }
1043    }
1044
1045    /// The pre-R572 inference this field replaces, kept only to give
1046    /// `WorkloadSpec::effective_archetype` a behavior-preserving fallback for
1047    /// specs written before this field existed (`archetype: None`).
1048    ///
1049    /// A volume that must follow the workload is the strongest signal of
1050    /// durable state → [`Self::Appliance`]. Absent that, `RestartPolicy::Never`
1051    /// is the existing forge/run-once convention (see
1052    /// [`RestartPolicy::Never`]'s doc comment) → [`Self::Job`]. Everything
1053    /// else defaults to the common case, [`Self::Server`].
1054    fn infer(volumes: &[VolumeMount], restart_policy: &RestartPolicy) -> Self {
1055        if !volumes.is_empty() {
1056            LifecycleArchetype::Appliance
1057        } else if matches!(restart_policy, RestartPolicy::Never) {
1058            LifecycleArchetype::Job
1059        } else {
1060            LifecycleArchetype::Server
1061        }
1062    }
1063}
1064
1065// ── WorkloadSpec ──────────────────────────────────────────────────────────────
1066
1067/// Complete typed description of a containerd workload handed to yubaba over
1068/// RPC. This is also the payload of the `kind = "container"` variant of
1069/// [`Workload`] on disk.
1070///
1071/// Yubaba never accepts compose YAML on its RPC surface — agents, the desktop,
1072/// and operator CLIs all hand yubaba `WorkloadSpec` values. See the arch doc
1073/// for the validation layers and evolution rules.
1074#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1075#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1076pub struct WorkloadSpec {
1077    /// Wire-format version; always `V1` today. Present at the top level so
1078    /// rolling clusters can detect and migrate across schema generations.
1079    pub schema_version: SchemaVersion,
1080
1081    /// DNS-friendly workload name, e.g. `"noisetable-api"`. Regex:
1082    /// `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`, length ≤ 63.
1083    pub name: String,
1084
1085    /// Container image to pull.
1086    pub image: ImageRef,
1087
1088    /// Tier tag controlling admission control and mesh filtering.
1089    pub tier: TierTag,
1090
1091    /// Tenant **isolation** axis (W206). Separates operators' workloads at the
1092    /// network / DB / mesh-identity level. Defaults to [`TenantId::singleton`]
1093    /// for specs that predate the axis, so single-tenant clusters keep every
1094    /// isolation primitive a no-op. Orthogonal to [`Self::tier`] (class) and
1095    /// [`Self::namespace`] (routing).
1096    #[serde(default = "TenantId::singleton")]
1097    pub tenant: TenantId,
1098
1099    /// Namespace **routing/naming** axis (W206). A pure naming key — never
1100    /// affects isolation; disambiguates DNS names and selects config root /
1101    /// provider zone within a tenant. Defaults to [`NamespaceId::singleton`].
1102    #[serde(default = "NamespaceId::singleton")]
1103    pub namespace: NamespaceId,
1104
1105    /// Target replica count. `0` registers the workload without deploying it.
1106    /// Range: 0–100 (cluster-wide cap; operator can raise it).
1107    pub replicas: u32,
1108
1109    /// Override the image's `CMD`. `None` leaves the image default.
1110    #[ts(optional = nullable)]
1111    pub command: Option<Vec<String>>,
1112
1113    /// Override the image's `ENTRYPOINT`. `None` leaves the image default.
1114    #[ts(optional = nullable)]
1115    pub entrypoint: Option<Vec<String>>,
1116
1117    /// Working directory inside the container.
1118    #[ts(optional = nullable)]
1119    pub workdir: Option<PathBuf>,
1120
1121    /// User to run as, e.g. `"1000:1000"` or `"appuser"`.
1122    #[ts(optional = nullable)]
1123    pub user: Option<String>,
1124
1125    /// Environment variables. Values may be literals, secret refs, or
1126    /// mesh-address references resolved by yubaba at deploy time.
1127    #[serde(default)]
1128    pub env: Vec<EnvVar>,
1129
1130    /// Secret mounts. Values never appear in the spec JSON — only references.
1131    #[serde(default)]
1132    pub secrets: Vec<SecretMount>,
1133
1134    /// Volume mounts.
1135    #[serde(default)]
1136    pub volumes: Vec<VolumeMount>,
1137
1138    /// Hard resource caps enforced by containerd/cgroups.
1139    pub resources: ResourceLimits,
1140
1141    /// Mesh idents that must reach `Ready` before this workload starts.
1142    #[serde(default)]
1143    pub depends_on: Vec<MeshIdent>,
1144
1145    /// Container liveness/readiness probe.
1146    #[ts(optional = nullable)]
1147    pub healthcheck: Option<Healthcheck>,
1148
1149    /// What yubaba does when the container exits.
1150    pub restart_policy: RestartPolicy,
1151
1152    /// Explicit lifecycle archetype (R572-F1 / W244): `server`, `appliance`,
1153    /// or `job`. `None` means the spec predates this field (or the author
1154    /// didn't set it) — callers MUST NOT read this directly to decide
1155    /// drainability; use [`WorkloadSpec::effective_archetype`], which falls
1156    /// back to the pre-R572 `volumes`/`restart_policy` inference so no
1157    /// existing spec's effective meaning changes.
1158    ///
1159    /// Additive: this field did not exist before R572-F1. Reconciler (F4)
1160    /// and scheduler (F5) branching on the resolved archetype are separate,
1161    /// later tickets — this field alone changes no runtime behavior.
1162    #[serde(default)]
1163    #[ts(optional = nullable)]
1164    pub archetype: Option<LifecycleArchetype>,
1165
1166    /// Graceful shutdown configuration.
1167    pub stop_policy: StopPolicy,
1168
1169    /// Network exposure configuration — mesh, public, and operator channels
1170    /// are independent and can be set in any combination.
1171    pub expose: ExposeSpec,
1172
1173    /// OCI-style labels, passed through to the container. Opaque to yubaba.
1174    #[serde(default)]
1175    pub labels: HashMap<String, String>,
1176
1177    /// Yah-specific metadata, conventionally prefixed `yah.*`. Opaque to
1178    /// yubaba beyond `yah.forge=true` which suppresses the Never-restart guard.
1179    #[serde(default)]
1180    pub annotations: HashMap<String, String>,
1181}
1182
1183impl WorkloadSpec {
1184    /// Build a `WorkloadSpec` for a forge run.
1185    ///
1186    /// Sets the conventional forge fields in one place so callers cannot
1187    /// forget any of them:
1188    ///
1189    /// - `restart_policy = Never`
1190    /// - `archetype = Some(LifecycleArchetype::Job)` — a forge run is
1191    ///   exactly the `container`-kind instance of the job archetype (W244);
1192    ///   set explicitly rather than left to infer since this constructor
1193    ///   knows its own shape
1194    /// - `expose.public = None`, `expose.operator = None`
1195    /// - `expose.mesh.identity = "forge.<forge_id>"`
1196    /// - `annotations["yah.forge"] = "true"` (suppresses the shape warning)
1197    /// - `tier` and `image` come from the caller; `ports` becomes the mesh
1198    ///   port list (empty is valid — forge jobs often don't expose ports)
1199    ///
1200    /// All other fields are set to safe defaults. Callers can mutate the
1201    /// returned value to fill in `command`, `env`, `resources`, etc.
1202    pub fn for_forge(
1203        forge_id: &str,
1204        image: ImageRef,
1205        tier: TierTag,
1206        ports: Vec<u16>,
1207    ) -> Self {
1208        let mut annotations = HashMap::new();
1209        annotations.insert("yah.forge".into(), "true".into());
1210
1211        WorkloadSpec {
1212            schema_version: SchemaVersion::V1,
1213            // NB: DNS-label safe (no dots) — `check_name` validation rejects
1214            // dots here. The container_id derives from this; the state-poll
1215            // keys off `expose.mesh.identity` (`forge.<id>`) instead, so those
1216            // two must be reconciled at the read path, NOT by dotting the name
1217            // (see R590-B9).
1218            name: format!("forge-{forge_id}"),
1219            image,
1220            tier,
1221            tenant: TenantId::singleton(),
1222            namespace: NamespaceId::singleton(),
1223            replicas: 1,
1224            command: None,
1225            entrypoint: None,
1226            workdir: None,
1227            user: None,
1228            env: vec![],
1229            secrets: vec![],
1230            volumes: vec![],
1231            resources: ResourceLimits {
1232                // R590-B10: forge workloads are BUILDS (cargo, buildkit, a
1233                // from-source V8 checkout+compile), not tiny services. The old
1234                // 256 MB placeholder became a hard cgroup memory.limit in
1235                // build_oci_spec and SIGKILL'd the rusty-v8 build mid-checkout
1236                // (git checkout of third_party/icu died of signal 9) — the
1237                // more so because /tmp is a RAM-backed tmpfs, so the source
1238                // tree counts against this limit too. 32 GiB is a bounded
1239                // ceiling that fits the V8 build's >12 GB peak with headroom,
1240                // protects the host from a runaway (vs truly unlimited), and is
1241                // above physical RAM on smaller build-workers (⇒ effectively
1242                // unlimited there). A per-step memory request threaded from the
1243                // pipeline is the eventual right model (see R590-B10).
1244                memory_mb: 32768,
1245                cpu_millis: 512,
1246                ephemeral_storage_mb: 512,
1247            },
1248            depends_on: vec![],
1249            healthcheck: None,
1250            restart_policy: RestartPolicy::Never,
1251            archetype: Some(LifecycleArchetype::Job),
1252            stop_policy: StopPolicy {
1253                signal: 15,
1254                grace_period: Millis::from_secs(30),
1255            },
1256            expose: ExposeSpec {
1257                mesh: MeshExpose {
1258                    identity: MeshIdent(format!("forge.{forge_id}")),
1259                    ports,
1260                    allow_from: vec![],
1261                },
1262                public: None,
1263                operator: None,
1264            },
1265            labels: HashMap::new(),
1266            annotations,
1267        }
1268    }
1269
1270    /// Whether this workload requests the **host network namespace** rather
1271    /// than an isolated one.
1272    ///
1273    /// Opt-in via `annotations["yah.network"] == "host"` (see
1274    /// [`HOST_NETWORK_ANNOTATION`] / [`HOST_NETWORK_VALUE`]). Default is the
1275    /// isolated netns every other workload gets — host networking is a
1276    /// privileged escape hatch for the few infra workloads that must bind a
1277    /// host port so an on-host ingress (e.g. a Cloudflare tunnel reaching
1278    /// `127.0.0.1:<port>`) can route to them without CNI/bridge plumbing.
1279    ///
1280    /// The backend (kamaji) is responsible for **guarding** this: host
1281    /// networking is only honoured for `tier == "infra"` workloads; a
1282    /// non-infra workload that sets the annotation is rejected at deploy. See
1283    /// `validate_spec_for_constable`.
1284    pub fn wants_host_network(&self) -> bool {
1285        self.annotations
1286            .get(HOST_NETWORK_ANNOTATION)
1287            .map(|v| v == HOST_NETWORK_VALUE)
1288            .unwrap_or(false)
1289    }
1290
1291    /// Resolve the lifecycle archetype (R572-F1 / W244): the explicit
1292    /// [`Self::archetype`] if set, otherwise the pre-R572 inference from
1293    /// `volumes`/`restart_policy` this field replaces.
1294    ///
1295    /// This is the one seam callers should use to ask "can I kill and
1296    /// reschedule this?" — it is intentionally the *only* place that
1297    /// implements the fallback, so behavior for pre-existing specs (no
1298    /// `archetype` on disk) is identical to what it was before this field
1299    /// existed. Consumers (reconciler R572-F4, scheduler R572-F5) branch on
1300    /// the return value; this crate does not itself change any reconciler or
1301    /// scheduler behavior.
1302    pub fn effective_archetype(&self) -> LifecycleArchetype {
1303        self.archetype
1304            .unwrap_or_else(|| LifecycleArchetype::infer(&self.volumes, &self.restart_policy))
1305    }
1306
1307    /// Fully-qualified mesh identity `<tenant>/<namespace>/<name>` (W206 /
1308    /// R558-F3), where `<name>` is this workload's [`MeshExpose::identity`].
1309    ///
1310    /// Within a tenant, workloads still address each other by the short
1311    /// identity (namespace disambiguates only on collision); the FQN is what
1312    /// makes the identity unambiguous across tenants and is exactly what a
1313    /// [`MeshPeer::CrossTenant`] grant names.
1314    pub fn fq_mesh_identity(&self) -> String {
1315        format!(
1316            "{}/{}/{}",
1317            self.tenant.0, self.namespace.0, self.expose.mesh.identity.0
1318        )
1319    }
1320
1321    /// The taint this workload requires its node to carry, if any (R594-F2 /
1322    /// W267 sovereign public ingress).
1323    ///
1324    /// Opt-in via `annotations["yah.placement.requires-taint"] = "<taint
1325    /// name>"` (see [`REQUIRES_TAINT_ANNOTATION`]) — same annotation-based,
1326    /// zero-blast-radius shape as [`Self::wants_host_network`], chosen so
1327    /// declaring this requirement does not force a struct-literal edit at
1328    /// every existing `WorkloadSpec { .. }` construction site the way a new
1329    /// plain field would (see R572-F1's handoff: ~26 sites for one field).
1330    ///
1331    /// **This only declares the requirement — nothing matches it yet.** The
1332    /// taint itself doesn't exist on the machine-TOML side until
1333    /// [R572-F3](yah://arch/symbol/R572) adds a `taints` list there, and
1334    /// nothing enforces repel-unless-tolerate placement until
1335    /// [R572-F5](yah://arch/symbol/R572)'s scheduler lands. Until then this
1336    /// is inert metadata a future scheduler can read.
1337    ///
1338    /// The public-ingress appliance (W267) is the first user: a
1339    /// `kind = "container"` workload with `archetype =
1340    /// Some(LifecycleArchetype::Appliance)` and
1341    /// `requires_taint() == Some(PUBLIC_IP_TAINT)`, so yubaba may one day
1342    /// place it only on machines carrying the `"public-ip"` taint and kamaji
1343    /// supervises it like any other container (no new `Workload` variant —
1344    /// see [`Workload::Container`]'s doc comment).
1345    pub fn requires_taint(&self) -> Option<&str> {
1346        self.annotations
1347            .get(REQUIRES_TAINT_ANNOTATION)
1348            .map(String::as_str)
1349    }
1350}
1351
1352/// Annotation key requesting a workload share the host network namespace.
1353/// See [`WorkloadSpec::wants_host_network`].
1354pub const HOST_NETWORK_ANNOTATION: &str = "yah.network";
1355
1356/// Annotation value (for [`HOST_NETWORK_ANNOTATION`]) selecting host
1357/// networking. Any other value leaves the workload in an isolated netns.
1358pub const HOST_NETWORK_VALUE: &str = "host";
1359
1360/// Annotation key declaring that a workload must land only on a node
1361/// carrying a specific taint. See [`WorkloadSpec::requires_taint`].
1362pub const REQUIRES_TAINT_ANNOTATION: &str = "yah.placement.requires-taint";
1363
1364/// Taint name (for [`REQUIRES_TAINT_ANNOTATION`]) identifying machines with
1365/// a publicly-routable IP — the W267 sovereign-ingress placement
1366/// requirement. The corresponding taint field on the machine TOML doesn't
1367/// exist yet (R572-F3); this constant is the agreed-upon name both sides
1368/// will use once it does.
1369pub const PUBLIC_IP_TAINT: &str = "public-ip";
1370
1371// ── ImageRef ─────────────────────────────────────────────────────────────────
1372
1373/// Container image reference identifying a specific image to pull.
1374///
1375/// **Digest is required.** Every executable image reference in the workspace
1376/// is content-addressed by `sha256:<hex>`. The `tag` is preserved as a
1377/// human-readable identifier but is not the source of truth — registries
1378/// return mutable `tag → digest` mappings and we don't trust them for
1379/// reproducibility. R438-T3 tightened `digest: Option<String> → String` to
1380/// make unpinned-image bugs impossible by construction.
1381///
1382/// **Two deserialize shapes.** The struct form
1383/// (`registry`/`repository`/`tag`/`digest` fields) is the on-disk envelope.
1384/// A **string form** (`image = "ghcr.io/foo/bar:v1@sha256:<hex>"`) is also
1385/// accepted and is the shape W164 transform recipes (R438-T4) and W165
1386/// `BuildMode::InContainer` (R438-T6) use. Both shapes go through a single
1387/// parser ([`compose_import::parse_pinned_image_ref`]) that rejects
1388/// bare-tag references at serde-deserialize.
1389#[derive(Debug, Clone, PartialEq, Eq, Serialize, TS)]
1390#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1391pub struct ImageRef {
1392    /// Registry hostname, e.g. `"ghcr.io"` or `"localhost:5000"`.
1393    pub registry: String,
1394
1395    /// Repository path, e.g. `"noisetable/api"`.
1396    pub repository: String,
1397
1398    /// Tag, e.g. `"v1.4.2"` or `"latest"`. Informational — the digest is
1399    /// the source of truth for image identity.
1400    pub tag: String,
1401
1402    /// Content-addressed pinned identity, e.g. `"sha256:abc..."`. Required.
1403    pub digest: String,
1404}
1405
1406impl<'de> Deserialize<'de> for ImageRef {
1407    fn deserialize<D>(de: D) -> Result<Self, D::Error>
1408    where
1409        D: serde::Deserializer<'de>,
1410    {
1411        #[derive(Deserialize)]
1412        struct Fields {
1413            registry: String,
1414            repository: String,
1415            tag: String,
1416            digest: String,
1417        }
1418
1419        // The string-or-struct `untagged` probe requires `deserialize_any`,
1420        // which only self-describing formats support. Postcard — the binary
1421        // wire behind the kamaji UDS — returns `WontImplement` for it, so a
1422        // `Workload::Container(WorkloadSpec)` carrying a nested `ImageRef`
1423        // failed to decode and every container deploy 500'd (R590-B3).
1424        //
1425        // The string form is purely an authoring convenience in human-readable
1426        // configs (`image = "ghcr.io/…@sha256:…"` in recipe/workload TOML and
1427        // JSON); the binary wire only ever carries the derived struct form
1428        // (Serialize is a plain struct derive). So branch on the format: text
1429        // keeps the string-or-struct convenience via `untagged`; binary decodes
1430        // the plain positional struct with no `deserialize_any`.
1431        if de.is_human_readable() {
1432            #[derive(Deserialize)]
1433            #[serde(untagged)]
1434            enum Repr {
1435                // Order matters for `untagged`: try the string form first so
1436                // explicit strings don't get coerced into a struct error.
1437                Pinned(String),
1438                Struct(Fields),
1439            }
1440
1441            match Repr::deserialize(de)? {
1442                Repr::Pinned(s) => {
1443                    compose_import::parse_pinned_image_ref(&s).map_err(serde::de::Error::custom)
1444                }
1445                Repr::Struct(f) => Ok(ImageRef {
1446                    registry: f.registry,
1447                    repository: f.repository,
1448                    tag: f.tag,
1449                    digest: f.digest,
1450                }),
1451            }
1452        } else {
1453            let f = Fields::deserialize(de)?;
1454            Ok(ImageRef {
1455                registry: f.registry,
1456                repository: f.repository,
1457                tag: f.tag,
1458                digest: f.digest,
1459            })
1460        }
1461    }
1462}
1463
1464// ── testing helpers ───────────────────────────────────────────────────────────
1465
1466/// Fixture helpers for test code that needs to construct types whose schemas
1467/// would otherwise demand operator-pinned values (digests, hashes). Doc-hidden
1468/// to discourage misuse from non-test code — production paths must source
1469/// digests from registry resolution or compile-time injection.
1470#[doc(hidden)]
1471pub mod testing {
1472    /// Fixed valid-format sha256 digest for test fixtures. All-zeros marker
1473    /// is impossible for any real image, so a leaked test fixture in a
1474    /// production code-path surfaces obviously.
1475    ///
1476    /// Aliases [`super::ImageRef::UNPINNED_DIGEST`] — the two are deliberately
1477    /// the same value: the fixture sentinel and the production "unpinned"
1478    /// marker must agree so [`super::ImageRef::pull_ref`]'s tag-fallback fires
1479    /// on exactly the digest `catalog_image` writes.
1480    pub const TEST_DIGEST: &str = super::ImageRef::UNPINNED_DIGEST;
1481
1482    /// Owned `String` form of [`TEST_DIGEST`] for fixture constructors.
1483    pub fn test_digest() -> String {
1484        TEST_DIGEST.to_string()
1485    }
1486}
1487
1488// ── EnvVar ────────────────────────────────────────────────────────────────────
1489
1490/// A single environment variable injected into the container.
1491#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1492#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1493pub struct EnvVar {
1494    /// Variable name, conventionally `SCREAMING_SNAKE_CASE`.
1495    pub name: String,
1496
1497    /// Value source.
1498    pub value: EnvValue,
1499}
1500
1501/// Value source for an environment variable.
1502#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1503#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1504#[serde(rename_all = "snake_case")]
1505pub enum EnvValue {
1506    /// Static string baked into the spec.
1507    Literal { value: String },
1508
1509    /// Resolved from a yubaba secret at deploy time; the secret value never
1510    /// appears in the spec JSON.
1511    FromSecret { secret: String, key: String },
1512
1513    /// Resolved from another workload's mesh address at deploy time by yubaba.
1514    /// Lets workloads reference each other symbolically without IP pinning.
1515    FromMesh { ident: MeshIdent, kind: MeshLookup },
1516}
1517
1518/// Which aspect of a mesh peer's address to inject.
1519#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
1520#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1521#[serde(rename_all = "snake_case")]
1522pub enum MeshLookup {
1523    /// Full URL, e.g. `"http://noisetable-db.pdx:5432"`.
1524    Url,
1525    /// Hostname only, e.g. `"noisetable-db.pdx"`.
1526    Host,
1527    /// Port only, e.g. `"5432"`.
1528    Port,
1529}
1530
1531// ── Secrets ───────────────────────────────────────────────────────────────────
1532
1533/// A secret value mounted into the container as an env var or file.
1534///
1535/// The secret value never appears in the spec JSON — only the reference.
1536/// Yubaba audits secret access per workload from these references.
1537#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1538#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1539pub struct SecretMount {
1540    /// Where yubaba reads the secret value from.
1541    pub source: SecretRef,
1542
1543    /// How the secret is surfaced inside the container.
1544    pub target: SecretTarget,
1545}
1546
1547/// Where yubaba resolves the secret value from.
1548#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1549#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1550#[serde(rename_all = "snake_case")]
1551pub enum SecretRef {
1552    /// Per-machine yubaba secret store at `/var/lib/yah/yubaba/secrets/`.
1553    LocalFile { path: PathBuf },
1554
1555    /// Raft-replicated cluster secret spanning all machines (planned; not in
1556    /// V1 deployment). Sketch preserved for wire compatibility.
1557    Cluster { name: String },
1558}
1559
1560/// How the secret is surfaced inside the container.
1561#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1562#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1563#[serde(rename_all = "snake_case")]
1564pub enum SecretTarget {
1565    /// Injected as an environment variable. Value never appears in spec JSON.
1566    /// Prefer `File` — env vars leak through subprocess env and log dumps.
1567    EnvVar { name: String },
1568
1569    /// Mounted as a file inside the container at `path` with `mode` (octal).
1570    File { path: PathBuf, mode: u32 },
1571}
1572
1573// ── Volumes ───────────────────────────────────────────────────────────────────
1574
1575/// A volume mount inside the container.
1576#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1577#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1578pub struct VolumeMount {
1579    /// Backing volume source.
1580    pub source: VolumeSource,
1581
1582    /// Absolute path inside the container.
1583    pub target: PathBuf,
1584
1585    /// Whether the container sees the volume as read-only.
1586    pub read_only: bool,
1587}
1588
1589/// Backing source for a volume mount.
1590#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1591#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1592#[serde(rename_all = "snake_case")]
1593pub enum VolumeSource {
1594    /// Yubaba-managed named volume; created on first use.
1595    Named { name: String },
1596
1597    /// Operator-managed host path. Yubaba rejects bind mounts unless
1598    /// `WorkloadSpec.tier == "infra"`; shape validation enforces this.
1599    Bind { host_path: PathBuf },
1600
1601    /// In-memory tmpfs; discarded on container stop. `size_mb` caps space
1602    /// consumed by the writable layer.
1603    Tmpfs { size_mb: u32 },
1604}
1605
1606// ── Durable forge produced-artifact convention (R603-T5) ──────────────────────
1607
1608/// Convention for a remote forge step's durable produced artifacts.
1609///
1610/// A remote build (e.g. the rusty_v8 musl build on a build-worker) writes its
1611/// output tarball to a path *inside* the container. The container's rootfs is
1612/// destroyed when kamaji reaps the EXITED container — so if the camp daemon is
1613/// down when the build finishes, the artifact is gone before boot-reconcile can
1614/// retrieve it (R603-T4 surfaced this as `Success`-but-`UNPUBLISHED`).
1615///
1616/// The fix (R603-T5) is a **host-persistent bind mount**: forge Subprocess
1617/// workloads mount [`HOST_ROOT`]`/<forge_id>` onto [`CONTAINER_DIR`], so a
1618/// build that writes its `produces` under `/yah/produced` lands the bytes on
1619/// the worker's host filesystem. yubaba then reads them back from the host path
1620/// ([`host_path`]) — which outlives container reaping — instead of the
1621/// unreachable container rootfs.
1622///
1623/// The container-side path and the host root are a shared convention between
1624/// three crates: the qed `build_workload_spec` that adds the mount, kamaji that
1625/// binds it, and the yubaba handler that reads + reaps it. Keeping it here (the
1626/// crate all three already depend on) is the single source of truth.
1627pub mod forge_produced {
1628    use std::path::{Path, PathBuf};
1629
1630    /// Conventional container-side directory a remote forge step writes its
1631    /// durable produced artifacts to. Bind-mounted onto a host-persistent dir.
1632    pub const CONTAINER_DIR: &str = "/yah/produced";
1633
1634    /// Host root under which each forge's durable produced dir lives, one
1635    /// subdir per run: `<HOST_ROOT>/<forge_id>/`. yubaba owns this directory —
1636    /// it creates the per-forge subdir at deploy, serves reads from it, and
1637    /// reaps it on teardown / TTL sweep.
1638    pub const HOST_ROOT: &str = "/var/lib/yah/qed/produced";
1639
1640    /// Forge mesh idents are `forge.<id>` (see [`WorkloadSpec::for_forge`]).
1641    /// Extract the bare `<id>`, or `None` for a non-forge ident.
1642    ///
1643    /// [`WorkloadSpec::for_forge`]: super::WorkloadSpec::for_forge
1644    pub fn forge_id_from_ident(ident: &str) -> Option<&str> {
1645        ident.strip_prefix("forge.")
1646    }
1647
1648    /// The host-persistent produced directory for one forge run.
1649    pub fn host_dir(forge_id: &str) -> PathBuf {
1650        PathBuf::from(HOST_ROOT).join(forge_id)
1651    }
1652
1653    /// Translate a container-side produced path to its durable host path for a
1654    /// given forge run. Returns `None` when `container_path` is not under
1655    /// [`CONTAINER_DIR`] (the caller then knows the artifact was not written to
1656    /// the durable location and won't survive reaping), or when the relative
1657    /// path contains a `..` component (a traversal attempt that could escape the
1658    /// per-forge dir — the reader must never serve a file outside it).
1659    pub fn host_path(forge_id: &str, container_path: &Path) -> Option<PathBuf> {
1660        let rel = container_path.strip_prefix(CONTAINER_DIR).ok()?;
1661        if rel
1662            .components()
1663            .any(|c| matches!(c, std::path::Component::ParentDir))
1664        {
1665            return None;
1666        }
1667        Some(host_dir(forge_id).join(rel))
1668    }
1669
1670    /// The durable produced-dir bind mount for a forge run: host
1671    /// `<HOST_ROOT>/<forge_id>` → container [`CONTAINER_DIR`], writable.
1672    pub fn durable_mount(forge_id: &str) -> super::VolumeMount {
1673        super::VolumeMount {
1674            source: super::VolumeSource::Bind {
1675                host_path: host_dir(forge_id),
1676            },
1677            target: PathBuf::from(CONTAINER_DIR),
1678            read_only: false,
1679        }
1680    }
1681
1682    /// True when `path` is (or is under) the conventional durable produced dir
1683    /// — the guard qed uses to enforce that declared `produces` land somewhere
1684    /// reap-durable.
1685    pub fn is_durable_path(path: &Path) -> bool {
1686        path.starts_with(CONTAINER_DIR)
1687    }
1688}
1689
1690// ── Resources ─────────────────────────────────────────────────────────────────
1691
1692/// Hard resource caps enforced by containerd/cgroups at runtime.
1693#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1694#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1695pub struct ResourceLimits {
1696    /// Maximum RAM the container may allocate, in MiB. The container is OOM-
1697    /// killed if it exceeds this.
1698    pub memory_mb: u32,
1699
1700    /// CPU **request** in millicores (k8s convention): `1000` = one full core,
1701    /// `250` = `.25 CPU`. Unlike a Docker relative weight this is an
1702    /// allocatable quantity a bin-packer can subtract from a node's budget.
1703    /// `0` means "no CPU limit". Backends that speak a relative weight derive
1704    /// it via [`ResourceLimits::cpu_shares`].
1705    pub cpu_millis: u32,
1706
1707    /// Cap on the writable layer + tmpfs footprint, in MiB.
1708    pub ephemeral_storage_mb: u32,
1709}
1710
1711impl ResourceLimits {
1712    /// The Docker/OCI relative CPU weight (`cpu.shares`, where `1024` ≈ one
1713    /// core) equivalent to this millicore request. The containerd and docker
1714    /// backends express CPU as a weight rather than a millicore request, so
1715    /// they derive it here instead of storing shares: `1000m` ⇒ `1024`.
1716    pub fn cpu_shares(&self) -> u64 {
1717        (u64::from(self.cpu_millis) * 1024) / 1000
1718    }
1719}
1720
1721// ── Healthcheck ───────────────────────────────────────────────────────────────
1722
1723/// Container health probe configuration.
1724#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1725#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1726pub struct Healthcheck {
1727    /// The probe executed to determine container health.
1728    pub probe: HealthProbe,
1729
1730    /// How often the probe runs.
1731    pub interval: Millis,
1732
1733    /// Per-probe timeout; a slow response counts as failure.
1734    pub timeout: Millis,
1735
1736    /// Time to wait after container start before the first probe. Shape
1737    /// validation warns (not errors) if this is less than
1738    /// `stop_policy.grace_period * 2`.
1739    pub initial_delay: Millis,
1740
1741    /// Number of consecutive failures before the container is marked
1742    /// `Unhealthy`.
1743    pub failure_threshold: u32,
1744}
1745
1746/// Mechanism used to check container health.
1747#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1748#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1749#[serde(rename_all = "snake_case")]
1750pub enum HealthProbe {
1751    /// HTTP GET to `path` on `port`. A 2xx (or `expect_status` if set)
1752    /// response counts as healthy.
1753    HttpGet {
1754        path: String,
1755        port: u16,
1756        #[ts(optional = nullable)]
1757        expect_status: Option<u16>,
1758    },
1759
1760    /// Run `argv` inside the container; exit-0 counts as healthy.
1761    Exec { argv: Vec<String> },
1762
1763    /// TCP connection to `port`; a successful connect counts as healthy.
1764    TcpConnect { port: u16 },
1765}
1766
1767// ── Restart / Stop ────────────────────────────────────────────────────────────
1768
1769/// What yubaba does when the container exits.
1770#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1771#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1772#[serde(rename_all = "snake_case")]
1773pub enum RestartPolicy {
1774    /// Restart unconditionally on any exit.
1775    Always,
1776
1777    /// Restart on non-zero exit, up to `max_attempts` times with exponential
1778    /// backoff. After exhaustion, the workload is marked `Failed`.
1779    OnFailure {
1780        max_attempts: u32,
1781        backoff: BackoffPolicy,
1782    },
1783
1784    /// Do not restart. The container runs once and exits.
1785    ///
1786    /// **Forge convention.** Forge runs (R094) synthesize a `WorkloadSpec`
1787    /// using [`WorkloadSpec::for_forge`] which sets all the conventional fields
1788    /// together:
1789    ///
1790    /// - `restart_policy = Never`
1791    /// - `expose.public = None`, `expose.operator = None`
1792    /// - `expose.mesh.identity = "forge.<forge_id>"` — distinguishable from
1793    ///   persistent mirror identities at the mesh layer
1794    /// - `tier = "infra"` (or the forge-spec's effective tier)
1795    /// - `annotations["yah.forge"] = "true"` — suppresses the shape warning
1796    ///
1797    /// Using `Never` on a persistent mirror (not a forge run) means the mirror
1798    /// stays dead after any exit — a likely misconfiguration. Shape validation
1799    /// emits a soft warning unless `annotations["yah.forge"] == "true"` is
1800    /// present. See R094 forge.
1801    Never,
1802}
1803
1804/// Exponential backoff parameters for `RestartPolicy::OnFailure`.
1805#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
1806#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1807pub struct BackoffPolicy {
1808    /// Initial delay before the first restart, in milliseconds.
1809    pub initial_ms: u32,
1810
1811    /// Maximum delay between retries, in milliseconds.
1812    pub max_ms: u32,
1813
1814    /// Backoff multiplier applied to each successive delay.
1815    pub multiplier: f32,
1816}
1817
1818/// Graceful shutdown configuration for yubaba's stop sequence.
1819#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1820#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1821pub struct StopPolicy {
1822    /// Signal number sent first, e.g. `15` (SIGTERM) or `2` (SIGINT).
1823    pub signal: i32,
1824
1825    /// Time yubaba waits after sending `signal` before issuing SIGKILL.
1826    pub grace_period: Millis,
1827}
1828
1829// ── Expose ────────────────────────────────────────────────────────────────────
1830
1831/// Network exposure configuration. The three channels are independent; any
1832/// combination is valid.
1833#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1834#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1835pub struct ExposeSpec {
1836    /// Mesh-internal exposure. Required; every workload must have a mesh
1837    /// identity even if no other workload currently reaches it.
1838    pub mesh: MeshExpose,
1839
1840    /// Public internet exposure via a Cloudflare tunnel route. `None` means
1841    /// the workload is not internet-reachable.
1842    #[ts(optional = nullable)]
1843    pub public: Option<PublicExpose>,
1844
1845    /// Operator-facing exposure via a Tailscale ACL tag. `None` means the
1846    /// workload is not operator-reachable via Tailscale.
1847    #[ts(optional = nullable)]
1848    pub operator: Option<OperatorExpose>,
1849}
1850
1851/// A peer permitted to initiate mesh connections to a workload (W206 / R558-F3).
1852///
1853/// Cross-tenant access is **deny-by-default**: a workload accepts inter-tenant
1854/// traffic only from peers it lists explicitly as [`MeshPeer::CrossTenant`].
1855/// Same-tenant access stays tier-based ([`MeshPeer::Tier`]) — the pre-R558
1856/// model — and an `allow_from` with no `Tier` entries still admits every
1857/// same-tenant peer (the historical "empty = allow all" default).
1858///
1859/// External serde tagging keeps this postcard-safe (R590-B3): no internal tag,
1860/// no untagged, no `skip_serializing_if`.
1861#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1862#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1863#[serde(rename_all = "snake_case")]
1864pub enum MeshPeer {
1865    /// Any **same-tenant** workload whose `tier` matches this tag. This is the
1866    /// pre-R558 `allow_from` semantics.
1867    Tier(TierTag),
1868
1869    /// A specific workload in **another tenant**, addressed by its fully
1870    /// qualified mesh identity `<tenant>/<namespace>/<name>`. There is no
1871    /// cross-tenant tier wildcard — each cross-tenant peer is granted
1872    /// individually, so a shared fleet stays isolated unless an operator opts
1873    /// in here.
1874    CrossTenant {
1875        tenant: TenantId,
1876        namespace: NamespaceId,
1877        /// Peer's mesh identity (its [`MeshExpose::identity`]).
1878        name: MeshIdent,
1879    },
1880}
1881
1882/// Mesh-internal port exposure and peer access control.
1883#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1884#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1885pub struct MeshExpose {
1886    /// DNS-segment mesh identity for this workload. Must be unique in the
1887    /// cluster. Regex: `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`, length ≤ 63.
1888    pub identity: MeshIdent,
1889
1890    /// Container-side ports this workload listens on. Other workloads reach
1891    /// it at `<identity>:<port>` on the mesh.
1892    pub ports: Vec<u16>,
1893
1894    /// Peers permitted to initiate connections to this workload on the mesh
1895    /// (W206 / R558-F3). Same-tenant tier rules and explicit cross-tenant
1896    /// grants share this one list. With **no** [`MeshPeer::Tier`] entries every
1897    /// same-tenant peer is admitted (the historical "empty = allow all"
1898    /// default); cross-tenant peers are always denied unless named by a
1899    /// [`MeshPeer::CrossTenant`] entry. See [`MeshExpose::admits_peer`].
1900    #[serde(default)]
1901    pub allow_from: Vec<MeshPeer>,
1902}
1903
1904impl MeshExpose {
1905    /// Whether a peer may initiate a mesh connection to a workload whose mesh
1906    /// exposure is `self`. `own_tenant` is the tenant of the workload being
1907    /// protected; the remaining arguments identify the connecting peer.
1908    ///
1909    /// Deny-by-default across tenants (W206 / R558-F3):
1910    /// - **Same tenant** (`own_tenant == peer_tenant`): admitted when the
1911    ///   peer's tier matches a [`MeshPeer::Tier`] rule, or when there are no
1912    ///   `Tier` rules at all (historical "empty `allow_from` = allow all
1913    ///   same-tenant").
1914    /// - **Cross tenant**: admitted only when an explicit
1915    ///   [`MeshPeer::CrossTenant`] entry matches the peer's
1916    ///   `(tenant, namespace, name)`.
1917    pub fn admits_peer(
1918        &self,
1919        own_tenant: &TenantId,
1920        peer_tenant: &TenantId,
1921        peer_namespace: &NamespaceId,
1922        peer_name: &MeshIdent,
1923        peer_tier: &TierTag,
1924    ) -> bool {
1925        if own_tenant == peer_tenant {
1926            let mut has_tier_rule = false;
1927            for peer in &self.allow_from {
1928                if let MeshPeer::Tier(t) = peer {
1929                    has_tier_rule = true;
1930                    if t == peer_tier {
1931                        return true;
1932                    }
1933                }
1934            }
1935            // No same-tenant tier restriction declared → admit all same-tenant.
1936            !has_tier_rule
1937        } else {
1938            self.allow_from.iter().any(|peer| {
1939                matches!(
1940                    peer,
1941                    MeshPeer::CrossTenant { tenant, namespace, name }
1942                        if tenant == peer_tenant
1943                            && namespace == peer_namespace
1944                            && name == peer_name
1945                )
1946            })
1947        }
1948    }
1949}
1950
1951/// The name by which a workload is addressed **within its own tenant** (W206 /
1952/// R558-F3), given every `(namespace, identity)` pair present in that tenant.
1953///
1954/// Within a tenant, a workload is reached by its short mesh `identity` when that
1955/// identity is unique across the tenant's namespaces. When two namespaces
1956/// expose the same identity, the name is ambiguous, so both are disambiguated
1957/// by a namespace prefix — `<namespace>.<identity>` (e.g. `yah.runner` vs
1958/// `noisetable.runner`). Cross-tenant addressing always uses the full FQN
1959/// ([`WorkloadSpec::fq_mesh_identity`]) and is out of scope here.
1960pub fn intra_tenant_address(
1961    namespace: &NamespaceId,
1962    identity: &MeshIdent,
1963    tenant_workloads: &[(NamespaceId, MeshIdent)],
1964) -> String {
1965    let collides = tenant_workloads
1966        .iter()
1967        .any(|(ns, id)| id == identity && ns != namespace);
1968    if collides {
1969        format!("{}.{}", namespace.0, identity.0)
1970    } else {
1971        identity.0.clone()
1972    }
1973}
1974
1975/// Public internet exposure via a Cloudflare tunnel route.
1976#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1977#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1978pub struct PublicExpose {
1979    /// Public hostname to route, e.g. `"api.noisetable.io"`. Semantic
1980    /// validation checks that this hostname is owned by a configured CF zone.
1981    pub hostname: String,
1982
1983    /// Container-side port to route traffic to. Shape validation requires this
1984    /// port to appear in `expose.mesh.ports`.
1985    pub port: u16,
1986
1987    /// TLS configuration for the public endpoint.
1988    pub tls: PublicTls,
1989}
1990
1991/// TLS mode for a public endpoint.
1992#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
1993#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1994#[serde(rename_all = "snake_case")]
1995pub enum PublicTls {
1996    /// Cloudflare manages the TLS certificate (default; requires a proxied DNS
1997    /// record in the configured zone).
1998    CfManaged,
1999
2000    /// User-supplied certificate referenced by name in the yubaba secret store.
2001    UserCertRef { name: String },
2002}
2003
2004/// Operator-facing exposure via a Tailscale ACL tag.
2005#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
2006#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2007pub struct OperatorExpose {
2008    /// Tailscale ACL tag granting access, e.g. `"tag:noisetable-ops"`. Semantic
2009    /// validation checks that this tag exists in the cluster's Tailscale ACL.
2010    pub tailscale_tag: String,
2011
2012    /// Container-side port to expose to Tailscale-authorized operators.
2013    pub port: u16,
2014}
2015
2016// ── ImageRef helpers ──────────────────────────────────────────────────────────
2017
2018impl ImageRef {
2019    /// The all-zeros sha256 digest that marks an image reference as **not
2020    /// content-pinned**. No real image can carry it, so a build that never
2021    /// injected a compile-time digest (dev builds) or a catalog image that
2022    /// isn't published-and-pinned yet lands on this sentinel. This is the
2023    /// single source of truth both the catalog emitter
2024    /// (`task::default_image::catalog_image`, which writes it) and the
2025    /// container-runtime resolvers ([`Self::pull_ref`], via kamaji) agree on —
2026    /// keeping them here means they cannot drift. [`testing::TEST_DIGEST`] is
2027    /// the same value re-exported for fixtures.
2028    pub const UNPINNED_DIGEST: &'static str =
2029        "sha256:0000000000000000000000000000000000000000000000000000000000000000";
2030
2031    /// Parse a full digest-pinned image reference —
2032    /// `[registry/]repo[:tag]@sha256:<hex>` — into its parts.
2033    ///
2034    /// This is the public door onto the same parser the `ImageRef` string-form
2035    /// `Deserialize` arm uses, so a config that spells an image as one string
2036    /// (a qed `step.image`, a transform recipe) and a config that spells it as
2037    /// a struct land on identical semantics. A bare tag is rejected: the whole
2038    /// point of the string form is that it carries the digest.
2039    pub fn parse_pinned(s: &str) -> Result<Self, String> {
2040        compose_import::parse_pinned_image_ref(s)
2041    }
2042
2043    /// Format this reference as a Docker-compatible image string,
2044    /// `{registry}/{repository}:{tag}@{digest}`. Tag is included for human
2045    /// readability; the digest is what the pull resolves against. Always emits
2046    /// the digest — this is the display/logging form; use [`Self::pull_ref`]
2047    /// for the string handed to a container runtime.
2048    pub fn docker_ref(&self) -> String {
2049        format!("{}/{}:{}@{}", self.registry, self.repository, self.tag, self.digest)
2050    }
2051
2052    /// True when this reference carries a real content-addressed digest, i.e.
2053    /// its digest is not the all-zeros [`Self::UNPINNED_DIGEST`] sentinel.
2054    pub fn is_pinned(&self) -> bool {
2055        self.digest != Self::UNPINNED_DIGEST
2056    }
2057
2058    /// The reference string to hand a container runtime for pull/resolve.
2059    ///
2060    /// - **Pinned** (real digest): `{registry}/{repository}:{tag}@{digest}` —
2061    ///   content-addressed, the reproducible path.
2062    /// - **Unpinned** (all-zeros [`Self::UNPINNED_DIGEST`]): `{registry}/{repository}:{tag}`
2063    ///   — tag-only. No registry or local store holds an image under the
2064    ///   sentinel digest, so `…@sha256:0000…` can never resolve; a
2065    ///   tag-pulled or locally-built image is keyed by `registry/repo:tag`.
2066    ///   This is the tag-fallback path that lets a not-yet-published catalog
2067    ///   image (e.g. a from-source build-worker image) still pull by tag.
2068    pub fn pull_ref(&self) -> String {
2069        if self.is_pinned() {
2070            format!("{}/{}:{}@{}", self.registry, self.repository, self.tag, self.digest)
2071        } else {
2072            format!("{}/{}:{}", self.registry, self.repository, self.tag)
2073        }
2074    }
2075}
2076
2077// ── WorkloadRuntime trait ─────────────────────────────────────────────────────
2078
2079/// Shared interface for deploying and managing `WorkloadSpec` containers.
2080///
2081/// This is the keystone abstraction (R256-F10) that makes sim and cloud
2082/// literally interchangeable at the container level:
2083///
2084/// - **Camp/sim tier**: `LocalDockerRuntime` in `cloud` implements this trait
2085///   via the docker CLI pointed at OrbStack (or any Docker-compatible socket).
2086///   No mesh — containers communicate over OrbStack's bridge network.
2087///
2088/// - **Yubaba/cloud-HA tier**: `yubaba::runtime::ContainerRuntime` (gRPC to
2089///   containerd) will implement this trait. Mesh assignment is a separate
2090///   orchestration step on top (handled by yubaba's raft layer), not part
2091///   of the shared deploy/supervise interface.
2092///
2093/// Callers that type against `WorkloadRuntime` automatically work with both
2094/// backends. Reconcilers in `cloud` use it today; yubaba wires its own impl
2095/// when R276 Tier-3 lands.
2096#[async_trait::async_trait]
2097pub trait WorkloadRuntime: Send + Sync {
2098    /// Deploy a workload described by `spec`. Pulls the image if needed,
2099    /// creates and starts the container, and returns an opaque workload ID
2100    /// (typically the container name derived from `spec.name`).
2101    ///
2102    /// Idempotent: re-deploying a running workload replaces it cleanly.
2103    async fn deploy_workload(&self, spec: &WorkloadSpec) -> anyhow::Result<String>;
2104
2105    /// Tear down a deployed workload — stop the process and remove all
2106    /// associated state. No-op when the workload is already gone.
2107    async fn teardown_workload(&self, name: &str) -> anyhow::Result<()>;
2108
2109    /// Returns `true` when the named workload is currently running (i.e.
2110    /// the container process is alive and has not exited).
2111    async fn is_running(&self, name: &str) -> anyhow::Result<bool>;
2112
2113    /// Probe the runtime backend. Returns `true` when the backend socket is
2114    /// reachable and healthy (e.g. docker daemon up, containerd gRPC up).
2115    /// Used by health endpoints and startup checks.
2116    async fn runtime_health(&self) -> anyhow::Result<bool>;
2117}
2118
2119// ── Tests ─────────────────────────────────────────────────────────────────────
2120
2121#[cfg(test)]
2122mod tests {
2123    use super::*;
2124
2125    // ── R603-T5 durable forge produced convention ──────────────────────────────
2126
2127    #[test]
2128    fn forge_produced_ident_parse() {
2129        assert_eq!(forge_produced::forge_id_from_ident("forge.abc123"), Some("abc123"));
2130        assert_eq!(forge_produced::forge_id_from_ident("svc.web"), None);
2131        assert_eq!(forge_produced::forge_id_from_ident("abc123"), None);
2132    }
2133
2134    #[test]
2135    fn forge_produced_host_path_translates_under_convention_dir() {
2136        let hp = forge_produced::host_path(
2137            "fid",
2138            std::path::Path::new("/yah/produced/librusty_v8.tar.gz"),
2139        )
2140        .expect("path under the convention dir translates");
2141        assert_eq!(
2142            hp,
2143            PathBuf::from("/var/lib/yah/qed/produced/fid/librusty_v8.tar.gz")
2144        );
2145    }
2146
2147    #[test]
2148    fn forge_produced_host_path_rejects_paths_outside_convention_dir() {
2149        assert_eq!(
2150            forge_produced::host_path("fid", std::path::Path::new("/tmp/x.tar.gz")),
2151            None,
2152            "a path outside /yah/produced has no durable host mapping"
2153        );
2154    }
2155
2156    #[test]
2157    fn forge_produced_host_path_rejects_traversal() {
2158        // A `..` component must never let a read escape the per-forge dir.
2159        assert_eq!(
2160            forge_produced::host_path(
2161                "fid",
2162                std::path::Path::new("/yah/produced/../../etc/passwd")
2163            ),
2164            None,
2165            "traversal out of the per-forge dir must be refused"
2166        );
2167    }
2168
2169    #[test]
2170    fn forge_produced_durable_mount_shape() {
2171        let m = forge_produced::durable_mount("fid");
2172        assert_eq!(m.target, PathBuf::from("/yah/produced"));
2173        assert!(!m.read_only, "the build must be able to write to it");
2174        assert_eq!(
2175            m.source,
2176            VolumeSource::Bind {
2177                host_path: PathBuf::from("/var/lib/yah/qed/produced/fid"),
2178            }
2179        );
2180    }
2181
2182    const HASH_64: &str = "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890";
2183
2184    #[test]
2185    fn blake_hash_accepts_64_hex() {
2186        let h: BlakeHash = toml::from_str(&format!("x = \"{HASH_64}\""))
2187            .map(|t: toml::Table| t["x"].as_str().unwrap().to_owned())
2188            .map(|s| serde_json::from_value(serde_json::Value::String(s)).unwrap())
2189            .unwrap();
2190        assert_eq!(h.0, HASH_64);
2191    }
2192
2193    #[test]
2194    fn blake_hash_rejects_wrong_length() {
2195        let short = "abcdef";
2196        let res: Result<BlakeHash, _> =
2197            serde_json::from_value(serde_json::Value::String(short.into()));
2198        assert!(res.is_err());
2199    }
2200
2201    #[test]
2202    fn blake_hash_rejects_non_hex() {
2203        let bad = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
2204        let res: Result<BlakeHash, _> =
2205            serde_json::from_value(serde_json::Value::String(bad.into()));
2206        assert!(res.is_err());
2207    }
2208
2209    fn image_ref(digest: &str) -> ImageRef {
2210        ImageRef {
2211            registry: "ghcr.io".into(),
2212            repository: "yah-ai/rusty-v8-musl-builder".into(),
2213            tag: "latest".into(),
2214            digest: digest.into(),
2215        }
2216    }
2217
2218    #[test]
2219    fn is_pinned_distinguishes_real_digest_from_sentinel() {
2220        assert!(!image_ref(ImageRef::UNPINNED_DIGEST).is_pinned());
2221        assert!(!image_ref(&testing::test_digest()).is_pinned());
2222        assert!(image_ref("sha256:deadbeef").is_pinned());
2223    }
2224
2225    #[test]
2226    fn pull_ref_pinned_carries_tag_and_digest() {
2227        assert_eq!(
2228            image_ref("sha256:deadbeef").pull_ref(),
2229            "ghcr.io/yah-ai/rusty-v8-musl-builder:latest@sha256:deadbeef",
2230        );
2231    }
2232
2233    #[test]
2234    fn pull_ref_unpinned_falls_back_to_tag_only() {
2235        // An unpinned catalog image (all-zeros sentinel) resolves by tag —
2236        // no store holds `…@sha256:0000…`, so the tag is the only usable key.
2237        assert_eq!(
2238            image_ref(ImageRef::UNPINNED_DIGEST).pull_ref(),
2239            "ghcr.io/yah-ai/rusty-v8-musl-builder:latest",
2240        );
2241    }
2242
2243    #[test]
2244    fn test_digest_alias_is_the_unpinned_sentinel() {
2245        assert_eq!(testing::TEST_DIGEST, ImageRef::UNPINNED_DIGEST);
2246    }
2247
2248    #[test]
2249    fn static_asset_workload_round_trips() {
2250        let src = format!(
2251            r#"
2252schema_version = "V1"
2253
2254[[asset]]
2255filename = "whisper/distil-large-v3-q5_1.bin"
2256source   = "sources/distil-large-v3-q5_1.bin"
2257blake3   = "{HASH_64}"
2258
2259[[asset]]
2260filename = "whisper/distil-large-v3-q4_0.bin"
2261source   = "sources/distil-large-v3-q4_0.bin"
2262blake3   = "{HASH_64}"
2263
2264[aliases]
2265"whisper-default" = "whisper/distil-large-v3-q5_1.bin"
2266"#
2267        );
2268        let w: StaticAssetWorkload = toml::from_str(&src).expect("parse");
2269        assert_eq!(w.assets.len(), 2);
2270        assert_eq!(w.assets[0].filename, "whisper/distil-large-v3-q5_1.bin");
2271        assert_eq!(w.assets[0].blake3.0, HASH_64);
2272        assert_eq!(w.aliases["whisper-default"], "whisper/distil-large-v3-q5_1.bin");
2273
2274        let back = toml::to_string(&w).expect("serialize");
2275        let w2: StaticAssetWorkload = toml::from_str(&back).expect("re-parse");
2276        assert_eq!(w, w2);
2277    }
2278
2279    #[test]
2280    fn license_round_trip_each_variant() {
2281        // Wire format is whatever serde's `rename_all = "kebab-case"` emits.
2282        // heck's kebab-case keeps letter→digit attached but splits digit→uppercase,
2283        // so `Apache2 → "apache2"` and `Bsd2Clause → "bsd2-clause"`.
2284        for (variant, on_wire) in [
2285            (License::Mit, "mit"),
2286            (License::Apache2, "apache2"),
2287            (License::Bsd2Clause, "bsd2-clause"),
2288            (License::Bsd3Clause, "bsd3-clause"),
2289            (License::Isc, "isc"),
2290        ] {
2291            let ser = serde_json::to_value(variant).expect("serialize");
2292            assert_eq!(ser, serde_json::Value::String(on_wire.into()));
2293            let back: License = serde_json::from_value(ser).expect("deserialize");
2294            assert_eq!(back, variant);
2295        }
2296    }
2297
2298    #[test]
2299    fn license_rejects_non_permissive_variants() {
2300        for unknown in ["GPL-3.0", "AGPL", "lgpl-2.1", "unknown", "MIT"] {
2301            let res: Result<License, _> =
2302                serde_json::from_value(serde_json::Value::String(unknown.into()));
2303            assert!(res.is_err(), "expected rejection for {unknown:?}");
2304        }
2305    }
2306
2307    #[test]
2308    fn fetch_source_round_trips() {
2309        let src = format!(
2310            r#"
2311url     = "https://example.invalid/upstream.bin"
2312blake3  = "{HASH_64}"
2313license = "mit"
2314"#
2315        );
2316        let fs: FetchSource = toml::from_str(&src).expect("parse");
2317        assert_eq!(fs.url, "https://example.invalid/upstream.bin");
2318        assert_eq!(fs.blake3.0, HASH_64);
2319        assert_eq!(fs.license, License::Mit);
2320
2321        let back = toml::to_string(&fs).expect("serialize");
2322        let fs2: FetchSource = toml::from_str(&back).expect("re-parse");
2323        assert_eq!(fs, fs2);
2324    }
2325
2326    #[test]
2327    fn fetch_source_rejects_unknown_license() {
2328        let src = format!(
2329            r#"
2330url     = "https://example.invalid/upstream.bin"
2331blake3  = "{HASH_64}"
2332license = "GPL-3.0"
2333"#
2334        );
2335        let res: Result<FetchSource, _> = toml::from_str(&src);
2336        assert!(res.is_err(), "expected non-permissive license to reject");
2337    }
2338
2339    #[test]
2340    fn asset_entry_derive_mode_round_trips() {
2341        let src = format!(
2342            r#"
2343schema_version = "V1"
2344
2345[[asset]]
2346filename = "whisper/distil-large-v3-q5_1.bin"
2347blake3   = "{HASH_64}"
2348
2349[asset.derive.fetch]
2350url     = "https://example.invalid/ggml-distil-large-v3.bin"
2351blake3  = "{HASH_64}"
2352license = "mit"
2353
2354[asset.derive.transform]
2355recipe = "whisper-quantize"
2356params = {{ quant = "q5_1" }}
2357"#
2358        );
2359        let w: StaticAssetWorkload = toml::from_str(&src).expect("parse");
2360        assert_eq!(w.assets.len(), 1);
2361        let entry = &w.assets[0];
2362        assert!(entry.source.is_none());
2363        let derive = entry.derive.as_ref().expect("derive present");
2364        assert_eq!(derive.fetch.url, "https://example.invalid/ggml-distil-large-v3.bin");
2365        assert_eq!(derive.fetch.license, License::Mit);
2366        let transform = derive.transform.as_ref().expect("transform present");
2367        assert_eq!(transform.recipe, "whisper-quantize");
2368        assert_eq!(transform.params.get("quant").map(String::as_str), Some("q5_1"));
2369
2370        let back = toml::to_string(&w).expect("serialize");
2371        let w2: StaticAssetWorkload = toml::from_str(&back).expect("re-parse");
2372        assert_eq!(w, w2);
2373    }
2374
2375    #[test]
2376    fn legacy_source_only_asset_serializes_without_derive_field() {
2377        // Verify the skip_serializing_if guards keep legacy TOMLs round-tripping
2378        // without ever emitting an empty `derive = ...` line.
2379        let src = format!(
2380            r#"
2381schema_version = "V1"
2382
2383[[asset]]
2384filename = "operator-curated.bin"
2385source   = "sources/operator-curated.bin"
2386blake3   = "{HASH_64}"
2387"#
2388        );
2389        let w: StaticAssetWorkload = toml::from_str(&src).expect("parse");
2390        let back = toml::to_string(&w).expect("serialize");
2391        assert!(!back.contains("derive"), "serialized output leaked a derive field: {back}");
2392        let w2: StaticAssetWorkload = toml::from_str(&back).expect("re-parse");
2393        assert_eq!(w, w2);
2394    }
2395
2396    /// W212/R518: the `[asset.derive.lock]` block round-trips through TOML, and
2397    /// is omitted from output when absent (so non-derive / unlocked assets stay
2398    /// clean).
2399    #[test]
2400    fn derive_lock_round_trips_through_toml() {
2401        let toml = r#"
2402url     = "https://example.invalid/config.json"
2403blake3  = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
2404license = "mit"
2405"#;
2406        let fetch: FetchSource = ::toml::from_str(toml).unwrap();
2407        let derive = AssetDerive {
2408            fetch,
2409            transform: Some(TransformSpec {
2410                recipe: "whisper-bundle-tar".into(),
2411                params: BTreeMap::new(),
2412            }),
2413            lock: Some(DeriveLock {
2414                input_hash: "1111111111111111111111111111111111111111111111111111111111111111".into(),
2415                output_blake3: "2222222222222222222222222222222222222222222222222222222222222222".into(),
2416            }),
2417        };
2418        let s = ::toml::to_string(&derive).unwrap();
2419        assert!(s.contains("[lock]"), "lock serialized: {s}");
2420        let back: AssetDerive = ::toml::from_str(&s).unwrap();
2421        assert_eq!(derive, back);
2422
2423        // Absent lock → no `[lock]` table in the output.
2424        let unlocked = AssetDerive { lock: None, ..derive };
2425        let s2 = ::toml::to_string(&unlocked).unwrap();
2426        assert!(!s2.contains("[lock]"), "unlocked must omit lock: {s2}");
2427    }
2428
2429    #[test]
2430    fn shape_static_asset_rejects_both_source_and_derive() {
2431        use crate::validate::{shape_static_asset, FieldPath, ShapeError};
2432
2433        let entry = AssetEntry {
2434            filename: "ambiguous.bin".into(),
2435            source: Some("sources/ambiguous.bin".into()),
2436            derive: Some(AssetDerive {
2437                fetch: FetchSource {
2438                    url: "https://example.invalid/x".into(),
2439                    blake3: BlakeHash(HASH_64.into()),
2440                    license: License::Mit,
2441                },
2442                transform: None,
2443                lock: None,
2444            }),
2445            blake3: BlakeHash(HASH_64.into()),
2446        };
2447        let w = StaticAssetWorkload {
2448            schema_version: SchemaVersion::V1,
2449            assets: vec![entry],
2450            aliases: BTreeMap::new(),
2451        };
2452        let err = shape_static_asset(&w).expect_err("XOR violated");
2453        match err {
2454            ShapeError::Field { path: FieldPath::Asset(0, "source"), .. } => {}
2455            other => panic!("expected Asset(0, \"source\") shape error, got {other:?}"),
2456        }
2457    }
2458
2459    #[test]
2460    fn shape_static_asset_rejects_neither_source_nor_derive() {
2461        use crate::validate::{shape_static_asset, FieldPath, ShapeError};
2462
2463        let entry = AssetEntry {
2464            filename: "empty.bin".into(),
2465            source: None,
2466            derive: None,
2467            blake3: BlakeHash(HASH_64.into()),
2468        };
2469        let w = StaticAssetWorkload {
2470            schema_version: SchemaVersion::V1,
2471            assets: vec![entry],
2472            aliases: BTreeMap::new(),
2473        };
2474        let err = shape_static_asset(&w).expect_err("XOR violated");
2475        match err {
2476            ShapeError::Field { path: FieldPath::Asset(0, "source"), .. } => {}
2477            other => panic!("expected Asset(0, \"source\") shape error, got {other:?}"),
2478        }
2479    }
2480
2481    #[test]
2482    fn shape_static_asset_accepts_either_mode() {
2483        use crate::validate::shape_static_asset;
2484
2485        let legacy = AssetEntry {
2486            filename: "a.bin".into(),
2487            source: Some("sources/a.bin".into()),
2488            derive: None,
2489            blake3: BlakeHash(HASH_64.into()),
2490        };
2491        let derived = AssetEntry {
2492            filename: "b.bin".into(),
2493            source: None,
2494            derive: Some(AssetDerive {
2495                fetch: FetchSource {
2496                    url: "https://example.invalid/b".into(),
2497                    blake3: BlakeHash(HASH_64.into()),
2498                    license: License::Apache2,
2499                },
2500                transform: None,
2501                lock: None,
2502            }),
2503            blake3: BlakeHash(HASH_64.into()),
2504        };
2505        let w = StaticAssetWorkload {
2506            schema_version: SchemaVersion::V1,
2507            assets: vec![legacy, derived],
2508            aliases: BTreeMap::new(),
2509        };
2510        shape_static_asset(&w).expect("both modes accepted");
2511    }
2512
2513    #[test]
2514    fn image_ref_string_form_rejects_bare_tag() {
2515        let res: Result<ImageRef, _> =
2516            serde_json::from_value(serde_json::Value::String("node:20".into()));
2517        let err = res.expect_err("bare-tag must reject");
2518        let msg = format!("{err}");
2519        assert!(msg.contains("digest"), "error should mention digest: {msg}");
2520    }
2521
2522    #[test]
2523    fn image_ref_string_form_accepts_digest_pinned() {
2524        let pinned = format!("node:20@sha256:{HASH_64}");
2525        let img: ImageRef =
2526            serde_json::from_value(serde_json::Value::String(pinned.clone())).expect("parse");
2527        assert_eq!(img.registry, "docker.io");
2528        assert_eq!(img.repository, "library/node");
2529        assert_eq!(img.tag, "20");
2530        assert_eq!(img.digest, format!("sha256:{HASH_64}"));
2531    }
2532
2533    #[test]
2534    fn image_ref_string_form_accepts_ghcr_with_pin() {
2535        let pinned = format!("ghcr.io/foo/bar:v1.7.4@sha256:{HASH_64}");
2536        let img: ImageRef =
2537            serde_json::from_value(serde_json::Value::String(pinned)).expect("parse");
2538        assert_eq!(img.registry, "ghcr.io");
2539        assert_eq!(img.repository, "foo/bar");
2540        assert_eq!(img.tag, "v1.7.4");
2541        assert!(img.digest.starts_with("sha256:"));
2542    }
2543
2544    #[test]
2545    fn image_ref_string_form_rejects_non_sha256_digest() {
2546        for bad in [
2547            "node:20@md5:abcdef",
2548            "node:20@sha1:abcdef",
2549            "node:20@sha256:",
2550            "node:20@sha256:zzznothex",
2551        ] {
2552            let res: Result<ImageRef, _> =
2553                serde_json::from_value(serde_json::Value::String(bad.into()));
2554            assert!(res.is_err(), "expected reject for {bad:?}");
2555        }
2556    }
2557
2558    #[test]
2559    fn image_ref_struct_form_rejects_missing_digest() {
2560        // Digest is now structurally required (R438-T3). Struct-form payloads
2561        // without `digest` must fail at serde-deserialize.
2562        let v = serde_json::json!({
2563            "registry": "ghcr.io",
2564            "repository": "noisetable/api",
2565            "tag": "v1.4.2",
2566        });
2567        let res: Result<ImageRef, _> = serde_json::from_value(v);
2568        assert!(res.is_err(), "missing digest must reject");
2569    }
2570
2571    #[test]
2572    fn image_ref_struct_form_round_trips_through_toml() {
2573        let img = ImageRef {
2574            registry: "ghcr.io".into(),
2575            repository: "ggerganov/whisper.cpp".into(),
2576            tag: "v1.7.4".into(),
2577            digest: format!("sha256:{HASH_64}"),
2578        };
2579        let toml_doc = toml::to_string(&img).expect("serialize");
2580        let back: ImageRef = toml::from_str(&toml_doc).expect("re-parse");
2581        assert_eq!(img, back);
2582    }
2583
2584    #[test]
2585    fn workload_envelope_dispatches_static_asset() {
2586        // Externally-tagged: the `static-asset` variant is a wrapping table
2587        // (R590-B3 flipped the Workload graph off internal `kind =` tags so the
2588        // whole spec is postcard-decodable over the kamaji UDS).
2589        let src = format!(
2590            r#"
2591[static-asset]
2592schema_version = "V1"
2593
2594[[static-asset.asset]]
2595filename = "foo/bar.bin"
2596source   = "sources/bar.bin"
2597blake3   = "{HASH_64}"
2598"#
2599        );
2600        let w: Workload = toml::from_str(&src).expect("parse");
2601        assert!(matches!(w, Workload::StaticAsset(_)));
2602    }
2603
2604    // ── R572-F1: lifecycle archetype discriminator ─────────────────────────
2605
2606    fn archetype_test_spec(name: &str) -> WorkloadSpec {
2607        WorkloadSpec::for_forge(
2608            name,
2609            ImageRef {
2610                registry: "ghcr.io".into(),
2611                repository: "yah/test".into(),
2612                tag: "latest".into(),
2613                digest: testing::test_digest(),
2614            },
2615            TierTag("infra".into()),
2616            vec![],
2617        )
2618    }
2619
2620    #[test]
2621    fn explicit_archetype_round_trips_through_json_and_wins_over_inference() {
2622        for archetype in [
2623            LifecycleArchetype::Server,
2624            LifecycleArchetype::Appliance,
2625            LifecycleArchetype::Job,
2626        ] {
2627            let mut spec = archetype_test_spec("explicit");
2628            // Volumes present + restart_policy Always would infer Appliance
2629            // (see effective_archetype_infers_* below) — deliberately
2630            // mismatched against every archetype under test so the
2631            // assertion actually proves the explicit field wins, not that
2632            // it happens to agree with inference.
2633            spec.volumes = vec![VolumeMount {
2634                source: VolumeSource::Named { name: "data".into() },
2635                target: PathBuf::from("/data"),
2636                read_only: false,
2637            }];
2638            spec.restart_policy = RestartPolicy::Always;
2639            spec.archetype = Some(archetype);
2640
2641            let json = serde_json::to_string(&spec).expect("serialize");
2642            assert!(
2643                json.contains("\"archetype\""),
2644                "explicit archetype must be present on the wire"
2645            );
2646            let back: WorkloadSpec = serde_json::from_str(&json).expect("deserialize");
2647            assert_eq!(spec, back, "spec did not survive JSON round-trip");
2648            assert_eq!(back.archetype, Some(archetype));
2649            assert_eq!(
2650                back.effective_archetype(),
2651                archetype,
2652                "explicit archetype must win over the volumes/restart_policy inference"
2653            );
2654        }
2655    }
2656
2657    #[test]
2658    fn archetype_serializes_as_null_when_none() {
2659        let mut spec = archetype_test_spec("omitted");
2660        spec.archetype = None;
2661        let json = serde_json::to_value(&spec).expect("to_value");
2662        // Postcard-native (R590-B3): no `skip_serializing_if` anywhere on the
2663        // graph, so every field is always on the wire — a None Option is an
2664        // explicit `null`, not an absent key. The binary UDS wire is positional
2665        // and requires the slot to be present.
2666        assert_eq!(json.get("archetype"), Some(&serde_json::Value::Null));
2667    }
2668
2669    #[test]
2670    fn spec_without_archetype_field_deserializes_to_none() {
2671        // Simulates an on-disk spec written before R572-F1: no `archetype`
2672        // key at all. Omitting the key must still parse to None (the additive-
2673        // default contract) even though we now always *emit* the field.
2674        let mut spec = archetype_test_spec("pre-existing");
2675        spec.archetype = None;
2676        let mut json = serde_json::to_value(&spec).expect("to_value");
2677        json.as_object_mut().unwrap().remove("archetype");
2678        let back: WorkloadSpec = serde_json::from_value(json).expect("deserialize");
2679        assert_eq!(back.archetype, None);
2680    }
2681
2682    #[test]
2683    fn effective_archetype_infers_appliance_from_volumes_when_field_absent() {
2684        // Pre-R572 behavior: a workload with a volume was understood (by
2685        // convention, never a type) to be stateful/pinned. Confirm that
2686        // meaning is preserved bit-for-bit through effective_archetype().
2687        let mut spec = archetype_test_spec("appliance-inferred");
2688        spec.volumes = vec![VolumeMount {
2689            source: VolumeSource::Named { name: "pgdata".into() },
2690            target: PathBuf::from("/var/lib/postgresql/data"),
2691            read_only: false,
2692        }];
2693        spec.restart_policy = RestartPolicy::Always;
2694        spec.archetype = None;
2695        assert_eq!(spec.effective_archetype(), LifecycleArchetype::Appliance);
2696    }
2697
2698    #[test]
2699    fn effective_archetype_infers_job_from_restart_never_when_field_absent() {
2700        // Pre-R572 behavior: RestartPolicy::Never + no volumes is the forge
2701        // run-once convention (see RestartPolicy::Never's own doc comment) —
2702        // structurally a job. WorkloadSpec::for_forge already produces
2703        // exactly this shape; isolate the pure-inference path by clearing
2704        // the explicit archetype for_forge now sets.
2705        let mut spec = archetype_test_spec("job-inferred");
2706        assert!(spec.volumes.is_empty());
2707        assert!(matches!(spec.restart_policy, RestartPolicy::Never));
2708        spec.archetype = None;
2709        assert_eq!(spec.effective_archetype(), LifecycleArchetype::Job);
2710    }
2711
2712    #[test]
2713    fn effective_archetype_defaults_to_server_as_the_common_case_when_field_absent() {
2714        // Pre-R572 behavior: no volumes + a restartable policy (the common
2715        // stateless-web-server shape) inferred as movable/fungible.
2716        let mut spec = archetype_test_spec("server-inferred");
2717        spec.restart_policy = RestartPolicy::Always;
2718        spec.archetype = None;
2719        assert_eq!(spec.effective_archetype(), LifecycleArchetype::Server);
2720    }
2721
2722    // ── R594-F2: public-ingress appliance (container-shaped, not a new
2723    // Workload variant — see Workload::Container's doc comment) ───────────
2724
2725    #[test]
2726    fn ingress_marked_spec_is_appliance_and_carries_public_ip_placement_requirement() {
2727        let mut spec = archetype_test_spec("public-ingress");
2728        spec.archetype = Some(LifecycleArchetype::Appliance);
2729        spec.annotations.insert(
2730            REQUIRES_TAINT_ANNOTATION.to_string(),
2731            PUBLIC_IP_TAINT.to_string(),
2732        );
2733
2734        assert_eq!(
2735            spec.effective_archetype(),
2736            LifecycleArchetype::Appliance,
2737            "ingress must be pinned-per-node/non-drainable, the R572 appliance sense"
2738        );
2739        assert_eq!(
2740            spec.requires_taint(),
2741            Some(PUBLIC_IP_TAINT),
2742            "ingress must declare it can only land on a public-ip-tainted node"
2743        );
2744
2745        // No taint exists to match against yet (R572-F3) and nothing
2746        // enforces placement yet (R572-F5) — confirm this ticket stays
2747        // declarative-only by checking a spec with no requirement stays
2748        // unaffected.
2749        let unrelated = archetype_test_spec("unrelated");
2750        assert_eq!(unrelated.requires_taint(), None);
2751    }
2752
2753    #[test]
2754    fn ingress_marked_spec_round_trips_through_json_as_a_container_workload() {
2755        // Mirrors the on-disk envelope: the externally-tagged `container`
2756        // variant wrapping the WorkloadSpec, exactly like every other
2757        // container-shaped workload. No new Workload variant, no new
2758        // discriminator.
2759        let mut inner = archetype_test_spec("public-ingress");
2760        inner.archetype = Some(LifecycleArchetype::Appliance);
2761        inner.annotations.insert(
2762            REQUIRES_TAINT_ANNOTATION.to_string(),
2763            PUBLIC_IP_TAINT.to_string(),
2764        );
2765        let workload = Workload::Container(inner.clone());
2766
2767        let json = serde_json::to_string(&workload).expect("serialize");
2768        assert!(json.contains("\"container\""));
2769        assert!(json.contains(REQUIRES_TAINT_ANNOTATION));
2770        assert!(json.contains(PUBLIC_IP_TAINT));
2771
2772        let back: Workload = serde_json::from_str(&json).expect("deserialize");
2773        match back {
2774            Workload::Container(spec) => {
2775                assert_eq!(spec, inner);
2776                assert_eq!(spec.effective_archetype(), LifecycleArchetype::Appliance);
2777                assert_eq!(spec.requires_taint(), Some(PUBLIC_IP_TAINT));
2778            }
2779            other => panic!("expected Workload::Container, got {other:?}"),
2780        }
2781    }
2782}