use crate::domain::{GateKind, NodeId, TierId}; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use std::path::Path; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Topology { pub repo: RepoConfig, pub backup: BackupConfig, #[serde(rename = "tier")] pub tiers: Vec, /// Extra repos to fetch and check out beside the main worktree before a /// build, so a path dependency that reaches across the repo split resolves. /// Empty (default) keeps an existing `sando.toml` working unedited. See /// [`AuxRepo`] and [`crate::build::checkout_aux_repos`]. #[serde(default, rename = "aux_repo")] pub aux_repos: Vec, } /// An auxiliary repo checked out beside the per-sha worktree so cross-repo path /// dependencies resolve at build time. /// /// The concrete case (2026-07-24): `mnw-cli` — a companion built from the MNW /// worktree — carries `synckit-client = { path = "../../synckit/synckit-client" }` /// after synckit moved to its own repo. From the companion crate at /// `//mnw-cli`, that path resolves to `/synckit`, a sibling /// of the per-sha worktree that Sando otherwise never creates, so the companion /// build failed with "No such file or directory". An `aux_repo` named to land at /// `checkout_dir = "synckit"` puts the synckit source exactly there. /// /// The checkout is at the FIXED `/`, not per-sha: the path /// dependency resolves to that spot regardless of the MNW sha, and builds /// serialize, so a single shared checkout refreshed to `branch` HEAD each build /// is correct. Because a path dep has no lockfile pin, "branch HEAD" is the honest /// resolution — the same contract as the dev working copy. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AuxRepo { /// Human label for logs and errors (e.g. `synckit`). pub name: String, /// Bare repo Sando fetches into and worktrees from, e.g. /// `/srv/sando/synckit.git`. Auto-created (hookless) on first build. pub bare_path: String, /// Canonical git remote fetched before checkout. Like [`RepoConfig::upstream`] /// but required here: an aux repo is pull-based (nobody pushes to its bare). pub upstream: String, /// Branch whose HEAD is checked out. pub branch: String, /// Where the worktree lands, relative to `cfg.workdir`. May name a nested /// location (`Libraries/docengine`), because a path dep resolves to wherever /// the dev tree keeps the crate and Sando has to match that shape. Every /// component must be a plain name — no leading slash, no `..` — so the /// checkout stays under the workdir. pub checkout_dir: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RepoConfig { pub bare_path: String, pub branch: String, /// Optional canonical git remote. When set, `/rebuild` fetches the deploy /// branch from here into the bare repo before worktree-ing the target sha, /// so a freshly-pushed commit is resolvable without anyone pushing to the /// bare repo directly (pull-based deploys). When unset, Sando relies on the /// bare repo already containing the sha (push-based / hook-driven). #[serde(default)] pub upstream: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BackupConfig { pub source: String, pub local_path: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Tier { pub name: TierId, #[serde(default)] pub provisioned: bool, pub gates: Vec, #[serde(default)] pub canary: CanaryPolicy, #[serde(default, rename = "node")] pub nodes: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Node { pub name: NodeId, pub ssh_target: String, pub release_root: String, /// systemd unit name to reload-or-restart after the symlink swap. /// Defaults to "makenotwork.service" because that's MNW's prod unit. #[serde(default = "default_service_name")] pub service_name: String, /// Opt-in config-drift guard. When set to the node's env-file path (e.g. /// `/etc/mnw/makenotwork.env`), the deploy sources that file and runs the /// freshly-rsynced binary in `MNW_CHECK_CONFIG=1` mode BEFORE the symlink /// swap. A required var missing on this node (a var added upstream but never /// added to the node's env — how testnot crash-looped on CDN_BASE_URL) then /// fails the promote with the running service still intact, instead of after /// the swap+restart. Unset (default) skips the check, so an existing /// `sando.toml` keeps working and it never runs against a binary too old to /// support the mode; enable it once a check-capable version is deployed. #[serde(default)] pub config_check_env_file: Option, /// Capability grant for this node's executor (see `ops_exec`). Defaults to /// the current behavior of every Sando node — actuate deploy+restart, /// observe health — so an existing `sando.toml` keeps working unedited. #[serde(default = "default_actuate")] pub actuate: Vec, #[serde(default = "default_observe")] pub observe: Vec, /// Optional HTTP readiness URL the `node_health` gate curls on the node (over /// its executor) after `systemctl is-active`. Typically a loopback address /// the service binds, e.g. `http://127.0.0.1:8080/health`. When unset, the /// gate proves the unit is active post-restart but does not HTTP-probe; set /// it for a full readiness check. Kept optional so an existing `sando.toml` /// needs no edit. #[serde(default)] pub health_url: Option, /// Companion services this node installs from the release bundle after the /// server is swapped and restarted. Each entry names a `[[companion]]` the /// daemon builds (see `Config::companions`) and says where its binary lands /// and which unit to restart — so a contract-coupled service (mnw-cli) ships /// in the same promote as the server instead of drifting. Empty (default) = /// server-only node, so an existing `sando.toml` keeps working unedited. #[serde(default, rename = "companion")] pub companions: Vec, } /// Where a node installs a built companion binary and which unit to bounce. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct NodeCompanion { /// Must match a `Config::companions[].name` — the bundle subdir to read from. pub name: String, /// Absolute path the companion binary is installed to on the node /// (the unit's `ExecStart`), e.g. `/opt/mnw-cli/mnw-cli`. pub install_path: String, /// systemd unit restarted after the binary is installed, e.g. /// `mnw-cli.service`. pub service_name: String, } fn default_service_name() -> String { "makenotwork.service".into() } /// The capability set every pre-existing Sando node implicitly had: it deploys /// and restarts, and is health-observed. Keeping these as the defaults is what /// lets `sando.toml` stay unchanged through the executor refactor. pub fn default_actuate() -> Vec { vec!["deploy".into(), "restart".into()] } pub fn default_observe() -> Vec { vec!["health".into()] } #[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)] #[serde(rename_all = "snake_case")] pub enum CanaryPolicy { #[default] Sequential, Parallel, } impl CanaryPolicy { pub fn as_str(self) -> &'static str { match self { CanaryPolicy::Sequential => "sequential", CanaryPolicy::Parallel => "parallel", } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum Gate { CargoTest, HardeningTest, Clippy, Fmt, CargoAudit, CargoDeny, MigrationDryRun, CodeSmoke, BootSmoke, NodeHealth, BurnIn { hours: u32 }, ManualConfirm, } impl Gate { /// The discriminant — the identifier we use in events, schema columns, /// and the TUI. Gate parameters (e.g. `BurnIn.hours`) stay with `Gate` /// and are not carried into `gate_runs` history. pub fn kind(&self) -> GateKind { match self { Gate::CargoTest => GateKind::CargoTest, Gate::HardeningTest => GateKind::HardeningTest, Gate::Clippy => GateKind::Clippy, Gate::Fmt => GateKind::Fmt, Gate::CargoAudit => GateKind::CargoAudit, Gate::CargoDeny => GateKind::CargoDeny, Gate::MigrationDryRun => GateKind::MigrationDryRun, Gate::CodeSmoke => GateKind::CodeSmoke, Gate::BootSmoke => GateKind::BootSmoke, Gate::NodeHealth => GateKind::NodeHealth, Gate::BurnIn { .. } => GateKind::BurnIn, Gate::ManualConfirm => GateKind::ManualConfirm, } } /// Gates that execute against a tier's freshly-deployed nodes, recording a /// `gate_runs` row, at the end of a successful promote to that tier — the /// evidence the *next* promote checks. Only `node_health`: it probes the /// nodes the deploy just shipped to. `boot_smoke` is NOT post-deploy — it is /// a build-time gate that boots the staged artifact on the build host and /// proves nothing about a deployed node (the Run-2 SERIOUS-3 blind spot: /// boot_smoke used to re-run locally at promote time and the next promote /// trusted a binary that never touched the node). pub fn runs_post_deploy(&self) -> bool { matches!(self, Gate::NodeHealth) } /// Gates evaluated at promote time against the deployed nodes or the /// operator, as opposed to build-time gates (`cargo_test`, /// `migration_dry_run`, `code_smoke`, `boot_smoke`) that run once on the build host and /// prove nothing about a promote. A serving tier whose gate list contains /// none of these would wave every promote straight through; `Topology /// ::validate` refuses to load such a config (the structural form of CF1's /// fail-closed default). `boot_smoke` no longer counts here — a serving tier /// must declare a real node-level / operator gate, not a host smoke test. pub fn guards_promotion(&self) -> bool { matches!( self, Gate::NodeHealth | Gate::BurnIn { .. } | Gate::ManualConfirm ) } } impl Topology { pub fn load(path: &Path) -> Result { let raw = std::fs::read_to_string(path) .with_context(|| format!("reading topology at {}", path.display()))?; let topo: Topology = toml::from_str(&raw)?; topo.validate()?; Ok(topo) } /// Defense-in-depth for the build-host guard: a host that serves a /// provisioned tier must never be designated the builder. The runtime /// hostname check in `build::run` is the real guard; this catches a /// misconfiguration (build_host pointed at a prod node's name/ssh_target) at /// startup, before the daemon ever accepts a build. Called from `main` once /// config + topology are both loaded. pub fn ensure_build_host_not_serving(&self, build_host: &str) -> Result<()> { for t in &self.tiers { if !t.provisioned || t.name.as_str() == "host" { continue; } for n in &t.nodes { if n.name.as_str() == build_host || n.ssh_target == build_host { anyhow::bail!( "build_host {build_host:?} is also node {} (ssh {}) in serving tier {} — \ the builder must not be a prod/serving node", n.name, n.ssh_target, t.name ); } } } Ok(()) } #[cfg(test)] pub(crate) fn validate_for_test(&self) -> Result<()> { self.validate() } fn validate(&self) -> Result<()> { anyhow::ensure!( !self.tiers.is_empty(), "topology must declare at least one tier" ); for t in &self.tiers { // The `host` tier is the build tier (cargo_test / migration_dry_run / // code_smoke / boot_smoke run once on the host); every other tier serves an // artifact to nodes, so it is exempted from the node and // promotion-gate checks the same way. let is_build_tier = t.name.as_str() == "host"; if t.provisioned && t.nodes.is_empty() && !is_build_tier { anyhow::bail!("tier {} is provisioned but has no nodes", t.name); } // Fail closed by default: a provisioned serving tier must declare at // least one gate that actually guards a promote. Without this, an // empty (or build-time-only) gate list waves every promote through // because `unsatisfied_gates` finds nothing to check (CF1 root cause). if t.provisioned && !is_build_tier && !t.gates.iter().any(Gate::guards_promotion) { anyhow::bail!( "tier {} is provisioned to serve but declares no promotion gate \ (need at least one of node_health / burn_in / manual_confirm)", t.name ); } } let mut seen_dirs: Vec> = Vec::new(); for aux in &self.aux_repos { anyhow::ensure!( !aux.name.is_empty() && !aux.bare_path.is_empty() && !aux.branch.is_empty(), "aux_repo entry has an empty name/bare_path/branch" ); // `checkout_dir` becomes a `workdir.join(..)`. Nesting is allowed — // docengine lives at `Libraries/docengine` in the dev tree and the // path dep resolves to that shape — but every component must be a // plain name so an aux repo can never write outside the workdir. let dir = &aux.checkout_dir; let parts: Vec<&str> = dir.split('/').collect(); anyhow::ensure!( !dir.is_empty() && !dir.contains('\\') && parts .iter() .all(|c| !c.is_empty() && *c != "." && *c != ".."), "aux_repo {} has an unsafe checkout_dir {dir:?} (must be a relative path of \ plain components: no leading slash, empty segments, or dot-dot)", aux.name, ); // Two checkouts may not share a dir, and neither may sit inside the // other: `git worktree add` into a path under a live worktree buries // one checkout in the other's tree, and whichever builds second wins. for prior in &seen_dirs { let common = prior.len().min(parts.len()); anyhow::ensure!( prior[..common] != parts[..common], "two aux_repo entries share or nest checkout_dir {dir:?}; \ they would clobber each other" ); } seen_dirs.push(parts); } Ok(()) } } #[cfg(test)] mod tests { use super::*; /// A minimal topology with one serving tier whose gate block is `gates`. fn topo_with_serving_gates(provisioned: bool, gates: &str) -> Topology { let raw = format!( r#" [repo] bare_path = "/tmp/repo.git" branch = "main" [backup] source = "ssh://prod/dump.sql.gz" local_path = "/tmp/dump.sql.gz" [[tier]] name = "b" provisioned = {provisioned} gates = [{gates}] [[tier.node]] name = "prod-1" ssh_target = "prod-1" release_root = "/srv/mnw" "# ); toml::from_str(&raw).expect("parse test topology") } #[test] fn provisioned_serving_tier_with_no_gates_is_rejected() { let topo = topo_with_serving_gates(true, ""); let err = topo.validate_for_test().unwrap_err().to_string(); assert!(err.contains("no promotion gate"), "{err}"); } #[test] fn provisioned_serving_tier_with_only_build_gates_is_rejected() { // cargo_test / migration_dry_run are build-time and prove nothing about a // promote, so a serving tier carrying only them still fails closed. let topo = topo_with_serving_gates( true, r#"{ kind = "cargo_test" }, { kind = "migration_dry_run" }"#, ); let err = topo.validate_for_test().unwrap_err().to_string(); assert!(err.contains("no promotion gate"), "{err}"); } #[test] fn provisioned_serving_tier_with_a_promotion_gate_is_accepted() { let topo = topo_with_serving_gates(true, r#"{ kind = "node_health" }"#); assert!(topo.validate_for_test().is_ok()); } #[test] fn provisioned_serving_tier_with_only_boot_smoke_is_rejected() { // boot_smoke is a build-host gate now; it proves nothing about a node, so // a serving tier carrying only boot_smoke must fail closed exactly like an // empty gate list (Run-2 SERIOUS-3 structural close). let topo = topo_with_serving_gates(true, r#"{ kind = "boot_smoke" }"#); let err = topo.validate_for_test().unwrap_err().to_string(); assert!(err.contains("no promotion gate"), "{err}"); } #[test] fn unprovisioned_tier_with_empty_gates_is_skipped() { // A declared-but-not-yet-provisioned tier (e.g. tier c) carries no // promote authority, so the gate requirement does not apply yet. let topo = topo_with_serving_gates(false, ""); assert!(topo.validate_for_test().is_ok()); } #[test] fn build_host_matching_a_serving_node_is_rejected() { // prod-1 is a node in the provisioned serving tier built above; naming it // as the builder must fail closed. let topo = topo_with_serving_gates(true, r#"{ kind = "node_health" }"#); let err = topo .ensure_build_host_not_serving("prod-1") .unwrap_err() .to_string(); assert!(err.contains("must not be a prod/serving node"), "{err}"); } #[test] fn build_host_distinct_from_serving_nodes_is_accepted() { let topo = topo_with_serving_gates(true, r#"{ kind = "node_health" }"#); assert!(topo.ensure_build_host_not_serving("fw13").is_ok()); } #[test] fn node_companions_default_empty_and_parse_when_present() { // A node without [[tier.node.companion]] is server-only. let plain = topo_with_serving_gates(true, r#"{ kind = "node_health" }"#); assert!(plain.tiers[0].nodes[0].companions.is_empty()); // A node that declares a companion carries its install target + unit. let raw = r#" [repo] bare_path = "/tmp/repo.git" branch = "main" [backup] source = "s" local_path = "/tmp/d" [[tier]] name = "b" provisioned = true gates = [{ kind = "node_health" }] [[tier.node]] name = "prod-1" ssh_target = "makenotwork@alpha-west-1" release_root = "/opt/mnw" [[tier.node.companion]] name = "mnw-cli" install_path = "/opt/mnw-cli/mnw-cli" service_name = "mnw-cli.service" "#; let topo: Topology = toml::from_str(raw).expect("parse companion topology"); let c = &topo.tiers[0].nodes[0].companions; assert_eq!(c.len(), 1); assert_eq!(c[0].name, "mnw-cli"); assert_eq!(c[0].install_path, "/opt/mnw-cli/mnw-cli"); assert_eq!(c[0].service_name, "mnw-cli.service"); } fn topo_with_aux(aux_block: &str) -> Result { let raw = format!( r#" [repo] bare_path = "/tmp/repo.git" branch = "main" [backup] source = "s" local_path = "/tmp/d" [[tier]] name = "b" provisioned = true gates = [{{ kind = "node_health" }}] [[tier.node]] name = "prod-1" ssh_target = "prod-1" release_root = "/srv/mnw" {aux_block} "# ); let topo: Topology = toml::from_str(&raw)?; topo.validate_for_test()?; Ok(topo) } #[test] fn aux_repos_default_empty() { let topo = topo_with_aux("").expect("no aux_repo block is fine"); assert!(topo.aux_repos.is_empty()); } #[test] fn aux_repo_parses_all_fields() { let topo = topo_with_aux( r#" [[aux_repo]] name = "synckit" bare_path = "/srv/sando/synckit.git" upstream = "git@ssh.makenot.work:max/synckit.git" branch = "main" checkout_dir = "synckit""#, ) .expect("valid aux_repo parses"); assert_eq!(topo.aux_repos.len(), 1); let a = &topo.aux_repos[0]; assert_eq!(a.name, "synckit"); assert_eq!(a.bare_path, "/srv/sando/synckit.git"); assert_eq!(a.upstream, "git@ssh.makenot.work:max/synckit.git"); assert_eq!(a.branch, "main"); assert_eq!(a.checkout_dir, "synckit"); } #[test] fn aux_repo_with_nested_checkout_dir_is_accepted() { let topo = topo_with_aux( r#" [[aux_repo]] name = "docengine" bare_path = "/srv/sando/docengine.git" upstream = "git@ssh.makenot.work:max/docengine.git" branch = "main" checkout_dir = "Libraries/docengine""#, ) .expect("a nested checkout_dir is a valid location"); assert_eq!(topo.aux_repos[0].checkout_dir, "Libraries/docengine"); } #[test] fn aux_repo_with_traversing_checkout_dir_is_rejected() { for bad in [ "../escape", "a/../../escape", "a/./b", "a//b", "/abs", "a/", "..", ".", ] { let err = topo_with_aux(&format!( r#" [[aux_repo]] name = "x" bare_path = "/srv/sando/x.git" upstream = "u" branch = "main" checkout_dir = "{bad}""#, )) .unwrap_err() .to_string(); assert!(err.contains("unsafe checkout_dir"), "for {bad:?}: {err}"); } } #[test] fn aux_repos_sharing_a_checkout_dir_are_rejected() { let err = topo_with_aux( r#" [[aux_repo]] name = "one" bare_path = "/srv/sando/one.git" upstream = "u" branch = "main" checkout_dir = "shared" [[aux_repo]] name = "two" bare_path = "/srv/sando/two.git" upstream = "u" branch = "main" checkout_dir = "shared""#, ) .unwrap_err() .to_string(); assert!(err.contains("share or nest checkout_dir"), "{err}"); } #[test] fn aux_repo_nested_inside_another_checkout_dir_is_rejected() { let err = topo_with_aux( r#" [[aux_repo]] name = "outer" bare_path = "/srv/sando/outer.git" upstream = "u" branch = "main" checkout_dir = "Libraries" [[aux_repo]] name = "inner" bare_path = "/srv/sando/inner.git" upstream = "u" branch = "main" checkout_dir = "Libraries/docengine""#, ) .unwrap_err() .to_string(); assert!(err.contains("share or nest checkout_dir"), "{err}"); } #[test] fn real_sando_toml_loads_clean() { // The shipped topology must satisfy the invariant — guards against a // regression that would lock sandod out of its own config. let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../sando.toml"); Topology::load(&path).expect("shipped sando.toml must validate"); } fn shipped() -> Topology { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../sando.toml"); Topology::load(&path).expect("shipped sando.toml must validate") } #[test] fn shipping_to_the_last_provisioned_tier_needs_an_operator_signoff() { // A tier's gates guard promotion *out* of it, which is the subtlety that // made manual_confirm inert: it sat on tier b, guarding b -> c, and c is // not provisioned. So the ship to production was cleared by node_health // + burn_in alone — and `hotfix: true` skips burn_in. // // The gate that matters therefore belongs on the PREDECESSOR of the last // provisioned tier. Asserted structurally so re-provisioning tiers cannot // silently strand the sign-off again. let topo = shipped(); let last = topo .tiers .iter() .rposition(|t| t.provisioned) .expect("some tier must be provisioned"); assert!(last > 0, "the production tier cannot be the first tier"); let guard = &topo.tiers[last - 1]; assert!( guard.gates.iter().any(|g| matches!(g, Gate::ManualConfirm)), "tier {} guards promotion into the last provisioned tier ({}), so it must require an operator sign-off; its gates are {:?}", guard.name, topo.tiers[last].name, guard .gates .iter() .map(|g| g.kind().as_str()) .collect::>(), ); } #[test] fn every_serving_node_has_a_readiness_probe() { // Without health_url, node_health degrades to `systemctl is-active`, // which a crash-looping binary satisfies between restarts — exactly what // the 0.10.14 CDN_BASE_URL crash-loop did on prod-1. let topo = shipped(); for tier in topo.tiers.iter().filter(|t| t.provisioned) { for node in &tier.nodes { assert!( node.health_url.is_some(), "node {} on tier {} has no health_url, so node_health proves only that systemd thinks the unit is running", node.name, tier.name, ); } } } }