Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/monetize

crates/monetize-shop-pairing/src/lib.rs

//! **The shop pairs a sold estate itself** (no operator machine in a sale, the owner,
//! 2026-10-08: "DWARFS MUST NOT BE INVOLVED!").
//!
//! The shop (monetize-server) links the installer's protocol (nordisk-pairing) HERE, in a crate
//! of its own, which monetize's workspace never does — so ANY build that runs the shop can
//! register it into monetize's open seam (`monetize_server::registry::Linked::installer`,
//! `[estate_orders] pairing = "shop-pairing"`): the solo monetize box (monetize-admin, G6)
//! and gunnar's front alike (G11, 2026-10-10: it lived inside gunnar-front, so a shop that
//! was not gunnar's front could not pair what it sold). It names NO product: what it speaks
//! for an estate is the contract the estate's product declares in its own facts
//! ([`ProductContract::of`], v2.0 P3) — its variants, box kind, feed keys and sale proof —
//! and the feed keys every product's boxes share are [`contract`]'s.
//!
//! * [`ShopPairing::mint`] — at the payment: the order's installer material (its own CA, the
//!   operator's certificate, the bootstrap certificate the boxes join with ONCE, the link
//!   keys) and each machine kind's SEED, which the lay hands that machine as its UpCloud
//!   `user_data` (the box reads it from the metadata: gunnar-server `pairing::seed`). All of
//!   it is sealed in the shop's custody and forgotten at the hand-off.
//! * [`ShopPairing::install`] — after the lay: the plan (the three laid machines), the feed
//!   (the operator — the buyer's account — the first-login invite's hash, the estate record,
//!   the sold front's keys), and `nordisk_pairing::installer::run` against the laid addresses
//!   over each box's WireGuard link, in this process. Its verdict is the job's.
//!
//! * [`ShopPairing::sale_check`] (S4) — before the capture: the sold front's PUBLIC
//!   `https://<host>` proves the product's own sale proof ([`sale_proof`]), trusting the
//!   certificate the shop minted for it.
//!
//! * [`bundle`] (F4) — after a PASSed pairing: the installer material the ESTATE keeps (the
//!   material, the door's ledger, the plan), handed back into the custody
//!   ([`monetize_server::custody::handoff::INSTALLER_MATERIAL`]); the sold front TAKES it
//!   (`SoldEstate.TakeMaterial`) into its primary's sealed slot, and is from then on its own
//!   installer: renewals, upgrades, recharges (gunnar-front `recharge`).
//!
//! The twin's lag and load are NOT read here: the estate reports them on the pull channel and
//! the shop reads its reports (monetize-server `estate_order::twin::ReportedTwinHealth`, G12);
//! monetize never dials an estate's own channels — no health reader is minted, and the bundle
//! is pulled, never PUT into the front's door. The one look it takes is the buyer's: the sale
//! check reads the front's PUBLIC pages, as anyone on the web reaches them.
//!
//! What a SOLD front is fed (the same keys the kit feeds a sold front, estate-box Y4): the
//! shop's static part `[estate_orders.sale_feed]` (gunnar free, …; `{{COMPANY}}`, `{{HOST}}`,
//! `{{APEX}}`, `{{SHOP_DOOR}}`, `{{MONETIZE_PUBKEY}}` filled per order), and per order the
//! console's break-glass bearer and the estate's client key (from the custody's hand-off), the
//! console's name and seller, its web hosts, and the ONE monetize's pull channel: its door
//! ([`contract::FEED_FLEET`]), the estate the boxes pull as ([`contract::FEED_FLEET_INSTANCE`])
//! and the ONE's key ([`contract::FEED_MONETIZE_PUBKEY`]). Never a shop credential.
//!
//! **G16 (ONE monetize, owner 2026-10-10):** a sold front runs NO monetize: it is fed no
//! `monetize.toml` (a sale feed naming one is refused), no `[clouds.shop]`, no backup key, no
//! monetize control host. Its tenants live in the ONE ledger (`gunnar/@<company>/<ns>`) and
//! its boxes pull their entitlements and orders over the Fleet channel.
//!
//! The ONE monetize's `SoldEstate` door the sold front calls IN to (grow, recharge, upgrade,
//! take the material) is fed on its own, [`contract::FEED_SHOP_DOOR`] (F4).

/// **The feed keys every product's sold estate is fed** — the shop's contract with the boxes, the
/// same for every product. What differs per product (its variants, its console bearer's key, its
/// free switch, its sale proof) is the product's own, in its facts ([`ProductContract::of`]).
pub mod contract {
    /// **The shop's door, fed to a sold front alone** (F4; gunnar-front
    /// `recharge::FEED_SHOP_DOOR`): TOML `door`, `company`, `shop_pubkey`, `client_key_secret`,
    /// `product` — where and as whom the estate calls IN, never a fragment of a monetize. With
    /// `product` (P3-FLEET, plan §8) the front's calls ride `Fleet.Ask` as that product's front;
    /// a front fed before the fold has none and its product's code names it (monetize-estate-side
    /// `ShopDoor::or_over_fleet`).
    pub const FEED_SHOP_DOOR: &str = "shop_door.toml";
    /// The welcome README the primary makes the buyer's first repository from (the product's
    /// own [`crate::ProductContract::welcome`]) and that repository's name (`WELCOME_REPO`).
    pub const FEED_OPERATOR_WELCOME: &str = "operator_welcome_readme";
    pub const WELCOME_REPO: &str = "welcome";
    /// The fed fragment of the front's monetize.toml (refused: a sold estate runs no monetize).
    pub const FEED_MONETIZE_TOML: &str = "monetize.toml";
    /// **The pull channel a sold estate's boxes report to** (G16): the ONE monetize's door.
    pub const FEED_FLEET: &str = "fleet";
    /// **The sold site's own pay page** (UW-6): a `{tenant}` template every refusal and Grace
    /// line ends in, replacing the medium's.
    pub const FEED_BILLING_URL: &str = "refusal_link";
    /// The estate the boxes pull as.
    pub const FEED_FLEET_INSTANCE: &str = "fleet_instance";
    /// The ONE monetize's verifying key every order and fact is checked under.
    pub const FEED_MONETIZE_PUBKEY: &str = "monetize_pubkey";
    /// The estate record's feed keys (`Record::to_feed`).
    pub const FEED_RECORD: &str = "estate.record";
    pub const RECORD_SCHEMA: &str = "1";
    pub const FEED_VARIANT: &str = "estate.variant";
    pub const FEED_VERSIONS: &str = "estate.versions";
    pub const FEED_BOXES: &str = "estate.boxes";
    pub const FEED_BOX_PREFIX: &str = "estate.box.";
    /// A record box's fields, in the record's order.
    pub const BOX_FIELDS: [&str; 10] = ["laid_as", "hostname", "title", "public", "utility", "size", "vcpu", "ram_mb", "system_disk_gb", "data"];
    /// **The site's own bearer at the ONE box**, a sealed secret slot of the front.
    pub const FEED_MONETIZE_BEARER: &str = "secret.monetize_bearer";
    /// The product the site's console sells.
    pub const FEED_CONSOLE_PRODUCT: &str = "console_product";
    /// **The site's public face** (TASKS-12; gunnar-front `console::FEED_PUBLIC_SITE`,
    /// holger-estate-front `console::PUBLIC_SITE_FEED`): `on` only for a site whose
    /// declaration says `public_site` (gunnar.rs, holger.rs).
    pub const FEED_PUBLIC_SITE: &str = "console_public_site";
    /// **How far the front's CLI hole reaches** (RA1-14; gunnar-front `web::hole::FEED_CLI_HOLE`):
    /// [`CLI_HOLE_PUBLIC`] only for a site whose declaration says `cli_hole_public` (gunnar.rs);
    /// unfed, the front keeps it to the estate's own network.
    pub const FEED_CLI_HOLE: &str = "front_cli_hole";
    /// [`FEED_CLI_HOLE`]'s one fed value.
    pub const CLI_HOLE_PUBLIC: &str = "public";
    /// **The repositories of a site's estate that are public** (NIGHT-PUBREPO; holger
    /// `server_lib::posture::PUBLIC_REPOSITORIES_FEED`): the names, comma-separated, fed to the
    /// main and the twin only for a site whose declaration says `public_repositories` (holger.rs:
    /// `crates,npm`); every other estate is fed nothing of it, and its boxes keep all private.
    pub const FEED_PUBLIC_REPOSITORIES: &str = "public_repositories";
}

/// **One product's contract** — what this installer speaks for an estate of the product, read
/// off the product's own facts ([`ProductContract::of`]; v2.0 P3, A28 H11/H12). The shop holds
/// no product's contract of its own: a product that does not declare one is not paired.
#[derive(Clone, Debug, PartialEq)]
pub struct ProductContract {
    pub product: String,
    /// The variant a sold estate is recorded as.
    pub sold_variant: String,
    /// The variant an operator site the ONE box laid itself is recorded as.
    pub site_variant: String,
    /// The pairing kind the main and the twin are seeded and planned as.
    pub box_kind: Kind,
    /// The seed file kinds (`seed.<kind>.toml`) of the front and of the product's boxes: the
    /// medium kinds the facts give the front and main roles (the lay hands each machine the
    /// seed of its medium kind: monetize-server `estate_order::give_seeds_as`).
    pub front_seed: String,
    pub box_seed: String,
    /// The feed key that makes the sold front's own product free.
    pub free_feed: String,
    /// **The welcome README** (with `{host}`, `{account}`, `{repo}`) the primary makes
    /// `<account>/welcome` from; `None`: the product makes none, and none is fed.
    pub welcome: Option<String>,
    /// **The pay page its front is fed** (`refusal_link`).
    pub billing: Billing,
    /// **What proves a sale** of it: the product's own routes ([`sale_proof::prove`]).
    pub proof: SaleProof,
    /// **The feed key the sold front reads its console bearer from** (lane L18).
    pub console_token_feed: String,
    /// **Its main ships an OFF-SITE copy** (lane O1): the order's material carries the estate's
    /// off-site key pair, and the main and the twin are fed the off-site keys the shop holds for
    /// the estate ([`offsite_feed_for`]).
    pub offsite: bool,
    /// **Its boxes serve the console's login themselves** (lane D7): the main and the twin are
    /// fed the console's bearer the front holds ([`box_feed_for`]).
    pub boxes_hold_console_token: bool,
    /// **The feed key its boxes bind their passkey plane to** (lane F12): fed the estate's host.
    /// `None`: the product's boxes hold no passkeys.
    pub passkey_rp_feed: Option<String>,
    /// **The served prefixes its front routes to its primary's repository** (HOL-REPO-NAME: the
    /// guest's `repo_names` rider, Holger's `["repo."]`): each name of the order under one is fed
    /// as `repo_hosts` (edda `estate-front::route`), and so served and certified.
    pub repo_prefixes: Vec<String>,
    /// **The served prefixes its front serves on :443 as a redirect only** (HOL-REPO-NAME: the
    /// guest's `redirect_names` rider, Gunnar's `["git."]`, kit parity h-front-sans): on the
    /// certificate, fed as `web_callback_only`. `None`: the guest names no such rider (one built
    /// before it), and a name under `git.` is left out of `web_hosts`, the rule before it.
    pub redirect_prefixes: Option<Vec<String>>,
}

pub use monetize_server::facts::Billing;
use monetize_server::facts::{Facts, SaleProof};

impl ProductContract {
    /// **The contract `facts` declare**, or the refusal that names the first thing missing: a
    /// product is paired by what it says of itself, never by a contract the shop guesses.
    pub fn of(facts: &Facts) -> Result<ProductContract, String> {
        let product = facts.kind.trim();
        if product.is_empty() {
            return Err("REFUSED [contract-no-kind] the product's facts name no kind: the shop's pairing pairs no estate of an unnamed product".into());
        }
        let need = |what: &str, v: &Option<String>| -> Result<String, String> {
            v.as_deref().map(str::trim).filter(|v| !v.is_empty()).map(str::to_owned).ok_or_else(|| format!("REFUSED [contract-{}] the {product} product's facts name no `{what}`: the shop's pairing does not guess a product's contract", what.replace('_', "-")))
        };
        let box_kind = Kind::named(&need("box_kind", &facts.box_kind)?).map_err(|e| format!("REFUSED [contract-box-kind] the {product} product's box kind: {e}"))?;
        let welcome = match facts.welcome {
            Some(true) => Some(need("welcome_readme", &facts.welcome_readme)?),
            _ => None,
        };
        let front_role = if facts.front_role.trim().is_empty() { "front" } else { facts.front_role.trim() };
        let medium = |role: &str| facts.medium_of.get(role).cloned().unwrap_or_else(|| facts.other_medium.clone());
        let (front_seed, box_seed) = (medium(front_role), medium("main"));
        if front_seed.trim().is_empty() || box_seed.trim().is_empty() {
            return Err(format!("REFUSED [contract-medium] the {product} product's facts name no medium for its front or its boxes: the shop's pairing seeds no machine it cannot name"));
        }
        Ok(ProductContract {
            product: product.to_string(),
            sold_variant: need("sold_variant", &facts.sold_variant)?,
            site_variant: need("site_variant", &facts.site_variant)?,
            box_kind,
            front_seed,
            box_seed,
            free_feed: need("free_feed", &facts.free_feed)?,
            welcome,
            billing: facts.billing.ok_or_else(|| format!("REFUSED [contract-billing] the {product} product's facts do not say where its pay page is (`billing`)"))?,
            proof: facts.proof.clone().ok_or_else(|| format!("REFUSED [contract-proof] the {product} product's facts carry no sale proof: no sale of it can be proven, so none is captured"))?,
            console_token_feed: need("console_token_feed", &facts.console_token_feed)?,
            offsite: facts.offsite.unwrap_or(false),
            boxes_hold_console_token: facts.boxes_hold_console_token.unwrap_or(false),
            passkey_rp_feed: facts.passkey_rp_feed.as_deref().map(str::trim).filter(|k| !k.is_empty()).map(str::to_owned),
            repo_prefixes: guest_lifecycle::prefixes_named(guest_lifecycle::RIDER_REPO_NAMES, &facts.default_shape).unwrap_or_default(),
            redirect_prefixes: guest_lifecycle::prefixes_named(guest_lifecycle::RIDER_REDIRECT_NAMES, &facts.default_shape),
        })
    }
}

