Skip to main content

cloud/
config.rs

1//! @yah:ticket(R040-F16, "pg-on-mesh service recipe: bind tailscale0 + pg_hba.conf snippet + ufw rules")
2//! @yah:at(2026-05-05T00:32:34Z)
3//! @yah:assignee(agent:claude)
4//! @yah:status(review)
5//! @yah:parent(R040)
6//! @yah:handoff("Companion to R040-F15. Inter-node TCP (Postgres primary↔replica, NATS clusters, anything raw-protocol) lives on the Headscale mesh, not on Hetzner public IPs. Each node has a stable 100.64.x.x mesh IP that survives replacement of the underlying box, so DNS / config / pg_hba never churn when a CPX-11 is rebuilt. WireGuard already encrypts the wire — TLS becomes defense-in-depth, not load-bearing. This ticket carries the concrete pg-shaped recipe so the first stateful service deploy doesn't have to re-derive the pattern; subsequent services (redis, NATS, etc.) cargo-cult from it.")
7//! @yah:next("ServiceConfig gains a `bind_interface: Option<String>` field (e.g. `Some(\"tailscale0\")` for mesh-only services). The cloud-init/podman compose renderer translates this into either `--network host` + `pg listen_addresses = '<mesh-ip>'` OR a podman macvlan/host-binding pattern that achieves the same.")
8//! @yah:next("Generated pg_hba.conf snippet: allow the mesh subnet (100.64.0.0/10) for replication + app users. Postgres binds to the node's tailscale0 mesh IP only — `listen_addresses` is templated from the node's `tailscale ip --4` at first boot.")
9//! @yah:next("Generated ufw rules: `ufw allow in on tailscale0 to any port 5432; ufw deny 5432` — mirrors the existing yah-yubaba 7443 pattern in mirror.yml. Same shape works for any mesh-only port.")
10//! @yah:next("Replica connection string uses primary's mesh IP, NOT its public IP. Stable across box replacement.")
11//! @yah:next("Out of scope: pg_basebackup orchestration, failover, WAL archiving — those belong in noisetable's domain; this ticket only standardizes the binding/firewall/auth shape so noisetable's pg deployment doesn't reinvent it.")
12//!
13//!
14//! @yah:ticket(R323-F9, "Add sync-wave ordering to ServiceComponent (deploy-panel wave order)")
15//! @yah:assignee(agent:claude)
16//! @yah:at(2026-05-26T15:20:25Z)
17//! @yah:status(review)
18//! @yah:phase(P2)
19//! @yah:parent(R323)
20//! @yah:next("ServiceComponent gains a wave/order field (or depends_on between components) so the deploy panel (R323-F4) can group workload rollout rows into sync waves (wave 0 parallel, wait healthy, wave 1, …). Today all components are implicitly wave 0.")
21//! @yah:next("compute_service/compute_cell in reconciler/sync_status.rs surface the wave per workload so F4 doesn't re-derive it.")
22//! @yah:gotcha("Until this lands, F4 should render every workload as wave 0 (no ordering).")
23//! @yah:handoff("Added wave: u32 (serde default=0, skip_serializing_if zero) to ServiceComponent in config.rs. Added is_zero_u32 helper. Fixed the three struct literal call-sites that now need wave: 0 (config.rs test, local_sim.rs x2, mesofact_static.rs). Added wave?: number to the TS ServiceComponent interface with a doc comment. Deploy panel now reads c.wave ?? 0 for each WorkloadRow instead of hardcoded 0. SyncFooter computes maxWave from the components array and renders 'wave 0' (all-zero case) or 'waves 0–N' (multi-wave). All 218 cloud lib tests pass; bun run typecheck clean.")
24//! @yah:verify("cargo test -p cloud --lib  # 218 passed")
25//! @yah:verify("cd packages/yah/ui && bun run typecheck  # no new errors")
26//! @yah:verify("In service.toml: add wave = 1 to a component, rebuild, open the deploy panel — that workload row shows 'w1' badge; SyncFooter shows 'waves 0–1'")
27//! @yah:verify("Component with no wave field in TOML deserializes as wave=0 (default). Saving a wave=0 component omits the field from the output TOML (skip_serializing_if).")
28//!
29//! @arch:see(.yah/docs/working/W142-pond.md)
30//!
31//! @yah:relay(R615, "Linked infra sources: sources.toml overlay so a camp can borrow another camp's substrate")
32//! @yah:at(2026-07-20T18:18:05Z)
33//! @yah:status(open)
34//! @arch:see(.yah/docs/working/W274-linked-infra-sources.md)
35//!
36//! @yah:ticket(R615-F1, "InfraSource types + SourcesConfig::load(infra_dir) parsing .yah/infra/sources.toml")
37//! @yah:status(review)
38//! @yah:assignee(agent:bundle-anthropic-miravel)
39//! @yah:at(2026-08-08T19:55:57Z)
40//! @yah:phase(P1)
41//! @yah:parent(R615)
42//! @yah:next("Add InfraSourceKind { Path { path }, Git(GitSource) } + InfraSource { owner, kind, mode, select } to cloud/src/config.rs. Reuse the existing GitSource (config.rs:1205, { repo, ref, subdir }) verbatim — do not invent a second git-source shape.")
43//! @yah:next("SourcesConfig::load(infra_dir) reads .yah/infra/sources.toml (schema_version = 1, ordered [[source]] array). Absent file = empty list, never an error — every existing camp has no sources.toml.")
44//! @yah:next("mode is the write-gate: read-only (borrower cannot mutate) vs owner-manages. Model it as an enum, not a bool, so a future read-write-with-approval tier is additive.")
45//! @yah:verify("cargo check -p cloud && cargo test -p cloud")
46//! @arch:see(.yah/docs/working/W274-linked-infra-sources.md)
47//! @yah:tier(Cleric)
48//! @yah:handoff("InfraSourceKind{Path{path},Git(GitSource)} + SourceMode{ReadOnly,Manage} + InfraSource{owner,kind,mode,select} + SourcesConfig{schema_version,source} all landed in oss/yubaba/crates/cloud/src/config.rs (after default_git_ref, ~line 1550). GitSource reused verbatim -- Git(GitSource) wraps the existing R561 type unchanged, no second git-source shape. InfraSourceKind is internally tagged (#[serde(tag=\"kind\", rename_all=\"kebab-case\")]) and flattened into InfraSource so a [[source]] table reads exactly like W274's example: owner/kind/path-or-repo+ref+subdir/mode/select all at one table level. mode: SourceMode defaults ReadOnly via #[serde(default)] on the field (enum, not bool, per the ticket's own instruction -- Manage is the explicit escape hatch). SourcesConfig::load(infra_dir) returns Ok(default()) -- schema_version=1, empty source list -- when sources.toml is absent; only parses+errors when the file exists and is malformed.")
49//! @yah:handoff("Tree anchor 85801e7f. Pathspec: oss/yubaba/crates/cloud/src/config.rs (only file touched). Tests: cargo test -p yah-cloud --lib (from oss/yubaba) 710 passed / 0 failed / 4 ignored, +6 new over the 704 baseline your R707-T6 verification recorded (sources_load_is_empty_when_the_file_is_absent, sources_parses_a_path_kind_exactly_like_w274s_example, sources_parses_a_git_kind_reusing_gitsource_verbatim, sources_mode_defaults_to_read_only_and_manage_is_explicit, sources_preserves_declaration_order, sources_round_trips_through_serialize). cargo check -p cloud also green (implied by the test build).")
50//! @yah:handoff("Tree anchor at handoff: 85801e7f6b76b369c0c8ecd2e5c7874990cd9286 — the shared tree as I left it. Diff against it (`git diff 85801e7f6b76b369c0c8ecd2e5c7874990cd9286..HEAD`) to see what landed under you, and quote this SHA rather than 'HEAD' in any revert/restore instruction.")
51//! @yah:next("R615-F2 picks this straight up: overlay these sources into CloudConfig::load, tagging origin{owner,source} and merging camp-local-wins-on-collision.")
52//! @yah:handoff("Verified pre-existing work: InfraSourceKind{Path,Git(GitSource)} + SourceMode + InfraSource + SourcesConfig all present in oss/yubaba/crates/cloud/src/config.rs at tree anchor 871fde1c, matching the inline @yah:handoff notes already on this ticket. GitSource reused verbatim, no second git-source shape. This session added no new code -- only ran verification and closed the board state, which a prior session left stuck in `open` despite the work being done (code + handoff notes landed, but board.review/handoff was never called).")
53//! @yah:verify("cargo check -p yah-cloud -- clean (2 pre-existing unrelated warnings)")
54//! @yah:verify("cargo test -p yah-cloud --lib -- 723 passed; 0 failed; 4 ignored (from oss/yubaba)")
55//!
56//! @yah:ticket(R615-F2, "Overlay loader: resolve sources in CloudConfig::load, tag origin, camp-local wins on collision")
57//! @yah:status(review)
58//! @yah:assignee(agent:bundle-anthropic-miravel)
59//! @yah:at(2026-08-08T19:56:05Z)
60//! @yah:phase(P1)
61//! @yah:parent(R615)
62//! @yah:next("In CloudConfig::load, after loading camp-local machines/providers/rules, resolve each source to an infra root (git sources read from the .yah/cache/infra/ sync cache — load stays offline), load that root's machines/providers/rules, tag each entry with origin { owner, source }, and overlay UNDER camp-local. Camp-local wins on name collision.")
63//! @yah:next("The machine load site is config.rs:533 (load_dir::<MachineConfig>(paths::machines_dir(...))). Note config.rs:575 load_from_config_dir is a SECOND machine load site that deliberately skips the inherit_machines redirect for multi-root/sibling trees (W206) — decide explicitly whether sources overlay applies there too, and document the answer either way.")
64//! @yah:verify("cargo check -p cloud && cargo test -p cloud")
65//! @yah:verify("A camp with sources.toml [[source]] kind=path to a sibling camp sees that camp's machines in CloudConfig::load, each tagged with the source owner")
66//! @yah:gotcha("Cross-camp MachineConfig schema skew is real: noisetable ships an older machine schema (location/server_type/hosts_mirrors) while yah's use region/arch/[connect]. A borrowed source can carry fields the borrower's binary predates. Overlay load MUST tolerate/skip unparseable foreign entries per-file and warn — never fail the whole load.")
67//! @arch:see(.yah/docs/working/W274-linked-infra-sources.md)
68//! @yah:depends_on(R615-F1)
69//! @yah:tier(Warrior)
70//! @yah:handoff("Overlay landed in CloudConfig::load (oss/yubaba/crates/cloud/src/config.rs). After camp-local machines/providers/legacy-merge finish, SourcesConfig::load(paths::infra_dir(workspace_root)) resolves + overlay_infra_sources() merges each source's machines/providers UNDER what's already there -- camp-local wins any name collision, and among sources themselves the earlier-declared one wins (both proven by dedicated tests). Provenance is NOT a field on MachineConfig/ProviderConfig: added CloudConfig.machine_origins/provider_origins: BTreeMap<String, InfraOrigin> instead, keyed by name/id. Reason recorded in a doc comment on InfraOrigin -- MachineConfig/ProviderConfig are constructed by struct literal in test helpers across several crates (including crates/yah/agent-tools/src/cloud_tools.rs, which is fenced/live-owned this session), so widening either shape would have forced an edit there for zero semantic gain; origin is a property of the LOAD, not the machine.")
71//! @yah:handoff("GOTCHA closed: added load_dir_tolerant<T>() -- a per-file-tolerant sibling of the existing (strict) load_dir -- so one unparseable foreign machine/provider (schema skew) skips-with-a-tracing::warn! and never sinks the rest of that source's directory or this camp's own load. Proven by one_unparseable_foreign_machine_does_not_sink_the_rest_of_the_directory_or_the_load. load_dir itself is untouched -- camp-local files still hard-fail on a bad TOML, which is correct, only borrowed roots get the tolerant path.")
72//! @yah:handoff("Git sources: InfraSource::infra_root() resolves kind=path to <workspace_root>/<path>/.yah/infra (live tree, no I/O beyond building the path) and kind=git to paths::infra_source_cache_dir(workspace_root, owner)/infra -- a NEW path helper in paths.rs, also what R615-T3's `yah infra sync` target directory must be so the two line up. An unsynced git source (cache dir absent) overlays nothing and is explicitly NOT an error (test: an_unsynced_git_source_overlays_nothing_and_is_not_an_error) -- load() stays fully offline as W274 §3 requires.")
73//! @yah:handoff("select filtering implemented for machines only (name exact-match or literal mesh_tags membership -- not a glob engine, matches W274's own example verbatim) via machine_matches_select(); does NOT apply to providers -- documented as a deliberate choice, nothing in W274 or the ticket describes a provider-scoped filter.")
74//! @yah:handoff("EXPLICIT DECISION on the config.rs:575-equivalent gotcha (now load_from_config_dir): sources overlay does NOT apply there. Multi-root sibling config dirs (W206 layout (b)) are a second config root INSIDE the same camp, not a second camp -- .yah/infra/sources.toml is tied to paths::infra_dir(workspace_root) specifically, which has no well-defined meaning for an arbitrary config_dir. Documented in the function's doc comment and proven by load_from_config_dir_never_applies_sources_overlay (a sources.toml at the real workspace root does NOT leak into a load_from_config_dir call against a sibling .noisetable/ dir under that same root).")
75//! @yah:handoff("Tree anchor 85801e7f. Pathspec: oss/yubaba/crates/cloud/src/config.rs, oss/yubaba/crates/cloud/src/paths.rs (added infra_source_cache_dir + 1 test), oss/yubaba/crates/cloud/src/reconciler/mesofact_bundle.rs (CloudConfig test-literal fixed for the 2 new fields), app/yah/cli/src/cloud.rs (3 CloudConfig test-literal sites fixed, same reason). Tests: cargo test -p yah-cloud --lib (from oss/yubaba) 720 passed / 0 failed / 4 ignored, +10 over R615-F1's 710 baseline (9 overlay tests in config.rs + 1 in paths.rs). cargo build -p yah --lib (repo root) green -- confirms nothing downstream (agent-tools, cloud.rs, hub) broke from CloudConfig's two new fields.")
76//! @yah:handoff("Tree anchor at handoff: 85801e7f6b76b369c0c8ecd2e5c7874990cd9286 — the shared tree as I left it. Diff against it (`git diff 85801e7f6b76b369c0c8ecd2e5c7874990cd9286..HEAD`) to see what landed under you, and quote this SHA rather than 'HEAD' in any revert/restore instruction.")
77//! @yah:next("R615-T3 (yah infra sync) is unblocked and has everything it needs: paths::infra_source_cache_dir(workspace_root, owner) is the exact target directory to clone/pull git sources into, already matching what F2's overlay reads from.")
78//! @yah:next("R615-F4 (Infra tab origin badge, not in my assigned lane) can read CloudConfig.machine_origins/provider_origins directly -- no further backend plumbing needed for the badge itself.")
79//! @yah:handoff("Verified pre-existing work: overlay landed in CloudConfig::load (oss/yubaba/crates/cloud/src/config.rs) at tree anchor 871fde1c -- SourcesConfig::load resolves sources, overlay_infra_sources() merges under camp-local with camp-local-wins and earlier-source-wins collision rules, machine_origins/provider_origins BTreeMaps added to CloudConfig, load_dir_tolerant() added for per-file-tolerant foreign schema skew, InfraSource::infra_root() resolves path/git kinds, load_from_config_dir explicitly does NOT get the overlay (documented). Matches this ticket's own inline @yah:handoff notes. This session added no new code -- only ran verification and closed board state that a prior session left stuck in `open` despite the work being done.")
80//! @yah:verify("cargo check -p yah-cloud -- clean (2 pre-existing unrelated warnings)")
81//! @yah:verify("cargo test -p yah-cloud --lib -- 723 passed; 0 failed; 4 ignored (from oss/yubaba), includes overlay tests + load_dir_tolerant test + infra_source_cache_dir test in paths.rs")
82//!
83//! @yah:ticket(R605-F12, "Sovereign groups have no voting axis, so non-voting membership is inexpressible and the raft guard is enforced by an absent field")
84//! @yah:status(review)
85//! @yah:at(2026-08-20T05:15:30Z)
86//! @yah:assignee(agent:bundle-anthropic-ashguard)
87//! @yah:parent(R605)
88//! @arch:see(.yah/docs/working/W325-isolated-x86-build-capacity.md)
89//! @yah:next("OPERATOR INTENT (2026-08-19) that the model cannot currently record: us-west-003 is a NON-VOTING member of the us-west-001-based (prod) sovereign group, and us-west-011 is a DIFFERENT sovereign (dev) from 001/003. The dev/prod split is already declared correctly. The non-voting membership is not — us-west-003.toml declares no sovereign_group at all.")
90//! @yah:next("THE GAP: MachineConfig::sovereign_group is a single Option<String>, so membership is binary, and judge_join (oss/yubaba/crates/cloud/src/config.rs:459) permits a join IFF both sides declare the same non-None group. There is no way to say 'in this blast radius, but not quorum-eligible'.")
91//! @yah:next("WHY THAT IS ACTIVELY BAD, not just missing: today the ONLY thing refusing us-west-003 into the prod raft at the join gate is its ABSENT stamp. Its own file is emphatic it must never hold a raft node id ('a home-internet partition should never be able to stall the raft'), and that guarantee currently rests on a field nobody wrote. Stamping it prod to record the operator's real intent would REMOVE the guard. This is precisely the W305 failure mode that produced R742-T4: `no-voter` sat inert on three nodes asserting something nothing enforced.")
92//! @yah:next("PROPOSED SHAPE (recommended): a second axis, e.g. sovereign_role = voter | non-voter (default voter for back-compat, or make it required), with judge_join permitting a same-group join only for voters. Then us-west-003 stamps prod + non-voter, the intent is machine-readable, and the raft guard stops depending on omission. us-west-004 (R605-T7) would take the same shape.")
93//! @yah:next("TOUCHES TWO COPIES OF THE PREDICATE, do not fix only one: cloud::judge_join renders the camp-side refusal, but the predicate itself lives in workload_spec::sovereign::join_permitted because yubaba's POST /raft/add-learner gate asks the same question and there is deliberately no yubaba -> cloud edge. Also re-read `yubaba serve --sovereign-group`, whose node-side gate is narrower on purpose (an unset flag means 'declared nothing', not 'declared standalone').")
94//! @yah:gotcha("THE CODE AND THE OPERATOR CURRENTLY DISAGREE ABOUT 003, and a reader should know which is which before editing. judge_join's own doc comment asserts 'prod and dev are both stamped, and us-west-002/003/015 are deliberately not raft members' — i.e. R742-F1 modelled 003 as STANDALONE. The operator's model is that it is a NON-VOTING MEMBER of prod. Those are different claims, not a wording difference: standalone means no blast-radius relationship to 001 at all. Do not silently 'correct' either side; this ticket is the reconciliation.")
95//! @yah:gotcha("FLEET STATE AS DECLARED (2026-08-19): prod = us-west-001, us-south-001, us-east-001. dev = us-west-011, us-west-013, us-west-014. NO sovereign_group declared = us-west-002, us-west-003, us-west-015. Verify against the files rather than trusting this list — xtask/tests/fleet_sovereign_groups.rs pins the roster and will need updating in the same change (it also asserts the stamp parses as a TOP-LEVEL key, which matters because 003 has a long comment block before [allocatable] where a stamp would silently become a member of that table).")
96//! @yah:gotcha("SEPARATE AXIS, DO NOT ENTANGLE: mesh membership is not sovereign membership. The standing rule is ONE mesh for the entire fleet regardless of group (operator, 2026-08-19), so us-west-003 and us-west-011 enrolling in headscale is unrelated work with no design question in it — see R605-T10. A voting axis on sovereign_group must not become a reason to keep any node off the mesh.")
97//! @yah:gotcha("SHARED-TREE COLLISION, live 2026-08-20: R772 (Miravel:spade, session:ce6d74a9) is refactoring oss/yubaba/crates/cloud/src/validate.rs at the same time and the file is currently RED - error[E0425] cannot find function load_machines at validate.rs:753, a half-landed extraction of the machine-loading walk that check_inert_taints / check_retired_arch_tags / the new check_unroled_sovereign_members all duplicate. That error is NOT from this ticket. Told them by party.chat and asked them to absorb check_unroled_sovereign_members into load_machines rather than leave one holdout. Do not hand-fight the file.")
98//! @yah:gotcha("R772 ALSO BROKE THREE PRE-EXISTING INGRESS TESTS, again not this ticket: two_services_fronting_one_node_collate_into_one_front_door, a_cross_service_hostname_clash_is_reported_with_both_declarations, one_mirrors_broken_declaration_does_not_hide_the_rest - all failing with 'providers.compute.use = hetzner - no such provider'. Cause is their new CloudConfig::load(workspace_root) at validate.rs:750 inside collate_workspace_ingress; the fronted_mirror fixture declares the slot but never writes infra/providers/hetzner.toml, and CloudConfig::load runs cross_ref_validate. Left alone deliberately - peer-owned.")
99//! @yah:gotcha("TRAP THAT MADE THREE OF MY OWN TESTS PASS FOR THE WRONG REASON: the machine-lint sweeps SKIP unparseable TOMLs by design (a peer's half-written scaffold must not sink the sweep). So a test fixture missing a REQUIRED MachineConfig field - mesh_tags is the one that bites - is silently skipped, the lint finds nothing, and every assert-empty test passes vacuously. Only the one test asserting found.len() == 1 noticed. write_sovereign_machine now always writes mesh_tags = [] and carries a comment saying why. Check this before trusting any new test in cloud::validate.")
100//! @yah:verify("cargo test -p yah-workload-spec --lib sovereign (from oss/yah-base) -- 9 passed, 0 failed. Covers both new refusals (a_non_voting_member_does_not_join_its_own_group, a_non_voting_target_has_no_quorum_to_join), the back-compat pin (the_default_role_is_the_pre_r605_f12_meaning), and the one-spelling round-trip across TOML/CLI/JSON.")
101//! @yah:verify("cargo test -p yubaba --lib sovereign (from oss/yubaba) -- 13 passed, 0 failed. Includes a_non_voting_joiner_is_refused_by_role_not_by_group, a_non_voting_target_refuses_every_joiner, a_group_without_a_role_key_is_a_voter_not_a_refusal (the deployed-fleet back-compat seam), a_peer_reports_its_role_in_the_toml_spelling.")
102//! @yah:verify("cargo test -p yubaba --test raft_sovereign_group (from oss/yubaba) -- 11 passed, 0 failed, up from 8. Three new end-to-end against real single-node rafts: a_non_voting_member_of_the_same_group_is_refused, a_non_voting_leader_refuses_to_grow_its_quorum, a_node_publishes_its_role_and_the_leader_reads_it_there (which also proves the request body cannot vote a non-voter in - the leader dials the joiner).")
103//! @yah:verify("cargo test -p xtask --test fleet_sovereign_groups (from repo root) -- 2 passed, 0 failed. THE DECISIVE ONE: parses the real .yah/infra/machines/*.toml through the actual MachineConfig deserializer. Confirms us-west-003 = prod + non-voter on disk, all six pre-existing voters now stamped sovereign_role = voter explicitly, and neither key swallowed by a table header.")
104//! @yah:verify("cargo test -p yah-cloud --lib (from oss/yubaba) -- 891 passed, 3 failed, where all 3 failures were R772's ingress-collate tests and none were mine. A clean re-run is BLOCKED, not failing: R555's in-flight AdmissionGrant.secrets field breaks velveteen-exec, and yah-cloud is not a root workspace member so its dev-deps can only resolve from the oss/yubaba workspace. Re-run once R555 lands.")
105//! @yah:handoff("LANDED, operator chose the second-axis shape (Call 1 = A, 2026-08-20). sovereign_role = voter | non-voter now sits beside sovereign_group, and ONE predicate judges both: workload_spec::sovereign::join_permitted(Membership, Membership) where Membership { group: Option<&str>, role: SovereignRole }. Permitted iff same non-None group AND both sides Voter. Both copies of the predicate call it - cloud::judge_join (camp-side) and yubaba::sovereign_group::judge (node-side) - so the rule itself cannot drift; only the prose differs, which was already the R742-F1 split.")
106//! @yah:handoff("WHY THE ROLE IS CHECKED ON BOTH SIDES, since only the joiner half was asked for: a join grows a quorum and it takes two nodes. Refusing a non-voting JOINER is the us-west-003 case. Refusing a non-voting TARGET is the same assertion read from the other end - a box declared non-voting that is serving add-learner is already holding a raft seat its own declaration forbids, and permitting there would paper over the contradiction. Both refusals name the role rather than the group when the groups match, because a message reading 'cross-group join refused: prod and prod' reads as a bug in the check.")
107//! @yah:handoff("THE DEFAULT IS THE LOAD-BEARING DECISION AND IT IS DELIBERATELY PERMISSIVE. An absent sovereign_role resolves to Voter (MachineConfig::sovereign_membership, the ONE place the Option is resolved). Reason: before this field, declaring a group WAS declaring quorum eligibility, so absence has to keep meaning that or the change silently retires six live voters. The permissiveness is bounded at the other end by cloud::validate::check_unroled_sovereign_members, which makes `yah cloud validate` FAIL on a group stamp with no role beside it - so the default can be reached by choice but not by silence. MachineConfig::sovereign_role stays Option<SovereignRole> (not a defaulted plain field) precisely so that lint can tell 'chose voter' from 'never considered it'.")
108//! @yah:handoff("NODE-SIDE BACK-COMPAT SEAM, pinned by a test because it is a decision and not an oversight: a peer answering GET /raft/status with a sovereign_group but NO sovereign_role key - every yubaba built between R742-F1 and R605-F12, which today is the entire prod raft - is read as Voter, not refused. Refusing would freeze a stamped cluster's growth until every member was rolled, strictly worse than what the role guards against, and it is the same degrade-toward-prior-behaviour stance the module already took for the group. Residue, named rather than hidden in read_group's doc: a box whose machine.toml says non-voter but whose daemon predates the flag answers 'voter' and the node gate admits it. judge_join refuses it camp-side, which is where operator-driven joins go. Window closes per-group as its nodes carry the flag.")
109//! @yah:handoff("FILES: workload-spec/src/sovereign.rs (SovereignRole + Membership + role-aware join_permitted, +227). cloud/src/config.rs (sovereign_role field, sovereign_membership(), judge_join same-group role branch, SovereignRole re-exported from cloud::config). cloud/src/validate.rs (check_unroled_sovereign_members + UnroledSovereignMember). app/yah/cli/src/cloud.rs (lint wired: ERROR in `yah cloud validate`, WARNING in the apply preflight - same split as inert-taint/retired-arch-tag, because an unwritten role changes no placement decision and the machine may be declared in a tree this camp does not own). yubaba/src/{sovereign_group,lib,main}.rs (--sovereign-role flag, ServerState.sovereign_role, /raft/status publishes it always-never-null, gate both directions). yubaba-test-harness/src/solo_node.rs (solo_node_with_sovereign_role). .yah/infra/machines/*.toml (7 files). xtask/tests/fleet_sovereign_groups.rs + fleet_build_placement.rs. W325 section 3d.")
110//! @yah:handoff("ONE BEHAVIOUR CHANGE WORTH A SECOND OPINION: a node started with --sovereign-role non-voter AND a --raft-node-id now refuses EVERY add-learner. I judged that correct - it is a contradiction the operator should see loudly - but the symptom is 'joins mysteriously stop working' rather than a startup refusal. main.rs warns loudly at boot when that pair is present; I did NOT make it fatal, because refusing to start could brick a node mid-roll. Reconsider if it bites.")
111//! @yah:handoff("NOT DONE, and it is a HARD GATE: .yah/schema/machine.toml.schema.json has NOT been regenerated, so sovereign_role is absent from it and schema-drift-guard (scripts/check-schema-drift.sh, a step in .yah/qed/check.toml, run by CI on every push) WILL FAIL. Fix is `cargo run -p xtask -- emit-schemas` from the repo root - it was queued behind ~7 concurrent peer cargo builds for the whole session. Nothing else is required to make this pushable.")
112//! @yah:handoff("ALSO NOT RE-CONFIRMED: `cargo test -p yah-cloud --lib` needs a clean run. Its last real run was 891 passed / 3 failed with all three failures belonging to R772's ingress-collate work and none to this ticket. The re-run is BLOCKED not failing - R555's in-flight AdmissionGrant.secrets field breaks velveteen-exec, and yah-cloud is not a root workspace member so its dev-deps only resolve from the oss/yubaba workspace where that break lives. Re-run from oss/yubaba once R555 lands.")
113//! @yah:verify("cargo run -p xtask -- emit-schemas (from repo root) -- wrote 8 files, exit 0 after an 18m24s build queued behind ~7 concurrent peer cargo jobs. .yah/schema/machine.toml.schema.json now carries the sovereign_role property (anyOf SovereignRole | null, with the full doc comment) and the SovereignRole definition as a oneOf over the two string enums voter / non-voter. The schema-drift-guard gate for THIS ticket is closed.")
114//! @yah:gotcha("emit-schemas IS ALL-OR-NOTHING AND WILL PICK UP A PEER'S UNCOMMITTED WORK. Running it to close this ticket's machine-schema drift also regenerated .yah/schema/secret.toml.schema.json (+34) from R555-F5's in-flight SecretAccess::Recipes / RecipeMatch source. That output is CORRECT for the tree as it stands and was not hand-edited, but it means the schema diff in the working tree is not purely R605-F12's: machine.toml.schema.json (+32) is this ticket, secret.toml.schema.json (+34) is R555. Told Ashguard:spade by party.chat so they carry it with their commit rather than regenerating on top. Anyone splitting these commits needs to split the schema diff too.")
115//! @yah:handoff("ALL GATES CLOSED as of 2026-08-20. Both items listed as outstanding in the earlier handoff notes are done: emit-schemas ran (machine.toml.schema.json carries sovereign_role + the SovereignRole voter/non-voter enum, drift guard satisfied), and cargo test -p yah-cloud --lib is 896 passed / 0 failed once R555 and R772 settled. 45 tests green across workload-spec (9), yubaba lib (13), yubaba raft integration (11), yah-cloud lib (10 of this ticket's, within 896), xtask fleet (2). Ready for review. NOTE for whoever commits: the working tree's schema diff is not purely this ticket - .yah/schema/machine.toml.schema.json (+32) is R605-F12, .yah/schema/secret.toml.schema.json (+34) is R555-F5, both correct generated output from one emit-schemas run. Ashguard:spade has agreed to carry theirs.")
116//! @yah:verify("cargo test -p yah-cloud --lib (from oss/yubaba) -- 896 passed, 0 FAILED, 4 ignored. The blocked check from earlier is now clean: R555 landed the velveteen-exec and TransformRecipe.secrets fixes, R772's ingress-collate work settled (they replaced the CloudConfig::load in collate_workspace_ingress with a narrower machines-only loader, so cross_ref_validate can no longer fail the collate over an unrelated provider typo). All 45 R605-F12 tests across the four crates are green simultaneously on one tree.")
117//! @yah:verify("Confirmed by NAME rather than by total, since a passing count proves nothing about which tests ran: cargo test -p yah-cloud --lib -- role voter voting lists all ten of this ticket's cloud tests green - a_non_voting_member_is_refused_into_its_own_group, a_non_voting_target_has_no_quorum_to_grow, a_refusal_names_the_group_when_fixing_the_role_would_not_help, an_unwritten_role_still_joins_its_group, a_non_voter_is_still_in_the_group_it_names, sovereign_role_round_trips_and_is_omitted_when_unwritten, a_group_with_no_role_is_reported_with_the_declaring_file, either_stated_role_is_clean, a_machine_in_no_group_is_not_asked_for_a_role, unroled_findings_are_ordered_by_file_so_output_is_stable.")
118//!
119//! @yah:ticket(R876-B7, "Node taints are structurally inert for mirror-declared placements: you cannot drain a node, and it fails silently")
120//! @yah:at(2026-09-09T09:05:55Z)
121//! @yah:status(review)
122//! @yah:assignee(agent:bundle-anthropic-ashguard)
123//! @yah:parent(R876)
124//! @yah:severity(high)
125//! @yah:next("SECOND HALF, and it is what makes the relay's headline question answerable: a working taint must produce a MOVE, not a refusal. Today regions=[] narrowing to zero candidates makes select_matching (config.rs:2010) bail by design (\"a half-placed workload that reports success is worse than a failed apply\"). A drain wants the opposite outcome — re-place onto a remaining candidate — which needs the slot to have more than one eligible machine in the first place. Pair this with R870-F16 (door follows the candidate set) or the drill still ends in a 503.")
126//! @yah:verify("Reuse the drill rather than writing a new one: xtask/tests/apex_failover.rs already asserts the CURRENT (broken) taint behaviour against the real tree, so fixing this must flip those assertions — that is the regression gate. Then re-run the live half: taint us-east-001, confirm placement selects a different tag:cloud-runner machine, restore byte-exact, and confirm yah.dev stays 200 throughout.")
127//! @yah:gotcha("IT FAILS SILENTLY, WHICH IS THE SHARP EDGE. \"no-server\" is a legal taint key, so the config lint passes and `yah cloud` reports nothing. An operator draining a node before maintenance gets a green run and a workload that never moved. The only lever that actually changes placement today is editing `required.regions`, and that REFUSES at resolution (select_matching bails rather than half-placing) instead of failing over — so there is currently no way to evacuate a node at all.")
128//! @yah:next("Tier: Cleric — the mechanism is located and one-line-visible, but the choice between declarable repulsion and unconditional taint consultation changes the meaning of every existing placement in the fleet, and the fix has to land alongside a re-place path or it converts a silent no-op into a hard refusal.")
129//! @yah:gotcha("MEASURED, NOT INFERRED — R876-S2's drill, 2026-09-09. `taints = [\"public-ip\", \"no-server\"]` was written onto the REAL .yah/infra/machines/us-east-001.toml and the resolver still placed yah-marketing on us-east-001, unchanged. Restored byte-exact (diff empty, sha256 back to 17dd15e2..., git clean against blob d66ab6d8); yah.dev stayed 200 throughout and no mutating apply was run.")
130//! @yah:next("THE MECHANISM, traced by R876-S2 and not yet re-verified by the leader. Taint repulsion keys off `RequiredSpec::repel_archetypes`; that field is `#[serde(skip)]` (oss/yubaba/crates/cloud/src/config.rs:4067), so a slot declared in a mirror's `required = {...}` ALWAYS deserializes with it empty. `matches` (config.rs:4182) consequently never reads `machine.taints` at all. Confirm both line anchors before editing — the shared tree moves.")
131//! @yah:handoff("SEMANTICS LANDED — repel-by-default + declarable toleration. `RequiredSpec::repel_archetypes: Vec<LifecycleArchetype>` (`#[serde(skip)]`) is DELETED and replaced by `tolerates: Vec<String>` (`#[serde(default)]`, deserializable) at oss/yubaba/crates/cloud/src/config.rs:4319. `matches` (config.rs:4397) no longer iterates a field of `self`: it walks `machine.taints`, classifies each key through `taint_effect`, and rejects any `TaintEffect::Repels(_)` key the spec does not name in `tolerates`. That inversion is the only shape that survives a field the wire cannot carry — the old sense was opt-in-to-be-repelled, so a mirror-declared `required = {...}` always deserialized with an empty archetype set and `machine.taints` was never read at all. Entries are machine taint keys spelled exactly as the node writes them (`no-appliance`, not `appliance`), so the node side and the slot side share one vocabulary with no translation. NO WIRE OR SCHEMA SHAPE CHANGE: `RequiredSpec` is not a typed node in any emitted schema (a mirror stores `required` as a free-form value read by `MirrorProviderSlot::required()`), verified by `rg \"RequiredSpec|tolerates|repel_archetypes\" .yah/schema/*.json` — the only hits are prose inside a doc-comment description.")
132//! @yah:handoff("THE MIGRATION TABLE — measured against the real tree, not reasoned about. FLEET TAINTS, all nine machines (`grep -rE \"^\\s*taints\\s*=\" .yah/infra/machines/*.toml`): us-east-001 [public-ip]; us-south-001 [no-appliance, public-ip]; us-west-001 [public-ip]; us-west-002 [no-server, no-appliance]; us-west-003 [no-appliance]; us-west-011 []; us-west-013 []; us-west-014 []; us-west-015 [no-server, no-appliance]. THE LOAD-BEARING FACT that makes this migration small: `public-ip` is an AFFINITY key (`AFFINITY_TAINT_KEYS`, `taint_effect` -> Attracts), NOT repulsion — so repel-by-default does not touch the three nodes carrying it, us-east-001 included. Reading every taint as repulsion would have evicted the apex on the next apply; only the `no-<archetype>` class repels. Exactly four machines are repelled by an undeclared spec: us-south-001, us-west-002, us-west-003, us-west-015. LIVE PLACEMENTS — the three `required` blocks that exist on disk (`grep -rn required .yah/services/*/mirrors/*.toml`): (1) yah-marketing providers.bundle, cloud.toml:213, `{regions=[us-east], mesh_tags=[tag:cloud-runner]}` -> us-east-001, UNCHANGED (its only taint is the affinity key). (2) yah-cloud providers.compute, `{regions=[us-west], mesh_tags=[tag:cloud-runner]}` -> us-west-001, UNCHANGED (us-west-003 newly drops out of the candidate set, but it sat behind us-west-001 in file-name order at replicas=1, so the resolved answer is identical). (3) yah-cloud-admin providers.compute, same constraint -> us-west-001, UNCHANGED. NET: repel-by-default moves ZERO live placements, so no toleration had to be added to any file under .yah/services/ or .yah/infra/ and none was. No file under .yah/infra/machines/ or .yah/services/ was written by this ticket at all.")
133//! @yah:handoff("THE ONE PLACEMENT THAT DID MOVE, and it is a test fixture rather than a live slot — found by the test suite, not by the survey, which is why the survey alone was not sufficient. `xtask/tests/mirror_ingress.rs::a_constraint_with_replicas_two_places_two_nodes_on_both_sides_and_renders_both` builds a SYNTHETIC `required = {mesh_tags=[tag:cloud-runner], replicas = 2}` against the REAL fleet. Four machines carry tag:cloud-runner — in declaration order us-east-001, us-south-001, us-west-001, us-west-003 — and us-south-001 + us-west-003 both declare `no-appliance`, so the second slot moves us-south-001 -> us-west-001. My migration survey enumerated only the `required` blocks ON DISK and therefore missed it: at replicas >= 2 the candidate-set narrowing DOES change the answer even when replicas = 1 hides it. Recorded here because it generalises — any future slot that widens to replicas >= 2 over cloud-runners inherits this. Fixed at the site that caught it (mirror_ingress.rs:502) rather than by weakening the assertion, and the migration lever is asserted right beside it: a fourth fixture declaring `tolerates = [\"no-appliance\"]` recovers the exact pre-B7 pair [us-east-001, us-south-001] on BOTH resolvers, so an operator hitting this class of break can see the fix in the test that breaks.")
134//! @yah:verify("BASELINE MEASURED BEFORE EDITING, then re-measured after. `cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib` = 1129 passed / 0 failed / 4 ignored, exit 0 (the run completed and printed its result line before my first Edit; a deferred W298 skew advisory later named config.rs as modified during the watcher's quiet window, which was my own subsequent edit, not a peer's). AFTER: 1137 passed / 0 failed / 4 ignored, exit 0 — +8, exactly the eight tests added, and no pre-existing test broke. NOTE FOR RE-RUNNERS: `cargo test -p yah-cloud --lib` from the repo root FAILS with \"package `yah-cloud` cannot be tested because it requires dev-dependencies and is not a member of the workspace\" — yah-cloud lives in the oss/yubaba workspace, so the invocation needs `--manifest-path oss/yubaba/Cargo.toml`. Also `cargo check --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --all-targets` exit 0 and `-p yubaba --all-targets` exit 0 (yubaba consumes cloud, so it is where the field removal would have surfaced). The four warnings in both are pre-existing and in files this ticket did not touch (mesofact_static.rs unused imports, app_manifest.rs dead field, pond_door.rs unused fn, reconciler/mod.rs non-snake-case).")
135//! @yah:verify("EIGHT NEW UNIT TESTS in config.rs, covering the three shapes the brief asked for plus the migration invariants: an_undeclared_spec_is_repelled_by_a_repelling_taint (tainted machine excluded — asserted on a `toml::from_str` RequiredSpec, i.e. the mirror path reproduced exactly, not a hand-built literal); an_explicit_toleration_admits_the_tainted_machine_again (tolerated -> included, per-key not blanket, and it deserializes); an_untainted_machine_matches_exactly_as_before; an_affinity_taint_does_not_repel (public-ip on us-east-001 — the assertion that stands between this change and an evicted apex); select_matching_drops_a_tainted_candidate_and_keeps_the_rest (the set-level predicate: tainting candidate 1 moves the placement to candidate 2, and asking for both is a shortfall error not a half-placement); admission_preserves_archetype_scoped_repulsion_across_the_inversion (a Server spec built by `admission_spec` is still repelled by no-server and still NOT by no-appliance — the pre-B7 answer, which is what makes the admit_workload path behaviourally identical); describe_names_the_toleration_so_a_refusal_is_readable; a_toleration_alone_is_still_an_unconstrained_spec.")
136//! @yah:verify("REGRESSION GATE FLIPPED, not deleted. `cargo test -p xtask --test main` (note: xtask has ONE test target named `main`; `--test apex_failover` does not exist — apex_failover is a `mod` in xtask/tests/main.rs). Result 65 passed / 1 failed. xtask/tests/apex_failover.rs: the drill's finding-1 test was inverted and renamed every_repelling_taint_at_once_leaves_the_apex_bundle_exactly_where_it_was -> ..._now_makes_the_apex_node_ineligible; it now asserts that ONE repelling key is enough (checked before the all-three case so a regression handling only the union is still caught), that all three refuse, and that restoring us-east-001's real taint list [\"public-ip\"] puts the placement straight back. The module header was rewritten to say the hole is closed. ADDED repel_by_default_moves_no_live_placement_in_the_real_tree — the migration table as an executable artifact: it loads the real .yah/ tree, asserts all three live `required` blocks resolve to the same machines they did pre-B7, asserts none of them declares a toleration (so it is the undeclared shape being tested), and asserts the fleet-wide statement that exactly [us-south-001, us-west-002, us-west-003, us-west-015] are repelled by a bare spec — notably NOT us-east-001. THE ONE REMAINING FAILURE IS PRE-EXISTING AND NOT MINE: workload_envelope::every_on_disk_workload_toml_parses_through_the_envelope, on .yah/infra/state/sources/scrabcake/site/site/workload.toml (`unknown field routes`). That is R658-B1's documented class (routes written under [build]); the path is gitignored generated runtime state (`git check-ignore` -> .yah/.gitignore:29 `/infra/state/`), was never committed, and R658-B1's own @yah:next names this exact file. My change touches no workload-spec type — `git status --porcelain -- oss/yah-base/` is empty.")
137//! @yah:handoff("SCOPE BOUNDARY HELD, deliberately. yah-marketing's candidate set was NOT widened: `.yah/services/yah-marketing/mirrors/cloud.toml:213` still reads `required = { regions = [\"us-east\"], mesh_tags = [\"tag:cloud-runner\"] }` and only us-east-001 declares region us-east. So a working taint on the apex node still ends in a REFUSAL, not a move — `select_matching` bails on the emptied candidate set, which is the safe outcome and the same one drill finding 2 records for the membership axis. AN ACTUAL EVACUATION NEEDS THREE THINGS IN THIS ORDER: (1) B7, this ticket, which makes the taint readable at all; (2) R870-F16, so the front door follows the candidate set — filed and unstarted; (3) a widened `required` on the mirror. Doing (3) before (2) buys a workload that relocates and a yah.dev that 503s, which is why it was not done here. Both the inverted finding-1 test and the module header in xtask/tests/apex_failover.rs state that ordering at the site, so the next agent to read the drill cannot mistake \"the taint works now\" for \"the node is drainable now\". NO MUTATING COMMAND WAS RUN: no `yah cloud apply`, no hotship activation, and nothing under .yah/infra/machines/ was written (the three machine TOMLs showing modified were already modified at session start and their diffs touch no taint/region/mesh_tag line — checked).")
138//! @yah:handoff("GENERATED ARTIFACTS REGENERATED, and one of them is a peer's. `cargo run -p xtask -- emit-schemas` was required because my doc-comment rewrite on `MachineConfig::taints` lands in the schema `description` — schema_drift::committed_schemas_match_current_rust_types was red on machine.toml.schema.json. The regen also swept in mirror.toml.schema.json (+7 lines), which is NOT mine: it is a `passway_image` field carrying an R870-F16 doc comment, pre-existing uncommitted drift from whoever owns that ticket. My change cannot have caused it — RequiredSpec is not a typed node in any emitted schema. Regenerated per CLAUDE.md / the shared-tree rule that derived files are not ownable and a red drift gate whose signal decays to zero is the worse outcome. @Glimmerstone:griffin holds R870-F23 and the R870 line: the mirror schema now carries your passway_image description, so if you were about to regenerate, it is already done. Both schema files are the only two under .yah/schema/ that changed.")
139//! @yah:verify("STEP 0 — @Glimmerstone:griffin's R876-B5 (tenant-scoped hotship activation) INDEPENDENTLY CONFIRMED, all four checks green, nothing fixed. (1) `bash -n scripts/hotship.sh` clean. (2) `./scripts/hotship.sh --nodes us-east-001 --binaries mesofact` REFUSES with exit 1 and the message \"--services is required to ACTIVATE a bundle-serve app (mesofact)\" — it refuses rather than falling back to the old broad runtime-path pattern, and the guard sits at hotship.sh:507 ahead of the version stamp and every remote call. (3) `--dry-run --services yah-marketing` previews the scope without touching anything and the scoping is real: \"in scope [yah-marketing]: pid 619423 / pid 619436 bundle dd8bdfb75a53\" versus \"NOT restarted (out of scope): pid 614524 bundle 86b2fa81bf42 service noisetable\", ending \"dry run: nothing signalled / NOTHING was installed\". (4) noisetable's serve is ALIVE AND UNRESTARTED on us-east-001: pgrep shows pid 614524 off /var/lib/yah/kamaji/bundles/runtimes/mesofact/0.8.32/x86_64-unknown-linux-musl/serve, and `ps -o lstart` reads \"Wed Sep 9 07:45:39 2026\" — the expected pid at the expected unchanged start time, etime 01:01:38. `curl -sS -o /dev/null -w %{http_code} https://yah.dev/` = 200. No real hotship activation was run.")
140//! @yah:verify("BUILDS. `cargo build` (root workspace) exit 0 — run twice independently, 5m18s and 3m13s, both green; the root workspace is where the change surfaces beyond oss/yubaba because yah-cloud reaches the CLI through the [patch.crates-io] bridge. `cargo check --manifest-path oss/yubaba/Cargo.toml -p yubaba --all-targets` exit 0. Clean re-measure of `cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib` after all annotation writes: 1137 passed / 0 failed / 4 ignored, exit 0 — identical to the first post-change measurement, so the earlier W298 skew advisory naming config.rs was my own board_update writes landing doc-comment annotations in the module header, not a peer edit. A later advisory on the root build named app/yah/cli/src/cloud.rs, which is a live peer's file and not one this ticket touched; the build was exit 0 regardless. FILES CHANGED BY THIS TICKET, complete: oss/yubaba/crates/cloud/src/config.rs, xtask/tests/apex_failover.rs, xtask/tests/mirror_ingress.rs, .yah/schema/machine.toml.schema.json, .yah/schema/mirror.toml.schema.json. Nothing under .yah/infra/ or .yah/services/ was written, no git write/revert/checkout was performed, and every edit went through the editor.")
141//! @yah:handoff("LEADER DECISION, so the semantics question is settled and should not be reopened: MACHINE TAINTS REPEL BY DEFAULT, with an explicit `tolerates` on the slot to opt back in. The old design inverted the obvious meaning — a taint had no effect unless the WORKLOAD declared which taints repelled it, i.e. taints were opt-in-to-be-repelled, which is both backwards and precisely why they silently did nothing. `repel_archetypes` was deleted rather than kept behind a flag defaulted to the old behaviour (CLAUDE.md, \"break it, don't tape it\").")
142//! @yah:verify("LEADER RE-VERIFICATION: this courier independently re-checked all four of @Glimmerstone:griffin's R876-B5 live claims as its step 0 and confirmed every one — `bash -n` clean, the `--services` refusal exits 1 with no fallback to the old broad pattern, `--dry-run` scopes to yah-marketing while excluding noisetable, noisetable's pid 614524 still alive with `lstart` 07:45:39 unchanged, and yah.dev 200. Cross-courier verification is why R876-B5 could be signed off on more than its own author's word.")
143//! @yah:gotcha("THE MIGRATION WAS THE RISK AND IT CAME BACK EMPTY, WHICH IS THE THING TO KNOW: `public-ip` — the taint that looked most likely to be load-bearing — is an AFFINITY key, not a repulsion key, so none of the three live mirror-declared placements (yah-marketing bundle to us-east-001; yah-cloud and yah-cloud-admin compute to us-west-001) changed, and no toleration was needed anywhere on disk. The one placement that did move was a synthetic `replicas = 2` test fixture, where us-south-001's `no-appliance` taint now yields us-west-001; it was fixed at that site with a `tolerates` fixture proving the pre-B7 pair is still expressible. Do not read the empty migration as \"taints were unused\" — read it as \"the one taint in wide use happened to be on the affinity axis\".")
144//!
145//! @yah:ticket(R870-F23, "Render and supervise the inner door: the service.toml + domain-manifest join that feeds passway's PathRouter config")
146//! @yah:status(review)
147//! @yah:phase(P2)
148//! @yah:at(2026-09-11T00:25:14Z)
149//! @yah:assignee(agent:bundle-anthropic-ashguard)
150//! @yah:parent(R870)
151//! @yah:next("THE CONSUMER SIDE IS DONE AND ITS FORMAT IS FIXED (R870-T18, in review). A passway binary becomes a service's own inner door by setting PASSWAY_PATH_ROUTES_FILE to a JSON mount table: {\"schema_version\":1,\"routes\":[{\"mount\":\"\",\"upstreams\":[\"127.0.0.1:8081\"]},{\"mount\":\"/app\",\"upstreams\":[\"127.0.0.1:8082\"],\"headers\":{\"cross-origin-opener-policy\":\"same-origin\"}}]}. Parser + validation: oss/passway/crates/passway/src/path_routes_file.rs (serde, deny_unknown_fields, schema_version must be 1, empty table refused, mount-with-no-upstream refused; mount well-formedness and duplicate-mount rejection are left to PathRouter::new so there is exactly one validator). Proven end to end against a FORKED binary in oss/passway/crates/passway/tests/path_routes_file.rs. This ticket is the producer: write that file.")
152//! @yah:next("WHY THIS IS A SEPARATE TICKET AND NOT HALF OF R870-T18. T18's own escape clause names the criterion — \"a different crate, a different release cadence\" — and it is met twice over. (a) The consumer is oss/passway, an independently versioned crate with its own export mirror; the producer is oss/yubaba (the join) plus oss/yah-base (the wire type) plus oss/kamaji (supervision), which roll to the fleet on a different cadence. (b) Nothing can reach a live inner door today because there is NO WORKLOAD KIND for one: WorkloadSpec carries typed per-kind carriers (MesofactServeBundle at oss/yah-base/crates/workload-spec/src/lib.rs:1437) and a passway inner door needs its own — plus a kamaji-allocated port, a routes file materialized on the node, and a place in the bundle deploy sequence. Landing a planner that nothing calls would have been the half-build T18 forbade.")
153//! @yah:next("THE JOIN, PRECISELY — no new vocabulary, which is R870-F15's own claim and it holds up. Inputs: .yah/services/<svc>/service.toml (ServiceComponent { id, kind, mount, ... }, config.rs:3427) and .yah/domains/<zone>.toml (DomainRoute { path, headers, mode }, config.rs:4558, where front_door = passway). Per mount: mount = path_route::mount_from_component(component.mount) — that function already exists and is already the ONE place the \"app\"/None to \"/app\"/\"\" translation happens; headers = the DomainRoute whose route_path_prefix(path) equals normalize_mount(component.mount) (cross_ref_validate already PROVES those two agree, config.rs:1688-1725, so the join cannot silently mismatch); upstreams = the address of the deployed unit serving that mount. Only the last one is placement-time and is why this needs the workload kind above. Group by DEPLOYED UNIT, not by component: every bundle-tier component of a service shares ONE bundle workload (that is config 1, R870-B11), so config-1 mounts collapse to a single root upstream and only independently-deployed units earn their own mount.")
154//! @yah:next("THE TWO ADMISSION RULES, and where each one goes. Both belong to the GENERATOR, never to passway — passway proxies whatever PathRouter it is handed and has no view of how many components a service declares. (1) A service with ONE independently-deployed unit gets NO inner tier at all — enforce by construction: the planner returns Option<InnerDoorPlan> and answers None below two units, so there is no config to write and no process to supervise, and the negative is assertable on the ABSENCE of the plan rather than on a site staying up. (2) A component cannot be both bundle-staged (config 1) and its own workload. R870-B11 landed the config-1-internal half in CloudConfig::cross_ref_validate (config.rs:1621-1657, two bundle components at one mount are refused); put this half in the SAME loop rather than a parallel one. NOTE, checked not assumed: the second half is NOT EXPRESSIBLE TODAY — [providers.bundle] is a per-MIRROR slot, not per-component, so there is no way to say \"give this one component its own workload\" at all. The rule becomes writable in the same commit that introduces that vocabulary, which is this ticket. Do not invent the vocabulary separately.")
155//! @yah:gotcha("DESIGN WRINKLE FOUND WHILE BUILDING R870-T18, and it is an operator call, not a coding one. passway ALWAYS terminates TLS on its listener: TlsMode has exactly two variants, Manual and Acme (oss/passway/crates/passway/src/tls.rs:215), and main() unconditionally calls proxy_service.add_tls_with_settings(&listen, None, tls_settings). So an inner door on loopback still needs a cert on disk, and the outer door still needs PASSWAY_UPSTREAM_TLS=true plus an SNI to reach it. That works — T18's binary-level test does exactly this with an rcgen self-signed leaf — but it means the \"cheap inner tier\" costs a cert, a renewal story, and an upstream TLS handshake per request on loopback. The obvious fix is a plaintext listener mode, and it was deliberately NOT taken in T18: adding a way for a public-facing trust-boundary door to serve cleartext is a security decision with a blast radius past this relay. Decide it before building the supervisor, because it changes what the workload spec has to carry.")
156//! @yah:verify("A two-component service whose components deploy INDEPENDENTLY gets an inner door: one yah cloud apply leaves both https://<host>/ and https://<host>/app/ at 200, and curl -sI on /app/ carries cross-origin-opener-policy: same-origin AND cross-origin-embedder-policy: require-corp from the /app/* route in the domain manifest, while / carries neither.")
157//! @yah:verify("THE NEGATIVE, asserted on absence rather than on uptime: a single-component service (yah-marketing) produces NO inner-door config and NO inner-door process — no routes file materialized on the node, no extra supervised workload in kamaji's table, and a byte-identical workload spec to today. A unit test on the planner returning None is the cheap half; the node-side absence check is the half that matters.")
158//! @yah:gotcha("OPERATOR CALL ASKED AND NOT ANSWERED (R870 relay leader, session:abde2cbb, 2026-09-09). The TLS question in this ticket first gotcha was put to the operator as a three-way choice and the prompt timed out unanswered after 30 minutes, so it remains genuinely open — it was not skipped and not decided by default. The three options as framed, so whoever picks this up does not have to re-derive them: (A) add a plaintext listener mode gated so it is structurally impossible to combine with a public bind — refuse at config load unless the bind is loopback, keep it mutually exclusive with ACME/cert paths; this was the leader recommendation, on the grounds that it makes the inner tier actually cheap as R870-F15 design claimed while keeping the risk a bounded testable invariant rather than an operator remembering not to misconfigure it. (B) keep TLS everywhere and have F23 carry a cert-issuance plus renewal story for every inner door, which is safest by construction and already proven working in R870-T18 binary-level test with an rcgen self-signed leaf, but makes every service with 2+ independently-deployed components pay a cert, a renewal and a loopback handshake per request. (C) park the tier — nothing regresses, because config 1 (bundle staging, R870-B11, in review) already covers the deploy-together case, which is the one noisetable actually needs. THIS IS THE ONLY THING BLOCKING F23 DESIGN; the join itself, both admission rules and the workload-kind vocabulary are all specified in this ticket next entries and need no further decisions.")
159//! @yah:handoff("OPERATOR CALL ANSWERED 2026-09-09: option (A), the loopback-only plaintext listener. It was re-put with ONE fact the earlier framing did not have, and that fact inverts the safety argument the three options were weighed on: option (B) was never \"already proven working\". pingora defaults verify_cert: true (pingora-core-0.8.1/src/upstreams/peer.rs:479, read not assumed) and passway NEVER overrides it — there is no verify_cert anywhere in oss/passway/crates/passway/src. R870-T18's test drove the door from an HTTP client with danger_accept_invalid_certs, not from an outer passway, so the outer-to-inner leg was untested. Since no CA issues for 127.0.0.1, \"keep TLS everywhere\" required a SECOND unbuilt change — a way to disable or pin upstream certificate verification on a public-facing door — traded for encrypting a hop that never leaves the loopback interface. (A) is strictly the smaller security surface, not merely the cheaper one.")
160//! @yah:handoff("PASSWAY: TlsMode::Plaintext, selected by PASSWAY_TLS_MODE=plaintext (a third value on the EXISTING discriminator, not a new bool env var — one variable owns the listener's TLS mode). All guards live in ONE function, tls.rs parse_listener_tls_mode, and each is a boot failure naming what to change: the bind must parse as a LITERAL loopback SocketAddr (0.0.0.0:443 — the default — is refused, and so is a hostname this process cannot prove); PASSWAY_TLS_CERT/KEY must be unset, so a configured public door cannot go cleartext by ADDING a variable rather than removing two; LISTEN_FDS is refused outright because under socket activation PASSWAY_LISTEN is only the key pingora looks the socket up by and proves nothing about the bind. An unrecognized PASSWAY_TLS_MODE is now also a boot failure instead of a silent fall-through to manual. main() reads the mode BEFORE the cert paths (plaintext has none), branches to proxy_service.add_tcp(&listen), and build_tls_settings returns Err rather than panicking on the variant it can no longer be handed.")
161//! @yah:handoff("THE VOCABULARY, and admission rule 2 made UNREPRESENTABLE rather than refused. ServiceComponent gains deploy: DeployTier { Bundle (default), Workload } — oss/yubaba/crates/cloud/src/config.rs. That is the per-component slot [providers.bundle] could not express, and because it is ONE field with two values, \"both bundle-staged and its own workload\" has no spelling at all; there is no rule to enforce. What remained checkable — two components claiming one mount — went into R870-B11's EXISTING cross_ref_validate loop rather than a parallel one. That loop previously filtered on kind and so skipped the workload tier entirely; it now covers both tiers, and only the explanation branches (bundle/bundle = one storage prefix in one bundle; workload/workload = one prefix in the inner-door table; mixed = the mount names two things serving one prefix). skip_serializing_if on the default keeps every existing service.toml byte-identical.")
162//! @yah:handoff("THE JOIN: new module oss/yubaba/crates/cloud/src/inner_door.rs. plan(&ServiceConfig, &domains) -> Result<Option<InnerDoorPlan>>. Rule 1 is by construction — None below two DEPLOYED UNITS, so the negative is assertable on the absence of a plan. Grouping is per unit but mounts are per COMPONENT: N bundle components collapse to one DeployedUnit::Bundle yet keep N mounts, because a bundle sub-mount can carry route headers the root does not and the collapse-to-root shape would silently drop them. Headers come from the DomainRoute whose route_path_prefix equals the component's normalize_mount — cross_ref_validate already PROVES those agree, so the lookup cannot mismatch. Err is reserved for one case: two-plus units with no root mount, which would 503 every unclaimed path. routes_file() refuses an unresolved upstream instead of skipping the mount — a dropped mount does not 503, it falls through to the root and serves the WRONG component with a 200. passway_mount() composes with normalize_mount rather than trimming slashes a second time.")
163//! @yah:handoff("SUPERVISION: WorkloadSpec gains files: Vec<InlineFile { path, content, mode }> (oss/yah-base/crates/workload-spec/src/lib.rs, appended last, serde(default), no skip_serializing_if — postcard is positional, so every pre-existing spec decodes to an empty vec). kamaji's NATIVE backend writes them in spawn_child BEFORE exec and on every respawn (materialize_files, oss/kamaji/crates/kamaji/src/native.rs); containerd/docker/microvm call the new kamaji::reject_unmaterializable_files and REFUSE such a spec by name rather than starting a door against a file that is not there — a silently-skipped route table comes up healthy and routes wrongly, which is worse than not starting. InnerDoorPlan::workload(listen_port, address) renders Workload::Container: argv /usr/local/bin/passway, env PASSWAY_TLS_MODE=plaintext + PASSWAY_LISTEN=127.0.0.1:<port> (the 127.0.0.1 is literal, NOT a parameter, so a wrong port cannot make the door reachable) + PASSWAY_PATH_ROUTES_FILE, and the table itself as the one InlineFile. Not a new Workload variant: TenantPasswayWorkload earns one by carrying config kamaji acts on; an inner door's whole config is an argv, three env vars and a file, so a variant would buy only exhaustive-match churn in peer-owned kamaji-proto (the R572-F1 trade).")
164//! @yah:verify("cargo test -p passway (oss/passway) = 205 lib + 43 + 35 integration, 283 passed / 0 failed, up from the 275 baseline @Ashguard:abde2cbb recorded on R870-T21. 8 new lib tests in tls::tests and 2 new integration tests in tests/path_routes_file.rs. THE END-TO-END ONE IS THE POINT: a_cleartext_inner_door_serves_the_same_mount_table_with_no_certificate forks a REAL passway binary with no PASSWAY_TLS_CERT set at all and asserts the same two-mount split and the same per-mount COOP header over plain http:// — i.e. the tier the operator authorized actually costs a process and nothing else. Its negative, a_cleartext_door_on_a_reachable_bind_refuses_to_start, spawns the binary on 0.0.0.0:0 (the DEFAULT bind, so it is the exact misconfiguration that would make an inner door a public cleartext one) and asserts a non-zero exit whose message names the bind.")
165//! @yah:verify("cargo test -p yah-cloud --lib = 1150 passed / 0 failed (11 new in inner_door::tests, 2 new in config::tests). The cheap half of this ticket's own negative is a_single_unit_service_gets_no_inner_door plus several_bundle_components_are_one_unit_and_still_get_no_door — three components sharing one bundle are still ONE unit and still get no door, which is the case that would be easy to get wrong by counting components. cargo test -p yubaba --lib = 952/0. cargo test -p kamaji --lib --all-features = 208/0 (2 new; the materialization test asserts ORDERING by having the child cat the file into a second path, not merely that the file exists). cargo test -p yah-workload-spec --all-features = 205 + 101, 0 failed. cargo test --workspace --all-features in oss/kamaji = 18+208+5+303, all green in-package.")
166//! @yah:gotcha("ONE PRE-EXISTING FLAKE, DIAGNOSED NOT WAVED THROUGH. kamaji-bin's server::tests::tenant_passway::the_list_reports_the_digest_of_the_spec_it_was_deployed_with FAILS under `cargo test --workspace --all-features` in oss/kamaji, reproducibly, and PASSES 303/303 under `cargo test -p kamaji-bin --lib --all-features` both parallel AND --test-threads=1. So it is cross-PACKAGE contention, not in-package parallelism and not this change: the failing assertion is the second deploy failing to Ack after `free_port()` (server.rs ~:8667) handed back a port another package's test binary had taken between the probe and the bind — a TOCTOU in the helper. Nothing in this ticket adds a port or touches that path; WorkloadSpec::files cannot reach it, since Workload::TenantPassway carries a TenantPasswayWorkload and no WorkloadSpec at all. Worth a real fix (bind-and-hold instead of probe-and-release) but it is not this relay's.")
167//! @yah:gotcha("ROLL ORDER MATTERS AND IS NOT THE USUAL \"JSON IGNORES UNKNOWN KEYS\" ANSWER — flagged by @Ashguard:eclipse (session:e188ccc2, R881-T6) mid-session. All three prod voters now run kamaji+yubaba 0.8.37-h5 (us-south-001 and us-west-001 rolled 2026-09-09; us-east-001 on 0.8.37-h1/h2), all built BEFORE WorkloadSpec::files existed. WorkloadSpec has no deny_unknown_fields, so on the JSON leg an un-rolled node ignores the field exactly as R870-B6's `origin` did. The postcard leg is the one that does NOT forgive: it is positional and non-self-describing, so a new yubaba encoding a spec with a trailing `files` to an old kamaji decoder is a DESYNC, not an ignored key. Before deploying any inner door, confirm which codec that node's kamaji link uses (kamaji-proto/src/codec.rs) and roll kamaji first if it is postcard. Nothing regresses until something actually SETS files — every existing spec encodes an empty vec — but the ordering is a real constraint, not a formality.")
168//! @yah:handoff("WIDER THAN THE TITLE, all mechanical and all compiler-verified. Adding two fields to types this many call sites construct exhaustively meant ~45 initializer repairs across FOUR workspaces: oss/yah-base (workload-spec + local-driver), oss/kamaji (incl. peer-owned kamaji-proto/src/codec.rs and kamaji-containerd-core), oss/yubaba, and the root (crates/yah/hub, app/yah/cli). Each is one line — `files: Vec::new(),` or `deploy: Default::default(),` — with no semantic content; they were driven off E0063 spans, not grep, so none was guessed. NOTE the sweep needs --all-features AND `cargo test --no-run`: `cargo check --all-targets` alone missed sites behind feature gates and in examples/. ALSO REGENERATED (both are pure functions of the tree, so this is not authorship): .yah/schema/{workload,service}.toml.schema.json via `cargo run -p xtask -- emit-schemas` and packages/yah/workload-spec/index.ts via the export-ts bin. Both drift gates still report red because they compare against GIT, and this camp defers commits — they go green with the commit, and the regenerated content is correct.")
169//! @yah:handoff("PHASE 1 DONE — the tier EXISTS and every piece of it is proven in isolation: the cleartext listener (proven through a forked binary), the vocabulary, the join with both admission rules, the wire carrier, and node-side materialization + restart. What is NOT done is the last hop: nothing CALLS plan() yet, so `yah cloud apply` still produces no inner door. That is deliberate rather than abandoned — it is placement work with a live-fleet verify attached, and it is the whole of phase 2.")
170//! @yah:handoff("Tree anchor at handoff: 6f984b53a9dd1a291d29fe7d4cb544b47d4f65e6 — the shared tree as I left it. Diff against it (`git diff 6f984b53a9dd1a291d29fe7d4cb544b47d4f65e6..HEAD`) to see what landed under you, and quote this SHA rather than 'HEAD' in any revert/restore instruction.")
171//! @yah:next("ONE DESIGN QUESTION PHASE 1 LEFT OPEN, stated so it is not rediscovered as a bug. A bundle-tier component at a non-root mount now gets its own entry in the inner-door table pointing at the SAME bundle upstream, purely so the domain manifest's per-path response headers can be applied (see a_bundle_components_sub_mount_keeps_its_headers_and_the_bundle_upstream). That is correct for headers and harmless for routing, but it means the inner door re-states routing the bundle already does internally. If the outer door or the Worker is ALREADY applying those headers for a config-1 service, the inner door would apply them twice — check which tier owns route headers for a passway front door before wiring step 4, because R746 put ROUTE_HEADERS into the Cloudflare Worker and I did not confirm the passway-front-door equivalent.")
172//! @yah:verify("THE LIVE HALF, unrun and needing a fleet: a two-component service whose components deploy independently gets one inner door from one `yah cloud apply`, with https://&lt;host&gt;/ and https://&lt;host&gt;/app/ both 200 and `curl -sI` on /app/ carrying cross-origin-opener-policy: same-origin AND cross-origin-embedder-policy: require-corp while / carries neither. The config-side half of exactly that assertion is already green as inner_door::tests::each_mount_carries_only_its_own_routes_headers, and the transport-side half as the forked-binary cleartext test — what remains unproven is only that apply joins them. THE NEGATIVE'S node-side half is also unrun: for a single-component service (yah-marketing), assert NO routes file is materialized on the node and NO extra workload appears in kamaji's table.")
173//! @yah:next("PHASE 2 IS FIVE STEPS AND EVERY INPUT ALREADY EXISTS. (1) Call inner_door::plan(&svc.service, &cfg.domains) once per service in the apply path; Ok(None) is the common answer and means do nothing at all. (2) Allocate the loopback port. It is deliberately a PARAMETER of InnerDoorPlan::workload rather than config — which port is free is a property of the node — so this is the only genuinely new decision: either take it from kamaji's ledger (oss/kamaji/crates/kamaji/src/ports.rs) or pin one per service. (3) Resolve each DeployedUnit to an address for the `address` closure: DeployedUnit::Bundle is the service's one bundle workload (R870-B11), DeployedUnit::Component(id) is that component's own workload. (4) Deploy the rendered workload in the bundle deploy sequence — BEFORE the outer door is repointed, since the door 503s until its upstream is up. (5) Repoint the outer door's PASSWAY_UPSTREAMS at 127.0.0.1:&lt;port&gt; instead of at the bundle, via IngressPlan::resolve_upstreams (oss/yubaba/crates/cloud/src/reconciler/ingress.rs:397).")
174//! @yah:handoff("DEFECT IN THIS TICKET'S OWN CHANGE, CAUGHT IN REVIEW BY @Ashguard:eclipse (session:e188ccc2) AND FIXED BEFORE IT LEFT THE TREE. WorkloadSpec rides the postcard `Deploy` frame (kamaji-proto/src/messages.rs:373, and V7's own stanza names `Workload::Container(WorkloadSpec)` as what that frame carries), and kamaji-proto/src/version.rs states the rule twice: every field on a postcard message is mandatory and always encoded, and the only compatibility mechanism is a ProtocolVersion bump. V2/V4/V5/V6 were each exactly \"a field appended to a struct\" and each got one. `files` is that shape and I had not bumped. The reasoning that made me miss it is the one V6's stanza already refutes: `#[serde(default)]` makes an OLD spec decode fine, so the JSON leg really is unaffected — but `default` only affects DEserialization, so a new yubaba still ENCODES a length varint an old kamaji reads as the next field and misparses from there. Now V8, CURRENT = V8, with a stanza naming the wrong reasoning rather than only the rule. cargo test -p kamaji-proto --all-features = 33/0; oss/kamaji workspace = 18+208+5+303+2+2+2+1, 0 failed.")
175//! @yah:gotcha("CORRECTION TO THE FLAKE GOTCHA ABOVE — my characterization was too narrow and would mislead the next reader, so read this one instead. I wrote that the tenant_passway digest test is \"green 303/303 in-package, fails only workspace-wide\". @Ashguard:eclipse measured the counter-example on the same tree: `cargo test -p kamaji -p kamaji-bin --lib --all-features`, in-package and parallel, failed a DIFFERENT test in the same module — deploy_arms_the_declared_socket_and_stop_releases_it (server.rs:8590) — and it failed identically before my sweep. On my own later run the workspace-wide invocation came back 303/0. So the truth is: at least two tests in server::tests::tenant_passway are intermittently flaky in BOTH configurations, the cause is `free_port()` probe-and-release losing the port between the probe and the bind (server.rs ~:8667), and it predates R870-F23. Do NOT read an in-package red there as a regression, and do not read a single green run as proof either. The fix is bind-and-hold; it belongs to neither R870 nor R881 and is unfiled — @Ashguard:eclipse tried and board.open refused for want of a parent relay.")
176//! @yah:gotcha("CONSEQUENCE OF THE V8 BUMP FOR ANY FLEET OPERATION, not just for this relay — relayed by @Ashguard:eclipse (session:e188ccc2) who is holding the fleet on R881-T6, and worth acting on before the next roll. The tree is now ProtocolVersion::V8; EVERY node runs a pre-V8 pair (us-east-001 on 0.8.37-h1/h2, us-south-001 and us-west-001 on 0.8.37-h5, the other six on 0.8.28-0.8.34). Nothing is broken, because each node is internally matched and the protocol is a node-local UDS. What changed is that `hotship --binaries yubaba` ALONE — or `kamaji` alone — is now a footgun on every node: it puts a V8 binary against a V7 sibling, and per version.rs:71 that does not fail cleanly, it misreads every field after the desync, \"which is how a wrong image or a wrong volume mount gets deployed instead of an error\". Ship the PAIR. That was harmless before this ticket and is not now.")
177//! @yah:handoff("PHASE 2 LANDED — `yah cloud apply` now produces an inner door. All five steps, with the call sites. (1) PLAN: `service_inner_door` (app/yah/cli/src/cloud.rs:9212) calls `inner_door::plan` once per service; `Ok(None)` is the answer for every service on disk today and returns before anything else runs. (2) PORT: derived, not allocated — `inner_door::listen_port(service)` (oss/yubaba/crates/cloud/src/inner_door.rs:346). (3) RESOLVE: `InnerDoorPlan::resolve_addresses` (inner_door.rs:418) maps each unit to a mesh ident via `unit_ident` (:398) and looks it up with the new `ServiceRecordFanout::address_for_ident` (reconciler/service_discovery.rs:426). (4) DEPLOY: `deploy_inner_door` (cloud.rs:9274), called at the END of the deploy-phase closure in BOTH apply paths — `reconcile_root` (cloud.rs:11877) and `handle_mirror_up` (cloud.rs:7100) — so it is after every unit registered a record and before the front-door phase repoints anything. (5) REPOINT: `IngressPlan::point_at_inner_door` (reconciler/ingress.rs:438), called from `reconcile_ingress_edge` (cloud.rs:7726).")
178//! @yah:handoff("STEP 2 ANSWERED — the port is DERIVED from the service name, not taken from kamaji's ledger, and the three facts that decided it were read rather than assumed. (a) `LedgerPorts` is node-local (a JSON file beside the supervisor's state dir) and yubaba's HTTP surface exposes no allocation verb at all — yubaba/src/lib.rs routes /workloads/*, /services, /node/*, and nothing for ports — so an apply has no way to ask. (b) A stated number is HONOURED, not rejected, on the path this workload takes: R844-F14's pin rule bites inside `LedgerPorts::resolve_set`, and `NativeRuntime::resolve_declared_ports` (oss/kamaji/crates/kamaji/src/native.rs:280) filters `pin.is_none()` BEFORE calling it. That matters because `PASSWAY_LISTEN` must carry the number, and a number the node picks after the spec is rendered cannot be in it. (c) A collision is not representable: the ledger allocates on the workload's MESH ip, an inner door binds loopback, so 100.64.0.3:14210 and 127.0.0.1:14210 are different sockets. The window is 10000-19999, deliberately below Linux's default ephemeral floor (32768) where `pick_free_port`'s bind(:0) draws from. FNV-1a written out inline rather than `DefaultHasher`, whose stability std does not promise — this number goes into a deployed door's env AND the outer door's upstream list, and a toolchain bump silently moving it would repoint one tier and not the other.")
179//! @yah:handoff("THE OPEN HEADER QUESTION IS ANSWERED, AND THE ANSWER IS NO CHANGE — grounded by reading, not assumed. The question was whether the passway FRONT door also applies per-route response headers. It does not: `PassProxy::response_filter` (oss/passway/crates/passway/src/proxy.rs:700) iterates `ctx.route_headers`, and its own doc at :694 states that vector is empty for `RoutingStrategy::ByHost` — which is what every outer door is. So the outer tier owns no headers and there is no double-apply to resolve there. A THIRD tier the question did not name does apply them, and is worth recording: the mesofact bundle ORIGIN, via `MESOFACT_ROUTE_HEADERS` set by `add_declared_route_headers` (app/yah/cli/src/cloud.rs:8612). For a mount served by `DeployedUnit::Bundle` both that origin and the inner door apply the route's headers — but CONVERGENTLY, not duplicatively: both read the same `.yah/domains` route map, `PathRouter` does not strip the mount prefix (oss/passway/crates/passway/src/path_route.rs has no strip/rewrite), so both match the same request path, and both use insert-semantics (`HeaderMap::insert` in mesofact's `RouteHeaderTable::apply`, `insert_header` in passway) — one header, one value. Do NOT collapse it to one owner. The bundle origin's coverage is strictly WIDER: it applies headers for a declared route that has no component mount (a `/docs/*` route served out of the root bundle's dist), which the inner door has no entry for. And the inner door is the ONLY owner for a `DeployTier::Workload` mount, since nothing hands such a component a header table. The two are complementary; removing either loses headers somewhere.")
180//! @yah:handoff("PLUMBING BUILT BECAUSE STEPS 3 AND 5 NEEDED IT, all three of which did not exist. (1) `inner_door::component_workload_ident(service, component_id)` (inner_door.rs:371) — the mesh identity a workload-tier component registers under. It is a NAMING RULE stated here because nothing else states it: a bundle's ident is a mirror fact (`BundleSlot::workload_name`, renameable with `name = \"...\"`), but a workload-tier component has no slot of its own, since `[providers.*]` is per-kind-per-mirror — the exact gap `DeployTier` was added to close. Folded through `reconciler::native_support::sanitize_ident`, which I widened from private to `pub(crate) mod` (reconciler/mod.rs) rather than writing a second normalizer. Getting the ident wrong fails LOUDLY: `routes_file` refuses a mount whose unit resolved to nothing, naming the unit. (2) `ServiceRecordFanout::address_for_ident` — deliberately SINGULAR where `upstreams_for` is plural. An inner door proxies over loopback to a unit on its own node; handed a fleet-wide set it would dial across the mesh, which is not what the cleartext-listener safety argument assumed. Two nodes, two addresses is ambiguity (None), not load balancing. Port selection follows `port_for`'s discipline exactly (`kamaji::DEFAULT_PORT_NAME` first, then the sole anonymous port) so a unit resolves the same way at both tiers or neither. (3) `IngressPlan::point_at_inner_door` OVERRIDES where `resolve_upstreams`/`resolve_ports` fill in — it clears both halves and then goes through those same two methods, so this stays the only place in the crate writing those fields. The ticket's step 5 named `resolve_upstreams`; used alone it is WRONG, because it skips a rule that already has an `upstream_host` and every mirror on disk pins one. A pin names ONE unit, and fronting a two-unit service from one unit serves half the site and 503s the other half, so the pin has to lose here and nowhere else.")
181//! @yah:handoff("TWO PLACEMENT DECISIONS PHASE 2 HAD TO MAKE, both recorded at the site. (a) The inner door lands on the FRONT DOORS, not the workload nodes — the outer door dials 127.0.0.1, so a door anywhere else is a door the outer tier cannot reach. `ingress_topology` (cloud.rs:9230) recomputes `resolve_ingress_placements` + `plan_ingress` in the deploy phase to learn that set; both are pure, so this costs no network and cannot disagree with the front-door phase's own answer. (b) SELF-DISCOVERY IS TURNED OFF for an inner-door service. `PASSWAY_UPSTREAM_SOURCE=yubaba` makes the door poll for the fronted workload's records and use those INSTEAD of its static set — which would route straight past the inner door to whichever unit registered under the mirror's ident, silently undoing step 5. The rendered note says so in its own words rather than reusing R844-F20's \"NOT self-discoverable ... MANUAL step\" wording, because this is not a degradation: the address is derived and byte-identical on every apply. (c) A mirror with two units and NO declared front door SKIPS with a note rather than failing — `reconcile_mirror_ingress` already returns early on `plans.is_empty()`, so there would be no outer door to repoint and nothing that can 503. Every `shape = \"local\"` dev mirror is in that state; bailing there would have broken `yah mirror up`.")
182//! @yah:handoff("DISCOVERED WORK, FIXED IN THIS PASS, NOT FILED AS A FOLLOWUP. `cargo test -p yah-cloud --lib` was 1161/2 on arrival, and the two reds were NOT mine and NOT a flake: `cloud_init::tests::{rendered_runcmd_entries_are_all_strings, coordinator_prestage_only_for_standalone}`. Cause: oss/yubaba/crates/cloud/templates/mirror.yml:107-108, the two R858-F17 turso-backup-helper runcmd entries, were written as BARE YAML scalars containing a `: ` — which makes the whole entry parse as a Mapping, so cloud-init skips it and the helpers never land on a provisioned node. The file is committed and clean (last touched by a8f0d501, i.e. it regressed AFTER phase 1's 1150/0 measurement), no live peer owns it, and the fix is two lines: double-quote the entries and escape the inner quotes. Both tests are green and the comment at the site names the gate. This is a real provisioning defect, not just a red test — a node provisioned since a8f0d501 has no turso-backup-hydrate / turso-backup-tail, and R858-F17's own design makes durability-declaring workloads refuse to deploy without them. Worth a look at whether any node was provisioned in that window.")
183//! @yah:verify("PHASE 2 MEASURED, every number run by me and read. `cargo test -p yah-cloud --lib` = 1163 passed / 0 failed (baseline 1150; +13 — 6 in inner_door::tests, 4 in service_discovery::tests, 3 in ingress::tests). `cargo test -p yah --lib` = 1549 / 0 (+3 new in a new `inner_door_apply_tests` module). `cargo test -p xtask --test main mirror_ingress` = 13 / 0 (baseline 11; +2). `cargo test -p yubaba --lib` = 952 / 0, exactly the baseline. `cargo test -p passway` in oss/passway = 205 + 43 + 37 = 285 / 0 against the 283 baseline, and `cargo test -p kamaji --lib --all-features` = 217 / 0 against 208 — BOTH deltas are peers', not mine: I touched neither crate. Sweeps: `cargo test --workspace --all-features --no-run` clean, and the same in oss/yubaba clean (only the two pre-existing unused-import warnings in a peer's in-flight mesofact_static.rs). NO SCHEMA REGEN NEEDED — this pass added functions, constants and one module-visibility widening, and no serde-visible field on any generator input, so .yah/schema/*.json and packages/yah/workload-spec/index.ts are untouched by construction.")
184//! @yah:verify("THE NEGATIVE IS ASSERTED IN THREE PLACES, at three different altitudes, because it is the claim the live fleet rests on. (1) `xtask/tests/mirror_ingress.rs::no_service_on_disk_gets_an_inner_door` walks the REAL `.yah/services/` tree and asserts every service plans `None`. That is the strongest form available without a fleet: the only way to be wrong about it is for a service to acquire `deploy = \"workload\"`, at which point the test names the service. Sibling `every_services_derived_inner_door_port_is_distinct` pins the port derivation against the real service list. (2) `cloud::inner_door_apply_tests::a_single_unit_service_leaves_the_outer_door_exactly_as_it_was` builds a two-component fixture that is BYTE-FOR-BYTE the positive test's, with one word changed (`workload` -> `bundle`), and asserts the rendered `PASSWAY_UPSTREAMS` is still the mirror's pinned `noisetable.com=100.64.0.3:8080`. So the difference between the two outcomes is provably that one field. (3) `inner_door::tests::{a_single_unit_service_gets_no_inner_door, several_bundle_components_are_one_unit_and_still_get_no_door}` from phase 1, still green. THE POSITIVE: `a_two_unit_service_repoints_the_outer_door_at_its_inner_door` (outer door renders `noisetable.com=127.0.0.1:<derived>`, and the port is asserted equal to what the door itself binds — two call sites in two phases that must not be able to disagree) and `the_rendered_table_splits_the_mounts_and_carries_only_their_own_headers` (both units addressed, COOP+COEP on /app and ABSENT on the root).")
185//! @yah:gotcha("TRANSIENT BUILD FAILURE SEEN AND DISPROVEN, recorded so the next reader does not re-chase it. The first `cargo test --workspace --all-features --no-run` came back with `can't find crate for 'runner'` / `'agent_tools'` / `'camp_service'` and a linker failing on a dozen absent `.rlib`s (libgif, libzune_jpeg, libimagesize...) in crates this ticket never touched — the exact shape CLAUDE.md's orphan-gc warning describes. Followed that procedure rather than cleaning: `cargo orphan-gc log -n 300` names NONE of the missing artifacts (every entry in the window reads `deleted 0 artifacts`), so orphan-gc is NOT confirmed here. The likelier cause is plain target-dir contention: a `yah-release-check` QED pipeline was holding the same `/Users/leif/ss/yah/target` for 29 minutes alongside this build. Re-ran with nothing else on the key: CLEAN, zero errors. Not reproducible, orphan-gc log does not name it, and the artifacts were never deleted per its own record.")
186//! @yah:next("WHAT REMAINS IS THE LIVE HALF ONLY, and it is an operator call the R870 leader is holding — phase 2 deliberately landed code + tests and touched no node. The two assertions: (a) POSITIVE — a two-component service whose components deploy independently gets one inner door from one `yah cloud apply`, with https://&lt;host&gt;/ and https://&lt;host&gt;/app/ both 200 and `curl -sI` on /app/ carrying cross-origin-opener-policy: same-origin AND cross-origin-embedder-policy: require-corp while / carries neither. (b) NEGATIVE, node-side — for a single-component service (yah-marketing), NO routes file materialized under /var/lib/passway/routes and NO extra workload in kamaji's table. Note that (b) is now also asserted statically against the real tree by `xtask/tests/mirror_ingress.rs::no_service_on_disk_gets_an_inner_door`, so the node-side check is confirmation rather than discovery. BEFORE RUNNING (a): there is no service with `deploy = \"workload\"` on disk, so one has to be declared first — and the R870-B6/V8 roll-order gotcha on this ticket applies the moment anything actually SETS `WorkloadSpec::files`. Confirm the target node's kamaji link codec (kamaji-proto/src/codec.rs) and roll the kamaji+yubaba PAIR first if it is postcard.")
187//! @yah:next("ONE THING PHASE 2 DID NOT BUILD, named so it is not mistaken for done: there is still no FLEET deploy path for a `DeployTier::Workload` component. `reconcile_component` (app/yah/cli/src/cloud.rs:8264) dispatches on `component.kind`, and the only non-bundle arms are `container` — which `ContainerReconciler::up` guards on `MirrorShape::Local`, and `LocalProcessReconciler`, which is the camp/dev tier and registers as `local-process-&lt;service&gt;-&lt;env&gt;-&lt;component&gt;`. So on a real mirror such a component is deployed by hand today (`yah cloud workload deploy`). That is exactly why `inner_door::component_workload_ident` had to STATE the ident rather than look it up. The failure mode is loud rather than silent — a component registered under any other ident leaves its unit unresolved and `routes_file` refuses the whole table, naming the unit — but whoever wires that deploy path must make it register under `component_workload_ident(service, id)`, or change both sides together. Related and already filed: R523-F1 (a component kind that deploys a stateful binary to a fleet node) is the same missing arm seen from the other direction.")
188//! @yah:handoff("PHASE 2 COMPLETE — `yah cloud apply` produces an inner door. Everything above this entry is the detail: the five call sites, the derived-port argument, the header-ownership answer (no change — the outer passway door owns no route headers, proven at proxy.rs:694/700, and the bundle origin's overlap is convergent and strictly wider), the three pieces of plumbing built because steps 3 and 5 needed them, the two placement decisions, and the one mirror.yml provisioning defect fixed on the way through. Nothing was deployed and no node was touched, per the dispatch. Green: yah-cloud 1163/0, yah 1549/0, yubaba 952/0, xtask mirror_ingress 13/0, passway 285/0, kamaji 217/0, both --all-features --no-run sweeps clean. Git policy is `defer`, so nothing is committed — the diff is 6 files: oss/yubaba/crates/cloud/src/{inner_door.rs, reconciler/mod.rs, reconciler/ingress.rs, reconciler/service_discovery.rs}, oss/yubaba/crates/cloud/templates/mirror.yml, app/yah/cli/src/cloud.rs, plus xtask/tests/mirror_ingress.rs.")
189//! @yah:handoff("Tree anchor at handoff: 88533e01f7f578b1520b633d05846973fa47f608 — the shared tree as I left it. Diff against it (`git diff 88533e01f7f578b1520b633d05846973fa47f608..HEAD`) to see what landed under you, and quote this SHA rather than 'HEAD' in any revert/restore instruction.")
190//! @yah:handoff("PHASE 2 ACCEPTED BY THE RELAY LEADER (@Ashguard:hydra, session:39386823). `yah cloud apply` now produces an inner door: all five steps wired, plus three pieces of plumbing that did not exist (`component_workload_ident`, `ServiceRecordFanout::address_for_ident`, `IngressPlan::point_at_inner_door`), the derived-port decision argued from three read facts, and the open header question answered NO CHANGE with the proof at proxy.rs:694/700. Implemented by @Ashguard:blade (session:54a6be05). The detail is in the handoff entries above this one; this entry records only that it was accepted and on what evidence.")
191//! @yah:verify("WHAT IS DELIBERATELY NOT VERIFIED, and it is the operator's call rather than an oversight: the LIVE half. No node was touched, nothing was deployed, nothing committed (git policy is `defer`). Running it needs a service with `deploy = \"workload\"` declared — none exists on disk — and the moment anything actually SETS `WorkloadSpec::files`, this ticket's own V8 roll-order gotcha binds: confirm the target node's kamaji link codec (kamaji-proto/src/codec.rs) and roll the kamaji+yubaba PAIR, never one alone.")
192//! @yah:verify("INDEPENDENTLY RE-RUN BY A SECOND COURIER (@Ashguard:dove, session:60d4f41f) who did not implement it, because a courier's self-report is the inner gate and not the outer one. All six commands reproduced the claimed counts EXACTLY: yah-cloud 1163/0 (4 ignored), yubaba 952/0, passway 285/0 (205+43+37), kamaji --lib --all-features 217/0, yah --lib 1549/0 (1 ignored), workspace --all-features --no-run clean. Every content check held: `point_at_inner_door` at ingress.rs:438; `inner_door::plan` reached from the apply path via `service_inner_door` (cloud.rs:9219) through `deploy_inner_door` (cloud.rs:9274, invoked at 7100 and 11877) and the ingress repoint at 7726; the port confirmed a deterministic per-service pin (FNV-1a into 10000-19999, inner_door.rs:346) and NOT kamaji's ledger, with the native.rs:282 `pin.is_none()` justification verified at the site. The negative is asserted three times, not once. CAVEAT ON THE MEASUREMENT ITSELF: the camp skew detector flagged 4 of 6 runs SUSPECT — peers edited kamaji/src/microvm.rs, kamaji-bin/src/main.rs and cloud/reconciler/mesofact_bundle.rs mid-run — so these are shared-tree numbers, not a frozen-tree measurement.")
193//! @yah:verify("ONE CLAIM CORRECTED AND ONE DEFECT FOUND BY THAT RE-RUN, both recorded rather than smoothed over. (1) CORRECTION: `cargo test -p yah-cloud --lib` does NOT run from the repo root — yah-cloud is not a root workspace member and needs dev-dependencies; it only works from `oss/yubaba`. Anyone reproducing the 1163/0 above must cd there first. (2) DEFECT, pre-existing and NOT caused by this ticket: `embedded_template_matches_workspace_canonical` is green VACUOUSLY — it resolves the workspace root via CARGO_MANIFEST_DIR.ancestors() to oss/yubaba, whose .yah/ holds only a .gitignore, so it takes the bootstrap branch and asserts nothing, while the repo-root twin at .yah/infra/cloud-init/mirror.yml is 128 diff-lines stale and missing the whole R858-F17 turso-backup block. FILED AS R870-B25, not left here. Note `rendered_runcmd_entries_are_all_strings` is a DIFFERENT test, is genuinely green, and is the gate that really catches the colon-space footgun this ticket fixed.")
194//! @yah:gotcha("SUPERSEDED BY R870-F27, and the @yah:next that said otherwise has been removed from this block: containerd DOES materialize WorkloadSpec::files now, so an inner door is no longer pinned to native-capable nodes. The backend-check step this ticket told its reader to perform before deploying is gone. Still refusing: Docker and MicroVm. The single fact both halves read is kamaji::Backend::materializes_files (oss/kamaji/crates/kamaji/src/lib.rs), not a list in prose.")
195//!
196//! @yah:ticket(R885-T14, "No cap:bundle-serving mesh capability exists — bundle/almanac/passway workloads are placed with nothing modelling where they can run")
197//! @yah:status(review)
198//! @yah:at(2026-09-12T07:16:50Z)
199//! @yah:assignee(agent:bundle-anthropic-ashguard)
200//! @yah:parent(R885)
201//! @yah:severity(P3)
202//! @yah:next("FOUND WHILE DISPROVING R885-T13, and it is the real gap that ticket's false premise was standing next to. `cap:native-exec` exists and is honoured (config.rs:2353-2357 via wants_native_exec) for `yah.exec = native` Container specs. But the workloads actually running on the fleet — MesofactServeBundle / Almanac / TenantPassway, served by kamaji's BundleBackend and JitRuntime — have NO corresponding mesh capability at all. All four live workloads on us-east-001 are of those kinds. So placement for the entire class of workload this fleet actually runs is unmodelled: nothing declares which nodes can serve bundles, and nothing checks. It works today because there is effectively one node doing it, which is exactly the condition under which an unmodelled constraint stays invisible. THE SHAPE OF THE FIX IS ALREADY IN THE TREE: R860-T5 closed this same gap for native-exec. Follow it — a `cap:bundle-serving` capability declared in .yah/infra/machines/*.toml, a `wants_bundle_serving` predicate beside `wants_native_exec`, and the placement check wired the same way. Establish the right granularity first: whether bundle / almanac / tenant-passway want one shared capability or separate ones is a real design question, and the answer depends on whether a node can serve one kind and not another. Tier: Cleric. ITS NATURAL HOME IS R860's AXIS, NOT R885's — R885 is about workloads running unbounded once placed, this is about where they are placed at all. Filed under R885 because that is where it was found and where the evidence is; move it to R860 if that relay is still live. Not urgent: nothing is broken today, and the cost is that the first multi-node bundle placement decision will be made by something that has no model of the constraint.")
203//! @yah:handoff("GRANULARITY SETTLED BY OPENING KAMAJI, NOT BY GUESSING — and the answer is smaller than the ticket assumed. kamaji gates each backend on its own cargo feature + startup flag: BundleBackend on `bundle-serving` + `--bundle-cache-dir` + `--bundle-origin` (`attach_bundle_backend`, oss/kamaji/crates/kamaji-bin/src/main.rs:924), JitRuntime on `tenant-passway` + `--tenant-passway-dir` (:706). Independent flags means separate capabilities, not one shared tag. But only ONE of the three named in the ticket needs modelling today: (1) BUNDLE gets `cap:bundle-serving`. (2) TENANT-PASSWAY gets nothing — there is no placement decision to gate: `yubaba::tenant_passway::reconcile_once` runs inside a node's own yubaba and drives that node's own kamaji over the local UDS, so which node arms a domain is decided by `YUBABA_TENANT_PASSWAY_STATE_DIR`, not by a selector. A tag would have no reader, which is the same wrong-fact R860-T5 refused to state for `cap:microvm`. (3) ALMANAC gets nothing ever — kamaji refuses `Workload::Almanac` outright (\"almanac and static-asset live in yubaba's reconcilers\", kamaji-bin/src/server.rs:1846) and yubaba reconciles it, so it is never node-placed.")
204//! @yah:verify("MEASURED, every number an exit-visible run. `cargo test -p yah-cloud --lib` (oss/yubaba, CARGO_TARGET_DIR=/tmp/r885t14-target) = 1205 passed / 0 failed / 4 ignored. The baseline is 1200 and it is recoverable from this session's own output rather than asserted: the first post-edit run read 1195 passed / 5 FAILED, those five being pre-existing fixtures the new axis correctly broke (synthetic machines with no `mesh_tags`), so 1200 before, +5 new tests, 1205 after. `cargo test -p xtask --test main` = 69 passed / 0 failed (the real-tree suite, incl. all 11 mirror_ingress, all 4 apex_failover, all 4 fleet_build_placement). `cargo test -p xtask --doc` green. `cargo check -p yubaba --all-targets` (oss/yubaba) clean. `cargo check -p yah --all-targets` (root) clean — flagged SUSPECT by the camp build rail (peers edited app/yah/cli/src/camp.rs, mesh.rs, oss/yah-base/crates/keys/src/spec.rs, oss/yubaba/crates/yubaba/src/lib.rs mid-run); none of those is a file this ticket touched and the CLI's only contact with the change is `resolve_bundle_machines`, whose signature is unchanged.")
205//! @yah:handoff("WHAT LANDED. (1) `pub const BUNDLE_SERVING_MESH_TAG: &str = \"cap:bundle-serving\"` in oss/yubaba/crates/cloud/src/config.rs beside NATIVE_EXEC_MESH_TAG, carrying the node-side gate, why a positive capability and not a taint, and why there is no `cap:tenant-passway` beside it. (2) oss/yubaba/crates/cloud/src/reconciler/mesofact_bundle.rs: `with_bundle_capability(&RequiredSpec) -> RequiredSpec` (idempotent) and `ensure_bundle_capable(&MachineConfig, ..)`, wired into BOTH arms of `resolve_bundle_machines` — the constraint arm gets the tag appended to the derived mesh_tags, the literal `machines = [...]` pin is refused with an error naming the tag AND the .yah/infra/machines/<name>.toml to edit. (3) oss/yubaba/crates/cloud/src/reconciler/ingress.rs: `required_for_role(role, required)` applied in both `resolve_ingress_placements` and `resolve_ingress_candidates`, so the deployer and the discovery fanout stay set-for-set across the new axis — the property resolve_bundle_machines' own doc promises and which a bundle-only check would have broken. (4) .yah/infra/machines/us-east-001.toml declares the tag. (5) W338 §Placement consequences gains item 5.")
206//! @yah:handoff("THE ARCHITECTURAL POINT, because it is why this was not one line beside the native tag. `cap:native-exec` is read in `admission_spec`, which covers `Workload::Container` and NOTHING ELSE. A bundle never reaches that function — it is placed by `resolve_bundle_machines` off the mirror's `providers.bundle` declaration, a completely separate resolver that an operator writes by hand. So the gap was not \"one more tag in the same `if`\"; it was the same class of gap one resolver over. The rule the two instances share, now written into W338: a capability tag belongs wherever a SELECTOR chooses a node, not wherever a spec is admitted. Anything that picks a machine has to know what that machine's kamaji was started with, because every kamaji backend is an opt-in flag.")
207//! @yah:handoff("THREE EXTRA FIXES, all outside the ticket title, all loud. (a) xtask/src/install.rs:717 — `clear_stale_provenance`'s doc comment had an INDENTED log excerpt, which rustdoc compiles as Rust, so `cargo test -p xtask` failed its doctest on main for everyone. Fenced as ```text. Pre-existing, unrelated to this ticket, one line. (b) .yah/schema/mirror.toml.schema.json regenerated (`cargo run -p xtask -- emit-schemas`) — the schema-drift gate was RED on arrival and the drift is @Ashguard:coffee's R584-F2 `local-mailcrab` doc-comment change on `MirrorConfig::drivers`, not mine (verified by reading the one-line diff before regenerating). Regenerated per the generated-artifacts-are-not-ownable rule; they were told. Zero of my own types are schemars-derived, so this change contributes nothing to any schema. (c) Corrected three stale claims at their sites rather than leaving them: config.rs's NATIVE_EXEC_MESH_TAG doc said `Workload::MesofactServeBundle` and `Workload::Almanac` are BundleBackend-served (MesofactServeBundle is a FIELD on Workload::MesofactStatic, not a variant; Almanac is never node-placed at all), and us-east-001.toml's R885-T13 block repeated the same three wrong names for the four processes it observes — all four are bundle workloads.")
208//! @yah:verify("NEW TESTS. Five in mesofact_bundle's `mod tests`, each keeping a capable AND an incapable node in one CloudConfig so a pass provably comes from the capability rather than an empty pool: a_node_without_the_bundle_backend_cannot_be_pinned_to_serve_a_bundle (refusal names the tag and the file; the SAME fleet + same declaration shape at a capable node still resolves); a_constraint_places_past_a_matching_node_that_cannot_serve_bundles (the incapable node is declared FIRST, so a resolver ignoring the axis returns it and the test fails; then dropping the capable node makes the same declaration refuse); the_ingress_planner_applies_the_same_capability_as_the_deployer (set-for-set, plus the candidate widener must not widen past the capability); a_mirror_that_declares_the_capability_itself_is_unchanged (idempotence); a_non_bundle_slot_requires_no_capability (regression guard on the role mapping — a static slot still places on a node with no bundle backend). The shared `machine()` fixture now carries the tag by default, with `machine_without_bundle_backend()` beside it, because every placement test there presupposes an eligible pool.")
209//! @yah:verify("REAL-TREE HALF, which is where the live-safety answer is. New xtask/tests/mirror_ingress.rs::exactly_one_machine_in_the_real_fleet_can_serve_a_bundle asserts the capable set over .yah/infra/machines/ is exactly [\"us-east-001\"] and that a `replicas = 2` bundle constraint therefore refuses NAMING the tag. It is a deliberate tripwire: the day a second node declares the capability, the \"one node serves every bundle\" reasoning scattered through yah-marketing's and noisetable's mirrors stops holding and this is what says so. The pre-existing a_constraint_with_replicas_two_… had to change — its scale-2 assertions need two capable nodes and the real fleet has one — so it now grants the capability to us-south-001/us-west-001 IN MEMORY, asserts first that neither declares it on disk (so the grant cannot go silently vacuous), and says at the site that this is a hypothetical fleet, not a claim about those boxes. Every one of its original assertions (repel-by-default moving the second slot, the toleration lever recovering the pre-B7 answer, absent-replicas being exactly one, the short-count refusal, the two-backend render through collate) is unchanged and green.")
210//! @yah:gotcha("THIS FAILS CLOSED AND THE BLAST RADIUS WAS CHECKED, NOT ASSUMED. A bundle can now only be placed on a node declaring `cap:bundle-serving`, and exactly one does. Every live bundle placement in reach still resolves: yah-marketing's `required = { regions = [\"us-east\"], mesh_tags = [\"tag:cloud-runner\"] }` lands on us-east-001 (green in the real-tree suite), and the noisetable camp's two `providers.bundle.machines = [\"us-east-001\"]` pins are covered because ~/ss/noisetable/.yah/infra/machines/ is an EMPTY DIRECTORY — that camp borrows this repo's inventory read-only through its .yah/infra/sources.toml [[source]] link, so declaring the tag here fixes it there too and no cross-camp edit was needed. NOT EXECUTED, and say so rather than implying it: I did not run `yah cloud validate`/`ingress collate` from ~/ss/noisetable against a rebuilt binary. That conclusion is read off the two mirrors' pins plus the sources.toml link, not observed.")
211//! @yah:assumes("us-east-001's `cap:bundle-serving` rests on a BEHAVIOURAL reading, not on that box's ExecStart line: it is the node every bundle in the fleet is placed on today, R870-T9 records noisetable.com serving live through a bundle from it, and R885-T13 observed four kamaji-forked bundle processes there on 2026-09-11. Nothing in-repo records `--bundle-cache-dir` on its kamaji command line. The tag is therefore right about what the box demonstrably does and unverified about how it was started; if a roll ever drops the flag the tag becomes a lie in the fail-OPEN direction (a deploy that is admitted and then refused — i.e. exactly today's behaviour, not worse). Settle it with `ps -o args= -C kamaji` / the kamaji.service ExecStart, the same evidence us-west-001.toml:61-67 records for the native tag.")
212//! @yah:cleanup("us-south-001 is the obvious second bundle-capable candidate — it already shares the passway demux pair with us-east-001 — and is deliberately left undeclared because nothing in-repo reads its kamaji flags either way. One `ps -o args= -C kamaji` on that box settles it; declaring it wrongly would route a bundle to a node that refuses it, which is the failure this axis exists to remove. Until then the fleet is genuinely single-node for bundle serving and exactly_one_machine_in_the_real_fleet_can_serve_a_bundle says so out loud.")
213//!
214//! @yah:relay(R926, "Register iroh relay + headscale as first-class camp services, with descriptions and HA-aware health checks")
215//! @yah:at(2026-09-18T03:47:41Z)
216//! @yah:status(open)
217//! @yah:assignee(agent:bundle-anthropic-ashguard)
218//! @arch:see(.yah/docs/working/W122-yah-mobile.md)
219//! @yah:handoff("FILED 2026-09-17 from an operator request made during R726-S22's device run (@Ashguard:dove, session:639e7b78). THE ASK, in the operator's words: the iroh relay and headscale should be listed in the yah services with DESCRIPTIONS and HEALTH CHECKS, \"since they can move around in HA mode\". GROUNDED STATE OF THE WORLD AT FILING, read rather than assumed: (1) The service registry is .yah/services/&lt;name&gt;/service.toml. Exactly nine services are registered - scrabcake, yah-analytics, yah-chat, yah-cloud, yah-cloud-admin, yah-cr, yah-dashboard, yah-desktop, yah-marketing. NEITHER an iroh relay NOR headscale is among them, so the operator's observation is correct. (2) The generated schema .yah/schema/service.toml.schema.json has top-level properties [components, db, domain, health_path, name, schema_version], required [domain, name, schema_version]. So a health HOOK already exists in the shape of `health_path` - this is NOT greenfield - but there is NO `description` field at all, which is new schema surface. (3) .yah/infra/machines/*.toml are pure INVENTORY (name, [allocatable], [connect], [registration]); they are not where a service is declared, so do not add it there. (4) The Rust side of health_path lives in oss/yubaba/crates/cloud/src/config.rs and src/lib.rs (also mirrored in oss/mesofact/crates/mesofact/src/lib.rs).")
220//! @yah:next("Wire the iroh relay explicitly rather than implicitly. R726-S22 measured a phone falling back to relay because there was no shared address family with the camp; the relay is the DESIGNED path in that case, not a failure - but today nothing in the service registry says the relay exists, so its health is unobservable from the camp UI.")
221//! @yah:next("Add a `description` field to the service schema (new surface - it does not exist), then REGENERATE the artifacts: `cargo run -p xtask -- emit-schemas` and the workload-spec export. They no longer regenerate on commit and schema-drift-guard in the `check` QED pipeline will fail the build otherwise.")
222//! @yah:next("HA is the actual hard part and deserves a design decision before code: `health_path` is a single path on a single declared domain, which cannot express \"this service currently lives on whichever of N machines won the election\". Decide whether a service gains a set of candidate endpoints with a liveness winner, or whether the registry queries the mesh's own service-records endpoint (the 100.64.0.3:7443/service-records?ready=true surface referenced in us-west-001.toml) as the source of truth. Do NOT bolt a second health mechanism beside health_path - see the repo's below-v1.0.0 rule; change the one that exists.")
223//! @yah:gotcha("HEADSCALE HAS A LOUD, DOCUMENTED FAILURE HISTORY AND THIS TICKET IS PARTLY A RESPONSE TO IT - read R858 before designing the health check. .yah/infra/machines/us-west-001.toml carries R858 (\"Mesh coordination outage: cloud.mesh.yah.dev refuses :443, so no camp machine can reach any 100.64.0.0/10 address\") plus a measured 2026-09-04 gotcha: tailscale reported \"fetch control key ... connect: connection refused\", port 22 answered while 80/443 were REFUSED, and consequently every mesh address stopped answering. THE PART THAT MATTERS FOR A HEALTH CHECK: the same gotcha records that THE PUBLIC SITE STAYED GREEN THROUGHOUT (yah.dev HTTP 200 in 0.81s) because the apex serves from us-east-001's own passway and never traverses the coordination server. So a naive HTTP health check against a public domain would have reported HEALTHY during a total mesh outage. Whatever check this ticket adds for headscale MUST probe the coordination path itself (the control-key fetch, or a mesh-address dial), not a public endpoint that is up for unrelated reasons. The repo's CLAUDE.md also warns that the headscale appliance already accumulated four half-owners of \"does this node have a config.yaml\" and that the seam between two of them took the mesh down twice - so give this ONE owner.")
224
225use anyhow::{bail, Context, Result};
226// R870-F26: an `[[ingress]]` edge embeds the renderer's own auth type rather
227// than a config-side copy of its five fields — see `IngressEdge::auth`.
228use local_driver::passway_ingress::{AuthSpelling, PasswayAuth};
229use serde::{Deserialize, Serialize};
230use std::collections::BTreeMap;
231use std::path::Path;
232use thiserror::Error;
233use workload_spec::secrets::SecretAccess;
234use workload_spec::sovereign::Membership;
235pub use workload_spec::sovereign::SovereignRole;
236use workload_spec::{validate, LifecycleArchetype, Locality, WorkloadSpec};
237
238/// Static node capacity declaration on `machine.toml` (R572-F3).
239///
240/// `memory_mb` and `cpu_millis` express the node's *total* hardware budget.
241/// F5's bin-packer subtracts the sum of committed workload requests from
242/// this floor to determine available headroom; an absent `allocatable`
243/// block means no capacity constraint is enforced (any workload fits).
244#[derive(Debug, Clone, Serialize, Deserialize)]
245#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
246pub struct NodeAllocatable {
247    /// Total physical RAM in mebibytes (e.g. 512 for a 512 MB node).
248    pub memory_mb: u32,
249    /// Total CPU in k8s millicores (1000 = 1 core, 250 = 0.25 CPU).
250    pub cpu_millis: u32,
251}
252
253/// `[registration]` — facts **observed** about a running box, written by the
254/// fleet rather than declared by an operator (R707-T1).
255///
256/// The rest of `machine.toml` is *declaration*: intent, operator-authored,
257/// reviewed and diffed like any other source. This block is the other half —
258/// what the box turned out to be once it booted and joined. Keeping the two
259/// apart is what lets the published fleet index (R707-F3) say which half it is
260/// carrying; publishing them under one schema would bake the confusion into a
261/// permanent record.
262///
263/// The split is a **provenance** boundary, not a trust or reach one:
264/// - *Declaration* answers "what did we ask for" — `name`, `region`, `arch`,
265///   `mesh_tags`, `[allocatable]`, and the declared reach in [`ConnectSpec`].
266/// - *Registration* answers "what did we observe" — the hostkey TOFU'd at
267///   attach, the mesh address headscale assigned at join.
268///
269/// It stays in the git-tracked TOML on purpose. Registration is not local
270/// scratch state: every consumer needs the mesh address to dial a node, so it
271/// has to travel with the declaration. (`.yah/infra/state/machines/<name>.json`
272/// — [`crate::state::MachineState`] — remains the *gitignored* sidecar for
273/// provider-side derivatives that nobody but this camp needs.)
274#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
275#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
276pub struct MachineRegistration {
277    /// Yubaba's ed25519 `/identity` fingerprint, TOFU-recorded by
278    /// `yah cloud machine attach` on first contact (`SHA256:…`). An observed
279    /// property of a running process — not the operator's intent — which is
280    /// why it moved out of the top level here.
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub hostkey_fingerprint: Option<String>,
283    /// Mesh (headscale/tailnet) IPv4 assigned at join, e.g. `"100.64.0.1"`.
284    /// Bare address, not a URL: the *port* is declared reach and lives on
285    /// [`ConnectSpec::yubaba_port`]. [`MachineConfig::yubaba_url`] composes the
286    /// two. Absent until the node has joined the mesh.
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub mesh_ipv4: Option<String>,
289    /// RFC3339 timestamp of the mesh join that produced `mesh_ipv4`. Free-form
290    /// audit; nothing keys off it.
291    #[serde(default, skip_serializing_if = "Option::is_none")]
292    pub joined_at: Option<String>,
293}
294
295impl MachineRegistration {
296    /// True when nothing has been observed yet — used to omit the whole
297    /// `[registration]` table from a serialized machine TOML.
298    pub fn is_empty(&self) -> bool {
299        self.hostkey_fingerprint.is_none() && self.mesh_ipv4.is_none() && self.joined_at.is_none()
300    }
301}
302
303/// Per-machine TOML from `.yah/infra/machines/<name>.toml`.
304///
305/// Two halves, split by provenance (R707-T1): everything here is *declaration*
306/// — operator intent under review and blame — except [`registration`], which
307/// carries what the fleet observed. See [`MachineRegistration`] for why the
308/// boundary is drawn there and what depends on it.
309///
310/// @yah:ticket(R860-T5, "Model per-node native-exec capability as an admission axis (W338 §Placement consequences 3 / R858-T4 gap)")
311/// @yah:status(review)
312/// @yah:phase(P1)
313/// @yah:at(2026-09-05T18:29:19Z)
314/// @yah:assignee(agent:bundle-anthropic-ashguard)
315/// @yah:parent(R860)
316/// @yah:next("Cheapest defensible shape: express it on MachineConfig, which already has the two vocabularies — `mesh_tags: Vec<String>` (config.rs:246, superset match, already carries `arch:`/`os:`/`tag:build-worker`) and `taints: Vec<String>` (config.rs:337). A `native-exec` mesh tag required by any group member whose kind is native is a one-line admission axis in `admission_spec()`. Whichever is chosen, it must be declared in .yah/infra/machines/*.toml for the nodes that actually run kamaji with --native-exec-dir, and `check_inert_taints` (config.rs:703) lints unread taint keys dead — so a taint nobody reads will be flagged.")
317/// @yah:verify("cargo test -p cloud --lib config")
318/// @arch:see(.yah/docs/working/W338-workload-dependencies-and-appliance-composition.md)
319/// @yah:depends_on(R860-T4)
320/// @yah:gotcha("Verified 2026-09-04: native-exec capability is modelled NOWHERE in placement — `rg \"native\" oss/yubaba/crates/cloud/src/config.rs` returns zero hits, and the raft state machine models no member attributes, labels or taints at all (`rg \"taint|capabilit|labels|mesh_tag\"` over raft/{mod,store,network}.rs yields one unrelated comment at raft/store.rs:591). Native-exec is a node-local kamaji startup decision today: `--native-exec-dir` (oss/kamaji/crates/kamaji-bin/src/main.rs:152-156, :51-55) plus the `native-exec` cargo feature (kamaji-bin/src/server.rs:329-330). A node without it refuses the deploy at dispatch time and nothing upstream can see that in advance — which is exactly the deploy-time surprise W338 wants turned into a placement precondition.")
321/// @yah:handoff("NATIVE-EXEC IS NOW A PLACEMENT PRECONDITION, NOT A DISPATCH-TIME SURPRISE. New `pub const NATIVE_EXEC_MESH_TAG: &str = \"cap:native-exec\"` in oss/yubaba/crates/cloud/src/config.rs (declared just above `node_selector_mesh_tags`), and one axis in `admission_spec()` immediately after the R860-T4 group loop: if ANY member of `placement_group(ws, declared)` returns true from `WorkloadSpec::wants_native_exec()`, the tag is appended to the derived `RequiredSpec.mesh_tags` (deduped). No new field on `RequiredSpec`, no signature change anywhere, no wire or serde change — the mesh_tags axis is already an AND-ed superset check against `machine.mesh_tags` in `matches` and is already rendered by `describe`, so a refusal now reads `required.mesh_tags=[...,cap:native-exec]`.")
322/// @yah:handoff("ITEM 1 — HOW A NATIVE WORKLOAD IS DETECTED, settled by opening the type rather than guessing. There is no `kind` on `WorkloadSpec`: on the wire a native workload is still `Workload::Container(WorkloadSpec)`, and the ONLY difference is the annotation `yah.exec = native`, read through `WorkloadSpec::wants_native_exec()` (oss/yah-base/crates/workload-spec/src/lib.rs:2939; consts `NATIVE_EXEC_ANNOTATION` / `NATIVE_EXEC_VALUE` at :3402/:3407). That accessor is what the admission axis calls — matching kamaji, whose `deploy_container` checks the same marker first and routes to `deploy_native_exec` (oss/kamaji/crates/kamaji-bin/src/server.rs). The `yah.exec` key is a substrate selector with a second value, `microvm` (`wants_microvm`, same key, R605-F8), so per-node microVM capability is the obvious sibling axis and is NOT modelled here — see next-steps.")
323/// @yah:handoff("ITEM 2 — DECLARATIONS LANDED ON TWO NODES, FROM READINGS RECORDED IN-REPO, NOT INFERRED. `cap:native-exec` added to `mesh_tags` in .yah/infra/machines/us-west-001.toml and .yah/infra/machines/us-west-003.toml, each with a comment naming its evidence and its re-check condition. us-west-001: the R858 gotcha in its own header records a `ps` reading taken on the box 2026-09-05 — pid 515908 is `/usr/local/bin/kamaji --native-exec-dir /var/lib/yah/kamaji/native`, supervising headscale as a native child. us-west-003: its header's 'THE DEPLOYED KAMAJI PREDATES THE microVM BACKEND' note quotes the box's actual ExecStart, read over ssh 2026-09-01, carrying `--native-exec-dir /var/lib/yah/kamaji/native` (corroborated by .yah/docs/architecture/A043-yah-on-machine-daemons.md's @yah:verify for the same probe). Both comments say plainly that the capability lives in the systemd unit's ExecStart, not in the TOML, so it must be re-checked after any roll.")
324/// @yah:handoff("ITEM 2, THE NEGATIVES — TWO NODES ARE KNOWN NOT TO HAVE IT AND WERE DELIBERATELY LEFT UNSET. us-south-001: kamaji refused headscale there 2026-09-03 with 'native backend not configured — start kamaji with --native-exec-dir' (the R858 chain, quoted in .yah/infra/machines/us-west-001.toml and W267). I did NOT edit us-south-001.toml — it was already dirty in the working tree at the anchor SHA and @Ashguard:eclipse is live on R858, so I left it alone rather than race it; the mechanism fails closed there, which is the correct state. us-west-015 (the sole darwin builder): W254-darwin-build-nodes.md's own next-step records that its kamaji is built/started `--docker` only. I added a comment to us-west-015.toml explaining that the tag is deliberately absent, that this is the node where the axis changes an error message (a darwin build row is native by construction, so it is now refused at ELECTION naming cap:native-exec instead of reaching the box and being refused by kamaji), and the exact enable sequence: rebuild with `--features native-exec`, restart with `--native-exec-dir <dir>`, THEN add the tag. us-west-002/011/013/014 are unestablished from the repo and left unset. THE OPERATOR-FACING ANSWER: the file is `.yah/infra/machines/<node>.toml` and the key is `mesh_tags`; add the literal string `cap:native-exec` to that array, and only after the roll.")
325/// @yah:handoff("DECISIONS THE BRIEF LEFT OPEN, all recorded in doc comments at the site. (1) MESH TAG, NOT TAINT — as recommended, and the doc says why in the terms the brief asked for: mesh tags are positive capability with superset matching ('this node CAN'), which is the claim being made; a taint is repulsion and would have to be inverted to `no-native-exec` on every node LACKING the backend (declaration burden on the majority, and silently wrong for a node nobody has edited) AND taught to `taint_effect`, or `check_inert_taints` would correctly lint the key dead. (2) THE `cap:` NAMESPACE IS NEW. Live prefixes are `tag:` (operator-assigned role), `arch:`/`os:` (silicon and userland facts, emitted as requirements by qed::platform::build_worker_mesh_tags), and `tier:` which R763 RETIRED for architecture and reserved for the environment axis — so reusing any of them would have stated the wrong kind of fact. A capability the daemon was configured with is none of those. Nothing validates tag prefixes (only `check_retired_arch_tags` looks at one), so this costs no wiring. (3) COMPUTED OVER THE GROUP, not the requirer — that is literally W338's sentence ('supply = self specs must be placeable where their requirer lands'), and the second test proves it: an ordinary container requirer with a `local` edge to a native provider is pulled onto a capable node. (4) FAILS CLOSED, accepted deliberately: an undeclared node is simply not a candidate, so an undeclared fleet reports 'no node admits' at election rather than dispatching to a node that refuses. Nothing in `.yah/infra/workloads/` is native-marked today (only yah-cloud-admin.toml exists there), so the only live consumer is the qed darwin build row, where failing closed is strictly the better error.")
326/// @yah:handoff("BLAST RADIUS, MEASURED. `admission_spec` is private and its callers are unchanged: `admit_workload` / `admit_workload_candidates` / `admit_workload_in_group` (config.rs), reached from app/yah/cli/src/cloud.rs (deploy, rolling, topology analyzer), app/yah/cli/src/yubaba_client.rs `elect_node`, and cloud/src/migrate.rs. The headscale appliance path inside yubaba (headscale_appliance.rs) does NOT go through admission — it is node-internal — so nothing eclipse holds on R858 is touched by this. Files edited, in full: oss/yubaba/crates/cloud/src/config.rs; .yah/infra/machines/{us-west-001,us-west-003,us-west-015}.toml. Nothing in oss/yubaba/crates/yubaba/ was opened, and oss/kamaji/crates/kamaji-bin/src/server.rs was READ ONLY (to confirm the marker check), per @Ashguard:hydra's contention triage.")
327/// @yah:handoff("ONE SCOPE ADDITION, stated loudly rather than slipped in: `MachineConfig::mesh_tags` (config.rs:256) had NO doc comment at all — the operator-facing declaration key for four tag namespaces was undocumented. I gave it one enumerating `tag:` / `arch:`+`os:` / the new `cap:` / retired `tier:`, and noting that nothing validates the prefix (which is why the two lints exist). CONSEQUENCE TO KNOW: that field's doc is the source of the `mesh_tags` description in the GENERATED .yah/schema/machine.toml.schema.json, so it is schema-drift-affecting — see the gotcha.")
328/// @yah:handoff("Tree anchor at handoff: 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2 — the shared tree as I found it and left it. Quote this SHA rather than 'HEAD' in any revert/restore instruction; to undo a hunk, read it with `git show 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2:<path>` and put it back with Edit, never `git checkout`/`restore` (they restore whole files and would delete peers' uncommitted work).")
329/// @yah:handoff("Tree anchor at handoff: 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2 — the shared tree as I left it. Diff against it (`git diff 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2..HEAD`) to see what landed under you, and quote this SHA rather than 'HEAD' in any revert/restore instruction.")
330/// @yah:next("MICROVM IS THE IDENTICAL UNMODELLED GAP, one line away. `yah.exec` is a substrate selector with a second value: `WorkloadSpec::wants_microvm()` (workload-spec/src/lib.rs, R605-F8), and kamaji constructs MicroVmRuntime only when started with `--microvm-dir` — A043's probe records that us-west-003's deployed kamaji has `--native-exec-dir` but NOT `--microvm-dir`, so a microvm-marked deploy is refused there by exactly the same dispatch-time surprise this ticket removed for native. The shape is `cap:microvm` alongside NATIVE_EXEC_MESH_TAG in the same `if` in `admission_spec`. Not done here because no node in the fleet can host one yet (R605-F14 must land a guest kernel + rootfs first), so declaring the tag anywhere today would be the wrong fact.")
331/// @yah:next("us-south-001 needs `cap:native-exec` DECIDED, not defaulted, and it is the R858 node. It is the one machine the repo positively records as LACKING the backend (kamaji refused headscale there 2026-09-03), so leaving the tag off is correct TODAY — but if R858's fix is 'give us-south-001 a native-capable kamaji' rather than 'stop moving headscale', then the roll and the tag must land together, in that order. I left .yah/infra/machines/us-south-001.toml untouched because it was already dirty at anchor 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2 and @Ashguard:eclipse is live on R858.")
332/// @yah:next("R860-T6 (`supply = \"self\"` provisioning) inherits this for free — `admission_spec` already requires the capability of the whole group, so a self-provisioned native member cannot be elected onto a node that cannot run it. What T6 must still not do is re-elect per member: reuse the node URL `elect_node` returned for the requirer, per R860-T4's handoff.")
333/// @yah:verify("BASELINE RECORDED BEFORE EDITING, at tree anchor 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2: `cargo test -p yah-cloud --lib` from oss/yubaba = 1090 passed / 0 failed / 4 ignored, exit 0 — exactly the count the brief predicted. AFTER: 1093 passed / 0 failed / 4 ignored, exit 0 (+3, exactly the three tests added). `cargo check -p yah-cloud --all-targets` exit 0 and `cargo check -p yubaba --all-targets` exit 0 (yubaba consumes cloud, so it is where any signature change would surface — there is none). Every exit code echoed explicitly via an `EXIT=$?` / `${PIPESTATUS[0]}` marker and read back, never inferred from an empty grep. The four `yah-cloud` warnings are all pre-existing and in other files (object-store r2.rs, reconciler/mesofact_static.rs unused imports, app_manifest.rs, reconciler/mod.rs non_snake_case); config.rs contributes none.")
334/// @yah:verify("NEW TESTS (config.rs `mod tests`, R860-T5 section at the end, after the R860-T4 block). (1) a_node_without_the_native_exec_capability_cannot_host_a_native_workload — a `yah.exec = native` spec is refused by a bare node with an error naming `cap:native-exec`, and admitted by a node declaring it, with both nodes in the same fleet so the choice is provably the tag. (2) a_local_edge_to_a_native_provider_makes_the_requirer_need_the_capability — an ordinary container requirer (asserted `!wants_native_exec()`) with a `local` edge to a native provider lands on the capable node, while the SAME spec without the edge still lands on the plain one, so the constraint provably comes from the group. (3) a_group_with_no_native_member_does_not_require_the_capability — the regression guard: the axis is absent from `admission_spec`'s mesh_tags and a group with a local edge between two ordinary specs still admits on a node declaring nothing. Helper `native_spec()` asserts the marker reads back through `wants_native_exec()` before the test uses it, so a typo cannot make the test pass vacuously.")
335/// @yah:verify("Machine-config lints were considered and are unaffected by construction: `check_inert_taints` reads `taints` (I touched none), and `check_retired_arch_tags` flags only the `tier:` prefix. `cap:` is a new namespace and nothing validates prefixes, so no lint fires and no lint needs teaching.")
336/// @yah:gotcha("SCHEMA DRIFT IS EXPECTED FROM THIS TICKET AND WAS ALREADY RED BEFORE IT. `.yah/schema/machine.toml.schema.json` is generated from `cloud::config` by `cargo run -p xtask -- emit-schemas`, and MachineConfig's DOC COMMENT is what the generator emits as its `description` — which means (a) my new `mesh_tags` doc changes it, and (b) so does this very handoff, because R860-T5's @yah: annotation block lives inside MachineConfig's doc at config.rs:201. That file was ALSO already dirty in the working tree at anchor 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2, before I touched anything — `scripts/check-schema-drift.sh` compares the regenerated tree against git, so it is red for any uncommitted schema edit regardless of author. Regenerate with `cargo run -p xtask -- emit-schemas` (or `scripts/check-schema-drift.sh --update`) when the root target dir is not contended; the pre-commit hook no longer does it (disabled 2026-08-15, see CLAUDE.md).")
337/// @yah:verify("SCHEMA REGENERATED IN THIS SESSION, so the drift gate is not left for the next reader: `cargo run --quiet -p xtask -- emit-schemas` exit 0, run from the repo root after the handoff was written (so it captures the annotation text too). Two files moved. `.yah/schema/machine.toml.schema.json`: MachineConfig's `description` grows by this ticket's annotation block, plus a genuinely new `mesh_tags.description` from the doc comment I added. `.yah/schema/workload.toml.schema.json`: +104 lines that are NOT mine — the `Locality` / `Requirement` / `Supply` / `WorkloadSpec.requires` types R860-T1 landed had never been emitted, so the sibling ticket's schema drift was still outstanding and my regen swept it in. Derived artifacts are not ownable (shared-tree doctrine), so this is deliberate rather than accidental; @Ashguard, whoever picks up R860-T1's review should know the schema now describes `requires`.")
338/// @yah:verify("FINAL RE-RUN AFTER THE HANDOFF ANNOTATION WAS WRITTEN INTO config.rs (the board write edits MachineConfig's doc block, so the file changed under the earlier green): `cargo test -p yah-cloud --lib` = 1093 passed / 0 failed / 4 ignored, exit 0. Unchanged. Note for anyone reading the camp build rail's skew warnings on this session: the one `SUSPECT RESULT` it emitted names `oss/yubaba/crates/cloud/src/config.rs` as modified mid-run, and that modification was MY OWN board_handoff annotation write, not a peer — the two authoritative runs (full lib test, and both cargo checks) each came back `Input closure unchanged across the whole run: no skew`.")
339/// @yah:verify("All builds were run with `CARGO_TARGET_DIR=/tmp/r860t5-target` rather than the shared oss/yubaba/target, following R860-T4's recorded gotcha — a peer (session:83093d9d) held the shared target lock for the entire session (20+ minutes of `cargo check -p yubaba --lib`). Costs one cold dep build, then every subsequent run is seconds. Worth reaching for immediately when the queue message says you are behind someone.")
340/// @yah:handoff("LEADER RE-VERIFIED (session:69b18855, independent of the courier's self-report). `cargo test -p yah-cloud --lib` from oss/yubaba: 1093 passed / 0 failed / 4 ignored, exit 0, against the 1090/0/4 baseline this relay's own T4 established — +3 = exactly its new tests. Axis confirmed by content: `NATIVE_EXEC_MESH_TAG = \"cap:native-exec\"` at config.rs:2304, appended to the derived `RequiredSpec.mesh_tags` at :2112-2114 when any `placement_group` member returns true from `WorkloadSpec::wants_native_exec()`. No new `RequiredSpec` field, no signature change, no wire change — it rides the existing AND-ed superset check, so a refusal now reads `required.mesh_tags=[...,cap:native-exec]`.")
341/// @yah:handoff("Tree anchor at handoff: 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2 — the shared tree as I left it. Diff against it (`git diff 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2..HEAD`) to see what landed under you, and quote this SHA rather than 'HEAD' in any revert/restore instruction.")
342/// @yah:verify("MACHINE DECLARATIONS AUDITED FOR PROVENANCE, because a wrong capability declaration is worse than an absent one. Both are traceable to measurements ALREADY RECORDED IN-REPO, not inferred: us-west-001 from the `ps` reading at us-west-001.toml:21 (pid 517125, ppid 515908 = `/usr/local/bin/kamaji --native-exec-dir /var/lib/yah/kamaji/native`, cgroup `0::/yubaba.slice/kamaji.service/native`, 2026-09-05); us-west-003 from the actual ExecStart read over ssh 2026-09-01 at us-west-003.toml:141. us-west-015 was deliberately left WITHOUT the tag and carries enable instructions at :207-217 — unknown fails closed, which is the correct direction. No node was guessed at and nothing was probed live.")
343/// @yah:handoff("THIS TICKET MODELS THE EXACT DRIFT THAT CAUSED THE 25-HOUR MESH OUTAGE, which is worth stating because it turns an abstract W338 bullet into a measured one. us-west-001.toml:8 records the root-cause chain: on 2026-09-03T06:03:03Z leadership moved to us-south-001, which tried to deploy headscale and kamaji refused — \\\"workload requests native host execution (yah.exec=native) but no native backend is available (native backend not configured — start kamaji with --native-exec-dir)\\\" — then the systemd fallback failed too, both at WARN, and the mesh had no coordination server for 25 hours. us-west-001.toml:10 names it explicitly as \\\"a silent per-node capability drift that placement does not model\\\". After this ticket, placement models it: a group needing native exec can no longer be admitted onto a node that has not declared `cap:native-exec`.")
344/// @yah:handoff("Tree anchor at handoff: 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2 — the shared tree as I left it. Diff against it (`git diff 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2..HEAD`) to see what landed under you, and quote this SHA rather than 'HEAD' in any revert/restore instruction.")
345/// @yah:verify("RE-VERIFIED AT HEAD 00ee20d1 (session:aa5e882d, 2026-09-05). `NATIVE_EXEC_MESH_TAG` present in oss/yubaba/crates/cloud/src/config.rs (declared above `node_selector_mesh_tags`, appended to the derived `RequiredSpec.mesh_tags` when any `placement_group` member wants native exec). `cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib` = 1141 passed / 0 failed / 4 ignored, exit 0.")
346/// @yah:cleanup("cap:microvm remains the identical unmodelled axis, one line from done in the same `if` in `admission_spec`. Deliberately NOT taken: no node in the fleet can host a microvm until R605-F14 lands a guest kernel + rootfs, so declaring the tag today would assert a false fact. Do it when R605-F14 lands, not before.")
347#[derive(Debug, Clone, Serialize, Deserialize)]
348#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
349pub struct MachineConfig {
350    pub name: String,
351    pub provider: String,
352    /// Who the hardware actually comes from (`"ovh"`, `"vultr"`, `"on-prem"`).
353    ///
354    /// Deliberately *not* [`provider`](Self::provider), which selects the
355    /// auto-provision driver: a box we rented by hand and brought up over SSH
356    /// is `provider = "static"` for its whole life, and writing the vendor
357    /// there instead would flip it driver-backed and make
358    /// [`validate`](Self::validate) demand `location` + `server_type` it has no
359    /// answer for. The two axes genuinely differ — vendor is who bills you,
360    /// `provider` is who yah can call an API against.
361    ///
362    /// Worth recording because vendor-scoped policy is invisible in every other
363    /// field and decides real work: outbound port 25, rDNS/PTR control, IP
364    /// reputation, egress billing. It survived only in TOML prose until now,
365    /// which made it ungreppable at exactly the moment you need it.
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub vendor: Option<String>,
368    /// Human label for the box (`"gamer"`, `"the GEEKOM"`). Free-form and never
369    /// matched on — [`name`](Self::name) stays the identity everywhere. This is
370    /// only so operators and agents can say which box they mean out loud.
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub nickname: Option<String>,
373    /// Provider DC code (e.g. Hetzner `"hil"`). **Provisioning-only**: required
374    /// iff the provider has an auto-provision driver ([`provider_has_machine_driver`]);
375    /// a BYO `static` node we brought up over SSH has no such code. Optional at
376    /// load time so static machine.tomls omit it; [`MachineConfig::validate`]
377    /// enforces presence at the right moment for driver-backed providers.
378    #[serde(default, skip_serializing_if = "Option::is_none")]
379    pub location: Option<String>,
380    /// Provider SKU/size (e.g. Hetzner `"ccx13"`). Provisioning-only, same
381    /// optionality contract as [`location`](Self::location).
382    #[serde(default, skip_serializing_if = "Option::is_none")]
383    pub server_type: Option<String>,
384    /// **Deprecated (R330-F16).** A machine should describe *itself* (region,
385    /// zone, provider, mesh_tags); *which* mirrors run on it is derived by the
386    /// reconciler from each mirror's `required` placement spec, not declared
387    /// here. Now optional + omitted-when-empty so new machine.tomls leave it
388    /// out. The legacy `resolve_mirror_machine` topology fallback still reads
389    /// it until yubaba's reverse-index supersedes the topology.toml path; once
390    /// that lands, this field and its readers are removed wholesale.
391    #[serde(default, skip_serializing_if = "Vec::is_empty")]
392    pub hosts_mirrors: Vec<String>,
393    /// Positive placement facts about this node, matched as a **superset**:
394    /// a workload is admitted only where every tag it requires is present, so
395    /// adding a tag can only ever make a machine match more, never fewer.
396    ///
397    /// Four namespaces are live, and they are not interchangeable:
398    /// - `tag:<role>` — a role the operator assigns (`tag:build-worker`,
399    ///   `tag:qed`, `tag:cloud-runner`, `tag:mac-builder`);
400    /// - `arch:<x86|arm>` / `os:<linux|darwin>` — facts about the silicon and
401    ///   userland, emitted as *requirements* by
402    ///   [`qed::platform::build_worker_mesh_tags`];
403    /// - `cap:<capability>` — something the node's daemons were configured to
404    ///   be able to do. Today just [`NATIVE_EXEC_MESH_TAG`] (R860-T5);
405    /// - `tier:` is **retired** for architecture (R763) and reserved for the
406    ///   environment axis — [`crate::validate::check_retired_arch_tags`]
407    ///   flags a machine still carrying `tier:<arch>`.
408    ///
409    /// Nothing validates the prefix, which is why the lint above exists: a tag
410    /// nobody requires is silently inert, and a *stale* one silently stops
411    /// matching and reports "no node" rather than "wrong tag".
412    pub mesh_tags: Vec<String>,
413    /// Canonical geo region label (latency axis), e.g. `"us-west"`. F16's three
414    /// topology axes are orthogonal: `region` = geo (latency), `zone` = failure
415    /// domain within a region (HA), `provider` = network/cost. `region` is
416    /// distinct from `location` (the provider's DC code, e.g. Hetzner `"hil"`):
417    /// `location` is provider-scoped, `region` is our provider-neutral label.
418    /// Optional for backward-compat; a machine without it never satisfies a
419    /// `required.regions` constraint.
420    #[serde(default, skip_serializing_if = "Option::is_none")]
421    pub region: Option<String>,
422    /// Failure-domain label within a region (HA axis), e.g. `"hil"`. For
423    /// single-DC Hetzner this typically mirrors `location`. F16 placement
424    /// matches `required.zones` against this. Optional for backward-compat.
425    #[serde(default, skip_serializing_if = "Option::is_none")]
426    pub zone: Option<String>,
427    /// Declared CPU architecture (`"x86_64"` / `"aarch64"`). A machine has
428    /// exactly one — it's a first-class property of the box, not a reach
429    /// detail and not a mesh tag. Drives the yubaba release triple. Optional
430    /// only because there's no provider API to probe it (static nodes declare
431    /// it; a driver-backed provider may leave it unset until known).
432    #[serde(default, skip_serializing_if = "Option::is_none")]
433    pub arch: Option<String>,
434    pub bucket: Option<BucketSpec>,
435    /// **Legacy location, superseded by `[registration].hostkey_fingerprint`**
436    /// (R707-T1). Still deserialized so machine TOMLs written before the split
437    /// keep parsing; never *read* directly — go through
438    /// [`MachineConfig::hostkey_fingerprint`], which prefers the registration
439    /// block. [`MachineConfig::normalize`] folds this into `registration`, and
440    /// [`MachineConfig::save`] normalizes before writing, so a load→save cycle
441    /// migrates the file rather than dropping the value.
442    #[serde(
443        rename = "hostkey_fingerprint",
444        default,
445        skip_serializing_if = "Option::is_none"
446    )]
447    pub legacy_hostkey_fingerprint: Option<String>,
448    /// Provider-side SSH-key IDs (Hetzner: from `GET /v1/ssh_keys`)
449    /// authorized for `root` at create time. Defaults to empty for
450    /// backwards-compat with existing machine declarations; an empty
451    /// list yields a Hetzner-emailed random root password (which the
452    /// driver currently discards). Populate this when you want pre-mesh
453    /// SSH access for bootstrap deploys or recovery.
454    #[serde(default, skip_serializing_if = "Vec::is_empty")]
455    pub ssh_keys: Vec<u64>,
456    /// Cloudflare Tunnel ID this machine joins (e.g. `abc123.cfargotunnel.com`).
457    /// `None` → no tunnel (mesh-only node, no public ingress).
458    /// When set, `yah cloud machine provision` reads `cloudflare-tunnel-token`
459    /// from the keys vault and injects the cloudflared install block into
460    /// cloud-init so the new machine connects to CF edge on first boot.
461    #[serde(default, skip_serializing_if = "Option::is_none")]
462    pub cloudflared: Option<String>,
463    /// Provider-issued floating/reserved IP that follows **public-ingress
464    /// ownership** onto this box — R859-F2 (W267 §Tier 1).
465    ///
466    /// The value is the provider's own identifier, opaque here and interpreted
467    /// only by the matching adapter: a Hetzner numeric floating-IP id as a
468    /// string, an OVH Additional-IP address (`"51.81.85.200"`), a Vultr
469    /// reserved-IP UUID. Same "the adapter is the boundary" convention
470    /// [`crate::envoy::floating_ip::FloatingIpAssignInput::ip_id`] documents.
471    ///
472    /// # Why it lives on the machine
473    ///
474    /// [`crate::envoy::floating_ip`] shipped the `floating_ip.*` verbs and
475    /// three provider adapters with no config anywhere saying *which* floating
476    /// IP is "the" ingress IP — the gap R594-F5 recorded and deliberately left.
477    /// This is that field, and it sits beside [`cloudflared`](Self::cloudflared)
478    /// on purpose: that is already the per-node "how the world reaches this
479    /// box" handle, and a floating IP is the sovereign-tier answer to the same
480    /// question. `[[ingress]]`'s
481    /// [`tunnel_id`](crate::config::IngressEdge::tunnel_id) is the *service*
482    /// side of ingress identity — which cohort a given service fronts through —
483    /// and a floating IP is not per-service: one IP moves between boxes, so it
484    /// cannot be partitioned by slot or hostname.
485    ///
486    /// # Absent means "no floating-IP path", never an error
487    ///
488    /// Most machines have none, and that is the normal case: mesh-only nodes,
489    /// boxes behind a Cloudflare tunnel, and every provider without a
490    /// floating-IP adapter. The effector skips such a machine cleanly rather
491    /// than refusing — see
492    /// [`plan_ingress_owner_effect`](crate::provider::floating_ip::plan_ingress_owner_effect).
493    ///
494    /// # The cohort has to agree
495    ///
496    /// Every machine that can hold the same ingress IP must declare the *same*
497    /// id: the IP is one resource that moves, so two ids inside one
498    /// [`sovereign_group`](Self::sovereign_group) means an ownership flip
499    /// silently reassigns a *different* IP than the one currently serving
500    /// traffic. `yah cloud validate` refuses that
501    /// ([`crate::validate::check_ingress_floating_ip`]) rather than leaving it
502    /// to be discovered during a failover.
503    #[serde(default, skip_serializing_if = "Option::is_none")]
504    pub ingress_floating_ip: Option<String>,
505    /// When `true`, this machine hosts operator-bridge workloads (Tailscale
506    /// operator access to mesh-internal services). `yah cloud machine provision`
507    /// will install tailscaled and run `tailscale up` during cloud-init via the
508    /// `{{OPERATOR_BRIDGE_BLOCK}}` placeholder. Defaults to `false` for
509    /// backward-compat with existing machine declarations.
510    #[serde(default)]
511    pub hosts_operator_bridge: bool,
512    /// BYO `static`-node reach descriptor. Static nodes have no provider API to
513    /// probe, so how the camp reaches them (SSH user@host + the yubaba URL,
514    /// which is loopback until the WireGuard mesh lands) is *declared* here.
515    /// `None` for driver-backed providers (Hetzner/Vultr), whose address is
516    /// resolved from the provider API / mesh at provision time.
517    #[serde(default, skip_serializing_if = "Option::is_none")]
518    pub connect: Option<ConnectSpec>,
519    /// Static node capacity (R572-F3). Declares the node's total hardware
520    /// budget; F5's scheduler subtracts committed workload requests from this
521    /// to check whether a new workload fits. Absent means unconstrained.
522    #[serde(default, skip_serializing_if = "Option::is_none")]
523    pub allocatable: Option<NodeAllocatable>,
524    /// Placement taint keys (R572-F3). A repelling key blocks placement by
525    /// default, and a placement opts back in by naming that exact key in
526    /// [`RequiredSpec::tolerates`] (R876-B7).
527    ///
528    /// The `unless` is real now. It was not between R742-T4 and R876-B7: the
529    /// spec side declared which archetypes it *was* rather than which taints it
530    /// tolerated, that field was `#[serde(skip)]`, and so every placement
531    /// declared as `required = {...}` in a mirror TOML read this list as empty
532    /// and could not be drained at all. See [`RequiredSpec::tolerates`].
533    ///
534    /// A key in this list influences placement in exactly one of two ways, and
535    /// [`taint_effect`] is the authority on which:
536    ///
537    /// - **repulsion** — `"no-server"` / `"no-appliance"` / `"no-job"` reject
538    ///   any placement that does not tolerate them. The archetype in the key is
539    ///   now vocabulary rather than a filter: `matches` does not compare it
540    ///   against the workload's class, it checks the toleration list, and
541    ///   [`admission_spec`] is what turns a workload's class into the
542    ///   tolerations that reproduce the old archetype-scoped behaviour;
543    /// - **affinity** — a key in [`AFFINITY_TAINT_KEYS`] (today just
544    ///   `"public-ip"`) that a workload names in
545    ///   `yah.placement.requires-taint`, which then *requires* this node.
546    ///
547    /// Anything else is **inert**: it parses, it round-trips, and no scheduler
548    /// decision can ever read it. `yah cloud validate` rejects such keys
549    /// (`validate::check_inert_taints`) rather than letting them sit looking
550    /// load-bearing — which is how `no-voter` spent months asserting a
551    /// falsehood on three nodes. Facts about a node that are not placement
552    /// inputs belong in [`mesh_tags`](Self::mesh_tags) or a comment.
553    #[serde(default, skip_serializing_if = "Vec::is_empty")]
554    pub taints: Vec<String>,
555    /// Which consensus group this node belongs to — W305/R742-F1. `None` means
556    /// standalone: in no group at all, which is us-west-002 and us-west-015.
557    ///
558    /// Membership is not by itself quorum eligibility; that is
559    /// [`sovereign_role`](Self::sovereign_role), added by R605-F12 because
560    /// us-west-003 is in prod's blast radius *and* must never vote in it.
561    ///
562    /// **Not a placement input.** It is deliberately absent from
563    /// [`RequiredSpec::matches`], and adding it there would be a category
564    /// error: a sovereign group is a *blast radius*, not a filter. Nothing
565    /// about "which quorum does this box vote in" should decide where a
566    /// workload runs — that is what made the fleet express three unrelated
567    /// properties through one taint list and get all three wrong (W305).
568    ///
569    /// What it *is* for is refusal. [`judge_join`] answers "may this node join
570    /// that node's cluster", and the answer is no unless both declare the same
571    /// group. Before this field the only guard was a comment in three machine
572    /// TOMLs saying "never run a raft join against this box from a shell
573    /// pointed at prod" — habit, with no mechanism behind it, which is the
574    /// same class of guard W257 §8 admitted to.
575    ///
576    /// # Why `sovereign_group` and not `raft_group`
577    ///
578    /// Raft is today's mechanism (operator, 2026-08-10). A field named for the
579    /// mechanism goes stale the day the mechanism is swapped, and every
580    /// consumer that reads it inherits the lie. `sovereign` names what the
581    /// group *has* — its own authority, its own upgrade cadence, its own
582    /// destruction — which stays true under any consensus protocol.
583    ///
584    /// Note the word already appears in this tree as prose (W267's title, the
585    /// `IngressProvider::Passway` doc comment's "sovereign edge"). That is an
586    /// adjective meaning "self-hosted, not SaaS"; this is the first time it
587    /// carries structure.
588    #[serde(default, skip_serializing_if = "Option::is_none")]
589    pub sovereign_group: Option<String>,
590    /// Whether this node may hold a seat in its group's quorum — R605-F12.
591    /// Meaningless without [`sovereign_group`](Self::sovereign_group): a
592    /// standalone box has no quorum to be eligible for.
593    ///
594    /// **`None` is "not written", not a third role.** Read it through
595    /// [`sovereign_membership`](Self::sovereign_membership), which resolves the
596    /// absence to [`SovereignRole::Voter`] — what declaring a group has always
597    /// meant, so the six nodes stamped before this field keep their seats
598    /// without an edit. The distinction is kept only so
599    /// [`crate::validate::check_unroled_sovereign_members`] can tell an
600    /// operator who *chose* voter from one who never considered the question;
601    /// no join decision reads the `Option` directly.
602    ///
603    /// # Why this is not a taint
604    ///
605    /// It was, once: `no-voter` sat in [`taints`](Self::taints) on three nodes
606    /// for months, read by nothing, and R742-T4 removed it because the taint
607    /// list is a *placement* vocabulary and this is not a placement input (see
608    /// [`taint_effect`]). Nor is it a second group label. It is a modifier on
609    /// the membership this node already declares, which is why it lives beside
610    /// the group and is judged with it in one predicate,
611    /// [`workload_spec::sovereign::join_permitted`].
612    #[serde(default, skip_serializing_if = "Option::is_none")]
613    pub sovereign_role: Option<SovereignRole>,
614    /// `[registration]` — the observed half (R707-T1). Empty until the box has
615    /// been attached / mesh-joined. See [`MachineRegistration`].
616    #[serde(default, skip_serializing_if = "MachineRegistration::is_empty")]
617    pub registration: MachineRegistration,
618}
619
620/// True iff `provider` has an auto-provision driver (create/destroy via API).
621/// Driver-backed providers require `location` + `server_type`; BYO `static`
622/// nodes (brought up over SSH) do not. The cloud-vs-vps distinction the fleet
623/// cares about lives here — at the provider-capability layer — not as a
624/// separate machine type (W242 BYO Phase-0 decision).
625pub fn provider_has_machine_driver(provider: &str) -> bool {
626    matches!(provider, "hetzner" | "vultr" | "digitalocean")
627}
628
629/// Taint keys a workload may name in `yah.placement.requires-taint` to
630/// *require* a node (W305/R742-T4 affinity vocabulary).
631///
632/// This is a closed list on purpose. `WorkloadSpec::requires_taint` returns
633/// free text, but every producer in the tree is code — `passway_ingress.rs`
634/// and `cloudflared_ingress.rs`, both emitting
635/// [`workload_spec::PUBLIC_IP_TAINT`] — and no on-disk `workload.toml` sets the
636/// annotation at all. So the set of keys a node can usefully carry for
637/// affinity is knowable at compile time, which is what lets
638/// [`taint_effect`] call anything outside it inert instead of guessing.
639///
640/// **Adding an affinity key means adding it here**, in the same change that
641/// teaches a workload to require it. That coupling is the point: it makes the
642/// node side and the workload side impossible to land apart.
643pub const AFFINITY_TAINT_KEYS: &[&str] = &[workload_spec::PUBLIC_IP_TAINT];
644
645/// How a key in [`MachineConfig::taints`] can affect placement.
646///
647/// W305 finding 1: before R742-T4 nothing asked this question, so a key that
648/// no scheduler path could read — `"qa"`, `"no-voter"` — parsed, validated,
649/// and quietly did nothing. Both of the findings that cost real fleet state
650/// were invisible for exactly that reason.
651#[derive(Debug, Clone, Copy, PartialEq, Eq)]
652pub enum TaintEffect {
653    /// `"no-<archetype>"`: rejects placement outright unless the constraint
654    /// names this key in [`RequiredSpec::tolerates`]. Read by
655    /// [`RequiredSpec::matches`], which walks `machine.taints` and classifies
656    /// each key through [`taint_effect`] (R876-B7).
657    Repels(LifecycleArchetype),
658    /// A key in [`AFFINITY_TAINT_KEYS`]: a workload naming it in
659    /// `yah.placement.requires-taint` is restricted to nodes carrying it.
660    Attracts,
661    /// Neither. No placement decision can read this key.
662    Inert,
663}
664
665/// Classify one node taint key. See [`TaintEffect`].
666///
667/// The repulsion half is derived from [`LifecycleArchetype::ALL`] rather than
668/// a literal list, so a fourth archetype makes `no-<its key>` live without an
669/// edit here.
670pub fn taint_effect(key: &str) -> TaintEffect {
671    if let Some(arch) = LifecycleArchetype::ALL
672        .into_iter()
673        .find(|a| key == format!("no-{}", a.taint_key()))
674    {
675        return TaintEffect::Repels(arch);
676    }
677    if AFFINITY_TAINT_KEYS.contains(&key) {
678        return TaintEffect::Attracts;
679    }
680    TaintEffect::Inert
681}
682
683/// Every key the scheduler *can* act on, sorted — for error messages that
684/// tell the operator what the legal vocabulary actually is instead of only
685/// what was wrong.
686pub fn live_taint_keys() -> Vec<String> {
687    let mut keys: Vec<String> = LifecycleArchetype::ALL
688        .into_iter()
689        .map(|a| format!("no-{}", a.taint_key()))
690        .chain(AFFINITY_TAINT_KEYS.iter().map(|k| (*k).to_string()))
691        .collect();
692    keys.sort();
693    keys
694}
695
696/// What [`judge_join`] decided about one proposed cluster join.
697///
698/// Shaped like yubaba's `PromotionVerdict` / `GeographyVerdict` and for the
699/// same reason: the rule stays unit-testable without a live cluster, and a
700/// refusal carries its reason from the place that knows it.
701#[derive(Debug, Clone, PartialEq, Eq)]
702pub enum JoinVerdict {
703    /// Both nodes declare the same sovereign group and both are voters. The
704    /// join is within one blast radius and grows a quorum both sides are
705    /// eligible for.
706    Permit,
707    /// The join is refused. Carries an operator-readable reason naming both
708    /// declared values and the file to edit — a refusal that only says
709    /// "invalid" gets worked around rather than fixed.
710    Refuse(String),
711}
712
713/// May `joiner` join the cluster `target` belongs to? — W305/R742-F1.
714///
715/// **A join is permitted iff both nodes declare the same non-`None`
716/// [`sovereign_group`](MachineConfig::sovereign_group) and both are
717/// [`SovereignRole::Voter`].** One rule, no special cases, and it makes the
718/// declaration mandatory before any quorum grows.
719///
720/// The case this exists for is two *different* declared groups: joining a dev
721/// Pi into prod is refused rather than trusted, where today the only guard is
722/// a comment saying not to do it. But an undeclared node is refused too, and
723/// that is the deliberate half — `None` means "in no group", not "unknown", so
724/// growing prod with an unstamped box is exactly as much a cross-group join as
725/// the dev case is. Failing open there would leave the operator believing a
726/// guarantee that was never evaluated, which is the reasoning
727/// `QuorumGeography::judge` already applies to untagged voters.
728///
729/// No legitimate flow pays for that strictness: prod and dev are both stamped,
730/// and us-west-002/015 are deliberately in no group at all. Adding a real
731/// member means declaring it first, which is the point.
732///
733/// # The non-voting refusal (R605-F12)
734///
735/// Same group and still refused, when either side declares
736/// [`SovereignRole::NonVoter`]. This is the case a group label alone could not
737/// express. us-west-003 is a residential-uplink build box the operator counts
738/// as part of prod — same secrets, same upgrade cadence, same destruction — and
739/// which must never hold a prod raft seat, because a home-internet partition
740/// should not be able to stall the quorum. Until R605-F12 the only thing
741/// refusing it was its *absent* stamp, so recording the operator's real intent
742/// (`sovereign_group = "prod"`) would have removed the guard. Now the intent
743/// and the guard are the same two lines.
744///
745/// Note what this is not: the refusal here is about *voting*, and it says
746/// nothing about the mesh. One mesh spans the whole fleet regardless of group
747/// or role (operator, 2026-08-19); a non-voter is reachable, schedulable and
748/// rollable like any other node.
749///
750/// This is the **camp-side** rendering of the rule. The predicate itself lives
751/// in [`workload_spec::sovereign::join_permitted`] because yubaba's
752/// `POST /raft/add-learner` gate asks the same question and cannot see this
753/// crate (there is deliberately no yubaba → cloud edge). Only the prose is
754/// duplicated, and it has to be: a refusal here names
755/// `.yah/infra/machines/<name>.toml`, while the node-side one has no machine
756/// name in hand and must also name `yubaba serve --sovereign-group`.
757///
758/// The node-side gate is *narrower* on purpose, and the difference is worth
759/// knowing when reading either: a daemon started without `--sovereign-group`
760/// has declared nothing rather than declared standalone, so yubaba resolves
761/// that unknown before it judges, and its gate is in force only once the
762/// cluster being joined declares a group. See `yubaba::sovereign_group`.
763pub fn judge_join(joiner: &MachineConfig, target: &MachineConfig) -> JoinVerdict {
764    let stamp_hint = |m: &MachineConfig| {
765        format!(
766            "declare `sovereign_group = \"<group>\"` in .yah/infra/machines/{}.toml",
767            m.name
768        )
769    };
770    let role_hint = |m: &MachineConfig| {
771        format!(
772            "set `sovereign_role = \"voter\"` in .yah/infra/machines/{}.toml",
773            m.name
774        )
775    };
776    if workload_spec::sovereign::join_permitted(
777        joiner.sovereign_membership(),
778        target.sovereign_membership(),
779    ) {
780        return JoinVerdict::Permit;
781    }
782    let (j, t) = (
783        joiner.sovereign_group.as_deref(),
784        target.sovereign_group.as_deref(),
785    );
786    // Everything below is a refusal; the only permitted shape returned above.
787    //
788    // R605-F12: when both sides name the SAME group, the role is the only thing
789    // left that can have refused, and it gets its own message. Falling through
790    // to the arms below would print "cross-group join refused: 'us-west-003' is
791    // in "prod" and 'us-west-001' is in "prod"" — a message that reads as a bug
792    // in the check rather than a decision about the fleet.
793    //
794    // Deliberately not hoisted above the group comparison. A non-voting joiner
795    // whose target is standalone is refused for *both* reasons, and naming the
796    // role there would send the operator to fix a field that would not have
797    // made the join legal anyway.
798    if let (Some(a), Some(b)) = (j, t) {
799        if a == b {
800            for (m, side, other) in [
801                (joiner, "the joiner", &target.name),
802                (target, "the target", &joiner.name),
803            ] {
804                if m.sovereign_membership().role.is_voter() {
805                    continue;
806                }
807                return JoinVerdict::Refuse(format!(
808                    "join refused: {side} '{}' is a NON-VOTING member of sovereign group {a:?}, \
809                     the same group as '{other}'. It is inside that blast radius — same secrets, \
810                     same upgrade cadence, same destruction — but declares itself ineligible for \
811                     the quorum, so this is refused by declaration rather than by omission. If it \
812                     should genuinely vote, {}; if it should not, this refusal is the field doing \
813                     its job and the join is the thing to reconsider.",
814                    m.name,
815                    role_hint(m),
816                ));
817            }
818        }
819    }
820    match (j, t) {
821        (Some(a), Some(b)) => JoinVerdict::Refuse(format!(
822            "cross-group join refused: '{}' is in sovereign group {a:?} and '{}' is in {b:?}. \
823             These are separate blast radii — separate quorums, separate upgrade cadences, \
824             separately destroyable — and merging them is not something a join can undo. If \
825             the move is genuinely intended, restamp '{}' to {b:?} first and treat it as \
826             leaving its old group.",
827            joiner.name,
828            target.name,
829            joiner.name,
830        )),
831        (None, Some(b)) => JoinVerdict::Refuse(format!(
832            "join refused: '{}' declares no sovereign_group, so it is standalone — in no \
833             group — while '{}' is in {b:?}. That is a cross-group join, not an unchecked \
834             one. To make '{}' a member of {b:?}, {}.",
835            joiner.name,
836            target.name,
837            joiner.name,
838            stamp_hint(joiner),
839        )),
840        (Some(a), None) => JoinVerdict::Refuse(format!(
841            "join refused: '{}' is in sovereign group {a:?} but '{}' declares none, so the \
842             target is standalone and has no group to join. Either {}, or found the group on \
843             '{}' rather than growing it.",
844            joiner.name,
845            target.name,
846            stamp_hint(target),
847            joiner.name,
848        )),
849        (None, None) => JoinVerdict::Refuse(format!(
850            "join refused: neither '{}' nor '{}' declares a sovereign_group, so this join \
851             would form a group nobody declared and nothing could later reason about. Name \
852             the group on both boxes first: {}, and the same for '{}'.",
853            joiner.name,
854            target.name,
855            stamp_hint(joiner),
856            target.name,
857        )),
858    }
859}
860
861impl MachineConfig {
862    /// This node's declared place in a sovereign group, as the shared join rule
863    /// wants it — R605-F12.
864    ///
865    /// The one place `sovereign_role`'s `None` is resolved. Absence means
866    /// [`SovereignRole::Voter`], which is what declaring a group meant before
867    /// the role existed; resolving it here rather than at each call site is what
868    /// keeps the camp-side and node-side gates from disagreeing about a node
869    /// that never wrote the field.
870    pub fn sovereign_membership(&self) -> Membership<'_> {
871        Membership {
872            group: self.sovereign_group.as_deref(),
873            role: self.sovereign_role.unwrap_or_default(),
874        }
875    }
876
877    /// Provider DC code, or `""` when omitted (static nodes). Most readers want
878    /// a `&str`; the driver-backed provision/status paths still go through
879    /// [`validate`](Self::validate) which guarantees presence for those.
880    pub fn location(&self) -> &str {
881        self.location.as_deref().unwrap_or("")
882    }
883
884    /// Provider SKU, or `""` when omitted (static nodes).
885    pub fn server_type(&self) -> &str {
886        self.server_type.as_deref().unwrap_or("")
887    }
888
889    /// Enforce the provisioning-only-field contract: a machine whose provider
890    /// has an auto-provision driver MUST declare `location` + `server_type`
891    /// (the driver can't create a server without them). Static nodes may omit
892    /// both. Call this before any provision/diff that assumes a driver.
893    pub fn validate(&self) -> Result<()> {
894        if provider_has_machine_driver(&self.provider) {
895            if self.location.is_none() {
896                anyhow::bail!(
897                    "machine '{}' (provider '{}') has an auto-provision driver but no `location`",
898                    self.name,
899                    self.provider
900                );
901            }
902            if self.server_type.is_none() {
903                anyhow::bail!(
904                    "machine '{}' (provider '{}') has an auto-provision driver but no `server_type`",
905                    self.name,
906                    self.provider
907                );
908            }
909        }
910        Ok(())
911    }
912
913    /// Declared taints that no placement decision can read (W305/R742-T4).
914    ///
915    /// Deliberately **not** folded into [`validate`](Self::validate): that
916    /// guard runs on the provision/diff hot path and answers a different
917    /// question (can the driver create this server). An inert taint is a lint
918    /// — it never breaks an operation in flight, it just means the file is
919    /// asserting something the scheduler will not honour. `yah cloud validate`
920    /// is where the operator asks for that judgement; see
921    /// [`crate::validate::check_inert_taints`].
922    pub fn inert_taints(&self) -> Vec<&str> {
923        self.taints
924            .iter()
925            .filter(|t| taint_effect(t) == TaintEffect::Inert)
926            .map(String::as_str)
927            .collect()
928    }
929
930    /// Yubaba's TOFU'd hostkey fingerprint, from `[registration]` and falling
931    /// back to the pre-R707-T1 top-level field. **The only read path** — a
932    /// caller that reaches for `legacy_hostkey_fingerprint` directly sees
933    /// `None` on every migrated machine.
934    pub fn hostkey_fingerprint(&self) -> Option<&str> {
935        self.registration
936            .hostkey_fingerprint
937            .as_deref()
938            .or(self.legacy_hostkey_fingerprint.as_deref())
939    }
940
941    /// Record (or clear) the observed hostkey fingerprint. Writes
942    /// `[registration]` and drops any pre-R707-T1 top-level value, so the two
943    /// locations can never disagree after a writeback.
944    pub fn set_hostkey_fingerprint(&mut self, fingerprint: Option<String>) {
945        self.registration.hostkey_fingerprint = fingerprint;
946        self.legacy_hostkey_fingerprint = None;
947    }
948
949    /// Mesh (tailnet) IPv4 for this node, or `None` pre-mesh.
950    ///
951    /// Prefers `[registration].mesh_ipv4`; falls back to the host of a legacy
952    /// `[connect].yubaba` URL when that host is in the `100.64.0.0/10` CGNAT
953    /// range the mesh uses. A loopback placeholder (`http://127.0.0.1:7443`,
954    /// meaning "pre-mesh, reachable only through an SSH tunnel") is *not* a
955    /// mesh address and yields `None`.
956    pub fn mesh_ipv4(&self) -> Option<&str> {
957        if let Some(ip) = self.registration.mesh_ipv4.as_deref() {
958            return Some(ip);
959        }
960        let url = self.connect.as_ref()?.yubaba.as_deref()?;
961        mesh_ipv4_from_url(url)
962    }
963
964    /// Base URL for this node's yubaba, or `None` when no reach resolves.
965    ///
966    /// Thin wrapper over [`reach`](Self::reach) for the many call sites that
967    /// only branch on presence. Prefer `reach` anywhere the operator sees the
968    /// outcome — a `None` here throws away a refusal that names exactly which
969    /// address is missing.
970    pub fn yubaba_url(&self) -> Option<String> {
971        self.reach().ok()
972    }
973
974    /// The **one** address automation dials for this node — mesh-only.
975    ///
976    /// `Err` is a *named refusal*, not an absence: a node with no mesh address
977    /// is unresolvable to every automated path, and R605-T10's whole complaint
978    /// is that this used to surface as a connect timeout against an address the
979    /// caller has no route to.
980    ///
981    /// Resolution order:
982    ///
983    /// 1. A declared `[connect].yubaba` on a **private** host (10/8,
984    ///    172.16/12, 192.168/16) is **not dialed** — see below.
985    /// 2. Any other declared `[connect].yubaba` wins verbatim. That includes
986    ///    the pre-mesh loopback placeholder (`http://127.0.0.1:7443`, "I have
987    ///    no mesh address; reach me through the SSH tunnel to `ssh`"), which is
988    ///    a genuine declaration and stays honoured.
989    /// 3. Otherwise `[registration].mesh_ipv4` composed with
990    ///    `[connect].yubaba_port`.
991    ///
992    /// **Why a LAN literal loses (R605-T10, operator 2026-08-19).** The LAN
993    /// address is an emergency break-glass route, never an official one, and
994    /// automation must ALWAYS assume the caller is not on that LAN — this camp
995    /// sits on 192.168.22.0/22 with no route to the fleet's 192.168.10.0/24 at
996    /// all. Writing one into the field every resolver dials does not sit beside
997    /// the mesh route, it *overrides* it: R707-T6 made a declared literal beat
998    /// `mesh_ipv4` outright, so us-west-011 (mesh-joined, healthy) was elected
999    /// for every aarch64 build and then dialed at an address that answers only
1000    /// from inside bldg-2506.
1001    ///
1002    /// **What R707-T6 wanted is preserved elsewhere.** Its forcing case was
1003    /// identity, not reach: the dev raft group advertises LAN addrs
1004    /// (`192.168.10.11:7443`, verified live off `/raft/status` 2026-08-27), and
1005    /// `rollout::yubaba::membership_to_nodes` has to map those back to declared
1006    /// machines. That match now runs against [`lan_endpoint`](Self::lan_endpoint),
1007    /// which is composed from the break-glass `[connect].address` metadata and
1008    /// is never dialed — so the two concerns the old precedence rule fused are
1009    /// split, and the literal can stop squatting a dialed field.
1010    ///
1011    /// The LAN address itself STAYS in the machine TOML. It is useful metadata
1012    /// and the manual `ssh` path is entitled to it; it is only disconnected
1013    /// from every automated process.
1014    pub fn reach(&self) -> Result<String, String> {
1015        let Some(connect) = self.connect.as_ref() else {
1016            return Err(format!(
1017                "machine {:?} declares no [connect] block, so nothing knows how to reach it \
1018                 \u{2192} declare one, or leave it unprovisioned and out of placement",
1019                self.name
1020            ));
1021        };
1022        let mesh = || {
1023            self.registration
1024                .mesh_ipv4
1025                .as_deref()
1026                .map(|ip| format!("http://{ip}:{}", connect.yubaba_port()))
1027        };
1028        if let Some(literal) = &connect.yubaba {
1029            let Some(lan) = private_ipv4_from_url(literal) else {
1030                return Ok(literal.clone());
1031            };
1032            return mesh().ok_or_else(|| {
1033                format!(
1034                    "machine {:?} is unresolvable to automation: its only declared yubaba reach \
1035                     is the private literal {:?} and it has no [registration].mesh_ipv4\n\
1036                     \u{2192} a LAN address is an emergency break-glass route, never an official \
1037                     one (R605-T10) — every automated path assumes the caller is NOT on {}/24\n\
1038                     \u{2192} mesh-join the box and record `mesh_ipv4` under [registration], then \
1039                     delete `[connect].yubaba` so the port composes with it",
1040                    self.name,
1041                    literal,
1042                    lan.rsplit_once('.').map(|(net, _)| net).unwrap_or(lan),
1043                )
1044            });
1045        }
1046        mesh().ok_or_else(|| {
1047            format!(
1048                "machine {:?} has no [registration].mesh_ipv4 and declares no \
1049                 [connect].yubaba, so no automated path can reach it\n\
1050                 \u{2192} mesh-join the box and record its tailnet address, or taint it out of \
1051                 placement — do not point `[connect].yubaba` at a LAN address (R605-T10)",
1052                self.name
1053            )
1054        })
1055    }
1056
1057    /// The LAN `host:port` this node's yubaba answers on, composed from the
1058    /// break-glass `[connect].address` metadata plus the declared port.
1059    ///
1060    /// **Identity only — never dial this.** It exists so a raft membership
1061    /// entry that names a node by its LAN address can be mapped back to the
1062    /// declared machine (`rollout::yubaba::membership_to_nodes`) without that
1063    /// address having to live in a field a resolver reads. `None` when the
1064    /// machine is unprovisioned.
1065    pub fn lan_endpoint(&self) -> Option<String> {
1066        let connect = self.connect.as_ref()?;
1067        Some(format!("{}:{}", connect.address, connect.yubaba_port()))
1068    }
1069
1070    /// Fold the pre-R707-T1 top-level `hostkey_fingerprint` into
1071    /// `[registration]`, and lift a mesh IP out of a legacy `[connect].yubaba`
1072    /// URL. Idempotent; a machine already on the split shape is untouched.
1073    ///
1074    /// [`save`](Self::save) calls this, so writing a machine TOML migrates it
1075    /// rather than round-tripping the old shape back out.
1076    pub fn normalize(&mut self) {
1077        if let Some(fp) = self.legacy_hostkey_fingerprint.take() {
1078            self.registration.hostkey_fingerprint.get_or_insert(fp);
1079        }
1080        if self.registration.mesh_ipv4.is_none() {
1081            if let Some(ip) = self
1082                .connect
1083                .as_ref()
1084                .and_then(|c| c.yubaba.as_deref())
1085                .and_then(mesh_ipv4_from_url)
1086                .map(str::to_string)
1087            {
1088                self.registration.mesh_ipv4 = Some(ip);
1089                // The URL was pure derivation from mesh IP + port; keep only
1090                // the declared half so the two can't drift apart.
1091                if let Some(c) = self.connect.as_mut() {
1092                    c.yubaba = None;
1093                }
1094            }
1095        }
1096    }
1097
1098    /// Persist to `<cloud_dir>/machines/<name>.toml`, creating the dir if needed.
1099    ///
1100    /// ⚠ Serializes the struct, so **operator comments in the target file are
1101    /// lost**. Pre-existing behaviour, not introduced here, but it is why
1102    /// registration writeback (`yah cloud machine attach`) goes through
1103    /// [`crate::state::MachineState`] and the comment-preserving path in the
1104    /// CLI rather than calling this on a hand-authored inventory file.
1105    pub fn save(&self, cloud_dir: &Path) -> Result<()> {
1106        let dir = cloud_dir.join("machines");
1107        std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
1108        let path = dir.join(format!("{}.toml", self.name));
1109        let mut normalized = self.clone();
1110        normalized.normalize();
1111        let s = toml::to_string_pretty(&normalized)
1112            .with_context(|| format!("serializing machine {}", self.name))?;
1113        std::fs::write(&path, s).with_context(|| format!("writing {}", path.display()))
1114    }
1115}
1116
1117/// Host of an `http://host:port` URL iff it is a mesh (headscale) IPv4 in the
1118/// `100.64.0.0/10` CGNAT range. String-level rather than URL-parsed: the
1119/// inventory format is stable and this crate carries no URL dependency (same
1120/// reasoning as `fleet_metrics::extract_host` and
1121/// `hub::coordinator::is_loopback_url`).
1122fn mesh_ipv4_from_url(url: &str) -> Option<&str> {
1123    let host = ipv4_host_of(url)?;
1124    let ip: std::net::Ipv4Addr = host.parse().ok()?;
1125    let [a, b, ..] = ip.octets();
1126    // 100.64.0.0/10 ⇒ first octet 100, second octet 64..=127.
1127    (a == 100 && (64..=127).contains(&b)).then_some(host)
1128}
1129
1130/// Host of an `http://host:port` URL iff it is an **RFC1918 private** IPv4 —
1131/// `10/8`, `172.16/12`, `192.168/16`. `None` for anything else, loopback and
1132/// the `100.64/10` mesh range included: neither is a LAN literal.
1133///
1134/// The judgement R605-T10 turns on. A private literal is only ever reachable
1135/// from inside one building, so it is metadata about where the box physically
1136/// sits and never an address automation may dial — see
1137/// [`MachineConfig::reach`] and [`crate::validate::check_lan_dial_targets`].
1138pub fn private_ipv4_from_url(url: &str) -> Option<&str> {
1139    let host = ipv4_host_of(url)?;
1140    is_private_ipv4(host).then_some(host)
1141}
1142
1143/// Whether a bare host string is an RFC1918 private IPv4 literal.
1144pub fn is_private_ipv4(host: &str) -> bool {
1145    let Ok(ip) = host.parse::<std::net::Ipv4Addr>() else {
1146        return false;
1147    };
1148    ip.is_private()
1149}
1150
1151/// Bare host of a `[scheme://]host[:port][/path]` string.
1152fn ipv4_host_of(url: &str) -> Option<&str> {
1153    let after_scheme = url.split("://").nth(1).unwrap_or(url);
1154    after_scheme.split(['/', ':']).next()
1155}
1156
1157/// Declared **reach** for a BYO `static` node (no provider API). Lives under
1158/// `[connect]` in the machine TOML.
1159///
1160/// Reach only — how the camp gets to the box. *Permission* is a separate axis
1161/// that belongs to cheers' scopes (W295 §"Deliberately deferred"); the two
1162/// collapse in practice today (mesh membership grants everything) and the data
1163/// model must not fuse them, so do not add an authorization field here.
1164///
1165/// `address`, `ssh` and `identity_file` stay whole, literal, operator-authored
1166/// strings even though their values often *look* derived. They are not:
1167/// us-west-001 dials SSH over its public IP while us-west-002 was deliberately
1168/// repointed at its tailnet IP (R608-F10) precisely because the LAN address is
1169/// unreachable off-LAN. Decomposing them into user + host and recomposing
1170/// would silently undo per-machine decisions like that one. `yubaba` is the
1171/// field that *was* derived — mesh IP plus a fixed port, rewritten by
1172/// mesh-join — so that is where R707-T1 cut.
1173#[derive(Debug, Clone, Serialize, Deserialize)]
1174#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1175pub struct ConnectSpec {
1176    /// Reachable IPv4/host for the box, e.g. `"45.32.194.254"`. Declared: which
1177    /// of a machine's several addresses the camp should use is an operator
1178    /// choice (public IP vs. LAN IP vs. tailnet IP).
1179    pub address: String,
1180    /// SSH target the camp dials for bootstrap + (pre-mesh) tunneled deploys,
1181    /// e.g. `"root@45.32.194.254"` or `"struc@100.64.0.4"`. Declared, whole —
1182    /// see the type doc. Pair with `identity_file` for a copy-pasteable
1183    /// `ssh -i <identity_file> <ssh>`.
1184    pub ssh: String,
1185    /// Private key path the camp uses to authenticate `ssh`, e.g.
1186    /// `"~/.ssh/yah"`. Every node in the fleet uses the same operator key
1187    /// today, but this is declared per-machine rather than assumed globally
1188    /// for the same reason `ssh` is whole rather than decomposed: a future
1189    /// node with a different key should not have to fight a hardcoded
1190    /// default. `~` is not shell-expanded by this crate — callers that shell
1191    /// out to `ssh`/`scp` pass it through `-i`, which expands it itself.
1192    pub identity_file: String,
1193    /// Port yubaba listens on. Declared reach; defaults to 7443 when omitted,
1194    /// which is every machine in the fleet today. Composed with the *observed*
1195    /// [`MachineRegistration::mesh_ipv4`] by [`MachineConfig::yubaba_url`].
1196    #[serde(default, skip_serializing_if = "Option::is_none")]
1197    pub yubaba_port: Option<u16>,
1198    /// Explicit yubaba base URL, overriding the composed form.
1199    ///
1200    /// Two live uses, both genuine declarations: a pre-mesh node saying
1201    /// `"http://127.0.0.1:7443"` — "I have no mesh address; reach me through
1202    /// the SSH tunnel to `ssh`" — and any node whose yubaba is not at
1203    /// `mesh_ipv4:port`. A URL here whose host *is* a mesh IP is the
1204    /// pre-R707-T1 shape; [`MachineConfig::normalize`] lifts it into
1205    /// `[registration].mesh_ipv4` and clears this field so the two cannot
1206    /// drift apart.
1207    #[serde(default, skip_serializing_if = "Option::is_none")]
1208    pub yubaba: Option<String>,
1209}
1210
1211/// Default yubaba listen port, used when `[connect].yubaba_port` is omitted.
1212pub const DEFAULT_YUBABA_PORT: u16 = 7443;
1213
1214impl ConnectSpec {
1215    /// Declared yubaba port, defaulting to [`DEFAULT_YUBABA_PORT`].
1216    pub fn yubaba_port(&self) -> u16 {
1217        self.yubaba_port.unwrap_or(DEFAULT_YUBABA_PORT)
1218    }
1219}
1220
1221#[derive(Debug, Clone, Serialize, Deserialize)]
1222#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
1223pub struct BucketSpec {
1224    pub name: String,
1225    pub public_read: bool,
1226}
1227
1228/// Per-camp mirror declaration from `.yah/cloud/mirrors/<id>/mirror.toml`
1229/// (folder form) or the legacy `.yah/cloud/mirrors/<id>.toml` (flat form).
1230///
1231/// The folder form is preferred for new mirrors so that per-mirror secrets
1232/// and override files can sit next to `mirror.toml` without polluting the
1233/// top-level `mirrors/` directory.
1234#[derive(Debug, Clone, Serialize, Deserialize)]
1235pub struct LegacyMirrorConfig {
1236    /// Logical camp name this mirror hosts, e.g. `"yah"` or `"noisetable"`.
1237    ///
1238    /// Serialised as `camp`; accepts the legacy `rig` spelling for files that
1239    /// predate the R137 rig→camp rename (one-time migration: `sed -i ''
1240    /// 's/^rig = /camp = /' ~/.yah/cloud/mirrors/*.toml`).
1241    #[serde(rename = "camp", alias = "rig")]
1242    pub camp: String,
1243    pub regions: Vec<String>,
1244    /// Workload names deployed as part of this mirror (references `workloads/<name>.toml`).
1245    /// Renamed from `services` in R092-F1; use `yah cloud config migrate-services-to-workloads`
1246    /// on repos that still have the old `services/` layout.
1247    #[serde(alias = "services")]
1248    pub workloads: Vec<String>,
1249    /// Base domain for Cloudflare-fronted services on this mirror's machines.
1250    /// Combined with the machine's `location` to build virtual-host names:
1251    /// e.g. `cloud_domain = "cloud.noisetable.example"` on machine in location
1252    /// `pdx` → Caddyfile site address `pdx.cloud.noisetable.example`.
1253    /// Optional: if unset the Caddyfile falls back to `:port` listeners.
1254    #[serde(default, skip_serializing_if = "Option::is_none")]
1255    pub cloud_domain: Option<String>,
1256}
1257
1258/// Error from loading or validating a single workload TOML file.
1259#[derive(Debug, Error)]
1260pub enum WorkloadConfigError {
1261    #[error("reading {path}: {source}")]
1262    Io {
1263        path: String,
1264        source: std::io::Error,
1265    },
1266    #[error("parsing {path}: {source}")]
1267    Toml {
1268        path: String,
1269        source: toml::de::Error,
1270    },
1271    #[error("invalid WorkloadSpec in {path}: {source}")]
1272    Shape {
1273        path: String,
1274        source: validate::ShapeError,
1275    },
1276}
1277
1278/// A workload declaration loaded from `.yah/cloud/workloads/<name>.toml`.
1279///
1280/// Each file is the human-authored TOML serialization of a [`WorkloadSpec`].
1281/// On load, the spec is validated against the shape layer; failures surface as
1282/// a [`CloudConfigError::Workload`] with the file path and field path.
1283#[derive(Debug, Clone, Serialize, Deserialize)]
1284pub struct WorkloadConfig {
1285    /// The validated spec.
1286    #[serde(flatten)]
1287    pub spec: WorkloadSpec,
1288}
1289
1290impl WorkloadConfig {
1291    /// Persist to `<cloud_dir>/workloads/<name>.toml`, creating the dir if needed.
1292    pub fn save(&self, cloud_dir: &Path) -> Result<()> {
1293        let dir = cloud_dir.join("workloads");
1294        std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
1295        let path = dir.join(format!("{}.toml", self.spec.name));
1296        let s = toml::to_string_pretty(self)
1297            .with_context(|| format!("serializing workload {}", self.spec.name))?;
1298        std::fs::write(&path, s).with_context(|| format!("writing {}", path.display()))
1299    }
1300}
1301
1302/// Error surfaced by [`CloudConfig::load`] when a workload TOML fails validation.
1303#[derive(Debug, Error)]
1304pub enum CloudConfigError {
1305    #[error(transparent)]
1306    Anyhow(#[from] anyhow::Error),
1307    #[error("workload validation failed: {0}")]
1308    Workload(WorkloadConfigError),
1309}
1310
1311/// Mirror-to-machine assignment table from `.yah/cloud/topology.toml`.
1312///
1313/// Declares which logical mirror names are assigned to which machines.
1314/// This is the source-canonical placement until yubaba raft observes it
1315/// (per the migration tracker in the arch doc).
1316#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1317pub struct TopologyConfig {
1318    /// Mirror→machine assignments.
1319    #[serde(default)]
1320    pub assignments: Vec<MirrorAssignment>,
1321    /// Declared buckets, logged by `yah cloud bucket create`.
1322    /// Source-canonical until yubaba raft observes actual placement.
1323    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1324    pub buckets: Vec<BucketLogEntry>,
1325}
1326
1327impl TopologyConfig {
1328    /// Load from a `topology.toml` file, returning `Default` when absent.
1329    pub fn load(path: &Path) -> Result<Self> {
1330        if !path.exists() {
1331            return Ok(Self::default());
1332        }
1333        let s =
1334            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1335        toml::from_str(&s).with_context(|| format!("parsing {}", path.display()))
1336    }
1337
1338    /// Persist to `topology.toml`, creating parent dirs if needed.
1339    pub fn save(&self, path: &Path) -> Result<()> {
1340        if let Some(parent) = path.parent() {
1341            std::fs::create_dir_all(parent)
1342                .with_context(|| format!("creating {}", parent.display()))?;
1343        }
1344        let s = toml::to_string_pretty(self).context("serializing topology")?;
1345        std::fs::write(path, s).with_context(|| format!("writing {}", path.display()))
1346    }
1347
1348    /// Find a declared bucket by name.
1349    pub fn bucket_by_name(&self, name: &str) -> Option<&BucketLogEntry> {
1350        self.buckets.iter().find(|b| b.name == name)
1351    }
1352
1353    /// Find a mutable declared bucket by name.
1354    pub fn bucket_by_name_mut(&mut self, name: &str) -> Option<&mut BucketLogEntry> {
1355        self.buckets.iter_mut().find(|b| b.name == name)
1356    }
1357
1358    /// Returns true if the bucket is declared as cross-machine (no owning machine).
1359    pub fn is_cross_machine_bucket(&self, name: &str) -> bool {
1360        self.buckets
1361            .iter()
1362            .any(|b| b.name == name && b.machine.is_none())
1363    }
1364}
1365
1366/// One mirror→machine placement entry in `topology.toml`.
1367#[derive(Debug, Clone, Serialize, Deserialize)]
1368pub struct MirrorAssignment {
1369    /// Logical mirror name, e.g. `"noisetable-pdx"`.
1370    pub mirror: String,
1371    /// Machine that hosts this mirror, e.g. `"noisetable-pdx-1"`.
1372    pub machine: String,
1373}
1374
1375/// A bucket declaration logged in `topology.toml` by `yah cloud bucket create`.
1376#[derive(Debug, Clone, Serialize, Deserialize)]
1377pub struct BucketLogEntry {
1378    pub name: String,
1379    /// Machine that owns this bucket. `None` marks it as cross-machine
1380    /// (no single-machine ownership; requires an explicit declaration in
1381    /// `topology.toml` before `yah cloud bucket create` will proceed without
1382    /// `--machine`).
1383    #[serde(default, skip_serializing_if = "Option::is_none")]
1384    pub machine: Option<String>,
1385    /// Logical location of the bucket, e.g. `"pdx"`.
1386    pub location: String,
1387    /// Current declared policy: `"private"` | `"public-read"` | `"signed-only"`.
1388    #[serde(default = "default_bucket_policy")]
1389    pub policy: String,
1390}
1391
1392fn default_bucket_policy() -> String {
1393    "private".to_string()
1394}
1395
1396#[derive(Debug, Clone, Serialize, Deserialize)]
1397pub struct PortMapping {
1398    pub host: u16,
1399    pub container: u16,
1400}
1401
1402/// A loaded service plus its per-environment mirrors.
1403///
1404/// Wraps the `service.toml` body and the directory of `mirrors/<env>.toml`
1405/// files that project the service onto concrete infra.
1406#[derive(Debug, Clone, Serialize, Deserialize)]
1407pub struct ServiceWithMirrors {
1408    pub service: ServiceConfig,
1409    /// Mirrors keyed by environment name (file stem of `mirrors/<env>.toml`).
1410    pub mirrors: BTreeMap<String, MirrorConfig>,
1411    /// Transform recipe names keyed by component id. Populated from each
1412    /// static-asset component's `workload.toml` at load time — not stored
1413    /// in service.toml. Only present for components that declare
1414    /// `[asset.derive.transform] recipe = "..."`.
1415    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1416    pub component_transform_recipes: BTreeMap<String, String>,
1417    /// Nodes each mirror's passway front door is placed on, keyed by env —
1418    /// exactly what [`MirrorConfig::passway_machines`] returns, with the envs
1419    /// that declare no passway edge left out.
1420    ///
1421    /// Derived at load time like `component_transform_recipes` above: it is
1422    /// stored in no TOML file. It exists so that a consumer of this wire type —
1423    /// the desktop `service_list` command, and through it the Services tab's
1424    /// custom-domain panel — never reconciles the two `ingress` spellings
1425    /// itself. An env present here with an **empty** list is a passway edge
1426    /// whose placement is co-located rather than declared; see
1427    /// [`MirrorConfig::passway_machines`] for why that is a different answer
1428    /// from being absent.
1429    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1430    pub passway_machines: BTreeMap<String, Vec<String>>,
1431}
1432
1433/// All cloud config loaded from a workspace root (the parent of `.yah/`).
1434///
1435/// Reads two trees:
1436/// - `.yah/infra/` — `machines/`, `providers/`
1437/// - `.yah/services/<svc>/` — `service.toml` + `mirrors/<env>.toml`
1438///
1439/// Pre-R215 fields (`legacy_mirrors`, `workloads`, `topology`) are still
1440/// populated from `.yah/cloud/` when present so pre-R215 callers (bucket
1441/// commands) keep compiling — they just see empty collections in a post-B1
1442/// workspace where the legacy data was deleted. These fields are scheduled
1443/// for removal in B3-T3. (`legacy_services` was the last of this group with
1444/// a live renderer — the compose/Caddy generator over it — and was removed
1445/// along with that renderer in R895-T2.)
1446#[derive(Debug)]
1447pub struct CloudConfig {
1448    /// Workspace root that was loaded — useful for path-resolving
1449    /// component references on a [`ServiceComponent`].
1450    pub workspace_root: std::path::PathBuf,
1451
1452    // ─── R215+ tree ────────────────────────────────────────────────────────
1453    /// `.yah/infra/machines/<name>.toml`
1454    pub machines: Vec<MachineConfig>,
1455    /// `.yah/infra/providers/<id>.toml`
1456    pub providers: Vec<ProviderConfig>,
1457    /// Provenance for every entry in `machines` that came from a linked
1458    /// `.yah/infra/sources.toml` source rather than this camp's own
1459    /// `.yah/infra/machines/` (R615-F2 / W274). Keyed by
1460    /// [`MachineConfig::name`]; a name absent here is camp-local. Empty from
1461    /// [`CloudConfig::load_from_config_dir`] — see its doc for why sources
1462    /// don't apply to multi-root sibling trees.
1463    pub machine_origins: BTreeMap<String, InfraOrigin>,
1464    /// Same as [`machine_origins`](Self::machine_origins), keyed by
1465    /// [`ProviderConfig::id`].
1466    pub provider_origins: BTreeMap<String, InfraOrigin>,
1467    /// `.yah/services/<svc>/` — service.toml plus mirrors/<env>.toml.
1468    pub services: BTreeMap<String, ServiceWithMirrors>,
1469    /// Measured restore times replayed from `.yah/cloud/recovery.jsonl`
1470    /// (R850-T2), keyed by workload name and summed across that workload's
1471    /// subjects. Empty in every camp that has never timed a restore — a missing
1472    /// journal is not an error, exactly like an unsynced infra source.
1473    ///
1474    /// This field is what lets [`crate::topology::analyze`] report a measured
1475    /// recovery instead of an extrapolation **while staying pure**: the
1476    /// measurement is read off the local tree here, at load, alongside every
1477    /// other declaration, so the analyzer gains no I/O and no `Path` argument.
1478    /// See [`crate::recovery_journal`].
1479    pub recovery_measurements: BTreeMap<String, crate::recovery_journal::WorkloadRecovery>,
1480    /// `.yah/domains/<name>.toml` — public-facing routing manifests
1481    /// (R347). Single file per domain; no nested per-env tree because
1482    /// domains themselves aren't projected onto infra — they describe
1483    /// how a Worker bundle ingresses requests onto services.
1484    pub domains: BTreeMap<String, DomainConfig>,
1485
1486    // ─── Pre-R215 legacy (slated for removal in B3-T3) ────────────────────
1487    /// Legacy mirrors from `.yah/cloud/mirrors/`.
1488    pub legacy_mirrors: Vec<LegacyMirrorConfig>,
1489    /// Workloads from `.yah/cloud/workloads/*.toml` (R092-F1 schema).
1490    pub workloads: Vec<WorkloadConfig>,
1491    /// Topology from `.yah/cloud/topology.toml` (mirror→machine assignments).
1492    pub topology: TopologyConfig,
1493}
1494
1495impl CloudConfig {
1496    /// Load all cloud config rooted at `workspace_root` (the parent of `.yah/`).
1497    ///
1498    /// Reads the R215+ tree (`.yah/infra/`, `.yah/services/<svc>/`) eagerly
1499    /// and the pre-R215 `.yah/cloud/` tree opportunistically. Returns `Err`
1500    /// immediately if any TOML fails to parse or a workload TOML fails
1501    /// shape validation; the error includes the file path and field path.
1502    ///
1503    /// Cross-ref validation runs after both trees finish loading: every
1504    /// `mirror.providers.X.use = "<id>"` must resolve to a real provider
1505    /// declared under `.yah/infra/providers/`.
1506    ///
1507    /// R844-B7 — **a missing `.yah/` is a wrong-root error, not an empty
1508    /// fleet.** Every sub-loader below tolerates a missing directory by
1509    /// returning empty, so before this check a call against the wrong
1510    /// directory produced a perfectly valid `CloudConfig` with zero machines,
1511    /// zero services and zero providers. Nothing downstream can tell that
1512    /// apart from a camp that genuinely declares nothing, so the failure
1513    /// surfaces as an operation that silently does nothing to nothing: a
1514    /// collate that renders no backends, a fanout that asks no nodes, a
1515    /// rollout that plans against an empty fleet. It was found the hard way —
1516    /// a live-fleet test in `app/yah/cli` called this with `"."`, which under
1517    /// `cargo test` is the *package* root, and passed while measuring nothing.
1518    ///
1519    /// The line is drawn at `.yah/` and only there: a workspace whose
1520    /// `.yah/infra/machines/` is absent or empty is a real, if unusual, camp
1521    /// with an empty fleet and still loads. `unknown` is not `answered with
1522    /// none`.
1523    pub fn load(workspace_root: &Path) -> Result<Self> {
1524        let yah_dir = crate::paths::yah_dir(workspace_root);
1525        if !yah_dir.is_dir() {
1526            anyhow::bail!(
1527                "not a yah workspace: no {} — expected the camp root (the parent \
1528                 of `.yah/`), got {}. This is a wrong-root error, not an empty \
1529                 fleet; a camp with no machines declared still has a `.yah/`.",
1530                yah_dir.display(),
1531                workspace_root.display(),
1532            );
1533        }
1534
1535        let mut providers = load_providers(&crate::paths::providers_dir(workspace_root))?;
1536        let services = load_services(&crate::paths::services_dir(workspace_root), workspace_root)?;
1537        let domains = load_domains(&crate::paths::domains_dir(workspace_root))?;
1538
1539        Self::cross_ref_validate(&providers, &services, &domains)?;
1540
1541        // Legacy `.yah/cloud/` reads — empty in post-B1 workspaces. Wrapped in
1542        // a helper so a missing tree is silent (no error, no warning).
1543        let cloud_dir = crate::paths::legacy_cloud_dir(workspace_root);
1544        let (legacy_mirrors, legacy_workloads, topology) = if cloud_dir.exists() {
1545            (
1546                load_mirrors(cloud_dir.join("mirrors"))?,
1547                load_workloads(cloud_dir.join("workloads"))?,
1548                load_topology(cloud_dir.join("topology.toml"))?,
1549            )
1550        } else {
1551            Default::default()
1552        };
1553
1554        // Workloads come from `.yah/infra/workloads/` (R215+). R568-T7: before
1555        // that path was read here, this field was populated *only* from the
1556        // legacy tree above — which R222-B1 emptied — so `cfg.workload(name)`
1557        // resolved nothing in every post-R215 camp and `yah cloud workload
1558        // deploy` could not find any declaration at all. The bug survived
1559        // because the only workloads ever deployed were forge/QED runs, which
1560        // build their spec in memory and never come through here. Same
1561        // dedupe-by-name shape as machines below: R215+ wins.
1562        let mut workloads = load_workloads(crate::paths::workloads_dir(workspace_root))?;
1563        let workload_names: std::collections::HashSet<String> =
1564            workloads.iter().map(|w| w.spec.name.clone()).collect();
1565        for w in legacy_workloads {
1566            if !workload_names.contains(&w.spec.name) {
1567                workloads.push(w);
1568            }
1569        }
1570
1571        // R870-B13: machines are resolved by [`resolve_fleet_inventory`] —
1572        // camp-local, the pre-R215 legacy tree, and every machine borrowed
1573        // through `.yah/infra/sources.toml`, in that precedence. This used to
1574        // be spelled out inline here, which made `CloudConfig::load` the only
1575        // reader that saw borrowed machines at all; the two *resolution*
1576        // callers in `validate`/`reconciler::domain` read a camp-local-only
1577        // loader and could not see a borrowing camp's fleet. There is now one
1578        // implementation and three callers.
1579        let fleet = resolve_fleet_inventory(workspace_root)?;
1580
1581        // Providers overlay here rather than inside `resolve_fleet_inventory`:
1582        // that function answers "which machines does this camp have", which is
1583        // the question with three readers. Providers have exactly one reader —
1584        // this load — so hoisting them would build a seam nothing crosses.
1585        let mut provider_origins = BTreeMap::new();
1586        overlay_source_providers(
1587            workspace_root,
1588            &fleet.sources,
1589            &mut providers,
1590            &mut provider_origins,
1591        );
1592
1593        Ok(Self {
1594            workspace_root: workspace_root.to_path_buf(),
1595            machines: fleet.machines,
1596            providers,
1597            machine_origins: fleet.origins,
1598            provider_origins,
1599            // Local, offline, and absent in most camps — the journal replays to
1600            // an empty map when the file isn't there (R850-T2).
1601            recovery_measurements: crate::recovery_journal::RecoveryJournal::at_workspace(
1602                workspace_root,
1603            )
1604            .replay(),
1605            services,
1606            domains,
1607            legacy_mirrors,
1608            workloads,
1609            topology,
1610        })
1611    }
1612
1613    /// Load the R215+ tree (`infra/`, `services/`, `domains/`) rooted at an
1614    /// arbitrary config directory instead of the hardcoded `.yah/`. This is the
1615    /// building block for multi-root deployments (W206 config layout (b), sibling
1616    /// `.noisetable/` trees) — see [`crate::multi_root`]. Part of R558-F4.
1617    ///
1618    /// `config_dir` is the `.X/` directory itself (e.g. `<parent>/.noisetable`);
1619    /// `workspace_root` remains the camp dir (the config dir's parent) so a
1620    /// component's `path` reference resolves against the same tree the classic
1621    /// [`CloudConfig::load`] uses. The legacy `.yah/cloud/` reads are skipped —
1622    /// multi-root deployments are post-R215 by construction — so `legacy_*`,
1623    /// `workloads`, and `topology` come back empty. Machines are read from
1624    /// `config_dir/infra/machines` directly (sibling trees declare their own
1625    /// inventory or none).
1626    ///
1627    /// R615-F2 decision, explicit rather than silent: **sources.toml overlay
1628    /// does NOT apply here.** This function
1629    /// exists specifically because a multi-root sibling tree (W206 layout
1630    /// (b), e.g. `.noisetable/`) is a *second config root inside the same
1631    /// camp*, not a second camp — `config_dir` is already wherever the
1632    /// caller decided this tree's infra lives, and `.yah/infra/sources.toml`
1633    /// (singular, tied to `paths::infra_dir(workspace_root)`) has no
1634    /// well-defined meaning for an arbitrary `config_dir` that isn't that
1635    /// path. A sibling tree that wants borrowed infra declares its own
1636    /// `sources.toml` under whichever root actually calls
1637    /// [`CloudConfig::load`] for it; `machine_origins`/`provider_origins`
1638    /// come back empty here, not wrong — there is nothing to overlay.
1639    pub fn load_from_config_dir(config_dir: &Path, workspace_root: &Path) -> Result<Self> {
1640        let providers = load_providers(&config_dir.join("infra").join("providers"))?;
1641        let services = load_services(&config_dir.join("services"), workspace_root)?;
1642        let domains = load_domains(&config_dir.join("domains"))?;
1643
1644        Self::cross_ref_validate(&providers, &services, &domains)?;
1645
1646        let machines = load_dir::<MachineConfig>(config_dir.join("infra").join("machines"))?;
1647
1648        Ok(Self {
1649            workspace_root: workspace_root.to_path_buf(),
1650            machines,
1651            providers,
1652            machine_origins: BTreeMap::new(),
1653            provider_origins: BTreeMap::new(),
1654            // Same reasoning as the sources overlay above: the recovery journal
1655            // is tied to `paths::recovery_journal(workspace_root)`, which has no
1656            // meaning for an arbitrary sibling config dir — and this loader
1657            // returns no `workloads` for a measurement to attach to anyway.
1658            recovery_measurements: BTreeMap::new(),
1659            services,
1660            domains,
1661            legacy_mirrors: vec![],
1662            workloads: vec![],
1663            topology: TopologyConfig::default(),
1664        })
1665    }
1666
1667    /// Cross-reference validation shared by [`CloudConfig::load`] and
1668    /// [`CloudConfig::load_from_config_dir`]: every mirror `providers.X.use =
1669    /// "<id>"` must resolve to a declared provider, and every domain route's
1670    /// `component = "<service>/<component-id>"` must resolve to a real component.
1671    fn cross_ref_validate(
1672        providers: &[ProviderConfig],
1673        services: &BTreeMap<String, ServiceWithMirrors>,
1674        domains: &BTreeMap<String, DomainConfig>,
1675    ) -> Result<()> {
1676        // Mirror `use = "<id>"` slots must resolve to a declared provider.
1677        let provider_ids: std::collections::HashSet<&str> =
1678            providers.iter().map(|p| p.id.as_str()).collect();
1679        for (svc_name, svc) in services {
1680            // A relative health path would be joined onto the origin as if it
1681            // were absolute by one URL builder and dropped by the next, so the
1682            // probe would silently ask a different question than the file
1683            // reads. Refuse it at load instead.
1684            if let Some(p) = &svc.service.health_path {
1685                if !p.starts_with('/') {
1686                    anyhow::bail!(
1687                        "services/{svc_name}/service.toml: health_path = \"{p}\" \
1688                         must be absolute — write \"/{p}\""
1689                    );
1690                }
1691            }
1692            for (env, mirror) in &svc.mirrors {
1693                for (slot, body) in &mirror.providers {
1694                    if let Some(id) = body.provider_id() {
1695                        if !provider_ids.contains(id) {
1696                            anyhow::bail!(
1697                                "services/{svc_name}/mirrors/{env}.toml: \
1698                                 providers.{slot}.use = \"{id}\" — no such provider; \
1699                                 declare it at infra/providers/{id}.toml"
1700                            );
1701                        }
1702                    }
1703                }
1704                // An `[[ingress]]` edge's own `use` is the same kind of
1705                // reference (R845) and gets the same check: a typo there is
1706                // otherwise invisible until `yah cloud apply` reaches the
1707                // Cloudflare arm and fails on a missing provider file.
1708                for (idx, edge) in mirror.ingress_edge_slice().iter().enumerate() {
1709                    if let Some(id) = edge.provider_id.as_deref() {
1710                        if !provider_ids.contains(id) {
1711                            anyhow::bail!(
1712                                "services/{svc_name}/mirrors/{env}.toml: \
1713                                 ingress[{idx}].use = \"{id}\" — no such provider; \
1714                                 declare it at infra/providers/{id}.toml"
1715                            );
1716                        }
1717                    }
1718                }
1719                // R905. A `[build.<id>]` override keyed by a component this
1720                // service does not declare is always a typo, and it is the
1721                // silent kind: nothing reads the table for a component that
1722                // isn't there, so the environment goes on building with the
1723                // command the operator believed they had replaced — which is
1724                // exactly the defect the override exists to fix, wearing a
1725                // config that looks like the fix.
1726                for key in mirror.build.keys() {
1727                    if !svc.service.components.iter().any(|c| &c.id == key) {
1728                        let declared: Vec<&str> = svc
1729                            .service
1730                            .components
1731                            .iter()
1732                            .map(|c| c.id.as_str())
1733                            .collect();
1734                        anyhow::bail!(
1735                            "services/{svc_name}/mirrors/{env}.toml: \
1736                             [build.{key}] — no component {key:?} in \
1737                             services/{svc_name}/service.toml (declared: {declared:?})"
1738                        );
1739                    }
1740                }
1741            }
1742        }
1743
1744        // R870-B11. Two bundle-tier components sharing a mount would stage
1745        // into the same `app/dist/<mount>/` prefix inside the service's one
1746        // assembled bundle and silently clobber each other on disk — the
1747        // exact failure class this ticket exists to fix, one level down
1748        // (there it was two components silently overwriting the same
1749        // *workload*; here it would be two components silently overwriting
1750        // the same *path inside* the workload). A mount is owned by exactly
1751        // one component; refuse the config before the clobber happens.
1752        //
1753        // R870-F23 widens the same loop to the workload tier rather than
1754        // adding a parallel one. A mount is owned by exactly one component
1755        // whichever tier serves it: two workload-tier components at one mount
1756        // would hand the inner door two upstream sets for one prefix, and two
1757        // components in *different* tiers at one mount is the same clobber
1758        // read from the routing side — the request reaches whichever of the
1759        // bundle and the workload the mount table happened to name. So the
1760        // rule is now "one component per mount, service-wide", and only the
1761        // explanation branches on tier.
1762        for (svc_name, svc) in services {
1763            let mut owner_by_mount: BTreeMap<String, (&str, DeployTier)> = BTreeMap::new();
1764            for component in &svc.service.components {
1765                let bundle_tier =
1766                    component.kind == "mesofact-static" || component.kind == "mesofact-spa";
1767                if !bundle_tier && component.deploy != DeployTier::Workload {
1768                    continue;
1769                }
1770                let mount = component
1771                    .mount
1772                    .as_deref()
1773                    .map(normalize_mount)
1774                    .unwrap_or_default();
1775                if let Some((existing, existing_tier)) =
1776                    owner_by_mount.insert(mount.clone(), (&component.id, component.deploy))
1777                {
1778                    let where_ = if mount.is_empty() {
1779                        "the service root (no `mount`)".to_string()
1780                    } else {
1781                        format!("mount = \"/{mount}\"")
1782                    };
1783                    let why = if existing_tier == component.deploy {
1784                        match component.deploy {
1785                            DeployTier::Bundle => {
1786                                "a bundle-tier component's mount is a storage prefix inside the \
1787                                 service's single assembled bundle (app/dist/<mount>/), so two \
1788                                 components at the same mount would stage into the same path and \
1789                                 silently overwrite each other"
1790                            }
1791                            DeployTier::Workload => {
1792                                "a workload-tier component's mount is its prefix in the service's \
1793                                 inner-door route table, so two components at the same mount would \
1794                                 claim one prefix and requests would reach whichever the table \
1795                                 named"
1796                            }
1797                        }
1798                    } else {
1799                        "one is staged into the service bundle and the other deploys as its own \
1800                         workload, so the mount names two different things that serve one prefix \
1801                         — the inner door can only route it to one of them"
1802                    };
1803                    anyhow::bail!(
1804                        "services/{svc_name}/service.toml: components \"{existing}\" and \
1805                         \"{}\" both declare {where_} — {why}. Give one of them a distinct \
1806                         `mount`.",
1807                        component.id,
1808                    );
1809                }
1810            }
1811        }
1812
1813        // Every domain route's `component = "<service>/<component-id>"` must
1814        // resolve to a real component.
1815        for (dom_name, dom) in domains {
1816            for (idx, route) in dom.routes.iter().enumerate() {
1817                let Some(component_ref) = route.mode.component() else {
1818                    continue; // redirects don't reference components
1819                };
1820                let Some((svc_name, comp_id)) = split_component_ref(component_ref) else {
1821                    anyhow::bail!(
1822                        "domains/{dom_name}.toml: routes[{idx}].component = \
1823                         \"{component_ref}\" — expected \"<service>/<component-id>\""
1824                    );
1825                };
1826                let Some(svc) = services.get(svc_name) else {
1827                    anyhow::bail!(
1828                        "domains/{dom_name}.toml: routes[{idx}].component = \
1829                         \"{component_ref}\" — no such service \"{svc_name}\" \
1830                         under services/"
1831                    );
1832                };
1833                let Some(component) = svc.service.components.iter().find(|c| c.id == comp_id)
1834                else {
1835                    anyhow::bail!(
1836                        "domains/{dom_name}.toml: routes[{idx}].component = \
1837                         \"{component_ref}\" — service \"{svc_name}\" has no \
1838                         component with id \"{comp_id}\""
1839                    );
1840                };
1841
1842                // R746: a mounted component must be routed where it publishes.
1843                // The publisher writes its bundle under the mount and the front
1844                // door looks a request up by its own path, so a route path and
1845                // a mount that disagree produce a 404 with its cause two files
1846                // away. Checked in both directions, since either one alone is
1847                // the same silent miss.
1848                //
1849                // Static routes only: `mount` is a *storage* prefix, and a
1850                // backend route proxies to an origin that owns its own paths.
1851                if !matches!(route.mode, RouteMode::Static { .. }) {
1852                    continue;
1853                }
1854                let mount = component.mount.as_deref().map(normalize_mount);
1855                let route_prefix = route_path_prefix(&route.path);
1856                if let Some(mount) = mount {
1857                    if mount != route_prefix {
1858                        anyhow::bail!(
1859                            "domains/{dom_name}.toml: routes[{idx}].path = \
1860                             \"{path}\" serves \"{component_ref}\", which \
1861                             declares mount = \"/{mount}\" — a mounted \
1862                             component publishes under its mount, so the route \
1863                             must be \"/{mount}\" or \"/{mount}/*\" (or drop \
1864                             the mount to serve from the service root)",
1865                            path = route.path,
1866                        );
1867                    }
1868                } else if !route_prefix.is_empty() {
1869                    anyhow::bail!(
1870                        "domains/{dom_name}.toml: routes[{idx}].path = \
1871                         \"{path}\" serves \"{component_ref}\", which declares \
1872                         no `mount` — its bundle publishes at the service root, \
1873                         so nothing is stored under \"/{route_prefix}\". Set \
1874                         mount = \"/{route_prefix}\" on the component, or route \
1875                         it at \"/*\"",
1876                        path = route.path,
1877                    );
1878                }
1879            }
1880        }
1881        Ok(())
1882    }
1883
1884    /// Look up a domain manifest by name (file stem under `.yah/domains/`).
1885    pub fn domain(&self, name: &str) -> Option<&DomainConfig> {
1886        self.domains.get(name)
1887    }
1888
1889    pub fn machine(&self, name: &str) -> Option<&MachineConfig> {
1890        self.machines.iter().find(|m| m.name == name)
1891    }
1892
1893    /// Look up a provider by id (matches `provider.id`, not the file stem).
1894    pub fn provider(&self, id: &str) -> Option<&ProviderConfig> {
1895        self.providers.iter().find(|p| p.id == id)
1896    }
1897
1898    /// Look up a service by name (matches `service.toml`'s `name` field).
1899    pub fn service(&self, name: &str) -> Option<&ServiceWithMirrors> {
1900        self.services.get(name)
1901    }
1902
1903    /// Look up a legacy mirror by camp name (pre-R215 .yah/cloud/mirrors/).
1904    pub fn legacy_mirror(&self, camp: &str) -> Option<&LegacyMirrorConfig> {
1905        self.legacy_mirrors.iter().find(|m| m.camp == camp)
1906    }
1907
1908    pub fn workload(&self, name: &str) -> Option<&WorkloadConfig> {
1909        self.workloads.iter().find(|w| w.spec.name == name)
1910    }
1911
1912    /// Every machine declaring `sovereign_group == group`, in declaration order.
1913    ///
1914    /// W305/R742-F3. A sovereign group has no file of its own — it exists only
1915    /// as the set of machines that name the same string — so "which boxes are
1916    /// the dev cluster" has to be *derived*, and before this it was not derived
1917    /// anywhere: `yah cloud rollout plan` still takes a hand-listed
1918    /// `--voter us-west-011 --voter us-west-013 …` for a fact the machine TOMLs
1919    /// already state (W314 gap 1).
1920    ///
1921    /// **This is not placement.** Resolving a group to its members is a
1922    /// *lookup*, and it stays outside [`RequiredSpec`] on purpose — see
1923    /// [`MachineConfig::sovereign_group`]. `migrate` calls this to pick the
1924    /// candidate set it then admits a workload against; nothing here filters
1925    /// scheduling, and adding `sovereign_group` to `matches` would still be the
1926    /// category error that doc warns about.
1927    ///
1928    /// An empty result means no machine declares `group`, which is
1929    /// indistinguishable from a typo — callers should say so with
1930    /// [`Self::declared_sovereign_groups`] rather than reporting "no
1931    /// candidates".
1932    pub fn machines_in_group(&self, group: &str) -> Vec<&MachineConfig> {
1933        self.machines
1934            .iter()
1935            .filter(|m| m.sovereign_group.as_deref() == Some(group))
1936            .collect()
1937    }
1938
1939    /// Every distinct `sovereign_group` declared by any machine, sorted.
1940    ///
1941    /// Exists so a bad `--to` names the real vocabulary instead of complaining
1942    /// abstractly — the same fail-loud shape [`taint_effect`]'s legal-key list
1943    /// gives `check_inert_taints`. Standalone machines (`None`) contribute
1944    /// nothing: "in no group" is not a group you can migrate *to*.
1945    pub fn declared_sovereign_groups(&self) -> Vec<&str> {
1946        let mut groups: Vec<&str> = self
1947            .machines
1948            .iter()
1949            .filter_map(|m| m.sovereign_group.as_deref())
1950            .collect();
1951        groups.sort_unstable();
1952        groups.dedup();
1953        groups
1954    }
1955
1956    /// F16 placement v1: the first machine satisfying every hard axis of `req`
1957    /// (region/zone/provider membership + mesh_tags superset). Declaration order
1958    /// in `.yah/infra/machines/` decides ties — deterministic-greedy, no
1959    /// backtracking. A fully-unconstrained `req` matches the first machine.
1960    ///
1961    /// Fails loud with the constraint summary and the candidate machine names
1962    /// when nothing matches, so `yah cloud apply` surfaces *why* placement
1963    /// failed instead of a silent empty set.
1964    pub fn resolve_machine(&self, req: &RequiredSpec) -> Result<&MachineConfig> {
1965        resolve_machine_among(&self.machines, req)
1966    }
1967
1968    /// F16 placement at horizontal scale: the first
1969    /// [`RequiredSpec::replica_count`] machines satisfying every hard axis of
1970    /// `req`, in declaration order (R844-F8).
1971    ///
1972    /// The N-valued form of [`Self::resolve_machine`], which is the N=1 case of
1973    /// this and not a different selector — both land in [`select_matching`].
1974    /// That shared bottom is what makes the deploy resolver
1975    /// (`reconciler::mesofact_bundle::resolve_bundle_machines`, which calls
1976    /// this) and the ingress planner's
1977    /// (`reconciler::ingress::resolve_ingress_placements`, which calls
1978    /// [`resolve_machines_among`] over the same `machines` slice) agree on the
1979    /// same N machines **by construction**. They must agree set-for-set, not
1980    /// merely in count: a front door aimed at nodes the workload was never
1981    /// deployed to renders a *subset* of the backends, which is the failure that
1982    /// looks like it worked.
1983    pub fn resolve_machines(&self, req: &RequiredSpec) -> Result<Vec<&MachineConfig>> {
1984        resolve_machines_among(&self.machines, req)
1985    }
1986
1987    /// F16 placement: first machine whose `mesh_tags` is a superset of
1988    /// `required`. Declaration order in `.yah/infra/machines/` decides ties.
1989    /// Empty `required` matches the first machine; callers should treat
1990    /// empty-required as "no constraint" and skip this lookup.
1991    ///
1992    /// Back-compat thin wrapper over [`CloudConfig::resolve_machine`] for the
1993    /// mesh-tags-only call sites that predate the topology axes.
1994    pub fn resolve_machine_by_mesh_tags(&self, required: &[String]) -> Option<&MachineConfig> {
1995        let req = RequiredSpec {
1996            mesh_tags: required.to_vec(),
1997            ..Default::default()
1998        };
1999        self.resolve_machine(&req).ok()
2000    }
2001
2002    /// Admission: resolve the target machine for a remote [`WorkloadSpec`],
2003    /// honoring the R594 mesh-tag node-selector annotation
2004    /// (`velveteen_exec::remote::NODE_SELECTOR_MESH_TAGS_ANNOTATION` =
2005    /// `yah.node-selector.mesh-tags`, comma-joined).
2006    ///
2007    /// The producer side (`velveteen_exec::remote::build_workload_spec`, R594) writes
2008    /// `TaskLocation::RemoteAny.mesh_tags` — e.g. `[tag:build-worker, arch:x86]`
2009    /// from [`qed::platform::build_worker_mesh_tags`] — into the workload's
2010    /// annotations. This is the consumer: candidates are restricted to machines
2011    /// whose `mesh_tags` are a **superset** of the requested set, so an amd64
2012    /// build lands on the `arch:x86` build-worker (us-west-002) and an arm64
2013    /// build on a `arch:arm` Pi5. Declaration order in `.yah/infra/machines/`
2014    /// breaks ties.
2015    ///
2016    /// An absent or empty annotation means "no mesh-tag constraint" — pre-R594
2017    /// behavior (any node), matching [`RequiredSpec::is_unconstrained`].
2018    ///
2019    /// This is the single admission seam: R572-F5 extends it with the capacity
2020    /// floor (workload request fits node allocatable−committed) and taint
2021    /// repulsion/affinity by enriching [`RequiredSpec::matches`] /
2022    /// [`Self::resolve_machine`]. Do not fork a second selector.
2023    pub fn admit_workload(&self, ws: &WorkloadSpec) -> Result<&MachineConfig> {
2024        self.resolve_machine(&admission_spec(ws, &self.workloads)?)
2025    }
2026
2027    /// Every machine that admits `ws`, in declaration order — the *pool*
2028    /// [`Self::admit_workload`] returns the head of (R605-T14).
2029    ///
2030    /// # Why a pool and not just the winner
2031    ///
2032    /// `tag:build-worker` is a statement that the tagged boxes are
2033    /// **interchangeable**: a build is booked against the tag, not against
2034    /// `us-west-002`. Returning one machine forced every caller to act as if it
2035    /// were booked against a name, and admission has no liveness input — so a
2036    /// tagged box that is asleep won the file-name tie-break and its builds
2037    /// failed rather than landing on the identical box next to it. That is
2038    /// exactly what happened on 2026-09-03 when `us-west-002` regained the tag.
2039    ///
2040    /// The fix is **not** to teach this function about liveness. It stays a pure
2041    /// function of the declared inventory (see `xtask/tests/fleet_build_placement.rs`
2042    /// on why a placement pin that needs the network is a flake). It hands the
2043    /// dispatcher the whole interchangeable set instead, and the dispatcher —
2044    /// which has the network — probes and fails over within it:
2045    /// `app/yah/cli/src/yubaba_client.rs`'s `MeshYubabaClient::deploy`.
2046    ///
2047    /// Order is the declaration order `admit_workload` already used, and callers
2048    /// should preserve it as their preference order rather than load-balancing
2049    /// across it: a retried build wants the node still holding its warm
2050    /// `target/`, which is the same reason [`first_match`] is deliberately
2051    /// first-fit.
2052    ///
2053    /// `Err` — never `Ok(vec![])` — when nothing admits `ws`, carrying the same
2054    /// message [`Self::admit_workload`] would have produced. "No node admits
2055    /// this" and "the pool is empty" are the same failure and must read the same.
2056    pub fn admit_workload_candidates(&self, ws: &WorkloadSpec) -> Result<Vec<&MachineConfig>> {
2057        let req = admission_spec(ws, &self.workloads)?;
2058        let all: Vec<&MachineConfig> = self.machines.iter().collect();
2059        let matched = matching(&all, &req);
2060        if matched.is_empty() {
2061            // Delegate the wording so the two paths cannot drift apart.
2062            return Err(first_match(&all, &req, DECLARED_POOL, EMPTY_DECLARED_POOL)
2063                .expect_err("matching() found nothing, so first_match cannot succeed"));
2064        }
2065        Ok(matched)
2066    }
2067
2068    /// [`Self::admit_workload`] restricted to the machines of one sovereign
2069    /// group (W305/R742-F3, `yah cloud migrate --to <group>`).
2070    ///
2071    /// Same [`RequiredSpec`], same [`RequiredSpec::matches`], same
2072    /// declaration-order tie-break — only the candidate *set* differs. That is
2073    /// the whole reason this is a narrowing of the admission seam rather than a
2074    /// second selector: a workload that cannot be scheduled onto a group's
2075    /// boxes must fail here for exactly the reason it would fail anywhere else,
2076    /// and `no-appliance` on the dev Pis (W305 finding 2) is precisely the case
2077    /// that must not be silently routed around by a migration verb.
2078    ///
2079    /// `Err` when the group has no members *or* when no member admits `ws`; the
2080    /// two are different mistakes, so callers wanting to tell them apart should
2081    /// check [`Self::machines_in_group`] first.
2082    pub fn admit_workload_in_group(
2083        &self,
2084        ws: &WorkloadSpec,
2085        group: &str,
2086    ) -> Result<&MachineConfig> {
2087        let members = self.machines_in_group(group);
2088        let empty_pool = format!(
2089            "(no machine declares sovereign_group = \"{group}\" — declared groups: {})",
2090            match self.declared_sovereign_groups().as_slice() {
2091                [] => "(none)".to_string(),
2092                gs => gs.join(", "),
2093            }
2094        );
2095        first_match(
2096            &members,
2097            &admission_spec(ws, &self.workloads)?,
2098            &format!("machines in sovereign group '{group}'"),
2099            &empty_pool,
2100        )
2101    }
2102}
2103
2104/// **The** placement selector: the first candidate satisfying every axis of
2105/// `req`, declaration order breaking ties, deterministic-greedy with no
2106/// backtracking.
2107///
2108/// Every path that picks a machine goes through here, and the only thing any
2109/// of them varies is *which machines are candidates* — never the predicate.
2110/// [`CloudConfig::resolve_machine`] passes the whole fleet;
2111/// [`CloudConfig::admit_workload_in_group`] passes one sovereign group's
2112/// members. That split is the point: a candidate-set narrowing composes with
2113/// the [`RequiredSpec`] axes for free, whereas expressing the same narrowing
2114/// *as* an axis would put facts like blast radius into a filter they must
2115/// never be in (see [`MachineConfig::sovereign_group`]).
2116///
2117/// So a new placement scope is a new candidate set plus a `pool` label, and a
2118/// new placement *constraint* is a field on [`RequiredSpec`] — those are the
2119/// two extension points, and neither is a second selector. `pool` and
2120/// `empty_pool` exist only so the failure names the set it actually searched;
2121/// a refusal that says "no candidates" without saying *among what* is one the
2122/// operator has to reconstruct by hand.
2123/// F16 placement v1 resolution over an explicit machine list — the
2124/// `.machines`-only half of [`CloudConfig::resolve_machine`], for callers that
2125/// have loaded just the machines tree rather than the whole cross-ref-validated
2126/// config.
2127///
2128/// R772: `resolve_ingress_placements` (`reconciler::ingress`) is the reason
2129/// this is `pub(crate)` rather than staying folded into
2130/// `CloudConfig::resolve_machine` — ingress collation walks every mirror in
2131/// the workspace and has no business hard-failing over an unrelated mirror's
2132/// `providers.X.use = "<id>"` typo, which is what going through
2133/// `CloudConfig::load`'s cross-ref validation would do. "Do not fork a second
2134/// selector" (see the module doc above) still holds: this is the *same*
2135/// [`first_match`], just handed a narrower candidate set than `self.machines`.
2136pub(crate) fn resolve_machine_among<'a>(
2137    machines: &'a [MachineConfig],
2138    req: &RequiredSpec,
2139) -> Result<&'a MachineConfig> {
2140    let all: Vec<&MachineConfig> = machines.iter().collect();
2141    first_match(&all, req, DECLARED_POOL, EMPTY_DECLARED_POOL)
2142}
2143
2144/// R844-F8: [`resolve_machine_among`] widened to the constraint's own replica
2145/// count — the first [`RequiredSpec::replica_count`] matching machines, in the
2146/// same declaration order, from the same candidate slice.
2147///
2148/// **The one entry point both resolvers share.**
2149/// `reconciler::ingress::resolve_ingress_placements` calls this directly and
2150/// `reconciler::mesofact_bundle::resolve_bundle_machines` reaches it through
2151/// [`CloudConfig::resolve_machines`], both over `cfg.machines` — so the ingress
2152/// planner and the deployer cannot pick different subsets. That is a structural
2153/// guarantee, not a tested coincidence, and it has to be: discovery aimed at a
2154/// node the bundle was never placed on publishes a hostname with a dead
2155/// backend behind it, and at scale > 1 the front door still answers from the
2156/// nodes that *did* get it.
2157///
2158/// Determinism is therefore part of correctness here. `machines` arrives in
2159/// file-name order (`load_dir`, pinned by
2160/// `machines_load_in_file_name_order_not_read_dir_order`), and selection is a
2161/// stable prefix of that order — so "the first two matching" is the same two
2162/// on both sides of the same tree.
2163pub(crate) fn resolve_machines_among<'a>(
2164    machines: &'a [MachineConfig],
2165    req: &RequiredSpec,
2166) -> Result<Vec<&'a MachineConfig>> {
2167    let all: Vec<&MachineConfig> = machines.iter().collect();
2168    select_matching(
2169        &all,
2170        req,
2171        req.replica_count(),
2172        DECLARED_POOL,
2173        EMPTY_DECLARED_POOL,
2174    )
2175}
2176
2177const DECLARED_POOL: &str = "declared machines";
2178const EMPTY_DECLARED_POOL: &str = "(no machines declared under .yah/infra/machines/)";
2179
2180fn first_match<'a>(
2181    candidates: &[&'a MachineConfig],
2182    req: &RequiredSpec,
2183    pool: &str,
2184    empty_pool: &str,
2185) -> Result<&'a MachineConfig> {
2186    Ok(select_matching(candidates, req, 1, pool, empty_pool)?
2187        .into_iter()
2188        .next()
2189        .expect("select_matching errors rather than returning short"))
2190}
2191
2192/// The N-selecting core of the placement selector: the first `want` candidates
2193/// satisfying `req`, in candidate order (R844-F8).
2194///
2195/// [`first_match`] is this with `want = 1`, which is why widening a caller to a
2196/// replica count cannot introduce a second selector — the predicate, the
2197/// ordering and the failure vocabulary are all one implementation.
2198///
2199/// **A shortfall is an error.** Matching one machine when two were asked for
2200/// returns `Err` naming both numbers and the pool searched, never a one-element
2201/// vec: a half-placed workload that reports success is worse than a failed
2202/// apply, because the front door then publishes a hostname whose backend set is
2203/// quietly smaller than declared. `want = 0` is the same mistake spelled
2204/// differently and is refused for the same reason.
2205fn select_matching<'a>(
2206    candidates: &[&'a MachineConfig],
2207    req: &RequiredSpec,
2208    want: usize,
2209    pool: &str,
2210    empty_pool: &str,
2211) -> Result<Vec<&'a MachineConfig>> {
2212    let names = || {
2213        if candidates.is_empty() {
2214            empty_pool.to_string()
2215        } else {
2216            candidates
2217                .iter()
2218                .map(|m| m.name.as_str())
2219                .collect::<Vec<_>>()
2220                .join(", ")
2221        }
2222    };
2223
2224    if want == 0 {
2225        anyhow::bail!(
2226            "replicas = 0 places {} on nothing — a placement that deploys to no machine is \
2227             a typo, not a scale-down; remove the slot instead",
2228            req.describe()
2229        );
2230    }
2231
2232    let mut matched = matching(candidates, req);
2233    if matched.len() >= want {
2234        matched.truncate(want);
2235        return Ok(matched);
2236    }
2237
2238    if want == 1 {
2239        anyhow::bail!(
2240            "no candidates matching {} — {pool}: {}",
2241            req.describe(),
2242            names()
2243        );
2244    }
2245    anyhow::bail!(
2246        "only {} of {want} machines match {} — placing fewer than the declared \
2247         `replicas = {want}` would publish a smaller backend set than the mirror asks for; \
2248         {pool}: {}",
2249        matched.len(),
2250        req.describe(),
2251        names()
2252    )
2253}
2254
2255/// The predicate itself, applied to every candidate in order — the one place
2256/// `req.matches` is called on a set.
2257///
2258/// [`select_matching`] takes a prefix of this; [`CloudConfig::admit_workload_candidates`]
2259/// takes all of it. Keeping both on this function is what makes "the pool the
2260/// dispatcher failed over within" and "the machine admission picked" the same
2261/// answer by construction rather than by two filters that happen to agree.
2262fn matching<'a>(candidates: &[&'a MachineConfig], req: &RequiredSpec) -> Vec<&'a MachineConfig> {
2263    candidates
2264        .iter()
2265        .copied()
2266        .filter(|m| req.matches(m))
2267        .collect()
2268}
2269
2270/// The [`RequiredSpec`] a workload is admitted against — the single place the
2271/// axes are derived from a [`WorkloadSpec`].
2272///
2273/// Extracted from [`CloudConfig::admit_workload`] so that
2274/// [`CloudConfig::admit_workload_in_group`] narrows the candidate set without
2275/// restating the axes. Forking that derivation is how the two paths would
2276/// silently disagree about whether a workload fits a node.
2277///
2278/// # It admits a group, not a workload (R860-T4 / W338)
2279///
2280/// The axes come from [`placement_group`] — `ws` plus the transitive closure of
2281/// its `local` requirement edges — because those members are placed together or
2282/// not at all. Capacity is their **sum**, archetype repulsion their **union**,
2283/// and mesh tags their union too. `prefer-local` and `anywhere` edges bind
2284/// nothing: a spec with neither `requires` nor `depends_on` local edges has a
2285/// group of exactly itself and resolves byte-identically to the pre-R860 axes.
2286///
2287/// This is the **only** gate. Node election is CLI-side
2288/// (`MeshYubabaClient::elect_node`, which picks a live member of the pool this
2289/// produces); the yubaba node process accepts whatever it is handed and never
2290/// re-checks placement, so a wrong group here is not caught downstream.
2291///
2292/// @yah:ticket(R860-T4, "Admission: place the transitive closure of `local` edges as one group, not one workload")
2293/// @yah:status(review)
2294/// @yah:phase(P1)
2295/// @yah:at(2026-09-05T18:29:13Z)
2296/// @yah:assignee(agent:bundle-anthropic-ashguard)
2297/// @yah:parent(R860)
2298/// @yah:next("W338 §Placement consequences 1 and 2. `admission_spec()` (config.rs:1974-1998) derives its axes from ONE spec; it must derive them from the group — the transitive closure of `local` requirement edges over `effective_requirements()`. `prefer-local` and `anywhere` edges do NOT bind the group. Three consequences: memory/cpu floor becomes the SUM of the group's requests, not the requirer's alone; `repel_archetype` becomes the union over members (so a group containing an Appliance is repelled by `no-appliance` even if the requirer is a Server); and the group is non-drainable if ANY member is an Appliance, which today is a per-workload check at yubaba/src/lib.rs:3117-3128 and now has to be computed over a set.")
2299/// @yah:verify("cargo test -p cloud --lib config")
2300/// @yah:gotcha("Node election is CLI-side, not cluster-side: `MeshYubabaClient::elect_node` (app/yah/cli/src/yubaba_client.rs:235-268) calls `admit_workload_candidates` (config.rs:1753), picks one node, and POSTs the deploy there. The yubaba node process never decides placement — it accepts whatever it is handed. So group admission has to be right in `config.rs` because there is no second gate downstream to catch it.")
2301/// @arch:see(.yah/docs/working/W338-workload-dependencies-and-appliance-composition.md)
2302/// @yah:depends_on(R860-T1)
2303/// @yah:handoff("ADMISSION NOW PLACES A GROUP, NOT A WORKLOAD. `admission_spec` (oss/yubaba/crates/cloud/src/config.rs:2009) takes `(ws, declared: &[WorkloadConfig])` and derives every axis from `placement_group(ws, declared)` (:2108) — the transitive closure of `local` requirement edges over `effective_requirements()`, traversing `Requirement::provides` where present and resolving by ident against `cfg.workloads` (.yah/infra/workloads/) otherwise, mesh-identity first and workload name second. Capacity is the SUM of the members' `memory_request_mb()` / `resources.cpu_millis` (saturating). Only `local` binds: `prefer-local` and `anywhere` (which every legacy `depends_on` folds into) are skipped, so a spec without local edges has a group of exactly itself and its axes are bit-identical to the pre-R860 derivation.")
2304/// @yah:handoff("REPEL BECAME A SET. `RequiredSpec::repel_archetype: Option<LifecycleArchetype>` is now `repel_archetypes: Vec<LifecycleArchetype>` (config.rs:3878), the union over group members; `matches` (:3971) rejects a node carrying `no-<taint_key()>` for ANY of them, `describe` emits one `not-tainted(...)` part per archetype, `is_unconstrained` tests `is_empty()`. The field is `#[serde(skip)]`, so no wire or schema drift, and grep over app/ crates/ oss/ xtask/ finds no other referent of the old name and no `RequiredSpec { .. }` literal outside config.rs — the rename is contained. `admit_workload` / `admit_workload_candidates` / `admit_workload_in_group` signatures are unchanged; all three now pass `&self.workloads`.")
2305/// @yah:handoff("CYCLE GUARD, AND THE BUG IT TOOK TO GET RIGHT. The walker keeps TWO visited lists: `in_group` (member mesh identities) and `expanded` (requirement idents already resolved). The first version used one list and was silently wrong in the common case — a requirement's ident IS its provider's mesh identity, so marking the ident before resolving made every provider look already-present and `placement_group` returned a group of one. Five of the new tests caught it. If you refactor this, keep the two questions separate.")
2306/// @yah:handoff("ELECT_NODE NEEDS NO CHANGE FOR THIS TICKET — read it (app/yah/cli/src/yubaba_client.rs:235-268). It calls `admit_workload_candidates`, so it now receives a pool already filtered to nodes that can host the WHOLE group, then probes for liveness within it. That is correct for T4 because only the requirer is deployed today. It becomes load-bearing at R860-T6: `supply = \"self\"` provisioning MUST reuse the node URL `elect_node` returned for the requirer and must not re-elect per member — the probe is liveness-sensitive, so a second election can legally return a different member of the same pool and split the group across two nodes.")
2307/// @yah:handoff("DECISIONS THE BRIEF DID NOT COVER, all recorded in doc comments at the site. (1) `mesh_tags` are UNIONED over the group — the axis is already a superset/AND check, so a node that cannot host one member cannot host the group; zero regression risk since nothing in the tree declares `requires` yet. (2) `nodes` (the R833-F8 operator pin) stays REQUIRER-ONLY: it is a membership list, so intersecting two members' pins can yield an empty vec, which the axis reads as no-constraint — the exact inverse of the conflict. (3) `requires_taint` is a single Option: the requirer's wins, else the first member declaring one. Two members demanding DIFFERENT taints is not representable and would be an unplaceable group; widening that axis to a set is a follow-up if a real case appears. (4) An unresolvable `local` ident is SKIPPED, not an error — admission is a pure function of the declared inventory and must not start refusing deploys over a provider a later ticket declares; the cost is that its request does not count toward the floor, which is the exposure `depends_on` has always had.")
2308/// @yah:handoff("DRAINABILITY: placement half landed, node half deliberately NOT touched. `group_is_drainable(members)` (config.rs:2160) is the set-valued predicate W338 §Placement consequences 2 asks for — false as soon as any member is an Appliance — and the `no-appliance` repulsion that follows from it is enforced through `repel_archetypes`. The node-side loop `drain_workloads` (oss/yubaba/crates/yubaba/src/lib.rs, the R572-F4 archetype_registry skip) still decides per workload and knows nothing about requirement edges, so a Server bound to an Appliance by a `local` edge would still be drained alone. Not fixed here for two reasons: that file has three sessions live in it (the brief named them), and the fix needs group edges plumbed to the node process, which is R860-T6's rail rather than a local edit. `yubaba` already depends on `cloud`, so the predicate is directly callable from there when that plumbing exists.")
2309/// @yah:verify("BASELINE recorded before editing, tree anchor 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2: `cargo test -p yah-cloud --lib` (from oss/yubaba) = 1081 passed, 0 failed, 4 ignored, exit 0. AFTER: 1090 passed, 0 failed, 4 ignored, exit 0 — +9, exactly the nine tests added. `cargo check -p yah-cloud --all-targets` exit 0, and `cargo check -p yubaba --all-targets` exit 0 as well (yubaba consumes `cloud`, so it is where the `repel_archetypes` rename would have surfaced). Every exit code echoed explicitly, never inferred from an empty grep.")
2310/// @yah:verify("NEW TESTS (config.rs `mod tests`, R860-T4 section at the end): a_local_edge_binds_the_provider_into_the_placement_group; prefer_local_and_anywhere_edges_do_not_bind_the_group (covers a legacy `depends_on` too); the_group_is_the_transitive_closure_and_traverses_inline_provides; an_ident_cycle_closes_the_group_instead_of_looping_forever; an_unresolvable_local_ident_is_skipped_rather_than_refused; the_capacity_floor_is_the_sum_of_the_group_not_the_requirer_alone (a 300 MiB node refuses two 256 MiB members and the error names memory_mb>=512; a 512 MiB node admits); a_server_requiring_an_appliance_locally_is_repelled_by_no_appliance (same requirer alone still lands on the tainted Pi, so the repulsion provably comes from the edge); a_group_containing_an_appliance_is_not_drainable; a_spec_with_no_local_edges_admits_exactly_as_it_did_before.")
2311/// @yah:gotcha("The camp's `yah build run` rail killed three consecutive verification runs against the shared oss/yubaba/target dir: each ended with only `Blocking waiting for file lock on build directory` in the log and no exit code, after 121s / 720s. The green result above was obtained with `CARGO_TARGET_DIR=/tmp/r860t4-target`, which sidesteps the contended lock at the cost of one cold dep build. Worth reaching for directly when the yubaba target dir is busy rather than burning three cycles discovering it.")
2312/// @yah:handoff("Tree anchor at handoff: 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2 — the shared tree as I left it. Diff against it (`git diff 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2..HEAD`) to see what landed under you, and quote this SHA rather than 'HEAD' in any revert/restore instruction.")
2313/// @yah:next("R860-T6 (supply = \"self\"): deploy the group's non-requirer members onto the node `elect_node` already returned for the requirer — do NOT re-elect per member, or a liveness probe can split the group across two nodes. `placement_group` (config.rs:2108) hands you the member specs in traversal order, requirer first.")
2314/// @yah:next("Node-side drain is still per-workload: teach `drain_workloads` (oss/yubaba/crates/yubaba/src/lib.rs) to consult `cloud::config::group_is_drainable` over the requesting workload's placement group once R860-T6 plumbs group membership to the node. Left untouched here on purpose — three sessions were live in that file.")
2315/// @yah:handoff("LEADER RE-VERIFIED (session:69b18855, independent of the courier's self-report). `cargo test -p yah-cloud --lib` from oss/yubaba: 1090 passed / 0 failed / 4 ignored, exit 0, against the courier's recorded 1081/0/4 baseline — +9 = exactly its new tests. Confirmed by content in config.rs: `placement_group` :2120 with the `req.locality != Locality::Local` guard at :2136 (so `prefer-local` and `anywhere` correctly do NOT bind), `group_is_drainable` :2172, and `RequiredSpec::repel_archetype: Option&lt;_&gt;` widened to `repel_archetypes: Vec&lt;_&gt;` at :3890 with the union built at :2039-2050 and enforced at :4004/:4044. The repel rename is `#[serde(skip)]`, so no wire or schema drift.")
2316/// @yah:handoff("Tree anchor at handoff: 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2 — the shared tree as I left it. Diff against it (`git diff 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2..HEAD`) to see what landed under you, and quote this SHA rather than 'HEAD' in any revert/restore instruction.")
2317/// @yah:verify("cargo test -p yah-cloud --lib (from oss/yubaba): 1090 passed / 0 failed / 4 ignored, exit 0, vs a 1081/0/4 baseline. Exit codes echoed explicitly throughout rather than inferred from an empty grep — the trap that cost R860-T1 three misses.")
2318/// @yah:gotcha("CORRECTION FROM R860-T6, and the leader propagated the error so it is worth naming: this ticket's handoff asserted \\\"`yubaba` already depends on `cloud`, so the predicate is directly callable from there\\\". THAT IS WRONG. `cloud` is a DEV-dependency of yubaba only — oss/yubaba/crates/yubaba/Cargo.toml:150-152, under the comment \\\"Integration test harness\\\" — and cloud's own Cargo.toml records that the runtime yubaba→cloud edge was DELIBERATELY avoided from R374-F3 onward. The leader repeated the claim verbatim in R860-T6's dispatch brief; T6's courier checked it against the manifest instead of trusting it, which is the only reason it did not become a runtime dependency inversion. Resolution: `group_is_drainable`'s body moved down to `workload_spec::group_is_drainable` (workload-spec/src/lib.rs:2365), the shared home both crates already depend on, and `cloud::config::group_is_drainable` (config.rs:2240) now delegates to it keeping its signature. Verified after the move: yah-cloud still 1093/0/4, yah-workload-spec 171+98/0.")
2319/// @yah:handoff("Tree anchor at handoff: 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2 — the shared tree as I left it. Diff against it (`git diff 0a85122cdb33dbf97ebc04b84e07d9cfc049c0b2..HEAD`) to see what landed under you, and quote this SHA rather than 'HEAD' in any revert/restore instruction.")
2320/// @yah:verify("RE-VERIFIED AT HEAD 00ee20d1 (session:aa5e882d, 2026-09-05). `cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib` = 1141 passed / 0 failed / 4 ignored, exit 0 (was 1093 at the first leader's check, 1110 at the second; the deltas are peers' tests). Group placement confirmed by content in oss/yubaba/crates/cloud/src/config.rs: `placement_group` derivation at :2073/:2108, `repel_archetypes: Vec&lt;LifecycleArchetype&gt;` at :3878. NOTE FOR ANYONE RE-RUNNING THIS: `cargo test -p yah-cloud --lib` from the repo root FAILS with \"package `yah-cloud` cannot be tested because it requires dev-dependencies and is not a member of the workspace\" — yah-cloud lives in the oss/yubaba workspace, so the invocation needs `--manifest-path oss/yubaba/Cargo.toml`.")
2321fn admission_spec(ws: &WorkloadSpec, declared: &[WorkloadConfig]) -> Result<RequiredSpec> {
2322    let group = placement_group(ws, declared);
2323
2324    // R894-F1: trust is a declared axis, and the substrate floor it implies is
2325    // a REFUSAL here — not a tag, not a downgrade, not a warning.
2326    //
2327    // Every other axis in this function narrows the candidate set: "which nodes
2328    // can host this". Trust is not that question. A `yah.trust = untrusted`
2329    // spec asking for `yah.exec = native` is not unplaceable — it is
2330    // *incoherent*, and there is no fleet on which it becomes coherent. Making
2331    // it a mesh tag would render it as "no node admits this", which reads like
2332    // a capacity problem and sends the operator to look at machines.
2333    //
2334    // It mirrors `wants_microvm`'s no-silent-downgrade semantics from the other
2335    // direction: kamaji refuses to run a microVM-marked spec as a container
2336    // because that delivers less isolation than was asked for; admission
2337    // refuses to place an untrusted spec on a weaker substrate for exactly the
2338    // same reason, one layer earlier, where the operator can still read why.
2339    //
2340    // Checked per member over the whole `placement_group`, not just `ws`.
2341    // R860-T4 made a `local` edge co-place its provider, so an untrusted member
2342    // reaching a node is reaching it whether or not the requirer is the
2343    // untrusted one — and each member carries its own pair, so the check is
2344    // per-member rather than over a group-wide maximum.
2345    check_trust_substrate(&group)?;
2346
2347    // Capacity is the group's demand, not the requirer's (W338 §Placement
2348    // consequences 1). Saturating rather than wrapping: an absurd declared
2349    // request must read as "nothing is big enough", never as a small number.
2350    //
2351    // `memory_request_mb()` and NOT `resources.memory_mb`: the latter is a
2352    // cgroup ceiling, and reading a ceiling as a floor made `for_forge`'s
2353    // deliberately-roomy 32 GiB limit mean "only place me on a 32 GiB node".
2354    // That excluded every build-worker in the fleet but one. The accessor falls
2355    // back to `resources.memory_mb` when no request is declared, so specs that
2356    // never set one are admitted exactly as before.
2357    let mut memory_mb: u32 = 0;
2358    let mut cpu_millis: u32 = 0;
2359    // R572-F5 taint repulsion, unioned over the group (W338 §Placement
2360    // consequences 2): a group is non-drainable — and `no-appliance`-repelled —
2361    // if *any* member is an Appliance, even when the requirer is a Server.
2362    //
2363    // R876-B7 inverted the sense. Repulsion is now unconditional in `matches`,
2364    // so what this loop collects is still the group's archetype union, but it is
2365    // converted below into the complementary TOLERATION set. Same predicate,
2366    // stated from the other side.
2367    let mut group_archetypes: Vec<LifecycleArchetype> = Vec::new();
2368    // Mesh tags are already AND-ed (a machine must be a superset), so unioning
2369    // them over the group is the same predicate applied to every member: a node
2370    // that cannot host one member cannot host the group.
2371    let mut mesh_tags = node_selector_mesh_tags(ws);
2372
2373    for member in &group {
2374        memory_mb = memory_mb.saturating_add(member.memory_request_mb());
2375        cpu_millis = cpu_millis.saturating_add(member.resources.cpu_millis);
2376        let arch = member.effective_archetype();
2377        if !group_archetypes.contains(&arch) {
2378            group_archetypes.push(arch);
2379        }
2380        for tag in node_selector_mesh_tags(member) {
2381            if !mesh_tags.contains(&tag) {
2382                mesh_tags.push(tag);
2383            }
2384        }
2385    }
2386
2387    // R860-T5 / W338 §Placement consequences 3: per-node native-exec
2388    // capability. Computed over the group for the same reason every other axis
2389    // is — a `local` edge to a native provider makes the *requirer* unplaceable
2390    // on a node without the backend, even when the requirer is an ordinary
2391    // container workload. This is the `supply = "self"` precondition W338 names:
2392    // a self-supplied native provider has to be placeable where its requirer
2393    // lands, and until now nothing upstream could see whether it was.
2394    //
2395    // Appended to `mesh_tags` rather than given its own field: the axis is
2396    // already an AND-ed superset check against `machine.mesh_tags`, `describe`
2397    // already renders it, and `RequiredSpec` needs no new shape. See
2398    // [`NATIVE_EXEC_MESH_TAG`] for why a tag and not a taint.
2399    if group.iter().any(WorkloadSpec::wants_native_exec)
2400        && !mesh_tags.iter().any(|t| t == NATIVE_EXEC_MESH_TAG)
2401    {
2402        mesh_tags.push(NATIVE_EXEC_MESH_TAG.to_string());
2403    }
2404
2405    // R894-F1 / R860-T5's deferred second half: the identical axis for the
2406    // microVM backend. Same `if`, same group-wide reasoning, same reason it is a
2407    // tag and not a taint — see [`MICROVM_MESH_TAG`] for why the precondition
2408    // R860-T5 was waiting on (a node that can actually boot a guest) is now met.
2409    //
2410    // This is what makes the trust floor above land somewhere real: without it,
2411    // an untrusted workload passes the coherence check and is then placed on a
2412    // node whose kamaji has no microVM backend, which refuses at dispatch.
2413    if group.iter().any(WorkloadSpec::wants_microvm)
2414        && !mesh_tags.iter().any(|t| t == MICROVM_MESH_TAG)
2415    {
2416        mesh_tags.push(MICROVM_MESH_TAG.to_string());
2417    }
2418
2419    Ok(RequiredSpec {
2420        mesh_tags,
2421        // R833-F8: imperative node pin. Derived here alongside the inferred
2422        // mesh tags rather than short-circuiting the resolver, so a pinned
2423        // workload is still checked against capacity and taints.
2424        //
2425        // Requirer-only on purpose: the pin is what the operator typed on
2426        // *this* deploy, and `nodes` is a membership list, so intersecting two
2427        // members' pins could yield an empty vec — which this axis reads as "no
2428        // constraint", i.e. the exact opposite of the conflict it represents.
2429        nodes: node_selector_node(ws).into_iter().collect(),
2430        memory_mb,
2431        cpu_millis,
2432        // R876-B7: the archetype union, restated as tolerations — every
2433        // repelling key that is NOT this group's own class. A Server group
2434        // tolerates `no-appliance` and `no-job` and is still blocked by
2435        // `no-server`, which is precisely what the pre-B7 `repel_archetypes`
2436        // axis computed. That equivalence is the migration: the `admit_workload`
2437        // path's placement answers are unchanged for every fleet machine, while
2438        // the mirror-declared path — which could never populate an archetype set
2439        // and so read no taints at all — becomes repel-by-default.
2440        //
2441        // Derived from `LifecycleArchetype::ALL` rather than a literal list, so
2442        // a fourth archetype is tolerated by unrelated groups automatically,
2443        // exactly as `taint_effect` already derives the repulsion half.
2444        tolerates: LifecycleArchetype::ALL
2445            .into_iter()
2446            .filter(|a| !group_archetypes.contains(a))
2447            .map(|a| format!("no-{}", a.taint_key()))
2448            .collect(),
2449        // R572-F5: taint affinity from the requires-taint annotation. The
2450        // requirer's wins; otherwise the first member that declares one, since
2451        // the group shares a node and this axis holds a single key. Two members
2452        // demanding *different* taints is not representable here and would be
2453        // an unplaceable group anyway — see the R860-T4 handoff.
2454        requires_taint: group
2455            .iter()
2456            .find_map(|m| m.requires_taint().map(str::to_owned)),
2457        ..Default::default()
2458    })
2459}
2460
2461/// Refuse any group member whose declared trust exceeds what its requested
2462/// [`workload_spec::ExecSubstrate`] provides (R894-F1).
2463///
2464/// The rule in one line: **a caller may request a stricter substrate than its
2465/// trust level requires, never a looser one.** `Trusted` floors at
2466/// [`workload_spec::ExecSubstrate::Native`] — the bottom of the ordering, i.e. no constraint,
2467/// which is what every workload in the fleet has today — and `Untrusted` floors
2468/// at [`workload_spec::ExecSubstrate::MicroVm`], which is the operator's 2026-09-11 call that
2469/// untrusted code never shares a kernel with the fleet.
2470///
2471/// A malformed [`workload_spec::TRUST_ANNOTATION`] is refused too, rather than
2472/// resolving to either side. See [`workload_spec::TrustDeclError`] for why
2473/// guessing in either direction is worse than a named refusal.
2474///
2475/// # Why here and not in `RequiredSpec::matches`
2476///
2477/// `matches` answers "can this node host this group". Trust coherence is a
2478/// property of the *spec alone* — no node makes an untrusted-and-native spec
2479/// legal — so it belongs on the path in, where it can fail with its own
2480/// sentence. Putting it in the predicate would spend a fleet scan to conclude
2481/// "no candidates", which names the wrong thing.
2482///
2483/// It is sited inside [`admission_spec`] and not in each `admit_*` method for
2484/// the reason that function's own docs give: `admission_spec` is the one place
2485/// the three admission entry points share, so a fourth entry point cannot be
2486/// added that skips this. Returning `Result` from it is what makes that
2487/// structural rather than a convention.
2488fn check_trust_substrate(group: &[WorkloadSpec]) -> Result<()> {
2489    for member in group {
2490        let trust = member.trust().map_err(|e| {
2491            anyhow::anyhow!(
2492                "workload '{}' has an unreadable trust declaration: {e}",
2493                member.name
2494            )
2495        })?;
2496        let floor = trust.minimum_substrate();
2497        let requested = member.exec_substrate();
2498        if requested < floor {
2499            bail!(
2500                "workload '{}' declares {}={} but requests the {} substrate, which is weaker than \
2501                 the {} minimum that trust level requires — untrusted code does not share a kernel \
2502                 with the fleet, so set {}={} on this spec (a stricter substrate is always allowed, \
2503                 a weaker one never is)",
2504                member.name,
2505                workload_spec::TRUST_ANNOTATION,
2506                trust.as_str(),
2507                requested.as_str(),
2508                floor.as_str(),
2509                workload_spec::NATIVE_EXEC_ANNOTATION,
2510                floor.annotation_value().unwrap_or("<container>"),
2511            );
2512        }
2513    }
2514    Ok(())
2515}
2516
2517/// The workloads that must be placed together with `ws`: the transitive closure
2518/// of `local` requirement edges over [`WorkloadSpec::effective_requirements`],
2519/// starting at the requirer (R860-T4 / W338 §"Each member keeps its own mesh
2520/// identity").
2521///
2522/// **Only `local` binds.** `prefer-local` explicitly "never blocks placement"
2523/// (W338's locality table) and `anywhere` is an ordinary service dependency —
2524/// treating either as a co-scheduling constraint would turn every `depends_on`
2525/// in the tree into one, since the legacy field folds in as `anywhere` + `wait`.
2526///
2527/// A group is **not** a new addressable object: every member keeps its own mesh
2528/// identity, spec and healthcheck (W338). This function returns the members'
2529/// specs so admission can take the sum / union over them, and nothing here
2530/// deploys, provisions or tears anything down — `supply = "self"` provisioning
2531/// is R860-T6 and per-node native-exec capability is R860-T5.
2532///
2533/// Two ways a member is reached, in this order:
2534/// - [`Requirement::provides`], the inline spec a `supply = "self"` requirement
2535///   carries;
2536/// - otherwise an ident lookup against `declared` (`.yah/infra/workloads/`),
2537///   matched on mesh identity first and on workload name second, because those
2538///   coincide for every spec in the tree today but the requirement is written in
2539///   the mesh-identity currency.
2540///
2541/// An ident that resolves to neither is **skipped**, not an error: admission is
2542/// a pure function of the declared inventory and must not start failing deploys
2543/// over a provider that a not-yet-written ticket will declare. The cost is that
2544/// its request does not count toward the floor, which is the same exposure
2545/// `depends_on` has always had.
2546///
2547/// **Cycle-guarded.** `validate::check_requires` bounds `provides` *nesting* to
2548/// depth 1 but nothing stops two separately-declared specs from requiring each
2549/// other, and this closure would otherwise not terminate. Each requirement ident
2550/// is resolved at most once and each member joins the group at most once, so a
2551/// cycle simply closes the group.
2552pub fn placement_group(ws: &WorkloadSpec, declared: &[WorkloadConfig]) -> Vec<WorkloadSpec> {
2553    let mut members = vec![ws.clone()];
2554    // Two separate visited sets, because the two questions differ: `in_group`
2555    // stops a workload being added twice, `expanded` stops an ident being
2556    // resolved twice. Folding them into one list makes the ident of a member
2557    // already in the group indistinguishable from the member itself — and since
2558    // a requirement's ident *is* its provider's mesh identity, that reads every
2559    // provider as already-present and silently returns a group of one.
2560    let mut in_group: Vec<String> = vec![group_key(ws)];
2561    let mut expanded: Vec<String> = Vec::new();
2562    let mut next = 0;
2563
2564    while next < members.len() {
2565        let requirements = members[next].effective_requirements();
2566        next += 1;
2567        for req in requirements {
2568            if req.locality != Locality::Local {
2569                continue;
2570            }
2571            if expanded.contains(&req.ident.0) {
2572                continue;
2573            }
2574            expanded.push(req.ident.0.clone());
2575
2576            let provider = match req.provides.as_deref() {
2577                Some(spec) => spec.clone(),
2578                None => match resolve_requirement_ident(&req.ident, declared) {
2579                    Some(spec) => spec,
2580                    None => continue,
2581                },
2582            };
2583            let key = group_key(&provider);
2584            if in_group.contains(&key) {
2585                continue;
2586            }
2587            in_group.push(key);
2588            members.push(provider);
2589        }
2590    }
2591
2592    members
2593}
2594
2595/// Whether a placement group may be drained off its node (W338 §Placement
2596/// consequences 2): false as soon as **any** member is an Appliance.
2597///
2598/// The set-valued form of the per-workload check the node itself makes in
2599/// `drain_workloads` (`oss/yubaba/crates/yubaba/src/lib.rs`), which skips an
2600/// Appliance by its own archetype and knows nothing about requirement edges. A
2601/// `Server` bound to an Appliance by a `local` edge has to move with it or not
2602/// at all, so draining it alone breaks the group the same way placing it alone
2603/// would.
2604///
2605/// R860-T6 moved the body to [`workload_spec::group_is_drainable`] and left this
2606/// signature untouched. The node's `drain_workloads` needs the identical
2607/// predicate, and yubaba has no runtime dependency on this crate by design
2608/// (R374-F3) — so the one implementation now lives in the crate both sides
2609/// already depend on, rather than being copied into the second caller.
2610pub fn group_is_drainable(members: &[WorkloadSpec]) -> bool {
2611    workload_spec::group_is_drainable(members)
2612}
2613
2614/// Identity a placement-group member is deduplicated by — its mesh identity,
2615/// which is the currency [`Requirement::ident`] is written in.
2616fn group_key(ws: &WorkloadSpec) -> String {
2617    ws.expose.mesh.identity.0.clone()
2618}
2619
2620/// Resolve a requirement's ident to a separately-declared spec: mesh identity
2621/// first, workload file name second.
2622fn resolve_requirement_ident(
2623    ident: &workload_spec::MeshIdent,
2624    declared: &[WorkloadConfig],
2625) -> Option<WorkloadSpec> {
2626    declared
2627        .iter()
2628        .find(|w| w.spec.expose.mesh.identity == *ident)
2629        .or_else(|| declared.iter().find(|w| w.spec.name == ident.0))
2630        .map(|w| w.spec.clone())
2631}
2632
2633/// The mesh tag a node declares to advertise that its kamaji can run **native**
2634/// (fork+exec) workloads — R860-T5 / W338 §"Placement consequences" 3.
2635///
2636/// A workload marked `yah.exec = native` ([`WorkloadSpec::wants_native_exec`])
2637/// is not containerized: kamaji fork+execs it on the node's own userland. That
2638/// backend only exists when the node's kamaji was **built** with the
2639/// `native-exec` cargo feature and **started** with `--native-exec-dir`
2640/// (`oss/kamaji/crates/kamaji-bin/src/main.rs`). Both are node-local startup
2641/// decisions, invisible to everything upstream — so before this tag, placement
2642/// happily elected a node whose kamaji then refused the deploy with
2643/// `BackendRefused: ... no native backend is available (native backend not
2644/// configured — start kamaji with --native-exec-dir)`. That is exactly how the
2645/// mesh lost its coordination server for 25 hours on 2026-09-03 (R858: raft
2646/// leadership moved headscale, a native workload, to `us-south-001`, which has
2647/// no such kamaji). [`admission_spec`] now requires this tag whenever any
2648/// placement-group member is native, which turns that dispatch-time surprise
2649/// into a placement precondition.
2650///
2651/// # Why a mesh tag and not a taint
2652///
2653/// The two vocabularies on [`MachineConfig`] mean opposite things. `mesh_tags`
2654/// are **positive capability** matched as a superset — "this node CAN" — which
2655/// is precisely the claim being made, and an extra tag on a machine can only
2656/// ever make it match *more* requirement sets, so declaring it is regression-
2657/// free. `taints` are **repulsion** — "keep this class off" — and would have to
2658/// be inverted (`no-native-exec` on every node lacking the backend, i.e. the
2659/// declaration burden falls on the majority) *and* taught to
2660/// [`taint_effect`], or [`crate::validate::check_inert_taints`] would correctly
2661/// lint the key dead.
2662///
2663/// # The `cap:` namespace
2664///
2665/// New here. The live prefixes are `tag:` (role — `tag:build-worker`,
2666/// `tag:qed`, `tag:cloud-runner`), `arch:` and `os:` (facts about the silicon
2667/// and userland), and `tier:` is reserved for the environment axis (R763, see
2668/// [`crate::validate::check_retired_arch_tags`]). A *capability the daemon was
2669/// configured with* is none of those: it is not a role an operator assigns and
2670/// not a property of the hardware, it is a fact about how kamaji was started,
2671/// and it changes when the node is rolled. Nothing validates tag prefixes, so
2672/// this costs no wiring.
2673///
2674/// # Fails closed
2675///
2676/// A node that does not declare it is not a candidate. An undeclared fleet
2677/// therefore reports "no node admits" at election time rather than dispatching
2678/// to a node that will refuse — the refusal moves earlier and names the
2679/// constraint, which is the whole point. Declared today (from readings recorded
2680/// in-repo, not inferred) on `us-west-001` and `us-west-003`; see those
2681/// machines' TOMLs for the evidence and the date.
2682///
2683/// # What it does NOT cover — the reading that looks like an inversion
2684///
2685/// This tag gates exactly one backend: [`WorkloadSpec::wants_native_exec`] on a
2686/// `Workload::Container` spec, whose only two in-tree producers are
2687/// `yubaba::headscale_appliance::appliance_spec` and
2688/// `velveteen_exec::remote::mark_native_exec` (forge build steps).
2689///
2690/// kamaji has **other** ways to fork a process onto the host userland, and none
2691/// of them are `yah.exec = native`: a `Workload::MesofactStatic` carrying a
2692/// `serve_bundle` is served by `BundleBackend` (cargo feature `bundle-serving`
2693/// + `--bundle-cache-dir` + `--bundle-origin`), and `Workload::TenantPassway`
2694/// by `kamaji::jit::JitRuntime` (cargo feature `tenant-passway` +
2695/// `--tenant-passway-dir`). Those are separate node-local startup decisions.
2696/// The bundle one is now modelled — see [`BUNDLE_SERVING_MESH_TAG`], R885-T14.
2697/// The JIT one deliberately is **not**; that const's docs say why.
2698///
2699/// The practical consequence, because it has already misled one reader: a node
2700/// can run several kamaji-forked host processes and correctly carry no
2701/// `cap:native-exec`. On 2026-09-11 `us-east-001` ran four (two bundle servers,
2702/// a revalidate receiver, an almanac feed) with no such tag while `us-west-001`
2703/// carried the tag and ran none, which reads as an inversion and is not one:
2704/// none of those four is a native-exec workload, and the tag never claimed
2705/// them.
2706pub const NATIVE_EXEC_MESH_TAG: &str = "cap:native-exec";
2707
2708/// The mesh tag a node declares to advertise that its kamaji can **serve W272
2709/// bundles** — R885-T14, the same axis [`NATIVE_EXEC_MESH_TAG`] models for the
2710/// native-exec backend.
2711///
2712/// A `Workload::MesofactStatic` carrying a `serve_bundle` is materialized and
2713/// supervised by `kamaji_bin::BundleBackend`, which only exists when the node's
2714/// kamaji was **built** with the `bundle-serving` cargo feature and **started**
2715/// with `--bundle-cache-dir` *and* `--bundle-origin` (or `$KAMAJI_BUNDLE_ORIGIN`)
2716/// — `attach_bundle_backend` in `oss/kamaji/crates/kamaji-bin/src/main.rs`
2717/// returns the context untouched without the cache dir, logging
2718/// "Deploy { MesofactStatic + serve_bundle } will refuse with BackendRefused".
2719/// All three are node-local startup decisions, invisible to everything upstream.
2720///
2721/// # The gap this closes
2722///
2723/// Bundle placement does not go through [`admission_spec`] at all — a bundle is
2724/// placed by `reconciler::mesofact_bundle::resolve_bundle_machines`, off the
2725/// mirror's `providers.bundle` declaration (`machines = [...]` or `required =
2726/// { … }`), which the operator writes and which knows nothing about backends.
2727/// So before this tag, a mirror whose constraint matched a node without the
2728/// bundle backend deployed there and was refused at dispatch, exactly the way
2729/// R858 lost headscale for 25 hours on the native axis. It stayed invisible
2730/// because one node (`us-east-001`) serves every bundle in the fleet — the
2731/// condition under which an unmodelled constraint costs nothing right up until
2732/// the second node appears.
2733///
2734/// Both arms of `resolve_bundle_machines` enforce it, including the literal
2735/// `machines = [...]` pin: an operator naming a node by hand is making exactly
2736/// the claim this tag exists to check, and a pin is where the mistake is most
2737/// likely, not least.
2738///
2739/// # Fails closed, like the native tag
2740///
2741/// A node that does not declare it cannot serve a bundle. Declared today on
2742/// `us-east-001` only; see that machine's TOML for the evidence and the date.
2743///
2744/// # Why there is no `cap:tenant-passway` beside this
2745///
2746/// Checked rather than assumed, and it is a real asymmetry.
2747/// `Workload::TenantPassway` has **no placement decision to gate**:
2748/// `yubaba::tenant_passway::reconcile_once` runs *inside the node's own yubaba*
2749/// and drives *that node's own* kamaji over the local UDS. Which node arms a
2750/// domain is decided by which node was started with
2751/// `YUBABA_TENANT_PASSWAY_STATE_DIR`, not by any selector — so a capability tag
2752/// would have no consumer, and R852-B4 records that the tier is enabled on no
2753/// fleet machine today. Declaring it now would be the same wrong fact
2754/// [`NATIVE_EXEC_MESH_TAG`]'s notes refuse to state for `cap:microvm`. Model it
2755/// when a *selector* exists to read it.
2756///
2757/// `Workload::Almanac` needs no tag either, and the reason is stronger: kamaji
2758/// refuses it outright (`server.rs`, "almanac and static-asset live in yubaba's
2759/// reconcilers"), so it is never node-placed. An "almanac feed" observed
2760/// forked on `us-east-001` is a bundle-staged feed fetcher running under
2761/// `BundleBackend`, covered by *this* tag — not a `Workload::Almanac`.
2762pub const BUNDLE_SERVING_MESH_TAG: &str = "cap:bundle-serving";
2763
2764/// The mesh tag a node declares to advertise that its kamaji can **boot a
2765/// Firecracker microVM** — the third instance of the axis
2766/// [`NATIVE_EXEC_MESH_TAG`] and [`BUNDLE_SERVING_MESH_TAG`] model, and the one
2767/// R860-T5 deliberately left open.
2768///
2769/// # Why it was deferred, and why it is no longer
2770///
2771/// R860-T5's `@yah:cleanup` says this tag is "one line from done in the same
2772/// `if` in [`admission_spec`]" and refuses to take it, because **no node in the
2773/// fleet could host a microVM**: the guest kernel and rootfs were gated on
2774/// R605-F14, and declaring a capability nothing has is asserting a false fact.
2775/// That precondition is met. `us-west-003` has had the backend attached since
2776/// 2026-09-10T23:27Z (its TOML records the drop-in, the journal line and the
2777/// staged guest material), and on 2026-09-11 R605-T24's
2778/// `.yah/qed/microvm-dispatch-smoke.toml` drove a forge through the entire
2779/// chain — qed → velveteen-exec → yubaba admission → kamaji → `MicroVmRuntime`
2780/// — asserting on `/proc/cmdline` tokens a container cannot produce.
2781///
2782/// R894-F1 is what made taking it *necessary* rather than merely available: an
2783/// untrusted workload now has [`workload_spec::ExecSubstrate::MicroVm`] as a hard floor, so
2784/// without this axis every untrusted workload would be admitted onto whichever
2785/// node won the tie-break and refused at dispatch — the exact 25-hour-outage
2786/// shape R858 paid for on the native axis.
2787///
2788/// # Fails closed, and the node-side fact is in a drop-in, not ExecStart
2789///
2790/// A node that does not declare it cannot host a microVM workload. Declared
2791/// today on `us-west-003` only.
2792///
2793/// Reading `ExecStart` **cannot** answer whether a node has this backend, and
2794/// that trap is written into `us-west-003`'s own TOML: the backend is enabled by
2795/// `Environment=KAMAJI_MICROVM_DIR=…` in
2796/// `/etc/systemd/system/kamaji.service.d/10-microvm.conf`, so the unit's
2797/// `ExecStart` carries no `--microvm-dir` while `MicroVmRuntime` constructs
2798/// anyway. The same TOML records that rolling the node to a published version
2799/// reverts the staged guest material — so this tag, like the other two, must be
2800/// re-checked after any roll.
2801pub const MICROVM_MESH_TAG: &str = "cap:microvm";
2802
2803/// Parse the R594 mesh-tag node-selector off a workload's annotations into the
2804/// requested tag set. Absent annotation or empty value ⇒ empty vec ("no
2805/// constraint"). Whitespace around each comma-separated tag is trimmed and
2806/// empty segments are dropped, so `"tag:build-worker, arch:x86"` and
2807/// `"tag:build-worker,arch:x86"` parse identically.
2808pub fn node_selector_mesh_tags(ws: &WorkloadSpec) -> Vec<String> {
2809    ws.annotations
2810        .get(velveteen_exec::remote::NODE_SELECTOR_MESH_TAGS_ANNOTATION)
2811        .map(|v| {
2812            v.split(',')
2813                .map(str::trim)
2814                .filter(|s| !s.is_empty())
2815                .map(String::from)
2816                .collect()
2817        })
2818        .unwrap_or_default()
2819}
2820
2821/// Parse the R833-F8 imperative node-selector off a workload's annotations —
2822/// the single machine `name` the operator pinned the run to
2823/// (`--where=node:us-west-003`). Absent or blank ⇒ `None` ("no constraint"),
2824/// which is every workload built before this axis existed.
2825///
2826/// One node, not a list: the annotation exists to express "run it *there*", and
2827/// a comma-joined set would be a worse spelling of the mesh-tag selector that
2828/// already handles "any of these".
2829pub fn node_selector_node(ws: &WorkloadSpec) -> Option<String> {
2830    ws.annotations
2831        .get(velveteen_exec::remote::NODE_SELECTOR_NODE_ANNOTATION)
2832        .map(|v| v.trim())
2833        .filter(|v| !v.is_empty())
2834        .map(String::from)
2835}
2836
2837/// Load every `.yah/infra/providers/*.toml` into a [`ProviderConfig`] list.
2838/// Missing directory → empty list.
2839fn load_providers(dir: &Path) -> Result<Vec<ProviderConfig>> {
2840    if !dir.exists() {
2841        return Ok(vec![]);
2842    }
2843    let mut items = vec![];
2844    let mut entries: Vec<_> = std::fs::read_dir(dir)
2845        .with_context(|| format!("reading {}", dir.display()))?
2846        .filter_map(|e| e.ok())
2847        .filter(|e| e.path().extension().map_or(false, |x| x == "toml"))
2848        .collect();
2849    entries.sort_by_key(|e| e.file_name());
2850    for entry in entries {
2851        items.push(ProviderConfig::load(&entry.path())?);
2852    }
2853    Ok(items)
2854}
2855
2856/// Map legacy mirror file stems to their canonical tier names.
2857///
2858/// Canonical tiers: `dev` / `pond` / `prod` / `ha`.
2859/// Legacy stems pre-R362: `local` (dev tier), `local-sim` / `sim` (pond tier).
2860/// Legacy stem `cloud` (prod tier) — renamed 2026-09-14: "cloud" named the
2861/// deployment mechanism, not the environment, and every operator-facing
2862/// surface already said "prod" (`yah cloud apply --env prod`, `mirror up ...
2863/// for prod`, the mirror files themselves are `prod.toml`) while only this
2864/// loader's internal key disagreed.
2865/// Both forms are accepted; canonical names are preferred for new files.
2866pub fn canonical_tier(stem: &str) -> &str {
2867    match stem {
2868        "local" => "dev",
2869        "local-sim" | "sim" => "pond",
2870        "cloud" => "prod",
2871        other => other,
2872    }
2873}
2874
2875/// Walk `.yah/services/<svc>/` for every service and its mirrors.
2876/// Missing directory → empty map. Mirror file stems are normalized to canonical
2877/// tier names via [`canonical_tier`] so callers always see `dev/pond/prod/ha`.
2878fn load_services(
2879    dir: &Path,
2880    workspace_root: &Path,
2881) -> Result<BTreeMap<String, ServiceWithMirrors>> {
2882    if !dir.exists() {
2883        return Ok(BTreeMap::new());
2884    }
2885    let mut out = BTreeMap::new();
2886    let mut entries: Vec<_> = std::fs::read_dir(dir)
2887        .with_context(|| format!("reading {}", dir.display()))?
2888        .filter_map(|e| e.ok())
2889        .filter(|e| e.path().is_dir())
2890        .collect();
2891    entries.sort_by_key(|e| e.file_name());
2892
2893    for entry in entries {
2894        let svc_dir = entry.path();
2895        let service_toml = svc_dir.join("service.toml");
2896        if !service_toml.exists() {
2897            // Skip directories without a service.toml — leaves room for
2898            // future siblings (e.g. `secrets/`, `README.md`) without
2899            // triggering false-positive parse errors.
2900            continue;
2901        }
2902        let service = ServiceConfig::load(&service_toml)?;
2903        let mut mirrors = BTreeMap::new();
2904        let mirrors_dir = svc_dir.join("mirrors");
2905        if mirrors_dir.exists() {
2906            let mut menv: Vec<_> = std::fs::read_dir(&mirrors_dir)
2907                .with_context(|| format!("reading {}", mirrors_dir.display()))?
2908                .filter_map(|e| e.ok())
2909                .filter(|e| e.path().extension().map_or(false, |x| x == "toml"))
2910                .collect();
2911            menv.sort_by_key(|e| e.file_name());
2912            for m in menv {
2913                let path = m.path();
2914                let stem = path
2915                    .file_stem()
2916                    .and_then(|s| s.to_str())
2917                    .unwrap_or("")
2918                    .to_string();
2919                let tier = canonical_tier(&stem).to_string();
2920                // Last-write wins if both legacy and canonical forms coexist
2921                // (e.g. local-sim.toml + pond.toml). Sort order ensures the
2922                // canonical file (pond.toml) wins because 'p' > 'l'.
2923                mirrors.insert(tier, MirrorConfig::load(&path)?);
2924            }
2925        }
2926        let mut component_transform_recipes = BTreeMap::new();
2927        for component in &service.components {
2928            if component.kind == "static-asset" {
2929                if let Some(recipe) =
2930                    read_component_transform_recipe(workspace_root, &component.path)
2931                {
2932                    component_transform_recipes.insert(component.id.clone(), recipe);
2933                }
2934            }
2935        }
2936        let passway_machines = mirrors
2937            .iter()
2938            .filter_map(|(env, m)| m.passway_machines().map(|ms| (env.clone(), ms)))
2939            .collect();
2940        out.insert(
2941            service.name.clone(),
2942            ServiceWithMirrors {
2943                service,
2944                mirrors,
2945                component_transform_recipes,
2946                passway_machines,
2947            },
2948        );
2949    }
2950    Ok(out)
2951}
2952
2953/// Read the first transform recipe name from a component's `workload.toml`.
2954/// Returns `None` when the file is absent or has no `[asset.derive.transform]`
2955/// section. Best-effort — parse failures are silently ignored so a malformed
2956/// workload.toml doesn't abort the entire service catalog load.
2957fn read_component_transform_recipe(workspace_root: &Path, component_path: &str) -> Option<String> {
2958    let workload_path = workspace_root.join(component_path).join("workload.toml");
2959    let text = std::fs::read_to_string(&workload_path).ok()?;
2960    let value: toml::Value = toml::from_str(&text).ok()?;
2961    let assets = value.get("asset")?.as_array()?;
2962    for asset in assets {
2963        if let Some(recipe) = asset
2964            .get("derive")
2965            .and_then(|d| d.get("transform"))
2966            .and_then(|t| t.get("recipe"))
2967            .and_then(|r| r.as_str())
2968        {
2969            return Some(recipe.to_string());
2970        }
2971    }
2972    None
2973}
2974
2975/// Load every `.yah/domains/*.toml` into a [`DomainConfig`] map keyed by
2976/// file stem. Missing directory → empty map.
2977pub(crate) fn load_domains(dir: &Path) -> Result<BTreeMap<String, DomainConfig>> {
2978    if !dir.exists() {
2979        return Ok(BTreeMap::new());
2980    }
2981    let mut out = BTreeMap::new();
2982    let mut entries: Vec<_> = std::fs::read_dir(dir)
2983        .with_context(|| format!("reading {}", dir.display()))?
2984        .filter_map(|e| e.ok())
2985        .filter(|e| e.path().extension().map_or(false, |x| x == "toml"))
2986        .collect();
2987    entries.sort_by_key(|e| e.file_name());
2988    for entry in entries {
2989        let path = entry.path();
2990        let stem = path
2991            .file_stem()
2992            .and_then(|s| s.to_str())
2993            .unwrap_or("")
2994            .to_string();
2995        let dom = DomainConfig::load(&path)?;
2996        if dom.name != stem {
2997            anyhow::bail!(
2998                "domains/{}.toml: name = \"{}\" must match the file stem",
2999                stem,
3000                dom.name
3001            );
3002        }
3003        out.insert(dom.name.clone(), dom);
3004    }
3005    Ok(out)
3006}
3007
3008/// Load and shape-validate all `*.toml` files in `dir` as [`WorkloadConfig`].
3009fn load_workloads(dir: std::path::PathBuf) -> Result<Vec<WorkloadConfig>> {
3010    if !dir.exists() {
3011        return Ok(vec![]);
3012    }
3013    let mut items = vec![];
3014    let mut entries: Vec<_> = std::fs::read_dir(&dir)
3015        .with_context(|| format!("reading {}", dir.display()))?
3016        .filter_map(|e| e.ok())
3017        .filter(|e| e.path().extension().map_or(false, |x| x == "toml"))
3018        .collect();
3019    entries.sort_by_key(|e| e.file_name());
3020
3021    for entry in entries {
3022        let path = entry.path();
3023        let path_str = path.display().to_string();
3024        let src =
3025            std::fs::read_to_string(&path).with_context(|| format!("reading {}", path_str))?;
3026        let spec: WorkloadSpec =
3027            toml::from_str(&src).with_context(|| format!("parsing {}", path_str))?;
3028
3029        // R892-B1: refuse a file whose keys the parser silently threw away.
3030        refuse_dropped_keys(&src, &spec, &path_str)?;
3031
3032        // Shape-validate before accepting into the loaded config.
3033        validate::shape(&spec)
3034            .map_err(|e| anyhow::anyhow!("workload {} failed shape validation: {e}", path_str))?;
3035
3036        items.push(WorkloadConfig { spec });
3037    }
3038    Ok(items)
3039}
3040
3041/// Refuse a workload file that declares keys the parser did not keep (R892-B1).
3042///
3043/// `WorkloadSpec` deliberately does **not** carry `deny_unknown_fields`, and
3044/// must not: the JSON leg of the deploy wire relies on an un-rolled node
3045/// ignoring a field it has never heard of, which is what lets a fleet cross a
3046/// schema change one node at a time. That forgiveness is right on the wire and
3047/// wrong in a hand-authored file — there, an ignored key is an operator's
3048/// declared intent evaporating between parse and serialise, with no diagnostic.
3049///
3050/// On 2026-09-11 that cost a production outage: `[resources]
3051/// ephemeral_storage_mb = 256` in noisetable's `noisetable-account.toml` had
3052/// been deleted from `ResourceLimits` by R885-T6, so the CLI read the file, drop
3053/// the value, and sent a spec the (older) node could not parse — after it had
3054/// destroyed the incumbent. The file said the right thing the whole time.
3055///
3056/// The check is a round trip rather than a key whitelist, so it needs no list to
3057/// maintain and catches every renamed, removed or misspelled key at once: parse
3058/// the file, re-serialise the parsed spec, and report any key the source
3059/// declared that the re-serialisation does not carry. Value *representation* may
3060/// legitimately change across that trip (an enum canonicalising its spelling),
3061/// so only missing KEYS are reported, never differing values.
3062fn refuse_dropped_keys(src: &str, spec: &WorkloadSpec, path_str: &str) -> Result<()> {
3063    let declared: toml::Value = match toml::from_str(src) {
3064        Ok(v) => v,
3065        // Unreachable: the caller just parsed this same text into a typed spec.
3066        Err(_) => return Ok(()),
3067    };
3068    let kept = match toml::Value::try_from(spec) {
3069        Ok(v) => v,
3070        // A spec that cannot be re-serialised is a bug in the schema, not in the
3071        // operator's file — say so rather than blaming their config, and let the
3072        // load proceed exactly as it did before this check existed.
3073        Err(e) => {
3074            eprintln!(
3075                "warning: {path_str} could not be checked for silently-dropped keys \
3076                 (re-serialising the parsed spec failed: {e})"
3077            );
3078            return Ok(());
3079        }
3080    };
3081
3082    let mut dropped = Vec::new();
3083    collect_dropped_keys(&declared, &kept, "", &mut dropped);
3084
3085    // R896-B5: a key whose field was deleted as inert is ignored, not refused —
3086    // otherwise every field deletion forces a same-day sweep of every camp's
3087    // committed TOML. Say so, so the dead key still gets cleaned up eventually.
3088    dropped.retain(|path| {
3089        let Some(retired) = workload_spec::RETIRED_KEYS.iter().find(|r| r.path == path) else {
3090            return true;
3091        };
3092        eprintln!(
3093            "warning: {path_str} declares `{path}`, retired by {} and ignored; delete it",
3094            retired.retired_by
3095        );
3096        false
3097    });
3098    if dropped.is_empty() {
3099        return Ok(());
3100    }
3101
3102    anyhow::bail!(
3103        "{path_str} declares {} the workload schema does not have, and their values were being \
3104         discarded in silence:\n\
3105         \x20 {}\n\
3106         \n\
3107         Delete them, or correct the spelling. A key that is present in the file and absent \
3108         from the deployed spec is exactly the failure that destroyed a live workload on \
3109         2026-09-11 (R892): the declaration reads as honoured and is not.",
3110        if dropped.len() == 1 { "a key" } else { "keys" },
3111        dropped.join("\n  ")
3112    );
3113}
3114
3115/// Recursive half of [`refuse_dropped_keys`] — keys in `declared` with no
3116/// counterpart in `kept`, reported as dotted paths.
3117fn collect_dropped_keys(
3118    declared: &toml::Value,
3119    kept: &toml::Value,
3120    prefix: &str,
3121    out: &mut Vec<String>,
3122) {
3123    match (declared, kept) {
3124        (toml::Value::Table(d), toml::Value::Table(k)) => {
3125            for (key, value) in d {
3126                match k.get(key) {
3127                    Some(kept_value) => {
3128                        collect_dropped_keys(value, kept_value, &format!("{prefix}{key}."), out)
3129                    }
3130                    None => out.push(format!("{prefix}{key}")),
3131                }
3132            }
3133        }
3134        // Element-wise only when nothing was added or removed. A length change
3135        // means the serialiser reshaped the list (materialisation appends mounts,
3136        // for one), and pairing across that would report nonsense.
3137        (toml::Value::Array(d), toml::Value::Array(k)) if d.len() == k.len() => {
3138            for (i, (dv, kv)) in d.iter().zip(k).enumerate() {
3139                collect_dropped_keys(dv, kv, &format!("{prefix}{i}."), out);
3140            }
3141        }
3142        _ => {}
3143    }
3144}
3145
3146/// Load all mirror configs from the `mirrors/` directory.
3147///
3148/// Handles two layouts that may coexist:
3149/// - **Folder**: `mirrors/<id>/mirror.toml` — preferred; allows secrets and
3150///   per-mirror overrides to live next to the config file.
3151/// - **Flat**: `mirrors/<id>.toml` — legacy; still supported.
3152///
3153/// Each file is parsed as [`LegacyMirrorConfig`]. A malformed file returns an error
3154/// that includes the file path and the TOML field path + line/column, so the
3155/// caller can surface it to the user directly.
3156fn load_mirrors(dir: std::path::PathBuf) -> Result<Vec<LegacyMirrorConfig>> {
3157    if !dir.exists() {
3158        return Ok(vec![]);
3159    }
3160    let mut mirrors = vec![];
3161    let mut entries: Vec<_> = std::fs::read_dir(&dir)
3162        .with_context(|| format!("reading {}", dir.display()))?
3163        .filter_map(|e| e.ok())
3164        .collect();
3165    entries.sort_by_key(|e| e.file_name());
3166
3167    for entry in entries {
3168        let path = entry.path();
3169        if path.is_dir() {
3170            // Folder layout: mirrors/<id>/mirror.toml
3171            let mirror_toml = path.join("mirror.toml");
3172            if mirror_toml.exists() {
3173                let src = std::fs::read_to_string(&mirror_toml)
3174                    .with_context(|| format!("reading {}", mirror_toml.display()))?;
3175                let cfg: LegacyMirrorConfig = toml::from_str(&src)
3176                    .with_context(|| format!("parsing {}", mirror_toml.display()))?;
3177                mirrors.push(cfg);
3178            }
3179        } else if path.extension().map_or(false, |e| e == "toml") {
3180            // Flat layout: mirrors/<id>.toml
3181            let src = std::fs::read_to_string(&path)
3182                .with_context(|| format!("reading {}", path.display()))?;
3183            let cfg: LegacyMirrorConfig =
3184                toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
3185            mirrors.push(cfg);
3186        }
3187    }
3188    Ok(mirrors)
3189}
3190
3191/// Load `topology.toml` if it exists; return a default (empty) topology otherwise.
3192fn load_topology(path: std::path::PathBuf) -> Result<TopologyConfig> {
3193    if !path.exists() {
3194        return Ok(TopologyConfig::default());
3195    }
3196    let src =
3197        std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
3198    toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
3199}
3200
3201/// R555-S1: entries are sorted by file name before parsing, so "declaration
3202/// order in `.yah/infra/machines/` breaks ties" — the contract
3203/// [`CloudConfig::admit_workload`] documents — is actually true. `read_dir`
3204/// yields filesystem order, which is unspecified and differs between APFS and
3205/// a hashed-dir ext4; without the sort, *which* of two equally-matching nodes a
3206/// workload admits to could change when an unrelated file is added to the
3207/// directory. That was latent while each tag set had one match and became
3208/// observable the day us-west-003 joined us-west-002 on
3209/// `[tag:build-worker, arch:x86, os:linux]`. Same sort `load_providers` has
3210/// always done.
3211fn load_dir<T: for<'de> Deserialize<'de>>(dir: std::path::PathBuf) -> Result<Vec<T>> {
3212    if !dir.exists() {
3213        return Ok(vec![]);
3214    }
3215    let mut entries: Vec<_> = std::fs::read_dir(&dir)
3216        .with_context(|| format!("reading {}", dir.display()))?
3217        .collect::<std::io::Result<Vec<_>>>()
3218        .with_context(|| format!("reading {}", dir.display()))?;
3219    entries.sort_by_key(|e| e.file_name());
3220
3221    let mut items = vec![];
3222    for entry in entries {
3223        let path = entry.path();
3224        if path.extension().map_or(false, |e| e == "toml") {
3225            let src = std::fs::read_to_string(&path)
3226                .with_context(|| format!("reading {}", path.display()))?;
3227            let item: T =
3228                toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
3229            items.push(item);
3230        }
3231    }
3232    Ok(items)
3233}
3234
3235// ─── New manifest shapes (R222 B2) ───────────────────────────────────────────
3236//
3237// The post-R215 layout splits substrate from service declarations:
3238//
3239//   .yah/infra/providers/<id>.toml      → ProviderConfig
3240//   .yah/services/<svc>/service.toml    → ServiceConfig
3241//   .yah/services/<svc>/mirrors/<env>.toml → MirrorConfig
3242//
3243// CloudConfig::load still reads the legacy layout — B3 swaps in these types
3244// and removes the Legacy* shapes plus TopologyConfig.
3245
3246/// Tag for the infrastructure provider kind. Drives which fields are valid in
3247/// a [`ProviderConfig`] body or a [`MirrorProviderSlot::Inline`] block.
3248///
3249/// Two flavors:
3250/// - **Account/runtime providers** (`cloudflare`, `hetzner`, `local-container`)
3251///   live as files under `.yah/infra/providers/<id>.toml` and are referenced
3252///   from a mirror via `use = "<id>"`.
3253/// - **Inline-only providers** (`miniflare-native`, `miniflare-container`,
3254///   `minio-container`) declare an operator-local stand-in directly inside a
3255///   mirror via `kind = "..."`. They carry no credentials and have no provider
3256///   file. The container-backed kinds ride on top of whichever
3257///   `local-container` runtime is declared in infra (orbstack/colima/docker);
3258///   the reconciler resolves the runtime at up-time.
3259#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
3260#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3261#[serde(rename_all = "kebab-case")]
3262pub enum Provider {
3263    /// Cloudflare account: R2 buckets, DNS, Workers, Tunnels.
3264    Cloudflare,
3265    /// Hetzner Cloud + Object Storage account.
3266    Hetzner,
3267    /// Vultr cloud VPS — auto-provisioned via the `cloud.vps.*` Envoy
3268    /// (`VultrEnvoy`), the burst/scaling counterpart to Hetzner. Driver-backed.
3269    Vultr,
3270    /// BYO bare/static node (OVH, on-prem, anything we did NOT provision via a
3271    /// cloud API). Brought up over SSH (`stand-up-yubaba.sh` / `yah cloud
3272    /// machine bootstrap`); reach is declared in the machine's `[connect]`
3273    /// block. No create/destroy driver — placement-only.
3274    Static,
3275    /// Dev-tier static surface: miniflare (workerd) running **natively** — no
3276    /// container — in front of whatever the mirror binds to the `s3`
3277    /// capability (W265, R584-F4).
3278    ///
3279    /// The door at every tier is the same compiled Worker bundle
3280    /// (`worker/router.bundle.js`); only the object store underneath differs,
3281    /// and that difference is now declared rather than branched on:
3282    ///
3283    /// ```toml
3284    /// [providers.static]
3285    /// kind = "miniflare-native"
3286    /// port = 4321
3287    ///
3288    /// [drivers.s3]
3289    /// kind = "local-s3-fs"
3290    /// ```
3291    ///
3292    /// This replaces `local-static`, which served a workload's `dist/` off
3293    /// disk and so gave the dev tier a storage interface no other tier had —
3294    /// the fork W265 exists to delete. Inline-only; it carries no credentials
3295    /// (the store is loopback, the Worker runs on this machine).
3296    MiniflareNative,
3297    /// Local container runtime (orbstack/colima/docker). Configured by a
3298    /// provider file under `.yah/infra/providers/` so the discovery hints +
3299    /// runtime override sit in one place.
3300    LocalContainer,
3301    /// Dev-tier compute: the component runs as a kamaji-supervised host
3302    /// process against the operator's real workspace, no container and no
3303    /// build step per edit. Inline-only — it carries no credentials, and
3304    /// "the machine you are sitting at" is not an account to point at.
3305    /// See `reconciler::local_process`.
3306    LocalProcess,
3307    /// Containerized miniflare (workerd subprocess) fronting MinIO — the
3308    /// pond-tier stand-in for a CF Worker + R2 static surface. Inline-only;
3309    /// the reconciler spawns miniflare via the JS runtime and starts a MinIO
3310    /// container on the local-container runtime.
3311    MiniflareContainer,
3312    /// Containerized MinIO providing an S3-compatible API — the pond-tier
3313    /// stand-in for Cloudflare R2. Inline-only; the reconciler spins up the
3314    /// container on the local-container runtime and auto-creates the declared
3315    /// bucket on first up.
3316    MinioContainer,
3317    /// Dev-tier PostgreSQL — a real server speaking real pgwire on loopback,
3318    /// supervised by kamaji as the `yah-pg-dev` workload (W265, R584-F1). No
3319    /// docker daemon: the driver fetches a per-arch PostgreSQL tarball on first
3320    /// run and `initdb`s a cluster under `.yah/infra/state/dev/pg/`.
3321    ///
3322    /// Inline-only — it carries no credentials worth a provider file (the
3323    /// cluster is loopback-bound with a fixed dev password). Declared under
3324    /// [`MirrorConfig::drivers`], not `providers`:
3325    ///
3326    /// ```toml
3327    /// [drivers.pg]
3328    /// kind = "local-pg-dev"
3329    /// ```
3330    LocalPgDev,
3331    /// Dev/pond-tier SMTP — [mailcrab] supervised by kamaji as the
3332    /// `yah-smtp-dev` workload (W265, R584-F2). A real SMTP listener that
3333    /// accepts every message and delivers none of them, plus a web inbox to
3334    /// read what was sent. No docker daemon: the driver fetches the per-arch
3335    /// mailcrab release binary on first run and caches it under
3336    /// `.yah/cache/mailcrab/`.
3337    ///
3338    /// Inline-only — it carries no credentials at all (the listener is
3339    /// loopback-bound and unauthenticated, which is the point: a catcher that
3340    /// refused unauthenticated mail would not catch the mail your app sends).
3341    /// Declared under [`MirrorConfig::drivers`], not `providers`:
3342    ///
3343    /// ```toml
3344    /// [drivers.smtp]
3345    /// kind = "local-mailcrab"
3346    /// ```
3347    ///
3348    /// [mailcrab]: https://github.com/tweedegolf/mailcrab
3349    LocalMailcrab,
3350    /// Dev-tier S3 — a filesystem-backed, path-style S3 surface supervised by
3351    /// kamaji as the `yah-s3-fs` workload (W265, R584-F3). No docker daemon
3352    /// and no download: the driver *is* the server, and objects live under
3353    /// `.yah/infra/state/dev/s3/data/<bucket>/`.
3354    ///
3355    /// Inline-only — the credentials are fixed dev strings on a loopback
3356    /// listener, which is not an account to point a provider file at.
3357    /// Declared under [`MirrorConfig::drivers`], not `providers`:
3358    ///
3359    /// ```toml
3360    /// [drivers.s3]
3361    /// kind = "local-s3-fs"
3362    /// ```
3363    ///
3364    /// Unlike its two siblings the binding is **optional**: the camp brings
3365    /// this driver up for any camp with a dev mirror whether or not a stanza
3366    /// says so, because every static-asset component needs object storage and
3367    /// [`crate::capability::Capability::for_component_kind`] already says as
3368    /// much. Declaring it is documentation, not activation — see
3369    /// `crate::reconciler::s3_driver::camp_needs_s3_driver`.
3370    LocalS3Fs,
3371}
3372
3373/// A provider account/runtime binding from `.yah/infra/providers/<id>.toml`.
3374///
3375/// The `kind` discriminator picks the schema for the remaining fields. Strict
3376/// on `kind` (unknown values are a parse error); permissive on per-kind fields
3377/// (carried as a free-form map so this loader stays stable as new fields land).
3378/// B3/B4 will tighten by introducing typed variants alongside JSON Schema.
3379#[derive(Debug, Clone, Serialize, Deserialize)]
3380#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3381pub struct ProviderConfig {
3382    pub schema_version: u32,
3383    pub id: String,
3384    pub kind: Provider,
3385    /// Reference into the OS keystore for live credentials (e.g.
3386    /// `"keystore://cloudflare/yah"`). `None` for providers that don't need
3387    /// creds (miniflare-native, optionally local-container).
3388    #[serde(default, skip_serializing_if = "Option::is_none")]
3389    pub credentials: Option<String>,
3390    /// Kind-specific fields. Examples:
3391    /// - cloudflare: `default_zone`
3392    /// - hetzner:    `default_location`, `default_server_type`, `ssh_keys`
3393    /// - local-container: `runtime`, `discovery`
3394    #[serde(flatten)]
3395    #[cfg_attr(
3396        feature = "json-schema",
3397        schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
3398    )]
3399    pub fields: BTreeMap<String, toml::Value>,
3400}
3401
3402impl ProviderConfig {
3403    /// Parse a single `providers/<id>.toml` file.
3404    pub fn load(path: &Path) -> Result<Self> {
3405        let src =
3406            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
3407        toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
3408    }
3409}
3410
3411/// An operator-facing service declaration from
3412/// `.yah/services/<svc>/service.toml`.
3413///
3414/// A service groups one or more components (a static surface, a containerized
3415/// API, an almanac…) under a single domain. Mirrors project the service onto
3416/// concrete infra; see [`MirrorConfig`].
3417#[derive(Debug, Clone, Serialize, Deserialize)]
3418#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3419pub struct ServiceConfig {
3420    pub schema_version: u32,
3421    pub name: String,
3422    pub domain: String,
3423    /// Path the front-door health probe requests, relative to
3424    /// [`domain`](Self::domain). `None` means `/`.
3425    ///
3426    /// `/` is the right question for a service whose root serves a site, and
3427    /// the wrong one for an API. An account/RPC origin that versions its
3428    /// surface answers only under its prefix and 404s everything else *on
3429    /// purpose* — so probing the root reported a broken cell for a service
3430    /// that was behaving exactly as designed, which is the failure mode the
3431    /// probe exists to remove rather than add to. Naming the path here makes
3432    /// the probe ask a question the service has agreed to answer.
3433    ///
3434    /// Service-scoped rather than per-component or per-mirror: one domain has
3435    /// one front door and therefore one canonical liveness URL, and that URL
3436    /// is a property of the service's own router — it does not vary by
3437    /// environment, so repeating it per mirror would only let the copies
3438    /// drift.
3439    ///
3440    /// Must be absolute (leading `/`); [`validate`](Self::validate) refuses
3441    /// anything else rather than silently joining it onto the origin.
3442    #[serde(default, skip_serializing_if = "Option::is_none")]
3443    pub health_path: Option<String>,
3444    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3445    pub components: Vec<ServiceComponent>,
3446    /// Databases this service exposes, grouped by environment (W241). Every
3447    /// entry becomes a data-workbench / `sql_*` catalog id of the shape
3448    /// `<env>:<service>:<name>` (e.g. `pond:scrabcake:main`). Optional and
3449    /// default-empty — services without databases omit the `[db]` table
3450    /// entirely.
3451    #[serde(default, skip_serializing_if = "DbCatalog::is_empty")]
3452    pub db: DbCatalog,
3453}
3454
3455impl ServiceConfig {
3456    /// Parse a single `services/<svc>/service.toml` file.
3457    pub fn load(path: &Path) -> Result<Self> {
3458        let src =
3459            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
3460        toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
3461    }
3462
3463    /// Persist to `.yah/services/<name>/service.toml`, creating the service
3464    /// directory if needed. Create-or-overwrite — the canonical replacement
3465    /// for the legacy `sites.json` write path. `workspace_root` is the camp
3466    /// dir (the parent of `.yah/`).
3467    pub fn save(&self, workspace_root: &Path) -> Result<()> {
3468        let dir = crate::paths::service_dir(workspace_root, &self.name);
3469        std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
3470        let path = crate::paths::service_toml(workspace_root, &self.name);
3471        let s = toml::to_string_pretty(self)
3472            .with_context(|| format!("serializing service {}", self.name))?;
3473        std::fs::write(&path, s).with_context(|| format!("writing {}", path.display()))
3474    }
3475
3476    /// Remove `.yah/services/<name>/` and everything under it (service.toml
3477    /// plus its `mirrors/`). Returns `false` when the directory was already
3478    /// absent, so callers can distinguish "deleted" from "no-op".
3479    pub fn delete(workspace_root: &Path, name: &str) -> Result<bool> {
3480        let dir = crate::paths::service_dir(workspace_root, name);
3481        if !dir.exists() {
3482            return Ok(false);
3483        }
3484        std::fs::remove_dir_all(&dir).with_context(|| format!("removing {}", dir.display()))?;
3485        Ok(true)
3486    }
3487}
3488
3489/// A git source for a component (R561-F1, "BYO git").
3490///
3491/// When a [`ServiceComponent`] sets `git`, the component's code is NOT in this
3492/// workspace — it lives in an external repo that the reconciler shallow-clones
3493/// into a source cache before build (approach A: clone-at-reconcile, so config
3494/// load + validation stay offline). The component's `path` is then interpreted
3495/// relative to `<checkout>/<subdir>` instead of the workspace root.
3496#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3497#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3498pub struct GitSource {
3499    /// Clone URL (https or ssh) of the tenant repo.
3500    pub repo: String,
3501    /// Branch, tag, or commit SHA to check out. Defaults to `"main"`.
3502    #[serde(default = "default_git_ref")]
3503    pub r#ref: String,
3504    /// Optional sub-directory within the repo that the workspace is rooted at
3505    /// (e.g. a monorepo's `site/`). `path` is resolved relative to this.
3506    #[serde(default, skip_serializing_if = "Option::is_none")]
3507    pub subdir: Option<String>,
3508}
3509
3510fn default_git_ref() -> String {
3511    "main".to_string()
3512}
3513
3514/// How to reach an external infra root (R615-F1 / W274, "linked infra
3515/// sources"): a filesystem link to a sibling camp's live tree, or a git
3516/// checkout of an extracted infra repo.
3517#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3518#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3519#[serde(tag = "kind", rename_all = "kebab-case")]
3520pub enum InfraSourceKind {
3521    /// Filesystem link — reads the owner's live tree. The dev-loop shortcut,
3522    /// and the whole story until W274's "infra as its own repo" end-state.
3523    /// `path` is relative to *this* camp's root; infra is read from
3524    /// `<path>/.yah/infra/`.
3525    Path {
3526        path: String,
3527    },
3528    /// Git link — reused verbatim from [`GitSource`] (R561, "BYO git"),
3529    /// lifted here from "a component's code" to "a camp's infra registry."
3530    /// Loading stays offline (W274 §3): `yah infra sync` (R615-T3) is what
3531    /// clones/pulls this into `.yah/cache/infra/<owner>/`; `CloudConfig::load`
3532    /// only ever reads that cache, never the network.
3533    Git(GitSource),
3534}
3535
3536/// Write-gate for a linked [`InfraSource`] (R615-F1 / W274).
3537///
3538/// An enum, not a bool: the two states today are "borrower renders/plans but
3539/// cannot reconcile" and "this camp genuinely co-administers the shared
3540/// root," and a future read-write-with-approval tier is a third variant, not
3541/// a renamed boolean.
3542#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
3543#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3544#[serde(rename_all = "kebab-case")]
3545pub enum SourceMode {
3546    /// Borrower can render and plan against the linked entries but cannot
3547    /// reconcile/mutate them — the owner remains the single manager. Default:
3548    /// a borrower is opt-in to write access, never opt-out of the safe state.
3549    #[default]
3550    ReadOnly,
3551    /// Escape hatch for a camp that genuinely co-administers a shared root.
3552    Manage,
3553}
3554
3555/// One `[[source]]` entry in `.yah/infra/sources.toml` (R615-F1 / W274) — an
3556/// external infra root this camp borrows machines/providers from.
3557#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3558#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3559pub struct InfraSource {
3560    /// Logical owner name, badged in the Infra tab (e.g. `"yah"`). Distinct
3561    /// from any camp/repo name the `kind` resolves through — this is what an
3562    /// operator sees on a borrowed row, not a path.
3563    pub owner: String,
3564    #[serde(flatten)]
3565    pub kind: InfraSourceKind,
3566    #[serde(default)]
3567    pub mode: SourceMode,
3568    /// Optional filter — name globs or mesh-tag selectors — to borrow a
3569    /// subset of the source root rather than everything it declares. Empty
3570    /// (the default) borrows everything.
3571    #[serde(default)]
3572    pub select: Vec<String>,
3573}
3574
3575fn default_sources_schema_version() -> u32 {
3576    1
3577}
3578
3579/// `.yah/infra/sources.toml` — the ordered list of external infra roots this
3580/// camp borrows from (R615-F1 / W274).
3581#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3582#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3583pub struct SourcesConfig {
3584    #[serde(default = "default_sources_schema_version")]
3585    pub schema_version: u32,
3586    /// `[[source]]` entries, in declaration order — overlay order matters
3587    /// when two linked sources both name the same machine (R615-F2).
3588    #[serde(default, rename = "source")]
3589    pub source: Vec<InfraSource>,
3590}
3591
3592impl Default for SourcesConfig {
3593    fn default() -> Self {
3594        Self {
3595            schema_version: default_sources_schema_version(),
3596            source: Vec::new(),
3597        }
3598    }
3599}
3600
3601impl SourcesConfig {
3602    /// Load `<infra_dir>/sources.toml`. A missing file is not an error —
3603    /// every camp without linked infra has none, which today is every camp —
3604    /// and yields an empty source list rather than `Err`.
3605    pub fn load(infra_dir: &Path) -> Result<Self> {
3606        let path = infra_dir.join("sources.toml");
3607        if !path.exists() {
3608            return Ok(Self::default());
3609        }
3610        let src =
3611            std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
3612        toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
3613    }
3614}
3615
3616impl InfraSource {
3617    /// Human-readable descriptor of *which* source this is, for
3618    /// [`InfraOrigin::source`] — distinguishes two linked sources from the
3619    /// same owner. Never includes credentials: `GitSource.repo` is a clone
3620    /// URL (https/ssh), the same thing R561 already treats as safe to log,
3621    /// with any real secret resolved separately via `keystore://` (W274's
3622    /// own precedent).
3623    fn describe(&self) -> String {
3624        match &self.kind {
3625            InfraSourceKind::Path { path } => format!("path:{path}"),
3626            InfraSourceKind::Git(g) => format!("git:{}@{}", g.repo, g.r#ref),
3627        }
3628    }
3629
3630    /// Resolve this source to an infra root directory (R615-F2 / W274 §3).
3631    /// Does no I/O and touches no network: `path` sources read the owner's
3632    /// live tree directly; `git` sources read wherever `yah infra sync`
3633    /// (R615-T3) last synced to, which may not exist yet (an unsynced git
3634    /// source overlays nothing, not an error — see [`load_dir_tolerant`]).
3635    ///
3636    /// `git.subdir` (reused verbatim from [`GitSource`]/R561) is honoured
3637    /// exactly like the component case: the checkout root when unset, or
3638    /// `<checkout>/<subdir>` when set — e.g. `subdir = "infra"` for a
3639    /// monorepo whose infra registry lives under `infra/` rather than at the
3640    /// clone's root. `yah infra sync` (R615-T3) clones into the *checkout*
3641    /// root ([`crate::paths::infra_source_cache_dir`]), never into a
3642    /// subdir-suffixed path, so this is the one place that appends `subdir`.
3643    fn infra_root(&self, workspace_root: &Path) -> std::path::PathBuf {
3644        match &self.kind {
3645            InfraSourceKind::Path { path } => workspace_root.join(path).join(".yah").join("infra"),
3646            InfraSourceKind::Git(g) => {
3647                let checkout = crate::paths::infra_source_cache_dir(workspace_root, &self.owner);
3648                match g.subdir.as_deref() {
3649                    Some(subdir) => checkout.join(subdir),
3650                    None => checkout,
3651                }
3652            }
3653        }
3654    }
3655}
3656
3657/// Provenance for a [`MachineConfig`] or [`ProviderConfig`] pulled in from a
3658/// linked `.yah/infra/sources.toml` entry, rather than declared in this
3659/// camp's own `.yah/infra/` (R615-F2 / W274).
3660///
3661/// Lives in [`CloudConfig::machine_origins`] / `provider_origins`, keyed by
3662/// name/id, rather than as a field on `MachineConfig`/`ProviderConfig`
3663/// themselves: those two types are constructed by struct literal in test
3664/// helpers across several crates (including ones this ticket has no reason to
3665/// touch), so widening either shape would ripple out past this crate for no
3666/// semantic gain — origin is a property of *this load*, not an inherent
3667/// property of the machine/provider. A name absent from the map is
3668/// camp-local; present means borrowed, and the Infra tab (R615-F4) / reconcile
3669/// gating (`InfraSource::mode`, copied onto `mode` below) read it from here.
3670#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3671#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3672pub struct InfraOrigin {
3673    /// The [`InfraSource::owner`] that supplied this entry, e.g. `"yah"`.
3674    pub owner: String,
3675    /// Which source, rendered — see [`InfraSource::describe`].
3676    pub source: String,
3677    /// The write-gate that applied when this entry was overlaid — copied
3678    /// from [`InfraSource::mode`] so a caller holding just the machine/
3679    /// provider doesn't need the source list in hand to know it's borrowed
3680    /// read-only.
3681    pub mode: SourceMode,
3682}
3683
3684/// Like [`load_dir`], but tolerant **per file**: a foreign infra root (an
3685/// owner's live tree, or a synced git checkout) can carry entries this
3686/// binary's `T` predates — noisetable's pre-migration machines used an older
3687/// schema than yah's, and the reverse will happen too as each side evolves
3688/// independently. One unparseable file on a source this camp doesn't own must
3689/// never sink every other entry in the same directory, let alone this camp's
3690/// own load (R615-F2 gotcha). Contrast [`load_dir`], which stays strict for
3691/// camp-local files, where a malformed TOML genuinely should be a hard error.
3692///
3693/// Returns the entries that parsed, plus `(path, error)` for every file that
3694/// didn't — the caller logs those, it doesn't drop them silently. A missing
3695/// or unreadable directory yields `(vec![], vec![])`, same "no entries" as
3696/// `load_dir`'s `!dir.exists()` case (an unsynced git source, or a source
3697/// root with no `providers/` at all, are both normal, not warnings).
3698fn load_dir_tolerant<T: for<'de> Deserialize<'de>>(
3699    dir: &Path,
3700) -> (Vec<T>, Vec<(std::path::PathBuf, anyhow::Error)>) {
3701    let Ok(read_dir) = std::fs::read_dir(dir) else {
3702        return (Vec::new(), Vec::new());
3703    };
3704    let mut entries: Vec<_> = read_dir.filter_map(|e| e.ok()).collect();
3705    entries.sort_by_key(|e| e.file_name());
3706
3707    let mut items = Vec::new();
3708    let mut skipped = Vec::new();
3709    for entry in entries {
3710        let path = entry.path();
3711        if path.extension().map_or(true, |e| e != "toml") {
3712            continue;
3713        }
3714        let parsed = std::fs::read_to_string(&path)
3715            .with_context(|| format!("reading {}", path.display()))
3716            .and_then(|src| {
3717                toml::from_str::<T>(&src).with_context(|| format!("parsing {}", path.display()))
3718            });
3719        match parsed {
3720            Ok(item) => items.push(item),
3721            Err(e) => skipped.push((path, e)),
3722        }
3723    }
3724    (items, skipped)
3725}
3726
3727/// Whether a borrowed machine passes an [`InfraSource::select`] filter
3728/// (R615-F2 / W274). Empty `select` borrows everything. A non-empty `select`
3729/// entry matches either the machine's exact `name` or literal membership in
3730/// its `mesh_tags` — the one shape W274's own example uses
3731/// (`select = ["tag:cloud-runner"]`). Not a glob engine: mesh tags are
3732/// already flat strings compared for exact equality everywhere else in this
3733/// crate (see `resolve_machine_by_mesh_tags`), so a select entry is that same
3734/// comparison, not a new pattern language.
3735fn machine_matches_select(machine: &MachineConfig, select: &[String]) -> bool {
3736    select.is_empty()
3737        || select
3738            .iter()
3739            .any(|s| *s == machine.name || machine.mesh_tags.contains(s))
3740}
3741
3742/// What one `[[source]]` in `.yah/infra/sources.toml` actually contributed to
3743/// [`FleetInventory`] on this load (R870-B13).
3744///
3745/// Recorded because a link that resolves to *nothing* is indistinguishable, at
3746/// every downstream use site, from a camp that declared no link at all — and
3747/// that is precisely the failure this ticket exists to fix. A source that
3748/// contributes zero machines is not an error here (an unsynced `kind = "git"`
3749/// source is legitimately empty, and `load()` must stay offline), so instead
3750/// the fact is *carried* to whoever fails for want of a machine. See
3751/// [`FleetInventory::describe_sources`].
3752#[derive(Debug, Clone, PartialEq, Eq)]
3753pub struct SourceContribution {
3754    /// [`InfraSource::owner`] — the name this camp knows the fleet by.
3755    pub owner: String,
3756    /// The source, rendered — see [`InfraSource::describe`].
3757    pub source: String,
3758    /// Where the link resolved to, i.e. the foreign `.yah/infra/`.
3759    pub root: std::path::PathBuf,
3760    /// Whether `root` exists on disk. `false` for a `kind = "path"` link
3761    /// aimed at a directory that is not a camp, and for a `kind = "git"`
3762    /// source that `yah infra sync` has never fetched.
3763    pub root_exists: bool,
3764    /// How many machines this source actually added to the inventory — after
3765    /// [`InfraSource::select`] filtering and after losing every name a
3766    /// camp-local entry or an earlier source already claimed.
3767    pub machines: usize,
3768}
3769
3770/// A camp's resolved machine inventory: **the** answer to "which machines does
3771/// this camp have", with exactly one implementation
3772/// ([`resolve_fleet_inventory`]) behind it (R870-B13).
3773///
3774/// A borrowing camp — one whose own `.yah/infra/machines/` is empty and which
3775/// declares `[[source]]` links to another camp's fleet in
3776/// `.yah/infra/sources.toml` — is the case this type exists for. Before it,
3777/// the overlay was applied inline inside [`CloudConfig::load`], so the two
3778/// callers that resolve a *machine name to a machine* (ingress collation and
3779/// the sovereign apex render) read a camp-local-only loader and saw an empty
3780/// fleet. There was no bug in either of them; the inventory simply had two
3781/// readers that disagreed about what the inventory was.
3782#[derive(Debug)]
3783pub struct FleetInventory {
3784    /// Camp-local machines first, then each source's contribution in
3785    /// declaration order. Camp-local wins any name collision; among sources,
3786    /// the earlier-declared one wins.
3787    pub machines: Vec<MachineConfig>,
3788    /// Provenance for the borrowed entries, keyed by [`MachineConfig::name`].
3789    /// A name absent here is camp-local. Same shape and meaning as
3790    /// [`CloudConfig::machine_origins`], which is populated from this.
3791    pub origins: BTreeMap<String, InfraOrigin>,
3792    /// The parsed `.yah/infra/sources.toml`, kept so a caller that already has
3793    /// an inventory in hand does not re-read it (`CloudConfig::load` overlays
3794    /// providers from the same list).
3795    pub sources: SourcesConfig,
3796    /// Per-source accounting — see [`SourceContribution`].
3797    pub contributions: Vec<SourceContribution>,
3798}
3799
3800impl FleetInventory {
3801    /// One line per declared `[[source]]`, for attaching to the error a caller
3802    /// raises when a machine name does not resolve (R870-B13).
3803    ///
3804    /// The failure being diagnosed is always "I was told about machine X and
3805    /// cannot find it", and the three ways a borrowing camp gets there — no
3806    /// link declared, a link pointing somewhere that is not a camp, a link
3807    /// whose `select` filtered X out — are indistinguishable from the name
3808    /// alone. Empty string when the camp declares no sources, so the caller
3809    /// can append it unconditionally without emitting a dangling header.
3810    pub fn describe_sources(&self) -> String {
3811        if self.contributions.is_empty() {
3812            return String::new();
3813        }
3814        let mut out = String::from("linked infra sources consulted:");
3815        for c in &self.contributions {
3816            out.push_str(&format!(
3817                "\n  {} ({}) -> {}{} — contributed {} machine(s)",
3818                c.owner,
3819                c.source,
3820                c.root.display(),
3821                if c.root_exists {
3822                    ""
3823                } else {
3824                    " [ABSENT: not a camp, or an unsynced git source]"
3825                },
3826                c.machines,
3827            ));
3828        }
3829        out
3830    }
3831}
3832
3833/// Resolve a camp's machine inventory: camp-local `.yah/infra/machines/`, the
3834/// pre-R215 `.yah/cloud/machines/` tree, then every machine borrowed through
3835/// `.yah/infra/sources.toml` (R870-B13, on R615-F2's mechanism).
3836///
3837/// **How a camp names another camp's fleet**, decided here rather than
3838/// invented: through the `[[source]]` entry R615-F1 already defines — `owner`
3839/// is the logical name an operator sees, `kind = "path"` resolves against the
3840/// borrowing camp's own root and `kind = "git"` against `yah infra sync`'s
3841/// cache. There is deliberately no second naming scheme: a camp that could
3842/// name a foreign fleet two ways would be a camp whose inventory can drift
3843/// from itself, which is the thing this ticket rejected.
3844///
3845/// **There is exactly one copy.** A `kind = "path"` source reads the owner's
3846/// live tree at `<path>/.yah/infra/` on every load — the borrowing camp
3847/// persists nothing, so the two can never disagree. `kind = "git"` reads a
3848/// synced checkout, which *is* a copy, but an explicit one with a named
3849/// refresh verb (`yah infra sync`) and a pinned `ref`; that is the cache with
3850/// an invalidation story, as against a hand-maintained second inventory.
3851///
3852/// Camp-local files are strict (a malformed TOML this camp owns is a hard
3853/// error) and foreign files are tolerant per-file (R615-F2: a foreign entry
3854/// whose schema this binary predates must not sink the load). A foreign
3855/// machine skipped that way is not silently lost — it fails loudly at the
3856/// point some caller needs it, with [`FleetInventory::describe_sources`]
3857/// naming the link it should have come from.
3858///
3859/// Deliberately *without* [`CloudConfig::load`]'s R844-B7 wrong-root guard: a
3860/// missing `.yah/infra/machines/` is an empty inventory here, because the
3861/// callers that resolve against it (ingress collation, apex render) are handed
3862/// a root that a `CloudConfig::load` already accepted.
3863pub fn resolve_fleet_inventory(workspace_root: &Path) -> Result<FleetInventory> {
3864    let mut machines = load_dir::<MachineConfig>(crate::paths::machines_dir(workspace_root))?;
3865
3866    // Pre-R215 `.yah/cloud/machines/`. Shouldn't have anything since R215-B1
3867    // moved them, but if it does we dedupe by name — R215+ wins.
3868    let cloud_dir = crate::paths::legacy_cloud_dir(workspace_root);
3869    if cloud_dir.exists() {
3870        let names: std::collections::HashSet<String> =
3871            machines.iter().map(|m| m.name.clone()).collect();
3872        for m in load_dir::<MachineConfig>(cloud_dir.join("machines"))? {
3873            if !names.contains(&m.name) {
3874                machines.push(m);
3875            }
3876        }
3877    }
3878
3879    // `SourcesConfig::load` never touches the network — git sources are read
3880    // from `yah infra sync`'s cache (R615-T3) — so this keeps the whole
3881    // offline contract `CloudConfig::load` has always had.
3882    let sources = SourcesConfig::load(&crate::paths::infra_dir(workspace_root))?;
3883    let mut origins = BTreeMap::new();
3884    let contributions = overlay_source_machines(workspace_root, &sources, &mut machines, &mut origins);
3885
3886    Ok(FleetInventory {
3887        machines,
3888        origins,
3889        sources,
3890        contributions,
3891    })
3892}
3893
3894/// Overlay every linked `.yah/infra/sources.toml` source's machines into
3895/// `machines`, recording provenance into `machine_origins` (R615-F2 / W274).
3896/// Must be called AFTER camp-local entries are already in the vector:
3897/// collision resolution is "first writer wins," so seeding with camp-local
3898/// first is what makes camp-local win over every source, and an earlier source
3899/// win over a later one.
3900///
3901/// `select` filters which machines a source contributes. Returns one
3902/// [`SourceContribution`] per declared source, in declaration order.
3903fn overlay_source_machines(
3904    workspace_root: &Path,
3905    sources: &SourcesConfig,
3906    machines: &mut Vec<MachineConfig>,
3907    machine_origins: &mut BTreeMap<String, InfraOrigin>,
3908) -> Vec<SourceContribution> {
3909    let mut seen_machine_names: std::collections::HashSet<String> =
3910        machines.iter().map(|m| m.name.clone()).collect();
3911    let mut contributions = Vec::with_capacity(sources.source.len());
3912
3913    for source in &sources.source {
3914        let root = source.infra_root(workspace_root);
3915        let origin = InfraOrigin {
3916            owner: source.owner.clone(),
3917            source: source.describe(),
3918            mode: source.mode,
3919        };
3920
3921        let (foreign_machines, skipped) = load_dir_tolerant::<MachineConfig>(&root.join("machines"));
3922        for (path, e) in skipped {
3923            tracing::warn!(
3924                "infra source {:?} ({}): skipping unparseable machine {}: {e:#}",
3925                source.owner,
3926                root.display(),
3927                path.display()
3928            );
3929        }
3930        let mut added = 0usize;
3931        for m in foreign_machines {
3932            if seen_machine_names.contains(&m.name) {
3933                continue; // camp-local, or an earlier source, already claimed this name
3934            }
3935            if !machine_matches_select(&m, &source.select) {
3936                continue;
3937            }
3938            seen_machine_names.insert(m.name.clone());
3939            machine_origins.insert(m.name.clone(), origin.clone());
3940            machines.push(m);
3941            added += 1;
3942        }
3943
3944        contributions.push(SourceContribution {
3945            owner: source.owner.clone(),
3946            source: source.describe(),
3947            root_exists: root.is_dir(),
3948            root,
3949            machines: added,
3950        });
3951    }
3952
3953    contributions
3954}
3955
3956/// Overlay every linked source's providers into `providers`, recording
3957/// provenance into `provider_origins` (R615-F2 / W274). Same first-writer-wins
3958/// rule as [`overlay_source_machines`], and the same requirement that
3959/// camp-local entries already be in the vector.
3960///
3961/// [`InfraSource::select`] deliberately does not apply: nothing in W274 or
3962/// R615-F1 describes a provider-scoped filter — every provider a source
3963/// declares either overlays whole or, on an id collision, doesn't.
3964fn overlay_source_providers(
3965    workspace_root: &Path,
3966    sources: &SourcesConfig,
3967    providers: &mut Vec<ProviderConfig>,
3968    provider_origins: &mut BTreeMap<String, InfraOrigin>,
3969) {
3970    let mut seen_provider_ids: std::collections::HashSet<String> =
3971        providers.iter().map(|p| p.id.clone()).collect();
3972
3973    for source in &sources.source {
3974        let root = source.infra_root(workspace_root);
3975        let origin = InfraOrigin {
3976            owner: source.owner.clone(),
3977            source: source.describe(),
3978            mode: source.mode,
3979        };
3980
3981        let (foreign_providers, skipped) =
3982            load_dir_tolerant::<ProviderConfig>(&root.join("providers"));
3983        for (path, e) in skipped {
3984            tracing::warn!(
3985                "infra source {:?} ({}): skipping unparseable provider {}: {e:#}",
3986                source.owner,
3987                root.display(),
3988                path.display()
3989            );
3990        }
3991        for p in foreign_providers {
3992            if seen_provider_ids.contains(&p.id) {
3993                continue;
3994            }
3995            seen_provider_ids.insert(p.id.clone());
3996            provider_origins.insert(p.id.clone(), origin.clone());
3997            providers.push(p);
3998        }
3999    }
4000}
4001
4002/// One component of a [`ServiceConfig`]. The `kind` (e.g. `"mesofact-static"`,
4003/// `"almanac"`, `"container"`) selects which reconciler runs against the
4004/// pointed-at workload manifest.
4005#[derive(Debug, Clone, Serialize, Deserialize)]
4006#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4007pub struct ServiceComponent {
4008    pub id: String,
4009    pub kind: String,
4010    /// Path of the directory holding this component's `workload.toml`. Relative
4011    /// to the workspace root for in-tree components, or to the materialized
4012    /// `<checkout>/<subdir>` when [`git`](Self::git) is set.
4013    pub path: String,
4014    /// Optional external git source (R561-F1). When set, the component's code
4015    /// is materialized by shallow-clone before build; see [`GitSource`].
4016    #[serde(default, skip_serializing_if = "Option::is_none")]
4017    pub git: Option<GitSource>,
4018    /// Operator-facing role label, e.g. `"static"`, `"dynamic"`, `"compute"`.
4019    pub role: String,
4020    /// Optional artifact kind this component publishes (`"static"`,
4021    /// `"container-image"`, …). Drives mirror provider-slot routing.
4022    #[serde(default, skip_serializing_if = "Option::is_none")]
4023    pub publishes: Option<String>,
4024    /// URL sub-path a static component's build output is published under,
4025    /// relative to the service's publish prefix (R746). `None` = the service
4026    /// root, which is what every pre-R746 component means.
4027    ///
4028    /// Static publishers lay a component's `out_dir` down at
4029    /// `<bucket>/<service>/<env>/…` and the front door fetches
4030    /// `${ASSET_ORIGIN}/<request path>` — the request path *is* the key. So a
4031    /// service with two static components had them overwrite each other at
4032    /// one prefix, and there was no way to say "this bundle serves under
4033    /// /app". `mount` is that: it appends to the publish prefix, which makes
4034    /// the URL sub-path and the storage sub-path the same string by
4035    /// construction rather than by two manifests agreeing.
4036    ///
4037    /// Cross-checked against the domain route that names the component
4038    /// ([`CloudConfig::cross_ref_validate`]): a component mounted at `/app`
4039    /// must be routed at `/app` or `/app/*`, because a disagreement means
4040    /// requests land on a prefix nothing published to — a 404 whose cause is
4041    /// two files apart.
4042    #[serde(default, skip_serializing_if = "Option::is_none")]
4043    pub mount: Option<String>,
4044    /// Sync-wave index (0-based). Components in wave 0 roll out in parallel
4045    /// first; the reconciler waits for all wave-N components to become healthy
4046    /// before starting wave N+1. Defaults to 0 (all components in one wave).
4047    #[serde(default, skip_serializing_if = "is_zero_u32")]
4048    pub wave: u32,
4049
4050    /// Whether this component ships inside the service's one assembled bundle
4051    /// or as a deployed unit of its own (R870-F23).
4052    ///
4053    /// This is the vocabulary R870-F15's design needed and the config did not
4054    /// have. `[providers.bundle]` is a per-**mirror** slot, so before this
4055    /// there was no way to say "give this one component its own workload" at
4056    /// all — the whole service was one bundle or it was nothing, and a service
4057    /// whose components genuinely release on different cadences had no shape
4058    /// to declare.
4059    ///
4060    /// It is one field rather than a pair of flags on purpose: a component
4061    /// being both bundle-staged and its own workload is the second admission
4062    /// rule R870-F23 was asked to enforce, and an enum makes it unrepresentable
4063    /// instead of merely refused.
4064    #[serde(default, skip_serializing_if = "DeployTier::is_default")]
4065    pub deploy: DeployTier,
4066}
4067
4068/// How one [`ServiceComponent`] reaches a node — see
4069/// [`ServiceComponent::deploy`].
4070#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
4071#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4072#[serde(rename_all = "kebab-case")]
4073pub enum DeployTier {
4074    /// Staged into the service's single assembled W272 bundle under
4075    /// `app/dist/<mount>/` and served by the one bundle workload (R870-B11).
4076    /// The default, and what every component in the tree means today.
4077    #[default]
4078    Bundle,
4079    /// Deployed as its own workload, with its own release cadence, its own
4080    /// address, and its own place in the inner door's mount table.
4081    Workload,
4082}
4083
4084impl DeployTier {
4085    /// Skip serializing the default so existing `service.toml` files
4086    /// round-trip byte-identically.
4087    fn is_default(&self) -> bool {
4088        matches!(self, DeployTier::Bundle)
4089    }
4090}
4091
4092#[inline]
4093fn is_zero_u32(n: &u32) -> bool {
4094    *n == 0
4095}
4096
4097/// A service's declared databases, grouped by environment (W241 §Sections).
4098/// Parsed from the `[db]` table of `service.toml`; each `[[db.<env>]]` array
4099/// entry names one database. The environment tag drives backend selection at
4100/// query time (see the data-workbench's `db.query` / the `sql_*` MCP tools):
4101/// `dev` = local file, `pond` = a DB inside the running pond container stack
4102/// (reached on a declared localhost port), `cloud` = a remote libSQL/Turso or
4103/// Postgres endpoint whose auth comes from an env var (never stored in TOML).
4104#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
4105#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4106pub struct DbCatalog {
4107    /// Local-file SQLite databases used in dev mode.
4108    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4109    pub dev: Vec<DevDb>,
4110    /// Databases running inside the pond container stack.
4111    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4112    pub pond: Vec<PondDb>,
4113    /// Remote cloud databases (Turso, Postgres).
4114    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4115    pub cloud: Vec<CloudDb>,
4116}
4117
4118impl DbCatalog {
4119    /// True when no database is declared in any environment. Lets
4120    /// [`ServiceConfig`] skip serializing an empty `[db]` table.
4121    pub fn is_empty(&self) -> bool {
4122        self.dev.is_empty() && self.pond.is_empty() && self.cloud.is_empty()
4123    }
4124}
4125
4126/// A dev-mode local SQLite database (`[[db.dev]]`). `path` is resolved
4127/// relative to the workspace root and opened as a local file — read/write, no
4128/// network, no auth.
4129#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4130#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4131pub struct DevDb {
4132    /// Logical name, unique within the service's `dev` list. Forms the `name`
4133    /// segment of the catalog id `dev:<service>:<name>`.
4134    pub name: String,
4135    /// On-disk SQLite path, relative to the workspace root (or absolute).
4136    pub path: String,
4137}
4138
4139/// A database running inside the pond container stack (`[[db.pond]]`). The
4140/// pond publishes the DB on a localhost TCP port; the hub connects to
4141/// `127.0.0.1:<port>` when the pond is up and returns a clear error when it is
4142/// not. Either `port` (defaulting to a libSQL/`sqld` HTTP endpoint) or a full
4143/// `url` must be given.
4144#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4145#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4146pub struct PondDb {
4147    /// Logical name, unique within the service's `pond` list.
4148    pub name: String,
4149    /// Localhost TCP port the pond publishes the DB on. Interpreted per
4150    /// [`kind`](Self::kind). Mutually complete with `url` (provide one).
4151    #[serde(default, skip_serializing_if = "Option::is_none")]
4152    pub port: Option<u16>,
4153    /// Full connection URL, overriding `port` when set (e.g. a non-localhost
4154    /// host or an explicit scheme).
4155    #[serde(default, skip_serializing_if = "Option::is_none")]
4156    pub url: Option<String>,
4157    /// Wire protocol the pond DB speaks. Selects how a bare `port` becomes a
4158    /// URL: `turso` → `http://127.0.0.1:<port>` (libSQL/`sqld` over Hrana),
4159    /// `postgres` → `postgres://127.0.0.1:<port>`.
4160    #[serde(default)]
4161    pub kind: PondDbKind,
4162}
4163
4164/// Wire protocol of a [`PondDb`].
4165#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
4166#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4167#[serde(rename_all = "kebab-case")]
4168pub enum PondDbKind {
4169    /// libSQL / `sqld` over Hrana HTTP — the default.
4170    #[default]
4171    Turso,
4172    /// PostgreSQL wire protocol.
4173    Postgres,
4174}
4175
4176/// A remote cloud database (`[[db.cloud]]`). The connection `url` is stored in
4177/// TOML but the credential never is — `auth_token_env` names an environment
4178/// variable the daemon reads at connect time, so the same declaration works
4179/// whether the token is provisioned service-locally or camp-shared (W241;
4180/// operator confirmed both scopes are needed). A camp-wide cloud DB not owned
4181/// by any single service is declared identically in `.yah/db/cloud.toml`.
4182#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4183#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4184pub struct CloudDb {
4185    /// Logical name, unique within its `cloud` list.
4186    pub name: String,
4187    /// Connection URL: `libsql://…` / `http(s)://…` (Turso, `sqld`) or
4188    /// `postgres://…`.
4189    pub url: String,
4190    /// Name of the environment variable holding the auth token. Resolved in
4191    /// the daemon at connect time (value never stored on disk). For a libSQL
4192    /// URL the token is threaded as `?auth_token=…`.
4193    #[serde(default, skip_serializing_if = "Option::is_none")]
4194    pub auth_token_env: Option<String>,
4195}
4196
4197/// A camp-shared cloud database catalog, parsed from `.yah/db/cloud.toml`.
4198/// These are cloud DBs not owned by any single service — declared once at camp
4199/// scope and addressed as `cloud:<name>` (two-segment id), distinct from a
4200/// service-local `cloud:<service>:<name>`.
4201#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
4202#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4203pub struct CampCloudDbs {
4204    #[serde(default, rename = "cloud", skip_serializing_if = "Vec::is_empty")]
4205    pub cloud: Vec<CloudDb>,
4206}
4207
4208impl CampCloudDbs {
4209    /// Load `<camp_root>/.yah/db/cloud.toml`, or an empty catalog if the file
4210    /// is absent (the common case — most camps declare no shared cloud DBs).
4211    pub fn load(camp_root: &Path) -> Result<Self> {
4212        let path = camp_root.join(".yah/db/cloud.toml");
4213        if !path.exists() {
4214            return Ok(Self::default());
4215        }
4216        let src = std::fs::read_to_string(&path)
4217            .with_context(|| format!("reading {}", path.display()))?;
4218        toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
4219    }
4220}
4221
4222/// Topological shape of a mirror — how its providers sit relative to each other.
4223#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4224#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4225#[serde(rename_all = "kebab-case")]
4226pub enum MirrorShape {
4227    /// Single machine hosts compute (and any non-Cloudflare-fronted static).
4228    SingleMachine,
4229    /// Operator-local dev mirror — static via built-in file server, compute
4230    /// via the local container runtime.
4231    Local,
4232    /// Multi-machine deployment (machines listed per provider slot).
4233    MultiMachine,
4234}
4235
4236/// Which public-ingress provider fronts this mirror's compute (W267, R594-F11).
4237///
4238/// Both arms answer exactly one question — *given these local workload ports,
4239/// make them publicly reachable at these hostnames* — and they differ only in
4240/// where the ingress rules live and who supervises the front door:
4241///
4242/// | | [`CloudflareTunnel`](Self::CloudflareTunnel) | [`Passway`](Self::Passway) |
4243/// |---|---|---|
4244/// | Ingress rules live | Cloudflare's API (token-form tunnels are remotely-managed) | the pingora `Backends` set in the proxy process |
4245/// | How they get there | an API call per deployed workload | passway polls `GET /service-records?ready=true` |
4246/// | Front door lifecycle | a kamaji-supervised `cloudflared` appliance | a kamaji-supervised passway appliance |
4247///
4248/// Flipping this field is the whole tier ladder: rented edge → sovereign edge
4249/// is a one-line mirror edit, not a rewrite. The provider owns **addressing**
4250/// and never **rendering** — the W173 render cube stays in mesofact's manifest.
4251#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
4252#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4253#[serde(rename_all = "kebab-case")]
4254pub enum IngressProvider {
4255    /// No public front door for this mirror. The default: a mirror that
4256    /// publishes to R2 behind a Worker, or a mesh-only compute tier, has no
4257    /// ingress provider to reconcile.
4258    #[default]
4259    None,
4260    /// Rented edge — `cloudflared` dials *out* from the node to Cloudflare's
4261    /// edge. Zero inbound ports, no TLS to manage on the box, hostname rules
4262    /// held in Cloudflare's API.
4263    CloudflareTunnel,
4264    /// Sovereign edge — passway terminates TLS on the node and load-balances
4265    /// an upstream set discovered from yubaba's service records.
4266    Passway,
4267}
4268
4269impl IngressProvider {
4270    /// `true` when this mirror declares a front door that has to be reconciled.
4271    pub fn is_declared(self) -> bool {
4272        !matches!(self, Self::None)
4273    }
4274
4275    /// Kebab-case wire name, as it appears in `mirrors/<env>.toml`.
4276    pub fn as_str(self) -> &'static str {
4277        match self {
4278            Self::None => "none",
4279            Self::CloudflareTunnel => "cloudflare-tunnel",
4280            Self::Passway => "passway",
4281        }
4282    }
4283}
4284
4285/// What a `cloudflare-tunnel` edge dials instead of the fronted workload —
4286/// W348 §1.3's **stacked** shape (R910).
4287///
4288/// `via = "passway"` puts the tunnel in front of the same node's passway door
4289/// for the same hostnames: cloudflared → the node's sni-demux on loopback
4290/// `:443` → the per-tenant passway → the workload. Passway keeps everything it
4291/// does on a public door — origin TLS, host routing, `[ingress.auth]`, ACME
4292/// (by DNS-01, the one challenge that reaches a NAT'd node) — and Cloudflare
4293/// owns only the browser-facing handshake. Without it a tunnel edge dials the
4294/// workload directly, and a tunnel edge and a passway edge claiming one
4295/// hostname is a partition conflict.
4296///
4297/// An enum rather than a bool because what it names is a front door, and
4298/// passway is simply the only one a tunnel can stack in front of today.
4299#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4300#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4301#[serde(rename_all = "kebab-case")]
4302pub enum IngressVia {
4303    /// The node's own passway door, reached through its sni-demux.
4304    Passway,
4305}
4306
4307impl IngressVia {
4308    /// Kebab-case wire name, as it appears in `mirrors/<env>.toml`.
4309    pub fn as_str(self) -> &'static str {
4310        match self {
4311            Self::Passway => "passway",
4312        }
4313    }
4314
4315    /// The provider of the edge a tunnel carrying this `via` stacks in front
4316    /// of — the edge that has to exist, on the same machines, for the pair to
4317    /// plan.
4318    pub fn provider(self) -> IngressProvider {
4319        match self {
4320            Self::Passway => IngressProvider::Passway,
4321        }
4322    }
4323}
4324
4325/// One declared **edge**: a front door, the slots it fronts, and the nodes it
4326/// is placed on (W305 F2).
4327///
4328/// A mirror declares a *list* of these, which is what lets one service mix
4329/// front doors — cloudflare for the public web tier, passway for an internal or
4330/// high-throughput one. Before this, [`MirrorConfig::ingress`] was a single
4331/// [`IngressProvider`], so a mirror could **swap** front doors but never mix
4332/// them.
4333///
4334/// ```toml
4335/// [[ingress]]
4336/// provider = "passway"
4337/// machines = ["us-east-001", "us-south-001"]
4338/// slots    = ["bundle"]
4339///
4340/// [[ingress]]
4341/// provider  = "cloudflare-tunnel"
4342/// hostnames = ["issues.yah.dev"]
4343/// ```
4344///
4345/// **The per-node appliance is derived from this, never declared beside it.**
4346/// An edge does invoke a cloudflared or passway process on a box, but that is a
4347/// *consequence* of the service's declaration:
4348/// [`collate_front_doors`](crate::reconciler::collate_front_doors) walks every
4349/// service and derives what each node must run. Declaring it node-side too is
4350/// what produces two sources of truth for one fact.
4351#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4352#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4353pub struct IngressEdge {
4354    /// Which front door this edge is. [`IngressProvider::None`] is rejected at
4355    /// plan time — an edge that fronts with nothing is always a typo, never an
4356    /// intent (write no edge instead).
4357    pub provider: IngressProvider,
4358    /// Nodes this front door is placed on — **independent of where the fronted
4359    /// workload runs** (R330-F37).
4360    ///
4361    /// Empty falls back to the fronted slot's own `machine` / `machines`, which
4362    /// is the co-located shape every mirror had before front-door placement was
4363    /// expressible. Listing several is what lets the ingress tier and the
4364    /// service tier scale independently: **N front doors over ONE deployment**,
4365    /// one rendered copy, so no cache coherence to settle.
4366    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4367    pub machines: Vec<String>,
4368    /// Provider slot roles this edge fronts (`"bundle"`, `"compute"`, …).
4369    ///
4370    /// One of the two selectors. With a single edge both may be empty, meaning
4371    /// "every fronted slot" — the legacy shape. With **several** edges a
4372    /// selector is mandatory on each, and the partition must be total and
4373    /// disjoint: a slot claimed by no edge, or by two, is an error naming it.
4374    /// An implicit catch-all across mixed front doors would silently publish a
4375    /// service through the wrong one.
4376    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4377    pub slots: Vec<String>,
4378    /// Public hostnames this edge fronts — the other selector, for partitioning
4379    /// by what the world dials rather than by which slot serves it.
4380    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4381    pub hostnames: Vec<String>,
4382    /// Cloudflare Tunnel id this edge publishes through, overriding the
4383    /// fronting machine's [`MachineConfig::cloudflared`].
4384    ///
4385    /// This is W267 Gap 3's real fix, and it is the *service* side of it: a node
4386    /// can join two cohorts' orange networks, and since §Granularity argues the
4387    /// tunnel credential **is** the isolation boundary, which cohort a given
4388    /// service fronts through is a property of the service, not of the box.
4389    /// `MachineConfig.cloudflared` stays as the per-node default (one tunnel is
4390    /// the common case, and the credential does live on the node), but it is no
4391    /// longer the only way to say it — so the node never has to enumerate
4392    /// cohorts.
4393    #[serde(default, skip_serializing_if = "Option::is_none")]
4394    pub tunnel_id: Option<String>,
4395    /// Infra provider id whose credentials this edge's front door authenticates
4396    /// with — `use = "cloudflare"`, resolved through
4397    /// `.yah/infra/providers/<id>.toml` exactly as a slot's `use` is.
4398    ///
4399    /// Same split as [`tunnel_id`](Self::tunnel_id), one field over: whose
4400    /// Cloudflare account holds the tunnel is a property of the **front door**,
4401    /// not of the box that runs the compute. Without this the account was read
4402    /// off the fronted slot's own `use`, which conflates two unrelated facts —
4403    /// and is unwritable for a slot whose compute provider is `kind = "static"`
4404    /// (a borrowed bare box: placement only, no credentials). Such a mirror had
4405    /// no way to name a Cloudflare account at all, short of writing
4406    /// `use = "cloudflare"` on the compute slot and lying about what runs it
4407    /// (R845).
4408    ///
4409    /// `None` falls back to the fronted slot's `use`, which is what every
4410    /// mirror written before this field meant.
4411    #[serde(default, rename = "use", skip_serializing_if = "Option::is_none")]
4412    pub provider_id: Option<String>,
4413    /// Digest-pinned image reference for this edge's front-door appliance,
4414    /// e.g. `localhost/passway:tag@sha256:<hex>` (R870-F16).
4415    ///
4416    /// `None` is the state of every mirror on disk today: the passway arm of
4417    /// `yah cloud apply` cannot deploy an appliance the mirror doesn't name an
4418    /// image for, so it renders the manual `yah cloud ingress deploy …
4419    /// --image <passway-ref>` step instead of running it. Declaring this field
4420    /// is what makes the arm self-sufficient, matching the CloudflareTunnel
4421    /// arm's real-API-call shape rather than only printing for an operator to
4422    /// copy by hand.
4423    #[serde(default, skip_serializing_if = "Option::is_none")]
4424    pub image: Option<String>,
4425    /// Cheers bearer-auth for this edge's door, spelled as an `[ingress.auth]`
4426    /// table under the `[[ingress]]` entry (R870-F26).
4427    ///
4428    /// ```toml
4429    /// [[ingress]]
4430    /// provider = "passway"
4431    /// image    = "localhost/passway:v1@sha256:…"
4432    ///
4433    /// [ingress.auth]
4434    /// key_secret       = "cheers/yah-camp/verify"
4435    /// kid              = "YOHV4Riq-g8fX4uYl8rTjQ"
4436    /// iss              = "yah-camp"
4437    /// aud              = "analytics.yah.dev"
4438    /// require_prefixes = ["/"]
4439    /// ```
4440    ///
4441    /// **This is what makes an apply-driven push FAITHFUL rather than merely
4442    /// blocked.** Before it, `yah cloud apply`'s Passway arm rebuilt the door's
4443    /// spec with `auth: None` because a mirror had no way to say otherwise, and
4444    /// `/workloads/deploy` is a full replace — so pushing at a door someone had
4445    /// deployed with `--auth-key-secret …` took its auth away and brought it
4446    /// back anonymous (R870-B24). That strip is guarded by a read-back in
4447    /// `push_passway_ingress`, and the guard STAYS: it covers a door that
4448    /// acquired auth in a way no mirror can see. This field is what lets the
4449    /// common case sail past that guard by carrying the auth instead of losing
4450    /// it — the guard early-returns on any push that carries auth of its own.
4451    ///
4452    /// [`PasswayAuth`] verbatim, not a config-side copy of its five fields: all
4453    /// five are required by `Deserialize`, so a half-written table is refused
4454    /// by serde naming the missing field, and the renderer that emits the
4455    /// `PASSWAY_AUTH_*` variables reads the very same struct.
4456    ///
4457    /// Only meaningful on a `provider = "passway"` edge — a cloudflare-tunnel
4458    /// edge carrying one is refused by [`MirrorConfig::ingress_edges`] rather
4459    /// than silently ignored, since ignoring it yields exactly the
4460    /// believed-protected-but-public door this vocabulary exists to prevent.
4461    #[serde(default, skip_serializing_if = "Option::is_none")]
4462    pub auth: Option<PasswayAuth>,
4463    /// Stack this edge in front of another front door on the same node instead
4464    /// of dialing the workload (R910) — see [`IngressVia`].
4465    ///
4466    /// ```toml
4467    /// [[ingress]]
4468    /// provider  = "passway"
4469    /// machines  = ["us-west-011"]
4470    /// hostnames = ["api-staging.noisetable.com"]
4471    ///
4472    /// [[ingress]]
4473    /// provider  = "cloudflare-tunnel"
4474    /// via       = "passway"
4475    /// use       = "cloudflare-tunnel-staging"
4476    /// machines  = ["us-west-011"]
4477    /// hostnames = ["api-staging.noisetable.com"]
4478    /// ```
4479    ///
4480    /// Only a `cloudflare-tunnel` edge may carry it, and the mirror must also
4481    /// declare the edge it names, claiming the **same hostnames on the same
4482    /// machines** — the tunnel dials its own node's loopback demux, so a pair
4483    /// split across nodes routes to nothing. Refused otherwise by
4484    /// [`plan_ingress`](crate::reconciler::plan_ingress), naming both edges.
4485    ///
4486    /// `None` is every mirror written before R910.
4487    #[serde(default, skip_serializing_if = "Option::is_none")]
4488    pub via: Option<IngressVia>,
4489    /// The door behind a tunnel, spelled `[ingress.tunnel_door]` on the
4490    /// **passway** edge a `via = "passway"` tunnel stacks in front of (R910-F2).
4491    ///
4492    /// ```toml
4493    /// [ingress.tunnel_door]
4494    /// contact_email = "ops@example.com"
4495    /// zone_id       = "<cloudflare zone id>"
4496    /// token_secret  = "example/staging/cf-dns-token"
4497    /// ports         = { "staging.example.com" = 8445 }
4498    /// ```
4499    ///
4500    /// Required exactly when the edge is derived behind a tunnel, refused
4501    /// otherwise — see `partition`. `yah cloud apply` turns it into one scoped
4502    /// enrollment per hostname, which the tunnel's machines route, arm and
4503    /// issue from; see [`TunnelDoor`].
4504    #[serde(default, skip_serializing_if = "Option::is_none")]
4505    pub tunnel_door: Option<TunnelDoor>,
4506}
4507
4508/// What a passway door behind a cloudflare tunnel needs that a public door
4509/// does not (R910-F2): where its per-hostname loopback listeners are, and the
4510/// inputs to issue its own certificates by DNS-01 — the only ACME challenge
4511/// that works when nothing public reaches the node.
4512///
4513/// One door (one cold passway, one certificate) per hostname, which is the
4514/// per-tenant shape yubaba's tenant tier arms — so each hostname names its own
4515/// port rather than sharing one listener.
4516#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4517#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4518#[serde(deny_unknown_fields)]
4519pub struct TunnelDoor {
4520    /// ACME account contact.
4521    pub contact_email: String,
4522    /// Cloudflare zone id the `_acme-challenge` TXT records are written into.
4523    pub zone_id: String,
4524    /// Cluster secret holding a `Zone:DNS:Edit` token for that zone, declared
4525    /// in the machines' sovereign group with an access rule naming each
4526    /// hostname's door (`passway.<hostname>`).
4527    pub token_secret: String,
4528    /// Loopback port each hostname's door listens on — the demux backend the
4529    /// tunnel's SNI is spliced to. Every fronted hostname needs one.
4530    pub ports: std::collections::BTreeMap<String, u16>,
4531}
4532
4533impl IngressEdge {
4534    /// An edge with no selector — fronts every fronted slot, legal only when it
4535    /// is the mirror's only edge.
4536    pub fn all_slots(provider: IngressProvider, machines: Vec<String>) -> Self {
4537        Self {
4538            provider,
4539            machines,
4540            slots: Vec::new(),
4541            hostnames: Vec::new(),
4542            tunnel_id: None,
4543            provider_id: None,
4544            image: None,
4545            auth: None,
4546            via: None,
4547            tunnel_door: None,
4548        }
4549    }
4550
4551    /// Refuse `via` on an edge that cannot stack (R910). A passway edge
4552    /// terminates the connection itself, so `via` there would be ignored — and
4553    /// an ignored `via` is a mirror that reads as tunnel-fronted while
4554    /// publishing the door's own address.
4555    pub fn validate_via(&self) -> Result<()> {
4556        if self.via.is_some() && self.provider != IngressProvider::CloudflareTunnel {
4557            bail!(
4558                "{}: declares `via`, but only a `provider = \"cloudflare-tunnel\"` edge can stack \
4559                 in front of another front door — a {:?} edge terminates the connection itself. \
4560                 Move `via` to the tunnel edge, or drop it.",
4561                self.label(),
4562                self.provider.as_str()
4563            );
4564        }
4565        Ok(())
4566    }
4567
4568    /// Refuse an `[ingress.auth]` table that cannot produce a protected door
4569    /// (R870-F26). Called from [`MirrorConfig::ingress_edges`], so every reader
4570    /// of a mirror — plan, collate, `yah cloud validate`, apply — gets it.
4571    ///
4572    /// Two failures, and they fail in opposite directions, which is why both
4573    /// are here rather than left to the deploy:
4574    ///
4575    /// - **Auth on a non-passway edge.** Nothing downstream would read it, so
4576    ///   the operator gets a door they believe is protected and is not. Only
4577    ///   passway renders `PASSWAY_AUTH_*`; a cloudflare-tunnel edge publishes
4578    ///   through Cloudflare Access instead and has no place to put these.
4579    /// - **A present-but-empty field.** `Deserialize` already refuses a
4580    ///   *missing* one by name; [`PasswayAuth::validate`] covers the rest, and
4581    ///   is the same implementation `yah cloud ingress deploy` runs on its
4582    ///   flags — so the two doors cannot diverge on what counts as configured.
4583    pub fn validate_auth(&self) -> Result<()> {
4584        let Some(auth) = &self.auth else {
4585            return Ok(());
4586        };
4587        if !matches!(self.provider, IngressProvider::Passway) {
4588            bail!(
4589                "{}: declares `[ingress.auth]`, but only `provider = \"passway\"` renders the \
4590                 PASSWAY_AUTH_* variables — this edge would deploy a door with NO bearer auth \
4591                 while the mirror says otherwise. Move the auth to the passway edge, or drop it.",
4592                self.label()
4593            );
4594        }
4595        auth.validate(AuthSpelling::MirrorTable)
4596            .map_err(|why| anyhow::anyhow!("{}: {why}", self.label()))
4597    }
4598
4599    /// Refuse an `[ingress.tunnel_door]` that cannot produce a working door
4600    /// (R910-F2). Whether the edge is actually behind a tunnel is a property
4601    /// of the pair, so `partition` checks that half.
4602    pub fn validate_tunnel_door(&self) -> Result<()> {
4603        let Some(door) = &self.tunnel_door else {
4604            return Ok(());
4605        };
4606        if self.provider != IngressProvider::Passway {
4607            bail!(
4608                "{}: declares `[ingress.tunnel_door]`, but only the `provider = \"passway\"` edge a \
4609                 tunnel stacks in front of has a door to describe. Move it to that edge, or drop it.",
4610                self.label()
4611            );
4612        }
4613        for (field, value) in [
4614            ("contact_email", &door.contact_email),
4615            ("zone_id", &door.zone_id),
4616            ("token_secret", &door.token_secret),
4617        ] {
4618            if value.trim().is_empty() {
4619                bail!("{}: `[ingress.tunnel_door].{field}` is empty", self.label());
4620            }
4621        }
4622        if door.ports.is_empty() {
4623            bail!(
4624                "{}: `[ingress.tunnel_door].ports` is empty — each fronted hostname needs the \
4625                 loopback port its door listens on",
4626                self.label()
4627            );
4628        }
4629        let mut seen: std::collections::BTreeMap<u16, &str> = std::collections::BTreeMap::new();
4630        for (host, port) in &door.ports {
4631            if *port == 0 {
4632                bail!("{}: `[ingress.tunnel_door].ports.{host:?}` is 0", self.label());
4633            }
4634            if let Some(other) = seen.insert(*port, host) {
4635                bail!(
4636                    "{}: `[ingress.tunnel_door].ports` gives {other:?} and {host:?} the same port \
4637                     {port} — one held socket cannot be two hostnames' door",
4638                    self.label()
4639                );
4640            }
4641        }
4642        Ok(())
4643    }
4644
4645    /// `true` when this edge names which slots/hostnames it fronts.
4646    pub fn has_selector(&self) -> bool {
4647        !self.slots.is_empty() || !self.hostnames.is_empty()
4648    }
4649
4650    /// Does this edge claim the rule derived from `slot` publishing `hostname`?
4651    ///
4652    /// A selectorless edge claims everything; that is checked to be
4653    /// unambiguous (one edge only) before this is consulted.
4654    pub fn claims(&self, slot: &str, hostname: &str) -> bool {
4655        if !self.has_selector() {
4656            return true;
4657        }
4658        self.slots.iter().any(|s| s == slot) || self.hostnames.iter().any(|h| h == hostname)
4659    }
4660
4661    /// Human-readable identity for an error message — the provider plus
4662    /// whichever selector was written.
4663    pub fn label(&self) -> String {
4664        let sel = match (self.slots.is_empty(), self.hostnames.is_empty()) {
4665            (true, true) => "no selector".to_string(),
4666            (false, true) => format!("slots = {:?}", self.slots),
4667            (true, false) => format!("hostnames = {:?}", self.hostnames),
4668            (false, false) => format!("slots = {:?} + hostnames = {:?}", self.slots, self.hostnames),
4669        };
4670        format!("[[ingress]] provider = {:?} ({sel})", self.provider.as_str())
4671    }
4672}
4673
4674/// A mirror's `ingress` declaration, in either spelling.
4675///
4676/// The list is the general form; the bare provider is shorthand for the single
4677/// edge fronting everything, and is kept rather than migrated because it is the
4678/// honest spelling for the common case — one service, one front door. Both
4679/// normalize to the same `Vec<IngressEdge>` through
4680/// [`MirrorConfig::ingress_edges`], so nothing downstream branches on which was
4681/// written.
4682#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
4683#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4684#[serde(untagged)]
4685pub enum IngressDecl {
4686    /// `ingress = "passway"` — one edge fronting every fronted slot, placed by
4687    /// the sibling [`MirrorConfig::ingress_machines`].
4688    Provider(IngressProvider),
4689    /// `[[ingress]]` — one entry per declared edge.
4690    Edges(Vec<IngressEdge>),
4691}
4692
4693/// Hand-written because `#[serde(untagged)]` throws the real error away.
4694///
4695/// A derived untagged `Deserialize` tries each variant and, on failure, reports
4696/// only `data did not match any variant of untagged enum IngressDecl` — so a
4697/// misspelled `provider = "passwya"` says nothing about providers, nothing about
4698/// the legal values, and points at the `[[ingress]]` header rather than the
4699/// field. Dispatching on the input shape first means each arm's own error
4700/// survives: a bad string names the legal provider vocabulary, a bad edge table
4701/// names the offending field.
4702impl<'de> Deserialize<'de> for IngressDecl {
4703    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
4704        struct DeclVisitor;
4705
4706        impl<'de> serde::de::Visitor<'de> for DeclVisitor {
4707            type Value = IngressDecl;
4708
4709            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
4710                f.write_str(
4711                    "a provider name (`ingress = \"passway\"`) or a list of edge tables \
4712                     (`[[ingress]]`)",
4713                )
4714            }
4715
4716            fn visit_str<E: serde::de::Error>(self, v: &str) -> std::result::Result<Self::Value, E> {
4717                IngressProvider::deserialize(serde::de::value::StrDeserializer::new(v))
4718                    .map(IngressDecl::Provider)
4719            }
4720
4721            fn visit_seq<A: serde::de::SeqAccess<'de>>(
4722                self,
4723                seq: A,
4724            ) -> std::result::Result<Self::Value, A::Error> {
4725                Vec::<IngressEdge>::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
4726                    .map(IngressDecl::Edges)
4727            }
4728        }
4729
4730        d.deserialize_any(DeclVisitor)
4731    }
4732}
4733
4734/// No front door — the shape of every mirror that publishes to R2 behind a
4735/// Worker, or runs a mesh-only compute tier.
4736impl Default for IngressDecl {
4737    fn default() -> Self {
4738        Self::Provider(IngressProvider::None)
4739    }
4740}
4741
4742impl IngressDecl {
4743    /// `true` when this mirror declares no front door at all.
4744    pub fn is_absent(&self) -> bool {
4745        match self {
4746            Self::Provider(p) => !p.is_declared(),
4747            Self::Edges(e) => e.is_empty(),
4748        }
4749    }
4750}
4751
4752impl From<IngressProvider> for IngressDecl {
4753    fn from(p: IngressProvider) -> Self {
4754        Self::Provider(p)
4755    }
4756}
4757
4758/// A service mirror — the projection of a [`ServiceConfig`] onto concrete
4759/// infra. Lives at `.yah/services/<svc>/mirrors/<env>.toml`.
4760#[derive(Debug, Clone, Serialize, Deserialize)]
4761#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4762pub struct MirrorConfig {
4763    pub schema_version: u32,
4764    pub shape: MirrorShape,
4765    /// Public-ingress edges fronting this mirror (W267, W305 F2). Defaults to
4766    /// none.
4767    ///
4768    /// Two spellings, one meaning — see [`IngressDecl`]. `ingress = "passway"`
4769    /// is one edge fronting everything; `[[ingress]]` entries declare several,
4770    /// each naming its provider plus the slots or hostnames it fronts. Read it
4771    /// through [`ingress_edges`](Self::ingress_edges), never by matching on the
4772    /// enum, so the two spellings cannot drift apart.
4773    ///
4774    /// Declared at mirror scope rather than per provider slot because a front
4775    /// door does **fan-in**: one `cloudflared` (or one passway) on a node
4776    /// multiplexes every hostname→port rule it fronts, so pinning one to a
4777    /// single slot would mint one edge connection per slot for no gain. An
4778    /// edge's `slots` selector is the general form of that — it groups slots
4779    /// behind one front door, it does not split a front door per slot.
4780    #[serde(default, skip_serializing_if = "IngressDecl::is_absent")]
4781    pub ingress: IngressDecl,
4782    /// Machines the front door is placed on — **independent of where the
4783    /// fronted workload runs** (R330-F37).
4784    ///
4785    /// The single-edge spelling of [`IngressEdge::machines`]: it applies to the
4786    /// one edge `ingress = "<provider>"` declares, and combining it with
4787    /// `[[ingress]]` entries is an error rather than a silent precedence rule.
4788    ///
4789    /// Empty (the default) keeps the pre-existing behaviour: the front door is
4790    /// co-located with the fronted slot's own `machine` / `machines`. That was
4791    /// never a design choice, it was an artifact of bundles binding
4792    /// `127.0.0.1` — nothing off-node could reach a workload, so a proxy had to
4793    /// sit on top of it. R599-F12 landed mesh binding, which removes the
4794    /// constraint: passway is a reverse proxy, and a valid front door needs a
4795    /// cert and an upstream it can *reach*, not a local copy of the service.
4796    ///
4797    /// Listing several machines is what lets the ingress tier and the service
4798    /// tier scale independently — **N front doors over ONE deployment**. There
4799    /// is still exactly one rendered copy of the site, so fanning the front door
4800    /// out introduces no cache-coherence problem; that only appears if you
4801    /// deploy the *workload* to every node instead.
4802    ///
4803    /// ```toml
4804    /// ingress = "passway"
4805    /// ingress_machines = ["us-east-001", "us-west-001"]
4806    /// ```
4807    ///
4808    /// Declaring this without [`ingress`](Self::ingress) is an error, not a
4809    /// no-op — it always means the operator expected a front door somewhere.
4810    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4811    pub ingress_machines: Vec<String>,
4812    /// Provider slots, keyed by role (`"static"`, `"compute"`, …). Each value
4813    /// either references a provider declared under `.yah/infra/providers/` or
4814    /// inlines a local-only provider (no creds, no infra file).
4815    ///
4816    /// A role is normally service-wide — one slot serves every component that
4817    /// shares it — but [`ReconcileCtx::slot`](crate::reconciler::ReconcileCtx::slot)
4818    /// looks up the component-qualified key `"<role>:<component id>"` first.
4819    /// A service with two components of the same role (e.g. two
4820    /// `mesofact-static` components under one mirror) declares
4821    /// `providers."static:<id>"` per component to give each its own port;
4822    /// omitting the qualifier keeps the pre-existing single-slot behavior.
4823    #[serde(default)]
4824    pub providers: BTreeMap<String, MirrorProviderSlot>,
4825    /// Capability→driver bindings, keyed by **capability** (`"pg"`, `"s3"`, …)
4826    /// rather than by slot role (W265 §Drivers).
4827    ///
4828    /// This is the generalization of [`Self::providers`]: `providers.static` /
4829    /// `providers.object_store` are the special case where the slot name and
4830    /// the capability happen to coincide, and keying by capability is what stops
4831    /// the slot enum growing one arm per tier-specific implementation. A service
4832    /// says "I need pg"; the mirror says which implementation of pg *this tier*
4833    /// uses; the app talks the same wire protocol either way and never forks.
4834    ///
4835    /// ```toml
4836    /// [drivers.pg]
4837    /// kind = "local-pg-dev"     # dev  — kamaji-supervised loopback postgres
4838    ///
4839    /// [drivers.smtp]
4840    /// kind = "local-mailcrab"   # dev/pond — a catcher with a browsable inbox
4841    /// ```
4842    ///
4843    /// Additive in P1: `drivers` lands *alongside* `providers`, and migrating
4844    /// the existing `providers.static` / `providers.object_store` declarations
4845    /// over is a separate pass (W265 §"Open follow-ups"). A mirror that declares
4846    /// neither is unchanged.
4847    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
4848    pub drivers: BTreeMap<String, MirrorProviderSlot>,
4849    /// Per-environment alias overrides for `kind = "static-asset"` components.
4850    ///
4851    /// Keys are logical names (e.g. `"whisper-default"`); values must be
4852    /// filenames present in the component's `workload.toml` catalog.
4853    /// **Resolution only** — this table may never introduce a filename absent
4854    /// from the catalog. Validated against the workload catalog at sync time.
4855    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
4856    pub asset_aliases: BTreeMap<String, String>,
4857    /// Per-environment build overrides, keyed by **component id** (R905).
4858    ///
4859    /// A `[build]` block lives on the component's `workload.toml`, and a
4860    /// component is declared exactly once in `service.toml` — so without this
4861    /// table a service that deploys the same component to two environments
4862    /// builds it identically for both. That is wrong for any bundle whose
4863    /// contents depend on the tier it is being built *for*: noisetable's
4864    /// landing site bakes `NOISETABLE_API_ORIGIN` into the shipped JS, so the
4865    /// staging site was served a production API origin and every call from it
4866    /// was blocked by production CORS.
4867    ///
4868    /// ```toml
4869    /// # .yah/services/noisetable-marketing/mirrors/staging.toml
4870    /// [build.site]
4871    /// command = "bun run build:staging"
4872    ///
4873    /// # or, without a sibling script per environment:
4874    /// [build.site.env]
4875    /// NOISETABLE_API_ORIGIN = "https://api-staging.noisetable.com"
4876    /// ```
4877    ///
4878    /// The environment axis stays on the mirror, where `providers`, `drivers`
4879    /// and `ingress` already live, rather than growing an `env`-keyed table on
4880    /// the component's own `BuildConfig` — a per-component struct is the wrong
4881    /// place to enumerate environments, and doing it there would have made the
4882    /// mirror the *second* per-environment surface instead of the only one.
4883    ///
4884    /// Deliberately NOT overridable here: `out_dir`. Where a bundler writes is
4885    /// a property of the project's own toolchain, not of the tier it is built
4886    /// for, and it is read independently of `[build]` by the publish path
4887    /// (`read_workload_out_dir`, `collect_component_files`) — making it
4888    /// per-environment would mean threading the mirror into every one of those
4889    /// readers to buy a knob no tier needs.
4890    ///
4891    /// Keys are validated against the service's declared component ids at
4892    /// config load (`cross_ref_validate`), so a typo is a refusal rather than
4893    /// an override that silently never fires.
4894    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
4895    pub build: BTreeMap<String, MirrorBuildOverride>,
4896}
4897
4898/// One component's per-environment build override — the value type of
4899/// [`MirrorConfig::build`] (R905).
4900///
4901/// Every field is additive-or-replacing against the component's own
4902/// `workload.toml [build]` table; an empty override is indistinguishable from
4903/// declaring none.
4904#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
4905#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
4906#[serde(deny_unknown_fields)]
4907pub struct MirrorBuildOverride {
4908    /// Replaces `build.command` for this environment.
4909    ///
4910    /// Absent leaves the workload's own command in place — including absent,
4911    /// which means "this project has no external bundler step" and must keep
4912    /// meaning that (R838-B1). An override may therefore *introduce* a command
4913    /// where the workload's `[build]` table declares none — a deliberate
4914    /// per-tier opt-in to a bundler, since the only way to write it is to name
4915    /// one. A workload with no `[build]` table at all is still skipped
4916    /// wholesale: there is no `out_dir` to publish from, so an override there
4917    /// would have nothing to hand the publish step.
4918    #[serde(default, skip_serializing_if = "Option::is_none")]
4919    pub command: Option<String>,
4920    /// Replaces `build.render_command` — the data-only re-render
4921    /// (`revalidate_static`). Overridden separately from `command` because the
4922    /// two run at different times against different inputs; a tier that needs
4923    /// a different bundler command usually needs the same renderer.
4924    #[serde(default, skip_serializing_if = "Option::is_none")]
4925    pub render_command: Option<String>,
4926    /// Environment variables exported to the build (and render) subprocess,
4927    /// applied on top of the inherited environment.
4928    ///
4929    /// This is the knob for the common case — the command is the same, only a
4930    /// baked-in origin/flag differs — and it is what keeps a project from
4931    /// having to pre-declare one `build:<env>` script per environment before
4932    /// any environment can exist.
4933    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
4934    pub env: BTreeMap<String, String>,
4935}
4936
4937impl MirrorBuildOverride {
4938    /// `true` when this override would change nothing.
4939    pub fn is_empty(&self) -> bool {
4940        self.command.is_none() && self.render_command.is_none() && self.env.is_empty()
4941    }
4942
4943    /// The override's `env` table as the `Vec<(String, String)>` that both
4944    /// `ExecContext::with_env` and `std::process::Command::envs` want.
4945    pub fn env_pairs(&self) -> Vec<(String, String)> {
4946        self.env
4947            .iter()
4948            .map(|(k, v)| (k.clone(), v.clone()))
4949            .collect()
4950    }
4951}
4952
4953impl MirrorConfig {
4954    /// This environment's build override for `component_id`, if any.
4955    ///
4956    /// Returns `None` for an override that exists but changes nothing, so
4957    /// callers can treat `Some(_)` as "something differs here" without
4958    /// re-checking each field.
4959    pub fn build_override(&self, component_id: &str) -> Option<&MirrorBuildOverride> {
4960        self.build.get(component_id).filter(|o| !o.is_empty())
4961    }
4962}
4963
4964impl MirrorConfig {
4965    /// This mirror's declared edges, with both spellings normalized (W305 F2).
4966    ///
4967    /// The single place `ingress` + `ingress_machines` are reconciled, so no
4968    /// consumer has to know which spelling was written. Returns an empty vec
4969    /// when the mirror declares no front door.
4970    ///
4971    /// Errors are the declarations that cannot mean anything:
4972    ///
4973    /// - `ingress_machines` with no `ingress` — front-door placement with no
4974    ///   front door to place, always a typo (R330-F37);
4975    /// - `ingress_machines` alongside `[[ingress]]` — placement declared twice,
4976    ///   in a form where one silently wins;
4977    /// - `provider = "none"` on an edge — an edge that fronts with nothing.
4978    /// The `[[ingress]]` entries exactly as written, without normalizing the
4979    /// scalar spelling or validating anything.
4980    ///
4981    /// [`ingress_edges`](Self::ingress_edges) is the one to reach for; this
4982    /// exists for the checks that must run *before* a mirror is known to be
4983    /// well-formed — cross-reference validation walks every mirror in the
4984    /// workspace, and hard-failing there on an unrelated mirror's shape error
4985    /// would report the wrong file. Empty for the scalar spelling, which has no
4986    /// edge table to carry per-edge fields.
4987    pub fn ingress_edge_slice(&self) -> &[IngressEdge] {
4988        match &self.ingress {
4989            IngressDecl::Edges(edges) => edges,
4990            IngressDecl::Provider(_) => &[],
4991        }
4992    }
4993
4994    pub fn ingress_edges(&self) -> Result<Vec<IngressEdge>> {
4995        match &self.ingress {
4996            IngressDecl::Provider(p) if !p.is_declared() => {
4997                if !self.ingress_machines.is_empty() {
4998                    bail!(
4999                        "mirror declares `ingress_machines = {:?}` but no `ingress` provider — \
5000                         front-door placement with no front door to place. Add \
5001                         `ingress = \"passway\"` (or \"cloudflare-tunnel\"), or drop \
5002                         `ingress_machines`.",
5003                        self.ingress_machines
5004                    );
5005                }
5006                Ok(Vec::new())
5007            }
5008            IngressDecl::Provider(p) => Ok(vec![IngressEdge::all_slots(
5009                *p,
5010                self.ingress_machines.clone(),
5011            )]),
5012            IngressDecl::Edges(edges) => {
5013                if !self.ingress_machines.is_empty() {
5014                    bail!(
5015                        "mirror declares both `[[ingress]]` edges and the single-edge \
5016                         `ingress_machines = {:?}` — front-door placement stated twice. Move \
5017                         those names onto the edge they place: `machines = [...]` inside the \
5018                         `[[ingress]]` entry.",
5019                        self.ingress_machines
5020                    );
5021                }
5022                for edge in edges {
5023                    if !edge.provider.is_declared() {
5024                        bail!(
5025                            "{}: `provider = \"none\"` fronts nothing. An edge exists to name a \
5026                             front door — delete the entry instead.",
5027                            edge.label()
5028                        );
5029                    }
5030                    edge.validate_auth()?;
5031                    edge.validate_via()?;
5032                    edge.validate_tunnel_door()?;
5033                }
5034                Ok(edges.clone())
5035            }
5036        }
5037    }
5038
5039    /// Nodes this mirror's **passway** front doors are placed on, in
5040    /// declaration order and de-duplicated — or `None` when the mirror declares
5041    /// no passway edge at all.
5042    ///
5043    /// `Some(vec![])` is a real and different answer from `None`: a passway edge
5044    /// is declared but names no machine, so its placement falls back to the
5045    /// fronted slot's own. That fallback is placement *resolution* — it belongs
5046    /// to [`IngressRule::machines`](crate::reconciler::IngressRule::machines)
5047    /// and the plan it is built from, not to a mirror read in isolation — so it
5048    /// is reported as "declared, placement unknown from here" rather than
5049    /// half-derived. A caller that needs a node to dial has to say so.
5050    ///
5051    /// Passway-only because the caller is tenant DNS onboarding: only a passway
5052    /// node serves yubaba's `GET /domains/{domain}/onboarding`. A
5053    /// cloudflare-tunnel edge publishes through Cloudflare's own DNS and has no
5054    /// such record to hand a tenant, so folding its machines in would point the
5055    /// UI at a node that cannot answer.
5056    ///
5057    /// Read through [`ingress_edges`](Self::ingress_edges), so both spellings
5058    /// are covered by construction. A declaration that cannot mean anything
5059    /// (`ingress_machines` with no `ingress`, or both spellings at once) reads
5060    /// as `None` rather than propagating an error: those are reported by
5061    /// cross-reference validation, which can name the offending file.
5062    pub fn passway_machines(&self) -> Option<Vec<String>> {
5063        let edges = self.ingress_edges().ok()?;
5064        let mut declared = false;
5065        let mut machines: Vec<String> = Vec::new();
5066        for edge in edges
5067            .iter()
5068            .filter(|e| matches!(e.provider, IngressProvider::Passway))
5069        {
5070            declared = true;
5071            for m in &edge.machines {
5072                if !machines.iter().any(|seen| seen == m) {
5073                    machines.push(m.clone());
5074                }
5075            }
5076        }
5077        declared.then_some(machines)
5078    }
5079
5080    /// Parse a single `mirrors/<env>.toml` file.
5081    pub fn load(path: &Path) -> Result<Self> {
5082        let src =
5083            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
5084        toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
5085    }
5086
5087    /// Persist to `.yah/services/<service>/mirrors/<env>.toml`, creating the
5088    /// `mirrors/` directory if needed. Create-or-overwrite. The mirror file is
5089    /// named by `env` (its stem); `service` selects the owning service dir.
5090    pub fn save(&self, workspace_root: &Path, service: &str, env: &str) -> Result<()> {
5091        let dir = crate::paths::service_mirrors_dir(workspace_root, service);
5092        std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
5093        let path = crate::paths::service_mirror_toml(workspace_root, service, env);
5094        let s = toml::to_string_pretty(self)
5095            .with_context(|| format!("serializing mirror {service}/{env}"))?;
5096        std::fs::write(&path, s).with_context(|| format!("writing {}", path.display()))
5097    }
5098
5099    /// Remove `.yah/services/<service>/mirrors/<env>.toml`. Returns `false`
5100    /// when the file was already absent. Leaves the service and its other
5101    /// mirrors untouched.
5102    ///
5103    /// Also checks legacy stems (e.g. `local-sim` when `env = "pond"`) so
5104    /// deleting a canonical tier name removes whichever file exists on disk.
5105    pub fn delete(workspace_root: &Path, service: &str, env: &str) -> Result<bool> {
5106        let path = crate::paths::service_mirror_toml(workspace_root, service, env);
5107        if path.exists() {
5108            std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
5109            return Ok(true);
5110        }
5111        // Try legacy file stems for canonical tier names.
5112        let legacy: &[&str] = match env {
5113            "dev" => &["local"],
5114            "pond" => &["local-sim", "sim"],
5115            "prod" => &["cloud"],
5116            _ => &[],
5117        };
5118        for stem in legacy {
5119            let alt = crate::paths::service_mirror_toml(workspace_root, service, stem);
5120            if alt.exists() {
5121                std::fs::remove_file(&alt)
5122                    .with_context(|| format!("removing {}", alt.display()))?;
5123                return Ok(true);
5124            }
5125        }
5126        Ok(false)
5127    }
5128}
5129
5130/// A provider slot inside a [`MirrorConfig`]. Two shapes:
5131/// - **Reference** (`use = "<provider-id>"`) — point at an infra-declared
5132///   provider; extra fields are slot-specific (bucket, zone, dns, …).
5133/// - **Inline** (`kind = "local-*"`) — for providers that need no infra
5134///   declaration because they carry no credentials.
5135#[derive(Debug, Clone, Serialize, Deserialize)]
5136#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
5137#[serde(untagged)]
5138pub enum MirrorProviderSlot {
5139    Reference {
5140        #[serde(rename = "use")]
5141        provider_id: String,
5142        #[serde(flatten)]
5143        #[cfg_attr(
5144            feature = "json-schema",
5145            schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
5146        )]
5147        fields: BTreeMap<String, toml::Value>,
5148    },
5149    Inline {
5150        kind: Provider,
5151        #[serde(flatten)]
5152        #[cfg_attr(
5153            feature = "json-schema",
5154            schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
5155        )]
5156        fields: BTreeMap<String, toml::Value>,
5157    },
5158}
5159
5160impl MirrorProviderSlot {
5161    /// Provider id this slot references, or `None` for inline slots.
5162    pub fn provider_id(&self) -> Option<&str> {
5163        match self {
5164            Self::Reference { provider_id, .. } => Some(provider_id),
5165            Self::Inline { .. } => None,
5166        }
5167    }
5168
5169    /// Provider kind for inline slots, or `None` for reference slots
5170    /// (resolve via the referenced [`ProviderConfig`]).
5171    pub fn inline_kind(&self) -> Option<Provider> {
5172        match self {
5173            Self::Reference { .. } => None,
5174            Self::Inline { kind, .. } => Some(*kind),
5175        }
5176    }
5177
5178    pub fn fields(&self) -> &BTreeMap<String, toml::Value> {
5179        match self {
5180            Self::Reference { fields, .. } | Self::Inline { fields, .. } => fields,
5181        }
5182    }
5183
5184    /// F16 placement: parse the optional `required = { … }` sub-table on this
5185    /// slot. Returns `None` when absent or unparseable (callers treat as no
5186    /// constraint). See [`RequiredSpec`] for the field grammar.
5187    pub fn required(&self) -> Option<RequiredSpec> {
5188        let v = self.fields().get("required")?.clone();
5189        v.try_into().ok()
5190    }
5191}
5192
5193/// F16 placement constraints declared on a [`MirrorProviderSlot`], lives under
5194/// `[providers.<role>] required = { regions = [...], mesh_tags = [...] }` in
5195/// `mirrors/<env>.toml`.
5196///
5197/// Hard (must-satisfy) axes, all AND-ed together:
5198/// - `regions` / `zones` / `providers` — *membership*: the machine's
5199///   `region` / `zone` / `provider` must be one of the listed values.
5200/// - `mesh_tags` — *superset*: the machine's `mesh_tags` must contain every
5201///   listed tag.
5202/// - `memory_mb` / `cpu_millis` — *capacity floor* (R572-F5): the machine's
5203///   `allocatable` budget must cover the demand. `0` = no constraint.
5204/// - *taint repulsion* — **unconditional** (R876-B7): the machine must not
5205///   carry any taint that [`taint_effect`] classifies as
5206///   [`TaintEffect::Repels`], unless that exact key is listed in
5207///   [`Self::tolerates`]. This axis is not declared; it applies to every spec.
5208/// - `requires_taint` — *taint affinity* (R572-F5): the machine must carry
5209///   this taint key (in `taints` or `mesh_tags`). `None` = no affinity.
5210///
5211/// These are the **only** readers of [`MachineConfig::taints`], which is
5212/// what makes [`taint_effect`]'s closed vocabulary well-founded.
5213///
5214/// [`MachineConfig::sovereign_group`] is deliberately **not** an axis here and
5215/// must not become one (W305/R742-F1). A sovereign group is a blast radius,
5216/// not a filter: which quorum a box votes in says nothing about whether a
5217/// workload may run on it, and a dev-group node exists precisely so dev-mode
5218/// services — stateful ones included — can be scheduled onto it. Filtering on
5219/// it would re-make the mistake W305 exists to undo, where one mechanism
5220/// silently carried three unrelated properties.
5221///
5222/// An empty / zero / None on every axis means "no constraint on that axis".
5223/// A fully-unconstrained `RequiredSpec` matches every machine (see
5224/// [`RequiredSpec::is_unconstrained`]).
5225#[derive(Debug, Clone, Default, Serialize, Deserialize)]
5226#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
5227pub struct RequiredSpec {
5228    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5229    pub regions: Vec<String>,
5230    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5231    pub zones: Vec<String>,
5232    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5233    pub providers: Vec<String>,
5234    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5235    pub mesh_tags: Vec<String>,
5236
5237    /// R833-F8: **imperative** placement — the machine must be one of these by
5238    /// `name`. Empty (the default) = no constraint, which is every pre-R833-F8
5239    /// caller.
5240    ///
5241    /// This is the one axis that is not a *capability* the scheduler infers.
5242    /// The operator typed `--where=node:us-west-003`, so it composes with the
5243    /// other axes exactly like the rest — a named node that fails the capacity
5244    /// floor or carries a repelling taint still does not match, and the refusal
5245    /// names why rather than silently placing the work somewhere else.
5246    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5247    pub nodes: Vec<String>,
5248
5249    /// R572-F5: minimum memory (MiB) the target node must have in its
5250    /// declared `allocatable` budget. `0` = no constraint. Filled by
5251    /// [`CloudConfig::admit_workload`] from the workload's
5252    /// `memory_request_mb()` — its placement **request**, which is not the
5253    /// same number as the `resources.memory_mb` cgroup **ceiling**.
5254    #[serde(default, skip_serializing_if = "is_zero_u32")]
5255    pub memory_mb: u32,
5256    /// R572-F5: minimum CPU (millicores) the target node must have in its
5257    /// declared `allocatable` budget. `0` = no constraint. Filled by
5258    /// [`CloudConfig::admit_workload`] from the workload's `resources.cpu_millis`.
5259    #[serde(default, skip_serializing_if = "is_zero_u32")]
5260    pub cpu_millis: u32,
5261    /// R876-B7: repelling node taints this placement **opts back in to**.
5262    /// Each entry is a machine taint key spelled exactly as it appears in
5263    /// [`MachineConfig::taints`] — `"no-appliance"`, not `"appliance"` — so the
5264    /// node side and the workload side share one vocabulary and nothing has to
5265    /// translate between them.
5266    ///
5267    /// # Why this replaced `repel_archetypes`
5268    ///
5269    /// Repulsion used to be **opt-in-to-be-repelled**: the spec named the
5270    /// archetypes it was, and only a `no-<that archetype>` taint blocked it.
5271    /// That field was `#[serde(skip)]`, so a slot declared as
5272    /// `required = { ... }` in a mirror TOML always deserialized with it empty
5273    /// and [`Self::matches`] never read [`MachineConfig::taints`] at all. Node
5274    /// taints were therefore structurally inert for every mirror-declared
5275    /// placement, and inert *silently* — `no-server` is a legal key, so
5276    /// `yah cloud validate` passed and an operator draining a node before
5277    /// maintenance got a green run and a workload that never moved (R876-S2's
5278    /// drill measured exactly this against the real tree).
5279    ///
5280    /// The sense is now inverted, which is the only shape that can survive a
5281    /// field the wire does not carry: **repulsion is unconditional and
5282    /// toleration is declared.** A spec that says nothing is repelled by every
5283    /// repelling taint — the reading an operator writing `taints = ["no-server"]`
5284    /// on a machine already assumed they were getting.
5285    ///
5286    /// Toleration is per-key and absolute; there is no wildcard. Listing a key
5287    /// no machine declares is harmless and matches nothing.
5288    ///
5289    /// [`admission_spec`] fills this from the placement group's archetypes —
5290    /// every repelling key that is *not* the group's own class — which is what
5291    /// makes the `admit_workload` path behave identically across this change
5292    /// (R860-T4 / W338 §Placement consequences 2 still hold: the group's
5293    /// archetypes are the union over `local` requirement edges, so a `Server`
5294    /// bound to an `Appliance` tolerates neither `no-server` nor
5295    /// `no-appliance`).
5296    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5297    pub tolerates: Vec<String>,
5298    /// R572-F5: taint the workload requires the target node to carry
5299    /// (annotation `yah.placement.requires-taint`). The node must have the
5300    /// key in its `taints` list or `mesh_tags`. `None` = no affinity constraint.
5301    #[serde(skip)]
5302    pub requires_taint: Option<String>,
5303
5304    /// R844-F8: **how many** machines this constraint places onto. `None` — the
5305    /// only shape on disk before this field — means one, so every mirror in the
5306    /// tree resolves byte-identically across the change.
5307    ///
5308    /// This is not a match axis: it never appears in [`Self::matches`] and never
5309    /// changes whether a given machine qualifies. It is the *cardinality* of the
5310    /// answer, which is why it lives here rather than as another filter — the
5311    /// operator declares what is required and how many of it, and the scheduler
5312    /// picks which.
5313    ///
5314    /// **Declared, never inferred.** The count is emphatically not "how many
5315    /// machines happen to match": deriving it that way would make adding a box
5316    /// to the fleet silently scale a production front door. A constraint that
5317    /// matches four machines and asks for two places on two.
5318    ///
5319    /// **Fewer matches than asked is an error** ([`select_matching`]), not a
5320    /// partial placement. Placing one of two and reporting success is the
5321    /// subset-that-looks-like-it-worked failure R844 exists to close.
5322    ///
5323    /// Deliberately absent from [`Self::is_unconstrained`], which answers "does
5324    /// every machine match" — a question about the predicate, not the count. A
5325    /// `required = { replicas = 2 }` with no axis is therefore still
5326    /// unconstrained, and the deploy side still refuses it as an
5327    /// underspecified placement.
5328    #[serde(default, skip_serializing_if = "Option::is_none")]
5329    pub replicas: Option<u32>,
5330}
5331
5332impl RequiredSpec {
5333    /// How many machines this constraint places onto — [`Self::replicas`],
5334    /// resolving the absent case to the pre-R844-F8 answer of one.
5335    ///
5336    /// The single place that default is spelled, so the ingress planner and the
5337    /// deploy resolver cannot disagree about what "no replica count" means.
5338    pub fn replica_count(&self) -> usize {
5339        self.replicas.unwrap_or(1) as usize
5340    }
5341
5342    /// True when no *declared* axis carries a constraint — every untainted
5343    /// machine matches.
5344    ///
5345    /// R876-B7: taint repulsion is deliberately absent from this conjunction,
5346    /// unlike the `repel_archetypes` it replaced. Repulsion is no longer an axis
5347    /// a spec declares — it applies to every spec — so including it would make
5348    /// the answer a property of the fleet rather than of the constraint. Nor
5349    /// does [`Self::tolerates`] belong here: a toleration *widens* the candidate
5350    /// set, and the callers of this predicate ask "did the operator narrow
5351    /// anything" in order to refuse an underspecified placement. A slot that
5352    /// declares only a toleration has still narrowed nothing.
5353    pub fn is_unconstrained(&self) -> bool {
5354        self.regions.is_empty()
5355            && self.zones.is_empty()
5356            && self.providers.is_empty()
5357            && self.mesh_tags.is_empty()
5358            && self.nodes.is_empty()
5359            && self.memory_mb == 0
5360            && self.cpu_millis == 0
5361            && self.requires_taint.is_none()
5362    }
5363
5364    /// Whether `machine` satisfies every hard axis.
5365    ///
5366    /// - Membership axes (region/zone/provider): machine must carry the field
5367    ///   and it must appear in the constraint list.
5368    /// - `mesh_tags`: machine tags must be a superset of the required set.
5369    /// - **R572-F5 capacity floor**: `machine.allocatable.{memory,cpu}` must
5370    ///   cover `self.{memory,cpu}`. A machine with no `allocatable` block passes
5371    ///   unconditionally (capacity unknown → no constraint enforced).
5372    /// - **Taint repulsion (R876-B7)**: machine must not carry *any* taint that
5373    ///   [`taint_effect`] classifies as [`TaintEffect::Repels`], unless that key
5374    ///   is listed in [`Self::tolerates`]. Applied unconditionally — this is the
5375    ///   axis no spec has to declare, and the one that makes a node drainable.
5376    /// - **R572-F5 taint affinity**: if `requires_taint` is set, the machine
5377    ///   must carry that key in its `taints` list or `mesh_tags`.
5378    ///
5379    /// A [`TaintEffect::Attracts`] key (today just `public-ip`) does **not**
5380    /// repel: it is the affinity vocabulary, so reading it as repulsion would
5381    /// evict every workload from the three nodes that carry it. Only the
5382    /// `no-<archetype>` class repels, and [`taint_effect`] is the single
5383    /// authority on which is which — which is why
5384    /// [`crate::validate::check_inert_taints`] refuses to let an unclassifiable
5385    /// key be declared: it would read as a constraint and be none.
5386    pub fn matches(&self, machine: &MachineConfig) -> bool {
5387        let member_ok = |constraint: &[String], value: Option<&str>| -> bool {
5388            constraint.is_empty() || value.map_or(false, |v| constraint.iter().any(|c| c == v))
5389        };
5390
5391        // R833-F8: imperative node pin, checked first because it is the axis a
5392        // human asserted rather than one the scheduler derived — a refusal
5393        // should read "us-west-003 does not match" and not lead with a tag set
5394        // the operator never typed.
5395        if !member_ok(&self.nodes, Some(machine.name.as_str())) {
5396            return false;
5397        }
5398
5399        // Membership + mesh-tags (pre-existing axes).
5400        if !member_ok(&self.regions, machine.region.as_deref())
5401            || !member_ok(&self.zones, machine.zone.as_deref())
5402            || !member_ok(&self.providers, Some(machine.provider.as_str()))
5403            || !self
5404                .mesh_tags
5405                .iter()
5406                .all(|t| machine.mesh_tags.iter().any(|mt| mt == t))
5407        {
5408            return false;
5409        }
5410
5411        // R572-F5: capacity floor. Skipped when machine has no allocatable
5412        // declaration (unknown capacity → passes, consistent with pre-F5 behaviour).
5413        if self.memory_mb > 0 || self.cpu_millis > 0 {
5414            if let Some(alloc) = &machine.allocatable {
5415                if self.memory_mb > alloc.memory_mb || self.cpu_millis > alloc.cpu_millis {
5416                    return false;
5417                }
5418            }
5419        }
5420
5421        // R876-B7: taint repulsion, repel-by-default. Every repelling taint on
5422        // the machine blocks placement unless this spec names it in
5423        // `tolerates`. Driven off `machine.taints` rather than off a field of
5424        // `self`, which is the whole point: a spec that arrives by deserializing
5425        // a mirror's `required = {...}` carries no repulsion declaration and
5426        // never could, so making repulsion conditional on one made node taints
5427        // structurally unreadable on that path (R876-S2).
5428        for taint in &machine.taints {
5429            if !matches!(taint_effect(taint), TaintEffect::Repels(_)) {
5430                continue;
5431            }
5432            if !self.tolerates.iter().any(|t| t == taint) {
5433                return false;
5434            }
5435        }
5436
5437        // R572-F5: taint affinity. Machine must carry the required taint key
5438        // in either its `taints` list or `mesh_tags`.
5439        if let Some(req) = &self.requires_taint {
5440            let has_it = machine.taints.iter().any(|t| t == req)
5441                || machine.mesh_tags.iter().any(|t| t == req);
5442            if !has_it {
5443                return false;
5444            }
5445        }
5446
5447        true
5448    }
5449
5450    /// Human-readable summary of the constraints, for fail-loud error messages.
5451    /// Example: `required.regions=[us-west] + required.mesh_tags=[tag:cloud-runner]`.
5452    pub fn describe(&self) -> String {
5453        let mut parts = Vec::new();
5454        let mut push = |label: &str, vals: &[String]| {
5455            if !vals.is_empty() {
5456                parts.push(format!("required.{label}=[{}]", vals.join(",")));
5457            }
5458        };
5459        push("nodes", &self.nodes);
5460        push("regions", &self.regions);
5461        push("zones", &self.zones);
5462        push("providers", &self.providers);
5463        push("mesh_tags", &self.mesh_tags);
5464        // Kept with the other list axes, and NOT moved below: `push` borrows
5465        // `parts` mutably for as long as it is live, so interleaving it with the
5466        // direct `parts.push` calls under it does not compile.
5467        push("tolerates", &self.tolerates);
5468        if self.memory_mb > 0 {
5469            parts.push(format!("memory_mb>={}", self.memory_mb));
5470        }
5471        if self.cpu_millis > 0 {
5472            parts.push(format!("cpu_millis>={}", self.cpu_millis));
5473        }
5474        if let Some(req) = &self.requires_taint {
5475            parts.push(format!("requires_taint={req}"));
5476        }
5477        if parts.is_empty() {
5478            "no constraints".to_string()
5479        } else {
5480            parts.join(" + ")
5481        }
5482    }
5483}
5484
5485/// Which front door actually serves a domain's requests (R594-F12).
5486///
5487/// Every domain manifest must say this out loud. Before it existed the
5488/// difference between "R2 serves this hostname directly" and "a Worker
5489/// serves it" was expressed *only* by whether the file happened to carry
5490/// `[[routes]]` — so binding a route-carrying domain straight to R2 was
5491/// accepted silently and served 200s on its SSG half while losing clean
5492/// URLs, SPA shell fallback, deferred-route pointers and branded error
5493/// pages. All of those live in the Worker
5494/// (`oss/mesofact/packages/mesofact-edge/src/router.ts`) or in
5495/// mesofact-serve; an R2 custom domain has none of them.
5496///
5497/// The vocabulary mirrors `scripts/cf-apex-mode.sh` (worker | grey | orange)
5498/// — this moves the choice into the config where it can be checked instead
5499/// of living in one bash script.
5500///
5501/// A front door does **fan-in** only. The render cube (SSG / SPA / SSR /
5502/// deferred / 404) is mesofact's manifest, not this one — see W173 and
5503/// `.yah/docs/working/W267-sovereign-public-ingress.md`
5504/// §"Two front doors, one render contract".
5505#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
5506#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
5507#[serde(rename_all = "kebab-case")]
5508pub enum FrontDoor {
5509    /// Cloudflare R2 custom domain. Requests hit R2 objects with edge
5510    /// caching and nothing else — no clean URLs, no SPA fallback, no
5511    /// branded errors. Correct for a pure asset tier (W175's verdict for
5512    /// `cdn.yah.dev`) and wrong for anything that renders pages.
5513    /// Implies zero `[[routes]]` and no `worker_bundle_path`.
5514    BucketDirect,
5515    /// Cloudflare Worker generated from this manifest's route table.
5516    Worker,
5517    /// Sovereign L7 ingress — the `passway` proxy on yah-owned metal
5518    /// (`oss/passway`, W267). Same route table as `worker`; different
5519    /// machine terminates TLS.
5520    Passway,
5521}
5522
5523impl FrontDoor {
5524    /// Whether this front door consumes the manifest's `[[routes]]` table.
5525    /// `bucket-direct` does not; the other two are nothing without it.
5526    pub fn is_route_driven(self) -> bool {
5527        matches!(self, FrontDoor::Worker | FrontDoor::Passway)
5528    }
5529
5530    /// The manifest spelling, for error messages.
5531    pub fn as_str(self) -> &'static str {
5532        match self {
5533            FrontDoor::BucketDirect => "bucket-direct",
5534            FrontDoor::Worker => "worker",
5535            FrontDoor::Passway => "passway",
5536        }
5537    }
5538}
5539
5540/// A routing manifest for one domain, from `.yah/domains/<name>.toml`.
5541///
5542/// The domain manifest is the *only* place that knows about path routing:
5543/// services declare static/backend components by opaque ID, and this
5544/// manifest binds those components to URL paths on a public-facing
5545/// domain. Generated Worker bundles consume this. See
5546/// `.yah/docs/working/W118-yah-domain-tiers.md` (R347).
5547#[derive(Debug, Clone, Serialize, Deserialize)]
5548#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
5549pub struct DomainConfig {
5550    pub schema_version: u32,
5551    /// Stable identifier for this domain (file stem of the manifest).
5552    /// Example: `"yah-dev"` for the `yah.dev` zone.
5553    pub name: String,
5554    /// The fully-qualified domain this manifest routes for. Example:
5555    /// `"yah.dev"`, `"app.yah.dev"`.
5556    pub domain: String,
5557    /// Which front door serves this domain (R594-F12). **Required** — a
5558    /// default here would silently re-create the defect the field exists to
5559    /// close. Cross-checked against `routes` / `worker_bundle_path` by
5560    /// [`DomainConfig::validate_front_door`] at load time.
5561    pub front_door: FrontDoor,
5562    /// Public CDN bucket name. Static-mode route components publish into
5563    /// this bucket. Owned by the domain, *not* by any single service.
5564    pub cdn_bucket: String,
5565    /// Optional path (relative to workspace root) where the generated
5566    /// Worker bundle lands. `None` while the bundle generator (R347-F4)
5567    /// is still being wired up.
5568    #[serde(default, skip_serializing_if = "Option::is_none")]
5569    pub worker_bundle_path: Option<String>,
5570    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5571    pub routes: Vec<DomainRoute>,
5572}
5573
5574/// One entry in a [`DomainConfig`]'s route table.
5575///
5576/// The `mode` discriminator picks the variant's body via serde's
5577/// internally-tagged enum representation. Path patterns follow the
5578/// Worker convention: a trailing `*` matches everything underneath.
5579#[derive(Debug, Clone, Serialize, Deserialize)]
5580#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
5581pub struct DomainRoute {
5582    /// URL pattern this route matches. Examples: `"/"`, `"/dashboard/*"`,
5583    /// `"/camp/ws"`.
5584    pub path: String,
5585    /// Response headers the front door sets on every response served under
5586    /// this route (R746). Empty by default.
5587    ///
5588    /// This is the manifest's answer to "who decides a path's response
5589    /// headers". Before it existed the answer was *nobody*: a `_headers` file
5590    /// is a Cloudflare Pages / Netlify convention, and neither of this
5591    /// repo's front doors reads one — a Worker returns what it fetched from
5592    /// R2, and R2 serves only the object's own httpMetadata. So a site could
5593    /// carry a `_headers` file declaring COOP/COEP and ship without them,
5594    /// which is exactly how it was found: `SharedArrayBuffer` is simply
5595    /// absent in a document served cross-origin-isolation-free, with no
5596    /// error anywhere to say why.
5597    ///
5598    /// Deliberately a free-form `name -> value` map rather than named fields
5599    /// for the isolation headers: the domain manifest has no business
5600    /// knowing which headers a route's payload happens to need. Ordering
5601    /// follows the route table's own rule — first matching route wins, no
5602    /// merging across routes (see the Worker's `applyRouteHeaders`).
5603    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
5604    pub headers: BTreeMap<String, String>,
5605    #[serde(flatten)]
5606    pub mode: RouteMode,
5607}
5608
5609/// Body of a [`DomainRoute`]. Three modes on the wire, four shapes here:
5610/// - **Static** (`mode = "static"`, `component = …`) — the door serves a
5611///   published component's bytes from its CDN prefix. Component ref points at
5612///   a `kind = "mesofact-static"` (or similar) service component.
5613/// - **StaticBucket** (`mode = "static"`, `bucket = …`, R560-F13) — the door
5614///   serves an R2 bucket's ROOT, keyed by the request path minus its leading
5615///   slash with nothing stripped or prepended. For a CDN whose route prefixes
5616///   ARE its buckets' top-level key prefixes (cdn.noisetable.com), where xlb
5617///   derives a blob's key from the very URL path it serves at, so path == key
5618///   is an invariant rather than a convention.
5619/// - **Backend** — Worker proxies to an HTTP origin owned by a backend
5620///   component (yubaba workload, gateway, etc.).
5621/// - **Redirect** — Worker emits a 30x to the target URL. Used to keep
5622///   old paths alive during domain refactors.
5623///
5624/// The two static shapes are separate variants rather than one variant with
5625/// two optional fields, so "both" and "neither" have no spelling in Rust. The
5626/// TOML keeps one `mode = "static"` and the choice between `component` and
5627/// `bucket` is refused at parse time unless exactly one is present — see
5628/// [`RouteModeWire`].
5629#[derive(Debug, Clone, Serialize, Deserialize)]
5630#[serde(try_from = "RouteModeWire", into = "RouteModeWire")]
5631pub enum RouteMode {
5632    Static {
5633        /// Component reference `"<service>/<component-id>"`. Validated
5634        /// at [`CloudConfig::load`] time.
5635        component: String,
5636    },
5637    StaticBucket {
5638        /// R2 bucket name. Validated against R2's naming rule at parse time,
5639        /// which is also what makes [`crate::route_table::r2_binding_name`]
5640        /// injective.
5641        bucket: String,
5642    },
5643    Backend {
5644        /// Component reference `"<service>/<component-id>"`. Validated
5645        /// at [`CloudConfig::load`] time.
5646        component: String,
5647        /// Origin URL the Worker `fetch()`es. Schema-permissive — could
5648        /// be `https://...`, `wss://...`, or a yah-internal mesh URL
5649        /// resolved by yubaba.
5650        origin: String,
5651        /// The path prefix this route's `path` becomes at the origin, when the
5652        /// two differ (R898-F3). `/api/issues*` with `origin_path = "/issues"`
5653        /// proxies `/api/issues/42` to `<origin>/issues/42`.
5654        ///
5655        /// Absent means an identity proxy — the public path reaches the origin
5656        /// unchanged. It is declared here rather than derived because it is a
5657        /// fact about the *upstream's* path layout, which this repo does not
5658        /// own: the issue tracker serves `/issues` and the almanac serves
5659        /// `/releases`, and both are live contracts that predate the domain
5660        /// manifest. Compiled into [`RouteRewrite`](crate::route_table::RouteRewrite)
5661        /// by [`DomainConfig::route_table`](crate::route_table).
5662        #[serde(default, skip_serializing_if = "Option::is_none")]
5663        origin_path: Option<String>,
5664    },
5665    Redirect {
5666        /// Absolute URL or path the Worker emits a 30x to.
5667        target: String,
5668        /// HTTP status code. Defaults to 308 (permanent + method-preserving)
5669        /// so deprecations don't silently turn POSTs into GETs.
5670        #[serde(default = "default_redirect_status")]
5671        status: u16,
5672    },
5673}
5674
5675fn default_redirect_status() -> u16 {
5676    308
5677}
5678
5679/// The TOML/JSON shape of a [`RouteMode`]: one `mode = "static"` whose body
5680/// names a `component` OR a `bucket`.
5681///
5682/// Private to parsing. The two optional fields exist only here, and
5683/// `TryFrom` turns them into exactly one [`RouteMode`] variant or refuses the
5684/// manifest naming both keys — so the contradictory route never reaches a
5685/// consumer. It is also the JSON schema's source, since the schema describes
5686/// what an author writes.
5687#[derive(Debug, Clone, Serialize, Deserialize)]
5688#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
5689#[serde(tag = "mode", rename_all = "kebab-case")]
5690enum RouteModeWire {
5691    Static {
5692        /// Component reference `"<service>/<component-id>"`: serve that
5693        /// component's published bytes. Exactly one of `component` / `bucket`.
5694        #[serde(default, skip_serializing_if = "Option::is_none")]
5695        component: Option<String>,
5696        /// R2 bucket name: serve the bucket ROOT, the key being the request
5697        /// path minus its leading slash with nothing stripped or prepended
5698        /// (R560-F13). Requires `front_door = "worker"`. Exactly one of
5699        /// `component` / `bucket`.
5700        #[serde(default, skip_serializing_if = "Option::is_none")]
5701        bucket: Option<String>,
5702    },
5703    // Field docs below are the schema's text; they restate [`RouteMode`]'s.
5704    Backend {
5705        /// Component reference `"<service>/<component-id>"`. Validated
5706        /// at [`CloudConfig::load`] time.
5707        component: String,
5708        /// Origin URL the Worker `fetch()`es. Schema-permissive — could
5709        /// be `https://...`, `wss://...`, or a yah-internal mesh URL
5710        /// resolved by yubaba.
5711        origin: String,
5712        /// The path prefix this route's `path` becomes at the origin, when the
5713        /// two differ (R898-F3). `/api/issues*` with `origin_path = "/issues"`
5714        /// proxies `/api/issues/42` to `<origin>/issues/42`.
5715        ///
5716        /// Absent means an identity proxy — the public path reaches the origin
5717        /// unchanged. It is declared here rather than derived because it is a
5718        /// fact about the *upstream's* path layout, which this repo does not
5719        /// own: the issue tracker serves `/issues` and the almanac serves
5720        /// `/releases`, and both are live contracts that predate the domain
5721        /// manifest. Compiled into [`RouteRewrite`](crate::route_table::RouteRewrite)
5722        /// by [`DomainConfig::route_table`](crate::route_table).
5723        #[serde(default, skip_serializing_if = "Option::is_none")]
5724        origin_path: Option<String>,
5725    },
5726    Redirect {
5727        /// Absolute URL or path the Worker emits a 30x to.
5728        target: String,
5729        /// HTTP status code. Defaults to 308 (permanent + method-preserving)
5730        /// so deprecations don't silently turn POSTs into GETs.
5731        #[serde(default = "default_redirect_status")]
5732        status: u16,
5733    },
5734}
5735
5736impl TryFrom<RouteModeWire> for RouteMode {
5737    type Error = String;
5738
5739    fn try_from(wire: RouteModeWire) -> std::result::Result<Self, String> {
5740        Ok(match wire {
5741            RouteModeWire::Static {
5742                component: Some(component),
5743                bucket: None,
5744            } => Self::Static { component },
5745            RouteModeWire::Static {
5746                component: None,
5747                bucket: Some(bucket),
5748            } => {
5749                validate_r2_bucket_name(&bucket)?;
5750                Self::StaticBucket { bucket }
5751            }
5752            RouteModeWire::Static {
5753                component: Some(component),
5754                bucket: Some(bucket),
5755            } => {
5756                return Err(format!(
5757                    "a static route declares both component = \"{component}\" and bucket = \
5758                     \"{bucket}\" — declare exactly one: `component` serves a published \
5759                     component from its CDN prefix, `bucket` serves an R2 bucket root with \
5760                     the request path as the key"
5761                ))
5762            }
5763            RouteModeWire::Static {
5764                component: None,
5765                bucket: None,
5766            } => {
5767                return Err("a static route declares neither `component` nor `bucket` — \
5768                     declare exactly one"
5769                    .to_string())
5770            }
5771            RouteModeWire::Backend {
5772                component,
5773                origin,
5774                origin_path,
5775            } => Self::Backend {
5776                component,
5777                origin,
5778                origin_path,
5779            },
5780            RouteModeWire::Redirect { target, status } => Self::Redirect { target, status },
5781        })
5782    }
5783}
5784
5785impl From<RouteMode> for RouteModeWire {
5786    fn from(mode: RouteMode) -> Self {
5787        match mode {
5788            RouteMode::Static { component } => Self::Static {
5789                component: Some(component),
5790                bucket: None,
5791            },
5792            RouteMode::StaticBucket { bucket } => Self::Static {
5793                component: None,
5794                bucket: Some(bucket),
5795            },
5796            RouteMode::Backend {
5797                component,
5798                origin,
5799                origin_path,
5800            } => Self::Backend {
5801                component,
5802                origin,
5803                origin_path,
5804            },
5805            RouteMode::Redirect { target, status } => Self::Redirect { target, status },
5806        }
5807    }
5808}
5809
5810// Hand-written only because schemars 0.8 does not follow `#[serde(try_from)]`:
5811// a derive would describe the Rust variants (`static-bucket`), which no
5812// manifest may spell. The schema is the wire shape an author writes.
5813#[cfg(feature = "json-schema")]
5814impl schemars::JsonSchema for RouteMode {
5815    fn schema_name() -> String {
5816        "RouteMode".to_string()
5817    }
5818
5819    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
5820        <RouteModeWire as schemars::JsonSchema>::json_schema(gen)
5821    }
5822}
5823
5824/// R2's bucket naming rule: 3–63 characters of lowercase letters, digits and
5825/// hyphens, starting and ending with a letter or digit.
5826///
5827/// Checked at parse time rather than left to the deploy's 400, and load-bearing
5828/// beyond that: the Worker binding name derived from a bucket
5829/// ([`crate::route_table::r2_binding_name`]) only maps `-` to `_`, which is
5830/// collision-free exactly because a bucket name can carry no `_` of its own.
5831fn validate_r2_bucket_name(bucket: &str) -> std::result::Result<(), String> {
5832    let valid_chars = bucket
5833        .bytes()
5834        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
5835    let valid_ends = bucket.starts_with(|c: char| c.is_ascii_alphanumeric())
5836        && bucket.ends_with(|c: char| c.is_ascii_alphanumeric());
5837    if (3..=63).contains(&bucket.len()) && valid_chars && valid_ends {
5838        Ok(())
5839    } else {
5840        Err(format!(
5841            "bucket = \"{bucket}\" is not an R2 bucket name — 3 to 63 characters of \
5842             lowercase letters, digits and hyphens, starting and ending with a letter or digit"
5843        ))
5844    }
5845}
5846
5847/// Normalize a component `mount` to a storage/URL key prefix: strip the
5848/// surrounding slashes. `"/app"`, `"app/"`, `"/app/"` → `"app"`; `"/"`, `""`
5849/// → `""` (the service root).
5850///
5851/// One producer on purpose — the publisher's key prefix, the route-path
5852/// cross-check and the front door's key lookup must all agree on what `/app`
5853/// means down to the byte, and three copies of `trim_matches('/')` is how they
5854/// stop agreeing.
5855pub fn normalize_mount(raw: &str) -> String {
5856    raw.trim_matches('/').to_string()
5857}
5858
5859/// The key prefix a domain route pattern serves under: `"/*"` → `""`,
5860/// `"/app/*"` and `"/app"` → `"app"`. The twin of [`normalize_mount`] on the
5861/// routing side.
5862pub fn route_path_prefix(path: &str) -> String {
5863    normalize_mount(path.strip_suffix('*').unwrap_or(path))
5864}
5865
5866/// The route-driven domain whose route table binds a component of `service`,
5867/// if any. Used by static publishers to pick up the per-route response
5868/// headers a service's paths were declared with.
5869///
5870/// Deterministic by `BTreeMap` key order when more than one domain routes the
5871/// same service (a legitimate shape: an apex and a staging host serving one
5872/// bundle). Returning the first is a real limitation, not a considered
5873/// choice — the day two such domains want *different* headers for one
5874/// component, this needs the domain identity threaded in rather than inferred.
5875pub fn domain_serving_service<'a>(
5876    domains: &'a BTreeMap<String, DomainConfig>,
5877    service: &str,
5878) -> Option<&'a DomainConfig> {
5879    domains
5880        .values()
5881        .find(|d| d.front_door.is_route_driven() && d.serves_service(service))
5882}
5883
5884/// The `ROUTE_HEADERS` Worker-binding value for `service`, read from the
5885/// workspace's domain manifests. `"[]"` when no route-driven domain routes the
5886/// service, or when the one that does declares no headers.
5887///
5888/// R898-F1 widened this into
5889/// [`route_table_for_service`](crate::route_table::route_table_for_service):
5890/// same lookup, same `.yah/domains/` read, the whole compiled table
5891/// (`{path, mode, resolved origin, headers, auth}`) instead of its header
5892/// column. This spelling survives because it is what the *bindings* carry until
5893/// R898-F2/F3 widen those consumers — and because it needs no placement, which
5894/// the reconcilers calling it do not have.
5895///
5896/// Reads `.yah/domains/` directly rather than taking a loaded [`CloudConfig`]:
5897/// the static reconcilers are handed a per-component [`ReconcileCtx`], not the
5898/// whole workspace config, and threading a config reference through all 22 of
5899/// its construction sites to reach one string would be a wide change for a
5900/// narrow read. Manifest parse errors propagate — a domain file that no longer
5901/// loads is a deploy-stopping fact, not a reason to ship a Worker with the
5902/// headers quietly missing.
5903pub fn route_headers_for_service(workspace_root: &Path, service: &str) -> Result<String> {
5904    Ok(domain_for_service(workspace_root, service)?
5905        .as_ref()
5906        .map(DomainConfig::route_headers_json)
5907        .unwrap_or_else(|| "[]".to_string()))
5908}
5909
5910/// The route-driven domain manifest serving `service`, loaded from
5911/// `.yah/domains/`.
5912///
5913/// The whole manifest rather than one projection of it, for the consumer that
5914/// needs more than the header column: R898-F3's Worker reconciler compiles the
5915/// full route table (`{path, mode, origin, rewrite, headers, auth}`) and cannot
5916/// re-derive modes and origins from `route_headers_json`'s output. Same lookup
5917/// [`route_headers_for_service`] makes — it is now a caller of this.
5918pub fn domain_for_service(workspace_root: &Path, service: &str) -> Result<Option<DomainConfig>> {
5919    let domains = load_domains(&crate::paths::domains_dir(workspace_root))?;
5920    Ok(domain_serving_service(&domains, service).cloned())
5921}
5922
5923impl DomainConfig {
5924    /// Parse a single `.yah/domains/<name>.toml`, rejecting a manifest whose
5925    /// declared front door contradicts its route table
5926    /// ([`Self::validate_front_door`]).
5927    pub fn load(path: &Path) -> Result<Self> {
5928        let src =
5929            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
5930        let dom: Self =
5931            toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
5932        dom.validate_front_door()
5933            .with_context(|| format!("validating {}", path.display()))?;
5934        dom.validate_route_headers()
5935            .with_context(|| format!("validating {}", path.display()))?;
5936        Ok(dom)
5937    }
5938
5939    /// R594-F12 — the front door must agree with the rest of the manifest.
5940    ///
5941    /// - `bucket-direct` is an R2 custom domain: a Worker route table would
5942    ///   never be consulted, so declaring one means the author expected
5943    ///   Worker behaviour (clean URLs, SPA fallback, branded errors) from a
5944    ///   surface that cannot provide it. Rejected rather than silently
5945    ///   ignored. Same for `worker_bundle_path` — nothing would deploy it.
5946    /// - `worker` / `passway` with an empty route table is a silent 404
5947    ///   machine: the front door exists, has nothing to serve, and every
5948    ///   request falls through to the catch-all.
5949    ///
5950    /// Called from [`Self::load`], so both [`CloudConfig::load`] and
5951    /// [`CloudConfig::load_from_config_dir`] enforce it.
5952    pub fn validate_front_door(&self) -> Result<()> {
5953        match self.front_door {
5954            FrontDoor::BucketDirect => {
5955                if let Some(route) = self.routes.first() {
5956                    anyhow::bail!(
5957                        "front_door = \"bucket-direct\" but routes[0].path = \"{}\" — \
5958                         an R2 custom domain never consults a route table, so this \
5959                         route would silently do nothing (no clean URLs, no SPA \
5960                         fallback, no branded errors). Set front_door = \"worker\" \
5961                         (or \"passway\") to keep the routes, or drop the [[routes]] \
5962                         to keep the bucket-direct binding.",
5963                        route.path
5964                    );
5965                }
5966                if let Some(path) = &self.worker_bundle_path {
5967                    anyhow::bail!(
5968                        "front_door = \"bucket-direct\" but worker_bundle_path = \
5969                         \"{path}\" — nothing deploys a Worker bundle for a domain \
5970                         bound straight to R2"
5971                    );
5972                }
5973            }
5974            FrontDoor::Worker | FrontDoor::Passway => {
5975                // R560-F13: a bucket route is read through a Worker R2 binding.
5976                // Passway has no R2 read path, so accepting one there would
5977                // compile an entry the door cannot serve — refused naming the
5978                // route instead.
5979                if self.front_door == FrontDoor::Passway {
5980                    if let Some(route) = self
5981                        .routes
5982                        .iter()
5983                        .find(|r| matches!(r.mode, RouteMode::StaticBucket { .. }))
5984                    {
5985                        anyhow::bail!(
5986                            "front_door = \"passway\" but routes path = \"{}\" declares \
5987                             `bucket` — a bucket route is served through a Cloudflare Worker \
5988                             R2 binding, and passway has no R2 read path. Set front_door = \
5989                             \"worker\", or serve the path from a published `component`.",
5990                            route.path
5991                        );
5992                    }
5993                }
5994                if self.routes.is_empty() {
5995                    anyhow::bail!(
5996                        "front_door = \"{}\" but [[routes]] is empty — a front door \
5997                         with no route table is a silent 404 machine. Declare at \
5998                         least one route, or set front_door = \"bucket-direct\" if \
5999                         this domain really is served straight from R2.",
6000                        self.front_door.as_str()
6001                    );
6002                }
6003            }
6004        }
6005        Ok(())
6006    }
6007
6008    // `route_headers_json` — the header column of the compiled route table —
6009    // lives in `crate::route_table` alongside `route_table`, `RouteTable` and
6010    // the one serializer both projections share (R898-F1).
6011
6012    /// R749-T5 — everything [`Self::route_headers_json`] emits must be
6013    /// *applicable*, checked here where the table is PRODUCED.
6014    ///
6015    /// That method serializes a typed struct, so the table's JSON *shape* is
6016    /// sound by construction. Its contents are not: a route's `headers` map is
6017    /// a free-form `name -> value` read verbatim out of hand-written TOML, so
6018    /// `"Cross Origin Opener Policy"` (spaces instead of hyphens) or a value
6019    /// carrying a newline ships a structurally-valid table that neither front
6020    /// door can apply — and they fail *differently*, neither naming the
6021    /// manifest line responsible:
6022    ///
6023    /// - **passway** — `mesofact::route_headers::RouteHeaderTable::parse`
6024    ///   refuses the start, so the origin is simply down.
6025    /// - **worker** — `validateRouteHeaderTable` accepts it (it checks shape,
6026    ///   not header validity) and `applyRouteHeaders` then throws inside the
6027    ///   exported `fetch`, which is a 500 on every request, not the
6028    ///   serve-without-the-headers degradation that code intends.
6029    ///
6030    /// So the strictness lives at the producer: a table that cannot be applied
6031    /// fails `yah cloud apply` at manifest load, naming domain, route and
6032    /// header. This is deliberately *not* a second parser — the check is
6033    /// `HeaderName`/`HeaderValue`'s own, the very constructors the passway door
6034    /// runs on the far side, and route *matching* semantics stay defined once,
6035    /// at the doors. Only routes that contribute to the table are checked, so
6036    /// the invariant is exactly "`route_headers_json`'s output parses".
6037    ///
6038    /// Called from [`Self::load`], alongside [`Self::validate_front_door`].
6039    pub fn validate_route_headers(&self) -> Result<()> {
6040        use axum::http::{HeaderName, HeaderValue};
6041
6042        for route in self.routes.iter().filter(|r| !r.headers.is_empty()) {
6043            if route.path.is_empty() {
6044                anyhow::bail!(
6045                    "domain \"{}\" declares response headers on a route whose `path` is \
6046                     empty — a rule that matches nothing (or everything, depending on \
6047                     which front door reads it) is not a policy",
6048                    self.name
6049                );
6050            }
6051            for (name, value) in &route.headers {
6052                HeaderName::try_from(name.as_str()).with_context(|| {
6053                    format!(
6054                        "domain \"{}\" route \"{}\" declares {name:?}, which is not a valid \
6055                         HTTP header name — names are token characters only, so it is \
6056                         `Cross-Origin-Opener-Policy`, never `Cross Origin Opener Policy`",
6057                        self.name, route.path
6058                    )
6059                })?;
6060                HeaderValue::try_from(value.as_str()).with_context(|| {
6061                    format!(
6062                        "domain \"{}\" route \"{}\" declares {name} = {value:?}, which is not \
6063                         a valid HTTP header value — no newlines and no control characters",
6064                        self.name, route.path
6065                    )
6066                })?;
6067            }
6068        }
6069        Ok(())
6070    }
6071
6072    /// Whether this domain's route table binds any component of `service`.
6073    pub fn serves_service(&self, service: &str) -> bool {
6074        self.routes.iter().any(|r| {
6075            r.mode
6076                .component()
6077                .and_then(split_component_ref)
6078                .is_some_and(|(svc, _)| svc == service)
6079        })
6080    }
6081
6082    /// Persist to `.yah/domains/<name>.toml`, creating the domains
6083    /// directory if needed. Create-or-overwrite.
6084    pub fn save(&self, workspace_root: &Path) -> Result<()> {
6085        let dir = crate::paths::domains_dir(workspace_root);
6086        std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
6087        let path = crate::paths::domain_toml(workspace_root, &self.name);
6088        let s = toml::to_string_pretty(self)
6089            .with_context(|| format!("serializing domain {}", self.name))?;
6090        std::fs::write(&path, s).with_context(|| format!("writing {}", path.display()))
6091    }
6092
6093    /// Remove `.yah/domains/<name>.toml`. Returns `false` when the file
6094    /// was already absent.
6095    pub fn delete(workspace_root: &Path, name: &str) -> Result<bool> {
6096        let path = crate::paths::domain_toml(workspace_root, name);
6097        if !path.exists() {
6098            return Ok(false);
6099        }
6100        std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
6101        Ok(true)
6102    }
6103}
6104
6105impl RouteMode {
6106    /// Component reference for static/backend modes; `None` for redirects and
6107    /// bucket-root static routes, which reference no component.
6108    pub fn component(&self) -> Option<&str> {
6109        match self {
6110            Self::Static { component } | Self::Backend { component, .. } => Some(component),
6111            Self::StaticBucket { .. } | Self::Redirect { .. } => None,
6112        }
6113    }
6114}
6115
6116// ─── Service-group vault (R706 / W294) ───────────────────────────────────────
6117
6118/// A camp's declaration of one cluster secret, from
6119/// `.yah/infra/secrets/<slug>.toml`.
6120///
6121/// This is the *authoring* side of the fleet's cluster-secret store: it names
6122/// where the value lives in the camp (a `fob` vault slot), what the fleet should
6123/// call it, and — the point of R706 — which workloads are allowed to mount it.
6124///
6125/// The declaration is not itself the enforcement point. `yah cloud secret put`
6126/// reads this file, seals the vault value under the cluster KEK, and ships the
6127/// ciphertext **with its access rule** into raft; yubaba's `ClusterResolver`
6128/// evaluates the rule on the node at mount time. Deleting this file does not
6129/// revoke anything — the record in raft is the live authority. That asymmetry is
6130/// deliberate: a rule that lived only in a git-tracked camp file would be
6131/// trivially bypassed by anyone who could reach the fleet without the camp.
6132///
6133/// ```toml
6134/// #:schema ../../schema/secret.toml.schema.json
6135/// schema_version = 2
6136/// name = "cheers/cloud-admin/verify-key"
6137/// vault_slot = "cheers-cloud-admin-verify-key"
6138/// groups = ["prod"]
6139/// description = "Ed25519 public key yah-cloud-admin verifies operator PASETOs with"
6140///
6141/// [access]
6142/// workloads = [{ workload = "yah-cloud-admin" }]
6143///
6144/// [target]
6145/// kind = "file"
6146/// path = "/run/secrets/cheers-verify.key"
6147/// mode = 0o400
6148/// ```
6149#[derive(Debug, Clone, Serialize, Deserialize)]
6150#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
6151pub struct SecretConfig {
6152    pub schema_version: u32,
6153
6154    /// Logical cluster-secret key, as `SecretRef::Cluster { name }` spells it —
6155    /// e.g. `"tls/yah.dev/cert"`, `"cheers/cloud-admin/verify-key"`. May contain
6156    /// `/`; the file stem is a filesystem-safe slug and carries no meaning.
6157    pub name: String,
6158
6159    /// The `fob` vault slot in this camp holding the plaintext value. Read by
6160    /// `yah cloud secret put` at ship time and never recorded anywhere else — in
6161    /// particular the value is not in this file, so the declaration is safe to
6162    /// commit.
6163    pub vault_slot: String,
6164
6165    /// The sovereign groups this secret belongs to (R911-F8). Required and
6166    /// non-empty; each entry must be a `sovereign_group` that some
6167    /// `.yah/infra/machines/*.toml` declares ([`SecretConfig::load`] checks).
6168    ///
6169    /// Cluster secrets live per group in the fleet object store
6170    /// (`secrets/<group>/<name>.sealed`), so a declaration with no group has
6171    /// nowhere to land and nothing to be compared against. `yah cloud secret
6172    /// put` refuses a node whose `/raft/status` group is not listed here, and
6173    /// `status` counts a declaration only against nodes in one of these groups.
6174    pub groups: Vec<String>,
6175
6176    /// Human note for `yah cloud secret ls`. What this secret is and who minted
6177    /// it — the thing nobody remembers 6 months later.
6178    #[serde(default, skip_serializing_if = "Option::is_none")]
6179    pub description: Option<String>,
6180
6181    /// How the vault slot's text decodes into the bytes the consumer expects.
6182    ///
6183    /// `fob` slots hold strings, but plenty of real secrets are **binary** — an
6184    /// Ed25519 key is exactly 32 raw bytes, and `yah-cloud-admin` rejects a key
6185    /// file of any other length. Without this field the only way to ship such a
6186    /// key would be to hope its bytes happened to be valid UTF-8, which for a
6187    /// random key they are not.
6188    ///
6189    /// Defaults to [`SecretEncoding::Utf8`] — the right answer for tokens,
6190    /// passwords, and PEM, which is most secrets.
6191    #[serde(default)]
6192    pub encoding: SecretEncoding,
6193
6194    /// Who may mount it. Stamped onto the raft record verbatim.
6195    ///
6196    /// Defaults to [`SecretAccess::default`] — the deny-all empty allow-list. A
6197    /// declaration that forgets this field produces a secret nobody can mount,
6198    /// which is the correct direction to fail in.
6199    ///
6200    /// Three forms:
6201    ///
6202    /// ```toml
6203    /// access = "allow_any"                              # explicit escape hatch
6204    ///
6205    /// [access]                                          # named workloads
6206    /// workloads = [{ workload = "yah-cloud-admin" }]
6207    ///
6208    /// [access]                                          # signed recipes (R555-F5)
6209    /// recipes = [{ recipe = "rusty-v8-musl", key = "3d40…" }]
6210    /// ```
6211    ///
6212    /// Use the `recipes` form for a credential a **dispatched build** needs (the
6213    /// R2 write key, the cosign signing key). A remote QED run's workload name
6214    /// is a fresh `forge-<uuid>` every time, so `workloads` cannot name it and
6215    /// `allow_any` over-answers — see W235 §Seam (c) secret scoping. `key` is
6216    /// the hex Ed25519 public key from the recipe's `[admission]` block.
6217    #[serde(default)]
6218    pub access: SecretAccess,
6219
6220    /// Advisory: the mount shape a consuming workload should declare. Not
6221    /// enforced — yubaba honours whatever the `WorkloadSpec` asks for — but it
6222    /// lets `yah cloud secret put` print the exact `SecretMount` to paste, so
6223    /// the consumer and the declaration can't drift on path or mode.
6224    #[serde(default, skip_serializing_if = "Option::is_none")]
6225    pub target: Option<SecretTargetDecl>,
6226}
6227
6228/// How a [`SecretConfig`]'s vault text becomes the bytes delivered to the
6229/// container (R706 / W294).
6230#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
6231#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
6232#[serde(rename_all = "kebab-case")]
6233pub enum SecretEncoding {
6234    /// Ship the vault string's UTF-8 bytes verbatim. Tokens, passwords, PEM.
6235    #[default]
6236    Utf8,
6237    /// The vault string is hex; ship the decoded bytes. Use for binary key
6238    /// material — e.g. a raw Ed25519 key, which must land as exactly 32 bytes.
6239    Hex,
6240}
6241
6242/// Advisory mount shape on a [`SecretConfig`]. Mirrors
6243/// `workload_spec::SecretTarget` in a TOML-friendly, externally-tagged-free
6244/// shape (a `kind` discriminator reads better in a hand-written manifest than
6245/// serde's default enum encoding).
6246#[derive(Debug, Clone, Serialize, Deserialize)]
6247#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
6248#[serde(tag = "kind", rename_all = "kebab-case")]
6249pub enum SecretTargetDecl {
6250    /// Mounted as a tmpfs-backed file inside the container.
6251    File {
6252        /// Absolute path inside the container.
6253        path: String,
6254        /// Unix permission bits. Defaults to `0o400` (owner-read-only).
6255        #[serde(default = "default_secret_mode")]
6256        mode: u32,
6257    },
6258    /// Injected as an environment variable. Prefer `file` — env vars leak
6259    /// through subprocess environments and log dumps.
6260    EnvVar { name: String },
6261}
6262
6263fn default_secret_mode() -> u32 {
6264    0o400
6265}
6266
6267impl SecretTargetDecl {
6268    /// The `workload_spec` target this declaration describes.
6269    pub fn to_target(&self) -> workload_spec::SecretTarget {
6270        match self {
6271            Self::File { path, mode } => workload_spec::SecretTarget::File {
6272                path: path.into(),
6273                mode: *mode,
6274            },
6275            Self::EnvVar { name } => workload_spec::SecretTarget::EnvVar { name: name.clone() },
6276        }
6277    }
6278}
6279
6280/// The `schema_version` every [`SecretConfig`] must carry. Version 2 added the
6281/// required `groups` (R911-F8).
6282pub const SECRET_CONFIG_SCHEMA_VERSION: u32 = 2;
6283
6284impl SecretConfig {
6285    /// Parse a single `.yah/infra/secrets/<slug>.toml`.
6286    ///
6287    /// `sovereign_groups` is the camp's group vocabulary
6288    /// ([`CloudConfig::declared_sovereign_groups`]); every entry in `groups`
6289    /// must be one of them.
6290    pub fn load(path: &Path, sovereign_groups: &[&str]) -> Result<Self> {
6291        let src =
6292            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
6293        let cfg: Self =
6294            toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
6295        cfg.validate()
6296            .and_then(|()| cfg.validate_groups(sovereign_groups))
6297            .with_context(|| format!("validating {}", path.display()))?;
6298        Ok(cfg)
6299    }
6300
6301    /// Load every declaration in `dir`, keyed by logical secret name. A missing
6302    /// directory is an empty map (a camp with no cluster secrets is normal).
6303    ///
6304    /// Two files declaring the same `name` is a hard error, not a last-writer-
6305    /// wins merge: they would race to define the access rule for one record, and
6306    /// whichever lost would look correct in git while being inert on the fleet.
6307    pub fn load_dir(dir: &Path, sovereign_groups: &[&str]) -> Result<BTreeMap<String, Self>> {
6308        let mut out: BTreeMap<String, Self> = BTreeMap::new();
6309        if !dir.exists() {
6310            return Ok(out);
6311        }
6312        for entry in std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
6313            let path = entry?.path();
6314            if path.extension().is_none_or(|e| e != "toml") {
6315                continue;
6316            }
6317            let cfg = Self::load(&path, sovereign_groups)?;
6318            if let Some(prev) = out.insert(cfg.name.clone(), cfg) {
6319                anyhow::bail!(
6320                    "two secret declarations both claim name {:?} (one of them is {}); \
6321                     a cluster secret must have exactly one declaration so its access \
6322                     rule has one author",
6323                    prev.name,
6324                    path.display()
6325                );
6326            }
6327        }
6328        Ok(out)
6329    }
6330
6331    /// Reject declarations that would produce an unusable or dangerous record.
6332    ///
6333    /// Structural only: whether each of `groups` names a real sovereign group
6334    /// needs the camp's machines, so that half is [`Self::validate_groups`].
6335    pub fn validate(&self) -> Result<()> {
6336        if self.schema_version != SECRET_CONFIG_SCHEMA_VERSION {
6337            anyhow::bail!(
6338                "`schema_version` is {}, expected {SECRET_CONFIG_SCHEMA_VERSION}: version 2 \
6339                 added the required `groups = [\"<sovereign group>\", ...]` (R911-F8)",
6340                self.schema_version
6341            );
6342        }
6343        if self.name.trim().is_empty() {
6344            anyhow::bail!("`name` must not be empty");
6345        }
6346        if self.groups.is_empty() {
6347            anyhow::bail!(
6348                "`groups` must name at least one sovereign group: cluster secrets live per \
6349                 group (secrets/<group>/), so a declaration in no group has nowhere to land"
6350            );
6351        }
6352        if let Some(bad) = self.groups.iter().find(|g| g.trim().is_empty()) {
6353            anyhow::bail!("`groups` has an empty entry: {bad:?}");
6354        }
6355        let mut seen = std::collections::BTreeSet::new();
6356        if let Some(dup) = self.groups.iter().find(|g| !seen.insert(g.as_str())) {
6357            anyhow::bail!("`groups` lists {dup:?} twice");
6358        }
6359        if self.vault_slot.trim().is_empty() {
6360            anyhow::bail!(
6361                "`vault_slot` must not be empty — it names the fob slot holding the value"
6362            );
6363        }
6364        // A deny-all rule is a *valid* record (it is the fail-closed default the
6365        // resolver relies on) but it is never a useful thing to deliberately
6366        // ship, so catching it here saves an operator the round-trip of
6367        // deploying a workload that mysteriously can't see its own secret.
6368        if let SecretAccess::Workloads(entries) = &self.access {
6369            if entries.is_empty() {
6370                anyhow::bail!(
6371                    "`[access]` admits nobody: list the workloads allowed to mount {:?} \
6372                     (e.g. `workloads = [{{ workload = \"my-service\" }}]`), or set \
6373                     `access = \"allow_any\"` to store it unrestricted",
6374                    self.name
6375                );
6376            }
6377            if let Some(bad) = entries.iter().find(|e| e.workload.trim().is_empty()) {
6378                anyhow::bail!("`[access]` entry has an empty `workload` name: {bad:?}");
6379            }
6380        }
6381        Ok(())
6382    }
6383
6384    /// Every entry in `groups` must be a sovereign group the camp's machines
6385    /// declare. A typo would otherwise produce a declaration no node ever
6386    /// matches, which `put` would refuse everywhere and `status` would never
6387    /// count, without either one saying why.
6388    pub fn validate_groups(&self, sovereign_groups: &[&str]) -> Result<()> {
6389        if let Some(unknown) = self
6390            .groups
6391            .iter()
6392            .find(|g| !sovereign_groups.contains(&g.as_str()))
6393        {
6394            anyhow::bail!(
6395                "`groups` names {unknown:?}, which no .yah/infra/machines/*.toml declares as a \
6396                 `sovereign_group` (declared: {})",
6397                if sovereign_groups.is_empty() {
6398                    "(none)".to_string()
6399                } else {
6400                    sovereign_groups.join(", ")
6401                }
6402            );
6403        }
6404        Ok(())
6405    }
6406}
6407
6408#[cfg(test)]
6409mod secret_config_tests {
6410    use super::*;
6411
6412    fn parse(body: &str) -> Result<SecretConfig> {
6413        let cfg: SecretConfig = toml::from_str(body)?;
6414        cfg.validate()?;
6415        Ok(cfg)
6416    }
6417
6418    #[test]
6419    fn minimal_declaration_parses_with_narrow_defaults() {
6420        let cfg = parse(
6421            r#"
6422schema_version = 2
6423name = "svc/token"
6424vault_slot = "svc-token"
6425groups = ["prod"]
6426[access]
6427workloads = [{ workload = "svc" }]
6428"#,
6429        )
6430        .unwrap();
6431
6432        assert_eq!(cfg.groups, vec!["prod".to_string()]);
6433        assert_eq!(cfg.encoding, SecretEncoding::Utf8, "text is the default");
6434        assert!(cfg.target.is_none());
6435        // The omitted tenant/namespace must narrow to the singletons, not widen
6436        // to a wildcard.
6437        assert!(cfg
6438            .access
6439            .admits(&workload_spec::secrets::SecretConsumer::workload("svc")));
6440        assert!(!cfg
6441            .access
6442            .admits(&workload_spec::secrets::SecretConsumer::workload("other")));
6443    }
6444
6445    #[test]
6446    fn allow_any_is_spelled_as_a_bare_string() {
6447        // The operator-facing spelling, pinned: `access = "allow_any"`.
6448        let cfg = parse(
6449            r#"
6450schema_version = 2
6451name = "public/thing"
6452vault_slot = "slot"
6453groups = ["prod"]
6454access = "allow_any"
6455"#,
6456        )
6457        .unwrap();
6458        assert_eq!(cfg.access, SecretAccess::AllowAny);
6459    }
6460
6461    #[test]
6462    fn a_declaration_with_no_access_block_is_rejected() {
6463        // Omitting `[access]` defaults to deny-all, which is the correct
6464        // *runtime* default but never a correct authoring intent — so it must
6465        // not silently produce a secret nobody can mount.
6466        let err = parse(
6467            r#"
6468schema_version = 2
6469name = "svc/token"
6470vault_slot = "svc-token"
6471groups = ["prod"]
6472"#,
6473        )
6474        .unwrap_err()
6475        .to_string();
6476        assert!(err.contains("admits nobody"), "got {err}");
6477    }
6478
6479    #[test]
6480    fn empty_name_or_slot_is_rejected() {
6481        assert!(parse(
6482            r#"
6483schema_version = 2
6484name = ""
6485vault_slot = "slot"
6486groups = ["prod"]
6487access = "allow_any"
6488"#
6489        )
6490        .is_err());
6491        assert!(parse(
6492            r#"
6493schema_version = 2
6494name = "x"
6495vault_slot = "  "
6496groups = ["prod"]
6497access = "allow_any"
6498"#
6499        )
6500        .is_err());
6501    }
6502
6503    #[test]
6504    fn target_declaration_maps_onto_the_workload_spec_type() {
6505        let cfg = parse(
6506            r#"
6507schema_version = 2
6508name = "svc/token"
6509vault_slot = "slot"
6510groups = ["prod"]
6511access = "allow_any"
6512[target]
6513kind = "file"
6514path = "/run/secrets/t"
6515"#,
6516        )
6517        .unwrap();
6518        match cfg.target.unwrap().to_target() {
6519            workload_spec::SecretTarget::File { path, mode } => {
6520                assert_eq!(path, std::path::PathBuf::from("/run/secrets/t"));
6521                assert_eq!(mode, 0o400, "owner-read-only by default");
6522            }
6523            other => panic!("expected File, got {other:?}"),
6524        }
6525    }
6526
6527    #[test]
6528    fn load_dir_is_empty_for_a_camp_with_no_secrets() {
6529        let tmp = tempfile::TempDir::new().unwrap();
6530        assert!(SecretConfig::load_dir(&tmp.path().join("nope"), &["prod"])
6531            .unwrap()
6532            .is_empty());
6533    }
6534
6535    /// Write `body` to a temp file and run the real loader over it, so the
6536    /// assertions see the error chain an operator would.
6537    fn load_body(body: &str, sovereign_groups: &[&str]) -> Result<SecretConfig> {
6538        let tmp = tempfile::TempDir::new().unwrap();
6539        let path = tmp.path().join("decl.toml");
6540        std::fs::write(&path, body).unwrap();
6541        SecretConfig::load(&path, sovereign_groups)
6542    }
6543
6544    #[test]
6545    fn a_declaration_without_groups_fails_to_load_naming_the_field() {
6546        let err = format!(
6547            "{:#}",
6548            load_body(
6549                "schema_version = 2\nname = \"svc/token\"\nvault_slot = \"slot\"\n\
6550                 access = \"allow_any\"\n",
6551                &["prod"],
6552            )
6553            .unwrap_err()
6554        );
6555        assert!(err.contains("groups"), "must name the field: {err}");
6556        assert!(err.contains("decl.toml"), "must name the file: {err}");
6557    }
6558
6559    #[test]
6560    fn an_empty_or_duplicated_group_list_is_rejected() {
6561        let err = format!(
6562            "{:#}",
6563            load_body(
6564                "schema_version = 2\nname = \"s\"\nvault_slot = \"slot\"\ngroups = []\n\
6565                 access = \"allow_any\"\n",
6566                &["prod"],
6567            )
6568            .unwrap_err()
6569        );
6570        assert!(err.contains("at least one sovereign group"), "got {err}");
6571
6572        let err = format!(
6573            "{:#}",
6574            load_body(
6575                "schema_version = 2\nname = \"s\"\nvault_slot = \"slot\"\n\
6576                 groups = [\"prod\", \"prod\"]\naccess = \"allow_any\"\n",
6577                &["prod"],
6578            )
6579            .unwrap_err()
6580        );
6581        assert!(err.contains("twice"), "got {err}");
6582    }
6583
6584    #[test]
6585    fn a_group_no_machine_declares_is_rejected_naming_the_vocabulary() {
6586        let err = format!(
6587            "{:#}",
6588            load_body(
6589                "schema_version = 2\nname = \"s\"\nvault_slot = \"slot\"\n\
6590                 groups = [\"stagin\"]\naccess = \"allow_any\"\n",
6591                &["dev", "prod"],
6592            )
6593            .unwrap_err()
6594        );
6595        assert!(err.contains("\"stagin\""), "names the bad entry: {err}");
6596        assert!(err.contains("dev, prod"), "names what is declared: {err}");
6597    }
6598
6599    #[test]
6600    fn a_version_1_declaration_is_refused_naming_the_migration() {
6601        let err = format!(
6602            "{:#}",
6603            load_body(
6604                "schema_version = 1\nname = \"s\"\nvault_slot = \"slot\"\n\
6605                 groups = [\"prod\"]\naccess = \"allow_any\"\n",
6606                &["prod"],
6607            )
6608            .unwrap_err()
6609        );
6610        assert!(err.contains("schema_version") && err.contains("groups"), "got {err}");
6611    }
6612}
6613
6614/// Split a `"<service>/<component-id>"` ref. Returns `None` if the ref
6615/// isn't shaped like `service/component`.
6616pub(crate) fn split_component_ref(s: &str) -> Option<(&str, &str)> {
6617    let (svc, comp) = s.split_once('/')?;
6618    if svc.is_empty() || comp.is_empty() || comp.contains('/') {
6619        return None;
6620    }
6621    Some((svc, comp))
6622}
6623
6624#[cfg(test)]
6625mod tests {
6626    use super::*;
6627    use std::path::PathBuf;
6628
6629    fn make_machine(name: &str, mesh_tags: Vec<&str>) -> MachineConfig {
6630        MachineConfig {
6631            name: name.into(),
6632            provider: "hetzner".into(),
6633            location: Some("hil".into()),
6634            server_type: Some("ccx13".into()),
6635            hosts_mirrors: vec![],
6636            mesh_tags: mesh_tags.into_iter().map(String::from).collect(),
6637            region: None,
6638            zone: None,
6639            arch: None,
6640            bucket: None,
6641            vendor: None,
6642            nickname: None,
6643            legacy_hostkey_fingerprint: None,
6644            registration: Default::default(),
6645            ssh_keys: vec![],
6646            cloudflared: None,
6647            hosts_operator_bridge: false,
6648            connect: None,
6649            allocatable: None,
6650            taints: vec![],
6651            sovereign_group: None,
6652            sovereign_role: None,
6653            ingress_floating_ip: None,
6654        }
6655    }
6656
6657    /// Like [`make_machine`] but with explicit topology axes for F16 tests.
6658    fn make_machine_topo(
6659        name: &str,
6660        provider: &str,
6661        region: &str,
6662        mesh_tags: Vec<&str>,
6663    ) -> MachineConfig {
6664        MachineConfig {
6665            provider: provider.into(),
6666            region: Some(region.into()),
6667            zone: Some(region.into()),
6668            ..make_machine(name, mesh_tags)
6669        }
6670    }
6671
6672    fn make_empty_cfg(machines: Vec<MachineConfig>) -> CloudConfig {
6673        CloudConfig {
6674            workspace_root: PathBuf::new(),
6675            machines,
6676            providers: vec![],
6677            machine_origins: BTreeMap::new(),
6678            provider_origins: BTreeMap::new(),
6679            recovery_measurements: BTreeMap::new(),
6680            services: BTreeMap::new(),
6681            domains: BTreeMap::new(),
6682            legacy_mirrors: vec![],
6683            workloads: vec![],
6684            topology: TopologyConfig::default(),
6685        }
6686    }
6687
6688    #[test]
6689    fn required_spec_parses_from_provider_fields() {
6690        let toml_src = r#"
6691use = "hetzner-primary"
6692[required]
6693mesh_tags = ["tag:cloud-runner"]
6694"#;
6695        let slot: MirrorProviderSlot = toml::from_str(toml_src).unwrap();
6696        let req = slot.required().expect("required block present");
6697        assert_eq!(req.mesh_tags, vec!["tag:cloud-runner"]);
6698    }
6699
6700    #[test]
6701    fn required_spec_absent_when_field_missing() {
6702        let slot: MirrorProviderSlot = toml::from_str(r#"use = "hetzner-primary""#).unwrap();
6703        assert!(slot.required().is_none());
6704    }
6705
6706    #[test]
6707    fn db_catalog_parses_all_env_blocks() {
6708        // W241 / R571-F8: a service.toml [db] table with dev/pond/cloud.
6709        let toml_src = r#"
6710schema_version = 1
6711name = "scrabcake"
6712domain = "scrabcake.net.yah.dev"
6713
6714[[db.dev]]
6715name = "main"
6716path = "data/dev.sqlite"
6717
6718[[db.pond]]
6719name = "main"
6720port = 5433
6721
6722[[db.pond]]
6723name = "pg"
6724port = 5432
6725kind = "postgres"
6726
6727[[db.cloud]]
6728name = "main"
6729url = "libsql://scrabcake.turso.io"
6730auth_token_env = "SCRABCAKE_TURSO_TOKEN"
6731"#;
6732        let svc: ServiceConfig = toml::from_str(toml_src).unwrap();
6733        assert_eq!(svc.db.dev.len(), 1);
6734        assert_eq!(svc.db.dev[0].path, "data/dev.sqlite");
6735        assert_eq!(svc.db.pond.len(), 2);
6736        assert_eq!(svc.db.pond[0].port, Some(5433));
6737        assert_eq!(svc.db.pond[0].kind, PondDbKind::Turso); // default
6738        assert_eq!(svc.db.pond[1].kind, PondDbKind::Postgres);
6739        assert_eq!(
6740            svc.db.cloud[0].auth_token_env.as_deref(),
6741            Some("SCRABCAKE_TURSO_TOKEN")
6742        );
6743    }
6744
6745    #[test]
6746    fn service_without_db_table_has_empty_catalog() {
6747        let svc: ServiceConfig =
6748            toml::from_str("schema_version = 1\nname = \"s\"\ndomain = \"s.dev\"\n").unwrap();
6749        assert!(svc.db.is_empty());
6750        // And an empty [db] must not appear when re-serialized.
6751        let out = toml::to_string(&svc).unwrap();
6752        assert!(
6753            !out.contains("[db"),
6754            "empty db table should be skipped: {out}"
6755        );
6756    }
6757
6758    #[test]
6759    fn camp_shared_cloud_toml_parses() {
6760        let src = r#"
6761[[cloud]]
6762name = "analytics"
6763url = "postgres://shared/analytics"
6764"#;
6765        let shared: CampCloudDbs = toml::from_str(src).unwrap();
6766        assert_eq!(shared.cloud.len(), 1);
6767        assert_eq!(shared.cloud[0].name, "analytics");
6768    }
6769
6770    #[test]
6771    fn resolve_machine_by_mesh_tags_superset_match() {
6772        let cfg = make_empty_cfg(vec![
6773            make_machine("yah-bnt-1", vec!["tag:primary-yah", "tag:tier-scratch"]),
6774            make_machine("us-west-001", vec!["tag:primary-yah", "tag:cloud-runner"]),
6775        ]);
6776        let picked = cfg
6777            .resolve_machine_by_mesh_tags(&["tag:cloud-runner".into()])
6778            .map(|m| m.name.as_str());
6779        assert_eq!(picked, Some("us-west-001"));
6780    }
6781
6782    #[test]
6783    fn resolve_machine_by_mesh_tags_returns_none_when_no_match() {
6784        let cfg = make_empty_cfg(vec![make_machine("yah-bnt-1", vec!["tag:primary-yah"])]);
6785        assert!(cfg
6786            .resolve_machine_by_mesh_tags(&["tag:cloud-runner".into()])
6787            .is_none());
6788    }
6789
6790    // ─── R590-F1 mesh-tag node-selector admission ───────────────────────────
6791
6792    /// Build a forge WorkloadSpec carrying the R594 node-selector annotation.
6793    /// `selector` is the comma-joined mesh-tag set; `None` omits the annotation
6794    /// entirely (pre-R594 "no constraint").
6795    fn ws_with_selector(selector: Option<&str>) -> WorkloadSpec {
6796        use workload_spec::{ImageRef, TierTag};
6797        let mut ws = WorkloadSpec::for_forge(
6798            "R590-F1-test",
6799            ImageRef {
6800                registry: "docker.io".into(),
6801                repository: "library/busybox".into(),
6802                tag: "latest".into(),
6803                digest: workload_spec::testing::test_digest(),
6804            },
6805            TierTag("infra".into()),
6806            vec![],
6807        );
6808        if let Some(sel) = selector {
6809            ws.annotations.insert(
6810                velveteen_exec::remote::NODE_SELECTOR_MESH_TAGS_ANNOTATION.into(),
6811                sel.into(),
6812            );
6813        }
6814        ws
6815    }
6816
6817    /// The build-worker fleet shape: one x86 node (us-west-002) and one arm
6818    /// node (a Pi5), both carrying `tag:build-worker`.
6819    fn build_worker_fleet() -> CloudConfig {
6820        make_empty_cfg(vec![
6821            make_machine("us-west-002", vec!["tag:build-worker", "arch:x86"]),
6822            make_machine("pi5-001", vec!["tag:build-worker", "arch:arm"]),
6823        ])
6824    }
6825
6826    #[test]
6827    fn admit_workload_routes_amd64_to_x86_worker() {
6828        let cfg = build_worker_fleet();
6829        let ws = ws_with_selector(Some("tag:build-worker,arch:x86"));
6830        let picked = cfg.admit_workload(&ws).unwrap();
6831        assert_eq!(picked.name, "us-west-002");
6832    }
6833
6834    #[test]
6835    fn admit_workload_routes_arm64_to_pi5_worker() {
6836        let cfg = build_worker_fleet();
6837        let ws = ws_with_selector(Some("tag:build-worker,arch:arm"));
6838        let picked = cfg.admit_workload(&ws).unwrap();
6839        assert_eq!(picked.name, "pi5-001");
6840    }
6841
6842    /// A forge run must be admissible on a build-worker smaller than its own
6843    /// cgroup ceiling.
6844    ///
6845    /// The fleet's arm build-workers are 8 GiB Pi-5s and `for_forge` sets a
6846    /// 32 GiB ceiling, so while admission read `resources.memory_mb` as the
6847    /// capacity floor this returned "no candidates" and *every* offloaded qed
6848    /// step to those nodes failed at dispatch — measured on desktop-release run
6849    /// b04cef47, where the aarch64-linux row died in 1.6s. The other
6850    /// build-workers (16 GiB us-west-003, and the arm Pi-5s) were excluded the
6851    /// same way, leaving one 47 GiB node as the fleet's only legal target for
6852    /// remote CI.
6853    #[test]
6854    fn admit_workload_places_a_forge_run_on_a_worker_smaller_than_its_ceiling() {
6855        let mut pi = make_machine("pi5-001", vec!["tag:build-worker", "arch:arm"]);
6856        pi.allocatable = Some(NodeAllocatable {
6857            memory_mb: 8192,
6858            cpu_millis: 4000,
6859        });
6860        let cfg = make_empty_cfg(vec![pi]);
6861
6862        let ws = ws_with_selector(Some("tag:build-worker,arch:arm"));
6863        assert!(
6864            ws.resources.memory_mb > 8192,
6865            "precondition: the ceiling must exceed the node, or this proves nothing"
6866        );
6867
6868        let picked = cfg
6869            .admit_workload(&ws)
6870            .expect("an 8 GiB build-worker must admit a forge run");
6871        assert_eq!(picked.name, "pi5-001");
6872    }
6873
6874    /// The floor is still enforced — the fix separates two numbers, it does not
6875    /// disable the R572-F5 capacity check.
6876    #[test]
6877    fn admit_workload_still_rejects_a_node_below_the_declared_request() {
6878        let mut tiny = make_machine("tiny-001", vec!["tag:build-worker", "arch:arm"]);
6879        tiny.allocatable = Some(NodeAllocatable {
6880            memory_mb: 512,
6881            cpu_millis: 4000,
6882        });
6883        let cfg = make_empty_cfg(vec![tiny]);
6884
6885        let ws = ws_with_selector(Some("tag:build-worker,arch:arm"));
6886        assert!(
6887            cfg.admit_workload(&ws).is_err(),
6888            "a 512 MiB node cannot satisfy a 2 GiB forge request"
6889        );
6890    }
6891
6892    // ─── R833-F8 imperative node-selector admission ─────────────────────────
6893
6894    /// Build a forge WorkloadSpec carrying the R833-F8 imperative node
6895    /// selector — the operator's `--where=node:<machine>`.
6896    fn ws_pinned_to(node: &str) -> WorkloadSpec {
6897        let mut ws = ws_with_selector(None);
6898        ws.annotations.insert(
6899            velveteen_exec::remote::NODE_SELECTOR_NODE_ANNOTATION.into(),
6900            node.into(),
6901        );
6902        ws
6903    }
6904
6905    /// The ticket's acceptance shape: a named node wins over the
6906    /// declaration-order tie-break that would otherwise decide placement.
6907    /// `us-west-002` is declared first and carries every tag, so an inferred
6908    /// placement lands there; the pin must reach `pi5-001` regardless.
6909    #[test]
6910    fn admit_workload_honours_an_explicitly_named_node() {
6911        let cfg = build_worker_fleet();
6912        assert_eq!(
6913            cfg.admit_workload(&ws_with_selector(Some("tag:build-worker")))
6914                .unwrap()
6915                .name,
6916            "us-west-002",
6917            "precondition: inference elects the first-declared node",
6918        );
6919        assert_eq!(
6920            cfg.admit_workload(&ws_pinned_to("pi5-001")).unwrap().name,
6921            "pi5-001",
6922        );
6923    }
6924
6925    /// A pin at a machine that is not declared fails loud, naming the
6926    /// constraint and the pool — the operator mistyped a node, and silently
6927    /// running the build somewhere else is the one outcome that must not
6928    /// happen.
6929    #[test]
6930    fn admit_workload_refuses_a_node_that_is_not_declared() {
6931        let cfg = build_worker_fleet();
6932        let err = cfg
6933            .admit_workload(&ws_pinned_to("us-west-404"))
6934            .unwrap_err()
6935            .to_string();
6936        assert!(err.contains("required.nodes=[us-west-404]"), "{err}");
6937        assert!(err.contains("us-west-002"), "the pool must be named: {err}");
6938    }
6939
6940    /// The pin narrows the candidate set; it does not suspend the other axes.
6941    /// A named node that cannot fit the workload still refuses, rather than
6942    /// being handed work it has no room for.
6943    #[test]
6944    fn a_pinned_node_is_still_checked_against_capacity() {
6945        let mut tiny = make_machine("tiny-001", vec!["tag:build-worker", "arch:arm"]);
6946        tiny.allocatable = Some(NodeAllocatable {
6947            memory_mb: 512,
6948            cpu_millis: 4000,
6949        });
6950        let cfg = make_empty_cfg(vec![tiny]);
6951        assert!(cfg.admit_workload(&ws_pinned_to("tiny-001")).is_err());
6952    }
6953
6954    /// Inference is untouched: with no node annotation the `nodes` axis is
6955    /// empty, which is "no constraint" — every pre-R833-F8 workload is admitted
6956    /// exactly as before.
6957    #[test]
6958    fn an_unpinned_workload_carries_no_node_constraint() {
6959        assert!(node_selector_node(&ws_with_selector(Some("arch:x86"))).is_none());
6960        assert_eq!(
6961            node_selector_node(&ws_pinned_to("us-west-003")).as_deref(),
6962            Some("us-west-003")
6963        );
6964        assert!(RequiredSpec::default().is_unconstrained());
6965        assert!(!RequiredSpec {
6966            nodes: vec!["us-west-003".into()],
6967            ..Default::default()
6968        }
6969        .is_unconstrained());
6970    }
6971
6972    #[test]
6973    fn admit_workload_rejects_node_missing_required_tag() {
6974        // Only an arm worker exists; an x86 build must NOT land on it.
6975        let cfg = make_empty_cfg(vec![make_machine(
6976            "pi5-001",
6977            vec!["tag:build-worker", "arch:arm"],
6978        )]);
6979        let ws = ws_with_selector(Some("tag:build-worker,arch:x86"));
6980        assert!(cfg.admit_workload(&ws).is_err());
6981    }
6982
6983    /// R555-S1 regression: with TWO nodes carrying the same tag set, which one
6984    /// admits must be decided by *declaration order* (file name), which is the
6985    /// contract `admit_workload` documents — not by `read_dir` order, which is
6986    /// filesystem-dependent and can change when an unrelated file appears in
6987    /// the directory. Written creation-order-reversed so a filesystem that
6988    /// yields creation order (rather than sorted order) trips it without the
6989    /// sort in `load_dir`.
6990    ///
6991    /// Live consequence this guards: `.yah/infra/machines/` carries both
6992    /// us-west-002 and us-west-003 on `[tag:build-worker, arch:x86, os:linux]`,
6993    /// so an x86 QED offload has two equal candidates. Unstable selection means
6994    /// a retried build cannot be relied on to land back on the node whose
6995    /// working state it left behind.
6996    #[test]
6997    fn equally_matching_machines_admit_in_file_name_order() {
6998        let tmp = tempfile::TempDir::new().unwrap();
6999        let machines = tmp.path().join(".yah").join("infra").join("machines");
7000        std::fs::create_dir_all(&machines).unwrap();
7001        let toml_for = |name: &str| {
7002            format!(
7003                r#"name = "{name}"
7004provider = "static"
7005mesh_tags = ["tag:build-worker", "arch:x86"]
7006"#
7007            )
7008        };
7009        // Reverse-of-sorted creation order on purpose.
7010        std::fs::write(machines.join("b-second.toml"), toml_for("b-second")).unwrap();
7011        std::fs::write(machines.join("a-first.toml"), toml_for("a-first")).unwrap();
7012
7013        let cfg = CloudConfig::load(tmp.path()).unwrap();
7014        assert_eq!(
7015            cfg.machines.iter().map(|m| m.name.as_str()).collect::<Vec<_>>(),
7016            vec!["a-first", "b-second"],
7017            "machines must load in file-name order, not read_dir order"
7018        );
7019
7020        let ws = ws_with_selector(Some("tag:build-worker,arch:x86"));
7021        assert_eq!(cfg.admit_workload(&ws).unwrap().name, "a-first");
7022
7023        // R605-T14: the same two nodes, seen as the pool they are. The head is
7024        // what `admit_workload` returns, and the tail is what the dispatcher
7025        // fails over to when the head does not answer — so these two views must
7026        // come from one predicate, not two.
7027        assert_eq!(
7028            cfg.admit_workload_candidates(&ws)
7029                .unwrap()
7030                .iter()
7031                .map(|m| m.name.as_str())
7032                .collect::<Vec<_>>(),
7033            vec!["a-first", "b-second"],
7034            "the pool must be every admissible node, in the same declaration order"
7035        );
7036    }
7037
7038    /// A pool of one is still a pool, and a pool of none is an `Err` that reads
7039    /// exactly like `admit_workload`'s — "nothing admits this" is one failure
7040    /// with one wording, not two.
7041    #[test]
7042    fn admit_workload_candidates_matches_admit_workload_on_the_edges() {
7043        let cfg = make_empty_cfg(vec![
7044            make_machine("x86-box", vec!["tag:build-worker", "arch:x86"]),
7045            make_machine("arm-box", vec!["tag:build-worker", "arch:arm"]),
7046        ]);
7047
7048        let one = ws_with_selector(Some("arch:arm"));
7049        assert_eq!(
7050            cfg.admit_workload_candidates(&one)
7051                .unwrap()
7052                .iter()
7053                .map(|m| m.name.as_str())
7054                .collect::<Vec<_>>(),
7055            vec!["arm-box"],
7056            "only one node carries arch:arm, so the pool is that one node"
7057        );
7058
7059        let none = ws_with_selector(Some("arch:riscv"));
7060        let pool_err = cfg.admit_workload_candidates(&none).unwrap_err().to_string();
7061        let single_err = cfg.admit_workload(&none).unwrap_err().to_string();
7062        assert_eq!(
7063            pool_err, single_err,
7064            "an empty pool must be refused in the same words as an unadmitted workload"
7065        );
7066    }
7067
7068    /// R844-B7 — the wrong-root half of the distinction. A directory with no
7069    /// `.yah/` at all used to load as a valid config with zero machines, so a
7070    /// caller pointed at the wrong directory got a green result that measured
7071    /// nothing. Asserting `load` merely *succeeds* is what let that through;
7072    /// the shape that catches it is a non-zero machine count, or — here — an
7073    /// `Err` naming the path that was looked for.
7074    #[test]
7075    fn loading_a_directory_that_is_not_a_yah_workspace_is_an_error() {
7076        let tmp = tempfile::TempDir::new().unwrap();
7077        // A plausible-looking package root: real files, real subdirectories,
7078        // no `.yah/`. This is exactly what `load_cloud(".")` reads when a test
7079        // runs under `cargo test` from a member crate.
7080        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
7081        std::fs::write(tmp.path().join("Cargo.toml"), "[package]\nname = \"x\"\n").unwrap();
7082
7083        let err = CloudConfig::load(tmp.path()).expect_err(
7084            "a directory with no .yah/ is the WRONG DIRECTORY, not a fleet with no machines",
7085        );
7086        let msg = format!("{err:#}");
7087        assert!(
7088            msg.contains("not a yah workspace"),
7089            "error must say the root is not a workspace, got: {msg}"
7090        );
7091        assert!(
7092            msg.contains(&tmp.path().join(".yah").display().to_string()),
7093            "error must name the path it looked for so an operator sees the \
7094             wrong-root immediately, got: {msg}"
7095        );
7096    }
7097
7098    /// R844-B7 — the other half, and the reason the check is drawn at `.yah/`
7099    /// rather than at the machine list: a camp that declares no machines is a
7100    /// real workspace and must keep loading. Blanket-erroring on an empty
7101    /// fleet would conflate `unknown` with `answered with none`, which is the
7102    /// exact confusion the check exists to remove.
7103    #[test]
7104    fn a_workspace_with_no_machines_declared_still_loads() {
7105        let tmp = tempfile::TempDir::new().unwrap();
7106        std::fs::create_dir_all(tmp.path().join(".yah")).unwrap();
7107
7108        let cfg = CloudConfig::load(tmp.path())
7109            .expect("a `.yah/` with no infra/machines/ is an empty fleet, not a wrong root");
7110        assert!(cfg.machines.is_empty(), "nothing was declared");
7111        assert!(cfg.services.is_empty());
7112        assert!(cfg.providers.is_empty());
7113
7114        // And an existing-but-empty machines dir is the same answer, not a
7115        // second special case.
7116        std::fs::create_dir_all(crate::paths::machines_dir(tmp.path())).unwrap();
7117        let cfg = CloudConfig::load(tmp.path()).expect("an empty machines/ dir still loads");
7118        assert!(cfg.machines.is_empty());
7119    }
7120
7121    #[test]
7122    fn admit_workload_empty_selector_is_unconstrained() {
7123        // Absent annotation ⇒ no mesh-tag constraint ⇒ first declared machine
7124        // (pre-R594 behavior preserved).
7125        let cfg = build_worker_fleet();
7126        let ws = ws_with_selector(None);
7127        let picked = cfg.admit_workload(&ws).unwrap();
7128        assert_eq!(picked.name, "us-west-002");
7129    }
7130
7131    #[test]
7132    fn node_selector_mesh_tags_trims_and_drops_empties() {
7133        let ws = ws_with_selector(Some(" tag:build-worker , arch:x86 ,"));
7134        assert_eq!(
7135            node_selector_mesh_tags(&ws),
7136            vec!["tag:build-worker".to_string(), "arch:x86".to_string()]
7137        );
7138        assert!(node_selector_mesh_tags(&ws_with_selector(None)).is_empty());
7139    }
7140
7141    // ─── F16 topology-aware resolver ────────────────────────────────────────
7142
7143    fn two_region_fleet() -> CloudConfig {
7144        make_empty_cfg(vec![
7145            make_machine_topo(
7146                "us-west-001",
7147                "hetzner",
7148                "us-west",
7149                vec!["tag:cloud-runner"],
7150            ),
7151            make_machine_topo(
7152                "eu-west-001",
7153                "hetzner",
7154                "eu-west",
7155                vec!["tag:cloud-runner"],
7156            ),
7157        ])
7158    }
7159
7160    #[test]
7161    fn resolve_machine_matches_on_region_plus_mesh_tags() {
7162        let cfg = two_region_fleet();
7163        let req = RequiredSpec {
7164            regions: vec!["us-west".into()],
7165            mesh_tags: vec!["tag:cloud-runner".into()],
7166            ..Default::default()
7167        };
7168        let picked = cfg.resolve_machine(&req).unwrap();
7169        assert_eq!(picked.name, "us-west-001");
7170    }
7171
7172    #[test]
7173    fn resolve_machine_region_disambiguates_same_tag() {
7174        // Both boxes carry tag:cloud-runner; the region axis selects eu-west.
7175        let cfg = two_region_fleet();
7176        let req = RequiredSpec {
7177            regions: vec!["eu-west".into()],
7178            mesh_tags: vec!["tag:cloud-runner".into()],
7179            ..Default::default()
7180        };
7181        assert_eq!(cfg.resolve_machine(&req).unwrap().name, "eu-west-001");
7182    }
7183
7184    #[test]
7185    fn resolve_machine_fails_loud_with_constraint_summary() {
7186        let cfg = two_region_fleet();
7187        let req = RequiredSpec {
7188            regions: vec!["us-central".into()],
7189            mesh_tags: vec!["tag:cloud-runner".into()],
7190            ..Default::default()
7191        };
7192        let err = cfg.resolve_machine(&req).unwrap_err().to_string();
7193        assert!(err.contains("required.regions=[us-central]"), "got: {err}");
7194        assert!(
7195            err.contains("required.mesh_tags=[tag:cloud-runner]"),
7196            "got: {err}"
7197        );
7198        // Names the candidates it rejected.
7199        assert!(err.contains("us-west-001"), "got: {err}");
7200    }
7201
7202    #[test]
7203    fn resolve_machine_provider_axis_filters() {
7204        let cfg = make_empty_cfg(vec![
7205            make_machine_topo("aws-west-1", "aws", "us-west", vec!["tag:cloud-runner"]),
7206            make_machine_topo("hz-west-1", "hetzner", "us-west", vec!["tag:cloud-runner"]),
7207        ]);
7208        let req = RequiredSpec {
7209            regions: vec!["us-west".into()],
7210            providers: vec!["hetzner".into()],
7211            ..Default::default()
7212        };
7213        assert_eq!(cfg.resolve_machine(&req).unwrap().name, "hz-west-1");
7214    }
7215
7216    #[test]
7217    fn unconstrained_required_spec_matches_first_machine() {
7218        let cfg = two_region_fleet();
7219        assert!(RequiredSpec::default().is_unconstrained());
7220        assert_eq!(
7221            cfg.resolve_machine(&RequiredSpec::default()).unwrap().name,
7222            "us-west-001"
7223        );
7224    }
7225
7226    #[test]
7227    fn required_spec_parses_topology_axes_from_toml() {
7228        let toml_src = r#"
7229use = "hetzner-primary"
7230[required]
7231regions = ["us-west"]
7232mesh_tags = ["tag:cloud-runner"]
7233"#;
7234        let slot: MirrorProviderSlot = toml::from_str(toml_src).unwrap();
7235        let req = slot.required().expect("required block present");
7236        assert_eq!(req.regions, vec!["us-west"]);
7237        assert_eq!(req.mesh_tags, vec!["tag:cloud-runner"]);
7238        assert!(req.zones.is_empty());
7239    }
7240
7241    // ─── R844-F8 replica count ──────────────────────────────────────────────
7242
7243    fn three_runner_fleet() -> CloudConfig {
7244        make_empty_cfg(vec![
7245            make_machine_topo("us-east-001", "hetzner", "us-east", vec!["tag:cloud-runner"]),
7246            make_machine_topo(
7247                "us-south-001",
7248                "hetzner",
7249                "us-south",
7250                vec!["tag:cloud-runner"],
7251            ),
7252            make_machine_topo(
7253                "us-west-001",
7254                "hetzner",
7255                "us-west",
7256                vec!["tag:cloud-runner"],
7257            ),
7258        ])
7259    }
7260
7261    #[test]
7262    fn an_absent_replica_count_still_places_exactly_one_machine() {
7263        // The migration is additive: every mirror on disk omits `replicas`, and
7264        // must resolve byte-identically to the pre-R844-F8 answer.
7265        let cfg = three_runner_fleet();
7266        let req = RequiredSpec {
7267            mesh_tags: vec!["tag:cloud-runner".into()],
7268            ..Default::default()
7269        };
7270        assert_eq!(req.replica_count(), 1);
7271        let names: Vec<&str> = cfg
7272            .resolve_machines(&req)
7273            .unwrap()
7274            .iter()
7275            .map(|m| m.name.as_str())
7276            .collect();
7277        assert_eq!(names, vec!["us-east-001"]);
7278        assert_eq!(cfg.resolve_machine(&req).unwrap().name, "us-east-001");
7279    }
7280
7281    #[test]
7282    fn a_replica_count_places_that_many_machines_not_every_match() {
7283        // Three machines match; two are asked for; two are placed. Inferring the
7284        // count from the match count would make adding a box to the fleet
7285        // silently scale a production front door.
7286        let cfg = three_runner_fleet();
7287        let req = RequiredSpec {
7288            mesh_tags: vec!["tag:cloud-runner".into()],
7289            replicas: Some(2),
7290            ..Default::default()
7291        };
7292        let names: Vec<&str> = cfg
7293            .resolve_machines(&req)
7294            .unwrap()
7295            .iter()
7296            .map(|m| m.name.as_str())
7297            .collect();
7298        assert_eq!(names, vec!["us-east-001", "us-south-001"]);
7299    }
7300
7301    #[test]
7302    fn fewer_matches_than_replicas_is_an_error_naming_both_numbers() {
7303        // Never a partial placement: one of two reported as success is the
7304        // subset-that-looks-like-it-worked failure in its purest form.
7305        let cfg = three_runner_fleet();
7306        let req = RequiredSpec {
7307            regions: vec!["us-east".into()],
7308            replicas: Some(2),
7309            ..Default::default()
7310        };
7311        let err = cfg.resolve_machines(&req).unwrap_err().to_string();
7312        assert!(err.contains("only 1 of 2"), "got: {err}");
7313        assert!(err.contains("required.regions=[us-east]"), "got: {err}");
7314        // …and names the pool it searched, like every other placement refusal.
7315        assert!(err.contains("declared machines"), "got: {err}");
7316        assert!(err.contains("us-south-001"), "got: {err}");
7317    }
7318
7319    #[test]
7320    fn zero_replicas_is_refused_rather_than_placing_nothing() {
7321        let cfg = three_runner_fleet();
7322        let req = RequiredSpec {
7323            mesh_tags: vec!["tag:cloud-runner".into()],
7324            replicas: Some(0),
7325            ..Default::default()
7326        };
7327        let err = cfg.resolve_machines(&req).unwrap_err().to_string();
7328        assert!(err.contains("replicas = 0"), "got: {err}");
7329    }
7330
7331    #[test]
7332    fn replicas_parses_from_the_inline_required_form() {
7333        // The INLINE form specifically: `[providers.bundle.required]` as a table
7334        // HEADER ends the slot's table and reparents every key below it.
7335        let slot: MirrorProviderSlot = toml::from_str(
7336            r#"
7337use = "hetzner-primary"
7338port = 8080
7339required = { regions = ["us-east"], mesh_tags = ["tag:cloud-runner"], replicas = 2 }
7340"#,
7341        )
7342        .unwrap();
7343        assert_eq!(
7344            slot.fields().get("port").and_then(|v| v.as_integer()),
7345            Some(8080),
7346            "the inline form leaves the slot's other keys where they were"
7347        );
7348        let req = slot.required().expect("required block present");
7349        assert_eq!(req.replicas, Some(2));
7350        assert_eq!(req.replica_count(), 2);
7351        // A count is not a match axis — it says how many, not which.
7352        assert!(!req.is_unconstrained());
7353        assert!(RequiredSpec {
7354            replicas: Some(2),
7355            ..Default::default()
7356        }
7357        .is_unconstrained());
7358    }
7359
7360    #[test]
7361    fn round_trip_machine() {
7362        let cfg = MachineConfig {
7363            name: "test-pdx-1".into(),
7364            provider: "hetzner".into(),
7365            location: Some("pdx".into()),
7366            server_type: Some("cpx22".into()),
7367            hosts_mirrors: vec!["noisetable".into()],
7368            mesh_tags: vec!["region:pdx".into()],
7369            region: Some("us-west".into()),
7370            zone: Some("pdx".into()),
7371            arch: None,
7372            bucket: Some(BucketSpec {
7373                name: "test-assets-pdx-1".into(),
7374                public_read: false,
7375            }),
7376            vendor: None,
7377            nickname: None,
7378            legacy_hostkey_fingerprint: None,
7379            registration: Default::default(),
7380            ssh_keys: vec![],
7381            cloudflared: None,
7382            hosts_operator_bridge: false,
7383            connect: None,
7384            allocatable: None,
7385            taints: vec![],
7386            sovereign_group: None,
7387            sovereign_role: None,
7388            ingress_floating_ip: None,
7389        };
7390        let s = toml::to_string(&cfg).unwrap();
7391        let back: MachineConfig = toml::from_str(&s).unwrap();
7392        assert_eq!(back.name, cfg.name);
7393        assert_eq!(back.location, cfg.location);
7394        assert_eq!(back.region.as_deref(), Some("us-west"));
7395        assert_eq!(back.zone.as_deref(), Some("pdx"));
7396    }
7397
7398    #[test]
7399    fn round_trip_mirror() {
7400        let cfg = LegacyMirrorConfig {
7401            camp: "noisetable".into(),
7402            regions: vec!["pdx".into(), "iad".into()],
7403            workloads: vec!["asset-registry".into()],
7404            cloud_domain: None,
7405        };
7406        let s = toml::to_string(&cfg).unwrap();
7407        let back: LegacyMirrorConfig = toml::from_str(&s).unwrap();
7408        assert_eq!(back.camp, cfg.camp);
7409        assert_eq!(back.regions, cfg.regions);
7410        assert_eq!(back.workloads, cfg.workloads);
7411    }
7412
7413    #[test]
7414    fn mirror_serialises_as_camp_key() {
7415        // Serialised form should use `camp`, not `rig`.
7416        let cfg = LegacyMirrorConfig {
7417            camp: "noisetable".into(),
7418            regions: vec!["pdx".into()],
7419            workloads: vec![],
7420            cloud_domain: None,
7421        };
7422        let s = toml::to_string(&cfg).unwrap();
7423        assert!(
7424            s.contains("camp = "),
7425            "serialised key should be 'camp': {s}"
7426        );
7427        assert!(!s.contains("rig = "), "old key should not appear: {s}");
7428    }
7429
7430    #[test]
7431    fn mirror_rig_alias_still_loads() {
7432        // Old mirrors/*.toml files use `rig = "..."` before the R137 rename;
7433        // the alias keeps them loading until the one-time `sed` migration runs.
7434        let toml_str =
7435            "rig = \"noisetable\"\nregions = [\"pdx\"]\nworkloads = [\"asset-registry\"]\n";
7436        let cfg: LegacyMirrorConfig = toml::from_str(toml_str).unwrap();
7437        assert_eq!(cfg.camp, "noisetable");
7438    }
7439
7440    #[test]
7441    fn mirror_services_alias_still_loads() {
7442        // Old mirrors/*.toml files use `services = [...]`; the alias keeps them
7443        // loading without a migration step.
7444        let toml_str =
7445            "camp = \"noisetable\"\nregions = [\"pdx\"]\nservices = [\"asset-registry\"]\n";
7446        let cfg: LegacyMirrorConfig = toml::from_str(toml_str).unwrap();
7447        assert_eq!(cfg.workloads, vec!["asset-registry"]);
7448    }
7449
7450    #[test]
7451    fn load_dir_missing_is_empty() {
7452        let dir = std::path::PathBuf::from("/nonexistent/path");
7453        let result: Vec<MachineConfig> = load_dir(dir).unwrap();
7454        assert!(result.is_empty());
7455    }
7456
7457    #[test]
7458    fn topology_round_trip() {
7459        let topo = TopologyConfig {
7460            assignments: vec![
7461                MirrorAssignment {
7462                    mirror: "noisetable-pdx".into(),
7463                    machine: "noisetable-pdx-1".into(),
7464                },
7465                MirrorAssignment {
7466                    mirror: "noisetable-iad".into(),
7467                    machine: "noisetable-iad-1".into(),
7468                },
7469            ],
7470            buckets: vec![],
7471        };
7472        let s = toml::to_string(&topo).unwrap();
7473        let back: TopologyConfig = toml::from_str(&s).unwrap();
7474        assert_eq!(back.assignments.len(), 2);
7475        assert_eq!(back.assignments[0].mirror, "noisetable-pdx");
7476        assert_eq!(back.assignments[1].machine, "noisetable-iad-1");
7477    }
7478
7479    #[test]
7480    fn topology_absent_returns_default() {
7481        let tmp = tempfile::TempDir::new().unwrap();
7482        let path = tmp.path().join("topology.toml");
7483        // file doesn't exist
7484        let topo = load_topology(path).unwrap();
7485        assert!(topo.assignments.is_empty());
7486    }
7487
7488    /// Helper: lay out a `<workspace_root>/.yah/cloud/` legacy tree for the
7489    /// pre-R215 cargo tests below; returns the legacy cloud_dir for writes.
7490    fn make_legacy_cloud_dir(root: &std::path::Path) -> std::path::PathBuf {
7491        let cloud_dir = root.join(".yah").join("cloud");
7492        std::fs::create_dir_all(&cloud_dir).unwrap();
7493        cloud_dir
7494    }
7495
7496    #[test]
7497    fn cloud_config_load_and_lookup() {
7498        let tmp = tempfile::TempDir::new().unwrap();
7499        let root = tmp.path();
7500        let cloud_dir = make_legacy_cloud_dir(root);
7501
7502        let machine = MachineConfig {
7503            name: "noisetable-pdx-1".into(),
7504            provider: "hetzner".into(),
7505            location: Some("pdx".into()),
7506            server_type: Some("cpx22".into()),
7507            hosts_mirrors: vec!["noisetable".into(), "yah".into()],
7508            mesh_tags: vec!["region:pdx".into(), "tier:t2".into()],
7509            region: None,
7510            zone: None,
7511            arch: None,
7512            bucket: Some(BucketSpec {
7513                name: "noisetable-assets-pdx-1".into(),
7514                public_read: false,
7515            }),
7516            vendor: None,
7517            nickname: None,
7518            legacy_hostkey_fingerprint: None,
7519            registration: Default::default(),
7520            ssh_keys: vec![],
7521            cloudflared: None,
7522            hosts_operator_bridge: false,
7523            connect: None,
7524            allocatable: None,
7525            taints: vec![],
7526            sovereign_group: None,
7527            sovereign_role: None,
7528            ingress_floating_ip: None,
7529        };
7530        // Land in the legacy tree so the legacy machine loader picks it up.
7531        machine.save(&cloud_dir).unwrap();
7532
7533        let mirror_toml = "camp = \"noisetable\"\nregions = [\"pdx\", \"iad\", \"fsn\"]\nworkloads = [\"asset-registry\"]\n";
7534        std::fs::create_dir_all(cloud_dir.join("mirrors")).unwrap();
7535        std::fs::write(cloud_dir.join("mirrors/noisetable.toml"), mirror_toml).unwrap();
7536
7537        let cfg = CloudConfig::load(root).unwrap();
7538
7539        assert_eq!(cfg.machines.len(), 1);
7540        assert_eq!(cfg.legacy_mirrors.len(), 1);
7541        assert_eq!(cfg.workloads.len(), 0); // no workloads/ dir yet
7542        assert!(cfg.services.is_empty(), "no R215+ services/ tree");
7543        assert!(cfg.providers.is_empty(), "no R215+ providers/ tree");
7544
7545        let m = cfg.machine("noisetable-pdx-1").unwrap();
7546        assert_eq!(m.location(), "pdx");
7547        assert_eq!(m.bucket.as_ref().unwrap().name, "noisetable-assets-pdx-1");
7548
7549        let mir = cfg.legacy_mirror("noisetable").unwrap();
7550        assert_eq!(mir.regions, vec!["pdx", "iad", "fsn"]);
7551        assert_eq!(mir.workloads, vec!["asset-registry"]);
7552    }
7553
7554    #[test]
7555    fn mirror_folder_layout_loads() {
7556        // Folder layout: mirrors/<id>/mirror.toml — new preferred form.
7557        let tmp = tempfile::TempDir::new().unwrap();
7558        let root = tmp.path();
7559        let cloud_dir = make_legacy_cloud_dir(root);
7560        let mirror_dir = cloud_dir.join("mirrors").join("yah-com");
7561        std::fs::create_dir_all(&mirror_dir).unwrap();
7562        std::fs::write(
7563            mirror_dir.join("mirror.toml"),
7564            "camp = \"yah\"\nregions = [\"pdx\"]\nworkloads = [\"yah-web\"]\n",
7565        )
7566        .unwrap();
7567
7568        let cfg = CloudConfig::load(root).unwrap();
7569        assert_eq!(cfg.legacy_mirrors.len(), 1);
7570        let mir = cfg.legacy_mirror("yah").unwrap();
7571        assert_eq!(mir.camp, "yah");
7572        assert_eq!(mir.workloads, vec!["yah-web"]);
7573    }
7574
7575    #[test]
7576    fn mirror_folder_and_flat_coexist() {
7577        // Both layouts may coexist in the same mirrors/ directory.
7578        let tmp = tempfile::TempDir::new().unwrap();
7579        let root = tmp.path();
7580        let cloud_dir = make_legacy_cloud_dir(root);
7581        let mirrors_root = cloud_dir.join("mirrors");
7582        std::fs::create_dir_all(&mirrors_root).unwrap();
7583
7584        // Flat legacy mirror
7585        std::fs::write(
7586            mirrors_root.join("noisetable.toml"),
7587            "camp = \"noisetable\"\nregions = [\"pdx\"]\nworkloads = []\n",
7588        )
7589        .unwrap();
7590
7591        // Folder-form mirror
7592        let yah_com_dir = mirrors_root.join("yah-com");
7593        std::fs::create_dir_all(&yah_com_dir).unwrap();
7594        std::fs::write(
7595            yah_com_dir.join("mirror.toml"),
7596            "camp = \"yah\"\nregions = [\"pdx\"]\nworkloads = []\n",
7597        )
7598        .unwrap();
7599
7600        let cfg = CloudConfig::load(root).unwrap();
7601        assert_eq!(cfg.legacy_mirrors.len(), 2);
7602        assert!(cfg.legacy_mirror("noisetable").is_some());
7603        assert!(cfg.legacy_mirror("yah").is_some());
7604    }
7605
7606    #[test]
7607    fn mirror_malformed_fails_with_field_path() {
7608        // A malformed mirror.toml should fail at load with a clear error
7609        // that includes the file path.
7610        let tmp = tempfile::TempDir::new().unwrap();
7611        let root = tmp.path();
7612        let cloud_dir = make_legacy_cloud_dir(root);
7613        let mirror_dir = cloud_dir.join("mirrors").join("bad");
7614        std::fs::create_dir_all(&mirror_dir).unwrap();
7615        // Missing required `camp` field
7616        std::fs::write(
7617            mirror_dir.join("mirror.toml"),
7618            "regions = [\"pdx\"]\nworkloads = []\n",
7619        )
7620        .unwrap();
7621
7622        let err = CloudConfig::load(root).unwrap_err();
7623        let msg = err.to_string();
7624        assert!(
7625            msg.contains("mirror.toml"),
7626            "error should reference the file path, got: {msg}"
7627        );
7628    }
7629
7630    #[test]
7631    fn workload_config_load_and_validate() {
7632        use workload_spec::{
7633            ExposeSpec, ImageRef, MeshExpose, MeshIdent, NamespaceId, ResourceLimits,
7634            RestartPolicy, StopPolicy, TenantId, TierTag, WorkloadSpec,
7635        };
7636
7637        let tmp = tempfile::TempDir::new().unwrap();
7638        let root = tmp.path();
7639        let cloud_dir = make_legacy_cloud_dir(root);
7640        std::fs::create_dir_all(cloud_dir.join("workloads")).unwrap();
7641
7642        let spec = WorkloadSpec {
7643            name: "asset-registry".into(),
7644            image: ImageRef {
7645                registry: "ghcr.io".into(),
7646                repository: "noisetable/asset-registry".into(),
7647                tag: "v1.0.0".into(),
7648                digest: workload_spec::testing::test_digest(),
7649            },
7650            tier: TierTag("tenant".into()),
7651            replicas: 1,
7652            command: None,
7653            entrypoint: None,
7654            workdir: None,
7655            user: None,
7656            env: vec![],
7657            secrets: vec![],
7658            volumes: vec![],
7659            resources: ResourceLimits {
7660                memory_mb: 256,
7661                cpu_millis: 512,
7662                memory_request_mb: None,
7663                cpu_limit_millis: None,
7664                pids_max: None,
7665                scratch_floor_mb: None,
7666            },
7667            depends_on: vec![],
7668            requires: vec![],
7669            healthcheck: None,
7670            restart_policy: RestartPolicy::Always,
7671            archetype: None,
7672            stop_policy: StopPolicy {
7673                signal: 15,
7674                grace_period: workload_spec::Millis::from_secs(10),
7675            },
7676            expose: ExposeSpec {
7677                mesh: MeshExpose {
7678                    identity: MeshIdent("asset-registry.pdx".into()),
7679                    ports: MeshExpose::anonymous_ports([8080]),
7680                    allow_from: vec![],
7681                },
7682                public: None,
7683                operator: None,
7684            },
7685            tenant: TenantId::singleton(),
7686            namespace: NamespaceId::singleton(),
7687            labels: Default::default(),
7688            durability: None,
7689            annotations: Default::default(),
7690            files: Vec::new(),
7691        };
7692
7693        let toml_str = toml::to_string_pretty(&spec).unwrap();
7694        std::fs::write(cloud_dir.join("workloads/asset-registry.toml"), &toml_str).unwrap();
7695
7696        let cfg = CloudConfig::load(root).unwrap();
7697        assert_eq!(cfg.workloads.len(), 1);
7698        assert_eq!(cfg.workloads[0].spec.name, "asset-registry");
7699        assert_eq!(cfg.workload("asset-registry").unwrap().spec.replicas, 1);
7700    }
7701
7702    /// Minimal valid spec for the R215+ loader tests below. Kept as a helper so
7703    /// the two tests differ only in *where* the file lands, which is the whole
7704    /// thing under test.
7705    #[cfg(test)]
7706    fn minimal_spec(name: &str, replicas: u32) -> workload_spec::WorkloadSpec {
7707        use workload_spec::{
7708            ExposeSpec, ImageRef, MeshExpose, MeshIdent, NamespaceId, ResourceLimits,
7709            RestartPolicy, StopPolicy, TenantId, TierTag, WorkloadSpec,
7710        };
7711        WorkloadSpec {
7712            name: name.into(),
7713            image: ImageRef {
7714                registry: "cr.yah.dev".into(),
7715                repository: name.into(),
7716                tag: "v1".into(),
7717                digest: workload_spec::testing::test_digest(),
7718            },
7719            tier: TierTag("infra".into()),
7720            replicas,
7721            command: None,
7722            entrypoint: None,
7723            workdir: None,
7724            user: None,
7725            env: vec![],
7726            secrets: vec![],
7727            volumes: vec![],
7728            resources: ResourceLimits {
7729                memory_mb: 256,
7730                cpu_millis: 250,
7731                memory_request_mb: None,
7732                cpu_limit_millis: None,
7733                pids_max: None,
7734                scratch_floor_mb: None,
7735            },
7736            depends_on: vec![],
7737            requires: vec![],
7738            healthcheck: None,
7739            restart_policy: RestartPolicy::Always,
7740            archetype: None,
7741            stop_policy: StopPolicy {
7742                signal: 15,
7743                grace_period: workload_spec::Millis::from_secs(10),
7744            },
7745            expose: ExposeSpec {
7746                mesh: MeshExpose {
7747                    identity: MeshIdent(name.into()),
7748                    ports: MeshExpose::anonymous_ports([4325]),
7749                    allow_from: vec![],
7750                },
7751                public: None,
7752                operator: None,
7753            },
7754            tenant: TenantId::singleton(),
7755            namespace: NamespaceId::singleton(),
7756            labels: Default::default(),
7757            durability: None,
7758            annotations: Default::default(),
7759            files: Vec::new(),
7760        }
7761    }
7762
7763    /// R568-T7. Workloads must load from the R215+ tree.
7764    ///
7765    /// Before the fix this function tested, `CloudConfig::load` read workloads
7766    /// ONLY from the pre-R215 `.yah/cloud/workloads/` — which R222-B1 emptied —
7767    /// so in any modern camp `cfg.workload(name)` returned `None` for every
7768    /// name and the entire `yah cloud workload …` surface was unreachable. The
7769    /// CLI's own error text has said `.yah/infra/workloads/` throughout, so the
7770    /// bug read as "you must have typoed the filename".
7771    ///
7772    /// Note the fixture writes NO legacy `.yah/cloud/` dir at all: that is the
7773    /// shape of a real post-R215 camp, and it is exactly the shape the old code
7774    /// could not serve.
7775    #[test]
7776    fn workloads_load_from_the_infra_tree() {
7777        let tmp = tempfile::TempDir::new().unwrap();
7778        let root = tmp.path();
7779        let dir = crate::paths::workloads_dir(root);
7780        std::fs::create_dir_all(&dir).unwrap();
7781        std::fs::write(
7782            dir.join("yah-cloud-admin.toml"),
7783            toml::to_string_pretty(&minimal_spec("yah-cloud-admin", 1)).unwrap(),
7784        )
7785        .unwrap();
7786
7787        let cfg = CloudConfig::load(root).unwrap();
7788        assert_eq!(cfg.workloads.len(), 1);
7789        assert_eq!(
7790            cfg.workload("yah-cloud-admin").unwrap().spec.replicas,
7791            1,
7792            "a workload declared under .yah/infra/workloads/ must be resolvable by name"
7793        );
7794    }
7795
7796    /// A camp mid-migration can have both trees. R215+ wins on a name
7797    /// collision — same precedence the machine loader applies — so moving a
7798    /// declaration into `.yah/infra/workloads/` takes effect immediately
7799    /// instead of being silently shadowed by the copy left behind.
7800    #[test]
7801    fn infra_workload_shadows_the_legacy_copy_of_the_same_name() {
7802        let tmp = tempfile::TempDir::new().unwrap();
7803        let root = tmp.path();
7804
7805        let legacy = make_legacy_cloud_dir(root);
7806        std::fs::create_dir_all(legacy.join("workloads")).unwrap();
7807        std::fs::write(
7808            legacy.join("workloads/shared.toml"),
7809            toml::to_string_pretty(&minimal_spec("shared", 9)).unwrap(),
7810        )
7811        .unwrap();
7812        // Legacy-only name, to prove the old tree is still read rather than
7813        // replaced wholesale.
7814        std::fs::write(
7815            legacy.join("workloads/legacy-only.toml"),
7816            toml::to_string_pretty(&minimal_spec("legacy-only", 3)).unwrap(),
7817        )
7818        .unwrap();
7819
7820        let infra = crate::paths::workloads_dir(root);
7821        std::fs::create_dir_all(&infra).unwrap();
7822        std::fs::write(
7823            infra.join("shared.toml"),
7824            toml::to_string_pretty(&minimal_spec("shared", 1)).unwrap(),
7825        )
7826        .unwrap();
7827
7828        let cfg = CloudConfig::load(root).unwrap();
7829        assert_eq!(cfg.workloads.len(), 2, "one `shared`, plus `legacy-only`");
7830        assert_eq!(
7831            cfg.workload("shared").unwrap().spec.replicas,
7832            1,
7833            "the .yah/infra/ copy must win over the legacy one"
7834        );
7835        assert_eq!(cfg.workload("legacy-only").unwrap().spec.replicas, 3);
7836    }
7837
7838    #[test]
7839    fn workload_loader_rejects_bad_spec() {
7840        use workload_spec::{
7841            ExposeSpec, ImageRef, MeshExpose, MeshIdent, NamespaceId, ResourceLimits,
7842            RestartPolicy, StopPolicy, TenantId, TierTag, WorkloadSpec,
7843        };
7844
7845        let tmp = tempfile::TempDir::new().unwrap();
7846        let root = tmp.path();
7847        let cloud_dir = make_legacy_cloud_dir(root);
7848        std::fs::create_dir_all(cloud_dir.join("workloads")).unwrap();
7849
7850        // Construct a spec that round-trips through TOML but fails shape
7851        // validation: replicas = 200 is above the max of 100.
7852        let mut spec = WorkloadSpec {
7853            name: "asset-registry".into(),
7854            image: ImageRef {
7855                registry: "ghcr.io".into(),
7856                repository: "test/app".into(),
7857                tag: "v1".into(),
7858                digest: workload_spec::testing::test_digest(),
7859            },
7860            tier: TierTag("tenant".into()),
7861            replicas: 200, // ← invalid: exceeds max 100
7862            command: None,
7863            entrypoint: None,
7864            workdir: None,
7865            user: None,
7866            env: vec![],
7867            secrets: vec![],
7868            volumes: vec![],
7869            resources: ResourceLimits {
7870                memory_mb: 256,
7871                cpu_millis: 512,
7872                memory_request_mb: None,
7873                cpu_limit_millis: None,
7874                pids_max: None,
7875                scratch_floor_mb: None,
7876            },
7877            depends_on: vec![],
7878            requires: vec![],
7879            healthcheck: None,
7880            restart_policy: RestartPolicy::Always,
7881            archetype: None,
7882            stop_policy: StopPolicy {
7883                signal: 15,
7884                grace_period: workload_spec::Millis::from_secs(10),
7885            },
7886            expose: ExposeSpec {
7887                mesh: MeshExpose {
7888                    identity: MeshIdent("asset-registry.pdx".into()),
7889                    ports: MeshExpose::anonymous_ports([8080]),
7890                    allow_from: vec![],
7891                },
7892                public: None,
7893                operator: None,
7894            },
7895            tenant: TenantId::singleton(),
7896            namespace: NamespaceId::singleton(),
7897            labels: Default::default(),
7898            durability: None,
7899            annotations: Default::default(),
7900            files: Vec::new(),
7901        };
7902
7903        let toml_str = toml::to_string_pretty(&spec).unwrap();
7904        std::fs::write(cloud_dir.join("workloads/bad.toml"), &toml_str).unwrap();
7905
7906        let result = CloudConfig::load(root);
7907        assert!(
7908            result.is_err(),
7909            "loading a WorkloadSpec with replicas=200 should return Err"
7910        );
7911        let msg = result.unwrap_err().to_string();
7912        assert!(
7913            msg.contains("shape validation")
7914                || msg.contains("Replicas")
7915                || msg.contains("replicas"),
7916            "error should mention shape validation or replicas field, got: {msg}"
7917        );
7918
7919        // The `spec` binding is only used for the write — suppress warning.
7920        let _ = &mut spec;
7921    }
7922
7923    #[test]
7924    fn workload_config_save_round_trip() {
7925        use workload_spec::{
7926            ExposeSpec, ImageRef, MeshExpose, MeshIdent, NamespaceId, ResourceLimits,
7927            RestartPolicy, StopPolicy, TenantId, TierTag, WorkloadSpec,
7928        };
7929
7930        let tmp = tempfile::TempDir::new().unwrap();
7931        let root = tmp.path();
7932
7933        let spec = WorkloadSpec {
7934            name: "signing-service".into(),
7935            image: ImageRef {
7936                registry: "ghcr.io".into(),
7937                repository: "noisetable/signing".into(),
7938                tag: "v2.0.0".into(),
7939                digest: workload_spec::testing::test_digest(),
7940            },
7941            tier: TierTag("private".into()),
7942            replicas: 2,
7943            command: None,
7944            entrypoint: None,
7945            workdir: None,
7946            user: None,
7947            env: vec![],
7948            secrets: vec![],
7949            volumes: vec![],
7950            resources: ResourceLimits {
7951                memory_mb: 128,
7952                cpu_millis: 256,
7953                memory_request_mb: None,
7954                cpu_limit_millis: None,
7955                pids_max: None,
7956                scratch_floor_mb: None,
7957            },
7958            depends_on: vec![],
7959            requires: vec![],
7960            healthcheck: None,
7961            restart_policy: RestartPolicy::Always,
7962            archetype: None,
7963            stop_policy: StopPolicy {
7964                signal: 15,
7965                grace_period: workload_spec::Millis::from_secs(5),
7966            },
7967            expose: ExposeSpec {
7968                mesh: MeshExpose {
7969                    identity: MeshIdent("signing.pdx".into()),
7970                    ports: MeshExpose::anonymous_ports([9090]),
7971                    allow_from: vec![],
7972                },
7973                public: None,
7974                operator: None,
7975            },
7976            tenant: TenantId::singleton(),
7977            namespace: NamespaceId::singleton(),
7978            labels: Default::default(),
7979            durability: None,
7980            annotations: Default::default(),
7981            files: Vec::new(),
7982        };
7983
7984        let wc = WorkloadConfig { spec };
7985        let cloud_dir = make_legacy_cloud_dir(root);
7986        wc.save(&cloud_dir).unwrap();
7987
7988        let loaded = CloudConfig::load(root).unwrap();
7989        assert_eq!(loaded.workloads.len(), 1);
7990        assert_eq!(loaded.workloads[0].spec.name, "signing-service");
7991        assert_eq!(loaded.workloads[0].spec.replicas, 2);
7992    }
7993
7994    #[test]
7995    fn machine_save_write_back_fingerprint() {
7996        let tmp = tempfile::TempDir::new().unwrap();
7997        let root = tmp.path();
7998
7999        let mut machine = MachineConfig {
8000            name: "test-pdx-1".into(),
8001            provider: "hetzner".into(),
8002            location: Some("pdx".into()),
8003            server_type: Some("cpx22".into()),
8004            hosts_mirrors: vec![],
8005            mesh_tags: vec![],
8006            region: None,
8007            zone: None,
8008            arch: None,
8009            bucket: None,
8010            vendor: None,
8011            nickname: None,
8012            legacy_hostkey_fingerprint: None,
8013            registration: Default::default(),
8014            ssh_keys: vec![],
8015            cloudflared: None,
8016            hosts_operator_bridge: false,
8017            connect: None,
8018            allocatable: None,
8019            taints: vec![],
8020            sovereign_group: None,
8021            sovereign_role: None,
8022            ingress_floating_ip: None,
8023        };
8024        machine.save(root).unwrap();
8025
8026        // Simulate A4: write back the hostkey fingerprint after provision.
8027        // R707-T1: registration is the write target; the accessor is the read.
8028        machine.registration.hostkey_fingerprint = Some("SHA256:abc123".into());
8029        machine.save(root).unwrap();
8030
8031        let reloaded: Vec<MachineConfig> = load_dir(root.join("machines")).unwrap();
8032        assert_eq!(reloaded.len(), 1);
8033        assert_eq!(reloaded[0].hostkey_fingerprint(), Some("SHA256:abc123"));
8034    }
8035
8036    // ─── New-shape (R222 B2) parse tests ────────────────────────────────────
8037    //
8038    // These mirror the Phase-A manifests committed under `.yah/services/` and
8039    // `.yah/infra/providers/`. Keeping the test strings inline (rather than
8040    // reading the on-disk files) so the loader stays runnable in any workdir
8041    // and so accidental edits to the on-disk files don't silently change
8042    // schema expectations.
8043
8044    #[test]
8045    fn provider_cloudflare_round_trips() {
8046        let src = r#"
8047schema_version = 1
8048id = "cloudflare"
8049kind = "cloudflare"
8050credentials = "keystore://cloudflare/yah"
8051default_zone = "yah.dev"
8052"#;
8053        let cfg: ProviderConfig = toml::from_str(src).unwrap();
8054        assert_eq!(cfg.id, "cloudflare");
8055        assert_eq!(cfg.kind, Provider::Cloudflare);
8056        assert_eq!(
8057            cfg.credentials.as_deref(),
8058            Some("keystore://cloudflare/yah")
8059        );
8060        assert_eq!(
8061            cfg.fields.get("default_zone").and_then(|v| v.as_str()),
8062            Some("yah.dev"),
8063        );
8064        let back = toml::to_string(&cfg).unwrap();
8065        let again: ProviderConfig = toml::from_str(&back).unwrap();
8066        assert_eq!(again.id, cfg.id);
8067        assert_eq!(again.kind, cfg.kind);
8068    }
8069
8070    #[test]
8071    fn provider_hetzner_round_trips() {
8072        let src = r#"
8073schema_version = 1
8074id = "hetzner"
8075kind = "hetzner"
8076credentials = "keystore://hetzner/yah"
8077default_location = "pdx"
8078default_server_type = "cpx11"
8079ssh_keys = []
8080"#;
8081        let cfg: ProviderConfig = toml::from_str(src).unwrap();
8082        assert_eq!(cfg.kind, Provider::Hetzner);
8083        assert_eq!(
8084            cfg.fields.get("default_location").and_then(|v| v.as_str()),
8085            Some("pdx"),
8086        );
8087        assert!(
8088            cfg.fields
8089                .get("ssh_keys")
8090                .map(|v| v.as_array().unwrap().is_empty())
8091                .unwrap_or(false),
8092            "ssh_keys must round-trip as empty array, got {:?}",
8093            cfg.fields.get("ssh_keys"),
8094        );
8095    }
8096
8097    #[test]
8098    fn provider_orbstack_local_container_round_trips() {
8099        let src = r#"
8100schema_version = 1
8101id = "orbstack"
8102kind = "local-container"
8103runtime = "auto"
8104
8105[discovery]
8106orbstack = "~/.orbstack/run/docker.sock"
8107colima   = "~/.colima/default/docker.sock"
8108docker   = "/var/run/docker.sock"
8109"#;
8110        let cfg: ProviderConfig = toml::from_str(src).unwrap();
8111        assert_eq!(cfg.kind, Provider::LocalContainer);
8112        assert_eq!(
8113            cfg.fields.get("runtime").and_then(|v| v.as_str()),
8114            Some("auto"),
8115        );
8116        let discovery = cfg
8117            .fields
8118            .get("discovery")
8119            .and_then(|v| v.as_table())
8120            .expect("discovery table");
8121        assert!(discovery.contains_key("orbstack"));
8122        assert!(discovery.contains_key("colima"));
8123        assert!(discovery.contains_key("docker"));
8124    }
8125
8126    #[test]
8127    fn provider_unknown_kind_fails() {
8128        let src = r#"
8129schema_version = 1
8130id = "made-up"
8131kind = "fly-io"
8132"#;
8133        let err = toml::from_str::<ProviderConfig>(src).unwrap_err();
8134        let msg = err.to_string();
8135        assert!(
8136            msg.contains("kind") || msg.contains("variant"),
8137            "unknown provider kind should surface as a serde error, got: {msg}"
8138        );
8139    }
8140
8141    #[test]
8142    fn service_dev_yah_round_trips() {
8143        let src = r#"
8144schema_version = 1
8145name = "dev-yah"
8146domain = "yah.dev"
8147
8148[[components]]
8149id = "site"
8150kind = "mesofact-static"
8151path = "app/yah/web"
8152role = "static"
8153"#;
8154        let cfg: ServiceConfig = toml::from_str(src).unwrap();
8155        assert_eq!(cfg.name, "dev-yah");
8156        assert_eq!(cfg.domain, "yah.dev");
8157        assert_eq!(cfg.components.len(), 1);
8158        let c = &cfg.components[0];
8159        assert_eq!(c.id, "site");
8160        assert_eq!(c.kind, "mesofact-static");
8161        assert_eq!(c.path, "app/yah/web");
8162        assert_eq!(c.role, "static");
8163        assert!(c.publishes.is_none());
8164
8165        let back = toml::to_string(&cfg).unwrap();
8166        let again: ServiceConfig = toml::from_str(&back).unwrap();
8167        assert_eq!(again.name, cfg.name);
8168        assert_eq!(again.components[0].kind, c.kind);
8169    }
8170
8171    #[test]
8172    fn mirror_prod_cloudflare_reference_parses() {
8173        let src = r#"
8174schema_version = 1
8175shape = "single-machine"
8176
8177[providers.static]
8178use = "cloudflare"
8179bucket = "yah-dev"
8180zone = "yah.dev"
8181dns = { record = "@", type = "CNAME" }
8182"#;
8183        let cfg: MirrorConfig = toml::from_str(src).unwrap();
8184        assert_eq!(cfg.shape, MirrorShape::SingleMachine);
8185        let slot = cfg.providers.get("static").expect("static slot");
8186        assert_eq!(slot.provider_id(), Some("cloudflare"));
8187        assert!(slot.inline_kind().is_none());
8188        if let MirrorProviderSlot::Reference { fields, .. } = slot {
8189            assert_eq!(
8190                fields.get("bucket").and_then(|v| v.as_str()),
8191                Some("yah-dev")
8192            );
8193            assert_eq!(fields.get("zone").and_then(|v| v.as_str()), Some("yah.dev"));
8194            let dns = fields
8195                .get("dns")
8196                .and_then(|v| v.as_table())
8197                .expect("dns table");
8198            assert_eq!(dns.get("record").and_then(|v| v.as_str()), Some("@"));
8199            assert_eq!(dns.get("type").and_then(|v| v.as_str()), Some("CNAME"));
8200        } else {
8201            panic!("expected Reference slot");
8202        }
8203    }
8204
8205    #[test]
8206    fn mirror_local_inline_static_and_orbstack_compute_parse() {
8207        let src = r#"
8208schema_version = 1
8209shape = "local"
8210
8211[providers.static]
8212kind = "miniflare-native"
8213port = 4321
8214artifact_dir = ".yah/infra/state/local/static"
8215
8216[providers.compute]
8217use = "orbstack"
8218"#;
8219        let cfg: MirrorConfig = toml::from_str(src).unwrap();
8220        assert_eq!(cfg.shape, MirrorShape::Local);
8221
8222        let static_slot = cfg.providers.get("static").expect("static slot");
8223        assert_eq!(static_slot.inline_kind(), Some(Provider::MiniflareNative));
8224        assert!(static_slot.provider_id().is_none());
8225        if let MirrorProviderSlot::Inline { fields, .. } = static_slot {
8226            assert_eq!(fields.get("port").and_then(|v| v.as_integer()), Some(4321));
8227            assert_eq!(
8228                fields.get("artifact_dir").and_then(|v| v.as_str()),
8229                Some(".yah/infra/state/local/static"),
8230            );
8231        } else {
8232            panic!("expected Inline slot for static");
8233        }
8234
8235        let compute_slot = cfg.providers.get("compute").expect("compute slot");
8236        assert_eq!(compute_slot.provider_id(), Some("orbstack"));
8237    }
8238
8239    #[test]
8240    fn mirror_pond_miniflare_minio_parse() {
8241        // pond-tier mirror: miniflare-container + minio, both inline.
8242        // T1 just needs these inline kinds to parse — the reconciler dispatch
8243        // arrives in R256-T3.
8244        let src = r#"
8245schema_version = 1
8246shape = "local"
8247
8248[providers.static]
8249kind = "miniflare-container"
8250port = 4322
8251bucket = "yah-dev"
8252
8253[providers.object_store]
8254kind = "minio-container"
8255api_port = 9000
8256console_port = 9001
8257bucket = "yah-dev"
8258"#;
8259        let cfg: MirrorConfig = toml::from_str(src).unwrap();
8260        assert_eq!(cfg.shape, MirrorShape::Local);
8261
8262        let static_slot = cfg.providers.get("static").expect("static slot");
8263        assert_eq!(
8264            static_slot.inline_kind(),
8265            Some(Provider::MiniflareContainer)
8266        );
8267        if let MirrorProviderSlot::Inline { fields, .. } = static_slot {
8268            assert_eq!(fields.get("port").and_then(|v| v.as_integer()), Some(4322));
8269            assert_eq!(
8270                fields.get("bucket").and_then(|v| v.as_str()),
8271                Some("yah-dev")
8272            );
8273        } else {
8274            panic!("expected Inline slot for miniflare-container static");
8275        }
8276
8277        let object_store_slot = cfg
8278            .providers
8279            .get("object_store")
8280            .expect("object_store slot");
8281        assert_eq!(
8282            object_store_slot.inline_kind(),
8283            Some(Provider::MinioContainer)
8284        );
8285        if let MirrorProviderSlot::Inline { fields, .. } = object_store_slot {
8286            assert_eq!(
8287                fields.get("api_port").and_then(|v| v.as_integer()),
8288                Some(9000)
8289            );
8290            assert_eq!(
8291                fields.get("console_port").and_then(|v| v.as_integer()),
8292                Some(9001)
8293            );
8294            assert_eq!(
8295                fields.get("bucket").and_then(|v| v.as_str()),
8296                Some("yah-dev")
8297            );
8298        } else {
8299            panic!("expected Inline slot for minio-container object_store");
8300        }
8301    }
8302
8303    #[test]
8304    fn provider_miniflare_container_kind_round_trips() {
8305        // Inline-only kind; never declared as a standalone provider file but
8306        // the enum round-trip is still exercised through ProviderConfig because
8307        // schemars/serde share the variant table.
8308        let cfg = MirrorProviderSlot::Inline {
8309            kind: Provider::MiniflareContainer,
8310            fields: BTreeMap::new(),
8311        };
8312        let s = toml::to_string(&cfg).unwrap();
8313        assert!(
8314            s.contains("kind = \"miniflare-container\""),
8315            "kebab-case wire form expected, got: {s}"
8316        );
8317        let back: MirrorProviderSlot = toml::from_str(&s).unwrap();
8318        assert_eq!(back.inline_kind(), Some(Provider::MiniflareContainer));
8319    }
8320
8321    #[test]
8322    fn provider_minio_container_kind_round_trips() {
8323        let cfg = MirrorProviderSlot::Inline {
8324            kind: Provider::MinioContainer,
8325            fields: BTreeMap::new(),
8326        };
8327        let s = toml::to_string(&cfg).unwrap();
8328        assert!(
8329            s.contains("kind = \"minio-container\""),
8330            "kebab-case wire form expected, got: {s}"
8331        );
8332        let back: MirrorProviderSlot = toml::from_str(&s).unwrap();
8333        assert_eq!(back.inline_kind(), Some(Provider::MinioContainer));
8334    }
8335
8336    #[test]
8337    fn mirror_compute_slot_with_machine_reference_parses() {
8338        // The on-disk prod.toml has a commented-out compute slot; this test
8339        // covers the form Phase B will need once yubaba is provisioned.
8340        let src = r#"
8341schema_version = 1
8342shape = "single-machine"
8343
8344[providers.compute]
8345use = "hetzner"
8346machine = "yah-cloud-1"
8347"#;
8348        let cfg: MirrorConfig = toml::from_str(src).unwrap();
8349        let slot = cfg.providers.get("compute").expect("compute slot");
8350        assert_eq!(slot.provider_id(), Some("hetzner"));
8351        if let MirrorProviderSlot::Reference { fields, .. } = slot {
8352            assert_eq!(
8353                fields.get("machine").and_then(|v| v.as_str()),
8354                Some("yah-cloud-1"),
8355            );
8356        }
8357    }
8358
8359    #[test]
8360    fn machine_yah_cloud_1_round_trips_with_existing_shape() {
8361        // The current machine TOML predates B2 — MachineConfig hasn't been
8362        // reshaped yet. This locks the expected shape so we notice if B3
8363        // accidentally regresses it.
8364        let src = r#"
8365name = "yah-cloud-1"
8366provider = "hetzner"
8367location = "pdx"
8368server_type = "cpx11"
8369hosts_mirrors = []
8370mesh_tags = ["tag:tier-scratch", "tag:primary-yah"]
8371ssh_keys = [111513970, 111525493]
8372"#;
8373        let cfg: MachineConfig = toml::from_str(src).unwrap();
8374        assert_eq!(cfg.name, "yah-cloud-1");
8375        assert_eq!(cfg.provider, "hetzner");
8376        assert_eq!(cfg.ssh_keys.len(), 2);
8377    }
8378
8379    #[test]
8380    fn static_node_omits_location_server_type_and_carries_connect() {
8381        // BYO Phase-0: a `static` node we brought up over SSH has no provider
8382        // DC code or SKU; it declares reach in `[connect]` instead. Must load.
8383        let src = r#"
8384name = "us-south-001"
8385provider = "static"
8386region = "us-south"
8387mesh_tags = ["tag:cloud-runner", "tag:voter-candidate"]
8388
8389[connect]
8390address = "45.32.194.254"
8391ssh = "root@45.32.194.254"
8392identity_file = "~/.ssh/yah"
8393yubaba = "http://127.0.0.1:7443"
8394arch = "x86_64"
8395"#;
8396        let cfg: MachineConfig = toml::from_str(src).unwrap();
8397        assert_eq!(cfg.provider, "static");
8398        assert!(cfg.location.is_none());
8399        assert!(cfg.server_type.is_none());
8400        assert_eq!(cfg.location(), ""); // accessor defaults empty
8401        let c = cfg.connect.as_ref().expect("connect block");
8402        assert_eq!(c.ssh, "root@45.32.194.254");
8403        // Loopback is a *declared* reach placeholder, so it stays in [connect]
8404        // verbatim and composes straight through (R707-T1).
8405        assert_eq!(c.yubaba.as_deref(), Some("http://127.0.0.1:7443"));
8406        assert_eq!(cfg.yubaba_url().as_deref(), Some("http://127.0.0.1:7443"));
8407        assert_eq!(cfg.mesh_ipv4(), None);
8408        // Static providers have no driver, so validate() is a no-op pass.
8409        assert!(!provider_has_machine_driver(&cfg.provider));
8410        cfg.validate().unwrap();
8411    }
8412
8413    // ─── R707-T1: declaration / registration split ──────────────────────────
8414
8415    /// The pre-split shape — top-level `hostkey_fingerprint`, mesh IP baked
8416    /// into `[connect].yubaba` — must keep parsing, and must read back through
8417    /// the accessors identically. Every machine TOML in the fleet was written
8418    /// this way, and other camps' inventories still are.
8419    #[test]
8420    fn legacy_shape_still_parses_and_reads_through_accessors() {
8421        let src = r#"
8422name = "us-west-001"
8423provider = "static"
8424region = "us-west"
8425arch = "x86_64"
8426mesh_tags = ["tag:cloud-runner"]
8427hostkey_fingerprint = "SHA256:dmpq"
8428
8429[connect]
8430address = "15.204.89.240"
8431ssh = "debian@15.204.89.240"
8432identity_file = "~/.ssh/yah"
8433yubaba = "http://100.64.0.1:7443"
8434"#;
8435        let cfg: MachineConfig = toml::from_str(src).unwrap();
8436        assert_eq!(cfg.hostkey_fingerprint(), Some("SHA256:dmpq"));
8437        assert_eq!(cfg.mesh_ipv4(), Some("100.64.0.1"));
8438        assert_eq!(cfg.yubaba_url().as_deref(), Some("http://100.64.0.1:7443"));
8439    }
8440
8441    /// The post-split shape reads identically to the legacy one above — same
8442    /// three accessor answers from a file that separates the two halves. This
8443    /// is the "unchanged in meaning" guarantee the fleet migration rests on.
8444    #[test]
8445    fn split_shape_is_equivalent_to_legacy_shape() {
8446        let legacy = r#"
8447name = "m"
8448provider = "static"
8449mesh_tags = []
8450hostkey_fingerprint = "SHA256:dmpq"
8451
8452[connect]
8453address = "15.204.89.240"
8454ssh = "debian@15.204.89.240"
8455identity_file = "~/.ssh/yah"
8456yubaba = "http://100.64.0.1:7443"
8457"#;
8458        let split = r#"
8459name = "m"
8460provider = "static"
8461mesh_tags = []
8462
8463[connect]
8464address = "15.204.89.240"
8465ssh = "debian@15.204.89.240"
8466identity_file = "~/.ssh/yah"
8467
8468[registration]
8469hostkey_fingerprint = "SHA256:dmpq"
8470mesh_ipv4 = "100.64.0.1"
8471"#;
8472        let old: MachineConfig = toml::from_str(legacy).unwrap();
8473        let new: MachineConfig = toml::from_str(split).unwrap();
8474        assert_eq!(old.hostkey_fingerprint(), new.hostkey_fingerprint());
8475        assert_eq!(old.mesh_ipv4(), new.mesh_ipv4());
8476        assert_eq!(old.yubaba_url(), new.yubaba_url());
8477    }
8478
8479    /// A non-default `[connect].yubaba_port` is declared reach and composes
8480    /// with the observed mesh address rather than being pinned into a URL.
8481    #[test]
8482    fn declared_port_composes_with_observed_mesh_address() {
8483        let src = r#"
8484name = "m"
8485provider = "static"
8486mesh_tags = []
8487
8488[connect]
8489address = "10.0.0.1"
8490ssh = "yah@10.0.0.1"
8491identity_file = "~/.ssh/yah"
8492yubaba_port = 9443
8493
8494[registration]
8495mesh_ipv4 = "100.64.0.9"
8496"#;
8497        let cfg: MachineConfig = toml::from_str(src).unwrap();
8498        assert_eq!(cfg.connect.as_ref().unwrap().yubaba_port(), 9443);
8499        assert_eq!(cfg.yubaba_url().as_deref(), Some("http://100.64.0.9:9443"));
8500    }
8501
8502    /// R605-T10 inverts R707-T6 for the private-literal case, and this is the
8503    /// node it was inverted for: us-west-014's shape, mesh-joined AND declaring
8504    /// a LAN `[connect].yubaba`. R707-T6 made the literal win outright so
8505    /// `rollout::yubaba::membership_to_nodes` could match the dev group's
8506    /// LAN-addressed raft membership — which fused identity into reach and made
8507    /// every automated dial go to an address only bldg-2506 can route.
8508    /// `lan_endpoint()` now serves that match, so the mesh address wins the
8509    /// dial and the literal is inert.
8510    #[test]
8511    fn a_private_literal_loses_to_the_registered_mesh_address() {
8512        let src = r#"
8513name = "us-west-014"
8514provider = "static"
8515mesh_tags = []
8516
8517[connect]
8518address = "192.168.10.14"
8519ssh = "yah@192.168.10.14"
8520identity_file = "~/.ssh/yah"
8521yubaba = "http://192.168.10.14:7443"
8522
8523[registration]
8524mesh_ipv4 = "100.64.0.6"
8525"#;
8526        let cfg: MachineConfig = toml::from_str(src).unwrap();
8527        assert_eq!(cfg.mesh_ipv4(), Some("100.64.0.6"), "still mesh-joined");
8528        assert_eq!(
8529            cfg.yubaba_url().as_deref(),
8530            Some("http://100.64.0.6:7443"),
8531            "automation dials the mesh, never the LAN literal"
8532        );
8533        assert_eq!(
8534            cfg.lan_endpoint().as_deref(),
8535            Some("192.168.10.14:7443"),
8536            "the LAN address is still recorded — as identity, not as reach"
8537        );
8538    }
8539
8540    /// The refusal R605-T10 asks for: a node whose ONLY declared reach is a LAN
8541    /// literal is unresolvable, and says so by name rather than returning a URL
8542    /// that will time out. us-west-011's shape before this ticket.
8543    #[test]
8544    fn a_lan_only_node_refuses_with_a_named_reason() {
8545        let src = r#"
8546name = "us-west-011"
8547provider = "static"
8548mesh_tags = []
8549
8550[connect]
8551address = "192.168.10.11"
8552ssh = "yah@192.168.10.11"
8553identity_file = "~/.ssh/yah"
8554yubaba = "http://192.168.10.11:7443"
8555"#;
8556        let cfg: MachineConfig = toml::from_str(src).unwrap();
8557        assert_eq!(cfg.yubaba_url(), None);
8558        let err = cfg.reach().unwrap_err();
8559        assert!(err.contains("us-west-011"), "{err}");
8560        assert!(err.contains("192.168.10.11"), "{err}");
8561        assert!(err.contains("mesh_ipv4"), "{err}");
8562    }
8563
8564    /// The loopback placeholder is a genuine declaration ("reach me through the
8565    /// SSH tunnel"), not a LAN literal — 127/8 is not RFC1918. It must keep
8566    /// resolving verbatim; `hub::coordinator::is_loopback_url` is what judges it
8567    /// downstream.
8568    #[test]
8569    fn a_loopback_placeholder_still_resolves_verbatim() {
8570        let src = r#"
8571name = "m"
8572provider = "static"
8573mesh_tags = []
8574
8575[connect]
8576address = "192.168.10.99"
8577ssh = "yah@192.168.10.99"
8578identity_file = "~/.ssh/yah"
8579yubaba = "http://127.0.0.1:7443"
8580"#;
8581        let cfg: MachineConfig = toml::from_str(src).unwrap();
8582        assert_eq!(cfg.yubaba_url().as_deref(), Some("http://127.0.0.1:7443"));
8583    }
8584
8585    #[test]
8586    fn private_ranges_are_exactly_rfc1918() {
8587        for lan in [
8588            "http://192.168.10.11:7443",
8589            "http://10.0.0.5:7443",
8590            "http://172.16.4.1:7443",
8591        ] {
8592            assert!(private_ipv4_from_url(lan).is_some(), "{lan}");
8593        }
8594        for not_lan in [
8595            "http://100.64.0.6:7443",  // mesh
8596            "http://127.0.0.1:7443",   // loopback
8597            "http://172.32.0.1:7443",  // just past 172.16/12
8598            "http://45.32.194.254:80", // public
8599            "http://us-west-001:7443", // name, not a literal
8600        ] {
8601            assert!(private_ipv4_from_url(not_lan).is_none(), "{not_lan}");
8602        }
8603    }
8604
8605    /// `normalize` migrates in place: the legacy fingerprint moves into
8606    /// `[registration]`, the mesh IP is lifted out of the URL, and the derived
8607    /// `[connect].yubaba` is cleared so the two halves cannot drift.
8608    #[test]
8609    fn normalize_migrates_legacy_fields_and_is_idempotent() {
8610        let src = r#"
8611name = "m"
8612provider = "static"
8613mesh_tags = []
8614hostkey_fingerprint = "SHA256:dmpq"
8615
8616[connect]
8617address = "15.204.89.240"
8618ssh = "debian@15.204.89.240"
8619identity_file = "~/.ssh/yah"
8620yubaba = "http://100.64.0.1:7443"
8621"#;
8622        let mut cfg: MachineConfig = toml::from_str(src).unwrap();
8623        cfg.normalize();
8624        assert!(cfg.legacy_hostkey_fingerprint.is_none());
8625        assert_eq!(
8626            cfg.registration.hostkey_fingerprint.as_deref(),
8627            Some("SHA256:dmpq")
8628        );
8629        assert_eq!(cfg.registration.mesh_ipv4.as_deref(), Some("100.64.0.1"));
8630        assert!(cfg.connect.as_ref().unwrap().yubaba.is_none());
8631        // Accessors still answer the same, and re-running changes nothing.
8632        assert_eq!(cfg.yubaba_url().as_deref(), Some("http://100.64.0.1:7443"));
8633        let once = format!("{cfg:?}");
8634        cfg.normalize();
8635        assert_eq!(once, format!("{cfg:?}"));
8636    }
8637
8638    /// A loopback `[connect].yubaba` is a declaration ("no mesh address yet —
8639    /// reach me through the SSH tunnel"), not a stale observation, so
8640    /// `normalize` must leave it alone. us-west-003/011/013 depend on this.
8641    #[test]
8642    fn normalize_leaves_pre_mesh_loopback_declaration_intact() {
8643        let src = r#"
8644name = "m"
8645provider = "static"
8646mesh_tags = []
8647
8648[connect]
8649address = "192.168.10.11"
8650ssh = "yah@192.168.10.11"
8651identity_file = "~/.ssh/yah"
8652yubaba = "http://127.0.0.1:7443"
8653"#;
8654        let mut cfg: MachineConfig = toml::from_str(src).unwrap();
8655        cfg.normalize();
8656        assert_eq!(
8657            cfg.connect.as_ref().unwrap().yubaba.as_deref(),
8658            Some("http://127.0.0.1:7443")
8659        );
8660        assert!(cfg.registration.is_empty());
8661        assert_eq!(cfg.mesh_ipv4(), None);
8662    }
8663
8664    /// `save` normalizes, so a legacy file that round-trips through the writer
8665    /// comes back on the split shape with nothing lost — the property that
8666    /// keeps `yah cloud machine attach` from re-emitting the old layout.
8667    #[test]
8668    fn save_writes_the_split_shape_from_a_legacy_config() {
8669        let tmp = tempfile::TempDir::new().unwrap();
8670        let root = tmp.path();
8671        let src = r#"
8672name = "m"
8673provider = "static"
8674mesh_tags = []
8675hostkey_fingerprint = "SHA256:dmpq"
8676
8677[connect]
8678address = "15.204.89.240"
8679ssh = "debian@15.204.89.240"
8680identity_file = "~/.ssh/yah"
8681yubaba = "http://100.64.0.1:7443"
8682"#;
8683        let cfg: MachineConfig = toml::from_str(src).unwrap();
8684        cfg.save(root).unwrap();
8685
8686        let written = std::fs::read_to_string(root.join("machines/m.toml")).unwrap();
8687        let reg_at = written
8688            .find("[registration]")
8689            .unwrap_or_else(|| panic!("no [registration] table: {written}"));
8690        let fp_at = written
8691            .find("hostkey_fingerprint")
8692            .unwrap_or_else(|| panic!("fingerprint dropped: {written}"));
8693        assert!(
8694            fp_at > reg_at,
8695            "legacy top-level field must not be re-emitted: {written}"
8696        );
8697        assert!(
8698            !written.contains("yubaba ="),
8699            "derived URL must not be re-emitted alongside mesh_ipv4: {written}"
8700        );
8701
8702        let reloaded: MachineConfig = toml::from_str(&written).unwrap();
8703        assert_eq!(reloaded.hostkey_fingerprint(), Some("SHA256:dmpq"));
8704        assert_eq!(
8705            reloaded.yubaba_url().as_deref(),
8706            Some("http://100.64.0.1:7443")
8707        );
8708    }
8709
8710    /// `[registration]` is omitted entirely for a machine nothing has been
8711    /// observed about — a scaffolded declaration stays clean.
8712    #[test]
8713    fn empty_registration_is_omitted_on_serialize() {
8714        let src = r#"
8715name = "m"
8716provider = "static"
8717mesh_tags = []
8718"#;
8719        let cfg: MachineConfig = toml::from_str(src).unwrap();
8720        assert!(cfg.registration.is_empty());
8721        let out = toml::to_string_pretty(&cfg).unwrap();
8722        assert!(!out.contains("[registration]"), "{out}");
8723    }
8724
8725    #[test]
8726    fn driver_provider_without_location_fails_validate() {
8727        // A driver-backed provider (hetzner/vultr) still MUST carry location +
8728        // server_type — the driver can't create a server without them. The
8729        // contract moved from load-time (required field) to provision-time
8730        // (validate), so the TOML loads but validate() rejects it.
8731        let src = r#"
8732name = "us-west-001"
8733provider = "hetzner"
8734mesh_tags = []
8735"#;
8736        let cfg: MachineConfig = toml::from_str(src).unwrap();
8737        assert!(provider_has_machine_driver(&cfg.provider));
8738        let err = cfg.validate().unwrap_err().to_string();
8739        assert!(
8740            err.contains("location"),
8741            "expected location complaint: {err}"
8742        );
8743    }
8744
8745    /// Helper for the new-tree integration tests below: lay out
8746    /// `<workspace>/.yah/{infra,services}/` with `dev-yah` + its mirrors and
8747    /// the three Phase-A providers (cloudflare, hetzner, orbstack).
8748    fn make_new_tree_with_dev_yah(root: &std::path::Path) {
8749        let infra = root.join(".yah").join("infra");
8750        let providers = infra.join("providers");
8751        std::fs::create_dir_all(&providers).unwrap();
8752        std::fs::write(
8753            providers.join("cloudflare.toml"),
8754            r#"schema_version = 1
8755id = "cloudflare"
8756kind = "cloudflare"
8757credentials = "keystore://cloudflare/yah"
8758default_zone = "yah.dev"
8759"#,
8760        )
8761        .unwrap();
8762        std::fs::write(
8763            providers.join("hetzner.toml"),
8764            r#"schema_version = 1
8765id = "hetzner"
8766kind = "hetzner"
8767credentials = "keystore://hetzner/yah"
8768default_location = "pdx"
8769default_server_type = "cpx11"
8770ssh_keys = []
8771"#,
8772        )
8773        .unwrap();
8774        std::fs::write(
8775            providers.join("orbstack.toml"),
8776            r#"schema_version = 1
8777id = "orbstack"
8778kind = "local-container"
8779runtime = "auto"
8780
8781[discovery]
8782orbstack = "~/.orbstack/run/docker.sock"
8783"#,
8784        )
8785        .unwrap();
8786
8787        let svc = root.join(".yah").join("services").join("dev-yah");
8788        std::fs::create_dir_all(svc.join("mirrors")).unwrap();
8789        std::fs::write(
8790            svc.join("service.toml"),
8791            r#"schema_version = 1
8792name = "dev-yah"
8793domain = "yah.dev"
8794
8795[[components]]
8796id = "site"
8797kind = "mesofact-static"
8798path = "app/yah/web"
8799role = "static"
8800"#,
8801        )
8802        .unwrap();
8803        std::fs::write(
8804            svc.join("mirrors/cloud.toml"),
8805            r#"schema_version = 1
8806shape = "single-machine"
8807
8808[providers.static]
8809use = "cloudflare"
8810bucket = "yah-dev"
8811zone = "yah.dev"
8812"#,
8813        )
8814        .unwrap();
8815        std::fs::write(
8816            svc.join("mirrors/local.toml"),
8817            r#"schema_version = 1
8818shape = "local"
8819
8820[providers.static]
8821kind = "miniflare-native"
8822port = 4321
8823
8824[providers.compute]
8825use = "orbstack"
8826"#,
8827        )
8828        .unwrap();
8829    }
8830
8831    #[test]
8832    fn cloud_config_load_new_tree_populates_providers_and_services() {
8833        let tmp = tempfile::TempDir::new().unwrap();
8834        let root = tmp.path();
8835        make_new_tree_with_dev_yah(root);
8836
8837        let cfg = CloudConfig::load(root).unwrap();
8838        assert_eq!(cfg.providers.len(), 3, "three providers loaded");
8839        assert!(cfg.provider("cloudflare").is_some());
8840        assert!(cfg.provider("hetzner").is_some());
8841        assert!(cfg.provider("orbstack").is_some());
8842
8843        let dev = cfg.service("dev-yah").expect("dev-yah service");
8844        assert_eq!(dev.service.domain, "yah.dev");
8845        assert_eq!(dev.service.components.len(), 1);
8846        assert_eq!(dev.mirrors.len(), 2);
8847        // Legacy file stems "cloud" and "local" are normalised to canonical tier names.
8848        assert!(dev.mirrors.contains_key("prod"), "cloud.toml → prod tier");
8849        assert!(dev.mirrors.contains_key("dev"), "local.toml → dev tier");
8850        assert_eq!(dev.mirrors["prod"].shape, MirrorShape::SingleMachine);
8851        assert_eq!(dev.mirrors["dev"].shape, MirrorShape::Local);
8852
8853        // Legacy fields stay empty when no .yah/cloud/ exists.
8854        assert!(cfg.legacy_mirrors.is_empty());
8855        assert!(cfg.workloads.is_empty());
8856    }
8857
8858    #[test]
8859    fn cloud_config_cross_ref_fails_on_missing_provider() {
8860        // Mirror references a provider id that doesn't exist.
8861        let tmp = tempfile::TempDir::new().unwrap();
8862        let root = tmp.path();
8863        let svc = root.join(".yah").join("services").join("dev-yah");
8864        std::fs::create_dir_all(svc.join("mirrors")).unwrap();
8865        std::fs::write(
8866            svc.join("service.toml"),
8867            "schema_version = 1\nname = \"dev-yah\"\ndomain = \"yah.dev\"\n",
8868        )
8869        .unwrap();
8870        std::fs::write(
8871            svc.join("mirrors/prod.toml"),
8872            "schema_version = 1\nshape = \"single-machine\"\n\n[providers.static]\nuse = \"fly-io\"\n",
8873        ).unwrap();
8874
8875        let err = CloudConfig::load(root).unwrap_err();
8876        let msg = err.to_string();
8877        assert!(
8878            msg.contains("fly-io"),
8879            "error should name the missing provider id, got: {msg}"
8880        );
8881        assert!(
8882            msg.contains("providers/fly-io.toml") || msg.contains("no such provider"),
8883            "error should hint at remedy, got: {msg}"
8884        );
8885    }
8886
8887    /// R905. `[build.<id>]` is the per-environment build override, and it is
8888    /// keyed by component id — so a key naming no declared component is a
8889    /// silent no-op: the environment goes on building with the command the
8890    /// operator believed they had replaced.
8891    #[test]
8892    fn cloud_config_cross_ref_fails_on_a_build_override_for_an_unknown_component() {
8893        let tmp = tempfile::TempDir::new().unwrap();
8894        let root = tmp.path();
8895        let svc = root.join(".yah").join("services").join("dev-yah");
8896        std::fs::create_dir_all(svc.join("mirrors")).unwrap();
8897        std::fs::write(
8898            svc.join("service.toml"),
8899            "schema_version = 1\nname = \"dev-yah\"\ndomain = \"yah.dev\"\n\n\
8900             [[components]]\nid = \"site\"\nkind = \"mesofact-spa\"\n\
8901             path = \"web/landing\"\nrole = \"static\"\n",
8902        )
8903        .unwrap();
8904        std::fs::write(
8905            svc.join("mirrors/staging.toml"),
8906            "schema_version = 1\nshape = \"single-machine\"\n\n\
8907             [build.sight]\ncommand = \"bun run build:staging\"\n",
8908        )
8909        .unwrap();
8910
8911        let msg = CloudConfig::load(root).unwrap_err().to_string();
8912        assert!(
8913            msg.contains("build.sight") && msg.contains("site"),
8914            "error should name the bad key and the declared ids, got: {msg}"
8915        );
8916    }
8917
8918    /// The same mirror, spelled correctly, loads and resolves — including the
8919    /// `env` half, which is the knob a project uses when it does not want a
8920    /// sibling `build:<env>` script per environment (R905).
8921    #[test]
8922    fn a_mirror_build_override_resolves_by_component_id() {
8923        let tmp = tempfile::TempDir::new().unwrap();
8924        let root = tmp.path();
8925        let svc = root.join(".yah").join("services").join("dev-yah");
8926        std::fs::create_dir_all(svc.join("mirrors")).unwrap();
8927        std::fs::write(
8928            svc.join("service.toml"),
8929            "schema_version = 1\nname = \"dev-yah\"\ndomain = \"yah.dev\"\n\n\
8930             [[components]]\nid = \"site\"\nkind = \"mesofact-spa\"\n\
8931             path = \"web/landing\"\nrole = \"static\"\n\n\
8932             [[components]]\nid = \"app\"\nkind = \"mesofact-static\"\n\
8933             path = \"app/browser\"\nrole = \"static\"\nmount = \"/app\"\n",
8934        )
8935        .unwrap();
8936        std::fs::write(
8937            svc.join("mirrors/staging.toml"),
8938            "schema_version = 1\nshape = \"single-machine\"\n\n\
8939             [build.site]\ncommand = \"bun run build:staging\"\n\n\
8940             [build.site.env]\nAPI_ORIGIN = \"https://api-staging.example.com\"\n",
8941        )
8942        .unwrap();
8943
8944        let cfg = CloudConfig::load(root).unwrap();
8945        let mirror = &cfg.service("dev-yah").unwrap().mirrors["staging"];
8946
8947        let site = mirror.build_override("site").expect("site override");
8948        assert_eq!(site.command.as_deref(), Some("bun run build:staging"));
8949        assert_eq!(
8950            site.env_pairs(),
8951            vec![(
8952                "API_ORIGIN".to_string(),
8953                "https://api-staging.example.com".to_string()
8954            )]
8955        );
8956        // A sibling component under the same mirror is untouched — the
8957        // override is per component, not per mirror.
8958        assert!(mirror.build_override("app").is_none());
8959    }
8960
8961    /// An override that names nothing reads as no override at all, so callers
8962    /// can treat `Some(_)` as "something differs here" (R905).
8963    #[test]
8964    fn an_empty_build_override_reads_as_absent() {
8965        let empty = MirrorBuildOverride::default();
8966        assert!(empty.is_empty());
8967        let mut m = mirror("");
8968        m.build.insert("site".into(), empty);
8969        assert!(m.build_override("site").is_none());
8970    }
8971
8972    #[test]
8973    fn cloud_config_cross_ref_fails_on_missing_provider_named_by_an_ingress_edge() {
8974        // R845: the edge's own `use` is a provider reference like any other, so
8975        // a typo has to fail here rather than at the Cloudflare arm of apply.
8976        let tmp = tempfile::TempDir::new().unwrap();
8977        let root = tmp.path();
8978        let svc = root.join(".yah").join("services").join("dev-yah");
8979        std::fs::create_dir_all(svc.join("mirrors")).unwrap();
8980        std::fs::write(
8981            svc.join("service.toml"),
8982            "schema_version = 1\nname = \"dev-yah\"\ndomain = \"yah.dev\"\n",
8983        )
8984        .unwrap();
8985        std::fs::write(
8986            svc.join("mirrors/prod.toml"),
8987            "schema_version = 1\nshape = \"single-machine\"\n\n\
8988             [providers.compute]\nkind = \"static\"\nmachine = \"borrowed-01\"\n\
8989             zone = \"a.yah.dev\"\nport = 8080\n\n\
8990             [[ingress]]\nprovider = \"cloudflare-tunnel\"\nuse = \"cloudflar\"\n",
8991        )
8992        .unwrap();
8993
8994        let msg = CloudConfig::load(root).unwrap_err().to_string();
8995        assert!(
8996            msg.contains("ingress[0].use") && msg.contains("cloudflar"),
8997            "error should name the edge and the typo'd id, got: {msg}"
8998        );
8999    }
9000
9001    #[test]
9002    fn cloud_config_cross_ref_passes_on_inline_only_mirror() {
9003        // Inline `kind = "miniflare-native"` doesn't require an infra provider.
9004        let tmp = tempfile::TempDir::new().unwrap();
9005        let root = tmp.path();
9006        let svc = root.join(".yah").join("services").join("local-only");
9007        std::fs::create_dir_all(svc.join("mirrors")).unwrap();
9008        std::fs::write(
9009            svc.join("service.toml"),
9010            "schema_version = 1\nname = \"local-only\"\ndomain = \"local.test\"\n",
9011        )
9012        .unwrap();
9013        std::fs::write(
9014            svc.join("mirrors/local.toml"),
9015            "schema_version = 1\nshape = \"local\"\n\n[providers.static]\nkind = \"miniflare-native\"\nport = 8080\n",
9016        ).unwrap();
9017
9018        // Should load fine: no `use=` references, no providers required.
9019        let cfg = CloudConfig::load(root).unwrap();
9020        assert!(cfg.service("local-only").is_some());
9021    }
9022
9023    fn mirror(src: &str) -> MirrorConfig {
9024        toml::from_str(&format!("schema_version = 1\nshape = \"single-machine\"\n{src}"))
9025            .expect("parse mirror")
9026    }
9027
9028    #[test]
9029    fn passway_machines_reads_both_ingress_spellings_the_same_way() {
9030        // The whole reason this is derived in Rust rather than read off a field
9031        // by the UI: these two mirrors say the identical thing, and a consumer
9032        // that reaches for `ingress_machines` sees the second one as empty.
9033        let scalar = mirror("ingress = \"passway\"\ningress_machines = [\"us-east-001\"]\n");
9034        let edges = mirror(
9035            "[[ingress]]\nprovider = \"passway\"\nmachines = [\"us-east-001\"]\n",
9036        );
9037        assert_eq!(scalar.passway_machines(), Some(vec!["us-east-001".into()]));
9038        assert_eq!(scalar.passway_machines(), edges.passway_machines());
9039    }
9040
9041    #[test]
9042    fn passway_machines_skips_a_cloudflare_tunnel_edge() {
9043        // A cloudflared node publishes through Cloudflare's DNS and does not
9044        // serve `GET /domains/{d}/onboarding`, so naming it here would point
9045        // the custom-domain UI at a node that cannot answer.
9046        let cf_only =
9047            mirror("[[ingress]]\nprovider = \"cloudflare-tunnel\"\nmachines = [\"cf-01\"]\n");
9048        assert_eq!(cf_only.passway_machines(), None);
9049
9050        let mixed = mirror(
9051            "[[ingress]]\nprovider = \"cloudflare-tunnel\"\nmachines = [\"cf-01\"]\n\
9052             slots = [\"static\"]\n\n\
9053             [[ingress]]\nprovider = \"passway\"\nmachines = [\"us-east-001\"]\n\
9054             slots = [\"bundle\"]\n",
9055        );
9056        assert_eq!(mixed.passway_machines(), Some(vec!["us-east-001".into()]));
9057    }
9058
9059    #[test]
9060    fn passway_machines_separates_declared_but_unplaced_from_undeclared() {
9061        // Some(vec![]) means "a passway front door exists, but its placement
9062        // falls back to the fronted slot's and is not knowable from the mirror".
9063        // None means there is no passway front door at all. Collapsing the two
9064        // would make a co-located edge indistinguishable from no edge.
9065        assert_eq!(mirror("ingress = \"passway\"\n").passway_machines(), Some(vec![]));
9066        assert_eq!(mirror("").passway_machines(), None);
9067        assert_eq!(mirror("ingress = \"none\"\n").passway_machines(), None);
9068    }
9069
9070    #[test]
9071    fn passway_machines_is_none_for_a_declaration_that_cannot_mean_anything() {
9072        // `ingress_machines` with no `ingress` is an error `ingress_edges` names
9073        // properly; swallowing it to None here is deliberate, because this is
9074        // read while loading every service in the workspace and hard-failing
9075        // would report an unrelated mirror's shape error from the wrong place.
9076        let orphaned = mirror("ingress_machines = [\"us-east-001\"]\n");
9077        assert!(orphaned.ingress_edges().is_err());
9078        assert_eq!(orphaned.passway_machines(), None);
9079    }
9080
9081    /// Same as [`mirror`] but surfacing the parse error instead of panicking —
9082    /// R870-F26's half-written-auth cases are refused BY serde, so the message
9083    /// only exists on this side of the `expect`.
9084    fn try_mirror(src: &str) -> std::result::Result<MirrorConfig, toml::de::Error> {
9085        toml::from_str(&format!("schema_version = 1\nshape = \"single-machine\"\n{src}"))
9086    }
9087
9088    const FULL_AUTH: &str = "[ingress.auth]\n\
9089         key_secret = \"cheers/yah-camp/verify\"\n\
9090         kid = \"YOHV4Riq-g8fX4uYl8rTjQ\"\n\
9091         iss = \"yah-camp\"\n\
9092         aud = \"analytics.yah.dev\"\n\
9093         require_prefixes = [\"/\"]\n";
9094
9095    /// R870-F26 — the vocabulary itself: a complete `[ingress.auth]` table
9096    /// lands on the edge as the renderer's own `PasswayAuth`, which is what
9097    /// `apply` hands to `PasswayIngressSpec` so the push carries the five
9098    /// variables rather than stripping them.
9099    #[test]
9100    fn an_ingress_edge_carries_a_declared_auth_table_through_to_the_renderers_type() {
9101        let m = mirror(&format!(
9102            "[[ingress]]\nprovider = \"passway\"\nmachines = [\"us-east-001\"]\n{FULL_AUTH}"
9103        ));
9104        let edges = m.ingress_edges().expect("a complete auth table is accepted");
9105        let auth = edges[0].auth.as_ref().expect("the table reached the edge");
9106        assert_eq!(auth.key_secret, "cheers/yah-camp/verify");
9107        assert_eq!(auth.kid, "YOHV4Riq-g8fX4uYl8rTjQ");
9108        assert_eq!(auth.iss, "yah-camp");
9109        assert_eq!(auth.aud, "analytics.yah.dev");
9110        assert_eq!(auth.require_prefixes, vec!["/".to_string()]);
9111    }
9112
9113    /// An edge with no auth is byte-identically what it was before the field
9114    /// existed. The default path is the one this must not move.
9115    #[test]
9116    fn an_edge_that_declares_no_auth_is_unchanged() {
9117        let m = mirror("[[ingress]]\nprovider = \"passway\"\nmachines = [\"us-east-001\"]\n");
9118        assert_eq!(m.ingress_edges().unwrap()[0].auth, None);
9119        // And the scalar spelling, which cannot express auth at all.
9120        assert_eq!(
9121            mirror("ingress = \"passway\"\n").ingress_edges().unwrap()[0].auth,
9122            None
9123        );
9124    }
9125
9126    /// A HALF-WRITTEN table is refused at load, naming the field that is
9127    /// missing — never deployed as a half-configured door.
9128    ///
9129    /// This is serde's own doing, and deliberately so: all five fields are
9130    /// required on `PasswayAuth`, so there is no partial value to construct.
9131    /// The dangerous half is the one that fails QUIETLY — `kid`/`iss`/`aud`
9132    /// without `key_secret` makes passway skip the whole feature and come up
9133    /// anonymous, with nothing anywhere complaining.
9134    #[test]
9135    fn a_half_written_auth_table_is_refused_naming_the_missing_field() {
9136        let cases = [
9137            ("key_secret", "kid = \"k\"\niss = \"i\"\naud = \"a\"\nrequire_prefixes = [\"/\"]\n"),
9138            ("kid", "key_secret = \"s\"\niss = \"i\"\naud = \"a\"\nrequire_prefixes = [\"/\"]\n"),
9139            ("iss", "key_secret = \"s\"\nkid = \"k\"\naud = \"a\"\nrequire_prefixes = [\"/\"]\n"),
9140            ("aud", "key_secret = \"s\"\nkid = \"k\"\niss = \"i\"\nrequire_prefixes = [\"/\"]\n"),
9141            ("require_prefixes", "key_secret = \"s\"\nkid = \"k\"\niss = \"i\"\naud = \"a\"\n"),
9142        ];
9143        for (missing, body) in cases {
9144            let err = try_mirror(&format!(
9145                "[[ingress]]\nprovider = \"passway\"\n[ingress.auth]\n{body}"
9146            ))
9147            .expect_err("a partial auth table must not load");
9148            assert!(
9149                err.to_string().contains(missing),
9150                "the refusal must name {missing}, got: {err}"
9151            );
9152        }
9153    }
9154
9155    /// The half serde cannot catch: a field that is PRESENT and empty. Refused
9156    /// by `PasswayAuth::validate`, the same implementation
9157    /// `yah cloud ingress deploy` runs against its flags — so the two authoring
9158    /// routes cannot disagree about what counts as configured.
9159    #[test]
9160    fn a_present_but_empty_auth_field_is_refused_naming_the_toml_key() {
9161        let err = mirror(
9162            "[[ingress]]\nprovider = \"passway\"\n[ingress.auth]\n\
9163             key_secret = \"s\"\nkid = \"\"\niss = \"i\"\naud = \"a\"\nrequire_prefixes = [\"/\"]\n",
9164        )
9165        .ingress_edges()
9166        .expect_err("an empty kid is a boot panic on a remote node")
9167        .to_string();
9168        assert!(err.contains("[ingress.auth].kid"), "{err}");
9169
9170        // The quiet one: a verify key protecting nothing is authenticated and
9171        // anonymous at once. The message names the TOML key, not the flag —
9172        // sending a mirror author to look for `--require-auth` costs them the
9173        // search this validation exists to save.
9174        let err = mirror(&format!(
9175            "[[ingress]]\nprovider = \"passway\"\n{}",
9176            FULL_AUTH.replace("require_prefixes = [\"/\"]", "require_prefixes = []")
9177        ))
9178        .ingress_edges()
9179        .expect_err("a door protecting no prefix must be refused")
9180        .to_string();
9181        assert!(err.contains("[ingress.auth].require_prefixes"), "{err}");
9182        assert!(!err.contains("--require-auth"), "wrong vocabulary: {err}");
9183    }
9184
9185    /// Auth on a non-passway edge is refused rather than ignored. Only passway
9186    /// renders `PASSWAY_AUTH_*`; silently dropping it hands the operator a door
9187    /// they believe is protected and is not — the exact outcome this whole
9188    /// vocabulary exists to prevent.
9189    #[test]
9190    fn auth_on_a_cloudflare_tunnel_edge_is_refused_rather_than_ignored() {
9191        let err = mirror(&format!(
9192            "[[ingress]]\nprovider = \"cloudflare-tunnel\"\nmachines = [\"cf-01\"]\n{FULL_AUTH}"
9193        ))
9194        .ingress_edges()
9195        .expect_err("only a passway edge can render bearer auth")
9196        .to_string();
9197        assert!(err.contains("passway"), "{err}");
9198        assert!(err.contains("[ingress.auth]"), "{err}");
9199    }
9200
9201    #[test]
9202    fn cloud_config_load_derives_passway_machines_only_for_passway_envs() {
9203        let tmp = tempfile::TempDir::new().unwrap();
9204        let root = tmp.path();
9205        let svc = root.join(".yah").join("services").join("dev-yah");
9206        std::fs::create_dir_all(svc.join("mirrors")).unwrap();
9207        std::fs::write(
9208            svc.join("service.toml"),
9209            "schema_version = 1\nname = \"dev-yah\"\ndomain = \"yah.dev\"\n",
9210        )
9211        .unwrap();
9212        std::fs::write(
9213            svc.join("mirrors/prod.toml"),
9214            "schema_version = 1\nshape = \"single-machine\"\n\
9215             ingress = \"passway\"\ningress_machines = [\"us-east-001\", \"us-west-001\"]\n\n\
9216             [providers.static]\nkind = \"miniflare-native\"\nport = 8080\n",
9217        )
9218        .unwrap();
9219        std::fs::write(
9220            svc.join("mirrors/local.toml"),
9221            "schema_version = 1\nshape = \"local\"\n\n\
9222             [providers.static]\nkind = \"miniflare-native\"\nport = 8080\n",
9223        )
9224        .unwrap();
9225
9226        let cfg = CloudConfig::load(root).unwrap();
9227        let svc = cfg.service("dev-yah").unwrap();
9228        assert_eq!(
9229            svc.passway_machines.get("prod"),
9230            Some(&vec!["us-east-001".to_string(), "us-west-001".to_string()])
9231        );
9232        assert!(
9233            !svc.passway_machines.contains_key("local"),
9234            "an env with no front door must be absent, not empty: {:?}",
9235            svc.passway_machines
9236        );
9237    }
9238
9239    #[test]
9240    fn cloud_config_load_coexists_legacy_and_new_trees() {
9241        // Both trees present — both fields populated independently.
9242        let tmp = tempfile::TempDir::new().unwrap();
9243        let root = tmp.path();
9244        make_new_tree_with_dev_yah(root);
9245
9246        let cloud_dir = make_legacy_cloud_dir(root);
9247        std::fs::create_dir_all(cloud_dir.join("mirrors")).unwrap();
9248        std::fs::write(
9249            cloud_dir.join("mirrors/noisetable.toml"),
9250            "camp = \"noisetable\"\nregions = [\"pdx\"]\nworkloads = []\n",
9251        )
9252        .unwrap();
9253
9254        let cfg = CloudConfig::load(root).unwrap();
9255        assert_eq!(cfg.providers.len(), 3);
9256        assert!(cfg.service("dev-yah").is_some());
9257        assert_eq!(cfg.legacy_mirrors.len(), 1);
9258        assert!(cfg.legacy_mirror("noisetable").is_some());
9259    }
9260
9261    #[test]
9262    fn web_workload_round_trips() {
9263        // app/yah/web/workload.toml is parsed as a WorkloadSpec via the
9264        // workload-spec crate. The minimum-viable manifest here exercises
9265        // schema_version + kind + build fields.
9266        //
9267        // The on-disk file uses the abbreviated v1 form (kind + build); the
9268        // full WorkloadSpec is verbose, so this test asserts the new
9269        // mesofact-static abbreviated form parses as raw TOML (B3 will plumb
9270        // it through WorkloadSpec proper).
9271        // `routes` above [build] — it is a top-level field, and TOML would
9272        // scope it into that table if written below the header (R658-B1).
9273        let src = r#"
9274schema_version = 1
9275kind = "mesofact-static"
9276
9277routes = "./routes.ts"
9278
9279[build]
9280command = "bun run build"
9281out_dir = "dist"
9282"#;
9283        let v: toml::Value = toml::from_str(src).unwrap();
9284        assert_eq!(
9285            v.get("schema_version").and_then(|x| x.as_integer()),
9286            Some(1)
9287        );
9288        assert_eq!(
9289            v.get("kind").and_then(|x| x.as_str()),
9290            Some("mesofact-static")
9291        );
9292        let build = v
9293            .get("build")
9294            .and_then(|x| x.as_table())
9295            .expect("build table");
9296        assert_eq!(
9297            build.get("command").and_then(|x| x.as_str()),
9298            Some("bun run build")
9299        );
9300        assert_eq!(build.get("out_dir").and_then(|x| x.as_str()), Some("dist"));
9301    }
9302
9303    // ─── Canonical CRUD: ServiceConfig/MirrorConfig save + delete (R323-F1) ──
9304
9305    #[test]
9306    fn service_config_save_creates_canonical_toml_and_round_trips() {
9307        let tmp = tempfile::TempDir::new().unwrap();
9308        let root = tmp.path();
9309
9310        let svc = ServiceConfig {
9311            schema_version: 1,
9312            name: "dev-yah".into(),
9313            domain: "yah.dev".into(),
9314            health_path: None,
9315            db: DbCatalog::default(),
9316            components: vec![ServiceComponent {
9317                mount: None,
9318                id: "site".into(),
9319                kind: "mesofact-static".into(),
9320                path: "app/yah/web".into(),
9321                role: "static".into(),
9322                publishes: Some("static".into()),
9323                wave: 0,
9324                git: None,
9325                deploy: Default::default(),
9326            }],
9327        };
9328        svc.save(root).unwrap();
9329
9330        // Landed at the canonical path.
9331        let path = crate::paths::service_toml(root, "dev-yah");
9332        assert!(
9333            path.exists(),
9334            "service.toml should exist at {}",
9335            path.display()
9336        );
9337
9338        // Reloads through the full CloudConfig loader (no mirrors yet).
9339        let cfg = CloudConfig::load(root).unwrap();
9340        let loaded = cfg.service("dev-yah").expect("dev-yah service");
9341        assert_eq!(loaded.service.domain, "yah.dev");
9342        assert_eq!(loaded.service.components.len(), 1);
9343        assert_eq!(
9344            loaded.service.components[0].publishes.as_deref(),
9345            Some("static")
9346        );
9347        assert!(loaded.mirrors.is_empty());
9348    }
9349
9350    #[test]
9351    fn a_declared_health_path_survives_the_loader() {
9352        // The field is only worth having if it reaches the consumer — the
9353        // desktop front-door probe reads it off the loaded service, so a
9354        // round-trip that drops it would leave the probe on `/` with the
9355        // config still reading correctly.
9356        let tmp = tempfile::TempDir::new().unwrap();
9357        let root = tmp.path();
9358
9359        ServiceConfig {
9360            schema_version: 1,
9361            name: "api".into(),
9362            domain: "api.noisetable.com".into(),
9363            health_path: Some("/api/v1/status".into()),
9364            components: vec![],
9365            db: DbCatalog::default(),
9366        }
9367        .save(root)
9368        .unwrap();
9369
9370        let cfg = CloudConfig::load(root).unwrap();
9371        assert_eq!(
9372            cfg.service("api").unwrap().service.health_path.as_deref(),
9373            Some("/api/v1/status")
9374        );
9375    }
9376
9377    #[test]
9378    fn a_relative_health_path_is_refused_at_load() {
9379        // Not a style rule. A relative path joins onto the origin differently
9380        // depending on which URL builder gets it, so the probe would ask a
9381        // question the file does not read as asking — and it would paint a
9382        // confident dot either way.
9383        let tmp = tempfile::TempDir::new().unwrap();
9384        let root = tmp.path();
9385
9386        ServiceConfig {
9387            schema_version: 1,
9388            name: "api".into(),
9389            domain: "api.noisetable.com".into(),
9390            health_path: Some("api/v1/status".into()),
9391            components: vec![],
9392            db: DbCatalog::default(),
9393        }
9394        .save(root)
9395        .unwrap();
9396
9397        let err = CloudConfig::load(root).expect_err("a relative health_path must not load");
9398        let msg = format!("{err:#}");
9399        assert!(
9400            msg.contains("health_path") && msg.contains("/api/v1/status"),
9401            "the error must name the field and the fix, got: {msg}"
9402        );
9403    }
9404
9405    #[test]
9406    fn service_config_save_overwrites_in_place() {
9407        let tmp = tempfile::TempDir::new().unwrap();
9408        let root = tmp.path();
9409
9410        let mut svc = ServiceConfig {
9411            schema_version: 1,
9412            name: "dev-yah".into(),
9413            domain: "yah.dev".into(),
9414            health_path: None,
9415            components: vec![],
9416            db: DbCatalog::default(),
9417        };
9418        svc.save(root).unwrap();
9419        svc.domain = "yah.example".into();
9420        svc.save(root).unwrap();
9421
9422        let cfg = CloudConfig::load(root).unwrap();
9423        assert_eq!(
9424            cfg.service("dev-yah").unwrap().service.domain,
9425            "yah.example"
9426        );
9427    }
9428
9429    #[test]
9430    fn mirror_config_save_round_trips_reference_and_inline_slots() {
9431        let tmp = tempfile::TempDir::new().unwrap();
9432        let root = tmp.path();
9433
9434        // A service must exist so the loader walks the mirrors/ dir.
9435        ServiceConfig {
9436            schema_version: 1,
9437            name: "dev-yah".into(),
9438            domain: "yah.dev".into(),
9439            health_path: None,
9440            components: vec![],
9441            db: DbCatalog::default(),
9442        }
9443        .save(root)
9444        .unwrap();
9445
9446        // The cloudflare provider the reference slot points at must resolve,
9447        // or CloudConfig::load's cross-ref check rejects the tree.
9448        let providers = crate::paths::providers_dir(root);
9449        std::fs::create_dir_all(&providers).unwrap();
9450        std::fs::write(
9451            providers.join("cloudflare.toml"),
9452            "schema_version = 1\nid = \"cloudflare\"\nkind = \"cloudflare\"\n",
9453        )
9454        .unwrap();
9455
9456        let mut providers_map = BTreeMap::new();
9457        providers_map.insert(
9458            "static".to_string(),
9459            MirrorProviderSlot::Reference {
9460                provider_id: "cloudflare".into(),
9461                fields: {
9462                    let mut f = BTreeMap::new();
9463                    f.insert("bucket".to_string(), toml::Value::String("yah-dev".into()));
9464                    f
9465                },
9466            },
9467        );
9468        providers_map.insert(
9469            "compute".to_string(),
9470            MirrorProviderSlot::Inline {
9471                kind: Provider::MiniflareNative,
9472                fields: {
9473                    let mut f = BTreeMap::new();
9474                    f.insert("port".to_string(), toml::Value::Integer(4321));
9475                    f
9476                },
9477            },
9478        );
9479        let mirror = MirrorConfig {
9480            schema_version: 1,
9481            shape: MirrorShape::SingleMachine,
9482            providers: providers_map,
9483            ingress: Default::default(),
9484            ingress_machines: Vec::new(),
9485            drivers: Default::default(),
9486            asset_aliases: Default::default(),
9487            build: Default::default(),
9488        };
9489        // Save with canonical name; legacy "cloud" is normalised to "prod" on load.
9490        mirror.save(root, "dev-yah", "prod").unwrap();
9491
9492        let path = crate::paths::service_mirror_toml(root, "dev-yah", "prod");
9493        assert!(
9494            path.exists(),
9495            "mirror toml should exist at {}",
9496            path.display()
9497        );
9498
9499        let cfg = CloudConfig::load(root).unwrap();
9500        let loaded = &cfg.service("dev-yah").unwrap().mirrors["prod"];
9501        assert_eq!(loaded.shape, MirrorShape::SingleMachine);
9502        assert_eq!(loaded.providers["static"].provider_id(), Some("cloudflare"));
9503        assert_eq!(
9504            loaded.providers["compute"].inline_kind(),
9505            Some(Provider::MiniflareNative)
9506        );
9507    }
9508
9509    #[test]
9510    fn service_delete_removes_dir_and_mirrors() {
9511        let tmp = tempfile::TempDir::new().unwrap();
9512        let root = tmp.path();
9513
9514        let svc = ServiceConfig {
9515            schema_version: 1,
9516            name: "dev-yah".into(),
9517            domain: "yah.dev".into(),
9518            health_path: None,
9519            components: vec![],
9520            db: DbCatalog::default(),
9521        };
9522        svc.save(root).unwrap();
9523        MirrorConfig {
9524            schema_version: 1,
9525            shape: MirrorShape::Local,
9526            providers: BTreeMap::new(),
9527            ingress: Default::default(),
9528            ingress_machines: Vec::new(),
9529            drivers: Default::default(),
9530            asset_aliases: Default::default(),
9531            build: Default::default(),
9532        }
9533        .save(root, "dev-yah", "local")
9534        .unwrap();
9535
9536        assert!(
9537            ServiceConfig::delete(root, "dev-yah").unwrap(),
9538            "first delete reports true"
9539        );
9540        assert!(!crate::paths::service_dir(root, "dev-yah").exists());
9541        // Idempotent: deleting again is a no-op that reports false.
9542        assert!(!ServiceConfig::delete(root, "dev-yah").unwrap());
9543
9544        let cfg = CloudConfig::load(root).unwrap();
9545        assert!(cfg.service("dev-yah").is_none());
9546    }
9547
9548    #[test]
9549    fn mirror_delete_leaves_other_mirrors_and_service_intact() {
9550        let tmp = tempfile::TempDir::new().unwrap();
9551        let root = tmp.path();
9552
9553        ServiceConfig {
9554            schema_version: 1,
9555            name: "dev-yah".into(),
9556            domain: "yah.dev".into(),
9557            health_path: None,
9558            components: vec![],
9559            db: DbCatalog::default(),
9560        }
9561        .save(root)
9562        .unwrap();
9563        for env in ["prod", "local"] {
9564            MirrorConfig {
9565                schema_version: 1,
9566                shape: MirrorShape::Local,
9567                providers: BTreeMap::new(),
9568                ingress: Default::default(),
9569                ingress_machines: Vec::new(),
9570                drivers: Default::default(),
9571                asset_aliases: Default::default(),
9572                build: Default::default(),
9573            }
9574            .save(root, "dev-yah", env)
9575            .unwrap();
9576        }
9577
9578        assert!(MirrorConfig::delete(root, "dev-yah", "prod").unwrap());
9579        assert!(!MirrorConfig::delete(root, "dev-yah", "prod").unwrap());
9580
9581        let cfg = CloudConfig::load(root).unwrap();
9582        let svc = cfg
9583            .service("dev-yah")
9584            .expect("service survives mirror delete");
9585        // "prod" is canonical and deletes directly; "local" normalises to "dev" on load.
9586        assert!(!svc.mirrors.contains_key("prod"));
9587        assert!(svc.mirrors.contains_key("dev"));
9588    }
9589
9590    // ─── DomainConfig (R347-F2) ────────────────────────────────────────────
9591
9592    fn write_marketing_service(root: &Path) {
9593        let svc = ServiceConfig {
9594            schema_version: 1,
9595            name: "yah-marketing".into(),
9596            domain: "yah.dev".into(),
9597            health_path: None,
9598            db: DbCatalog::default(),
9599            components: vec![ServiceComponent {
9600                mount: None,
9601                id: "site".into(),
9602                kind: "mesofact-static".into(),
9603                path: "app/yah/web".into(),
9604                role: "static".into(),
9605                publishes: None,
9606                wave: 0,
9607                git: None,
9608                deploy: Default::default(),
9609            }],
9610        };
9611        svc.save(root).unwrap();
9612    }
9613
9614    #[test]
9615    fn round_trip_domain_with_each_route_mode() {
9616        let dom = DomainConfig {
9617            schema_version: 1,
9618            name: "yah-dev".into(),
9619            domain: "yah.dev".into(),
9620            front_door: FrontDoor::Worker,
9621            cdn_bucket: "yah-dev".into(),
9622            worker_bundle_path: Some(".yah/workers/yah-dev/".into()),
9623            routes: vec![
9624                DomainRoute {
9625                    headers: Default::default(),
9626                    path: "/".into(),
9627                    mode: RouteMode::Static {
9628                        component: "yah-marketing/site".into(),
9629                    },
9630                },
9631                DomainRoute {
9632                    headers: Default::default(),
9633                    path: "/dashboard/api/*".into(),
9634                    mode: RouteMode::Backend {
9635                        component: "yah-dashboard/api".into(),
9636                        origin: "https://api.dashboard.yah.dev".into(),
9637                        origin_path: None,
9638                    },
9639                },
9640                DomainRoute {
9641                    headers: Default::default(),
9642                    path: "/old".into(),
9643                    mode: RouteMode::Redirect {
9644                        target: "https://yah.dev/blog".into(),
9645                        status: 308,
9646                    },
9647                },
9648            ],
9649        };
9650        let s = toml::to_string(&dom).unwrap();
9651        let back: DomainConfig = toml::from_str(&s).unwrap();
9652        assert_eq!(back.name, "yah-dev");
9653        assert_eq!(back.routes.len(), 3);
9654        assert!(matches!(back.routes[0].mode, RouteMode::Static { .. }));
9655        assert!(matches!(back.routes[1].mode, RouteMode::Backend { .. }));
9656        assert!(matches!(back.routes[2].mode, RouteMode::Redirect { .. }));
9657    }
9658
9659    /// A one-route `cdn.noisetable.com`-shaped manifest whose static route body
9660    /// is `body`.
9661    fn static_route_manifest(body: &str) -> String {
9662        format!(
9663            "schema_version = 1\nname = \"cdn-noisetable-com\"\ndomain = \"cdn.noisetable.com\"\n\
9664             front_door = \"worker\"\ncdn_bucket = \"noisetable-marketing\"\n\n\
9665             [[routes]]\npath = \"/engine/*\"\nmode = \"static\"\n{body}\n"
9666        )
9667    }
9668
9669    /// R560-F13 — a static route names a `component` OR a `bucket`, never both
9670    /// and never neither, and a bucket has to be a real R2 bucket name.
9671    #[test]
9672    fn a_static_route_names_exactly_one_of_component_or_bucket() {
9673        let dom: DomainConfig =
9674            toml::from_str(&static_route_manifest("bucket = \"noisetable-releases\"")).unwrap();
9675        assert!(matches!(
9676            &dom.routes[0].mode,
9677            RouteMode::StaticBucket { bucket } if bucket == "noisetable-releases"
9678        ));
9679        dom.validate_front_door().unwrap();
9680
9681        let dom: DomainConfig =
9682            toml::from_str(&static_route_manifest("component = \"svc/site\"")).unwrap();
9683        assert!(matches!(
9684            &dom.routes[0].mode,
9685            RouteMode::Static { component } if component == "svc/site"
9686        ));
9687
9688        for (body, needle) in [
9689            (
9690                "component = \"svc/site\"\nbucket = \"noisetable-releases\"",
9691                "both",
9692            ),
9693            ("", "neither"),
9694            ("bucket = \"Noisetable_Releases\"", "not an R2 bucket name"),
9695        ] {
9696            let err = toml::from_str::<DomainConfig>(&static_route_manifest(body))
9697                .unwrap_err()
9698                .to_string();
9699            assert!(err.contains(needle), "{body:?}: {err}");
9700        }
9701    }
9702
9703    /// The Rust variant is `StaticBucket`; the manifest spelling stays
9704    /// `mode = "static"` + `bucket`, through a save as well as a load.
9705    #[test]
9706    fn a_bucket_route_round_trips_as_mode_static_with_a_bucket_key() {
9707        let dom: DomainConfig =
9708            toml::from_str(&static_route_manifest("bucket = \"noisetable-releases\"")).unwrap();
9709        let s = toml::to_string(&dom).unwrap();
9710        assert!(s.contains("mode = \"static\""), "{s}");
9711        assert!(s.contains("bucket = \"noisetable-releases\""), "{s}");
9712        assert!(!s.contains("component"), "{s}");
9713        let back: DomainConfig = toml::from_str(&s).unwrap();
9714        assert!(matches!(back.routes[0].mode, RouteMode::StaticBucket { .. }));
9715    }
9716
9717    /// Passway has no R2 read path, so a bucket route on it is refused at load
9718    /// naming the route, not compiled into an entry that door cannot serve.
9719    #[test]
9720    fn passway_refuses_a_bucket_route() {
9721        let mut dom: DomainConfig =
9722            toml::from_str(&static_route_manifest("bucket = \"noisetable-releases\"")).unwrap();
9723        dom.front_door = FrontDoor::Passway;
9724        let err = dom.validate_front_door().unwrap_err().to_string();
9725        assert!(err.contains("passway") && err.contains("/engine/*"), "{err}");
9726    }
9727
9728    #[test]
9729    fn redirect_status_defaults_to_308() {
9730        let src = r#"
9731schema_version = 1
9732name = "yah-dev"
9733domain = "yah.dev"
9734front_door = "worker"
9735cdn_bucket = "yah-dev"
9736
9737[[routes]]
9738path = "/old"
9739mode = "redirect"
9740target = "https://yah.dev/blog"
9741"#;
9742        let dom: DomainConfig = toml::from_str(src).unwrap();
9743        let RouteMode::Redirect { status, .. } = &dom.routes[0].mode else {
9744            panic!("expected redirect");
9745        };
9746        assert_eq!(*status, 308);
9747    }
9748
9749    #[test]
9750    fn missing_domains_dir_is_empty() {
9751        let tmp = tempfile::TempDir::new().unwrap();
9752        // R844-B7: `.yah/` must exist or this is a wrong-root error rather
9753        // than an empty tree. The absent directory under test is `domains/`.
9754        std::fs::create_dir_all(tmp.path().join(".yah")).unwrap();
9755        let cfg = CloudConfig::load(tmp.path()).unwrap();
9756        assert!(cfg.domains.is_empty());
9757    }
9758
9759    #[test]
9760    fn save_reload_roundtrip() {
9761        let tmp = tempfile::TempDir::new().unwrap();
9762        let root = tmp.path();
9763        write_marketing_service(root);
9764
9765        let dom = DomainConfig {
9766            schema_version: 1,
9767            name: "yah-dev".into(),
9768            domain: "yah.dev".into(),
9769            front_door: FrontDoor::Worker,
9770            cdn_bucket: "yah-dev".into(),
9771            worker_bundle_path: None,
9772            routes: vec![DomainRoute {
9773                headers: Default::default(),
9774                path: "/".into(),
9775                mode: RouteMode::Static {
9776                    component: "yah-marketing/site".into(),
9777                },
9778            }],
9779        };
9780        dom.save(root).unwrap();
9781
9782        let cfg = CloudConfig::load(root).unwrap();
9783        let loaded = cfg.domain("yah-dev").expect("yah-dev domain");
9784        assert_eq!(loaded.domain, "yah.dev");
9785        assert_eq!(loaded.routes.len(), 1);
9786    }
9787
9788    #[test]
9789    fn delete_returns_false_when_absent() {
9790        let tmp = tempfile::TempDir::new().unwrap();
9791        assert!(!DomainConfig::delete(tmp.path(), "no-such-domain").unwrap());
9792    }
9793
9794    #[test]
9795    fn delete_returns_true_first_time() {
9796        let tmp = tempfile::TempDir::new().unwrap();
9797        let root = tmp.path();
9798        let dom = DomainConfig {
9799            schema_version: 1,
9800            name: "yah-dev".into(),
9801            domain: "yah.dev".into(),
9802            front_door: FrontDoor::BucketDirect,
9803            cdn_bucket: "yah-dev".into(),
9804            worker_bundle_path: None,
9805            routes: vec![],
9806        };
9807        dom.save(root).unwrap();
9808        assert!(DomainConfig::delete(root, "yah-dev").unwrap());
9809        assert!(!DomainConfig::delete(root, "yah-dev").unwrap());
9810    }
9811
9812    // ---- R594-F12: front-door discriminator ------------------------------
9813
9814    /// Write a raw domain manifest so the tests exercise the deserialize +
9815    /// validate path, not a hand-built struct that skipped serde.
9816    fn write_domain_toml(root: &Path, stem: &str, body: &str) {
9817        let dir = root.join(".yah").join("domains");
9818        std::fs::create_dir_all(&dir).unwrap();
9819        std::fs::write(dir.join(format!("{stem}.toml")), body).unwrap();
9820    }
9821
9822    #[test]
9823    fn front_door_is_required() {
9824        let tmp = tempfile::TempDir::new().unwrap();
9825        let root = tmp.path();
9826        write_marketing_service(root);
9827        write_domain_toml(
9828            root,
9829            "yah-dev",
9830            r#"
9831schema_version = 1
9832name = "yah-dev"
9833domain = "yah.dev"
9834cdn_bucket = "yah-dev"
9835[[routes]]
9836path = "/*"
9837mode = "static"
9838component = "yah-marketing/site"
9839"#,
9840        );
9841        let err = CloudConfig::load(root).unwrap_err().to_string();
9842        // serde's own missing-field message; the point is that omitting the
9843        // discriminator is not a silently-defaulted state.
9844        assert!(err.contains("yah-dev.toml"), "{err}");
9845    }
9846
9847    #[test]
9848    fn bucket_direct_with_routes_is_rejected() {
9849        let tmp = tempfile::TempDir::new().unwrap();
9850        let root = tmp.path();
9851        write_marketing_service(root);
9852        write_domain_toml(
9853            root,
9854            "cdn-yah-dev",
9855            r#"
9856schema_version = 1
9857name = "cdn-yah-dev"
9858domain = "cdn.yah.dev"
9859front_door = "bucket-direct"
9860cdn_bucket = "yah-dev"
9861[[routes]]
9862path = "/docs/*"
9863mode = "static"
9864component = "yah-marketing/site"
9865"#,
9866        );
9867        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
9868        assert!(err.contains("front_door"), "{err}");
9869        assert!(err.contains("/docs/*"), "{err}");
9870    }
9871
9872    #[test]
9873    fn bucket_direct_with_worker_bundle_path_is_rejected() {
9874        let tmp = tempfile::TempDir::new().unwrap();
9875        let root = tmp.path();
9876        write_domain_toml(
9877            root,
9878            "cdn-yah-dev",
9879            r#"
9880schema_version = 1
9881name = "cdn-yah-dev"
9882domain = "cdn.yah.dev"
9883front_door = "bucket-direct"
9884cdn_bucket = "yah-dev"
9885worker_bundle_path = ".yah/workers/cdn-yah-dev/"
9886"#,
9887        );
9888        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
9889        assert!(err.contains("worker_bundle_path"), "{err}");
9890    }
9891
9892    // ── R746: per-route response headers + component mounts ──────────────────
9893
9894    /// A two-component service: `site` at the root, `app` mounted at `/app`
9895    /// with isolation headers on its route. This is the noisetable.com shape
9896    /// the primitive was built for.
9897    fn write_two_component_service(root: &Path) {
9898        let svc = ServiceConfig {
9899            schema_version: 1,
9900            name: "yah-marketing".into(),
9901            domain: "yah.dev".into(),
9902            health_path: None,
9903            db: DbCatalog::default(),
9904            components: vec![
9905                ServiceComponent {
9906                    mount: None,
9907                    id: "site".into(),
9908                    kind: "mesofact-static".into(),
9909                    path: "app/yah/web".into(),
9910                    role: "static".into(),
9911                    publishes: None,
9912                    wave: 0,
9913                    git: None,
9914                    deploy: Default::default(),
9915                },
9916                ServiceComponent {
9917                    mount: Some("/app".into()),
9918                    id: "app".into(),
9919                    kind: "mesofact-static".into(),
9920                    path: "app/browser".into(),
9921                    role: "static".into(),
9922                    publishes: None,
9923                    wave: 0,
9924                    git: None,
9925                    deploy: Default::default(),
9926                },
9927            ],
9928        };
9929        svc.save(root).unwrap();
9930    }
9931
9932    const MOUNTED_DOMAIN: &str = r#"
9933schema_version = 1
9934name = "yah-dev"
9935domain = "yah.dev"
9936front_door = "worker"
9937cdn_bucket = "yah-dev"
9938
9939[[routes]]
9940path = "/app/*"
9941mode = "static"
9942component = "yah-marketing/app"
9943headers = { "Cross-Origin-Opener-Policy" = "same-origin", "Cross-Origin-Embedder-Policy" = "require-corp" }
9944
9945[[routes]]
9946path = "/*"
9947mode = "static"
9948component = "yah-marketing/site"
9949"#;
9950
9951    #[test]
9952    fn a_mounted_component_routed_at_its_mount_loads() {
9953        let tmp = tempfile::TempDir::new().unwrap();
9954        let root = tmp.path();
9955        write_two_component_service(root);
9956        write_domain_toml(root, "yah-dev", MOUNTED_DOMAIN);
9957        let cfg = CloudConfig::load(root).unwrap();
9958        let dom = cfg.domain("yah-dev").unwrap();
9959        assert_eq!(dom.routes.len(), 2);
9960        assert_eq!(
9961            dom.routes[0].headers.get("Cross-Origin-Opener-Policy").map(String::as_str),
9962            Some("same-origin")
9963        );
9964        assert!(dom.routes[1].headers.is_empty());
9965    }
9966
9967    /// The header table reaches the Worker in MANIFEST order with headerless
9968    /// routes dropped. Order is the whole contract — the front door applies the
9969    /// first match, so `/app/*` before `/*` is what isolates the app without
9970    /// isolating the marketing site.
9971    #[test]
9972    fn route_headers_json_preserves_order_and_drops_headerless_routes() {
9973        let tmp = tempfile::TempDir::new().unwrap();
9974        let root = tmp.path();
9975        write_two_component_service(root);
9976        write_domain_toml(root, "yah-dev", MOUNTED_DOMAIN);
9977        let cfg = CloudConfig::load(root).unwrap();
9978        let json = cfg.domain("yah-dev").unwrap().route_headers_json();
9979
9980        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
9981        let rules = parsed.as_array().unwrap();
9982        assert_eq!(rules.len(), 1, "the headerless catch-all is dropped: {json}");
9983        assert_eq!(rules[0]["path"], "/app/*");
9984        assert_eq!(rules[0]["headers"]["Cross-Origin-Embedder-Policy"], "require-corp");
9985    }
9986
9987    #[test]
9988    fn route_headers_json_is_an_empty_array_when_nothing_declares_headers() {
9989        let tmp = tempfile::TempDir::new().unwrap();
9990        let root = tmp.path();
9991        write_marketing_service(root);
9992        write_domain_toml(
9993            root,
9994            "yah-dev",
9995            r#"
9996schema_version = 1
9997name = "yah-dev"
9998domain = "yah.dev"
9999front_door = "worker"
10000cdn_bucket = "yah-dev"
10001
10002[[routes]]
10003path = "/*"
10004mode = "static"
10005component = "yah-marketing/site"
10006"#,
10007        );
10008        let cfg = CloudConfig::load(root).unwrap();
10009        assert_eq!(cfg.domain("yah-dev").unwrap().route_headers_json(), "[]");
10010    }
10011
10012    /// The reconciler's own entry point: given a workspace root and a service
10013    /// name, produce the binding value. `"[]"` when nothing routes the service.
10014    #[test]
10015    fn route_headers_for_service_reads_the_workspace_domains() {
10016        let tmp = tempfile::TempDir::new().unwrap();
10017        let root = tmp.path();
10018        write_two_component_service(root);
10019        write_domain_toml(root, "yah-dev", MOUNTED_DOMAIN);
10020        assert!(route_headers_for_service(root, "yah-marketing")
10021            .unwrap()
10022            .contains("require-corp"));
10023        assert_eq!(route_headers_for_service(root, "some-other-svc").unwrap(), "[]");
10024    }
10025
10026    // ---- R749-T5: a broken table fails the DEPLOY, not the edge -----------
10027
10028    /// The manifest's `headers` map is hand-written TOML, so a header name with
10029    /// spaces in it is one keystroke away — and it survives serialization into
10030    /// a structurally-valid table that neither front door can apply. Fail at
10031    /// load, naming the domain, the route and the header, instead of shipping a
10032    /// binding the Worker throws on and an origin that refuses to boot.
10033    #[test]
10034    fn a_route_header_name_that_is_not_a_header_name_fails_the_load() {
10035        let tmp = tempfile::TempDir::new().unwrap();
10036        let root = tmp.path();
10037        write_marketing_service(root);
10038        write_domain_toml(
10039            root,
10040            "yah-dev",
10041            r#"
10042schema_version = 1
10043name = "yah-dev"
10044domain = "yah.dev"
10045front_door = "worker"
10046cdn_bucket = "yah-dev"
10047
10048[[routes]]
10049path = "/*"
10050mode = "static"
10051component = "yah-marketing/site"
10052headers = { "Cross Origin Opener Policy" = "same-origin" }
10053"#,
10054        );
10055        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
10056        assert!(err.contains("yah-dev"), "{err}");
10057        assert!(err.contains("/*"), "{err}");
10058        assert!(err.contains("Cross Origin Opener Policy"), "{err}");
10059        assert!(err.contains("not a valid HTTP header name"), "{err}");
10060    }
10061
10062    /// A newline in a value is header injection if it ever reached the wire, so
10063    /// both doors reject it and so does this.
10064    #[test]
10065    fn a_route_header_value_that_is_not_a_header_value_fails_the_load() {
10066        let tmp = tempfile::TempDir::new().unwrap();
10067        let root = tmp.path();
10068        write_marketing_service(root);
10069        write_domain_toml(
10070            root,
10071            "yah-dev",
10072            r#"
10073schema_version = 1
10074name = "yah-dev"
10075domain = "yah.dev"
10076front_door = "worker"
10077cdn_bucket = "yah-dev"
10078
10079[[routes]]
10080path = "/*"
10081mode = "static"
10082component = "yah-marketing/site"
10083headers = { "X-Frame-Options" = "DENY\nSet-Cookie: pwned=1" }
10084"#,
10085        );
10086        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
10087        assert!(err.contains("X-Frame-Options"), "{err}");
10088        assert!(err.contains("not a valid HTTP header value"), "{err}");
10089    }
10090
10091    /// The invariant this gate exists to hold: everything `route_headers_json`
10092    /// emits is applicable. A headerless route contributes no rule, so its path
10093    /// is not the table's business — only rules that ship are checked.
10094    #[test]
10095    fn a_headerless_route_is_not_subject_to_the_route_header_gate() {
10096        let tmp = tempfile::TempDir::new().unwrap();
10097        let root = tmp.path();
10098        write_two_component_service(root);
10099        write_domain_toml(root, "yah-dev", MOUNTED_DOMAIN);
10100        let cfg = CloudConfig::load(root).unwrap();
10101        cfg.domain("yah-dev")
10102            .unwrap()
10103            .validate_route_headers()
10104            .unwrap();
10105    }
10106
10107    /// A `bucket-direct` domain has no front door to set headers on, so it must
10108    /// not be picked up as a service's header source.
10109    #[test]
10110    fn route_headers_ignores_domains_that_are_not_route_driven() {
10111        let doms: BTreeMap<String, DomainConfig> = [(
10112            "cdn".to_string(),
10113            DomainConfig {
10114                schema_version: 1,
10115                name: "cdn".into(),
10116                domain: "cdn.yah.dev".into(),
10117                front_door: FrontDoor::BucketDirect,
10118                cdn_bucket: "yah-dev".into(),
10119                worker_bundle_path: None,
10120                routes: vec![],
10121            },
10122        )]
10123        .into_iter()
10124        .collect();
10125        assert!(domain_serving_service(&doms, "yah-marketing").is_none());
10126    }
10127
10128    #[test]
10129    fn a_mount_that_disagrees_with_its_route_path_is_rejected() {
10130        let tmp = tempfile::TempDir::new().unwrap();
10131        let root = tmp.path();
10132        write_two_component_service(root);
10133        write_domain_toml(
10134            root,
10135            "yah-dev",
10136            r#"
10137schema_version = 1
10138name = "yah-dev"
10139domain = "yah.dev"
10140front_door = "worker"
10141cdn_bucket = "yah-dev"
10142
10143[[routes]]
10144path = "/studio/*"
10145mode = "static"
10146component = "yah-marketing/app"
10147"#,
10148        );
10149        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
10150        assert!(err.contains("mount = \"/app\""), "{err}");
10151        assert!(err.contains("/studio/*"), "{err}");
10152    }
10153
10154    /// The other direction: routing an unmounted component under a sub-path
10155    /// points requests at a prefix nothing published to.
10156    #[test]
10157    fn routing_an_unmounted_component_under_a_subpath_is_rejected() {
10158        let tmp = tempfile::TempDir::new().unwrap();
10159        let root = tmp.path();
10160        write_marketing_service(root);
10161        write_domain_toml(
10162            root,
10163            "yah-dev",
10164            r#"
10165schema_version = 1
10166name = "yah-dev"
10167domain = "yah.dev"
10168front_door = "worker"
10169cdn_bucket = "yah-dev"
10170
10171[[routes]]
10172path = "/docs/*"
10173mode = "static"
10174component = "yah-marketing/site"
10175"#,
10176        );
10177        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
10178        assert!(err.contains("no `mount`"), "{err}");
10179        assert!(err.contains("/docs"), "{err}");
10180    }
10181
10182    #[test]
10183    fn mount_and_route_prefix_normalization_agree() {
10184        for m in ["/app", "app", "app/", "/app/"] {
10185            assert_eq!(normalize_mount(m), "app", "mount {m:?}");
10186        }
10187        assert_eq!(normalize_mount("/"), "");
10188        assert_eq!(route_path_prefix("/*"), "");
10189        assert_eq!(route_path_prefix("/app/*"), "app");
10190        assert_eq!(route_path_prefix("/app"), "app");
10191        assert_eq!(route_path_prefix("/"), "");
10192    }
10193
10194    // ── R870-B11: a mount is owned by exactly one bundle-tier component ────
10195
10196    /// Two bundle-tier components at the same explicit mount would stage into
10197    /// the same `app/dist/<mount>/` prefix inside one assembled bundle and
10198    /// silently clobber each other — reject at load, before that happens.
10199    #[test]
10200    fn two_bundle_components_at_the_same_mount_are_rejected() {
10201        let tmp = tempfile::TempDir::new().unwrap();
10202        let root = tmp.path();
10203        let svc = ServiceConfig {
10204            schema_version: 1,
10205            name: "noisetable-marketing".into(),
10206            domain: "noisetable.com".into(),
10207            health_path: None,
10208            db: DbCatalog::default(),
10209            components: vec![
10210                ServiceComponent {
10211                    mount: Some("/app".into()),
10212                    id: "app".into(),
10213                    kind: "mesofact-static".into(),
10214                    path: "app/browser".into(),
10215                    role: "static".into(),
10216                    publishes: None,
10217                    wave: 0,
10218                    git: None,
10219                    deploy: Default::default(),
10220                },
10221                ServiceComponent {
10222                    mount: Some("app/".into()),
10223                    id: "app2".into(),
10224                    kind: "mesofact-spa".into(),
10225                    path: "app/other".into(),
10226                    role: "static".into(),
10227                    publishes: None,
10228                    wave: 0,
10229                    git: None,
10230                    deploy: Default::default(),
10231                },
10232            ],
10233        };
10234        svc.save(root).unwrap();
10235        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
10236        assert!(err.contains("\"app\""), "{err}");
10237        assert!(err.contains("\"app2\""), "{err}");
10238        assert!(err.contains("mount = \"/app\""), "{err}");
10239    }
10240
10241    /// The unmounted case: two bundle-tier components both leaving `mount`
10242    /// unset both claim the service root, which collides exactly the same
10243    /// way — this is the noisetable shape the ticket was filed against, if
10244    /// `app`'s mount had been forgotten instead of declared.
10245    #[test]
10246    fn two_bundle_components_with_no_mount_are_rejected() {
10247        let tmp = tempfile::TempDir::new().unwrap();
10248        let root = tmp.path();
10249        let svc = ServiceConfig {
10250            schema_version: 1,
10251            name: "noisetable-marketing".into(),
10252            domain: "noisetable.com".into(),
10253            health_path: None,
10254            db: DbCatalog::default(),
10255            components: vec![
10256                ServiceComponent {
10257                    mount: None,
10258                    id: "site".into(),
10259                    kind: "mesofact-spa".into(),
10260                    path: "web/landing".into(),
10261                    role: "static".into(),
10262                    publishes: None,
10263                    wave: 0,
10264                    git: None,
10265                    deploy: Default::default(),
10266                },
10267                ServiceComponent {
10268                    mount: None,
10269                    id: "app".into(),
10270                    kind: "mesofact-static".into(),
10271                    path: "app/browser".into(),
10272                    role: "static".into(),
10273                    publishes: None,
10274                    wave: 0,
10275                    git: None,
10276                    deploy: Default::default(),
10277                },
10278            ],
10279        };
10280        svc.save(root).unwrap();
10281        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
10282        assert!(err.contains("\"site\""), "{err}");
10283        assert!(err.contains("\"app\""), "{err}");
10284        assert!(err.contains("the service root"), "{err}");
10285    }
10286
10287    /// R870-F23 widened the same loop to the workload tier. Two components in
10288    /// DIFFERENT tiers at one mount is the same clobber read from the routing
10289    /// side: the inner door's table names one upstream for that prefix, so a
10290    /// request reaches either the bundle or the workload and nothing says
10291    /// which.
10292    #[test]
10293    fn a_bundle_component_and_a_workload_component_at_one_mount_are_rejected() {
10294        let tmp = tempfile::TempDir::new().unwrap();
10295        let root = tmp.path();
10296        let svc = ServiceConfig {
10297            schema_version: 1,
10298            name: "noisetable".into(),
10299            domain: "noisetable.com".into(),
10300            health_path: None,
10301            db: DbCatalog::default(),
10302            components: vec![
10303                ServiceComponent {
10304                    mount: Some("app".into()),
10305                    id: "app-bundle".into(),
10306                    kind: "mesofact-spa".into(),
10307                    path: "app/browser".into(),
10308                    role: "static".into(),
10309                    publishes: None,
10310                    wave: 0,
10311                    git: None,
10312                    deploy: DeployTier::Bundle,
10313                },
10314                ServiceComponent {
10315                    mount: Some("/app/".into()),
10316                    id: "app-service".into(),
10317                    kind: "container".into(),
10318                    path: "app/server".into(),
10319                    role: "compute".into(),
10320                    publishes: None,
10321                    wave: 0,
10322                    git: None,
10323                    deploy: DeployTier::Workload,
10324                },
10325            ],
10326        };
10327        svc.save(root).unwrap();
10328        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
10329        assert!(err.contains("\"app-bundle\""), "{err}");
10330        assert!(err.contains("\"app-service\""), "{err}");
10331        assert!(err.contains("deploys as its own workload"), "{err}");
10332    }
10333
10334    /// And two WORKLOAD-tier components at one mount, which the pre-R870-F23
10335    /// loop skipped entirely (it filtered on `kind`, and a workload-tier
10336    /// component need not be a mesofact kind at all).
10337    #[test]
10338    fn two_workload_components_at_one_mount_are_rejected() {
10339        let tmp = tempfile::TempDir::new().unwrap();
10340        let root = tmp.path();
10341        let svc = ServiceConfig {
10342            schema_version: 1,
10343            name: "noisetable".into(),
10344            domain: "noisetable.com".into(),
10345            health_path: None,
10346            db: DbCatalog::default(),
10347            components: vec![
10348                ServiceComponent {
10349                    mount: None,
10350                    id: "api".into(),
10351                    kind: "container".into(),
10352                    path: "svc/api".into(),
10353                    role: "compute".into(),
10354                    publishes: None,
10355                    wave: 0,
10356                    git: None,
10357                    deploy: DeployTier::Workload,
10358                },
10359                ServiceComponent {
10360                    mount: Some("/".into()),
10361                    id: "api2".into(),
10362                    kind: "container".into(),
10363                    path: "svc/api2".into(),
10364                    role: "compute".into(),
10365                    publishes: None,
10366                    wave: 0,
10367                    git: None,
10368                    deploy: DeployTier::Workload,
10369                },
10370            ],
10371        };
10372        svc.save(root).unwrap();
10373        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
10374        assert!(err.contains("inner-door route table"), "{err}");
10375        assert!(err.contains("the service root"), "{err}");
10376    }
10377
10378    /// The legitimate shape (distinct mounts) is untouched — regression guard
10379    /// so the new check does not become the next silent-overwrite bug.
10380    #[test]
10381    fn bundle_components_at_distinct_mounts_still_load() {
10382        let tmp = tempfile::TempDir::new().unwrap();
10383        let root = tmp.path();
10384        write_two_component_service(root);
10385        assert!(CloudConfig::load(root).is_ok());
10386    }
10387
10388    #[test]
10389    fn worker_with_no_routes_is_rejected() {
10390        let tmp = tempfile::TempDir::new().unwrap();
10391        let root = tmp.path();
10392        write_domain_toml(
10393            root,
10394            "yah-dev",
10395            r#"
10396schema_version = 1
10397name = "yah-dev"
10398domain = "yah.dev"
10399front_door = "worker"
10400cdn_bucket = "yah-dev"
10401"#,
10402        );
10403        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
10404        assert!(err.contains("front_door = \"worker\""), "{err}");
10405        assert!(err.contains("404"), "{err}");
10406    }
10407
10408    #[test]
10409    fn passway_with_no_routes_is_rejected_too() {
10410        let tmp = tempfile::TempDir::new().unwrap();
10411        let root = tmp.path();
10412        write_domain_toml(
10413            root,
10414            "yah-dev",
10415            r#"
10416schema_version = 1
10417name = "yah-dev"
10418domain = "yah.dev"
10419front_door = "passway"
10420cdn_bucket = "yah-dev"
10421"#,
10422        );
10423        let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
10424        assert!(err.contains("front_door = \"passway\""), "{err}");
10425    }
10426
10427    #[test]
10428    fn bucket_direct_without_routes_loads() {
10429        let tmp = tempfile::TempDir::new().unwrap();
10430        let root = tmp.path();
10431        // Exactly the shape .yah/domains/cdn-yah-dev.toml ships (W175: a pure
10432        // asset tier deliberately has no Worker behaviours).
10433        write_domain_toml(
10434            root,
10435            "cdn-yah-dev",
10436            r#"
10437schema_version = 1
10438name = "cdn-yah-dev"
10439domain = "cdn.yah.dev"
10440front_door = "bucket-direct"
10441cdn_bucket = "yah-dev"
10442"#,
10443        );
10444        let cfg = CloudConfig::load(root).unwrap();
10445        let dom = cfg.domain("cdn-yah-dev").expect("cdn-yah-dev domain");
10446        assert_eq!(dom.front_door, FrontDoor::BucketDirect);
10447        assert!(!dom.front_door.is_route_driven());
10448    }
10449
10450    #[test]
10451    fn front_door_round_trips_through_save() {
10452        let tmp = tempfile::TempDir::new().unwrap();
10453        let root = tmp.path();
10454        write_marketing_service(root);
10455        let dom = DomainConfig {
10456            schema_version: 1,
10457            name: "yah-dev".into(),
10458            domain: "yah.dev".into(),
10459            front_door: FrontDoor::Passway,
10460            cdn_bucket: "yah-dev".into(),
10461            worker_bundle_path: None,
10462            routes: vec![DomainRoute {
10463                headers: Default::default(),
10464                path: "/*".into(),
10465                mode: RouteMode::Static {
10466                    component: "yah-marketing/site".into(),
10467                },
10468            }],
10469        };
10470        dom.save(root).unwrap();
10471        let cfg = CloudConfig::load(root).unwrap();
10472        assert_eq!(
10473            cfg.domain("yah-dev").unwrap().front_door,
10474            FrontDoor::Passway
10475        );
10476    }
10477
10478    // The four manifests this repo actually ships are asserted in
10479    // `tests/live_workspace_smoke.rs` — that's the only place with a
10480    // depth-agnostic path to the live `.yah/` tree and a skip path for the
10481    // standalone mirror checkout.
10482
10483    #[test]
10484    fn cross_ref_bails_on_missing_service() {
10485        let tmp = tempfile::TempDir::new().unwrap();
10486        let root = tmp.path();
10487        // No services declared at all — component ref must fail to resolve.
10488        let dom = DomainConfig {
10489            schema_version: 1,
10490            name: "yah-dev".into(),
10491            domain: "yah.dev".into(),
10492            front_door: FrontDoor::Worker,
10493            cdn_bucket: "yah-dev".into(),
10494            worker_bundle_path: None,
10495            routes: vec![DomainRoute {
10496                headers: Default::default(),
10497                path: "/".into(),
10498                mode: RouteMode::Static {
10499                    component: "yah-marketing/site".into(),
10500                },
10501            }],
10502        };
10503        dom.save(root).unwrap();
10504
10505        let err = CloudConfig::load(root).unwrap_err();
10506        let msg = format!("{err:#}");
10507        assert!(msg.contains("no such service"), "got: {msg}");
10508        assert!(msg.contains("yah-marketing"), "got: {msg}");
10509    }
10510
10511    #[test]
10512    fn cross_ref_bails_on_missing_component() {
10513        let tmp = tempfile::TempDir::new().unwrap();
10514        let root = tmp.path();
10515        write_marketing_service(root); // has component id "site", not "elsewhere"
10516
10517        let dom = DomainConfig {
10518            schema_version: 1,
10519            name: "yah-dev".into(),
10520            domain: "yah.dev".into(),
10521            front_door: FrontDoor::Worker,
10522            cdn_bucket: "yah-dev".into(),
10523            worker_bundle_path: None,
10524            routes: vec![DomainRoute {
10525                headers: Default::default(),
10526                path: "/".into(),
10527                mode: RouteMode::Static {
10528                    component: "yah-marketing/elsewhere".into(),
10529                },
10530            }],
10531        };
10532        dom.save(root).unwrap();
10533
10534        let err = CloudConfig::load(root).unwrap_err();
10535        let msg = format!("{err:#}");
10536        assert!(msg.contains("no component with id"), "got: {msg}");
10537        assert!(msg.contains("elsewhere"), "got: {msg}");
10538    }
10539
10540    #[test]
10541    fn cross_ref_bails_on_malformed_ref() {
10542        let tmp = tempfile::TempDir::new().unwrap();
10543        let root = tmp.path();
10544        write_marketing_service(root);
10545
10546        let dom = DomainConfig {
10547            schema_version: 1,
10548            name: "yah-dev".into(),
10549            domain: "yah.dev".into(),
10550            front_door: FrontDoor::Worker,
10551            cdn_bucket: "yah-dev".into(),
10552            worker_bundle_path: None,
10553            routes: vec![DomainRoute {
10554                headers: Default::default(),
10555                path: "/".into(),
10556                mode: RouteMode::Static {
10557                    component: "no-slash-here".into(),
10558                },
10559            }],
10560        };
10561        dom.save(root).unwrap();
10562
10563        let err = CloudConfig::load(root).unwrap_err();
10564        let msg = format!("{err:#}");
10565        assert!(msg.contains("expected"), "got: {msg}");
10566    }
10567
10568    #[test]
10569    fn redirect_routes_skip_component_validation() {
10570        let tmp = tempfile::TempDir::new().unwrap();
10571        let root = tmp.path();
10572        // No services at all — redirect must still load cleanly because it
10573        // references nothing.
10574        let dom = DomainConfig {
10575            schema_version: 1,
10576            name: "yah-dev".into(),
10577            domain: "yah.dev".into(),
10578            front_door: FrontDoor::Worker,
10579            cdn_bucket: "yah-dev".into(),
10580            worker_bundle_path: None,
10581            routes: vec![DomainRoute {
10582                headers: Default::default(),
10583                path: "/old".into(),
10584                mode: RouteMode::Redirect {
10585                    target: "https://yah.dev/blog".into(),
10586                    status: 308,
10587                },
10588            }],
10589        };
10590        dom.save(root).unwrap();
10591
10592        let cfg = CloudConfig::load(root).unwrap();
10593        assert!(cfg.domain("yah-dev").is_some());
10594    }
10595
10596    #[test]
10597    fn name_must_match_file_stem() {
10598        let tmp = tempfile::TempDir::new().unwrap();
10599        let root = tmp.path();
10600        // Hand-write a file whose stem disagrees with its `name`.
10601        let dir = root.join(".yah").join("domains");
10602        std::fs::create_dir_all(&dir).unwrap();
10603        std::fs::write(
10604            dir.join("yah-dev.toml"),
10605            r#"schema_version = 1
10606name = "different-name"
10607domain = "yah.dev"
10608front_door = "bucket-direct"
10609cdn_bucket = "yah-dev"
10610"#,
10611        )
10612        .unwrap();
10613
10614        let err = CloudConfig::load(root).unwrap_err();
10615        let msg = format!("{err:#}");
10616        assert!(msg.contains("must match the file stem"), "got: {msg}");
10617    }
10618
10619    #[test]
10620    fn net_alias_tier_subdomain_manifest_loads_and_cross_refs() {
10621        // R561-F2: a per-tenant subdomain manifest on the net.yah.dev wildcard
10622        // alias tier is just a DomainConfig whose `domain` is `<name>.net.yah.dev`
10623        // and whose static route cross-refs the tenant's service component.
10624        // This is exactly the shape .yah/domains/scrabcake-net-yah-dev.toml ships.
10625        let tmp = tempfile::TempDir::new().unwrap();
10626        let root = tmp.path();
10627        write_marketing_service(root); // service "yah-marketing", component "site"
10628
10629        let dom = DomainConfig {
10630            schema_version: 1,
10631            name: "tenant-net-yah-dev".into(),
10632            domain: "tenant.net.yah.dev".into(),
10633            front_door: FrontDoor::Worker,
10634            cdn_bucket: "net-yah-dev".into(), // shared per-tier bucket
10635            worker_bundle_path: None,
10636            routes: vec![DomainRoute {
10637                headers: Default::default(),
10638                path: "/*".into(),
10639                mode: RouteMode::Static {
10640                    component: "yah-marketing/site".into(),
10641                },
10642            }],
10643        };
10644        dom.save(root).unwrap();
10645
10646        let cfg = CloudConfig::load(root).unwrap();
10647        let dom = cfg
10648            .domain("tenant-net-yah-dev")
10649            .expect("net-tier subdomain manifest should load");
10650        assert_eq!(dom.domain, "tenant.net.yah.dev");
10651        assert_eq!(dom.cdn_bucket, "net-yah-dev");
10652    }
10653
10654    // ─── R572-F3: NodeAllocatable + taints ──────────────────────────────────
10655
10656    #[test]
10657    fn machine_allocatable_round_trips() {
10658        let toml_src = r#"
10659name = "us-west-001"
10660provider = "static"
10661mesh_tags = ["tag:cloud-runner"]
10662[allocatable]
10663memory_mb = 3800
10664cpu_millis = 2000
10665"#;
10666        let m: MachineConfig = toml::from_str(toml_src).unwrap();
10667        let a = m.allocatable.as_ref().expect("allocatable should parse");
10668        assert_eq!(a.memory_mb, 3800);
10669        assert_eq!(a.cpu_millis, 2000);
10670
10671        let s = toml::to_string(&m).unwrap();
10672        let back: MachineConfig = toml::from_str(&s).unwrap();
10673        let a2 = back.allocatable.as_ref().unwrap();
10674        assert_eq!(a2.memory_mb, 3800);
10675        assert_eq!(a2.cpu_millis, 2000);
10676    }
10677
10678    #[test]
10679    fn machine_taints_round_trips() {
10680        let toml_src = r#"
10681name = "us-south-001"
10682provider = "static"
10683mesh_tags = ["tag:cloud-runner"]
10684taints = ["no-appliance"]
10685"#;
10686        let m: MachineConfig = toml::from_str(toml_src).unwrap();
10687        assert_eq!(m.taints, vec!["no-appliance"]);
10688
10689        let s = toml::to_string(&m).unwrap();
10690        let back: MachineConfig = toml::from_str(&s).unwrap();
10691        assert_eq!(back.taints, vec!["no-appliance"]);
10692    }
10693
10694    #[test]
10695    fn machine_allocatable_absent_is_none() {
10696        let toml_src = "name = \"node\"\nprovider = \"static\"\nmesh_tags = []\n";
10697        let m: MachineConfig = toml::from_str(toml_src).unwrap();
10698        assert!(m.allocatable.is_none());
10699        assert!(m.taints.is_empty());
10700    }
10701
10702    #[test]
10703    fn machine_allocatable_skipped_when_none() {
10704        let m = make_machine("node", vec![]);
10705        let s = toml::to_string(&m).unwrap();
10706        assert!(
10707            !s.contains("allocatable"),
10708            "None allocatable must be omitted: {s}"
10709        );
10710        assert!(!s.contains("taints"), "empty taints must be omitted: {s}");
10711    }
10712
10713    #[test]
10714    fn machine_multiple_taints_round_trip() {
10715        let toml_src = r#"
10716name = "quarantined"
10717provider = "static"
10718mesh_tags = ["tag:build-worker"]
10719taints = ["no-server", "no-appliance", "no-job"]
10720"#;
10721        let m: MachineConfig = toml::from_str(toml_src).unwrap();
10722        assert_eq!(m.taints.len(), 3);
10723        assert!(m.taints.contains(&"no-server".to_string()));
10724        assert!(m.taints.contains(&"no-appliance".to_string()));
10725        assert!(m.taints.contains(&"no-job".to_string()));
10726        // R742-T4: every key here is one the scheduler reads. This fixture
10727        // used to carry `no-voter`, which none of them is.
10728        assert!(m.inert_taints().is_empty());
10729    }
10730
10731    // ─── R742-T4 (W305): inert-taint classification ─────────────────────────
10732
10733    #[test]
10734    fn every_archetype_repel_key_is_live() {
10735        for arch in LifecycleArchetype::ALL {
10736            let key = format!("no-{}", arch.taint_key());
10737            assert_eq!(
10738                taint_effect(&key),
10739                TaintEffect::Repels(arch),
10740                "{key} must repel {arch:?}"
10741            );
10742        }
10743    }
10744
10745    #[test]
10746    fn public_ip_is_an_affinity_key_not_an_inert_one() {
10747        assert_eq!(
10748            taint_effect(workload_spec::PUBLIC_IP_TAINT),
10749            TaintEffect::Attracts
10750        );
10751    }
10752
10753    #[test]
10754    fn a_free_form_taint_is_inert_and_says_so() {
10755        // W305's headline example: `taints = ["qa"]` parsed clean and did
10756        // nothing. Environment is not expressible as a taint.
10757        assert_eq!(taint_effect("qa"), TaintEffect::Inert);
10758        // And the one that actually cost fleet state: `no-voter` reads as an
10759        // exclusion and excludes nothing — "voter" is not an archetype.
10760        assert_eq!(taint_effect("no-voter"), TaintEffect::Inert);
10761        // A near-miss on a real key is inert too, not silently forgiven.
10762        assert_eq!(taint_effect("no-servers"), TaintEffect::Inert);
10763
10764        let m = make_machine_with_capacity(
10765            "dev-pi",
10766            8192,
10767            4000,
10768            vec!["no-appliance", "no-voter", "qa"],
10769        );
10770        assert_eq!(m.inert_taints(), vec!["no-voter", "qa"]);
10771    }
10772
10773    // ─── R876-B7: repel-by-default + declarable toleration ──────────────────
10774
10775    /// The headline inversion. A bare `RequiredSpec` — which is exactly what
10776    /// deserializing a mirror's `required = { regions, mesh_tags }` produces,
10777    /// since no TOML in the tree writes `tolerates` — is now repelled by a
10778    /// repelling taint. Before B7 it matched, because repulsion was conditional
10779    /// on a `#[serde(skip)]` field that this path could never fill.
10780    #[test]
10781    fn an_undeclared_spec_is_repelled_by_a_repelling_taint() {
10782        let tainted = make_machine_with_capacity("n", 8192, 4000, vec!["no-server"]);
10783        assert!(!RequiredSpec::default().matches(&tainted));
10784
10785        // And it is the DESERIALIZED shape that matters, not a hand-built one:
10786        // this is the mirror path reproduced exactly.
10787        let from_toml: RequiredSpec =
10788            toml::from_str("regions = [\"us-east\"]\n").expect("a mirror-shaped required parses");
10789        assert!(from_toml.tolerates.is_empty());
10790        let mut in_region = tainted.clone();
10791        in_region.region = Some("us-east".to_string());
10792        assert!(
10793            !from_toml.matches(&in_region),
10794            "a mirror-declared placement must now read machine.taints"
10795        );
10796    }
10797
10798    /// The opt-back-in half, and the one an operator writes by hand.
10799    #[test]
10800    fn an_explicit_toleration_admits_the_tainted_machine_again() {
10801        let tainted = make_machine_with_capacity("n", 8192, 4000, vec!["no-server"]);
10802        let spec = RequiredSpec {
10803            tolerates: vec!["no-server".to_string()],
10804            ..Default::default()
10805        };
10806        assert!(spec.matches(&tainted));
10807
10808        // Per-key, not a blanket pass: tolerating one repelling key says nothing
10809        // about another.
10810        let both = make_machine_with_capacity("n", 8192, 4000, vec!["no-server", "no-appliance"]);
10811        assert!(!spec.matches(&both));
10812
10813        // And it deserializes — the whole point of replacing a `#[serde(skip)]`
10814        // field is that a mirror can now declare this.
10815        let from_toml: RequiredSpec = toml::from_str("tolerates = [\"no-server\"]\n")
10816            .expect("a slot can declare a toleration");
10817        assert!(from_toml.matches(&tainted));
10818    }
10819
10820    /// An untainted machine is unaffected, which is what makes the migration
10821    /// bounded: six of the nine fleet machines carry no repelling taint at all.
10822    #[test]
10823    fn an_untainted_machine_matches_exactly_as_before() {
10824        let clean = make_machine_with_capacity("n", 8192, 4000, vec![]);
10825        assert!(RequiredSpec::default().matches(&clean));
10826        assert!(RequiredSpec {
10827            tolerates: vec!["no-server".to_string()],
10828            ..Default::default()
10829        }
10830        .matches(&clean));
10831    }
10832
10833    /// THE MIGRATION'S LOAD-BEARING FACT. `public-ip` is on three fleet nodes
10834    /// including us-east-001, the only origin serving the yah.dev apex. It is an
10835    /// *affinity* key, so repel-by-default must not touch it — reading every
10836    /// taint as repulsion would evict the apex on the next apply.
10837    #[test]
10838    fn an_affinity_taint_does_not_repel() {
10839        let public = make_machine_with_capacity("us-east-001", 8192, 4000, vec!["public-ip"]);
10840        assert!(
10841            RequiredSpec::default().matches(&public),
10842            "public-ip attracts; it must never be read as repulsion"
10843        );
10844    }
10845
10846    /// `select_matching` filters on the same predicate, so a tainted machine
10847    /// leaves the candidate set rather than being silently placed onto.
10848    #[test]
10849    fn select_matching_drops_a_tainted_candidate_and_keeps_the_rest() {
10850        let drained = make_machine_with_capacity("drained", 8192, 4000, vec!["no-server"]);
10851        let healthy = make_machine_with_capacity("healthy", 8192, 4000, vec![]);
10852        let pool = [&drained, &healthy];
10853
10854        let picked = select_matching(&pool, &RequiredSpec::default(), 1, "test pool", "empty")
10855            .expect("one candidate remains");
10856        assert_eq!(
10857            picked.iter().map(|m| m.name.as_str()).collect::<Vec<_>>(),
10858            vec!["healthy"],
10859            "tainting the first candidate moves the placement to the second"
10860        );
10861
10862        // Asking for both is a shortfall, not a half-placement.
10863        let err = select_matching(&pool, &RequiredSpec::default(), 2, "test pool", "empty")
10864            .expect_err("only one of two matches");
10865        assert!(format!("{err:#}").contains("only 1 of 2 machines match"));
10866    }
10867
10868    /// The `admit_workload` path must be behaviourally unchanged: its spec is
10869    /// built by `admission_spec`, which now emits the complementary tolerations.
10870    #[test]
10871    fn admission_preserves_archetype_scoped_repulsion_across_the_inversion() {
10872        let ws = minimal_spec("srv", 1); // a Server
10873        let req = admission_spec(&ws, &[]).unwrap();
10874        assert_eq!(ws.effective_archetype(), LifecycleArchetype::Server);
10875
10876        let no_server = make_machine_with_capacity("n", 8192, 4000, vec!["no-server"]);
10877        let no_appliance = make_machine_with_capacity("n", 8192, 4000, vec!["no-appliance"]);
10878        assert!(!req.matches(&no_server), "its own class still repels it");
10879        assert!(
10880            req.matches(&no_appliance),
10881            "another class's taint still does not — this is the pre-B7 answer"
10882        );
10883    }
10884
10885    #[test]
10886    fn describe_names_the_toleration_so_a_refusal_is_readable() {
10887        let spec = RequiredSpec {
10888            regions: vec!["us-west".to_string()],
10889            tolerates: vec!["no-appliance".to_string()],
10890            ..Default::default()
10891        };
10892        assert_eq!(
10893            spec.describe(),
10894            "required.regions=[us-west] + required.tolerates=[no-appliance]"
10895        );
10896    }
10897
10898    /// A toleration widens; it must not make an underspecified slot look
10899    /// specified, or the deploy side stops refusing one.
10900    #[test]
10901    fn a_toleration_alone_is_still_an_unconstrained_spec() {
10902        assert!(RequiredSpec {
10903            tolerates: vec!["no-server".to_string()],
10904            ..Default::default()
10905        }
10906        .is_unconstrained());
10907    }
10908
10909    #[test]
10910    fn an_inert_taint_changes_no_placement_decision() {
10911        // The reason this is a lint and not a behaviour change: the guard's
10912        // whole premise is that these keys are invisible to `matches`.
10913        let clean = make_machine_with_capacity("n", 8192, 4000, vec![]);
10914        let noisy = make_machine_with_capacity("n", 8192, 4000, vec!["no-voter", "qa"]);
10915        // R876-B7: still true under repel-by-default, and for a sharper reason —
10916        // `matches` now walks `machine.taints` itself, so an unclassifiable key
10917        // is skipped by `taint_effect` rather than merely never looked up.
10918        for arch in LifecycleArchetype::ALL {
10919            let req = RequiredSpec {
10920                tolerates: tolerations_excluding(&[arch]),
10921                ..Default::default()
10922            };
10923            assert_eq!(req.matches(&clean), req.matches(&noisy));
10924            assert!(req.matches(&noisy), "neither key repels");
10925        }
10926    }
10927
10928    /// The toleration set [`admission_spec`] derives for a group of `archetypes`
10929    /// — every repelling key that is not the group's own class.
10930    fn tolerations_excluding(archetypes: &[LifecycleArchetype]) -> Vec<String> {
10931        LifecycleArchetype::ALL
10932            .into_iter()
10933            .filter(|a| !archetypes.contains(a))
10934            .map(|a| format!("no-{}", a.taint_key()))
10935            .collect()
10936    }
10937
10938    #[test]
10939    fn live_taint_keys_lists_the_whole_legal_vocabulary() {
10940        assert_eq!(
10941            live_taint_keys(),
10942            vec!["no-appliance", "no-job", "no-server", "public-ip"]
10943        );
10944    }
10945
10946    // ─── R742-F1 (W305): sovereign groups ───────────────────────────────────
10947
10948    /// A machine in `group`, with the role left unwritten — which is the state
10949    /// of every machine TOML that predates R605-F12 and resolves to `voter`.
10950    fn in_group(name: &str, group: Option<&str>) -> MachineConfig {
10951        MachineConfig {
10952            sovereign_group: group.map(String::from),
10953            ..make_machine(name, vec![])
10954        }
10955    }
10956
10957    /// A machine in `group` with its quorum eligibility stated (R605-F12).
10958    fn in_group_as(name: &str, group: &str, role: SovereignRole) -> MachineConfig {
10959        MachineConfig {
10960            sovereign_group: Some(group.to_string()),
10961            sovereign_role: Some(role),
10962            ..make_machine(name, vec![])
10963        }
10964    }
10965
10966    #[test]
10967    fn a_join_within_one_sovereign_group_is_permitted() {
10968        assert_eq!(
10969            judge_join(
10970                &in_group("us-west-013", Some("dev")),
10971                &in_group("us-west-011", Some("dev")),
10972            ),
10973            JoinVerdict::Permit
10974        );
10975    }
10976
10977    /// The case the field exists for: before it, the only thing standing
10978    /// between a dev Pi and the prod quorum was a comment in a TOML.
10979    #[test]
10980    fn a_cross_group_join_is_refused_naming_both_groups() {
10981        let verdict = judge_join(
10982            &in_group("us-west-011", Some("dev")),
10983            &in_group("us-west-001", Some("prod")),
10984        );
10985        let JoinVerdict::Refuse(msg) = verdict else {
10986            panic!("a dev node joining prod must be refused: {verdict:?}");
10987        };
10988        // A refusal that does not name what it saw is one the operator has to
10989        // go and reconstruct, so it gets worked around instead of fixed.
10990        assert!(msg.contains("us-west-011") && msg.contains("us-west-001"), "{msg}");
10991        assert!(msg.contains("dev") && msg.contains("prod"), "{msg}");
10992    }
10993
10994    /// `None` is a declaration ("standalone, in no group"), not a gap — so
10995    /// growing prod with an unstamped box is a cross-group join too, and the
10996    /// refusal has to say which file makes it legal.
10997    #[test]
10998    fn an_undeclared_node_cannot_join_a_declared_group() {
10999        let verdict = judge_join(
11000            &in_group("us-west-002", None),
11001            &in_group("us-west-001", Some("prod")),
11002        );
11003        let JoinVerdict::Refuse(msg) = verdict else {
11004            panic!("an unstamped node joining prod must be refused: {verdict:?}");
11005        };
11006        assert!(
11007            msg.contains(".yah/infra/machines/us-west-002.toml"),
11008            "the refusal must name the file to stamp: {msg}"
11009        );
11010    }
11011
11012    #[test]
11013    fn a_declared_node_cannot_join_a_standalone_target() {
11014        // us-west-003 is `mode: standalone` on purpose; it is not a group of
11015        // one waiting to be grown.
11016        let verdict = judge_join(
11017            &in_group("us-west-001", Some("prod")),
11018            &in_group("us-west-003", None),
11019        );
11020        assert!(matches!(verdict, JoinVerdict::Refuse(msg) if msg.contains("us-west-003")));
11021    }
11022
11023    #[test]
11024    fn two_undeclared_nodes_cannot_form_an_undeclared_group() {
11025        let verdict = judge_join(
11026            &in_group("us-west-002", None),
11027            &in_group("us-west-015", None),
11028        );
11029        assert!(
11030            matches!(&verdict, JoinVerdict::Refuse(msg) if msg.contains("us-west-002")
11031                && msg.contains("us-west-015")),
11032            "forming a group nobody declared must be refused, naming both: {verdict:?}"
11033        );
11034    }
11035
11036    // ─── R605-F12: the voting axis ──────────────────────────────────────────
11037
11038    /// The whole ticket in one assertion. us-west-003 is a member of prod —
11039    /// same secrets, same upgrade cadence, same destruction — and must never
11040    /// hold a prod raft seat. Before the role axis, the only thing refusing it
11041    /// was its *absent* group stamp, so writing down the truth above would have
11042    /// removed the guard.
11043    #[test]
11044    fn a_non_voting_member_is_refused_into_its_own_group() {
11045        let verdict = judge_join(
11046            &in_group_as("us-west-003", "prod", SovereignRole::NonVoter),
11047            &in_group_as("us-west-001", "prod", SovereignRole::Voter),
11048        );
11049        let JoinVerdict::Refuse(msg) = verdict else {
11050            panic!("a non-voting prod member must not join the prod quorum: {verdict:?}");
11051        };
11052        assert!(msg.contains("us-west-003") && msg.contains("NON-VOTING"), "{msg}");
11053        // The refusal must not blame the group: both sides say "prod", and a
11054        // cross-group message here would read as a bug in the check itself.
11055        assert!(!msg.contains("cross-group"), "{msg}");
11056        assert!(
11057            msg.contains(".yah/infra/machines/us-west-003.toml"),
11058            "the refusal must name the file that decides it: {msg}"
11059        );
11060    }
11061
11062    /// Read from the other end: a box declared non-voting has no quorum seat to
11063    /// be grown, so it cannot be a join target either.
11064    #[test]
11065    fn a_non_voting_target_has_no_quorum_to_grow() {
11066        let verdict = judge_join(
11067            &in_group_as("us-west-001", "prod", SovereignRole::Voter),
11068            &in_group_as("us-west-003", "prod", SovereignRole::NonVoter),
11069        );
11070        assert!(
11071            matches!(&verdict, JoinVerdict::Refuse(msg) if msg.contains("the target")
11072                && msg.contains("us-west-003")),
11073            "{verdict:?}"
11074        );
11075    }
11076
11077    /// A non-voter joining a *standalone* target is refused for two reasons at
11078    /// once, and the message must pick the one whose fix would actually work.
11079    /// Naming the role here would send the operator to flip `sovereign_role`
11080    /// and come back to the same refusal.
11081    #[test]
11082    fn a_refusal_names_the_group_when_fixing_the_role_would_not_help() {
11083        let verdict = judge_join(
11084            &in_group_as("us-west-003", "prod", SovereignRole::NonVoter),
11085            &in_group("us-west-002", None),
11086        );
11087        let JoinVerdict::Refuse(msg) = verdict else {
11088            panic!("a standalone target has no group to join: {verdict:?}");
11089        };
11090        assert!(
11091            msg.contains(".yah/infra/machines/us-west-002.toml"),
11092            "the refusal must point at the target's missing group stamp: {msg}"
11093        );
11094        assert!(!msg.contains("NON-VOTING"), "{msg}");
11095    }
11096
11097    /// The back-compat seam, pinned: the six nodes stamped before R605-F12
11098    /// write no role, and an absent role means what declaring a group has
11099    /// always meant. If this flips, the live prod and dev quorums stop being
11100    /// growable on a config the operator never edited.
11101    #[test]
11102    fn an_unwritten_role_still_joins_its_group() {
11103        let joiner = in_group("us-west-013", Some("dev"));
11104        assert_eq!(joiner.sovereign_role, None);
11105        assert_eq!(
11106            judge_join(&joiner, &in_group("us-west-011", Some("dev"))),
11107            JoinVerdict::Permit
11108        );
11109        assert_eq!(
11110            judge_join(
11111                &joiner,
11112                &in_group_as("us-west-011", "dev", SovereignRole::Voter)
11113            ),
11114            JoinVerdict::Permit
11115        );
11116    }
11117
11118    /// A non-voting member is still a *member*, and the two claims must not be
11119    /// conflated: `sovereign_membership()` reports the group either way, so a
11120    /// consumer asking "is this box in prod's blast radius" gets yes.
11121    #[test]
11122    fn a_non_voter_is_still_in_the_group_it_names() {
11123        let m = in_group_as("us-west-003", "prod", SovereignRole::NonVoter);
11124        assert_eq!(m.sovereign_membership().group, Some("prod"));
11125        assert!(!m.sovereign_membership().role.is_voter());
11126
11127        // …and the group-membership query the fleet reads is unaffected by it.
11128        let cfg = make_empty_cfg(vec![
11129            m,
11130            in_group_as("us-west-001", "prod", SovereignRole::Voter),
11131        ]);
11132        assert_eq!(
11133            cfg.machines_in_group("prod")
11134                .iter()
11135                .map(|m| m.name.as_str())
11136                .collect::<Vec<_>>(),
11137            vec!["us-west-003", "us-west-001"]
11138        );
11139    }
11140
11141    /// The role travels through TOML in one spelling, and an absent one stays
11142    /// absent on the way back out — otherwise every machine file would grow a
11143    /// `sovereign_role = "voter"` line the operator never wrote, and the
11144    /// unroled-member lint would have nothing left to find.
11145    #[test]
11146    fn sovereign_role_round_trips_and_is_omitted_when_unwritten() {
11147        let m: MachineConfig = toml::from_str(
11148            r#"
11149name = "us-west-003"
11150provider = "static"
11151region = "us-west"
11152arch = "x86_64"
11153mesh_tags = []
11154sovereign_group = "prod"
11155sovereign_role = "non-voter"
11156"#,
11157        )
11158        .unwrap();
11159        assert_eq!(m.sovereign_role, Some(SovereignRole::NonVoter));
11160        assert!(toml::to_string(&m)
11161            .unwrap()
11162            .contains(r#"sovereign_role = "non-voter""#));
11163
11164        let unwritten = MachineConfig {
11165            sovereign_role: None,
11166            ..m
11167        };
11168        assert!(!toml::to_string(&unwritten)
11169            .unwrap()
11170            .contains("sovereign_role"));
11171    }
11172
11173    /// The invariant the ticket is most explicit about: a sovereign group is a
11174    /// blast radius, not a filter. If this ever fails, `matches` has grown an
11175    /// axis it must not have and dev-mode workloads have silently become
11176    /// unschedulable on the dev group.
11177    #[test]
11178    fn sovereign_group_is_not_a_placement_input() {
11179        let standalone = in_group("n", None);
11180        let grouped = in_group("n", Some("dev"));
11181        let other = in_group("n", Some("prod"));
11182
11183        for spec in [
11184            RequiredSpec::default(),
11185            RequiredSpec {
11186                regions: vec!["us-west".into()],
11187                ..Default::default()
11188            },
11189            RequiredSpec {
11190                tolerates: tolerations_excluding(&[LifecycleArchetype::Appliance]),
11191                ..Default::default()
11192            },
11193        ] {
11194            let baseline = spec.matches(&standalone);
11195            assert_eq!(spec.matches(&grouped), baseline);
11196            assert_eq!(spec.matches(&other), baseline);
11197        }
11198    }
11199
11200    // ─── R742-F3 (W305): group → machine set, and group-scoped admission ────
11201
11202    /// The primitive `migrate --to` needs and `rollout plan` still lacks
11203    /// (W314 gap 1): a group exists only as the set of machines naming it, so
11204    /// membership has to be derived rather than declared anywhere.
11205    #[test]
11206    fn machines_in_group_derives_membership_from_the_declarations() {
11207        let cfg = make_empty_cfg(vec![
11208            in_group("us-west-001", Some("prod")),
11209            in_group("us-west-011", Some("dev")),
11210            in_group("us-west-013", Some("dev")),
11211            in_group("us-west-002", None),
11212        ]);
11213
11214        let dev: Vec<&str> = cfg
11215            .machines_in_group("dev")
11216            .iter()
11217            .map(|m| m.name.as_str())
11218            .collect();
11219        assert_eq!(dev, vec!["us-west-011", "us-west-013"]);
11220        assert_eq!(cfg.machines_in_group("prod").len(), 1);
11221
11222        // Standalone is "in no group", not "in a group called none" — so an
11223        // unstamped box is never swept into a migration target.
11224        assert!(cfg.machines_in_group("").is_empty());
11225        assert!(cfg.machines_in_group("staging").is_empty());
11226    }
11227
11228    #[test]
11229    fn declared_sovereign_groups_is_the_vocabulary_a_bad_target_is_named_against() {
11230        let cfg = make_empty_cfg(vec![
11231            in_group("a", Some("prod")),
11232            in_group("b", Some("dev")),
11233            in_group("c", Some("prod")),
11234            in_group("d", None),
11235        ]);
11236        // Sorted + deduped, and standalone contributes nothing.
11237        assert_eq!(cfg.declared_sovereign_groups(), vec!["dev", "prod"]);
11238        assert!(make_empty_cfg(vec![in_group("a", None)])
11239            .declared_sovereign_groups()
11240            .is_empty());
11241    }
11242
11243    /// Group-scoped admission must be the SAME predicate as unscoped
11244    /// admission, only over fewer candidates. If it ever diverges, `migrate`
11245    /// becomes a way to place a workload somewhere `yah cloud apply` would
11246    /// refuse — which is exactly the silent routing-around W305 exists to stop.
11247    #[test]
11248    fn admit_workload_in_group_narrows_candidates_without_changing_the_predicate() {
11249        let mut prod = in_group("us-west-001", Some("prod"));
11250        prod.mesh_tags = vec!["tag:cloud-runner".into()];
11251        let mut dev_repels = in_group("us-west-011", Some("dev"));
11252        dev_repels.taints = vec!["no-appliance".into()];
11253        let mut dev_ok = in_group("us-west-013", Some("dev"));
11254        dev_ok.mesh_tags = vec!["tag:cloud-runner".into()];
11255
11256        let cfg = make_empty_cfg(vec![prod, dev_repels, dev_ok]);
11257
11258        let mut ws = ws_with_selector(None);
11259        ws.archetype = Some(LifecycleArchetype::Appliance);
11260
11261        // Unscoped picks the first match in declaration order.
11262        assert_eq!(cfg.admit_workload(&ws).unwrap().name, "us-west-001");
11263        // Scoped skips the repelling dev node and lands on the other one —
11264        // the taint is honoured, not bypassed.
11265        assert_eq!(
11266            cfg.admit_workload_in_group(&ws, "dev").unwrap().name,
11267            "us-west-013"
11268        );
11269    }
11270
11271    #[test]
11272    fn admit_workload_in_group_distinguishes_an_empty_group_from_a_repelling_one() {
11273        let mut dev = in_group("us-west-011", Some("dev"));
11274        dev.taints = vec!["no-appliance".into()];
11275        let cfg = make_empty_cfg(vec![in_group("us-west-001", Some("prod")), dev]);
11276
11277        let mut ws = ws_with_selector(None);
11278        ws.archetype = Some(LifecycleArchetype::Appliance);
11279
11280        // A group nobody declares names the legal vocabulary, because a typo
11281        // is the realistic cause and "no candidates" would send the operator
11282        // hunting for a placement problem that does not exist.
11283        let missing = cfg.admit_workload_in_group(&ws, "stagng").unwrap_err().to_string();
11284        assert!(missing.contains("no machine declares"), "{missing}");
11285        assert!(missing.contains("dev") && missing.contains("prod"), "{missing}");
11286
11287        // A group that exists but refuses names the machines it tried.
11288        let repelled = cfg.admit_workload_in_group(&ws, "dev").unwrap_err().to_string();
11289        assert!(repelled.contains("us-west-011"), "{repelled}");
11290    }
11291
11292    #[test]
11293    fn sovereign_group_round_trips_and_is_omitted_when_standalone() {
11294        let src = r#"
11295name = "us-west-011"
11296provider = "static"
11297mesh_tags = []
11298sovereign_group = "dev"
11299"#;
11300        let m: MachineConfig = toml::from_str(src).unwrap();
11301        assert_eq!(m.sovereign_group.as_deref(), Some("dev"));
11302        assert!(toml::to_string(&m).unwrap().contains("sovereign_group"));
11303
11304        // A machine that predates the field parses as standalone and does not
11305        // grow the key back on write.
11306        let legacy: MachineConfig =
11307            toml::from_str("name = \"us-west-002\"\nprovider = \"static\"\nmesh_tags = []\n")
11308                .unwrap();
11309        assert_eq!(legacy.sovereign_group, None);
11310        assert!(!toml::to_string(&legacy).unwrap().contains("sovereign_group"));
11311    }
11312
11313    // ─── R572-F5: capacity floor + absolute (untolerable) taints ────────────
11314
11315    fn make_machine_with_capacity(
11316        name: &str,
11317        memory_mb: u32,
11318        cpu_millis: u32,
11319        taints: Vec<&str>,
11320    ) -> MachineConfig {
11321        MachineConfig {
11322            allocatable: Some(NodeAllocatable {
11323                memory_mb,
11324                cpu_millis,
11325            }),
11326            taints: taints.into_iter().map(String::from).collect(),
11327            ..make_machine(name, vec![])
11328        }
11329    }
11330
11331    fn server_spec(memory_mb: u32, cpu_millis: u32) -> WorkloadSpec {
11332        use workload_spec::{ImageRef, LifecycleArchetype, TierTag};
11333        let mut ws = WorkloadSpec::for_forge(
11334            "f5-test",
11335            ImageRef {
11336                registry: "localhost".into(),
11337                repository: "test".into(),
11338                tag: "latest".into(),
11339                digest: workload_spec::testing::test_digest(),
11340            },
11341            TierTag("infra".into()),
11342            vec![],
11343        );
11344        ws.archetype = Some(LifecycleArchetype::Server);
11345        ws.resources.memory_mb = memory_mb;
11346        ws.resources.cpu_millis = cpu_millis;
11347        // These are SERVER specs that borrow `for_forge` as a constructor
11348        // shortcut, so drop the forge memory request it stamps on — otherwise
11349        // every spec here silently requests the forge default instead of the
11350        // `memory_mb` the caller passed, and the capacity-floor tests below
11351        // stop testing their own argument. A server workload declares no
11352        // request, which is the documented fall-back-to-`resources.memory_mb`
11353        // path (`WorkloadSpec::memory_request_mb`).
11354        ws.resources.memory_request_mb = None;
11355        ws
11356    }
11357
11358    fn appliance_spec_ws(memory_mb: u32, cpu_millis: u32) -> WorkloadSpec {
11359        use workload_spec::LifecycleArchetype;
11360        let mut ws = server_spec(memory_mb, cpu_millis);
11361        ws.archetype = Some(LifecycleArchetype::Appliance);
11362        ws
11363    }
11364
11365    #[test]
11366    fn capacity_floor_rejects_undersized_node() {
11367        let cfg = make_empty_cfg(vec![make_machine_with_capacity("small", 256, 500, vec![])]);
11368        let ws = server_spec(512, 1000); // demands more than available
11369        assert!(cfg.admit_workload(&ws).is_err());
11370    }
11371
11372    #[test]
11373    fn capacity_floor_accepts_exact_fit() {
11374        let cfg = make_empty_cfg(vec![make_machine_with_capacity("exact", 512, 1000, vec![])]);
11375        let ws = server_spec(512, 1000);
11376        assert_eq!(cfg.admit_workload(&ws).unwrap().name, "exact");
11377    }
11378
11379    #[test]
11380    fn capacity_floor_passes_when_allocatable_absent() {
11381        // A machine with no allocatable block skips the capacity check (no data).
11382        let cfg = make_empty_cfg(vec![make_machine("no-alloc", vec![])]);
11383        let ws = server_spec(99999, 99999); // would exceed any real node
11384        assert_eq!(cfg.admit_workload(&ws).unwrap().name, "no-alloc");
11385    }
11386
11387    #[test]
11388    fn taint_repulsion_blocks_appliance_on_no_appliance_node() {
11389        let cfg = make_empty_cfg(vec![make_machine_with_capacity(
11390            "south",
11391            1024,
11392            2000,
11393            vec!["no-appliance"],
11394        )]);
11395        let ws = appliance_spec_ws(256, 500);
11396        assert!(
11397            cfg.admit_workload(&ws).is_err(),
11398            "appliance must be repelled by no-appliance taint"
11399        );
11400    }
11401
11402    #[test]
11403    fn taint_repulsion_allows_server_on_no_appliance_node() {
11404        // "no-appliance" only repels Appliance workloads; servers are unaffected.
11405        let cfg = make_empty_cfg(vec![make_machine_with_capacity(
11406            "south",
11407            1024,
11408            2000,
11409            vec!["no-appliance"],
11410        )]);
11411        let ws = server_spec(256, 500);
11412        assert_eq!(cfg.admit_workload(&ws).unwrap().name, "south");
11413    }
11414
11415    #[test]
11416    fn taint_repulsion_job_not_blocked_by_no_server() {
11417        use workload_spec::LifecycleArchetype;
11418        let cfg = make_empty_cfg(vec![make_machine_with_capacity(
11419            "build-box",
11420            8192,
11421            4000,
11422            vec!["no-server", "no-appliance"],
11423        )]);
11424        let mut ws = server_spec(256, 500);
11425        ws.archetype = Some(LifecycleArchetype::Job);
11426        // Job only repelled by "no-job"; "no-server" and "no-appliance" don't affect it.
11427        assert_eq!(cfg.admit_workload(&ws).unwrap().name, "build-box");
11428    }
11429
11430    #[test]
11431    fn requires_taint_affinity_blocks_placement_without_it() {
11432        use workload_spec::{LifecycleArchetype, PUBLIC_IP_TAINT, REQUIRES_TAINT_ANNOTATION};
11433        // Simulate the passway ingress appliance: requires "public-ip" taint.
11434        let mut ws = appliance_spec_ws(256, 512);
11435        ws.archetype = Some(LifecycleArchetype::Appliance);
11436        ws.annotations
11437            .insert(REQUIRES_TAINT_ANNOTATION.into(), PUBLIC_IP_TAINT.into());
11438
11439        // Node without the taint: rejected.
11440        let cfg = make_empty_cfg(vec![make_machine_with_capacity(
11441            "no-pip",
11442            2048,
11443            2000,
11444            vec![],
11445        )]);
11446        assert!(cfg.admit_workload(&ws).is_err());
11447
11448        // Node with the taint: accepted.
11449        let cfg = make_empty_cfg(vec![make_machine_with_capacity(
11450            "pub-node",
11451            2048,
11452            2000,
11453            vec!["public-ip"],
11454        )]);
11455        assert_eq!(cfg.admit_workload(&ws).unwrap().name, "pub-node");
11456    }
11457
11458    #[test]
11459    fn w244_fleet_scenario_appliance_rejected_from_south_and_west002() {
11460        // Full W244 fleet table scenario:
11461        // us-west-001/east-001: no taints, large capacity → appliance lands here
11462        // us-south-001: no-appliance taint → appliance rejected
11463        // us-west-002: no-server, no-appliance → appliance rejected
11464        let cfg = make_empty_cfg(vec![
11465            make_machine_with_capacity("us-south-001", 512, 1000, vec!["no-appliance"]),
11466            make_machine_with_capacity(
11467                "us-west-002",
11468                16384,
11469                8000,
11470                vec!["no-server", "no-appliance"],
11471            ),
11472            make_machine_with_capacity("us-west-001", 4096, 4000, vec![]),
11473        ]);
11474        let ws = appliance_spec_ws(256, 500);
11475        // Skips south (no-appliance) and west-002 (no-appliance), lands on west-001.
11476        assert_eq!(cfg.admit_workload(&ws).unwrap().name, "us-west-001");
11477    }
11478
11479    #[test]
11480    fn w244_fleet_scenario_job_lands_on_west002_first() {
11481        use workload_spec::LifecycleArchetype;
11482        // Jobs should prefer (or at least land on) the job-only box.
11483        let cfg = make_empty_cfg(vec![
11484            make_machine_with_capacity("us-west-001", 4096, 4000, vec![]),
11485            make_machine_with_capacity(
11486                "us-west-002",
11487                16384,
11488                8000,
11489                vec!["no-server", "no-appliance"],
11490            ),
11491        ]);
11492        let mut ws = server_spec(256, 500);
11493        ws.archetype = Some(LifecycleArchetype::Job);
11494        // No fleet node declares `no-job`, so a Job is repelled by nothing;
11495        // west-001 comes first in declaration order (greedy, no preference),
11496        // which is the expected tie-break. Note this is *absence of a repel
11497        // key*, not toleration — no workload can tolerate a taint (W305).
11498        let picked = cfg.admit_workload(&ws).unwrap();
11499        // Both are eligible.
11500        assert!(
11501            picked.name == "us-west-001" || picked.name == "us-west-002",
11502            "job must land on an eligible node, got {}",
11503            picked.name
11504        );
11505    }
11506
11507    #[test]
11508    fn r569_f4_macos_node_taints_keep_cloud_critical_off_but_admit_build_jobs() {
11509        use workload_spec::LifecycleArchetype;
11510        // R569-F4: the headless M2 (us-west-015) joins the fleet as a
11511        // build-worker but must never take cloud-critical load. It carries the
11512        // same repel set as the x86 build-worker (`no-server, no-appliance` —
11513        // see .yah/infra/machines/us-west-015.toml). This pins that intent:
11514        // with a plain cloud node available beside the Mac, every
11515        // cloud-critical archetype lands on the cloud node and never the Mac;
11516        // build Jobs (the Mac's actual purpose) remain eligible on it.
11517        //
11518        // R742-T4: `no-voter` used to sit in this set and in the TOML. It was
11519        // never read here — there is no "voter" workload archetype — and
11520        // R569-F3's learner-only join is what actually keeps the box out of
11521        // quorum. It is now rejected by `yah cloud validate` as inert.
11522        let mac_taints = vec!["no-server", "no-appliance"];
11523        let fleet = || {
11524            make_empty_cfg(vec![
11525                make_machine_with_capacity("us-west-015", 24576, 8000, mac_taints.clone()),
11526                make_machine_with_capacity("us-west-001", 4096, 4000, vec![]),
11527            ])
11528        };
11529
11530        // A cloud-critical Server workload is repelled from the Mac and lands
11531        // on the untainted cloud node.
11532        let cfg = fleet();
11533        assert_eq!(
11534            cfg.admit_workload(&server_spec(256, 500)).unwrap().name,
11535            "us-west-001",
11536            "a Server workload must never land on the no-server Mac node"
11537        );
11538
11539        // Same for an Appliance (pinned/stateful cloud-critical) workload.
11540        let cfg = fleet();
11541        assert_eq!(
11542            cfg.admit_workload(&appliance_spec_ws(256, 500))
11543                .unwrap()
11544                .name,
11545            "us-west-001",
11546            "an Appliance workload must never land on the no-appliance Mac node"
11547        );
11548
11549        // Sharpest repulsion proof: with ONLY the Mac in the fleet, a
11550        // cloud-critical Server workload is rejected outright — the taint keeps
11551        // it off even when that means nowhere to run.
11552        let mac_only = make_empty_cfg(vec![make_machine_with_capacity(
11553            "us-west-015",
11554            24576,
11555            8000,
11556            mac_taints.clone(),
11557        )]);
11558        assert!(
11559            mac_only.admit_workload(&server_spec(256, 500)).is_err(),
11560            "a Server workload must be repelled from a Mac-only fleet, not admitted"
11561        );
11562
11563        // But the Mac's real job — build/forge workloads — IS admitted on it:
11564        // it tolerates every fleet taint (there is no `no-job`).
11565        let mut job = server_spec(256, 500);
11566        job.archetype = Some(LifecycleArchetype::Job);
11567        assert_eq!(
11568            mac_only.admit_workload(&job).unwrap().name,
11569            "us-west-015",
11570            "a build Job must still be admitted on the Mac build-worker"
11571        );
11572    }
11573
11574    // ─── R615-F1: linked infra sources (`.yah/infra/sources.toml`) ─────────
11575
11576    #[test]
11577    fn sources_load_is_empty_when_the_file_is_absent() {
11578        // "Every camp without linked infra has none" — which today is every
11579        // camp — must not be an error.
11580        let tmp = tempfile::TempDir::new().unwrap();
11581        let cfg = SourcesConfig::load(tmp.path()).unwrap();
11582        assert_eq!(cfg, SourcesConfig::default());
11583        assert!(cfg.source.is_empty());
11584        assert_eq!(cfg.schema_version, 1);
11585    }
11586
11587    #[test]
11588    fn sources_parses_a_path_kind_exactly_like_w274s_example() {
11589        let tmp = tempfile::TempDir::new().unwrap();
11590        std::fs::write(
11591            tmp.path().join("sources.toml"),
11592            r#"
11593schema_version = 1
11594
11595[[source]]
11596owner = "yah"
11597kind  = "path"
11598path  = "../yah"
11599mode  = "read-only"
11600"#,
11601        )
11602        .unwrap();
11603        let cfg = SourcesConfig::load(tmp.path()).unwrap();
11604        assert_eq!(cfg.source.len(), 1);
11605        let s = &cfg.source[0];
11606        assert_eq!(s.owner, "yah");
11607        assert_eq!(s.mode, SourceMode::ReadOnly);
11608        assert!(s.select.is_empty());
11609        match &s.kind {
11610            InfraSourceKind::Path { path } => assert_eq!(path, "../yah"),
11611            other => panic!("expected Path, got {other:?}"),
11612        }
11613    }
11614
11615    #[test]
11616    fn sources_parses_a_git_kind_reusing_gitsource_verbatim() {
11617        let tmp = tempfile::TempDir::new().unwrap();
11618        std::fs::write(
11619            tmp.path().join("sources.toml"),
11620            r#"
11621schema_version = 1
11622
11623[[source]]
11624owner  = "yah"
11625kind   = "git"
11626repo   = "git@github.com:yah-ai/infra.git"
11627ref    = "main"
11628subdir = "infra"
11629select = ["tag:cloud-runner"]
11630mode   = "read-only"
11631"#,
11632        )
11633        .unwrap();
11634        let cfg = SourcesConfig::load(tmp.path()).unwrap();
11635        assert_eq!(cfg.source.len(), 1);
11636        let s = &cfg.source[0];
11637        assert_eq!(s.select, vec!["tag:cloud-runner".to_string()]);
11638        match &s.kind {
11639            InfraSourceKind::Git(git) => {
11640                assert_eq!(git.repo, "git@github.com:yah-ai/infra.git");
11641                assert_eq!(git.r#ref, "main");
11642                assert_eq!(git.subdir.as_deref(), Some("infra"));
11643            }
11644            other => panic!("expected Git, got {other:?}"),
11645        }
11646    }
11647
11648    #[test]
11649    fn sources_mode_defaults_to_read_only_and_manage_is_explicit() {
11650        let tmp = tempfile::TempDir::new().unwrap();
11651        std::fs::write(
11652            tmp.path().join("sources.toml"),
11653            r#"
11654schema_version = 1
11655
11656[[source]]
11657owner = "a"
11658kind  = "path"
11659path  = "../a"
11660
11661[[source]]
11662owner = "b"
11663kind  = "path"
11664path  = "../b"
11665mode  = "manage"
11666"#,
11667        )
11668        .unwrap();
11669        let cfg = SourcesConfig::load(tmp.path()).unwrap();
11670        assert_eq!(cfg.source[0].mode, SourceMode::ReadOnly, "omitted mode = read-only");
11671        assert_eq!(cfg.source[1].mode, SourceMode::Manage);
11672    }
11673
11674    #[test]
11675    fn sources_preserves_declaration_order() {
11676        // Overlay order matters (R615-F2) when two sources name the same
11677        // machine — the list must round-trip in file order, not be reordered
11678        // by owner or kind.
11679        let tmp = tempfile::TempDir::new().unwrap();
11680        std::fs::write(
11681            tmp.path().join("sources.toml"),
11682            r#"
11683schema_version = 1
11684
11685[[source]]
11686owner = "second"
11687kind  = "path"
11688path  = "../second"
11689
11690[[source]]
11691owner = "first"
11692kind  = "path"
11693path  = "../first"
11694"#,
11695        )
11696        .unwrap();
11697        let cfg = SourcesConfig::load(tmp.path()).unwrap();
11698        let owners: Vec<&str> = cfg.source.iter().map(|s| s.owner.as_str()).collect();
11699        assert_eq!(owners, vec!["second", "first"]);
11700    }
11701
11702    #[test]
11703    fn sources_round_trips_through_serialize() {
11704        let cfg = SourcesConfig {
11705            schema_version: 1,
11706            source: vec![
11707                InfraSource {
11708                    owner: "yah".into(),
11709                    kind: InfraSourceKind::Path {
11710                        path: "../yah".into(),
11711                    },
11712                    mode: SourceMode::ReadOnly,
11713                    select: vec![],
11714                },
11715                InfraSource {
11716                    owner: "yah".into(),
11717                    kind: InfraSourceKind::Git(GitSource {
11718                        repo: "git@github.com:yah-ai/infra.git".into(),
11719                        r#ref: "main".into(),
11720                        subdir: Some("infra".into()),
11721                    }),
11722                    mode: SourceMode::Manage,
11723                    select: vec!["tag:cloud-runner".into()],
11724                },
11725            ],
11726        };
11727        let toml_str = toml::to_string_pretty(&cfg).unwrap();
11728        let reloaded: SourcesConfig = toml::from_str(&toml_str).unwrap();
11729        assert_eq!(reloaded, cfg, "round-trip through TOML must be lossless:\n{toml_str}");
11730    }
11731
11732    // ─── R615-F2: overlay loader in CloudConfig::load ───────────────────────
11733
11734    fn write_min_machine(dir: &Path, name: &str, extra_toml: &str) {
11735        std::fs::create_dir_all(dir).unwrap();
11736        // `extra_toml` supplies `mesh_tags` when the caller cares about it;
11737        // otherwise default to the empty list. Never hardcode `mesh_tags`
11738        // here as well as in `extra_toml` -- TOML rejects a duplicate key.
11739        let mesh_tags = if extra_toml.contains("mesh_tags") {
11740            String::new()
11741        } else {
11742            "mesh_tags = []\n".to_string()
11743        };
11744        std::fs::write(
11745            dir.join(format!("{name}.toml")),
11746            format!("name = \"{name}\"\nprovider = \"static\"\n{mesh_tags}{extra_toml}"),
11747        )
11748        .unwrap();
11749    }
11750
11751    fn write_min_provider(dir: &Path, id: &str) {
11752        std::fs::create_dir_all(dir).unwrap();
11753        std::fs::write(
11754            dir.join(format!("{id}.toml")),
11755            format!("schema_version = 1\nid = \"{id}\"\nkind = \"static\"\n"),
11756        )
11757        .unwrap();
11758    }
11759
11760    fn write_sources_toml(camp_root: &Path, body: &str) {
11761        let dir = camp_root.join(".yah/infra");
11762        std::fs::create_dir_all(&dir).unwrap();
11763        std::fs::write(dir.join("sources.toml"), body).unwrap();
11764    }
11765
11766    #[test]
11767    fn load_with_no_sources_toml_is_unchanged() {
11768        let tmp = tempfile::TempDir::new().unwrap();
11769        write_min_machine(&tmp.path().join(".yah/infra/machines"), "local-1", "");
11770        let cfg = CloudConfig::load(tmp.path()).unwrap();
11771        assert_eq!(cfg.machines.len(), 1);
11772        assert!(cfg.machine_origins.is_empty());
11773        assert!(cfg.provider_origins.is_empty());
11774    }
11775
11776    #[test]
11777    fn path_source_overlays_machines_and_providers_tagged_with_origin() {
11778        let camp = tempfile::TempDir::new().unwrap();
11779        let other = tempfile::TempDir::new().unwrap();
11780        write_min_machine(&other.path().join(".yah/infra/machines"), "borrowed-1", "");
11781        write_min_provider(&other.path().join(".yah/infra/providers"), "borrowed-provider");
11782        write_sources_toml(
11783            camp.path(),
11784            &format!(
11785                "schema_version = 1\n\n[[source]]\nowner = \"other\"\nkind = \"path\"\npath = \"{}\"\n",
11786                other.path().display()
11787            ),
11788        );
11789
11790        let cfg = CloudConfig::load(camp.path()).unwrap();
11791        assert_eq!(cfg.machines.len(), 1);
11792        assert_eq!(cfg.machines[0].name, "borrowed-1");
11793        assert_eq!(cfg.providers.len(), 1);
11794        assert_eq!(cfg.providers[0].id, "borrowed-provider");
11795
11796        let origin = cfg.machine_origins.get("borrowed-1").expect("origin recorded");
11797        assert_eq!(origin.owner, "other");
11798        assert_eq!(origin.mode, SourceMode::ReadOnly);
11799        assert!(origin.source.starts_with("path:"));
11800        assert_eq!(
11801            cfg.provider_origins.get("borrowed-provider").unwrap().owner,
11802            "other"
11803        );
11804    }
11805
11806    #[test]
11807    fn camp_local_wins_on_name_collision_and_carries_no_origin() {
11808        let camp = tempfile::TempDir::new().unwrap();
11809        let other = tempfile::TempDir::new().unwrap();
11810        // Both declare a machine named "shared" -- camp-local's copy must win,
11811        // and it must never gain an origin tag.
11812        write_min_machine(&camp.path().join(".yah/infra/machines"), "shared", "");
11813        write_min_machine(
11814            &other.path().join(".yah/infra/machines"),
11815            "shared",
11816            "nickname = \"the borrowed one\"\n",
11817        );
11818        write_sources_toml(
11819            camp.path(),
11820            &format!(
11821                "schema_version = 1\n\n[[source]]\nowner = \"other\"\nkind = \"path\"\npath = \"{}\"\n",
11822                other.path().display()
11823            ),
11824        );
11825
11826        let cfg = CloudConfig::load(camp.path()).unwrap();
11827        assert_eq!(cfg.machines.len(), 1, "the name collides, so exactly one entry");
11828        assert_eq!(cfg.machines[0].nickname, None, "camp-local's copy, not the borrowed one");
11829        assert!(
11830            !cfg.machine_origins.contains_key("shared"),
11831            "camp-local entries never carry an origin tag"
11832        );
11833    }
11834
11835    #[test]
11836    fn an_earlier_source_wins_over_a_later_one_on_collision() {
11837        let camp = tempfile::TempDir::new().unwrap();
11838        let first = tempfile::TempDir::new().unwrap();
11839        let second = tempfile::TempDir::new().unwrap();
11840        write_min_machine(&first.path().join(".yah/infra/machines"), "dup", "");
11841        write_min_machine(&second.path().join(".yah/infra/machines"), "dup", "");
11842        write_sources_toml(
11843            camp.path(),
11844            &format!(
11845                "schema_version = 1\n\n[[source]]\nowner = \"first\"\nkind = \"path\"\npath = \"{}\"\n\n[[source]]\nowner = \"second\"\nkind = \"path\"\npath = \"{}\"\n",
11846                first.path().display(),
11847                second.path().display()
11848            ),
11849        );
11850
11851        let cfg = CloudConfig::load(camp.path()).unwrap();
11852        assert_eq!(cfg.machines.len(), 1);
11853        assert_eq!(cfg.machine_origins.get("dup").unwrap().owner, "first");
11854    }
11855
11856    #[test]
11857    fn select_filters_borrowed_machines_by_name_or_mesh_tag() {
11858        let camp = tempfile::TempDir::new().unwrap();
11859        let other = tempfile::TempDir::new().unwrap();
11860        write_min_machine(&other.path().join(".yah/infra/machines"), "runner-1", "mesh_tags = [\"tag:cloud-runner\"]\n");
11861        write_min_machine(&other.path().join(".yah/infra/machines"), "excluded-1", "");
11862        write_sources_toml(
11863            camp.path(),
11864            &format!(
11865                "schema_version = 1\n\n[[source]]\nowner = \"other\"\nkind = \"path\"\npath = \"{}\"\nselect = [\"tag:cloud-runner\"]\n",
11866                other.path().display()
11867            ),
11868        );
11869
11870        let cfg = CloudConfig::load(camp.path()).unwrap();
11871        assert_eq!(cfg.machines.len(), 1);
11872        assert_eq!(cfg.machines[0].name, "runner-1");
11873    }
11874
11875    #[test]
11876    fn one_unparseable_foreign_machine_does_not_sink_the_rest_of_the_directory_or_the_load() {
11877        let camp = tempfile::TempDir::new().unwrap();
11878        let other = tempfile::TempDir::new().unwrap();
11879        let dir = other.path().join(".yah/infra/machines");
11880        write_min_machine(&dir, "good", "");
11881        // Schema-skew gotcha: a foreign machine this binary's MachineConfig
11882        // can't parse at all (not just an unknown field -- MachineConfig has
11883        // no deny_unknown_fields, so this has to fail on a TYPE, not a name).
11884        std::fs::write(dir.join("bad.toml"), "name = 1\nprovider = 2\n").unwrap();
11885        write_sources_toml(
11886            camp.path(),
11887            &format!(
11888                "schema_version = 1\n\n[[source]]\nowner = \"other\"\nkind = \"path\"\npath = \"{}\"\n",
11889                other.path().display()
11890            ),
11891        );
11892
11893        // Must not error at all -- camp-local load must never fail because a
11894        // source it doesn't own has one bad file.
11895        let cfg = CloudConfig::load(camp.path()).unwrap();
11896        assert_eq!(cfg.machines.len(), 1, "the good entry still loads");
11897        assert_eq!(cfg.machines[0].name, "good");
11898    }
11899
11900    #[test]
11901    fn an_unsynced_git_source_overlays_nothing_and_is_not_an_error() {
11902        // No `yah infra sync` (R615-T3) has ever run, so the cache dir this
11903        // resolves to doesn't exist. Must be silent, not fatal.
11904        let camp = tempfile::TempDir::new().unwrap();
11905        write_sources_toml(
11906            camp.path(),
11907            "schema_version = 1\n\n[[source]]\nowner = \"yah\"\nkind = \"git\"\nrepo = \"git@github.com:yah-ai/infra.git\"\nref = \"main\"\n",
11908        );
11909        let cfg = CloudConfig::load(camp.path()).unwrap();
11910        assert!(cfg.machines.is_empty());
11911        assert!(cfg.machine_origins.is_empty());
11912    }
11913
11914    #[test]
11915    fn a_synced_git_source_reads_from_the_cache_dir_not_the_repo_path() {
11916        // No `subdir` declared -- the checkout ROOT is the infra root.
11917        let camp = tempfile::TempDir::new().unwrap();
11918        let cache = crate::paths::infra_source_cache_dir(camp.path(), "yah");
11919        write_min_machine(&cache.join("machines"), "synced-1", "");
11920        write_sources_toml(
11921            camp.path(),
11922            "schema_version = 1\n\n[[source]]\nowner = \"yah\"\nkind = \"git\"\nrepo = \"git@github.com:yah-ai/infra.git\"\nref = \"main\"\n",
11923        );
11924        let cfg = CloudConfig::load(camp.path()).unwrap();
11925        assert_eq!(cfg.machines.len(), 1);
11926        assert_eq!(cfg.machines[0].name, "synced-1");
11927        assert!(cfg.machine_origins.get("synced-1").unwrap().source.starts_with("git:"));
11928    }
11929
11930    #[test]
11931    fn a_git_sources_subdir_is_honoured_like_the_component_case() {
11932        // W274's own example declares `subdir = "infra"` for a monorepo whose
11933        // registry lives under a subdirectory of the clone rather than at its
11934        // root -- prove `infra_root` actually reads it, not just `.subdir` on
11935        // GitSource parsing (R615-F1 already covers that half).
11936        let camp = tempfile::TempDir::new().unwrap();
11937        let cache = crate::paths::infra_source_cache_dir(camp.path(), "yah");
11938        write_min_machine(&cache.join("infra").join("machines"), "subdir-1", "");
11939        // Also plant a decoy at the checkout root to prove the root itself is
11940        // NOT read when a subdir is declared.
11941        write_min_machine(&cache.join("machines"), "root-decoy", "");
11942        write_sources_toml(
11943            camp.path(),
11944            "schema_version = 1\n\n[[source]]\nowner = \"yah\"\nkind = \"git\"\nrepo = \"git@github.com:yah-ai/infra.git\"\nref = \"main\"\nsubdir = \"infra\"\n",
11945        );
11946        let cfg = CloudConfig::load(camp.path()).unwrap();
11947        assert_eq!(cfg.machines.len(), 1);
11948        assert_eq!(cfg.machines[0].name, "subdir-1");
11949    }
11950
11951    #[test]
11952    fn load_from_config_dir_never_applies_sources_overlay() {
11953        // R615-F2's explicit decision: multi-root sibling trees don't inherit
11954        // the classic .yah/infra/sources.toml. Prove it rather than assert it
11955        // silently -- a sources.toml sitting at workspace_root/.yah/infra/
11956        // must NOT leak into a load_from_config_dir call even though both
11957        // share the same workspace_root.
11958        let camp = tempfile::TempDir::new().unwrap();
11959        let other = tempfile::TempDir::new().unwrap();
11960        write_min_machine(&other.path().join(".yah/infra/machines"), "borrowed-1", "");
11961        write_sources_toml(
11962            camp.path(),
11963            &format!(
11964                "schema_version = 1\n\n[[source]]\nowner = \"other\"\nkind = \"path\"\npath = \"{}\"\n",
11965                other.path().display()
11966            ),
11967        );
11968        let sibling_config_dir = camp.path().join(".noisetable");
11969        std::fs::create_dir_all(&sibling_config_dir).unwrap();
11970
11971        let cfg = CloudConfig::load_from_config_dir(&sibling_config_dir, camp.path()).unwrap();
11972        assert!(cfg.machines.is_empty(), "sources.toml must not apply here");
11973        assert!(cfg.machine_origins.is_empty());
11974    }
11975
11976    // ─── R615-T5: `inherit_machines` retirement — cutover proof ────────────
11977
11978    /// The successor to R615-T5's parity proof. That earlier pair of tests
11979    /// asserted the legacy `[infra].inherit_machines` redirect and an
11980    /// equivalent `kind = "path"` source resolved the same machine set, and
11981    /// that the two coexisted without duplicating rows. Both claims were about
11982    /// a mechanism that no longer exists, so they retired with it — what has
11983    /// to hold *now* is the other half of the same guarantee: a camp that
11984    /// declares only `sources.toml` resolves the shared root exactly as the
11985    /// redirect used to, and a stale `inherit_machines` key left behind in
11986    /// `camp.toml` changes nothing.
11987    ///
11988    /// That stale-key case is not hypothetical: it is precisely the state a
11989    /// camp is in between the code cutover and someone tidying its
11990    /// `camp.toml`, and a silent re-resolution there would double-count the
11991    /// borrowed nodes or hide their origin badge.
11992    #[test]
11993    fn a_stale_inherit_machines_key_does_not_change_what_sources_toml_resolves() {
11994        let shared = tempfile::TempDir::new().unwrap();
11995        write_min_machine(&shared.path().join(".yah/infra/machines"), "shared-node-1", "");
11996        write_min_machine(&shared.path().join(".yah/infra/machines"), "shared-node-2", "");
11997
11998        let sources_toml = format!(
11999            "schema_version = 1\n\n[[source]]\nowner = \"yah\"\nkind = \"path\"\npath = \"{}\"\nmode = \"read-only\"\n",
12000            shared.path().display()
12001        );
12002
12003        // Camp A: migrated cleanly — sources.toml only.
12004        let clean = tempfile::TempDir::new().unwrap();
12005        write_sources_toml(clean.path(), &sources_toml);
12006
12007        // Camp B: mid-migration — same source, plus the retired key still
12008        // sitting in camp.toml pointing at the same root.
12009        let stale = tempfile::TempDir::new().unwrap();
12010        std::fs::create_dir_all(stale.path().join(".yah")).unwrap();
12011        std::fs::write(
12012            stale.path().join(".yah/camp.toml"),
12013            format!(
12014                "[infra]\ninherit_machines = \"{}\"\n",
12015                shared.path().display()
12016            ),
12017        )
12018        .unwrap();
12019        write_sources_toml(stale.path(), &sources_toml);
12020
12021        let via_clean = CloudConfig::load(clean.path()).unwrap();
12022        let via_stale = CloudConfig::load(stale.path()).unwrap();
12023
12024        let names = |cfg: &CloudConfig| {
12025            let mut v: Vec<String> = cfg.machines.iter().map(|m| m.name.clone()).collect();
12026            v.sort();
12027            v
12028        };
12029        assert_eq!(
12030            names(&via_clean),
12031            names(&via_stale),
12032            "a leftover inherit_machines key must be inert — the retired redirect is gone"
12033        );
12034        assert_eq!(names(&via_clean), vec!["shared-node-1", "shared-node-2"]);
12035
12036        // And both are *borrowed*, not camp-local. This is the operator-facing
12037        // win the stopgap could never deliver: under the old redirect these
12038        // resolved with no origin at all, indistinguishable from locally-owned
12039        // nodes.
12040        assert_eq!(via_clean.machine_origins.len(), 2);
12041        assert_eq!(via_stale.machine_origins.len(), 2);
12042        for origin in via_stale.machine_origins.values() {
12043            assert_eq!(origin.owner, "yah");
12044            assert_eq!(origin.mode, SourceMode::ReadOnly);
12045        }
12046    }
12047
12048    // ─── R860-T4 (W338): placement groups ───────────────────────────────────
12049
12050    /// One requirement edge, written the way a spec author writes it.
12051    fn requirement(ident: &str, locality: Locality) -> workload_spec::Requirement {
12052        workload_spec::Requirement {
12053            ident: workload_spec::MeshIdent(ident.into()),
12054            locality,
12055            supply: workload_spec::Supply::Wait,
12056            provides: None,
12057        }
12058    }
12059
12060    /// A `minimal_spec` (256 MiB / 250 millicores, Server by inference) that
12061    /// requires the given edges.
12062    fn spec_requiring(name: &str, requires: Vec<workload_spec::Requirement>) -> WorkloadSpec {
12063        WorkloadSpec {
12064            requires,
12065            ..minimal_spec(name, 1)
12066        }
12067    }
12068
12069    /// The declared inventory an ident is resolved against — `.yah/infra/workloads/`.
12070    fn declared(specs: Vec<WorkloadSpec>) -> Vec<WorkloadConfig> {
12071        specs.into_iter().map(|spec| WorkloadConfig { spec }).collect()
12072    }
12073
12074    fn member_names(group: &[WorkloadSpec]) -> Vec<&str> {
12075        group.iter().map(|s| s.name.as_str()).collect()
12076    }
12077
12078    /// The headline case: `local` means "same node", so the two specs are one
12079    /// placement unit and admission has to reason about both.
12080    #[test]
12081    fn a_local_edge_binds_the_provider_into_the_placement_group() {
12082        let inventory = declared(vec![minimal_spec("headscale-replicator", 1)]);
12083        let requirer = spec_requiring(
12084            "headscale",
12085            vec![requirement("headscale-replicator", Locality::Local)],
12086        );
12087
12088        assert_eq!(
12089            member_names(&placement_group(&requirer, &inventory)),
12090            vec!["headscale", "headscale-replicator"]
12091        );
12092    }
12093
12094    /// The edge that must NOT bind. `prefer-local` "never blocks placement"
12095    /// (W338's locality table), and `anywhere` — which is what every legacy
12096    /// `depends_on` folds into — is an ordinary service dependency. Binding
12097    /// either would silently make every dependency in the tree a co-scheduling
12098    /// constraint and start summing unrelated workloads into the capacity floor.
12099    #[test]
12100    fn prefer_local_and_anywhere_edges_do_not_bind_the_group() {
12101        let inventory = declared(vec![
12102            minimal_spec("headscale-db", 1),
12103            minimal_spec("metrics", 1),
12104            minimal_spec("legacy-dep", 1),
12105        ]);
12106
12107        let requirer = WorkloadSpec {
12108            depends_on: vec![workload_spec::MeshIdent("legacy-dep".into())],
12109            ..spec_requiring(
12110                "headscale",
12111                vec![
12112                    requirement("headscale-db", Locality::PreferLocal),
12113                    requirement("metrics", Locality::Anywhere),
12114                ],
12115            )
12116        };
12117
12118        assert_eq!(
12119            member_names(&placement_group(&requirer, &inventory)),
12120            vec!["headscale"]
12121        );
12122    }
12123
12124    /// Transitive, and via the inline spec a `supply = "self"` requirement
12125    /// carries rather than via an ident lookup — the sidecar shape W338's
12126    /// worked example is built on.
12127    #[test]
12128    fn the_group_is_the_transitive_closure_and_traverses_inline_provides() {
12129        let inline = workload_spec::Requirement {
12130            supply: workload_spec::Supply::SelfProvision,
12131            provides: Some(Box::new(minimal_spec("headscale-restore", 1))),
12132            ..requirement("headscale-restore", Locality::Local)
12133        };
12134        let middle = WorkloadSpec {
12135            requires: vec![requirement("wal-shipper", Locality::Local)],
12136            ..minimal_spec("headscale-replicator", 1)
12137        };
12138        let inventory = declared(vec![middle, minimal_spec("wal-shipper", 1)]);
12139
12140        let requirer = spec_requiring(
12141            "headscale",
12142            vec![
12143                inline,
12144                requirement("headscale-replicator", Locality::Local),
12145            ],
12146        );
12147
12148        assert_eq!(
12149            member_names(&placement_group(&requirer, &inventory)),
12150            vec![
12151                "headscale",
12152                "headscale-restore",
12153                "headscale-replicator",
12154                "wal-shipper"
12155            ]
12156        );
12157    }
12158
12159    /// `validate::check_requires` bounds `provides` nesting to depth 1 but
12160    /// cannot stop two separately-declared specs from naming each other. Without
12161    /// the visited set this closure never terminates, so admission would hang
12162    /// rather than refuse — the worst failure shape for a deploy gate.
12163    #[test]
12164    fn an_ident_cycle_closes_the_group_instead_of_looping_forever() {
12165        let b = spec_requiring("b", vec![requirement("a", Locality::Local)]);
12166        let a = spec_requiring("a", vec![requirement("b", Locality::Local)]);
12167        let inventory = declared(vec![a.clone(), b]);
12168
12169        assert_eq!(member_names(&placement_group(&a, &inventory)), vec!["a", "b"]);
12170    }
12171
12172    /// An unresolvable ident is skipped, not fatal: admission is a pure function
12173    /// of the declared inventory, and refusing every deploy whose provider is
12174    /// not yet declared would make `requires` unusable before R860-T6 lands.
12175    #[test]
12176    fn an_unresolvable_local_ident_is_skipped_rather_than_refused() {
12177        let requirer = spec_requiring("headscale", vec![requirement("not-declared", Locality::Local)]);
12178        assert_eq!(
12179            member_names(&placement_group(&requirer, &[])),
12180            vec!["headscale"]
12181        );
12182    }
12183
12184    /// W338 §Placement consequences 1: the capacity floor is the group's sum.
12185    /// A node that fits the requirer alone must refuse the group — placing it
12186    /// there would oversubscribe the node the moment the provider follows.
12187    #[test]
12188    fn the_capacity_floor_is_the_sum_of_the_group_not_the_requirer_alone() {
12189        let provider = minimal_spec("headscale-replicator", 1);
12190        let requirer = spec_requiring(
12191            "headscale",
12192            vec![requirement("headscale-replicator", Locality::Local)],
12193        );
12194        // Two `minimal_spec`s: 256 MiB + 250 millicores each.
12195        let inventory = declared(vec![provider]);
12196
12197        let too_small = CloudConfig {
12198            workloads: inventory.clone(),
12199            ..make_empty_cfg(vec![make_machine_with_capacity("small", 300, 4000, vec![])])
12200        };
12201        let err = too_small.admit_workload(&requirer).unwrap_err().to_string();
12202        assert!(
12203            err.contains("memory_mb>=512"),
12204            "the floor must name the group's summed demand, got: {err}"
12205        );
12206
12207        let big_enough = CloudConfig {
12208            workloads: inventory,
12209            ..make_empty_cfg(vec![make_machine_with_capacity("roomy", 512, 4000, vec![])])
12210        };
12211        assert_eq!(
12212            big_enough.admit_workload(&requirer).unwrap().name,
12213            "roomy",
12214            "a node covering the sum must still admit the group"
12215        );
12216    }
12217
12218    /// W338 §Placement consequences 2, and the reason repulsion is computed over
12219    /// a set at all: the requirer is a `Server`, so the pre-R860 axis would have
12220    /// let it onto a `no-appliance` dev Pi and dragged its Appliance provider
12221    /// there with it.
12222    #[test]
12223    fn a_server_requiring_an_appliance_locally_is_repelled_by_no_appliance() {
12224        let appliance = WorkloadSpec {
12225            archetype: Some(LifecycleArchetype::Appliance),
12226            ..minimal_spec("headscale", 1)
12227        };
12228        let requirer = spec_requiring("headscale-ui", vec![requirement("headscale", Locality::Local)]);
12229        assert_eq!(
12230            requirer.effective_archetype(),
12231            LifecycleArchetype::Server,
12232            "precondition: the requirer itself must not be an Appliance"
12233        );
12234
12235        let cfg = CloudConfig {
12236            workloads: declared(vec![appliance]),
12237            ..make_empty_cfg(vec![
12238                make_machine_with_capacity("dev-pi", 8192, 4000, vec!["no-appliance"]),
12239                make_machine_with_capacity("us-west-001", 8192, 4000, vec![]),
12240            ])
12241        };
12242
12243        assert_eq!(
12244            cfg.admit_workload(&requirer).unwrap().name,
12245            "us-west-001",
12246            "the dev Pi repels the group's Appliance member"
12247        );
12248
12249        // And with the Appliance gone from the group, the same requirer is
12250        // admissible on the same Pi — proving the repulsion came from the edge.
12251        let alone = minimal_spec("headscale-ui", 1);
12252        assert_eq!(cfg.admit_workload(&alone).unwrap().name, "dev-pi");
12253    }
12254
12255    /// The set-valued form of the per-workload drain skip the node makes in
12256    /// `drain_workloads`: one Appliance member pins the whole group.
12257    #[test]
12258    fn a_group_containing_an_appliance_is_not_drainable() {
12259        let server = minimal_spec("headscale-ui", 1);
12260        let appliance = WorkloadSpec {
12261            archetype: Some(LifecycleArchetype::Appliance),
12262            ..minimal_spec("headscale", 1)
12263        };
12264
12265        assert!(group_is_drainable(std::slice::from_ref(&server)));
12266        assert!(!group_is_drainable(&[server, appliance]));
12267    }
12268
12269    /// The regression that matters most: nothing in the tree declares
12270    /// `requires` yet, so every existing spec's group is exactly itself and its
12271    /// admission axes must be bit-identical to the pre-R860 derivation.
12272    #[test]
12273    fn a_spec_with_no_local_edges_admits_exactly_as_it_did_before() {
12274        let ws = ws_with_selector(Some("tag:build-worker,arch:x86"));
12275        let req = admission_spec(&ws, &[]).unwrap();
12276
12277        assert_eq!(req.mesh_tags, vec!["tag:build-worker", "arch:x86"]);
12278        assert_eq!(req.memory_mb, ws.memory_request_mb());
12279        assert_eq!(req.cpu_millis, ws.resources.cpu_millis);
12280        // R876-B7: the axis is now the complement — every repelling key EXCEPT
12281        // this spec's own class, which is the same predicate stated from the
12282        // other side. Asserted against the derivation rather than a literal so
12283        // it stays true if a fourth archetype is added.
12284        assert_eq!(
12285            req.tolerates,
12286            tolerations_excluding(&[ws.effective_archetype()])
12287        );
12288        let own = format!("no-{}", ws.effective_archetype().taint_key());
12289        assert!(
12290            !req.tolerates.contains(&own),
12291            "a spec never tolerates the taint aimed at its own class"
12292        );
12293    }
12294
12295    // ─── R860-T5 (W338 §Placement consequences 3): native-exec capability ────
12296
12297    /// A `minimal_spec` carrying the `yah.exec = native` marker — the only way
12298    /// a workload says "fork+exec me on the host" (`WorkloadSpec::
12299    /// wants_native_exec`). It stays a Container workload on the wire; the
12300    /// marker is the whole difference.
12301    fn native_spec(name: &str) -> WorkloadSpec {
12302        let mut ws = minimal_spec(name, 1);
12303        ws.annotations.insert(
12304            workload_spec::NATIVE_EXEC_ANNOTATION.to_string(),
12305            workload_spec::NATIVE_EXEC_VALUE.to_string(),
12306        );
12307        assert!(ws.wants_native_exec(), "precondition: the marker must read back");
12308        ws
12309    }
12310
12311    /// The R858 failure, now caught at placement instead of at dispatch: a node
12312    /// whose kamaji has no `--native-exec-dir` accepted the election and then
12313    /// refused the deploy, and nothing upstream could see it coming.
12314    #[test]
12315    fn a_node_without_the_native_exec_capability_cannot_host_a_native_workload() {
12316        let native = native_spec("headscale");
12317
12318        let incapable = make_empty_cfg(vec![make_machine("us-south-001", vec![])]);
12319        let err = incapable.admit_workload(&native).unwrap_err().to_string();
12320        assert!(
12321            err.contains(NATIVE_EXEC_MESH_TAG),
12322            "the refusal must name the missing capability, got: {err}"
12323        );
12324
12325        let capable = make_empty_cfg(vec![
12326            make_machine("us-south-001", vec![]),
12327            make_machine("us-west-001", vec![NATIVE_EXEC_MESH_TAG]),
12328        ]);
12329        assert_eq!(
12330            capable.admit_workload(&native).unwrap().name,
12331            "us-west-001",
12332            "a node declaring the capability admits the native workload"
12333        );
12334    }
12335
12336    /// W338's actual sentence: a `supply = "self"` spec "must be placeable where
12337    /// its requirer lands". The requirer here is an ordinary container workload
12338    /// — it is the *provider* reached by a `local` edge that needs the host
12339    /// backend, so the capability has to be required of the group, not of the
12340    /// spec being deployed.
12341    #[test]
12342    fn a_local_edge_to_a_native_provider_makes_the_requirer_need_the_capability() {
12343        let requirer = spec_requiring(
12344            "headscale-ui",
12345            vec![requirement("headscale", Locality::Local)],
12346        );
12347        assert!(
12348            !requirer.wants_native_exec(),
12349            "precondition: the requirer itself is an ordinary container workload"
12350        );
12351
12352        let cfg = CloudConfig {
12353            workloads: declared(vec![native_spec("headscale")]),
12354            ..make_empty_cfg(vec![
12355                make_machine("plain", vec![]),
12356                make_machine("us-west-001", vec![NATIVE_EXEC_MESH_TAG]),
12357            ])
12358        };
12359
12360        assert_eq!(
12361            cfg.admit_workload(&requirer).unwrap().name,
12362            "us-west-001",
12363            "the group's native member pulls the requirer onto a capable node"
12364        );
12365
12366        // Without the edge the same requirer is admissible on the plain node,
12367        // so the constraint provably came from the group and not from the spec.
12368        let alone = minimal_spec("headscale-ui", 1);
12369        assert_eq!(cfg.admit_workload(&alone).unwrap().name, "plain");
12370    }
12371
12372    /// The regression guard: nothing in the tree is native-marked today, so
12373    /// every existing spec's axes must be untouched by this ticket.
12374    #[test]
12375    fn a_group_with_no_native_member_does_not_require_the_capability() {
12376        let inventory = declared(vec![minimal_spec("headscale-replicator", 1)]);
12377        let requirer = spec_requiring(
12378            "headscale",
12379            vec![requirement("headscale-replicator", Locality::Local)],
12380        );
12381
12382        let req = admission_spec(&requirer, &inventory).unwrap();
12383        assert!(
12384            !req.mesh_tags.iter().any(|t| t == NATIVE_EXEC_MESH_TAG),
12385            "no native member ⇒ no capability axis, got: {:?}",
12386            req.mesh_tags
12387        );
12388
12389        // And it still lands on a node that declares nothing at all.
12390        let cfg = CloudConfig {
12391            workloads: inventory,
12392            ..make_empty_cfg(vec![make_machine("plain", vec![])])
12393        };
12394        assert_eq!(cfg.admit_workload(&requirer).unwrap().name, "plain");
12395    }
12396
12397    // ─── R894-F1: trust declares a minimum isolation substrate ───────────────
12398
12399    /// A `minimal_spec` marked untrusted **without** raising its substrate —
12400    /// i.e. the incoherent pairing this ticket exists to refuse.
12401    ///
12402    /// It deliberately does not go through `WorkloadSpec::stamp_untrusted`,
12403    /// which raises the substrate as it stamps: the point of these tests is the
12404    /// admission-side gate, so the spec has to arrive in the state a buggy or
12405    /// hostile producer would leave it in, not the state the correct producer
12406    /// guarantees.
12407    fn untrusted_spec(name: &str, exec: Option<&str>) -> WorkloadSpec {
12408        let mut ws = minimal_spec(name, 1);
12409        ws.annotations.insert(
12410            workload_spec::TRUST_ANNOTATION.to_string(),
12411            workload_spec::TRUST_UNTRUSTED_VALUE.to_string(),
12412        );
12413        if let Some(v) = exec {
12414            ws.annotations.insert(
12415                workload_spec::NATIVE_EXEC_ANNOTATION.to_string(),
12416                v.to_string(),
12417            );
12418        }
12419        assert_eq!(
12420            ws.trust().unwrap(),
12421            workload_spec::TrustLevel::Untrusted,
12422            "precondition: the trust marker must read back"
12423        );
12424        ws
12425    }
12426
12427    /// THE ACCEPTANCE GATE. Both refusals happen inside `admit_workload` — the
12428    /// real dispatch path `MeshYubabaClient::elect_node` calls — against a fleet
12429    /// that contains a microVM-capable node, so the refusal is provably the
12430    /// trust rule and not "nothing admits this".
12431    #[test]
12432    fn admit_workload_refuses_untrusted_code_on_a_shared_kernel() {
12433        let cfg = make_empty_cfg(vec![
12434            make_machine("plain", vec![]),
12435            make_machine("us-west-003", vec![MICROVM_MESH_TAG]),
12436        ]);
12437
12438        // (1) Untrusted + `yah.exec = native`: the widest possible substrate.
12439        let native = untrusted_spec("tenant-camp", Some(workload_spec::NATIVE_EXEC_VALUE));
12440        let err = cfg.admit_workload(&native).unwrap_err().to_string();
12441        assert!(
12442            err.contains("tenant-camp") && err.contains("native") && err.contains("microvm"),
12443            "the refusal must name the workload, what it asked for and the floor, got: {err}"
12444        );
12445
12446        // (2) Untrusted with no substrate marker at all — the container default.
12447        // This is the one a "absent means trusted for ALL origins" spelling
12448        // would have admitted.
12449        let container = untrusted_spec("tenant-camp", None);
12450        assert_eq!(
12451            container.exec_substrate(),
12452            workload_spec::ExecSubstrate::Container,
12453            "precondition: no marker means the container backend"
12454        );
12455        let err = cfg.admit_workload(&container).unwrap_err().to_string();
12456        assert!(
12457            err.contains("container") && err.contains("microvm"),
12458            "an unmarked untrusted spec is refused for the same reason, got: {err}"
12459        );
12460
12461        // (3) The same spec asking for a microVM is admitted, onto the node that
12462        // declares the capability. Same fleet, same workload name — so (1) and
12463        // (2) provably failed on the substrate and nothing else.
12464        let vm = untrusted_spec("tenant-camp", Some(workload_spec::MICROVM_EXEC_VALUE));
12465        assert_eq!(cfg.admit_workload(&vm).unwrap().name, "us-west-003");
12466    }
12467
12468    /// A caller may always request *more* isolation than it needs. A trusted
12469    /// workload asking for a microVM is not "exceeding" anything — the rule is
12470    /// one-directional.
12471    #[test]
12472    fn a_trusted_workload_may_still_request_a_stricter_substrate() {
12473        let mut ws = minimal_spec("forge-build", 1);
12474        ws.annotations.insert(
12475            workload_spec::NATIVE_EXEC_ANNOTATION.to_string(),
12476            workload_spec::MICROVM_EXEC_VALUE.to_string(),
12477        );
12478        assert_eq!(ws.trust().unwrap(), workload_spec::TrustLevel::Trusted);
12479
12480        let cfg = make_empty_cfg(vec![
12481            make_machine("plain", vec![]),
12482            make_machine("us-west-003", vec![MICROVM_MESH_TAG]),
12483        ]);
12484        assert_eq!(cfg.admit_workload(&ws).unwrap().name, "us-west-003");
12485    }
12486
12487    /// An untrusted member reached by a `local` edge is still on the node, so
12488    /// the group is refused even though the spec being deployed is fine — the
12489    /// same group-wide reasoning every other axis in `admission_spec` uses.
12490    #[test]
12491    fn an_untrusted_provider_refuses_the_whole_placement_group() {
12492        let requirer = spec_requiring(
12493            "camp-front",
12494            vec![requirement("tenant-camp", Locality::Local)],
12495        );
12496        assert_eq!(
12497            requirer.trust().unwrap(),
12498            workload_spec::TrustLevel::Trusted,
12499            "precondition: the requirer itself is an ordinary trusted workload"
12500        );
12501
12502        let cfg = CloudConfig {
12503            workloads: declared(vec![untrusted_spec("tenant-camp", None)]),
12504            ..make_empty_cfg(vec![make_machine("us-west-003", vec![MICROVM_MESH_TAG])])
12505        };
12506        let err = cfg.admit_workload(&requirer).unwrap_err().to_string();
12507        assert!(
12508            err.contains("tenant-camp"),
12509            "the refusal must name the offending MEMBER, not the requirer, got: {err}"
12510        );
12511
12512        // The same requirer without the edge admits fine, so the refusal
12513        // provably came from the group.
12514        let alone = minimal_spec("camp-front", 1);
12515        assert_eq!(cfg.admit_workload(&alone).unwrap().name, "us-west-003");
12516    }
12517
12518    /// A typo in the trust value is refused, not resolved to either side.
12519    /// Reading it as trusted would turn the microVM floor off by misspelling.
12520    #[test]
12521    fn an_unreadable_trust_declaration_is_refused_rather_than_defaulted() {
12522        let mut ws = minimal_spec("tenant-camp", 1);
12523        ws.annotations.insert(
12524            workload_spec::TRUST_ANNOTATION.to_string(),
12525            "untrused".to_string(),
12526        );
12527
12528        let cfg = make_empty_cfg(vec![make_machine("plain", vec![])]);
12529        let err = cfg.admit_workload(&ws).unwrap_err().to_string();
12530        assert!(
12531            err.contains("untrused") && err.contains("tenant-camp"),
12532            "the refusal must quote the unreadable value, got: {err}"
12533        );
12534    }
12535
12536    /// The regression guard for the new mesh-tag axis, in the shape R860-T5's
12537    /// own guard uses: nothing in the fleet is microVM-marked today, so every
12538    /// existing spec's axes must be untouched.
12539    #[test]
12540    fn a_group_with_no_microvm_member_does_not_require_the_capability() {
12541        let ws = minimal_spec("headscale-ui", 1);
12542        let req = admission_spec(&ws, &[]).unwrap();
12543        assert!(
12544            !req.mesh_tags.iter().any(|t| t == MICROVM_MESH_TAG),
12545            "no microVM member ⇒ no capability axis, got: {:?}",
12546            req.mesh_tags
12547        );
12548
12549        // And a microVM-marked spec is refused by a node declaring nothing,
12550        // naming the tag — the dispatch-time surprise R858 paid for.
12551        let mut vm = minimal_spec("forge-build", 1);
12552        vm.annotations.insert(
12553            workload_spec::NATIVE_EXEC_ANNOTATION.to_string(),
12554            workload_spec::MICROVM_EXEC_VALUE.to_string(),
12555        );
12556        let cfg = make_empty_cfg(vec![make_machine("plain", vec![])]);
12557        let err = cfg.admit_workload(&vm).unwrap_err().to_string();
12558        assert!(
12559            err.contains(MICROVM_MESH_TAG),
12560            "the refusal must name the missing capability, got: {err}"
12561        );
12562    }
12563
12564    /// The gate is structural, not a convention followed at three call sites:
12565    /// every admission entry point goes through `admission_spec`, so all three
12566    /// refuse the same spec.
12567    #[test]
12568    fn every_admission_entry_point_enforces_the_trust_floor() {
12569        let ws = untrusted_spec("tenant-camp", Some(workload_spec::NATIVE_EXEC_VALUE));
12570        let mut machine = make_machine("us-west-003", vec![MICROVM_MESH_TAG]);
12571        machine.sovereign_group = Some("home".to_string());
12572        let cfg = make_empty_cfg(vec![machine]);
12573
12574        assert!(cfg.admit_workload(&ws).is_err());
12575        assert!(cfg.admit_workload_candidates(&ws).is_err());
12576        assert!(cfg.admit_workload_in_group(&ws, "home").is_err());
12577    }
12578
12579    // ── R892-B1: a declared key must never be dropped in silence ─────────────
12580
12581    /// The real shape, not a hand-minimised one: a key check that passes on a
12582    /// toy spec and trips on a production file is worse than no check.
12583    /// Modelled on `.yah/infra/workloads/yah-cloud-admin.toml`.
12584    const REAL_WORKLOAD_TOML: &str = r#"
12585name = "yah-cloud-admin"
12586tier = "infra"
12587archetype = "server"
12588replicas = 1
12589restart_policy = "always"
12590
12591[image]
12592registry = "cr.yah.dev"
12593repository = "yah-cloud-admin"
12594tag = "20260903-amd64"
12595digest = "sha256:efaa7824ebf1654b226e4bf9cf4f86f1ce39b17900895b1f9d83e4d987f58733"
12596
12597[resources]
12598memory_mb = 256
12599cpu_millis = 250
12600
12601[annotations]
12602"yah.network" = "host"
12603
12604[expose.mesh]
12605identity = "yah-cloud-admin"
12606ports = [4325]
12607allow_from = []
12608
12609[[env]]
12610name = "YAH_CLOUD_ADMIN_ADDR"
12611value = { literal = { value = "100.64.0.1:4325" } }
12612
12613[[secrets]]
12614source = { cluster = { name = "cheers/cloud-admin/verify-key" } }
12615target = { file = { path = "/run/secrets/cheers-verify.key", mode = 0o400 } }
12616
12617[healthcheck]
12618probe = { http_get = { path = "/__mesofact/health", port = 4325, expect_status = 200 } }
12619interval = 15000
12620timeout = 5000
12621initial_delay = 20000
12622failure_threshold = 3
12623
12624[stop_policy]
12625signal = 15
12626grace_period = 10000
12627"#;
12628
12629    fn check_keys(src: &str) -> Result<()> {
12630        let spec: WorkloadSpec = toml::from_str(src).expect("fixture must parse");
12631        refuse_dropped_keys(src, &spec, "fixture.toml")
12632    }
12633
12634    /// Non-vacuity, and the guard against a check that flags everything: a file
12635    /// whose every key the schema knows must load clean.
12636    #[test]
12637    fn a_workload_file_whose_keys_all_survive_the_parse_is_accepted() {
12638        check_keys(REAL_WORKLOAD_TOML).expect("a fully-known file must not be refused");
12639    }
12640
12641    /// The 2026-09-11 outage, reproduced in one line of TOML: R885-T6 deleted
12642    /// `ResourceLimits::ephemeral_storage_mb`, every camp's file still declared
12643    /// it, and serde discarded it without a word.
12644    #[test]
12645    fn the_key_that_caused_the_outage_is_now_refused_by_name() {
12646        let src = REAL_WORKLOAD_TOML.replace(
12647            "cpu_millis = 250",
12648            "cpu_millis = 250\nephemeral_storage_mb = 256",
12649        );
12650        let err = check_keys(&src).expect_err("a dropped key must refuse the file");
12651        let msg = format!("{err:#}");
12652        assert!(
12653            msg.contains("resources.ephemeral_storage_mb"),
12654            "the refusal must name the key by its full path, got: {msg}"
12655        );
12656    }
12657
12658    /// Nested and top-level keys are both reported, so a misspelling anywhere in
12659    /// the file is as loud as a removed field.
12660    #[test]
12661    fn every_unknown_key_is_named_not_just_the_first() {
12662        let src = format!("{REAL_WORKLOAD_TOML}\nreplica_count = 3\n\n[healthcheck_typo]\nx = 1\n");
12663        let err = check_keys(&src).expect_err("unknown keys must refuse the file");
12664        let msg = format!("{err:#}");
12665        assert!(msg.contains("replica_count"), "got: {msg}");
12666        assert!(msg.contains("healthcheck_typo"), "got: {msg}");
12667    }
12668
12669    /// A value the serialiser re-spells (an enum, a duration) is not a dropped
12670    /// key. Only a missing KEY is, which is what keeps this check from firing on
12671    /// every legitimate file in the fleet.
12672    #[test]
12673    fn a_canonicalised_value_is_not_reported_as_dropped() {
12674        let declared = toml::Value::try_from(toml::toml! {
12675            restart = "always"
12676            [nested]
12677            list = [1, 2]
12678        })
12679        .unwrap();
12680        let kept = toml::Value::try_from(toml::toml! {
12681            restart = "Always"
12682            [nested]
12683            list = [9, 9]
12684        })
12685        .unwrap();
12686        let mut out = Vec::new();
12687        collect_dropped_keys(&declared, &kept, "", &mut out);
12688        assert!(out.is_empty(), "values differ, keys do not: {out:?}");
12689    }
12690
12691    /// R896-B5: a key whose field was deleted as inert loads with a warning
12692    /// instead of refusing the file, so deleting the field does not break every
12693    /// camp whose committed TOML still declares it. Driven off the registry, so
12694    /// the next retired key is covered the moment it is listed.
12695    #[test]
12696    fn every_retired_key_is_ignored_not_refused() {
12697        for retired in workload_spec::RETIRED_KEYS {
12698            let mut declared: toml::Value = toml::from_str(REAL_WORKLOAD_TOML).unwrap();
12699            let (parents, leaf) = match retired.path.rsplit_once('.') {
12700                Some((p, l)) => (p.split('.').collect::<Vec<_>>(), l),
12701                None => (vec![], retired.path),
12702            };
12703            let mut table = declared.as_table_mut().unwrap();
12704            for p in parents {
12705                table = table
12706                    .entry(p)
12707                    .or_insert_with(|| toml::Value::Table(Default::default()))
12708                    .as_table_mut()
12709                    .unwrap();
12710            }
12711            table.insert(leaf.into(), toml::Value::Integer(1));
12712            let src = toml::to_string(&declared).unwrap();
12713            check_keys(&src)
12714                .unwrap_or_else(|e| panic!("retired `{}` must not refuse: {e:#}", retired.path));
12715        }
12716    }
12717
12718    /// The registry is an exemption from R892-B1, not a hole in it: a retired
12719    /// key sitting beside an unknown one still refuses the file, naming only the
12720    /// unknown key.
12721    #[test]
12722    fn a_retired_key_does_not_excuse_an_unknown_one() {
12723        let src = format!("schema_version = 1\n{REAL_WORKLOAD_TOML}\nreplica_count = 3\n");
12724        let msg = format!("{:#}", check_keys(&src).expect_err("unknown key must still refuse"));
12725        assert!(msg.contains("replica_count"), "got: {msg}");
12726        assert!(!msg.contains("schema_version"), "retired key must not be named: {msg}");
12727    }
12728}