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
119use anyhow::{bail, Context, Result};
120use serde::{Deserialize, Serialize};
121use std::collections::{BTreeMap, HashMap};
122use std::path::Path;
123use thiserror::Error;
124use workload_spec::secrets::SecretAccess;
125use workload_spec::sovereign::Membership;
126pub use workload_spec::sovereign::SovereignRole;
127use workload_spec::{validate, LifecycleArchetype, TenantId, WorkloadSpec};
128
129/// Static node capacity declaration on `machine.toml` (R572-F3).
130///
131/// `memory_mb` and `cpu_millis` express the node's *total* hardware budget.
132/// F5's bin-packer subtracts the sum of committed workload requests from
133/// this floor to determine available headroom; an absent `allocatable`
134/// block means no capacity constraint is enforced (any workload fits).
135#[derive(Debug, Clone, Serialize, Deserialize)]
136#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
137pub struct NodeAllocatable {
138 /// Total physical RAM in mebibytes (e.g. 512 for a 512 MB node).
139 pub memory_mb: u32,
140 /// Total CPU in k8s millicores (1000 = 1 core, 250 = 0.25 CPU).
141 pub cpu_millis: u32,
142}
143
144/// `[registration]` — facts **observed** about a running box, written by the
145/// fleet rather than declared by an operator (R707-T1).
146///
147/// The rest of `machine.toml` is *declaration*: intent, operator-authored,
148/// reviewed and diffed like any other source. This block is the other half —
149/// what the box turned out to be once it booted and joined. Keeping the two
150/// apart is what lets the published fleet index (R707-F3) say which half it is
151/// carrying; publishing them under one schema would bake the confusion into a
152/// permanent record.
153///
154/// The split is a **provenance** boundary, not a trust or reach one:
155/// - *Declaration* answers "what did we ask for" — `name`, `region`, `arch`,
156/// `mesh_tags`, `[allocatable]`, and the declared reach in [`ConnectSpec`].
157/// - *Registration* answers "what did we observe" — the hostkey TOFU'd at
158/// attach, the mesh address headscale assigned at join.
159///
160/// It stays in the git-tracked TOML on purpose. Registration is not local
161/// scratch state: every consumer needs the mesh address to dial a node, so it
162/// has to travel with the declaration. (`.yah/infra/state/machines/<name>.json`
163/// — [`crate::state::MachineState`] — remains the *gitignored* sidecar for
164/// provider-side derivatives that nobody but this camp needs.)
165#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
166#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
167pub struct MachineRegistration {
168 /// Yubaba's ed25519 `/identity` fingerprint, TOFU-recorded by
169 /// `yah cloud machine attach` on first contact (`SHA256:…`). An observed
170 /// property of a running process — not the operator's intent — which is
171 /// why it moved out of the top level here.
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub hostkey_fingerprint: Option<String>,
174 /// Mesh (headscale/tailnet) IPv4 assigned at join, e.g. `"100.64.0.1"`.
175 /// Bare address, not a URL: the *port* is declared reach and lives on
176 /// [`ConnectSpec::yubaba_port`]. [`MachineConfig::yubaba_url`] composes the
177 /// two. Absent until the node has joined the mesh.
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub mesh_ipv4: Option<String>,
180 /// RFC3339 timestamp of the mesh join that produced `mesh_ipv4`. Free-form
181 /// audit; nothing keys off it.
182 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub joined_at: Option<String>,
184}
185
186impl MachineRegistration {
187 /// True when nothing has been observed yet — used to omit the whole
188 /// `[registration]` table from a serialized machine TOML.
189 pub fn is_empty(&self) -> bool {
190 self.hostkey_fingerprint.is_none() && self.mesh_ipv4.is_none() && self.joined_at.is_none()
191 }
192}
193
194/// Per-machine TOML from `.yah/infra/machines/<name>.toml`.
195///
196/// Two halves, split by provenance (R707-T1): everything here is *declaration*
197/// — operator intent under review and blame — except [`registration`], which
198/// carries what the fleet observed. See [`MachineRegistration`] for why the
199/// boundary is drawn there and what depends on it.
200#[derive(Debug, Clone, Serialize, Deserialize)]
201#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
202pub struct MachineConfig {
203 pub name: String,
204 pub provider: String,
205 /// Who the hardware actually comes from (`"ovh"`, `"vultr"`, `"on-prem"`).
206 ///
207 /// Deliberately *not* [`provider`](Self::provider), which selects the
208 /// auto-provision driver: a box we rented by hand and brought up over SSH
209 /// is `provider = "static"` for its whole life, and writing the vendor
210 /// there instead would flip it driver-backed and make
211 /// [`validate`](Self::validate) demand `location` + `server_type` it has no
212 /// answer for. The two axes genuinely differ — vendor is who bills you,
213 /// `provider` is who yah can call an API against.
214 ///
215 /// Worth recording because vendor-scoped policy is invisible in every other
216 /// field and decides real work: outbound port 25, rDNS/PTR control, IP
217 /// reputation, egress billing. It survived only in TOML prose until now,
218 /// which made it ungreppable at exactly the moment you need it.
219 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub vendor: Option<String>,
221 /// Human label for the box (`"gamer"`, `"the GEEKOM"`). Free-form and never
222 /// matched on — [`name`](Self::name) stays the identity everywhere. This is
223 /// only so operators and agents can say which box they mean out loud.
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub nickname: Option<String>,
226 /// Provider DC code (e.g. Hetzner `"hil"`). **Provisioning-only**: required
227 /// iff the provider has an auto-provision driver ([`provider_has_machine_driver`]);
228 /// a BYO `static` node we brought up over SSH has no such code. Optional at
229 /// load time so static machine.tomls omit it; [`MachineConfig::validate`]
230 /// enforces presence at the right moment for driver-backed providers.
231 #[serde(default, skip_serializing_if = "Option::is_none")]
232 pub location: Option<String>,
233 /// Provider SKU/size (e.g. Hetzner `"ccx13"`). Provisioning-only, same
234 /// optionality contract as [`location`](Self::location).
235 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub server_type: Option<String>,
237 /// **Deprecated (R330-F16).** A machine should describe *itself* (region,
238 /// zone, provider, mesh_tags); *which* mirrors run on it is derived by the
239 /// reconciler from each mirror's `required` placement spec, not declared
240 /// here. Now optional + omitted-when-empty so new machine.tomls leave it
241 /// out. The legacy `resolve_mirror_machine` topology fallback still reads
242 /// it until yubaba's reverse-index supersedes the topology.toml path; once
243 /// that lands, this field and its readers are removed wholesale.
244 #[serde(default, skip_serializing_if = "Vec::is_empty")]
245 pub hosts_mirrors: Vec<String>,
246 pub mesh_tags: Vec<String>,
247 /// Canonical geo region label (latency axis), e.g. `"us-west"`. F16's three
248 /// topology axes are orthogonal: `region` = geo (latency), `zone` = failure
249 /// domain within a region (HA), `provider` = network/cost. `region` is
250 /// distinct from `location` (the provider's DC code, e.g. Hetzner `"hil"`):
251 /// `location` is provider-scoped, `region` is our provider-neutral label.
252 /// Optional for backward-compat; a machine without it never satisfies a
253 /// `required.regions` constraint.
254 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub region: Option<String>,
256 /// Failure-domain label within a region (HA axis), e.g. `"hil"`. For
257 /// single-DC Hetzner this typically mirrors `location`. F16 placement
258 /// matches `required.zones` against this. Optional for backward-compat.
259 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub zone: Option<String>,
261 /// Declared CPU architecture (`"x86_64"` / `"aarch64"`). A machine has
262 /// exactly one — it's a first-class property of the box, not a reach
263 /// detail and not a mesh tag. Drives the yubaba release triple. Optional
264 /// only because there's no provider API to probe it (static nodes declare
265 /// it; a driver-backed provider may leave it unset until known).
266 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub arch: Option<String>,
268 pub bucket: Option<BucketSpec>,
269 /// **Legacy location, superseded by `[registration].hostkey_fingerprint`**
270 /// (R707-T1). Still deserialized so machine TOMLs written before the split
271 /// keep parsing; never *read* directly — go through
272 /// [`MachineConfig::hostkey_fingerprint`], which prefers the registration
273 /// block. [`MachineConfig::normalize`] folds this into `registration`, and
274 /// [`MachineConfig::save`] normalizes before writing, so a load→save cycle
275 /// migrates the file rather than dropping the value.
276 #[serde(
277 rename = "hostkey_fingerprint",
278 default,
279 skip_serializing_if = "Option::is_none"
280 )]
281 pub legacy_hostkey_fingerprint: Option<String>,
282 /// Provider-side SSH-key IDs (Hetzner: from `GET /v1/ssh_keys`)
283 /// authorized for `root` at create time. Defaults to empty for
284 /// backwards-compat with existing machine declarations; an empty
285 /// list yields a Hetzner-emailed random root password (which the
286 /// driver currently discards). Populate this when you want pre-mesh
287 /// SSH access for bootstrap deploys or recovery.
288 #[serde(default, skip_serializing_if = "Vec::is_empty")]
289 pub ssh_keys: Vec<u64>,
290 /// Cloudflare Tunnel ID this machine joins (e.g. `abc123.cfargotunnel.com`).
291 /// `None` → no tunnel (mesh-only node, no public ingress).
292 /// When set, `yah cloud machine provision` reads `cloudflare-tunnel-token`
293 /// from the keys vault and injects the cloudflared install block into
294 /// cloud-init so the new machine connects to CF edge on first boot.
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub cloudflared: Option<String>,
297 /// When `true`, this machine hosts operator-bridge workloads (Tailscale
298 /// operator access to mesh-internal services). `yah cloud machine provision`
299 /// will install tailscaled and run `tailscale up` during cloud-init via the
300 /// `{{OPERATOR_BRIDGE_BLOCK}}` placeholder. Defaults to `false` for
301 /// backward-compat with existing machine declarations.
302 #[serde(default)]
303 pub hosts_operator_bridge: bool,
304 /// BYO `static`-node reach descriptor. Static nodes have no provider API to
305 /// probe, so how the camp reaches them (SSH user@host + the yubaba URL,
306 /// which is loopback until the WireGuard mesh lands) is *declared* here.
307 /// `None` for driver-backed providers (Hetzner/Vultr), whose address is
308 /// resolved from the provider API / mesh at provision time.
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub connect: Option<ConnectSpec>,
311 /// Static node capacity (R572-F3). Declares the node's total hardware
312 /// budget; F5's scheduler subtracts committed workload requests from this
313 /// to check whether a new workload fits. Absent means unconstrained.
314 #[serde(default, skip_serializing_if = "Option::is_none")]
315 pub allocatable: Option<NodeAllocatable>,
316 /// Placement taint keys (R572-F3). **There is no toleration** — a
317 /// `no-<archetype>` taint is an absolute block, not a preference
318 /// (W305/R742-T4; the pre-2026-08-11 "repel-unless-tolerate" wording here
319 /// described an `unless` that was never built).
320 ///
321 /// A key in this list influences placement in exactly one of two ways, and
322 /// [`taint_effect`] is the authority on which:
323 ///
324 /// - **repulsion** — `"no-server"` / `"no-appliance"` / `"no-job"` reject
325 /// workloads of that [`LifecycleArchetype`] outright;
326 /// - **affinity** — a key in [`AFFINITY_TAINT_KEYS`] (today just
327 /// `"public-ip"`) that a workload names in
328 /// `yah.placement.requires-taint`, which then *requires* this node.
329 ///
330 /// Anything else is **inert**: it parses, it round-trips, and no scheduler
331 /// decision can ever read it. `yah cloud validate` rejects such keys
332 /// (`validate::check_inert_taints`) rather than letting them sit looking
333 /// load-bearing — which is how `no-voter` spent months asserting a
334 /// falsehood on three nodes. Facts about a node that are not placement
335 /// inputs belong in [`mesh_tags`](Self::mesh_tags) or a comment.
336 #[serde(default, skip_serializing_if = "Vec::is_empty")]
337 pub taints: Vec<String>,
338 /// Which consensus group this node belongs to — W305/R742-F1. `None` means
339 /// standalone: in no group at all, which is us-west-002 and us-west-015.
340 ///
341 /// Membership is not by itself quorum eligibility; that is
342 /// [`sovereign_role`](Self::sovereign_role), added by R605-F12 because
343 /// us-west-003 is in prod's blast radius *and* must never vote in it.
344 ///
345 /// **Not a placement input.** It is deliberately absent from
346 /// [`RequiredSpec::matches`], and adding it there would be a category
347 /// error: a sovereign group is a *blast radius*, not a filter. Nothing
348 /// about "which quorum does this box vote in" should decide where a
349 /// workload runs — that is what made the fleet express three unrelated
350 /// properties through one taint list and get all three wrong (W305).
351 ///
352 /// What it *is* for is refusal. [`judge_join`] answers "may this node join
353 /// that node's cluster", and the answer is no unless both declare the same
354 /// group. Before this field the only guard was a comment in three machine
355 /// TOMLs saying "never run a raft join against this box from a shell
356 /// pointed at prod" — habit, with no mechanism behind it, which is the
357 /// same class of guard W257 §8 admitted to.
358 ///
359 /// # Why `sovereign_group` and not `raft_group`
360 ///
361 /// Raft is today's mechanism (operator, 2026-08-10). A field named for the
362 /// mechanism goes stale the day the mechanism is swapped, and every
363 /// consumer that reads it inherits the lie. `sovereign` names what the
364 /// group *has* — its own authority, its own upgrade cadence, its own
365 /// destruction — which stays true under any consensus protocol.
366 ///
367 /// Note the word already appears in this tree as prose (W267's title, the
368 /// `IngressProvider::Passway` doc comment's "sovereign edge"). That is an
369 /// adjective meaning "self-hosted, not SaaS"; this is the first time it
370 /// carries structure.
371 #[serde(default, skip_serializing_if = "Option::is_none")]
372 pub sovereign_group: Option<String>,
373 /// Whether this node may hold a seat in its group's quorum — R605-F12.
374 /// Meaningless without [`sovereign_group`](Self::sovereign_group): a
375 /// standalone box has no quorum to be eligible for.
376 ///
377 /// **`None` is "not written", not a third role.** Read it through
378 /// [`sovereign_membership`](Self::sovereign_membership), which resolves the
379 /// absence to [`SovereignRole::Voter`] — what declaring a group has always
380 /// meant, so the six nodes stamped before this field keep their seats
381 /// without an edit. The distinction is kept only so
382 /// [`crate::validate::check_unroled_sovereign_members`] can tell an
383 /// operator who *chose* voter from one who never considered the question;
384 /// no join decision reads the `Option` directly.
385 ///
386 /// # Why this is not a taint
387 ///
388 /// It was, once: `no-voter` sat in [`taints`](Self::taints) on three nodes
389 /// for months, read by nothing, and R742-T4 removed it because the taint
390 /// list is a *placement* vocabulary and this is not a placement input (see
391 /// [`taint_effect`]). Nor is it a second group label. It is a modifier on
392 /// the membership this node already declares, which is why it lives beside
393 /// the group and is judged with it in one predicate,
394 /// [`workload_spec::sovereign::join_permitted`].
395 #[serde(default, skip_serializing_if = "Option::is_none")]
396 pub sovereign_role: Option<SovereignRole>,
397 /// `[registration]` — the observed half (R707-T1). Empty until the box has
398 /// been attached / mesh-joined. See [`MachineRegistration`].
399 #[serde(default, skip_serializing_if = "MachineRegistration::is_empty")]
400 pub registration: MachineRegistration,
401}
402
403/// True iff `provider` has an auto-provision driver (create/destroy via API).
404/// Driver-backed providers require `location` + `server_type`; BYO `static`
405/// nodes (brought up over SSH) do not. The cloud-vs-vps distinction the fleet
406/// cares about lives here — at the provider-capability layer — not as a
407/// separate machine type (W242 BYO Phase-0 decision).
408pub fn provider_has_machine_driver(provider: &str) -> bool {
409 matches!(provider, "hetzner" | "vultr" | "digitalocean")
410}
411
412/// Taint keys a workload may name in `yah.placement.requires-taint` to
413/// *require* a node (W305/R742-T4 affinity vocabulary).
414///
415/// This is a closed list on purpose. `WorkloadSpec::requires_taint` returns
416/// free text, but every producer in the tree is code — `passway_ingress.rs`
417/// and `cloudflared_ingress.rs`, both emitting
418/// [`workload_spec::PUBLIC_IP_TAINT`] — and no on-disk `workload.toml` sets the
419/// annotation at all. So the set of keys a node can usefully carry for
420/// affinity is knowable at compile time, which is what lets
421/// [`taint_effect`] call anything outside it inert instead of guessing.
422///
423/// **Adding an affinity key means adding it here**, in the same change that
424/// teaches a workload to require it. That coupling is the point: it makes the
425/// node side and the workload side impossible to land apart.
426pub const AFFINITY_TAINT_KEYS: &[&str] = &[workload_spec::PUBLIC_IP_TAINT];
427
428/// How a key in [`MachineConfig::taints`] can affect placement.
429///
430/// W305 finding 1: before R742-T4 nothing asked this question, so a key that
431/// no scheduler path could read — `"qa"`, `"no-voter"` — parsed, validated,
432/// and quietly did nothing. Both of the findings that cost real fleet state
433/// were invisible for exactly that reason.
434#[derive(Debug, Clone, Copy, PartialEq, Eq)]
435pub enum TaintEffect {
436 /// `"no-<archetype>"`: rejects workloads of that archetype outright. Read
437 /// by [`RequiredSpec::matches`] via `repel_archetype`.
438 Repels(LifecycleArchetype),
439 /// A key in [`AFFINITY_TAINT_KEYS`]: a workload naming it in
440 /// `yah.placement.requires-taint` is restricted to nodes carrying it.
441 Attracts,
442 /// Neither. No placement decision can read this key.
443 Inert,
444}
445
446/// Classify one node taint key. See [`TaintEffect`].
447///
448/// The repulsion half is derived from [`LifecycleArchetype::ALL`] rather than
449/// a literal list, so a fourth archetype makes `no-<its key>` live without an
450/// edit here.
451pub fn taint_effect(key: &str) -> TaintEffect {
452 if let Some(arch) = LifecycleArchetype::ALL
453 .into_iter()
454 .find(|a| key == format!("no-{}", a.taint_key()))
455 {
456 return TaintEffect::Repels(arch);
457 }
458 if AFFINITY_TAINT_KEYS.contains(&key) {
459 return TaintEffect::Attracts;
460 }
461 TaintEffect::Inert
462}
463
464/// Every key the scheduler *can* act on, sorted — for error messages that
465/// tell the operator what the legal vocabulary actually is instead of only
466/// what was wrong.
467pub fn live_taint_keys() -> Vec<String> {
468 let mut keys: Vec<String> = LifecycleArchetype::ALL
469 .into_iter()
470 .map(|a| format!("no-{}", a.taint_key()))
471 .chain(AFFINITY_TAINT_KEYS.iter().map(|k| (*k).to_string()))
472 .collect();
473 keys.sort();
474 keys
475}
476
477/// What [`judge_join`] decided about one proposed cluster join.
478///
479/// Shaped like yubaba's `PromotionVerdict` / `GeographyVerdict` and for the
480/// same reason: the rule stays unit-testable without a live cluster, and a
481/// refusal carries its reason from the place that knows it.
482#[derive(Debug, Clone, PartialEq, Eq)]
483pub enum JoinVerdict {
484 /// Both nodes declare the same sovereign group and both are voters. The
485 /// join is within one blast radius and grows a quorum both sides are
486 /// eligible for.
487 Permit,
488 /// The join is refused. Carries an operator-readable reason naming both
489 /// declared values and the file to edit — a refusal that only says
490 /// "invalid" gets worked around rather than fixed.
491 Refuse(String),
492}
493
494/// May `joiner` join the cluster `target` belongs to? — W305/R742-F1.
495///
496/// **A join is permitted iff both nodes declare the same non-`None`
497/// [`sovereign_group`](MachineConfig::sovereign_group) and both are
498/// [`SovereignRole::Voter`].** One rule, no special cases, and it makes the
499/// declaration mandatory before any quorum grows.
500///
501/// The case this exists for is two *different* declared groups: joining a dev
502/// Pi into prod is refused rather than trusted, where today the only guard is
503/// a comment saying not to do it. But an undeclared node is refused too, and
504/// that is the deliberate half — `None` means "in no group", not "unknown", so
505/// growing prod with an unstamped box is exactly as much a cross-group join as
506/// the dev case is. Failing open there would leave the operator believing a
507/// guarantee that was never evaluated, which is the reasoning
508/// `QuorumGeography::judge` already applies to untagged voters.
509///
510/// No legitimate flow pays for that strictness: prod and dev are both stamped,
511/// and us-west-002/015 are deliberately in no group at all. Adding a real
512/// member means declaring it first, which is the point.
513///
514/// # The non-voting refusal (R605-F12)
515///
516/// Same group and still refused, when either side declares
517/// [`SovereignRole::NonVoter`]. This is the case a group label alone could not
518/// express. us-west-003 is a residential-uplink build box the operator counts
519/// as part of prod — same secrets, same upgrade cadence, same destruction — and
520/// which must never hold a prod raft seat, because a home-internet partition
521/// should not be able to stall the quorum. Until R605-F12 the only thing
522/// refusing it was its *absent* stamp, so recording the operator's real intent
523/// (`sovereign_group = "prod"`) would have removed the guard. Now the intent
524/// and the guard are the same two lines.
525///
526/// Note what this is not: the refusal here is about *voting*, and it says
527/// nothing about the mesh. One mesh spans the whole fleet regardless of group
528/// or role (operator, 2026-08-19); a non-voter is reachable, schedulable and
529/// rollable like any other node.
530///
531/// This is the **camp-side** rendering of the rule. The predicate itself lives
532/// in [`workload_spec::sovereign::join_permitted`] because yubaba's
533/// `POST /raft/add-learner` gate asks the same question and cannot see this
534/// crate (there is deliberately no yubaba → cloud edge). Only the prose is
535/// duplicated, and it has to be: a refusal here names
536/// `.yah/infra/machines/<name>.toml`, while the node-side one has no machine
537/// name in hand and must also name `yubaba serve --sovereign-group`.
538///
539/// The node-side gate is *narrower* on purpose, and the difference is worth
540/// knowing when reading either: a daemon started without `--sovereign-group`
541/// has declared nothing rather than declared standalone, so yubaba resolves
542/// that unknown before it judges, and its gate is in force only once the
543/// cluster being joined declares a group. See `yubaba::sovereign_group`.
544pub fn judge_join(joiner: &MachineConfig, target: &MachineConfig) -> JoinVerdict {
545 let stamp_hint = |m: &MachineConfig| {
546 format!(
547 "declare `sovereign_group = \"<group>\"` in .yah/infra/machines/{}.toml",
548 m.name
549 )
550 };
551 let role_hint = |m: &MachineConfig| {
552 format!(
553 "set `sovereign_role = \"voter\"` in .yah/infra/machines/{}.toml",
554 m.name
555 )
556 };
557 if workload_spec::sovereign::join_permitted(
558 joiner.sovereign_membership(),
559 target.sovereign_membership(),
560 ) {
561 return JoinVerdict::Permit;
562 }
563 let (j, t) = (
564 joiner.sovereign_group.as_deref(),
565 target.sovereign_group.as_deref(),
566 );
567 // Everything below is a refusal; the only permitted shape returned above.
568 //
569 // R605-F12: when both sides name the SAME group, the role is the only thing
570 // left that can have refused, and it gets its own message. Falling through
571 // to the arms below would print "cross-group join refused: 'us-west-003' is
572 // in "prod" and 'us-west-001' is in "prod"" — a message that reads as a bug
573 // in the check rather than a decision about the fleet.
574 //
575 // Deliberately not hoisted above the group comparison. A non-voting joiner
576 // whose target is standalone is refused for *both* reasons, and naming the
577 // role there would send the operator to fix a field that would not have
578 // made the join legal anyway.
579 if let (Some(a), Some(b)) = (j, t) {
580 if a == b {
581 for (m, side, other) in [
582 (joiner, "the joiner", &target.name),
583 (target, "the target", &joiner.name),
584 ] {
585 if m.sovereign_membership().role.is_voter() {
586 continue;
587 }
588 return JoinVerdict::Refuse(format!(
589 "join refused: {side} '{}' is a NON-VOTING member of sovereign group {a:?}, \
590 the same group as '{other}'. It is inside that blast radius — same secrets, \
591 same upgrade cadence, same destruction — but declares itself ineligible for \
592 the quorum, so this is refused by declaration rather than by omission. If it \
593 should genuinely vote, {}; if it should not, this refusal is the field doing \
594 its job and the join is the thing to reconsider.",
595 m.name,
596 role_hint(m),
597 ));
598 }
599 }
600 }
601 match (j, t) {
602 (Some(a), Some(b)) => JoinVerdict::Refuse(format!(
603 "cross-group join refused: '{}' is in sovereign group {a:?} and '{}' is in {b:?}. \
604 These are separate blast radii — separate quorums, separate upgrade cadences, \
605 separately destroyable — and merging them is not something a join can undo. If \
606 the move is genuinely intended, restamp '{}' to {b:?} first and treat it as \
607 leaving its old group.",
608 joiner.name,
609 target.name,
610 joiner.name,
611 )),
612 (None, Some(b)) => JoinVerdict::Refuse(format!(
613 "join refused: '{}' declares no sovereign_group, so it is standalone — in no \
614 group — while '{}' is in {b:?}. That is a cross-group join, not an unchecked \
615 one. To make '{}' a member of {b:?}, {}.",
616 joiner.name,
617 target.name,
618 joiner.name,
619 stamp_hint(joiner),
620 )),
621 (Some(a), None) => JoinVerdict::Refuse(format!(
622 "join refused: '{}' is in sovereign group {a:?} but '{}' declares none, so the \
623 target is standalone and has no group to join. Either {}, or found the group on \
624 '{}' rather than growing it.",
625 joiner.name,
626 target.name,
627 stamp_hint(target),
628 joiner.name,
629 )),
630 (None, None) => JoinVerdict::Refuse(format!(
631 "join refused: neither '{}' nor '{}' declares a sovereign_group, so this join \
632 would form a group nobody declared and nothing could later reason about. Name \
633 the group on both boxes first: {}, and the same for '{}'.",
634 joiner.name,
635 target.name,
636 stamp_hint(joiner),
637 target.name,
638 )),
639 }
640}
641
642impl MachineConfig {
643 /// This node's declared place in a sovereign group, as the shared join rule
644 /// wants it — R605-F12.
645 ///
646 /// The one place `sovereign_role`'s `None` is resolved. Absence means
647 /// [`SovereignRole::Voter`], which is what declaring a group meant before
648 /// the role existed; resolving it here rather than at each call site is what
649 /// keeps the camp-side and node-side gates from disagreeing about a node
650 /// that never wrote the field.
651 pub fn sovereign_membership(&self) -> Membership<'_> {
652 Membership {
653 group: self.sovereign_group.as_deref(),
654 role: self.sovereign_role.unwrap_or_default(),
655 }
656 }
657
658 /// Provider DC code, or `""` when omitted (static nodes). Most readers want
659 /// a `&str`; the driver-backed provision/status paths still go through
660 /// [`validate`](Self::validate) which guarantees presence for those.
661 pub fn location(&self) -> &str {
662 self.location.as_deref().unwrap_or("")
663 }
664
665 /// Provider SKU, or `""` when omitted (static nodes).
666 pub fn server_type(&self) -> &str {
667 self.server_type.as_deref().unwrap_or("")
668 }
669
670 /// Enforce the provisioning-only-field contract: a machine whose provider
671 /// has an auto-provision driver MUST declare `location` + `server_type`
672 /// (the driver can't create a server without them). Static nodes may omit
673 /// both. Call this before any provision/diff that assumes a driver.
674 pub fn validate(&self) -> Result<()> {
675 if provider_has_machine_driver(&self.provider) {
676 if self.location.is_none() {
677 anyhow::bail!(
678 "machine '{}' (provider '{}') has an auto-provision driver but no `location`",
679 self.name,
680 self.provider
681 );
682 }
683 if self.server_type.is_none() {
684 anyhow::bail!(
685 "machine '{}' (provider '{}') has an auto-provision driver but no `server_type`",
686 self.name,
687 self.provider
688 );
689 }
690 }
691 Ok(())
692 }
693
694 /// Declared taints that no placement decision can read (W305/R742-T4).
695 ///
696 /// Deliberately **not** folded into [`validate`](Self::validate): that
697 /// guard runs on the provision/diff hot path and answers a different
698 /// question (can the driver create this server). An inert taint is a lint
699 /// — it never breaks an operation in flight, it just means the file is
700 /// asserting something the scheduler will not honour. `yah cloud validate`
701 /// is where the operator asks for that judgement; see
702 /// [`crate::validate::check_inert_taints`].
703 pub fn inert_taints(&self) -> Vec<&str> {
704 self.taints
705 .iter()
706 .filter(|t| taint_effect(t) == TaintEffect::Inert)
707 .map(String::as_str)
708 .collect()
709 }
710
711 /// Yubaba's TOFU'd hostkey fingerprint, from `[registration]` and falling
712 /// back to the pre-R707-T1 top-level field. **The only read path** — a
713 /// caller that reaches for `legacy_hostkey_fingerprint` directly sees
714 /// `None` on every migrated machine.
715 pub fn hostkey_fingerprint(&self) -> Option<&str> {
716 self.registration
717 .hostkey_fingerprint
718 .as_deref()
719 .or(self.legacy_hostkey_fingerprint.as_deref())
720 }
721
722 /// Record (or clear) the observed hostkey fingerprint. Writes
723 /// `[registration]` and drops any pre-R707-T1 top-level value, so the two
724 /// locations can never disagree after a writeback.
725 pub fn set_hostkey_fingerprint(&mut self, fingerprint: Option<String>) {
726 self.registration.hostkey_fingerprint = fingerprint;
727 self.legacy_hostkey_fingerprint = None;
728 }
729
730 /// Mesh (tailnet) IPv4 for this node, or `None` pre-mesh.
731 ///
732 /// Prefers `[registration].mesh_ipv4`; falls back to the host of a legacy
733 /// `[connect].yubaba` URL when that host is in the `100.64.0.0/10` CGNAT
734 /// range the mesh uses. A loopback placeholder (`http://127.0.0.1:7443`,
735 /// meaning "pre-mesh, reachable only through an SSH tunnel") is *not* a
736 /// mesh address and yields `None`.
737 pub fn mesh_ipv4(&self) -> Option<&str> {
738 if let Some(ip) = self.registration.mesh_ipv4.as_deref() {
739 return Some(ip);
740 }
741 let url = self.connect.as_ref()?.yubaba.as_deref()?;
742 mesh_ipv4_from_url(url)
743 }
744
745 /// Base URL for this node's yubaba, or `None` when no reach resolves.
746 ///
747 /// Thin wrapper over [`reach`](Self::reach) for the many call sites that
748 /// only branch on presence. Prefer `reach` anywhere the operator sees the
749 /// outcome — a `None` here throws away a refusal that names exactly which
750 /// address is missing.
751 pub fn yubaba_url(&self) -> Option<String> {
752 self.reach().ok()
753 }
754
755 /// The **one** address automation dials for this node — mesh-only.
756 ///
757 /// `Err` is a *named refusal*, not an absence: a node with no mesh address
758 /// is unresolvable to every automated path, and R605-T10's whole complaint
759 /// is that this used to surface as a connect timeout against an address the
760 /// caller has no route to.
761 ///
762 /// Resolution order:
763 ///
764 /// 1. A declared `[connect].yubaba` on a **private** host (10/8,
765 /// 172.16/12, 192.168/16) is **not dialed** — see below.
766 /// 2. Any other declared `[connect].yubaba` wins verbatim. That includes
767 /// the pre-mesh loopback placeholder (`http://127.0.0.1:7443`, "I have
768 /// no mesh address; reach me through the SSH tunnel to `ssh`"), which is
769 /// a genuine declaration and stays honoured.
770 /// 3. Otherwise `[registration].mesh_ipv4` composed with
771 /// `[connect].yubaba_port`.
772 ///
773 /// **Why a LAN literal loses (R605-T10, operator 2026-08-19).** The LAN
774 /// address is an emergency break-glass route, never an official one, and
775 /// automation must ALWAYS assume the caller is not on that LAN — this camp
776 /// sits on 192.168.22.0/22 with no route to the fleet's 192.168.10.0/24 at
777 /// all. Writing one into the field every resolver dials does not sit beside
778 /// the mesh route, it *overrides* it: R707-T6 made a declared literal beat
779 /// `mesh_ipv4` outright, so us-west-011 (mesh-joined, healthy) was elected
780 /// for every aarch64 build and then dialed at an address that answers only
781 /// from inside bldg-2506.
782 ///
783 /// **What R707-T6 wanted is preserved elsewhere.** Its forcing case was
784 /// identity, not reach: the dev raft group advertises LAN addrs
785 /// (`192.168.10.11:7443`, verified live off `/raft/status` 2026-08-27), and
786 /// `rollout::yubaba::membership_to_nodes` has to map those back to declared
787 /// machines. That match now runs against [`lan_endpoint`](Self::lan_endpoint),
788 /// which is composed from the break-glass `[connect].address` metadata and
789 /// is never dialed — so the two concerns the old precedence rule fused are
790 /// split, and the literal can stop squatting a dialed field.
791 ///
792 /// The LAN address itself STAYS in the machine TOML. It is useful metadata
793 /// and the manual `ssh` path is entitled to it; it is only disconnected
794 /// from every automated process.
795 pub fn reach(&self) -> Result<String, String> {
796 let Some(connect) = self.connect.as_ref() else {
797 return Err(format!(
798 "machine {:?} declares no [connect] block, so nothing knows how to reach it \
799 \u{2192} declare one, or leave it unprovisioned and out of placement",
800 self.name
801 ));
802 };
803 let mesh = || {
804 self.registration
805 .mesh_ipv4
806 .as_deref()
807 .map(|ip| format!("http://{ip}:{}", connect.yubaba_port()))
808 };
809 if let Some(literal) = &connect.yubaba {
810 let Some(lan) = private_ipv4_from_url(literal) else {
811 return Ok(literal.clone());
812 };
813 return mesh().ok_or_else(|| {
814 format!(
815 "machine {:?} is unresolvable to automation: its only declared yubaba reach \
816 is the private literal {:?} and it has no [registration].mesh_ipv4\n\
817 \u{2192} a LAN address is an emergency break-glass route, never an official \
818 one (R605-T10) — every automated path assumes the caller is NOT on {}/24\n\
819 \u{2192} mesh-join the box and record `mesh_ipv4` under [registration], then \
820 delete `[connect].yubaba` so the port composes with it",
821 self.name,
822 literal,
823 lan.rsplit_once('.').map(|(net, _)| net).unwrap_or(lan),
824 )
825 });
826 }
827 mesh().ok_or_else(|| {
828 format!(
829 "machine {:?} has no [registration].mesh_ipv4 and declares no \
830 [connect].yubaba, so no automated path can reach it\n\
831 \u{2192} mesh-join the box and record its tailnet address, or taint it out of \
832 placement — do not point `[connect].yubaba` at a LAN address (R605-T10)",
833 self.name
834 )
835 })
836 }
837
838 /// The LAN `host:port` this node's yubaba answers on, composed from the
839 /// break-glass `[connect].address` metadata plus the declared port.
840 ///
841 /// **Identity only — never dial this.** It exists so a raft membership
842 /// entry that names a node by its LAN address can be mapped back to the
843 /// declared machine (`rollout::yubaba::membership_to_nodes`) without that
844 /// address having to live in a field a resolver reads. `None` when the
845 /// machine is unprovisioned.
846 pub fn lan_endpoint(&self) -> Option<String> {
847 let connect = self.connect.as_ref()?;
848 Some(format!("{}:{}", connect.address, connect.yubaba_port()))
849 }
850
851 /// Fold the pre-R707-T1 top-level `hostkey_fingerprint` into
852 /// `[registration]`, and lift a mesh IP out of a legacy `[connect].yubaba`
853 /// URL. Idempotent; a machine already on the split shape is untouched.
854 ///
855 /// [`save`](Self::save) calls this, so writing a machine TOML migrates it
856 /// rather than round-tripping the old shape back out.
857 pub fn normalize(&mut self) {
858 if let Some(fp) = self.legacy_hostkey_fingerprint.take() {
859 self.registration.hostkey_fingerprint.get_or_insert(fp);
860 }
861 if self.registration.mesh_ipv4.is_none() {
862 if let Some(ip) = self
863 .connect
864 .as_ref()
865 .and_then(|c| c.yubaba.as_deref())
866 .and_then(mesh_ipv4_from_url)
867 .map(str::to_string)
868 {
869 self.registration.mesh_ipv4 = Some(ip);
870 // The URL was pure derivation from mesh IP + port; keep only
871 // the declared half so the two can't drift apart.
872 if let Some(c) = self.connect.as_mut() {
873 c.yubaba = None;
874 }
875 }
876 }
877 }
878
879 /// Persist to `<cloud_dir>/machines/<name>.toml`, creating the dir if needed.
880 ///
881 /// ⚠ Serializes the struct, so **operator comments in the target file are
882 /// lost**. Pre-existing behaviour, not introduced here, but it is why
883 /// registration writeback (`yah cloud machine attach`) goes through
884 /// [`crate::state::MachineState`] and the comment-preserving path in the
885 /// CLI rather than calling this on a hand-authored inventory file.
886 pub fn save(&self, cloud_dir: &Path) -> Result<()> {
887 let dir = cloud_dir.join("machines");
888 std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
889 let path = dir.join(format!("{}.toml", self.name));
890 let mut normalized = self.clone();
891 normalized.normalize();
892 let s = toml::to_string_pretty(&normalized)
893 .with_context(|| format!("serializing machine {}", self.name))?;
894 std::fs::write(&path, s).with_context(|| format!("writing {}", path.display()))
895 }
896}
897
898/// Host of an `http://host:port` URL iff it is a mesh (headscale) IPv4 in the
899/// `100.64.0.0/10` CGNAT range. String-level rather than URL-parsed: the
900/// inventory format is stable and this crate carries no URL dependency (same
901/// reasoning as `fleet_metrics::extract_host` and
902/// `hub::coordinator::is_loopback_url`).
903fn mesh_ipv4_from_url(url: &str) -> Option<&str> {
904 let host = ipv4_host_of(url)?;
905 let ip: std::net::Ipv4Addr = host.parse().ok()?;
906 let [a, b, ..] = ip.octets();
907 // 100.64.0.0/10 ⇒ first octet 100, second octet 64..=127.
908 (a == 100 && (64..=127).contains(&b)).then_some(host)
909}
910
911/// Host of an `http://host:port` URL iff it is an **RFC1918 private** IPv4 —
912/// `10/8`, `172.16/12`, `192.168/16`. `None` for anything else, loopback and
913/// the `100.64/10` mesh range included: neither is a LAN literal.
914///
915/// The judgement R605-T10 turns on. A private literal is only ever reachable
916/// from inside one building, so it is metadata about where the box physically
917/// sits and never an address automation may dial — see
918/// [`MachineConfig::reach`] and [`crate::validate::check_lan_dial_targets`].
919pub fn private_ipv4_from_url(url: &str) -> Option<&str> {
920 let host = ipv4_host_of(url)?;
921 is_private_ipv4(host).then_some(host)
922}
923
924/// Whether a bare host string is an RFC1918 private IPv4 literal.
925pub fn is_private_ipv4(host: &str) -> bool {
926 let Ok(ip) = host.parse::<std::net::Ipv4Addr>() else {
927 return false;
928 };
929 ip.is_private()
930}
931
932/// Bare host of a `[scheme://]host[:port][/path]` string.
933fn ipv4_host_of(url: &str) -> Option<&str> {
934 let after_scheme = url.split("://").nth(1).unwrap_or(url);
935 after_scheme.split(['/', ':']).next()
936}
937
938/// Declared **reach** for a BYO `static` node (no provider API). Lives under
939/// `[connect]` in the machine TOML.
940///
941/// Reach only — how the camp gets to the box. *Permission* is a separate axis
942/// that belongs to cheers' scopes (W295 §"Deliberately deferred"); the two
943/// collapse in practice today (mesh membership grants everything) and the data
944/// model must not fuse them, so do not add an authorization field here.
945///
946/// `address` and `ssh` stay whole, literal, operator-authored strings even
947/// though their values often *look* derived. They are not: us-west-001 dials
948/// SSH over its public IP while us-west-002 was deliberately repointed at its
949/// tailnet IP (R608-F10) precisely because the LAN address is unreachable
950/// off-LAN. Decomposing them into user + host and recomposing would silently
951/// undo per-machine decisions like that one. `yubaba` is the field that *was*
952/// derived — mesh IP plus a fixed port, rewritten by mesh-join — so that is
953/// where R707-T1 cut.
954#[derive(Debug, Clone, Serialize, Deserialize)]
955#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
956pub struct ConnectSpec {
957 /// Reachable IPv4/host for the box, e.g. `"45.32.194.254"`. Declared: which
958 /// of a machine's several addresses the camp should use is an operator
959 /// choice (public IP vs. LAN IP vs. tailnet IP).
960 pub address: String,
961 /// SSH target the camp dials for bootstrap + (pre-mesh) tunneled deploys,
962 /// e.g. `"root@45.32.194.254"` or `"struc@100.64.0.4"`. Uses the operator's
963 /// `~/.ssh/yah` key. Declared, whole — see the type doc.
964 pub ssh: String,
965 /// Port yubaba listens on. Declared reach; defaults to 7443 when omitted,
966 /// which is every machine in the fleet today. Composed with the *observed*
967 /// [`MachineRegistration::mesh_ipv4`] by [`MachineConfig::yubaba_url`].
968 #[serde(default, skip_serializing_if = "Option::is_none")]
969 pub yubaba_port: Option<u16>,
970 /// Explicit yubaba base URL, overriding the composed form.
971 ///
972 /// Two live uses, both genuine declarations: a pre-mesh node saying
973 /// `"http://127.0.0.1:7443"` — "I have no mesh address; reach me through
974 /// the SSH tunnel to `ssh`" — and any node whose yubaba is not at
975 /// `mesh_ipv4:port`. A URL here whose host *is* a mesh IP is the
976 /// pre-R707-T1 shape; [`MachineConfig::normalize`] lifts it into
977 /// `[registration].mesh_ipv4` and clears this field so the two cannot
978 /// drift apart.
979 #[serde(default, skip_serializing_if = "Option::is_none")]
980 pub yubaba: Option<String>,
981}
982
983/// Default yubaba listen port, used when `[connect].yubaba_port` is omitted.
984pub const DEFAULT_YUBABA_PORT: u16 = 7443;
985
986impl ConnectSpec {
987 /// Declared yubaba port, defaulting to [`DEFAULT_YUBABA_PORT`].
988 pub fn yubaba_port(&self) -> u16 {
989 self.yubaba_port.unwrap_or(DEFAULT_YUBABA_PORT)
990 }
991}
992
993#[derive(Debug, Clone, Serialize, Deserialize)]
994#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
995pub struct BucketSpec {
996 pub name: String,
997 pub public_read: bool,
998}
999
1000/// Per-camp mirror declaration from `.yah/cloud/mirrors/<id>/mirror.toml`
1001/// (folder form) or the legacy `.yah/cloud/mirrors/<id>.toml` (flat form).
1002///
1003/// The folder form is preferred for new mirrors so that per-mirror secrets
1004/// and override files can sit next to `mirror.toml` without polluting the
1005/// top-level `mirrors/` directory.
1006#[derive(Debug, Clone, Serialize, Deserialize)]
1007pub struct LegacyMirrorConfig {
1008 /// Logical camp name this mirror hosts, e.g. `"yah"` or `"noisetable"`.
1009 ///
1010 /// Serialised as `camp`; accepts the legacy `rig` spelling for files that
1011 /// predate the R137 rig→camp rename (one-time migration: `sed -i ''
1012 /// 's/^rig = /camp = /' ~/.yah/cloud/mirrors/*.toml`).
1013 #[serde(rename = "camp", alias = "rig")]
1014 pub camp: String,
1015 pub regions: Vec<String>,
1016 /// Workload names deployed as part of this mirror (references `workloads/<name>.toml`).
1017 /// Renamed from `services` in R092-F1; use `yah cloud config migrate-services-to-workloads`
1018 /// on repos that still have the old `services/` layout.
1019 #[serde(alias = "services")]
1020 pub workloads: Vec<String>,
1021 /// Base domain for Cloudflare-fronted services on this mirror's machines.
1022 /// Combined with the machine's `location` to build virtual-host names:
1023 /// e.g. `cloud_domain = "cloud.noisetable.example"` on machine in location
1024 /// `pdx` → Caddyfile site address `pdx.cloud.noisetable.example`.
1025 /// Optional: if unset the Caddyfile falls back to `:port` listeners.
1026 #[serde(default, skip_serializing_if = "Option::is_none")]
1027 pub cloud_domain: Option<String>,
1028}
1029
1030/// Error from loading or validating a single workload TOML file.
1031#[derive(Debug, Error)]
1032pub enum WorkloadConfigError {
1033 #[error("reading {path}: {source}")]
1034 Io {
1035 path: String,
1036 source: std::io::Error,
1037 },
1038 #[error("parsing {path}: {source}")]
1039 Toml {
1040 path: String,
1041 source: toml::de::Error,
1042 },
1043 #[error("invalid WorkloadSpec in {path}: {source}")]
1044 Shape {
1045 path: String,
1046 source: validate::ShapeError,
1047 },
1048}
1049
1050/// A workload declaration loaded from `.yah/cloud/workloads/<name>.toml`.
1051///
1052/// Each file is the human-authored TOML serialization of a [`WorkloadSpec`].
1053/// On load, the spec is validated against the shape layer; failures surface as
1054/// a [`CloudConfigError::Workload`] with the file path and field path.
1055#[derive(Debug, Clone, Serialize, Deserialize)]
1056pub struct WorkloadConfig {
1057 /// The validated spec.
1058 #[serde(flatten)]
1059 pub spec: WorkloadSpec,
1060}
1061
1062impl WorkloadConfig {
1063 /// Persist to `<cloud_dir>/workloads/<name>.toml`, creating the dir if needed.
1064 pub fn save(&self, cloud_dir: &Path) -> Result<()> {
1065 let dir = cloud_dir.join("workloads");
1066 std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
1067 let path = dir.join(format!("{}.toml", self.spec.name));
1068 let s = toml::to_string_pretty(self)
1069 .with_context(|| format!("serializing workload {}", self.spec.name))?;
1070 std::fs::write(&path, s).with_context(|| format!("writing {}", path.display()))
1071 }
1072}
1073
1074/// Error surfaced by [`CloudConfig::load`] when a workload TOML fails validation.
1075#[derive(Debug, Error)]
1076pub enum CloudConfigError {
1077 #[error(transparent)]
1078 Anyhow(#[from] anyhow::Error),
1079 #[error("workload validation failed: {0}")]
1080 Workload(WorkloadConfigError),
1081}
1082
1083/// Mirror-to-machine assignment table from `.yah/cloud/topology.toml`.
1084///
1085/// Declares which logical mirror names are assigned to which machines.
1086/// This is the source-canonical placement until yubaba raft observes it
1087/// (per the migration tracker in the arch doc).
1088#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1089pub struct TopologyConfig {
1090 /// Mirror→machine assignments.
1091 #[serde(default)]
1092 pub assignments: Vec<MirrorAssignment>,
1093 /// Declared buckets, logged by `yah cloud bucket create`.
1094 /// Source-canonical until yubaba raft observes actual placement.
1095 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1096 pub buckets: Vec<BucketLogEntry>,
1097}
1098
1099impl TopologyConfig {
1100 /// Load from a `topology.toml` file, returning `Default` when absent.
1101 pub fn load(path: &Path) -> Result<Self> {
1102 if !path.exists() {
1103 return Ok(Self::default());
1104 }
1105 let s =
1106 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
1107 toml::from_str(&s).with_context(|| format!("parsing {}", path.display()))
1108 }
1109
1110 /// Persist to `topology.toml`, creating parent dirs if needed.
1111 pub fn save(&self, path: &Path) -> Result<()> {
1112 if let Some(parent) = path.parent() {
1113 std::fs::create_dir_all(parent)
1114 .with_context(|| format!("creating {}", parent.display()))?;
1115 }
1116 let s = toml::to_string_pretty(self).context("serializing topology")?;
1117 std::fs::write(path, s).with_context(|| format!("writing {}", path.display()))
1118 }
1119
1120 /// Find a declared bucket by name.
1121 pub fn bucket_by_name(&self, name: &str) -> Option<&BucketLogEntry> {
1122 self.buckets.iter().find(|b| b.name == name)
1123 }
1124
1125 /// Find a mutable declared bucket by name.
1126 pub fn bucket_by_name_mut(&mut self, name: &str) -> Option<&mut BucketLogEntry> {
1127 self.buckets.iter_mut().find(|b| b.name == name)
1128 }
1129
1130 /// Returns true if the bucket is declared as cross-machine (no owning machine).
1131 pub fn is_cross_machine_bucket(&self, name: &str) -> bool {
1132 self.buckets
1133 .iter()
1134 .any(|b| b.name == name && b.machine.is_none())
1135 }
1136}
1137
1138/// One mirror→machine placement entry in `topology.toml`.
1139#[derive(Debug, Clone, Serialize, Deserialize)]
1140pub struct MirrorAssignment {
1141 /// Logical mirror name, e.g. `"noisetable-pdx"`.
1142 pub mirror: String,
1143 /// Machine that hosts this mirror, e.g. `"noisetable-pdx-1"`.
1144 pub machine: String,
1145}
1146
1147/// A bucket declaration logged in `topology.toml` by `yah cloud bucket create`.
1148#[derive(Debug, Clone, Serialize, Deserialize)]
1149pub struct BucketLogEntry {
1150 pub name: String,
1151 /// Machine that owns this bucket. `None` marks it as cross-machine
1152 /// (no single-machine ownership; requires an explicit declaration in
1153 /// `topology.toml` before `yah cloud bucket create` will proceed without
1154 /// `--machine`).
1155 #[serde(default, skip_serializing_if = "Option::is_none")]
1156 pub machine: Option<String>,
1157 /// Logical location of the bucket, e.g. `"pdx"`.
1158 pub location: String,
1159 /// Current declared policy: `"private"` | `"public-read"` | `"signed-only"`.
1160 #[serde(default = "default_bucket_policy")]
1161 pub policy: String,
1162}
1163
1164fn default_bucket_policy() -> String {
1165 "private".to_string()
1166}
1167
1168/// Per-service config from `.yah/cloud/services/<name>.toml`.
1169///
1170/// **Deprecated.** The `services/` layout was replaced by `workloads/` in R092-F1.
1171/// Kept to allow in-place reads for repos that haven't migrated yet; use
1172/// `yah cloud config migrate-services-to-workloads` to upgrade.
1173#[derive(Debug, Clone, Serialize, Deserialize)]
1174pub struct LegacyServiceConfig {
1175 pub name: String,
1176 pub image: String,
1177 pub version: String,
1178 #[serde(default)]
1179 pub env: HashMap<String, String>,
1180 #[serde(default)]
1181 pub ports: Vec<PortMapping>,
1182 #[serde(default)]
1183 pub mesh_only: bool,
1184 /// Network interface this service binds to exclusively (e.g. `"tailscale0"`).
1185 ///
1186 /// When set the compose renderer emits `network_mode: "host"` and the
1187 /// service is NOT joined to the shared compose bridge network. The service
1188 /// process must bind its listen socket to the named interface's IP — for
1189 /// Postgres this means setting `POSTGRES_LISTEN_ADDRESSES` to the node's
1190 /// `tailscale ip --4` output at first boot. See [`crate::mesh_service`] for
1191 /// the standard pg_hba.conf snippet and ufw rules to pair with this field.
1192 #[serde(default, skip_serializing_if = "Option::is_none")]
1193 pub bind_interface: Option<String>,
1194
1195 /// Tenant this service belongs to (W206 isolation axis). Absent in the
1196 /// service TOML → [`TenantId::singleton`], keeping single-tenant machines
1197 /// on one shared compose network. When a machine hosts services from two
1198 /// or more distinct tenants, the compose renderer (R558-T2) splits them
1199 /// into per-tenant `<tenant>-<tier>` networks so cross-tenant stacks on the
1200 /// same host are not bridged together.
1201 #[serde(default = "TenantId::singleton")]
1202 pub tenant: TenantId,
1203}
1204
1205#[derive(Debug, Clone, Serialize, Deserialize)]
1206pub struct PortMapping {
1207 pub host: u16,
1208 pub container: u16,
1209}
1210
1211/// A loaded service plus its per-environment mirrors.
1212///
1213/// Wraps the `service.toml` body and the directory of `mirrors/<env>.toml`
1214/// files that project the service onto concrete infra.
1215#[derive(Debug, Clone, Serialize, Deserialize)]
1216pub struct ServiceWithMirrors {
1217 pub service: ServiceConfig,
1218 /// Mirrors keyed by environment name (file stem of `mirrors/<env>.toml`).
1219 pub mirrors: BTreeMap<String, MirrorConfig>,
1220 /// Transform recipe names keyed by component id. Populated from each
1221 /// static-asset component's `workload.toml` at load time — not stored
1222 /// in service.toml. Only present for components that declare
1223 /// `[asset.derive.transform] recipe = "..."`.
1224 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1225 pub component_transform_recipes: BTreeMap<String, String>,
1226}
1227
1228/// All cloud config loaded from a workspace root (the parent of `.yah/`).
1229///
1230/// Reads two trees:
1231/// - `.yah/infra/` — `machines/`, `providers/`
1232/// - `.yah/services/<svc>/` — `service.toml` + `mirrors/<env>.toml`
1233///
1234/// Pre-R215 fields (`legacy_mirrors`, `legacy_services`, `workloads`,
1235/// `topology`) are still populated from `.yah/cloud/` when present so
1236/// pre-R215 callers (compose.rs, bucket commands) keep compiling — they
1237/// just see empty collections in a post-B1 workspace where the legacy
1238/// data was deleted. These fields are scheduled for removal in B3-T3.
1239#[derive(Debug)]
1240pub struct CloudConfig {
1241 /// Workspace root that was loaded — useful for path-resolving
1242 /// component references on a [`ServiceComponent`].
1243 pub workspace_root: std::path::PathBuf,
1244
1245 // ─── R215+ tree ────────────────────────────────────────────────────────
1246 /// `.yah/infra/machines/<name>.toml`
1247 pub machines: Vec<MachineConfig>,
1248 /// `.yah/infra/providers/<id>.toml`
1249 pub providers: Vec<ProviderConfig>,
1250 /// Provenance for every entry in `machines` that came from a linked
1251 /// `.yah/infra/sources.toml` source rather than this camp's own
1252 /// `.yah/infra/machines/` (R615-F2 / W274). Keyed by
1253 /// [`MachineConfig::name`]; a name absent here is camp-local. Empty from
1254 /// [`CloudConfig::load_from_config_dir`] — see its doc for why sources
1255 /// don't apply to multi-root sibling trees.
1256 pub machine_origins: BTreeMap<String, InfraOrigin>,
1257 /// Same as [`machine_origins`](Self::machine_origins), keyed by
1258 /// [`ProviderConfig::id`].
1259 pub provider_origins: BTreeMap<String, InfraOrigin>,
1260 /// `.yah/services/<svc>/` — service.toml plus mirrors/<env>.toml.
1261 pub services: BTreeMap<String, ServiceWithMirrors>,
1262 /// `.yah/domains/<name>.toml` — public-facing routing manifests
1263 /// (R347). Single file per domain; no nested per-env tree because
1264 /// domains themselves aren't projected onto infra — they describe
1265 /// how a Worker bundle ingresses requests onto services.
1266 pub domains: BTreeMap<String, DomainConfig>,
1267
1268 // ─── Pre-R215 legacy (slated for removal in B3-T3) ────────────────────
1269 /// Legacy mirrors from `.yah/cloud/mirrors/`.
1270 pub legacy_mirrors: Vec<LegacyMirrorConfig>,
1271 /// Workloads from `.yah/cloud/workloads/*.toml` (R092-F1 schema).
1272 pub workloads: Vec<WorkloadConfig>,
1273 /// Topology from `.yah/cloud/topology.toml` (mirror→machine assignments).
1274 pub topology: TopologyConfig,
1275 /// Legacy services from `.yah/cloud/services/*.toml` (pre-R092 layout).
1276 pub legacy_services: Vec<LegacyServiceConfig>,
1277}
1278
1279impl CloudConfig {
1280 /// Load all cloud config rooted at `workspace_root` (the parent of `.yah/`).
1281 ///
1282 /// Reads the R215+ tree (`.yah/infra/`, `.yah/services/<svc>/`) eagerly
1283 /// and the pre-R215 `.yah/cloud/` tree opportunistically. Returns `Err`
1284 /// immediately if any TOML fails to parse or a workload TOML fails
1285 /// shape validation; the error includes the file path and field path.
1286 ///
1287 /// Cross-ref validation runs after both trees finish loading: every
1288 /// `mirror.providers.X.use = "<id>"` must resolve to a real provider
1289 /// declared under `.yah/infra/providers/`.
1290 pub fn load(workspace_root: &Path) -> Result<Self> {
1291 let mut providers = load_providers(&crate::paths::providers_dir(workspace_root))?;
1292 let services = load_services(&crate::paths::services_dir(workspace_root), workspace_root)?;
1293 let domains = load_domains(&crate::paths::domains_dir(workspace_root))?;
1294
1295 Self::cross_ref_validate(&providers, &services, &domains)?;
1296
1297 // Legacy `.yah/cloud/` reads — empty in post-B1 workspaces. Wrapped in
1298 // a helper so a missing tree is silent (no error, no warning).
1299 let cloud_dir = crate::paths::legacy_cloud_dir(workspace_root);
1300 let (legacy_machines, legacy_mirrors, legacy_workloads, topology, legacy_services) =
1301 if cloud_dir.exists() {
1302 (
1303 load_dir::<MachineConfig>(cloud_dir.join("machines"))?,
1304 load_mirrors(cloud_dir.join("mirrors"))?,
1305 load_workloads(cloud_dir.join("workloads"))?,
1306 load_topology(cloud_dir.join("topology.toml"))?,
1307 load_dir::<LegacyServiceConfig>(cloud_dir.join("services"))?,
1308 )
1309 } else {
1310 Default::default()
1311 };
1312
1313 // Workloads come from `.yah/infra/workloads/` (R215+). R568-T7: before
1314 // that path was read here, this field was populated *only* from the
1315 // legacy tree above — which R222-B1 emptied — so `cfg.workload(name)`
1316 // resolved nothing in every post-R215 camp and `yah cloud workload
1317 // deploy` could not find any declaration at all. The bug survived
1318 // because the only workloads ever deployed were forge/QED runs, which
1319 // build their spec in memory and never come through here. Same
1320 // dedupe-by-name shape as machines below: R215+ wins.
1321 let mut workloads = load_workloads(crate::paths::workloads_dir(workspace_root))?;
1322 let workload_names: std::collections::HashSet<String> =
1323 workloads.iter().map(|w| w.spec.name.clone()).collect();
1324 for w in legacy_workloads {
1325 if !workload_names.contains(&w.spec.name) {
1326 workloads.push(w);
1327 }
1328 }
1329
1330 // Machines come from `.yah/infra/machines/` (R215+); the pre-R215
1331 // tree shouldn't have any since B1 moved them, but if it does we
1332 // dedupe by name (R215 wins).
1333 let mut machines = load_dir::<MachineConfig>(crate::paths::machines_dir(workspace_root))?;
1334 let names: std::collections::HashSet<String> =
1335 machines.iter().map(|m| m.name.clone()).collect();
1336 for m in legacy_machines {
1337 if !names.contains(&m.name) {
1338 machines.push(m);
1339 }
1340 }
1341
1342 // R615-F2: overlay every linked `.yah/infra/sources.toml` source's
1343 // machines/providers UNDER what's already loaded above, so camp-local
1344 // (including the legacy-tree entries just merged in) always wins on a
1345 // name collision. `SourcesConfig::load` itself never touches the
1346 // network — git sources are read from `yah infra sync`'s cache
1347 // (R615-T3), so this call keeps `load()`'s whole offline contract.
1348 let sources = SourcesConfig::load(&crate::paths::infra_dir(workspace_root))?;
1349 let mut machine_origins = BTreeMap::new();
1350 let mut provider_origins = BTreeMap::new();
1351 overlay_infra_sources(
1352 workspace_root,
1353 &sources,
1354 &mut machines,
1355 &mut providers,
1356 &mut machine_origins,
1357 &mut provider_origins,
1358 );
1359
1360 Ok(Self {
1361 workspace_root: workspace_root.to_path_buf(),
1362 machines,
1363 providers,
1364 machine_origins,
1365 provider_origins,
1366 services,
1367 domains,
1368 legacy_mirrors,
1369 workloads,
1370 topology,
1371 legacy_services,
1372 })
1373 }
1374
1375 /// Load the R215+ tree (`infra/`, `services/`, `domains/`) rooted at an
1376 /// arbitrary config directory instead of the hardcoded `.yah/`. This is the
1377 /// building block for multi-root deployments (W206 config layout (b), sibling
1378 /// `.noisetable/` trees) — see [`crate::multi_root`]. Part of R558-F4.
1379 ///
1380 /// `config_dir` is the `.X/` directory itself (e.g. `<parent>/.noisetable`);
1381 /// `workspace_root` remains the camp dir (the config dir's parent) so a
1382 /// component's `path` reference resolves against the same tree the classic
1383 /// [`CloudConfig::load`] uses. The legacy `.yah/cloud/` reads are skipped —
1384 /// multi-root deployments are post-R215 by construction — so `legacy_*`,
1385 /// `workloads`, and `topology` come back empty. Machines are read from
1386 /// `config_dir/infra/machines` directly (sibling trees declare their own
1387 /// inventory or none).
1388 ///
1389 /// R615-F2 decision, explicit rather than silent: **sources.toml overlay
1390 /// does NOT apply here.** This function
1391 /// exists specifically because a multi-root sibling tree (W206 layout
1392 /// (b), e.g. `.noisetable/`) is a *second config root inside the same
1393 /// camp*, not a second camp — `config_dir` is already wherever the
1394 /// caller decided this tree's infra lives, and `.yah/infra/sources.toml`
1395 /// (singular, tied to `paths::infra_dir(workspace_root)`) has no
1396 /// well-defined meaning for an arbitrary `config_dir` that isn't that
1397 /// path. A sibling tree that wants borrowed infra declares its own
1398 /// `sources.toml` under whichever root actually calls
1399 /// [`CloudConfig::load`] for it; `machine_origins`/`provider_origins`
1400 /// come back empty here, not wrong — there is nothing to overlay.
1401 pub fn load_from_config_dir(config_dir: &Path, workspace_root: &Path) -> Result<Self> {
1402 let providers = load_providers(&config_dir.join("infra").join("providers"))?;
1403 let services = load_services(&config_dir.join("services"), workspace_root)?;
1404 let domains = load_domains(&config_dir.join("domains"))?;
1405
1406 Self::cross_ref_validate(&providers, &services, &domains)?;
1407
1408 let machines = load_dir::<MachineConfig>(config_dir.join("infra").join("machines"))?;
1409
1410 Ok(Self {
1411 workspace_root: workspace_root.to_path_buf(),
1412 machines,
1413 providers,
1414 machine_origins: BTreeMap::new(),
1415 provider_origins: BTreeMap::new(),
1416 services,
1417 domains,
1418 legacy_mirrors: vec![],
1419 workloads: vec![],
1420 topology: TopologyConfig::default(),
1421 legacy_services: vec![],
1422 })
1423 }
1424
1425 /// Cross-reference validation shared by [`CloudConfig::load`] and
1426 /// [`CloudConfig::load_from_config_dir`]: every mirror `providers.X.use =
1427 /// "<id>"` must resolve to a declared provider, and every domain route's
1428 /// `component = "<service>/<component-id>"` must resolve to a real component.
1429 fn cross_ref_validate(
1430 providers: &[ProviderConfig],
1431 services: &BTreeMap<String, ServiceWithMirrors>,
1432 domains: &BTreeMap<String, DomainConfig>,
1433 ) -> Result<()> {
1434 // Mirror `use = "<id>"` slots must resolve to a declared provider.
1435 let provider_ids: std::collections::HashSet<&str> =
1436 providers.iter().map(|p| p.id.as_str()).collect();
1437 for (svc_name, svc) in services {
1438 for (env, mirror) in &svc.mirrors {
1439 for (slot, body) in &mirror.providers {
1440 if let Some(id) = body.provider_id() {
1441 if !provider_ids.contains(id) {
1442 anyhow::bail!(
1443 "services/{svc_name}/mirrors/{env}.toml: \
1444 providers.{slot}.use = \"{id}\" — no such provider; \
1445 declare it at infra/providers/{id}.toml"
1446 );
1447 }
1448 }
1449 }
1450 }
1451 }
1452
1453 // Every domain route's `component = "<service>/<component-id>"` must
1454 // resolve to a real component.
1455 for (dom_name, dom) in domains {
1456 for (idx, route) in dom.routes.iter().enumerate() {
1457 let Some(component_ref) = route.mode.component() else {
1458 continue; // redirects don't reference components
1459 };
1460 let Some((svc_name, comp_id)) = split_component_ref(component_ref) else {
1461 anyhow::bail!(
1462 "domains/{dom_name}.toml: routes[{idx}].component = \
1463 \"{component_ref}\" — expected \"<service>/<component-id>\""
1464 );
1465 };
1466 let Some(svc) = services.get(svc_name) else {
1467 anyhow::bail!(
1468 "domains/{dom_name}.toml: routes[{idx}].component = \
1469 \"{component_ref}\" — no such service \"{svc_name}\" \
1470 under services/"
1471 );
1472 };
1473 let Some(component) = svc.service.components.iter().find(|c| c.id == comp_id)
1474 else {
1475 anyhow::bail!(
1476 "domains/{dom_name}.toml: routes[{idx}].component = \
1477 \"{component_ref}\" — service \"{svc_name}\" has no \
1478 component with id \"{comp_id}\""
1479 );
1480 };
1481
1482 // R746: a mounted component must be routed where it publishes.
1483 // The publisher writes its bundle under the mount and the front
1484 // door looks a request up by its own path, so a route path and
1485 // a mount that disagree produce a 404 with its cause two files
1486 // away. Checked in both directions, since either one alone is
1487 // the same silent miss.
1488 //
1489 // Static routes only: `mount` is a *storage* prefix, and a
1490 // backend route proxies to an origin that owns its own paths.
1491 if !matches!(route.mode, RouteMode::Static { .. }) {
1492 continue;
1493 }
1494 let mount = component.mount.as_deref().map(normalize_mount);
1495 let route_prefix = route_path_prefix(&route.path);
1496 if let Some(mount) = mount {
1497 if mount != route_prefix {
1498 anyhow::bail!(
1499 "domains/{dom_name}.toml: routes[{idx}].path = \
1500 \"{path}\" serves \"{component_ref}\", which \
1501 declares mount = \"/{mount}\" — a mounted \
1502 component publishes under its mount, so the route \
1503 must be \"/{mount}\" or \"/{mount}/*\" (or drop \
1504 the mount to serve from the service root)",
1505 path = route.path,
1506 );
1507 }
1508 } else if !route_prefix.is_empty() {
1509 anyhow::bail!(
1510 "domains/{dom_name}.toml: routes[{idx}].path = \
1511 \"{path}\" serves \"{component_ref}\", which declares \
1512 no `mount` — its bundle publishes at the service root, \
1513 so nothing is stored under \"/{route_prefix}\". Set \
1514 mount = \"/{route_prefix}\" on the component, or route \
1515 it at \"/*\"",
1516 path = route.path,
1517 );
1518 }
1519 }
1520 }
1521 Ok(())
1522 }
1523
1524 /// Look up a domain manifest by name (file stem under `.yah/domains/`).
1525 pub fn domain(&self, name: &str) -> Option<&DomainConfig> {
1526 self.domains.get(name)
1527 }
1528
1529 pub fn machine(&self, name: &str) -> Option<&MachineConfig> {
1530 self.machines.iter().find(|m| m.name == name)
1531 }
1532
1533 /// Look up a provider by id (matches `provider.id`, not the file stem).
1534 pub fn provider(&self, id: &str) -> Option<&ProviderConfig> {
1535 self.providers.iter().find(|p| p.id == id)
1536 }
1537
1538 /// Look up a service by name (matches `service.toml`'s `name` field).
1539 pub fn service(&self, name: &str) -> Option<&ServiceWithMirrors> {
1540 self.services.get(name)
1541 }
1542
1543 /// Look up a legacy mirror by camp name (pre-R215 .yah/cloud/mirrors/).
1544 pub fn legacy_mirror(&self, camp: &str) -> Option<&LegacyMirrorConfig> {
1545 self.legacy_mirrors.iter().find(|m| m.camp == camp)
1546 }
1547
1548 pub fn workload(&self, name: &str) -> Option<&WorkloadConfig> {
1549 self.workloads.iter().find(|w| w.spec.name == name)
1550 }
1551
1552 /// Every machine declaring `sovereign_group == group`, in declaration order.
1553 ///
1554 /// W305/R742-F3. A sovereign group has no file of its own — it exists only
1555 /// as the set of machines that name the same string — so "which boxes are
1556 /// the dev cluster" has to be *derived*, and before this it was not derived
1557 /// anywhere: `yah cloud rollout plan` still takes a hand-listed
1558 /// `--voter us-west-011 --voter us-west-013 …` for a fact the machine TOMLs
1559 /// already state (W314 gap 1).
1560 ///
1561 /// **This is not placement.** Resolving a group to its members is a
1562 /// *lookup*, and it stays outside [`RequiredSpec`] on purpose — see
1563 /// [`MachineConfig::sovereign_group`]. `migrate` calls this to pick the
1564 /// candidate set it then admits a workload against; nothing here filters
1565 /// scheduling, and adding `sovereign_group` to `matches` would still be the
1566 /// category error that doc warns about.
1567 ///
1568 /// An empty result means no machine declares `group`, which is
1569 /// indistinguishable from a typo — callers should say so with
1570 /// [`Self::declared_sovereign_groups`] rather than reporting "no
1571 /// candidates".
1572 pub fn machines_in_group(&self, group: &str) -> Vec<&MachineConfig> {
1573 self.machines
1574 .iter()
1575 .filter(|m| m.sovereign_group.as_deref() == Some(group))
1576 .collect()
1577 }
1578
1579 /// Every distinct `sovereign_group` declared by any machine, sorted.
1580 ///
1581 /// Exists so a bad `--to` names the real vocabulary instead of complaining
1582 /// abstractly — the same fail-loud shape [`taint_effect`]'s legal-key list
1583 /// gives `check_inert_taints`. Standalone machines (`None`) contribute
1584 /// nothing: "in no group" is not a group you can migrate *to*.
1585 pub fn declared_sovereign_groups(&self) -> Vec<&str> {
1586 let mut groups: Vec<&str> = self
1587 .machines
1588 .iter()
1589 .filter_map(|m| m.sovereign_group.as_deref())
1590 .collect();
1591 groups.sort_unstable();
1592 groups.dedup();
1593 groups
1594 }
1595
1596 /// F16 placement v1: the first machine satisfying every hard axis of `req`
1597 /// (region/zone/provider membership + mesh_tags superset). Declaration order
1598 /// in `.yah/infra/machines/` decides ties — deterministic-greedy, no
1599 /// backtracking. A fully-unconstrained `req` matches the first machine.
1600 ///
1601 /// Fails loud with the constraint summary and the candidate machine names
1602 /// when nothing matches, so `yah cloud apply` surfaces *why* placement
1603 /// failed instead of a silent empty set.
1604 pub fn resolve_machine(&self, req: &RequiredSpec) -> Result<&MachineConfig> {
1605 resolve_machine_among(&self.machines, req)
1606 }
1607
1608 /// F16 placement: first machine whose `mesh_tags` is a superset of
1609 /// `required`. Declaration order in `.yah/infra/machines/` decides ties.
1610 /// Empty `required` matches the first machine; callers should treat
1611 /// empty-required as "no constraint" and skip this lookup.
1612 ///
1613 /// Back-compat thin wrapper over [`CloudConfig::resolve_machine`] for the
1614 /// mesh-tags-only call sites that predate the topology axes.
1615 pub fn resolve_machine_by_mesh_tags(&self, required: &[String]) -> Option<&MachineConfig> {
1616 let req = RequiredSpec {
1617 mesh_tags: required.to_vec(),
1618 ..Default::default()
1619 };
1620 self.resolve_machine(&req).ok()
1621 }
1622
1623 /// Admission: resolve the target machine for a remote [`WorkloadSpec`],
1624 /// honoring the R594 mesh-tag node-selector annotation
1625 /// (`velveteen_exec::remote::NODE_SELECTOR_MESH_TAGS_ANNOTATION` =
1626 /// `yah.node-selector.mesh-tags`, comma-joined).
1627 ///
1628 /// The producer side (`velveteen_exec::remote::build_workload_spec`, R594) writes
1629 /// `TaskLocation::RemoteAny.mesh_tags` — e.g. `[tag:build-worker, arch:x86]`
1630 /// from [`qed::platform::build_worker_mesh_tags`] — into the workload's
1631 /// annotations. This is the consumer: candidates are restricted to machines
1632 /// whose `mesh_tags` are a **superset** of the requested set, so an amd64
1633 /// build lands on the `arch:x86` build-worker (us-west-002) and an arm64
1634 /// build on a `arch:arm` Pi5. Declaration order in `.yah/infra/machines/`
1635 /// breaks ties.
1636 ///
1637 /// An absent or empty annotation means "no mesh-tag constraint" — pre-R594
1638 /// behavior (any node), matching [`RequiredSpec::is_unconstrained`].
1639 ///
1640 /// This is the single admission seam: R572-F5 extends it with the capacity
1641 /// floor (workload request fits node allocatable−committed) and taint
1642 /// repulsion/affinity by enriching [`RequiredSpec::matches`] /
1643 /// [`Self::resolve_machine`]. Do not fork a second selector.
1644 pub fn admit_workload(&self, ws: &WorkloadSpec) -> Result<&MachineConfig> {
1645 self.resolve_machine(&admission_spec(ws))
1646 }
1647
1648 /// [`Self::admit_workload`] restricted to the machines of one sovereign
1649 /// group (W305/R742-F3, `yah cloud migrate --to <group>`).
1650 ///
1651 /// Same [`RequiredSpec`], same [`RequiredSpec::matches`], same
1652 /// declaration-order tie-break — only the candidate *set* differs. That is
1653 /// the whole reason this is a narrowing of the admission seam rather than a
1654 /// second selector: a workload that cannot be scheduled onto a group's
1655 /// boxes must fail here for exactly the reason it would fail anywhere else,
1656 /// and `no-appliance` on the dev Pis (W305 finding 2) is precisely the case
1657 /// that must not be silently routed around by a migration verb.
1658 ///
1659 /// `Err` when the group has no members *or* when no member admits `ws`; the
1660 /// two are different mistakes, so callers wanting to tell them apart should
1661 /// check [`Self::machines_in_group`] first.
1662 pub fn admit_workload_in_group(
1663 &self,
1664 ws: &WorkloadSpec,
1665 group: &str,
1666 ) -> Result<&MachineConfig> {
1667 let members = self.machines_in_group(group);
1668 let empty_pool = format!(
1669 "(no machine declares sovereign_group = \"{group}\" — declared groups: {})",
1670 match self.declared_sovereign_groups().as_slice() {
1671 [] => "(none)".to_string(),
1672 gs => gs.join(", "),
1673 }
1674 );
1675 first_match(
1676 &members,
1677 &admission_spec(ws),
1678 &format!("machines in sovereign group '{group}'"),
1679 &empty_pool,
1680 )
1681 }
1682}
1683
1684/// **The** placement selector: the first candidate satisfying every axis of
1685/// `req`, declaration order breaking ties, deterministic-greedy with no
1686/// backtracking.
1687///
1688/// Every path that picks a machine goes through here, and the only thing any
1689/// of them varies is *which machines are candidates* — never the predicate.
1690/// [`CloudConfig::resolve_machine`] passes the whole fleet;
1691/// [`CloudConfig::admit_workload_in_group`] passes one sovereign group's
1692/// members. That split is the point: a candidate-set narrowing composes with
1693/// the [`RequiredSpec`] axes for free, whereas expressing the same narrowing
1694/// *as* an axis would put facts like blast radius into a filter they must
1695/// never be in (see [`MachineConfig::sovereign_group`]).
1696///
1697/// So a new placement scope is a new candidate set plus a `pool` label, and a
1698/// new placement *constraint* is a field on [`RequiredSpec`] — those are the
1699/// two extension points, and neither is a second selector. `pool` and
1700/// `empty_pool` exist only so the failure names the set it actually searched;
1701/// a refusal that says "no candidates" without saying *among what* is one the
1702/// operator has to reconstruct by hand.
1703/// F16 placement v1 resolution over an explicit machine list — the
1704/// `.machines`-only half of [`CloudConfig::resolve_machine`], for callers that
1705/// have loaded just the machines tree rather than the whole cross-ref-validated
1706/// config.
1707///
1708/// R772: `resolve_ingress_placements` (`reconciler::ingress`) is the reason
1709/// this is `pub(crate)` rather than staying folded into
1710/// `CloudConfig::resolve_machine` — ingress collation walks every mirror in
1711/// the workspace and has no business hard-failing over an unrelated mirror's
1712/// `providers.X.use = "<id>"` typo, which is what going through
1713/// `CloudConfig::load`'s cross-ref validation would do. "Do not fork a second
1714/// selector" (see the module doc above) still holds: this is the *same*
1715/// [`first_match`], just handed a narrower candidate set than `self.machines`.
1716pub(crate) fn resolve_machine_among<'a>(
1717 machines: &'a [MachineConfig],
1718 req: &RequiredSpec,
1719) -> Result<&'a MachineConfig> {
1720 let all: Vec<&MachineConfig> = machines.iter().collect();
1721 first_match(
1722 &all,
1723 req,
1724 "declared machines",
1725 "(no machines declared under .yah/infra/machines/)",
1726 )
1727}
1728
1729fn first_match<'a>(
1730 candidates: &[&'a MachineConfig],
1731 req: &RequiredSpec,
1732 pool: &str,
1733 empty_pool: &str,
1734) -> Result<&'a MachineConfig> {
1735 candidates
1736 .iter()
1737 .copied()
1738 .find(|m| req.matches(m))
1739 .ok_or_else(|| {
1740 let names = if candidates.is_empty() {
1741 empty_pool.to_string()
1742 } else {
1743 candidates
1744 .iter()
1745 .map(|m| m.name.as_str())
1746 .collect::<Vec<_>>()
1747 .join(", ")
1748 };
1749 anyhow::anyhow!(
1750 "no candidates matching {} — {pool}: {names}",
1751 req.describe()
1752 )
1753 })
1754}
1755
1756/// The [`RequiredSpec`] a workload is admitted against — the single place the
1757/// axes are derived from a [`WorkloadSpec`].
1758///
1759/// Extracted from [`CloudConfig::admit_workload`] so that
1760/// [`CloudConfig::admit_workload_in_group`] narrows the candidate set without
1761/// restating the axes. Forking that derivation is how the two paths would
1762/// silently disagree about whether a workload fits a node.
1763fn admission_spec(ws: &WorkloadSpec) -> RequiredSpec {
1764 RequiredSpec {
1765 mesh_tags: node_selector_mesh_tags(ws),
1766 // R833-F8: imperative node pin. Derived here alongside the inferred
1767 // mesh tags rather than short-circuiting the resolver, so a pinned
1768 // workload is still checked against capacity and taints.
1769 nodes: node_selector_node(ws).into_iter().collect(),
1770 // R572-F5: capacity floor from the workload's resource request.
1771 //
1772 // `memory_request_mb()` and NOT `resources.memory_mb`: the latter
1773 // is a cgroup ceiling, and reading a ceiling as a floor made
1774 // `for_forge`'s deliberately-roomy 32 GiB limit mean "only place
1775 // me on a 32 GiB node". That excluded every build-worker in the
1776 // fleet but one. The accessor falls back to `resources.memory_mb`
1777 // when no request is declared, so specs that never set one are
1778 // admitted exactly as before.
1779 memory_mb: ws.memory_request_mb(),
1780 cpu_millis: ws.resources.cpu_millis,
1781 // R572-F5: taint repulsion derived from the workload's effective archetype.
1782 repel_archetype: Some(ws.effective_archetype()),
1783 // R572-F5: taint affinity from the requires-taint annotation.
1784 requires_taint: ws.requires_taint().map(str::to_owned),
1785 ..Default::default()
1786 }
1787}
1788
1789/// Parse the R594 mesh-tag node-selector off a workload's annotations into the
1790/// requested tag set. Absent annotation or empty value ⇒ empty vec ("no
1791/// constraint"). Whitespace around each comma-separated tag is trimmed and
1792/// empty segments are dropped, so `"tag:build-worker, arch:x86"` and
1793/// `"tag:build-worker,arch:x86"` parse identically.
1794pub fn node_selector_mesh_tags(ws: &WorkloadSpec) -> Vec<String> {
1795 ws.annotations
1796 .get(velveteen_exec::remote::NODE_SELECTOR_MESH_TAGS_ANNOTATION)
1797 .map(|v| {
1798 v.split(',')
1799 .map(str::trim)
1800 .filter(|s| !s.is_empty())
1801 .map(String::from)
1802 .collect()
1803 })
1804 .unwrap_or_default()
1805}
1806
1807/// Parse the R833-F8 imperative node-selector off a workload's annotations —
1808/// the single machine `name` the operator pinned the run to
1809/// (`--where=node:us-west-003`). Absent or blank ⇒ `None` ("no constraint"),
1810/// which is every workload built before this axis existed.
1811///
1812/// One node, not a list: the annotation exists to express "run it *there*", and
1813/// a comma-joined set would be a worse spelling of the mesh-tag selector that
1814/// already handles "any of these".
1815pub fn node_selector_node(ws: &WorkloadSpec) -> Option<String> {
1816 ws.annotations
1817 .get(velveteen_exec::remote::NODE_SELECTOR_NODE_ANNOTATION)
1818 .map(|v| v.trim())
1819 .filter(|v| !v.is_empty())
1820 .map(String::from)
1821}
1822
1823/// Load every `.yah/infra/providers/*.toml` into a [`ProviderConfig`] list.
1824/// Missing directory → empty list.
1825fn load_providers(dir: &Path) -> Result<Vec<ProviderConfig>> {
1826 if !dir.exists() {
1827 return Ok(vec![]);
1828 }
1829 let mut items = vec![];
1830 let mut entries: Vec<_> = std::fs::read_dir(dir)
1831 .with_context(|| format!("reading {}", dir.display()))?
1832 .filter_map(|e| e.ok())
1833 .filter(|e| e.path().extension().map_or(false, |x| x == "toml"))
1834 .collect();
1835 entries.sort_by_key(|e| e.file_name());
1836 for entry in entries {
1837 items.push(ProviderConfig::load(&entry.path())?);
1838 }
1839 Ok(items)
1840}
1841
1842/// Map legacy mirror file stems to their canonical tier names.
1843///
1844/// Canonical tiers: `dev` / `pond` / `cloud` / `ha`.
1845/// Legacy stems pre-R362: `local` (dev tier), `local-sim` / `sim` (pond tier), `prod` (cloud tier).
1846/// Both forms are accepted; canonical names are preferred for new files.
1847pub fn canonical_tier(stem: &str) -> &str {
1848 match stem {
1849 "local" => "dev",
1850 "local-sim" | "sim" => "pond",
1851 "prod" => "cloud",
1852 other => other,
1853 }
1854}
1855
1856/// Walk `.yah/services/<svc>/` for every service and its mirrors.
1857/// Missing directory → empty map. Mirror file stems are normalized to canonical
1858/// tier names via [`canonical_tier`] so callers always see `dev/pond/cloud/ha`.
1859fn load_services(
1860 dir: &Path,
1861 workspace_root: &Path,
1862) -> Result<BTreeMap<String, ServiceWithMirrors>> {
1863 if !dir.exists() {
1864 return Ok(BTreeMap::new());
1865 }
1866 let mut out = BTreeMap::new();
1867 let mut entries: Vec<_> = std::fs::read_dir(dir)
1868 .with_context(|| format!("reading {}", dir.display()))?
1869 .filter_map(|e| e.ok())
1870 .filter(|e| e.path().is_dir())
1871 .collect();
1872 entries.sort_by_key(|e| e.file_name());
1873
1874 for entry in entries {
1875 let svc_dir = entry.path();
1876 let service_toml = svc_dir.join("service.toml");
1877 if !service_toml.exists() {
1878 // Skip directories without a service.toml — leaves room for
1879 // future siblings (e.g. `secrets/`, `README.md`) without
1880 // triggering false-positive parse errors.
1881 continue;
1882 }
1883 let service = ServiceConfig::load(&service_toml)?;
1884 let mut mirrors = BTreeMap::new();
1885 let mirrors_dir = svc_dir.join("mirrors");
1886 if mirrors_dir.exists() {
1887 let mut menv: Vec<_> = std::fs::read_dir(&mirrors_dir)
1888 .with_context(|| format!("reading {}", mirrors_dir.display()))?
1889 .filter_map(|e| e.ok())
1890 .filter(|e| e.path().extension().map_or(false, |x| x == "toml"))
1891 .collect();
1892 menv.sort_by_key(|e| e.file_name());
1893 for m in menv {
1894 let path = m.path();
1895 let stem = path
1896 .file_stem()
1897 .and_then(|s| s.to_str())
1898 .unwrap_or("")
1899 .to_string();
1900 let tier = canonical_tier(&stem).to_string();
1901 // Last-write wins if both legacy and canonical forms coexist
1902 // (e.g. local-sim.toml + pond.toml). Sort order ensures the
1903 // canonical file (pond.toml) wins because 'p' > 'l'.
1904 mirrors.insert(tier, MirrorConfig::load(&path)?);
1905 }
1906 }
1907 let mut component_transform_recipes = BTreeMap::new();
1908 for component in &service.components {
1909 if component.kind == "static-asset" {
1910 if let Some(recipe) =
1911 read_component_transform_recipe(workspace_root, &component.path)
1912 {
1913 component_transform_recipes.insert(component.id.clone(), recipe);
1914 }
1915 }
1916 }
1917 out.insert(
1918 service.name.clone(),
1919 ServiceWithMirrors {
1920 service,
1921 mirrors,
1922 component_transform_recipes,
1923 },
1924 );
1925 }
1926 Ok(out)
1927}
1928
1929/// Read the first transform recipe name from a component's `workload.toml`.
1930/// Returns `None` when the file is absent or has no `[asset.derive.transform]`
1931/// section. Best-effort — parse failures are silently ignored so a malformed
1932/// workload.toml doesn't abort the entire service catalog load.
1933fn read_component_transform_recipe(workspace_root: &Path, component_path: &str) -> Option<String> {
1934 let workload_path = workspace_root.join(component_path).join("workload.toml");
1935 let text = std::fs::read_to_string(&workload_path).ok()?;
1936 let value: toml::Value = toml::from_str(&text).ok()?;
1937 let assets = value.get("asset")?.as_array()?;
1938 for asset in assets {
1939 if let Some(recipe) = asset
1940 .get("derive")
1941 .and_then(|d| d.get("transform"))
1942 .and_then(|t| t.get("recipe"))
1943 .and_then(|r| r.as_str())
1944 {
1945 return Some(recipe.to_string());
1946 }
1947 }
1948 None
1949}
1950
1951/// Load every `.yah/domains/*.toml` into a [`DomainConfig`] map keyed by
1952/// file stem. Missing directory → empty map.
1953fn load_domains(dir: &Path) -> Result<BTreeMap<String, DomainConfig>> {
1954 if !dir.exists() {
1955 return Ok(BTreeMap::new());
1956 }
1957 let mut out = BTreeMap::new();
1958 let mut entries: Vec<_> = std::fs::read_dir(dir)
1959 .with_context(|| format!("reading {}", dir.display()))?
1960 .filter_map(|e| e.ok())
1961 .filter(|e| e.path().extension().map_or(false, |x| x == "toml"))
1962 .collect();
1963 entries.sort_by_key(|e| e.file_name());
1964 for entry in entries {
1965 let path = entry.path();
1966 let stem = path
1967 .file_stem()
1968 .and_then(|s| s.to_str())
1969 .unwrap_or("")
1970 .to_string();
1971 let dom = DomainConfig::load(&path)?;
1972 if dom.name != stem {
1973 anyhow::bail!(
1974 "domains/{}.toml: name = \"{}\" must match the file stem",
1975 stem,
1976 dom.name
1977 );
1978 }
1979 out.insert(dom.name.clone(), dom);
1980 }
1981 Ok(out)
1982}
1983
1984/// Load and shape-validate all `*.toml` files in `dir` as [`WorkloadConfig`].
1985fn load_workloads(dir: std::path::PathBuf) -> Result<Vec<WorkloadConfig>> {
1986 if !dir.exists() {
1987 return Ok(vec![]);
1988 }
1989 let mut items = vec![];
1990 let mut entries: Vec<_> = std::fs::read_dir(&dir)
1991 .with_context(|| format!("reading {}", dir.display()))?
1992 .filter_map(|e| e.ok())
1993 .filter(|e| e.path().extension().map_or(false, |x| x == "toml"))
1994 .collect();
1995 entries.sort_by_key(|e| e.file_name());
1996
1997 for entry in entries {
1998 let path = entry.path();
1999 let path_str = path.display().to_string();
2000 let src =
2001 std::fs::read_to_string(&path).with_context(|| format!("reading {}", path_str))?;
2002 let spec: WorkloadSpec =
2003 toml::from_str(&src).with_context(|| format!("parsing {}", path_str))?;
2004
2005 // Shape-validate before accepting into the loaded config.
2006 validate::shape(&spec)
2007 .map_err(|e| anyhow::anyhow!("workload {} failed shape validation: {e}", path_str))?;
2008
2009 items.push(WorkloadConfig { spec });
2010 }
2011 Ok(items)
2012}
2013
2014/// Load all mirror configs from the `mirrors/` directory.
2015///
2016/// Handles two layouts that may coexist:
2017/// - **Folder**: `mirrors/<id>/mirror.toml` — preferred; allows secrets and
2018/// per-mirror overrides to live next to the config file.
2019/// - **Flat**: `mirrors/<id>.toml` — legacy; still supported.
2020///
2021/// Each file is parsed as [`LegacyMirrorConfig`]. A malformed file returns an error
2022/// that includes the file path and the TOML field path + line/column, so the
2023/// caller can surface it to the user directly.
2024fn load_mirrors(dir: std::path::PathBuf) -> Result<Vec<LegacyMirrorConfig>> {
2025 if !dir.exists() {
2026 return Ok(vec![]);
2027 }
2028 let mut mirrors = vec![];
2029 let mut entries: Vec<_> = std::fs::read_dir(&dir)
2030 .with_context(|| format!("reading {}", dir.display()))?
2031 .filter_map(|e| e.ok())
2032 .collect();
2033 entries.sort_by_key(|e| e.file_name());
2034
2035 for entry in entries {
2036 let path = entry.path();
2037 if path.is_dir() {
2038 // Folder layout: mirrors/<id>/mirror.toml
2039 let mirror_toml = path.join("mirror.toml");
2040 if mirror_toml.exists() {
2041 let src = std::fs::read_to_string(&mirror_toml)
2042 .with_context(|| format!("reading {}", mirror_toml.display()))?;
2043 let cfg: LegacyMirrorConfig = toml::from_str(&src)
2044 .with_context(|| format!("parsing {}", mirror_toml.display()))?;
2045 mirrors.push(cfg);
2046 }
2047 } else if path.extension().map_or(false, |e| e == "toml") {
2048 // Flat layout: mirrors/<id>.toml
2049 let src = std::fs::read_to_string(&path)
2050 .with_context(|| format!("reading {}", path.display()))?;
2051 let cfg: LegacyMirrorConfig =
2052 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
2053 mirrors.push(cfg);
2054 }
2055 }
2056 Ok(mirrors)
2057}
2058
2059/// Load `topology.toml` if it exists; return a default (empty) topology otherwise.
2060fn load_topology(path: std::path::PathBuf) -> Result<TopologyConfig> {
2061 if !path.exists() {
2062 return Ok(TopologyConfig::default());
2063 }
2064 let src =
2065 std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
2066 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
2067}
2068
2069/// R555-S1: entries are sorted by file name before parsing, so "declaration
2070/// order in `.yah/infra/machines/` breaks ties" — the contract
2071/// [`CloudConfig::admit_workload`] documents — is actually true. `read_dir`
2072/// yields filesystem order, which is unspecified and differs between APFS and
2073/// a hashed-dir ext4; without the sort, *which* of two equally-matching nodes a
2074/// workload admits to could change when an unrelated file is added to the
2075/// directory. That was latent while each tag set had one match and became
2076/// observable the day us-west-003 joined us-west-002 on
2077/// `[tag:build-worker, arch:x86, os:linux]`. Same sort `load_providers` has
2078/// always done.
2079fn load_dir<T: for<'de> Deserialize<'de>>(dir: std::path::PathBuf) -> Result<Vec<T>> {
2080 if !dir.exists() {
2081 return Ok(vec![]);
2082 }
2083 let mut entries: Vec<_> = std::fs::read_dir(&dir)
2084 .with_context(|| format!("reading {}", dir.display()))?
2085 .collect::<std::io::Result<Vec<_>>>()
2086 .with_context(|| format!("reading {}", dir.display()))?;
2087 entries.sort_by_key(|e| e.file_name());
2088
2089 let mut items = vec![];
2090 for entry in entries {
2091 let path = entry.path();
2092 if path.extension().map_or(false, |e| e == "toml") {
2093 let src = std::fs::read_to_string(&path)
2094 .with_context(|| format!("reading {}", path.display()))?;
2095 let item: T =
2096 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
2097 items.push(item);
2098 }
2099 }
2100 Ok(items)
2101}
2102
2103// ─── New manifest shapes (R222 B2) ───────────────────────────────────────────
2104//
2105// The post-R215 layout splits substrate from service declarations:
2106//
2107// .yah/infra/providers/<id>.toml → ProviderConfig
2108// .yah/services/<svc>/service.toml → ServiceConfig
2109// .yah/services/<svc>/mirrors/<env>.toml → MirrorConfig
2110//
2111// CloudConfig::load still reads the legacy layout — B3 swaps in these types
2112// and removes the Legacy* shapes plus TopologyConfig.
2113
2114/// Tag for the infrastructure provider kind. Drives which fields are valid in
2115/// a [`ProviderConfig`] body or a [`MirrorProviderSlot::Inline`] block.
2116///
2117/// Two flavors:
2118/// - **Account/runtime providers** (`cloudflare`, `hetzner`, `local-container`)
2119/// live as files under `.yah/infra/providers/<id>.toml` and are referenced
2120/// from a mirror via `use = "<id>"`.
2121/// - **Inline-only providers** (`local-static`, `miniflare-container`,
2122/// `minio-container`) declare an operator-local stand-in directly inside a
2123/// mirror via `kind = "..."`. They carry no credentials and have no provider
2124/// file. The container-backed kinds ride on top of whichever
2125/// `local-container` runtime is declared in infra (orbstack/colima/docker);
2126/// the reconciler resolves the runtime at up-time.
2127#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
2128#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2129#[serde(rename_all = "kebab-case")]
2130pub enum Provider {
2131 /// Cloudflare account: R2 buckets, DNS, Workers, Tunnels.
2132 Cloudflare,
2133 /// Hetzner Cloud + Object Storage account.
2134 Hetzner,
2135 /// Vultr cloud VPS — auto-provisioned via the `cloud.vps.*` Envoy
2136 /// (`VultrEnvoy`), the burst/scaling counterpart to Hetzner. Driver-backed.
2137 Vultr,
2138 /// BYO bare/static node (OVH, on-prem, anything we did NOT provision via a
2139 /// cloud API). Brought up over SSH (`stand-up-yubaba.sh` / `yah cloud
2140 /// machine bootstrap`); reach is declared in the machine's `[connect]`
2141 /// block. No create/destroy driver — placement-only.
2142 Static,
2143 /// Built-in static-file server bound to localhost. Inline-only; never
2144 /// declared as a standalone provider file because it carries no creds.
2145 LocalStatic,
2146 /// Local container runtime (orbstack/colima/docker). Configured by a
2147 /// provider file under `.yah/infra/providers/` so the discovery hints +
2148 /// runtime override sit in one place.
2149 LocalContainer,
2150 /// Dev-tier compute: the component runs as a kamaji-supervised host
2151 /// process against the operator's real workspace, no container and no
2152 /// build step per edit. Inline-only — it carries no credentials, and
2153 /// "the machine you are sitting at" is not an account to point at.
2154 /// See `reconciler::local_process`.
2155 LocalProcess,
2156 /// Containerized miniflare (workerd subprocess) fronting MinIO — the
2157 /// pond-tier stand-in for a CF Worker + R2 static surface. Inline-only;
2158 /// the reconciler spawns miniflare via the JS runtime and starts a MinIO
2159 /// container on the local-container runtime.
2160 MiniflareContainer,
2161 /// Containerized MinIO providing an S3-compatible API — the pond-tier
2162 /// stand-in for Cloudflare R2. Inline-only; the reconciler spins up the
2163 /// container on the local-container runtime and auto-creates the declared
2164 /// bucket on first up.
2165 MinioContainer,
2166 /// Dev-tier PostgreSQL — a real server speaking real pgwire on loopback,
2167 /// supervised by kamaji as the `yah-pg-dev` workload (W265, R584-F1). No
2168 /// docker daemon: the driver fetches a per-arch PostgreSQL tarball on first
2169 /// run and `initdb`s a cluster under `.yah/infra/state/dev/pg/`.
2170 ///
2171 /// Inline-only — it carries no credentials worth a provider file (the
2172 /// cluster is loopback-bound with a fixed dev password). Declared under
2173 /// [`MirrorConfig::drivers`], not `providers`:
2174 ///
2175 /// ```toml
2176 /// [drivers.pg]
2177 /// kind = "local-pg-dev"
2178 /// ```
2179 LocalPgDev,
2180}
2181
2182/// A provider account/runtime binding from `.yah/infra/providers/<id>.toml`.
2183///
2184/// The `kind` discriminator picks the schema for the remaining fields. Strict
2185/// on `kind` (unknown values are a parse error); permissive on per-kind fields
2186/// (carried as a free-form map so this loader stays stable as new fields land).
2187/// B3/B4 will tighten by introducing typed variants alongside JSON Schema.
2188#[derive(Debug, Clone, Serialize, Deserialize)]
2189#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2190pub struct ProviderConfig {
2191 pub schema_version: u32,
2192 pub id: String,
2193 pub kind: Provider,
2194 /// Reference into the OS keystore for live credentials (e.g.
2195 /// `"keystore://cloudflare/yah"`). `None` for providers that don't need
2196 /// creds (local-static, optionally local-container).
2197 #[serde(default, skip_serializing_if = "Option::is_none")]
2198 pub credentials: Option<String>,
2199 /// Kind-specific fields. Examples:
2200 /// - cloudflare: `default_zone`
2201 /// - hetzner: `default_location`, `default_server_type`, `ssh_keys`
2202 /// - local-container: `runtime`, `discovery`
2203 #[serde(flatten)]
2204 #[cfg_attr(
2205 feature = "json-schema",
2206 schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
2207 )]
2208 pub fields: BTreeMap<String, toml::Value>,
2209}
2210
2211impl ProviderConfig {
2212 /// Parse a single `providers/<id>.toml` file.
2213 pub fn load(path: &Path) -> Result<Self> {
2214 let src =
2215 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
2216 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
2217 }
2218}
2219
2220/// An operator-facing service declaration from
2221/// `.yah/services/<svc>/service.toml`.
2222///
2223/// A service groups one or more components (a static surface, a containerized
2224/// API, an almanac…) under a single domain. Mirrors project the service onto
2225/// concrete infra; see [`MirrorConfig`].
2226#[derive(Debug, Clone, Serialize, Deserialize)]
2227#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2228pub struct ServiceConfig {
2229 pub schema_version: u32,
2230 pub name: String,
2231 pub domain: String,
2232 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2233 pub components: Vec<ServiceComponent>,
2234 /// Databases this service exposes, grouped by environment (W241). Every
2235 /// entry becomes a data-workbench / `sql_*` catalog id of the shape
2236 /// `<env>:<service>:<name>` (e.g. `pond:scrabcake:main`). Optional and
2237 /// default-empty — services without databases omit the `[db]` table
2238 /// entirely.
2239 #[serde(default, skip_serializing_if = "DbCatalog::is_empty")]
2240 pub db: DbCatalog,
2241}
2242
2243impl ServiceConfig {
2244 /// Parse a single `services/<svc>/service.toml` file.
2245 pub fn load(path: &Path) -> Result<Self> {
2246 let src =
2247 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
2248 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
2249 }
2250
2251 /// Persist to `.yah/services/<name>/service.toml`, creating the service
2252 /// directory if needed. Create-or-overwrite — the canonical replacement
2253 /// for the legacy `sites.json` write path. `workspace_root` is the camp
2254 /// dir (the parent of `.yah/`).
2255 pub fn save(&self, workspace_root: &Path) -> Result<()> {
2256 let dir = crate::paths::service_dir(workspace_root, &self.name);
2257 std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
2258 let path = crate::paths::service_toml(workspace_root, &self.name);
2259 let s = toml::to_string_pretty(self)
2260 .with_context(|| format!("serializing service {}", self.name))?;
2261 std::fs::write(&path, s).with_context(|| format!("writing {}", path.display()))
2262 }
2263
2264 /// Remove `.yah/services/<name>/` and everything under it (service.toml
2265 /// plus its `mirrors/`). Returns `false` when the directory was already
2266 /// absent, so callers can distinguish "deleted" from "no-op".
2267 pub fn delete(workspace_root: &Path, name: &str) -> Result<bool> {
2268 let dir = crate::paths::service_dir(workspace_root, name);
2269 if !dir.exists() {
2270 return Ok(false);
2271 }
2272 std::fs::remove_dir_all(&dir).with_context(|| format!("removing {}", dir.display()))?;
2273 Ok(true)
2274 }
2275}
2276
2277/// A git source for a component (R561-F1, "BYO git").
2278///
2279/// When a [`ServiceComponent`] sets `git`, the component's code is NOT in this
2280/// workspace — it lives in an external repo that the reconciler shallow-clones
2281/// into a source cache before build (approach A: clone-at-reconcile, so config
2282/// load + validation stay offline). The component's `path` is then interpreted
2283/// relative to `<checkout>/<subdir>` instead of the workspace root.
2284#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2285#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2286pub struct GitSource {
2287 /// Clone URL (https or ssh) of the tenant repo.
2288 pub repo: String,
2289 /// Branch, tag, or commit SHA to check out. Defaults to `"main"`.
2290 #[serde(default = "default_git_ref")]
2291 pub r#ref: String,
2292 /// Optional sub-directory within the repo that the workspace is rooted at
2293 /// (e.g. a monorepo's `site/`). `path` is resolved relative to this.
2294 #[serde(default, skip_serializing_if = "Option::is_none")]
2295 pub subdir: Option<String>,
2296}
2297
2298fn default_git_ref() -> String {
2299 "main".to_string()
2300}
2301
2302/// How to reach an external infra root (R615-F1 / W274, "linked infra
2303/// sources"): a filesystem link to a sibling camp's live tree, or a git
2304/// checkout of an extracted infra repo.
2305#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2306#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2307#[serde(tag = "kind", rename_all = "kebab-case")]
2308pub enum InfraSourceKind {
2309 /// Filesystem link — reads the owner's live tree. The dev-loop shortcut,
2310 /// and the whole story until W274's "infra as its own repo" end-state.
2311 /// `path` is relative to *this* camp's root; infra is read from
2312 /// `<path>/.yah/infra/`.
2313 Path {
2314 path: String,
2315 },
2316 /// Git link — reused verbatim from [`GitSource`] (R561, "BYO git"),
2317 /// lifted here from "a component's code" to "a camp's infra registry."
2318 /// Loading stays offline (W274 §3): `yah infra sync` (R615-T3) is what
2319 /// clones/pulls this into `.yah/cache/infra/<owner>/`; `CloudConfig::load`
2320 /// only ever reads that cache, never the network.
2321 Git(GitSource),
2322}
2323
2324/// Write-gate for a linked [`InfraSource`] (R615-F1 / W274).
2325///
2326/// An enum, not a bool: the two states today are "borrower renders/plans but
2327/// cannot reconcile" and "this camp genuinely co-administers the shared
2328/// root," and a future read-write-with-approval tier is a third variant, not
2329/// a renamed boolean.
2330#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2331#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2332#[serde(rename_all = "kebab-case")]
2333pub enum SourceMode {
2334 /// Borrower can render and plan against the linked entries but cannot
2335 /// reconcile/mutate them — the owner remains the single manager. Default:
2336 /// a borrower is opt-in to write access, never opt-out of the safe state.
2337 #[default]
2338 ReadOnly,
2339 /// Escape hatch for a camp that genuinely co-administers a shared root.
2340 Manage,
2341}
2342
2343/// One `[[source]]` entry in `.yah/infra/sources.toml` (R615-F1 / W274) — an
2344/// external infra root this camp borrows machines/providers from.
2345#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2346#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2347pub struct InfraSource {
2348 /// Logical owner name, badged in the Infra tab (e.g. `"yah"`). Distinct
2349 /// from any camp/repo name the `kind` resolves through — this is what an
2350 /// operator sees on a borrowed row, not a path.
2351 pub owner: String,
2352 #[serde(flatten)]
2353 pub kind: InfraSourceKind,
2354 #[serde(default)]
2355 pub mode: SourceMode,
2356 /// Optional filter — name globs or mesh-tag selectors — to borrow a
2357 /// subset of the source root rather than everything it declares. Empty
2358 /// (the default) borrows everything.
2359 #[serde(default)]
2360 pub select: Vec<String>,
2361}
2362
2363fn default_sources_schema_version() -> u32 {
2364 1
2365}
2366
2367/// `.yah/infra/sources.toml` — the ordered list of external infra roots this
2368/// camp borrows from (R615-F1 / W274).
2369#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2370#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2371pub struct SourcesConfig {
2372 #[serde(default = "default_sources_schema_version")]
2373 pub schema_version: u32,
2374 /// `[[source]]` entries, in declaration order — overlay order matters
2375 /// when two linked sources both name the same machine (R615-F2).
2376 #[serde(default, rename = "source")]
2377 pub source: Vec<InfraSource>,
2378}
2379
2380impl Default for SourcesConfig {
2381 fn default() -> Self {
2382 Self {
2383 schema_version: default_sources_schema_version(),
2384 source: Vec::new(),
2385 }
2386 }
2387}
2388
2389impl SourcesConfig {
2390 /// Load `<infra_dir>/sources.toml`. A missing file is not an error —
2391 /// every camp without linked infra has none, which today is every camp —
2392 /// and yields an empty source list rather than `Err`.
2393 pub fn load(infra_dir: &Path) -> Result<Self> {
2394 let path = infra_dir.join("sources.toml");
2395 if !path.exists() {
2396 return Ok(Self::default());
2397 }
2398 let src =
2399 std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
2400 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
2401 }
2402}
2403
2404impl InfraSource {
2405 /// Human-readable descriptor of *which* source this is, for
2406 /// [`InfraOrigin::source`] — distinguishes two linked sources from the
2407 /// same owner. Never includes credentials: `GitSource.repo` is a clone
2408 /// URL (https/ssh), the same thing R561 already treats as safe to log,
2409 /// with any real secret resolved separately via `keystore://` (W274's
2410 /// own precedent).
2411 fn describe(&self) -> String {
2412 match &self.kind {
2413 InfraSourceKind::Path { path } => format!("path:{path}"),
2414 InfraSourceKind::Git(g) => format!("git:{}@{}", g.repo, g.r#ref),
2415 }
2416 }
2417
2418 /// Resolve this source to an infra root directory (R615-F2 / W274 §3).
2419 /// Does no I/O and touches no network: `path` sources read the owner's
2420 /// live tree directly; `git` sources read wherever `yah infra sync`
2421 /// (R615-T3) last synced to, which may not exist yet (an unsynced git
2422 /// source overlays nothing, not an error — see [`load_dir_tolerant`]).
2423 ///
2424 /// `git.subdir` (reused verbatim from [`GitSource`]/R561) is honoured
2425 /// exactly like the component case: the checkout root when unset, or
2426 /// `<checkout>/<subdir>` when set — e.g. `subdir = "infra"` for a
2427 /// monorepo whose infra registry lives under `infra/` rather than at the
2428 /// clone's root. `yah infra sync` (R615-T3) clones into the *checkout*
2429 /// root ([`crate::paths::infra_source_cache_dir`]), never into a
2430 /// subdir-suffixed path, so this is the one place that appends `subdir`.
2431 fn infra_root(&self, workspace_root: &Path) -> std::path::PathBuf {
2432 match &self.kind {
2433 InfraSourceKind::Path { path } => workspace_root.join(path).join(".yah").join("infra"),
2434 InfraSourceKind::Git(g) => {
2435 let checkout = crate::paths::infra_source_cache_dir(workspace_root, &self.owner);
2436 match g.subdir.as_deref() {
2437 Some(subdir) => checkout.join(subdir),
2438 None => checkout,
2439 }
2440 }
2441 }
2442 }
2443}
2444
2445/// Provenance for a [`MachineConfig`] or [`ProviderConfig`] pulled in from a
2446/// linked `.yah/infra/sources.toml` entry, rather than declared in this
2447/// camp's own `.yah/infra/` (R615-F2 / W274).
2448///
2449/// Lives in [`CloudConfig::machine_origins`] / `provider_origins`, keyed by
2450/// name/id, rather than as a field on `MachineConfig`/`ProviderConfig`
2451/// themselves: those two types are constructed by struct literal in test
2452/// helpers across several crates (including ones this ticket has no reason to
2453/// touch), so widening either shape would ripple out past this crate for no
2454/// semantic gain — origin is a property of *this load*, not an inherent
2455/// property of the machine/provider. A name absent from the map is
2456/// camp-local; present means borrowed, and the Infra tab (R615-F4) / reconcile
2457/// gating (`InfraSource::mode`, copied onto `mode` below) read it from here.
2458#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2459#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2460pub struct InfraOrigin {
2461 /// The [`InfraSource::owner`] that supplied this entry, e.g. `"yah"`.
2462 pub owner: String,
2463 /// Which source, rendered — see [`InfraSource::describe`].
2464 pub source: String,
2465 /// The write-gate that applied when this entry was overlaid — copied
2466 /// from [`InfraSource::mode`] so a caller holding just the machine/
2467 /// provider doesn't need the source list in hand to know it's borrowed
2468 /// read-only.
2469 pub mode: SourceMode,
2470}
2471
2472/// Like [`load_dir`], but tolerant **per file**: a foreign infra root (an
2473/// owner's live tree, or a synced git checkout) can carry entries this
2474/// binary's `T` predates — noisetable's pre-migration machines used an older
2475/// schema than yah's, and the reverse will happen too as each side evolves
2476/// independently. One unparseable file on a source this camp doesn't own must
2477/// never sink every other entry in the same directory, let alone this camp's
2478/// own load (R615-F2 gotcha). Contrast [`load_dir`], which stays strict for
2479/// camp-local files, where a malformed TOML genuinely should be a hard error.
2480///
2481/// Returns the entries that parsed, plus `(path, error)` for every file that
2482/// didn't — the caller logs those, it doesn't drop them silently. A missing
2483/// or unreadable directory yields `(vec![], vec![])`, same "no entries" as
2484/// `load_dir`'s `!dir.exists()` case (an unsynced git source, or a source
2485/// root with no `providers/` at all, are both normal, not warnings).
2486fn load_dir_tolerant<T: for<'de> Deserialize<'de>>(
2487 dir: &Path,
2488) -> (Vec<T>, Vec<(std::path::PathBuf, anyhow::Error)>) {
2489 let Ok(read_dir) = std::fs::read_dir(dir) else {
2490 return (Vec::new(), Vec::new());
2491 };
2492 let mut entries: Vec<_> = read_dir.filter_map(|e| e.ok()).collect();
2493 entries.sort_by_key(|e| e.file_name());
2494
2495 let mut items = Vec::new();
2496 let mut skipped = Vec::new();
2497 for entry in entries {
2498 let path = entry.path();
2499 if path.extension().map_or(true, |e| e != "toml") {
2500 continue;
2501 }
2502 let parsed = std::fs::read_to_string(&path)
2503 .with_context(|| format!("reading {}", path.display()))
2504 .and_then(|src| {
2505 toml::from_str::<T>(&src).with_context(|| format!("parsing {}", path.display()))
2506 });
2507 match parsed {
2508 Ok(item) => items.push(item),
2509 Err(e) => skipped.push((path, e)),
2510 }
2511 }
2512 (items, skipped)
2513}
2514
2515/// Whether a borrowed machine passes an [`InfraSource::select`] filter
2516/// (R615-F2 / W274). Empty `select` borrows everything. A non-empty `select`
2517/// entry matches either the machine's exact `name` or literal membership in
2518/// its `mesh_tags` — the one shape W274's own example uses
2519/// (`select = ["tag:cloud-runner"]`). Not a glob engine: mesh tags are
2520/// already flat strings compared for exact equality everywhere else in this
2521/// crate (see `resolve_machine_by_mesh_tags`), so a select entry is that same
2522/// comparison, not a new pattern language.
2523fn machine_matches_select(machine: &MachineConfig, select: &[String]) -> bool {
2524 select.is_empty()
2525 || select
2526 .iter()
2527 .any(|s| *s == machine.name || machine.mesh_tags.contains(s))
2528}
2529
2530/// Overlay every linked `.yah/infra/sources.toml` source's machines and
2531/// providers into `machines`/`providers`, recording provenance into
2532/// `machine_origins`/`provider_origins` (R615-F2 / W274). Must be called
2533/// AFTER camp-local entries are already in both vectors and both origin maps
2534/// are seeded with every camp-local name/id already `HashSet`-tracked as
2535/// "seen": collision resolution is "first writer wins," so seeding with
2536/// camp-local first is what makes camp-local win over every source, and an
2537/// earlier source win over a later one.
2538///
2539/// `select` filters which machines a source contributes; it does not apply
2540/// to providers (nothing in W274 or the source ticket describes a
2541/// provider-scoped filter — every provider a source declares either overlays
2542/// whole or, on a name collision, doesn't).
2543fn overlay_infra_sources(
2544 workspace_root: &Path,
2545 sources: &SourcesConfig,
2546 machines: &mut Vec<MachineConfig>,
2547 providers: &mut Vec<ProviderConfig>,
2548 machine_origins: &mut BTreeMap<String, InfraOrigin>,
2549 provider_origins: &mut BTreeMap<String, InfraOrigin>,
2550) {
2551 let mut seen_machine_names: std::collections::HashSet<String> =
2552 machines.iter().map(|m| m.name.clone()).collect();
2553 let mut seen_provider_ids: std::collections::HashSet<String> =
2554 providers.iter().map(|p| p.id.clone()).collect();
2555
2556 for source in &sources.source {
2557 let root = source.infra_root(workspace_root);
2558 let origin = InfraOrigin {
2559 owner: source.owner.clone(),
2560 source: source.describe(),
2561 mode: source.mode,
2562 };
2563
2564 let (foreign_machines, skipped) = load_dir_tolerant::<MachineConfig>(&root.join("machines"));
2565 for (path, e) in skipped {
2566 tracing::warn!(
2567 "infra source {:?} ({}): skipping unparseable machine {}: {e:#}",
2568 source.owner,
2569 root.display(),
2570 path.display()
2571 );
2572 }
2573 for m in foreign_machines {
2574 if seen_machine_names.contains(&m.name) {
2575 continue; // camp-local, or an earlier source, already claimed this name
2576 }
2577 if !machine_matches_select(&m, &source.select) {
2578 continue;
2579 }
2580 seen_machine_names.insert(m.name.clone());
2581 machine_origins.insert(m.name.clone(), origin.clone());
2582 machines.push(m);
2583 }
2584
2585 let (foreign_providers, skipped) = load_dir_tolerant::<ProviderConfig>(&root.join("providers"));
2586 for (path, e) in skipped {
2587 tracing::warn!(
2588 "infra source {:?} ({}): skipping unparseable provider {}: {e:#}",
2589 source.owner,
2590 root.display(),
2591 path.display()
2592 );
2593 }
2594 for p in foreign_providers {
2595 if seen_provider_ids.contains(&p.id) {
2596 continue;
2597 }
2598 seen_provider_ids.insert(p.id.clone());
2599 provider_origins.insert(p.id.clone(), origin.clone());
2600 providers.push(p);
2601 }
2602 }
2603}
2604
2605/// One component of a [`ServiceConfig`]. The `kind` (e.g. `"mesofact-static"`,
2606/// `"almanac"`, `"container"`) selects which reconciler runs against the
2607/// pointed-at workload manifest.
2608#[derive(Debug, Clone, Serialize, Deserialize)]
2609#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2610pub struct ServiceComponent {
2611 pub id: String,
2612 pub kind: String,
2613 /// Path of the directory holding this component's `workload.toml`. Relative
2614 /// to the workspace root for in-tree components, or to the materialized
2615 /// `<checkout>/<subdir>` when [`git`](Self::git) is set.
2616 pub path: String,
2617 /// Optional external git source (R561-F1). When set, the component's code
2618 /// is materialized by shallow-clone before build; see [`GitSource`].
2619 #[serde(default, skip_serializing_if = "Option::is_none")]
2620 pub git: Option<GitSource>,
2621 /// Operator-facing role label, e.g. `"static"`, `"dynamic"`, `"compute"`.
2622 pub role: String,
2623 /// Optional artifact kind this component publishes (`"static"`,
2624 /// `"container-image"`, …). Drives mirror provider-slot routing.
2625 #[serde(default, skip_serializing_if = "Option::is_none")]
2626 pub publishes: Option<String>,
2627 /// URL sub-path a static component's build output is published under,
2628 /// relative to the service's publish prefix (R746). `None` = the service
2629 /// root, which is what every pre-R746 component means.
2630 ///
2631 /// Static publishers lay a component's `out_dir` down at
2632 /// `<bucket>/<service>/<env>/…` and the front door fetches
2633 /// `${ASSET_ORIGIN}/<request path>` — the request path *is* the key. So a
2634 /// service with two static components had them overwrite each other at
2635 /// one prefix, and there was no way to say "this bundle serves under
2636 /// /app". `mount` is that: it appends to the publish prefix, which makes
2637 /// the URL sub-path and the storage sub-path the same string by
2638 /// construction rather than by two manifests agreeing.
2639 ///
2640 /// Cross-checked against the domain route that names the component
2641 /// ([`CloudConfig::cross_ref_validate`]): a component mounted at `/app`
2642 /// must be routed at `/app` or `/app/*`, because a disagreement means
2643 /// requests land on a prefix nothing published to — a 404 whose cause is
2644 /// two files apart.
2645 #[serde(default, skip_serializing_if = "Option::is_none")]
2646 pub mount: Option<String>,
2647 /// Sync-wave index (0-based). Components in wave 0 roll out in parallel
2648 /// first; the reconciler waits for all wave-N components to become healthy
2649 /// before starting wave N+1. Defaults to 0 (all components in one wave).
2650 #[serde(default, skip_serializing_if = "is_zero_u32")]
2651 pub wave: u32,
2652}
2653
2654#[inline]
2655fn is_zero_u32(n: &u32) -> bool {
2656 *n == 0
2657}
2658
2659/// A service's declared databases, grouped by environment (W241 §Sections).
2660/// Parsed from the `[db]` table of `service.toml`; each `[[db.<env>]]` array
2661/// entry names one database. The environment tag drives backend selection at
2662/// query time (see the data-workbench's `db.query` / the `sql_*` MCP tools):
2663/// `dev` = local file, `pond` = a DB inside the running pond container stack
2664/// (reached on a declared localhost port), `cloud` = a remote libSQL/Turso or
2665/// Postgres endpoint whose auth comes from an env var (never stored in TOML).
2666#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
2667#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2668pub struct DbCatalog {
2669 /// Local-file SQLite databases used in dev mode.
2670 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2671 pub dev: Vec<DevDb>,
2672 /// Databases running inside the pond container stack.
2673 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2674 pub pond: Vec<PondDb>,
2675 /// Remote cloud databases (Turso, Postgres).
2676 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2677 pub cloud: Vec<CloudDb>,
2678}
2679
2680impl DbCatalog {
2681 /// True when no database is declared in any environment. Lets
2682 /// [`ServiceConfig`] skip serializing an empty `[db]` table.
2683 pub fn is_empty(&self) -> bool {
2684 self.dev.is_empty() && self.pond.is_empty() && self.cloud.is_empty()
2685 }
2686}
2687
2688/// A dev-mode local SQLite database (`[[db.dev]]`). `path` is resolved
2689/// relative to the workspace root and opened as a local file — read/write, no
2690/// network, no auth.
2691#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2692#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2693pub struct DevDb {
2694 /// Logical name, unique within the service's `dev` list. Forms the `name`
2695 /// segment of the catalog id `dev:<service>:<name>`.
2696 pub name: String,
2697 /// On-disk SQLite path, relative to the workspace root (or absolute).
2698 pub path: String,
2699}
2700
2701/// A database running inside the pond container stack (`[[db.pond]]`). The
2702/// pond publishes the DB on a localhost TCP port; the hub connects to
2703/// `127.0.0.1:<port>` when the pond is up and returns a clear error when it is
2704/// not. Either `port` (defaulting to a libSQL/`sqld` HTTP endpoint) or a full
2705/// `url` must be given.
2706#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2707#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2708pub struct PondDb {
2709 /// Logical name, unique within the service's `pond` list.
2710 pub name: String,
2711 /// Localhost TCP port the pond publishes the DB on. Interpreted per
2712 /// [`kind`](Self::kind). Mutually complete with `url` (provide one).
2713 #[serde(default, skip_serializing_if = "Option::is_none")]
2714 pub port: Option<u16>,
2715 /// Full connection URL, overriding `port` when set (e.g. a non-localhost
2716 /// host or an explicit scheme).
2717 #[serde(default, skip_serializing_if = "Option::is_none")]
2718 pub url: Option<String>,
2719 /// Wire protocol the pond DB speaks. Selects how a bare `port` becomes a
2720 /// URL: `turso` → `http://127.0.0.1:<port>` (libSQL/`sqld` over Hrana),
2721 /// `postgres` → `postgres://127.0.0.1:<port>`.
2722 #[serde(default)]
2723 pub kind: PondDbKind,
2724}
2725
2726/// Wire protocol of a [`PondDb`].
2727#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2728#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2729#[serde(rename_all = "kebab-case")]
2730pub enum PondDbKind {
2731 /// libSQL / `sqld` over Hrana HTTP — the default.
2732 #[default]
2733 Turso,
2734 /// PostgreSQL wire protocol.
2735 Postgres,
2736}
2737
2738/// A remote cloud database (`[[db.cloud]]`). The connection `url` is stored in
2739/// TOML but the credential never is — `auth_token_env` names an environment
2740/// variable the daemon reads at connect time, so the same declaration works
2741/// whether the token is provisioned service-locally or camp-shared (W241;
2742/// operator confirmed both scopes are needed). A camp-wide cloud DB not owned
2743/// by any single service is declared identically in `.yah/db/cloud.toml`.
2744#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2745#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2746pub struct CloudDb {
2747 /// Logical name, unique within its `cloud` list.
2748 pub name: String,
2749 /// Connection URL: `libsql://…` / `http(s)://…` (Turso, `sqld`) or
2750 /// `postgres://…`.
2751 pub url: String,
2752 /// Name of the environment variable holding the auth token. Resolved in
2753 /// the daemon at connect time (value never stored on disk). For a libSQL
2754 /// URL the token is threaded as `?auth_token=…`.
2755 #[serde(default, skip_serializing_if = "Option::is_none")]
2756 pub auth_token_env: Option<String>,
2757}
2758
2759/// A camp-shared cloud database catalog, parsed from `.yah/db/cloud.toml`.
2760/// These are cloud DBs not owned by any single service — declared once at camp
2761/// scope and addressed as `cloud:<name>` (two-segment id), distinct from a
2762/// service-local `cloud:<service>:<name>`.
2763#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
2764#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2765pub struct CampCloudDbs {
2766 #[serde(default, rename = "cloud", skip_serializing_if = "Vec::is_empty")]
2767 pub cloud: Vec<CloudDb>,
2768}
2769
2770impl CampCloudDbs {
2771 /// Load `<camp_root>/.yah/db/cloud.toml`, or an empty catalog if the file
2772 /// is absent (the common case — most camps declare no shared cloud DBs).
2773 pub fn load(camp_root: &Path) -> Result<Self> {
2774 let path = camp_root.join(".yah/db/cloud.toml");
2775 if !path.exists() {
2776 return Ok(Self::default());
2777 }
2778 let src = std::fs::read_to_string(&path)
2779 .with_context(|| format!("reading {}", path.display()))?;
2780 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
2781 }
2782}
2783
2784/// Topological shape of a mirror — how its providers sit relative to each other.
2785#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2786#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2787#[serde(rename_all = "kebab-case")]
2788pub enum MirrorShape {
2789 /// Single machine hosts compute (and any non-Cloudflare-fronted static).
2790 SingleMachine,
2791 /// Operator-local dev mirror — static via built-in file server, compute
2792 /// via the local container runtime.
2793 Local,
2794 /// Multi-machine deployment (machines listed per provider slot).
2795 MultiMachine,
2796}
2797
2798/// Which public-ingress provider fronts this mirror's compute (W267, R594-F11).
2799///
2800/// Both arms answer exactly one question — *given these local workload ports,
2801/// make them publicly reachable at these hostnames* — and they differ only in
2802/// where the ingress rules live and who supervises the front door:
2803///
2804/// | | [`CloudflareTunnel`](Self::CloudflareTunnel) | [`Passway`](Self::Passway) |
2805/// |---|---|---|
2806/// | Ingress rules live | Cloudflare's API (token-form tunnels are remotely-managed) | the pingora `Backends` set in the proxy process |
2807/// | How they get there | an API call per deployed workload | passway polls `GET /service-records?ready=true` |
2808/// | Front door lifecycle | a kamaji-supervised `cloudflared` appliance | a kamaji-supervised passway appliance |
2809///
2810/// Flipping this field is the whole tier ladder: rented edge → sovereign edge
2811/// is a one-line mirror edit, not a rewrite. The provider owns **addressing**
2812/// and never **rendering** — the W173 render cube stays in mesofact's manifest.
2813#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
2814#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2815#[serde(rename_all = "kebab-case")]
2816pub enum IngressProvider {
2817 /// No public front door for this mirror. The default: a mirror that
2818 /// publishes to R2 behind a Worker, or a mesh-only compute tier, has no
2819 /// ingress provider to reconcile.
2820 #[default]
2821 None,
2822 /// Rented edge — `cloudflared` dials *out* from the node to Cloudflare's
2823 /// edge. Zero inbound ports, no TLS to manage on the box, hostname rules
2824 /// held in Cloudflare's API.
2825 CloudflareTunnel,
2826 /// Sovereign edge — passway terminates TLS on the node and load-balances
2827 /// an upstream set discovered from yubaba's service records.
2828 Passway,
2829}
2830
2831impl IngressProvider {
2832 /// `true` when this mirror declares a front door that has to be reconciled.
2833 pub fn is_declared(self) -> bool {
2834 !matches!(self, Self::None)
2835 }
2836
2837 /// Kebab-case wire name, as it appears in `mirrors/<env>.toml`.
2838 pub fn as_str(self) -> &'static str {
2839 match self {
2840 Self::None => "none",
2841 Self::CloudflareTunnel => "cloudflare-tunnel",
2842 Self::Passway => "passway",
2843 }
2844 }
2845}
2846
2847/// One declared **edge**: a front door, the slots it fronts, and the nodes it
2848/// is placed on (W305 F2).
2849///
2850/// A mirror declares a *list* of these, which is what lets one service mix
2851/// front doors — cloudflare for the public web tier, passway for an internal or
2852/// high-throughput one. Before this, [`MirrorConfig::ingress`] was a single
2853/// [`IngressProvider`], so a mirror could **swap** front doors but never mix
2854/// them.
2855///
2856/// ```toml
2857/// [[ingress]]
2858/// provider = "passway"
2859/// machines = ["us-east-001", "us-south-001"]
2860/// slots = ["bundle"]
2861///
2862/// [[ingress]]
2863/// provider = "cloudflare-tunnel"
2864/// hostnames = ["issues.yah.dev"]
2865/// ```
2866///
2867/// **The per-node appliance is derived from this, never declared beside it.**
2868/// An edge does invoke a cloudflared or passway process on a box, but that is a
2869/// *consequence* of the service's declaration:
2870/// [`collate_front_doors`](crate::reconciler::collate_front_doors) walks every
2871/// service and derives what each node must run. Declaring it node-side too is
2872/// what produces two sources of truth for one fact.
2873#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2874#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2875pub struct IngressEdge {
2876 /// Which front door this edge is. [`IngressProvider::None`] is rejected at
2877 /// plan time — an edge that fronts with nothing is always a typo, never an
2878 /// intent (write no edge instead).
2879 pub provider: IngressProvider,
2880 /// Nodes this front door is placed on — **independent of where the fronted
2881 /// workload runs** (R330-F37).
2882 ///
2883 /// Empty falls back to the fronted slot's own `machine` / `machines`, which
2884 /// is the co-located shape every mirror had before front-door placement was
2885 /// expressible. Listing several is what lets the ingress tier and the
2886 /// service tier scale independently: **N front doors over ONE deployment**,
2887 /// one rendered copy, so no cache coherence to settle.
2888 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2889 pub machines: Vec<String>,
2890 /// Provider slot roles this edge fronts (`"bundle"`, `"compute"`, …).
2891 ///
2892 /// One of the two selectors. With a single edge both may be empty, meaning
2893 /// "every fronted slot" — the legacy shape. With **several** edges a
2894 /// selector is mandatory on each, and the partition must be total and
2895 /// disjoint: a slot claimed by no edge, or by two, is an error naming it.
2896 /// An implicit catch-all across mixed front doors would silently publish a
2897 /// service through the wrong one.
2898 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2899 pub slots: Vec<String>,
2900 /// Public hostnames this edge fronts — the other selector, for partitioning
2901 /// by what the world dials rather than by which slot serves it.
2902 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2903 pub hostnames: Vec<String>,
2904 /// Cloudflare Tunnel id this edge publishes through, overriding the
2905 /// fronting machine's [`MachineConfig::cloudflared`].
2906 ///
2907 /// This is W267 Gap 3's real fix, and it is the *service* side of it: a node
2908 /// can join two cohorts' orange networks, and since §Granularity argues the
2909 /// tunnel credential **is** the isolation boundary, which cohort a given
2910 /// service fronts through is a property of the service, not of the box.
2911 /// `MachineConfig.cloudflared` stays as the per-node default (one tunnel is
2912 /// the common case, and the credential does live on the node), but it is no
2913 /// longer the only way to say it — so the node never has to enumerate
2914 /// cohorts.
2915 #[serde(default, skip_serializing_if = "Option::is_none")]
2916 pub tunnel_id: Option<String>,
2917}
2918
2919impl IngressEdge {
2920 /// An edge with no selector — fronts every fronted slot, legal only when it
2921 /// is the mirror's only edge.
2922 pub fn all_slots(provider: IngressProvider, machines: Vec<String>) -> Self {
2923 Self {
2924 provider,
2925 machines,
2926 slots: Vec::new(),
2927 hostnames: Vec::new(),
2928 tunnel_id: None,
2929 }
2930 }
2931
2932 /// `true` when this edge names which slots/hostnames it fronts.
2933 pub fn has_selector(&self) -> bool {
2934 !self.slots.is_empty() || !self.hostnames.is_empty()
2935 }
2936
2937 /// Does this edge claim the rule derived from `slot` publishing `hostname`?
2938 ///
2939 /// A selectorless edge claims everything; that is checked to be
2940 /// unambiguous (one edge only) before this is consulted.
2941 pub fn claims(&self, slot: &str, hostname: &str) -> bool {
2942 if !self.has_selector() {
2943 return true;
2944 }
2945 self.slots.iter().any(|s| s == slot) || self.hostnames.iter().any(|h| h == hostname)
2946 }
2947
2948 /// Human-readable identity for an error message — the provider plus
2949 /// whichever selector was written.
2950 pub fn label(&self) -> String {
2951 let sel = match (self.slots.is_empty(), self.hostnames.is_empty()) {
2952 (true, true) => "no selector".to_string(),
2953 (false, true) => format!("slots = {:?}", self.slots),
2954 (true, false) => format!("hostnames = {:?}", self.hostnames),
2955 (false, false) => format!("slots = {:?} + hostnames = {:?}", self.slots, self.hostnames),
2956 };
2957 format!("[[ingress]] provider = {:?} ({sel})", self.provider.as_str())
2958 }
2959}
2960
2961/// A mirror's `ingress` declaration, in either spelling.
2962///
2963/// The list is the general form; the bare provider is shorthand for the single
2964/// edge fronting everything, and is kept rather than migrated because it is the
2965/// honest spelling for the common case — one service, one front door. Both
2966/// normalize to the same `Vec<IngressEdge>` through
2967/// [`MirrorConfig::ingress_edges`], so nothing downstream branches on which was
2968/// written.
2969#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2970#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
2971#[serde(untagged)]
2972pub enum IngressDecl {
2973 /// `ingress = "passway"` — one edge fronting every fronted slot, placed by
2974 /// the sibling [`MirrorConfig::ingress_machines`].
2975 Provider(IngressProvider),
2976 /// `[[ingress]]` — one entry per declared edge.
2977 Edges(Vec<IngressEdge>),
2978}
2979
2980/// Hand-written because `#[serde(untagged)]` throws the real error away.
2981///
2982/// A derived untagged `Deserialize` tries each variant and, on failure, reports
2983/// only `data did not match any variant of untagged enum IngressDecl` — so a
2984/// misspelled `provider = "passwya"` says nothing about providers, nothing about
2985/// the legal values, and points at the `[[ingress]]` header rather than the
2986/// field. Dispatching on the input shape first means each arm's own error
2987/// survives: a bad string names the legal provider vocabulary, a bad edge table
2988/// names the offending field.
2989impl<'de> Deserialize<'de> for IngressDecl {
2990 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
2991 struct DeclVisitor;
2992
2993 impl<'de> serde::de::Visitor<'de> for DeclVisitor {
2994 type Value = IngressDecl;
2995
2996 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
2997 f.write_str(
2998 "a provider name (`ingress = \"passway\"`) or a list of edge tables \
2999 (`[[ingress]]`)",
3000 )
3001 }
3002
3003 fn visit_str<E: serde::de::Error>(self, v: &str) -> std::result::Result<Self::Value, E> {
3004 IngressProvider::deserialize(serde::de::value::StrDeserializer::new(v))
3005 .map(IngressDecl::Provider)
3006 }
3007
3008 fn visit_seq<A: serde::de::SeqAccess<'de>>(
3009 self,
3010 seq: A,
3011 ) -> std::result::Result<Self::Value, A::Error> {
3012 Vec::<IngressEdge>::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
3013 .map(IngressDecl::Edges)
3014 }
3015 }
3016
3017 d.deserialize_any(DeclVisitor)
3018 }
3019}
3020
3021/// No front door — the shape of every mirror that publishes to R2 behind a
3022/// Worker, or runs a mesh-only compute tier.
3023impl Default for IngressDecl {
3024 fn default() -> Self {
3025 Self::Provider(IngressProvider::None)
3026 }
3027}
3028
3029impl IngressDecl {
3030 /// `true` when this mirror declares no front door at all.
3031 pub fn is_absent(&self) -> bool {
3032 match self {
3033 Self::Provider(p) => !p.is_declared(),
3034 Self::Edges(e) => e.is_empty(),
3035 }
3036 }
3037}
3038
3039impl From<IngressProvider> for IngressDecl {
3040 fn from(p: IngressProvider) -> Self {
3041 Self::Provider(p)
3042 }
3043}
3044
3045/// A service mirror — the projection of a [`ServiceConfig`] onto concrete
3046/// infra. Lives at `.yah/services/<svc>/mirrors/<env>.toml`.
3047#[derive(Debug, Clone, Serialize, Deserialize)]
3048#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3049pub struct MirrorConfig {
3050 pub schema_version: u32,
3051 pub shape: MirrorShape,
3052 /// Public-ingress edges fronting this mirror (W267, W305 F2). Defaults to
3053 /// none.
3054 ///
3055 /// Two spellings, one meaning — see [`IngressDecl`]. `ingress = "passway"`
3056 /// is one edge fronting everything; `[[ingress]]` entries declare several,
3057 /// each naming its provider plus the slots or hostnames it fronts. Read it
3058 /// through [`ingress_edges`](Self::ingress_edges), never by matching on the
3059 /// enum, so the two spellings cannot drift apart.
3060 ///
3061 /// Declared at mirror scope rather than per provider slot because a front
3062 /// door does **fan-in**: one `cloudflared` (or one passway) on a node
3063 /// multiplexes every hostname→port rule it fronts, so pinning one to a
3064 /// single slot would mint one edge connection per slot for no gain. An
3065 /// edge's `slots` selector is the general form of that — it groups slots
3066 /// behind one front door, it does not split a front door per slot.
3067 #[serde(default, skip_serializing_if = "IngressDecl::is_absent")]
3068 pub ingress: IngressDecl,
3069 /// Machines the front door is placed on — **independent of where the
3070 /// fronted workload runs** (R330-F37).
3071 ///
3072 /// The single-edge spelling of [`IngressEdge::machines`]: it applies to the
3073 /// one edge `ingress = "<provider>"` declares, and combining it with
3074 /// `[[ingress]]` entries is an error rather than a silent precedence rule.
3075 ///
3076 /// Empty (the default) keeps the pre-existing behaviour: the front door is
3077 /// co-located with the fronted slot's own `machine` / `machines`. That was
3078 /// never a design choice, it was an artifact of bundles binding
3079 /// `127.0.0.1` — nothing off-node could reach a workload, so a proxy had to
3080 /// sit on top of it. R599-F12 landed mesh binding, which removes the
3081 /// constraint: passway is a reverse proxy, and a valid front door needs a
3082 /// cert and an upstream it can *reach*, not a local copy of the service.
3083 ///
3084 /// Listing several machines is what lets the ingress tier and the service
3085 /// tier scale independently — **N front doors over ONE deployment**. There
3086 /// is still exactly one rendered copy of the site, so fanning the front door
3087 /// out introduces no cache-coherence problem; that only appears if you
3088 /// deploy the *workload* to every node instead.
3089 ///
3090 /// ```toml
3091 /// ingress = "passway"
3092 /// ingress_machines = ["us-east-001", "us-west-001"]
3093 /// ```
3094 ///
3095 /// Declaring this without [`ingress`](Self::ingress) is an error, not a
3096 /// no-op — it always means the operator expected a front door somewhere.
3097 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3098 pub ingress_machines: Vec<String>,
3099 /// Provider slots, keyed by role (`"static"`, `"compute"`, …). Each value
3100 /// either references a provider declared under `.yah/infra/providers/` or
3101 /// inlines a local-only provider (no creds, no infra file).
3102 ///
3103 /// A role is normally service-wide — one slot serves every component that
3104 /// shares it — but [`ReconcileCtx::slot`](crate::reconciler::ReconcileCtx::slot)
3105 /// looks up the component-qualified key `"<role>:<component id>"` first.
3106 /// A service with two components of the same role (e.g. two
3107 /// `mesofact-static` components under one mirror) declares
3108 /// `providers."static:<id>"` per component to give each its own port;
3109 /// omitting the qualifier keeps the pre-existing single-slot behavior.
3110 #[serde(default)]
3111 pub providers: BTreeMap<String, MirrorProviderSlot>,
3112 /// Capability→driver bindings, keyed by **capability** (`"pg"`, `"s3"`, …)
3113 /// rather than by slot role (W265 §Drivers).
3114 ///
3115 /// This is the generalization of [`Self::providers`]: `providers.static` /
3116 /// `providers.object_store` are the special case where the slot name and
3117 /// the capability happen to coincide, and keying by capability is what stops
3118 /// the slot enum growing one arm per tier-specific implementation. A service
3119 /// says "I need pg"; the mirror says which implementation of pg *this tier*
3120 /// uses; the app talks the same wire protocol either way and never forks.
3121 ///
3122 /// ```toml
3123 /// [drivers.pg]
3124 /// kind = "local-pg-dev" # dev — kamaji-supervised loopback postgres
3125 /// ```
3126 ///
3127 /// Additive in P1: `drivers` lands *alongside* `providers`, and migrating
3128 /// the existing `providers.static` / `providers.object_store` declarations
3129 /// over is a separate pass (W265 §"Open follow-ups"). A mirror that declares
3130 /// neither is unchanged.
3131 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
3132 pub drivers: BTreeMap<String, MirrorProviderSlot>,
3133 /// Per-environment alias overrides for `kind = "static-asset"` components.
3134 ///
3135 /// Keys are logical names (e.g. `"whisper-default"`); values must be
3136 /// filenames present in the component's `workload.toml` catalog.
3137 /// **Resolution only** — this table may never introduce a filename absent
3138 /// from the catalog. Validated against the workload catalog at sync time.
3139 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
3140 pub asset_aliases: BTreeMap<String, String>,
3141}
3142
3143impl MirrorConfig {
3144 /// This mirror's declared edges, with both spellings normalized (W305 F2).
3145 ///
3146 /// The single place `ingress` + `ingress_machines` are reconciled, so no
3147 /// consumer has to know which spelling was written. Returns an empty vec
3148 /// when the mirror declares no front door.
3149 ///
3150 /// Errors are the declarations that cannot mean anything:
3151 ///
3152 /// - `ingress_machines` with no `ingress` — front-door placement with no
3153 /// front door to place, always a typo (R330-F37);
3154 /// - `ingress_machines` alongside `[[ingress]]` — placement declared twice,
3155 /// in a form where one silently wins;
3156 /// - `provider = "none"` on an edge — an edge that fronts with nothing.
3157 pub fn ingress_edges(&self) -> Result<Vec<IngressEdge>> {
3158 match &self.ingress {
3159 IngressDecl::Provider(p) if !p.is_declared() => {
3160 if !self.ingress_machines.is_empty() {
3161 bail!(
3162 "mirror declares `ingress_machines = {:?}` but no `ingress` provider — \
3163 front-door placement with no front door to place. Add \
3164 `ingress = \"passway\"` (or \"cloudflare-tunnel\"), or drop \
3165 `ingress_machines`.",
3166 self.ingress_machines
3167 );
3168 }
3169 Ok(Vec::new())
3170 }
3171 IngressDecl::Provider(p) => Ok(vec![IngressEdge::all_slots(
3172 *p,
3173 self.ingress_machines.clone(),
3174 )]),
3175 IngressDecl::Edges(edges) => {
3176 if !self.ingress_machines.is_empty() {
3177 bail!(
3178 "mirror declares both `[[ingress]]` edges and the single-edge \
3179 `ingress_machines = {:?}` — front-door placement stated twice. Move \
3180 those names onto the edge they place: `machines = [...]` inside the \
3181 `[[ingress]]` entry.",
3182 self.ingress_machines
3183 );
3184 }
3185 for edge in edges {
3186 if !edge.provider.is_declared() {
3187 bail!(
3188 "{}: `provider = \"none\"` fronts nothing. An edge exists to name a \
3189 front door — delete the entry instead.",
3190 edge.label()
3191 );
3192 }
3193 }
3194 Ok(edges.clone())
3195 }
3196 }
3197 }
3198
3199 /// Parse a single `mirrors/<env>.toml` file.
3200 pub fn load(path: &Path) -> Result<Self> {
3201 let src =
3202 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
3203 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))
3204 }
3205
3206 /// Persist to `.yah/services/<service>/mirrors/<env>.toml`, creating the
3207 /// `mirrors/` directory if needed. Create-or-overwrite. The mirror file is
3208 /// named by `env` (its stem); `service` selects the owning service dir.
3209 pub fn save(&self, workspace_root: &Path, service: &str, env: &str) -> Result<()> {
3210 let dir = crate::paths::service_mirrors_dir(workspace_root, service);
3211 std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
3212 let path = crate::paths::service_mirror_toml(workspace_root, service, env);
3213 let s = toml::to_string_pretty(self)
3214 .with_context(|| format!("serializing mirror {service}/{env}"))?;
3215 std::fs::write(&path, s).with_context(|| format!("writing {}", path.display()))
3216 }
3217
3218 /// Remove `.yah/services/<service>/mirrors/<env>.toml`. Returns `false`
3219 /// when the file was already absent. Leaves the service and its other
3220 /// mirrors untouched.
3221 ///
3222 /// Also checks legacy stems (e.g. `local-sim` when `env = "pond"`) so
3223 /// deleting a canonical tier name removes whichever file exists on disk.
3224 pub fn delete(workspace_root: &Path, service: &str, env: &str) -> Result<bool> {
3225 let path = crate::paths::service_mirror_toml(workspace_root, service, env);
3226 if path.exists() {
3227 std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
3228 return Ok(true);
3229 }
3230 // Try legacy file stems for canonical tier names.
3231 let legacy: &[&str] = match env {
3232 "dev" => &["local"],
3233 "pond" => &["local-sim", "sim"],
3234 "cloud" => &["prod"],
3235 _ => &[],
3236 };
3237 for stem in legacy {
3238 let alt = crate::paths::service_mirror_toml(workspace_root, service, stem);
3239 if alt.exists() {
3240 std::fs::remove_file(&alt)
3241 .with_context(|| format!("removing {}", alt.display()))?;
3242 return Ok(true);
3243 }
3244 }
3245 Ok(false)
3246 }
3247}
3248
3249/// A provider slot inside a [`MirrorConfig`]. Two shapes:
3250/// - **Reference** (`use = "<provider-id>"`) — point at an infra-declared
3251/// provider; extra fields are slot-specific (bucket, zone, dns, …).
3252/// - **Inline** (`kind = "local-*"`) — for providers that need no infra
3253/// declaration because they carry no credentials.
3254#[derive(Debug, Clone, Serialize, Deserialize)]
3255#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3256#[serde(untagged)]
3257pub enum MirrorProviderSlot {
3258 Reference {
3259 #[serde(rename = "use")]
3260 provider_id: String,
3261 #[serde(flatten)]
3262 #[cfg_attr(
3263 feature = "json-schema",
3264 schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
3265 )]
3266 fields: BTreeMap<String, toml::Value>,
3267 },
3268 Inline {
3269 kind: Provider,
3270 #[serde(flatten)]
3271 #[cfg_attr(
3272 feature = "json-schema",
3273 schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
3274 )]
3275 fields: BTreeMap<String, toml::Value>,
3276 },
3277}
3278
3279impl MirrorProviderSlot {
3280 /// Provider id this slot references, or `None` for inline slots.
3281 pub fn provider_id(&self) -> Option<&str> {
3282 match self {
3283 Self::Reference { provider_id, .. } => Some(provider_id),
3284 Self::Inline { .. } => None,
3285 }
3286 }
3287
3288 /// Provider kind for inline slots, or `None` for reference slots
3289 /// (resolve via the referenced [`ProviderConfig`]).
3290 pub fn inline_kind(&self) -> Option<Provider> {
3291 match self {
3292 Self::Reference { .. } => None,
3293 Self::Inline { kind, .. } => Some(*kind),
3294 }
3295 }
3296
3297 pub fn fields(&self) -> &BTreeMap<String, toml::Value> {
3298 match self {
3299 Self::Reference { fields, .. } | Self::Inline { fields, .. } => fields,
3300 }
3301 }
3302
3303 /// F16 placement: parse the optional `required = { … }` sub-table on this
3304 /// slot. Returns `None` when absent or unparseable (callers treat as no
3305 /// constraint). See [`RequiredSpec`] for the field grammar.
3306 pub fn required(&self) -> Option<RequiredSpec> {
3307 let v = self.fields().get("required")?.clone();
3308 v.try_into().ok()
3309 }
3310}
3311
3312/// F16 placement constraints declared on a [`MirrorProviderSlot`], lives under
3313/// `[providers.<role>] required = { regions = [...], mesh_tags = [...] }` in
3314/// `mirrors/<env>.toml`.
3315///
3316/// Hard (must-satisfy) axes, all AND-ed together:
3317/// - `regions` / `zones` / `providers` — *membership*: the machine's
3318/// `region` / `zone` / `provider` must be one of the listed values.
3319/// - `mesh_tags` — *superset*: the machine's `mesh_tags` must contain every
3320/// listed tag.
3321/// - `memory_mb` / `cpu_millis` — *capacity floor* (R572-F5): the machine's
3322/// `allocatable` budget must cover the demand. `0` = no constraint.
3323/// - `repel_archetype` — *taint repulsion* (R572-F5): the machine must not
3324/// carry the taint `"no-<archetype.taint_key()>"` for the workload's class.
3325/// `None` = no repulsion check. Absolute — see [`Self::repel_archetype`].
3326/// - `requires_taint` — *taint affinity* (R572-F5): the machine must carry
3327/// this taint key (in `taints` or `mesh_tags`). `None` = no affinity.
3328///
3329/// These two are the **only** readers of [`MachineConfig::taints`], which is
3330/// what makes [`taint_effect`]'s closed vocabulary well-founded.
3331///
3332/// [`MachineConfig::sovereign_group`] is deliberately **not** an axis here and
3333/// must not become one (W305/R742-F1). A sovereign group is a blast radius,
3334/// not a filter: which quorum a box votes in says nothing about whether a
3335/// workload may run on it, and a dev-group node exists precisely so dev-mode
3336/// services — stateful ones included — can be scheduled onto it. Filtering on
3337/// it would re-make the mistake W305 exists to undo, where one mechanism
3338/// silently carried three unrelated properties.
3339///
3340/// An empty / zero / None on every axis means "no constraint on that axis".
3341/// A fully-unconstrained `RequiredSpec` matches every machine (see
3342/// [`RequiredSpec::is_unconstrained`]).
3343#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3344#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3345pub struct RequiredSpec {
3346 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3347 pub regions: Vec<String>,
3348 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3349 pub zones: Vec<String>,
3350 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3351 pub providers: Vec<String>,
3352 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3353 pub mesh_tags: Vec<String>,
3354
3355 /// R833-F8: **imperative** placement — the machine must be one of these by
3356 /// `name`. Empty (the default) = no constraint, which is every pre-R833-F8
3357 /// caller.
3358 ///
3359 /// This is the one axis that is not a *capability* the scheduler infers.
3360 /// The operator typed `--where=node:us-west-003`, so it composes with the
3361 /// other axes exactly like the rest — a named node that fails the capacity
3362 /// floor or carries a repelling taint still does not match, and the refusal
3363 /// names why rather than silently placing the work somewhere else.
3364 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3365 pub nodes: Vec<String>,
3366
3367 /// R572-F5: minimum memory (MiB) the target node must have in its
3368 /// declared `allocatable` budget. `0` = no constraint. Filled by
3369 /// [`CloudConfig::admit_workload`] from the workload's
3370 /// `memory_request_mb()` — its placement **request**, which is not the
3371 /// same number as the `resources.memory_mb` cgroup **ceiling**.
3372 #[serde(default, skip_serializing_if = "is_zero_u32")]
3373 pub memory_mb: u32,
3374 /// R572-F5: minimum CPU (millicores) the target node must have in its
3375 /// declared `allocatable` budget. `0` = no constraint. Filled by
3376 /// [`CloudConfig::admit_workload`] from the workload's `resources.cpu_millis`.
3377 #[serde(default, skip_serializing_if = "is_zero_u32")]
3378 pub cpu_millis: u32,
3379 /// R572-F5: effective archetype of the workload being placed. The scheduler
3380 /// rejects any node that carries the taint `"no-<archetype.taint_key()>"`.
3381 /// `None` = no repulsion check (backwards-compat for callers that don't
3382 /// thread a spec through).
3383 ///
3384 /// **This is an absolute block, not a preference.**
3385 /// [`CloudConfig::admit_workload`] sets it unconditionally from the
3386 /// workload's effective archetype, and nothing in the tree tolerates a
3387 /// taint — so a workload cannot opt out of a `no-<archetype>` node
3388 /// (W305 finding 2 / R742-T4). Adding toleration means giving
3389 /// `WorkloadSpec` a tolerations list and consulting it here; until then,
3390 /// do not describe this as "repel-unless-tolerate".
3391 #[serde(skip)]
3392 pub repel_archetype: Option<LifecycleArchetype>,
3393 /// R572-F5: taint the workload requires the target node to carry
3394 /// (annotation `yah.placement.requires-taint`). The node must have the
3395 /// key in its `taints` list or `mesh_tags`. `None` = no affinity constraint.
3396 #[serde(skip)]
3397 pub requires_taint: Option<String>,
3398}
3399
3400impl RequiredSpec {
3401 /// True when no axis carries a constraint — every machine matches.
3402 pub fn is_unconstrained(&self) -> bool {
3403 self.regions.is_empty()
3404 && self.zones.is_empty()
3405 && self.providers.is_empty()
3406 && self.mesh_tags.is_empty()
3407 && self.nodes.is_empty()
3408 && self.memory_mb == 0
3409 && self.cpu_millis == 0
3410 && self.repel_archetype.is_none()
3411 && self.requires_taint.is_none()
3412 }
3413
3414 /// Whether `machine` satisfies every hard axis.
3415 ///
3416 /// - Membership axes (region/zone/provider): machine must carry the field
3417 /// and it must appear in the constraint list.
3418 /// - `mesh_tags`: machine tags must be a superset of the required set.
3419 /// - **R572-F5 capacity floor**: `machine.allocatable.{memory,cpu}` must
3420 /// cover `self.{memory,cpu}`. A machine with no `allocatable` block passes
3421 /// unconditionally (capacity unknown → no constraint enforced).
3422 /// - **R572-F5 taint repulsion**: machine must not carry the taint
3423 /// `"no-<archetype.taint_key()>"` for the workload's class. Absolute —
3424 /// the workload has no way to tolerate it (W305 finding 2).
3425 /// - **R572-F5 taint affinity**: if `requires_taint` is set, the machine
3426 /// must carry that key in its `taints` list or `mesh_tags`.
3427 ///
3428 /// Any *other* taint on the machine is ignored here, which is precisely
3429 /// why [`crate::validate::check_inert_taints`] refuses to let one be
3430 /// declared: it would read as a constraint and be none.
3431 pub fn matches(&self, machine: &MachineConfig) -> bool {
3432 let member_ok = |constraint: &[String], value: Option<&str>| -> bool {
3433 constraint.is_empty() || value.map_or(false, |v| constraint.iter().any(|c| c == v))
3434 };
3435
3436 // R833-F8: imperative node pin, checked first because it is the axis a
3437 // human asserted rather than one the scheduler derived — a refusal
3438 // should read "us-west-003 does not match" and not lead with a tag set
3439 // the operator never typed.
3440 if !member_ok(&self.nodes, Some(machine.name.as_str())) {
3441 return false;
3442 }
3443
3444 // Membership + mesh-tags (pre-existing axes).
3445 if !member_ok(&self.regions, machine.region.as_deref())
3446 || !member_ok(&self.zones, machine.zone.as_deref())
3447 || !member_ok(&self.providers, Some(machine.provider.as_str()))
3448 || !self
3449 .mesh_tags
3450 .iter()
3451 .all(|t| machine.mesh_tags.iter().any(|mt| mt == t))
3452 {
3453 return false;
3454 }
3455
3456 // R572-F5: capacity floor. Skipped when machine has no allocatable
3457 // declaration (unknown capacity → passes, consistent with pre-F5 behaviour).
3458 if self.memory_mb > 0 || self.cpu_millis > 0 {
3459 if let Some(alloc) = &machine.allocatable {
3460 if self.memory_mb > alloc.memory_mb || self.cpu_millis > alloc.cpu_millis {
3461 return false;
3462 }
3463 }
3464 }
3465
3466 // R572-F5: taint repulsion. A node taint "no-<archetype>" rejects the
3467 // workload class outright — there is no toleration list to consult.
3468 if let Some(arch) = self.repel_archetype {
3469 let repel_key = format!("no-{}", arch.taint_key());
3470 if machine.taints.iter().any(|t| *t == repel_key) {
3471 return false;
3472 }
3473 }
3474
3475 // R572-F5: taint affinity. Machine must carry the required taint key
3476 // in either its `taints` list or `mesh_tags`.
3477 if let Some(req) = &self.requires_taint {
3478 let has_it = machine.taints.iter().any(|t| t == req)
3479 || machine.mesh_tags.iter().any(|t| t == req);
3480 if !has_it {
3481 return false;
3482 }
3483 }
3484
3485 true
3486 }
3487
3488 /// Human-readable summary of the constraints, for fail-loud error messages.
3489 /// Example: `required.regions=[us-west] + required.mesh_tags=[tag:cloud-runner]`.
3490 pub fn describe(&self) -> String {
3491 let mut parts = Vec::new();
3492 let mut push = |label: &str, vals: &[String]| {
3493 if !vals.is_empty() {
3494 parts.push(format!("required.{label}=[{}]", vals.join(",")));
3495 }
3496 };
3497 push("nodes", &self.nodes);
3498 push("regions", &self.regions);
3499 push("zones", &self.zones);
3500 push("providers", &self.providers);
3501 push("mesh_tags", &self.mesh_tags);
3502 if self.memory_mb > 0 {
3503 parts.push(format!("memory_mb>={}", self.memory_mb));
3504 }
3505 if self.cpu_millis > 0 {
3506 parts.push(format!("cpu_millis>={}", self.cpu_millis));
3507 }
3508 if let Some(arch) = self.repel_archetype {
3509 parts.push(format!("not-tainted(no-{})", arch.taint_key()));
3510 }
3511 if let Some(req) = &self.requires_taint {
3512 parts.push(format!("requires_taint={req}"));
3513 }
3514 if parts.is_empty() {
3515 "no constraints".to_string()
3516 } else {
3517 parts.join(" + ")
3518 }
3519 }
3520}
3521
3522/// Which front door actually serves a domain's requests (R594-F12).
3523///
3524/// Every domain manifest must say this out loud. Before it existed the
3525/// difference between "R2 serves this hostname directly" and "a Worker
3526/// serves it" was expressed *only* by whether the file happened to carry
3527/// `[[routes]]` — so binding a route-carrying domain straight to R2 was
3528/// accepted silently and served 200s on its SSG half while losing clean
3529/// URLs, SPA shell fallback, deferred-route pointers and branded error
3530/// pages. All of those live in the Worker
3531/// (`oss/mesofact/packages/mesofact-edge/src/router.ts`) or in
3532/// mesofact-serve; an R2 custom domain has none of them.
3533///
3534/// The vocabulary mirrors `scripts/cf-apex-mode.sh` (worker | grey | orange)
3535/// — this moves the choice into the config where it can be checked instead
3536/// of living in one bash script.
3537///
3538/// A front door does **fan-in** only. The render cube (SSG / SPA / SSR /
3539/// deferred / 404) is mesofact's manifest, not this one — see W173 and
3540/// `.yah/docs/working/W267-sovereign-public-ingress.md`
3541/// §"Two front doors, one render contract".
3542#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3543#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3544#[serde(rename_all = "kebab-case")]
3545pub enum FrontDoor {
3546 /// Cloudflare R2 custom domain. Requests hit R2 objects with edge
3547 /// caching and nothing else — no clean URLs, no SPA fallback, no
3548 /// branded errors. Correct for a pure asset tier (W175's verdict for
3549 /// `cdn.yah.dev`) and wrong for anything that renders pages.
3550 /// Implies zero `[[routes]]` and no `worker_bundle_path`.
3551 BucketDirect,
3552 /// Cloudflare Worker generated from this manifest's route table.
3553 Worker,
3554 /// Sovereign L7 ingress — the `passway` proxy on yah-owned metal
3555 /// (`oss/passway`, W267). Same route table as `worker`; different
3556 /// machine terminates TLS.
3557 Passway,
3558}
3559
3560impl FrontDoor {
3561 /// Whether this front door consumes the manifest's `[[routes]]` table.
3562 /// `bucket-direct` does not; the other two are nothing without it.
3563 pub fn is_route_driven(self) -> bool {
3564 matches!(self, FrontDoor::Worker | FrontDoor::Passway)
3565 }
3566
3567 /// The manifest spelling, for error messages.
3568 pub fn as_str(self) -> &'static str {
3569 match self {
3570 FrontDoor::BucketDirect => "bucket-direct",
3571 FrontDoor::Worker => "worker",
3572 FrontDoor::Passway => "passway",
3573 }
3574 }
3575}
3576
3577/// A routing manifest for one domain, from `.yah/domains/<name>.toml`.
3578///
3579/// The domain manifest is the *only* place that knows about path routing:
3580/// services declare static/backend components by opaque ID, and this
3581/// manifest binds those components to URL paths on a public-facing
3582/// domain. Generated Worker bundles consume this. See
3583/// `.yah/docs/working/W118-yah-domain-tiers.md` (R347).
3584#[derive(Debug, Clone, Serialize, Deserialize)]
3585#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3586pub struct DomainConfig {
3587 pub schema_version: u32,
3588 /// Stable identifier for this domain (file stem of the manifest).
3589 /// Example: `"yah-dev"` for the `yah.dev` zone.
3590 pub name: String,
3591 /// The fully-qualified domain this manifest routes for. Example:
3592 /// `"yah.dev"`, `"app.yah.dev"`.
3593 pub domain: String,
3594 /// Which front door serves this domain (R594-F12). **Required** — a
3595 /// default here would silently re-create the defect the field exists to
3596 /// close. Cross-checked against `routes` / `worker_bundle_path` by
3597 /// [`DomainConfig::validate_front_door`] at load time.
3598 pub front_door: FrontDoor,
3599 /// Public CDN bucket name. Static-mode route components publish into
3600 /// this bucket. Owned by the domain, *not* by any single service.
3601 pub cdn_bucket: String,
3602 /// Optional path (relative to workspace root) where the generated
3603 /// Worker bundle lands. `None` while the bundle generator (R347-F4)
3604 /// is still being wired up.
3605 #[serde(default, skip_serializing_if = "Option::is_none")]
3606 pub worker_bundle_path: Option<String>,
3607 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3608 pub routes: Vec<DomainRoute>,
3609}
3610
3611/// One entry in a [`DomainConfig`]'s route table.
3612///
3613/// The `mode` discriminator picks the variant's body via serde's
3614/// internally-tagged enum representation. Path patterns follow the
3615/// Worker convention: a trailing `*` matches everything underneath.
3616#[derive(Debug, Clone, Serialize, Deserialize)]
3617#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3618pub struct DomainRoute {
3619 /// URL pattern this route matches. Examples: `"/"`, `"/dashboard/*"`,
3620 /// `"/camp/ws"`.
3621 pub path: String,
3622 /// Response headers the front door sets on every response served under
3623 /// this route (R746). Empty by default.
3624 ///
3625 /// This is the manifest's answer to "who decides a path's response
3626 /// headers". Before it existed the answer was *nobody*: a `_headers` file
3627 /// is a Cloudflare Pages / Netlify convention, and neither of this
3628 /// repo's front doors reads one — a Worker returns what it fetched from
3629 /// R2, and R2 serves only the object's own httpMetadata. So a site could
3630 /// carry a `_headers` file declaring COOP/COEP and ship without them,
3631 /// which is exactly how it was found: `SharedArrayBuffer` is simply
3632 /// absent in a document served cross-origin-isolation-free, with no
3633 /// error anywhere to say why.
3634 ///
3635 /// Deliberately a free-form `name -> value` map rather than named fields
3636 /// for the isolation headers: the domain manifest has no business
3637 /// knowing which headers a route's payload happens to need. Ordering
3638 /// follows the route table's own rule — first matching route wins, no
3639 /// merging across routes (see the Worker's `applyRouteHeaders`).
3640 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
3641 pub headers: BTreeMap<String, String>,
3642 #[serde(flatten)]
3643 pub mode: RouteMode,
3644}
3645
3646/// Body of a [`DomainRoute`]. Three modes:
3647/// - **Static** — Worker reads from the domain's CDN bucket. Component
3648/// ref points at a `kind = "mesofact-static"` (or similar) service
3649/// component.
3650/// - **Backend** — Worker proxies to an HTTP origin owned by a backend
3651/// component (yubaba workload, gateway, etc.).
3652/// - **Redirect** — Worker emits a 30x to the target URL. Used to keep
3653/// old paths alive during domain refactors.
3654#[derive(Debug, Clone, Serialize, Deserialize)]
3655#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3656#[serde(tag = "mode", rename_all = "kebab-case")]
3657pub enum RouteMode {
3658 Static {
3659 /// Component reference `"<service>/<component-id>"`. Validated
3660 /// at [`CloudConfig::load`] time.
3661 component: String,
3662 },
3663 Backend {
3664 /// Component reference `"<service>/<component-id>"`. Validated
3665 /// at [`CloudConfig::load`] time.
3666 component: String,
3667 /// Origin URL the Worker `fetch()`es. Schema-permissive — could
3668 /// be `https://...`, `wss://...`, or a yah-internal mesh URL
3669 /// resolved by yubaba.
3670 origin: String,
3671 },
3672 Redirect {
3673 /// Absolute URL or path the Worker emits a 30x to.
3674 target: String,
3675 /// HTTP status code. Defaults to 308 (permanent + method-preserving)
3676 /// so deprecations don't silently turn POSTs into GETs.
3677 #[serde(default = "default_redirect_status")]
3678 status: u16,
3679 },
3680}
3681
3682fn default_redirect_status() -> u16 {
3683 308
3684}
3685
3686/// Normalize a component `mount` to a storage/URL key prefix: strip the
3687/// surrounding slashes. `"/app"`, `"app/"`, `"/app/"` → `"app"`; `"/"`, `""`
3688/// → `""` (the service root).
3689///
3690/// One producer on purpose — the publisher's key prefix, the route-path
3691/// cross-check and the front door's key lookup must all agree on what `/app`
3692/// means down to the byte, and three copies of `trim_matches('/')` is how they
3693/// stop agreeing.
3694pub fn normalize_mount(raw: &str) -> String {
3695 raw.trim_matches('/').to_string()
3696}
3697
3698/// The key prefix a domain route pattern serves under: `"/*"` → `""`,
3699/// `"/app/*"` and `"/app"` → `"app"`. The twin of [`normalize_mount`] on the
3700/// routing side.
3701pub fn route_path_prefix(path: &str) -> String {
3702 normalize_mount(path.strip_suffix('*').unwrap_or(path))
3703}
3704
3705/// The route-driven domain whose route table binds a component of `service`,
3706/// if any. Used by static publishers to pick up the per-route response
3707/// headers a service's paths were declared with.
3708///
3709/// Deterministic by `BTreeMap` key order when more than one domain routes the
3710/// same service (a legitimate shape: an apex and a staging host serving one
3711/// bundle). Returning the first is a real limitation, not a considered
3712/// choice — the day two such domains want *different* headers for one
3713/// component, this needs the domain identity threaded in rather than inferred.
3714pub fn domain_serving_service<'a>(
3715 domains: &'a BTreeMap<String, DomainConfig>,
3716 service: &str,
3717) -> Option<&'a DomainConfig> {
3718 domains
3719 .values()
3720 .find(|d| d.front_door.is_route_driven() && d.serves_service(service))
3721}
3722
3723/// The `ROUTE_HEADERS` Worker-binding value for `service`, read from the
3724/// workspace's domain manifests. `"[]"` when no route-driven domain routes the
3725/// service, or when the one that does declares no headers.
3726///
3727/// Reads `.yah/domains/` directly rather than taking a loaded [`CloudConfig`]:
3728/// the static reconcilers are handed a per-component [`ReconcileCtx`], not the
3729/// whole workspace config, and threading a config reference through all 22 of
3730/// its construction sites to reach one string would be a wide change for a
3731/// narrow read. Manifest parse errors propagate — a domain file that no longer
3732/// loads is a deploy-stopping fact, not a reason to ship a Worker with the
3733/// headers quietly missing.
3734pub fn route_headers_for_service(workspace_root: &Path, service: &str) -> Result<String> {
3735 let domains = load_domains(&crate::paths::domains_dir(workspace_root))?;
3736 Ok(domain_serving_service(&domains, service)
3737 .map(DomainConfig::route_headers_json)
3738 .unwrap_or_else(|| "[]".to_string()))
3739}
3740
3741impl DomainConfig {
3742 /// Parse a single `.yah/domains/<name>.toml`, rejecting a manifest whose
3743 /// declared front door contradicts its route table
3744 /// ([`Self::validate_front_door`]).
3745 pub fn load(path: &Path) -> Result<Self> {
3746 let src =
3747 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
3748 let dom: Self =
3749 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
3750 dom.validate_front_door()
3751 .with_context(|| format!("validating {}", path.display()))?;
3752 Ok(dom)
3753 }
3754
3755 /// R594-F12 — the front door must agree with the rest of the manifest.
3756 ///
3757 /// - `bucket-direct` is an R2 custom domain: a Worker route table would
3758 /// never be consulted, so declaring one means the author expected
3759 /// Worker behaviour (clean URLs, SPA fallback, branded errors) from a
3760 /// surface that cannot provide it. Rejected rather than silently
3761 /// ignored. Same for `worker_bundle_path` — nothing would deploy it.
3762 /// - `worker` / `passway` with an empty route table is a silent 404
3763 /// machine: the front door exists, has nothing to serve, and every
3764 /// request falls through to the catch-all.
3765 ///
3766 /// Called from [`Self::load`], so both [`CloudConfig::load`] and
3767 /// [`CloudConfig::load_from_config_dir`] enforce it.
3768 pub fn validate_front_door(&self) -> Result<()> {
3769 match self.front_door {
3770 FrontDoor::BucketDirect => {
3771 if let Some(route) = self.routes.first() {
3772 anyhow::bail!(
3773 "front_door = \"bucket-direct\" but routes[0].path = \"{}\" — \
3774 an R2 custom domain never consults a route table, so this \
3775 route would silently do nothing (no clean URLs, no SPA \
3776 fallback, no branded errors). Set front_door = \"worker\" \
3777 (or \"passway\") to keep the routes, or drop the [[routes]] \
3778 to keep the bucket-direct binding.",
3779 route.path
3780 );
3781 }
3782 if let Some(path) = &self.worker_bundle_path {
3783 anyhow::bail!(
3784 "front_door = \"bucket-direct\" but worker_bundle_path = \
3785 \"{path}\" — nothing deploys a Worker bundle for a domain \
3786 bound straight to R2"
3787 );
3788 }
3789 }
3790 FrontDoor::Worker | FrontDoor::Passway => {
3791 if self.routes.is_empty() {
3792 anyhow::bail!(
3793 "front_door = \"{}\" but [[routes]] is empty — a front door \
3794 with no route table is a silent 404 machine. Declare at \
3795 least one route, or set front_door = \"bucket-direct\" if \
3796 this domain really is served straight from R2.",
3797 self.front_door.as_str()
3798 );
3799 }
3800 }
3801 }
3802 Ok(())
3803 }
3804
3805 /// The `ROUTE_HEADERS` Worker binding for this domain (R746) — the route
3806 /// table's `path` + `headers` pairs, in manifest order, with routes that
3807 /// declare no headers dropped. `"[]"` when nothing declares any.
3808 ///
3809 /// Order is load-bearing and must survive serialization: the front door
3810 /// applies the FIRST matching rule, so `/app/*` above `/*` is what gives
3811 /// the app its isolation headers and leaves the marketing site alone.
3812 /// That is why this is a `Vec` of pairs and not a map keyed by path.
3813 pub fn route_headers_json(&self) -> String {
3814 #[derive(Serialize)]
3815 struct Rule<'a> {
3816 path: &'a str,
3817 headers: &'a BTreeMap<String, String>,
3818 }
3819 let rules: Vec<Rule<'_>> = self
3820 .routes
3821 .iter()
3822 .filter(|r| !r.headers.is_empty())
3823 .map(|r| Rule {
3824 path: &r.path,
3825 headers: &r.headers,
3826 })
3827 .collect();
3828 serde_json::to_string(&rules).unwrap_or_else(|_| "[]".to_string())
3829 }
3830
3831 /// Whether this domain's route table binds any component of `service`.
3832 pub fn serves_service(&self, service: &str) -> bool {
3833 self.routes.iter().any(|r| {
3834 r.mode
3835 .component()
3836 .and_then(split_component_ref)
3837 .is_some_and(|(svc, _)| svc == service)
3838 })
3839 }
3840
3841 /// Persist to `.yah/domains/<name>.toml`, creating the domains
3842 /// directory if needed. Create-or-overwrite.
3843 pub fn save(&self, workspace_root: &Path) -> Result<()> {
3844 let dir = crate::paths::domains_dir(workspace_root);
3845 std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
3846 let path = crate::paths::domain_toml(workspace_root, &self.name);
3847 let s = toml::to_string_pretty(self)
3848 .with_context(|| format!("serializing domain {}", self.name))?;
3849 std::fs::write(&path, s).with_context(|| format!("writing {}", path.display()))
3850 }
3851
3852 /// Remove `.yah/domains/<name>.toml`. Returns `false` when the file
3853 /// was already absent.
3854 pub fn delete(workspace_root: &Path, name: &str) -> Result<bool> {
3855 let path = crate::paths::domain_toml(workspace_root, name);
3856 if !path.exists() {
3857 return Ok(false);
3858 }
3859 std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
3860 Ok(true)
3861 }
3862}
3863
3864impl RouteMode {
3865 /// Component reference for static/backend modes; `None` for redirects.
3866 pub fn component(&self) -> Option<&str> {
3867 match self {
3868 Self::Static { component } | Self::Backend { component, .. } => Some(component),
3869 Self::Redirect { .. } => None,
3870 }
3871 }
3872}
3873
3874// ─── Service-group vault (R706 / W294) ───────────────────────────────────────
3875
3876/// A camp's declaration of one cluster secret, from
3877/// `.yah/infra/secrets/<slug>.toml`.
3878///
3879/// This is the *authoring* side of the fleet's cluster-secret store: it names
3880/// where the value lives in the camp (a `fob` vault slot), what the fleet should
3881/// call it, and — the point of R706 — which workloads are allowed to mount it.
3882///
3883/// The declaration is not itself the enforcement point. `yah cloud secret put`
3884/// reads this file, seals the vault value under the cluster KEK, and ships the
3885/// ciphertext **with its access rule** into raft; yubaba's `ClusterResolver`
3886/// evaluates the rule on the node at mount time. Deleting this file does not
3887/// revoke anything — the record in raft is the live authority. That asymmetry is
3888/// deliberate: a rule that lived only in a git-tracked camp file would be
3889/// trivially bypassed by anyone who could reach the fleet without the camp.
3890///
3891/// ```toml
3892/// #:schema ../../schema/secret.toml.schema.json
3893/// schema_version = 1
3894/// name = "cheers/cloud-admin/verify-key"
3895/// vault_slot = "cheers-cloud-admin-verify-key"
3896/// description = "Ed25519 public key yah-cloud-admin verifies operator PASETOs with"
3897///
3898/// [access]
3899/// workloads = [{ workload = "yah-cloud-admin" }]
3900///
3901/// [target]
3902/// kind = "file"
3903/// path = "/run/secrets/cheers-verify.key"
3904/// mode = 0o400
3905/// ```
3906#[derive(Debug, Clone, Serialize, Deserialize)]
3907#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3908pub struct SecretConfig {
3909 pub schema_version: u32,
3910
3911 /// Logical cluster-secret key, as `SecretRef::Cluster { name }` spells it —
3912 /// e.g. `"tls/yah.dev/cert"`, `"cheers/cloud-admin/verify-key"`. May contain
3913 /// `/`; the file stem is a filesystem-safe slug and carries no meaning.
3914 pub name: String,
3915
3916 /// The `fob` vault slot in this camp holding the plaintext value. Read by
3917 /// `yah cloud secret put` at ship time and never recorded anywhere else — in
3918 /// particular the value is not in this file, so the declaration is safe to
3919 /// commit.
3920 pub vault_slot: String,
3921
3922 /// Human note for `yah cloud secret ls`. What this secret is and who minted
3923 /// it — the thing nobody remembers 6 months later.
3924 #[serde(default, skip_serializing_if = "Option::is_none")]
3925 pub description: Option<String>,
3926
3927 /// How the vault slot's text decodes into the bytes the consumer expects.
3928 ///
3929 /// `fob` slots hold strings, but plenty of real secrets are **binary** — an
3930 /// Ed25519 key is exactly 32 raw bytes, and `yah-cloud-admin` rejects a key
3931 /// file of any other length. Without this field the only way to ship such a
3932 /// key would be to hope its bytes happened to be valid UTF-8, which for a
3933 /// random key they are not.
3934 ///
3935 /// Defaults to [`SecretEncoding::Utf8`] — the right answer for tokens,
3936 /// passwords, and PEM, which is most secrets.
3937 #[serde(default)]
3938 pub encoding: SecretEncoding,
3939
3940 /// Who may mount it. Stamped onto the raft record verbatim.
3941 ///
3942 /// Defaults to [`SecretAccess::default`] — the deny-all empty allow-list. A
3943 /// declaration that forgets this field produces a secret nobody can mount,
3944 /// which is the correct direction to fail in.
3945 ///
3946 /// Three forms:
3947 ///
3948 /// ```toml
3949 /// access = "allow_any" # explicit escape hatch
3950 ///
3951 /// [access] # named workloads
3952 /// workloads = [{ workload = "yah-cloud-admin" }]
3953 ///
3954 /// [access] # signed recipes (R555-F5)
3955 /// recipes = [{ recipe = "rusty-v8-musl", key = "3d40…" }]
3956 /// ```
3957 ///
3958 /// Use the `recipes` form for a credential a **dispatched build** needs (the
3959 /// R2 write key, the cosign signing key). A remote QED run's workload name
3960 /// is a fresh `forge-<uuid>` every time, so `workloads` cannot name it and
3961 /// `allow_any` over-answers — see W235 §Seam (c) secret scoping. `key` is
3962 /// the hex Ed25519 public key from the recipe's `[admission]` block.
3963 #[serde(default)]
3964 pub access: SecretAccess,
3965
3966 /// Advisory: the mount shape a consuming workload should declare. Not
3967 /// enforced — yubaba honours whatever the `WorkloadSpec` asks for — but it
3968 /// lets `yah cloud secret put` print the exact `SecretMount` to paste, so
3969 /// the consumer and the declaration can't drift on path or mode.
3970 #[serde(default, skip_serializing_if = "Option::is_none")]
3971 pub target: Option<SecretTargetDecl>,
3972}
3973
3974/// How a [`SecretConfig`]'s vault text becomes the bytes delivered to the
3975/// container (R706 / W294).
3976#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3977#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3978#[serde(rename_all = "kebab-case")]
3979pub enum SecretEncoding {
3980 /// Ship the vault string's UTF-8 bytes verbatim. Tokens, passwords, PEM.
3981 #[default]
3982 Utf8,
3983 /// The vault string is hex; ship the decoded bytes. Use for binary key
3984 /// material — e.g. a raw Ed25519 key, which must land as exactly 32 bytes.
3985 Hex,
3986}
3987
3988/// Advisory mount shape on a [`SecretConfig`]. Mirrors
3989/// `workload_spec::SecretTarget` in a TOML-friendly, externally-tagged-free
3990/// shape (a `kind` discriminator reads better in a hand-written manifest than
3991/// serde's default enum encoding).
3992#[derive(Debug, Clone, Serialize, Deserialize)]
3993#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
3994#[serde(tag = "kind", rename_all = "kebab-case")]
3995pub enum SecretTargetDecl {
3996 /// Mounted as a tmpfs-backed file inside the container.
3997 File {
3998 /// Absolute path inside the container.
3999 path: String,
4000 /// Unix permission bits. Defaults to `0o400` (owner-read-only).
4001 #[serde(default = "default_secret_mode")]
4002 mode: u32,
4003 },
4004 /// Injected as an environment variable. Prefer `file` — env vars leak
4005 /// through subprocess environments and log dumps.
4006 EnvVar { name: String },
4007}
4008
4009fn default_secret_mode() -> u32 {
4010 0o400
4011}
4012
4013impl SecretTargetDecl {
4014 /// The `workload_spec` target this declaration describes.
4015 pub fn to_target(&self) -> workload_spec::SecretTarget {
4016 match self {
4017 Self::File { path, mode } => workload_spec::SecretTarget::File {
4018 path: path.into(),
4019 mode: *mode,
4020 },
4021 Self::EnvVar { name } => workload_spec::SecretTarget::EnvVar { name: name.clone() },
4022 }
4023 }
4024}
4025
4026impl SecretConfig {
4027 /// Parse a single `.yah/infra/secrets/<slug>.toml`.
4028 pub fn load(path: &Path) -> Result<Self> {
4029 let src =
4030 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
4031 let cfg: Self =
4032 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
4033 cfg.validate()
4034 .with_context(|| format!("validating {}", path.display()))?;
4035 Ok(cfg)
4036 }
4037
4038 /// Load every declaration in `dir`, keyed by logical secret name. A missing
4039 /// directory is an empty map (a camp with no cluster secrets is normal).
4040 ///
4041 /// Two files declaring the same `name` is a hard error, not a last-writer-
4042 /// wins merge: they would race to define the access rule for one record, and
4043 /// whichever lost would look correct in git while being inert on the fleet.
4044 pub fn load_dir(dir: &Path) -> Result<BTreeMap<String, Self>> {
4045 let mut out: BTreeMap<String, Self> = BTreeMap::new();
4046 if !dir.exists() {
4047 return Ok(out);
4048 }
4049 for entry in std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
4050 let path = entry?.path();
4051 if path.extension().is_none_or(|e| e != "toml") {
4052 continue;
4053 }
4054 let cfg = Self::load(&path)?;
4055 if let Some(prev) = out.insert(cfg.name.clone(), cfg) {
4056 anyhow::bail!(
4057 "two secret declarations both claim name {:?} (one of them is {}); \
4058 a cluster secret must have exactly one declaration so its access \
4059 rule has one author",
4060 prev.name,
4061 path.display()
4062 );
4063 }
4064 }
4065 Ok(out)
4066 }
4067
4068 /// Reject declarations that would produce an unusable or dangerous record.
4069 pub fn validate(&self) -> Result<()> {
4070 if self.name.trim().is_empty() {
4071 anyhow::bail!("`name` must not be empty");
4072 }
4073 if self.vault_slot.trim().is_empty() {
4074 anyhow::bail!(
4075 "`vault_slot` must not be empty — it names the fob slot holding the value"
4076 );
4077 }
4078 // A deny-all rule is a *valid* record (it is the fail-closed default the
4079 // resolver relies on) but it is never a useful thing to deliberately
4080 // ship, so catching it here saves an operator the round-trip of
4081 // deploying a workload that mysteriously can't see its own secret.
4082 if let SecretAccess::Workloads(entries) = &self.access {
4083 if entries.is_empty() {
4084 anyhow::bail!(
4085 "`[access]` admits nobody: list the workloads allowed to mount {:?} \
4086 (e.g. `workloads = [{{ workload = \"my-service\" }}]`), or set \
4087 `access = \"allow_any\"` to store it unrestricted",
4088 self.name
4089 );
4090 }
4091 if let Some(bad) = entries.iter().find(|e| e.workload.trim().is_empty()) {
4092 anyhow::bail!("`[access]` entry has an empty `workload` name: {bad:?}");
4093 }
4094 }
4095 Ok(())
4096 }
4097}
4098
4099#[cfg(test)]
4100mod secret_config_tests {
4101 use super::*;
4102
4103 fn parse(body: &str) -> Result<SecretConfig> {
4104 let cfg: SecretConfig = toml::from_str(body)?;
4105 cfg.validate()?;
4106 Ok(cfg)
4107 }
4108
4109 #[test]
4110 fn minimal_declaration_parses_with_narrow_defaults() {
4111 let cfg = parse(
4112 r#"
4113schema_version = 1
4114name = "svc/token"
4115vault_slot = "svc-token"
4116[access]
4117workloads = [{ workload = "svc" }]
4118"#,
4119 )
4120 .unwrap();
4121
4122 assert_eq!(cfg.encoding, SecretEncoding::Utf8, "text is the default");
4123 assert!(cfg.target.is_none());
4124 // The omitted tenant/namespace must narrow to the singletons, not widen
4125 // to a wildcard.
4126 assert!(cfg
4127 .access
4128 .admits(&workload_spec::secrets::SecretConsumer::workload("svc")));
4129 assert!(!cfg
4130 .access
4131 .admits(&workload_spec::secrets::SecretConsumer::workload("other")));
4132 }
4133
4134 #[test]
4135 fn allow_any_is_spelled_as_a_bare_string() {
4136 // The operator-facing spelling, pinned: `access = "allow_any"`.
4137 let cfg = parse(
4138 r#"
4139schema_version = 1
4140name = "public/thing"
4141vault_slot = "slot"
4142access = "allow_any"
4143"#,
4144 )
4145 .unwrap();
4146 assert_eq!(cfg.access, SecretAccess::AllowAny);
4147 }
4148
4149 #[test]
4150 fn a_declaration_with_no_access_block_is_rejected() {
4151 // Omitting `[access]` defaults to deny-all, which is the correct
4152 // *runtime* default but never a correct authoring intent — so it must
4153 // not silently produce a secret nobody can mount.
4154 let err = parse(
4155 r#"
4156schema_version = 1
4157name = "svc/token"
4158vault_slot = "svc-token"
4159"#,
4160 )
4161 .unwrap_err()
4162 .to_string();
4163 assert!(err.contains("admits nobody"), "got {err}");
4164 }
4165
4166 #[test]
4167 fn empty_name_or_slot_is_rejected() {
4168 assert!(parse(
4169 r#"
4170schema_version = 1
4171name = ""
4172vault_slot = "slot"
4173access = "allow_any"
4174"#
4175 )
4176 .is_err());
4177 assert!(parse(
4178 r#"
4179schema_version = 1
4180name = "x"
4181vault_slot = " "
4182access = "allow_any"
4183"#
4184 )
4185 .is_err());
4186 }
4187
4188 #[test]
4189 fn target_declaration_maps_onto_the_workload_spec_type() {
4190 let cfg = parse(
4191 r#"
4192schema_version = 1
4193name = "svc/token"
4194vault_slot = "slot"
4195access = "allow_any"
4196[target]
4197kind = "file"
4198path = "/run/secrets/t"
4199"#,
4200 )
4201 .unwrap();
4202 match cfg.target.unwrap().to_target() {
4203 workload_spec::SecretTarget::File { path, mode } => {
4204 assert_eq!(path, std::path::PathBuf::from("/run/secrets/t"));
4205 assert_eq!(mode, 0o400, "owner-read-only by default");
4206 }
4207 other => panic!("expected File, got {other:?}"),
4208 }
4209 }
4210
4211 #[test]
4212 fn load_dir_is_empty_for_a_camp_with_no_secrets() {
4213 let tmp = tempfile::TempDir::new().unwrap();
4214 assert!(SecretConfig::load_dir(&tmp.path().join("nope"))
4215 .unwrap()
4216 .is_empty());
4217 }
4218}
4219
4220/// Split a `"<service>/<component-id>"` ref. Returns `None` if the ref
4221/// isn't shaped like `service/component`.
4222fn split_component_ref(s: &str) -> Option<(&str, &str)> {
4223 let (svc, comp) = s.split_once('/')?;
4224 if svc.is_empty() || comp.is_empty() || comp.contains('/') {
4225 return None;
4226 }
4227 Some((svc, comp))
4228}
4229
4230#[cfg(test)]
4231mod tests {
4232 use super::*;
4233 use std::path::PathBuf;
4234
4235 fn make_machine(name: &str, mesh_tags: Vec<&str>) -> MachineConfig {
4236 MachineConfig {
4237 name: name.into(),
4238 provider: "hetzner".into(),
4239 location: Some("hil".into()),
4240 server_type: Some("ccx13".into()),
4241 hosts_mirrors: vec![],
4242 mesh_tags: mesh_tags.into_iter().map(String::from).collect(),
4243 region: None,
4244 zone: None,
4245 arch: None,
4246 bucket: None,
4247 vendor: None,
4248 nickname: None,
4249 legacy_hostkey_fingerprint: None,
4250 registration: Default::default(),
4251 ssh_keys: vec![],
4252 cloudflared: None,
4253 hosts_operator_bridge: false,
4254 connect: None,
4255 allocatable: None,
4256 taints: vec![],
4257 sovereign_group: None,
4258 sovereign_role: None,
4259 }
4260 }
4261
4262 /// Like [`make_machine`] but with explicit topology axes for F16 tests.
4263 fn make_machine_topo(
4264 name: &str,
4265 provider: &str,
4266 region: &str,
4267 mesh_tags: Vec<&str>,
4268 ) -> MachineConfig {
4269 MachineConfig {
4270 provider: provider.into(),
4271 region: Some(region.into()),
4272 zone: Some(region.into()),
4273 ..make_machine(name, mesh_tags)
4274 }
4275 }
4276
4277 fn make_empty_cfg(machines: Vec<MachineConfig>) -> CloudConfig {
4278 CloudConfig {
4279 workspace_root: PathBuf::new(),
4280 machines,
4281 providers: vec![],
4282 machine_origins: BTreeMap::new(),
4283 provider_origins: BTreeMap::new(),
4284 services: BTreeMap::new(),
4285 domains: BTreeMap::new(),
4286 legacy_mirrors: vec![],
4287 workloads: vec![],
4288 topology: TopologyConfig::default(),
4289 legacy_services: vec![],
4290 }
4291 }
4292
4293 #[test]
4294 fn required_spec_parses_from_provider_fields() {
4295 let toml_src = r#"
4296use = "hetzner-primary"
4297[required]
4298mesh_tags = ["tag:cloud-runner"]
4299"#;
4300 let slot: MirrorProviderSlot = toml::from_str(toml_src).unwrap();
4301 let req = slot.required().expect("required block present");
4302 assert_eq!(req.mesh_tags, vec!["tag:cloud-runner"]);
4303 }
4304
4305 #[test]
4306 fn required_spec_absent_when_field_missing() {
4307 let slot: MirrorProviderSlot = toml::from_str(r#"use = "hetzner-primary""#).unwrap();
4308 assert!(slot.required().is_none());
4309 }
4310
4311 #[test]
4312 fn db_catalog_parses_all_env_blocks() {
4313 // W241 / R571-F8: a service.toml [db] table with dev/pond/cloud.
4314 let toml_src = r#"
4315schema_version = 1
4316name = "scrabcake"
4317domain = "scrabcake.net.yah.dev"
4318
4319[[db.dev]]
4320name = "main"
4321path = "data/dev.sqlite"
4322
4323[[db.pond]]
4324name = "main"
4325port = 5433
4326
4327[[db.pond]]
4328name = "pg"
4329port = 5432
4330kind = "postgres"
4331
4332[[db.cloud]]
4333name = "main"
4334url = "libsql://scrabcake.turso.io"
4335auth_token_env = "SCRABCAKE_TURSO_TOKEN"
4336"#;
4337 let svc: ServiceConfig = toml::from_str(toml_src).unwrap();
4338 assert_eq!(svc.db.dev.len(), 1);
4339 assert_eq!(svc.db.dev[0].path, "data/dev.sqlite");
4340 assert_eq!(svc.db.pond.len(), 2);
4341 assert_eq!(svc.db.pond[0].port, Some(5433));
4342 assert_eq!(svc.db.pond[0].kind, PondDbKind::Turso); // default
4343 assert_eq!(svc.db.pond[1].kind, PondDbKind::Postgres);
4344 assert_eq!(
4345 svc.db.cloud[0].auth_token_env.as_deref(),
4346 Some("SCRABCAKE_TURSO_TOKEN")
4347 );
4348 }
4349
4350 #[test]
4351 fn service_without_db_table_has_empty_catalog() {
4352 let svc: ServiceConfig =
4353 toml::from_str("schema_version = 1\nname = \"s\"\ndomain = \"s.dev\"\n").unwrap();
4354 assert!(svc.db.is_empty());
4355 // And an empty [db] must not appear when re-serialized.
4356 let out = toml::to_string(&svc).unwrap();
4357 assert!(
4358 !out.contains("[db"),
4359 "empty db table should be skipped: {out}"
4360 );
4361 }
4362
4363 #[test]
4364 fn camp_shared_cloud_toml_parses() {
4365 let src = r#"
4366[[cloud]]
4367name = "analytics"
4368url = "postgres://shared/analytics"
4369"#;
4370 let shared: CampCloudDbs = toml::from_str(src).unwrap();
4371 assert_eq!(shared.cloud.len(), 1);
4372 assert_eq!(shared.cloud[0].name, "analytics");
4373 }
4374
4375 #[test]
4376 fn resolve_machine_by_mesh_tags_superset_match() {
4377 let cfg = make_empty_cfg(vec![
4378 make_machine("yah-bnt-1", vec!["tag:primary-yah", "tag:tier-scratch"]),
4379 make_machine("us-west-001", vec!["tag:primary-yah", "tag:cloud-runner"]),
4380 ]);
4381 let picked = cfg
4382 .resolve_machine_by_mesh_tags(&["tag:cloud-runner".into()])
4383 .map(|m| m.name.as_str());
4384 assert_eq!(picked, Some("us-west-001"));
4385 }
4386
4387 #[test]
4388 fn resolve_machine_by_mesh_tags_returns_none_when_no_match() {
4389 let cfg = make_empty_cfg(vec![make_machine("yah-bnt-1", vec!["tag:primary-yah"])]);
4390 assert!(cfg
4391 .resolve_machine_by_mesh_tags(&["tag:cloud-runner".into()])
4392 .is_none());
4393 }
4394
4395 // ─── R590-F1 mesh-tag node-selector admission ───────────────────────────
4396
4397 /// Build a forge WorkloadSpec carrying the R594 node-selector annotation.
4398 /// `selector` is the comma-joined mesh-tag set; `None` omits the annotation
4399 /// entirely (pre-R594 "no constraint").
4400 fn ws_with_selector(selector: Option<&str>) -> WorkloadSpec {
4401 use workload_spec::{ImageRef, TierTag};
4402 let mut ws = WorkloadSpec::for_forge(
4403 "R590-F1-test",
4404 ImageRef {
4405 registry: "docker.io".into(),
4406 repository: "library/busybox".into(),
4407 tag: "latest".into(),
4408 digest: workload_spec::testing::test_digest(),
4409 },
4410 TierTag("infra".into()),
4411 vec![],
4412 );
4413 if let Some(sel) = selector {
4414 ws.annotations.insert(
4415 velveteen_exec::remote::NODE_SELECTOR_MESH_TAGS_ANNOTATION.into(),
4416 sel.into(),
4417 );
4418 }
4419 ws
4420 }
4421
4422 /// The build-worker fleet shape: one x86 node (us-west-002) and one arm
4423 /// node (a Pi5), both carrying `tag:build-worker`.
4424 fn build_worker_fleet() -> CloudConfig {
4425 make_empty_cfg(vec![
4426 make_machine("us-west-002", vec!["tag:build-worker", "arch:x86"]),
4427 make_machine("pi5-001", vec!["tag:build-worker", "arch:arm"]),
4428 ])
4429 }
4430
4431 #[test]
4432 fn admit_workload_routes_amd64_to_x86_worker() {
4433 let cfg = build_worker_fleet();
4434 let ws = ws_with_selector(Some("tag:build-worker,arch:x86"));
4435 let picked = cfg.admit_workload(&ws).unwrap();
4436 assert_eq!(picked.name, "us-west-002");
4437 }
4438
4439 #[test]
4440 fn admit_workload_routes_arm64_to_pi5_worker() {
4441 let cfg = build_worker_fleet();
4442 let ws = ws_with_selector(Some("tag:build-worker,arch:arm"));
4443 let picked = cfg.admit_workload(&ws).unwrap();
4444 assert_eq!(picked.name, "pi5-001");
4445 }
4446
4447 /// A forge run must be admissible on a build-worker smaller than its own
4448 /// cgroup ceiling.
4449 ///
4450 /// The fleet's arm build-workers are 8 GiB Pi-5s and `for_forge` sets a
4451 /// 32 GiB ceiling, so while admission read `resources.memory_mb` as the
4452 /// capacity floor this returned "no candidates" and *every* offloaded qed
4453 /// step to those nodes failed at dispatch — measured on desktop-release run
4454 /// b04cef47, where the aarch64-linux row died in 1.6s. The other
4455 /// build-workers (16 GiB us-west-003, and the arm Pi-5s) were excluded the
4456 /// same way, leaving one 47 GiB node as the fleet's only legal target for
4457 /// remote CI.
4458 #[test]
4459 fn admit_workload_places_a_forge_run_on_a_worker_smaller_than_its_ceiling() {
4460 let mut pi = make_machine("pi5-001", vec!["tag:build-worker", "arch:arm"]);
4461 pi.allocatable = Some(NodeAllocatable {
4462 memory_mb: 8192,
4463 cpu_millis: 4000,
4464 });
4465 let cfg = make_empty_cfg(vec![pi]);
4466
4467 let ws = ws_with_selector(Some("tag:build-worker,arch:arm"));
4468 assert!(
4469 ws.resources.memory_mb > 8192,
4470 "precondition: the ceiling must exceed the node, or this proves nothing"
4471 );
4472
4473 let picked = cfg
4474 .admit_workload(&ws)
4475 .expect("an 8 GiB build-worker must admit a forge run");
4476 assert_eq!(picked.name, "pi5-001");
4477 }
4478
4479 /// The floor is still enforced — the fix separates two numbers, it does not
4480 /// disable the R572-F5 capacity check.
4481 #[test]
4482 fn admit_workload_still_rejects_a_node_below_the_declared_request() {
4483 let mut tiny = make_machine("tiny-001", vec!["tag:build-worker", "arch:arm"]);
4484 tiny.allocatable = Some(NodeAllocatable {
4485 memory_mb: 512,
4486 cpu_millis: 4000,
4487 });
4488 let cfg = make_empty_cfg(vec![tiny]);
4489
4490 let ws = ws_with_selector(Some("tag:build-worker,arch:arm"));
4491 assert!(
4492 cfg.admit_workload(&ws).is_err(),
4493 "a 512 MiB node cannot satisfy a 2 GiB forge request"
4494 );
4495 }
4496
4497 // ─── R833-F8 imperative node-selector admission ─────────────────────────
4498
4499 /// Build a forge WorkloadSpec carrying the R833-F8 imperative node
4500 /// selector — the operator's `--where=node:<machine>`.
4501 fn ws_pinned_to(node: &str) -> WorkloadSpec {
4502 let mut ws = ws_with_selector(None);
4503 ws.annotations.insert(
4504 velveteen_exec::remote::NODE_SELECTOR_NODE_ANNOTATION.into(),
4505 node.into(),
4506 );
4507 ws
4508 }
4509
4510 /// The ticket's acceptance shape: a named node wins over the
4511 /// declaration-order tie-break that would otherwise decide placement.
4512 /// `us-west-002` is declared first and carries every tag, so an inferred
4513 /// placement lands there; the pin must reach `pi5-001` regardless.
4514 #[test]
4515 fn admit_workload_honours_an_explicitly_named_node() {
4516 let cfg = build_worker_fleet();
4517 assert_eq!(
4518 cfg.admit_workload(&ws_with_selector(Some("tag:build-worker")))
4519 .unwrap()
4520 .name,
4521 "us-west-002",
4522 "precondition: inference elects the first-declared node",
4523 );
4524 assert_eq!(
4525 cfg.admit_workload(&ws_pinned_to("pi5-001")).unwrap().name,
4526 "pi5-001",
4527 );
4528 }
4529
4530 /// A pin at a machine that is not declared fails loud, naming the
4531 /// constraint and the pool — the operator mistyped a node, and silently
4532 /// running the build somewhere else is the one outcome that must not
4533 /// happen.
4534 #[test]
4535 fn admit_workload_refuses_a_node_that_is_not_declared() {
4536 let cfg = build_worker_fleet();
4537 let err = cfg
4538 .admit_workload(&ws_pinned_to("us-west-404"))
4539 .unwrap_err()
4540 .to_string();
4541 assert!(err.contains("required.nodes=[us-west-404]"), "{err}");
4542 assert!(err.contains("us-west-002"), "the pool must be named: {err}");
4543 }
4544
4545 /// The pin narrows the candidate set; it does not suspend the other axes.
4546 /// A named node that cannot fit the workload still refuses, rather than
4547 /// being handed work it has no room for.
4548 #[test]
4549 fn a_pinned_node_is_still_checked_against_capacity() {
4550 let mut tiny = make_machine("tiny-001", vec!["tag:build-worker", "arch:arm"]);
4551 tiny.allocatable = Some(NodeAllocatable {
4552 memory_mb: 512,
4553 cpu_millis: 4000,
4554 });
4555 let cfg = make_empty_cfg(vec![tiny]);
4556 assert!(cfg.admit_workload(&ws_pinned_to("tiny-001")).is_err());
4557 }
4558
4559 /// Inference is untouched: with no node annotation the `nodes` axis is
4560 /// empty, which is "no constraint" — every pre-R833-F8 workload is admitted
4561 /// exactly as before.
4562 #[test]
4563 fn an_unpinned_workload_carries_no_node_constraint() {
4564 assert!(node_selector_node(&ws_with_selector(Some("arch:x86"))).is_none());
4565 assert_eq!(
4566 node_selector_node(&ws_pinned_to("us-west-003")).as_deref(),
4567 Some("us-west-003")
4568 );
4569 assert!(RequiredSpec::default().is_unconstrained());
4570 assert!(!RequiredSpec {
4571 nodes: vec!["us-west-003".into()],
4572 ..Default::default()
4573 }
4574 .is_unconstrained());
4575 }
4576
4577 #[test]
4578 fn admit_workload_rejects_node_missing_required_tag() {
4579 // Only an arm worker exists; an x86 build must NOT land on it.
4580 let cfg = make_empty_cfg(vec![make_machine(
4581 "pi5-001",
4582 vec!["tag:build-worker", "arch:arm"],
4583 )]);
4584 let ws = ws_with_selector(Some("tag:build-worker,arch:x86"));
4585 assert!(cfg.admit_workload(&ws).is_err());
4586 }
4587
4588 /// R555-S1 regression: with TWO nodes carrying the same tag set, which one
4589 /// admits must be decided by *declaration order* (file name), which is the
4590 /// contract `admit_workload` documents — not by `read_dir` order, which is
4591 /// filesystem-dependent and can change when an unrelated file appears in
4592 /// the directory. Written creation-order-reversed so a filesystem that
4593 /// yields creation order (rather than sorted order) trips it without the
4594 /// sort in `load_dir`.
4595 ///
4596 /// Live consequence this guards: `.yah/infra/machines/` carries both
4597 /// us-west-002 and us-west-003 on `[tag:build-worker, arch:x86, os:linux]`,
4598 /// so an x86 QED offload has two equal candidates. Unstable selection means
4599 /// a retried build cannot be relied on to land back on the node whose
4600 /// working state it left behind.
4601 #[test]
4602 fn equally_matching_machines_admit_in_file_name_order() {
4603 let tmp = tempfile::TempDir::new().unwrap();
4604 let machines = tmp.path().join(".yah").join("infra").join("machines");
4605 std::fs::create_dir_all(&machines).unwrap();
4606 let toml_for = |name: &str| {
4607 format!(
4608 r#"name = "{name}"
4609provider = "static"
4610mesh_tags = ["tag:build-worker", "arch:x86"]
4611"#
4612 )
4613 };
4614 // Reverse-of-sorted creation order on purpose.
4615 std::fs::write(machines.join("b-second.toml"), toml_for("b-second")).unwrap();
4616 std::fs::write(machines.join("a-first.toml"), toml_for("a-first")).unwrap();
4617
4618 let cfg = CloudConfig::load(tmp.path()).unwrap();
4619 assert_eq!(
4620 cfg.machines.iter().map(|m| m.name.as_str()).collect::<Vec<_>>(),
4621 vec!["a-first", "b-second"],
4622 "machines must load in file-name order, not read_dir order"
4623 );
4624
4625 let ws = ws_with_selector(Some("tag:build-worker,arch:x86"));
4626 assert_eq!(cfg.admit_workload(&ws).unwrap().name, "a-first");
4627 }
4628
4629 #[test]
4630 fn admit_workload_empty_selector_is_unconstrained() {
4631 // Absent annotation ⇒ no mesh-tag constraint ⇒ first declared machine
4632 // (pre-R594 behavior preserved).
4633 let cfg = build_worker_fleet();
4634 let ws = ws_with_selector(None);
4635 let picked = cfg.admit_workload(&ws).unwrap();
4636 assert_eq!(picked.name, "us-west-002");
4637 }
4638
4639 #[test]
4640 fn node_selector_mesh_tags_trims_and_drops_empties() {
4641 let ws = ws_with_selector(Some(" tag:build-worker , arch:x86 ,"));
4642 assert_eq!(
4643 node_selector_mesh_tags(&ws),
4644 vec!["tag:build-worker".to_string(), "arch:x86".to_string()]
4645 );
4646 assert!(node_selector_mesh_tags(&ws_with_selector(None)).is_empty());
4647 }
4648
4649 // ─── F16 topology-aware resolver ────────────────────────────────────────
4650
4651 fn two_region_fleet() -> CloudConfig {
4652 make_empty_cfg(vec![
4653 make_machine_topo(
4654 "us-west-001",
4655 "hetzner",
4656 "us-west",
4657 vec!["tag:cloud-runner"],
4658 ),
4659 make_machine_topo(
4660 "eu-west-001",
4661 "hetzner",
4662 "eu-west",
4663 vec!["tag:cloud-runner"],
4664 ),
4665 ])
4666 }
4667
4668 #[test]
4669 fn resolve_machine_matches_on_region_plus_mesh_tags() {
4670 let cfg = two_region_fleet();
4671 let req = RequiredSpec {
4672 regions: vec!["us-west".into()],
4673 mesh_tags: vec!["tag:cloud-runner".into()],
4674 ..Default::default()
4675 };
4676 let picked = cfg.resolve_machine(&req).unwrap();
4677 assert_eq!(picked.name, "us-west-001");
4678 }
4679
4680 #[test]
4681 fn resolve_machine_region_disambiguates_same_tag() {
4682 // Both boxes carry tag:cloud-runner; the region axis selects eu-west.
4683 let cfg = two_region_fleet();
4684 let req = RequiredSpec {
4685 regions: vec!["eu-west".into()],
4686 mesh_tags: vec!["tag:cloud-runner".into()],
4687 ..Default::default()
4688 };
4689 assert_eq!(cfg.resolve_machine(&req).unwrap().name, "eu-west-001");
4690 }
4691
4692 #[test]
4693 fn resolve_machine_fails_loud_with_constraint_summary() {
4694 let cfg = two_region_fleet();
4695 let req = RequiredSpec {
4696 regions: vec!["us-central".into()],
4697 mesh_tags: vec!["tag:cloud-runner".into()],
4698 ..Default::default()
4699 };
4700 let err = cfg.resolve_machine(&req).unwrap_err().to_string();
4701 assert!(err.contains("required.regions=[us-central]"), "got: {err}");
4702 assert!(
4703 err.contains("required.mesh_tags=[tag:cloud-runner]"),
4704 "got: {err}"
4705 );
4706 // Names the candidates it rejected.
4707 assert!(err.contains("us-west-001"), "got: {err}");
4708 }
4709
4710 #[test]
4711 fn resolve_machine_provider_axis_filters() {
4712 let cfg = make_empty_cfg(vec![
4713 make_machine_topo("aws-west-1", "aws", "us-west", vec!["tag:cloud-runner"]),
4714 make_machine_topo("hz-west-1", "hetzner", "us-west", vec!["tag:cloud-runner"]),
4715 ]);
4716 let req = RequiredSpec {
4717 regions: vec!["us-west".into()],
4718 providers: vec!["hetzner".into()],
4719 ..Default::default()
4720 };
4721 assert_eq!(cfg.resolve_machine(&req).unwrap().name, "hz-west-1");
4722 }
4723
4724 #[test]
4725 fn unconstrained_required_spec_matches_first_machine() {
4726 let cfg = two_region_fleet();
4727 assert!(RequiredSpec::default().is_unconstrained());
4728 assert_eq!(
4729 cfg.resolve_machine(&RequiredSpec::default()).unwrap().name,
4730 "us-west-001"
4731 );
4732 }
4733
4734 #[test]
4735 fn required_spec_parses_topology_axes_from_toml() {
4736 let toml_src = r#"
4737use = "hetzner-primary"
4738[required]
4739regions = ["us-west"]
4740mesh_tags = ["tag:cloud-runner"]
4741"#;
4742 let slot: MirrorProviderSlot = toml::from_str(toml_src).unwrap();
4743 let req = slot.required().expect("required block present");
4744 assert_eq!(req.regions, vec!["us-west"]);
4745 assert_eq!(req.mesh_tags, vec!["tag:cloud-runner"]);
4746 assert!(req.zones.is_empty());
4747 }
4748
4749 #[test]
4750 fn round_trip_machine() {
4751 let cfg = MachineConfig {
4752 name: "test-pdx-1".into(),
4753 provider: "hetzner".into(),
4754 location: Some("pdx".into()),
4755 server_type: Some("cpx22".into()),
4756 hosts_mirrors: vec!["noisetable".into()],
4757 mesh_tags: vec!["region:pdx".into()],
4758 region: Some("us-west".into()),
4759 zone: Some("pdx".into()),
4760 arch: None,
4761 bucket: Some(BucketSpec {
4762 name: "test-assets-pdx-1".into(),
4763 public_read: false,
4764 }),
4765 vendor: None,
4766 nickname: None,
4767 legacy_hostkey_fingerprint: None,
4768 registration: Default::default(),
4769 ssh_keys: vec![],
4770 cloudflared: None,
4771 hosts_operator_bridge: false,
4772 connect: None,
4773 allocatable: None,
4774 taints: vec![],
4775 sovereign_group: None,
4776 sovereign_role: None,
4777 };
4778 let s = toml::to_string(&cfg).unwrap();
4779 let back: MachineConfig = toml::from_str(&s).unwrap();
4780 assert_eq!(back.name, cfg.name);
4781 assert_eq!(back.location, cfg.location);
4782 assert_eq!(back.region.as_deref(), Some("us-west"));
4783 assert_eq!(back.zone.as_deref(), Some("pdx"));
4784 }
4785
4786 #[test]
4787 fn round_trip_mirror() {
4788 let cfg = LegacyMirrorConfig {
4789 camp: "noisetable".into(),
4790 regions: vec!["pdx".into(), "iad".into()],
4791 workloads: vec!["asset-registry".into()],
4792 cloud_domain: None,
4793 };
4794 let s = toml::to_string(&cfg).unwrap();
4795 let back: LegacyMirrorConfig = toml::from_str(&s).unwrap();
4796 assert_eq!(back.camp, cfg.camp);
4797 assert_eq!(back.regions, cfg.regions);
4798 assert_eq!(back.workloads, cfg.workloads);
4799 }
4800
4801 #[test]
4802 fn mirror_serialises_as_camp_key() {
4803 // Serialised form should use `camp`, not `rig`.
4804 let cfg = LegacyMirrorConfig {
4805 camp: "noisetable".into(),
4806 regions: vec!["pdx".into()],
4807 workloads: vec![],
4808 cloud_domain: None,
4809 };
4810 let s = toml::to_string(&cfg).unwrap();
4811 assert!(
4812 s.contains("camp = "),
4813 "serialised key should be 'camp': {s}"
4814 );
4815 assert!(!s.contains("rig = "), "old key should not appear: {s}");
4816 }
4817
4818 #[test]
4819 fn mirror_rig_alias_still_loads() {
4820 // Old mirrors/*.toml files use `rig = "..."` before the R137 rename;
4821 // the alias keeps them loading until the one-time `sed` migration runs.
4822 let toml_str =
4823 "rig = \"noisetable\"\nregions = [\"pdx\"]\nworkloads = [\"asset-registry\"]\n";
4824 let cfg: LegacyMirrorConfig = toml::from_str(toml_str).unwrap();
4825 assert_eq!(cfg.camp, "noisetable");
4826 }
4827
4828 #[test]
4829 fn mirror_services_alias_still_loads() {
4830 // Old mirrors/*.toml files use `services = [...]`; the alias keeps them
4831 // loading without a migration step.
4832 let toml_str =
4833 "camp = \"noisetable\"\nregions = [\"pdx\"]\nservices = [\"asset-registry\"]\n";
4834 let cfg: LegacyMirrorConfig = toml::from_str(toml_str).unwrap();
4835 assert_eq!(cfg.workloads, vec!["asset-registry"]);
4836 }
4837
4838 #[test]
4839 fn round_trip_service_legacy() {
4840 let cfg = LegacyServiceConfig {
4841 name: "asset-registry".into(),
4842 image: "ghcr.io/noisetable/asset-registry".into(),
4843 version: "v1.0.0".into(),
4844 env: HashMap::new(),
4845 ports: vec![PortMapping {
4846 host: 8080,
4847 container: 8080,
4848 }],
4849 mesh_only: false,
4850 bind_interface: None,
4851 tenant: TenantId::singleton(),
4852 };
4853 let s = toml::to_string(&cfg).unwrap();
4854 let back: LegacyServiceConfig = toml::from_str(&s).unwrap();
4855 assert_eq!(back.name, cfg.name);
4856 assert_eq!(back.image, cfg.image);
4857 }
4858
4859 #[test]
4860 fn service_bind_interface_round_trips() {
4861 let cfg = LegacyServiceConfig {
4862 name: "postgres".into(),
4863 image: "postgres".into(),
4864 version: "16".into(),
4865 env: HashMap::new(),
4866 ports: vec![PortMapping {
4867 host: 5432,
4868 container: 5432,
4869 }],
4870 mesh_only: true,
4871 bind_interface: Some("tailscale0".into()),
4872 tenant: TenantId::singleton(),
4873 };
4874 let s = toml::to_string(&cfg).unwrap();
4875 let back: LegacyServiceConfig = toml::from_str(&s).unwrap();
4876 assert_eq!(back.bind_interface.as_deref(), Some("tailscale0"));
4877 }
4878
4879 #[test]
4880 fn service_bind_interface_absent_is_none() {
4881 let toml_str = "name = \"app\"\nimage = \"app\"\nversion = \"v1\"\n";
4882 let cfg: LegacyServiceConfig = toml::from_str(toml_str).unwrap();
4883 assert!(
4884 cfg.bind_interface.is_none(),
4885 "bind_interface should default to None"
4886 );
4887 }
4888
4889 #[test]
4890 fn service_bind_interface_skipped_when_none() {
4891 let cfg = LegacyServiceConfig {
4892 name: "app".into(),
4893 image: "app".into(),
4894 version: "v1".into(),
4895 env: HashMap::new(),
4896 ports: vec![],
4897 mesh_only: false,
4898 bind_interface: None,
4899 tenant: TenantId::singleton(),
4900 };
4901 let s = toml::to_string(&cfg).unwrap();
4902 assert!(!s.contains("bind_interface"), "None should be skipped: {s}");
4903 }
4904
4905 #[test]
4906 fn load_dir_missing_is_empty() {
4907 let dir = std::path::PathBuf::from("/nonexistent/path");
4908 let result: Vec<MachineConfig> = load_dir(dir).unwrap();
4909 assert!(result.is_empty());
4910 }
4911
4912 #[test]
4913 fn topology_round_trip() {
4914 let topo = TopologyConfig {
4915 assignments: vec![
4916 MirrorAssignment {
4917 mirror: "noisetable-pdx".into(),
4918 machine: "noisetable-pdx-1".into(),
4919 },
4920 MirrorAssignment {
4921 mirror: "noisetable-iad".into(),
4922 machine: "noisetable-iad-1".into(),
4923 },
4924 ],
4925 buckets: vec![],
4926 };
4927 let s = toml::to_string(&topo).unwrap();
4928 let back: TopologyConfig = toml::from_str(&s).unwrap();
4929 assert_eq!(back.assignments.len(), 2);
4930 assert_eq!(back.assignments[0].mirror, "noisetable-pdx");
4931 assert_eq!(back.assignments[1].machine, "noisetable-iad-1");
4932 }
4933
4934 #[test]
4935 fn topology_absent_returns_default() {
4936 let tmp = tempfile::TempDir::new().unwrap();
4937 let path = tmp.path().join("topology.toml");
4938 // file doesn't exist
4939 let topo = load_topology(path).unwrap();
4940 assert!(topo.assignments.is_empty());
4941 }
4942
4943 /// Helper: lay out a `<workspace_root>/.yah/cloud/` legacy tree for the
4944 /// pre-R215 cargo tests below; returns the legacy cloud_dir for writes.
4945 fn make_legacy_cloud_dir(root: &std::path::Path) -> std::path::PathBuf {
4946 let cloud_dir = root.join(".yah").join("cloud");
4947 std::fs::create_dir_all(&cloud_dir).unwrap();
4948 cloud_dir
4949 }
4950
4951 #[test]
4952 fn cloud_config_load_and_lookup() {
4953 let tmp = tempfile::TempDir::new().unwrap();
4954 let root = tmp.path();
4955 let cloud_dir = make_legacy_cloud_dir(root);
4956
4957 let machine = MachineConfig {
4958 name: "noisetable-pdx-1".into(),
4959 provider: "hetzner".into(),
4960 location: Some("pdx".into()),
4961 server_type: Some("cpx22".into()),
4962 hosts_mirrors: vec!["noisetable".into(), "yah".into()],
4963 mesh_tags: vec!["region:pdx".into(), "tier:t2".into()],
4964 region: None,
4965 zone: None,
4966 arch: None,
4967 bucket: Some(BucketSpec {
4968 name: "noisetable-assets-pdx-1".into(),
4969 public_read: false,
4970 }),
4971 vendor: None,
4972 nickname: None,
4973 legacy_hostkey_fingerprint: None,
4974 registration: Default::default(),
4975 ssh_keys: vec![],
4976 cloudflared: None,
4977 hosts_operator_bridge: false,
4978 connect: None,
4979 allocatable: None,
4980 taints: vec![],
4981 sovereign_group: None,
4982 sovereign_role: None,
4983 };
4984 // Land in the legacy tree so the legacy machine loader picks it up.
4985 machine.save(&cloud_dir).unwrap();
4986
4987 let mirror_toml = "camp = \"noisetable\"\nregions = [\"pdx\", \"iad\", \"fsn\"]\nworkloads = [\"asset-registry\"]\n";
4988 std::fs::create_dir_all(cloud_dir.join("mirrors")).unwrap();
4989 std::fs::write(cloud_dir.join("mirrors/noisetable.toml"), mirror_toml).unwrap();
4990
4991 // Legacy services/ dir (backward compat)
4992 let svc_toml = "name = \"asset-registry\"\nimage = \"ghcr.io/noisetable/asset-registry\"\nversion = \"v1.0.0\"\nmesh_only = false\n";
4993 std::fs::create_dir_all(cloud_dir.join("services")).unwrap();
4994 std::fs::write(cloud_dir.join("services/asset-registry.toml"), svc_toml).unwrap();
4995
4996 let cfg = CloudConfig::load(root).unwrap();
4997
4998 assert_eq!(cfg.machines.len(), 1);
4999 assert_eq!(cfg.legacy_mirrors.len(), 1);
5000 assert_eq!(cfg.legacy_services.len(), 1);
5001 assert_eq!(cfg.workloads.len(), 0); // no workloads/ dir yet
5002 assert!(cfg.services.is_empty(), "no R215+ services/ tree");
5003 assert!(cfg.providers.is_empty(), "no R215+ providers/ tree");
5004
5005 let m = cfg.machine("noisetable-pdx-1").unwrap();
5006 assert_eq!(m.location(), "pdx");
5007 assert_eq!(m.bucket.as_ref().unwrap().name, "noisetable-assets-pdx-1");
5008
5009 let mir = cfg.legacy_mirror("noisetable").unwrap();
5010 assert_eq!(mir.regions, vec!["pdx", "iad", "fsn"]);
5011 assert_eq!(mir.workloads, vec!["asset-registry"]);
5012 }
5013
5014 #[test]
5015 fn mirror_folder_layout_loads() {
5016 // Folder layout: mirrors/<id>/mirror.toml — new preferred form.
5017 let tmp = tempfile::TempDir::new().unwrap();
5018 let root = tmp.path();
5019 let cloud_dir = make_legacy_cloud_dir(root);
5020 let mirror_dir = cloud_dir.join("mirrors").join("yah-com");
5021 std::fs::create_dir_all(&mirror_dir).unwrap();
5022 std::fs::write(
5023 mirror_dir.join("mirror.toml"),
5024 "camp = \"yah\"\nregions = [\"pdx\"]\nworkloads = [\"yah-web\"]\n",
5025 )
5026 .unwrap();
5027
5028 let cfg = CloudConfig::load(root).unwrap();
5029 assert_eq!(cfg.legacy_mirrors.len(), 1);
5030 let mir = cfg.legacy_mirror("yah").unwrap();
5031 assert_eq!(mir.camp, "yah");
5032 assert_eq!(mir.workloads, vec!["yah-web"]);
5033 }
5034
5035 #[test]
5036 fn mirror_folder_and_flat_coexist() {
5037 // Both layouts may coexist in the same mirrors/ directory.
5038 let tmp = tempfile::TempDir::new().unwrap();
5039 let root = tmp.path();
5040 let cloud_dir = make_legacy_cloud_dir(root);
5041 let mirrors_root = cloud_dir.join("mirrors");
5042 std::fs::create_dir_all(&mirrors_root).unwrap();
5043
5044 // Flat legacy mirror
5045 std::fs::write(
5046 mirrors_root.join("noisetable.toml"),
5047 "camp = \"noisetable\"\nregions = [\"pdx\"]\nworkloads = []\n",
5048 )
5049 .unwrap();
5050
5051 // Folder-form mirror
5052 let yah_com_dir = mirrors_root.join("yah-com");
5053 std::fs::create_dir_all(&yah_com_dir).unwrap();
5054 std::fs::write(
5055 yah_com_dir.join("mirror.toml"),
5056 "camp = \"yah\"\nregions = [\"pdx\"]\nworkloads = []\n",
5057 )
5058 .unwrap();
5059
5060 let cfg = CloudConfig::load(root).unwrap();
5061 assert_eq!(cfg.legacy_mirrors.len(), 2);
5062 assert!(cfg.legacy_mirror("noisetable").is_some());
5063 assert!(cfg.legacy_mirror("yah").is_some());
5064 }
5065
5066 #[test]
5067 fn mirror_malformed_fails_with_field_path() {
5068 // A malformed mirror.toml should fail at load with a clear error
5069 // that includes the file path.
5070 let tmp = tempfile::TempDir::new().unwrap();
5071 let root = tmp.path();
5072 let cloud_dir = make_legacy_cloud_dir(root);
5073 let mirror_dir = cloud_dir.join("mirrors").join("bad");
5074 std::fs::create_dir_all(&mirror_dir).unwrap();
5075 // Missing required `camp` field
5076 std::fs::write(
5077 mirror_dir.join("mirror.toml"),
5078 "regions = [\"pdx\"]\nworkloads = []\n",
5079 )
5080 .unwrap();
5081
5082 let err = CloudConfig::load(root).unwrap_err();
5083 let msg = err.to_string();
5084 assert!(
5085 msg.contains("mirror.toml"),
5086 "error should reference the file path, got: {msg}"
5087 );
5088 }
5089
5090 #[test]
5091 fn workload_config_load_and_validate() {
5092 use workload_spec::{
5093 ExposeSpec, ImageRef, MeshExpose, MeshIdent, NamespaceId, ResourceLimits,
5094 RestartPolicy, SchemaVersion, StopPolicy, TenantId, TierTag, WorkloadSpec,
5095 };
5096
5097 let tmp = tempfile::TempDir::new().unwrap();
5098 let root = tmp.path();
5099 let cloud_dir = make_legacy_cloud_dir(root);
5100 std::fs::create_dir_all(cloud_dir.join("workloads")).unwrap();
5101
5102 let spec = WorkloadSpec {
5103 schema_version: SchemaVersion::V1,
5104 name: "asset-registry".into(),
5105 image: ImageRef {
5106 registry: "ghcr.io".into(),
5107 repository: "noisetable/asset-registry".into(),
5108 tag: "v1.0.0".into(),
5109 digest: workload_spec::testing::test_digest(),
5110 },
5111 tier: TierTag("tenant".into()),
5112 replicas: 1,
5113 command: None,
5114 entrypoint: None,
5115 workdir: None,
5116 user: None,
5117 env: vec![],
5118 secrets: vec![],
5119 volumes: vec![],
5120 resources: ResourceLimits {
5121 memory_mb: 256,
5122 cpu_millis: 512,
5123 ephemeral_storage_mb: 512,
5124 },
5125 depends_on: vec![],
5126 healthcheck: None,
5127 restart_policy: RestartPolicy::Always,
5128 archetype: None,
5129 stop_policy: StopPolicy {
5130 signal: 15,
5131 grace_period: workload_spec::Millis::from_secs(10),
5132 },
5133 expose: ExposeSpec {
5134 mesh: MeshExpose {
5135 identity: MeshIdent("asset-registry.pdx".into()),
5136 ports: vec![8080],
5137 allow_from: vec![],
5138 },
5139 public: None,
5140 operator: None,
5141 },
5142 tenant: TenantId::singleton(),
5143 namespace: NamespaceId::singleton(),
5144 labels: Default::default(),
5145 annotations: Default::default(),
5146 };
5147
5148 let toml_str = toml::to_string_pretty(&spec).unwrap();
5149 std::fs::write(cloud_dir.join("workloads/asset-registry.toml"), &toml_str).unwrap();
5150
5151 let cfg = CloudConfig::load(root).unwrap();
5152 assert_eq!(cfg.workloads.len(), 1);
5153 assert_eq!(cfg.workloads[0].spec.name, "asset-registry");
5154 assert_eq!(cfg.workload("asset-registry").unwrap().spec.replicas, 1);
5155 }
5156
5157 /// Minimal valid spec for the R215+ loader tests below. Kept as a helper so
5158 /// the two tests differ only in *where* the file lands, which is the whole
5159 /// thing under test.
5160 #[cfg(test)]
5161 fn minimal_spec(name: &str, replicas: u32) -> workload_spec::WorkloadSpec {
5162 use workload_spec::{
5163 ExposeSpec, ImageRef, MeshExpose, MeshIdent, NamespaceId, ResourceLimits,
5164 RestartPolicy, SchemaVersion, StopPolicy, TenantId, TierTag, WorkloadSpec,
5165 };
5166 WorkloadSpec {
5167 schema_version: SchemaVersion::V1,
5168 name: name.into(),
5169 image: ImageRef {
5170 registry: "cr.yah.dev".into(),
5171 repository: name.into(),
5172 tag: "v1".into(),
5173 digest: workload_spec::testing::test_digest(),
5174 },
5175 tier: TierTag("infra".into()),
5176 replicas,
5177 command: None,
5178 entrypoint: None,
5179 workdir: None,
5180 user: None,
5181 env: vec![],
5182 secrets: vec![],
5183 volumes: vec![],
5184 resources: ResourceLimits {
5185 memory_mb: 256,
5186 cpu_millis: 250,
5187 ephemeral_storage_mb: 128,
5188 },
5189 depends_on: vec![],
5190 healthcheck: None,
5191 restart_policy: RestartPolicy::Always,
5192 archetype: None,
5193 stop_policy: StopPolicy {
5194 signal: 15,
5195 grace_period: workload_spec::Millis::from_secs(10),
5196 },
5197 expose: ExposeSpec {
5198 mesh: MeshExpose {
5199 identity: MeshIdent(name.into()),
5200 ports: vec![4325],
5201 allow_from: vec![],
5202 },
5203 public: None,
5204 operator: None,
5205 },
5206 tenant: TenantId::singleton(),
5207 namespace: NamespaceId::singleton(),
5208 labels: Default::default(),
5209 annotations: Default::default(),
5210 }
5211 }
5212
5213 /// R568-T7. Workloads must load from the R215+ tree.
5214 ///
5215 /// Before the fix this function tested, `CloudConfig::load` read workloads
5216 /// ONLY from the pre-R215 `.yah/cloud/workloads/` — which R222-B1 emptied —
5217 /// so in any modern camp `cfg.workload(name)` returned `None` for every
5218 /// name and the entire `yah cloud workload …` surface was unreachable. The
5219 /// CLI's own error text has said `.yah/infra/workloads/` throughout, so the
5220 /// bug read as "you must have typoed the filename".
5221 ///
5222 /// Note the fixture writes NO legacy `.yah/cloud/` dir at all: that is the
5223 /// shape of a real post-R215 camp, and it is exactly the shape the old code
5224 /// could not serve.
5225 #[test]
5226 fn workloads_load_from_the_infra_tree() {
5227 let tmp = tempfile::TempDir::new().unwrap();
5228 let root = tmp.path();
5229 let dir = crate::paths::workloads_dir(root);
5230 std::fs::create_dir_all(&dir).unwrap();
5231 std::fs::write(
5232 dir.join("yah-cloud-admin.toml"),
5233 toml::to_string_pretty(&minimal_spec("yah-cloud-admin", 1)).unwrap(),
5234 )
5235 .unwrap();
5236
5237 let cfg = CloudConfig::load(root).unwrap();
5238 assert_eq!(cfg.workloads.len(), 1);
5239 assert_eq!(
5240 cfg.workload("yah-cloud-admin").unwrap().spec.replicas,
5241 1,
5242 "a workload declared under .yah/infra/workloads/ must be resolvable by name"
5243 );
5244 }
5245
5246 /// A camp mid-migration can have both trees. R215+ wins on a name
5247 /// collision — same precedence the machine loader applies — so moving a
5248 /// declaration into `.yah/infra/workloads/` takes effect immediately
5249 /// instead of being silently shadowed by the copy left behind.
5250 #[test]
5251 fn infra_workload_shadows_the_legacy_copy_of_the_same_name() {
5252 let tmp = tempfile::TempDir::new().unwrap();
5253 let root = tmp.path();
5254
5255 let legacy = make_legacy_cloud_dir(root);
5256 std::fs::create_dir_all(legacy.join("workloads")).unwrap();
5257 std::fs::write(
5258 legacy.join("workloads/shared.toml"),
5259 toml::to_string_pretty(&minimal_spec("shared", 9)).unwrap(),
5260 )
5261 .unwrap();
5262 // Legacy-only name, to prove the old tree is still read rather than
5263 // replaced wholesale.
5264 std::fs::write(
5265 legacy.join("workloads/legacy-only.toml"),
5266 toml::to_string_pretty(&minimal_spec("legacy-only", 3)).unwrap(),
5267 )
5268 .unwrap();
5269
5270 let infra = crate::paths::workloads_dir(root);
5271 std::fs::create_dir_all(&infra).unwrap();
5272 std::fs::write(
5273 infra.join("shared.toml"),
5274 toml::to_string_pretty(&minimal_spec("shared", 1)).unwrap(),
5275 )
5276 .unwrap();
5277
5278 let cfg = CloudConfig::load(root).unwrap();
5279 assert_eq!(cfg.workloads.len(), 2, "one `shared`, plus `legacy-only`");
5280 assert_eq!(
5281 cfg.workload("shared").unwrap().spec.replicas,
5282 1,
5283 "the .yah/infra/ copy must win over the legacy one"
5284 );
5285 assert_eq!(cfg.workload("legacy-only").unwrap().spec.replicas, 3);
5286 }
5287
5288 #[test]
5289 fn workload_loader_rejects_bad_spec() {
5290 use workload_spec::{
5291 ExposeSpec, ImageRef, MeshExpose, MeshIdent, NamespaceId, ResourceLimits,
5292 RestartPolicy, SchemaVersion, StopPolicy, TenantId, TierTag, WorkloadSpec,
5293 };
5294
5295 let tmp = tempfile::TempDir::new().unwrap();
5296 let root = tmp.path();
5297 let cloud_dir = make_legacy_cloud_dir(root);
5298 std::fs::create_dir_all(cloud_dir.join("workloads")).unwrap();
5299
5300 // Construct a spec that round-trips through TOML but fails shape
5301 // validation: replicas = 200 is above the max of 100.
5302 let mut spec = WorkloadSpec {
5303 schema_version: SchemaVersion::V1,
5304 name: "asset-registry".into(),
5305 image: ImageRef {
5306 registry: "ghcr.io".into(),
5307 repository: "test/app".into(),
5308 tag: "v1".into(),
5309 digest: workload_spec::testing::test_digest(),
5310 },
5311 tier: TierTag("tenant".into()),
5312 replicas: 200, // ← invalid: exceeds max 100
5313 command: None,
5314 entrypoint: None,
5315 workdir: None,
5316 user: None,
5317 env: vec![],
5318 secrets: vec![],
5319 volumes: vec![],
5320 resources: ResourceLimits {
5321 memory_mb: 256,
5322 cpu_millis: 512,
5323 ephemeral_storage_mb: 512,
5324 },
5325 depends_on: vec![],
5326 healthcheck: None,
5327 restart_policy: RestartPolicy::Always,
5328 archetype: None,
5329 stop_policy: StopPolicy {
5330 signal: 15,
5331 grace_period: workload_spec::Millis::from_secs(10),
5332 },
5333 expose: ExposeSpec {
5334 mesh: MeshExpose {
5335 identity: MeshIdent("asset-registry.pdx".into()),
5336 ports: vec![8080],
5337 allow_from: vec![],
5338 },
5339 public: None,
5340 operator: None,
5341 },
5342 tenant: TenantId::singleton(),
5343 namespace: NamespaceId::singleton(),
5344 labels: Default::default(),
5345 annotations: Default::default(),
5346 };
5347
5348 let toml_str = toml::to_string_pretty(&spec).unwrap();
5349 std::fs::write(cloud_dir.join("workloads/bad.toml"), &toml_str).unwrap();
5350
5351 let result = CloudConfig::load(root);
5352 assert!(
5353 result.is_err(),
5354 "loading a WorkloadSpec with replicas=200 should return Err"
5355 );
5356 let msg = result.unwrap_err().to_string();
5357 assert!(
5358 msg.contains("shape validation")
5359 || msg.contains("Replicas")
5360 || msg.contains("replicas"),
5361 "error should mention shape validation or replicas field, got: {msg}"
5362 );
5363
5364 // The `spec` binding is only used for the write — suppress warning.
5365 let _ = &mut spec;
5366 }
5367
5368 #[test]
5369 fn workload_config_save_round_trip() {
5370 use workload_spec::{
5371 ExposeSpec, ImageRef, MeshExpose, MeshIdent, NamespaceId, ResourceLimits,
5372 RestartPolicy, SchemaVersion, StopPolicy, TenantId, TierTag, WorkloadSpec,
5373 };
5374
5375 let tmp = tempfile::TempDir::new().unwrap();
5376 let root = tmp.path();
5377
5378 let spec = WorkloadSpec {
5379 schema_version: SchemaVersion::V1,
5380 name: "signing-service".into(),
5381 image: ImageRef {
5382 registry: "ghcr.io".into(),
5383 repository: "noisetable/signing".into(),
5384 tag: "v2.0.0".into(),
5385 digest: workload_spec::testing::test_digest(),
5386 },
5387 tier: TierTag("private".into()),
5388 replicas: 2,
5389 command: None,
5390 entrypoint: None,
5391 workdir: None,
5392 user: None,
5393 env: vec![],
5394 secrets: vec![],
5395 volumes: vec![],
5396 resources: ResourceLimits {
5397 memory_mb: 128,
5398 cpu_millis: 256,
5399 ephemeral_storage_mb: 256,
5400 },
5401 depends_on: vec![],
5402 healthcheck: None,
5403 restart_policy: RestartPolicy::Always,
5404 archetype: None,
5405 stop_policy: StopPolicy {
5406 signal: 15,
5407 grace_period: workload_spec::Millis::from_secs(5),
5408 },
5409 expose: ExposeSpec {
5410 mesh: MeshExpose {
5411 identity: MeshIdent("signing.pdx".into()),
5412 ports: vec![9090],
5413 allow_from: vec![],
5414 },
5415 public: None,
5416 operator: None,
5417 },
5418 tenant: TenantId::singleton(),
5419 namespace: NamespaceId::singleton(),
5420 labels: Default::default(),
5421 annotations: Default::default(),
5422 };
5423
5424 let wc = WorkloadConfig { spec };
5425 let cloud_dir = make_legacy_cloud_dir(root);
5426 wc.save(&cloud_dir).unwrap();
5427
5428 let loaded = CloudConfig::load(root).unwrap();
5429 assert_eq!(loaded.workloads.len(), 1);
5430 assert_eq!(loaded.workloads[0].spec.name, "signing-service");
5431 assert_eq!(loaded.workloads[0].spec.replicas, 2);
5432 }
5433
5434 #[test]
5435 fn machine_save_write_back_fingerprint() {
5436 let tmp = tempfile::TempDir::new().unwrap();
5437 let root = tmp.path();
5438
5439 let mut machine = MachineConfig {
5440 name: "test-pdx-1".into(),
5441 provider: "hetzner".into(),
5442 location: Some("pdx".into()),
5443 server_type: Some("cpx22".into()),
5444 hosts_mirrors: vec![],
5445 mesh_tags: vec![],
5446 region: None,
5447 zone: None,
5448 arch: None,
5449 bucket: None,
5450 vendor: None,
5451 nickname: None,
5452 legacy_hostkey_fingerprint: None,
5453 registration: Default::default(),
5454 ssh_keys: vec![],
5455 cloudflared: None,
5456 hosts_operator_bridge: false,
5457 connect: None,
5458 allocatable: None,
5459 taints: vec![],
5460 sovereign_group: None,
5461 sovereign_role: None,
5462 };
5463 machine.save(root).unwrap();
5464
5465 // Simulate A4: write back the hostkey fingerprint after provision.
5466 // R707-T1: registration is the write target; the accessor is the read.
5467 machine.registration.hostkey_fingerprint = Some("SHA256:abc123".into());
5468 machine.save(root).unwrap();
5469
5470 let reloaded: Vec<MachineConfig> = load_dir(root.join("machines")).unwrap();
5471 assert_eq!(reloaded.len(), 1);
5472 assert_eq!(reloaded[0].hostkey_fingerprint(), Some("SHA256:abc123"));
5473 }
5474
5475 // ─── New-shape (R222 B2) parse tests ────────────────────────────────────
5476 //
5477 // These mirror the Phase-A manifests committed under `.yah/services/` and
5478 // `.yah/infra/providers/`. Keeping the test strings inline (rather than
5479 // reading the on-disk files) so the loader stays runnable in any workdir
5480 // and so accidental edits to the on-disk files don't silently change
5481 // schema expectations.
5482
5483 #[test]
5484 fn provider_cloudflare_round_trips() {
5485 let src = r#"
5486schema_version = 1
5487id = "cloudflare"
5488kind = "cloudflare"
5489credentials = "keystore://cloudflare/yah"
5490default_zone = "yah.dev"
5491"#;
5492 let cfg: ProviderConfig = toml::from_str(src).unwrap();
5493 assert_eq!(cfg.id, "cloudflare");
5494 assert_eq!(cfg.kind, Provider::Cloudflare);
5495 assert_eq!(
5496 cfg.credentials.as_deref(),
5497 Some("keystore://cloudflare/yah")
5498 );
5499 assert_eq!(
5500 cfg.fields.get("default_zone").and_then(|v| v.as_str()),
5501 Some("yah.dev"),
5502 );
5503 let back = toml::to_string(&cfg).unwrap();
5504 let again: ProviderConfig = toml::from_str(&back).unwrap();
5505 assert_eq!(again.id, cfg.id);
5506 assert_eq!(again.kind, cfg.kind);
5507 }
5508
5509 #[test]
5510 fn provider_hetzner_round_trips() {
5511 let src = r#"
5512schema_version = 1
5513id = "hetzner"
5514kind = "hetzner"
5515credentials = "keystore://hetzner/yah"
5516default_location = "pdx"
5517default_server_type = "cpx11"
5518ssh_keys = []
5519"#;
5520 let cfg: ProviderConfig = toml::from_str(src).unwrap();
5521 assert_eq!(cfg.kind, Provider::Hetzner);
5522 assert_eq!(
5523 cfg.fields.get("default_location").and_then(|v| v.as_str()),
5524 Some("pdx"),
5525 );
5526 assert!(
5527 cfg.fields
5528 .get("ssh_keys")
5529 .map(|v| v.as_array().unwrap().is_empty())
5530 .unwrap_or(false),
5531 "ssh_keys must round-trip as empty array, got {:?}",
5532 cfg.fields.get("ssh_keys"),
5533 );
5534 }
5535
5536 #[test]
5537 fn provider_orbstack_local_container_round_trips() {
5538 let src = r#"
5539schema_version = 1
5540id = "orbstack"
5541kind = "local-container"
5542runtime = "auto"
5543
5544[discovery]
5545orbstack = "~/.orbstack/run/docker.sock"
5546colima = "~/.colima/default/docker.sock"
5547docker = "/var/run/docker.sock"
5548"#;
5549 let cfg: ProviderConfig = toml::from_str(src).unwrap();
5550 assert_eq!(cfg.kind, Provider::LocalContainer);
5551 assert_eq!(
5552 cfg.fields.get("runtime").and_then(|v| v.as_str()),
5553 Some("auto"),
5554 );
5555 let discovery = cfg
5556 .fields
5557 .get("discovery")
5558 .and_then(|v| v.as_table())
5559 .expect("discovery table");
5560 assert!(discovery.contains_key("orbstack"));
5561 assert!(discovery.contains_key("colima"));
5562 assert!(discovery.contains_key("docker"));
5563 }
5564
5565 #[test]
5566 fn provider_unknown_kind_fails() {
5567 let src = r#"
5568schema_version = 1
5569id = "made-up"
5570kind = "fly-io"
5571"#;
5572 let err = toml::from_str::<ProviderConfig>(src).unwrap_err();
5573 let msg = err.to_string();
5574 assert!(
5575 msg.contains("kind") || msg.contains("variant"),
5576 "unknown provider kind should surface as a serde error, got: {msg}"
5577 );
5578 }
5579
5580 #[test]
5581 fn service_dev_yah_round_trips() {
5582 let src = r#"
5583schema_version = 1
5584name = "dev-yah"
5585domain = "yah.dev"
5586
5587[[components]]
5588id = "site"
5589kind = "mesofact-static"
5590path = "app/yah/web"
5591role = "static"
5592"#;
5593 let cfg: ServiceConfig = toml::from_str(src).unwrap();
5594 assert_eq!(cfg.name, "dev-yah");
5595 assert_eq!(cfg.domain, "yah.dev");
5596 assert_eq!(cfg.components.len(), 1);
5597 let c = &cfg.components[0];
5598 assert_eq!(c.id, "site");
5599 assert_eq!(c.kind, "mesofact-static");
5600 assert_eq!(c.path, "app/yah/web");
5601 assert_eq!(c.role, "static");
5602 assert!(c.publishes.is_none());
5603
5604 let back = toml::to_string(&cfg).unwrap();
5605 let again: ServiceConfig = toml::from_str(&back).unwrap();
5606 assert_eq!(again.name, cfg.name);
5607 assert_eq!(again.components[0].kind, c.kind);
5608 }
5609
5610 #[test]
5611 fn mirror_prod_cloudflare_reference_parses() {
5612 let src = r#"
5613schema_version = 1
5614shape = "single-machine"
5615
5616[providers.static]
5617use = "cloudflare"
5618bucket = "yah-dev"
5619zone = "yah.dev"
5620dns = { record = "@", type = "CNAME" }
5621"#;
5622 let cfg: MirrorConfig = toml::from_str(src).unwrap();
5623 assert_eq!(cfg.shape, MirrorShape::SingleMachine);
5624 let slot = cfg.providers.get("static").expect("static slot");
5625 assert_eq!(slot.provider_id(), Some("cloudflare"));
5626 assert!(slot.inline_kind().is_none());
5627 if let MirrorProviderSlot::Reference { fields, .. } = slot {
5628 assert_eq!(
5629 fields.get("bucket").and_then(|v| v.as_str()),
5630 Some("yah-dev")
5631 );
5632 assert_eq!(fields.get("zone").and_then(|v| v.as_str()), Some("yah.dev"));
5633 let dns = fields
5634 .get("dns")
5635 .and_then(|v| v.as_table())
5636 .expect("dns table");
5637 assert_eq!(dns.get("record").and_then(|v| v.as_str()), Some("@"));
5638 assert_eq!(dns.get("type").and_then(|v| v.as_str()), Some("CNAME"));
5639 } else {
5640 panic!("expected Reference slot");
5641 }
5642 }
5643
5644 #[test]
5645 fn mirror_local_inline_static_and_orbstack_compute_parse() {
5646 let src = r#"
5647schema_version = 1
5648shape = "local"
5649
5650[providers.static]
5651kind = "local-static"
5652port = 4321
5653artifact_dir = ".yah/infra/state/local/static"
5654
5655[providers.compute]
5656use = "orbstack"
5657"#;
5658 let cfg: MirrorConfig = toml::from_str(src).unwrap();
5659 assert_eq!(cfg.shape, MirrorShape::Local);
5660
5661 let static_slot = cfg.providers.get("static").expect("static slot");
5662 assert_eq!(static_slot.inline_kind(), Some(Provider::LocalStatic));
5663 assert!(static_slot.provider_id().is_none());
5664 if let MirrorProviderSlot::Inline { fields, .. } = static_slot {
5665 assert_eq!(fields.get("port").and_then(|v| v.as_integer()), Some(4321));
5666 assert_eq!(
5667 fields.get("artifact_dir").and_then(|v| v.as_str()),
5668 Some(".yah/infra/state/local/static"),
5669 );
5670 } else {
5671 panic!("expected Inline slot for static");
5672 }
5673
5674 let compute_slot = cfg.providers.get("compute").expect("compute slot");
5675 assert_eq!(compute_slot.provider_id(), Some("orbstack"));
5676 }
5677
5678 #[test]
5679 fn mirror_pond_miniflare_minio_parse() {
5680 // pond-tier mirror: miniflare-container + minio, both inline.
5681 // T1 just needs these inline kinds to parse — the reconciler dispatch
5682 // arrives in R256-T3.
5683 let src = r#"
5684schema_version = 1
5685shape = "local"
5686
5687[providers.static]
5688kind = "miniflare-container"
5689port = 4322
5690bucket = "yah-dev"
5691
5692[providers.object_store]
5693kind = "minio-container"
5694api_port = 9000
5695console_port = 9001
5696bucket = "yah-dev"
5697"#;
5698 let cfg: MirrorConfig = toml::from_str(src).unwrap();
5699 assert_eq!(cfg.shape, MirrorShape::Local);
5700
5701 let static_slot = cfg.providers.get("static").expect("static slot");
5702 assert_eq!(
5703 static_slot.inline_kind(),
5704 Some(Provider::MiniflareContainer)
5705 );
5706 if let MirrorProviderSlot::Inline { fields, .. } = static_slot {
5707 assert_eq!(fields.get("port").and_then(|v| v.as_integer()), Some(4322));
5708 assert_eq!(
5709 fields.get("bucket").and_then(|v| v.as_str()),
5710 Some("yah-dev")
5711 );
5712 } else {
5713 panic!("expected Inline slot for miniflare-container static");
5714 }
5715
5716 let object_store_slot = cfg
5717 .providers
5718 .get("object_store")
5719 .expect("object_store slot");
5720 assert_eq!(
5721 object_store_slot.inline_kind(),
5722 Some(Provider::MinioContainer)
5723 );
5724 if let MirrorProviderSlot::Inline { fields, .. } = object_store_slot {
5725 assert_eq!(
5726 fields.get("api_port").and_then(|v| v.as_integer()),
5727 Some(9000)
5728 );
5729 assert_eq!(
5730 fields.get("console_port").and_then(|v| v.as_integer()),
5731 Some(9001)
5732 );
5733 assert_eq!(
5734 fields.get("bucket").and_then(|v| v.as_str()),
5735 Some("yah-dev")
5736 );
5737 } else {
5738 panic!("expected Inline slot for minio-container object_store");
5739 }
5740 }
5741
5742 #[test]
5743 fn provider_miniflare_container_kind_round_trips() {
5744 // Inline-only kind; never declared as a standalone provider file but
5745 // the enum round-trip is still exercised through ProviderConfig because
5746 // schemars/serde share the variant table.
5747 let cfg = MirrorProviderSlot::Inline {
5748 kind: Provider::MiniflareContainer,
5749 fields: BTreeMap::new(),
5750 };
5751 let s = toml::to_string(&cfg).unwrap();
5752 assert!(
5753 s.contains("kind = \"miniflare-container\""),
5754 "kebab-case wire form expected, got: {s}"
5755 );
5756 let back: MirrorProviderSlot = toml::from_str(&s).unwrap();
5757 assert_eq!(back.inline_kind(), Some(Provider::MiniflareContainer));
5758 }
5759
5760 #[test]
5761 fn provider_minio_container_kind_round_trips() {
5762 let cfg = MirrorProviderSlot::Inline {
5763 kind: Provider::MinioContainer,
5764 fields: BTreeMap::new(),
5765 };
5766 let s = toml::to_string(&cfg).unwrap();
5767 assert!(
5768 s.contains("kind = \"minio-container\""),
5769 "kebab-case wire form expected, got: {s}"
5770 );
5771 let back: MirrorProviderSlot = toml::from_str(&s).unwrap();
5772 assert_eq!(back.inline_kind(), Some(Provider::MinioContainer));
5773 }
5774
5775 #[test]
5776 fn mirror_compute_slot_with_machine_reference_parses() {
5777 // The on-disk prod.toml has a commented-out compute slot; this test
5778 // covers the form Phase B will need once yubaba is provisioned.
5779 let src = r#"
5780schema_version = 1
5781shape = "single-machine"
5782
5783[providers.compute]
5784use = "hetzner"
5785machine = "yah-cloud-1"
5786"#;
5787 let cfg: MirrorConfig = toml::from_str(src).unwrap();
5788 let slot = cfg.providers.get("compute").expect("compute slot");
5789 assert_eq!(slot.provider_id(), Some("hetzner"));
5790 if let MirrorProviderSlot::Reference { fields, .. } = slot {
5791 assert_eq!(
5792 fields.get("machine").and_then(|v| v.as_str()),
5793 Some("yah-cloud-1"),
5794 );
5795 }
5796 }
5797
5798 #[test]
5799 fn machine_yah_cloud_1_round_trips_with_existing_shape() {
5800 // The current machine TOML predates B2 — MachineConfig hasn't been
5801 // reshaped yet. This locks the expected shape so we notice if B3
5802 // accidentally regresses it.
5803 let src = r#"
5804name = "yah-cloud-1"
5805provider = "hetzner"
5806location = "pdx"
5807server_type = "cpx11"
5808hosts_mirrors = []
5809mesh_tags = ["tag:tier-scratch", "tag:primary-yah"]
5810ssh_keys = [111513970, 111525493]
5811"#;
5812 let cfg: MachineConfig = toml::from_str(src).unwrap();
5813 assert_eq!(cfg.name, "yah-cloud-1");
5814 assert_eq!(cfg.provider, "hetzner");
5815 assert_eq!(cfg.ssh_keys.len(), 2);
5816 }
5817
5818 #[test]
5819 fn static_node_omits_location_server_type_and_carries_connect() {
5820 // BYO Phase-0: a `static` node we brought up over SSH has no provider
5821 // DC code or SKU; it declares reach in `[connect]` instead. Must load.
5822 let src = r#"
5823name = "us-south-001"
5824provider = "static"
5825region = "us-south"
5826mesh_tags = ["tag:cloud-runner", "tag:voter-candidate"]
5827
5828[connect]
5829address = "45.32.194.254"
5830ssh = "root@45.32.194.254"
5831yubaba = "http://127.0.0.1:7443"
5832arch = "x86_64"
5833"#;
5834 let cfg: MachineConfig = toml::from_str(src).unwrap();
5835 assert_eq!(cfg.provider, "static");
5836 assert!(cfg.location.is_none());
5837 assert!(cfg.server_type.is_none());
5838 assert_eq!(cfg.location(), ""); // accessor defaults empty
5839 let c = cfg.connect.as_ref().expect("connect block");
5840 assert_eq!(c.ssh, "root@45.32.194.254");
5841 // Loopback is a *declared* reach placeholder, so it stays in [connect]
5842 // verbatim and composes straight through (R707-T1).
5843 assert_eq!(c.yubaba.as_deref(), Some("http://127.0.0.1:7443"));
5844 assert_eq!(cfg.yubaba_url().as_deref(), Some("http://127.0.0.1:7443"));
5845 assert_eq!(cfg.mesh_ipv4(), None);
5846 // Static providers have no driver, so validate() is a no-op pass.
5847 assert!(!provider_has_machine_driver(&cfg.provider));
5848 cfg.validate().unwrap();
5849 }
5850
5851 // ─── R707-T1: declaration / registration split ──────────────────────────
5852
5853 /// The pre-split shape — top-level `hostkey_fingerprint`, mesh IP baked
5854 /// into `[connect].yubaba` — must keep parsing, and must read back through
5855 /// the accessors identically. Every machine TOML in the fleet was written
5856 /// this way, and other camps' inventories still are.
5857 #[test]
5858 fn legacy_shape_still_parses_and_reads_through_accessors() {
5859 let src = r#"
5860name = "us-west-001"
5861provider = "static"
5862region = "us-west"
5863arch = "x86_64"
5864mesh_tags = ["tag:cloud-runner"]
5865hostkey_fingerprint = "SHA256:dmpq"
5866
5867[connect]
5868address = "15.204.89.240"
5869ssh = "debian@15.204.89.240"
5870yubaba = "http://100.64.0.1:7443"
5871"#;
5872 let cfg: MachineConfig = toml::from_str(src).unwrap();
5873 assert_eq!(cfg.hostkey_fingerprint(), Some("SHA256:dmpq"));
5874 assert_eq!(cfg.mesh_ipv4(), Some("100.64.0.1"));
5875 assert_eq!(cfg.yubaba_url().as_deref(), Some("http://100.64.0.1:7443"));
5876 }
5877
5878 /// The post-split shape reads identically to the legacy one above — same
5879 /// three accessor answers from a file that separates the two halves. This
5880 /// is the "unchanged in meaning" guarantee the fleet migration rests on.
5881 #[test]
5882 fn split_shape_is_equivalent_to_legacy_shape() {
5883 let legacy = r#"
5884name = "m"
5885provider = "static"
5886mesh_tags = []
5887hostkey_fingerprint = "SHA256:dmpq"
5888
5889[connect]
5890address = "15.204.89.240"
5891ssh = "debian@15.204.89.240"
5892yubaba = "http://100.64.0.1:7443"
5893"#;
5894 let split = r#"
5895name = "m"
5896provider = "static"
5897mesh_tags = []
5898
5899[connect]
5900address = "15.204.89.240"
5901ssh = "debian@15.204.89.240"
5902
5903[registration]
5904hostkey_fingerprint = "SHA256:dmpq"
5905mesh_ipv4 = "100.64.0.1"
5906"#;
5907 let old: MachineConfig = toml::from_str(legacy).unwrap();
5908 let new: MachineConfig = toml::from_str(split).unwrap();
5909 assert_eq!(old.hostkey_fingerprint(), new.hostkey_fingerprint());
5910 assert_eq!(old.mesh_ipv4(), new.mesh_ipv4());
5911 assert_eq!(old.yubaba_url(), new.yubaba_url());
5912 }
5913
5914 /// A non-default `[connect].yubaba_port` is declared reach and composes
5915 /// with the observed mesh address rather than being pinned into a URL.
5916 #[test]
5917 fn declared_port_composes_with_observed_mesh_address() {
5918 let src = r#"
5919name = "m"
5920provider = "static"
5921mesh_tags = []
5922
5923[connect]
5924address = "10.0.0.1"
5925ssh = "yah@10.0.0.1"
5926yubaba_port = 9443
5927
5928[registration]
5929mesh_ipv4 = "100.64.0.9"
5930"#;
5931 let cfg: MachineConfig = toml::from_str(src).unwrap();
5932 assert_eq!(cfg.connect.as_ref().unwrap().yubaba_port(), 9443);
5933 assert_eq!(cfg.yubaba_url().as_deref(), Some("http://100.64.0.9:9443"));
5934 }
5935
5936 /// R605-T10 inverts R707-T6 for the private-literal case, and this is the
5937 /// node it was inverted for: us-west-014's shape, mesh-joined AND declaring
5938 /// a LAN `[connect].yubaba`. R707-T6 made the literal win outright so
5939 /// `rollout::yubaba::membership_to_nodes` could match the dev group's
5940 /// LAN-addressed raft membership — which fused identity into reach and made
5941 /// every automated dial go to an address only bldg-2506 can route.
5942 /// `lan_endpoint()` now serves that match, so the mesh address wins the
5943 /// dial and the literal is inert.
5944 #[test]
5945 fn a_private_literal_loses_to_the_registered_mesh_address() {
5946 let src = r#"
5947name = "us-west-014"
5948provider = "static"
5949mesh_tags = []
5950
5951[connect]
5952address = "192.168.10.14"
5953ssh = "yah@192.168.10.14"
5954yubaba = "http://192.168.10.14:7443"
5955
5956[registration]
5957mesh_ipv4 = "100.64.0.6"
5958"#;
5959 let cfg: MachineConfig = toml::from_str(src).unwrap();
5960 assert_eq!(cfg.mesh_ipv4(), Some("100.64.0.6"), "still mesh-joined");
5961 assert_eq!(
5962 cfg.yubaba_url().as_deref(),
5963 Some("http://100.64.0.6:7443"),
5964 "automation dials the mesh, never the LAN literal"
5965 );
5966 assert_eq!(
5967 cfg.lan_endpoint().as_deref(),
5968 Some("192.168.10.14:7443"),
5969 "the LAN address is still recorded — as identity, not as reach"
5970 );
5971 }
5972
5973 /// The refusal R605-T10 asks for: a node whose ONLY declared reach is a LAN
5974 /// literal is unresolvable, and says so by name rather than returning a URL
5975 /// that will time out. us-west-011's shape before this ticket.
5976 #[test]
5977 fn a_lan_only_node_refuses_with_a_named_reason() {
5978 let src = r#"
5979name = "us-west-011"
5980provider = "static"
5981mesh_tags = []
5982
5983[connect]
5984address = "192.168.10.11"
5985ssh = "yah@192.168.10.11"
5986yubaba = "http://192.168.10.11:7443"
5987"#;
5988 let cfg: MachineConfig = toml::from_str(src).unwrap();
5989 assert_eq!(cfg.yubaba_url(), None);
5990 let err = cfg.reach().unwrap_err();
5991 assert!(err.contains("us-west-011"), "{err}");
5992 assert!(err.contains("192.168.10.11"), "{err}");
5993 assert!(err.contains("mesh_ipv4"), "{err}");
5994 }
5995
5996 /// The loopback placeholder is a genuine declaration ("reach me through the
5997 /// SSH tunnel"), not a LAN literal — 127/8 is not RFC1918. It must keep
5998 /// resolving verbatim; `hub::coordinator::is_loopback_url` is what judges it
5999 /// downstream.
6000 #[test]
6001 fn a_loopback_placeholder_still_resolves_verbatim() {
6002 let src = r#"
6003name = "m"
6004provider = "static"
6005mesh_tags = []
6006
6007[connect]
6008address = "192.168.10.99"
6009ssh = "yah@192.168.10.99"
6010yubaba = "http://127.0.0.1:7443"
6011"#;
6012 let cfg: MachineConfig = toml::from_str(src).unwrap();
6013 assert_eq!(cfg.yubaba_url().as_deref(), Some("http://127.0.0.1:7443"));
6014 }
6015
6016 #[test]
6017 fn private_ranges_are_exactly_rfc1918() {
6018 for lan in [
6019 "http://192.168.10.11:7443",
6020 "http://10.0.0.5:7443",
6021 "http://172.16.4.1:7443",
6022 ] {
6023 assert!(private_ipv4_from_url(lan).is_some(), "{lan}");
6024 }
6025 for not_lan in [
6026 "http://100.64.0.6:7443", // mesh
6027 "http://127.0.0.1:7443", // loopback
6028 "http://172.32.0.1:7443", // just past 172.16/12
6029 "http://45.32.194.254:80", // public
6030 "http://us-west-001:7443", // name, not a literal
6031 ] {
6032 assert!(private_ipv4_from_url(not_lan).is_none(), "{not_lan}");
6033 }
6034 }
6035
6036 /// `normalize` migrates in place: the legacy fingerprint moves into
6037 /// `[registration]`, the mesh IP is lifted out of the URL, and the derived
6038 /// `[connect].yubaba` is cleared so the two halves cannot drift.
6039 #[test]
6040 fn normalize_migrates_legacy_fields_and_is_idempotent() {
6041 let src = r#"
6042name = "m"
6043provider = "static"
6044mesh_tags = []
6045hostkey_fingerprint = "SHA256:dmpq"
6046
6047[connect]
6048address = "15.204.89.240"
6049ssh = "debian@15.204.89.240"
6050yubaba = "http://100.64.0.1:7443"
6051"#;
6052 let mut cfg: MachineConfig = toml::from_str(src).unwrap();
6053 cfg.normalize();
6054 assert!(cfg.legacy_hostkey_fingerprint.is_none());
6055 assert_eq!(
6056 cfg.registration.hostkey_fingerprint.as_deref(),
6057 Some("SHA256:dmpq")
6058 );
6059 assert_eq!(cfg.registration.mesh_ipv4.as_deref(), Some("100.64.0.1"));
6060 assert!(cfg.connect.as_ref().unwrap().yubaba.is_none());
6061 // Accessors still answer the same, and re-running changes nothing.
6062 assert_eq!(cfg.yubaba_url().as_deref(), Some("http://100.64.0.1:7443"));
6063 let once = format!("{cfg:?}");
6064 cfg.normalize();
6065 assert_eq!(once, format!("{cfg:?}"));
6066 }
6067
6068 /// A loopback `[connect].yubaba` is a declaration ("no mesh address yet —
6069 /// reach me through the SSH tunnel"), not a stale observation, so
6070 /// `normalize` must leave it alone. us-west-003/011/013 depend on this.
6071 #[test]
6072 fn normalize_leaves_pre_mesh_loopback_declaration_intact() {
6073 let src = r#"
6074name = "m"
6075provider = "static"
6076mesh_tags = []
6077
6078[connect]
6079address = "192.168.10.11"
6080ssh = "yah@192.168.10.11"
6081yubaba = "http://127.0.0.1:7443"
6082"#;
6083 let mut cfg: MachineConfig = toml::from_str(src).unwrap();
6084 cfg.normalize();
6085 assert_eq!(
6086 cfg.connect.as_ref().unwrap().yubaba.as_deref(),
6087 Some("http://127.0.0.1:7443")
6088 );
6089 assert!(cfg.registration.is_empty());
6090 assert_eq!(cfg.mesh_ipv4(), None);
6091 }
6092
6093 /// `save` normalizes, so a legacy file that round-trips through the writer
6094 /// comes back on the split shape with nothing lost — the property that
6095 /// keeps `yah cloud machine attach` from re-emitting the old layout.
6096 #[test]
6097 fn save_writes_the_split_shape_from_a_legacy_config() {
6098 let tmp = tempfile::TempDir::new().unwrap();
6099 let root = tmp.path();
6100 let src = r#"
6101name = "m"
6102provider = "static"
6103mesh_tags = []
6104hostkey_fingerprint = "SHA256:dmpq"
6105
6106[connect]
6107address = "15.204.89.240"
6108ssh = "debian@15.204.89.240"
6109yubaba = "http://100.64.0.1:7443"
6110"#;
6111 let cfg: MachineConfig = toml::from_str(src).unwrap();
6112 cfg.save(root).unwrap();
6113
6114 let written = std::fs::read_to_string(root.join("machines/m.toml")).unwrap();
6115 let reg_at = written
6116 .find("[registration]")
6117 .unwrap_or_else(|| panic!("no [registration] table: {written}"));
6118 let fp_at = written
6119 .find("hostkey_fingerprint")
6120 .unwrap_or_else(|| panic!("fingerprint dropped: {written}"));
6121 assert!(
6122 fp_at > reg_at,
6123 "legacy top-level field must not be re-emitted: {written}"
6124 );
6125 assert!(
6126 !written.contains("yubaba ="),
6127 "derived URL must not be re-emitted alongside mesh_ipv4: {written}"
6128 );
6129
6130 let reloaded: MachineConfig = toml::from_str(&written).unwrap();
6131 assert_eq!(reloaded.hostkey_fingerprint(), Some("SHA256:dmpq"));
6132 assert_eq!(
6133 reloaded.yubaba_url().as_deref(),
6134 Some("http://100.64.0.1:7443")
6135 );
6136 }
6137
6138 /// `[registration]` is omitted entirely for a machine nothing has been
6139 /// observed about — a scaffolded declaration stays clean.
6140 #[test]
6141 fn empty_registration_is_omitted_on_serialize() {
6142 let src = r#"
6143name = "m"
6144provider = "static"
6145mesh_tags = []
6146"#;
6147 let cfg: MachineConfig = toml::from_str(src).unwrap();
6148 assert!(cfg.registration.is_empty());
6149 let out = toml::to_string_pretty(&cfg).unwrap();
6150 assert!(!out.contains("[registration]"), "{out}");
6151 }
6152
6153 #[test]
6154 fn driver_provider_without_location_fails_validate() {
6155 // A driver-backed provider (hetzner/vultr) still MUST carry location +
6156 // server_type — the driver can't create a server without them. The
6157 // contract moved from load-time (required field) to provision-time
6158 // (validate), so the TOML loads but validate() rejects it.
6159 let src = r#"
6160name = "us-west-001"
6161provider = "hetzner"
6162mesh_tags = []
6163"#;
6164 let cfg: MachineConfig = toml::from_str(src).unwrap();
6165 assert!(provider_has_machine_driver(&cfg.provider));
6166 let err = cfg.validate().unwrap_err().to_string();
6167 assert!(
6168 err.contains("location"),
6169 "expected location complaint: {err}"
6170 );
6171 }
6172
6173 /// Helper for the new-tree integration tests below: lay out
6174 /// `<workspace>/.yah/{infra,services}/` with `dev-yah` + its mirrors and
6175 /// the three Phase-A providers (cloudflare, hetzner, orbstack).
6176 fn make_new_tree_with_dev_yah(root: &std::path::Path) {
6177 let infra = root.join(".yah").join("infra");
6178 let providers = infra.join("providers");
6179 std::fs::create_dir_all(&providers).unwrap();
6180 std::fs::write(
6181 providers.join("cloudflare.toml"),
6182 r#"schema_version = 1
6183id = "cloudflare"
6184kind = "cloudflare"
6185credentials = "keystore://cloudflare/yah"
6186default_zone = "yah.dev"
6187"#,
6188 )
6189 .unwrap();
6190 std::fs::write(
6191 providers.join("hetzner.toml"),
6192 r#"schema_version = 1
6193id = "hetzner"
6194kind = "hetzner"
6195credentials = "keystore://hetzner/yah"
6196default_location = "pdx"
6197default_server_type = "cpx11"
6198ssh_keys = []
6199"#,
6200 )
6201 .unwrap();
6202 std::fs::write(
6203 providers.join("orbstack.toml"),
6204 r#"schema_version = 1
6205id = "orbstack"
6206kind = "local-container"
6207runtime = "auto"
6208
6209[discovery]
6210orbstack = "~/.orbstack/run/docker.sock"
6211"#,
6212 )
6213 .unwrap();
6214
6215 let svc = root.join(".yah").join("services").join("dev-yah");
6216 std::fs::create_dir_all(svc.join("mirrors")).unwrap();
6217 std::fs::write(
6218 svc.join("service.toml"),
6219 r#"schema_version = 1
6220name = "dev-yah"
6221domain = "yah.dev"
6222
6223[[components]]
6224id = "site"
6225kind = "mesofact-static"
6226path = "app/yah/web"
6227role = "static"
6228"#,
6229 )
6230 .unwrap();
6231 std::fs::write(
6232 svc.join("mirrors/prod.toml"),
6233 r#"schema_version = 1
6234shape = "single-machine"
6235
6236[providers.static]
6237use = "cloudflare"
6238bucket = "yah-dev"
6239zone = "yah.dev"
6240"#,
6241 )
6242 .unwrap();
6243 std::fs::write(
6244 svc.join("mirrors/local.toml"),
6245 r#"schema_version = 1
6246shape = "local"
6247
6248[providers.static]
6249kind = "local-static"
6250port = 4321
6251
6252[providers.compute]
6253use = "orbstack"
6254"#,
6255 )
6256 .unwrap();
6257 }
6258
6259 #[test]
6260 fn cloud_config_load_new_tree_populates_providers_and_services() {
6261 let tmp = tempfile::TempDir::new().unwrap();
6262 let root = tmp.path();
6263 make_new_tree_with_dev_yah(root);
6264
6265 let cfg = CloudConfig::load(root).unwrap();
6266 assert_eq!(cfg.providers.len(), 3, "three providers loaded");
6267 assert!(cfg.provider("cloudflare").is_some());
6268 assert!(cfg.provider("hetzner").is_some());
6269 assert!(cfg.provider("orbstack").is_some());
6270
6271 let dev = cfg.service("dev-yah").expect("dev-yah service");
6272 assert_eq!(dev.service.domain, "yah.dev");
6273 assert_eq!(dev.service.components.len(), 1);
6274 assert_eq!(dev.mirrors.len(), 2);
6275 // Legacy file stems "prod" and "local" are normalised to canonical tier names.
6276 assert!(dev.mirrors.contains_key("cloud"), "prod.toml → cloud tier");
6277 assert!(dev.mirrors.contains_key("dev"), "local.toml → dev tier");
6278 assert_eq!(dev.mirrors["cloud"].shape, MirrorShape::SingleMachine);
6279 assert_eq!(dev.mirrors["dev"].shape, MirrorShape::Local);
6280
6281 // Legacy fields stay empty when no .yah/cloud/ exists.
6282 assert!(cfg.legacy_mirrors.is_empty());
6283 assert!(cfg.legacy_services.is_empty());
6284 assert!(cfg.workloads.is_empty());
6285 }
6286
6287 #[test]
6288 fn cloud_config_cross_ref_fails_on_missing_provider() {
6289 // Mirror references a provider id that doesn't exist.
6290 let tmp = tempfile::TempDir::new().unwrap();
6291 let root = tmp.path();
6292 let svc = root.join(".yah").join("services").join("dev-yah");
6293 std::fs::create_dir_all(svc.join("mirrors")).unwrap();
6294 std::fs::write(
6295 svc.join("service.toml"),
6296 "schema_version = 1\nname = \"dev-yah\"\ndomain = \"yah.dev\"\n",
6297 )
6298 .unwrap();
6299 std::fs::write(
6300 svc.join("mirrors/prod.toml"),
6301 "schema_version = 1\nshape = \"single-machine\"\n\n[providers.static]\nuse = \"fly-io\"\n",
6302 ).unwrap();
6303
6304 let err = CloudConfig::load(root).unwrap_err();
6305 let msg = err.to_string();
6306 assert!(
6307 msg.contains("fly-io"),
6308 "error should name the missing provider id, got: {msg}"
6309 );
6310 assert!(
6311 msg.contains("providers/fly-io.toml") || msg.contains("no such provider"),
6312 "error should hint at remedy, got: {msg}"
6313 );
6314 }
6315
6316 #[test]
6317 fn cloud_config_cross_ref_passes_on_inline_only_mirror() {
6318 // Inline `kind = "local-static"` doesn't require an infra provider.
6319 let tmp = tempfile::TempDir::new().unwrap();
6320 let root = tmp.path();
6321 let svc = root.join(".yah").join("services").join("local-only");
6322 std::fs::create_dir_all(svc.join("mirrors")).unwrap();
6323 std::fs::write(
6324 svc.join("service.toml"),
6325 "schema_version = 1\nname = \"local-only\"\ndomain = \"local.test\"\n",
6326 )
6327 .unwrap();
6328 std::fs::write(
6329 svc.join("mirrors/local.toml"),
6330 "schema_version = 1\nshape = \"local\"\n\n[providers.static]\nkind = \"local-static\"\nport = 8080\n",
6331 ).unwrap();
6332
6333 // Should load fine: no `use=` references, no providers required.
6334 let cfg = CloudConfig::load(root).unwrap();
6335 assert!(cfg.service("local-only").is_some());
6336 }
6337
6338 #[test]
6339 fn cloud_config_load_coexists_legacy_and_new_trees() {
6340 // Both trees present — both fields populated independently.
6341 let tmp = tempfile::TempDir::new().unwrap();
6342 let root = tmp.path();
6343 make_new_tree_with_dev_yah(root);
6344
6345 let cloud_dir = make_legacy_cloud_dir(root);
6346 std::fs::create_dir_all(cloud_dir.join("mirrors")).unwrap();
6347 std::fs::write(
6348 cloud_dir.join("mirrors/noisetable.toml"),
6349 "camp = \"noisetable\"\nregions = [\"pdx\"]\nworkloads = []\n",
6350 )
6351 .unwrap();
6352
6353 let cfg = CloudConfig::load(root).unwrap();
6354 assert_eq!(cfg.providers.len(), 3);
6355 assert!(cfg.service("dev-yah").is_some());
6356 assert_eq!(cfg.legacy_mirrors.len(), 1);
6357 assert!(cfg.legacy_mirror("noisetable").is_some());
6358 }
6359
6360 #[test]
6361 fn web_workload_round_trips() {
6362 // app/yah/web/workload.toml is parsed as a WorkloadSpec via the
6363 // workload-spec crate. The minimum-viable manifest here exercises
6364 // schema_version + kind + build fields.
6365 //
6366 // The on-disk file uses the abbreviated v1 form (kind + build); the
6367 // full WorkloadSpec is verbose, so this test asserts the new
6368 // mesofact-static abbreviated form parses as raw TOML (B3 will plumb
6369 // it through WorkloadSpec proper).
6370 // `routes` above [build] — it is a top-level field, and TOML would
6371 // scope it into that table if written below the header (R658-B1).
6372 let src = r#"
6373schema_version = 1
6374kind = "mesofact-static"
6375
6376routes = "./routes.ts"
6377
6378[build]
6379command = "bun run build"
6380out_dir = "dist"
6381"#;
6382 let v: toml::Value = toml::from_str(src).unwrap();
6383 assert_eq!(
6384 v.get("schema_version").and_then(|x| x.as_integer()),
6385 Some(1)
6386 );
6387 assert_eq!(
6388 v.get("kind").and_then(|x| x.as_str()),
6389 Some("mesofact-static")
6390 );
6391 let build = v
6392 .get("build")
6393 .and_then(|x| x.as_table())
6394 .expect("build table");
6395 assert_eq!(
6396 build.get("command").and_then(|x| x.as_str()),
6397 Some("bun run build")
6398 );
6399 assert_eq!(build.get("out_dir").and_then(|x| x.as_str()), Some("dist"));
6400 }
6401
6402 // ─── Canonical CRUD: ServiceConfig/MirrorConfig save + delete (R323-F1) ──
6403
6404 #[test]
6405 fn service_config_save_creates_canonical_toml_and_round_trips() {
6406 let tmp = tempfile::TempDir::new().unwrap();
6407 let root = tmp.path();
6408
6409 let svc = ServiceConfig {
6410 schema_version: 1,
6411 name: "dev-yah".into(),
6412 domain: "yah.dev".into(),
6413 db: DbCatalog::default(),
6414 components: vec![ServiceComponent {
6415 mount: None,
6416 id: "site".into(),
6417 kind: "mesofact-static".into(),
6418 path: "app/yah/web".into(),
6419 role: "static".into(),
6420 publishes: Some("static".into()),
6421 wave: 0,
6422 git: None,
6423 }],
6424 };
6425 svc.save(root).unwrap();
6426
6427 // Landed at the canonical path.
6428 let path = crate::paths::service_toml(root, "dev-yah");
6429 assert!(
6430 path.exists(),
6431 "service.toml should exist at {}",
6432 path.display()
6433 );
6434
6435 // Reloads through the full CloudConfig loader (no mirrors yet).
6436 let cfg = CloudConfig::load(root).unwrap();
6437 let loaded = cfg.service("dev-yah").expect("dev-yah service");
6438 assert_eq!(loaded.service.domain, "yah.dev");
6439 assert_eq!(loaded.service.components.len(), 1);
6440 assert_eq!(
6441 loaded.service.components[0].publishes.as_deref(),
6442 Some("static")
6443 );
6444 assert!(loaded.mirrors.is_empty());
6445 }
6446
6447 #[test]
6448 fn service_config_save_overwrites_in_place() {
6449 let tmp = tempfile::TempDir::new().unwrap();
6450 let root = tmp.path();
6451
6452 let mut svc = ServiceConfig {
6453 schema_version: 1,
6454 name: "dev-yah".into(),
6455 domain: "yah.dev".into(),
6456 components: vec![],
6457 db: DbCatalog::default(),
6458 };
6459 svc.save(root).unwrap();
6460 svc.domain = "yah.example".into();
6461 svc.save(root).unwrap();
6462
6463 let cfg = CloudConfig::load(root).unwrap();
6464 assert_eq!(
6465 cfg.service("dev-yah").unwrap().service.domain,
6466 "yah.example"
6467 );
6468 }
6469
6470 #[test]
6471 fn mirror_config_save_round_trips_reference_and_inline_slots() {
6472 let tmp = tempfile::TempDir::new().unwrap();
6473 let root = tmp.path();
6474
6475 // A service must exist so the loader walks the mirrors/ dir.
6476 ServiceConfig {
6477 schema_version: 1,
6478 name: "dev-yah".into(),
6479 domain: "yah.dev".into(),
6480 components: vec![],
6481 db: DbCatalog::default(),
6482 }
6483 .save(root)
6484 .unwrap();
6485
6486 // The cloudflare provider the reference slot points at must resolve,
6487 // or CloudConfig::load's cross-ref check rejects the tree.
6488 let providers = crate::paths::providers_dir(root);
6489 std::fs::create_dir_all(&providers).unwrap();
6490 std::fs::write(
6491 providers.join("cloudflare.toml"),
6492 "schema_version = 1\nid = \"cloudflare\"\nkind = \"cloudflare\"\n",
6493 )
6494 .unwrap();
6495
6496 let mut providers_map = BTreeMap::new();
6497 providers_map.insert(
6498 "static".to_string(),
6499 MirrorProviderSlot::Reference {
6500 provider_id: "cloudflare".into(),
6501 fields: {
6502 let mut f = BTreeMap::new();
6503 f.insert("bucket".to_string(), toml::Value::String("yah-dev".into()));
6504 f
6505 },
6506 },
6507 );
6508 providers_map.insert(
6509 "compute".to_string(),
6510 MirrorProviderSlot::Inline {
6511 kind: Provider::LocalStatic,
6512 fields: {
6513 let mut f = BTreeMap::new();
6514 f.insert("port".to_string(), toml::Value::Integer(4321));
6515 f
6516 },
6517 },
6518 );
6519 let mirror = MirrorConfig {
6520 schema_version: 1,
6521 shape: MirrorShape::SingleMachine,
6522 providers: providers_map,
6523 ingress: Default::default(),
6524 ingress_machines: Vec::new(),
6525 drivers: Default::default(),
6526 asset_aliases: Default::default(),
6527 };
6528 // Save with canonical name; legacy "prod" is normalised to "cloud" on load.
6529 mirror.save(root, "dev-yah", "cloud").unwrap();
6530
6531 let path = crate::paths::service_mirror_toml(root, "dev-yah", "cloud");
6532 assert!(
6533 path.exists(),
6534 "mirror toml should exist at {}",
6535 path.display()
6536 );
6537
6538 let cfg = CloudConfig::load(root).unwrap();
6539 let loaded = &cfg.service("dev-yah").unwrap().mirrors["cloud"];
6540 assert_eq!(loaded.shape, MirrorShape::SingleMachine);
6541 assert_eq!(loaded.providers["static"].provider_id(), Some("cloudflare"));
6542 assert_eq!(
6543 loaded.providers["compute"].inline_kind(),
6544 Some(Provider::LocalStatic)
6545 );
6546 }
6547
6548 #[test]
6549 fn service_delete_removes_dir_and_mirrors() {
6550 let tmp = tempfile::TempDir::new().unwrap();
6551 let root = tmp.path();
6552
6553 let svc = ServiceConfig {
6554 schema_version: 1,
6555 name: "dev-yah".into(),
6556 domain: "yah.dev".into(),
6557 components: vec![],
6558 db: DbCatalog::default(),
6559 };
6560 svc.save(root).unwrap();
6561 MirrorConfig {
6562 schema_version: 1,
6563 shape: MirrorShape::Local,
6564 providers: BTreeMap::new(),
6565 ingress: Default::default(),
6566 ingress_machines: Vec::new(),
6567 drivers: Default::default(),
6568 asset_aliases: Default::default(),
6569 }
6570 .save(root, "dev-yah", "local")
6571 .unwrap();
6572
6573 assert!(
6574 ServiceConfig::delete(root, "dev-yah").unwrap(),
6575 "first delete reports true"
6576 );
6577 assert!(!crate::paths::service_dir(root, "dev-yah").exists());
6578 // Idempotent: deleting again is a no-op that reports false.
6579 assert!(!ServiceConfig::delete(root, "dev-yah").unwrap());
6580
6581 let cfg = CloudConfig::load(root).unwrap();
6582 assert!(cfg.service("dev-yah").is_none());
6583 }
6584
6585 #[test]
6586 fn mirror_delete_leaves_other_mirrors_and_service_intact() {
6587 let tmp = tempfile::TempDir::new().unwrap();
6588 let root = tmp.path();
6589
6590 ServiceConfig {
6591 schema_version: 1,
6592 name: "dev-yah".into(),
6593 domain: "yah.dev".into(),
6594 components: vec![],
6595 db: DbCatalog::default(),
6596 }
6597 .save(root)
6598 .unwrap();
6599 for env in ["prod", "local"] {
6600 MirrorConfig {
6601 schema_version: 1,
6602 shape: MirrorShape::Local,
6603 providers: BTreeMap::new(),
6604 ingress: Default::default(),
6605 ingress_machines: Vec::new(),
6606 drivers: Default::default(),
6607 asset_aliases: Default::default(),
6608 }
6609 .save(root, "dev-yah", env)
6610 .unwrap();
6611 }
6612
6613 assert!(MirrorConfig::delete(root, "dev-yah", "prod").unwrap());
6614 assert!(!MirrorConfig::delete(root, "dev-yah", "prod").unwrap());
6615
6616 let cfg = CloudConfig::load(root).unwrap();
6617 let svc = cfg
6618 .service("dev-yah")
6619 .expect("service survives mirror delete");
6620 // Legacy file stems are normalised on load: "prod" → "cloud", "local" → "dev".
6621 assert!(!svc.mirrors.contains_key("cloud"));
6622 assert!(svc.mirrors.contains_key("dev"));
6623 }
6624
6625 // ─── DomainConfig (R347-F2) ────────────────────────────────────────────
6626
6627 fn write_marketing_service(root: &Path) {
6628 let svc = ServiceConfig {
6629 schema_version: 1,
6630 name: "yah-marketing".into(),
6631 domain: "yah.dev".into(),
6632 db: DbCatalog::default(),
6633 components: vec![ServiceComponent {
6634 mount: None,
6635 id: "site".into(),
6636 kind: "mesofact-static".into(),
6637 path: "app/yah/web".into(),
6638 role: "static".into(),
6639 publishes: None,
6640 wave: 0,
6641 git: None,
6642 }],
6643 };
6644 svc.save(root).unwrap();
6645 }
6646
6647 #[test]
6648 fn round_trip_domain_with_each_route_mode() {
6649 let dom = DomainConfig {
6650 schema_version: 1,
6651 name: "yah-dev".into(),
6652 domain: "yah.dev".into(),
6653 front_door: FrontDoor::Worker,
6654 cdn_bucket: "yah-dev".into(),
6655 worker_bundle_path: Some(".yah/workers/yah-dev/".into()),
6656 routes: vec![
6657 DomainRoute {
6658 headers: Default::default(),
6659 path: "/".into(),
6660 mode: RouteMode::Static {
6661 component: "yah-marketing/site".into(),
6662 },
6663 },
6664 DomainRoute {
6665 headers: Default::default(),
6666 path: "/dashboard/api/*".into(),
6667 mode: RouteMode::Backend {
6668 component: "yah-dashboard/api".into(),
6669 origin: "https://api.dashboard.yah.dev".into(),
6670 },
6671 },
6672 DomainRoute {
6673 headers: Default::default(),
6674 path: "/old".into(),
6675 mode: RouteMode::Redirect {
6676 target: "https://yah.dev/blog".into(),
6677 status: 308,
6678 },
6679 },
6680 ],
6681 };
6682 let s = toml::to_string(&dom).unwrap();
6683 let back: DomainConfig = toml::from_str(&s).unwrap();
6684 assert_eq!(back.name, "yah-dev");
6685 assert_eq!(back.routes.len(), 3);
6686 assert!(matches!(back.routes[0].mode, RouteMode::Static { .. }));
6687 assert!(matches!(back.routes[1].mode, RouteMode::Backend { .. }));
6688 assert!(matches!(back.routes[2].mode, RouteMode::Redirect { .. }));
6689 }
6690
6691 #[test]
6692 fn redirect_status_defaults_to_308() {
6693 let src = r#"
6694schema_version = 1
6695name = "yah-dev"
6696domain = "yah.dev"
6697front_door = "worker"
6698cdn_bucket = "yah-dev"
6699
6700[[routes]]
6701path = "/old"
6702mode = "redirect"
6703target = "https://yah.dev/blog"
6704"#;
6705 let dom: DomainConfig = toml::from_str(src).unwrap();
6706 let RouteMode::Redirect { status, .. } = &dom.routes[0].mode else {
6707 panic!("expected redirect");
6708 };
6709 assert_eq!(*status, 308);
6710 }
6711
6712 #[test]
6713 fn missing_domains_dir_is_empty() {
6714 let tmp = tempfile::TempDir::new().unwrap();
6715 let cfg = CloudConfig::load(tmp.path()).unwrap();
6716 assert!(cfg.domains.is_empty());
6717 }
6718
6719 #[test]
6720 fn save_reload_roundtrip() {
6721 let tmp = tempfile::TempDir::new().unwrap();
6722 let root = tmp.path();
6723 write_marketing_service(root);
6724
6725 let dom = DomainConfig {
6726 schema_version: 1,
6727 name: "yah-dev".into(),
6728 domain: "yah.dev".into(),
6729 front_door: FrontDoor::Worker,
6730 cdn_bucket: "yah-dev".into(),
6731 worker_bundle_path: None,
6732 routes: vec![DomainRoute {
6733 headers: Default::default(),
6734 path: "/".into(),
6735 mode: RouteMode::Static {
6736 component: "yah-marketing/site".into(),
6737 },
6738 }],
6739 };
6740 dom.save(root).unwrap();
6741
6742 let cfg = CloudConfig::load(root).unwrap();
6743 let loaded = cfg.domain("yah-dev").expect("yah-dev domain");
6744 assert_eq!(loaded.domain, "yah.dev");
6745 assert_eq!(loaded.routes.len(), 1);
6746 }
6747
6748 #[test]
6749 fn delete_returns_false_when_absent() {
6750 let tmp = tempfile::TempDir::new().unwrap();
6751 assert!(!DomainConfig::delete(tmp.path(), "no-such-domain").unwrap());
6752 }
6753
6754 #[test]
6755 fn delete_returns_true_first_time() {
6756 let tmp = tempfile::TempDir::new().unwrap();
6757 let root = tmp.path();
6758 let dom = DomainConfig {
6759 schema_version: 1,
6760 name: "yah-dev".into(),
6761 domain: "yah.dev".into(),
6762 front_door: FrontDoor::BucketDirect,
6763 cdn_bucket: "yah-dev".into(),
6764 worker_bundle_path: None,
6765 routes: vec![],
6766 };
6767 dom.save(root).unwrap();
6768 assert!(DomainConfig::delete(root, "yah-dev").unwrap());
6769 assert!(!DomainConfig::delete(root, "yah-dev").unwrap());
6770 }
6771
6772 // ---- R594-F12: front-door discriminator ------------------------------
6773
6774 /// Write a raw domain manifest so the tests exercise the deserialize +
6775 /// validate path, not a hand-built struct that skipped serde.
6776 fn write_domain_toml(root: &Path, stem: &str, body: &str) {
6777 let dir = root.join(".yah").join("domains");
6778 std::fs::create_dir_all(&dir).unwrap();
6779 std::fs::write(dir.join(format!("{stem}.toml")), body).unwrap();
6780 }
6781
6782 #[test]
6783 fn front_door_is_required() {
6784 let tmp = tempfile::TempDir::new().unwrap();
6785 let root = tmp.path();
6786 write_marketing_service(root);
6787 write_domain_toml(
6788 root,
6789 "yah-dev",
6790 r#"
6791schema_version = 1
6792name = "yah-dev"
6793domain = "yah.dev"
6794cdn_bucket = "yah-dev"
6795[[routes]]
6796path = "/*"
6797mode = "static"
6798component = "yah-marketing/site"
6799"#,
6800 );
6801 let err = CloudConfig::load(root).unwrap_err().to_string();
6802 // serde's own missing-field message; the point is that omitting the
6803 // discriminator is not a silently-defaulted state.
6804 assert!(err.contains("yah-dev.toml"), "{err}");
6805 }
6806
6807 #[test]
6808 fn bucket_direct_with_routes_is_rejected() {
6809 let tmp = tempfile::TempDir::new().unwrap();
6810 let root = tmp.path();
6811 write_marketing_service(root);
6812 write_domain_toml(
6813 root,
6814 "cdn-yah-dev",
6815 r#"
6816schema_version = 1
6817name = "cdn-yah-dev"
6818domain = "cdn.yah.dev"
6819front_door = "bucket-direct"
6820cdn_bucket = "yah-dev"
6821[[routes]]
6822path = "/docs/*"
6823mode = "static"
6824component = "yah-marketing/site"
6825"#,
6826 );
6827 let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
6828 assert!(err.contains("front_door"), "{err}");
6829 assert!(err.contains("/docs/*"), "{err}");
6830 }
6831
6832 #[test]
6833 fn bucket_direct_with_worker_bundle_path_is_rejected() {
6834 let tmp = tempfile::TempDir::new().unwrap();
6835 let root = tmp.path();
6836 write_domain_toml(
6837 root,
6838 "cdn-yah-dev",
6839 r#"
6840schema_version = 1
6841name = "cdn-yah-dev"
6842domain = "cdn.yah.dev"
6843front_door = "bucket-direct"
6844cdn_bucket = "yah-dev"
6845worker_bundle_path = ".yah/workers/cdn-yah-dev/"
6846"#,
6847 );
6848 let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
6849 assert!(err.contains("worker_bundle_path"), "{err}");
6850 }
6851
6852 // ── R746: per-route response headers + component mounts ──────────────────
6853
6854 /// A two-component service: `site` at the root, `app` mounted at `/app`
6855 /// with isolation headers on its route. This is the noisetable.com shape
6856 /// the primitive was built for.
6857 fn write_two_component_service(root: &Path) {
6858 let svc = ServiceConfig {
6859 schema_version: 1,
6860 name: "yah-marketing".into(),
6861 domain: "yah.dev".into(),
6862 db: DbCatalog::default(),
6863 components: vec![
6864 ServiceComponent {
6865 mount: None,
6866 id: "site".into(),
6867 kind: "mesofact-static".into(),
6868 path: "app/yah/web".into(),
6869 role: "static".into(),
6870 publishes: None,
6871 wave: 0,
6872 git: None,
6873 },
6874 ServiceComponent {
6875 mount: Some("/app".into()),
6876 id: "app".into(),
6877 kind: "mesofact-static".into(),
6878 path: "app/browser".into(),
6879 role: "static".into(),
6880 publishes: None,
6881 wave: 0,
6882 git: None,
6883 },
6884 ],
6885 };
6886 svc.save(root).unwrap();
6887 }
6888
6889 const MOUNTED_DOMAIN: &str = r#"
6890schema_version = 1
6891name = "yah-dev"
6892domain = "yah.dev"
6893front_door = "worker"
6894cdn_bucket = "yah-dev"
6895
6896[[routes]]
6897path = "/app/*"
6898mode = "static"
6899component = "yah-marketing/app"
6900headers = { "Cross-Origin-Opener-Policy" = "same-origin", "Cross-Origin-Embedder-Policy" = "require-corp" }
6901
6902[[routes]]
6903path = "/*"
6904mode = "static"
6905component = "yah-marketing/site"
6906"#;
6907
6908 #[test]
6909 fn a_mounted_component_routed_at_its_mount_loads() {
6910 let tmp = tempfile::TempDir::new().unwrap();
6911 let root = tmp.path();
6912 write_two_component_service(root);
6913 write_domain_toml(root, "yah-dev", MOUNTED_DOMAIN);
6914 let cfg = CloudConfig::load(root).unwrap();
6915 let dom = cfg.domain("yah-dev").unwrap();
6916 assert_eq!(dom.routes.len(), 2);
6917 assert_eq!(
6918 dom.routes[0].headers.get("Cross-Origin-Opener-Policy").map(String::as_str),
6919 Some("same-origin")
6920 );
6921 assert!(dom.routes[1].headers.is_empty());
6922 }
6923
6924 /// The header table reaches the Worker in MANIFEST order with headerless
6925 /// routes dropped. Order is the whole contract — the front door applies the
6926 /// first match, so `/app/*` before `/*` is what isolates the app without
6927 /// isolating the marketing site.
6928 #[test]
6929 fn route_headers_json_preserves_order_and_drops_headerless_routes() {
6930 let tmp = tempfile::TempDir::new().unwrap();
6931 let root = tmp.path();
6932 write_two_component_service(root);
6933 write_domain_toml(root, "yah-dev", MOUNTED_DOMAIN);
6934 let cfg = CloudConfig::load(root).unwrap();
6935 let json = cfg.domain("yah-dev").unwrap().route_headers_json();
6936
6937 let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
6938 let rules = parsed.as_array().unwrap();
6939 assert_eq!(rules.len(), 1, "the headerless catch-all is dropped: {json}");
6940 assert_eq!(rules[0]["path"], "/app/*");
6941 assert_eq!(rules[0]["headers"]["Cross-Origin-Embedder-Policy"], "require-corp");
6942 }
6943
6944 #[test]
6945 fn route_headers_json_is_an_empty_array_when_nothing_declares_headers() {
6946 let tmp = tempfile::TempDir::new().unwrap();
6947 let root = tmp.path();
6948 write_marketing_service(root);
6949 write_domain_toml(
6950 root,
6951 "yah-dev",
6952 r#"
6953schema_version = 1
6954name = "yah-dev"
6955domain = "yah.dev"
6956front_door = "worker"
6957cdn_bucket = "yah-dev"
6958
6959[[routes]]
6960path = "/*"
6961mode = "static"
6962component = "yah-marketing/site"
6963"#,
6964 );
6965 let cfg = CloudConfig::load(root).unwrap();
6966 assert_eq!(cfg.domain("yah-dev").unwrap().route_headers_json(), "[]");
6967 }
6968
6969 /// The reconciler's own entry point: given a workspace root and a service
6970 /// name, produce the binding value. `"[]"` when nothing routes the service.
6971 #[test]
6972 fn route_headers_for_service_reads_the_workspace_domains() {
6973 let tmp = tempfile::TempDir::new().unwrap();
6974 let root = tmp.path();
6975 write_two_component_service(root);
6976 write_domain_toml(root, "yah-dev", MOUNTED_DOMAIN);
6977 assert!(route_headers_for_service(root, "yah-marketing")
6978 .unwrap()
6979 .contains("require-corp"));
6980 assert_eq!(route_headers_for_service(root, "some-other-svc").unwrap(), "[]");
6981 }
6982
6983 /// A `bucket-direct` domain has no front door to set headers on, so it must
6984 /// not be picked up as a service's header source.
6985 #[test]
6986 fn route_headers_ignores_domains_that_are_not_route_driven() {
6987 let doms: BTreeMap<String, DomainConfig> = [(
6988 "cdn".to_string(),
6989 DomainConfig {
6990 schema_version: 1,
6991 name: "cdn".into(),
6992 domain: "cdn.yah.dev".into(),
6993 front_door: FrontDoor::BucketDirect,
6994 cdn_bucket: "yah-dev".into(),
6995 worker_bundle_path: None,
6996 routes: vec![],
6997 },
6998 )]
6999 .into_iter()
7000 .collect();
7001 assert!(domain_serving_service(&doms, "yah-marketing").is_none());
7002 }
7003
7004 #[test]
7005 fn a_mount_that_disagrees_with_its_route_path_is_rejected() {
7006 let tmp = tempfile::TempDir::new().unwrap();
7007 let root = tmp.path();
7008 write_two_component_service(root);
7009 write_domain_toml(
7010 root,
7011 "yah-dev",
7012 r#"
7013schema_version = 1
7014name = "yah-dev"
7015domain = "yah.dev"
7016front_door = "worker"
7017cdn_bucket = "yah-dev"
7018
7019[[routes]]
7020path = "/studio/*"
7021mode = "static"
7022component = "yah-marketing/app"
7023"#,
7024 );
7025 let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
7026 assert!(err.contains("mount = \"/app\""), "{err}");
7027 assert!(err.contains("/studio/*"), "{err}");
7028 }
7029
7030 /// The other direction: routing an unmounted component under a sub-path
7031 /// points requests at a prefix nothing published to.
7032 #[test]
7033 fn routing_an_unmounted_component_under_a_subpath_is_rejected() {
7034 let tmp = tempfile::TempDir::new().unwrap();
7035 let root = tmp.path();
7036 write_marketing_service(root);
7037 write_domain_toml(
7038 root,
7039 "yah-dev",
7040 r#"
7041schema_version = 1
7042name = "yah-dev"
7043domain = "yah.dev"
7044front_door = "worker"
7045cdn_bucket = "yah-dev"
7046
7047[[routes]]
7048path = "/docs/*"
7049mode = "static"
7050component = "yah-marketing/site"
7051"#,
7052 );
7053 let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
7054 assert!(err.contains("no `mount`"), "{err}");
7055 assert!(err.contains("/docs"), "{err}");
7056 }
7057
7058 #[test]
7059 fn mount_and_route_prefix_normalization_agree() {
7060 for m in ["/app", "app", "app/", "/app/"] {
7061 assert_eq!(normalize_mount(m), "app", "mount {m:?}");
7062 }
7063 assert_eq!(normalize_mount("/"), "");
7064 assert_eq!(route_path_prefix("/*"), "");
7065 assert_eq!(route_path_prefix("/app/*"), "app");
7066 assert_eq!(route_path_prefix("/app"), "app");
7067 assert_eq!(route_path_prefix("/"), "");
7068 }
7069
7070 #[test]
7071 fn worker_with_no_routes_is_rejected() {
7072 let tmp = tempfile::TempDir::new().unwrap();
7073 let root = tmp.path();
7074 write_domain_toml(
7075 root,
7076 "yah-dev",
7077 r#"
7078schema_version = 1
7079name = "yah-dev"
7080domain = "yah.dev"
7081front_door = "worker"
7082cdn_bucket = "yah-dev"
7083"#,
7084 );
7085 let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
7086 assert!(err.contains("front_door = \"worker\""), "{err}");
7087 assert!(err.contains("404"), "{err}");
7088 }
7089
7090 #[test]
7091 fn passway_with_no_routes_is_rejected_too() {
7092 let tmp = tempfile::TempDir::new().unwrap();
7093 let root = tmp.path();
7094 write_domain_toml(
7095 root,
7096 "yah-dev",
7097 r#"
7098schema_version = 1
7099name = "yah-dev"
7100domain = "yah.dev"
7101front_door = "passway"
7102cdn_bucket = "yah-dev"
7103"#,
7104 );
7105 let err = format!("{:#}", CloudConfig::load(root).unwrap_err());
7106 assert!(err.contains("front_door = \"passway\""), "{err}");
7107 }
7108
7109 #[test]
7110 fn bucket_direct_without_routes_loads() {
7111 let tmp = tempfile::TempDir::new().unwrap();
7112 let root = tmp.path();
7113 // Exactly the shape .yah/domains/cdn-yah-dev.toml ships (W175: a pure
7114 // asset tier deliberately has no Worker behaviours).
7115 write_domain_toml(
7116 root,
7117 "cdn-yah-dev",
7118 r#"
7119schema_version = 1
7120name = "cdn-yah-dev"
7121domain = "cdn.yah.dev"
7122front_door = "bucket-direct"
7123cdn_bucket = "yah-dev"
7124"#,
7125 );
7126 let cfg = CloudConfig::load(root).unwrap();
7127 let dom = cfg.domain("cdn-yah-dev").expect("cdn-yah-dev domain");
7128 assert_eq!(dom.front_door, FrontDoor::BucketDirect);
7129 assert!(!dom.front_door.is_route_driven());
7130 }
7131
7132 #[test]
7133 fn front_door_round_trips_through_save() {
7134 let tmp = tempfile::TempDir::new().unwrap();
7135 let root = tmp.path();
7136 write_marketing_service(root);
7137 let dom = DomainConfig {
7138 schema_version: 1,
7139 name: "yah-dev".into(),
7140 domain: "yah.dev".into(),
7141 front_door: FrontDoor::Passway,
7142 cdn_bucket: "yah-dev".into(),
7143 worker_bundle_path: None,
7144 routes: vec![DomainRoute {
7145 headers: Default::default(),
7146 path: "/*".into(),
7147 mode: RouteMode::Static {
7148 component: "yah-marketing/site".into(),
7149 },
7150 }],
7151 };
7152 dom.save(root).unwrap();
7153 let cfg = CloudConfig::load(root).unwrap();
7154 assert_eq!(
7155 cfg.domain("yah-dev").unwrap().front_door,
7156 FrontDoor::Passway
7157 );
7158 }
7159
7160 // The four manifests this repo actually ships are asserted in
7161 // `tests/live_workspace_smoke.rs` — that's the only place with a
7162 // depth-agnostic path to the live `.yah/` tree and a skip path for the
7163 // standalone mirror checkout.
7164
7165 #[test]
7166 fn cross_ref_bails_on_missing_service() {
7167 let tmp = tempfile::TempDir::new().unwrap();
7168 let root = tmp.path();
7169 // No services declared at all — component ref must fail to resolve.
7170 let dom = DomainConfig {
7171 schema_version: 1,
7172 name: "yah-dev".into(),
7173 domain: "yah.dev".into(),
7174 front_door: FrontDoor::Worker,
7175 cdn_bucket: "yah-dev".into(),
7176 worker_bundle_path: None,
7177 routes: vec![DomainRoute {
7178 headers: Default::default(),
7179 path: "/".into(),
7180 mode: RouteMode::Static {
7181 component: "yah-marketing/site".into(),
7182 },
7183 }],
7184 };
7185 dom.save(root).unwrap();
7186
7187 let err = CloudConfig::load(root).unwrap_err();
7188 let msg = format!("{err:#}");
7189 assert!(msg.contains("no such service"), "got: {msg}");
7190 assert!(msg.contains("yah-marketing"), "got: {msg}");
7191 }
7192
7193 #[test]
7194 fn cross_ref_bails_on_missing_component() {
7195 let tmp = tempfile::TempDir::new().unwrap();
7196 let root = tmp.path();
7197 write_marketing_service(root); // has component id "site", not "elsewhere"
7198
7199 let dom = DomainConfig {
7200 schema_version: 1,
7201 name: "yah-dev".into(),
7202 domain: "yah.dev".into(),
7203 front_door: FrontDoor::Worker,
7204 cdn_bucket: "yah-dev".into(),
7205 worker_bundle_path: None,
7206 routes: vec![DomainRoute {
7207 headers: Default::default(),
7208 path: "/".into(),
7209 mode: RouteMode::Static {
7210 component: "yah-marketing/elsewhere".into(),
7211 },
7212 }],
7213 };
7214 dom.save(root).unwrap();
7215
7216 let err = CloudConfig::load(root).unwrap_err();
7217 let msg = format!("{err:#}");
7218 assert!(msg.contains("no component with id"), "got: {msg}");
7219 assert!(msg.contains("elsewhere"), "got: {msg}");
7220 }
7221
7222 #[test]
7223 fn cross_ref_bails_on_malformed_ref() {
7224 let tmp = tempfile::TempDir::new().unwrap();
7225 let root = tmp.path();
7226 write_marketing_service(root);
7227
7228 let dom = DomainConfig {
7229 schema_version: 1,
7230 name: "yah-dev".into(),
7231 domain: "yah.dev".into(),
7232 front_door: FrontDoor::Worker,
7233 cdn_bucket: "yah-dev".into(),
7234 worker_bundle_path: None,
7235 routes: vec![DomainRoute {
7236 headers: Default::default(),
7237 path: "/".into(),
7238 mode: RouteMode::Static {
7239 component: "no-slash-here".into(),
7240 },
7241 }],
7242 };
7243 dom.save(root).unwrap();
7244
7245 let err = CloudConfig::load(root).unwrap_err();
7246 let msg = format!("{err:#}");
7247 assert!(msg.contains("expected"), "got: {msg}");
7248 }
7249
7250 #[test]
7251 fn redirect_routes_skip_component_validation() {
7252 let tmp = tempfile::TempDir::new().unwrap();
7253 let root = tmp.path();
7254 // No services at all — redirect must still load cleanly because it
7255 // references nothing.
7256 let dom = DomainConfig {
7257 schema_version: 1,
7258 name: "yah-dev".into(),
7259 domain: "yah.dev".into(),
7260 front_door: FrontDoor::Worker,
7261 cdn_bucket: "yah-dev".into(),
7262 worker_bundle_path: None,
7263 routes: vec![DomainRoute {
7264 headers: Default::default(),
7265 path: "/old".into(),
7266 mode: RouteMode::Redirect {
7267 target: "https://yah.dev/blog".into(),
7268 status: 308,
7269 },
7270 }],
7271 };
7272 dom.save(root).unwrap();
7273
7274 let cfg = CloudConfig::load(root).unwrap();
7275 assert!(cfg.domain("yah-dev").is_some());
7276 }
7277
7278 #[test]
7279 fn name_must_match_file_stem() {
7280 let tmp = tempfile::TempDir::new().unwrap();
7281 let root = tmp.path();
7282 // Hand-write a file whose stem disagrees with its `name`.
7283 let dir = root.join(".yah").join("domains");
7284 std::fs::create_dir_all(&dir).unwrap();
7285 std::fs::write(
7286 dir.join("yah-dev.toml"),
7287 r#"schema_version = 1
7288name = "different-name"
7289domain = "yah.dev"
7290front_door = "bucket-direct"
7291cdn_bucket = "yah-dev"
7292"#,
7293 )
7294 .unwrap();
7295
7296 let err = CloudConfig::load(root).unwrap_err();
7297 let msg = format!("{err:#}");
7298 assert!(msg.contains("must match the file stem"), "got: {msg}");
7299 }
7300
7301 #[test]
7302 fn net_alias_tier_subdomain_manifest_loads_and_cross_refs() {
7303 // R561-F2: a per-tenant subdomain manifest on the net.yah.dev wildcard
7304 // alias tier is just a DomainConfig whose `domain` is `<name>.net.yah.dev`
7305 // and whose static route cross-refs the tenant's service component.
7306 // This is exactly the shape .yah/domains/scrabcake-net-yah-dev.toml ships.
7307 let tmp = tempfile::TempDir::new().unwrap();
7308 let root = tmp.path();
7309 write_marketing_service(root); // service "yah-marketing", component "site"
7310
7311 let dom = DomainConfig {
7312 schema_version: 1,
7313 name: "tenant-net-yah-dev".into(),
7314 domain: "tenant.net.yah.dev".into(),
7315 front_door: FrontDoor::Worker,
7316 cdn_bucket: "net-yah-dev".into(), // shared per-tier bucket
7317 worker_bundle_path: None,
7318 routes: vec![DomainRoute {
7319 headers: Default::default(),
7320 path: "/*".into(),
7321 mode: RouteMode::Static {
7322 component: "yah-marketing/site".into(),
7323 },
7324 }],
7325 };
7326 dom.save(root).unwrap();
7327
7328 let cfg = CloudConfig::load(root).unwrap();
7329 let dom = cfg
7330 .domain("tenant-net-yah-dev")
7331 .expect("net-tier subdomain manifest should load");
7332 assert_eq!(dom.domain, "tenant.net.yah.dev");
7333 assert_eq!(dom.cdn_bucket, "net-yah-dev");
7334 }
7335
7336 // ─── R572-F3: NodeAllocatable + taints ──────────────────────────────────
7337
7338 #[test]
7339 fn machine_allocatable_round_trips() {
7340 let toml_src = r#"
7341name = "us-west-001"
7342provider = "static"
7343mesh_tags = ["tag:cloud-runner"]
7344[allocatable]
7345memory_mb = 3800
7346cpu_millis = 2000
7347"#;
7348 let m: MachineConfig = toml::from_str(toml_src).unwrap();
7349 let a = m.allocatable.as_ref().expect("allocatable should parse");
7350 assert_eq!(a.memory_mb, 3800);
7351 assert_eq!(a.cpu_millis, 2000);
7352
7353 let s = toml::to_string(&m).unwrap();
7354 let back: MachineConfig = toml::from_str(&s).unwrap();
7355 let a2 = back.allocatable.as_ref().unwrap();
7356 assert_eq!(a2.memory_mb, 3800);
7357 assert_eq!(a2.cpu_millis, 2000);
7358 }
7359
7360 #[test]
7361 fn machine_taints_round_trips() {
7362 let toml_src = r#"
7363name = "us-south-001"
7364provider = "static"
7365mesh_tags = ["tag:cloud-runner"]
7366taints = ["no-appliance"]
7367"#;
7368 let m: MachineConfig = toml::from_str(toml_src).unwrap();
7369 assert_eq!(m.taints, vec!["no-appliance"]);
7370
7371 let s = toml::to_string(&m).unwrap();
7372 let back: MachineConfig = toml::from_str(&s).unwrap();
7373 assert_eq!(back.taints, vec!["no-appliance"]);
7374 }
7375
7376 #[test]
7377 fn machine_allocatable_absent_is_none() {
7378 let toml_src = "name = \"node\"\nprovider = \"static\"\nmesh_tags = []\n";
7379 let m: MachineConfig = toml::from_str(toml_src).unwrap();
7380 assert!(m.allocatable.is_none());
7381 assert!(m.taints.is_empty());
7382 }
7383
7384 #[test]
7385 fn machine_allocatable_skipped_when_none() {
7386 let m = make_machine("node", vec![]);
7387 let s = toml::to_string(&m).unwrap();
7388 assert!(
7389 !s.contains("allocatable"),
7390 "None allocatable must be omitted: {s}"
7391 );
7392 assert!(!s.contains("taints"), "empty taints must be omitted: {s}");
7393 }
7394
7395 #[test]
7396 fn machine_multiple_taints_round_trip() {
7397 let toml_src = r#"
7398name = "quarantined"
7399provider = "static"
7400mesh_tags = ["tag:build-worker"]
7401taints = ["no-server", "no-appliance", "no-job"]
7402"#;
7403 let m: MachineConfig = toml::from_str(toml_src).unwrap();
7404 assert_eq!(m.taints.len(), 3);
7405 assert!(m.taints.contains(&"no-server".to_string()));
7406 assert!(m.taints.contains(&"no-appliance".to_string()));
7407 assert!(m.taints.contains(&"no-job".to_string()));
7408 // R742-T4: every key here is one the scheduler reads. This fixture
7409 // used to carry `no-voter`, which none of them is.
7410 assert!(m.inert_taints().is_empty());
7411 }
7412
7413 // ─── R742-T4 (W305): inert-taint classification ─────────────────────────
7414
7415 #[test]
7416 fn every_archetype_repel_key_is_live() {
7417 for arch in LifecycleArchetype::ALL {
7418 let key = format!("no-{}", arch.taint_key());
7419 assert_eq!(
7420 taint_effect(&key),
7421 TaintEffect::Repels(arch),
7422 "{key} must repel {arch:?}"
7423 );
7424 }
7425 }
7426
7427 #[test]
7428 fn public_ip_is_an_affinity_key_not_an_inert_one() {
7429 assert_eq!(
7430 taint_effect(workload_spec::PUBLIC_IP_TAINT),
7431 TaintEffect::Attracts
7432 );
7433 }
7434
7435 #[test]
7436 fn a_free_form_taint_is_inert_and_says_so() {
7437 // W305's headline example: `taints = ["qa"]` parsed clean and did
7438 // nothing. Environment is not expressible as a taint.
7439 assert_eq!(taint_effect("qa"), TaintEffect::Inert);
7440 // And the one that actually cost fleet state: `no-voter` reads as an
7441 // exclusion and excludes nothing — "voter" is not an archetype.
7442 assert_eq!(taint_effect("no-voter"), TaintEffect::Inert);
7443 // A near-miss on a real key is inert too, not silently forgiven.
7444 assert_eq!(taint_effect("no-servers"), TaintEffect::Inert);
7445
7446 let m = make_machine_with_capacity(
7447 "dev-pi",
7448 8192,
7449 4000,
7450 vec!["no-appliance", "no-voter", "qa"],
7451 );
7452 assert_eq!(m.inert_taints(), vec!["no-voter", "qa"]);
7453 }
7454
7455 #[test]
7456 fn an_inert_taint_changes_no_placement_decision() {
7457 // The reason this is a lint and not a behaviour change: the guard's
7458 // whole premise is that these keys are invisible to `matches`.
7459 let clean = make_machine_with_capacity("n", 8192, 4000, vec![]);
7460 let noisy = make_machine_with_capacity("n", 8192, 4000, vec!["no-voter", "qa"]);
7461 for arch in LifecycleArchetype::ALL {
7462 let req = RequiredSpec {
7463 repel_archetype: Some(arch),
7464 ..Default::default()
7465 };
7466 assert_eq!(req.matches(&clean), req.matches(&noisy));
7467 }
7468 }
7469
7470 #[test]
7471 fn live_taint_keys_lists_the_whole_legal_vocabulary() {
7472 assert_eq!(
7473 live_taint_keys(),
7474 vec!["no-appliance", "no-job", "no-server", "public-ip"]
7475 );
7476 }
7477
7478 // ─── R742-F1 (W305): sovereign groups ───────────────────────────────────
7479
7480 /// A machine in `group`, with the role left unwritten — which is the state
7481 /// of every machine TOML that predates R605-F12 and resolves to `voter`.
7482 fn in_group(name: &str, group: Option<&str>) -> MachineConfig {
7483 MachineConfig {
7484 sovereign_group: group.map(String::from),
7485 ..make_machine(name, vec![])
7486 }
7487 }
7488
7489 /// A machine in `group` with its quorum eligibility stated (R605-F12).
7490 fn in_group_as(name: &str, group: &str, role: SovereignRole) -> MachineConfig {
7491 MachineConfig {
7492 sovereign_group: Some(group.to_string()),
7493 sovereign_role: Some(role),
7494 ..make_machine(name, vec![])
7495 }
7496 }
7497
7498 #[test]
7499 fn a_join_within_one_sovereign_group_is_permitted() {
7500 assert_eq!(
7501 judge_join(
7502 &in_group("us-west-013", Some("dev")),
7503 &in_group("us-west-011", Some("dev")),
7504 ),
7505 JoinVerdict::Permit
7506 );
7507 }
7508
7509 /// The case the field exists for: before it, the only thing standing
7510 /// between a dev Pi and the prod quorum was a comment in a TOML.
7511 #[test]
7512 fn a_cross_group_join_is_refused_naming_both_groups() {
7513 let verdict = judge_join(
7514 &in_group("us-west-011", Some("dev")),
7515 &in_group("us-west-001", Some("prod")),
7516 );
7517 let JoinVerdict::Refuse(msg) = verdict else {
7518 panic!("a dev node joining prod must be refused: {verdict:?}");
7519 };
7520 // A refusal that does not name what it saw is one the operator has to
7521 // go and reconstruct, so it gets worked around instead of fixed.
7522 assert!(msg.contains("us-west-011") && msg.contains("us-west-001"), "{msg}");
7523 assert!(msg.contains("dev") && msg.contains("prod"), "{msg}");
7524 }
7525
7526 /// `None` is a declaration ("standalone, in no group"), not a gap — so
7527 /// growing prod with an unstamped box is a cross-group join too, and the
7528 /// refusal has to say which file makes it legal.
7529 #[test]
7530 fn an_undeclared_node_cannot_join_a_declared_group() {
7531 let verdict = judge_join(
7532 &in_group("us-west-002", None),
7533 &in_group("us-west-001", Some("prod")),
7534 );
7535 let JoinVerdict::Refuse(msg) = verdict else {
7536 panic!("an unstamped node joining prod must be refused: {verdict:?}");
7537 };
7538 assert!(
7539 msg.contains(".yah/infra/machines/us-west-002.toml"),
7540 "the refusal must name the file to stamp: {msg}"
7541 );
7542 }
7543
7544 #[test]
7545 fn a_declared_node_cannot_join_a_standalone_target() {
7546 // us-west-003 is `mode: standalone` on purpose; it is not a group of
7547 // one waiting to be grown.
7548 let verdict = judge_join(
7549 &in_group("us-west-001", Some("prod")),
7550 &in_group("us-west-003", None),
7551 );
7552 assert!(matches!(verdict, JoinVerdict::Refuse(msg) if msg.contains("us-west-003")));
7553 }
7554
7555 #[test]
7556 fn two_undeclared_nodes_cannot_form_an_undeclared_group() {
7557 let verdict = judge_join(
7558 &in_group("us-west-002", None),
7559 &in_group("us-west-015", None),
7560 );
7561 assert!(
7562 matches!(&verdict, JoinVerdict::Refuse(msg) if msg.contains("us-west-002")
7563 && msg.contains("us-west-015")),
7564 "forming a group nobody declared must be refused, naming both: {verdict:?}"
7565 );
7566 }
7567
7568 // ─── R605-F12: the voting axis ──────────────────────────────────────────
7569
7570 /// The whole ticket in one assertion. us-west-003 is a member of prod —
7571 /// same secrets, same upgrade cadence, same destruction — and must never
7572 /// hold a prod raft seat. Before the role axis, the only thing refusing it
7573 /// was its *absent* group stamp, so writing down the truth above would have
7574 /// removed the guard.
7575 #[test]
7576 fn a_non_voting_member_is_refused_into_its_own_group() {
7577 let verdict = judge_join(
7578 &in_group_as("us-west-003", "prod", SovereignRole::NonVoter),
7579 &in_group_as("us-west-001", "prod", SovereignRole::Voter),
7580 );
7581 let JoinVerdict::Refuse(msg) = verdict else {
7582 panic!("a non-voting prod member must not join the prod quorum: {verdict:?}");
7583 };
7584 assert!(msg.contains("us-west-003") && msg.contains("NON-VOTING"), "{msg}");
7585 // The refusal must not blame the group: both sides say "prod", and a
7586 // cross-group message here would read as a bug in the check itself.
7587 assert!(!msg.contains("cross-group"), "{msg}");
7588 assert!(
7589 msg.contains(".yah/infra/machines/us-west-003.toml"),
7590 "the refusal must name the file that decides it: {msg}"
7591 );
7592 }
7593
7594 /// Read from the other end: a box declared non-voting has no quorum seat to
7595 /// be grown, so it cannot be a join target either.
7596 #[test]
7597 fn a_non_voting_target_has_no_quorum_to_grow() {
7598 let verdict = judge_join(
7599 &in_group_as("us-west-001", "prod", SovereignRole::Voter),
7600 &in_group_as("us-west-003", "prod", SovereignRole::NonVoter),
7601 );
7602 assert!(
7603 matches!(&verdict, JoinVerdict::Refuse(msg) if msg.contains("the target")
7604 && msg.contains("us-west-003")),
7605 "{verdict:?}"
7606 );
7607 }
7608
7609 /// A non-voter joining a *standalone* target is refused for two reasons at
7610 /// once, and the message must pick the one whose fix would actually work.
7611 /// Naming the role here would send the operator to flip `sovereign_role`
7612 /// and come back to the same refusal.
7613 #[test]
7614 fn a_refusal_names_the_group_when_fixing_the_role_would_not_help() {
7615 let verdict = judge_join(
7616 &in_group_as("us-west-003", "prod", SovereignRole::NonVoter),
7617 &in_group("us-west-002", None),
7618 );
7619 let JoinVerdict::Refuse(msg) = verdict else {
7620 panic!("a standalone target has no group to join: {verdict:?}");
7621 };
7622 assert!(
7623 msg.contains(".yah/infra/machines/us-west-002.toml"),
7624 "the refusal must point at the target's missing group stamp: {msg}"
7625 );
7626 assert!(!msg.contains("NON-VOTING"), "{msg}");
7627 }
7628
7629 /// The back-compat seam, pinned: the six nodes stamped before R605-F12
7630 /// write no role, and an absent role means what declaring a group has
7631 /// always meant. If this flips, the live prod and dev quorums stop being
7632 /// growable on a config the operator never edited.
7633 #[test]
7634 fn an_unwritten_role_still_joins_its_group() {
7635 let joiner = in_group("us-west-013", Some("dev"));
7636 assert_eq!(joiner.sovereign_role, None);
7637 assert_eq!(
7638 judge_join(&joiner, &in_group("us-west-011", Some("dev"))),
7639 JoinVerdict::Permit
7640 );
7641 assert_eq!(
7642 judge_join(
7643 &joiner,
7644 &in_group_as("us-west-011", "dev", SovereignRole::Voter)
7645 ),
7646 JoinVerdict::Permit
7647 );
7648 }
7649
7650 /// A non-voting member is still a *member*, and the two claims must not be
7651 /// conflated: `sovereign_membership()` reports the group either way, so a
7652 /// consumer asking "is this box in prod's blast radius" gets yes.
7653 #[test]
7654 fn a_non_voter_is_still_in_the_group_it_names() {
7655 let m = in_group_as("us-west-003", "prod", SovereignRole::NonVoter);
7656 assert_eq!(m.sovereign_membership().group, Some("prod"));
7657 assert!(!m.sovereign_membership().role.is_voter());
7658
7659 // …and the group-membership query the fleet reads is unaffected by it.
7660 let cfg = make_empty_cfg(vec![
7661 m,
7662 in_group_as("us-west-001", "prod", SovereignRole::Voter),
7663 ]);
7664 assert_eq!(
7665 cfg.machines_in_group("prod")
7666 .iter()
7667 .map(|m| m.name.as_str())
7668 .collect::<Vec<_>>(),
7669 vec!["us-west-003", "us-west-001"]
7670 );
7671 }
7672
7673 /// The role travels through TOML in one spelling, and an absent one stays
7674 /// absent on the way back out — otherwise every machine file would grow a
7675 /// `sovereign_role = "voter"` line the operator never wrote, and the
7676 /// unroled-member lint would have nothing left to find.
7677 #[test]
7678 fn sovereign_role_round_trips_and_is_omitted_when_unwritten() {
7679 let m: MachineConfig = toml::from_str(
7680 r#"
7681name = "us-west-003"
7682provider = "static"
7683region = "us-west"
7684arch = "x86_64"
7685mesh_tags = []
7686sovereign_group = "prod"
7687sovereign_role = "non-voter"
7688"#,
7689 )
7690 .unwrap();
7691 assert_eq!(m.sovereign_role, Some(SovereignRole::NonVoter));
7692 assert!(toml::to_string(&m)
7693 .unwrap()
7694 .contains(r#"sovereign_role = "non-voter""#));
7695
7696 let unwritten = MachineConfig {
7697 sovereign_role: None,
7698 ..m
7699 };
7700 assert!(!toml::to_string(&unwritten)
7701 .unwrap()
7702 .contains("sovereign_role"));
7703 }
7704
7705 /// The invariant the ticket is most explicit about: a sovereign group is a
7706 /// blast radius, not a filter. If this ever fails, `matches` has grown an
7707 /// axis it must not have and dev-mode workloads have silently become
7708 /// unschedulable on the dev group.
7709 #[test]
7710 fn sovereign_group_is_not_a_placement_input() {
7711 let standalone = in_group("n", None);
7712 let grouped = in_group("n", Some("dev"));
7713 let other = in_group("n", Some("prod"));
7714
7715 for spec in [
7716 RequiredSpec::default(),
7717 RequiredSpec {
7718 regions: vec!["us-west".into()],
7719 ..Default::default()
7720 },
7721 RequiredSpec {
7722 repel_archetype: Some(LifecycleArchetype::Appliance),
7723 ..Default::default()
7724 },
7725 ] {
7726 let baseline = spec.matches(&standalone);
7727 assert_eq!(spec.matches(&grouped), baseline);
7728 assert_eq!(spec.matches(&other), baseline);
7729 }
7730 }
7731
7732 // ─── R742-F3 (W305): group → machine set, and group-scoped admission ────
7733
7734 /// The primitive `migrate --to` needs and `rollout plan` still lacks
7735 /// (W314 gap 1): a group exists only as the set of machines naming it, so
7736 /// membership has to be derived rather than declared anywhere.
7737 #[test]
7738 fn machines_in_group_derives_membership_from_the_declarations() {
7739 let cfg = make_empty_cfg(vec![
7740 in_group("us-west-001", Some("prod")),
7741 in_group("us-west-011", Some("dev")),
7742 in_group("us-west-013", Some("dev")),
7743 in_group("us-west-002", None),
7744 ]);
7745
7746 let dev: Vec<&str> = cfg
7747 .machines_in_group("dev")
7748 .iter()
7749 .map(|m| m.name.as_str())
7750 .collect();
7751 assert_eq!(dev, vec!["us-west-011", "us-west-013"]);
7752 assert_eq!(cfg.machines_in_group("prod").len(), 1);
7753
7754 // Standalone is "in no group", not "in a group called none" — so an
7755 // unstamped box is never swept into a migration target.
7756 assert!(cfg.machines_in_group("").is_empty());
7757 assert!(cfg.machines_in_group("staging").is_empty());
7758 }
7759
7760 #[test]
7761 fn declared_sovereign_groups_is_the_vocabulary_a_bad_target_is_named_against() {
7762 let cfg = make_empty_cfg(vec![
7763 in_group("a", Some("prod")),
7764 in_group("b", Some("dev")),
7765 in_group("c", Some("prod")),
7766 in_group("d", None),
7767 ]);
7768 // Sorted + deduped, and standalone contributes nothing.
7769 assert_eq!(cfg.declared_sovereign_groups(), vec!["dev", "prod"]);
7770 assert!(make_empty_cfg(vec![in_group("a", None)])
7771 .declared_sovereign_groups()
7772 .is_empty());
7773 }
7774
7775 /// Group-scoped admission must be the SAME predicate as unscoped
7776 /// admission, only over fewer candidates. If it ever diverges, `migrate`
7777 /// becomes a way to place a workload somewhere `yah cloud apply` would
7778 /// refuse — which is exactly the silent routing-around W305 exists to stop.
7779 #[test]
7780 fn admit_workload_in_group_narrows_candidates_without_changing_the_predicate() {
7781 let mut prod = in_group("us-west-001", Some("prod"));
7782 prod.mesh_tags = vec!["tag:cloud-runner".into()];
7783 let mut dev_repels = in_group("us-west-011", Some("dev"));
7784 dev_repels.taints = vec!["no-appliance".into()];
7785 let mut dev_ok = in_group("us-west-013", Some("dev"));
7786 dev_ok.mesh_tags = vec!["tag:cloud-runner".into()];
7787
7788 let cfg = make_empty_cfg(vec![prod, dev_repels, dev_ok]);
7789
7790 let mut ws = ws_with_selector(None);
7791 ws.archetype = Some(LifecycleArchetype::Appliance);
7792
7793 // Unscoped picks the first match in declaration order.
7794 assert_eq!(cfg.admit_workload(&ws).unwrap().name, "us-west-001");
7795 // Scoped skips the repelling dev node and lands on the other one —
7796 // the taint is honoured, not bypassed.
7797 assert_eq!(
7798 cfg.admit_workload_in_group(&ws, "dev").unwrap().name,
7799 "us-west-013"
7800 );
7801 }
7802
7803 #[test]
7804 fn admit_workload_in_group_distinguishes_an_empty_group_from_a_repelling_one() {
7805 let mut dev = in_group("us-west-011", Some("dev"));
7806 dev.taints = vec!["no-appliance".into()];
7807 let cfg = make_empty_cfg(vec![in_group("us-west-001", Some("prod")), dev]);
7808
7809 let mut ws = ws_with_selector(None);
7810 ws.archetype = Some(LifecycleArchetype::Appliance);
7811
7812 // A group nobody declares names the legal vocabulary, because a typo
7813 // is the realistic cause and "no candidates" would send the operator
7814 // hunting for a placement problem that does not exist.
7815 let missing = cfg.admit_workload_in_group(&ws, "stagng").unwrap_err().to_string();
7816 assert!(missing.contains("no machine declares"), "{missing}");
7817 assert!(missing.contains("dev") && missing.contains("prod"), "{missing}");
7818
7819 // A group that exists but refuses names the machines it tried.
7820 let repelled = cfg.admit_workload_in_group(&ws, "dev").unwrap_err().to_string();
7821 assert!(repelled.contains("us-west-011"), "{repelled}");
7822 }
7823
7824 #[test]
7825 fn sovereign_group_round_trips_and_is_omitted_when_standalone() {
7826 let src = r#"
7827name = "us-west-011"
7828provider = "static"
7829mesh_tags = []
7830sovereign_group = "dev"
7831"#;
7832 let m: MachineConfig = toml::from_str(src).unwrap();
7833 assert_eq!(m.sovereign_group.as_deref(), Some("dev"));
7834 assert!(toml::to_string(&m).unwrap().contains("sovereign_group"));
7835
7836 // A machine that predates the field parses as standalone and does not
7837 // grow the key back on write.
7838 let legacy: MachineConfig =
7839 toml::from_str("name = \"us-west-002\"\nprovider = \"static\"\nmesh_tags = []\n")
7840 .unwrap();
7841 assert_eq!(legacy.sovereign_group, None);
7842 assert!(!toml::to_string(&legacy).unwrap().contains("sovereign_group"));
7843 }
7844
7845 // ─── R572-F5: capacity floor + absolute (untolerable) taints ────────────
7846
7847 fn make_machine_with_capacity(
7848 name: &str,
7849 memory_mb: u32,
7850 cpu_millis: u32,
7851 taints: Vec<&str>,
7852 ) -> MachineConfig {
7853 MachineConfig {
7854 allocatable: Some(NodeAllocatable {
7855 memory_mb,
7856 cpu_millis,
7857 }),
7858 taints: taints.into_iter().map(String::from).collect(),
7859 ..make_machine(name, vec![])
7860 }
7861 }
7862
7863 fn server_spec(memory_mb: u32, cpu_millis: u32) -> WorkloadSpec {
7864 use workload_spec::{ImageRef, LifecycleArchetype, ResourceLimits, TierTag};
7865 let mut ws = WorkloadSpec::for_forge(
7866 "f5-test",
7867 ImageRef {
7868 registry: "localhost".into(),
7869 repository: "test".into(),
7870 tag: "latest".into(),
7871 digest: workload_spec::testing::test_digest(),
7872 },
7873 TierTag("infra".into()),
7874 vec![],
7875 );
7876 ws.archetype = Some(LifecycleArchetype::Server);
7877 ws.resources = ResourceLimits {
7878 memory_mb,
7879 cpu_millis,
7880 ephemeral_storage_mb: 0,
7881 };
7882 // These are SERVER specs that borrow `for_forge` as a constructor
7883 // shortcut, so drop the forge memory request it stamps on — otherwise
7884 // every spec here silently requests the forge default instead of the
7885 // `memory_mb` the caller passed, and the capacity-floor tests below
7886 // stop testing their own argument. A server workload declares no
7887 // request, which is the documented fall-back-to-`resources.memory_mb`
7888 // path (`WorkloadSpec::memory_request_mb`).
7889 ws.annotations
7890 .remove(workload_spec::MEMORY_REQUEST_ANNOTATION);
7891 ws
7892 }
7893
7894 fn appliance_spec_ws(memory_mb: u32, cpu_millis: u32) -> WorkloadSpec {
7895 use workload_spec::LifecycleArchetype;
7896 let mut ws = server_spec(memory_mb, cpu_millis);
7897 ws.archetype = Some(LifecycleArchetype::Appliance);
7898 ws
7899 }
7900
7901 #[test]
7902 fn capacity_floor_rejects_undersized_node() {
7903 let cfg = make_empty_cfg(vec![make_machine_with_capacity("small", 256, 500, vec![])]);
7904 let ws = server_spec(512, 1000); // demands more than available
7905 assert!(cfg.admit_workload(&ws).is_err());
7906 }
7907
7908 #[test]
7909 fn capacity_floor_accepts_exact_fit() {
7910 let cfg = make_empty_cfg(vec![make_machine_with_capacity("exact", 512, 1000, vec![])]);
7911 let ws = server_spec(512, 1000);
7912 assert_eq!(cfg.admit_workload(&ws).unwrap().name, "exact");
7913 }
7914
7915 #[test]
7916 fn capacity_floor_passes_when_allocatable_absent() {
7917 // A machine with no allocatable block skips the capacity check (no data).
7918 let cfg = make_empty_cfg(vec![make_machine("no-alloc", vec![])]);
7919 let ws = server_spec(99999, 99999); // would exceed any real node
7920 assert_eq!(cfg.admit_workload(&ws).unwrap().name, "no-alloc");
7921 }
7922
7923 #[test]
7924 fn taint_repulsion_blocks_appliance_on_no_appliance_node() {
7925 let cfg = make_empty_cfg(vec![make_machine_with_capacity(
7926 "south",
7927 1024,
7928 2000,
7929 vec!["no-appliance"],
7930 )]);
7931 let ws = appliance_spec_ws(256, 500);
7932 assert!(
7933 cfg.admit_workload(&ws).is_err(),
7934 "appliance must be repelled by no-appliance taint"
7935 );
7936 }
7937
7938 #[test]
7939 fn taint_repulsion_allows_server_on_no_appliance_node() {
7940 // "no-appliance" only repels Appliance workloads; servers are unaffected.
7941 let cfg = make_empty_cfg(vec![make_machine_with_capacity(
7942 "south",
7943 1024,
7944 2000,
7945 vec!["no-appliance"],
7946 )]);
7947 let ws = server_spec(256, 500);
7948 assert_eq!(cfg.admit_workload(&ws).unwrap().name, "south");
7949 }
7950
7951 #[test]
7952 fn taint_repulsion_job_not_blocked_by_no_server() {
7953 use workload_spec::LifecycleArchetype;
7954 let cfg = make_empty_cfg(vec![make_machine_with_capacity(
7955 "build-box",
7956 8192,
7957 4000,
7958 vec!["no-server", "no-appliance"],
7959 )]);
7960 let mut ws = server_spec(256, 500);
7961 ws.archetype = Some(LifecycleArchetype::Job);
7962 // Job only repelled by "no-job"; "no-server" and "no-appliance" don't affect it.
7963 assert_eq!(cfg.admit_workload(&ws).unwrap().name, "build-box");
7964 }
7965
7966 #[test]
7967 fn requires_taint_affinity_blocks_placement_without_it() {
7968 use workload_spec::{LifecycleArchetype, PUBLIC_IP_TAINT, REQUIRES_TAINT_ANNOTATION};
7969 // Simulate the passway ingress appliance: requires "public-ip" taint.
7970 let mut ws = appliance_spec_ws(256, 512);
7971 ws.archetype = Some(LifecycleArchetype::Appliance);
7972 ws.annotations
7973 .insert(REQUIRES_TAINT_ANNOTATION.into(), PUBLIC_IP_TAINT.into());
7974
7975 // Node without the taint: rejected.
7976 let cfg = make_empty_cfg(vec![make_machine_with_capacity(
7977 "no-pip",
7978 2048,
7979 2000,
7980 vec![],
7981 )]);
7982 assert!(cfg.admit_workload(&ws).is_err());
7983
7984 // Node with the taint: accepted.
7985 let cfg = make_empty_cfg(vec![make_machine_with_capacity(
7986 "pub-node",
7987 2048,
7988 2000,
7989 vec!["public-ip"],
7990 )]);
7991 assert_eq!(cfg.admit_workload(&ws).unwrap().name, "pub-node");
7992 }
7993
7994 #[test]
7995 fn w244_fleet_scenario_appliance_rejected_from_south_and_west002() {
7996 // Full W244 fleet table scenario:
7997 // us-west-001/east-001: no taints, large capacity → appliance lands here
7998 // us-south-001: no-appliance taint → appliance rejected
7999 // us-west-002: no-server, no-appliance → appliance rejected
8000 let cfg = make_empty_cfg(vec![
8001 make_machine_with_capacity("us-south-001", 512, 1000, vec!["no-appliance"]),
8002 make_machine_with_capacity(
8003 "us-west-002",
8004 16384,
8005 8000,
8006 vec!["no-server", "no-appliance"],
8007 ),
8008 make_machine_with_capacity("us-west-001", 4096, 4000, vec![]),
8009 ]);
8010 let ws = appliance_spec_ws(256, 500);
8011 // Skips south (no-appliance) and west-002 (no-appliance), lands on west-001.
8012 assert_eq!(cfg.admit_workload(&ws).unwrap().name, "us-west-001");
8013 }
8014
8015 #[test]
8016 fn w244_fleet_scenario_job_lands_on_west002_first() {
8017 use workload_spec::LifecycleArchetype;
8018 // Jobs should prefer (or at least land on) the job-only box.
8019 let cfg = make_empty_cfg(vec![
8020 make_machine_with_capacity("us-west-001", 4096, 4000, vec![]),
8021 make_machine_with_capacity(
8022 "us-west-002",
8023 16384,
8024 8000,
8025 vec!["no-server", "no-appliance"],
8026 ),
8027 ]);
8028 let mut ws = server_spec(256, 500);
8029 ws.archetype = Some(LifecycleArchetype::Job);
8030 // No fleet node declares `no-job`, so a Job is repelled by nothing;
8031 // west-001 comes first in declaration order (greedy, no preference),
8032 // which is the expected tie-break. Note this is *absence of a repel
8033 // key*, not toleration — no workload can tolerate a taint (W305).
8034 let picked = cfg.admit_workload(&ws).unwrap();
8035 // Both are eligible.
8036 assert!(
8037 picked.name == "us-west-001" || picked.name == "us-west-002",
8038 "job must land on an eligible node, got {}",
8039 picked.name
8040 );
8041 }
8042
8043 #[test]
8044 fn r569_f4_macos_node_taints_keep_cloud_critical_off_but_admit_build_jobs() {
8045 use workload_spec::LifecycleArchetype;
8046 // R569-F4: the headless M2 (us-west-015) joins the fleet as a
8047 // build-worker but must never take cloud-critical load. It carries the
8048 // same repel set as the x86 build-worker (`no-server, no-appliance` —
8049 // see .yah/infra/machines/us-west-015.toml). This pins that intent:
8050 // with a plain cloud node available beside the Mac, every
8051 // cloud-critical archetype lands on the cloud node and never the Mac;
8052 // build Jobs (the Mac's actual purpose) remain eligible on it.
8053 //
8054 // R742-T4: `no-voter` used to sit in this set and in the TOML. It was
8055 // never read here — there is no "voter" workload archetype — and
8056 // R569-F3's learner-only join is what actually keeps the box out of
8057 // quorum. It is now rejected by `yah cloud validate` as inert.
8058 let mac_taints = vec!["no-server", "no-appliance"];
8059 let fleet = || {
8060 make_empty_cfg(vec![
8061 make_machine_with_capacity("us-west-015", 24576, 8000, mac_taints.clone()),
8062 make_machine_with_capacity("us-west-001", 4096, 4000, vec![]),
8063 ])
8064 };
8065
8066 // A cloud-critical Server workload is repelled from the Mac and lands
8067 // on the untainted cloud node.
8068 let cfg = fleet();
8069 assert_eq!(
8070 cfg.admit_workload(&server_spec(256, 500)).unwrap().name,
8071 "us-west-001",
8072 "a Server workload must never land on the no-server Mac node"
8073 );
8074
8075 // Same for an Appliance (pinned/stateful cloud-critical) workload.
8076 let cfg = fleet();
8077 assert_eq!(
8078 cfg.admit_workload(&appliance_spec_ws(256, 500))
8079 .unwrap()
8080 .name,
8081 "us-west-001",
8082 "an Appliance workload must never land on the no-appliance Mac node"
8083 );
8084
8085 // Sharpest repulsion proof: with ONLY the Mac in the fleet, a
8086 // cloud-critical Server workload is rejected outright — the taint keeps
8087 // it off even when that means nowhere to run.
8088 let mac_only = make_empty_cfg(vec![make_machine_with_capacity(
8089 "us-west-015",
8090 24576,
8091 8000,
8092 mac_taints.clone(),
8093 )]);
8094 assert!(
8095 mac_only.admit_workload(&server_spec(256, 500)).is_err(),
8096 "a Server workload must be repelled from a Mac-only fleet, not admitted"
8097 );
8098
8099 // But the Mac's real job — build/forge workloads — IS admitted on it:
8100 // it tolerates every fleet taint (there is no `no-job`).
8101 let mut job = server_spec(256, 500);
8102 job.archetype = Some(LifecycleArchetype::Job);
8103 assert_eq!(
8104 mac_only.admit_workload(&job).unwrap().name,
8105 "us-west-015",
8106 "a build Job must still be admitted on the Mac build-worker"
8107 );
8108 }
8109
8110 // ─── R615-F1: linked infra sources (`.yah/infra/sources.toml`) ─────────
8111
8112 #[test]
8113 fn sources_load_is_empty_when_the_file_is_absent() {
8114 // "Every camp without linked infra has none" — which today is every
8115 // camp — must not be an error.
8116 let tmp = tempfile::TempDir::new().unwrap();
8117 let cfg = SourcesConfig::load(tmp.path()).unwrap();
8118 assert_eq!(cfg, SourcesConfig::default());
8119 assert!(cfg.source.is_empty());
8120 assert_eq!(cfg.schema_version, 1);
8121 }
8122
8123 #[test]
8124 fn sources_parses_a_path_kind_exactly_like_w274s_example() {
8125 let tmp = tempfile::TempDir::new().unwrap();
8126 std::fs::write(
8127 tmp.path().join("sources.toml"),
8128 r#"
8129schema_version = 1
8130
8131[[source]]
8132owner = "yah"
8133kind = "path"
8134path = "../yah"
8135mode = "read-only"
8136"#,
8137 )
8138 .unwrap();
8139 let cfg = SourcesConfig::load(tmp.path()).unwrap();
8140 assert_eq!(cfg.source.len(), 1);
8141 let s = &cfg.source[0];
8142 assert_eq!(s.owner, "yah");
8143 assert_eq!(s.mode, SourceMode::ReadOnly);
8144 assert!(s.select.is_empty());
8145 match &s.kind {
8146 InfraSourceKind::Path { path } => assert_eq!(path, "../yah"),
8147 other => panic!("expected Path, got {other:?}"),
8148 }
8149 }
8150
8151 #[test]
8152 fn sources_parses_a_git_kind_reusing_gitsource_verbatim() {
8153 let tmp = tempfile::TempDir::new().unwrap();
8154 std::fs::write(
8155 tmp.path().join("sources.toml"),
8156 r#"
8157schema_version = 1
8158
8159[[source]]
8160owner = "yah"
8161kind = "git"
8162repo = "git@github.com:yah-ai/infra.git"
8163ref = "main"
8164subdir = "infra"
8165select = ["tag:cloud-runner"]
8166mode = "read-only"
8167"#,
8168 )
8169 .unwrap();
8170 let cfg = SourcesConfig::load(tmp.path()).unwrap();
8171 assert_eq!(cfg.source.len(), 1);
8172 let s = &cfg.source[0];
8173 assert_eq!(s.select, vec!["tag:cloud-runner".to_string()]);
8174 match &s.kind {
8175 InfraSourceKind::Git(git) => {
8176 assert_eq!(git.repo, "git@github.com:yah-ai/infra.git");
8177 assert_eq!(git.r#ref, "main");
8178 assert_eq!(git.subdir.as_deref(), Some("infra"));
8179 }
8180 other => panic!("expected Git, got {other:?}"),
8181 }
8182 }
8183
8184 #[test]
8185 fn sources_mode_defaults_to_read_only_and_manage_is_explicit() {
8186 let tmp = tempfile::TempDir::new().unwrap();
8187 std::fs::write(
8188 tmp.path().join("sources.toml"),
8189 r#"
8190schema_version = 1
8191
8192[[source]]
8193owner = "a"
8194kind = "path"
8195path = "../a"
8196
8197[[source]]
8198owner = "b"
8199kind = "path"
8200path = "../b"
8201mode = "manage"
8202"#,
8203 )
8204 .unwrap();
8205 let cfg = SourcesConfig::load(tmp.path()).unwrap();
8206 assert_eq!(cfg.source[0].mode, SourceMode::ReadOnly, "omitted mode = read-only");
8207 assert_eq!(cfg.source[1].mode, SourceMode::Manage);
8208 }
8209
8210 #[test]
8211 fn sources_preserves_declaration_order() {
8212 // Overlay order matters (R615-F2) when two sources name the same
8213 // machine — the list must round-trip in file order, not be reordered
8214 // by owner or kind.
8215 let tmp = tempfile::TempDir::new().unwrap();
8216 std::fs::write(
8217 tmp.path().join("sources.toml"),
8218 r#"
8219schema_version = 1
8220
8221[[source]]
8222owner = "second"
8223kind = "path"
8224path = "../second"
8225
8226[[source]]
8227owner = "first"
8228kind = "path"
8229path = "../first"
8230"#,
8231 )
8232 .unwrap();
8233 let cfg = SourcesConfig::load(tmp.path()).unwrap();
8234 let owners: Vec<&str> = cfg.source.iter().map(|s| s.owner.as_str()).collect();
8235 assert_eq!(owners, vec!["second", "first"]);
8236 }
8237
8238 #[test]
8239 fn sources_round_trips_through_serialize() {
8240 let cfg = SourcesConfig {
8241 schema_version: 1,
8242 source: vec![
8243 InfraSource {
8244 owner: "yah".into(),
8245 kind: InfraSourceKind::Path {
8246 path: "../yah".into(),
8247 },
8248 mode: SourceMode::ReadOnly,
8249 select: vec![],
8250 },
8251 InfraSource {
8252 owner: "yah".into(),
8253 kind: InfraSourceKind::Git(GitSource {
8254 repo: "git@github.com:yah-ai/infra.git".into(),
8255 r#ref: "main".into(),
8256 subdir: Some("infra".into()),
8257 }),
8258 mode: SourceMode::Manage,
8259 select: vec!["tag:cloud-runner".into()],
8260 },
8261 ],
8262 };
8263 let toml_str = toml::to_string_pretty(&cfg).unwrap();
8264 let reloaded: SourcesConfig = toml::from_str(&toml_str).unwrap();
8265 assert_eq!(reloaded, cfg, "round-trip through TOML must be lossless:\n{toml_str}");
8266 }
8267
8268 // ─── R615-F2: overlay loader in CloudConfig::load ───────────────────────
8269
8270 fn write_min_machine(dir: &Path, name: &str, extra_toml: &str) {
8271 std::fs::create_dir_all(dir).unwrap();
8272 // `extra_toml` supplies `mesh_tags` when the caller cares about it;
8273 // otherwise default to the empty list. Never hardcode `mesh_tags`
8274 // here as well as in `extra_toml` -- TOML rejects a duplicate key.
8275 let mesh_tags = if extra_toml.contains("mesh_tags") {
8276 String::new()
8277 } else {
8278 "mesh_tags = []\n".to_string()
8279 };
8280 std::fs::write(
8281 dir.join(format!("{name}.toml")),
8282 format!("name = \"{name}\"\nprovider = \"static\"\n{mesh_tags}{extra_toml}"),
8283 )
8284 .unwrap();
8285 }
8286
8287 fn write_min_provider(dir: &Path, id: &str) {
8288 std::fs::create_dir_all(dir).unwrap();
8289 std::fs::write(
8290 dir.join(format!("{id}.toml")),
8291 format!("schema_version = 1\nid = \"{id}\"\nkind = \"static\"\n"),
8292 )
8293 .unwrap();
8294 }
8295
8296 fn write_sources_toml(camp_root: &Path, body: &str) {
8297 let dir = camp_root.join(".yah/infra");
8298 std::fs::create_dir_all(&dir).unwrap();
8299 std::fs::write(dir.join("sources.toml"), body).unwrap();
8300 }
8301
8302 #[test]
8303 fn load_with_no_sources_toml_is_unchanged() {
8304 let tmp = tempfile::TempDir::new().unwrap();
8305 write_min_machine(&tmp.path().join(".yah/infra/machines"), "local-1", "");
8306 let cfg = CloudConfig::load(tmp.path()).unwrap();
8307 assert_eq!(cfg.machines.len(), 1);
8308 assert!(cfg.machine_origins.is_empty());
8309 assert!(cfg.provider_origins.is_empty());
8310 }
8311
8312 #[test]
8313 fn path_source_overlays_machines_and_providers_tagged_with_origin() {
8314 let camp = tempfile::TempDir::new().unwrap();
8315 let other = tempfile::TempDir::new().unwrap();
8316 write_min_machine(&other.path().join(".yah/infra/machines"), "borrowed-1", "");
8317 write_min_provider(&other.path().join(".yah/infra/providers"), "borrowed-provider");
8318 write_sources_toml(
8319 camp.path(),
8320 &format!(
8321 "schema_version = 1\n\n[[source]]\nowner = \"other\"\nkind = \"path\"\npath = \"{}\"\n",
8322 other.path().display()
8323 ),
8324 );
8325
8326 let cfg = CloudConfig::load(camp.path()).unwrap();
8327 assert_eq!(cfg.machines.len(), 1);
8328 assert_eq!(cfg.machines[0].name, "borrowed-1");
8329 assert_eq!(cfg.providers.len(), 1);
8330 assert_eq!(cfg.providers[0].id, "borrowed-provider");
8331
8332 let origin = cfg.machine_origins.get("borrowed-1").expect("origin recorded");
8333 assert_eq!(origin.owner, "other");
8334 assert_eq!(origin.mode, SourceMode::ReadOnly);
8335 assert!(origin.source.starts_with("path:"));
8336 assert_eq!(
8337 cfg.provider_origins.get("borrowed-provider").unwrap().owner,
8338 "other"
8339 );
8340 }
8341
8342 #[test]
8343 fn camp_local_wins_on_name_collision_and_carries_no_origin() {
8344 let camp = tempfile::TempDir::new().unwrap();
8345 let other = tempfile::TempDir::new().unwrap();
8346 // Both declare a machine named "shared" -- camp-local's copy must win,
8347 // and it must never gain an origin tag.
8348 write_min_machine(&camp.path().join(".yah/infra/machines"), "shared", "");
8349 write_min_machine(
8350 &other.path().join(".yah/infra/machines"),
8351 "shared",
8352 "nickname = \"the borrowed one\"\n",
8353 );
8354 write_sources_toml(
8355 camp.path(),
8356 &format!(
8357 "schema_version = 1\n\n[[source]]\nowner = \"other\"\nkind = \"path\"\npath = \"{}\"\n",
8358 other.path().display()
8359 ),
8360 );
8361
8362 let cfg = CloudConfig::load(camp.path()).unwrap();
8363 assert_eq!(cfg.machines.len(), 1, "the name collides, so exactly one entry");
8364 assert_eq!(cfg.machines[0].nickname, None, "camp-local's copy, not the borrowed one");
8365 assert!(
8366 !cfg.machine_origins.contains_key("shared"),
8367 "camp-local entries never carry an origin tag"
8368 );
8369 }
8370
8371 #[test]
8372 fn an_earlier_source_wins_over_a_later_one_on_collision() {
8373 let camp = tempfile::TempDir::new().unwrap();
8374 let first = tempfile::TempDir::new().unwrap();
8375 let second = tempfile::TempDir::new().unwrap();
8376 write_min_machine(&first.path().join(".yah/infra/machines"), "dup", "");
8377 write_min_machine(&second.path().join(".yah/infra/machines"), "dup", "");
8378 write_sources_toml(
8379 camp.path(),
8380 &format!(
8381 "schema_version = 1\n\n[[source]]\nowner = \"first\"\nkind = \"path\"\npath = \"{}\"\n\n[[source]]\nowner = \"second\"\nkind = \"path\"\npath = \"{}\"\n",
8382 first.path().display(),
8383 second.path().display()
8384 ),
8385 );
8386
8387 let cfg = CloudConfig::load(camp.path()).unwrap();
8388 assert_eq!(cfg.machines.len(), 1);
8389 assert_eq!(cfg.machine_origins.get("dup").unwrap().owner, "first");
8390 }
8391
8392 #[test]
8393 fn select_filters_borrowed_machines_by_name_or_mesh_tag() {
8394 let camp = tempfile::TempDir::new().unwrap();
8395 let other = tempfile::TempDir::new().unwrap();
8396 write_min_machine(&other.path().join(".yah/infra/machines"), "runner-1", "mesh_tags = [\"tag:cloud-runner\"]\n");
8397 write_min_machine(&other.path().join(".yah/infra/machines"), "excluded-1", "");
8398 write_sources_toml(
8399 camp.path(),
8400 &format!(
8401 "schema_version = 1\n\n[[source]]\nowner = \"other\"\nkind = \"path\"\npath = \"{}\"\nselect = [\"tag:cloud-runner\"]\n",
8402 other.path().display()
8403 ),
8404 );
8405
8406 let cfg = CloudConfig::load(camp.path()).unwrap();
8407 assert_eq!(cfg.machines.len(), 1);
8408 assert_eq!(cfg.machines[0].name, "runner-1");
8409 }
8410
8411 #[test]
8412 fn one_unparseable_foreign_machine_does_not_sink_the_rest_of_the_directory_or_the_load() {
8413 let camp = tempfile::TempDir::new().unwrap();
8414 let other = tempfile::TempDir::new().unwrap();
8415 let dir = other.path().join(".yah/infra/machines");
8416 write_min_machine(&dir, "good", "");
8417 // Schema-skew gotcha: a foreign machine this binary's MachineConfig
8418 // can't parse at all (not just an unknown field -- MachineConfig has
8419 // no deny_unknown_fields, so this has to fail on a TYPE, not a name).
8420 std::fs::write(dir.join("bad.toml"), "name = 1\nprovider = 2\n").unwrap();
8421 write_sources_toml(
8422 camp.path(),
8423 &format!(
8424 "schema_version = 1\n\n[[source]]\nowner = \"other\"\nkind = \"path\"\npath = \"{}\"\n",
8425 other.path().display()
8426 ),
8427 );
8428
8429 // Must not error at all -- camp-local load must never fail because a
8430 // source it doesn't own has one bad file.
8431 let cfg = CloudConfig::load(camp.path()).unwrap();
8432 assert_eq!(cfg.machines.len(), 1, "the good entry still loads");
8433 assert_eq!(cfg.machines[0].name, "good");
8434 }
8435
8436 #[test]
8437 fn an_unsynced_git_source_overlays_nothing_and_is_not_an_error() {
8438 // No `yah infra sync` (R615-T3) has ever run, so the cache dir this
8439 // resolves to doesn't exist. Must be silent, not fatal.
8440 let camp = tempfile::TempDir::new().unwrap();
8441 write_sources_toml(
8442 camp.path(),
8443 "schema_version = 1\n\n[[source]]\nowner = \"yah\"\nkind = \"git\"\nrepo = \"git@github.com:yah-ai/infra.git\"\nref = \"main\"\n",
8444 );
8445 let cfg = CloudConfig::load(camp.path()).unwrap();
8446 assert!(cfg.machines.is_empty());
8447 assert!(cfg.machine_origins.is_empty());
8448 }
8449
8450 #[test]
8451 fn a_synced_git_source_reads_from_the_cache_dir_not_the_repo_path() {
8452 // No `subdir` declared -- the checkout ROOT is the infra root.
8453 let camp = tempfile::TempDir::new().unwrap();
8454 let cache = crate::paths::infra_source_cache_dir(camp.path(), "yah");
8455 write_min_machine(&cache.join("machines"), "synced-1", "");
8456 write_sources_toml(
8457 camp.path(),
8458 "schema_version = 1\n\n[[source]]\nowner = \"yah\"\nkind = \"git\"\nrepo = \"git@github.com:yah-ai/infra.git\"\nref = \"main\"\n",
8459 );
8460 let cfg = CloudConfig::load(camp.path()).unwrap();
8461 assert_eq!(cfg.machines.len(), 1);
8462 assert_eq!(cfg.machines[0].name, "synced-1");
8463 assert!(cfg.machine_origins.get("synced-1").unwrap().source.starts_with("git:"));
8464 }
8465
8466 #[test]
8467 fn a_git_sources_subdir_is_honoured_like_the_component_case() {
8468 // W274's own example declares `subdir = "infra"` for a monorepo whose
8469 // registry lives under a subdirectory of the clone rather than at its
8470 // root -- prove `infra_root` actually reads it, not just `.subdir` on
8471 // GitSource parsing (R615-F1 already covers that half).
8472 let camp = tempfile::TempDir::new().unwrap();
8473 let cache = crate::paths::infra_source_cache_dir(camp.path(), "yah");
8474 write_min_machine(&cache.join("infra").join("machines"), "subdir-1", "");
8475 // Also plant a decoy at the checkout root to prove the root itself is
8476 // NOT read when a subdir is declared.
8477 write_min_machine(&cache.join("machines"), "root-decoy", "");
8478 write_sources_toml(
8479 camp.path(),
8480 "schema_version = 1\n\n[[source]]\nowner = \"yah\"\nkind = \"git\"\nrepo = \"git@github.com:yah-ai/infra.git\"\nref = \"main\"\nsubdir = \"infra\"\n",
8481 );
8482 let cfg = CloudConfig::load(camp.path()).unwrap();
8483 assert_eq!(cfg.machines.len(), 1);
8484 assert_eq!(cfg.machines[0].name, "subdir-1");
8485 }
8486
8487 #[test]
8488 fn load_from_config_dir_never_applies_sources_overlay() {
8489 // R615-F2's explicit decision: multi-root sibling trees don't inherit
8490 // the classic .yah/infra/sources.toml. Prove it rather than assert it
8491 // silently -- a sources.toml sitting at workspace_root/.yah/infra/
8492 // must NOT leak into a load_from_config_dir call even though both
8493 // share the same workspace_root.
8494 let camp = tempfile::TempDir::new().unwrap();
8495 let other = tempfile::TempDir::new().unwrap();
8496 write_min_machine(&other.path().join(".yah/infra/machines"), "borrowed-1", "");
8497 write_sources_toml(
8498 camp.path(),
8499 &format!(
8500 "schema_version = 1\n\n[[source]]\nowner = \"other\"\nkind = \"path\"\npath = \"{}\"\n",
8501 other.path().display()
8502 ),
8503 );
8504 let sibling_config_dir = camp.path().join(".noisetable");
8505 std::fs::create_dir_all(&sibling_config_dir).unwrap();
8506
8507 let cfg = CloudConfig::load_from_config_dir(&sibling_config_dir, camp.path()).unwrap();
8508 assert!(cfg.machines.is_empty(), "sources.toml must not apply here");
8509 assert!(cfg.machine_origins.is_empty());
8510 }
8511
8512 // ─── R615-T5: `inherit_machines` retirement — cutover proof ────────────
8513
8514 /// The successor to R615-T5's parity proof. That earlier pair of tests
8515 /// asserted the legacy `[infra].inherit_machines` redirect and an
8516 /// equivalent `kind = "path"` source resolved the same machine set, and
8517 /// that the two coexisted without duplicating rows. Both claims were about
8518 /// a mechanism that no longer exists, so they retired with it — what has
8519 /// to hold *now* is the other half of the same guarantee: a camp that
8520 /// declares only `sources.toml` resolves the shared root exactly as the
8521 /// redirect used to, and a stale `inherit_machines` key left behind in
8522 /// `camp.toml` changes nothing.
8523 ///
8524 /// That stale-key case is not hypothetical: it is precisely the state a
8525 /// camp is in between the code cutover and someone tidying its
8526 /// `camp.toml`, and a silent re-resolution there would double-count the
8527 /// borrowed nodes or hide their origin badge.
8528 #[test]
8529 fn a_stale_inherit_machines_key_does_not_change_what_sources_toml_resolves() {
8530 let shared = tempfile::TempDir::new().unwrap();
8531 write_min_machine(&shared.path().join(".yah/infra/machines"), "shared-node-1", "");
8532 write_min_machine(&shared.path().join(".yah/infra/machines"), "shared-node-2", "");
8533
8534 let sources_toml = format!(
8535 "schema_version = 1\n\n[[source]]\nowner = \"yah\"\nkind = \"path\"\npath = \"{}\"\nmode = \"read-only\"\n",
8536 shared.path().display()
8537 );
8538
8539 // Camp A: migrated cleanly — sources.toml only.
8540 let clean = tempfile::TempDir::new().unwrap();
8541 write_sources_toml(clean.path(), &sources_toml);
8542
8543 // Camp B: mid-migration — same source, plus the retired key still
8544 // sitting in camp.toml pointing at the same root.
8545 let stale = tempfile::TempDir::new().unwrap();
8546 std::fs::create_dir_all(stale.path().join(".yah")).unwrap();
8547 std::fs::write(
8548 stale.path().join(".yah/camp.toml"),
8549 format!(
8550 "[infra]\ninherit_machines = \"{}\"\n",
8551 shared.path().display()
8552 ),
8553 )
8554 .unwrap();
8555 write_sources_toml(stale.path(), &sources_toml);
8556
8557 let via_clean = CloudConfig::load(clean.path()).unwrap();
8558 let via_stale = CloudConfig::load(stale.path()).unwrap();
8559
8560 let names = |cfg: &CloudConfig| {
8561 let mut v: Vec<String> = cfg.machines.iter().map(|m| m.name.clone()).collect();
8562 v.sort();
8563 v
8564 };
8565 assert_eq!(
8566 names(&via_clean),
8567 names(&via_stale),
8568 "a leftover inherit_machines key must be inert — the retired redirect is gone"
8569 );
8570 assert_eq!(names(&via_clean), vec!["shared-node-1", "shared-node-2"]);
8571
8572 // And both are *borrowed*, not camp-local. This is the operator-facing
8573 // win the stopgap could never deliver: under the old redirect these
8574 // resolved with no origin at all, indistinguishable from locally-owned
8575 // nodes.
8576 assert_eq!(via_clean.machine_origins.len(), 2);
8577 assert_eq!(via_stale.machine_origins.len(), 2);
8578 for origin in via_stale.machine_origins.values() {
8579 assert_eq!(origin.owner, "yah");
8580 assert_eq!(origin.mode, SourceMode::ReadOnly);
8581 }
8582 }
8583}