/// **The sale check's transport** (S4): the sold front over its public HTTPS.
pub mod sale_check;
/// **The sale check from data** (A28 H12): the product's own `SaleProof`, run over the sold front.
pub mod sale_proof;

use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

use monetize_server::estate_order::{guest_lifecycle, InstallRequest, InstallVerdict, Installer, LaidOrder, WgPeer};
use nordisk_pairing::installer::{Material, Plan, PlanVm};
use nordisk_pairing::mtls::InstallerCa;
use nordisk_pairing::seed::{Front, Kind, LinkSeed, Seed, TunnelKind};

/// The name this installer is linked under (`[estate_orders] pairing`).
pub const NAME: &str = "shop-pairing";
/// How long the order's installer CA and its certificates live.
pub const MATERIAL_VALID: Duration = Duration::from_secs(180 * 24 * 3600);
/// The elected primary's offer the front waits for before anything closes.
pub const TICKET_OFFER: &str = "ticket_pubkey";
/// **Auto-repair** (owner 2026-10-12: a dead main is rebuilt from the twin by autorepair): the
/// word both fronts and Gunnar's boxes read (nordisk-pairing `autofill::FEED_REPAIR_AUTO`). ON
/// (`true`) for every shop-laid estate unless the site's `[estate_orders.sale_feed]` turns it off.
pub const REPAIR_AUTO: &str = "repair_auto";
/// The shared feed keys (the kit's contract: `installer::feed`, `operator_invite_feed`).
pub const FEED_ADMIN_PUBKEY: &str = "admin_pubkey";
pub const FEED_OPERATOR: &str = "operator_name";
pub const FEED_OPERATOR_INVITE: &str = "operator_invite_sha256";
pub const FEED_OPERATOR_INVITE_TTL: &str = "operator_invite_ttl_secs";
/// The operator key's files in the order's material (the primary's first identity; nobody
/// holds it after the hand-off).
pub const OPERATOR_KEY: &str = "operator.key";
pub const OPERATOR_PUB: &str = "operator.pub";

/// The installer monetize builds by name.
pub fn factory() -> monetize_server::registry::InstallerFactory {
    monetize_server::registry::InstallerFactory { name: NAME, build }
}

fn build(b: &monetize_server::registry::InstallerBuild<'_>) -> Result<Arc<dyn Installer>, String> {
    // S5: an earlier sale's secret offers (a sold front's web TLS key) off this shop's disk.
    let swept = sweep_secret_offers(&b.data_dir.join("estate-orders"));
    if swept > 0 {
        eprintln!("monetize-server: shop pairing: {swept} sold estate(s)' secret offers removed from this shop's disk");
    }
    let sale_feed = b.orders.sale_feed.clone();
    if b.orders.bench_fleet_late_s > 0 {
        eprintln!("monetize-server: shop pairing: BENCH fleet-feed-late — every box's first feed lacks {} for {} s", FLEET_LATE_KEYS.join(", "), b.orders.bench_fleet_late_s);
    }
    if b.orders.installer_link_psk {
        eprintln!("monetize-server: shop pairing: installer_link_psk = true — the installer's link of a new order carries a pre-shared key (nordisk-pairing >= 0.5.29 media only)");
    }
    Ok(Arc::new(ShopPairing { sale_feed, budget_s: b.orders.installer_timeout_secs.max(600), fleet_late_s: b.orders.bench_fleet_late_s, installer_link_psk: b.orders.installer_link_psk }))
}

/// **The pull channel's keys the bench's `fleet-feed-late` holds back** (`[estate_orders]
/// bench_fleet_late_s`): the ONE's door, the estate the boxes pull as, and the seam they dial.
pub const FLEET_LATE_KEYS: [&str; 3] = [contract::FEED_FLEET, contract::FEED_FLEET_INSTANCE, "fleet_at"];

/// Pure: **the bench's `fleet-feed-late`** on a plan — the shared feed names the keys every
/// VM's first feed is without, and for how long (nordisk-pairing `installer.late_feed`).
pub fn fleet_late(plan: &mut Plan, secs: u64) {
    if secs == 0 {
        return;
    }
    plan.feed.insert(nordisk_pairing::installer::LATE_FEED.to_string(), FLEET_LATE_KEYS.join(","));
    plan.feed.insert(nordisk_pairing::installer::LATE_FEED_S.to_string(), secs.to_string());
}

/// **Every link of a laid estate gets its own WireGuard pre-shared key** (lane WG-PSK): one per
/// box, minted afresh for this lay ([`nordisk_pairing::installer::mint_wg_psk`], the OS
/// generator), fed to the box and to the front ([`Plan::with_wg_psks`]). Never logged.
pub fn with_fresh_wg_psks(plan: Plan) -> Result<Plan, String> {
    let psks = plan.vms.iter().filter(|v| v.kind != Kind::Front).map(|v| Ok((v.name.clone(), nordisk_pairing::installer::mint_wg_psk()?))).collect::<Result<BTreeMap<String, String>, String>>()?;
    plan.with_wg_psks(&psks)
}

pub struct ShopPairing {
    /// `[estate_orders.sale_feed]`: the sold front's static keys, with placeholders.
    pub sale_feed: BTreeMap<String, String>,
    pub budget_s: u64,
    /// `[estate_orders] bench_fleet_late_s` ([`fleet_late`]): 0 everywhere but a bench.
    pub fleet_late_s: u64,
    /// `[estate_orders] installer_link_psk` ([`mint_material_with`]): the installer's link of a
    /// new order carries a pre-shared key.
    pub installer_link_psk: bool,
}

/// **The order's material and seeds**, minted fresh for `c`'s estate: the files the custody
/// seals, the product's boxes seeded as its kind, each seed under the file name the lay hands
/// the machine of that medium kind (`seed.<medium>.toml`, monetize-server
/// `estate_order::give_seeds_as`).
pub fn mint_material_for(c: &ProductContract, host: &str) -> Result<Vec<(String, String)>, String> {
    mint_material_with(c, host, true)
}

/// [`mint_material_for`], the installer link's pre-shared key minted (`link_psk`, lane
/// WG-PSK-3: one per order, 32 bytes from the OS generator, in every seed's `[installer_link]`
/// and in the link file the installer dials with) or not (a release whose media predate
/// nordisk-pairing 0.5.29).
pub fn mint_material_with(c: &ProductContract, host: &str, link_psk: bool) -> Result<Vec<(String, String)>, String> {
    use nordisk_pairing::installer::{CA_CERT, CA_KEY, INSTALLER_CERT, INSTALLER_KEY, LINK_KEYS};
    let psk = if link_psk { Some(nordisk_pairing::installer::mint_wg_psk()?) } else { None };
    let ca = InstallerCa::mint(host, MATERIAL_VALID).map_err(|e| e.to_string())?;
    let me = ca.issue_installer(MATERIAL_VALID).map_err(|e| e.to_string())?;
    let boot = ca.issue_bootstrap(MATERIAL_VALID).map_err(|e| e.to_string())?;
    let (installer_private, installer_public) = wg_appliance_core::keys::generate_keypair_b64();
    let (vm_private, vm_public) = wg_appliance_core::keys::generate_keypair_b64();
    let seed = |kind: Kind| -> Result<String, String> {
        let s = Seed {
            estate: host.to_string(),
            tunnel: TunnelKind::Wireguard,
            front: Front::default(),
            kind,
            installer_ca_pem: ca.cert_pem.clone(),
            bootstrap_cert_pem: boot.cert_pem.clone(),
            bootstrap_key_pem: boot.key_pem.clone(),
            peers_expected: 3,
            mullvad: None,
            tailscale: None,
            installer_link: Some(LinkSeed { installer_pubkey: installer_public.clone(), vm_private: vm_private.clone(), port: nordisk_pairing::installer_link::LINK_PORT, psk: psk.clone() }),
        };
        s.check().map_err(|e| e.to_string())?;
        s.render().map_err(|e| e.to_string())
    };
    let (op_pem, op_pub) = mint_operator_key()?;
    let mut files = vec![
        (CA_CERT.to_string(), ca.cert_pem.clone()),
        (CA_KEY.to_string(), ca.key_pem.clone()),
        (INSTALLER_CERT.to_string(), me.cert_pem),
        (INSTALLER_KEY.to_string(), me.key_pem),
        (LINK_KEYS.to_string(), Material::link_file_with_psk(&installer_private, &vm_public, psk.as_deref())),
        (OPERATOR_KEY.to_string(), op_pem),
        (OPERATOR_PUB.to_string(), op_pub),
        // The product's OWN front and boxes, by the medium kind its facts give each.
        (format!("{}{}.toml", monetize_server::estate_order::SEED_FILE_PREFIX, c.front_seed), seed(Kind::Front)?),
        (format!("{}{}.toml", monetize_server::estate_order::SEED_FILE_PREFIX, c.box_seed), seed(c.box_kind)?),
    ];
    if c.offsite {
        files.extend(mint_offsite_pair());
    }
    Ok(files)
}

/// **The estate's off-site key pair**, minted fresh (lane O1): X25519, base64 of 32 bytes each
/// (Holger's `offsite::key32`) — the private half as [`monetize_server::custody::OFFSITE_KEY_FILE`],
/// kept by the ONE box's custody past the hand-off, and the public half the main is fed as
/// `offsite_recipient`.
pub fn mint_offsite_pair() -> [(String, String); 2] {
    let (private, public) = wg_appliance_core::keys::generate_keypair_b64();
    [(monetize_server::custody::OFFSITE_KEY_FILE.to_string(), private), (monetize_server::custody::OFFSITE_PUB_FILE.to_string(), public)]
}

/// Pure: **what the boxes of `c`'s estate are fed of its off-site copy** (lane O1) — the shop's
/// off-site feed for the estate (`InstallRequest.offsite`: the store, the estate's prefix and
/// the recipient its custody keeps), the recipient the order's material carries when the feed
/// names none. Empty when `c` ships no copy, when the shop holds no store for the estate, or
/// when no recipient is known: the copy is then OFF and the box says so.
pub fn offsite_feed_for(c: &ProductContract, offsite: &BTreeMap<String, String>, material_recipient: Option<&str>) -> BTreeMap<String, String> {
    use monetize_server::estate_order::{FEED_OFFSITE_ENDPOINT, FEED_OFFSITE_RECIPIENT};
    if !c.offsite || offsite.get(FEED_OFFSITE_ENDPOINT).is_none_or(|v| v.trim().is_empty()) {
        return BTreeMap::new();
    }
    let mut f = offsite.clone();
    if f.get(FEED_OFFSITE_RECIPIENT).is_none_or(|v| v.trim().is_empty()) {
        match material_recipient.map(str::trim).filter(|r| !r.is_empty()) {
            Some(r) => {
                f.insert(FEED_OFFSITE_RECIPIENT.to_string(), r.to_string());
            }
            None => return BTreeMap::new(),
        }
    }
    f
}

/// Pure: **what the main and the twin are fed** beside their WireGuard keys: the relay
/// (S10) and the estate's off-site copy ([`offsite_feed_for`]).
pub fn box_feed(relay: &BTreeMap<String, String>, offsite: BTreeMap<String, String>) -> BTreeMap<String, String> {
    let mut f = relay.clone();
    f.extend(offsite);
    f
}

/// **What the main and the twin are fed, for `c`** (lane D7): [`box_feed`], and for a product
/// whose boxes serve the console's login themselves, the console's bearer the front is fed
/// (`c.console_token_feed`, the SAME on every VM, as Holger's kit fed it). Holger's shipped
/// declaration names that login (`StaticToken(subject: "console", token_file:
/// "/data/holger-console-token")`) and a box waits for the bearer before its doors start;
/// fed to the front alone, test3-holger-rs's main and twin never served. Gunnar's boxes hold
/// no console bearer (`console_admin_token` is the front's alone): [`box_feed`] unchanged.
pub fn box_feed_for(c: &ProductContract, relay: &BTreeMap<String, String>, offsite: BTreeMap<String, String>, front: &BTreeMap<String, String>) -> BTreeMap<String, String> {
    let mut f = box_feed(relay, offsite);
    // Main and twin follow the front's auto-repair word (Gunnar's boxes kick their own fill).
    if let Some(a) = front.get(REPAIR_AUTO) {
        f.insert(REPAIR_AUTO.to_string(), a.clone());
    }
    if c.boxes_hold_console_token {
        if let Some(t) = front.get(&c.console_token_feed).filter(|t| !t.trim().is_empty()) {
            f.insert(c.console_token_feed.clone(), t.clone());
        }
        // A16 (C19): the boxes serve the console's own pages, so they are told the site the
        // estate was bought at, as the front is (its sign-up page leads there).
        if let Some(p) = front.get("console_provider").filter(|p| !p.trim().is_empty()) {
            f.insert("console_provider".to_string(), p.clone());
        }
    }
    f
}

fn read(dir: &Path, name: &str) -> Result<String, String> {
    std::fs::read_to_string(dir.join(name)).map(|t| t.trim().to_string()).map_err(|e| format!("the custody's hand-off has no {name}: {e}"))
}

