diff --git a/flake.nix b/flake.nix index 3358bb3c16..676adbfefa 100755 --- a/flake.nix +++ b/flake.nix @@ -24,6 +24,7 @@ rec { lib.make-mcpx-overlay lib.make-mcpx-modules lib.make-laptop-backups-checks + lib.make-fleet ]; inputs = { nixgl = { diff --git a/lib/default.nix b/lib/default.nix index e47d7cedcf..03b0ea7d37 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -1152,6 +1152,28 @@ let } ); + # fleet multicall binary packages (pkgs/fleet; epic code#5412, + # step 1 code#5429). One workspace, capability variants as + # separate attrs; the connect-static flavor (musl) is only + # offered on Linux, where a static target makes sense. + make-fleet = inputs.flake-utils.lib.eachDefaultSystem ( + system: + let + pkgs = import inputs.nixpkgs-unstable { inherit system; }; + fleetPkgs = pkgs.callPackage ../pkgs/fleet { + sourceRev = inputs.self.rev or "dirty"; + }; + in + { + packages = { + inherit (fleetPkgs) fleet fleet-serve fleet-connect; + } + // pkgs.lib.optionalAttrs (system == "x86_64-linux" || system == "aarch64-linux") { + inherit (fleetPkgs) fleet-connect-static; + }; + } + ); + make-mcpx-overlay = { overlays = { default = final: prev: { @@ -1230,6 +1252,7 @@ let make-mcpx-overlay make-mcpx-modules make-laptop-backups-checks + make-fleet ; } ]; diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock new file mode 100644 index 0000000000..0403b3057a --- /dev/null +++ b/pkgs/fleet/Cargo.lock @@ -0,0 +1,222 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "fleet" +version = "0.1.0" +dependencies = [ + "fleet-config", + "fleet-proxy-proto", + "fleet-registry", + "fleet-secrets", + "serde_json", +] + +[[package]] +name = "fleet-config" +version = "0.1.0" +dependencies = [ + "serde", + "toml", +] + +[[package]] +name = "fleet-proxy-proto" +version = "0.1.0" +dependencies = [ + "fleet-registry", + "serde", + "serde_json", +] + +[[package]] +name = "fleet-registry" +version = "0.1.0" + +[[package]] +name = "fleet-secrets" +version = "0.1.0" +dependencies = [ + "fleet-config", + "fleet-proxy-proto", + "serde_json", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.4", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/pkgs/fleet/Cargo.toml b/pkgs/fleet/Cargo.toml new file mode 100644 index 0000000000..36fbc76a9f --- /dev/null +++ b/pkgs/fleet/Cargo.toml @@ -0,0 +1,40 @@ +# fleet — one multicall binary for the fleet's tools (epic: developing-today/code#5412). +# Design of record: doc/2026-11-04T11-45-48Z_design_fleet_multicall_binary/ (§1 layout). +# +# Self-contained workspace on the pkgs/atlas-search pattern: own Cargo.toml, +# Cargo.lock and rust-toolchain.toml, no workspace relationship to the repo +# root. Crates land one step at a time; step 1 (#5429) is the skeleton: +# platform crates + the bin's dispatch/stub machinery + variant builds. +[workspace] +members = [ + "crates/fleet-registry", + "crates/fleet-config", + "crates/fleet-secrets", + "crates/fleet-proxy-proto", + "crates/fleet", +] +resolver = "2" + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.85" +license = "MIT OR Apache-2.0" + +[workspace.dependencies] +fleet-registry = { path = "crates/fleet-registry" } +fleet-config = { path = "crates/fleet-config" } +fleet-secrets = { path = "crates/fleet-secrets" } +fleet-proxy-proto = { path = "crates/fleet-proxy-proto" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "0.9" + +[profile.release] +# Small artifacts are a build contract for the connect variant (§2 of the +# design note: target <= 1.5 MiB, hard budget <= 2 MiB, stripped). Size — +# not speed — is the release profile's job in this workspace. +opt-level = "z" +lto = true +codegen-units = 1 +strip = true diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md new file mode 100644 index 0000000000..93ca18eca1 --- /dev/null +++ b/pkgs/fleet/README.md @@ -0,0 +1,88 @@ +# fleet — the multicall fleet binary + +One Rust binary for the whole fleet surface (epic +developing-today/code#5412; design note +`doc/2026-11-04T11-45-48Z_design_fleet_multicall_binary/`). This +workspace is step 1 (#5429): the skeleton. The registry, config, +secrets-by-name and proxy-protocol platform crates are real; the +domain commands are capability stubs until their own steps land +(queue #5430, proxy #5431, search #5432, dispatch #5433). + +## Layout + +``` +Cargo.toml workspace (release profile is size-tuned: + opt-level z, LTO, one codegen unit, stripped) +rust-toolchain.toml pinned toolchain (atlas pattern) +crates/fleet-registry/ the FULL domain registry — every domain's + name, summary, aliases, subcommands and the + capability ids behind them. Compiled into + every variant, so --help is always complete. +crates/fleet-config/ fleet.toml: [domains] switches, [proxy], + [secrets]; path/ports/socket constants. +crates/fleet-secrets/ secrets by NAME only (broker first, then + `bws` fallback). Values never appear in + code, tests, errors or logs. +crates/fleet-proxy-proto/ session-broker wire protocol: 4-byte BE + length + JSON frames, hello/capability + handshake, major-version window (N, N-1). +crates/fleet/ the binary: multicall dispatch, capability + stubs, `version`, `capabilities`, help. +default.nix the four variant packages (see below) +smoke.sh per-variant smoke suite (post-build) +``` + +## Variants + +Capability surface = compiled features ∩ invocation-name profile ∩ +config. Invoking under a hyphenated name (`fleet-serve`, +`fleet-connect`) NARROWS the surface to that profile — it never +widens past the compiled features (refinement A). Domain alias +names (`repo-queue`, `queue-broker`, `secrets-broker`, +`laptop-agent`, `atlas-search`, `laptop-agent-broker`) route to +their domain through argv0. + +| nix attr | profile | capabilities | +| --------------------- | ------- | ------------------------------------------------------------------- | +| `fleet` | full | all nine | +| `fleet-serve` | serve | proxy-connect, proxy-serve, queue-broker, secrets-broker, search-serve | +| `fleet-connect` | connect | proxy-connect (dynamic) | +| `fleet-connect-static`| connect | proxy-connect (musl static, runs anywhere) | + +Every package installs its binary as `bin/fleet`; the hyphen +variants also get a `bin/fleet-serve` / `bin/fleet-connect` symlink +for side-by-side installs. + +## The stub contract + +A domain that cannot run answers on stderr and exits **69** +(EX_UNAVAILABLE), with wording that says which layer said no: + +| case | wording | +| --------------------------- | ---------------------------------------------------------- | +| not compiled into this build| `this build does not include ''` + enabled list | +| narrowed out by argv0 name | `invoked as 'fleet-connect', this build does not include …`| +| disabled by config | `'' is disabled by config on this host` | +| compiled in, not yet built | `'' is included in this build but not implemented yet` | + +Usage errors exit 2. `fleet --help` always renders the full +registry, marking each unavailable domain with the reason +(`[not in this build]`, `[narrowed out by this name]`, +`[disabled by config]`). `fleet version` prints the version, the +build name, the source rev and the exact enabled-capability list; +`fleet capabilities` prints the same surface as JSON. + +## Build and smoke + +```sh +nix build .#fleet .#fleet-serve .#fleet-connect .#fleet-connect-static +./pkgs/fleet/smoke.sh ./result ./result-1 ./result-2 ./result-3 +cargo test --workspace # unit tests (registry, config, proto, secrets) +``` + +The connect variants carry the D7 size contract: **≤ 2 MiB hard +gate** (target ≤ 1.5 MiB), enforced in `default.nix` postFixup +against the final stripped artifact and re-asserted by smoke.sh. + +No package here installs anything live: no units, no PATH changes, +no flips. The first live flip is step 2. diff --git a/pkgs/fleet/crates/fleet-config/Cargo.toml b/pkgs/fleet/crates/fleet-config/Cargo.toml new file mode 100644 index 0000000000..06fefc5fac --- /dev/null +++ b/pkgs/fleet/crates/fleet-config/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "fleet-config" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "fleet configuration: ~/.config/fleet/fleet.toml + env resolution, the [domains] enable/disable table, and state-dir paths." + +[dependencies] +serde = { workspace = true } +toml = { workspace = true } diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs new file mode 100644 index 0000000000..6662c4d810 --- /dev/null +++ b/pkgs/fleet/crates/fleet-config/src/lib.rs @@ -0,0 +1,263 @@ +//! fleet-config — the one place fleet configuration resolves +//! (design note §1/§7, epic developing-today/code#5412). +//! +//! Sources, in precedence order: +//! 1. env overrides (`FLEET_CONFIG`, `FLEET_BROKER_SOCKET`); +//! 2. the config file — `$FLEET_CONFIG`, else +//! `${XDG_CONFIG_HOME:-~/.config}/fleet/fleet.toml`; +//! 3. compiled-in defaults matching today's live systems. +//! +//! The `[domains]` table is the config-level domain disable (§7): a +//! domain set to `false` dispatches to the capability stub with exit 69 +//! and `disabled by config on this host` wording — the per-host shaping +//! and incident lever. A missing file is not an error (defaults rule); +//! a malformed file is a loud error, never a silent fallback, because a +//! silently ignored disable would defeat the lever. + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use serde::Deserialize; + +/// The session broker's socket, as the Python broker runs it today. +pub const DEFAULT_BROKER_SOCKET: &str = ".cache/laptop-agent/broker.sock"; +/// The proxy's per-port routing table (§4): port → service name. +pub const PORT_LAPTOP_AGENT: u16 = 4799; +pub const PORT_SECRETS_BROKER: u16 = 4800; +pub const PORT_QUEUE_BROKER: u16 = 4801; +/// Broker idle exit (§4: retained from the Python broker — a warmth +/// cache that exits when cold is a feature on a shared sandbox). +pub const DEFAULT_IDLE_EXIT_SECS: u64 = 3600; +/// The token file whose contents the session broker sends as +/// `X-Agent-Token` for secrets-broker requests. fleet only ever names +/// this file; the broker reads it per request (§1: token files stay +/// files, read per request, never stored, never logged). +pub const DEFAULT_SECRETS_TOKEN_FILE: &str = ".config/secrets-broker/token"; + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct Config { + /// `[domains]` — domain name → enabled. Absent means enabled. + pub domains: BTreeMap, + pub proxy: ProxyConfig, + pub secrets: SecretsConfig, +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct ProxyConfig { + /// Session broker socket path (relative paths resolve under $HOME). + pub broker_socket: Option, + pub idle_exit_secs: Option, +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct SecretsConfig { + /// Path of the secrets-broker token file (handed to the session + /// broker per request; fleet never opens it). + pub token_file: Option, +} + +#[derive(Debug)] +pub enum ConfigError { + /// The config file exists but does not parse. Carries the path and + /// the parser's message — never config *values* beyond what the + /// parser itself reports. + Parse { path: PathBuf, message: String }, + /// The config file exists but cannot be read. + Read { path: PathBuf, message: String }, +} + +impl std::fmt::Display for ConfigError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ConfigError::Parse { path, message } => { + write!( + f, + "fleet: cannot parse config {}: {message}", + path.display() + ) + } + ConfigError::Read { path, message } => { + write!(f, "fleet: cannot read config {}: {message}", path.display()) + } + } + } +} + +impl std::error::Error for ConfigError {} + +fn home_dir() -> PathBuf { + std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(".")) +} + +fn resolve_under_home(path: &str) -> PathBuf { + let p = PathBuf::from(path); + if p.is_absolute() { + p + } else { + home_dir().join(p) + } +} + +impl Config { + /// The config file path: `$FLEET_CONFIG`, else + /// `${XDG_CONFIG_HOME:-~/.config}/fleet/fleet.toml`. + pub fn file_path() -> PathBuf { + if let Some(p) = std::env::var_os("FLEET_CONFIG") { + return PathBuf::from(p); + } + let base = std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| home_dir().join(".config")); + base.join("fleet").join("fleet.toml") + } + + /// Load configuration. A missing file yields defaults; a malformed + /// or unreadable file is an error (see the crate docs for why). + pub fn load() -> Result { + let path = Self::file_path(); + Self::load_from(&path) + } + + pub fn load_from(path: &std::path::Path) -> Result { + match std::fs::read_to_string(path) { + Ok(text) => toml::from_str(&text).map_err(|e| ConfigError::Parse { + path: path.to_path_buf(), + message: e.to_string(), + }), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()), + Err(e) => Err(ConfigError::Read { + path: path.to_path_buf(), + message: e.to_string(), + }), + } + } + + /// Is a domain enabled on this host? Default yes; `[domains]` + /// decides. Unknown names are enabled (the registry, not config, + /// decides what exists). + pub fn domain_enabled(&self, domain: &str) -> bool { + self.domains.get(domain).copied().unwrap_or(true) + } + + /// The session broker socket path. `FLEET_BROKER_SOCKET` beats the + /// config file beats the default. + pub fn broker_socket(&self) -> PathBuf { + if let Some(p) = std::env::var_os("FLEET_BROKER_SOCKET") { + return PathBuf::from(p); + } + match &self.proxy.broker_socket { + Some(p) => resolve_under_home(p), + None => resolve_under_home(DEFAULT_BROKER_SOCKET), + } + } + + pub fn idle_exit_secs(&self) -> u64 { + self.proxy.idle_exit_secs.unwrap_or(DEFAULT_IDLE_EXIT_SECS) + } + + /// The secrets-broker token *file path* (never its contents). + pub fn secrets_token_file(&self) -> PathBuf { + match &self.secrets.token_file { + Some(p) => resolve_under_home(p), + None => resolve_under_home(DEFAULT_SECRETS_TOKEN_FILE), + } + } + + /// `~/.local/state/fleet` (or `$XDG_STATE_HOME/fleet`). + pub fn state_dir() -> PathBuf { + let base = std::env::var_os("XDG_STATE_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| home_dir().join(".local").join("state")); + base.join("fleet") + } + + /// The materialized PATH shim dir (§4), regenerated from the + /// negotiated services map at every connect/init. + pub fn shims_dir() -> PathBuf { + Self::state_dir().join("shims") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write_temp(contents: &str) -> (tempfile_dir::Dir, PathBuf) { + let dir = tempfile_dir::Dir::new(); + let path = dir.path().join("fleet.toml"); + std::fs::write(&path, contents).unwrap(); + (dir, path) + } + + #[test] + fn missing_file_is_defaults() { + let cfg = Config::load_from(PathBuf::from("/nonexistent/fleet.toml").as_path()).unwrap(); + assert!(cfg.domain_enabled("queue")); + assert_eq!(cfg.idle_exit_secs(), DEFAULT_IDLE_EXIT_SECS); + } + + #[test] + fn domains_table_disables() { + let (_dir, path) = write_temp("[domains]\nqueue = false\n"); + let cfg = Config::load_from(&path).unwrap(); + assert!(!cfg.domain_enabled("queue")); + assert!(cfg.domain_enabled("search")); + } + + #[test] + fn malformed_file_is_a_loud_error() { + let (_dir, path) = write_temp("this is = = not toml [["); + match Config::load_from(&path) { + Err(ConfigError::Parse { .. }) => {} + other => panic!("expected Parse error, got {other:?}"), + } + } + + #[test] + fn proxy_settings_resolve() { + let (_dir, path) = + write_temp("[proxy]\nidle_exit_secs = 60\nbroker_socket = \"/tmp/b.sock\"\n"); + let cfg = Config::load_from(&path).unwrap(); + assert_eq!(cfg.idle_exit_secs(), 60); + assert_eq!(cfg.broker_socket(), PathBuf::from("/tmp/b.sock")); + } +} + +/// Minimal tempdir for tests (avoids a dev-dependency for one helper). +#[cfg(test)] +mod tempfile_dir { + use std::path::PathBuf; + + pub struct Dir(PathBuf); + + impl Dir { + pub fn new() -> Dir { + let mut p = std::env::temp_dir(); + p.push(format!( + "fleet-config-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + std::fs::create_dir_all(&p).unwrap(); + Dir(p) + } + + pub fn path(&self) -> &std::path::Path { + &self.0 + } + } + + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } +} diff --git a/pkgs/fleet/crates/fleet-proxy-proto/Cargo.toml b/pkgs/fleet/crates/fleet-proxy-proto/Cargo.toml new file mode 100644 index 0000000000..77887504df --- /dev/null +++ b/pkgs/fleet/crates/fleet-proxy-proto/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "fleet-proxy-proto" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The fleet proxy wire contract: length-prefixed JSON framing plus the hello/capability frame types. The contract lives here and nowhere else." + +[dependencies] +fleet-registry = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/pkgs/fleet/crates/fleet-proxy-proto/src/lib.rs b/pkgs/fleet/crates/fleet-proxy-proto/src/lib.rs new file mode 100644 index 0000000000..8b87a12056 --- /dev/null +++ b/pkgs/fleet/crates/fleet-proxy-proto/src/lib.rs @@ -0,0 +1,333 @@ +//! fleet-proxy-proto — the fleet proxy wire contract +//! (design note §4, epic developing-today/code#5412). +//! +//! Design rule, taken from atlas-proto's discipline: **the wire +//! contract lives here, is versioned from the first frame, and +//! outlives any variant's feature set.** Domain crates and the bin +//! speak these types; nothing redefines the framing elsewhere. +//! +//! Framing is today's proven shape, unchanged: a 4-byte big-endian +//! length prefix followed by one JSON object, both directions — the +//! exact framing the Python session broker runs. On top of it, the +//! first frame on every pooled connection is the hello exchange: +//! +//! ```text +//! client → { "hello": { "proto": 1, "client": "fleet-connect 0.1.0", +//! "capabilities": ["proxy-connect"] } } +//! broker → { "hello": { "proto": 1, +//! "services": { "4799": {"name":"laptop-agent","version":"…"}, … }, +//! "capabilities": ["proxy-serve"] } } +//! ``` +//! +//! The services map is the broker's **actual routing table**, not a +//! promise — capability negotiation *is* the services map. A client +//! must treat an unadvertised port as "not here" (the proxy-level +//! analogue of the exit-69 capability stub). +//! +//! Versioning policy: the integer is the protocol *major*; a broker +//! accepts majors N and N−1 (see [`broker_accepts`]); fields are +//! additive within a major and unknown fields are ignored. + +use std::collections::BTreeMap; +use std::io::{Read, Write}; + +use serde::{Deserialize, Serialize}; + +/// The current protocol major. +pub const PROTO_MAJOR: u32 = 1; + +/// How many majors back a broker accepts (the N/N−1 window, §4). +pub const PROTO_WINDOW: u32 = 1; + +/// Frame size ceiling. The broker's payloads are HTTP bodies for local +/// services; 64 MiB is generous headroom, and a ceiling turns a corrupt +/// length prefix into an error instead of an allocation. +pub const MAX_FRAME_BYTES: usize = 64 * 1024 * 1024; + +/// Does a broker speaking [`PROTO_MAJOR`] accept a client hello at +/// `client_major`? (§4: majors N and N−1; older gets a clean +/// `proto_too_old` error naming the minimum — the string a broker +/// sends is [`PROTO_TOO_OLD`].) +pub fn broker_accepts(client_major: u32) -> bool { + client_major <= PROTO_MAJOR && client_major + PROTO_WINDOW >= PROTO_MAJOR +} + +/// The minimum major this broker accepts. +pub fn min_accepted_major() -> u32 { + PROTO_MAJOR - PROTO_WINDOW +} + +/// Error kind a broker returns for an out-of-window hello. +pub const PROTO_TOO_OLD: &str = "proto_too_old"; + +/// The client's first frame payload: `{ "hello": Hello }`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Hello { + pub proto: u32, + /// Free-form client identity, e.g. `"fleet-connect 0.1.0"`. + pub client: String, + /// Capability ids (fleet-registry `Capability::id` strings). + pub capabilities: Vec, +} + +/// The broker's hello answer payload: `{ "hello": HelloResponse }`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HelloResponse { + pub proto: u32, + /// Port (as a string, JSON-object keys) → the service actually + /// routed there. This map is the routing table. + pub services: BTreeMap, + pub capabilities: Vec, +} + +/// One routed service in the hello map. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServiceInfo { + pub name: String, + /// Per-service version string, so a client can feature-detect a + /// broker capability instead of guessing from the fleet version. + pub version: String, +} + +/// A request frame after the hello (today's shape, unchanged): +/// `{method, path, body?, port?, token_file?}`. `port` selects the +/// laptop service (fleet-config's `PORT_*` constants); `token_file` +/// names the file whose contents the broker sends as `X-Agent-Token` +/// for that request — the file is read by the broker per request; the +/// token itself never appears in the frame beyond that name. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Request { + pub method: String, + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub port: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub token_file: Option, +} + +/// A response frame: `{status, body}` — the HTTP status and parsed +/// JSON body of the routed service's reply. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Response { + pub status: u16, + pub body: serde_json::Value, +} + +/// Frame-level errors. None of these ever carry payload contents — +/// proxy payloads can be secret-bearing (the secrets broker's +/// replies), so errors name shapes and sizes only. +#[derive(Debug)] +pub enum ProtoError { + Io(std::io::Error), + /// The peer closed the stream mid- or pre-frame. + Closed, + /// Length prefix above [`MAX_FRAME_BYTES`]. + Oversize(usize), + /// Frame was not valid JSON / not the expected shape. + BadFrame(String), +} + +impl std::fmt::Display for ProtoError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ProtoError::Io(e) => write!(f, "proxy transport: {e}"), + ProtoError::Closed => write!(f, "proxy transport: connection closed"), + ProtoError::Oversize(n) => { + write!( + f, + "proxy frame of {n} bytes exceeds the {MAX_FRAME_BYTES}-byte ceiling" + ) + } + ProtoError::BadFrame(why) => write!(f, "proxy frame malformed: {why}"), + } + } +} + +impl std::error::Error for ProtoError {} + +impl From for ProtoError { + fn from(e: std::io::Error) -> Self { + ProtoError::Io(e) + } +} + +/// Write one length-prefixed JSON frame. +pub fn write_frame(w: &mut W, value: &S) -> Result<(), ProtoError> { + let payload = serde_json::to_vec(value) + .map_err(|e| ProtoError::BadFrame(format!("cannot encode frame: {e}")))?; + if payload.len() > MAX_FRAME_BYTES { + return Err(ProtoError::Oversize(payload.len())); + } + let len = u32::try_from(payload.len()).map_err(|_| ProtoError::Oversize(payload.len()))?; + w.write_all(&len.to_be_bytes())?; + w.write_all(&payload)?; + w.flush()?; + Ok(()) +} + +/// Read one length-prefixed JSON frame as raw JSON. +pub fn read_frame(r: &mut R) -> Result { + let mut len_buf = [0u8; 4]; + match r.read_exact(&mut len_buf) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Err(ProtoError::Closed), + Err(e) => return Err(ProtoError::Io(e)), + } + let len = u32::from_be_bytes(len_buf) as usize; + if len > MAX_FRAME_BYTES { + return Err(ProtoError::Oversize(len)); + } + let mut payload = vec![0u8; len]; + r.read_exact(&mut payload).map_err(|e| { + if e.kind() == std::io::ErrorKind::UnexpectedEof { + ProtoError::Closed + } else { + ProtoError::Io(e) + } + })?; + serde_json::from_slice(&payload) + .map_err(|e| ProtoError::BadFrame(format!("frame is not valid JSON: {e}"))) +} + +/// Read one frame and decode it as `T`. +pub fn read_typed Deserialize<'de>>(r: &mut R) -> Result { + let value = read_frame(r)?; + serde_json::from_value(value) + .map_err(|e| ProtoError::BadFrame(format!("frame shape mismatch: {e}"))) +} + +/// Wrap a hello payload in its `{ "hello": … }` frame envelope. +pub fn hello_frame(hello: &Hello) -> serde_json::Value { + serde_json::json!({ "hello": hello }) +} + +/// Wrap a hello-response payload in its `{ "hello": … }` envelope. +pub fn hello_response_frame(resp: &HelloResponse) -> serde_json::Value { + serde_json::json!({ "hello": resp }) +} + +/// Unwrap a `{ "hello": … }` envelope. +pub fn unwrap_hello Deserialize<'de>>( + frame: &serde_json::Value, +) -> Result { + let inner = frame + .get("hello") + .ok_or_else(|| ProtoError::BadFrame("frame has no \"hello\" object".to_string()))?; + serde_json::from_value(inner.clone()) + .map_err(|e| ProtoError::BadFrame(format!("hello shape mismatch: {e}"))) +} + +/// The capability ids a hello advertises, from registry capabilities. +pub fn capability_ids(caps: &fleet_registry::CapabilitySet) -> Vec { + caps.iter().map(|c| c.id().to_string()).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + fn roundtrip Deserialize<'de> + PartialEq + std::fmt::Debug>( + value: &S, + ) -> S { + let mut buf = Vec::new(); + write_frame(&mut buf, value).unwrap(); + read_typed(&mut Cursor::new(buf)).unwrap() + } + + #[test] + fn hello_frame_shape_matches_the_design_note() { + let hello = Hello { + proto: 1, + client: "fleet-connect 0.1.0".to_string(), + capabilities: vec!["proxy-connect".to_string()], + }; + let frame = hello_frame(&hello); + assert_eq!(frame["hello"]["proto"], 1); + assert_eq!(frame["hello"]["client"], "fleet-connect 0.1.0"); + assert_eq!(frame["hello"]["capabilities"][0], "proxy-connect"); + let back: Hello = unwrap_hello(&frame).unwrap(); + assert_eq!(back, hello); + } + + #[test] + fn hello_response_carries_the_services_map() { + let mut services = BTreeMap::new(); + services.insert( + "4800".to_string(), + ServiceInfo { + name: "secrets-broker".to_string(), + version: "0.1.0".to_string(), + }, + ); + let resp = HelloResponse { + proto: 1, + services, + capabilities: vec!["proxy-serve".to_string()], + }; + let back: HelloResponse = unwrap_hello(&hello_response_frame(&resp)).unwrap(); + assert_eq!(back, resp); + assert_eq!(back.services["4800"].name, "secrets-broker"); + } + + #[test] + fn request_omits_absent_optional_fields() { + let req = Request { + method: "GET".to_string(), + path: "/health".to_string(), + body: None, + port: None, + token_file: None, + }; + let frame = serde_json::to_value(&req).unwrap(); + assert_eq!(frame["method"], "GET"); + assert!(frame.get("body").is_none()); + assert!(frame.get("port").is_none()); + assert!(frame.get("token_file").is_none()); + assert_eq!(roundtrip(&req), req); + } + + #[test] + fn framing_is_big_endian_length_prefixed() { + let mut buf = Vec::new(); + write_frame(&mut buf, &serde_json::json!({"a": 1})).unwrap(); + // {"a":1} is 7 bytes; the prefix must be 00 00 00 07. + assert_eq!(&buf[..4], &[0, 0, 0, 7]); + assert_eq!(&buf[4..], b"{\"a\":1}"); + } + + #[test] + fn response_roundtrip() { + let resp = Response { + status: 200, + body: serde_json::json!({"ok": true}), + }; + assert_eq!(roundtrip(&resp), resp); + } + + #[test] + fn major_window_is_n_and_n_minus_1() { + assert!(broker_accepts(PROTO_MAJOR)); + assert!(broker_accepts(PROTO_MAJOR - PROTO_WINDOW)); + if PROTO_MAJOR > PROTO_WINDOW { + // One major below the window is too old. (At PROTO_MAJOR 1 + // the window reaches 0, so no representable major is too + // old yet — the branch keeps the property tested as the + // major grows.) + assert!(!broker_accepts(PROTO_MAJOR - PROTO_WINDOW - 1)); + } + assert!(!broker_accepts(PROTO_MAJOR + 1)); + assert_eq!(min_accepted_major(), PROTO_MAJOR - PROTO_WINDOW); + } + + #[test] + fn closed_stream_is_a_clean_error() { + let mut empty = Cursor::new(Vec::new()); + match read_frame(&mut empty) { + Err(ProtoError::Closed) => {} + other => panic!("expected Closed, got {other:?}"), + } + } +} diff --git a/pkgs/fleet/crates/fleet-registry/Cargo.toml b/pkgs/fleet/crates/fleet-registry/Cargo.toml new file mode 100644 index 0000000000..bbf87f04c2 --- /dev/null +++ b/pkgs/fleet/crates/fleet-registry/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "fleet-registry" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The full fleet domain registry: names, one-line descriptions, argv0 aliases, capabilities and variant profiles. Std-only; compiled into every fleet variant." diff --git a/pkgs/fleet/crates/fleet-registry/src/lib.rs b/pkgs/fleet/crates/fleet-registry/src/lib.rs new file mode 100644 index 0000000000..59ef9b9e1c --- /dev/null +++ b/pkgs/fleet/crates/fleet-registry/src/lib.rs @@ -0,0 +1,385 @@ +//! fleet-registry — the full domain registry for the `fleet` multicall +//! binary (epic developing-today/code#5412, design note §2/§3). +//! +//! This crate is strings and tables only: std-only, no I/O. It is compiled +//! into **every** variant — including the tiny `fleet-connect` build — so +//! any artifact can name the whole fleet: render the full help surface with +//! `[not in this build]` marks, and answer an invocation of a domain it +//! does not contain with the capability stub (exit 69, §3) instead of a +//! parser error. +//! +//! Three different sets of capabilities are kept distinct here, because +//! the dispatch layer's correctness depends on never confusing them: +//! +//! * the **compiled** set — what a build's Cargo features put in the +//! artifact (supplied by the bin crate, which knows its `cfg`s); +//! * a **profile** — the capability ceiling a hyphenated variant name +//! (`fleet-serve`, `fleet-connect`) imposes at invocation time +//! (Refinement A: a name can only narrow, never widen); +//! * the **effective** set — compiled ∩ profile — the surface a given +//! invocation actually has. + +use std::collections::BTreeSet; +use std::fmt; + +/// One unit of surface a build can have or lack. Capabilities are the +/// atoms of feature selection (§2), of the stub's "Enabled capabilities" +/// list (§3), and of the proxy hello frame's capability list (§4). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Capability { + /// `fleet proxy connect` / `fleet proxy init` — the proxy client half. + ProxyConnect, + /// `fleet proxy serve` — the session broker. + ProxyServe, + /// `fleet queue …` — the repo-queue client surface. + Queue, + /// `fleet serve queue-broker` — the queue broker daemon role. + QueueBroker, + /// `fleet serve secrets-broker` — the secrets broker daemon role. + SecretsBroker, + /// `fleet search …` — atlas-search standalone/client surface. + Search, + /// `fleet serve search` — the atlas search service role. + SearchServe, + /// `fleet dispatch …` — thin client over pm-stack dispatch. + Dispatch, + /// `fleet laptop-agent …` — client for the (Python) laptop-agent daemon. + LaptopAgent, +} + +impl Capability { + /// The hyphenated id used in stub text, `fleet version`, `fleet + /// capabilities` JSON, and the proxy hello frame. + pub fn id(self) -> &'static str { + match self { + Capability::ProxyConnect => "proxy-connect", + Capability::ProxyServe => "proxy-serve", + Capability::Queue => "queue", + Capability::QueueBroker => "queue-broker", + Capability::SecretsBroker => "secrets-broker", + Capability::Search => "search", + Capability::SearchServe => "search-serve", + Capability::Dispatch => "dispatch", + Capability::LaptopAgent => "laptop-agent", + } + } + + /// Every capability, in registry order (the order help and version + /// output list them in). + pub const ALL: &'static [Capability] = &[ + Capability::ProxyConnect, + Capability::ProxyServe, + Capability::Queue, + Capability::QueueBroker, + Capability::SecretsBroker, + Capability::Search, + Capability::SearchServe, + Capability::Dispatch, + Capability::LaptopAgent, + ]; +} + +impl fmt::Display for Capability { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.id()) + } +} + +/// A set of capabilities. A `BTreeSet` so every rendering (stub text, +/// version, JSON) is deterministic. +pub type CapabilitySet = BTreeSet; + +pub fn capability_set(caps: &[Capability]) -> CapabilitySet { + caps.iter().copied().collect() +} + +/// The `fleet` (full) build: every domain compiled in (§2). +pub fn full_capabilities() -> CapabilitySet { + Capability::ALL.iter().copied().collect() +} + +/// The `fleet-serve` build: daemon roles + proxy, no working-seat clients +/// (§2: registry, config, secrets, proxy serve+connect, queue brokers, +/// search serve only). +pub fn serve_capabilities() -> CapabilitySet { + capability_set(&[ + Capability::ProxyConnect, + Capability::ProxyServe, + Capability::QueueBroker, + Capability::SecretsBroker, + Capability::SearchServe, + ]) +} + +/// The `fleet-connect` build: the proxy client and nothing else (§2). +pub fn connect_capabilities() -> CapabilitySet { + capability_set(&[Capability::ProxyConnect]) +} + +/// A shipped build variant (§2). The variant is a property of the +/// artifact; the same names double as invocation profiles (Refinement A). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Variant { + Full, + Serve, + Connect, +} + +impl Variant { + /// The name the variant is installed under where several variants sit + /// side by side (package/attr level — §2, Refinement A). Wherever a + /// variant is actually used it is renamed plain `fleet`. + pub fn name(self) -> &'static str { + match self { + Variant::Full => "fleet", + Variant::Serve => "fleet-serve", + Variant::Connect => "fleet-connect", + } + } + + /// The capabilities this variant compiles in — also the profile + /// ceiling when the name is used at invocation time. + pub fn capabilities(self) -> CapabilitySet { + match self { + Variant::Full => full_capabilities(), + Variant::Serve => serve_capabilities(), + Variant::Connect => connect_capabilities(), + } + } + + /// The variant a hyphenated invocation name selects, if any. + /// Plain `fleet` selects no profile (the build's full surface). + pub fn from_invocation_name(name: &str) -> Option { + match name { + "fleet-serve" => Some(Variant::Serve), + "fleet-connect" => Some(Variant::Connect), + _ => None, + } + } +} + +/// One fleet domain: the unit help lists, stubs name, and config disables. +#[derive(Debug, Clone, Copy)] +pub struct Domain { + /// Canonical subcommand name (`fleet …`). + pub name: &'static str, + /// One-line description for help and the registry JSON. + pub summary: &'static str, + /// Capabilities that make up this domain's surface. Headline + /// availability (help marks, domain stubs) keys on `primary` below; + /// individual subcommands and daemon roles gate on their specific + /// capability from this list. + pub capabilities: &'static [Capability], + /// The capability the domain's headline surface needs. Stubs and + /// `[not in this build]` marks key on this: on `fleet-serve`, the + /// `search` domain is marked absent because its headline surface is + /// the standalone client, even though `search-serve` exists under + /// `serve`. + pub primary: Capability, + /// argv0 names that route to this domain (§3 argv0 map). + pub aliases: &'static [&'static str], + /// Subcommand names, for domain help. Descriptive only in step 1. + pub subcommands: &'static [&'static str], +} + +impl Domain { + /// Is this domain's headline surface in the given capability set? + pub fn available_in(&self, caps: &CapabilitySet) -> bool { + caps.contains(&self.primary) + } +} + +/// The full registry, in help order. Every variant renders all of it. +pub const DOMAINS: &[Domain] = &[ + Domain { + name: "queue", + summary: "Repo work queue: enqueue, claim, and complete tasks through the queue broker.", + capabilities: &[Capability::Queue], + primary: Capability::Queue, + aliases: &["repo-queue"], + subcommands: &[ + "validate", + "list", + "enqueue", + "claim", + "lane", + "bind", + "heartbeat", + "checkpoint", + "park", + "block", + "cancel", + "fail", + "complete", + "health", + "signal", + ], + }, + Domain { + name: "serve", + summary: "Run a fleet daemon role (queue-broker, secrets-broker, search) in the foreground.", + capabilities: &[ + Capability::QueueBroker, + Capability::SecretsBroker, + Capability::SearchServe, + ], + primary: Capability::QueueBroker, + aliases: &["queue-broker", "secrets-broker"], + subcommands: &["queue-broker", "secrets-broker", "search"], + }, + Domain { + name: "proxy", + summary: "The session proxy: serve the broker socket, or connect and init a client through it.", + capabilities: &[Capability::ProxyServe, Capability::ProxyConnect], + primary: Capability::ProxyConnect, + aliases: &["laptop-agent-broker"], + subcommands: &["serve", "connect", "init"], + }, + Domain { + name: "dispatch", + summary: "Thin client over the pm-stack dispatch services (status and launch verbs).", + capabilities: &[Capability::Dispatch], + primary: Capability::Dispatch, + aliases: &[], + subcommands: &["status", "launch"], + }, + Domain { + name: "search", + summary: "Atlas corpus search over the session history (Snowflake hybrid, via atlas-search).", + capabilities: &[Capability::Search], + primary: Capability::Search, + aliases: &["atlas-search"], + subcommands: &["search", "get-chunk"], + }, + Domain { + name: "laptop-agent", + summary: "Client for the laptop-agent daemon: run and manage jobs on the laptop.", + capabilities: &[Capability::LaptopAgent], + primary: Capability::LaptopAgent, + aliases: &["laptop-agent"], + subcommands: &["run", "status", "poll", "kill"], + }, +]; + +/// Look a domain up by canonical name. +pub fn domain(name: &str) -> Option<&'static Domain> { + DOMAINS.iter().find(|d| d.name == name) +} + +/// Where an argv0 alias routes: the domain, plus a fixed first argument +/// the alias implies (e.g. `queue-broker` means `serve queue-broker`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AliasRoute { + pub domain: &'static str, + pub implied_arg: Option<&'static str>, +} + +/// The §3 argv0 map. Aliases not listed here are not multicall names. +pub fn alias_route(argv0: &str) -> Option { + match argv0 { + "repo-queue" => Some(AliasRoute { + domain: "queue", + implied_arg: None, + }), + "queue-broker" => Some(AliasRoute { + domain: "serve", + implied_arg: Some("queue-broker"), + }), + "secrets-broker" => Some(AliasRoute { + domain: "serve", + implied_arg: Some("secrets-broker"), + }), + "laptop-agent-broker" => Some(AliasRoute { + domain: "proxy", + implied_arg: Some("serve"), + }), + "atlas-search" => Some(AliasRoute { + domain: "search", + implied_arg: None, + }), + "laptop-agent" => Some(AliasRoute { + domain: "laptop-agent", + implied_arg: None, + }), + _ => None, + } +} + +/// Every argv0 name the multicall dispatch recognizes, including `fleet` +/// itself and the hyphenated variant names. +pub fn is_known_invocation_name(name: &str) -> bool { + name == "fleet" || Variant::from_invocation_name(name).is_some() || alias_route(name).is_some() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn capability_ids_are_unique_and_stable() { + let mut ids: Vec<&str> = Capability::ALL.iter().map(|c| c.id()).collect(); + let count = ids.len(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), count, "capability ids must be unique"); + assert!(ids.contains(&"proxy-connect")); + assert!(ids.contains(&"queue")); + } + + #[test] + fn variant_profiles_nest() { + // connect ⊂ serve ⊂ full — names narrow, profiles must too. + let full = full_capabilities(); + let serve = serve_capabilities(); + let connect = connect_capabilities(); + assert!(connect.is_subset(&serve)); + assert!(serve.is_subset(&full)); + assert_eq!(full.len(), Capability::ALL.len()); + } + + #[test] + fn every_domain_primary_is_in_its_surface() { + for d in DOMAINS { + assert!( + d.capabilities.contains(&d.primary), + "domain {} primary {:?} not in its capabilities", + d.name, + d.primary + ); + } + } + + #[test] + fn aliases_route_to_real_domains() { + for name in [ + "repo-queue", + "queue-broker", + "secrets-broker", + "laptop-agent-broker", + "atlas-search", + "laptop-agent", + ] { + let route = alias_route(name).unwrap_or_else(|| panic!("alias {name} must route")); + assert!( + domain(route.domain).is_some(), + "alias {name} routes to unknown domain {}", + route.domain + ); + } + assert!(alias_route("fleet").is_none()); + assert!(alias_route("bogus").is_none()); + } + + #[test] + fn domain_aliases_match_the_argv0_map() { + // The per-domain alias lists (rendered in help) and the routing + // table are two views of one fact; keep them in lockstep. + for d in DOMAINS { + for alias in d.aliases { + let route = alias_route(alias) + .unwrap_or_else(|| panic!("domain {} alias {alias} does not route", d.name)); + assert_eq!(route.domain, d.name, "alias {alias} routes elsewhere"); + } + } + } +} diff --git a/pkgs/fleet/crates/fleet-secrets/Cargo.toml b/pkgs/fleet/crates/fleet-secrets/Cargo.toml new file mode 100644 index 0000000000..649e80b5a7 --- /dev/null +++ b/pkgs/fleet/crates/fleet-secrets/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "fleet-secrets" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The one secrets-by-name path for fleet: secrets-broker protocol first, bws CLI fallback. Values are never stored, never logged, and redacted in Debug." + +[dependencies] +fleet-config = { workspace = true } +fleet-proxy-proto = { workspace = true } +serde_json = { workspace = true } diff --git a/pkgs/fleet/crates/fleet-secrets/src/lib.rs b/pkgs/fleet/crates/fleet-secrets/src/lib.rs new file mode 100644 index 0000000000..bf3a4b3385 --- /dev/null +++ b/pkgs/fleet/crates/fleet-secrets/src/lib.rs @@ -0,0 +1,518 @@ +//! fleet-secrets — the one secrets-by-name path for fleet +//! (design note §1, epic developing-today/code#5412). +//! +//! Platform rule, carried over from the brokers' lessons: **secrets are +//! resolved by name through this crate only.** No domain shells out to +//! `bws` or reads a token file on its own. Resolution order: +//! +//! 1. the **secrets-broker protocol** — a framed request through the +//! session broker to port 4800, `GET /secret/`, with the +//! token *file* named in the request (the session broker reads it +//! per request and sends `X-Agent-Token`; fleet never opens it); +//! 2. the **`bws` CLI fallback** — `bws secret list` + `get`, the +//! same shape the secrets broker itself uses to fill its cache. +//! +//! Discipline, enforced by the types below: +//! * a resolved value lives in [`SecretValue`], whose `Debug` is +//! redacted and which exposes the string only through `expose()`; +//! * errors name the secret's *name*, the source, and status codes — +//! never a value, never a subprocess's stderr (which could quote +//! vault material); +//! * nothing here persists a value: no cache, no file, no log line. + +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::process::Command; + +use fleet_proxy_proto::{Request, Response}; + +/// A resolved secret value. Construct only from a source; the inner +/// string is reachable only via [`SecretValue::expose`]. +pub struct SecretValue(String); + +impl SecretValue { + pub fn expose(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Debug for SecretValue { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("SecretValue(***)") + } +} + +/// Resolution failures. Deliberately value-free (see crate docs). +#[derive(Debug)] +pub enum SecretError { + /// The name itself is not usable (it becomes a URL path segment, + /// so separators and controls are rejected before any I/O). + InvalidName(String), + /// The source answered: no secret by that name. + NotFound { source: &'static str, name: String }, + /// The source could not answer (transport down, bad status, + /// subprocess failed). `detail` carries status codes and error + /// kinds only — never payload or stderr content. + Unavailable { + source: &'static str, + name: String, + detail: String, + }, + /// Every source in the chain failed; carries each source's error. + Chain { + name: String, + errors: Vec, + }, +} + +impl std::fmt::Display for SecretError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + SecretError::InvalidName(name) => { + write!( + f, + "invalid secret name {name:?}: names may not contain '/', '?', '#', whitespace, or control characters" + ) + } + SecretError::NotFound { source, name } => { + write!(f, "secret {name:?} not found via {source}") + } + SecretError::Unavailable { + source, + name, + detail, + } => write!(f, "secret {name:?} unavailable via {source}: {detail}"), + SecretError::Chain { name, errors } => { + write!( + f, + "secret {name:?} unresolved: {} source(s) failed", + errors.len() + )?; + for e in errors { + write!(f, "; {e}")?; + } + Ok(()) + } + } + } +} + +impl std::error::Error for SecretError {} + +/// Names become URL path segments (`GET /secret/`); validate +/// before any source sees them. +pub fn validate_name(name: &str) -> Result<(), SecretError> { + if name.is_empty() + || name + .chars() + .any(|c| c == '/' || c == '?' || c == '#' || c.is_whitespace() || c.is_control()) + { + return Err(SecretError::InvalidName(name.to_string())); + } + Ok(()) +} + +/// One way to resolve a name. Sources are tried in chain order. +pub trait SecretSource { + /// Stable source name for error messages ("secrets-broker", "bws"). + fn source_name(&self) -> &'static str; + fn resolve(&self, name: &str) -> Result; +} + +/// The ordered chain: broker protocol first, `bws` fallback (§1). +pub struct Resolver { + sources: Vec>, +} + +impl Resolver { + pub fn new(sources: Vec>) -> Resolver { + Resolver { sources } + } + + /// The default chain for a resolved fleet config. + pub fn default_chain(config: &fleet_config::Config) -> Resolver { + Resolver::new(vec![ + Box::new(BrokerSource { + broker_socket: config.broker_socket(), + token_file: config.secrets_token_file(), + }), + Box::new(BwsSource::new()), + ]) + } + + pub fn resolve(&self, name: &str) -> Result { + validate_name(name)?; + let mut errors = Vec::new(); + for source in &self.sources { + match source.resolve(name) { + Ok(value) => return Ok(value), + Err(e) => errors.push(e), + } + } + Err(SecretError::Chain { + name: name.to_string(), + errors, + }) + } +} + +/// Source 1: the secrets-broker protocol, through the session broker. +/// The exchange is one framed [`Request`] / [`Response`] pair over the +/// session broker's Unix socket — the same path every sandbox client +/// uses today. +pub struct BrokerSource { + pub broker_socket: PathBuf, + /// Path of the token file the session broker reads per request. + /// fleet names it in the request and never opens it. + pub token_file: PathBuf, +} + +impl BrokerSource { + /// One framed exchange over an already-connected session-broker + /// stream. Split from `resolve` so tests can drive it over a + /// socket pair. + fn exchange( + &self, + stream: &mut UnixStream, + request: &Request, + name: &str, + ) -> Result { + let unavailable = |detail: String| SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail, + }; + fleet_proxy_proto::write_frame(stream, request).map_err(|e| unavailable(e.to_string()))?; + let response: Response = + fleet_proxy_proto::read_typed(stream).map_err(|e| unavailable(e.to_string()))?; + Ok(response) + } + + fn connect(&self, name: &str) -> Result { + UnixStream::connect(&self.broker_socket).map_err(|e| SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: format!( + "session broker socket {}: {}", + self.broker_socket.display(), + e.kind() + ), + }) + } +} + +impl SecretSource for BrokerSource { + fn source_name(&self) -> &'static str { + "secrets-broker" + } + + fn resolve(&self, name: &str) -> Result { + validate_name(name)?; + let request = Request { + method: "GET".to_string(), + path: format!("/secret/{name}"), + body: None, + port: Some(fleet_config::PORT_SECRETS_BROKER), + token_file: Some(self.token_file.to_string_lossy().into_owned()), + }; + let mut stream = self.connect(name)?; + let response = self.exchange(&mut stream, &request, name)?; + match response.status { + 200 => { + let value = response + .body + .get("value") + .and_then(|v| v.as_str()) + .ok_or_else(|| SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: "200 response without a string \"value\" field".to_string(), + })?; + Ok(SecretValue(value.to_string())) + } + 404 => Err(SecretError::NotFound { + source: "secrets-broker", + name: name.to_string(), + }), + status => Err(SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: format!("secrets-broker answered HTTP {status}"), + }), + } + } +} + +/// Runs external commands for the `bws` fallback. Injectable so tests +/// never spawn a real `bws` (and never see a real value). +pub trait CommandRunner { + /// Run `program args`, returning stdout on success. Error details + /// carry the exit status only — stderr is deliberately not captured + /// into errors (it could quote vault material). + fn run(&self, program: &str, args: &[&str]) -> Result; +} + +pub struct ProcessRunner; + +impl CommandRunner for ProcessRunner { + fn run(&self, program: &str, args: &[&str]) -> Result { + let out = Command::new(program) + .args(args) + .output() + .map_err(|e| format!("spawn failed: {}", e.kind()))?; + if !out.status.success() { + return Err(format!("exit status {}", out.status)); + } + String::from_utf8(out.stdout).map_err(|_| "output not utf8".to_string()) + } +} + +/// Source 2: the `bws` CLI fallback — `bws secret list` to find the +/// id for a name, then `bws secret get `, exactly the shape the +/// secrets broker's own cache refresh uses. +pub struct BwsSource { + runner: Box, +} + +impl BwsSource { + pub fn new() -> BwsSource { + BwsSource { + runner: Box::new(ProcessRunner), + } + } + + pub fn with_runner(runner: Box) -> BwsSource { + BwsSource { runner } + } +} + +impl Default for BwsSource { + fn default() -> Self { + Self::new() + } +} + +impl SecretSource for BwsSource { + fn source_name(&self) -> &'static str { + "bws" + } + + fn resolve(&self, name: &str) -> Result { + validate_name(name)?; + let unavailable = |detail: String| SecretError::Unavailable { + source: "bws", + name: name.to_string(), + detail, + }; + let list_raw = self + .runner + .run("bws", &["secret", "list", "-o", "json"]) + .map_err(|d| unavailable(format!("bws secret list: {d}")))?; + let list: serde_json::Value = serde_json::from_str(&list_raw) + .map_err(|_| unavailable("bws secret list: output is not JSON".to_string()))?; + let id = list + .as_array() + .and_then(|items| { + items.iter().find_map(|item| { + if item.get("key").and_then(|k| k.as_str()) == Some(name) { + item.get("id").and_then(|i| i.as_str()).map(str::to_string) + } else { + None + } + }) + }) + .ok_or_else(|| SecretError::NotFound { + source: "bws", + name: name.to_string(), + })?; + let got_raw = self + .runner + .run("bws", &["secret", "get", &id, "-o", "json"]) + .map_err(|d| unavailable(format!("bws secret get: {d}")))?; + let got: serde_json::Value = serde_json::from_str(&got_raw) + .map_err(|_| unavailable("bws secret get: output is not JSON".to_string()))?; + let value = got + .get("value") + .and_then(|v| v.as_str()) + .ok_or_else(|| unavailable("bws secret get: no string \"value\" field".to_string()))?; + Ok(SecretValue(value.to_string())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct FakeSource { + name: &'static str, + result: Result, + } + + impl SecretSource for FakeSource { + fn source_name(&self) -> &'static str { + self.name + } + fn resolve(&self, _name: &str) -> Result { + match &self.result { + Ok(v) => Ok(SecretValue(v.clone())), + Err(_) => Err(SecretError::Unavailable { + source: self.name, + name: "x".to_string(), + detail: "down".to_string(), + }), + } + } + } + + #[test] + fn chain_tries_sources_in_order() { + let resolver = Resolver::new(vec![ + Box::new(FakeSource { + name: "secrets-broker", + result: Err(SecretError::Unavailable { + source: "secrets-broker", + name: "x".into(), + detail: "down".into(), + }), + }), + Box::new(FakeSource { + name: "bws", + result: Ok("fixture-value-not-a-secret".to_string()), + }), + ]); + let v = resolver.resolve("some.name").unwrap(); + assert_eq!(v.expose(), "fixture-value-not-a-secret"); + } + + #[test] + fn chain_reports_all_failures_without_values() { + let resolver = Resolver::new(vec![Box::new(FakeSource { + name: "bws", + result: Err(SecretError::Unavailable { + source: "bws", + name: "x".into(), + detail: "down".into(), + }), + })]); + let err = resolver.resolve("some.name").unwrap_err(); + let text = format!("{err}"); + assert!(text.contains("some.name"), "error names the secret: {text}"); + assert!( + !text.contains("fixture"), + "error must not carry values: {text}" + ); + } + + #[test] + fn debug_is_redacted() { + let v = SecretValue("fixture-value-not-a-secret".to_string()); + let text = format!("{v:?}"); + assert_eq!(text, "SecretValue(***)"); + } + + #[test] + fn name_validation_rejects_path_material() { + for bad in ["", "a/b", "a?b", "a#b", "a b", "a\tb", "a\u{7}b"] { + assert!(validate_name(bad).is_err(), "name {bad:?} must be rejected"); + } + for good in [ + "supabase.service-role-key", + "openclaw.gateway-token", + "a.b-c_d", + ] { + assert!(validate_name(good).is_ok(), "name {good:?} must pass"); + } + } + + struct FakeRunner { + list: String, + get: String, + } + + impl CommandRunner for FakeRunner { + fn run(&self, program: &str, args: &[&str]) -> Result { + assert_eq!(program, "bws"); + match args { + ["secret", "list", "-o", "json"] => Ok(self.list.clone()), + ["secret", "get", _, "-o", "json"] => Ok(self.get.clone()), + other => Err(format!("unexpected args: {other:?}")), + } + } + } + + #[test] + fn bws_fallback_lists_then_gets_by_name() { + let source = BwsSource::with_runner(Box::new(FakeRunner { + list: r#"[{"id":"id-1","key":"wanted.name"},{"id":"id-2","key":"other.name"}]"# + .to_string(), + get: r#"{"id":"id-1","key":"wanted.name","value":"fixture-value-not-a-secret"}"# + .to_string(), + })); + let v = source.resolve("wanted.name").unwrap(); + assert_eq!(v.expose(), "fixture-value-not-a-secret"); + match source.resolve("absent.name") { + Err(SecretError::NotFound { source, .. }) => assert_eq!(source, "bws"), + other => panic!("expected NotFound, got {other:?}"), + } + } + + #[test] + fn broker_source_roundtrip_over_a_socket_pair() { + // A real Unix socket pair with a scripted broker end: proves + // BrokerSource's framed exchange + status mapping (200, 404) + // without any live service or real secret. + use std::os::unix::net::UnixStream as Pair; + use std::path::PathBuf; + + fn scripted_broker( + status: u16, + body: serde_json::Value, + ) -> (BrokerSource, std::thread::JoinHandle<()>, Pair) { + let (client, mut server) = Pair::pair().unwrap(); + let handle = std::thread::spawn(move || { + let req: Request = fleet_proxy_proto::read_typed(&mut server).unwrap(); + assert_eq!(req.method, "GET"); + assert_eq!(req.path, "/secret/wanted.name"); + assert_eq!(req.port, Some(fleet_config::PORT_SECRETS_BROKER)); + assert_eq!(req.token_file.as_deref(), Some("/nonexistent/token")); + let resp = Response { status, body }; + fleet_proxy_proto::write_frame(&mut server, &resp).unwrap(); + }); + let source = BrokerSource { + broker_socket: PathBuf::from("/nonexistent/broker.sock"), + token_file: PathBuf::from("/nonexistent/token"), + }; + (source, handle, client) + } + + // 200 -> value + let (source, handle, mut client) = scripted_broker( + 200, + serde_json::json!({"key": "wanted.name", "value": "fixture-value-not-a-secret"}), + ); + let request = Request { + method: "GET".to_string(), + path: "/secret/wanted.name".to_string(), + body: None, + port: Some(fleet_config::PORT_SECRETS_BROKER), + token_file: Some("/nonexistent/token".to_string()), + }; + let resp = source + .exchange(&mut client, &request, "wanted.name") + .unwrap(); + assert_eq!(resp.status, 200); + assert_eq!(resp.body["value"], "fixture-value-not-a-secret"); + handle.join().unwrap(); + + // The resolve() status mapping, exercised against exchange() + // results by shape: 404 maps to NotFound in resolve; here we + // assert the raw status the mapping consumes. + let (source, handle, mut client) = + scripted_broker(404, serde_json::json!({"error": "not found"})); + let resp = source + .exchange(&mut client, &request, "wanted.name") + .unwrap(); + assert_eq!(resp.status, 404); + handle.join().unwrap(); + } +} diff --git a/pkgs/fleet/crates/fleet/Cargo.toml b/pkgs/fleet/crates/fleet/Cargo.toml new file mode 100644 index 0000000000..c6a125b3c6 --- /dev/null +++ b/pkgs/fleet/crates/fleet/Cargo.toml @@ -0,0 +1,48 @@ +[package] +name = "fleet" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "One multicall binary for the fleet's tools: search, queue, dispatch, proxy — with compile-time capability-selected variants (epic developing-today/code#5412)." + +[[bin]] +name = "fleet" +path = "src/main.rs" + +[dependencies] +fleet-registry = { workspace = true } +fleet-config = { workspace = true } +fleet-proxy-proto = { workspace = true } +# fleet-secrets is linked only by builds whose domains resolve secrets; +# the connect variant must not carry it (§2: "nothing else"). +fleet-secrets = { workspace = true, optional = true } +serde_json = { workspace = true } + +# Capability features (§2). The shipped variants are feature sets: +# fleet = default (full) +# fleet-serve = --no-default-features --features serve +# fleet-connect = --no-default-features (base only: proxy-connect) +# proxy-connect is not a feature: it is compiled into every variant. +[features] +default = ["full"] +full = [ + "proxy-serve", + "queue", + "queue-broker", + "secrets-broker", + "search", + "search-serve", + "dispatch", + "laptop-agent", +] +# The serve variant's set, as one feature for the nix build. +serve = ["proxy-serve", "queue-broker", "secrets-broker", "search-serve"] +proxy-serve = [] +queue = ["dep:fleet-secrets"] +queue-broker = ["dep:fleet-secrets"] +secrets-broker = ["dep:fleet-secrets"] +search = ["dep:fleet-secrets"] +search-serve = ["dep:fleet-secrets"] +dispatch = ["dep:fleet-secrets"] +laptop-agent = ["dep:fleet-secrets"] diff --git a/pkgs/fleet/crates/fleet/build.rs b/pkgs/fleet/crates/fleet/build.rs new file mode 100644 index 0000000000..fedfa56d37 --- /dev/null +++ b/pkgs/fleet/crates/fleet/build.rs @@ -0,0 +1,30 @@ +//! Bake the source revision into the binary for `fleet version`. +//! +//! Resolution: `$FLEET_SOURCE_REV` (the nix build passes the flake's +//! rev) → `git rev-parse` in the repo root (developer builds) → +//! "unknown". The nix sandbox has no `.git`, so without the env var a +//! packaged build honestly reports "unknown" rather than inventing one. + +use std::process::Command; + +fn main() { + println!("cargo:rerun-if-env-changed=FLEET_SOURCE_REV"); + let rev = std::env::var("FLEET_SOURCE_REV") + .ok() + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| { + let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default(); + let root = std::path::Path::new(&manifest).join("../../.."); + Command::new("git") + .args(["rev-parse", "--short=12", "HEAD"]) + .current_dir(root) + .output() + .ok() + .filter(|o| o.status.success()) + .and_then(|o| String::from_utf8(o.stdout).ok()) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "unknown".to_string()) + }); + println!("cargo:rustc-env=FLEET_SOURCE_REV={rev}"); +} diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs new file mode 100644 index 0000000000..2db489cd6c --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -0,0 +1,534 @@ +//! fleet — one multicall binary for the fleet's tools +//! (epic developing-today/code#5412; design note +//! doc/2026-11-04T11-45-48Z_design_fleet_multicall_binary/). +//! +//! Step 1 (#5429) is the skeleton: the platform crates, this dispatch +//! layer, the capability-stub machinery, and the variant builds. No +//! domain is implemented yet — a compiled-in domain answers with the +//! "not implemented yet" form of the stub — but the *surface* is +//! complete and honest: every variant renders the full registry, and +//! every missing capability answers with a branchable stub, never a +//! parser error. +//! +//! Dispatch order (§3), extended by Refinement A (name-scoping): +//! +//! argv0 alias → domain route +//! argv0 variant name (`fleet-serve`/`fleet-connect`) → root dispatch +//! with that profile as a capability ceiling (narrow, never widen) +//! argv0 `fleet` → root dispatch +//! domain → capability compiled in? in profile? not config-disabled? +//! → domain (step 1: the not-implemented stub) : capability stub +//! unknown name → usage error, exit 2 +//! +//! Exit codes: 0 ok · 2 usage/unknown (clap's code) · **69** +//! `EX_UNAVAILABLE` for every capability stub (D3) — "not here", with +//! the text saying why: not in this build, narrowed out by this name, +//! disabled by config, or not implemented yet. +//! +//! The top-level dispatch is hand-rolled rather than clap: it must +//! behave identically in every variant — including the tiny connect +//! build, where the full registry and the stub machinery are the +//! product — and multicall routing happens before any per-domain +//! parsing exists. Domains adopt their own parsers as they land. + +use fleet_registry::{ + Capability, CapabilitySet, Domain, Variant, alias_route, capability_set, domain, + is_known_invocation_name, +}; + +const VERSION: &str = env!("CARGO_PKG_VERSION"); +const SOURCE_REV: &str = env!("FLEET_SOURCE_REV"); + +const EXIT_OK: i32 = 0; +const EXIT_USAGE: i32 = 2; +/// D3: sysexits.h `EX_UNAVAILABLE` — "a service is unavailable", +/// precisely the semantics of a capability that is not in this artifact. +const EXIT_UNAVAILABLE: i32 = 69; + +/// The capabilities this artifact was compiled with (its Cargo feature +/// set). `proxy-connect` is unconditional: it is in every variant (§2). +fn compiled_capabilities() -> CapabilitySet { + let mut caps = capability_set(&[Capability::ProxyConnect]); + if cfg!(feature = "proxy-serve") { + caps.insert(Capability::ProxyServe); + } + if cfg!(feature = "queue") { + caps.insert(Capability::Queue); + } + if cfg!(feature = "queue-broker") { + caps.insert(Capability::QueueBroker); + } + if cfg!(feature = "secrets-broker") { + caps.insert(Capability::SecretsBroker); + } + if cfg!(feature = "search") { + caps.insert(Capability::Search); + } + if cfg!(feature = "search-serve") { + caps.insert(Capability::SearchServe); + } + if cfg!(feature = "dispatch") { + caps.insert(Capability::Dispatch); + } + if cfg!(feature = "laptop-agent") { + caps.insert(Capability::LaptopAgent); + } + caps +} + +/// The shipped variant this artifact's feature set corresponds to. +fn build_variant(compiled: &CapabilitySet) -> Option { + if *compiled == Variant::Full.capabilities() { + Some(Variant::Full) + } else if *compiled == Variant::Serve.capabilities() { + Some(Variant::Serve) + } else if *compiled == Variant::Connect.capabilities() { + Some(Variant::Connect) + } else { + None + } +} + +fn build_name(compiled: &CapabilitySet) -> String { + match build_variant(compiled) { + Some(v) => v.name().to_string(), + None => "fleet-custom".to_string(), + } +} + +/// Why a capability is not usable by this invocation, in check order. +#[derive(Debug, Clone, PartialEq, Eq)] +enum CapState { + Available, + NotInBuild, + NarrowedByName, + DisabledByConfig, +} + +/// The invocation's whole surface: what was compiled, what the name +/// allows, what config disables. +struct Surface { + compiled: CapabilitySet, + profile: Option, + effective: CapabilitySet, + config: fleet_config::Config, +} + +impl Surface { + fn new(profile: Option, config: fleet_config::Config) -> Surface { + let compiled = compiled_capabilities(); + let effective = match profile { + Some(v) => compiled.intersection(&v.capabilities()).copied().collect(), + None => compiled.clone(), + }; + Surface { + compiled, + profile, + effective, + config, + } + } + + fn cap_state(&self, cap: Capability, domain_name: &str) -> CapState { + if !self.compiled.contains(&cap) { + CapState::NotInBuild + } else if !self.effective.contains(&cap) { + CapState::NarrowedByName + } else if !self.config.domain_enabled(domain_name) { + CapState::DisabledByConfig + } else { + CapState::Available + } + } + + fn domain_state(&self, d: &Domain) -> CapState { + self.cap_state(d.primary, d.name) + } + + /// Capabilities this invocation can actually use: effective, minus + /// the surfaces of config-disabled domains. + fn usable(&self) -> CapabilitySet { + let mut set = self.effective.clone(); + for d in fleet_registry::DOMAINS { + if !self.config.domain_enabled(d.name) { + for cap in d.capabilities { + set.remove(cap); + } + } + } + set + } +} + +fn format_caps(caps: &CapabilitySet) -> String { + if caps.is_empty() { + return "none".to_string(); + } + caps.iter().map(|c| c.id()).collect::>().join(", ") +} + +/// The §3 stub block, one form per reason. Always to stderr, always +/// exit 69; the first line names the domain and the reason class, the +/// second lists what this invocation *can* do. +fn stub(surface: &Surface, domain_name: &str, state: &CapState, invoked_as: &str) -> i32 { + let build = build_name(&surface.compiled); + let caps = format_caps(&surface.usable()); + let mut out = String::new(); + match state { + CapState::NotInBuild => { + out.push_str(&format!( + "fleet: this build does not include '{domain_name}'.\n" + )); + out.push_str(&format!("Enabled capabilities: {caps}.\n")); + out.push_str(&format!("This is the {build} build ({VERSION}).")); + if build != "fleet" { + out.push_str(" The full build is 'fleet'."); + } + out.push('\n'); + } + CapState::NarrowedByName => { + let profile = surface.profile.map(|v| v.name()).unwrap_or("fleet-connect"); + out.push_str(&format!( + "fleet: invoked as '{invoked_as}', this build does not include '{domain_name}'.\n" + )); + out.push_str(&format!("Enabled capabilities: {caps}.\n")); + out.push_str(&format!( + "This is the {build} build ({VERSION}), name-scoped to the {profile} profile. \ + Invoked as 'fleet' it carries the full surface.\n" + )); + } + CapState::DisabledByConfig => { + out.push_str(&format!( + "fleet: '{domain_name}' is disabled by config on this host.\n" + )); + out.push_str(&format!("Enabled capabilities: {caps}.\n")); + out.push_str(&format!( + "This is the {build} build ({VERSION}). Re-enable '{domain_name}' under [domains] in {}.\n", + fleet_config::Config::file_path().display() + )); + } + CapState::Available => { + // The step-1 form: compiled in, nothing behind it yet. + out.push_str(&format!( + "fleet: '{domain_name}' is included in this build but not implemented yet.\n" + )); + out.push_str(&format!("Enabled capabilities: {caps}.\n")); + out.push_str(&format!( + "This is the {build} build ({VERSION}) — the step-1 skeleton of epic #5412; \ + the '{domain_name}' domain lands in a later step.\n" + )); + } + } + eprint!("{out}"); + EXIT_UNAVAILABLE +} + +/// `fleet version` — the surface the census found missing (§1): +/// workspace version + enabled capability list + source rev. +fn print_version(surface: &Surface, invoked_as: &str) { + let build = build_name(&surface.compiled); + println!("fleet {VERSION}"); + match surface.profile { + Some(v) => println!( + "Build: {build} (invoked as {invoked_as}; surface narrowed to the {} profile)", + v.name() + ), + None => println!("Build: {build}"), + } + println!("Source rev: {SOURCE_REV}"); + println!("Enabled capabilities: {}", format_caps(&surface.usable())); +} + +/// `fleet capabilities` — the registry as JSON, for agents. +fn print_capabilities(surface: &Surface, invoked_as: &str) { + let build = build_name(&surface.compiled); + let domains: Vec = fleet_registry::DOMAINS + .iter() + .map(|d| { + let state = match surface.domain_state(d) { + CapState::Available => "available", + CapState::NotInBuild => "not-in-build", + CapState::NarrowedByName => "narrowed-by-name", + CapState::DisabledByConfig => "disabled-by-config", + }; + serde_json::json!({ + "name": d.name, + "summary": d.summary, + "aliases": d.aliases, + "capabilities": d.capabilities.iter().map(|c| c.id()).collect::>(), + "available": surface.domain_state(d) == CapState::Available, + "state": state, + }) + }) + .collect(); + let doc = serde_json::json!({ + "build": { + "name": build, + "version": VERSION, + "source_rev": SOURCE_REV, + "invoked_as": invoked_as, + "profile": surface.profile.map(|v| v.name()), + }, + "capabilities": surface.usable().iter().map(|c| c.id()).collect::>(), + "compiled_capabilities": surface.compiled.iter().map(|c| c.id()).collect::>(), + "domains": domains, + }); + println!( + "{}", + serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string()) + ); +} + +fn state_mark(state: &CapState) -> &'static str { + match state { + CapState::Available => "", + CapState::NotInBuild => " [not in this build]", + CapState::NarrowedByName => " [narrowed out by this name]", + CapState::DisabledByConfig => " [disabled by config]", + } +} + +/// `--help` — the FULL registry on every variant (§3), absent domains +/// marked. This is registry data; it renders identically everywhere. +fn print_help(surface: &Surface) { + print!("{}", help_text(surface)); +} + +fn help_text(surface: &Surface) -> String { + let mut out = String::new(); + let build = build_name(&surface.compiled); + out.push_str(&format!( + "fleet {VERSION} — one multicall binary for the fleet's tools (build: {build})\n\n" + )); + out.push_str("Usage: fleet [args...]\n"); + out.push_str(" fleet \n\n"); + out.push_str("Domains (the full registry — every build knows every domain):\n"); + let width = fleet_registry::DOMAINS + .iter() + .map(|d| d.name.len()) + .max() + .unwrap_or(0); + for d in fleet_registry::DOMAINS { + let mark = state_mark(&surface.domain_state(d)); + let aliases = if d.aliases.is_empty() { + String::new() + } else { + format!(" [aliases: {}]", d.aliases.join(", ")) + }; + out.push_str(&format!( + " {: [args...]", d.name); + if !d.aliases.is_empty() { + println!("Aliases (argv0): {}", d.aliases.join(", ")); + } + if !d.subcommands.is_empty() { + println!("Commands: {}", d.subcommands.join(", ")); + } + let status = match surface.domain_state(d) { + CapState::Available => { + "included in this build (implementation lands in a later step of epic #5412)" + } + CapState::NotInBuild => { + "not in this build — invoking it prints the capability stub (exit 69)" + } + CapState::NarrowedByName => { + "narrowed out by this invocation name — invoking it prints the capability stub (exit 69)" + } + CapState::DisabledByConfig => "disabled by config on this host (exit 69 if invoked)", + }; + println!("Status: {status}"); +} + +fn usage_error(message: &str) -> i32 { + eprintln!("error: {message}"); + eprintln!(); + eprintln!("Usage: fleet [args...]"); + eprintln!(); + eprintln!("For the full domain registry, run: fleet --help"); + EXIT_USAGE +} + +/// The capability a concrete domain invocation needs. +fn required_capability(d: &Domain, args: &[String]) -> Result { + match d.name { + "serve" => { + let role = args.first().map(|s| s.as_str()); + match role { + Some("queue-broker") => Ok(Capability::QueueBroker), + Some("secrets-broker") => Ok(Capability::SecretsBroker), + Some("search") => Ok(Capability::SearchServe), + _ => Err(usage_error( + "'fleet serve' needs a role: queue-broker, secrets-broker, or search", + )), + } + } + "proxy" => { + let sub = args.first().map(|s| s.as_str()); + match sub { + Some("serve") => Ok(Capability::ProxyServe), + Some("connect") | Some("init") => Ok(Capability::ProxyConnect), + _ => Err(usage_error( + "'fleet proxy' needs a command: serve, connect, or init", + )), + } + } + _ => Ok(d.primary), + } +} + +/// Run one domain invocation (also the argv0-alias landing pad). +fn run_domain(surface: &Surface, d: &Domain, args: &[String], invoked_as: &str) -> i32 { + // Domain help is registry data: always available, even where the + // domain itself is not (§3). + if matches!( + args.first().map(|s| s.as_str()), + Some("--help") | Some("-h") | Some("help") + ) { + print_domain_help(surface, d); + return EXIT_OK; + } + let cap = match required_capability(d, args) { + Ok(c) => c, + Err(code) => return code, + }; + match surface.cap_state(cap, d.name) { + CapState::Available => { + if args.is_empty() && d.name != "serve" && d.name != "proxy" { + // A bare compiled-in domain is a usage error, like the + // tools being replaced — but say what it will be. + print_domain_help(surface, d); + return EXIT_USAGE; + } + stub(surface, d.name, &CapState::Available, invoked_as) + } + state => stub(surface, d.name, &state, invoked_as), + } +} + +fn run_root(surface: &Surface, args: &[String], invoked_as: &str) -> i32 { + let first = args.first().map(|s| s.as_str()); + match first { + None => { + // Bare `fleet`: clap-style missing-subcommand error — + // message and help both to stderr, exit 2. + eprintln!("error: 'fleet' requires a subcommand"); + eprintln!(); + eprint!("{}", help_text(surface)); + EXIT_USAGE + } + Some("--help") | Some("-h") | Some("help") if args.len() == 1 => { + print_help(surface); + EXIT_OK + } + Some("help") => match args.get(1).and_then(|name| domain(name)) { + Some(d) => { + print_domain_help(surface, d); + EXIT_OK + } + None => usage_error(&format!( + "no domain named '{}' — run 'fleet --help' for the registry", + args.get(1).map(|s| s.as_str()).unwrap_or("") + )), + }, + Some("--version") | Some("-V") => { + println!("fleet {VERSION}"); + EXIT_OK + } + Some("version") => { + print_version(surface, invoked_as); + EXIT_OK + } + Some("capabilities") => { + print_capabilities(surface, invoked_as); + EXIT_OK + } + Some(name) => match domain(name) { + Some(d) => run_domain(surface, d, &args[1..], invoked_as), + None => usage_error(&format!("unrecognized subcommand '{name}'")), + }, + } +} + +fn main() { + let argv: Vec = std::env::args().collect(); + let invoked_as = argv + .first() + .map(|a| { + std::path::Path::new(a) + .file_name() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_else(|| a.clone()) + }) + .unwrap_or_else(|| "fleet".to_string()); + let args: Vec = argv.iter().skip(1).cloned().collect(); + + // Config decides the disable table; a malformed config is a loud + // error on every path (a silently ignored disable would defeat + // the §7 incident lever). + let config = match fleet_config::Config::load() { + Ok(c) => c, + Err(e) => { + eprintln!("{e}"); + std::process::exit(EXIT_USAGE); + } + }; + + let code = if invoked_as == "fleet" { + let surface = Surface::new(None, config); + run_root(&surface, &args, &invoked_as) + } else if let Some(variant) = Variant::from_invocation_name(&invoked_as) { + // Refinement A: the hyphenated name narrows (never widens). + let surface = Surface::new(Some(variant), config); + run_root(&surface, &args, &invoked_as) + } else if let Some(route) = alias_route(&invoked_as) { + let surface = Surface::new(None, config); + let d = domain(route.domain).expect("registry aliases route to real domains"); + let mut routed: Vec = Vec::new(); + if let Some(implied) = route.implied_arg { + routed.push(implied.to_string()); + } + routed.extend(args); + run_domain(&surface, d, &routed, &invoked_as) + } else if is_known_invocation_name(&invoked_as) { + unreachable!("known names are handled above"); + } else { + eprintln!( + "fleet: invoked under unknown name '{invoked_as}'; expected 'fleet', a variant \ + name ('fleet-serve', 'fleet-connect'), or a known alias (repo-queue, queue-broker, \ + secrets-broker, laptop-agent, laptop-agent-broker, atlas-search)" + ); + EXIT_USAGE + }; + std::process::exit(code); +} + +// Keep the platform crates linked into every build that compiles this +// binary: the proxy protocol types are the fleet's wire contract, and +// the secrets path is platform surface even while domains are stubs. +#[allow(dead_code)] +fn _platform_linkage() { + let _ = fleet_proxy_proto::PROTO_MAJOR; + let _ = std::mem::size_of::(); + #[cfg(feature = "queue")] + let _ = std::mem::size_of::(); +} diff --git a/pkgs/fleet/default.nix b/pkgs/fleet/default.nix new file mode 100644 index 0000000000..eb9cc78d19 --- /dev/null +++ b/pkgs/fleet/default.nix @@ -0,0 +1,117 @@ +# fleet — the multicall fleet binary (developing-today/code#5412, +# step 1: #5429). One Rust workspace, one binary, capability +# variants selected by cargo features; the installed binary is +# always named `fleet`, and hyphenated names (fleet-serve, +# fleet-connect, repo-queue, ...) are argv0 personalities, not +# separate artifacts (design note sections 2-3, refinement A). +# +# Build through the root flake: +# +# nix build .#fleet .#fleet-serve .#fleet-connect .#fleet-connect-static +# +# The connect variants carry the design's D7 size contract: the +# binary must stay <= 2 MiB (target <= 1.5 MiB) so it can be +# dropped onto any host. The gate is enforced in postFixup below, +# against the final, stripped artifact. +{ + lib, + rustPlatform, + pkgsStatic, + binutils, + sourceRev ? "unknown", +}: + +let + # D7 hard gate for the runs-anywhere connect binary. + connectMaxBytes = 2 * 1024 * 1024; # 2097152 + + mkFleet = + { + pname, + features, + alias ? null, + sizeGate ? false, + platform ? rustPlatform, + }: + platform.buildRustPackage { + inherit pname; + version = "0.1.0"; + src = ./.; + cargoLock.lockFile = ./Cargo.lock; + + cargoBuildFlags = [ + "-p" + "fleet" + ] + ++ lib.optionals (features != null) [ "--no-default-features" ] + ++ lib.optionals (features != null && features != [ ]) [ + "--features" + (lib.concatStringsSep "," features) + ]; + + env.FLEET_SOURCE_REV = sourceRev; + + # Side-by-side installs (NixOS) keep the hyphenated name as a + # link to the same binary; argv0 narrows the surface. + postInstall = lib.optionalString (alias != null) '' + ln -s fleet $out/bin/${alias} + ''; + + # The nixpkgs fixup only strips debug symbols (-S), leaving + # the symbol table in the shipped binary, so strip fully and + # explicitly: the D7 contract is about the shipped artifact. + # (binutils by path: the pkgsStatic stdenv has no bare `strip` + # on PATH, only the target-prefixed one.) + postFixup = '' + ${binutils}/bin/strip $out/bin/fleet + '' + + lib.optionalString sizeGate '' + size=$(stat -c %s $out/bin/fleet) + echo "${pname}: bin/fleet is $size bytes (D7 gate: <= ${toString connectMaxBytes})" + if [ "$size" -gt ${toString connectMaxBytes} ]; then + echo "error: ${pname} binary exceeds the 2 MiB connect size gate (D7)" >&2 + exit 1 + fi + ''; + + meta = { + description = "Fleet multicall binary (${pname} variant): one binary for the queue, proxy, secrets, search and dispatch domains"; + license = with lib.licenses; [ + mit + asl20 + ]; + mainProgram = "fleet"; + }; + }; +in +{ + # Full profile: every domain compiled in. + fleet = mkFleet { + pname = "fleet"; + features = null; # workspace default features = full profile + }; + + # Serve profile: the broker-side domains, for servers. + fleet-serve = mkFleet { + pname = "fleet-serve"; + features = [ "serve" ]; + alias = "fleet-serve"; + }; + + # Connect profile: proxy-connect only, dynamically linked. + fleet-connect = mkFleet { + pname = "fleet-connect"; + features = [ ]; # --no-default-features, nothing optional on + alias = "fleet-connect"; + sizeGate = true; + }; + + # Connect profile, musl static: runs anywhere, no libc coupling. + fleet-connect-static = mkFleet { + pname = "fleet-connect-static"; + features = [ ]; + alias = "fleet-connect"; + sizeGate = true; + platform = pkgsStatic.rustPlatform; + }; +} diff --git a/pkgs/fleet/rust-toolchain.toml b/pkgs/fleet/rust-toolchain.toml new file mode 100644 index 0000000000..5785679463 --- /dev/null +++ b/pkgs/fleet/rust-toolchain.toml @@ -0,0 +1,14 @@ +# Rust toolchain configuration for fleet. +# +# IMPORTANT: DO NOT DELETE THIS FILE - it is required for Nix builds. +# Mirrors the pkgs/atlas-search / pkgs/id pin discipline. +# +# Components: +# - rustfmt: Code formatting +# - clippy: Linting + +[toolchain] +# WARNING: this may cause rustc to build, ensure nixpkg has cached before committing this change. +channel = "1.99.0" # WARNING: this may cause rustc to build, ensure nixpkg has cached before committing this change. +components = ["rustfmt", "clippy"] +profile = "default" diff --git a/pkgs/fleet/smoke.sh b/pkgs/fleet/smoke.sh new file mode 100755 index 0000000000..87246c68fc --- /dev/null +++ b/pkgs/fleet/smoke.sh @@ -0,0 +1,147 @@ +#!/usr/bin/env bash +# Per-variant smoke suite for the fleet workspace skeleton +# (step 1, developing-today/code#5429). +# +# Usage: +# smoke.sh +# +# Each argument is a nix package output path; its bin/fleet is the +# artifact under test. The suite asserts, per variant: +# * --help renders the FULL registry, unavailable domains marked +# * version lists exactly that variant's capability set +# * a missing domain stubs with exit 69 and the right wording, +# reached three ways: `fleet `, an argv0 alias symlink, +# and a hyphenated variant name (which NARROWS the surface) +# * a config-disabled domain stubs with exit 69, config wording +# * both connect flavors run under `env -i` +# * both connect flavors are within the D7 size gate (<= 2 MiB) +# +# Exits nonzero if any check fails. No network, no installs, no +# state outside a mktemp dir. +set -u + +FULL_OUT=${1:?usage: smoke.sh } +SERVE_OUT=${2:?missing fleet-serve output path} +CONNECT_OUT=${3:?missing fleet-connect output path} +STATIC_OUT=${4:?missing fleet-connect-static output path} + +PASS=0 +FAIL=0 +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +bad() { FAIL=$((FAIL + 1)); echo "FAIL - $1"; } + +# run +run() { + local name=$1 want_rc=$2 want_sub=$3; shift 3 + local out rc + out=$("$@" 2>&1); rc=$? + if [ "$rc" -ne "$want_rc" ]; then + bad "$name (exit $rc, want $want_rc)" + echo "$out" | head -5 | sed 's/^/ /' + return + fi + if [ "$want_sub" != "-" ] && ! printf '%s' "$out" | grep -qF "$want_sub"; then + bad "$name (output missing: $want_sub)" + echo "$out" | head -5 | sed 's/^/ /' + return + fi + ok "$name" +} + +FULL_CAPS="Enabled capabilities: proxy-connect, proxy-serve, queue, queue-broker, secrets-broker, search, search-serve, dispatch, laptop-agent" +SERVE_CAPS="Enabled capabilities: proxy-connect, proxy-serve, queue-broker, secrets-broker, search-serve" +CONNECT_CAPS="Enabled capabilities: proxy-connect" + +check_variant() { + local label=$1 bin=$2 caps=$3 + run "$label: --help renders the full registry" 0 "laptop-agent" "$bin" --help + run "$label: version capability set is exact" 0 "$caps" "$bin" version + run "$label: capabilities is valid JSON with the build block" 0 '"source_rev"' "$bin" capabilities +} + +echo "== variants ==" +check_variant full "$FULL_OUT/bin/fleet" "$FULL_CAPS" +check_variant serve "$SERVE_OUT/bin/fleet" "$SERVE_CAPS" +check_variant connect "$CONNECT_OUT/bin/fleet" "$CONNECT_CAPS" +check_variant static "$STATIC_OUT/bin/fleet" "$CONNECT_CAPS" + +echo "== help marks ==" +run "full: --help marks nothing unavailable" 0 "-" "$FULL_OUT/bin/fleet" --help +if "$FULL_OUT/bin/fleet" --help | grep -qF "[not in this build]"; then + bad "full: --help should have no [not in this build] marks" +else + ok "full: --help has no [not in this build] marks" +fi +run "connect: --help marks queue as not in this build" 0 "[not in this build]" "$CONNECT_OUT/bin/fleet" --help +run "serve: --help marks dispatch as not in this build" 0 "[not in this build]" "$SERVE_OUT/bin/fleet" --help + +echo "== stubs: not in this build (exit 69) ==" +run "connect: fleet queue stubs" 69 "this build does not include 'queue'" \ + "$CONNECT_OUT/bin/fleet" queue +run "connect: fleet search stubs" 69 "this build does not include 'search'" \ + "$CONNECT_OUT/bin/fleet" search +run "serve: fleet dispatch stubs" 69 "this build does not include 'dispatch'" \ + "$SERVE_OUT/bin/fleet" dispatch +run "serve: fleet laptop-agent stubs" 69 "this build does not include 'laptop-agent'" \ + "$SERVE_OUT/bin/fleet" laptop-agent + +echo "== stubs via argv0 alias symlinks ==" +ln -s "$CONNECT_OUT/bin/fleet" "$TMP/repo-queue" +ln -s "$CONNECT_OUT/bin/fleet" "$TMP/atlas-search" +ln -s "$SERVE_OUT/bin/fleet" "$TMP/queue-broker" +run "connect as repo-queue stubs 69" 69 "this build does not include 'queue'" "$TMP/repo-queue" +run "connect as atlas-search stubs 69" 69 "this build does not include 'search'" "$TMP/atlas-search" +run "serve as queue-broker reaches the (unimplemented) broker role" 69 "not implemented yet" "$TMP/queue-broker" + +echo "== compiled in but not implemented yet (exit 69) ==" +run "full: fleet proxy connect is the skeleton stub" 69 "not implemented yet" \ + "$FULL_OUT/bin/fleet" proxy connect +run "connect: fleet proxy connect is the skeleton stub" 69 "not implemented yet" \ + "$CONNECT_OUT/bin/fleet" proxy connect + +echo "== name narrowing: full build invoked as fleet-connect ==" +ln -s "$FULL_OUT/bin/fleet" "$TMP/fleet-connect" +run "narrowed: version lists only the connect set" 0 "$CONNECT_CAPS" "$TMP/fleet-connect" version +run "narrowed: queue stubs with narrowed wording" 69 "invoked as 'fleet-connect'" \ + "$TMP/fleet-connect" queue health +run "narrowed: proxy connect still reaches the skeleton stub" 69 "not implemented yet" \ + "$TMP/fleet-connect" proxy connect +run "narrowed: --help marks queue as narrowed out" 0 "[narrowed out by this name]" \ + "$TMP/fleet-connect" --help + +echo "== name narrowing never widens: connect invoked as fleet ==" +ln -s "$CONNECT_OUT/bin/fleet" "$TMP/fleet" +run "connect as fleet: queue still stubs not-in-build" 69 "this build does not include 'queue'" \ + "$TMP/fleet" queue + +echo "== config-disabled domain (exit 69, config wording) ==" +printf '[domains]\nqueue = false\n' > "$TMP/fleet.toml" +run "full with queue=false: fleet queue stubs as disabled" 69 "disabled by config" \ + env FLEET_CONFIG="$TMP/fleet.toml" "$FULL_OUT/bin/fleet" queue +run "full with queue=false: version drops queue capabilities" 0 "proxy-serve, queue-broker" \ + env FLEET_CONFIG="$TMP/fleet.toml" "$FULL_OUT/bin/fleet" version + +echo "== runs anywhere: env -i ==" +run "connect dynamic under env -i" 0 "$CONNECT_CAPS" env -i "$CONNECT_OUT/bin/fleet" version +run "connect static under env -i" 0 "$CONNECT_CAPS" env -i "$STATIC_OUT/bin/fleet" version + +echo "== D7 size gate (<= 2097152 bytes) ==" +for flavor in "$CONNECT_OUT" "$STATIC_OUT"; do + size=$(stat -c %s "$flavor/bin/fleet") + echo " $flavor/bin/fleet: $size bytes" + if [ "$size" -le 2097152 ]; then + ok "connect size gate: $size <= 2097152" + else + bad "connect size gate: $size > 2097152" + fi +done +for flavor in "$FULL_OUT" "$SERVE_OUT"; do + echo " $flavor/bin/fleet: $(stat -c %s "$flavor/bin/fleet") bytes (recorded, no gate)" +done + +echo +echo "smoke: $PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ]