From a9d10aca84d11583c7892589404cd20eb5ed0645 Mon Sep 17 00:00:00 2001 From: Drew Pope Date: Wed, 4 Nov 2026 07:39:36 -0600 Subject: [PATCH] =?UTF-8?q?feat(fleet):=20queue=20domain=20=E2=80=94=20rep?= =?UTF-8?q?o-queue=20client=20+=20broker=20roles=20in=20pkgs/fleet=20(step?= =?UTF-8?q?=202,=20#5430)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port the broker family (sandbox ~/tools/fleet-brokers, code#5362) into pkgs/fleet as crates/fleet-queue: the repo-queue client, the queue-broker and secrets-broker serve roles, and packet validation, refactored onto the platform crates — credentials resolve by name through fleet-secrets (the queue-broker source is a SecretSource over the secrets-broker HTTP API; the secrets-broker refresh runs bws through the CommandRunner seam), and all three programs share one structured logging facility (src/log.rs) with the domain as a field, byte-identical stderr to the ad-hoc prefixes it replaces. Wire behavior is preserved: same HTTP surface, envelopes, framing, exit codes, and stdout shapes (serde_json preserve_order where the consumers read key order). repo-queue gains the surface the census found missing: --help renders from the fleet registry and --version reports the release through the argv0 route (fleet queue equally). The brokers keep building as standalone artifacts (the fleet-brokers package: repo-queue / queue-broker / secrets-broker from src/bin shims over the same library) — the migration rollback inventory. A fleet-static (full profile, musl) artifact joins the variant set for non-nix install contexts. The broker systemd user units land in home/common/default.nix as fleet serve definitions — the dezren39/nix PR #1459 module pattern ported into this tree per ruling D1, consuming this flake's own packages. Live migration evidence (per-flip round-trips, rollback exercise) is recorded on #5430. --- home/common/default.nix | 54 + lib/default.nix | 4 +- pkgs/fleet/.gitignore | 1 + pkgs/fleet/Cargo.lock | 762 ++++++++++ pkgs/fleet/Cargo.toml | 7 +- pkgs/fleet/README.md | 28 +- pkgs/fleet/crates/fleet-queue/Cargo.toml | 46 + .../fleet-queue/src/bin/queue-broker.rs | 9 + .../crates/fleet-queue/src/bin/repo-queue.rs | 9 + .../fleet-queue/src/bin/secrets-broker.rs | 9 + pkgs/fleet/crates/fleet-queue/src/client.rs | 1248 +++++++++++++++++ pkgs/fleet/crates/fleet-queue/src/lib.rs | 32 + pkgs/fleet/crates/fleet-queue/src/log.rs | 12 + .../crates/fleet-queue/src/queue_broker.rs | 664 +++++++++ .../crates/fleet-queue/src/secrets_broker.rs | 290 ++++ pkgs/fleet/crates/fleet-queue/src/validate.rs | 468 +++++++ pkgs/fleet/crates/fleet-secrets/src/lib.rs | 8 + pkgs/fleet/crates/fleet/Cargo.toml | 7 +- pkgs/fleet/crates/fleet/src/main.rs | 57 +- pkgs/fleet/default.nix | 53 + pkgs/fleet/smoke.sh | 51 +- 21 files changed, 3792 insertions(+), 27 deletions(-) create mode 100644 pkgs/fleet/.gitignore create mode 100644 pkgs/fleet/crates/fleet-queue/Cargo.toml create mode 100644 pkgs/fleet/crates/fleet-queue/src/bin/queue-broker.rs create mode 100644 pkgs/fleet/crates/fleet-queue/src/bin/repo-queue.rs create mode 100644 pkgs/fleet/crates/fleet-queue/src/bin/secrets-broker.rs create mode 100644 pkgs/fleet/crates/fleet-queue/src/client.rs create mode 100644 pkgs/fleet/crates/fleet-queue/src/lib.rs create mode 100644 pkgs/fleet/crates/fleet-queue/src/log.rs create mode 100644 pkgs/fleet/crates/fleet-queue/src/queue_broker.rs create mode 100644 pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs create mode 100644 pkgs/fleet/crates/fleet-queue/src/validate.rs diff --git a/home/common/default.nix b/home/common/default.nix index 26235fd2bb..8aefa36038 100644 --- a/home/common/default.nix +++ b/home/common/default.nix @@ -47,6 +47,21 @@ let rustc = atlasSearchToolchain; }; }; + # The fleet multicall package (pkgs/fleet), built with the + # toolchain pinned by its own rust-toolchain.toml — the + # atlas-search pattern above. Used as the broker units' + # ExecStart below (`fleet serve `); deliberately not in + # home.packages — the resolved `repo-queue` on PATH stays the + # standalone artifact until the proxy step's shim dir (design + # note §4) supersedes the hand-maintained symlinks. + fleetToolchain = (pkgs.extend (import inputs.id-rust-overlay)).rust-bin.fromRustupToolchainFile ../../pkgs/fleet/rust-toolchain.toml; + fleetPkgs = pkgs.callPackage ../../pkgs/fleet { + rustPlatform = pkgs.makeRustPlatform { + cargo = fleetToolchain; + rustc = fleetToolchain; + }; + sourceRev = inputs.self.rev or "dirty"; + }; # Upstream prebuilt release binaries for tools where nixpkgs trails upstream. # See pkgs/latest-cli/default.nix for the rationale, the tradeoffs, and the # list of things deliberately NOT bumped. @@ -908,6 +923,45 @@ in }; }; + # Fleet broker roles (epic #5412 step 2, #5430): the secrets and + # queue brokers as `fleet serve ` units — one unit per role, + # as they have run since code#5362. This is the home-module + # pattern ported from dezren39/nix PR #1459 (closed as superseded + # by ruling D1) into this tree, now consuming this flake's own + # pkgs/fleet instead of a vendored copy. The unit files these + # definitions replace were hand-installed; home-manager converges + # them on the next activation, and the step-2 flips re-point the + # live files at the same artifact in the meantime. + systemd.user.services.secrets-broker = { + Unit = { + Description = "secrets-broker — resident Bitwarden secrets cache (code#5362)"; + After = [ "network-online.target" ]; + }; + Service = { + ExecStart = "${fleetPkgs.fleet}/bin/fleet serve secrets-broker"; + Restart = "on-failure"; + RestartSec = 5; + }; + Install.WantedBy = [ "default.target" ]; + }; + + systemd.user.services.queue-broker = { + Unit = { + Description = "queue-broker — repo-health queue service (code#5362)"; + After = [ + "network-online.target" + "secrets-broker.service" + ]; + Wants = [ "secrets-broker.service" ]; + }; + Service = { + ExecStart = "${fleetPkgs.fleet}/bin/fleet serve queue-broker"; + Restart = "on-failure"; + RestartSec = 5; + }; + Install.WantedBy = [ "default.target" ]; + }; + systemd.user.services.sync-models = { Unit = { Description = "Sync AI models for OpenCode providers from models.dev and agy"; diff --git a/lib/default.nix b/lib/default.nix index 03b0ea7d37..e1ef3f311b 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -1166,10 +1166,10 @@ let in { packages = { - inherit (fleetPkgs) fleet fleet-serve fleet-connect; + inherit (fleetPkgs) fleet fleet-serve fleet-connect fleet-brokers; } // pkgs.lib.optionalAttrs (system == "x86_64-linux" || system == "aarch64-linux") { - inherit (fleetPkgs) fleet-connect-static; + inherit (fleetPkgs) fleet-connect-static fleet-static; }; } ); diff --git a/pkgs/fleet/.gitignore b/pkgs/fleet/.gitignore new file mode 100644 index 0000000000..ea8c4bf7f3 --- /dev/null +++ b/pkgs/fleet/.gitignore @@ -0,0 +1 @@ +/target diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock index 0403b3057a..443fbb3bd3 100644 --- a/pkgs/fleet/Cargo.lock +++ b/pkgs/fleet/Cargo.lock @@ -2,18 +2,146 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ascii" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chunked_transfer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" + +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] +name = "crc32fast" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "equivalent" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "fleet" version = "0.1.0" dependencies = [ "fleet-config", "fleet-proxy-proto", + "fleet-queue", "fleet-registry", "fleet-secrets", "serde_json", @@ -36,6 +164,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "fleet-queue" +version = "0.1.0" +dependencies = [ + "fleet-secrets", + "serde", + "serde_json", + "tiny_http", + "ureq", +] + [[package]] name = "fleet-registry" version = "0.1.0" @@ -49,12 +188,164 @@ dependencies = [ "serde_json", ] +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -71,12 +362,79 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -95,6 +453,55 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "serde" version = "1.0.229" @@ -131,6 +538,8 @@ version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ + "foldhash", + "indexmap", "itoa", "memchr", "serde", @@ -147,6 +556,36 @@ dependencies = [ "serde_core", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "3.0.9" @@ -158,6 +597,69 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tiny_http" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82" +dependencies = [ + "ascii", + "chunked_transfer", + "httpdate", + "log", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "toml" version = "0.9.12+spec-1.1.0" @@ -203,6 +705,171 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" +dependencies = [ + "base64", + "cookie_store", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "0.7.15" @@ -215,6 +882,101 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/pkgs/fleet/Cargo.toml b/pkgs/fleet/Cargo.toml index 36fbc76a9f..b561ad9c25 100644 --- a/pkgs/fleet/Cargo.toml +++ b/pkgs/fleet/Cargo.toml @@ -3,14 +3,16 @@ # # 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. +# root. Crates land one step at a time: step 1 (#5429) the skeleton +# (platform crates + the bin's dispatch/stub machinery + variant +# builds); step 2 (#5430) the queue domain (crates/fleet-queue). [workspace] members = [ "crates/fleet-registry", "crates/fleet-config", "crates/fleet-secrets", "crates/fleet-proxy-proto", + "crates/fleet-queue", "crates/fleet", ] resolver = "2" @@ -26,6 +28,7 @@ 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" } +fleet-queue = { path = "crates/fleet-queue" } serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "0.9" diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index 93ca18eca1..3a361067a6 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -3,10 +3,12 @@ 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). +workspace began as the step-1 (#5429) skeleton: the registry, +config, secrets-by-name and proxy-protocol platform crates. Step 2 +(#5430) landed the queue domain — the repo-queue client and the +queue-broker / secrets-broker serve roles are real below. The +remaining domains are capability stubs until their own steps land +(proxy #5431, dispatch #5432, search #5433). ## Layout @@ -26,6 +28,14 @@ crates/fleet-secrets/ secrets by NAME only (broker first, then 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-queue/ the queue domain (step 2): the repo-queue + client, the queue-broker and secrets-broker + roles, and packet validation — the broker + family's first source home (code#5362). + Its src/bin/ builds the standalone + repo-queue / queue-broker / secrets-broker + artifacts (the `fleet-brokers` package): + the migration's rollback inventory. crates/fleet/ the binary: multicall dispatch, capability stubs, `version`, `capabilities`, help. default.nix the four variant packages (see below) @@ -48,6 +58,7 @@ their domain through argv0. | `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) | +| `fleet-brokers` | — | standalone repo-queue / queue-broker / secrets-broker (rollback) | Every package installs its binary as `bin/fleet`; the hyphen variants also get a `bin/fleet-serve` / `bin/fleet-connect` symlink @@ -84,5 +95,10 @@ 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. +Step 1 installed nothing live. Step 2 performs the queue pilot's +flips — the laptop's broker units re-point at `fleet serve +`, then the sandbox `~/tools/bin/repo-queue` symlink at the +fleet artifact — each verified by health plus a real +enqueue→claim→complete round-trip before the next begins (the +evidence lives on #5430). The standalone artifacts above are the +rollback for every flip. diff --git a/pkgs/fleet/crates/fleet-queue/Cargo.toml b/pkgs/fleet/crates/fleet-queue/Cargo.toml new file mode 100644 index 0000000000..b47465ea02 --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "fleet-queue" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The fleet queue domain: the repo-queue client surface plus the queue-broker and secrets-broker server roles (epic developing-today/code#5412, step 2 #5430)." + +# The three surfaces are separate features so the shipped variants +# compile exactly the surface they carry (design note §2): the full +# build takes all three, fleet-serve takes the two broker roles +# without the client, and a client-only build is possible for the +# standalone artifact. +[features] +client = [] +queue-broker = ["dep:tiny_http", "dep:ureq"] +secrets-broker = ["dep:tiny_http"] + +[dependencies] +fleet-secrets = { workspace = true } +serde = { workspace = true } +# preserve_order: the brokers' JSON key order is part of the wire and +# stdout shape the fleet already consumes (the standalone workspace +# built serde_json the same way). +serde_json = { version = "1", features = ["preserve_order"] } +tiny_http = { version = "0.12", optional = true } +ureq = { version = "3", features = ["rustls", "json"], optional = true } + +# Standalone artifacts — the migration's rollback inventory (design +# note §7): the same code as the fleet binary's queue domain, shipped +# under the historical names while the migration runs. Built by the +# `fleet-brokers` package in pkgs/fleet/default.nix. +[[bin]] +name = "repo-queue" +path = "src/bin/repo-queue.rs" +required-features = ["client"] + +[[bin]] +name = "queue-broker" +path = "src/bin/queue-broker.rs" +required-features = ["queue-broker"] + +[[bin]] +name = "secrets-broker" +path = "src/bin/secrets-broker.rs" +required-features = ["secrets-broker"] diff --git a/pkgs/fleet/crates/fleet-queue/src/bin/queue-broker.rs b/pkgs/fleet/crates/fleet-queue/src/bin/queue-broker.rs new file mode 100644 index 0000000000..2eeaf2395e --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/bin/queue-broker.rs @@ -0,0 +1,9 @@ +//! Standalone `queue-broker` — the queue broker role's own +//! artifact, kept building from the fleet workspace for the whole +//! migration as the standing rollback inventory (design note §7). +//! The same code runs inside the fleet binary as +//! `fleet serve queue-broker`. + +fn main() { + std::process::exit(fleet_queue::queue_broker::run()); +} diff --git a/pkgs/fleet/crates/fleet-queue/src/bin/repo-queue.rs b/pkgs/fleet/crates/fleet-queue/src/bin/repo-queue.rs new file mode 100644 index 0000000000..440152fe8f --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/bin/repo-queue.rs @@ -0,0 +1,9 @@ +//! Standalone `repo-queue` — the queue client's own artifact, kept +//! building from the fleet workspace for the whole migration as the +//! standing rollback inventory (design note §7). The same client +//! code runs inside the fleet binary as the queue domain. + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + std::process::exit(fleet_queue::client::run(&args)); +} diff --git a/pkgs/fleet/crates/fleet-queue/src/bin/secrets-broker.rs b/pkgs/fleet/crates/fleet-queue/src/bin/secrets-broker.rs new file mode 100644 index 0000000000..ebabdb9d0f --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/bin/secrets-broker.rs @@ -0,0 +1,9 @@ +//! Standalone `secrets-broker` — the secrets broker role's own +//! artifact, kept building from the fleet workspace for the whole +//! migration as the standing rollback inventory (design note §7). +//! The same code runs inside the fleet binary as +//! `fleet serve secrets-broker`. + +fn main() { + std::process::exit(fleet_queue::secrets_broker::run()); +} diff --git a/pkgs/fleet/crates/fleet-queue/src/client.rs b/pkgs/fleet/crates/fleet-queue/src/client.rs new file mode 100644 index 0000000000..e47ad2cb1f --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/client.rs @@ -0,0 +1,1248 @@ +//! repo-queue client — the queue domain's client surface +//! (fleet-queue, step 2 of epic developing-today/code#5412, #5430; +//! ported from the standalone repo-queue crate, code#5362). +//! +//! Same CLI surface, exit codes, and stdout formats as the retired +//! repo-queue.py. Two transports reach the same queue-broker: from +//! the sandbox, the session proxy (the laptop-agent broker's Unix +//! socket); on the laptop itself, a direct HTTP connection selected +//! by REPO_QUEUE_BROKER_URL or ~/.config/repo-queue/broker-url (the +//! opencode claimant and the worker sessions it launches use this). +//! No Bitwarden fetch, no direct Supabase access. Exit 3 means the +//! broker path itself is unavailable. +//! +//! Entry points: the fleet binary's queue domain and the standalone +//! `repo-queue` artifact (src/bin/repo-queue.rs) both call `run`. + +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::os::unix::net::UnixStream; +use std::process::exit; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde_json::{Map, Value, json}; + +const QUEUE_BROKER_PORT: u64 = 4801; +const DEFAULT_QUEUE: &str = "repo-health-code-shadow"; +const DEFAULT_WORKER: &str = "repo-worker-code"; +const TELEMETRY_FIELDS: [&str; 4] = ["pool", "model", "effort", "cost_usd"]; +const TERMINAL_STATUSES: [&str; 3] = ["done", "cancelled", "failed"]; + +fn home() -> String { + std::env::var("HOME").unwrap_or_default() +} + +fn eprint(s: &str) { + eprintln!("{s}"); +} + +fn die(code: i32, msg: &str) -> ! { + eprintln!("repo-queue: {msg}"); + exit(code); +} + +fn print_json(v: &Value) { + println!( + "{}", + serde_json::to_string_pretty(v).unwrap_or_else(|_| "null".to_string()) + ); +} + +// --------------------------------------------------------------------------- +// Session-proxy transport +// --------------------------------------------------------------------------- + +fn broker_sock() -> String { + format!("{}/.cache/laptop-agent/broker.sock", home()) +} + +// --------------------------------------------------------------------------- +// Direct-broker transport (on-laptop use: the opencode claimant and +// the worker sessions it launches run on the same host as the +// queue-broker, where no session proxy exists). Selected by +// REPO_QUEUE_BROKER_URL or ~/.config/repo-queue/broker-url; the token +// comes from REPO_QUEUE_TOKEN_FILE or ~/.config/queue-broker/token. +// With neither configured, the session-proxy transport below is used, +// exactly as before. +// --------------------------------------------------------------------------- + +fn direct_broker_url() -> Option { + if let Ok(u) = std::env::var("REPO_QUEUE_BROKER_URL") { + let u = u.trim().to_string(); + if !u.is_empty() { + return Some(u); + } + } + let p = format!("{}/.config/repo-queue/broker-url", home()); + if let Ok(s) = std::fs::read_to_string(&p) { + let u = s.trim().to_string(); + if !u.is_empty() { + return Some(u); + } + } + None +} + +fn direct_roundtrip(url: &str, path: &str, body: &Value) -> Result { + let rest = url + .strip_prefix("http://") + .ok_or("broker URL must be http://host:port")?; + let hostport = rest.trim_end_matches('/'); + if hostport.is_empty() || hostport.contains('/') { + return Err(format!("bad broker URL {url:?}")); + } + let token_file = std::env::var("REPO_QUEUE_TOKEN_FILE") + .unwrap_or_else(|_| format!("{}/.config/queue-broker/token", home())); + let token = std::fs::read_to_string(&token_file) + .map_err(|e| format!("cannot read queue-broker token file {token_file}: {e}"))?; + let token = token.trim(); + let payload = serde_json::to_vec(body).unwrap(); + let mut s = TcpStream::connect(hostport) + .map_err(|e| format!("cannot connect to queue-broker at {hostport}: {e}"))?; + s.set_read_timeout(Some(Duration::from_secs(300))).ok(); + s.set_write_timeout(Some(Duration::from_secs(60))).ok(); + let head = format!( + "POST {path} HTTP/1.1\r\nHost: {hostport}\r\nX-Agent-Token: {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + payload.len() + ); + s.write_all(head.as_bytes()) + .and_then(|_| s.write_all(&payload)) + .map_err(|e| format!("queue-broker write failed: {e}"))?; + let mut raw = Vec::new(); + s.read_to_end(&mut raw) + .map_err(|e| format!("queue-broker read failed: {e}"))?; + let split = raw + .windows(4) + .position(|w| w == b"\r\n\r\n") + .ok_or("queue-broker bad reply")?; + let head_txt = String::from_utf8_lossy(&raw[..split]).to_string(); + let status: u64 = head_txt + .split_whitespace() + .nth(1) + .and_then(|c| c.parse().ok()) + .unwrap_or(0); + let resp_body: Value = serde_json::from_slice(&raw[split + 4..]).unwrap_or(Value::Null); + if status == 401 { + die(3, "queue-broker rejected the client token (HTTP 401)"); + } + if status >= 400 { + let msg = resp_body + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("queue-broker error") + .to_string(); + die(3, &msg); + } + Ok(resp_body) +} + +fn broker_roundtrip(path: &str, body: &Value) -> Result { + if let Some(url) = direct_broker_url() { + return direct_roundtrip(&url, path, body); + } + let payload = json!({ + "method": "POST", + "path": path, + "body": body, + "port": QUEUE_BROKER_PORT, + "token_file": format!("{}/tools/queue-broker-token", home()), + }); + let data = serde_json::to_vec(&payload).unwrap(); + for attempt in 0..2 { + match unix_roundtrip(&data) { + Ok(resp) => { + let status = resp.get("status").and_then(|s| s.as_u64()).unwrap_or(0); + let body = resp.get("body").cloned().unwrap_or(Value::Null); + if status == 401 { + die(3, "queue-broker rejected the client token (HTTP 401)"); + } + if status >= 400 { + let msg = body + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("session proxy error") + .to_string(); + die(3, &msg); + } + return Ok(body); + } + Err(e) => { + if attempt == 0 { + spawn_broker(); + continue; + } + return Err(e); + } + } + } + Err("unreachable".to_string()) +} + +fn unix_roundtrip(data: &[u8]) -> Result { + let mut s = UnixStream::connect(broker_sock()) + .map_err(|e| format!("cannot connect to session proxy: {e}"))?; + s.set_read_timeout(Some(Duration::from_secs(660))).ok(); + s.set_write_timeout(Some(Duration::from_secs(60))).ok(); + s.write_all(&(data.len() as u64).to_be_bytes()) + .and_then(|_| s.write_all(data)) + .map_err(|e| format!("session proxy write failed: {e}"))?; + let mut hdr = [0u8; 8]; + s.read_exact(&mut hdr) + .map_err(|e| format!("session proxy read failed: {e}"))?; + let n = u64::from_be_bytes(hdr) as usize; + let mut buf = vec![0u8; n]; + s.read_exact(&mut buf) + .map_err(|e| format!("session proxy read failed: {e}"))?; + serde_json::from_slice(&buf).map_err(|e| format!("session proxy bad reply: {e}")) +} + +fn spawn_broker() { + let dir = format!("{}/.cache/laptop-agent", home()); + let _ = std::fs::create_dir_all(&dir); + let log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(format!("{dir}/broker.log")); + let (out, err) = match log { + Ok(f) => ( + std::process::Stdio::from(f.try_clone().unwrap()), + std::process::Stdio::from(f), + ), + Err(_) => (std::process::Stdio::null(), std::process::Stdio::null()), + }; + let _ = std::process::Command::new("python3") + .arg(format!("{}/tools/laptop-agent-broker.py", home())) + .stdout(out) + .stderr(err) + .stdin(std::process::Stdio::null()) + .spawn(); + for _ in 0..50 { + if std::path::Path::new(&broker_sock()).exists() { + // Give the listener a moment to accept. + std::thread::sleep(Duration::from_millis(100)); + return; + } + std::thread::sleep(Duration::from_millis(100)); + } +} + +/// POST one queue-broker command; dies (exit 3) when the broker path +/// is unavailable, otherwise returns the response envelope (which may +/// itself be {ok:false, exit, error} — the caller decides). +fn call(path: &str, body: &Value) -> Value { + match broker_roundtrip(path, body) { + Ok(v) => v, + Err(e) => die(3, &e), + } +} + +/// Unwrap an envelope: on {ok:false} print the error and exit with its +/// code; otherwise return the envelope for field extraction. +fn unwrap_ok(resp: Value) -> Value { + if resp.get("ok").and_then(|o| o.as_bool()) == Some(false) { + let code = resp.get("exit").and_then(|e| e.as_i64()).unwrap_or(4) as i32; + let msg = resp + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("queue-broker error") + .to_string(); + die(code, &msg); + } + resp +} + +fn require_row(resp: &Value, fn_name: &str) -> Value { + let row = resp.get("row").cloned().unwrap_or(Value::Null); + if row.is_null() { + die( + 5, + &format!( + "{fn_name}: no matching claimed row (task not claimed by this worker, or already terminal)" + ), + ); + } + row +} + +fn row_or_ledger(resp: &Value, fn_name: &str) { + let row = require_row(resp, fn_name); + if let Some(ledger) = resp.get("lane_ledger") { + print_json(&json!({"task": row, "lane_ledger": ledger})); + } else { + print_json(&row); + } +} + +// --------------------------------------------------------------------------- +// Time helpers (ISO 8601 <-> epoch, civil-date math) +// --------------------------------------------------------------------------- + +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146097 + doe - 719468 +} + +fn civil_from_days(z: i64) -> (i64, i64, i64) { + let z = z + 719468; + let era = if z >= 0 { z } else { z - 146096 } / 146097; + let doe = z - era * 146097; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +/// Parse an ISO 8601 timestamp to epoch microseconds (None if unusable). +fn parse_ts(v: &Value) -> Option { + let s = v.as_str()?; + parse_ts_str(s) +} + +fn parse_ts_str(s: &str) -> Option { + let (date, rest) = s.split_once('T')?; + let mut dp = date.split('-'); + let y: i64 = dp.next()?.parse().ok()?; + let mo: i64 = dp.next()?.parse().ok()?; + let d: i64 = dp.next()?.parse().ok()?; + let (time, offset_min) = if let Some(t) = rest.strip_suffix('Z') { + (t, 0i64) + } else if let Some(idx) = rest.rfind(['+', '-']) { + if idx == 0 { + return None; + } + let (t, off) = rest.split_at(idx); + let sign = if rest.as_bytes()[idx] == b'-' { -1 } else { 1 }; + let mut op = off[1..].split(':'); + let oh: i64 = op.next()?.parse().ok()?; + let om: i64 = op.next().unwrap_or("0").parse().ok()?; + (t, sign * (oh * 60 + om)) + } else { + (rest, 0) + }; + let mut tp = time.split(':'); + let h: i64 = tp.next()?.parse().ok()?; + let mi: i64 = tp.next()?.parse().ok()?; + let sec_part = tp.next().unwrap_or("0"); + let (sec_s, frac) = match sec_part.split_once('.') { + Some((a, b)) => (a, b), + None => (sec_part, ""), + }; + let sec: i64 = sec_s.parse().ok()?; + let mut micros: i64 = 0; + let mut scale = 100_000i64; + for c in frac.chars().take(6) { + micros += c.to_digit(10)? as i64 * scale; + scale /= 10; + } + let days = days_from_civil(y, mo, d); + let epoch_s = days * 86400 + h * 3600 + mi * 60 + sec - offset_min * 60; + Some(epoch_s * 1_000_000 + micros) +} + +fn now_micros() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_micros() as i64) + .unwrap_or(0) +} + +fn utcnow_iso() -> String { + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0); + let days = secs.div_euclid(86400); + let rem = secs.rem_euclid(86400); + let (y, m, d) = civil_from_days(days); + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + rem / 3600, + (rem % 3600) / 60, + rem % 60 + ) +} + +fn age_str(created: &Value) -> String { + let Some(c) = parse_ts(created) else { + return String::new(); + }; + let secs = ((now_micros() - c) / 1_000_000).max(0); + let (d, rem) = (secs / 86400, secs % 86400); + let (h, rem) = (rem / 3600, rem % 3600); + let (m, s) = (rem / 60, rem % 60); + if d > 0 { + format!("{d}d {h:02}:{m:02}") + } else { + format!("{h}:{m:02}:{s:02}") + } +} + +// --------------------------------------------------------------------------- +// Formatting (mirrors repo-queue.py tables) +// --------------------------------------------------------------------------- + +fn fmt_cell(v: Option<&Value>) -> String { + match v { + None | Some(Value::Null) => String::new(), + Some(Value::Object(_)) | Some(Value::Array(_)) => { + serde_json::to_string(v.unwrap()).unwrap_or_default() + } + Some(Value::String(s)) => s.clone(), + Some(other) => other.to_string(), + } +} + +fn truncate(s: &str, n: usize) -> String { + if s.chars().count() <= n { + s.to_string() + } else { + let head: String = s.chars().take(n - 1).collect(); + format!("{head}…") + } +} + +fn print_table(cols: &[String], rows: &[Vec]) { + let mut widths: Vec = cols.iter().map(|c| c.chars().count()).collect(); + for r in rows { + for (i, c) in r.iter().enumerate() { + widths[i] = widths[i].max(c.chars().count()); + } + } + let fmt_row = |cells: &[String]| -> String { + cells + .iter() + .enumerate() + .map(|(i, c)| { + let pad = widths[i] - c.chars().count(); + format!("{}{}", c, " ".repeat(pad)) + }) + .collect::>() + .join(" ") + }; + println!("{}", fmt_row(cols)); + let dashes: Vec = cols.iter().map(|c| "-".repeat(c.chars().count())).collect(); + println!("{}", fmt_row(&dashes)); + for r in rows { + println!("{}", fmt_row(r)); + } +} + +// --------------------------------------------------------------------------- +// Argument parsing (argparse-shaped subset the fleet uses) +// --------------------------------------------------------------------------- + +struct Args { + pos: Vec, + opts: Map, +} + +fn parse_args(rest: &[String], flags: &[&str], bools: &[&str]) -> Args { + let mut pos = Vec::new(); + let mut opts = Map::new(); + let mut i = 0; + while i < rest.len() { + let a = &rest[i]; + if let Some(long) = a.strip_prefix("--") { + let (name, inline) = match long.split_once('=') { + Some((n, v)) => (n.to_string(), Some(v.to_string())), + None => (long.to_string(), None), + }; + if bools.contains(&name.as_str()) { + opts.insert(name, Value::Bool(true)); + i += 1; + } else if flags.contains(&name.as_str()) { + if let Some(v) = inline { + opts.insert(name, Value::String(v)); + i += 1; + } else if i + 1 < rest.len() { + opts.insert(name, Value::String(rest[i + 1].clone())); + i += 2; + } else { + die(2, &format!("argument --{name}: expected one argument")); + } + } else { + die(2, &format!("unrecognized argument: --{name}")); + } + } else { + pos.push(a.clone()); + i += 1; + } + } + Args { pos, opts } +} + +impl Args { + fn get(&self, name: &str) -> Option { + self.opts + .get(name) + .and_then(|v| v.as_str()) + .map(|s| s.to_string()) + } + fn has(&self, name: &str) -> bool { + self.opts.contains_key(name) + } + fn get_i64(&self, name: &str) -> Option { + self.get(name).and_then(|s| s.parse().ok()) + } + fn pos_i64(&self, idx: usize, what: &str) -> i64 { + match self.pos.get(idx).and_then(|s| s.parse::().ok()) { + Some(n) => n, + None => die(2, &format!("argument {what}: invalid int value")), + } + } +} + +fn default_queue() -> String { + std::env::var("REPO_QUEUE_DEFAULT_QUEUE").unwrap_or_else(|_| DEFAULT_QUEUE.to_string()) +} + +fn opt_queue(args: &Args) -> String { + args.get("queue").unwrap_or_else(default_queue) +} + +fn opt_worker(args: &Args) -> String { + args.get("worker") + .unwrap_or_else(|| DEFAULT_WORKER.to_string()) +} + +fn load_packet(path: &str) -> Value { + let text = match std::fs::read_to_string(path) { + Ok(t) => t, + Err(e) => die(2, &format!("cannot read packet file: {e}")), + }; + match serde_json::from_str(&text) { + Ok(v) => v, + Err(e) => die(2, &format!("packet file is not valid JSON: {e}")), + } +} + +fn progress_arg(args: &Args) -> Option { + let raw = args.get("progress"); + let pfile = args.get("progress-file"); + if raw.is_some() && pfile.is_some() { + die(2, "pass only one of --progress / --progress-file"); + } + let raw = if let Some(f) = pfile { + match std::fs::read_to_string(&f) { + Ok(t) => Some(t), + Err(e) => die(2, &format!("cannot read progress file: {e}")), + } + } else { + raw + }; + let raw = raw?; + let val: Value = match serde_json::from_str(&raw) { + Ok(v) => v, + Err(e) => die(2, &format!("--progress is not valid JSON: {e}")), + }; + if !val.is_object() { + die(2, "--progress must be a JSON object"); + } + Some(val) +} + +fn execution_arg(args: &Args) -> Option { + let raw = args.get("execution")?; + let val: Value = match serde_json::from_str(&raw) { + Ok(v) => v, + Err(e) => die(2, &format!("--execution is not valid JSON: {e}")), + }; + if !val.is_object() { + die(2, "--execution must be a JSON object"); + } + if let Some(lane) = val.get("lane") { + if lane != &json!("opencode") && lane != &json!("direct") { + die(2, "--execution.lane must be 'opencode' or 'direct'"); + } + } + Some(val) +} + +fn py_str_list(items: &[String]) -> String { + let inner: Vec = items.iter().map(|s| format!("'{s}'")).collect(); + format!("[{}]", inner.join(", ")) +} + +fn check_telemetry_fields(obj: &Value, source: &str) { + for field in TELEMETRY_FIELDS { + let Some(v) = obj.get(field) else { continue }; + if v.is_null() { + continue; + } + if field == "cost_usd" { + let ok = matches!(v, Value::Number(n) if n.as_f64().map(|x| x >= 0.0).unwrap_or(false)); + if !ok { + die( + 2, + &format!( + "{source}: telemetry field 'cost_usd' must be a non-negative number or null" + ), + ); + } + } else if !matches!(v, Value::String(s) if !s.is_empty()) { + die( + 2, + &format!("{source}: telemetry field '{field}' must be a non-empty string or null"), + ); + } + } +} + +/// Shared validate flow for `validate` and `enqueue`: returns warnings +/// after printing them; dies (exit 2) on errors exactly like +/// repo-queue.py's check_packet. +fn validate_via_broker(packet: &Value, quiet: bool) -> Vec { + let resp = call("/validate", &json!({"packet": packet})); + let resp = unwrap_ok(resp); + let warnings: Vec = resp + .get("warnings") + .and_then(|w| w.as_array()) + .map(|a| { + a.iter() + .filter_map(|w| w.as_str().map(|s| s.to_string())) + .collect() + }) + .unwrap_or_default(); + let errors: Vec = resp + .get("errors") + .and_then(|w| w.as_array()) + .map(|a| { + a.iter() + .filter_map(|w| w.as_str().map(|s| s.to_string())) + .collect() + }) + .unwrap_or_default(); + for w in &warnings { + eprint(&format!("warning: {w}")); + } + if !errors.is_empty() { + for e in &errors { + eprint(&format!("error: {e}")); + } + die( + 2, + &format!("packet validation failed ({} error(s))", errors.len()), + ); + } + if !quiet { + eprint("packet valid (repo-task/v1)"); + } + warnings +} + +// --------------------------------------------------------------------------- +// Subcommands +// --------------------------------------------------------------------------- + +fn cmd_validate(rest: &[String]) -> i32 { + let args = parse_args(rest, &[], &[]); + let path = args + .pos + .first() + .cloned() + .unwrap_or_else(|| die(2, "validate: packet required")); + let packet = load_packet(&path); + validate_via_broker(&packet, false); + print_json(&json!({ + "valid": true, + "dedupe_key": packet.get("dedupe_key").cloned().unwrap_or(Value::Null), + "kind": packet.get("payload").and_then(|p| p.get("kind")).cloned().unwrap_or(Value::Null), + "title": packet.get("title").cloned().unwrap_or(Value::Null), + })); + 0 +} + +fn cmd_enqueue(rest: &[String]) -> i32 { + let args = parse_args(rest, &["queue"], &["dry-run"]); + let path = args + .pos + .first() + .cloned() + .unwrap_or_else(|| die(2, "enqueue: packet required")); + let packet = load_packet(&path); + let dry_run = args.has("dry-run"); + validate_via_broker(&packet, dry_run); + let queue = opt_queue(&args); + let call_started = now_micros(); + let resp = call( + "/enqueue", + &json!({"packet": packet, "queue": queue, "dry_run": dry_run}), + ); + let resp = unwrap_ok(resp); + if dry_run { + let mut task = resp.get("task").cloned().unwrap_or(json!({})); + if let Some(o) = task.as_object_mut() { + o.insert("_dry_run".to_string(), Value::Bool(true)); + o.insert("_rpc".to_string(), json!("agent.enqueue_repo_task")); + } + print_json(&task); + return 0; + } + let row = resp.get("row").cloned().unwrap_or(Value::Null); + // Outcome classification (mirrors _enqueue_outcome in repo-queue.py). + let tid = row.get("id").cloned().unwrap_or(Value::Null); + let q = row + .get("queue") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let s = row + .get("status") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let created_raw = row.get("created_at").cloned().unwrap_or(Value::Null); + let created = parse_ts(&created_raw); + let updated = parse_ts(&row.get("updated_at").cloned().unwrap_or(Value::Null)); + let skew = 10_000_000i64; // 10 s in micros + let mut warnings: Vec = Vec::new(); + let line; + if created.map(|c| c >= call_started - skew).unwrap_or(false) { + line = format!( + "enqueued new task {} (queue {q}, status {s})", + fmt_cell(Some(&tid)) + ); + } else { + if q != queue { + warnings.push(format!( + "dedupe hit is in a different queue ({q} != requested {queue})" + )); + } + if s == "queued" && updated.map(|u| u >= call_started - skew).unwrap_or(false) { + line = format!( + "revived: existing task {} (queue {q}, status {s}, created {})", + fmt_cell(Some(&tid)), + fmt_cell(Some(&created_raw)) + ); + } else { + if TERMINAL_STATUSES.contains(&s.as_str()) { + warnings.push(format!("dedupe hit is in a terminal state (status {s})")); + } + line = format!( + "dedupe hit: existing task {} (queue {q}, status {s}, created {})", + fmt_cell(Some(&tid)), + fmt_cell(Some(&created_raw)) + ); + } + } + println!("{line}"); + for w in &warnings { + println!("warning: {w}"); + } + print_json(&row); + 0 +} + +fn cmd_list(rest: &[String]) -> i32 { + let args = parse_args(rest, &["queue", "status", "limit", "not-before"], &[]); + let resp = call( + "/list", + &json!({ + "queue": opt_queue(&args), + "status": args.get("status"), + "limit": args.get_i64("limit").unwrap_or(20), + "not_before": args.get("not-before"), + }), + ); + let resp = unwrap_ok(resp); + let rows = resp + .get("rows") + .and_then(|r| r.as_array()) + .cloned() + .unwrap_or_default(); + if rows.is_empty() { + println!("(no tasks)"); + return 0; + } + let cols: Vec = ["task", "priority", "status", "age", "dedupe_key", "title"] + .iter() + .map(|s| s.to_string()) + .collect(); + let str_rows: Vec> = rows + .iter() + .map(|r| { + vec![ + format!("task {}", fmt_cell(r.get("id"))), + fmt_cell(r.get("priority")), + fmt_cell(r.get("status")), + age_str(&r.get("created_at").cloned().unwrap_or(Value::Null)), + fmt_cell(r.get("dedupe_key")), + truncate(&fmt_cell(r.get("title")), 72), + ] + }) + .collect(); + print_table(&cols, &str_rows); + 0 +} + +fn cmd_claim(rest: &[String]) -> i32 { + let args = parse_args(rest, &["queue", "worker", "lease-seconds", "lane"], &[]); + let mut body = json!({ + "queue": opt_queue(&args), + "worker": opt_worker(&args), + "lease_seconds": args.get_i64("lease-seconds").unwrap_or(2700), + }); + if let Some(lane) = args.get("lane") { + body["lane"] = json!(lane); + } + let resp = unwrap_ok(call("/claim", &body)); + let row = resp.get("row").cloned().unwrap_or(Value::Null); + if row.is_null() { + eprint("repo-queue: no claimable task"); + print_json(&json!({"task": Value::Null})); + return 5; + } + print_json(&row); + 0 +} + +fn cmd_lane(rest: &[String]) -> i32 { + let args = parse_args(rest, &["worker", "exclusion-reason"], &[]); + let resp = unwrap_ok(call( + "/lane", + &json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "exclusion_reason": args.get("exclusion-reason"), + }), + )); + print_json(&require_row(&resp, "assign_repo_task_lane")); + 0 +} + +fn cmd_bind(rest: &[String]) -> i32 { + let args = parse_args(rest, &["worker", "session-id", "launched-by"], &[]); + let session_id = args + .get("session-id") + .unwrap_or_else(|| die(2, "bind: --session-id is required")); + let resp = unwrap_ok(call( + "/bind", + &json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "session_id": session_id, + "launched_by": args.get("launched-by").unwrap_or_else(|| "opencode-claimant".to_string()), + }), + )); + print_json(&require_row(&resp, "bind_repo_task_lane_session")); + 0 +} + +fn cmd_heartbeat(rest: &[String]) -> i32 { + let args = parse_args( + rest, + &["worker", "extend-seconds", "progress", "progress-file"], + &[], + ); + let resp = unwrap_ok(call( + "/heartbeat", + &json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "extend_seconds": args.get_i64("extend-seconds").unwrap_or(900), + "progress": progress_arg(&args), + }), + )); + print_json(&require_row(&resp, "heartbeat_task")); + 0 +} + +fn cmd_checkpoint(rest: &[String]) -> i32 { + let args = parse_args(rest, &["worker", "stage", "progress", "progress-file"], &[]); + let stage = args + .get("stage") + .unwrap_or_else(|| die(2, "checkpoint: --stage is required")); + let resp = unwrap_ok(call( + "/checkpoint", + &json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "stage": stage, + "progress": progress_arg(&args).unwrap_or(json!({})), + }), + )); + print_json(&require_row(&resp, "checkpoint_task")); + 0 +} + +fn cmd_park(rest: &[String]) -> i32 { + let args = parse_args( + rest, + &[ + "worker", + "reason", + "delay-seconds", + "not-before", + "progress", + "progress-file", + "ready-condition", + "execution", + ], + &[], + ); + if args.has("delay-seconds") && args.has("not-before") { + die( + 2, + "argument --not-before: not allowed with argument --delay-seconds", + ); + } + let reason = args + .get("reason") + .unwrap_or_else(|| die(2, "park: --reason is required")); + let mut body = json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "reason": reason, + "progress": progress_arg(&args).unwrap_or(json!({})), + }); + if let Some(nb) = args.get("not-before") { + body["not_before"] = json!(nb); + } else if let Some(d) = args.get_i64("delay-seconds") { + body["delay_seconds"] = json!(d); + } + if let Some(rc_raw) = args.get("ready-condition") { + let rc: Value = match serde_json::from_str(&rc_raw) { + Ok(v) => v, + Err(e) => die(2, &format!("--ready-condition is not valid JSON: {e}")), + }; + if !rc.is_object() { + die(2, "--ready-condition must be a JSON object"); + } + body["ready_condition"] = rc; + } + if let Some(ex) = execution_arg(&args) { + body["execution"] = ex; + } + let resp = unwrap_ok(call("/park", &body)); + row_or_ledger(&resp, "park_task"); + 0 +} + +fn cmd_block(rest: &[String]) -> i32 { + let args = parse_args( + rest, + &[ + "worker", + "reason-class", + "blocker", + "progress", + "progress-file", + ], + &[], + ); + let rc = args + .get("reason-class") + .unwrap_or_else(|| die(2, "block: --reason-class is required")); + let blocker = args + .get("blocker") + .unwrap_or_else(|| die(2, "block: --blocker is required")); + let resp = unwrap_ok(call( + "/block", + &json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "reason_class": rc, + "blocker": blocker, + "progress": progress_arg(&args).unwrap_or(json!({})), + }), + )); + print_json(&require_row(&resp, "block_task")); + 0 +} + +fn cmd_cancel(rest: &[String]) -> i32 { + let args = parse_args(rest, &["worker", "reason"], &[]); + let reason = args + .get("reason") + .unwrap_or_else(|| die(2, "cancel: --reason is required")); + let worker = args + .get("worker") + .unwrap_or_else(|| "fleet-monitor".to_string()); + let resp = unwrap_ok(call( + "/cancel", + &json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": worker, + "reason": reason, + }), + )); + print_json(&require_row(&resp, "cancel_repo_task")); + 0 +} + +fn cmd_fail(rest: &[String]) -> i32 { + let args = parse_args(rest, &["worker", "error", "reason-class", "execution"], &[]); + let error = args + .get("error") + .unwrap_or_else(|| die(2, "fail: --error is required")); + let reason_class = args + .get("reason-class") + .unwrap_or_else(|| "transient".to_string()); + if !["transient", "deterministic", "blocked"].contains(&reason_class.as_str()) { + die( + 2, + &format!("argument --reason-class: invalid choice: '{reason_class}'"), + ); + } + let mut body = json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "error": error, + "reason_class": reason_class, + }); + if let Some(ex) = execution_arg(&args) { + body["execution"] = ex; + } + let resp = unwrap_ok(call("/fail", &body)); + row_or_ledger(&resp, "fail_repo_task"); + 0 +} + +fn cmd_complete(rest: &[String]) -> i32 { + let args = parse_args( + rest, + &["worker", "result", "result-file", "telemetry", "execution"], + &[], + ); + let mut result_raw = args.get("result"); + if let Some(f) = args.get("result-file") { + result_raw = Some(match std::fs::read_to_string(&f) { + Ok(t) => t, + Err(e) => die(2, &format!("cannot read result file: {e}")), + }); + } + let mut result_obj = json!({}); + if let Some(raw) = result_raw { + if !raw.is_empty() { + result_obj = match serde_json::from_str(&raw) { + Ok(v) => v, + Err(e) => die(2, &format!("--result is not valid JSON: {e}")), + }; + if !result_obj.is_object() { + die(2, "--result must be a JSON object"); + } + } + } + check_telemetry_fields(&result_obj, "--result"); + if let Some(tel_raw) = args.get("telemetry") { + let tel: Value = match serde_json::from_str(&tel_raw) { + Ok(v) => v, + Err(e) => die(2, &format!("--telemetry is not valid JSON: {e}")), + }; + if !tel.is_object() { + die(2, "--telemetry must be a JSON object"); + } + let unknown: Vec = tel + .as_object() + .unwrap() + .keys() + .filter(|k| !TELEMETRY_FIELDS.contains(&k.as_str())) + .cloned() + .collect(); + if !unknown.is_empty() { + let mut sorted = unknown.clone(); + sorted.sort(); + die( + 2, + &format!( + "--telemetry: unknown field(s) {}; allowed: {}", + py_str_list(&sorted), + py_str_list( + &TELEMETRY_FIELDS + .iter() + .map(|s| s.to_string()) + .collect::>() + ) + ), + ); + } + check_telemetry_fields(&tel, "--telemetry"); + for field in TELEMETRY_FIELDS { + if tel.get(field).is_some() && result_obj.get(field).is_none() { + result_obj[field] = tel[field].clone(); + } + } + } + let ex = execution_arg(&args); + if let Some(ex) = &ex { + if result_obj.get("execution").is_none() { + let mut block = Map::new(); + block.insert( + "lane".to_string(), + ex.get("lane").cloned().unwrap_or(Value::Null), + ); + block.insert( + "session_id".to_string(), + ex.get("session_id").cloned().unwrap_or(Value::Null), + ); + let has_fb = ex + .get("fallback_reason") + .map(|v| !v.is_null()) + .unwrap_or(false); + block.insert("fallback".to_string(), Value::Bool(has_fb)); + if has_fb { + block.insert("fallback_reason".to_string(), ex["fallback_reason"].clone()); + } + if let Some(a) = ex.get("assigned") { + block.insert("assigned".to_string(), a.clone()); + } + result_obj["execution"] = Value::Object(block); + } + } + let mut body = json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "result": result_obj, + }); + if let Some(ex) = ex { + body["execution"] = ex; + } + let resp = unwrap_ok(call("/complete", &body)); + row_or_ledger(&resp, "complete_task"); + 0 +} + +fn cmd_health(rest: &[String]) -> i32 { + let args = parse_args(rest, &["queue"], &[]); + let mut body = json!({}); + if let Some(q) = args.get("queue") { + body["queue"] = json!(q); + } + let resp = unwrap_ok(call("/health", &body)); + let netloc = resp + .get("project_netloc") + .and_then(|v| v.as_str()) + .unwrap_or(""); + let source = resp + .get("project_source") + .and_then(|v| v.as_str()) + .unwrap_or("bitwarden"); + println!("project: {netloc} (resolved via {source})"); + let rows = resp + .get("rows") + .and_then(|r| r.as_array()) + .cloned() + .unwrap_or_default(); + if rows.is_empty() { + println!("(no queues have tasks)"); + return 0; + } + let cols: Vec = rows[0] + .as_object() + .map(|o| o.keys().cloned().collect()) + .unwrap_or_default(); + let str_rows: Vec> = rows + .iter() + .map(|r| cols.iter().map(|c| fmt_cell(r.get(c))).collect()) + .collect(); + print_table(&cols, &str_rows); + 0 +} + +fn cmd_signal(rest: &[String]) -> i32 { + let args = parse_args(rest, &["queue", "reason"], &[]); + let queue = opt_queue(&args); + let reason = args + .get("reason") + .unwrap_or_else(|| "manual_signal".to_string()); + let resp = unwrap_ok(call("/signal-count", &json!({"queue": queue}))); + let queued_count = resp.get("queued_count").cloned().unwrap_or(json!(0)); + let oldest = resp.get("oldest_queued_at").cloned().unwrap_or(Value::Null); + + let signal_path = std::env::var("REPO_QUEUE_SIGNAL_PATH").unwrap_or_else(|_| { + format!( + "{}/workspace/goals/keep-the-four-repos-healthy/hidden_files/repo-queue-signal.json", + home() + ) + }); + let dir = std::path::Path::new(&signal_path) + .parent() + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default(); + let state_path = format!("{dir}/repo-queue-signal-state.json"); + let mut generation: i64 = 0; + for candidate in [&signal_path, &state_path] { + if let Ok(text) = std::fs::read_to_string(candidate) { + if let Ok(prev) = serde_json::from_str::(&text) { + if prev.get("queue").and_then(|q| q.as_str()) == Some(queue.as_str()) { + if let Some(g) = prev.get("generation").and_then(|g| g.as_i64()) { + generation = generation.max(g); + } + } + } + } + } + generation += 1; + let updated = utcnow_iso(); + let signal = json!({ + "queue": queue, + "generation": generation, + "queued_count": queued_count, + "oldest_queued_at": oldest, + "updated_at": updated, + "reason": reason, + }); + let state = json!({ + "queue": queue, + "generation": generation, + "updated_at": updated, + }); + let _ = std::fs::create_dir_all(&dir); + atomic_write_json(&signal_path, &signal); + atomic_write_json(&state_path, &state); + print_json(&signal); + 0 +} + +fn atomic_write_json(path: &str, obj: &Value) { + let tmp = format!("{path}.tmp{}", std::process::id()); + let mut text = serde_json::to_string_pretty(obj).unwrap_or_default(); + text.push('\n'); + match std::fs::write(&tmp, &text).and_then(|_| std::fs::rename(&tmp, path)) { + Ok(_) => {} + Err(e) => { + let _ = std::fs::remove_file(&tmp); + die(3, &format!("cannot write {path}: {e}")); + } + } +} + +pub fn run(args: &[String]) -> i32 { + if args.is_empty() { + eprint( + "usage: repo-queue ...", + ); + return 2; + } + let sub = args[0].as_str(); + let rest = &args[1..]; + match sub { + "validate" => cmd_validate(rest), + "enqueue" => cmd_enqueue(rest), + "list" => cmd_list(rest), + "claim" => cmd_claim(rest), + "lane" => cmd_lane(rest), + "bind" => cmd_bind(rest), + "heartbeat" => cmd_heartbeat(rest), + "checkpoint" => cmd_checkpoint(rest), + "park" => cmd_park(rest), + "block" => cmd_block(rest), + "cancel" => cmd_cancel(rest), + "fail" => cmd_fail(rest), + "complete" => cmd_complete(rest), + "health" => cmd_health(rest), + "signal" => cmd_signal(rest), + _ => { + eprint(&format!("repo-queue: unknown command {sub:?}")); + 2 + } + } +} diff --git a/pkgs/fleet/crates/fleet-queue/src/lib.rs b/pkgs/fleet/crates/fleet-queue/src/lib.rs new file mode 100644 index 0000000000..8fa8911ce1 --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/lib.rs @@ -0,0 +1,32 @@ +//! fleet-queue — the queue domain of the fleet multicall binary +//! (design note §1/§6, epic developing-today/code#5412; step 2, +//! #5430: the pilot). +//! +//! This crate is the first real source home of the broker family +//! (code#5362): the `repo-queue` client surface and the +//! queue-broker + secrets-broker server roles, ported from the +//! sandbox `~/tools/fleet-brokers` workspace (archived in place the +//! day this landed; the laptop's `~/fleet-brokers/bin` copy is +//! superseded by the unit flips of the same step). Wire behavior is +//! preserved exactly — the brokers speak to existing clients, and +//! the laptop-agent session proxy keeps working as a client of the +//! brokers — while the internals sit on the platform crates: +//! secrets resolve by name through `fleet-secrets`, and logging is +//! one facility with the domain as a field ([`log`]). +//! +//! Surfaces are feature-gated so each shipped variant compiles +//! exactly what it carries: `client`, `queue-broker`, +//! `secrets-broker`. The crate also ships the three standalone +//! binaries under their historical names (src/bin/) — the +//! migration's standing rollback inventory (design note §7). + +pub mod log; + +#[cfg(feature = "client")] +pub mod client; +#[cfg(feature = "queue-broker")] +pub mod queue_broker; +#[cfg(feature = "secrets-broker")] +pub mod secrets_broker; +#[cfg(feature = "queue-broker")] +pub mod validate; diff --git a/pkgs/fleet/crates/fleet-queue/src/log.rs b/pkgs/fleet/crates/fleet-queue/src/log.rs new file mode 100644 index 0000000000..5d2feaf12b --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/log.rs @@ -0,0 +1,12 @@ +//! The queue domain's one logging facility (design note §1). +//! +//! Every line carries the domain as its field — the established +//! `: ` shape the brokers have always emitted on +//! stderr — so one journal query follows a request across client, +//! queue-broker, and secrets-broker, and the port changed no log +//! text anyone already greps for. + +/// Emit one stderr line for `domain`: `": "`. +pub fn info(domain: &str, message: &str) { + eprintln!("{domain}: {message}"); +} diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs new file mode 100644 index 0000000000..e7ae56e825 --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -0,0 +1,664 @@ +//! queue-broker — the repo-health queue as a resident laptop service +//! (code#5362). Server-side port of repo-queue.py's HTTP layer: the +//! Supabase service-role key lives only here, fetched from the +//! secrets broker; all queue semantics stay in the Postgres RPCs. +//! Sandbox clients reach it only through the session proxy. +//! +//! Protocol: POST / with a JSON args object; response is a +//! JSON envelope {ok:true, ...} or {ok:false, exit, error} where exit +//! mirrors repo-queue.py's exit codes (2 validation, 3 config, 4 HTTP, +//! 5 no row). Auth: X-Agent-Token header. +//! +//! Env: QUEUE_BROKER_BIND (default 100.99.113.103:4801), +//! QUEUE_BROKER_TOKEN_FILE (default ~/.config/queue-broker/token), +//! QUEUE_BROKER_SECRETS_URL (default http://100.99.113.103:4800), +//! QUEUE_BROKER_SECRETS_TOKEN_FILE (default ~/.config/secrets-broker/token). + +use std::sync::{Arc, RwLock}; +use std::time::Duration; + +use fleet_secrets::{Resolver, SecretError, SecretSource, SecretValue}; +use serde_json::{Value, json}; +use tiny_http::{Header, Method, Response, Server, StatusCode}; + +const PILOT_REPO: &str = "developing-today/code"; + +#[derive(Clone)] +struct Creds { + key: String, + base: String, // project URL, no trailing slash +} + +struct State { + secrets_url: String, + secrets_token: String, + creds: RwLock>, + agent: ureq::Agent, +} + +struct BErr { + exit: i32, + msg: String, +} + +fn err4(msg: String) -> BErr { + BErr { exit: 4, msg } +} + +/// The queue broker's secrets-by-name source: a direct HTTP call to +/// the secrets broker on this host (the two brokers are colocated; +/// no session proxy sits between them). The wire exchange is the +/// established one — GET /secret/ with the X-Agent-Token +/// header — and the error strings preserve the standalone broker's +/// wording inside the platform crate's error shape. +struct DirectSecrets { + url: String, + token: String, + agent: ureq::Agent, +} + +impl SecretSource for DirectSecrets { + fn source_name(&self) -> &'static str { + "secrets-broker" + } + + fn resolve(&self, name: &str) -> Result { + let unavailable = |detail: String| SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail, + }; + let url = format!("{}/secret/{}", self.url, name); + let mut resp = self + .agent + .get(&url) + .header("X-Agent-Token", &self.token) + .call() + .map_err(|e| unavailable(format!("secrets broker unreachable: {e}")))?; + let status = resp.status().as_u16(); + let text = resp.body_mut().read_to_string().unwrap_or_default(); + if status == 404 { + return Err(SecretError::NotFound { + source: "secrets-broker", + name: name.to_string(), + }); + } + if status >= 300 { + return Err(unavailable(format!( + "secrets broker HTTP {status} for {name}: {}", + trim(&text, 200) + ))); + } + let v: Value = serde_json::from_str(&text) + .map_err(|e| unavailable(format!("secrets broker bad JSON for {name}: {e}")))?; + v.get("value") + .and_then(|x| x.as_str()) + .map(|s| SecretValue::from_resolved(s.to_string())) + .ok_or(SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: format!("secrets broker response for {name} has no value"), + }) + } +} + +impl State { + fn fetch_creds(&self) -> Result { + // Secrets resolve by name through the platform crate + // (fleet-secrets, design §1): the one-off HTTP exchange with + // the colocated secrets broker is a SecretSource, and the + // names flow through validate_name / SecretValue / the chain + // error shape like every other fleet consumer. + let resolver = Resolver::new(vec![Box::new(DirectSecrets { + url: self.secrets_url.clone(), + token: self.secrets_token.clone(), + agent: self.agent.clone(), + })]); + let get_secret = |name: &str| -> Result { + resolver + .resolve(name) + .map(|v| v.expose().to_string()) + .map_err(|e| BErr { + exit: 3, + msg: e.to_string(), + }) + }; + // Startup race: the secrets broker may still be doing its first + // vault load; retry 503s for up to ~60 s. + let mut last_err = None; + for _ in 0..20 { + match ( + get_secret("supabase.muse-dev2.service-role-key"), + get_secret("supabase.muse-dev2.project-url"), + ) { + (Ok(key), Ok(url)) => { + let creds = Creds { + key, + base: url.trim_end_matches('/').to_string(), + }; + *self.creds.write().unwrap() = Some(creds.clone()); + return Ok(creds); + } + (Err(e), _) | (_, Err(e)) => { + let retryable = e.msg.contains("503"); + last_err = Some(e); + if !retryable { + break; + } + std::thread::sleep(Duration::from_secs(3)); + } + } + } + Err(last_err.unwrap_or(BErr { + exit: 3, + msg: "credential fetch failed".into(), + })) + } + + fn creds(&self) -> Result { + if let Some(c) = self.creds.read().unwrap().clone() { + return Ok(c); + } + self.fetch_creds() + } + + /// One PostgREST request. Returns (parsed body, content-range). + fn postgrest( + &self, + method: &str, + path: &str, + body: Option<&Value>, + count_exact: bool, + ) -> Result<(Value, Option), BErr> { + for attempt in 0..2 { + let creds = self.creds()?; + let url = format!("{}/rest/v1/{}", creds.base, path); + let bearer = format!("Bearer {}", creds.key); + let mut headers: Vec<(&str, &str)> = vec![ + ("apikey", &creds.key), + ("Authorization", &bearer), + ("Accept-Profile", "agent"), + ]; + if method != "GET" { + headers.push(("Content-Profile", "agent")); + headers.push(("Content-Type", "application/json")); + } + if count_exact { + headers.push(("Prefer", "count=exact")); + } + // ureq's builders are typestated (WithBody vs WithoutBody), + // so each arm applies the same header set itself. + let sent = match (method, body) { + ("GET", _) => { + let mut r = self.agent.get(&url); + for (k, v) in &headers { + r = r.header(*k, *v); + } + r.call() + } + (_, Some(b)) => { + let mut r = self.agent.post(&url); + for (k, v) in &headers { + r = r.header(*k, *v); + } + r.send_json(b.clone()) + } + (_, None) => { + let mut r = self.agent.post(&url); + for (k, v) in &headers { + r = r.header(*k, *v); + } + r.send("") + } + }; + let mut resp = sent.map_err(|e| err4(format!("PostgREST request failed: {e}")))?; + let status = resp.status().as_u16(); + let content_range = resp + .headers() + .get("content-range") + .and_then(|v| v.to_str().ok()) + .map(|s| s.to_string()); + let text = resp.body_mut().read_to_string().unwrap_or_default(); + if status == 401 && attempt == 0 { + // Key may have rotated: refetch from the secrets broker. + *self.creds.write().unwrap() = None; + continue; + } + if status >= 300 { + return Err(err4(format!( + "HTTP {status} from PostgREST: {}", + trim(text.trim(), 500) + ))); + } + let parsed = if text.trim().is_empty() { + Value::Null + } else { + serde_json::from_str(&text) + .map_err(|e| err4(format!("PostgREST returned non-JSON: {e}")))? + }; + return Ok((parsed, content_range)); + } + Err(err4( + "PostgREST request failed after credential refresh".into(), + )) + } + + fn rpc(&self, fn_name: &str, args: Value) -> Result { + let (v, _) = self.postgrest("POST", &format!("rpc/{fn_name}"), Some(&args), false)?; + Ok(v) + } +} + +fn trim(s: &str, n: usize) -> String { + s.chars().take(n).collect() +} + +/// Percent-encode like Python urllib quote(s, safe). +fn quote(s: &str, safe: &str) -> String { + let mut out = String::new(); + for b in s.bytes() { + let c = b as char; + if c.is_ascii_alphanumeric() || "-._~".contains(c) || safe.contains(c) { + out.push(c); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +fn ok(fields: Value) -> Value { + let mut m = json!({"ok": true}); + if let (Some(dst), Some(src)) = (m.as_object_mut(), fields.as_object()) { + for (k, v) in src { + dst.insert(k.clone(), v.clone()); + } + } + m +} + +fn fail(exit: i32, msg: impl Into) -> Value { + json!({"ok": false, "exit": exit, "error": msg.into()}) +} + +fn record_execution(st: &State, req: &Value, row: &Value) -> Result, BErr> { + let Some(ex) = req.get("execution").filter(|e| e.is_object()) else { + return Ok(None); + }; + let ledger = st.rpc( + "record_repo_task_lane_execution", + json!({ + "p_task_id": req.get("task_id"), + "p_worker": req.get("worker"), + "p_executed_lane": ex.get("lane"), + "p_fallback_reason": ex.get("fallback_reason"), + "p_session_id": ex.get("session_id"), + }), + )?; + let _ = row; + Ok(Some(ledger)) +} + +/// Verbs whose RPC takes the args object nearly verbatim. +fn simple_rpc(st: &State, fn_name: &str, args: Value) -> Value { + match st.rpc(fn_name, args) { + Ok(row) => ok(json!({"row": row})), + Err(e) => fail(e.exit, e.msg), + } +} + +fn verb_with_execution(st: &State, fn_name: &str, args: Value, req: &Value) -> Value { + let row = match st.rpc(fn_name, args) { + Ok(r) => r, + Err(e) => return fail(e.exit, e.msg), + }; + if row.is_null() { + return ok(json!({"row": Value::Null})); + } + match record_execution(st, req, &row) { + Ok(Some(ledger)) => ok(json!({"row": row, "lane_ledger": ledger})), + Ok(None) => ok(json!({"row": row})), + Err(e) => fail(e.exit, e.msg), + } +} + +fn dispatch(st: &State, path: &str, req: &Value) -> Value { + match path { + "/validate" => { + let packet = req.get("packet").cloned().unwrap_or(Value::Null); + let (errors, warnings) = crate::validate::validate_packet(&packet); + ok(json!({"errors": errors, "warnings": warnings})) + } + "/enqueue" => { + let packet = req.get("packet").cloned().unwrap_or(Value::Null); + let (errors, warnings) = crate::validate::validate_packet(&packet); + if !errors.is_empty() { + return json!({ + "ok": false, "exit": 2, + "error": format!("packet validation failed ({} error(s))", errors.len()), + "errors": errors, "warnings": warnings, + }); + } + let queue = req + .get("queue") + .and_then(|q| q.as_str()) + .unwrap_or("") + .to_string(); + let task = crate::validate::task_from_packet(&packet, &queue); + if req + .get("dry_run") + .and_then(|d| d.as_bool()) + .unwrap_or(false) + { + return ok(json!({"dry_run": true, "task": task, "warnings": warnings})); + } + let repo = packet + .get("payload") + .and_then(|p| p.get("repo")) + .and_then(|r| r.as_str()) + .map(|s| s.to_string()); + let rpc_name = match repo.as_deref() { + None | Some(PILOT_REPO) => "enqueue_repo_task", + _ => "enqueue_repo_task_fleet", + }; + let args = json!({ + "p_queue": task.get("queue"), + "p_title": task.get("title"), + "p_body": task.get("body"), + "p_payload": task.get("payload"), + "p_dedupe_key": task.get("dedupe_key"), + "p_priority": task.get("priority"), + "p_not_before": task.get("not_before"), + "p_max_attempts": task.get("max_attempts"), + }); + match st.rpc(rpc_name, args) { + Ok(row) if !row.is_null() => { + ok(json!({"row": row, "rpc": rpc_name, "warnings": warnings})) + } + Ok(_) => fail(5, format!("{rpc_name} returned no row")), + Err(e) => fail(e.exit, e.msg), + } + } + "/claim" => { + let mut args = json!({ + "p_worker": req.get("worker"), + "p_queue": req.get("queue"), + "p_lease_seconds": req.get("lease_seconds"), + }); + if let Some(lane) = req.get("lane").filter(|l| !l.is_null()) { + args["p_lane_id"] = lane.clone(); + } + simple_rpc(st, "claim_repo_task", args) + } + "/lane" => simple_rpc( + st, + "assign_repo_task_lane", + json!({ + "p_task_id": req.get("task_id"), + "p_worker": req.get("worker"), + "p_exclusion_reason": req.get("exclusion_reason"), + }), + ), + "/bind" => simple_rpc( + st, + "bind_repo_task_lane_session", + json!({ + "p_task_id": req.get("task_id"), + "p_worker": req.get("worker"), + "p_session_id": req.get("session_id"), + "p_launched_by": req.get("launched_by"), + }), + ), + "/heartbeat" => simple_rpc( + st, + "heartbeat_task", + json!({ + "p_task_id": req.get("task_id"), + "p_worker": req.get("worker"), + "p_extend_seconds": req.get("extend_seconds"), + "p_progress": req.get("progress"), + }), + ), + "/checkpoint" => simple_rpc( + st, + "checkpoint_task", + json!({ + "p_task_id": req.get("task_id"), + "p_worker": req.get("worker"), + "p_stage": req.get("stage"), + "p_progress": req.get("progress").cloned().unwrap_or(json!({})), + }), + ), + "/park" => { + let mut args = json!({ + "p_task_id": req.get("task_id"), + "p_worker": req.get("worker"), + "p_reason": req.get("reason"), + "p_progress": req.get("progress").cloned().unwrap_or(json!({})), + }); + if let Some(nb) = req.get("not_before").filter(|v| !v.is_null()) { + args["p_not_before"] = nb.clone(); + } else if let Some(d) = req.get("delay_seconds").filter(|v| !v.is_null()) { + args["p_delay_seconds"] = d.clone(); + } + if let Some(rc) = req.get("ready_condition").filter(|v| !v.is_null()) { + args["p_ready_condition"] = rc.clone(); + } + verb_with_execution(st, "park_task", args, req) + } + "/block" => simple_rpc( + st, + "block_task", + json!({ + "p_task_id": req.get("task_id"), + "p_worker": req.get("worker"), + "p_reason_class": req.get("reason_class"), + "p_blocker": req.get("blocker"), + "p_progress": req.get("progress").cloned().unwrap_or(json!({})), + }), + ), + "/cancel" => simple_rpc( + st, + "cancel_repo_task", + json!({ + "p_task_id": req.get("task_id"), + "p_worker": req.get("worker"), + "p_reason": req.get("reason"), + }), + ), + "/fail" => verb_with_execution( + st, + "fail_repo_task", + json!({ + "p_task_id": req.get("task_id"), + "p_worker": req.get("worker"), + "p_error": req.get("error"), + "p_reason_class": req.get("reason_class"), + }), + req, + ), + "/complete" => verb_with_execution( + st, + "complete_task", + json!({ + "p_task_id": req.get("task_id"), + "p_worker": req.get("worker"), + "p_result": req.get("result").cloned().unwrap_or(json!({})), + }), + req, + ), + "/list" => { + let queue = req.get("queue").and_then(|q| q.as_str()).unwrap_or(""); + let limit = req.get("limit").and_then(|l| l.as_i64()).unwrap_or(20); + // `rich` adds the claim/binding fields the on-laptop + // opencode claimant's poll.py needs (it reads through the + // broker since the binary-direct migration retired the + // Python helper it used to import). + let select = if req.get("rich").and_then(|r| r.as_bool()).unwrap_or(false) { + "id,queue,title,priority,status,dedupe_key,created_at,not_before,worker_id,lease_until,lane_id,attempts,max_attempts,progress" + } else { + "id,queue,title,priority,status,dedupe_key,created_at,not_before" + }; + let mut path = format!( + "tasks?select={select}&queue=eq.{}&order=priority.asc,created_at.asc&limit={limit}", + quote(queue, "") + ); + if let Some(s) = req.get("status").and_then(|s| s.as_str()) { + path += &format!("&status=eq.{}", quote(s, "")); + } + if let Some(nb) = req.get("not_before").and_then(|s| s.as_str()) { + path += &format!("&or=(not_before.is.null,not_before.lte.{})", quote(nb, ":")); + } + match st.postgrest("GET", &path, None, false) { + Ok((rows, _)) => ok(json!({"rows": rows})), + Err(e) => fail(e.exit, e.msg), + } + } + "/health" => { + let creds = match st.creds() { + Ok(c) => c, + Err(e) => return fail(e.exit, e.msg), + }; + let netloc = creds + .base + .split("://") + .nth(1) + .unwrap_or(&creds.base) + .split('/') + .next() + .unwrap_or("") + .to_string(); + let mut path = "repo_queue_health?select=*".to_string(); + if let Some(q) = req.get("queue").and_then(|q| q.as_str()) { + path += &format!("&queue=eq.{}", quote(q, "")); + } + match st.postgrest("GET", &path, None, false) { + Ok((rows, _)) => ok( + json!({"project_netloc": netloc, "project_source": "bitwarden", "rows": rows}), + ), + Err(e) => fail(e.exit, e.msg), + } + } + "/signal-count" => { + let queue = req.get("queue").and_then(|q| q.as_str()).unwrap_or(""); + let path = format!( + "tasks?select=id,created_at&queue=eq.{}&status=eq.queued&order=created_at.asc&limit=1", + quote(queue, "") + ); + match st.postgrest("GET", &path, None, true) { + Ok((rows, content_range)) => { + let arr = rows.as_array().cloned().unwrap_or_default(); + let mut count = arr.len() as i64; + if let Some(cr) = content_range { + if let Some(total) = cr.rsplit('/').next() { + if let Ok(n) = total.parse::() { + count = n; + } + } + } + let oldest = arr + .first() + .and_then(|r| r.get("created_at")) + .cloned() + .unwrap_or(Value::Null); + ok(json!({"queued_count": count, "oldest_queued_at": oldest})) + } + Err(e) => fail(e.exit, e.msg), + } + } + "/healthz" => ok(json!({"service": "queue-broker"})), + _ => json!({"ok": false, "exit": 2, "error": format!("unknown command {path}")}), + } +} + +fn json_response(status: u16, body: Value) -> Response>> { + let data = serde_json::to_vec(&body).unwrap_or_else(|_| b"{}".to_vec()); + Response::from_data(data) + .with_status_code(StatusCode(status)) + .with_header(Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap()) +} + +fn token_ok(req: &tiny_http::Request, expected: &str) -> bool { + req.headers() + .iter() + .find(|h| h.field.as_str().to_ascii_lowercase() == "x-agent-token") + .map(|h| h.value.as_str() == expected) + .unwrap_or(false) +} + +pub fn run() -> i32 { + let bind = + std::env::var("QUEUE_BROKER_BIND").unwrap_or_else(|_| "100.99.113.103:4801".to_string()); + let home = std::env::var("HOME").expect("HOME unset"); + let token_file = std::env::var("QUEUE_BROKER_TOKEN_FILE") + .unwrap_or_else(|_| format!("{home}/.config/queue-broker/token")); + let token = std::fs::read_to_string(&token_file) + .map(|t| t.trim().to_string()) + .unwrap_or_else(|_| { + crate::log::info( + "queue-broker", + &format!("cannot read token file {token_file}"), + ); + std::process::exit(3); + }); + let secrets_url = std::env::var("QUEUE_BROKER_SECRETS_URL") + .unwrap_or_else(|_| "http://100.99.113.103:4800".to_string()); + let secrets_token_file = std::env::var("QUEUE_BROKER_SECRETS_TOKEN_FILE") + .unwrap_or_else(|_| format!("{home}/.config/secrets-broker/token")); + let secrets_token = std::fs::read_to_string(&secrets_token_file) + .map(|t| t.trim().to_string()) + .unwrap_or_else(|_| { + crate::log::info( + "queue-broker", + &format!("cannot read secrets token file {secrets_token_file}"), + ); + std::process::exit(3); + }); + + let agent: ureq::Agent = ureq::Agent::config_builder() + .http_status_as_error(false) + .timeout_global(Some(Duration::from_secs(90))) + .build() + .into(); + let state = Arc::new(State { + secrets_url, + secrets_token, + creds: RwLock::new(None), + agent, + }); + + let server = Server::http(&bind).unwrap_or_else(|e| { + crate::log::info("queue-broker", &format!("cannot bind {bind}: {e:?}")); + std::process::exit(3); + }); + crate::log::info("queue-broker", &format!("listening on {bind}")); + for mut req in server.incoming_requests() { + let state = Arc::clone(&state); + let token = token.clone(); + std::thread::spawn(move || { + let path = req.url().split('?').next().unwrap_or("").to_string(); + let resp = if req.method() == &Method::Get && path == "/healthz" { + json_response(200, ok(json!({"service": "queue-broker"}))) + } else if !token_ok(&req, &token) { + json_response(401, json!({"error": "unauthorized"})) + } else if req.method() != &Method::Post { + json_response(405, json!({"error": "POST only"})) + } else { + let mut buf = String::new(); + match req.as_reader().read_to_string(&mut buf) { + Ok(_) => { + let parsed: Value = serde_json::from_str(&buf).unwrap_or(Value::Null); + json_response(200, dispatch(&state, &path, &parsed)) + } + Err(e) => json_response( + 400, + json!({"ok": false, "exit": 2, "error": format!("bad body: {e}")}), + ), + } + }; + let _ = req.respond(resp); + }); + } + // incoming_requests() ends only when the server stops. + 0 +} diff --git a/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs b/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs new file mode 100644 index 0000000000..d40dfe0718 --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs @@ -0,0 +1,290 @@ +//! secrets-broker — resident Bitwarden Secrets Manager cache (code#5362). +//! +//! Fetches the vault's secrets ONCE per TTL via the `bws` CLI on the +//! laptop and serves them to token-authed local consumers, replacing the +//! per-call `bws secret list` + `get` fetch that made every +//! repo-queue.py invocation pay 10-40 s. Binds the laptop tailnet IP +//! only; consumers reach it through the sandbox session proxy. +//! +//! Endpoints (header `X-Agent-Token` required except /health): +//! GET /health -> {ok, secrets, last_refresh_unix, refreshing} +//! GET /secrets -> {names: [...]} +//! GET /secret/ -> {key, value} | 404 | 503 (not loaded yet) +//! +//! Env: SECRETS_BROKER_BIND (default 100.99.113.103:4800), +//! SECRETS_BROKER_TOKEN_FILE (default ~/.config/secrets-broker/token), +//! SECRETS_BROKER_TTL_S (default 900). + +use std::collections::HashMap; +use std::process::Command; +use std::sync::{Arc, RwLock}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde_json::{Value, json}; +use tiny_http::{Header, Method, Response, Server, StatusCode}; + +struct State { + secrets: RwLock>, + last_refresh: RwLock>, + refreshing: RwLock, +} + +fn now_unix() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn bws_token() -> Option { + if let Ok(t) = std::env::var("BWS_ACCESS_TOKEN") { + if !t.trim().is_empty() { + return Some(t.trim().to_string()); + } + } + let home = std::env::var("HOME").ok()?; + for rel in [".config/bitwarden/access-token", ".config/bws/access-token"] { + if let Ok(t) = std::fs::read_to_string(format!("{home}/{rel}")) { + if !t.trim().is_empty() { + return Some(t.trim().to_string()); + } + } + } + None +} + +/// Runs `bws` for the vault refresh, through the platform crate's +/// CommandRunner discipline (fleet-secrets, design §1): stdout on +/// success; on failure the error carries the exit status only — +/// never stderr, which could quote vault material. (The standalone +/// broker included a trimmed stderr excerpt in this log-only error; +/// the port deliberately adopts the stricter platform rule.) +struct BwsRunner { + token: String, +} + +impl fleet_secrets::CommandRunner for BwsRunner { + fn run(&self, program: &str, args: &[&str]) -> Result { + let out = Command::new(program) + .args(args) + .env("BWS_ACCESS_TOKEN", &self.token) + .output() + .map_err(|e| format!("spawn failed: {}", e.kind()))?; + if !out.status.success() { + return Err(out.status.to_string()); + } + String::from_utf8(out.stdout).map_err(|_| "output not utf8".to_string()) + } +} + +fn bws_run(args: &[&str], token: &str) -> Result { + let runner = BwsRunner { + token: token.to_string(), + }; + fleet_secrets::CommandRunner::run(&runner, "bws", args) + .map_err(|e| format!("bws {} failed: {e}", args.join(" "))) +} + +/// One full vault refresh: list, then get each secret (8-way parallel). +fn refresh(state: &Arc) -> Result { + { + let mut r = state.refreshing.write().unwrap(); + if *r { + return Err("refresh already in progress".into()); + } + *r = true; + } + let result = do_refresh(state); + *state.refreshing.write().unwrap() = false; + result +} + +fn do_refresh(state: &Arc) -> Result { + let token = bws_token().ok_or("no Bitwarden access token available")?; + let list_raw = bws_run(&["secret", "list", "-o", "json"], &token)?; + let list: Value = + serde_json::from_str(&list_raw).map_err(|e| format!("bws list not json: {e}"))?; + let items: Vec<(String, String)> = list + .as_array() + .ok_or("bws list is not an array")? + .iter() + .filter_map(|s| { + Some(( + s.get("id")?.as_str()?.to_string(), + s.get("key")?.as_str()?.to_string(), + )) + }) + .collect(); + // Fetch values with a small worker pool over a shared index. + let items = Arc::new(items); + let idx = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let got = Arc::new(RwLock::new(HashMap::new())); + let mut handles = Vec::new(); + for _ in 0..8 { + let items = Arc::clone(&items); + let idx = Arc::clone(&idx); + let got = Arc::clone(&got); + let token = token.clone(); + handles.push(std::thread::spawn(move || { + loop { + let i = idx.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if i >= items.len() { + return; + } + let (id, key) = &items[i]; + if let Ok(raw) = bws_run(&["secret", "get", id, "-o", "json"], &token) { + if let Ok(v) = serde_json::from_str::(&raw) { + if let Some(val) = v.get("value").and_then(|x| x.as_str()) { + got.write().unwrap().insert(key.clone(), val.to_string()); + } + } + } + } + })); + } + for h in handles { + let _ = h.join(); + } + let map = got.read().unwrap().clone(); + let n = map.len(); + *state.secrets.write().unwrap() = map; + *state.last_refresh.write().unwrap() = Some(now_unix()); + Ok(n) +} + +fn json_response(status: u16, body: Value) -> Response>> { + let data = serde_json::to_vec(&body).unwrap_or_else(|_| b"{}".to_vec()); + Response::from_data(data) + .with_status_code(StatusCode(status)) + .with_header(Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap()) +} + +fn token_ok(req: &tiny_http::Request, expected: &str) -> bool { + req.headers() + .iter() + .find(|h| h.field.as_str().to_ascii_lowercase() == "x-agent-token") + .map(|h| h.value.as_str() == expected) + .unwrap_or(false) +} + +pub fn run() -> i32 { + let bind = + std::env::var("SECRETS_BROKER_BIND").unwrap_or_else(|_| "100.99.113.103:4800".to_string()); + let home = std::env::var("HOME").expect("HOME unset"); + let token_file = std::env::var("SECRETS_BROKER_TOKEN_FILE") + .unwrap_or_else(|_| format!("{home}/.config/secrets-broker/token")); + let token = std::fs::read_to_string(&token_file) + .map(|t| t.trim().to_string()) + .unwrap_or_else(|_| { + crate::log::info( + "secrets-broker", + &format!("cannot read token file {token_file}"), + ); + std::process::exit(3); + }); + let ttl_s: u64 = std::env::var("SECRETS_BROKER_TTL_S") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(900); + + let state = Arc::new(State { + secrets: RwLock::new(HashMap::new()), + last_refresh: RwLock::new(None), + refreshing: RwLock::new(false), + }); + + // Background refresh loop: initial load + TTL refresh, + // stale-while-revalidate (the cache keeps serving during a refresh, + // and a failed refresh keeps the old values). + { + let state = Arc::clone(&state); + std::thread::spawn(move || { + loop { + match refresh(&state) { + Ok(n) => crate::log::info("secrets-broker", &format!("refreshed {n} secrets")), + Err(e) => crate::log::info("secrets-broker", &format!("refresh failed: {e}")), + } + std::thread::sleep(Duration::from_secs(ttl_s)); + } + }); + } + + let server = Server::http(&bind).unwrap_or_else(|e| { + crate::log::info("secrets-broker", &format!("cannot bind {bind}: {e:?}")); + std::process::exit(3); + }); + crate::log::info("secrets-broker", &format!("listening on {bind}")); + for mut req in server.incoming_requests() { + let state = Arc::clone(&state); + let token = token.clone(); + std::thread::spawn(move || { + let url = req.url().to_string(); + let path = url.split('?').next().unwrap_or("").to_string(); + let resp = if req.method() == &Method::Get && path == "/health" { + json_response( + 200, + json!({ + "ok": true, + "secrets": state.secrets.read().unwrap().len(), + "last_refresh_unix": state.last_refresh.read().unwrap().clone(), + "refreshing": *state.refreshing.read().unwrap(), + }), + ) + } else if !token_ok(&req, &token) { + json_response(401, json!({"error": "unauthorized"})) + } else if req.method() == &Method::Get && path == "/secrets" { + let mut names: Vec = + state.secrets.read().unwrap().keys().cloned().collect(); + names.sort(); + json_response(200, json!({"names": names})) + } else if req.method() == &Method::Post && path == "/refresh" { + let mut buf = String::new(); + let _ = req.as_reader().read_to_string(&mut buf); + let st = Arc::clone(&state); + std::thread::spawn(move || { + let _ = refresh(&st); + }); + json_response(202, json!({"ok": true, "refresh": "started"})) + } else if req.method() == &Method::Get && path.starts_with("/secret/") { + let name = path.trim_start_matches("/secret/").to_string(); + let name = url_decode(&name); + let cache = state.secrets.read().unwrap(); + match cache.get(&name) { + Some(v) => json_response(200, json!({"key": name, "value": v})), + None => { + if state.last_refresh.read().unwrap().is_none() { + json_response(503, json!({"error": "secrets not loaded yet"})) + } else { + json_response(404, json!({"error": "no such secret"})) + } + } + } + } else { + json_response(404, json!({"error": "not found"})) + }; + let _ = req.respond(resp); + }); + } + // incoming_requests() ends only when the server stops. + 0 +} + +fn url_decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + if let Ok(v) = + u8::from_str_radix(std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""), 16) + { + out.push(v); + i += 3; + continue; + } + } + out.push(if bytes[i] == b'+' { b' ' } else { bytes[i] }); + i += 1; + } + String::from_utf8_lossy(&out).to_string() +} diff --git a/pkgs/fleet/crates/fleet-queue/src/validate.rs b/pkgs/fleet/crates/fleet-queue/src/validate.rs new file mode 100644 index 0000000000..656334a7ab --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/validate.rs @@ -0,0 +1,468 @@ +//! Packet validation — faithful port of repo-queue.py's built-in +//! (manual) validator: envelope checks, manual schema checks, and the +//! dedupe-key family rules. (Legacy Python prefers the jsonschema +//! library when importable; messages for exotic packets can differ in +//! wording, but accept/reject semantics match the manual contract and +//! the database RPCs remain the backstop.) + +use serde_json::{Value, json}; + +pub const PRIORITY_SCALE: [i64; 7] = [10, 20, 30, 40, 50, 70, 90]; +pub const KINDS: [&str; 4] = ["pr_shepherd", "triage", "small_fix", "ci_investigation"]; +pub const FLEET_REPOS: [&str; 6] = [ + "developing-today/code", + "developing-today/opencode", + "developing-today/openchamber", + "dezren39/nix", + "developing-today/zettel", + "dezren39/dezren39", +]; +const PAYLOAD_WARN_BYTES: usize = 4096; +const PAYLOAD_MAX_BYTES: usize = 16384; +const BODY_WARN_WORDS: usize = 250; + +pub const DEDUPE_PATTERNS_DOC: &str = "fix: repo-health:v1:fix::issue:\n\ +triage: repo-health:v1:triage::issue:\n\ +pr: repo-health:v1:pr::pr:\n\ +pr-set: repo-health:v1:pr-set::-[-...] (sorted)\n\ +set: repo-health:v1:set::owed:\n\ +maintenance: repo-health:v1:maintenance:::"; + +fn is_empty(v: Option<&Value>) -> bool { + match v { + None | Some(Value::Null) => true, + Some(Value::String(s)) => s.is_empty(), + Some(Value::Array(a)) => a.is_empty(), + Some(Value::Object(o)) => o.is_empty(), + _ => false, + } +} + +fn manual_schema_errors(p: &Value) -> Vec { + let mut errs = Vec::new(); + let obj = match p.as_object() { + Some(o) => o, + None => return vec!["payload: must be a JSON object".to_string()], + }; + let get = |f: &str| obj.get(f); + if get("schema") != Some(&json!("repo-task/v1")) { + errs.push("payload.schema: must be 'repo-task/v1'".to_string()); + } + let kind_ok = matches!(get("kind"), Some(Value::String(k)) if KINDS.contains(&k.as_str())); + if !kind_ok { + let mut sorted = KINDS; + sorted.sort(); + errs.push(format!("payload.kind: must be one of {sorted:?}")); + } + let repo_ok = + matches!(get("repo"), Some(Value::String(r)) if FLEET_REPOS.contains(&r.as_str())); + if !repo_ok { + errs.push(format!( + "payload.repo: {} is not a fleet repo", + python_repr(get("repo")) + )); + } + for f in ["problem", "priority_reason"] { + if is_empty(get(f)) { + errs.push(format!("payload.{f}: required field missing or empty")); + } + } + for f in ["evidence", "acceptance", "tests", "context_refs"] { + if !matches!(get(f), Some(Value::Array(_))) { + errs.push(format!("payload.{f}: must be a list")); + } + } + for f in ["evidence", "acceptance", "tests"] { + if let Some(Value::Array(a)) = get(f) { + if a.is_empty() { + errs.push(format!("payload.{f}: must not be empty")); + } + } + } + match get("scope") { + Some(Value::Object(scope)) => { + if !matches!(scope.get("include"), Some(Value::Array(_))) { + errs.push("payload.scope.include: must be a list".to_string()); + } + if is_empty(scope.get("exclude")) { + errs.push("payload.scope.exclude: required (scope exclusions)".to_string()); + } + } + _ => errs.push("payload.scope: must be an object with include/exclude".to_string()), + } + match get("risk") { + Some(Value::Object(risk)) if matches!(risk.get("level"), Some(Value::String(l)) if ["low","medium","high"].contains(&l.as_str())) => { + if !matches!(risk.get("flags"), Some(Value::Array(_))) { + errs.push("payload.risk.flags: must be a list".to_string()); + } + } + _ => errs.push("payload.risk.level: must be low|medium|high".to_string()), + } + for f in ["timebox_minutes", "max_attempts"] { + let ok = + matches!(get(f), Some(Value::Number(n)) if n.as_i64().map(|v| v >= 1).unwrap_or(false)); + if !ok { + errs.push(format!("payload.{f}: must be a positive integer")); + } + } + let ded_ok = matches!(get("dedupe"), Some(Value::Object(d)) + if !is_empty(d.get("checked_at")) && !is_empty(d.get("basis"))); + if !ded_ok { + errs.push("payload.dedupe: must have checked_at and basis".to_string()); + } + let has_issue = matches!(get("issue"), Some(Value::Object(i)) + if matches!(i.get("number"), Some(Value::Number(n)) if n.is_i64())); + let has_prs = matches!(get("prs"), Some(Value::Array(a)) if !a.is_empty()); + let has_set = matches!(get("set"), Some(Value::Object(_))); + let has_source = matches!(get("source"), Some(Value::Object(s)) + if matches!(s.get("pr"), Some(Value::Number(n)) if n.is_i64()) + && matches!(s.get("finding"), Some(Value::String(f)) if !f.is_empty())); + if !(has_issue || has_prs || has_set || has_source) { + errs.push( + "payload identity: need issue.number, a non-empty prs list, a set object, \ + or a pre-filing source {pr, finding}" + .to_string(), + ); + } + errs +} + +/// Python-style repr for the one message that embeds a value. +fn python_repr(v: Option<&Value>) -> String { + match v { + None | Some(Value::Null) => "None".to_string(), + Some(Value::String(s)) => format!("'{s}'"), + Some(other) => other.to_string(), + } +} + +pub struct DedupeMatch { + pub family: String, + pub repo: String, + pub num: Option, + pub nums: Option>, + pub origin: Option, +} + +fn all_digits(s: &str) -> bool { + !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) +} + +/// Hand-rolled equivalent of the DEDUPE_REGEXES family patterns. +fn match_dedupe(key: &str) -> Option { + let rest = key.strip_prefix("repo-health:v1:")?; + // set family has a different shape: set::owed: + if let Some(tail) = rest.strip_prefix("set:") { + let (num_s, repo) = tail.split_once(":owed:")?; + if all_digits(num_s) && FLEET_REPOS.contains(&repo) { + return Some(DedupeMatch { + family: "set".into(), + repo: repo.to_string(), + num: None, + nums: None, + origin: num_s.parse().ok(), + }); + } + return None; + } + for fam in ["fix", "triage", "pr-set", "pr", "maintenance"] { + let Some(after) = rest.strip_prefix(&format!("{fam}:")) else { + continue; + }; + for repo in FLEET_REPOS { + let Some(tail) = after.strip_prefix(&format!("{repo}:")) else { + continue; + }; + match fam { + "fix" | "triage" => { + if let Some(n) = tail.strip_prefix("issue:") { + if all_digits(n) { + return Some(DedupeMatch { + family: fam.into(), + repo: repo.to_string(), + num: n.parse().ok(), + nums: None, + origin: None, + }); + } + } + } + "pr" => { + if let Some(n) = tail.strip_prefix("pr:") { + if all_digits(n) { + return Some(DedupeMatch { + family: fam.into(), + repo: repo.to_string(), + num: n.parse().ok(), + nums: None, + origin: None, + }); + } + } + } + "pr-set" => { + let parts: Vec<&str> = tail.split('-').collect(); + if parts.iter().all(|p| all_digits(p)) { + return Some(DedupeMatch { + family: fam.into(), + repo: repo.to_string(), + num: None, + nums: Some(parts.iter().filter_map(|p| p.parse().ok()).collect()), + origin: None, + }); + } + } + "maintenance" => { + // :; slug [a-z0-9][a-z0-9_-]* + if let Some((slug, week)) = tail.rsplit_once(':') { + let slug_ok = !slug.is_empty() + && slug + .bytes() + .next() + .map(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) + .unwrap_or(false) + && slug.bytes().all(|b| { + b.is_ascii_lowercase() + || b.is_ascii_digit() + || b == b'_' + || b == b'-' + }); + let wb = week.as_bytes(); + let week_ok = week.len() == 8 + && all_digits(&week[..4]) + && week.as_bytes()[4] == b'-' + && wb[5] == b'W' + && all_digits(&week[6..]); + if slug_ok && week_ok { + return Some(DedupeMatch { + family: fam.into(), + repo: repo.to_string(), + num: None, + nums: None, + origin: None, + }); + } + } + } + _ => {} + } + } + // Family prefix matched but no repo/tail did: Python would fall + // through to trying other families too (regexes are tried in + // order over the whole key). Keep scanning other families. + } + None +} + +fn kind_families(kind: &str) -> Option<&'static [&'static str]> { + match kind { + "small_fix" => Some(&["fix"]), + "triage" => Some(&["triage", "maintenance"]), + "pr_shepherd" => Some(&["pr", "pr-set", "set"]), + "ci_investigation" => Some(&["fix", "triage", "pr"]), + _ => None, + } +} + +fn dedupe_errors(packet: &Value, payload: &Value) -> Vec { + let mut errors = Vec::new(); + let key = match packet.get("dedupe_key") { + Some(Value::String(k)) if !k.is_empty() => k.clone(), + _ => { + return vec![format!( + "packet.dedupe_key: required deterministic key:\n{DEDUPE_PATTERNS_DOC}" + )]; + } + }; + let m = match match_dedupe(&key) { + Some(m) => m, + None => { + return vec![format!( + "packet.dedupe_key: '{key}' matches no design pattern:\n{DEDUPE_PATTERNS_DOC}" + )]; + } + }; + if let Some(repo) = payload.get("repo") { + if repo != &json!(m.repo) { + errors.push(format!( + "packet.dedupe_key: repo '{}' in key does not match payload.repo {}", + m.repo, + python_repr(Some(repo)) + )); + } + } + let kind = payload.get("kind").and_then(|k| k.as_str()).unwrap_or(""); + if let Some(allowed) = kind_families(kind) { + if !allowed.contains(&m.family.as_str()) { + let mut sorted = allowed.to_vec(); + sorted.sort(); + errors.push(format!( + "packet.dedupe_key: family '{}' is not valid for kind '{}' (allowed: {:?})", + m.family, kind, sorted + )); + } + } + let issue_no = payload + .get("issue") + .and_then(|i| i.get("number")) + .and_then(|n| n.as_i64()); + let pr_numbers: Vec = payload + .get("prs") + .and_then(|p| p.as_array()) + .map(|a| { + a.iter() + .filter_map(|p| p.get("number").and_then(|n| n.as_i64())) + .collect() + }) + .unwrap_or_default(); + match m.family.as_str() { + "fix" | "triage" => { + let n = m.num.unwrap_or(0); + if let Some(ino) = issue_no { + if n != ino { + errors.push(format!( + "packet.dedupe_key: issue {n} in key does not match payload.issue.number {ino}" + )); + } + } + } + "pr" => { + let n = m.num.unwrap_or(0); + if !pr_numbers.is_empty() && !pr_numbers.contains(&n) { + errors.push(format!( + "packet.dedupe_key: PR {n} in key is not in payload.prs {pr_numbers:?}" + )); + } + } + "pr-set" => { + let nums = m.nums.clone().unwrap_or_default(); + let mut sorted = nums.clone(); + sorted.sort(); + if nums != sorted { + errors + .push("packet.dedupe_key: pr-set numbers must be sorted ascending".to_string()); + } + if !pr_numbers.is_empty() { + let mut sp = pr_numbers.clone(); + sp.sort(); + if nums != sp { + errors.push(format!( + "packet.dedupe_key: pr-set {nums:?} does not match payload.prs {sp:?}" + )); + } + } + } + "set" => { + let origin = m.origin.unwrap_or(0); + if let Some(st) = payload.get("set").and_then(|s| s.as_object()) { + if let Some(oi) = st.get("origin_issue").and_then(|v| v.as_i64()) { + if oi != origin { + errors.push(format!( + "packet.dedupe_key: origin issue {origin} does not match payload.set.origin_issue {oi}" + )); + } + } + } + } + _ => {} + } + errors +} + +/// validate_packet: returns (errors, warnings). +pub fn validate_packet(packet: &Value) -> (Vec, Vec) { + let mut errors: Vec = Vec::new(); + let mut warnings: Vec = Vec::new(); + let Some(obj) = packet.as_object() else { + return (vec!["packet: must be a JSON object".to_string()], warnings); + }; + let Some(payload) = obj.get("payload").filter(|p| p.is_object()) else { + return ( + vec!["packet.payload: required object (repo-task/v1 payload)".to_string()], + warnings, + ); + }; + errors.extend(manual_schema_errors(payload)); + + match obj.get("title") { + Some(Value::String(t)) if !t.trim().is_empty() => {} + _ => errors.push("packet.title: required non-empty string".to_string()), + } + match obj.get("priority") { + None => errors.push( + "packet.priority: required (numeric priority from the design scale: 10, 20, 30, 40, 50, 70, 90)" + .to_string(), + ), + Some(Value::Number(n)) if n.is_i64() => { + let v = n.as_i64().unwrap(); + if !PRIORITY_SCALE.contains(&v) { + errors.push(format!( + "packet.priority: {v} is not on the design scale {:?}", + PRIORITY_SCALE + )); + } + } + Some(_) => errors.push("packet.priority: must be an integer".to_string()), + } + if let Some(Value::String(body)) = obj.get("body") { + let words = body.split_whitespace().count(); + if words > BODY_WARN_WORDS { + warnings.push(format!( + "packet.body: {words} words exceeds the ~{BODY_WARN_WORDS}-word design target" + )); + } + } + let size = serde_json::to_string(payload).map(|s| s.len()).unwrap_or(0); + if size > PAYLOAD_MAX_BYTES { + errors.push(format!( + "payload size: {size} bytes exceeds the {PAYLOAD_MAX_BYTES}-byte hard ceiling (evidence and pointers, not full diffs/logs)" + )); + } else if size > PAYLOAD_WARN_BYTES { + warnings.push(format!( + "payload size: {size} bytes is above the {PAYLOAD_WARN_BYTES}-byte design target" + )); + } + if let Some(tb) = payload.get("timebox_minutes").and_then(|v| v.as_i64()) { + if tb != 20 && tb != 45 { + warnings.push(format!( + "payload.timebox_minutes: {tb} is not a standard design timebox (20 triage / 45 standard)" + )); + } + } + if let Some(ma) = payload.get("max_attempts").and_then(|v| v.as_i64()) { + let kind = payload.get("kind").and_then(|k| k.as_str()).unwrap_or(""); + let want = if kind == "triage" || kind == "ci_investigation" { + 6 + } else { + 4 + }; + if ma != want { + warnings.push(format!( + "payload.max_attempts: design default for {kind} is {want}, packet says {ma}" + )); + } + } + errors.extend(dedupe_errors(packet, payload)); + (errors, warnings) +} + +/// task_from_packet: the agent.tasks row shape the enqueue RPC takes. +pub fn task_from_packet(packet: &Value, queue: &str) -> Value { + let payload = packet.get("payload").cloned().unwrap_or(json!({})); + let max_attempts = packet + .get("max_attempts") + .filter(|v| !v.is_null()) + .or_else(|| payload.get("max_attempts")) + .cloned() + .unwrap_or(json!(4)); + json!({ + "queue": queue, + "title": packet.get("title").cloned().unwrap_or(Value::Null), + "body": packet.get("body").cloned().unwrap_or(Value::Null), + "payload": payload, + "dedupe_key": packet.get("dedupe_key").cloned().unwrap_or(Value::Null), + "priority": packet.get("priority").cloned().unwrap_or(Value::Null), + "not_before": packet.get("not_before").cloned().unwrap_or(Value::Null), + "max_attempts": max_attempts, + }) +} diff --git a/pkgs/fleet/crates/fleet-secrets/src/lib.rs b/pkgs/fleet/crates/fleet-secrets/src/lib.rs index 76911346d5..8bfbb2f407 100644 --- a/pkgs/fleet/crates/fleet-secrets/src/lib.rs +++ b/pkgs/fleet/crates/fleet-secrets/src/lib.rs @@ -31,6 +31,14 @@ use fleet_proxy_proto::{Request, Response}; pub struct SecretValue(String); impl SecretValue { + /// Wrap a value a [`SecretSource`] has just resolved from its + /// backend. Source implementations outside this crate construct + /// values only here, so every resolved secret immediately sits + /// behind the redacted newtype. + pub fn from_resolved(value: String) -> SecretValue { + SecretValue(value) + } + pub fn expose(&self) -> &str { &self.0 } diff --git a/pkgs/fleet/crates/fleet/Cargo.toml b/pkgs/fleet/crates/fleet/Cargo.toml index c6a125b3c6..f7baa5289a 100644 --- a/pkgs/fleet/crates/fleet/Cargo.toml +++ b/pkgs/fleet/crates/fleet/Cargo.toml @@ -14,6 +14,7 @@ path = "src/main.rs" fleet-registry = { workspace = true } fleet-config = { workspace = true } fleet-proxy-proto = { workspace = true } +fleet-queue = { workspace = true, optional = 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 } @@ -39,9 +40,9 @@ full = [ # 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"] +queue = ["dep:fleet-secrets", "dep:fleet-queue", "fleet-queue/client"] +queue-broker = ["dep:fleet-secrets", "dep:fleet-queue", "fleet-queue/queue-broker"] +secrets-broker = ["dep:fleet-secrets", "dep:fleet-queue", "fleet-queue/secrets-broker"] search = ["dep:fleet-secrets"] search-serve = ["dep:fleet-secrets"] dispatch = ["dep:fleet-secrets"] diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 2db489cd6c..0a85906055 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -2,13 +2,15 @@ //! (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. +//! Step 1 (#5429) built the skeleton: the platform crates, this +//! dispatch layer, the capability-stub machinery, and the variant +//! builds. Step 2 (#5430) landed the first real domain — queue: the +//! repo-queue client and the queue-broker / secrets-broker serve +//! roles run for real below. A compiled-in domain that has not +//! landed yet 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): //! @@ -345,9 +347,14 @@ fn print_domain_help(surface: &Surface, d: &Domain) { 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::Available => match d.name { + "queue" => "included in this build", + "serve" => { + "included in this build (queue-broker and secrets-broker roles; \ + the search role lands in a later step)" + } + _ => "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)" } @@ -413,6 +420,36 @@ fn run_domain(surface: &Surface, d: &Domain, args: &[String], invoked_as: &str) }; match surface.cap_state(cap, d.name) { CapState::Available => { + // Step 2 (#5430): the queue domain runs for real — the + // repo-queue client surface and the two broker roles. + // `--version` through the argv0 route is the census fix: + // repo-queue had no version surface at all before this. + #[cfg(feature = "queue")] + if d.name == "queue" { + if matches!( + args.first().map(|s| s.as_str()), + Some("--version") | Some("-V") + ) { + println!( + "{} {VERSION}", + if invoked_as == "repo-queue" { + "repo-queue" + } else { + "fleet" + } + ); + return EXIT_OK; + } + return fleet_queue::client::run(args); + } + #[cfg(feature = "queue-broker")] + if d.name == "serve" && args.first().map(|s| s.as_str()) == Some("queue-broker") { + return fleet_queue::queue_broker::run(); + } + #[cfg(feature = "secrets-broker")] + if d.name == "serve" && args.first().map(|s| s.as_str()) == Some("secrets-broker") { + return fleet_queue::secrets_broker::run(); + } 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. diff --git a/pkgs/fleet/default.nix b/pkgs/fleet/default.nix index eb9cc78d19..220bba42e6 100644 --- a/pkgs/fleet/default.nix +++ b/pkgs/fleet/default.nix @@ -106,6 +106,59 @@ in sizeGate = true; }; + # The standalone broker artifacts (queue domain, step 2 #5430): + # repo-queue / queue-broker / secrets-broker built from the same + # workspace under their historical names — the migration's + # rollback inventory (design note §7). While the queue pilot's + # flips proceed, a unit or symlink can always be re-pointed at + # one of these; they retire only at the epic's close, not before. + fleet-brokers = rustPlatform.buildRustPackage { + pname = "fleet-brokers"; + version = "0.1.0"; + src = ./.; + cargoLock.lockFile = ./Cargo.lock; + + cargoBuildFlags = [ + "-p" + "fleet-queue" + "--features" + "client,queue-broker,secrets-broker" + "--bins" + ]; + cargoTestFlags = [ + "-p" + "fleet-queue" + "--features" + "client,queue-broker,secrets-broker" + ]; + + # Same explicit full strip as mkFleet (nixpkgs fixup leaves the + # symbol table in). + postFixup = '' + ${binutils}/bin/strip $out/bin/repo-queue $out/bin/queue-broker $out/bin/secrets-broker + ''; + + meta = { + description = "Fleet queue-domain standalone artifacts (repo-queue, queue-broker, secrets-broker): the queue pilot's rollback inventory"; + license = with lib.licenses; [ + mit + asl20 + ]; + }; + }; + + # Full profile, musl static: the same capability set as `fleet`, + # linked for foreign soil (refinement B: linkage is a per-context + # choice). This is the artifact non-nix hosts install — the queue + # pilot's sandbox `repo-queue` symlink flip (#5430) points at a + # copy of it, because a glibc-dynamic laptop build names store + # paths the sandbox does not have. + fleet-static = mkFleet { + pname = "fleet-static"; + features = null; # workspace default features = full profile + platform = pkgsStatic.rustPlatform; + }; + # Connect profile, musl static: runs anywhere, no libc coupling. fleet-connect-static = mkFleet { pname = "fleet-connect-static"; diff --git a/pkgs/fleet/smoke.sh b/pkgs/fleet/smoke.sh index 87246c68fc..ee2b082829 100755 --- a/pkgs/fleet/smoke.sh +++ b/pkgs/fleet/smoke.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash -# Per-variant smoke suite for the fleet workspace skeleton -# (step 1, developing-today/code#5429). +# Per-variant smoke suite for the fleet workspace +# (step 1, developing-today/code#5429; queue-domain sections added +# by step 2, #5430). # # Usage: # smoke.sh @@ -28,7 +29,9 @@ STATIC_OUT=${4:?missing fleet-connect-static output path} PASS=0 FAIL=0 TMP=$(mktemp -d) -trap 'rm -rf "$TMP"' EXIT +SB_PID="" +QB_PID="" +trap 'kill $SB_PID $QB_PID 2>/dev/null; rm -rf "$TMP"' EXIT ok() { PASS=$((PASS + 1)); echo "ok - $1"; } bad() { FAIL=$((FAIL + 1)); echo "FAIL - $1"; } @@ -94,7 +97,8 @@ 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" +run "serve as queue-broker reaches the real broker role (missing token file: exit 3)" 3 "cannot read token file" \ + env QUEUE_BROKER_TOKEN_FILE="$TMP/no-such-token" "$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" \ @@ -102,6 +106,45 @@ run "full: fleet proxy connect is the skeleton stub" 69 "not implemented yet" \ run "connect: fleet proxy connect is the skeleton stub" 69 "not implemented yet" \ "$CONNECT_OUT/bin/fleet" proxy connect +echo "== queue domain: serve roles bind + answer; client surface (step 2, #5430) ==" +# Scratch token files: the roles refuse to start without them. The +# contents are dummies — these instances serve nothing real. +printf 'smoke-secrets-token\n' > "$TMP/sb-token" +printf 'smoke-queue-token\n' > "$TMP/qb-token" + +# secrets-broker role on a scratch port: /health answers unauthenticated. +env SECRETS_BROKER_BIND=127.0.0.1:19800 SECRETS_BROKER_TOKEN_FILE="$TMP/sb-token" \ + "$SERVE_OUT/bin/fleet" serve secrets-broker >"$TMP/sb.log" 2>&1 & +SB_PID=$! +# queue-broker role on a scratch port: /healthz answers +# unauthenticated. Its secrets URL points at a dead port so a +# credential fetch fails fast (exit 3) rather than retrying — enough +# to prove the client reached the broker and read its envelope. +env QUEUE_BROKER_BIND=127.0.0.1:19801 QUEUE_BROKER_TOKEN_FILE="$TMP/qb-token" \ + QUEUE_BROKER_SECRETS_URL=http://127.0.0.1:9 QUEUE_BROKER_SECRETS_TOKEN_FILE="$TMP/sb-token" \ + "$FULL_OUT/bin/fleet" serve queue-broker >"$TMP/qb.log" 2>&1 & +QB_PID=$! +sleep 1 +run "secrets-broker role: /health answers" 0 '"ok":true' curl -sf http://127.0.0.1:19800/health +run "queue-broker role: /healthz answers" 0 '"service":"queue-broker"' curl -sf http://127.0.0.1:19801/healthz + +# Client surface (the census gap §1): --help renders from the +# registry; --version reports the release through the argv0 route. +mkdir -p "$TMP/full" +ln -s "$FULL_OUT/bin/fleet" "$TMP/full/repo-queue" +run "repo-queue: --help renders the queue commands" 0 "Commands: validate" "$TMP/full/repo-queue" --help +run "repo-queue: --version reports the fleet release" 0 "repo-queue 0.1.0" "$TMP/full/repo-queue" --version +run "fleet queue: --help renders the queue commands" 0 "Commands: validate" "$FULL_OUT/bin/fleet" queue --help + +# Client -> broker wiring: health reaches the scratch queue-broker, +# which answers with its credential failure (exit 3, broker wording). +run "repo-queue: health reaches the broker (creds fail fast, exit 3)" 3 "secrets broker" \ + env REPO_QUEUE_BROKER_URL=http://127.0.0.1:19801 REPO_QUEUE_TOKEN_FILE="$TMP/qb-token" \ + "$TMP/full/repo-queue" health +kill "$SB_PID" "$QB_PID" 2>/dev/null +SB_PID="" +QB_PID="" + 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