/// The lowercase hex SHA-256 of a secret's trimmed text (what gunnar keeps of an invite).
pub fn sha256_hex(secret: &str) -> String {
    use sha2::Digest as _;
    sha2::Sha256::digest(secret.trim().as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
}

/// Pure: **the shared feed** of `c`'s estate — the operator (the buyer's account) and its first
/// identity, the first-login invite's hash and lifetime, the estate record; the welcome and the
/// pay page only where the product has them.
pub fn shared_feed_for(c: &ProductContract, order: &LaidOrder, account: &str, admin_pubkey: &str, invite: &str) -> Result<BTreeMap<String, String>, String> {
    if account.trim().is_empty() {
        return Err("the order names no account: a sold estate is its buyer's".into());
    }
    let host = order.names.first().cloned().unwrap_or_else(|| format!("{}.{}", order.company, order.apex));
    let mut f = BTreeMap::from([
        (FEED_ADMIN_PUBKEY.to_string(), admin_pubkey.trim().to_string()),
        (FEED_OPERATOR.to_string(), account.trim().to_string()),
        (FEED_OPERATOR_INVITE.to_string(), sha256_hex(invite)),
        (FEED_OPERATOR_INVITE_TTL.to_string(), order.first_login_ttl_secs.max(60).to_string()),
    ]);
    if let Some(k) = &c.passkey_rp_feed {
        f.insert(k.clone(), host.trim().trim_end_matches('.').to_ascii_lowercase());
    }
    if let Some(readme) = &c.welcome {
        f.insert(contract::FEED_OPERATOR_WELCOME.to_string(), welcome_readme(readme, &host, account.trim()));
    }
    match c.billing {
        // UW-6: the sold site's console serves `/billing/{tenant}` (its renew page).
        Billing::Console => {
            f.insert(contract::FEED_BILLING_URL.to_string(), format!("https://{}/billing/{{tenant}}", canonical_of(&host, &order.names)));
        }
        // M4: the pay page the site row carries, as the shop made it for this order.
        Billing::SitePayPage if !order.pay_page.trim().is_empty() => {
            f.insert(contract::FEED_BILLING_URL.to_string(), order.pay_page.trim().to_string());
        }
        Billing::SitePayPage => {}
    }
    f.extend(record_feed_for(c, order));
    Ok(f)
}

/// Pure: **the estate record** as feed keys (gunnar-grpc `topology::Record::to_feed`): the three
/// laid machines as declared, never measured, recorded as `c`'s sold variant, no versions.
pub fn record_feed_for(c: &ProductContract, order: &LaidOrder) -> BTreeMap<String, String> {
    use contract::*;
    let mut f = BTreeMap::from([
        (FEED_RECORD.to_string(), RECORD_SCHEMA.to_string()),
        (FEED_VARIANT.to_string(), c.sold_variant.clone()),
        (FEED_VERSIONS.to_string(), String::new()),
        (FEED_BOXES.to_string(), order.estate.machines.iter().map(|m| m.role.clone()).collect::<Vec<_>>().join(",")),
    ]);
    for m in &order.estate.machines {
        let values = [
            m.role.clone(),
            m.hostname.clone(),
            m.title.clone(),
            m.public_ipv4.clone(),
            m.utility_ipv4.clone(),
            m.plan.clone(),
            "0".to_string(),
            "0".to_string(),
            m.disks.first().map(|d| d.gib).unwrap_or(0).to_string(),
            m.disks.iter().skip(1).map(|d| format!("{} GB {}", d.gib, d.tier)).collect::<Vec<_>>().join(", "),
        ];
        for (field, value) in BOX_FIELDS.iter().zip(values) {
            f.insert(format!("{FEED_BOX_PREFIX}{}.{field}", m.role), value);
        }
    }
    f
}

/// **The operator's first identity**, minted fresh: an OpenSSH ed25519 key — `(private, public)`.
pub fn mint_operator_key() -> Result<(String, String), String> {
    let mut seed = [0u8; 32];
    rand_core::RngCore::fill_bytes(&mut rand_core::OsRng, &mut seed);
    let key = ssh_key::PrivateKey::from(ssh_key::private::Ed25519Keypair::from_seed(&seed));
    seed.fill(0);
    let private = key.to_openssh(ssh_key::LineEnding::LF).map_err(|e| format!("encoding the operator key: {e}"))?;
    let public = key.public_key().to_openssh().map_err(|e| format!("encoding the operator key: {e}"))?;
    Ok((private.to_string(), public))
}

/// The prefix of a `[estate_orders.sale_feed]` key that is a DIRECTIVE to the shop's pairing,
/// never fed to the front.
pub const DIRECTIVE_PREFIX: &str = "shop.";
/// **`shop.mint_certificate = "true"`**: the sold front can reach no ACME (the UpCloud mock),
/// so the shop mints it a certificate for the order's names (90 days, self-signed).
pub const MINT_CERTIFICATE: &str = "shop.mint_certificate";

/// **`shop.reach = "utility"`**: the shop reaches the estate it sells over the UTILITY network
/// — the installer's link and the sale check dial each machine's utility address. For a shop
/// that runs INSIDE a machine of the same provider and zone (the ONE box): its utility network
/// reaches the sold machines (on the UpCloud mock a guest cannot route to another guest's
/// public, loopback address; on UpCloud the installer's ports need not face the internet).
pub const REACH: &str = "shop.reach";

/// Whether the shop's directives say to reach the sold estate over its utility network.
pub fn reach_over_utility(sale_feed: &BTreeMap<String, String>) -> bool {
    sale_feed.get(REACH).is_some_and(|v| v.trim() == "utility")
}

/// **The plan dialled over the utility network**: each machine's link at its utility
/// address ([`REACH`]). Stub until GREEN.
pub fn reached_over_utility(plan: &mut Plan) {
    for v in &mut plan.vms {
        v.public = v.utility;
    }
}

/// Where the sale check reaches the sold front over the utility network: `<utility>:443`.
/// Stub until GREEN.
pub fn front_at_utility(at: &monetize_server::estate_order::SaleCheckAt<'_>) -> Result<std::net::SocketAddr, String> {
    let front = at.front.ok_or_else(|| format!("{} has no laid front to reach", at.host))?;
    let ip: std::net::Ipv4Addr = front.utility_ipv4.trim().parse().map_err(|e| format!("the front's utility address {:?}: {e}", front.utility_ipv4))?;
    Ok(std::net::SocketAddr::from((ip, 443)))
}

/// Pure but for the key: **a self-signed certificate for `names`**, 90 days — `(cert, key)` PEM.
pub fn self_signed(names: &[String]) -> Result<(String, String), String> {
    let key = rcgen::KeyPair::generate().map_err(|e| e.to_string())?;
    let mut p = rcgen::CertificateParams::new(names.to_vec()).map_err(|e| e.to_string())?;
    let now = std::time::SystemTime::now();
    p.not_before = now.into();
    p.not_after = (now + Duration::from_secs(90 * 24 * 3600)).into();
    let cert = p.self_signed(&key).map_err(|e| e.to_string())?;
    Ok((cert.pem(), key.serialize_pem()))
}

/// Pure: **the sold front's feed**, in `c`'s words — the shop's static part with this order's
/// names filled in (`{{COMPANY}}`, `{{HOST}}`, `{{APEX}}`, and the ONE's `{{SHOP_DOOR}}` and
/// `{{MONETIZE_PUBKEY}}` from the order), the shop's directives taken out ([`DIRECTIVE_PREFIX`]),
/// the order's own values from the custody's hand-off, the console bearer under the key `c`'s
/// front reads, `c`'s free switch, and the ONE's pull channel.
pub fn front_feed_for(c: &ProductContract, sale_feed: &BTreeMap<String, String>, order: &LaidOrder, handoff: &Path) -> Result<BTreeMap<String, String>, String> {
    let host = order.names.first().cloned().unwrap_or_else(|| format!("{}.{}", order.company, order.apex));
    let fill = |v: &str| {
        v.replace("{{COMPANY}}", &order.company)
            .replace("{{HOST}}", &host)
            .replace("{{APEX}}", &order.apex)
            .replace("{{SHOP_DOOR}}", order.shop_door.trim())
            .replace("{{MONETIZE_PUBKEY}}", order.monetize_pubkey.trim())
    };
    let mut f: BTreeMap<String, String> = sale_feed.iter().filter(|(k, _)| !k.starts_with(DIRECTIVE_PREFIX)).map(|(k, v)| (k.clone(), fill(v))).collect();
    // HOL-REPO-NAME: the names of the order the product routes to its primary's repository —
    // served (the lay wrote their records), so routed, in `web_hosts` and certified.
    joined_into(&mut f, FEED_REPO_HOSTS, &served_under(&c.repo_prefixes, order, &host));
    if sale_feed.get(MINT_CERTIFICATE).is_some_and(|v| v.trim() == "true") {
        let names = served_names(order, &host, &f);
        let (cert, key) = self_signed(&names)?;
        f.insert(format!("tls.{host}.cert"), cert);
        f.insert(format!("tls.{host}.key"), key);
    }
    if f.contains_key(contract::FEED_MONETIZE_TOML) {
        return Err(format!("[estate_orders.sale_feed] names {}: a sold estate runs no monetize of its own (ONE monetize, G16)", contract::FEED_MONETIZE_TOML));
    }
    // **F4: the ONE monetize's door, fed on its own** — the sold front's recharge, upgrade and
    // material take call IN through it, signed with the client key below (no monetize on the
    // estate).
    if !order.shop_door.trim().is_empty() && order.monetize_pubkey.trim().len() == 64 {
        let mut shop = toml::Table::new();
        shop.insert("door".into(), toml::Value::String(order.shop_door.trim().to_string()));
        shop.insert("company".into(), toml::Value::String(order.company.clone()));
        shop.insert("shop_pubkey".into(), toml::Value::String(order.monetize_pubkey.trim().to_string()));
        shop.insert("client_key_secret".into(), toml::Value::String(monetize_server::shop_cloud::CLIENT_KEY_SECRET.into()));
        // P3-FLEET (plan §8): the product the front signs its `Fleet.Ask` as.
        shop.insert("product".into(), toml::Value::String(c.product.clone()));
        f.insert(contract::FEED_SHOP_DOOR.into(), toml::to_string(&shop).map_err(|e| e.to_string())?);
    }
    f.insert(c.console_token_feed.clone(), read(handoff, monetize_server::custody::handoff::CONSOLE_TOKEN)?);
    f.insert("secret.shop_client_key".into(), read(handoff, monetize_server::custody::handoff::ESTATE_CLIENT)?);
    f.insert("console_instance".into(), order.company.clone());
    // WWW-CANON: the provider site serves www. as its product does (the order's names say so).
    let provider = order.apex.trim().trim_end_matches('.').to_ascii_lowercase();
    let www_served = order.names.iter().any(|n| n.starts_with("www."));
    f.insert("console_provider".into(), format!("https://{}", if www_served && !provider.starts_with("www.") { format!("www.{provider}") } else { provider }));
    let served = served_names(order, &host, &f);
    // HOL-REPO-NAME: every served name is on the front's certificate; the product's redirect-only
    // ones (Gunnar's `git.<site>`, its forge is ssh) answer no web face. A guest that names no
    // redirect rider: its `git.` names are left out, as before the rider.
    let legacy_git = c.redirect_prefixes.is_none();
    f.insert("web_hosts".into(), served.iter().filter(|n| !(legacy_git && n.starts_with("git."))).cloned().collect::<Vec<_>>().join(","));
    joined_into(&mut f, FEED_WEB_CALLBACK_ONLY, &served_under(c.redirect_prefixes.as_deref().unwrap_or_default(), order, &host));
    f.insert(contract::FEED_FLEET.into(), order.shop_door.trim().to_string());
    f.insert(contract::FEED_FLEET_INSTANCE.into(), order.company.clone());
    f.insert(contract::FEED_MONETIZE_PUBKEY.into(), order.monetize_pubkey.trim().to_string());
    f.entry(c.free_feed.clone()).or_insert_with(|| "true".into());
    // Auto-repair ON unless the site's sale_feed said otherwise (owner 2026-10-12).
    f.entry(REPAIR_AUTO.into()).or_insert_with(|| "true".into());
    Ok(f).and_then(never_a_shop_credential)
}

/// The front's feed key of the names routed to its primary's repository (edda
/// `estate-front::route::FEED_REPO_HOSTS`).
pub const FEED_REPO_HOSTS: &str = "repo_hosts";
/// The front's feed key of the names that answer no web face (edda
/// `estate-front::web::FEED_WEB_CALLBACK_ONLY`).
pub const FEED_WEB_CALLBACK_ONLY: &str = "web_callback_only";

/// Pure: **the order's names under `prefixes`** of `host` (HOL-REPO-NAME) — only names the order
/// serves (the lay wrote their records), never the host itself, each once, in `prefixes`' order.
pub fn served_under(prefixes: &[String], order: &LaidOrder, host: &str) -> Vec<String> {
    let mut names: Vec<String> = Vec::new();
    for p in prefixes.iter().map(|p| p.trim()).filter(|p| !p.is_empty()) {
        let name = format!("{p}{host}");
        if order.names.iter().any(|n| n.eq_ignore_ascii_case(&name)) && !names.contains(&name) {
            names.push(name);
        }
    }
    names
}

/// `names` joined into `f`'s comma list `key` — what it named first, then each new one once.
fn joined_into(f: &mut BTreeMap<String, String>, key: &str, names: &[String]) {
    if names.is_empty() {
        return;
    }
    let mut all: Vec<String> = f.get(key).map(String::as_str).unwrap_or("").split(',').map(str::trim).filter(|n| !n.is_empty()).map(str::to_owned).collect();
    for n in names {
        if !all.iter().any(|a| a.eq_ignore_ascii_case(n)) {
            all.push(n.clone());
        }
    }
    f.insert(key.to_string(), all.join(","));
}

/// Pure: **the names a sold front serves** — the order's (else its host), and every name the feed
/// routes to its primary's repository (`repo_hosts`, edda `estate-front::route`: a routed name must
/// be one of `web_hosts`, in the front's certificate; lane OX-WGDS3), each once, in that order.
pub fn served_names(order: &LaidOrder, host: &str, f: &BTreeMap<String, String>) -> Vec<String> {
    let mut names: Vec<String> = if order.names.is_empty() { vec![host.to_string()] } else { order.names.clone() };
    for r in f.get(FEED_REPO_HOSTS).map(String::as_str).unwrap_or("").split(',').map(str::trim).filter(|r| !r.is_empty()) {
        if !names.iter().any(|n| n == r) {
            names.push(r.to_string());
        }
    }
    names
}

/// Pure (WWW-CANON, owner 2026-10-30: the sites are `www.<site>`): **the canonical name of
/// `host`** — `www.<host>` when `names` (the estate's served names) carry it, else `host`.
pub fn canonical_of(host: &str, names: &[String]) -> String {
    let www = format!("www.{host}");
    if !host.starts_with("www.") && names.iter().any(|n| n.eq_ignore_ascii_case(&www)) {
        www
    } else {
        host.to_string()
    }
}

/// A sold estate — and an operator site — is never fed a credential of the shop's.
fn never_a_shop_credential(f: BTreeMap<String, String>) -> Result<BTreeMap<String, String>, String> {
    for never in ["secret.upcloud_token", "secret.stripe_key", "secret.stripe_webhook", "secret.smtp_url", "secret.smtp_from"] {
        if f.contains_key(never) {
            return Err(format!("[estate_orders.sale_feed] names {never}: a sold estate is never fed a shop credential"));
        }
    }
    Ok(f)
}

/// Pure: **the buyer's welcome README**, the product's own (`template`, its facts'
/// `welcome_readme`) with `{host}`, `{account}` and `{repo}` filled in — the one repository the
/// estate is handed over with (`<account>/welcome`, made by the primary itself).
pub fn welcome_readme(template: &str, host: &str, account: &str) -> String {
    template.replace("{host}", host).replace("{account}", account).replace("{repo}", contract::WELCOME_REPO)
}

/// Pure: **the plan** — the three laid machines at the overlay's addresses, the front fed alone.
/// `relay`: the relay a sold estate's gunnar boxes mail through (S10 resend) — fed to the
/// main and the twin (which may become the main), never the front.
/// Pure: **an operator site's front feed** (an operator-site order, owner 2026-10-13) — the
/// sold front's, as the kit feeds a site of the ONE variant: it is NOT told it is somebody's
/// sold instance (`console_instance`, `console_provider`) nor that its product is free; it IS
/// handed the site's own bearer at the ONE box and the product its console sells.
pub fn site_front_feed(c: &ProductContract, mut sold: BTreeMap<String, String>, site: &monetize_server::estate_order::SiteFeed) -> Result<BTreeMap<String, String>, String> {
    if site.bearer.trim().is_empty() {
        return Err("the site order names no bearer: its console could sell nothing as its site".into());
    }
    for k in ["console_instance", "console_provider", c.free_feed.as_str(), contract::FEED_PUBLIC_SITE, contract::FEED_CLI_HOLE] {
        sold.remove(k);
    }
    if site.public_site {
        sold.insert(contract::FEED_PUBLIC_SITE.into(), "on".into());
    }
    if site.cli_hole_public {
        sold.insert(contract::FEED_CLI_HOLE.into(), contract::CLI_HOLE_PUBLIC.into());
    }
    sold.insert(contract::FEED_MONETIZE_BEARER.into(), site.bearer.trim().to_string());
    sold.insert(contract::FEED_CONSOLE_PRODUCT.into(), site.product.trim().to_string());
    // Its boxes pull as the site's own label — the estate the ONE box already knows.
    if !site.label.trim().is_empty() {
        sold.insert(contract::FEED_FLEET_INSTANCE.into(), site.label.trim().to_string());
    }
    Ok(sold)
}

/// Pure: **an operator site's feeds** (`site`; `None`: a sold estate, nothing changes): its
/// front fed as the enrolled site it is ([`site_front_feed`]), its seed's principal and the
/// site variant in the shared feed. Answers the front's feed.
///
/// RA5-17: a site's box laid AGAIN (the guardian's relay, a plan change that adds machines) is
/// fed the site's box keys too, by a site feed with NO bearer — only the site's own lay mints
/// its bearer, so the standing front keeps its feed as it is (as before the site feed came)
/// and is never refused for the bearer it does not carry.
pub fn with_site(c: &ProductContract, feed: &mut BTreeMap<String, String>, front: BTreeMap<String, String>, site: Option<&monetize_server::estate_order::SiteFeed>) -> Result<BTreeMap<String, String>, String> {
    let Some(site) = site else { return Ok(front) };
    let front = if site.bearer.trim().is_empty() { front } else { site_front_feed(c, front, site)? };
    if let Some((k, v)) = seed_principal_feed(&site.seed_key) {
        feed.insert(k, v);
    }
    feed.insert(contract::FEED_VARIANT.to_string(), c.site_variant.clone());
    Ok(front)
}

/// Pure: **what the main and the twin of `site`'s estate are fed** over `boxes`: the site's
/// public repositories ([`contract::FEED_PUBLIC_REPOSITORIES`], NIGHT-PUBREPO) when its
/// declaration names any; a sold estate (`None`) and a site that names none are fed nothing of
/// it, and a key that came in with the box feed is never passed on.
pub fn site_box_feed(boxes: BTreeMap<String, String>, site: Option<&monetize_server::estate_order::SiteFeed>) -> BTreeMap<String, String> {
    let mut f = boxes;
    f.remove(contract::FEED_PUBLIC_REPOSITORIES);
    if let Some(site) = site.filter(|s| !s.public_repositories.is_empty()) {
        f.insert(contract::FEED_PUBLIC_REPOSITORIES.to_string(), site.public_repositories.join(","));
    }
    f
}

/// The machine principal gunnar's attribution gate exempts for a seed into an empty repository
/// (gunnar-policy `AiTrailerPolicy::seed_principal`; the kit's `SEED_PRINCIPAL`).
pub const SEED_PRINCIPAL: &str = "installer-seed";

/// Pure: **the seed's principal as fed** (the kit's `Principal::feed`): `principal.installer-seed
/// = "machine none <public key>"`; `None` when the order named no seed key.
pub fn seed_principal_feed(seed_key: &str) -> Option<(String, String)> {
    let key = seed_key.trim();
    (key.starts_with("ssh-") && !key.contains('\n')).then(|| (format!("principal.{SEED_PRINCIPAL}"), format!("machine none {key}")))
}

/// Pure: **the ticket key the primary offered**, out of the installer's `offers.toml`
/// (`[<vm>] ticket_pubkey = "<64 hex>"`); empty when no box offered one.
pub fn ticket_key_of(offers_toml: &str) -> String {
    let Ok(t) = toml::from_str::<toml::Table>(offers_toml) else { return String::new() };
    t.values().filter_map(|vm| vm.get(TICKET_OFFER).and_then(toml::Value::as_str)).map(|k| k.trim().to_ascii_lowercase()).find(|k| k.len() == 64 && k.bytes().all(|b| b.is_ascii_hexdigit())).unwrap_or_default()
}

/// The offer key of each box's own fleet key (64 hex, the public half of `<data>/fleet/box.ed25519`):
/// Gunnar's `installer_listener::OFFER_FLEET_PUBKEY`, Holger's `paired::OFFER_FLEET_KEY`.
pub const FLEET_OFFER: &str = "fleet_pubkey";

/// Pure: **each box's fleet key as it offered it**, out of the installer's `offers.toml`
/// (`[<role>] fleet_pubkey = "<64 hex>"`), by role, in the guardian's encoding (base64 Ed25519,
/// `monetize_guardian::Store::register_key`). A box that offered none (older media) is not
/// named: it pins its own key on its first call inside the pin window, as before.
pub fn appliance_keys_of(offers_toml: &str) -> BTreeMap<String, String> {
    let Ok(t) = toml::from_str::<toml::Table>(offers_toml) else { return BTreeMap::new() };
    let raw = |hex: &str| -> Option<Vec<u8>> {
        let hex = hex.trim();
        (hex.len() == 64).then_some(())?;
        (0..32).map(|i| u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()).collect()
    };
    t.iter()
        .filter_map(|(role, vm)| Some((role.clone(), monetize_embed::signing::base64_encode(&raw(vm.get(FLEET_OFFER)?.as_str()?)?))))
        .collect()
}

/// Pure: **the plan** of `c`'s estate — the three laid machines at the overlay's addresses,
/// the front fed alone; `relay` (S10 resend) fed to the main and the twin (which may become
/// the main), never the front.
pub fn plan_of_for(c: &ProductContract, order: &LaidOrder, feed: BTreeMap<String, String>, front_feed: BTreeMap<String, String>, relay: &BTreeMap<String, String>, budget_s: u64) -> Result<Plan, String> {
    let ip = |what: &str, v: &str| v.parse::<std::net::Ipv4Addr>().map_err(|e| format!("{what} {v:?}: {e}"));
    let mut vms = Vec::new();
    for (role, kind, overlay) in [("front", Kind::Front, nordisk_pairing::OVERLAY_FRONT), ("main", c.box_kind, nordisk_pairing::OVERLAY_BOX_A), ("twin", c.box_kind, nordisk_pairing::OVERLAY_BOX_B)] {
        let m = order.estate.machine(role).ok_or_else(|| format!("the order lays no {role}"))?;
        let utility = ip(&format!("{role} utility"), &m.utility_ipv4)?;
        vms.push(PlanVm {
            name: role.to_string(),
            // The lean estate (owner 2026-10-23): a box laid with no public IPv4 sits behind
            // its front; the ONE box laid it on its own account and zone and reaches it over
            // the utility network (the installer's link, the live door, the custody step).
            public: if m.public_ipv4.trim().is_empty() { utility } else { ip(&format!("{role} public"), &m.public_ipv4)? },
            utility,
            overlay,
            kind,
            feed: match kind {
                Kind::Front => front_feed.clone(),
                // A box behind its front leaves through the front's egress door (the lean estate).
                _ if m.public_ipv4.trim().is_empty() => {
                    let mut f = relay.clone();
                    f.insert(nordisk_pairing::egress::FEED_EGRESS.to_string(), nordisk_pairing::egress::door_url());
                    f
                }
                _ => relay.clone(),
            },
        });
    }
    let p = Plan {
        estate: order.names.first().cloned().unwrap_or_else(|| format!("{}.{}", order.company, order.apex)),
        tunnel: TunnelKind::Wireguard,
        vms,
        feed,
        front: None,
        port: nordisk_pairing::bootstrap::PORT,
        link_port: nordisk_pairing::installer_link::LINK_PORT,
        budget_s,
        close_when: nordisk_pairing::installer::CloseWhen::Paired,
        box_cert_valid_s: Some(MATERIAL_VALID.as_secs()),
        front_waits_for: vec![TICKET_OFFER.to_string()],
    };
    p.check()?;
    Ok(p)
}

impl ShopPairing {
    /// **The sold front as the sale check reaches it** (S4): `https://<host>` by DNS, over the
    /// utility network ([`REACH`]) or where [`sale_check::front_reached_at`] says, trusting the
    /// web's roots and the certificate the shop minted for it.
    fn front(&self, at: &monetize_server::estate_order::SaleCheckAt<'_>) -> Result<sale_check::Https, String> {
        let addr = if reach_over_utility(&self.sale_feed) { front_at_utility(at)? } else { sale_check::front_addr(at)? };
        let pin = std::fs::read(at.run_dir.join(sale_check::FRONT_CERT)).ok();
        sale_check::Https::new(at.host, addr, pin.as_deref())
    }
}

impl Installer for ShopPairing {
    /// The shop's pairing mints only for a product it is told ([`Installer::mint_for`]).
    fn mint(&self, _company: &str, _host: &str) -> Result<Vec<(String, String)>, String> {
        Err("REFUSED [contract-no-kind] the shop's pairing mints an order's material for its product's facts alone, and none were named".into())
    }

    /// **The order's material** for an estate of the product `facts` describe.
    fn mint_for(&self, facts: &Facts, _company: &str, host: &str) -> Result<Vec<(String, String)>, String> {
        mint_material_with(&ProductContract::of(facts)?, host, self.installer_link_psk)
    }

    /// **The sale check** (S4): the sold front's public `https://<host>` proves the product's own
    /// sale proof ([`sale_proof::prove`]) before the shop captures.
    fn sale_check(&self, at: &monetize_server::estate_order::SaleCheckAt<'_>) -> Result<String, String> {
        let c = ProductContract::of(at.facts)?;
        sale_proof::prove(&c.proof, &self.front(at)?, at.host, at.account, at.console_token, at.first_login)
    }

    /// **The site's first-admin door** (owner 2026-10-22, `site first-link`): its public front,
    /// reached as the sale check reaches it, asked whether its door is spent and whether the
    /// custody's invite still opens it ([`sale_proof::first_door`]).
    fn first_door(&self, at: &monetize_server::estate_order::SaleCheckAt<'_>) -> Result<monetize_server::estate_order::FirstDoor, String> {
        let c = ProductContract::of(at.facts)?;
        sale_proof::first_door(&c.proof, &self.front(at)?, at.host, at.account, at.first_login)
    }

    /// **One call on the site's console at its public front** (OX-WGDS3, `site console`),
    /// reached as the sale check reaches it, with the custody's break-glass bearer (the front
    /// swaps it for the primary's console bearer). A repository call names `repo.<host>` as its
    /// `Host` under the front's own certificate. The answer never carries the bearer.
    fn console_call(&self, at: &monetize_server::estate_order::SaleCheckAt<'_>, call: &monetize_server::estate_order::console::ConsoleCall) -> Result<(u16, Vec<u8>), String> {
        let mut front = self.front(at)?;
        if call.repo_host {
            front = front.with_host_header(&format!("repo.{}", at.host));
        }
        let (status, body) = front.call(&call.method, &call.path_and_query, call.body.as_deref(), call.content_type.as_deref(), Some(at.console_token)).map_err(|e| sale_check::scrub(&e, &[at.console_token]))?;
        // A body that names the bearer is answered with it withheld; any other, byte for byte.
        let t = at.console_token.as_bytes();
        let names_it = t.len() >= 4 && body.windows(t.len()).any(|w| w == t);
        Ok((status, if names_it { sale_check::scrub(&String::from_utf8_lossy(&body), &[at.console_token]).into_bytes() } else { body }))
    }

    fn install(&self, req: &InstallRequest) -> Result<InstallVerdict, String> {
        let order: LaidOrder = serde_json::from_slice(&std::fs::read(&req.laid).map_err(|e| format!("{}: {e}", req.laid.display()))?).map_err(|e| format!("laid.json: {e}"))?;
        let material_dir = req.handoff.join(monetize_server::custody::handoff::MATERIAL_DIR);
        let material = Material::load(&material_dir)?;
        let admin = read(&material_dir, OPERATOR_PUB)?;
        let invite = read(&req.handoff, monetize_server::custody::handoff::FIRST_LOGIN)?;
        let c = &ProductContract::of(&req.facts)?;
        let mut feed = shared_feed_for(c, &order, &req.account, &admin, &invite)?;
        let mut front = front_feed_for(c, &self.sale_feed, &order, &req.handoff)?;
        // An operator site laid itself: fed as the enrolled site it is.
        front = with_site(c, &mut feed, front, req.site.as_ref())?;
        // S4: the sale check trusts the certificate the shop minted for this front, and only it.
        sale_check::keep_front_cert(&req.run, &order.names.first().cloned().unwrap_or_else(|| format!("{}.{}", order.company, order.apex)), &front)?;
        let boxes = box_feed_for(c, &req.relay, offsite_feed_for(c, &req.offsite, offsite_recipient_in(c, &req.offsite, &material_dir, &req.handoff)?.as_deref()), &front);
        let boxes = site_box_feed(boxes, req.site.as_ref());
        let mut plan = plan_of_for(c, &order, feed, front, &boxes, self.budget_s)?;
        if reach_over_utility(&self.sale_feed) {
            reached_over_utility(&mut plan);
        }
        fleet_late(&mut plan, self.fleet_late_s);
        plan = with_fresh_wg_psks(plan)?;
        let mut paths = Vec::new();
        for vm in &plan.vms {
            paths.push((vm.clone(), nordisk_pairing::installer::path_to(&plan, vm, material.link.as_ref())?));
        }
        let sink_dir = req.run.join("pairing");
        forget_secret_offers(&sink_dir)?;
        let sink = ShopSink(nordisk_pairing::installer::FolderSink::new(&sink_dir, true)?, req.narrate.clone());
        let out = nordisk_pairing::installer::run(&plan, &material, paths, &sink);
        // **The estate keeps its own installer material** (F4, the owner 2026-10-09): handed
        // back into the custody, where the sold front TAKES it (`SoldEstate.TakeMaterial`) —
        // the shop never PUTs it into the estate (ONE monetize: monetize dials no estate). A
        // paired estate whose bundle could not be kept is not delivered: it could never be
        // upgraded, recharged or renewed.
        let kept = match &out {
            Ok(_) => bundle(&material_dir, &sink_dir, &plan).and_then(|b| {
                let back = req.handoff.join(monetize_server::custody::handoff::RETURN_DIR);
                std::fs::create_dir_all(&back).map_err(|e| format!("{}: {e}", back.display()))?;
                monetize_server::custody::write_private(&back.join(monetize_server::custody::handoff::INSTALLER_MATERIAL), &b)
            }),
            Err(_) => Ok(()),
        };
        let (word, detail, peers) = match (&out, kept) {
            (Ok(o), Ok(())) => ("PASS", format!("the shop paired {} machine(s) itself; no operator machine took part; the estate's installer material waits in the custody for its front to take", o.vms.len()), peers_of(o)),
            (Ok(_), Err(e)) => ("FAIL", format!("the shop paired the estate, but its installer material could not be kept: {e}"), Vec::new()),
            (Err(e), _) => ("FAIL", format!("the shop's pairing: {e}"), Vec::new()),
        };
        let offers = std::fs::read_to_string(sink_dir.join(nordisk_pairing::installer::OFFERS_FILE)).unwrap_or_default();
        let ticket_key = ticket_key_of(&offers);
        // F-L-01: the ONE box pins exactly the fleet key each box offered (a box that offered
        // none, older media, keeps the guardian's pin window).
        let appliance_keys = if word == "PASS" { appliance_keys_of(&offers) } else { BTreeMap::new() };
        let v = InstallVerdict { verdict: word.into(), detail, receipt: serde_json::json!({"verb": "shop-pairing", "verdict": word}), peers, appliance_keys, ticket_key };
        write_verdict(&req.run, &v)?;
        Ok(v)
    }

    /// **Every laid box asked its pair status again** (F5, test3-holger-rs 2026-10-20: failed by
    /// its install deadline, then paired after a reboot of its front): over each box's installer
    /// link, with the order's own installer material, all boxes at once, each waited for at most
    /// [`STATUS_WAIT`]. Only asked: nothing is fed, closed or laid.
    fn pair_status(&self, req: &InstallRequest) -> Result<monetize_server::estate_order::PairCheck, String> {
        let order: LaidOrder = serde_json::from_slice(&std::fs::read(&req.laid).map_err(|e| format!("{}: {e}", req.laid.display()))?).map_err(|e| format!("laid.json: {e}"))?;
        let material = Material::load(&req.handoff.join(monetize_server::custody::handoff::MATERIAL_DIR))?;
        let c = &ProductContract::of(&req.facts)?;
        let mut plan = plan_of_for(c, &order, BTreeMap::new(), BTreeMap::new(), &BTreeMap::new(), self.budget_s)?;
        if reach_over_utility(&self.sale_feed) {
            reached_over_utility(&mut plan);
        }
        let boxes = std::thread::scope(|s| {
            // A32-14, stays a task: scoped threads, one per machine, joined below.
            let asked: Vec<_> = plan.vms.iter().map(|vm| (vm.name.clone(), s.spawn(|| status_of(&plan, vm, &material)))).collect();
            asked.into_iter().map(|(name, h)| (name, h.join().unwrap_or_else(|_| Err("the ask panicked".into())))).collect::<Vec<_>>()
        });
        let ticket_key = std::fs::read_to_string(req.run.join("pairing").join(nordisk_pairing::installer::OFFERS_FILE)).map(|t| ticket_key_of(&t)).unwrap_or_default();
        Ok(monetize_server::estate_order::PairCheck { boxes, ticket_key })
    }

    /// **`role`'s live door, asked over the installer's link with the custody's material** (F9):
    /// the ONE box takes an update step of a box whose front's primary keeps no material.
    fn live_running(&self, req: &InstallRequest, role: &str) -> Result<monetize_server::estate_order::update::LiveRunning, String> {
        let r = self.live_door(req, role, LIVE_WAIT)?.live_running()?;
        Ok(monetize_server::estate_order::update::LiveRunning { base: r.base, app: r.app, slot: r.slot, live_update: r.live_update })
    }

    /// **The release's live app staged into `role`'s slot** over the installer's link (F9).
    fn live_stage(&self, req: &InstallRequest, role: &str, stage: &monetize_server::estate_order::update::LiveStage) -> Result<String, String> {
        let s = nordisk_pairing::live::Stage { pin_hex: stage.pin_hex.clone(), signature: stage.signature.clone(), base: stage.base.clone(), archive: stage.archive.clone() };
        // Lane B5: what the release declares rides with it.
        let d = nordisk_pairing::live::Declared { release: stage.release.clone(), env: stage.env.clone() };
        self.live_door(req, role, LIVE_STAGE_WAIT)?.live_stage_declared(&s, &d)
    }
}

/// How long one box's live door is waited for when asked (F9).
pub const LIVE_WAIT: Duration = Duration::from_secs(30);
/// How long a stage may take to be taken (the archive goes over the link).
pub const LIVE_STAGE_WAIT: Duration = Duration::from_secs(300);

impl ShopPairing {
    /// The installer's client to `role`'s log door, over its link, with the order's own
    /// installer material as the custody handed it over (F5's way, [`Installer::pair_status`]).
    fn live_door(&self, req: &InstallRequest, role: &str, wait: Duration) -> Result<nordisk_pairing::installer::Client, String> {
        let order: LaidOrder = serde_json::from_slice(&std::fs::read(&req.laid).map_err(|e| format!("{}: {e}", req.laid.display()))?).map_err(|e| format!("laid.json: {e}"))?;
        let material = Material::load(&req.handoff.join(monetize_server::custody::handoff::MATERIAL_DIR))?;
        let c = &ProductContract::of(&req.facts)?;
        let mut plan = plan_of_for(c, &order, BTreeMap::new(), BTreeMap::new(), &BTreeMap::new(), self.budget_s)?;
        if reach_over_utility(&self.sale_feed) {
            reached_over_utility(&mut plan);
        }
        let vm = plan.vms.iter().find(|v| v.name == role).ok_or_else(|| format!("the order's plan names no {role}"))?;
        let path = nordisk_pairing::installer::path_to(&plan, vm, material.link.as_ref())?;
        nordisk_pairing::installer::Client::new(path, &material.ca.cert_pem, &material.me, wait)
    }
}

/// How long one box is waited for when it is asked its pair status again (F5).
pub const STATUS_WAIT: Duration = Duration::from_secs(10);

/// Pure: **the pair status line of a box whose install is CLOSED** (F5). A box answers its
/// status door only while its install is open; once closed it refuses it (`[install-closed]`,
/// only its log door is left). The installer closes a box only after every box PAIRED
/// (`CloseWhen::Paired`), so a closed box is a PAIRED one.
pub fn closed_line(vm: &str) -> String {
    format!("   pair   {vm}: install closed · PAIRED")
}

/// **One box's pair status, asked over the installer's link** (F5): its signal line, or
/// [`closed_line`] for a box whose install is closed; `Err` the box did not answer.
fn status_of(plan: &Plan, vm: &PlanVm, m: &Material) -> Result<String, String> {
    let path = nordisk_pairing::installer::path_to(plan, vm, m.link.as_ref())?;
    let mut c = nordisk_pairing::installer::Client::new(path, &m.ca.cert_pem, &m.me, STATUS_WAIT)?;
    match c.status() {
        Ok(signal) => Ok(signal.line()),
        Err(e) if e.contains("[install-closed]") => Ok(closed_line(&vm.name)),
        Err(e) => Err(e),
    }
}

/// **The recipient the order's material carries** (lane O1): its `offsite.pub` — or, for an
/// order paid before its pair was minted, a pair minted NOW and handed back into the custody
/// (`return/`, sealed by the custody's take-back, kept past the hand-off). `None` when `c` ships
/// no copy, the shop holds no store for the estate, the feed already names the recipient, or no
/// material is held (a box laid again after the hand-off: a pair minted there could be kept by
/// nobody).
fn offsite_recipient_in(c: &ProductContract, offsite: &BTreeMap<String, String>, material_dir: &Path, handoff: &Path) -> Result<Option<String>, String> {
    use monetize_server::estate_order::{FEED_OFFSITE_ENDPOINT, FEED_OFFSITE_RECIPIENT};
    if !c.offsite || offsite.get(FEED_OFFSITE_ENDPOINT).is_none() || offsite.get(FEED_OFFSITE_RECIPIENT).is_some() || !material_dir.is_dir() {
        return Ok(None);
    }
    if let Ok(r) = read(material_dir, monetize_server::custody::OFFSITE_PUB_FILE) {
        return Ok(Some(r).filter(|r| !r.is_empty()));
    }
    let back = handoff.join(monetize_server::custody::handoff::RETURN_DIR);
    std::fs::create_dir_all(&back).map_err(|e| format!("{}: {e}", back.display()))?;
    let pair = mint_offsite_pair();
    for (name, text) in &pair {
        monetize_server::custody::write_private(&back.join(name), text.as_bytes())?;
    }
    Ok(Some(pair[1].1.clone()))
}

/// Keep the verdict beside `laid.json` in `run`.
fn write_verdict(run: &Path, v: &InstallVerdict) -> Result<(), String> {
    let file = monetize_server::estate_order::VERDICT_FILE;
    let bytes = serde_json::to_vec(v).map_err(|e| format!("encoding the install verdict: {e}"))?;
    write_atomic(run, file, &bytes).map_err(|e| format!("keeping the install verdict at {}: {e}", run.join(file).display()))
}

/// `dir/name` replaced whole: a temp beside it, synced, renamed over it, the directory synced.
fn write_atomic(dir: &Path, name: &str, bytes: &[u8]) -> std::io::Result<()> {
    use std::io::Write as _;
    let tmp = dir.join(format!(".{name}.tmp-{}", std::process::id()));
    let written = (|| {
        let mut f = std::fs::File::create(&tmp)?;
        f.write_all(bytes)?;
        f.sync_all()?;
        std::fs::rename(&tmp, dir.join(name))
    })();
    if written.is_err() {
        let _ = std::fs::remove_file(&tmp);
    }
    written?;
    if let Ok(d) = std::fs::File::open(dir) {
        let _ = d.sync_all();
    }
    Ok(())
}

/// **The shop's sink** (S5, trace-private 2026-10-09): the pairing's ledger, logs, status and
/// public offers as [`nordisk_pairing::installer::FolderSink`] keeps them, and NEVER a secret
/// offer — the sold front hands its web TLS certificate AND KEY over at its close (for a
/// successor's feed), and the shop must not keep a sold estate's key on its disk.
///
/// Every line it is handed is ALSO said to the order's narrator (the test button,
/// 2026-10-11: the setup's logs go to monetize) — the installer's own narration
/// and each box's filtered log; never an offer, never a secret.
pub struct ShopSink(pub nordisk_pairing::installer::FolderSink, pub monetize_server::estate_order::setup_log::Narrate);

impl nordisk_pairing::installer::Sink for ShopSink {
    fn lines(&self, vm: &str, lines: &[String]) {
        for l in lines {
            self.1.say(vm, &published(l));
        }
        self.0.lines(vm, lines)
    }
    fn status(&self, vm: &str, signal: Option<&nordisk_pairing::signal::Signal>, last_line: &str) {
        self.0.status(vm, signal, last_line)
    }
    fn ledger(&self, door: &nordisk_pairing::door::Door) {
        self.0.ledger(door)
    }
    fn say(&self, line: &str) {
        self.1.say("installer", &published(line));
        self.0.say(line)
    }
    fn offer(&self, vm: &str, offer: &BTreeMap<String, String>) {
        self.0.offer(vm, offer)
    }
    fn secret_offer(&self, vm: &str, offer: &nordisk_pairing::bootstrap::SecretOffer) -> Result<(), String> {
        // Said by its keys' count only — never a name that could carry a host, never a value.
        self.0.say(&format!("{vm}: its secret offer ({} value(s)) is NOT kept at the shop: a sold estate's keys stay on the estate", offer.expose().len()));
        Ok(())
    }
}

/// **A line as it may be published** (STINKY ST-18: every sold install's lines go on the bus
/// and into `setup-lines.jsonl`): the installer's own sink filter (nordisk-pairing
/// `redact::clean` — tokens, keys, env records, opaque runs withheld), then every mail address
/// masked (`bu***@example.com`). Idempotent.
pub fn published(line: &str) -> String {
    let clean = nordisk_pairing::redact::clean(line);
    clean.split(' ').map(mask_address).collect::<Vec<_>>().join(" ")
}

fn mask_address(word: &str) -> String {
    let Some((local, domain)) = word.split_once('@') else { return word.to_owned() };
    let lead: String = local.chars().take_while(|c| !c.is_alphanumeric()).collect();
    let name = &local[lead.len()..];
    if name.is_empty() || !domain.contains('.') || domain.starts_with('.') || name.ends_with("***") {
        return word.to_owned();
    }
    format!("{lead}{}***@{domain}", name.chars().take(2).collect::<String>())
}

/// **A sold estate's secret offers off the shop's disk** (S5): `<run>/pairing/secret-offers.toml`
/// removed — an earlier sale's, written before [`ShopSink`]. Answers whether one was there.
pub fn forget_secret_offers(sink_dir: &Path) -> Result<bool, String> {
    let p = sink_dir.join(nordisk_pairing::installer::SECRET_OFFERS_FILE);
    match std::fs::remove_file(&p) {
        Ok(()) => Ok(true),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(format!("{}: {e}", p.display())),
    }
}

/// **Every sale's secret offers swept off the shop's disk** (S5): `<orders>/<co>/pairing/` for
/// each order this shop holds. Answers how many were removed.
pub fn sweep_secret_offers(orders_dir: &Path) -> usize {
    std::fs::read_dir(orders_dir).into_iter().flatten().flatten().filter(|e| forget_secret_offers(&e.path().join("pairing")).unwrap_or(false)).count()
}

/// The installer material bundle's schema word (gunnar-front `recharge::Kept`).
pub const BUNDLE_V: &str = "installer-material/1";

/// **The bundle the estate keeps** (F4): every file of the order's material (the CA and its
/// key, the installer's certificate and key, the link keys, the seeds — never a bundle kept
/// before, never the private half of its off-site pair), the door's ledger the pairing left, and the plan it paired by (with its feeds and
/// PSKs) — what re-admits an upgraded or recharged box and renews its certificates. JSON; a
/// secret as a whole.
pub fn bundle(material_dir: &Path, sink_dir: &Path, plan: &Plan) -> Result<Vec<u8>, String> {
    let mut files = BTreeMap::new();
    for e in std::fs::read_dir(material_dir).map_err(|e| format!("{}: {e}", material_dir.display()))?.flatten() {
        let p = e.path();
        let name = e.file_name().to_string_lossy().to_string();
        // The estate never holds the private half of its own off-site pair (lane O1).
        if p.is_file() && name != monetize_server::custody::handoff::INSTALLER_MATERIAL && name != monetize_server::custody::OFFSITE_KEY_FILE {
            files.insert(name, std::fs::read_to_string(&p).map_err(|e| format!("{}: {e}", p.display()))?);
        }
    }
    let ledger = std::fs::read_to_string(sink_dir.join("ledger.toml")).map_err(|e| format!("the pairing's ledger: {e}"))?;
    serde_json::to_vec(&serde_json::json!({"v": BUNDLE_V, "files": files, "ledger": ledger, "plan": plan})).map_err(|e| e.to_string())
}

/// The estate's WireGuard peers from the installer's outcome: public halves only.
fn peers_of(o: &nordisk_pairing::installer::Outcome) -> Vec<WgPeer> {
    o.vms.iter().map(|v| WgPeer { name: v.name.clone(), ..WgPeer::default() }).collect()
}

#[cfg(test)]
mod tests {
    /// ★ A16 (C19): **a sold Holger's boxes are told the site it was bought at**
    /// (`console_provider`, as its front is), so the main's sign-up page leads there on an own
    /// domain too. Gunnar's boxes are fed as before; an older box ignores the key.
    #[test]
    fn a_sold_holgers_boxes_are_told_its_provider() {
        let front = BTreeMap::from([("console_provider".to_string(), "https://holger.rs".to_string()), ("console_instance".to_string(), "acme".to_string())]);
        let boxes = super::box_feed_for(&holger(), &BTreeMap::new(), BTreeMap::new(), &front);
        assert_eq!(boxes.get("console_provider").map(String::as_str), Some("https://holger.rs"));
        let gunnar = super::box_feed_for(&gunnar(), &BTreeMap::new(), BTreeMap::new(), &front);
        assert!(!gunnar.contains_key("console_provider"), "Gunnar's boxes unchanged");
    }

    use super::*;
    #[allow(unused_imports)]
    use crate::test_fixtures::*;

    /// ★ An operator site laid by the shop is fed as the kit feeds a site of the ONE variant:
    /// its own bearer and product, never "you are somebody's sold instance", never free.
    #[test]
    fn an_operator_sites_front_is_fed_its_bearer_and_product_and_is_no_sold_instance() {
        let sold = BTreeMap::from([("console_instance".to_string(), "gunnarrs".to_string()), ("console_provider".to_string(), "https://gunnar.rs".to_string()), ("plugin.gunnar.free".to_string(), "true".to_string()), ("web_hosts".to_string(), "gunnar.rs,www.gunnar.rs".to_string()), (contract::FEED_FLEET_INSTANCE.to_string(), "gunnarrs".to_string())]);
        let site = monetize_server::estate_order::SiteFeed { bearer: "b".repeat(64), product: "gunnar".into(), label: "gunnar-rs".into(), seed_key: String::new(), public_site: false, cli_hole_public: false, public_repositories: Vec::new() };
        assert_eq!(seed_principal_feed("ssh-ed25519 AAAAC3Nz installer-seed"), Some(("principal.installer-seed".to_string(), "machine none ssh-ed25519 AAAAC3Nz installer-seed".to_string())));
        assert_eq!(seed_principal_feed(""), None);
        let f = site_front_feed(&gunnar(), sold.clone(), &site).unwrap();
        assert!(!f.contains_key("console_instance") && !f.contains_key("console_provider") && !f.contains_key("plugin.gunnar.free"), "{:?}", f.keys());
        assert_eq!((f[contract::FEED_MONETIZE_BEARER].as_str(), f[contract::FEED_CONSOLE_PRODUCT].as_str()), ("b".repeat(64).as_str(), "gunnar"));
        assert_eq!(f[contract::FEED_FLEET_INSTANCE], "gunnar-rs", "its boxes pull as the site's own label");
        assert_eq!(f["web_hosts"], "gunnar.rs,www.gunnar.rs");
        assert!(site_front_feed(&gunnar(), sold, &monetize_server::estate_order::SiteFeed::default()).is_err(), "no bearer, no site");
        let key = "ab".repeat(32);
        assert_eq!(ticket_key_of(&format!("[front]\nversion = \"1\"\n[main]\nticket_pubkey = \"{}\"\n", key.to_uppercase())), key);
        assert_eq!(ticket_key_of("[main]\nversion = \"1\"\n"), "");
    }

    /// ★ RA1-14 (RA1-SEC leftover): **the CLI's gRPC hole is open to the internet on a site that
    /// says so** (`[estates.<label>] cli_hole_public`, gunnar.rs) and on no other front: a site
    /// that does not say it is fed nothing of it, and gunnar-front's default is the estate's own
    /// network. Before, `GUNNAR_FRONT_HOLE=public` rode the METERED front medium, so every sold
    /// estate's front built from it opened the hole too.
    #[test]
    fn only_a_site_that_says_so_is_fed_a_public_cli_hole() {
        assert_eq!((contract::FEED_CLI_HOLE, contract::CLI_HOLE_PUBLIC), ("front_cli_hole", "public"));
        let sold = BTreeMap::from([(contract::FEED_CLI_HOLE.to_string(), "public".to_string())]);
        let mut site = monetize_server::estate_order::SiteFeed { bearer: "b".repeat(64), product: "gunnar".into(), label: "test2-gunnar-rs".into(), ..Default::default() };
        assert!(!site_front_feed(&gunnar(), sold.clone(), &site).unwrap().contains_key(contract::FEED_CLI_HOLE), "a site that does not say it is fed nothing of it");
        site.cli_hole_public = true;
        assert_eq!(site_front_feed(&gunnar(), BTreeMap::new(), &site).unwrap()[contract::FEED_CLI_HOLE], "public");
    }

    /// ★ TASKS-12 (owner 2026-10-25): **only a site whose declaration says `public_site` is
    /// fed `console_public_site = on`** (gunnar.rs, holger.rs); every other site's front is fed
    /// nothing of it, and a key that came in with the sold feed is never passed on.
    #[test]
    fn only_a_public_site_is_fed_its_public_switch() {
        assert_eq!(contract::FEED_PUBLIC_SITE, "console_public_site");
        let sold = BTreeMap::from([(contract::FEED_PUBLIC_SITE.to_string(), "on".to_string())]);
        let mut site = monetize_server::estate_order::SiteFeed { bearer: "b".repeat(64), product: "gunnar".into(), label: "test2-gunnar-rs".into(), ..Default::default() };
        assert!(!site_front_feed(&gunnar(), sold.clone(), &site).unwrap().contains_key(contract::FEED_PUBLIC_SITE), "a site that does not say it is fed nothing of it");
        site.public_site = true;
        site.label = "gunnar-rs".into();
        assert_eq!(site_front_feed(&gunnar(), BTreeMap::new(), &site).unwrap()[contract::FEED_PUBLIC_SITE], "on");
    }

    /// ★ NIGHT-PUBREPO (owner 2026-10-28): **only a site whose declaration names public
    /// repositories feeds its main and twin them** (holger.rs: `crates,npm`); a sold estate and
    /// a site that names none are fed nothing of it, and a key that came in is never passed on.
    #[test]
    fn only_a_site_that_names_public_repositories_feeds_its_boxes_them() {
        assert_eq!(contract::FEED_PUBLIC_REPOSITORIES, "public_repositories");
        let came = BTreeMap::from([(contract::FEED_PUBLIC_REPOSITORIES.to_string(), "bundles".to_string()), ("auto_repair".to_string(), "true".to_string())]);
        let mut site = monetize_server::estate_order::SiteFeed { bearer: "b".repeat(64), product: "holger".into(), label: "holger-rs".into(), ..Default::default() };
        assert!(!site_box_feed(came.clone(), None).contains_key(contract::FEED_PUBLIC_REPOSITORIES), "a sold estate is fed nothing of it");
        let none = site_box_feed(came.clone(), Some(&site));
        assert!(!none.contains_key(contract::FEED_PUBLIC_REPOSITORIES), "a site that names none is fed nothing of it");
        assert_eq!(none["auto_repair"], "true", "the rest of the box feed is kept");
        site.public_repositories = vec!["crates".into(), "npm".into()];
        assert_eq!(site_box_feed(came, Some(&site))[contract::FEED_PUBLIC_REPOSITORIES], "crates,npm");
    }

    /// F-L-01: **every box's offered fleet key is named in the verdict** in the guardian's
    /// encoding, so the ONE box pins exactly it (no first-caller window); a box that offered
    /// none, or a malformed key, is left to the pin window.
    #[test]
    fn each_box_offered_fleet_key_is_named_in_the_guardians_encoding() {
        let (main, twin) = ([7u8; 32], [9u8; 32]);
        let hex = |k: &[u8; 32]| k.iter().map(|b| format!("{b:02x}")).collect::<String>();
        let offers = format!("[front]\nversion = \"1\"\n[main]\nversion = \"1\"\nticket_pubkey = \"{}\"\nfleet_pubkey = \"{}\"\n[twin]\nfleet_pubkey = \"{}\"\n", hex(&main), hex(&main), hex(&twin).to_uppercase());
        let keys = appliance_keys_of(&offers);
        assert_eq!(keys.get("main"), Some(&monetize_embed::signing::base64_encode(&main)));
        assert_eq!(keys.get("twin"), Some(&monetize_embed::signing::base64_encode(&twin)));
        assert_eq!(keys.get("front"), None, "a box that offered no fleet key keeps the pin window");
        assert_eq!(keys.len(), 2);
        assert!(appliance_keys_of("[main]\nfleet_pubkey = \"abc\"\n").is_empty(), "a malformed key is never named");
        assert!(appliance_keys_of("not toml [").is_empty());
    }

    fn verdict() -> InstallVerdict {
        InstallVerdict { verdict: "PASS".into(), detail: "paired".into(), receipt: serde_json::json!({"verb": "shop-pairing"}), peers: Vec::new(), appliance_keys: Default::default(), ticket_key: String::new() }
    }

    /// ★ F5: **a box whose install is closed is a PAIRED box on a re-check** (the installer
    /// closes only after every box PAIRED); a box that did not answer is named so.
    #[test]
    fn a_closed_box_is_a_paired_one_on_a_recheck() {
        use monetize_server::estate_order::{recheck_words, PairCheck};
        let roles = ["front", "main", "twin"];
        let all = PairCheck { boxes: vec![("front".into(), Ok(closed_line("front"))), ("main".into(), Ok(closed_line("main"))), ("twin".into(), Ok(closed_line("twin")))], ticket_key: String::new() };
        assert_eq!(recheck_words(&all, &roles), None, "every box closed: every box PAIRED");
        let silent = PairCheck { boxes: vec![("front".into(), Ok(closed_line("front"))), ("main".into(), Ok(closed_line("main"))), ("twin".into(), Err("no answer within 10 s".into()))], ticket_key: String::new() };
        assert_eq!(recheck_words(&silent, &roles).as_deref(), Some("twin: did not answer: no answer within 10 s"));
    }

    /// Stinky row 15 (2026-10-10): the verdict was `let _ = fs::write(..)`, so
    /// an order whose verdict could not be kept was reported installed and
    /// then hung in an unknown state.
    #[test]
    fn a_verdict_that_cannot_be_kept_fails_the_install() {
        let dir = tempfile::tempdir().unwrap();
        let not_a_dir = dir.path().join("run");
        std::fs::write(&not_a_dir, b"a file where the run directory should be").unwrap();
        assert!(write_verdict(&not_a_dir, &verdict()).is_err(), "the failure is the install's");
    }

    #[test]
    fn a_kept_verdict_replaces_the_old_one_whole() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(monetize_server::estate_order::VERDICT_FILE);
        std::fs::write(&path, b"{\"verdict\": \"FAIL\", half a verdict").unwrap();
        write_verdict(dir.path(), &verdict()).unwrap();
        let back: InstallVerdict = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        assert_eq!(back, verdict());
        let strays: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).filter(|n| n != monetize_server::estate_order::VERDICT_FILE).collect();
        assert!(strays.is_empty(), "no temp is left behind: {strays:?}");
    }

    fn order() -> LaidOrder {
        serde_json::from_value(serde_json::json!({
            "company": "acme", "apex": "test2.gunnar.rs", "domain": "",
            "names": ["acme.test2.gunnar.rs", "www.acme.test2.gunnar.rs", "git.acme.test2.gunnar.rs"],
            "estate": {"reference": "estate/acme", "company": "acme", "zone": "se-sto1", "machines": [
                {"role": "front", "hostname": "f", "title": "f", "plan": "STARTER-4xCPU-8GB", "server": "s1", "public_ipv4": "198.51.100.1", "utility_ipv4": "10.6.0.1", "disks": [{"title": "sys", "id": "d1", "gib": 40, "tier": "standard", "address": "virtio:0"}]},
                {"role": "main", "hostname": "m", "title": "m", "plan": "STARTER-4xCPU-16GB", "server": "s2", "public_ipv4": "198.51.100.2", "utility_ipv4": "10.6.0.2", "disks": [{"title": "sys", "id": "d2", "gib": 50, "tier": "standard", "address": "virtio:0"}]},
                {"role": "twin", "hostname": "t", "title": "t", "plan": "STARTER-1xCPU-2GB", "server": "s3", "public_ipv4": "198.51.100.3", "utility_ipv4": "10.6.0.3", "disks": [{"title": "sys", "id": "d3", "gib": 20, "tier": "standard", "address": "virtio:0"}]}
            ]},
            "first_login_ttl_secs": 604800
        }))
        .unwrap()
    }

    /// ★ **The order's material: its own CA, and each kind's seed a box can read from its
    /// metadata** — WireGuard, the installer's link, the bootstrap pair, the estate's host;
    /// the installer side loads as the kit's material does.
    #[test]
    fn the_orders_material_and_seeds_are_minted_for_its_host() {
        let files = mint_material("acme.test2.gunnar.rs").unwrap();
        let get = |n: &str| files.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone()).unwrap_or_else(|| panic!("{n}"));
        for (name, kind) in [("seed.front.toml", Kind::Front), ("seed.gunnar.toml", Kind::Gunnar)] {
            let s = Seed::parse(&get(name)).unwrap();
            assert_eq!((s.estate.as_str(), s.kind, s.tunnel), ("acme.test2.gunnar.rs", kind, TunnelKind::Wireguard));
            assert!(s.installer_link.is_some() && s.bootstrap_key_pem.contains("PRIVATE KEY"));
        }
        let dir = tempfile::tempdir().unwrap();
        for (n, v) in &files {
            std::fs::write(dir.path().join(n), v).unwrap();
        }
        let m = Material::load(dir.path()).expect("the installer's side loads");
        assert!(m.link.is_some());
        assert!(get(OPERATOR_PUB).starts_with("ssh-ed25519 "));
        assert_ne!(mint_material("acme.test2.gunnar.rs").unwrap()[0].1, get("ca.cert.pem"), "a new CA per order");
        // ★ ONE monetize (G12/F4): no health reader — the twin is read from the estate's reports.
        assert!(!files.iter().any(|(k, _)| k.contains("reader")), "no reader is minted: {:?}", files.iter().map(|(k, _)| k).collect::<Vec<_>>());
    }

    /// ★ **What a sold estate is fed**: the buyer's account as the operator and the invite's
    /// hash, never the invite; the sold front's keys with the order's names, its bearer and
    /// client key from the hand-off; a shop credential in the static part is refused.
    /// ★ G16 (ONE monetize): NO monetize of its own — no monetize.toml, no backup key, no
    /// control host; its boxes are fed the ONE's pull channel, the estate and the ONE's key.
    #[test]
    fn a_sold_estate_is_fed_its_own_keys_and_never_a_shop_credential() {
        let mut o = order();
        o.shop_door = "https://monetize.ignalina.dk".into();
        o.monetize_pubkey = "ab".repeat(32);
        let f = shared_feed(&o, "acme-owner", "ssh-ed25519 AAAA op", "inviteinviteinvite").unwrap();
        assert_eq!(f.get(FEED_OPERATOR).map(String::as_str), Some("acme-owner"));
        assert_eq!(f.get(FEED_OPERATOR_INVITE).map(String::len), Some(64));
        assert!(!f.values().any(|v| v.contains("inviteinviteinvite")), "never the invite itself");
        assert!(shared_feed(&o, " ", "ssh-ed25519 A", "x").is_err(), "a sold estate is its buyer's");
        // ★ UW-6: every box is told the sold SITE's own pay page — never the one baked into the medium.
        assert_eq!(f.get(contract::FEED_BILLING_URL).map(String::as_str), Some("https://www.acme.test2.gunnar.rs/billing/{tenant}"), "on the site's www name (WWW-CANON)");
        assert_eq!(contract::FEED_BILLING_URL, "refusal_link");
        let welcome = &f[contract::FEED_OPERATOR_WELCOME];
        assert!(welcome.contains("Thank you for buying **acme.test2.gunnar.rs**") && welcome.contains("git.acme.test2.gunnar.rs:2222/acme-owner/welcome.git"), "{welcome}");
        let dir = tempfile::tempdir().unwrap();
        for (n, v) in [("console-admin-token", "aa"), ("estate-client.key", "cc")] {
            std::fs::write(dir.path().join(n), v).unwrap();
        }
        let sale = BTreeMap::from([("welcome_note".to_string(), "# {{HOST}} sold by {{APEX}}".to_string())]);
        let front = front_feed(&sale, &o, dir.path()).expect("no backup key in the hand-off, none needed");
        assert_eq!(front.get("welcome_note").map(String::as_str), Some("# acme.test2.gunnar.rs sold by test2.gunnar.rs"));
        // HOL-REPO-NAME (kit parity, h-front-sans): the forge's `git.<site>` is on the front's
        // certificate as a redirect-only name — https there verifies, and is sent to the site.
        assert_eq!(front.get("web_hosts").map(String::as_str), Some("acme.test2.gunnar.rs,www.acme.test2.gunnar.rs,git.acme.test2.gunnar.rs"));
        assert_eq!(front.get("web_callback_only").map(String::as_str), Some("git.acme.test2.gunnar.rs"), "the forge's name answers no web face");
        assert!(!front.contains_key("repo_hosts"), "Gunnar routes no repository through :443");
        for gone in [contract::FEED_MONETIZE_TOML, "monetize_backup_kek", "monetize_control_host"] {
            assert!(!front.contains_key(gone), "G16: a sold front runs no monetize, so no {gone}: {:?}", front.keys().collect::<Vec<_>>());
        }
        assert_eq!(front.get(contract::FEED_FLEET).map(String::as_str), Some("https://monetize.ignalina.dk"), "the ONE's pull channel");
        assert_eq!(front.get(contract::FEED_FLEET_INSTANCE).map(String::as_str), Some("acme"));
        assert_eq!(front.get(contract::FEED_MONETIZE_PUBKEY).map(String::as_str), Some("ab".repeat(32).as_str()), "the ONE's key");
        assert_eq!(front.get("secret.shop_client_key").map(String::as_str), Some("cc"));
        let own = BTreeMap::from([(contract::FEED_MONETIZE_TOML.to_string(), "[clouds.shop]".to_string())]);
        assert!(front_feed(&own, &o, dir.path()).unwrap_err().contains("runs no monetize"), "a sale feed that still names a monetize.toml is refused by name");
        assert_eq!(front.get("console_provider").map(String::as_str), Some("https://www.test2.gunnar.rs"), "the provider site's www name (WWW-CANON)");
        assert_eq!(front.get("plugin.gunnar.free").map(String::as_str), Some("true"));
        let bad = BTreeMap::from([("secret.upcloud_token".to_string(), "x".to_string())]);
        assert!(front_feed(&bad, &o, dir.path()).unwrap_err().contains("never fed a shop credential"));
        let p = plan_of(&o, f.clone(), front.clone(), &BTreeMap::new(), 1800).unwrap();
        assert_eq!(p.vms.iter().map(|v| (v.name.as_str(), v.feed.is_empty())).collect::<Vec<_>>(), vec![("front", false), ("main", true), ("twin", true)]);
        assert_eq!(p.front_waits_for, vec![TICKET_OFFER.to_string()]);
        // ★ P1 (S10 resend): the main and the twin mail through the relay the shop was fed for
        // sold estates; the front is never fed it.
        let relay = BTreeMap::from([("secret.smtp_url".to_string(), "smtp://u:p@smtp.example:587".to_string()), ("secret.smtp_from".to_string(), "estate@example.invalid".to_string())]);
        let p = plan_of(&o, f, front, &relay, 1800).unwrap();
        for v in &p.vms {
            let fed = v.feed.contains_key("secret.smtp_url") && v.feed.contains_key("secret.smtp_from");
            assert_eq!(fed, v.name != "front", "{}: {:?}", v.name, v.feed.keys().collect::<Vec<_>>());
        }
        assert!(!p.feed.contains_key("secret.smtp_url"), "never in the shared feed (the front reads it too)");
    }

    /// ★ **A box laid with no public IPv4 is reached over its utility address** (owner
    /// 2026-10-23, the lean estate: one public IPv4 per estate, on the front). The ONE box lays
    /// the estate on its own account and zone, so its utility network reaches main and the twin:
    /// the installer's link, the live door and the custody step dial their utility address,
    /// whatever `shop.reach` says; the front keeps its public address.
    #[test]
    fn a_box_with_no_public_ipv4_is_dialled_at_its_utility_address() {
        let mut o = order();
        for m in o.estate.machines.iter_mut().filter(|m| m.role != "front") {
            m.public_ipv4 = String::new();
        }
        let p = plan_of(&o, BTreeMap::from([("operator_name".to_string(), "acme-owner".to_string())]), BTreeMap::new(), &BTreeMap::new(), 600).expect("a lean estate is a plan");
        let at: Vec<(String, String)> = p.vms.iter().map(|v| (v.name.clone(), v.public.to_string())).collect();
        assert_eq!(at, vec![("front".into(), "198.51.100.1".into()), ("main".into(), "10.6.0.2".into()), ("twin".into(), "10.6.0.3".into())]);
        // ... and leaves through its front's egress door, which only it is fed.
        let doors: Vec<Option<&str>> = p.vms.iter().map(|v| v.feed.get(nordisk_pairing::egress::FEED_EGRESS).map(String::as_str)).collect();
        assert_eq!(doors, vec![None, Some("http://10.44.0.1:3128"), Some("http://10.44.0.1:3128")]);
        let full = plan_of(&order(), BTreeMap::new(), BTreeMap::new(), &BTreeMap::new(), 600).unwrap();
        assert!(full.vms.iter().all(|v| !v.feed.contains_key(nordisk_pairing::egress::FEED_EGRESS)), "a box with its own public IPv4 is fed no door");
        let mut o = order();
        o.estate.machines[0].public_ipv4 = "not an address".into();
        assert!(plan_of(&o, BTreeMap::new(), BTreeMap::new(), &BTreeMap::new(), 600).unwrap_err().contains("front public"), "a public address that is given must still be one");
    }

    /// ★ **`shop.reach = "utility"`: a shop inside a machine of the same provider reaches the
    /// estate it sells over the utility network** (the ONE box on the UpCloud mock, A3
    /// 2026-10-11: a guest cannot route to another guest's public, loopback address). The
    /// installer's link dials each machine's utility address, the sale check the front's
    /// `<utility>:443`; the directive is never fed to the front.
    #[test]
    fn a_shop_reaching_over_utility_dials_each_machines_utility_address() {
        let o = order();
        let mut sale = BTreeMap::from([(REACH.to_string(), "utility".to_string())]);
        assert!(reach_over_utility(&sale));
        let mut p = plan_of(&o, BTreeMap::from([("operator_name".to_string(), "acme-owner".to_string())]), BTreeMap::new(), &BTreeMap::new(), 600).unwrap();
        reached_over_utility(&mut p);
        for v in &p.vms {
            assert_eq!(v.public, v.utility, "{} dialled at its utility address", v.name);
        }
        p.check().expect("a plan dialled over utility is a plan");
        let dir = tempfile::tempdir().unwrap();
        let front = o.estate.machine("front").unwrap().clone();
        let at = monetize_server::estate_order::SaleCheckAt { facts: &monetize_server::testing::lifecycles::gunnar_facts(), company: "acme", host: "acme.test2.gunnar.rs", account: "acme-owner", front: Some(&front), run_dir: dir.path(), console_token: "t", first_login: "i" };
        assert_eq!(front_at_utility(&at).unwrap(), "10.6.0.1:443".parse().unwrap());
        let none = monetize_server::estate_order::SaleCheckAt { front: None, ..at };
        assert!(front_at_utility(&none).is_err(), "no laid front, nothing to reach");
        sale.insert(REACH.to_string(), "public".to_string());
        assert!(!reach_over_utility(&sale), "only `utility` changes the reach");
        for (k, v) in [("console-admin-token", "aa"), ("estate-client.key", "cc")] {
            std::fs::write(dir.path().join(k), v).unwrap();
        }
        let f = front_feed(&BTreeMap::from([(REACH.to_string(), "utility".to_string())]), &o, dir.path()).unwrap();
        assert!(!f.contains_key(REACH), "a directive is never fed");
    }

    /// ★ **The shop's directives are never fed; `shop.mint_certificate` gives a front that can
    /// reach no ACME (the UpCloud mock) a certificate for the order's names**, and the shop's
    /// own door and key are filled in from the order.
    #[test]
    fn a_directive_is_never_fed_and_a_minted_certificate_names_the_orders_hosts() {
        let mut o = order();
        o.shop_door = "https://monetize.ignalina.dk".into();
        o.monetize_pubkey = "ab".repeat(32);
        let dir = tempfile::tempdir().unwrap();
        for (n, v) in [("console-admin-token", "aa"), ("estate-client.key", "cc")] {
            std::fs::write(dir.path().join(n), v).unwrap();
        }
        let sale = BTreeMap::from([
            (MINT_CERTIFICATE.to_string(), "true".to_string()),
            ("about".to_string(), "door {{SHOP_DOOR}} key {{MONETIZE_PUBKEY}}".to_string()),
        ]);
        let front = front_feed(&sale, &o, dir.path()).unwrap();
        assert!(!front.keys().any(|k| k.starts_with(DIRECTIVE_PREFIX)), "{:?}", front.keys().collect::<Vec<_>>());
        assert_eq!(front["about"], format!("door https://monetize.ignalina.dk key {}", "ab".repeat(32)), "the sale feed's placeholders are filled");
        assert!(!front.contains_key(contract::FEED_MONETIZE_TOML), "G16: no [clouds.shop], no monetize.toml at all");
        // ★ F4: the ONE monetize's door, fed on its own (no monetize on the estate needed to call IN).
        let door: toml::Table = toml::from_str(&front[contract::FEED_SHOP_DOOR]).unwrap();
        assert_eq!((door["door"].as_str(), door["company"].as_str(), door["client_key_secret"].as_str()), (Some("https://monetize.ignalina.dk"), Some("acme"), Some("shop_client_key")));
        assert_eq!(door["shop_pubkey"].as_str(), Some("ab".repeat(32).as_str()));
        // ★ P3-FLEET (plan §8): the product its front signs its Fleet asks as.
        assert_eq!(door["product"].as_str(), Some("gunnar"), "{door:?}");
        assert!(!door.contains_key("enabled"), "{door:?}");
        let pem = &front["tls.acme.test2.gunnar.rs.cert"];
        assert!(pem.contains("BEGIN CERTIFICATE") && front["tls.acme.test2.gunnar.rs.key"].contains("PRIVATE KEY"));
        let der = x509_parser::pem::parse_x509_pem(pem.as_bytes()).unwrap().1;
        let cert = der.parse_x509().unwrap();
        let sans: Vec<String> = cert.subject_alternative_name().unwrap().unwrap().value.general_names.iter().map(|g| g.to_string()).collect();
        for n in &o.names {
            assert!(sans.iter().any(|s| s.contains(n.as_str())), "{n} not in {sans:?}");
        }
        assert!(front_feed(&BTreeMap::new(), &o, dir.path()).unwrap().keys().all(|k| !k.starts_with("tls.")), "no directive, no certificate");
    }

    /// ★ **S5: the shop never keeps a sold front's web TLS key** — the front's secret offer (its
    /// certificate and key, for a successor) is dropped by the shop's sink; the ledger and the
    /// public offers are kept; an earlier sale's `secret-offers.toml` is removed.
    #[test]
    fn the_shop_keeps_no_secret_offer_of_a_sold_front() {
        use nordisk_pairing::installer::Sink as _;
        let dir = tempfile::tempdir().unwrap();
        let sink = ShopSink(nordisk_pairing::installer::FolderSink::new(dir.path(), false).unwrap(), Default::default());
        let secret = nordisk_pairing::bootstrap::SecretOffer::new(BTreeMap::from([("tls.acme.test2.gunnar.rs.key".to_string(), "-----BEGIN PRIVATE KEY-----".to_string())]));
        sink.secret_offer("front", &secret).expect("the close goes on");
        sink.offer("main", &BTreeMap::from([("ticket_pubkey".to_string(), "ab".to_string())]));
        let on_disk: Vec<String> = walk(dir.path()).into_iter().filter(|p| std::fs::read_to_string(p).is_ok_and(|t| t.contains("PRIVATE KEY"))).map(|p| p.display().to_string()).collect();
        assert!(on_disk.is_empty(), "the sold front's key is on the shop's disk: {on_disk:?}");
        assert!(dir.path().join("offers.toml").is_file(), "the public offers are kept");
        // An earlier sale's file is swept.
        std::fs::write(dir.path().join("secret-offers.toml"), "[front]\nkey = \"-----BEGIN PRIVATE KEY-----\"\n").unwrap();
        assert!(forget_secret_offers(dir.path()).unwrap(), "it was there");
        assert!(!dir.path().join("secret-offers.toml").exists());
        assert!(!forget_secret_offers(dir.path()).unwrap(), "asked again: nothing");
    }

    /// ★ **The pairing's lines go to monetize** (the test button, 2026-10-11): every
    /// filtered box line and every line of the installer's own narration is said to
    /// the order's narrator, naming who said it; an offer is never said.
    #[test]
    fn the_pairings_lines_are_said_to_the_orders_narrator() {
        use nordisk_pairing::installer::Sink as _;
        let dir = tempfile::tempdir().unwrap();
        let heard = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(String, String)>::new()));
        let h = heard.clone();
        let narrate = monetize_server::estate_order::setup_log::Narrate::with(move |src, line| h.lock().unwrap().push((src.to_owned(), line.to_owned())));
        let sink = ShopSink(nordisk_pairing::installer::FolderSink::new(dir.path(), false).unwrap(), narrate);
        sink.say("pairing 3 machine(s)");
        sink.lines("acme-main", &["booted".to_string(), "serving".to_string()]);
        sink.offer("acme-main", &BTreeMap::from([("ticket_pubkey".to_string(), "ab".to_string())]));
        let heard = heard.lock().unwrap().clone();
        assert_eq!(
            heard,
            [("installer".to_string(), "pairing 3 machine(s)".to_string()), ("acme-main".to_string(), "booted".to_string()), ("acme-main".to_string(), "serving".to_string())]
        );
    }

    /// ★ **STINKY ST-18: what reaches the bus and `setup-lines.jsonl` is redacted** — the
    /// installer's sink filter (nordisk-pairing `redact::clean`) on every line said to the
    /// narrator, the installer's own narration too (its errors echo what a box answered);
    /// a buyer's mail address is masked. Progress lines pass unchanged.
    #[test]
    fn the_lines_said_to_the_narrator_are_redacted() {
        use nordisk_pairing::installer::Sink as _;
        let dir = tempfile::tempdir().unwrap();
        let heard = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let h = heard.clone();
        let narrate = monetize_server::estate_order::setup_log::Narrate::with(move |_, line| h.lock().unwrap().push(line.to_owned()));
        let sink = ShopSink(nordisk_pairing::installer::FolderSink::new(dir.path(), false).unwrap(), narrate);
        sink.say("acme-main: not yet — 401 Bearer abcdefabcdef0123 refused");
        sink.say("the owner is buyer.person@example.com");
        sink.lines("acme-main", &["stripe key sk_live_51Habc".to_string(), "ADMIN_TOKEN=hunter2hunter2".to_string(), "serving".to_string()]);
        let heard = heard.lock().unwrap().clone();
        let all = heard.join("\n");
        for secret in ["abcdefabcdef0123", "sk_live_51Habc", "hunter2hunter2", "buyer.person@example.com"] {
            assert!(!all.contains(secret), "{secret} reached the narrator: {all}");
        }
        assert_eq!(heard.len(), 5, "{heard:?}");
        assert_eq!(heard[4], "serving", "progress passes unchanged");
        assert!(heard[1].contains("@example.com"), "the address is masked, not dropped: {}", heard[1]);
    }

    /// **The estate record as gunnar reads it** (gunnar-grpc `topology::Record::from_feed`; its
    /// equality with gunnar's own `to_feed` is held by gunnar-front's contract test): the three
    /// laid machines, as declared.
    #[test]
    fn the_estate_record_is_fed_in_gunnars_words() {
        let f = shared_feed(&order(), "acme-owner", "ssh-ed25519 AAAA op", "x").unwrap();
        assert_eq!(f[contract::FEED_RECORD], "1");
        assert_eq!(f[contract::FEED_VARIANT], gunnar().sold_variant);
        assert_eq!(f[contract::FEED_BOXES], "front,main,twin");
        assert_eq!(f[contract::FEED_VERSIONS], "");
        assert_eq!(f["estate.box.main.size"], "STARTER-4xCPU-16GB");
        assert_eq!((f["estate.box.twin.public"].as_str(), f["estate.box.twin.utility"].as_str(), f["estate.box.twin.system_disk_gb"].as_str()), ("198.51.100.3", "10.6.0.3", "20"));
        assert_eq!(f.keys().filter(|k| k.starts_with(contract::FEED_BOX_PREFIX)).count(), 3 * contract::BOX_FIELDS.len());
        let (private, public) = mint_operator_key().unwrap();
        assert!(private.starts_with("-----BEGIN OPENSSH PRIVATE KEY-----") && public.starts_with("ssh-ed25519 "));
        assert_eq!(ssh_key::PrivateKey::from_openssh(&private).unwrap().public_key().to_openssh().unwrap(), public);
    }

    fn walk(d: &Path) -> Vec<std::path::PathBuf> {
        let mut out = Vec::new();
        for e in std::fs::read_dir(d).into_iter().flatten().flatten() {
            let p = e.path();
            if p.is_dir() {
                out.extend(walk(&p));
            } else {
                out.push(p);
            }
        }
        out
    }


    /// ★ **The bundle the estate keeps** (F4): every material file (never a bundle kept
    /// before), the door's ledger and the plan (feeds and all) — and it reads back as it went in.
    #[test]
    fn the_kept_bundle_holds_the_material_the_ledger_and_the_plan() {
        let dir = tempfile::tempdir().unwrap();
        let (material, sink) = (dir.path().join("material"), dir.path().join("pairing"));
        std::fs::create_dir_all(&material).unwrap();
        std::fs::create_dir_all(&sink).unwrap();
        for (n, v) in mint_material("acme.test2.gunnar.rs").unwrap() {
            std::fs::write(material.join(n), v).unwrap();
        }
        std::fs::write(material.join(monetize_server::custody::handoff::INSTALLER_MATERIAL), "an older bundle").unwrap();
        std::fs::write(sink.join("ledger.toml"), "# the door's ledger\n").unwrap();
        let plan = plan_of(&order(), BTreeMap::from([("operator_name".to_string(), "acme-owner".to_string())]), BTreeMap::new(), &BTreeMap::new(), 600).unwrap();
        let b: serde_json::Value = serde_json::from_slice(&bundle(&material, &sink, &plan).unwrap()).unwrap();
        assert_eq!(b["v"], BUNDLE_V);
        for (f, _) in mint_material("acme.test2.gunnar.rs").unwrap() {
            assert!(b["files"][f.as_str()].as_str().is_some_and(|t| !t.is_empty()), "{f} is kept");
        }
        assert!(b["files"].get(monetize_server::custody::handoff::INSTALLER_MATERIAL).is_none(), "never a bundle in a bundle");
        assert_eq!(b["ledger"], "# the door's ledger\n");
        let back: Plan = serde_json::from_value(b["plan"].clone()).expect("the plan reads back");
        assert_eq!(back, plan);
    }
}

#[cfg(test)]
pub(crate) mod test_fixtures;
#[cfg(test)]
mod holger_tests;
#[cfg(test)]
mod l18_tests;
#[cfg(test)]
mod m4_tests;