diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..eeae235 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,72 @@ +name: CI + +on: + pull_request: + push: + branches: + - main + - master + - "codex/**" + - "forge/**" + workflow_dispatch: + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + format-and-lint: + name: Format and Lint + runs-on: ubuntu-latest + timeout-minutes: 15 + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + + - name: Cache Rust artifacts + uses: Swatinem/rust-cache@v2 + + - name: Check formatting + run: cargo fmt --check + + - name: Run Clippy + run: cargo clippy --locked --all-targets -- -D warnings + + build-and-test: + name: Build and Test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + - macos-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Cache Rust artifacts + uses: Swatinem/rust-cache@v2 + + - name: Compile all targets + run: cargo check --locked --all-targets + + - name: Run test suite + run: cargo test --locked --all-targets diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..509500a --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +target/ + +.DS_Store + +.forge/logs/ +*.log diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..93e5d53 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2295 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.2.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "compact_str" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b79c4069c6cad78e2e0cdfcbd26275770669fb39fd308a752dc110e83b9af32" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags", + "crossterm_winapi", + "futures-core", + "mio", + "parking_lot", + "rustix", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core", + "quote", + "syn", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "forge" +version = "0.1.0" +dependencies = [ + "clap", + "crossterm", + "dirs", + "futures", + "ratatui", + "reqwest", + "serde", + "serde_json", + "thiserror 1.0.69", + "tokio", + "toml", + "tracing", + "tracing-appender", + "tracing-subscriber", +] + +[[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 = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.0", +] + +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb2d60ef19920a3a9193c3e371f726ec1dafc045dac788d0fb3704272458971" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "iri-string" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.185" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" + +[[package]] +name = "libredox" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "mio" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-conv" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.59.0", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "ratatui" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" +dependencies = [ + "bitflags", + "cassowary", + "compact_str", + "crossterm", + "indoc", + "instability", + "itertools", + "lru", + "paste", + "strum", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.0", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustls" +version = "0.23.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69f9466fb2c14ea04357e91413efb882e2a6d4a406e625449bc0a5d360d53a21" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8279bb85272c9f10811ae6a6c547ff594d6a7f3c6c6b02ee9726d1d0dcfcdd06" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl 2.0.18", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.52.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67dee974fe86fd92cc45b7a95fdd2f99a36a6d7b0d431a231178d3d670bbcc6" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror 2.0.18", + "time", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-segmentation" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" + +[[package]] +name = "unicode-truncate" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width 0.1.14", +] + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[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_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..1e1fce6 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "forge" +version = "0.1.0" +edition = "2021" +license = "MIT" +description = "Forge: a terminal-native DevOps command center" + +[dependencies] +clap = { version = "4.5", features = ["derive"] } +crossterm = { version = "0.28", features = ["event-stream"] } +dirs = "5.0" +futures = "0.3" +ratatui = "0.29" +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +thiserror = "1.0" +tokio = { version = "1.44", features = ["macros", "rt-multi-thread", "process", "io-util", "sync", "time", "signal"] } +toml = "0.8" +tracing = "0.1" +tracing-appender = "0.2" +tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..c10c44f --- /dev/null +++ b/docs/README.md @@ -0,0 +1,15 @@ +# Docs Layout + +Top-level product documents remain in the repository root for visibility: + +- `AGENTS.md` +- `PROJECT_BRIEF.md` +- `ARCHITECTURE.md` + +This `docs/` directory is reserved for implementation-facing material that can grow without +turning the repository root into a dumping ground, for example: + +- architectural decision records +- subsystem design notes +- runtime flow documentation +- operator or contributor guides diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..8546a37 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "stable" +components = ["rustfmt", "clippy"] + diff --git a/src/ai/context.rs b/src/ai/context.rs new file mode 100644 index 0000000..1670295 --- /dev/null +++ b/src/ai/context.rs @@ -0,0 +1,143 @@ +use crate::domain::{ + AiCommandContext, AiContextBundle, AiGitContext, AiLogContext, AiProjectContext, + AiServiceContext, AiTestContext, AiTimelineContext, AiUiContext, AppState, FocusTarget, + LogSource, ModalState, +}; + +pub fn build_context(state: &AppState) -> AiContextBundle { + let limits = &state.config.ai; + + AiContextBundle { + ui: AiUiContext { + focus: focus_label(state.ui.focus).to_string(), + dashboard_tab: state.ui.dashboard_tab.title().to_string(), + modal: state.ui.modal.as_ref().map(modal_label), + pending_approvals: state.approvals.pending.len(), + }, + project: AiProjectContext { + name: state.project.name.clone(), + root: state.project.root.clone(), + stack_hints: state.project.stack_hints.clone(), + config_paths: state.project.config_paths.clone(), + discovered_files: state + .project + .discovered_files + .iter() + .take(limits.max_changed_files) + .cloned() + .collect(), + }, + git: AiGitContext { + branch: state.git.branch.clone(), + head: state.git.head.clone(), + is_dirty: state.git.is_dirty, + changed_files: state + .git + .changed_files + .iter() + .take(limits.max_changed_files) + .cloned() + .collect(), + }, + commands: state + .commands + .records + .iter() + .rev() + .take(limits.max_recent_commands) + .map(|record| AiCommandContext { + id: record.id, + raw: record.raw.clone(), + provenance: record.provenance, + status: record.status, + exit_code: record.exit_code, + output_line_count: record.output_line_count, + background: record.background, + }) + .collect(), + services: state + .services + .registry + .iter() + .rev() + .take(limits.max_recent_services) + .map(|service| AiServiceContext { + id: service.id, + name: service.name.clone(), + health: service.health, + pid: service.pid, + ports: service.ports.clone(), + tags: service.tags.clone(), + }) + .collect(), + tests: state + .tests + .recent_runs + .iter() + .rev() + .take(limits.max_recent_tests) + .map(|run| AiTestContext { + runner: run.runner.clone(), + status: run.status, + pass_count: run.pass_count, + fail_count: run.fail_count, + failed_tests: run.failed_tests.clone(), + }) + .collect(), + logs: state + .logs + .recent + .iter() + .rev() + .take(limits.max_recent_logs) + .map(|entry| AiLogContext { + ts: entry.ts, + source_label: log_source_label(&entry.source), + stream: entry.stream, + severity: entry.severity, + service_id: entry.service_id, + command_id: entry.command_id, + raw: entry.raw.clone(), + }) + .collect(), + timeline: state + .timeline + .entries + .iter() + .rev() + .take(limits.max_recent_events) + .map(|entry| AiTimelineContext { + at: entry.at, + kind: entry.kind, + message: entry.message.clone(), + }) + .collect(), + } +} + +fn focus_label(focus: FocusTarget) -> &'static str { + match focus { + FocusTarget::CommandPane => "command", + FocusTarget::DashboardPane => "dashboard", + FocusTarget::EventStream => "events", + FocusTarget::Modal => "modal", + } +} + +fn modal_label(modal: &ModalState) -> String { + match modal { + ModalState::Approval(id) => format!("approval:{id}"), + ModalState::Help => "help".to_string(), + ModalState::Error(_) => "error".to_string(), + } +} + +fn log_source_label(source: &LogSource) -> String { + match source { + LogSource::Command(command_id) => format!("command:{command_id}"), + LogSource::Service(service_id) => format!("service:{service_id}"), + LogSource::System => "system".to_string(), + LogSource::Git => "git".to_string(), + LogSource::Ai => "ai".to_string(), + } +} diff --git a/src/ai/mod.rs b/src/ai/mod.rs new file mode 100644 index 0000000..595d91d --- /dev/null +++ b/src/ai/mod.rs @@ -0,0 +1,6 @@ +mod context; +mod provider; +mod providers; + +pub use context::build_context; +pub use provider::{AiProvider, AiRuntime}; diff --git a/src/ai/provider.rs b/src/ai/provider.rs new file mode 100644 index 0000000..b25d169 --- /dev/null +++ b/src/ai/provider.rs @@ -0,0 +1,36 @@ +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; + +use crate::ai::providers; +use crate::config::AiConfig; +use crate::domain::{AiRequest, AiResponse}; +use crate::shared::error::AppResult; + +pub type AiFuture = Pin> + Send>>; + +pub trait AiProvider: Send + Sync { + fn name(&self) -> &str; + fn execute(&self, request: AiRequest) -> AiFuture; +} + +#[derive(Clone)] +pub struct AiRuntime { + provider: Arc, +} + +impl AiRuntime { + pub fn from_config(config: &AiConfig) -> Self { + Self { + provider: providers::build_provider(config), + } + } + + pub fn provider_name(&self) -> &str { + self.provider.name() + } + + pub async fn execute(&self, request: AiRequest) -> AppResult { + self.provider.execute(request).await + } +} diff --git a/src/ai/providers/mock.rs b/src/ai/providers/mock.rs new file mode 100644 index 0000000..317c6d6 --- /dev/null +++ b/src/ai/providers/mock.rs @@ -0,0 +1,82 @@ +use crate::ai::provider::{AiFuture, AiProvider}; +use crate::domain::{AiCitation, AiRequest, AiRequestKind, AiResponse}; +use crate::shared::time::now_utc; + +pub struct MockProvider { + model: Option, +} + +impl MockProvider { + pub fn new(model: Option) -> Self { + Self { model } + } +} + +impl AiProvider for MockProvider { + fn name(&self) -> &str { + "mock" + } + + fn execute(&self, request: AiRequest) -> AiFuture { + let model = self.model.clone(); + Box::pin(async move { Ok(mock_response(request, model)) }) + } +} + +fn mock_response(request: AiRequest, model: Option) -> AiResponse { + let branch = request + .context + .git + .branch + .clone() + .unwrap_or_else(|| "unknown".to_string()); + let message = match request.kind { + AiRequestKind::Assist => format!( + "Mock provider reviewed the current Forge context for `{}` in repo `{}` on branch `{}`.", + request.prompt, request.context.project.name, branch + ), + AiRequestKind::Diagnose => format!( + "Mock diagnosis reviewed {} commands, {} logs, and {} timeline entries for `{}`.", + request.context.commands.len(), + request.context.logs.len(), + request.context.timeline.len(), + request.prompt + ), + }; + + let mut recommendations = vec![ + format!("Review branch `{branch}` before applying changes."), + format!( + "Inspect the {} most recent timeline events for correlated state changes.", + request.context.timeline.len() + ), + ]; + + if let Some(log) = request.context.logs.first() { + recommendations.push(format!( + "Inspect `{}` for the newest log activity.", + log.source_label + )); + } + + AiResponse { + request_id: request.id, + created_at: now_utc(), + provider: "mock".to_string(), + model, + summary: format!("Mock AI response for `{}`", request.prompt), + message, + recommendations, + proposals: Vec::new(), + citations: vec![AiCitation { + label: "context".to_string(), + detail: format!( + "repo={} dirty={} services={} tests={}", + request.context.project.name, + request.context.git.is_dirty, + request.context.services.len(), + request.context.tests.len() + ), + }], + } +} diff --git a/src/ai/providers/mod.rs b/src/ai/providers/mod.rs new file mode 100644 index 0000000..722bb7c --- /dev/null +++ b/src/ai/providers/mod.rs @@ -0,0 +1,20 @@ +mod mock; +mod openai; +mod unconfigured; + +use std::sync::Arc; + +use crate::ai::provider::AiProvider; +use crate::config::AiConfig; + +pub fn build_provider(config: &AiConfig) -> Arc { + match (config.enabled, config.provider.as_deref()) { + (false, _) => Arc::new(unconfigured::UnconfiguredProvider::disabled()), + (true, Some("mock")) => Arc::new(mock::MockProvider::new(config.model.clone())), + (true, Some("openai")) => Arc::new(openai::OpenAiProvider::new(config)), + (true, Some(provider)) => { + Arc::new(unconfigured::UnconfiguredProvider::unsupported(provider)) + } + (true, None) => Arc::new(unconfigured::UnconfiguredProvider::missing()), + } +} diff --git a/src/ai/providers/openai.rs b/src/ai/providers/openai.rs new file mode 100644 index 0000000..e0fba6b --- /dev/null +++ b/src/ai/providers/openai.rs @@ -0,0 +1,447 @@ +use std::time::Duration; + +use reqwest::Client; +use serde::Deserialize; +use serde_json::{json, Value}; + +use crate::ai::provider::{AiFuture, AiProvider}; +use crate::config::AiConfig; +use crate::domain::{AiCitation, AiRequest, AiResponse}; +use crate::shared::error::AiError; +use crate::shared::time::now_utc; + +const DEFAULT_MODEL: &str = "gpt-5-mini"; +const DEFAULT_BASE_URL: &str = "https://api.openai.com/v1/responses"; + +pub struct OpenAiProvider { + client: Client, + api_key: Option, + endpoint: String, + default_model: String, +} + +impl OpenAiProvider { + pub fn new(config: &AiConfig) -> Self { + let timeout = Duration::from_secs(config.request_timeout_secs); + let client = Client::builder() + .timeout(timeout) + .build() + .unwrap_or_else(|_| Client::new()); + let endpoint = std::env::var("OPENAI_BASE_URL") + .or_else(|_| std::env::var("OPENAI_API_BASE")) + .unwrap_or_else(|_| DEFAULT_BASE_URL.to_string()); + let endpoint = normalize_endpoint(&endpoint); + + Self { + client, + api_key: std::env::var("OPENAI_API_KEY").ok(), + endpoint, + default_model: config + .model + .clone() + .unwrap_or_else(|| DEFAULT_MODEL.to_string()), + } + } +} + +impl AiProvider for OpenAiProvider { + fn name(&self) -> &str { + "openai" + } + + fn execute(&self, request: AiRequest) -> AiFuture { + let client = self.client.clone(); + let api_key = self.api_key.clone(); + let endpoint = self.endpoint.clone(); + let default_model = self.default_model.clone(); + + Box::pin(async move { + let api_key = api_key.ok_or(AiError::MissingApiKey { + provider: "openai".to_string(), + env_var: "OPENAI_API_KEY".to_string(), + })?; + + let payload = build_payload(&request, &default_model); + let response = client + .post(endpoint) + .bearer_auth(api_key) + .json(&payload) + .send() + .await + .map_err(|error| AiError::ProviderUnavailable { + provider: "openai".to_string(), + reason: error.to_string(), + })?; + + let status = response.status(); + let body = response + .text() + .await + .map_err(|error| AiError::ProviderUnavailable { + provider: "openai".to_string(), + reason: error.to_string(), + })?; + + if !status.is_success() { + return Err(AiError::ProviderUnavailable { + provider: "openai".to_string(), + reason: format!("HTTP {status}: {}", truncate(&body, 240)), + } + .into()); + } + + let parsed: OpenAiResponseEnvelope = + serde_json::from_str(&body).map_err(|error| AiError::ProviderUnavailable { + provider: "openai".to_string(), + reason: format!("invalid OpenAI response body: {error}"), + })?; + + let output_text = + extract_output_text(&parsed).ok_or_else(|| AiError::ProviderUnavailable { + provider: "openai".to_string(), + reason: "OpenAI response did not contain text output".to_string(), + })?; + + let structured: StructuredAiResponse = + serde_json::from_str(&output_text).map_err(|error| { + AiError::ProviderUnavailable { + provider: "openai".to_string(), + reason: format!( + "OpenAI response was not valid structured JSON: {error}; body={}", + truncate(&output_text, 240) + ), + } + })?; + + Ok(AiResponse { + request_id: request.id, + created_at: now_utc(), + provider: "openai".to_string(), + model: parsed.model.or(request.model.clone()), + summary: structured.summary, + message: structured.message, + recommendations: structured.recommendations, + proposals: Vec::new(), + citations: structured + .citations + .into_iter() + .map(|citation| AiCitation { + label: citation.label, + detail: citation.detail, + }) + .collect(), + }) + }) + } +} + +fn build_payload(request: &AiRequest, default_model: &str) -> Value { + let model = request + .model + .clone() + .unwrap_or_else(|| default_model.to_string()); + let developer_prompt = build_developer_prompt(request); + + json!({ + "model": model, + "input": [ + { + "role": "developer", + "content": developer_prompt, + }, + { + "role": "user", + "content": request.prompt, + } + ], + "text": { + "format": { + "type": "json_schema", + "name": "forge_ai_response", + "strict": true, + "schema": response_schema() + } + } + }) +} + +fn build_developer_prompt(request: &AiRequest) -> String { + format!( + concat!( + "You are Forge, a terminal-native DevOps command center assistant.\n", + "Use the provided repository/runtime context. Be concrete, grounded, and concise.\n", + "Do not claim certainty when evidence is weak.\n", + "Do not propose hidden actions.\n", + "Return JSON matching the requested schema.\n\n", + "Request kind: {}\n", + "UI focus: {}\n", + "Dashboard tab: {}\n", + "Repo: {}\n", + "Project root: {}\n", + "Git branch: {}\n", + "Git head: {}\n", + "Git dirty: {}\n", + "Changed files: {}\n", + "Recent commands:\n{}\n", + "Recent services:\n{}\n", + "Recent tests:\n{}\n", + "Recent logs:\n{}\n", + "Recent timeline:\n{}\n" + ), + request.kind.label(), + request.context.ui.focus, + request.context.ui.dashboard_tab, + request.context.project.name, + request.context.project.root.display(), + request + .context + .git + .branch + .clone() + .unwrap_or_else(|| "unknown".to_string()), + request + .context + .git + .head + .clone() + .unwrap_or_else(|| "unknown".to_string()), + request.context.git.is_dirty, + render_list( + &request + .context + .git + .changed_files + .iter() + .map(|file| file.as_str()) + .collect::>() + ), + render_list( + &request + .context + .commands + .iter() + .map(|command| format!("#{} {:?} {}", command.id, command.status, command.raw)) + .collect::>() + ), + render_list( + &request + .context + .services + .iter() + .map(|service| format!( + "{} {:?} pid={:?}", + service.name, service.health, service.pid + )) + .collect::>() + ), + render_list( + &request + .context + .tests + .iter() + .map(|test| format!( + "{} {:?} pass={} fail={}", + test.runner, test.status, test.pass_count, test.fail_count + )) + .collect::>() + ), + render_list( + &request + .context + .logs + .iter() + .map(|log| format!( + "[{:?}] {} {}", + log.severity, + log.source_label, + truncate(&log.raw, 160) + )) + .collect::>() + ), + render_list( + &request + .context + .timeline + .iter() + .map(|event| format!("[{:?}] {}", event.kind, truncate(&event.message, 160))) + .collect::>() + ) + ) +} + +fn render_list(items: &[T]) -> String { + if items.is_empty() { + "- none".to_string() + } else { + items + .iter() + .map(|item| format!("- {}", item.to_string())) + .collect::>() + .join("\n") + } +} + +fn response_schema() -> Value { + json!({ + "type": "object", + "additionalProperties": false, + "required": ["summary", "message", "recommendations", "citations"], + "properties": { + "summary": { + "type": "string", + "description": "A short one-line grounded summary." + }, + "message": { + "type": "string", + "description": "A concise but complete explanation or diagnosis for the user." + }, + "recommendations": { + "type": "array", + "items": { "type": "string" }, + "description": "Concrete next steps or checks." + }, + "citations": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["label", "detail"], + "properties": { + "label": { "type": "string" }, + "detail": { "type": "string" } + } + }, + "description": "Short references to the context used." + } + } + }) +} + +fn normalize_endpoint(raw: &str) -> String { + let trimmed = raw.trim_end_matches('/'); + if trimmed.ends_with("/responses") { + trimmed.to_string() + } else { + format!("{trimmed}/responses") + } +} + +fn extract_output_text(response: &OpenAiResponseEnvelope) -> Option { + if let Some(text) = response.output_text.as_ref() { + if !text.trim().is_empty() { + return Some(text.clone()); + } + } + + let combined = response + .output + .as_ref()? + .iter() + .flat_map(|item| item.content.iter()) + .filter(|content| content.kind == "output_text") + .map(|content| content.text.as_str()) + .collect::>() + .join(""); + + (!combined.trim().is_empty()).then_some(combined) +} + +fn truncate(value: &str, max_chars: usize) -> String { + let chars = value.chars().collect::>(); + if chars.len() <= max_chars { + return value.to_string(); + } + let visible = chars + .into_iter() + .take(max_chars.saturating_sub(1)) + .collect::(); + format!("{visible}…") +} + +#[derive(Debug, Deserialize)] +struct OpenAiResponseEnvelope { + #[serde(default)] + model: Option, + #[serde(default)] + output_text: Option, + #[serde(default)] + output: Option>, +} + +#[derive(Debug, Deserialize)] +struct OpenAiOutputItem { + #[serde(default)] + content: Vec, +} + +#[derive(Debug, Deserialize)] +struct OpenAiContentItem { + #[serde(rename = "type")] + kind: String, + #[serde(default)] + text: String, +} + +#[derive(Debug, Deserialize)] +struct StructuredAiResponse { + summary: String, + message: String, + recommendations: Vec, + citations: Vec, +} + +#[derive(Debug, Deserialize)] +struct StructuredCitation { + label: String, + detail: String, +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use crate::ai::providers::openai::{build_payload, extract_output_text, StructuredAiResponse}; + use crate::config::ForgeConfig; + use crate::domain::{AiRequest, AiRequestKind, AppState, GitSnapshot, ProjectContext}; + use crate::shared::ids::AiRequestId; + use crate::shared::time::now_utc; + + #[test] + fn extracts_output_text_from_output_items() { + let response = serde_json::from_value(json!({ + "model": "gpt-5-mini", + "output": [ + { + "content": [ + { "type": "output_text", "text": "{\"summary\":\"s\",\"message\":\"m\",\"recommendations\":[],\"citations\":[]}" } + ] + } + ] + })) + .expect("response should deserialize"); + + let text = extract_output_text(&response).expect("text should exist"); + let parsed: StructuredAiResponse = + serde_json::from_str(&text).expect("structured text should parse"); + assert_eq!(parsed.summary, "s"); + } + + #[test] + fn build_payload_uses_json_schema_format() { + let config = ForgeConfig::default(); + let state = AppState::new(config, ProjectContext::default(), GitSnapshot::default()); + let request = AiRequest { + id: AiRequestId(1), + kind: AiRequestKind::Assist, + created_at: now_utc(), + provider: Some("openai".to_string()), + model: Some("gpt-5-mini".to_string()), + prompt: "Summarize this repo".to_string(), + context: crate::ai::build_context(&state), + }; + + let payload = build_payload(&request, "gpt-5-mini"); + assert_eq!(payload["text"]["format"]["type"], "json_schema"); + assert_eq!(payload["model"], "gpt-5-mini"); + } +} diff --git a/src/ai/providers/unconfigured.rs b/src/ai/providers/unconfigured.rs new file mode 100644 index 0000000..681e58a --- /dev/null +++ b/src/ai/providers/unconfigured.rs @@ -0,0 +1,51 @@ +use crate::ai::provider::{AiFuture, AiProvider}; +use crate::domain::AiRequest; +use crate::shared::error::AiError; + +pub struct UnconfiguredProvider { + name: String, + message: String, +} + +impl UnconfiguredProvider { + pub fn disabled() -> Self { + Self { + name: "disabled".to_string(), + message: "AI is disabled in the Forge configuration.".to_string(), + } + } + + pub fn missing() -> Self { + Self { + name: "unconfigured".to_string(), + message: + "AI provider is not configured yet. Set `ai.provider` to a supported provider." + .to_string(), + } + } + + pub fn unsupported(provider: &str) -> Self { + Self { + name: provider.to_string(), + message: format!("AI provider `{provider}` is not implemented yet in this build."), + } + } +} + +impl AiProvider for UnconfiguredProvider { + fn name(&self) -> &str { + &self.name + } + + fn execute(&self, _request: AiRequest) -> AiFuture { + let provider = self.name.clone(); + let message = self.message.clone(); + Box::pin(async move { + Err(AiError::ProviderUnavailable { + provider, + reason: message, + } + .into()) + }) + } +} diff --git a/src/app/bootstrap.rs b/src/app/bootstrap.rs new file mode 100644 index 0000000..af1f31d --- /dev/null +++ b/src/app/bootstrap.rs @@ -0,0 +1,42 @@ +use crate::ai::AiRuntime; +use crate::app::AppStore; +use crate::config::{load_config, CliArgs}; +use crate::domain::{AppState, GitSnapshot, ProjectContext, TimelineKind}; +use crate::infra::{git, project}; +use crate::observability::{init_observability, install_panic_hook}; +use crate::runtime::Runtime; +use crate::shared::error::AppResult; +use crate::shared::time::now_utc; +use crate::ui::terminal::TerminalUi; + +pub async fn bootstrap(cli: CliArgs) -> AppResult { + let loaded = load_config(&cli)?; + let observability = init_observability(&loaded.config.observability, &loaded.cwd)?; + install_panic_hook(); + + let project = project::scan_project( + &loaded.cwd, + loaded.global_config_path.clone(), + loaded.project_config_path.clone(), + ) + .unwrap_or_else(|_| ProjectContext::default()); + let git = if loaded.config.git.enabled { + git::snapshot_git(&project.root).unwrap_or_else(|_| GitSnapshot::default()) + } else { + GitSnapshot::default() + }; + + let mut state = AppState::new(loaded.config.clone(), project, git); + state.diagnostics.log_file = observability.log_file.clone(); + state.timeline.entries.push(crate::domain::TimelineEntry { + id: crate::shared::ids::TimelineId(0), + at: now_utc(), + kind: TimelineKind::System, + message: "Forge bootstrapped".to_string(), + }); + + let store = AppStore::new(state); + let terminal = TerminalUi::new()?; + let ai_runtime = AiRuntime::from_config(&loaded.config.ai); + Ok(Runtime::new(store, terminal, observability, ai_runtime)) +} diff --git a/src/app/effects.rs b/src/app/effects.rs new file mode 100644 index 0000000..9e884bb --- /dev/null +++ b/src/app/effects.rs @@ -0,0 +1,89 @@ +use std::path::PathBuf; + +use crate::domain::{AiRequest, AiResponse, ExecutionRequest}; +use crate::domain::{ApprovalRequest, DiagnosticLevel, GitSnapshot, OutputStream, ProjectContext}; +use crate::shared::ids::{AiRequestId, ApprovalId, CommandId, JobId, ServiceId}; + +#[derive(Debug, Clone)] +pub enum UiIntent { + KeyChar(char), + Backspace, + Submit, + ClearInput, + NextFocus, + PrevFocus, + NextTab, + PrevTab, + ApproveCurrent, + DenyCurrent, + Resize(u16, u16), + Tick, + Quit, + Esc, +} + +#[derive(Debug, Clone)] +pub enum AppAction { + Ui(UiIntent), + ParsedInput(crate::commands::ParsedInput), + Approve(ApprovalId), + Deny(ApprovalId), + Cancel(CommandId), +} + +#[derive(Debug, Clone)] +pub enum AppEvent { + ProjectScanned(ProjectContext), + GitRefreshed(GitSnapshot), + AiStarted { + request_id: AiRequestId, + provider: String, + }, + AiCompleted(AiResponse), + AiFailed { + request_id: AiRequestId, + provider: String, + message: String, + }, + CommandStarted { + command_id: CommandId, + job_id: JobId, + service_id: Option, + pid: Option, + }, + CommandOutput { + command_id: CommandId, + job_id: JobId, + service_id: Option, + stream: OutputStream, + chunk: String, + }, + CommandExited { + command_id: CommandId, + job_id: JobId, + service_id: Option, + exit_code: i32, + }, + CommandCancelled { + command_id: CommandId, + job_id: JobId, + service_id: Option, + }, + Diagnostic { + level: DiagnosticLevel, + message: String, + context: Option, + }, + Error(String), +} + +#[derive(Debug, Clone)] +pub enum Effect { + RunAiRequest(Box), + ExecuteCommand(ExecutionRequest), + CancelCommand(CommandId), + RefreshProjectContext(PathBuf), + RefreshGit(PathBuf), + Shutdown, + QueueApproval(ApprovalRequest), +} diff --git a/src/app/mod.rs b/src/app/mod.rs new file mode 100644 index 0000000..d9664c1 --- /dev/null +++ b/src/app/mod.rs @@ -0,0 +1,6 @@ +pub mod bootstrap; +mod effects; +mod store; + +pub use effects::{AppAction, AppEvent, Effect, UiIntent}; +pub use store::AppStore; diff --git a/src/app/store.rs b/src/app/store.rs new file mode 100644 index 0000000..c41e9c8 --- /dev/null +++ b/src/app/store.rs @@ -0,0 +1,852 @@ +use std::collections::BTreeMap; + +use crate::ai; +use crate::app::{AppAction, AppEvent, Effect, UiIntent}; +use crate::commands::{parse_input, ParsedInput}; +use crate::domain::{ + AiMessage, AiMessageRole, AiRequest, AiRequestKind, AiStatus, AppState, ApprovalDecision, + ApprovalMode, ApprovalRequest, CommandRecord, CommandStatus, DashboardTab, DiagnosticLevel, + DiagnosticRecord, ExecutionMode, ExecutionRequest, FocusTarget, JobRecord, JobStatus, + ModalState, Notification, NotificationLevel, ProcessSnapshot, ProcessStatus, ServiceHealth, + ServiceRecord, ServiceSource, TimelineEntry, TimelineKind, +}; +use crate::safety::{approval_message, approval_mode_for, classify_command}; +use crate::shared::ids::{ApprovalId, CommandId, IdGenerator}; +use crate::shared::time::now_utc; + +pub struct AppStore { + state: AppState, + ids: IdGenerator, +} + +impl AppStore { + pub fn new(state: AppState) -> Self { + Self { + state, + ids: IdGenerator::new(), + } + } + + pub fn state(&self) -> &AppState { + &self.state + } + + pub fn state_mut(&mut self) -> &mut AppState { + &mut self.state + } + + pub fn dispatch_action(&mut self, action: AppAction) -> Vec { + match action { + AppAction::Ui(intent) => self.handle_ui_intent(intent), + AppAction::ParsedInput(input) => self.handle_parsed_input(input), + AppAction::Approve(id) => self.resolve_approval(id, true), + AppAction::Deny(id) => self.resolve_approval(id, false), + AppAction::Cancel(command_id) => { + self.append_timeline( + TimelineKind::Command, + format!("cancellation requested for command #{command_id}"), + ); + vec![Effect::CancelCommand(command_id)] + } + } + } + + pub fn dispatch_event(&mut self, event: AppEvent) -> Vec { + match event { + AppEvent::ProjectScanned(project) => { + self.state.project = project.clone(); + self.append_timeline( + TimelineKind::System, + format!("project context refreshed for {}", project.name), + ); + } + AppEvent::GitRefreshed(snapshot) => { + self.state.git = snapshot; + } + AppEvent::AiStarted { + request_id, + provider, + } => { + self.state.ai.status = AiStatus::Running; + self.state.ai.active_request = Some(request_id); + self.append_timeline( + TimelineKind::Ai, + format!("AI request #{request_id} started via {provider}"), + ); + } + AppEvent::AiCompleted(response) => { + let request_id = response.request_id; + let summary = truncate_for_timeline(&response.summary, 96); + let history_limit = self.state.config.ai.history_limit; + self.state.ai.status = AiStatus::Completed; + self.state.ai.active_request = None; + self.state.ai.last_error = None; + self.state.ai.last_response = Some(response.clone()); + self.state.ai.push_message( + AiMessage { + role: AiMessageRole::Assistant, + content: response.message.clone(), + created_at: now_utc(), + }, + history_limit, + ); + self.append_timeline( + TimelineKind::Ai, + format!("AI response ready for request #{request_id}: {summary}"), + ); + self.push_notification( + NotificationLevel::Info, + format!("AI response ready for request #{request_id}"), + ); + } + AppEvent::AiFailed { + request_id, + provider, + message, + } => { + self.state.ai.status = AiStatus::Failed; + self.state.ai.active_request = None; + self.state.ai.last_error = Some(message.clone()); + self.append_timeline( + TimelineKind::Ai, + format!( + "AI request #{request_id} failed via {provider}: {}", + truncate_for_timeline(&message, 96) + ), + ); + self.push_notification( + NotificationLevel::Warn, + format!("AI request #{request_id} failed: {message}"), + ); + } + AppEvent::CommandStarted { + command_id, + job_id, + service_id, + pid, + } => { + if let Some(command) = self.find_command_mut(command_id) { + command.status = CommandStatus::Running; + command.started_at = Some(now_utc()); + } + if let Some(job) = self.find_job_mut(job_id) { + job.status = JobStatus::Running; + job.started_at = Some(now_utc()); + job.pid = pid; + } + let process = ProcessSnapshot { + id: self.ids.next_process(), + command_id: Some(command_id), + job_id: Some(job_id), + pid, + label: self + .find_command(command_id) + .map(|command| command.raw.clone()) + .unwrap_or_else(|| "managed command".to_string()), + status: ProcessStatus::Running, + cpu_percent: None, + memory_bytes: None, + observed_at: now_utc(), + }; + self.upsert_process(process); + if let Some(service_id) = service_id { + self.upsert_service(ServiceRecord { + id: service_id, + name: self + .find_command(command_id) + .map(|command| command.raw.clone()) + .unwrap_or_else(|| "background service".to_string()), + source: ServiceSource::ManagedCommand, + pid, + ports: Vec::new(), + health: ServiceHealth::Healthy, + tags: vec!["managed".to_string()], + linked_command: Some(command_id), + last_seen: now_utc(), + }); + } + self.state.commands.active_command = Some(command_id); + self.append_timeline( + TimelineKind::Command, + format!( + "command #{command_id} started{}", + pid.map(|pid| format!(" (pid {pid})")).unwrap_or_default() + ), + ); + } + AppEvent::CommandOutput { + command_id, + job_id: _, + service_id, + stream, + chunk, + } => { + if let Some(command) = self.find_command_mut(command_id) { + command.output_line_count += 1; + } + let log_entry = crate::infra::logs::normalize_command_output( + self.ids.next_log(), + now_utc(), + command_id, + service_id, + stream, + chunk.clone(), + ); + let source_key = crate::infra::logs::source_key(&log_entry.source); + let per_source_capacity = self.state.config.logs.per_source_capacity; + self.state.logs.recent.push(log_entry.clone()); + self.state + .logs + .per_source + .entry(source_key) + .or_insert_with(|| { + crate::shared::ring_buffer::RingBuffer::new(per_source_capacity) + }) + .push(log_entry.clone()); + self.append_timeline( + TimelineKind::Log, + format!( + "#{} {}", + command_id, + truncate_for_timeline(&log_entry.raw, 96) + ), + ); + } + AppEvent::CommandExited { + command_id, + job_id, + service_id, + exit_code, + } => { + let succeeded = exit_code == 0; + if let Some(command) = self.find_command_mut(command_id) { + command.status = if succeeded { + CommandStatus::Succeeded + } else { + CommandStatus::Failed + }; + command.exit_code = Some(exit_code); + command.ended_at = Some(now_utc()); + } + if let Some(job) = self.find_job_mut(job_id) { + job.status = if succeeded { + JobStatus::Succeeded + } else { + JobStatus::Failed + }; + job.ended_at = Some(now_utc()); + } + if let Some(service_id) = service_id { + if let Some(service) = self.find_service_mut(service_id) { + service.health = if succeeded { + ServiceHealth::Stopped + } else { + ServiceHealth::Degraded + }; + service.last_seen = now_utc(); + } + } + self.mark_process( + command_id, + if succeeded { + ProcessStatus::Exited + } else { + ProcessStatus::Failed + }, + ); + self.state.commands.active_command = None; + self.append_timeline( + TimelineKind::Command, + format!("command #{command_id} exited with code {exit_code}"), + ); + if !succeeded { + self.push_notification( + NotificationLevel::Warn, + format!("command #{command_id} failed with exit code {exit_code}"), + ); + } + } + AppEvent::CommandCancelled { + command_id, + job_id, + service_id, + } => { + if let Some(command) = self.find_command_mut(command_id) { + command.status = CommandStatus::Cancelled; + command.ended_at = Some(now_utc()); + } + if let Some(job) = self.find_job_mut(job_id) { + job.status = JobStatus::Cancelled; + job.ended_at = Some(now_utc()); + } + if let Some(service_id) = service_id { + if let Some(service) = self.find_service_mut(service_id) { + service.health = ServiceHealth::Stopped; + service.last_seen = now_utc(); + } + } + self.mark_process(command_id, ProcessStatus::Cancelled); + self.append_timeline( + TimelineKind::Command, + format!("command #{command_id} cancelled"), + ); + } + AppEvent::Diagnostic { + level, + message, + context, + } => { + self.state.diagnostics.records.push(DiagnosticRecord { + at: now_utc(), + level, + message: message.clone(), + context, + }); + if matches!(level, DiagnosticLevel::Warn | DiagnosticLevel::Error) { + self.push_notification(NotificationLevel::Warn, message.clone()); + } + } + AppEvent::Error(message) => { + self.state.ui.modal = Some(ModalState::Error(message.clone())); + self.state.ui.focus = FocusTarget::Modal; + self.state.diagnostics.records.push(DiagnosticRecord { + at: now_utc(), + level: DiagnosticLevel::Error, + message: message.clone(), + context: None, + }); + self.append_timeline(TimelineKind::Error, message.clone()); + self.push_notification(NotificationLevel::Error, message); + } + } + Vec::new() + } + + fn handle_ui_intent(&mut self, intent: UiIntent) -> Vec { + match intent { + UiIntent::KeyChar(c) => { + if let Some(ModalState::Approval(_)) = self.state.ui.modal.as_ref() { + match c { + 'y' | 'Y' => { + return self.dispatch_action(AppAction::Ui(UiIntent::ApproveCurrent)) + } + 'n' | 'N' => { + return self.dispatch_action(AppAction::Ui(UiIntent::DenyCurrent)) + } + _ => return Vec::new(), + } + } else if matches!(self.state.ui.focus, FocusTarget::CommandPane) { + self.state.ui.input_buffer.push(c); + } else if self.state.ui.modal.is_some() { + return Vec::new(); + } + } + UiIntent::Backspace => { + self.state.ui.input_buffer.pop(); + } + UiIntent::Submit => { + if let Some(modal) = self.state.ui.modal.as_ref() { + return match modal { + ModalState::Approval(_) => { + self.dispatch_action(AppAction::Ui(UiIntent::ApproveCurrent)) + } + ModalState::Help | ModalState::Error(_) => { + self.close_modal(); + Vec::new() + } + }; + } + + if self.state.ui.input_buffer.trim().is_empty() { + if let Some(approval_id) = self.current_inline_approval_id() { + return self.dispatch_action(AppAction::Approve(approval_id)); + } + return Vec::new(); + } + + let raw = std::mem::take(&mut self.state.ui.input_buffer); + match parse_input(&raw) { + Ok(parsed) => return self.dispatch_action(AppAction::ParsedInput(parsed)), + Err(message) => { + self.push_notification(NotificationLevel::Warn, message.clone()); + self.append_timeline(TimelineKind::Error, message); + } + } + } + UiIntent::ClearInput => { + self.state.ui.input_buffer.clear(); + } + UiIntent::NextFocus => { + if self.state.ui.modal.is_some() { + self.state.ui.focus = FocusTarget::Modal; + return Vec::new(); + } + self.state.ui.focus = match self.state.ui.focus { + FocusTarget::CommandPane => FocusTarget::DashboardPane, + FocusTarget::DashboardPane => FocusTarget::EventStream, + FocusTarget::EventStream | FocusTarget::Modal => FocusTarget::CommandPane, + }; + } + UiIntent::PrevFocus => { + if self.state.ui.modal.is_some() { + self.state.ui.focus = FocusTarget::Modal; + return Vec::new(); + } + self.state.ui.focus = match self.state.ui.focus { + FocusTarget::CommandPane | FocusTarget::Modal => FocusTarget::EventStream, + FocusTarget::DashboardPane => FocusTarget::CommandPane, + FocusTarget::EventStream => FocusTarget::DashboardPane, + }; + } + UiIntent::NextTab => self.advance_tab(true), + UiIntent::PrevTab => self.advance_tab(false), + UiIntent::ApproveCurrent => { + if let Some(approval_id) = self.current_approval_id() { + return self.dispatch_action(AppAction::Approve(approval_id)); + } else if self.state.ui.modal.is_some() { + self.close_modal(); + } + } + UiIntent::DenyCurrent => { + if let Some(approval_id) = self.current_approval_id() { + return self.dispatch_action(AppAction::Deny(approval_id)); + } + self.close_modal(); + } + UiIntent::Resize(width, height) => { + self.state.ui.terminal_size = (width, height); + } + UiIntent::Tick => { + self.state.app.tick_count += 1; + let mut effects = Vec::new(); + if self.state.config.git.enabled && self.state.app.tick_count.is_multiple_of(50) { + effects.push(Effect::RefreshGit(self.state.project.root.clone())); + } + if self.state.app.tick_count.is_multiple_of(100) { + effects.push(Effect::RefreshProjectContext( + self.state.project.root.clone(), + )); + } + return effects; + } + UiIntent::Quit => { + self.state.app.should_quit = true; + return vec![Effect::Shutdown]; + } + UiIntent::Esc => { + if self.state.ui.modal.is_some() { + return match self.state.ui.modal.as_ref() { + Some(ModalState::Approval(_)) => { + self.dispatch_action(AppAction::Ui(UiIntent::DenyCurrent)) + } + Some(ModalState::Help) | Some(ModalState::Error(_)) => { + self.close_modal(); + Vec::new() + } + None => Vec::new(), + }; + } + self.state.ui.input_buffer.clear(); + } + } + Vec::new() + } + + fn handle_parsed_input(&mut self, input: ParsedInput) -> Vec { + match input { + ParsedInput::Execute { + command, + background, + provenance, + } => self.prepare_execution(command, background, provenance), + ParsedInput::Quit => self.dispatch_action(AppAction::Ui(UiIntent::Quit)), + ParsedInput::Clear => { + self.state.ui.input_buffer.clear(); + self.state.logs.recent.clear(); + self.state.logs.per_source.clear(); + self.append_timeline( + TimelineKind::System, + "cleared command input and visible log buffer".to_string(), + ); + Vec::new() + } + ParsedInput::NextTab => { + self.advance_tab(true); + Vec::new() + } + ParsedInput::PrevTab => { + self.advance_tab(false); + Vec::new() + } + ParsedInput::ApprovePending => { + if let Some(approval_id) = self.current_approval_id() { + self.dispatch_action(AppAction::Approve(approval_id)) + } else { + self.push_notification( + NotificationLevel::Info, + "no pending approvals".to_string(), + ); + Vec::new() + } + } + ParsedInput::DenyPending => { + if let Some(approval_id) = self.current_approval_id() { + self.dispatch_action(AppAction::Deny(approval_id)) + } else { + self.push_notification( + NotificationLevel::Info, + "no pending approvals".to_string(), + ); + Vec::new() + } + } + ParsedInput::Cancel(command_id) => self.dispatch_action(AppAction::Cancel(command_id)), + ParsedInput::Help => { + self.state.ui.modal = Some(ModalState::Help); + self.state.ui.focus = FocusTarget::Modal; + self.append_timeline(TimelineKind::System, "opened help reference".to_string()); + Vec::new() + } + ParsedInput::AiPrompt { prompt, kind } => self.prepare_ai_request(prompt, kind), + } + } + + fn prepare_ai_request(&mut self, prompt: String, kind: AiRequestKind) -> Vec { + if !self.state.ai.enabled { + let message = "AI is disabled in the current Forge configuration.".to_string(); + self.state.ai.status = AiStatus::Disabled; + self.state.ai.last_error = Some(message.clone()); + self.push_notification(NotificationLevel::Warn, message.clone()); + self.append_timeline(TimelineKind::Ai, message); + return Vec::new(); + } + + let request = AiRequest { + id: self.ids.next_ai_request(), + kind, + prompt: prompt.clone(), + created_at: now_utc(), + provider: self.state.ai.provider.clone(), + model: self.state.ai.model.clone(), + context: ai::build_context(&self.state), + }; + + let history_limit = self.state.config.ai.history_limit; + self.state.ai.status = AiStatus::Queued; + self.state.ai.push_request(request.clone(), history_limit); + self.state.ai.push_message( + AiMessage { + role: AiMessageRole::User, + content: prompt.clone(), + created_at: now_utc(), + }, + history_limit, + ); + self.state.ai.active_request = Some(request.id); + self.state.ai.last_error = None; + self.append_timeline( + TimelineKind::Ai, + format!( + "queued AI {} request #{}: {}", + kind.label().to_ascii_lowercase(), + request.id, + truncate_for_timeline(&prompt, 96) + ), + ); + self.push_notification( + NotificationLevel::Info, + format!("queued AI {} request", kind.label().to_ascii_lowercase()), + ); + vec![Effect::RunAiRequest(Box::new(request))] + } + + fn prepare_execution( + &mut self, + raw: String, + background: bool, + provenance: crate::domain::CommandProvenance, + ) -> Vec { + let safety_class = classify_command(&raw); + let command_id = self.ids.next_command(); + let job_id = self.ids.next_job(); + let service_id = background.then(|| self.ids.next_service()); + let request = ExecutionRequest { + command_id, + job_id, + service_id, + raw: raw.clone(), + cwd: self.state.project.root.clone(), + env: BTreeMap::new(), + shell: self.state.config.commands.default_shell.clone(), + mode: ExecutionMode::Managed, + provenance, + background, + safety_class, + }; + let approval_mode = approval_mode_for(safety_class, &self.state.config.safety); + let status = match approval_mode { + Some(ApprovalMode::InlineReview) => CommandStatus::PendingReview, + Some(ApprovalMode::ModalConfirm) => CommandStatus::PendingApproval, + None => CommandStatus::Queued, + }; + + self.state.commands.history.push(raw.clone()); + if self.state.commands.history.len() > self.state.config.commands.history_limit { + let overflow = + self.state.commands.history.len() - self.state.config.commands.history_limit; + self.state.commands.history.drain(0..overflow); + } + + self.state + .commands + .records + .push(CommandRecord::from_request(&request, status)); + self.state.jobs.records.push(JobRecord { + id: job_id, + command_id, + label: raw.clone(), + pid: None, + background, + status: JobStatus::Queued, + started_at: None, + ended_at: None, + }); + + if let Some(mode) = approval_mode { + let approval = ApprovalRequest { + id: self.ids.next_approval(), + command_id, + created_at: now_utc(), + class: safety_class, + mode, + summary: raw.clone(), + detail: format!( + "{} action classified as {}", + if background { + "background" + } else { + "foreground" + }, + safety_class.label() + ), + execution: request, + }; + self.append_timeline(TimelineKind::Approval, approval_message(&approval)); + if matches!(approval.mode, ApprovalMode::ModalConfirm) { + self.state.ui.modal = Some(ModalState::Approval(approval.id)); + self.state.ui.focus = FocusTarget::Modal; + } + self.state.approvals.pending.push(approval.clone()); + return vec![Effect::QueueApproval(approval)]; + } + + self.append_timeline( + TimelineKind::Command, + format!( + "queued command #{command_id}: {}", + truncate_for_timeline(&raw, 96) + ), + ); + vec![Effect::ExecuteCommand(request)] + } + + fn resolve_approval(&mut self, approval_id: ApprovalId, approved: bool) -> Vec { + let position = self + .state + .approvals + .pending + .iter() + .position(|request| request.id == approval_id); + let Some(position) = position else { + return Vec::new(); + }; + + let request = self.state.approvals.pending.remove(position); + self.state.approvals.history.push(ApprovalDecision { + approval_id, + command_id: request.command_id, + approved, + decided_at: now_utc(), + note: None, + }); + self.state.ui.modal = None; + self.state.ui.focus = FocusTarget::CommandPane; + + if approved { + if let Some(command) = self.find_command_mut(request.command_id) { + command.status = CommandStatus::Queued; + } + self.append_timeline( + TimelineKind::Approval, + format!("approved command #{}", request.command_id), + ); + return vec![Effect::ExecuteCommand(request.execution)]; + } + + if let Some(command) = self.find_command_mut(request.command_id) { + command.status = CommandStatus::Denied; + command.ended_at = Some(now_utc()); + } + if let Some(job) = self.find_job_by_command_mut(request.command_id) { + job.status = JobStatus::Cancelled; + job.ended_at = Some(now_utc()); + } + self.append_timeline( + TimelineKind::Approval, + format!("denied command #{}", request.command_id), + ); + Vec::new() + } + + fn current_approval_id(&self) -> Option { + if let Some(modal) = self.state.ui.modal.as_ref() { + return match modal { + ModalState::Approval(id) => Some(*id), + ModalState::Help | ModalState::Error(_) => None, + }; + } + self.current_inline_approval_id() + } + + fn close_modal(&mut self) { + self.state.ui.modal = None; + self.state.ui.focus = FocusTarget::CommandPane; + } + + fn current_inline_approval_id(&self) -> Option { + self.state + .approvals + .pending + .iter() + .find(|request| matches!(request.mode, ApprovalMode::InlineReview)) + .map(|request| request.id) + } + + fn append_timeline(&mut self, kind: TimelineKind, message: String) { + self.state.timeline.entries.push(TimelineEntry { + id: self.ids.next_timeline(), + at: now_utc(), + kind, + message, + }); + } + + fn push_notification(&mut self, level: NotificationLevel, message: String) { + self.state.notifications.items.push(Notification { + id: self.ids.next_notification(), + level, + message, + created_at: now_utc(), + }); + if self.state.notifications.items.len() > 10 { + let overflow = self.state.notifications.items.len() - 10; + self.state.notifications.items.drain(0..overflow); + } + } + + fn advance_tab(&mut self, forward: bool) { + let tabs = DashboardTab::all(); + let current_index = tabs + .iter() + .position(|tab| *tab == self.state.ui.dashboard_tab) + .unwrap_or(0); + let next_index = if forward { + (current_index + 1) % tabs.len() + } else if current_index == 0 { + tabs.len() - 1 + } else { + current_index - 1 + }; + self.state.ui.dashboard_tab = tabs[next_index]; + } + + fn find_command(&self, id: CommandId) -> Option<&CommandRecord> { + self.state + .commands + .records + .iter() + .find(|record| record.id == id) + } + + fn find_command_mut(&mut self, id: CommandId) -> Option<&mut CommandRecord> { + self.state + .commands + .records + .iter_mut() + .find(|record| record.id == id) + } + + fn find_job_mut(&mut self, id: crate::shared::ids::JobId) -> Option<&mut JobRecord> { + self.state + .jobs + .records + .iter_mut() + .find(|record| record.id == id) + } + + fn find_job_by_command_mut(&mut self, id: CommandId) -> Option<&mut JobRecord> { + self.state + .jobs + .records + .iter_mut() + .find(|record| record.command_id == id) + } + + fn upsert_service(&mut self, service: ServiceRecord) { + match self + .state + .services + .registry + .iter_mut() + .find(|record| record.id == service.id) + { + Some(existing) => *existing = service, + None => self.state.services.registry.push(service), + } + } + + fn find_service_mut( + &mut self, + id: crate::shared::ids::ServiceId, + ) -> Option<&mut ServiceRecord> { + self.state + .services + .registry + .iter_mut() + .find(|record| record.id == id) + } + + fn upsert_process(&mut self, process: ProcessSnapshot) { + match self + .state + .processes + .snapshots + .iter_mut() + .find(|record| record.command_id == process.command_id) + { + Some(existing) => *existing = process, + None => self.state.processes.snapshots.push(process), + } + } + + fn mark_process(&mut self, command_id: CommandId, status: ProcessStatus) { + if let Some(process) = self + .state + .processes + .snapshots + .iter_mut() + .find(|record| record.command_id == Some(command_id)) + { + process.status = status; + process.observed_at = now_utc(); + } + } +} + +fn truncate_for_timeline(message: &str, max_len: usize) -> String { + let trimmed = message.trim(); + if trimmed.len() <= max_len { + return trimmed.to_string(); + } + format!("{}...", &trimmed[..max_len.saturating_sub(3)]) +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs new file mode 100644 index 0000000..cf5ae63 --- /dev/null +++ b/src/commands/mod.rs @@ -0,0 +1,97 @@ +use crate::domain::{AiRequestKind, CommandProvenance}; +use crate::shared::ids::CommandId; + +#[derive(Debug, Clone)] +pub enum ParsedInput { + Execute { + command: String, + background: bool, + provenance: CommandProvenance, + }, + Quit, + Clear, + NextTab, + PrevTab, + ApprovePending, + DenyPending, + Cancel(CommandId), + Help, + AiPrompt { + prompt: String, + kind: AiRequestKind, + }, +} + +pub fn parse_input(input: &str) -> Result { + let trimmed = input.trim(); + if trimmed.is_empty() { + return Err("input is empty".to_string()); + } + + if !trimmed.starts_with('/') { + let (command, background) = parse_shell(trimmed); + return Ok(ParsedInput::Execute { + command, + background, + provenance: CommandProvenance::UserInput, + }); + } + + if trimmed == "/quit" || trimmed == "/exit" { + return Ok(ParsedInput::Quit); + } + if trimmed == "/clear" { + return Ok(ParsedInput::Clear); + } + if trimmed == "/tab next" || trimmed == "/next-tab" { + return Ok(ParsedInput::NextTab); + } + if trimmed == "/tab prev" || trimmed == "/prev-tab" { + return Ok(ParsedInput::PrevTab); + } + if trimmed == "/approve" { + return Ok(ParsedInput::ApprovePending); + } + if trimmed == "/deny" { + return Ok(ParsedInput::DenyPending); + } + if trimmed == "/help" { + return Ok(ParsedInput::Help); + } + if let Some(rest) = trimmed.strip_prefix("/bg ") { + return Ok(ParsedInput::Execute { + command: rest.trim().to_string(), + background: true, + provenance: CommandProvenance::SlashCommand, + }); + } + if let Some(rest) = trimmed.strip_prefix("/cancel ") { + let id = rest + .trim() + .parse::() + .map_err(|_| "cancel expects a numeric command id".to_string())?; + return Ok(ParsedInput::Cancel(CommandId(id))); + } + if let Some(rest) = trimmed.strip_prefix("/ai ") { + return Ok(ParsedInput::AiPrompt { + prompt: rest.trim().to_string(), + kind: AiRequestKind::Assist, + }); + } + if let Some(rest) = trimmed.strip_prefix("/diagnose ") { + return Ok(ParsedInput::AiPrompt { + prompt: rest.trim().to_string(), + kind: AiRequestKind::Diagnose, + }); + } + + Err(format!("unknown slash command: {trimmed}")) +} + +fn parse_shell(input: &str) -> (String, bool) { + let trimmed = input.trim(); + if let Some(stripped) = trimmed.strip_suffix('&') { + return (stripped.trim().to_string(), true); + } + (trimmed.to_string(), false) +} diff --git a/src/config/loader.rs b/src/config/loader.rs new file mode 100644 index 0000000..bdd6335 --- /dev/null +++ b/src/config/loader.rs @@ -0,0 +1,148 @@ +use std::fs; +use std::path::{Path, PathBuf}; + +use clap::Parser; + +use crate::config::schema::{ForgeConfig, PartialForgeConfig}; +use crate::shared::error::{AppResult, ConfigError}; + +#[derive(Debug, Clone, Parser)] +#[command(name = "forge", version, about = "Forge DevOps command center")] +pub struct CliArgs { + #[arg(long)] + pub config: Option, + #[arg(long)] + pub cwd: Option, + #[arg(long)] + pub debug: bool, + #[arg(long)] + pub tick_rate_ms: Option, + #[arg(long)] + pub log_level: Option, + #[arg(long)] + pub ai_provider: Option, + #[arg(long)] + pub ai_model: Option, +} + +#[derive(Debug, Clone)] +pub struct LoadedConfig { + pub config: ForgeConfig, + pub cwd: PathBuf, + pub global_config_path: Option, + pub project_config_path: Option, +} + +pub fn load_config(cli: &CliArgs) -> AppResult { + let cwd = match cli.cwd.clone() { + Some(path) => path, + None => std::env::current_dir()?, + }; + + let mut config = ForgeConfig::default(); + + let global_candidate = dirs::config_dir().map(|dir| dir.join("forge").join("config.toml")); + let global_config_path = + if let Some(path) = global_candidate.as_ref().filter(|path| path.exists()) { + read_partial(path)?.apply_to(&mut config); + Some(path.clone()) + } else { + None + }; + + let project_candidate = cli.config.clone().or_else(|| { + let path = cwd.join(".forge").join("config.toml"); + path.exists().then_some(path) + }); + + if let Some(path) = project_candidate.as_ref() { + read_partial(path)?.apply_to(&mut config); + } + + apply_env_overrides(&mut config); + apply_cli_overrides(cli, &mut config); + config.normalize(); + + Ok(LoadedConfig { + config, + cwd, + global_config_path, + project_config_path: project_candidate, + }) +} + +fn read_partial(path: &Path) -> AppResult { + let raw = fs::read_to_string(path).map_err(|source| ConfigError::Read { + path: path.to_path_buf(), + source, + })?; + if raw.trim().is_empty() { + return Ok(PartialForgeConfig::default()); + } + toml::from_str(&raw) + .map_err(|source| ConfigError::Parse { + path: path.to_path_buf(), + source, + }) + .map_err(Into::into) +} + +fn apply_env_overrides(config: &mut ForgeConfig) { + if let Ok(value) = std::env::var("FORGE_TICK_RATE_MS") { + if let Ok(parsed) = value.parse::() { + config.ui.tick_rate_ms = parsed; + } + } + if let Ok(value) = std::env::var("FORGE_LOG_LEVEL") { + config.observability.log_level = value; + } + if let Ok(value) = std::env::var("FORGE_SHELL") { + config.commands.default_shell = value; + } + if let Ok(value) = std::env::var("FORGE_AI_ENABLED") { + match value.to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => config.ai.enabled = true, + "0" | "false" | "no" | "off" => config.ai.enabled = false, + _ => {} + } + } + if let Ok(value) = std::env::var("FORGE_AI_PROVIDER") { + config.ai.provider = Some(value); + } + if let Ok(value) = std::env::var("FORGE_AI_MODEL") { + config.ai.model = Some(value); + } + if let Ok(value) = std::env::var("FORGE_AI_TIMEOUT_SECS") { + if let Ok(parsed) = value.parse::() { + config.ai.request_timeout_secs = parsed; + } + } + if let Ok(value) = std::env::var("FORGE_EVENT_STREAM_HEIGHT") { + if let Ok(parsed) = value.parse::() { + config.ui.event_stream_height = parsed; + } + } + if let Ok(value) = std::env::var("FORGE_MAIN_SPLIT_PCT") { + if let Ok(parsed) = value.parse::() { + config.ui.main_split_pct = parsed; + } + } +} + +fn apply_cli_overrides(cli: &CliArgs, config: &mut ForgeConfig) { + if let Some(value) = cli.tick_rate_ms { + config.ui.tick_rate_ms = value; + } + if let Some(value) = cli.log_level.as_ref() { + config.observability.log_level = value.clone(); + } + if let Some(value) = cli.ai_provider.as_ref() { + config.ai.provider = Some(value.clone()); + } + if let Some(value) = cli.ai_model.as_ref() { + config.ai.model = Some(value.clone()); + } + if cli.debug { + config.observability.log_level = "debug".to_string(); + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs new file mode 100644 index 0000000..55b1d0b --- /dev/null +++ b/src/config/mod.rs @@ -0,0 +1,8 @@ +mod loader; +mod schema; + +pub use loader::{load_config, CliArgs, LoadedConfig}; +pub use schema::{ + AiConfig, CommandConfig, ForgeConfig, GitConfig, LogConfig, ObservabilityConfig, SafetyConfig, + ServiceConfig, UiConfig, +}; diff --git a/src/config/schema.rs b/src/config/schema.rs new file mode 100644 index 0000000..35ce294 --- /dev/null +++ b/src/config/schema.rs @@ -0,0 +1,397 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(default)] +pub struct ForgeConfig { + pub ui: UiConfig, + pub commands: CommandConfig, + pub safety: SafetyConfig, + pub services: ServiceConfig, + pub logs: LogConfig, + pub git: GitConfig, + pub ai: AiConfig, + pub observability: ObservabilityConfig, +} + +impl ForgeConfig { + pub fn normalize(&mut self) { + self.ui.tick_rate_ms = self.ui.tick_rate_ms.max(33); + self.ui.main_split_pct = self.ui.main_split_pct.clamp(25, 75); + self.ui.event_stream_height = self.ui.event_stream_height.clamp(6, 16); + self.commands.scrollback_limit = self.commands.scrollback_limit.max(100); + self.commands.history_limit = self.commands.history_limit.max(25); + self.logs.global_capacity = self.logs.global_capacity.max(200); + self.logs.per_source_capacity = self.logs.per_source_capacity.max(50); + self.ai.request_timeout_secs = self.ai.request_timeout_secs.max(5); + self.ai.history_limit = self.ai.history_limit.max(5); + self.ai.max_recent_commands = self.ai.max_recent_commands.max(1); + self.ai.max_recent_logs = self.ai.max_recent_logs.max(1); + self.ai.max_recent_events = self.ai.max_recent_events.max(1); + self.ai.max_recent_services = self.ai.max_recent_services.max(1); + self.ai.max_recent_tests = self.ai.max_recent_tests.max(1); + self.ai.max_changed_files = self.ai.max_changed_files.max(1); + self.observability.diagnostics_capacity = self.observability.diagnostics_capacity.max(100); + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct UiConfig { + pub tick_rate_ms: u64, + pub main_split_pct: u16, + pub event_stream_height: u16, + pub history_preview: usize, +} + +impl Default for UiConfig { + fn default() -> Self { + Self { + tick_rate_ms: 120, + main_split_pct: 40, + event_stream_height: 8, + history_preview: 6, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct CommandConfig { + pub default_shell: String, + pub scrollback_limit: usize, + pub history_limit: usize, +} + +impl Default for CommandConfig { + fn default() -> Self { + Self { + default_shell: std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()), + scrollback_limit: 2_000, + history_limit: 200, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct SafetyConfig { + pub caution_requires_review: bool, + pub destructive_requires_confirmation: bool, +} + +impl Default for SafetyConfig { + fn default() -> Self { + Self { + caution_requires_review: true, + destructive_requires_confirmation: true, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct ServiceConfig { + pub health_stale_after_secs: u64, +} + +impl Default for ServiceConfig { + fn default() -> Self { + Self { + health_stale_after_secs: 15, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct LogConfig { + pub global_capacity: usize, + pub per_source_capacity: usize, +} + +impl Default for LogConfig { + fn default() -> Self { + Self { + global_capacity: 2_000, + per_source_capacity: 300, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct GitConfig { + pub enabled: bool, +} + +impl Default for GitConfig { + fn default() -> Self { + Self { enabled: true } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct AiConfig { + pub enabled: bool, + pub provider: Option, + pub model: Option, + pub request_timeout_secs: u64, + pub history_limit: usize, + pub max_recent_commands: usize, + pub max_recent_logs: usize, + pub max_recent_events: usize, + pub max_recent_services: usize, + pub max_recent_tests: usize, + pub max_changed_files: usize, +} + +impl Default for AiConfig { + fn default() -> Self { + Self { + enabled: true, + provider: None, + model: None, + request_timeout_secs: 30, + history_limit: 20, + max_recent_commands: 6, + max_recent_logs: 12, + max_recent_events: 12, + max_recent_services: 6, + max_recent_tests: 4, + max_changed_files: 12, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct ObservabilityConfig { + pub log_level: String, + pub diagnostics_capacity: usize, + pub log_to_file: bool, +} + +impl Default for ObservabilityConfig { + fn default() -> Self { + Self { + log_level: "info".to_string(), + diagnostics_capacity: 500, + log_to_file: true, + } + } +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct PartialForgeConfig { + pub ui: PartialUiConfig, + pub commands: PartialCommandConfig, + pub safety: PartialSafetyConfig, + pub services: PartialServiceConfig, + pub logs: PartialLogConfig, + pub git: PartialGitConfig, + pub ai: PartialAiConfig, + pub observability: PartialObservabilityConfig, +} + +impl PartialForgeConfig { + pub fn apply_to(self, config: &mut ForgeConfig) { + self.ui.apply_to(&mut config.ui); + self.commands.apply_to(&mut config.commands); + self.safety.apply_to(&mut config.safety); + self.services.apply_to(&mut config.services); + self.logs.apply_to(&mut config.logs); + self.git.apply_to(&mut config.git); + self.ai.apply_to(&mut config.ai); + self.observability.apply_to(&mut config.observability); + } +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct PartialUiConfig { + pub tick_rate_ms: Option, + pub main_split_pct: Option, + pub event_stream_height: Option, + pub history_preview: Option, +} + +impl PartialUiConfig { + fn apply_to(self, config: &mut UiConfig) { + if let Some(value) = self.tick_rate_ms { + config.tick_rate_ms = value; + } + if let Some(value) = self.main_split_pct { + config.main_split_pct = value; + } + if let Some(value) = self.event_stream_height { + config.event_stream_height = value; + } + if let Some(value) = self.history_preview { + config.history_preview = value; + } + } +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct PartialCommandConfig { + pub default_shell: Option, + pub scrollback_limit: Option, + pub history_limit: Option, +} + +impl PartialCommandConfig { + fn apply_to(self, config: &mut CommandConfig) { + if let Some(value) = self.default_shell { + config.default_shell = value; + } + if let Some(value) = self.scrollback_limit { + config.scrollback_limit = value; + } + if let Some(value) = self.history_limit { + config.history_limit = value; + } + } +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct PartialSafetyConfig { + pub caution_requires_review: Option, + pub destructive_requires_confirmation: Option, +} + +impl PartialSafetyConfig { + fn apply_to(self, config: &mut SafetyConfig) { + if let Some(value) = self.caution_requires_review { + config.caution_requires_review = value; + } + if let Some(value) = self.destructive_requires_confirmation { + config.destructive_requires_confirmation = value; + } + } +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct PartialServiceConfig { + pub health_stale_after_secs: Option, +} + +impl PartialServiceConfig { + fn apply_to(self, config: &mut ServiceConfig) { + if let Some(value) = self.health_stale_after_secs { + config.health_stale_after_secs = value; + } + } +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct PartialLogConfig { + pub global_capacity: Option, + pub per_source_capacity: Option, +} + +impl PartialLogConfig { + fn apply_to(self, config: &mut LogConfig) { + if let Some(value) = self.global_capacity { + config.global_capacity = value; + } + if let Some(value) = self.per_source_capacity { + config.per_source_capacity = value; + } + } +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct PartialGitConfig { + pub enabled: Option, +} + +impl PartialGitConfig { + fn apply_to(self, config: &mut GitConfig) { + if let Some(value) = self.enabled { + config.enabled = value; + } + } +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct PartialAiConfig { + pub enabled: Option, + pub provider: Option, + pub model: Option, + pub request_timeout_secs: Option, + pub history_limit: Option, + pub max_recent_commands: Option, + pub max_recent_logs: Option, + pub max_recent_events: Option, + pub max_recent_services: Option, + pub max_recent_tests: Option, + pub max_changed_files: Option, +} + +impl PartialAiConfig { + fn apply_to(self, config: &mut AiConfig) { + if let Some(value) = self.enabled { + config.enabled = value; + } + if self.provider.is_some() { + config.provider = self.provider; + } + if self.model.is_some() { + config.model = self.model; + } + if let Some(value) = self.request_timeout_secs { + config.request_timeout_secs = value; + } + if let Some(value) = self.history_limit { + config.history_limit = value; + } + if let Some(value) = self.max_recent_commands { + config.max_recent_commands = value; + } + if let Some(value) = self.max_recent_logs { + config.max_recent_logs = value; + } + if let Some(value) = self.max_recent_events { + config.max_recent_events = value; + } + if let Some(value) = self.max_recent_services { + config.max_recent_services = value; + } + if let Some(value) = self.max_recent_tests { + config.max_recent_tests = value; + } + if let Some(value) = self.max_changed_files { + config.max_changed_files = value; + } + } +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct PartialObservabilityConfig { + pub log_level: Option, + pub diagnostics_capacity: Option, + pub log_to_file: Option, +} + +impl PartialObservabilityConfig { + fn apply_to(self, config: &mut ObservabilityConfig) { + if let Some(value) = self.log_level { + config.log_level = value; + } + if let Some(value) = self.diagnostics_capacity { + config.diagnostics_capacity = value; + } + if let Some(value) = self.log_to_file { + config.log_to_file = value; + } + } +} diff --git a/src/domain/ai.rs b/src/domain/ai.rs new file mode 100644 index 0000000..6493f41 --- /dev/null +++ b/src/domain/ai.rs @@ -0,0 +1,243 @@ +use std::path::PathBuf; +use std::time::SystemTime; + +use crate::domain::{ + approval::SafetyClass, command::CommandProvenance, command::CommandStatus, log::LogSeverity, + log::LogStream, service::ServiceHealth, test::TestStatus, timeline::TimelineKind, +}; +use crate::shared::ids::{AiRequestId, CommandId, ServiceId}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AiRequestKind { + Assist, + Diagnose, +} + +impl AiRequestKind { + pub fn label(&self) -> &'static str { + match self { + Self::Assist => "Assist", + Self::Diagnose => "Diagnose", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AiStatus { + Disabled, + Unconfigured, + Ready, + Queued, + Running, + Completed, + Failed, +} + +impl AiStatus { + pub fn label(&self) -> &'static str { + match self { + Self::Disabled => "OFF", + Self::Unconfigured => "SETUP", + Self::Ready => "READY", + Self::Queued => "QUEUED", + Self::Running => "RUNNING", + Self::Completed => "DONE", + Self::Failed => "ERROR", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AiMessageRole { + System, + User, + Assistant, +} + +#[derive(Debug, Clone)] +pub struct AiMessage { + pub role: AiMessageRole, + pub content: String, + pub created_at: SystemTime, +} + +#[derive(Debug, Clone)] +pub struct AiUiContext { + pub focus: String, + pub dashboard_tab: String, + pub modal: Option, + pub pending_approvals: usize, +} + +#[derive(Debug, Clone)] +pub struct AiProjectContext { + pub name: String, + pub root: PathBuf, + pub stack_hints: Vec, + pub config_paths: Vec, + pub discovered_files: Vec, +} + +#[derive(Debug, Clone)] +pub struct AiGitContext { + pub branch: Option, + pub head: Option, + pub is_dirty: bool, + pub changed_files: Vec, +} + +#[derive(Debug, Clone)] +pub struct AiCommandContext { + pub id: CommandId, + pub raw: String, + pub provenance: CommandProvenance, + pub status: CommandStatus, + pub exit_code: Option, + pub output_line_count: usize, + pub background: bool, +} + +#[derive(Debug, Clone)] +pub struct AiServiceContext { + pub id: ServiceId, + pub name: String, + pub health: ServiceHealth, + pub pid: Option, + pub ports: Vec, + pub tags: Vec, +} + +#[derive(Debug, Clone)] +pub struct AiTestContext { + pub runner: String, + pub status: TestStatus, + pub pass_count: usize, + pub fail_count: usize, + pub failed_tests: Vec, +} + +#[derive(Debug, Clone)] +pub struct AiLogContext { + pub ts: SystemTime, + pub source_label: String, + pub stream: LogStream, + pub severity: LogSeverity, + pub service_id: Option, + pub command_id: Option, + pub raw: String, +} + +#[derive(Debug, Clone)] +pub struct AiTimelineContext { + pub at: SystemTime, + pub kind: TimelineKind, + pub message: String, +} + +#[derive(Debug, Clone)] +pub struct AiContextBundle { + pub ui: AiUiContext, + pub project: AiProjectContext, + pub git: AiGitContext, + pub commands: Vec, + pub services: Vec, + pub tests: Vec, + pub logs: Vec, + pub timeline: Vec, +} + +#[derive(Debug, Clone)] +pub struct AiRequest { + pub id: AiRequestId, + pub kind: AiRequestKind, + pub created_at: SystemTime, + pub provider: Option, + pub model: Option, + pub prompt: String, + pub context: AiContextBundle, +} + +#[derive(Debug, Clone)] +pub struct AiCitation { + pub label: String, + pub detail: String, +} + +#[derive(Debug, Clone)] +pub struct AiActionProposal { + pub summary: String, + pub detail: String, + pub command: Option, + pub safety_class: SafetyClass, +} + +#[derive(Debug, Clone)] +pub struct AiResponse { + pub request_id: AiRequestId, + pub created_at: SystemTime, + pub provider: String, + pub model: Option, + pub summary: String, + pub message: String, + pub recommendations: Vec, + pub proposals: Vec, + pub citations: Vec, +} + +#[derive(Debug, Clone)] +pub struct AiSessionState { + pub enabled: bool, + pub provider: Option, + pub model: Option, + pub status: AiStatus, + pub active_request: Option, + pub requests: Vec, + pub messages: Vec, + pub last_context: Option, + pub last_response: Option, + pub last_error: Option, +} + +impl AiSessionState { + pub fn from_config(enabled: bool, provider: Option, model: Option) -> Self { + let status = if !enabled { + AiStatus::Disabled + } else if provider.is_some() { + AiStatus::Ready + } else { + AiStatus::Unconfigured + }; + + Self { + enabled, + provider, + model, + status, + active_request: None, + requests: Vec::new(), + messages: Vec::new(), + last_context: None, + last_response: None, + last_error: None, + } + } + + pub fn push_request(&mut self, request: AiRequest, limit: usize) { + self.active_request = Some(request.id); + self.last_context = Some(request.context.clone()); + self.requests.push(request); + trim_vec(&mut self.requests, limit); + } + + pub fn push_message(&mut self, message: AiMessage, limit: usize) { + self.messages.push(message); + trim_vec(&mut self.messages, limit); + } +} + +fn trim_vec(items: &mut Vec, limit: usize) { + if items.len() > limit { + let overflow = items.len() - limit; + items.drain(0..overflow); + } +} diff --git a/src/domain/app.rs b/src/domain/app.rs new file mode 100644 index 0000000..32a4f0f --- /dev/null +++ b/src/domain/app.rs @@ -0,0 +1,152 @@ +use std::time::SystemTime; + +use crate::config::ForgeConfig; +use crate::domain::{ + AiSessionState, ApprovalState, CommandState, DiagnosticsState, GitSnapshot, JobState, LogState, + ProcessState, ProjectContext, ServiceState, TestState, TimelineState, +}; +use crate::shared::ids::{ApprovalId, NotificationId}; +use crate::shared::time::now_utc; + +#[derive(Debug, Clone)] +pub struct AppMetaState { + pub started_at: SystemTime, + pub tick_count: u64, + pub should_quit: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FocusTarget { + CommandPane, + DashboardPane, + EventStream, + Modal, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DashboardTab { + Services, + Processes, + Logs, + Git, + Tests, +} + +impl DashboardTab { + pub fn all() -> [DashboardTab; 5] { + [ + DashboardTab::Services, + DashboardTab::Processes, + DashboardTab::Logs, + DashboardTab::Git, + DashboardTab::Tests, + ] + } + + pub fn title(&self) -> &'static str { + match self { + DashboardTab::Services => "Services", + DashboardTab::Processes => "Processes", + DashboardTab::Logs => "Logs", + DashboardTab::Git => "Git", + DashboardTab::Tests => "Tests", + } + } +} + +#[derive(Debug, Clone)] +pub enum ModalState { + Approval(ApprovalId), + Help, + Error(String), +} + +#[derive(Debug, Clone)] +pub struct UiState { + pub focus: FocusTarget, + pub dashboard_tab: DashboardTab, + pub input_buffer: String, + pub modal: Option, + pub terminal_size: (u16, u16), + pub approval_cursor: usize, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NotificationLevel { + Info, + Warn, + Error, +} + +#[derive(Debug, Clone)] +pub struct Notification { + pub id: NotificationId, + pub level: NotificationLevel, + pub message: String, + pub created_at: SystemTime, +} + +#[derive(Debug, Clone, Default)] +pub struct NotificationState { + pub items: Vec, +} + +#[derive(Debug, Clone)] +pub struct AppState { + pub app: AppMetaState, + pub ui: UiState, + pub config: ForgeConfig, + pub project: ProjectContext, + pub git: GitSnapshot, + pub commands: CommandState, + pub jobs: JobState, + pub services: ServiceState, + pub processes: ProcessState, + pub logs: LogState, + pub tests: TestState, + pub timeline: TimelineState, + pub approvals: ApprovalState, + pub ai: AiSessionState, + pub diagnostics: DiagnosticsState, + pub notifications: NotificationState, +} + +impl AppState { + pub fn new(config: ForgeConfig, project: ProjectContext, git: GitSnapshot) -> Self { + let diagnostics_capacity = config.observability.diagnostics_capacity; + let global_log_capacity = config.logs.global_capacity; + Self { + app: AppMetaState { + started_at: now_utc(), + tick_count: 0, + should_quit: false, + }, + ui: UiState { + focus: FocusTarget::CommandPane, + dashboard_tab: DashboardTab::Services, + input_buffer: String::new(), + modal: None, + terminal_size: (0, 0), + approval_cursor: 0, + }, + config: config.clone(), + project, + git, + commands: CommandState::default(), + jobs: JobState::default(), + services: ServiceState::default(), + processes: ProcessState::default(), + logs: LogState::new(global_log_capacity), + tests: TestState::default(), + timeline: TimelineState::new(global_log_capacity), + approvals: ApprovalState::default(), + ai: AiSessionState::from_config( + config.ai.enabled, + config.ai.provider.clone(), + config.ai.model.clone(), + ), + diagnostics: DiagnosticsState::new(diagnostics_capacity), + notifications: NotificationState::default(), + } + } +} diff --git a/src/domain/approval.rs b/src/domain/approval.rs new file mode 100644 index 0000000..837b71c --- /dev/null +++ b/src/domain/approval.rs @@ -0,0 +1,58 @@ +use std::time::SystemTime; + +use crate::domain::command::ExecutionRequest; +use crate::shared::ids::{ApprovalId, CommandId}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum SafetyClass { + Passive, + Safe, + Caution, + Risky, + Destructive, +} + +impl SafetyClass { + pub fn label(&self) -> &'static str { + match self { + Self::Passive => "Passive", + Self::Safe => "Safe", + Self::Caution => "Caution", + Self::Risky => "Risky", + Self::Destructive => "Destructive", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ApprovalMode { + InlineReview, + ModalConfirm, +} + +#[derive(Debug, Clone)] +pub struct ApprovalRequest { + pub id: ApprovalId, + pub command_id: CommandId, + pub created_at: SystemTime, + pub class: SafetyClass, + pub mode: ApprovalMode, + pub summary: String, + pub detail: String, + pub execution: ExecutionRequest, +} + +#[derive(Debug, Clone)] +pub struct ApprovalDecision { + pub approval_id: ApprovalId, + pub command_id: CommandId, + pub approved: bool, + pub decided_at: SystemTime, + pub note: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct ApprovalState { + pub pending: Vec, + pub history: Vec, +} diff --git a/src/domain/command.rs b/src/domain/command.rs new file mode 100644 index 0000000..ca6a7ca --- /dev/null +++ b/src/domain/command.rs @@ -0,0 +1,93 @@ +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::time::SystemTime; + +use crate::domain::approval::SafetyClass; +use crate::shared::ids::{CommandId, JobId, ServiceId}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExecutionMode { + Managed, + Pty, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CommandProvenance { + UserInput, + SlashCommand, + ApprovalEscalation, + AiSuggestion, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CommandStatus { + PendingReview, + PendingApproval, + Queued, + Running, + Succeeded, + Failed, + Cancelled, + Denied, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OutputStream { + Stdout, + Stderr, +} + +#[derive(Debug, Clone)] +pub struct ExecutionRequest { + pub command_id: CommandId, + pub job_id: JobId, + pub service_id: Option, + pub raw: String, + pub cwd: PathBuf, + pub env: BTreeMap, + pub shell: String, + pub mode: ExecutionMode, + pub provenance: CommandProvenance, + pub background: bool, + pub safety_class: SafetyClass, +} + +#[derive(Debug, Clone)] +pub struct CommandRecord { + pub id: CommandId, + pub raw: String, + pub cwd: PathBuf, + pub provenance: CommandProvenance, + pub safety_class: SafetyClass, + pub background: bool, + pub status: CommandStatus, + pub started_at: Option, + pub ended_at: Option, + pub exit_code: Option, + pub output_line_count: usize, +} + +impl CommandRecord { + pub fn from_request(request: &ExecutionRequest, status: CommandStatus) -> Self { + Self { + id: request.command_id, + raw: request.raw.clone(), + cwd: request.cwd.clone(), + provenance: request.provenance, + safety_class: request.safety_class, + background: request.background, + status, + started_at: None, + ended_at: None, + exit_code: None, + output_line_count: 0, + } + } +} + +#[derive(Debug, Clone, Default)] +pub struct CommandState { + pub history: Vec, + pub records: Vec, + pub active_command: Option, +} diff --git a/src/domain/diagnostics.rs b/src/domain/diagnostics.rs new file mode 100644 index 0000000..58b4f50 --- /dev/null +++ b/src/domain/diagnostics.rs @@ -0,0 +1,36 @@ +use std::path::PathBuf; +use std::time::SystemTime; + +use crate::shared::ring_buffer::RingBuffer; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DiagnosticLevel { + Trace, + Debug, + Info, + Warn, + Error, +} + +#[derive(Debug, Clone)] +pub struct DiagnosticRecord { + pub at: SystemTime, + pub level: DiagnosticLevel, + pub message: String, + pub context: Option, +} + +#[derive(Debug, Clone)] +pub struct DiagnosticsState { + pub records: RingBuffer, + pub log_file: Option, +} + +impl DiagnosticsState { + pub fn new(capacity: usize) -> Self { + Self { + records: RingBuffer::new(capacity), + log_file: None, + } + } +} diff --git a/src/domain/git.rs b/src/domain/git.rs new file mode 100644 index 0000000..356d175 --- /dev/null +++ b/src/domain/git.rs @@ -0,0 +1,25 @@ +use std::path::PathBuf; +use std::time::SystemTime; + +#[derive(Debug, Clone)] +pub struct GitSnapshot { + pub root: Option, + pub branch: Option, + pub head: Option, + pub is_dirty: bool, + pub changed_files: Vec, + pub last_refreshed: SystemTime, +} + +impl Default for GitSnapshot { + fn default() -> Self { + Self { + root: None, + branch: None, + head: None, + is_dirty: false, + changed_files: Vec::new(), + last_refreshed: SystemTime::now(), + } + } +} diff --git a/src/domain/job.rs b/src/domain/job.rs new file mode 100644 index 0000000..afea44d --- /dev/null +++ b/src/domain/job.rs @@ -0,0 +1,29 @@ +use std::time::SystemTime; + +use crate::shared::ids::{CommandId, JobId}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum JobStatus { + Queued, + Running, + Succeeded, + Failed, + Cancelled, +} + +#[derive(Debug, Clone)] +pub struct JobRecord { + pub id: JobId, + pub command_id: CommandId, + pub label: String, + pub pid: Option, + pub background: bool, + pub status: JobStatus, + pub started_at: Option, + pub ended_at: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct JobState { + pub records: Vec, +} diff --git a/src/domain/log.rs b/src/domain/log.rs new file mode 100644 index 0000000..1bee01f --- /dev/null +++ b/src/domain/log.rs @@ -0,0 +1,67 @@ +use std::collections::BTreeMap; +use std::time::SystemTime; + +use crate::shared::ids::{CommandId, LogId, ServiceId}; +use crate::shared::ring_buffer::RingBuffer; + +#[derive(Debug, Clone)] +pub enum LogSource { + Command(CommandId), + Service(ServiceId), + System, + Git, + Ai, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LogStream { + Stdout, + Stderr, + System, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LogSeverity { + Trace, + Debug, + Info, + Warn, + Error, + Unknown, +} + +#[derive(Debug, Clone)] +pub struct LogEntry { + pub id: LogId, + pub ts: SystemTime, + pub source: LogSource, + pub stream: LogStream, + pub service_id: Option, + pub command_id: Option, + pub severity: LogSeverity, + pub raw: String, + pub fields: BTreeMap, +} + +#[derive(Debug, Clone, Default)] +pub struct LogFilters { + pub source_key: Option, + pub text: Option, +} + +#[derive(Debug, Clone)] +pub struct LogState { + pub recent: RingBuffer, + pub per_source: BTreeMap>, + pub filters: LogFilters, +} + +impl LogState { + pub fn new(global_capacity: usize) -> Self { + Self { + recent: RingBuffer::new(global_capacity), + per_source: BTreeMap::new(), + filters: LogFilters::default(), + } + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs new file mode 100644 index 0000000..1925e49 --- /dev/null +++ b/src/domain/mod.rs @@ -0,0 +1,37 @@ +pub mod ai; +pub mod app; +pub mod approval; +pub mod command; +pub mod diagnostics; +pub mod git; +pub mod job; +pub mod log; +pub mod process; +pub mod project; +pub mod service; +pub mod test; +pub mod timeline; + +pub use ai::{ + AiActionProposal, AiCitation, AiCommandContext, AiContextBundle, AiGitContext, AiLogContext, + AiMessage, AiMessageRole, AiProjectContext, AiRequest, AiRequestKind, AiResponse, + AiServiceContext, AiSessionState, AiStatus, AiTestContext, AiTimelineContext, AiUiContext, +}; +pub use app::{ + AppMetaState, AppState, DashboardTab, FocusTarget, ModalState, Notification, NotificationLevel, + NotificationState, UiState, +}; +pub use approval::{ApprovalDecision, ApprovalMode, ApprovalRequest, ApprovalState, SafetyClass}; +pub use command::{ + CommandProvenance, CommandRecord, CommandState, CommandStatus, ExecutionMode, ExecutionRequest, + OutputStream, +}; +pub use diagnostics::{DiagnosticLevel, DiagnosticRecord, DiagnosticsState}; +pub use git::GitSnapshot; +pub use job::{JobRecord, JobState, JobStatus}; +pub use log::{LogEntry, LogFilters, LogSeverity, LogSource, LogState, LogStream}; +pub use process::{ProcessSnapshot, ProcessState, ProcessStatus}; +pub use project::ProjectContext; +pub use service::{ServiceHealth, ServiceRecord, ServiceSource, ServiceState}; +pub use test::{TestRunRecord, TestState, TestStatus}; +pub use timeline::{TimelineEntry, TimelineKind, TimelineState}; diff --git a/src/domain/process.rs b/src/domain/process.rs new file mode 100644 index 0000000..265f391 --- /dev/null +++ b/src/domain/process.rs @@ -0,0 +1,30 @@ +use std::time::SystemTime; + +use crate::shared::ids::{CommandId, JobId, ProcessId}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProcessStatus { + Starting, + Running, + Exited, + Failed, + Cancelled, +} + +#[derive(Debug, Clone)] +pub struct ProcessSnapshot { + pub id: ProcessId, + pub command_id: Option, + pub job_id: Option, + pub pid: Option, + pub label: String, + pub status: ProcessStatus, + pub cpu_percent: Option, + pub memory_bytes: Option, + pub observed_at: SystemTime, +} + +#[derive(Debug, Clone, Default)] +pub struct ProcessState { + pub snapshots: Vec, +} diff --git a/src/domain/project.rs b/src/domain/project.rs new file mode 100644 index 0000000..0ef3942 --- /dev/null +++ b/src/domain/project.rs @@ -0,0 +1,28 @@ +use std::path::PathBuf; + +#[derive(Debug, Clone)] +pub struct ProjectContext { + pub root: PathBuf, + pub name: String, + pub config_paths: Vec, + pub stack_hints: Vec, + pub discovered_files: Vec, +} + +impl Default for ProjectContext { + fn default() -> Self { + let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + let name = root + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| "forge".to_string()); + + Self { + root, + name, + config_paths: Vec::new(), + stack_hints: Vec::new(), + discovered_files: Vec::new(), + } + } +} diff --git a/src/domain/service.rs b/src/domain/service.rs new file mode 100644 index 0000000..689681d --- /dev/null +++ b/src/domain/service.rs @@ -0,0 +1,38 @@ +use std::time::SystemTime; + +use crate::shared::ids::{CommandId, ServiceId}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ServiceSource { + Config, + ManagedCommand, + ProcessObservation, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ServiceHealth { + Unknown, + Starting, + Healthy, + Degraded, + Unhealthy, + Stopped, +} + +#[derive(Debug, Clone)] +pub struct ServiceRecord { + pub id: ServiceId, + pub name: String, + pub source: ServiceSource, + pub pid: Option, + pub ports: Vec, + pub health: ServiceHealth, + pub tags: Vec, + pub linked_command: Option, + pub last_seen: SystemTime, +} + +#[derive(Debug, Clone, Default)] +pub struct ServiceState { + pub registry: Vec, +} diff --git a/src/domain/test.rs b/src/domain/test.rs new file mode 100644 index 0000000..e693235 --- /dev/null +++ b/src/domain/test.rs @@ -0,0 +1,28 @@ +use std::time::SystemTime; + +use crate::shared::ids::CommandId; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TestStatus { + Passed, + Failed, + Running, + Unknown, +} + +#[derive(Debug, Clone)] +pub struct TestRunRecord { + pub runner: String, + pub status: TestStatus, + pub pass_count: usize, + pub fail_count: usize, + pub failed_tests: Vec, + pub duration_ms: Option, + pub source_command: Option, + pub recorded_at: SystemTime, +} + +#[derive(Debug, Clone, Default)] +pub struct TestState { + pub recent_runs: Vec, +} diff --git a/src/domain/timeline.rs b/src/domain/timeline.rs new file mode 100644 index 0000000..df957fb --- /dev/null +++ b/src/domain/timeline.rs @@ -0,0 +1,35 @@ +use std::time::SystemTime; + +use crate::shared::ids::TimelineId; +use crate::shared::ring_buffer::RingBuffer; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TimelineKind { + System, + Ai, + Command, + Log, + Approval, + Error, +} + +#[derive(Debug, Clone)] +pub struct TimelineEntry { + pub id: TimelineId, + pub at: SystemTime, + pub kind: TimelineKind, + pub message: String, +} + +#[derive(Debug, Clone)] +pub struct TimelineState { + pub entries: RingBuffer, +} + +impl TimelineState { + pub fn new(capacity: usize) -> Self { + Self { + entries: RingBuffer::new(capacity), + } + } +} diff --git a/src/infra/git/mod.rs b/src/infra/git/mod.rs new file mode 100644 index 0000000..5accbd8 --- /dev/null +++ b/src/infra/git/mod.rs @@ -0,0 +1,52 @@ +use std::path::{Path, PathBuf}; +use std::process::Command; + +use crate::domain::GitSnapshot; +use crate::shared::error::{AppResult, InfraError}; +use crate::shared::time::now_utc; + +pub fn snapshot_git(root: &Path) -> AppResult { + let branch = run_git(root, &["rev-parse", "--abbrev-ref", "HEAD"])?; + let head = run_git(root, &["rev-parse", "--short", "HEAD"])?; + let status = run_git(root, &["status", "--porcelain"])?; + let changed_files = status + .lines() + .filter_map(|line| { + line.get(3..) + .map(str::trim) + .filter(|value| !value.is_empty()) + }) + .map(ToString::to_string) + .collect::>(); + + Ok(GitSnapshot { + root: Some(root.to_path_buf()), + branch: Some(branch.trim().to_string()), + head: Some(head.trim().to_string()), + is_dirty: !changed_files.is_empty(), + changed_files, + last_refreshed: now_utc(), + }) +} + +fn run_git(root: &Path, args: &[&str]) -> AppResult { + let output = Command::new("git") + .arg("-C") + .arg(root) + .args(args) + .output() + .map_err(|error| InfraError::Git { + path: PathBuf::from(root), + message: error.to_string(), + })?; + + if !output.status.success() { + return Err(InfraError::Git { + path: PathBuf::from(root), + message: String::from_utf8_lossy(&output.stderr).trim().to_string(), + } + .into()); + } + + Ok(String::from_utf8_lossy(&output.stdout).to_string()) +} diff --git a/src/infra/logs/mod.rs b/src/infra/logs/mod.rs new file mode 100644 index 0000000..a867e91 --- /dev/null +++ b/src/infra/logs/mod.rs @@ -0,0 +1,66 @@ +use std::collections::BTreeMap; +use std::time::SystemTime; + +use crate::domain::{LogEntry, LogSeverity, LogSource, LogStream, OutputStream}; +use crate::shared::ids::{CommandId, LogId, ServiceId}; + +pub fn normalize_command_output( + id: LogId, + ts: SystemTime, + command_id: CommandId, + service_id: Option, + stream: OutputStream, + chunk: String, +) -> LogEntry { + let severity = infer_severity(&chunk, stream); + let stream_type = match stream { + OutputStream::Stdout => LogStream::Stdout, + OutputStream::Stderr => LogStream::Stderr, + }; + + let mut fields = BTreeMap::new(); + fields.insert("command_id".to_string(), command_id.to_string()); + if let Some(service_id) = service_id { + fields.insert("service_id".to_string(), service_id.to_string()); + } + + LogEntry { + id, + ts, + source: service_id + .map(LogSource::Service) + .unwrap_or(LogSource::Command(command_id)), + stream: stream_type, + service_id, + command_id: Some(command_id), + severity, + raw: chunk, + fields, + } +} + +pub fn infer_severity(chunk: &str, stream: OutputStream) -> LogSeverity { + let lower = chunk.to_ascii_lowercase(); + if matches!(stream, OutputStream::Stderr) || lower.contains("error") || lower.contains("failed") + { + LogSeverity::Error + } else if lower.contains("warn") { + LogSeverity::Warn + } else if lower.contains("debug") { + LogSeverity::Debug + } else if lower.contains("trace") { + LogSeverity::Trace + } else { + LogSeverity::Info + } +} + +pub fn source_key(source: &LogSource) -> String { + match source { + LogSource::Command(command_id) => format!("command:{command_id}"), + LogSource::Service(service_id) => format!("service:{service_id}"), + LogSource::System => "system".to_string(), + LogSource::Git => "git".to_string(), + LogSource::Ai => "ai".to_string(), + } +} diff --git a/src/infra/mod.rs b/src/infra/mod.rs new file mode 100644 index 0000000..727a82a --- /dev/null +++ b/src/infra/mod.rs @@ -0,0 +1,5 @@ +pub mod git; +pub mod logs; +pub mod monitor; +pub mod project; +pub mod shell; diff --git a/src/infra/monitor/mod.rs b/src/infra/monitor/mod.rs new file mode 100644 index 0000000..aec41d0 --- /dev/null +++ b/src/infra/monitor/mod.rs @@ -0,0 +1,6 @@ +pub fn service_name_from_command(raw: &str) -> String { + raw.split_whitespace() + .next() + .unwrap_or("service") + .to_string() +} diff --git a/src/infra/project/mod.rs b/src/infra/project/mod.rs new file mode 100644 index 0000000..b928276 --- /dev/null +++ b/src/infra/project/mod.rs @@ -0,0 +1,88 @@ +use std::fs; +use std::path::{Path, PathBuf}; + +use crate::domain::ProjectContext; +use crate::shared::error::{AppResult, InfraError}; + +pub fn scan_project( + start_dir: &Path, + global_config_path: Option, + project_config_path: Option, +) -> AppResult { + let root = find_project_root(start_dir).ok_or_else(|| InfraError::Project { + path: start_dir.to_path_buf(), + message: "could not determine project root".to_string(), + })?; + let name = root + .file_name() + .map(|segment| segment.to_string_lossy().into_owned()) + .unwrap_or_else(|| "forge".to_string()); + let mut discovered_files = Vec::new(); + let mut stack_hints = Vec::new(); + let mut config_paths = Vec::new(); + + for candidate in [ + root.join("Cargo.toml"), + root.join("docker-compose.yml"), + root.join("docker-compose.yaml"), + root.join(".forge").join("config.toml"), + root.join("package.json"), + ] { + if candidate.exists() { + if candidate + .file_name() + .is_some_and(|name| name == "Cargo.toml") + { + stack_hints.push("rust".to_string()); + } + if candidate + .file_name() + .is_some_and(|name| name.to_string_lossy().contains("docker-compose")) + { + stack_hints.push("docker-compose".to_string()); + } + discovered_files.push(candidate); + } + } + + if let Some(path) = global_config_path { + config_paths.push(path); + } + if let Some(path) = project_config_path { + config_paths.push(path); + } + if config_paths.is_empty() { + let candidate = root.join(".forge").join("config.toml"); + if candidate.exists() { + config_paths.push(candidate); + } + } + + let top_entries = fs::read_dir(&root) + .map_err(|source| InfraError::Project { + path: root.clone(), + message: source.to_string(), + })? + .flatten() + .map(|entry| entry.path()) + .take(10) + .collect::>(); + discovered_files.extend(top_entries); + + Ok(ProjectContext { + root, + name, + config_paths, + stack_hints, + discovered_files, + }) +} + +fn find_project_root(start_dir: &Path) -> Option { + for candidate in start_dir.ancestors() { + if candidate.join(".git").exists() { + return Some(candidate.to_path_buf()); + } + } + Some(start_dir.to_path_buf()) +} diff --git a/src/infra/shell/mod.rs b/src/infra/shell/mod.rs new file mode 100644 index 0000000..44bdccc --- /dev/null +++ b/src/infra/shell/mod.rs @@ -0,0 +1,186 @@ +use std::collections::HashMap; +use std::process::Stdio; +use std::sync::Arc; + +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::process::Command; +use tokio::sync::{mpsc, oneshot, Mutex}; + +use crate::app::AppEvent; +use crate::domain::{ExecutionMode, ExecutionRequest, OutputStream}; +use crate::shared::error::{AppResult, InfraError}; +use crate::shared::ids::CommandId; + +pub type CancellationRegistry = Arc>>>; + +pub fn spawn_managed_command( + request: ExecutionRequest, + events_tx: mpsc::Sender, + cancellations: CancellationRegistry, +) -> AppResult<()> { + if !matches!(request.mode, ExecutionMode::Managed) { + return Err(InfraError::Runtime("PTY execution is not implemented yet".to_string()).into()); + } + + let mut command = build_shell_command(&request); + command.stdout(Stdio::piped()).stderr(Stdio::piped()); + + let mut child = command.spawn().map_err(|source| InfraError::Spawn { + command: request.raw.clone(), + source, + })?; + + let pid = child.id(); + let command_id = request.command_id; + let job_id = request.job_id; + let service_id = request.service_id; + let raw = request.raw.clone(); + let stdout = child.stdout.take(); + let stderr = child.stderr.take(); + let (cancel_tx, mut cancel_rx) = oneshot::channel(); + let events_tx_for_task = events_tx.clone(); + let cancellations_for_task = cancellations.clone(); + + tokio::spawn(async move { + { + let mut registry = cancellations_for_task.lock().await; + registry.insert(command_id, cancel_tx); + } + + let _ = events_tx_for_task + .send(AppEvent::CommandStarted { + command_id, + job_id, + service_id, + pid, + }) + .await; + + if let Some(stdout) = stdout { + spawn_stream_reader( + stdout, + events_tx_for_task.clone(), + command_id, + job_id, + service_id, + OutputStream::Stdout, + ); + } + if let Some(stderr) = stderr { + spawn_stream_reader( + stderr, + events_tx_for_task.clone(), + command_id, + job_id, + service_id, + OutputStream::Stderr, + ); + } + + tokio::select! { + _ = &mut cancel_rx => { + if let Err(error) = child.kill().await { + let _ = events_tx_for_task.send(AppEvent::Error(format!( + "failed to cancel command `{raw}`: {error}" + ))).await; + } else { + let _ = events_tx_for_task.send(AppEvent::CommandCancelled { + command_id, + job_id, + service_id, + }).await; + } + } + status = child.wait() => { + match status { + Ok(exit_status) => { + let _ = events_tx_for_task.send(AppEvent::CommandExited { + command_id, + job_id, + service_id, + exit_code: exit_status.code().unwrap_or(-1), + }).await; + } + Err(error) => { + let _ = events_tx_for_task.send(AppEvent::Error(format!( + "failed waiting for command `{raw}`: {error}" + ))).await; + } + } + } + } + + let mut registry = cancellations_for_task.lock().await; + registry.remove(&command_id); + }); + + Ok(()) +} + +fn build_shell_command(request: &ExecutionRequest) -> Command { + let mut command = if cfg!(windows) { + let shell = if request.shell.trim().is_empty() { + "cmd".to_string() + } else { + request.shell.clone() + }; + let mut command = Command::new(shell); + command.arg("/C").arg(&request.raw); + command + } else { + let shell = if request.shell.trim().is_empty() { + "/bin/sh".to_string() + } else { + request.shell.clone() + }; + let mut command = Command::new(shell); + command.arg("-lc").arg(&request.raw); + command + }; + + command.current_dir(&request.cwd); + for (key, value) in &request.env { + command.env(key, value); + } + command.kill_on_drop(true); + command +} + +fn spawn_stream_reader( + reader: R, + events_tx: mpsc::Sender, + command_id: CommandId, + job_id: crate::shared::ids::JobId, + service_id: Option, + stream: OutputStream, +) where + R: tokio::io::AsyncRead + Unpin + Send + 'static, +{ + tokio::spawn(async move { + let mut lines = BufReader::new(reader).lines(); + loop { + match lines.next_line().await { + Ok(Some(line)) => { + let _ = events_tx + .send(AppEvent::CommandOutput { + command_id, + job_id, + service_id, + stream, + chunk: line, + }) + .await; + } + Ok(None) => break, + Err(error) => { + let _ = events_tx + .send(AppEvent::Error(format!( + "failed reading command output: {error}" + ))) + .await; + break; + } + } + } + }); +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..15d1760 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,11 @@ +pub mod ai; +pub mod app; +pub mod commands; +pub mod config; +pub mod domain; +pub mod infra; +pub mod observability; +pub mod runtime; +pub mod safety; +pub mod shared; +pub mod ui; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..4ecd33f --- /dev/null +++ b/src/main.rs @@ -0,0 +1,10 @@ +use clap::Parser; +use forge::config::CliArgs; +use forge::shared::error::AppResult; + +#[tokio::main] +async fn main() -> AppResult<()> { + let cli = CliArgs::parse(); + let runtime = forge::app::bootstrap::bootstrap(cli).await?; + runtime.run().await +} diff --git a/src/observability/mod.rs b/src/observability/mod.rs new file mode 100644 index 0000000..369f83b --- /dev/null +++ b/src/observability/mod.rs @@ -0,0 +1,62 @@ +use std::fs::{self, OpenOptions}; +use std::path::{Path, PathBuf}; + +use tracing_subscriber::EnvFilter; + +use crate::config::ObservabilityConfig; +use crate::shared::error::AppResult; + +pub struct ObservabilityHandle { + pub log_file: Option, + _guard: Option, +} + +pub fn init_observability( + config: &ObservabilityConfig, + cwd: &Path, +) -> AppResult { + if config.log_to_file { + let logs_dir = cwd.join(".forge").join("logs"); + fs::create_dir_all(&logs_dir)?; + let log_file = logs_dir.join("forge.log"); + let file = OpenOptions::new() + .create(true) + .append(true) + .open(&log_file)?; + let (writer, guard) = tracing_appender::non_blocking(file); + let subscriber = tracing_subscriber::fmt() + .with_env_filter( + EnvFilter::try_new(config.log_level.clone()) + .unwrap_or_else(|_| EnvFilter::new("info")), + ) + .with_ansi(false) + .with_writer(writer) + .finish(); + let _ = tracing::subscriber::set_global_default(subscriber); + return Ok(ObservabilityHandle { + log_file: Some(log_file), + _guard: Some(guard), + }); + } + + let subscriber = tracing_subscriber::fmt() + .with_env_filter( + EnvFilter::try_new(config.log_level.clone()).unwrap_or_else(|_| EnvFilter::new("info")), + ) + .with_ansi(false) + .finish(); + let _ = tracing::subscriber::set_global_default(subscriber); + + Ok(ObservabilityHandle { + log_file: None, + _guard: None, + }) +} + +pub fn install_panic_hook() { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let _ = crate::ui::terminal::restore_terminal(); + previous(info); + })); +} diff --git a/src/runtime/engine.rs b/src/runtime/engine.rs new file mode 100644 index 0000000..0f9ba5c --- /dev/null +++ b/src/runtime/engine.rs @@ -0,0 +1,200 @@ +use std::time::Duration; + +use crossterm::event::{Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; +use futures::StreamExt; +use tokio::sync::mpsc; +use tracing::{error, info}; + +use crate::ai::AiRuntime; +use crate::app::{AppAction, AppEvent, AppStore, Effect, UiIntent}; +use crate::commands::ParsedInput; +use crate::domain::FocusTarget; +use crate::observability::ObservabilityHandle; +use crate::runtime::RuntimeSupervisor; +use crate::shared::error::AppResult; +use crate::ui::{render, terminal::TerminalUi}; + +pub struct Runtime { + store: AppStore, + terminal: TerminalUi, + supervisor: RuntimeSupervisor, + events_rx: mpsc::Receiver, + _observability: ObservabilityHandle, +} + +impl Runtime { + pub fn new( + store: AppStore, + terminal: TerminalUi, + observability: ObservabilityHandle, + ai_runtime: AiRuntime, + ) -> Self { + let (events_tx, events_rx) = mpsc::channel(512); + let supervisor = RuntimeSupervisor::new(events_tx, ai_runtime); + Self { + store, + terminal, + supervisor, + events_rx, + _observability: observability, + } + } + + pub async fn run(mut self) -> AppResult<()> { + info!("forge runtime starting"); + self.supervisor + .refresh_git(self.store.state().project.root.clone()); + self.render()?; + + let mut tick = tokio::time::interval(Duration::from_millis( + self.store.state().config.ui.tick_rate_ms, + )); + let mut input_events = EventStream::new(); + + loop { + if self.store.state().app.should_quit { + break; + } + + tokio::select! { + maybe_event = input_events.next() => { + if let Some(result) = maybe_event { + match result { + Ok(event) => { + let effects = self.handle_terminal_event(event); + self.apply_effects(effects).await?; + self.render()?; + } + Err(error) => { + error!(%error, "terminal input error"); + let effects = self.store.dispatch_event(AppEvent::Error(error.to_string())); + self.apply_effects(effects).await?; + self.render()?; + } + } + } + } + Some(event) = self.events_rx.recv() => { + let effects = self.store.dispatch_event(event); + self.apply_effects(effects).await?; + self.render()?; + } + _ = tick.tick() => { + let effects = self.store.dispatch_action(AppAction::Ui(UiIntent::Tick)); + self.apply_effects(effects).await?; + self.render()?; + } + signal = tokio::signal::ctrl_c() => { + if signal.is_ok() { + let effects = self.store.dispatch_action(AppAction::Ui(UiIntent::Quit)); + self.apply_effects(effects).await?; + } + } + } + } + + info!("forge runtime shutting down"); + self.terminal.restore()?; + Ok(()) + } + + async fn apply_effects(&mut self, effects: Vec) -> AppResult<()> { + for effect in effects { + match effect { + Effect::RunAiRequest(request) => { + self.supervisor.run_ai_request(*request).await?; + } + Effect::ExecuteCommand(request) => { + self.supervisor.execute_command(request).await?; + } + Effect::CancelCommand(command_id) => { + self.supervisor.cancel_command(command_id).await?; + } + Effect::RefreshProjectContext(path) => { + self.supervisor.refresh_project(path); + } + Effect::RefreshGit(path) => { + self.supervisor.refresh_git(path); + } + Effect::Shutdown => { + self.store.state_mut().app.should_quit = true; + } + Effect::QueueApproval(_request) => {} + } + } + Ok(()) + } + + fn render(&mut self) -> AppResult<()> { + self.terminal + .draw(|frame| render(frame, self.store.state()))?; + Ok(()) + } + + fn handle_terminal_event(&mut self, event: Event) -> Vec { + let action = match event { + Event::Key(key) => map_key_event(key, self.store.state()), + Event::Resize(width, height) => Some(AppAction::Ui(UiIntent::Resize(width, height))), + _ => None, + }; + + action + .map(|action| self.store.dispatch_action(action)) + .unwrap_or_default() + } +} + +fn map_key_event(key: KeyEvent, state: &crate::domain::AppState) -> Option { + if !matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) { + return None; + } + + if matches!(key.code, KeyCode::F(1)) { + return Some(AppAction::ParsedInput(ParsedInput::Help)); + } + + match key.code { + KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => { + Some(AppAction::Ui(UiIntent::Quit)) + } + KeyCode::Char('l') if key.modifiers.contains(KeyModifiers::CONTROL) => { + Some(AppAction::Ui(UiIntent::ClearInput)) + } + KeyCode::Tab => Some(AppAction::Ui(UiIntent::NextFocus)), + KeyCode::BackTab => Some(AppAction::Ui(UiIntent::PrevFocus)), + KeyCode::Left + if key.modifiers.is_empty() + && matches!(state.ui.focus, FocusTarget::DashboardPane) + && state.ui.modal.is_none() => + { + Some(AppAction::Ui(UiIntent::PrevTab)) + } + KeyCode::Right + if key.modifiers.is_empty() + && matches!(state.ui.focus, FocusTarget::DashboardPane) + && state.ui.modal.is_none() => + { + Some(AppAction::Ui(UiIntent::NextTab)) + } + KeyCode::Left if key.modifiers.contains(KeyModifiers::ALT) => { + Some(AppAction::Ui(UiIntent::PrevTab)) + } + KeyCode::Right if key.modifiers.contains(KeyModifiers::ALT) => { + Some(AppAction::Ui(UiIntent::NextTab)) + } + KeyCode::Enter => Some(AppAction::Ui(UiIntent::Submit)), + KeyCode::Backspace => Some(AppAction::Ui(UiIntent::Backspace)), + KeyCode::Esc => Some(AppAction::Ui(UiIntent::Esc)), + KeyCode::Char('?') + if key.modifiers == KeyModifiers::SHIFT + && !matches!(state.ui.focus, FocusTarget::CommandPane) + && state.ui.modal.is_none() => + { + Some(AppAction::ParsedInput(ParsedInput::Help)) + } + KeyCode::Char(c) if key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT => { + Some(AppAction::Ui(UiIntent::KeyChar(c))) + } + _ => None, + } +} diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs new file mode 100644 index 0000000..188d6f3 --- /dev/null +++ b/src/runtime/mod.rs @@ -0,0 +1,5 @@ +mod engine; +mod supervisor; + +pub use engine::Runtime; +pub use supervisor::RuntimeSupervisor; diff --git a/src/runtime/supervisor.rs b/src/runtime/supervisor.rs new file mode 100644 index 0000000..941f026 --- /dev/null +++ b/src/runtime/supervisor.rs @@ -0,0 +1,115 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Arc; + +use tokio::sync::{mpsc, oneshot, Mutex}; + +use crate::ai::AiRuntime; +use crate::app::AppEvent; +use crate::domain::{AiRequest, ExecutionRequest}; +use crate::infra::{git, project, shell}; +use crate::shared::error::AppResult; +use crate::shared::ids::CommandId; + +#[derive(Clone)] +pub struct RuntimeSupervisor { + events_tx: mpsc::Sender, + ai_runtime: AiRuntime, + cancellations: Arc>>>, +} + +impl RuntimeSupervisor { + pub fn new(events_tx: mpsc::Sender, ai_runtime: AiRuntime) -> Self { + Self { + events_tx, + ai_runtime, + cancellations: Arc::new(Mutex::new(HashMap::new())), + } + } + + pub fn events_tx(&self) -> mpsc::Sender { + self.events_tx.clone() + } + + pub async fn execute_command(&self, request: ExecutionRequest) -> AppResult<()> { + shell::spawn_managed_command(request, self.events_tx.clone(), self.cancellations.clone()) + } + + pub async fn run_ai_request(&self, request: AiRequest) -> AppResult<()> { + let events_tx = self.events_tx.clone(); + let ai_runtime = self.ai_runtime.clone(); + tokio::spawn(async move { + let request_id = request.id; + let provider = ai_runtime.provider_name().to_string(); + + let _ = events_tx + .send(AppEvent::AiStarted { + request_id, + provider: provider.clone(), + }) + .await; + + match ai_runtime.execute(request).await { + Ok(response) => { + let _ = events_tx.send(AppEvent::AiCompleted(response)).await; + } + Err(error) => { + let _ = events_tx + .send(AppEvent::AiFailed { + request_id, + provider, + message: error.to_string(), + }) + .await; + } + } + }); + Ok(()) + } + + pub async fn cancel_command(&self, command_id: CommandId) -> AppResult<()> { + let mut registry = self.cancellations.lock().await; + if let Some(cancel_tx) = registry.remove(&command_id) { + let _ = cancel_tx.send(()); + } + Ok(()) + } + + pub fn refresh_project(&self, start_dir: PathBuf) { + let events_tx = self.events_tx.clone(); + tokio::spawn(async move { + let result = + tokio::task::spawn_blocking(move || project::scan_project(&start_dir, None, None)) + .await; + match result { + Ok(Ok(project)) => { + let _ = events_tx.send(AppEvent::ProjectScanned(project)).await; + } + Ok(Err(error)) => { + let _ = events_tx.send(AppEvent::Error(error.to_string())).await; + } + Err(error) => { + let _ = events_tx.send(AppEvent::Error(error.to_string())).await; + } + } + }); + } + + pub fn refresh_git(&self, root: PathBuf) { + let events_tx = self.events_tx.clone(); + tokio::spawn(async move { + let result = tokio::task::spawn_blocking(move || git::snapshot_git(&root)).await; + match result { + Ok(Ok(snapshot)) => { + let _ = events_tx.send(AppEvent::GitRefreshed(snapshot)).await; + } + Ok(Err(error)) => { + let _ = events_tx.send(AppEvent::Error(error.to_string())).await; + } + Err(error) => { + let _ = events_tx.send(AppEvent::Error(error.to_string())).await; + } + } + }); + } +} diff --git a/src/safety/mod.rs b/src/safety/mod.rs new file mode 100644 index 0000000..67958ed --- /dev/null +++ b/src/safety/mod.rs @@ -0,0 +1,111 @@ +use crate::config::SafetyConfig; +use crate::domain::{ApprovalMode, ApprovalRequest, SafetyClass}; + +pub fn classify_command(command: &str) -> SafetyClass { + let normalized = command.trim().to_ascii_lowercase(); + + if normalized.is_empty() { + return SafetyClass::Passive; + } + + let destructive_patterns = [ + "rm -rf", + "git reset --hard", + "git clean -fd", + "mkfs", + "shutdown", + "reboot", + "docker system prune", + ]; + if destructive_patterns + .iter() + .any(|pattern| normalized.contains(pattern)) + { + return SafetyClass::Destructive; + } + + let risky_patterns = [ + "git reset", + "git clean", + "sed -i", + "cargo add", + "cargo remove", + "npm install", + "pnpm add", + "pip install", + "mv ", + "cp ", + " >", + " >>", + "tee ", + ]; + if risky_patterns + .iter() + .any(|pattern| normalized.contains(pattern)) + { + return SafetyClass::Risky; + } + + let caution_patterns = [ + "kill ", + "pkill", + "docker restart", + "docker compose restart", + "brew services restart", + "cargo test", + "cargo fmt", + "cargo clippy", + ]; + if caution_patterns + .iter() + .any(|pattern| normalized.contains(pattern)) + { + return SafetyClass::Caution; + } + + let passive_prefixes = [ + "ls", + "pwd", + "echo", + "cat", + "git status", + "git diff", + "ps", + "top", + "tail", + "head", + ]; + if passive_prefixes + .iter() + .any(|prefix| normalized.starts_with(prefix)) + { + return SafetyClass::Passive; + } + + SafetyClass::Safe +} + +pub fn approval_mode_for(class: SafetyClass, config: &SafetyConfig) -> Option { + match class { + SafetyClass::Passive | SafetyClass::Safe => None, + SafetyClass::Caution if config.caution_requires_review => Some(ApprovalMode::InlineReview), + SafetyClass::Caution => None, + SafetyClass::Risky => Some(ApprovalMode::ModalConfirm), + SafetyClass::Destructive if config.destructive_requires_confirmation => { + Some(ApprovalMode::ModalConfirm) + } + SafetyClass::Destructive => None, + } +} + +pub fn approval_message(request: &ApprovalRequest) -> String { + match request.class { + SafetyClass::Caution => format!("Review before running: {}", request.summary), + SafetyClass::Risky => format!("Approval required: {}", request.summary), + SafetyClass::Destructive => format!( + "Destructive action requires confirmation: {}", + request.summary + ), + SafetyClass::Passive | SafetyClass::Safe => request.summary.clone(), + } +} diff --git a/src/shared/error.rs b/src/shared/error.rs new file mode 100644 index 0000000..35834b6 --- /dev/null +++ b/src/shared/error.rs @@ -0,0 +1,81 @@ +use std::path::PathBuf; + +use thiserror::Error; + +pub type AppResult = Result; + +#[derive(Debug, Error)] +pub enum AppError { + #[error(transparent)] + Ai(#[from] AiError), + #[error(transparent)] + Config(#[from] ConfigError), + #[error(transparent)] + Infra(#[from] InfraError), + #[error(transparent)] + Io(#[from] std::io::Error), + #[error(transparent)] + TomlDe(#[from] toml::de::Error), + #[error(transparent)] + Join(#[from] tokio::task::JoinError), + #[error("{0}")] + Message(String), +} + +#[derive(Debug, Error)] +pub enum AiError { + #[error("AI is disabled in the current configuration")] + Disabled, + #[error("AI provider is not configured")] + ProviderNotConfigured, + #[error("unsupported AI provider `{0}`")] + UnsupportedProvider(String), + #[error("missing API key for provider `{provider}` in `${env_var}`")] + MissingApiKey { provider: String, env_var: String }, + #[error("AI provider `{provider}` is unavailable: {reason}")] + ProviderUnavailable { provider: String, reason: String }, +} + +#[derive(Debug, Error)] +pub enum ConfigError { + #[error("failed to read config at {path}: {source}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("failed to parse config at {path}: {source}")] + Parse { + path: PathBuf, + #[source] + source: toml::de::Error, + }, + #[error("invalid configuration: {0}")] + Invalid(String), +} + +#[derive(Debug, Error)] +pub enum InfraError { + #[error("failed to spawn command `{command}`: {source}")] + Spawn { + command: String, + #[source] + source: std::io::Error, + }, + #[error("git inspection failed for {path}: {message}")] + Git { path: PathBuf, message: String }, + #[error("project scan failed for {path}: {message}")] + Project { path: PathBuf, message: String }, + #[error("ai provider `{provider}` failed: {message}")] + Ai { provider: String, message: String }, + #[error("terminal failure: {0}")] + Terminal(String), + #[error("runtime failure: {0}")] + Runtime(String), +} + +impl AppError { + pub fn message(message: impl Into) -> Self { + Self::Message(message.into()) + } +} diff --git a/src/shared/ids.rs b/src/shared/ids.rs new file mode 100644 index 0000000..fd0e97c --- /dev/null +++ b/src/shared/ids.rs @@ -0,0 +1,89 @@ +use std::fmt::{Display, Formatter}; +use std::sync::atomic::{AtomicU64, Ordering}; + +macro_rules! define_id { + ($name:ident) => { + #[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + serde::Serialize, + serde::Deserialize, + )] + pub struct $name(pub u64); + + impl Display for $name { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } + } + }; +} + +define_id!(ApprovalId); +define_id!(AiRequestId); +define_id!(CommandId); +define_id!(JobId); +define_id!(LogId); +define_id!(NotificationId); +define_id!(ProcessId); +define_id!(ServiceId); +define_id!(TimelineId); + +#[derive(Debug, Default)] +pub struct IdGenerator { + next: AtomicU64, +} + +impl IdGenerator { + pub fn new() -> Self { + Self { + next: AtomicU64::new(1), + } + } + + pub fn next_raw(&self) -> u64 { + self.next.fetch_add(1, Ordering::Relaxed) + } + + pub fn next_command(&self) -> CommandId { + CommandId(self.next_raw()) + } + + pub fn next_job(&self) -> JobId { + JobId(self.next_raw()) + } + + pub fn next_service(&self) -> ServiceId { + ServiceId(self.next_raw()) + } + + pub fn next_log(&self) -> LogId { + LogId(self.next_raw()) + } + + pub fn next_timeline(&self) -> TimelineId { + TimelineId(self.next_raw()) + } + + pub fn next_approval(&self) -> ApprovalId { + ApprovalId(self.next_raw()) + } + + pub fn next_ai_request(&self) -> AiRequestId { + AiRequestId(self.next_raw()) + } + + pub fn next_process(&self) -> ProcessId { + ProcessId(self.next_raw()) + } + + pub fn next_notification(&self) -> NotificationId { + NotificationId(self.next_raw()) + } +} diff --git a/src/shared/mod.rs b/src/shared/mod.rs new file mode 100644 index 0000000..17ac995 --- /dev/null +++ b/src/shared/mod.rs @@ -0,0 +1,4 @@ +pub mod error; +pub mod ids; +pub mod ring_buffer; +pub mod time; diff --git a/src/shared/ring_buffer.rs b/src/shared/ring_buffer.rs new file mode 100644 index 0000000..ac2010a --- /dev/null +++ b/src/shared/ring_buffer.rs @@ -0,0 +1,59 @@ +use std::collections::VecDeque; + +#[derive(Debug, Clone)] +pub struct RingBuffer { + capacity: usize, + items: VecDeque, +} + +impl RingBuffer { + pub fn new(capacity: usize) -> Self { + Self { + capacity: capacity.max(1), + items: VecDeque::with_capacity(capacity.max(1)), + } + } + + pub fn push(&mut self, item: T) { + if self.items.len() == self.capacity { + self.items.pop_front(); + } + self.items.push_back(item); + } + + pub fn clear(&mut self) { + self.items.clear(); + } + + pub fn len(&self) -> usize { + self.items.len() + } + + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + pub fn iter(&self) -> impl DoubleEndedIterator { + self.items.iter() + } + + pub fn iter_mut(&mut self) -> impl DoubleEndedIterator { + self.items.iter_mut() + } + + pub fn to_vec(&self) -> Vec + where + T: Clone, + { + self.items.iter().cloned().collect() + } +} + +impl IntoIterator for RingBuffer { + type Item = T; + type IntoIter = std::collections::vec_deque::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.items.into_iter() + } +} diff --git a/src/shared/time.rs b/src/shared/time.rs new file mode 100644 index 0000000..d663cd1 --- /dev/null +++ b/src/shared/time.rs @@ -0,0 +1,18 @@ +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +pub fn now_utc() -> SystemTime { + SystemTime::now() +} + +pub fn format_timestamp(ts: SystemTime) -> String { + let elapsed = ts + .duration_since(UNIX_EPOCH) + .unwrap_or(Duration::from_secs(0)); + let secs = elapsed.as_secs(); + let day_secs = secs % 86_400; + let hours = day_secs / 3_600; + let minutes = (day_secs % 3_600) / 60; + let seconds = day_secs % 60; + let millis = elapsed.subsec_millis(); + format!("{hours:02}:{minutes:02}:{seconds:02}.{millis:03}") +} diff --git a/src/ui/mod.rs b/src/ui/mod.rs new file mode 100644 index 0000000..a3af0b1 --- /dev/null +++ b/src/ui/mod.rs @@ -0,0 +1,5 @@ +pub mod terminal; +pub mod theme; +mod views; + +pub use views::render; diff --git a/src/ui/terminal.rs b/src/ui/terminal.rs new file mode 100644 index 0000000..e160f2a --- /dev/null +++ b/src/ui/terminal.rs @@ -0,0 +1,53 @@ +use std::io::{self, Stdout}; + +use crossterm::execute; +use crossterm::terminal::{ + disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen, +}; +use ratatui::backend::CrosstermBackend; +use ratatui::Terminal; + +use crate::shared::error::AppResult; + +pub struct TerminalUi { + terminal: Terminal>, +} + +impl TerminalUi { + pub fn new() -> AppResult { + enable_raw_mode()?; + let mut stdout = io::stdout(); + execute!(stdout, EnterAlternateScreen)?; + let backend = CrosstermBackend::new(stdout); + let mut terminal = Terminal::new(backend)?; + terminal.hide_cursor()?; + Ok(Self { terminal }) + } + + pub fn draw(&mut self, mut render: F) -> AppResult<()> + where + F: FnMut(&mut ratatui::Frame<'_>), + { + self.terminal.draw(|frame| render(frame))?; + Ok(()) + } + + pub fn restore(&mut self) -> AppResult<()> { + restore_terminal()?; + self.terminal.show_cursor()?; + Ok(()) + } +} + +impl Drop for TerminalUi { + fn drop(&mut self) { + let _ = self.restore(); + } +} + +pub fn restore_terminal() -> AppResult<()> { + disable_raw_mode()?; + let mut stdout = io::stdout(); + execute!(stdout, LeaveAlternateScreen)?; + Ok(()) +} diff --git a/src/ui/theme.rs b/src/ui/theme.rs new file mode 100644 index 0000000..ee48db8 --- /dev/null +++ b/src/ui/theme.rs @@ -0,0 +1,94 @@ +use ratatui::style::{Color, Modifier, Style}; + +use crate::domain::{LogSeverity, NotificationLevel, ServiceHealth, TimelineKind}; + +pub const BG_BASE: Color = Color::Rgb(16, 18, 22); +pub const BG_ELEVATED: Color = Color::Rgb(22, 26, 33); +pub const PANEL_BORDER: Color = Color::Rgb(82, 92, 107); +pub const PANEL_FOCUS: Color = Color::Rgb(86, 156, 214); +pub const TEXT_PRIMARY: Color = Color::Rgb(232, 236, 241); +pub const TEXT_MUTED: Color = Color::Rgb(146, 156, 169); +pub const TEXT_SUBTLE: Color = Color::Rgb(103, 112, 124); +pub const ACCENT: Color = Color::Rgb(87, 156, 255); +pub const SUCCESS: Color = Color::Rgb(108, 196, 145); +pub const WARN: Color = Color::Rgb(242, 201, 76); +pub const ERROR: Color = Color::Rgb(235, 111, 146); +pub const INFO: Color = Color::Rgb(86, 182, 194); + +pub fn pane_border(focused: bool) -> Style { + Style::default().fg(if focused { PANEL_FOCUS } else { PANEL_BORDER }) +} + +pub fn panel_title(focused: bool) -> Style { + Style::default() + .fg(if focused { PANEL_FOCUS } else { TEXT_MUTED }) + .add_modifier(Modifier::BOLD) +} + +pub fn section_title() -> Style { + Style::default().fg(TEXT_MUTED).add_modifier(Modifier::BOLD) +} + +pub fn primary() -> Style { + Style::default().fg(TEXT_PRIMARY) +} + +pub fn muted() -> Style { + Style::default().fg(TEXT_MUTED) +} + +pub fn subtle() -> Style { + Style::default().fg(TEXT_SUBTLE) +} + +pub fn accent() -> Style { + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD) +} + +pub fn status_badge(bg: Color) -> Style { + Style::default() + .fg(Color::Black) + .bg(bg) + .add_modifier(Modifier::BOLD) +} + +pub fn notification_color(level: NotificationLevel) -> Color { + match level { + NotificationLevel::Info => INFO, + NotificationLevel::Warn => WARN, + NotificationLevel::Error => ERROR, + } +} + +pub fn health_color(health: ServiceHealth) -> Color { + match health { + ServiceHealth::Healthy => SUCCESS, + ServiceHealth::Starting => INFO, + ServiceHealth::Degraded => WARN, + ServiceHealth::Unhealthy => ERROR, + ServiceHealth::Stopped => TEXT_SUBTLE, + ServiceHealth::Unknown => TEXT_MUTED, + } +} + +pub fn severity_color(severity: LogSeverity) -> Color { + match severity { + LogSeverity::Trace => TEXT_SUBTLE, + LogSeverity::Debug => INFO, + LogSeverity::Info => TEXT_PRIMARY, + LogSeverity::Warn => WARN, + LogSeverity::Error => ERROR, + LogSeverity::Unknown => TEXT_MUTED, + } +} + +pub fn timeline_color(kind: TimelineKind) -> Color { + match kind { + TimelineKind::System => INFO, + TimelineKind::Ai => SUCCESS, + TimelineKind::Command => ACCENT, + TimelineKind::Log => TEXT_PRIMARY, + TimelineKind::Approval => WARN, + TimelineKind::Error => ERROR, + } +} diff --git a/src/ui/views/command_pane.rs b/src/ui/views/command_pane.rs new file mode 100644 index 0000000..d0cbd9a --- /dev/null +++ b/src/ui/views/command_pane.rs @@ -0,0 +1,392 @@ +use ratatui::layout::Rect; +use ratatui::layout::{Constraint, Direction, Layout}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use ratatui::Frame; + +use crate::domain::{AiMessageRole, AiStatus, AppState, ApprovalMode}; +use crate::shared::time::format_timestamp; +use crate::ui::theme; + +pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { + let block = Block::default() + .title(Span::styled(" Command / AI ", theme::panel_title(focused))) + .borders(Borders::ALL) + .border_style(theme::pane_border(focused)) + .style(theme::primary().bg(theme::BG_BASE)); + let inner = block.inner(area); + frame.render_widget(block, area); + + let sections = Layout::default() + .direction(Direction::Vertical) + .constraints([Constraint::Min(0), Constraint::Length(5)]) + .split(inner); + + let top = Layout::default() + .direction(Direction::Vertical) + .constraints([Constraint::Length(4), Constraint::Min(0)]) + .split(sections[0]); + + render_activity(frame, top[0], state); + let history_height = (state.config.ui.history_preview as u16).clamp(4, 8); + let body = Layout::default() + .direction(Direction::Vertical) + .constraints([Constraint::Min(8), Constraint::Length(history_height)]) + .split(top[1]); + render_ai_panel(frame, body[0], state); + render_history(frame, body[1], state); + render_input(frame, sections[1], state, focused); +} + +fn render_input(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { + let content_width = area.width.saturating_sub(6) as usize; + let visible_input = visible_input_text(&state.ui.input_buffer, content_width.max(8)); + + let lines = vec![ + Line::from(vec![ + Span::styled(" $ ", theme::status_badge(theme::ACCENT)), + Span::raw(" "), + Span::styled(visible_input, theme::primary()), + Span::styled( + if focused { "█" } else { " " }, + if focused { + theme::accent() + } else { + theme::subtle() + }, + ), + ]), + Line::from(vec![Span::styled( + if state.ui.input_buffer.is_empty() { + "Start typing a shell command or use /help for slash commands." + } else { + "Enter runs the command. Tab changes focus. Alt+Left/Right switches dashboard tabs." + }, + theme::muted(), + )]), + Line::from(vec![ + Span::styled("shell ", theme::subtle()), + Span::styled( + state.config.commands.default_shell.clone(), + theme::primary(), + ), + Span::raw(" "), + Span::styled("focus ", theme::subtle()), + Span::styled( + if focused { "command" } else { "other" }, + if focused { + theme::accent() + } else { + theme::muted() + }, + ), + ]), + ]; + frame.render_widget( + Paragraph::new(lines).block( + Block::default() + .title(Span::styled(" Input ", theme::section_title())) + .borders(Borders::ALL) + .border_style(theme::pane_border(focused)), + ), + area, + ); +} + +fn render_activity(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + let mut lines = Vec::new(); + + if let Some(approval) = state + .approvals + .pending + .iter() + .find(|request| matches!(request.mode, ApprovalMode::InlineReview)) + { + lines.push(Line::from(vec![ + Span::styled("REVIEW ", theme::status_badge(theme::WARN)), + Span::raw(" "), + Span::styled( + format!( + "#{} [{}] {}", + approval.command_id, + approval.class.label(), + approval.summary + ), + theme::primary(), + ), + ])); + lines.push(Line::from(vec![ + Span::styled("Enter", theme::accent()), + Span::styled(" approve", theme::muted()), + Span::raw(" "), + Span::styled("Esc", theme::accent()), + Span::styled(" deny", theme::muted()), + ])); + } else { + lines.push(Line::from(vec![ + Span::styled("READY ", theme::status_badge(theme::SUCCESS)), + Span::raw(" "), + Span::styled("No inline approvals waiting", theme::muted()), + ])); + lines.push(Line::from(vec![ + Span::styled("Enter", theme::accent()), + Span::styled(" run command", theme::muted()), + Span::raw(" "), + Span::styled("Ctrl+L", theme::accent()), + Span::styled(" clear input", theme::muted()), + ])); + } + + if let Some(notification) = state.notifications.items.last() { + let color = theme::notification_color(notification.level); + lines.push(Line::raw("")); + lines.push(Line::from(vec![ + Span::styled("LAST NOTICE ", theme::status_badge(color)), + Span::raw(" "), + Span::styled( + format!( + "[{}] {}", + format_timestamp(notification.created_at), + notification.message + ), + theme::primary(), + ), + ])); + } else { + lines.push(Line::raw("")); + lines.push(Line::from(vec![ + Span::styled("/help", theme::accent()), + Span::styled(" for slash commands and key hints", theme::muted()), + ])); + } + + frame.render_widget( + Paragraph::new(lines) + .block(Block::default().title(Span::styled(" Activity ", theme::section_title()))) + .wrap(Wrap { trim: false }), + area, + ); +} + +fn render_history(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + let mut lines = Vec::new(); + + if state.commands.records.is_empty() { + lines.push(Line::from(vec![ + Span::styled("No commands yet.", theme::muted()), + Span::raw(" "), + Span::styled("Try", theme::muted()), + Span::raw(" "), + Span::styled("pwd", theme::accent()), + Span::raw(" "), + Span::styled("or", theme::muted()), + Span::raw(" "), + Span::styled("sleep 5 &", theme::accent()), + Span::raw(" "), + Span::styled("to seed the dashboard.", theme::muted()), + ])); + } + + for record in state + .commands + .records + .iter() + .rev() + .take(state.config.ui.history_preview.max(6)) + { + let status_color = match record.status { + crate::domain::CommandStatus::PendingReview + | crate::domain::CommandStatus::PendingApproval => theme::WARN, + crate::domain::CommandStatus::Queued | crate::domain::CommandStatus::Running => { + theme::ACCENT + } + crate::domain::CommandStatus::Succeeded => theme::SUCCESS, + crate::domain::CommandStatus::Failed | crate::domain::CommandStatus::Denied => { + theme::ERROR + } + crate::domain::CommandStatus::Cancelled => theme::TEXT_SUBTLE, + }; + let summary = if let Some(code) = record.exit_code { + format!("exit {code}") + } else { + format!("{:?}", record.status).to_lowercase() + }; + lines.push(Line::from(vec![ + Span::styled(format!("#{} ", record.id), theme::accent()), + Span::styled(format!("[{summary}] "), theme::status_badge(status_color)), + Span::raw(" "), + Span::styled(record.raw.clone(), theme::primary()), + ])); + } + + let block = Block::default().title(Span::styled(" Recent Commands ", theme::section_title())); + frame.render_widget( + Paragraph::new(lines) + .block(block) + .wrap(Wrap { trim: false }), + area, + ); +} + +fn render_ai_panel(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + let mut lines = Vec::new(); + let (status_label, status_color) = match state.ai.status { + AiStatus::Disabled => ("OFF", theme::TEXT_SUBTLE), + AiStatus::Unconfigured => ("SETUP", theme::WARN), + AiStatus::Ready => ("READY", theme::SUCCESS), + AiStatus::Queued => ("QUEUED", theme::INFO), + AiStatus::Running => ("RUNNING", theme::INFO), + AiStatus::Completed => ("DONE", theme::SUCCESS), + AiStatus::Failed => ("ERROR", theme::ERROR), + }; + + lines.push(Line::from(vec![ + Span::styled( + format!(" {} ", status_label), + theme::status_badge(status_color), + ), + Span::raw(" "), + Span::styled( + state + .ai + .provider + .clone() + .unwrap_or_else(|| "provider:unconfigured".to_string()), + theme::primary(), + ), + if let Some(model) = state.ai.model.as_ref() { + Span::styled(format!(" model:{model}"), theme::muted()) + } else { + Span::styled(" model:default", theme::muted()) + }, + ])); + + if let Some(request) = state.ai.requests.last() { + lines.push(Line::from(vec![ + Span::styled( + format!("{} ", request.kind.label().to_ascii_uppercase()), + theme::accent(), + ), + Span::styled( + visible_input_text(&request.prompt, area.width.saturating_sub(12) as usize), + theme::primary(), + ), + ])); + } + + match state.ai.status { + AiStatus::Running | AiStatus::Queued => { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + "AI request is running against the configured provider.", + theme::muted(), + )])); + } + AiStatus::Failed => { + lines.push(Line::raw("")); + if let Some(error) = state.ai.last_error.as_ref() { + lines.push(Line::from(vec![Span::styled( + truncate_multiline(error, area.width.saturating_sub(4) as usize), + theme::primary(), + )])); + } + } + _ => { + if let Some(response) = state.ai.last_response.as_ref() { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + response.summary.clone(), + theme::primary(), + )])); + lines.push(Line::from(vec![Span::styled( + truncate_multiline(&response.message, area.width.saturating_sub(4) as usize), + theme::muted(), + )])); + if !response.recommendations.is_empty() { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + "Recommendations", + theme::section_title(), + )])); + for recommendation in response.recommendations.iter().take(3) { + lines.push(Line::from(vec![ + Span::styled("• ", theme::accent()), + Span::styled( + truncate_multiline( + recommendation, + area.width.saturating_sub(6) as usize, + ), + theme::primary(), + ), + ])); + } + } + if !response.citations.is_empty() { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + "Grounding", + theme::section_title(), + )])); + for citation in response.citations.iter().take(2) { + lines.push(Line::from(vec![ + Span::styled(format!("{} ", citation.label), theme::accent()), + Span::styled( + truncate_multiline( + &citation.detail, + area.width.saturating_sub(6) as usize, + ), + theme::muted(), + ), + ])); + } + } + } else if let Some(message) = state + .ai + .messages + .iter() + .rev() + .find(|message| matches!(message.role, AiMessageRole::Assistant)) + { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + truncate_multiline(&message.content, area.width.saturating_sub(4) as usize), + theme::primary(), + )])); + } else { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + "Use /ai for assistance or /diagnose for grounded diagnosis.", + theme::muted(), + )])); + } + } + } + + frame.render_widget( + Paragraph::new(lines) + .block(Block::default().title(Span::styled(" AI Response ", theme::section_title()))) + .wrap(Wrap { trim: false }), + area, + ); +} + +fn visible_input_text(input: &str, max_chars: usize) -> String { + if input.is_empty() { + return "Type a shell command".to_string(); + } + + let chars = input.chars().collect::>(); + if chars.len() <= max_chars { + return input.to_string(); + } + + let tail = chars[chars.len().saturating_sub(max_chars - 1)..] + .iter() + .collect::(); + format!("…{tail}") +} + +fn truncate_multiline(value: &str, max_chars: usize) -> String { + let single_line = value.lines().collect::>().join(" "); + visible_input_text(&single_line, max_chars.max(8)) +} diff --git a/src/ui/views/dashboard.rs b/src/ui/views/dashboard.rs new file mode 100644 index 0000000..ea7272f --- /dev/null +++ b/src/ui/views/dashboard.rs @@ -0,0 +1,329 @@ +use ratatui::layout::Rect; +use ratatui::layout::{Constraint, Direction, Layout}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use ratatui::Frame; + +use crate::domain::{AppState, DashboardTab, ProcessStatus}; +use crate::shared::time::format_timestamp; +use crate::ui::theme; + +pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { + let block = Block::default() + .title(Span::styled(" Dashboard ", theme::panel_title(focused))) + .borders(Borders::ALL) + .border_style(theme::pane_border(focused)) + .style(theme::primary().bg(theme::BG_BASE)); + let inner = block.inner(area); + frame.render_widget(block, area); + + let sections = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Length(2), + Constraint::Length(2), + Constraint::Min(8), + ]) + .split(inner); + + render_tabs(frame, sections[0], state); + render_context(frame, sections[1], state); + + let lines = match state.ui.dashboard_tab { + DashboardTab::Services => services_lines(state), + DashboardTab::Processes => processes_lines(state), + DashboardTab::Logs => log_lines(state), + DashboardTab::Git => git_lines(state), + DashboardTab::Tests => test_lines(state), + }; + + frame.render_widget( + Paragraph::new(lines) + .block(Block::default()) + .wrap(Wrap { trim: false }), + sections[2], + ); +} + +fn services_lines(state: &AppState) -> Vec> { + let mut lines = vec![Line::from(vec![ + Span::styled("Managed services", theme::section_title()), + Span::styled(" background jobs and long-lived processes", theme::muted()), + ])]; + if state.services.registry.is_empty() { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + "No managed services yet.", + theme::primary(), + )])); + lines.push(Line::from(vec![ + Span::styled("Try ", theme::muted()), + Span::styled("sleep 30 &", theme::accent()), + Span::styled(" or ", theme::muted()), + Span::styled("/bg cargo run", theme::accent()), + Span::styled(" to create one.", theme::muted()), + ])); + return lines; + } + + for service in state.services.registry.iter().rev().take(12) { + let health = format!("{:?}", service.health).to_lowercase(); + lines.push(Line::from(vec![ + Span::styled(format!("#{} ", service.id), theme::accent()), + Span::styled( + format!("[{health}] "), + theme::status_badge(theme::health_color(service.health)), + ), + Span::raw(" "), + Span::styled(service.name.clone(), theme::primary()), + Span::raw(" "), + Span::styled(format!("pid:{:?}", service.pid), theme::muted()), + ])); + } + lines +} + +fn processes_lines(state: &AppState) -> Vec> { + let mut lines = vec![Line::from(vec![ + Span::styled("Tracked processes", theme::section_title()), + Span::styled(" active and recently completed jobs", theme::muted()), + ])]; + if state.processes.snapshots.is_empty() { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + "No tracked processes.", + theme::primary(), + )])); + lines.push(Line::from(vec![Span::styled( + "Foreground and background commands populate this view.", + theme::muted(), + )])); + return lines; + } + + for process in state.processes.snapshots.iter().rev().take(12) { + let status = match process.status { + ProcessStatus::Starting => "starting", + ProcessStatus::Running => "running", + ProcessStatus::Exited => "exited", + ProcessStatus::Failed => "failed", + ProcessStatus::Cancelled => "cancelled", + }; + let color = match process.status { + ProcessStatus::Running => theme::SUCCESS, + ProcessStatus::Starting => theme::INFO, + ProcessStatus::Exited => theme::TEXT_SUBTLE, + ProcessStatus::Failed => theme::ERROR, + ProcessStatus::Cancelled => theme::WARN, + }; + lines.push(Line::from(vec![ + Span::styled(format!("[{status}] "), theme::status_badge(color)), + Span::raw(" "), + Span::styled(process.label.clone(), theme::primary()), + Span::raw(" "), + Span::styled(format!("pid:{:?}", process.pid), theme::muted()), + ])); + } + lines +} + +fn log_lines(state: &AppState) -> Vec> { + let mut lines = vec![Line::from(vec![ + Span::styled("Recent logs", theme::section_title()), + Span::styled(" newest entries first", theme::muted()), + ])]; + if state.logs.recent.is_empty() { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + "No logs captured yet.", + theme::primary(), + )])); + lines.push(Line::from(vec![Span::styled( + "Run a command to start filling the log buffer.", + theme::muted(), + )])); + return lines; + } + + for entry in state.logs.recent.iter().rev().take(14) { + let level = match entry.severity { + crate::domain::LogSeverity::Trace => "trace", + crate::domain::LogSeverity::Debug => "debug", + crate::domain::LogSeverity::Info => "info", + crate::domain::LogSeverity::Warn => "warn", + crate::domain::LogSeverity::Error => "error", + crate::domain::LogSeverity::Unknown => "unknown", + }; + lines.push(Line::from(vec![ + Span::styled(format!("{} ", format_timestamp(entry.ts)), theme::subtle()), + Span::styled( + format!("[{level}] "), + theme::status_badge(theme::severity_color(entry.severity)), + ), + Span::raw(" "), + Span::styled(entry.raw.clone(), theme::primary()), + ])); + } + lines +} + +fn git_lines(state: &AppState) -> Vec> { + let mut lines = vec![Line::from(vec![ + Span::styled("Repository context", theme::section_title()), + Span::styled(" current branch and changed files", theme::muted()), + ])]; + lines.push(Line::raw("")); + lines.push(Line::from(vec![ + Span::styled("Branch ", theme::muted()), + Span::styled( + state + .git + .branch + .clone() + .unwrap_or_else(|| "unknown".to_string()), + theme::primary(), + ), + ])); + lines.push(Line::from(vec![ + Span::styled("HEAD ", theme::muted()), + Span::styled( + state + .git + .head + .clone() + .unwrap_or_else(|| "unknown".to_string()), + theme::primary(), + ), + ])); + lines.push(Line::from(vec![ + Span::styled("Status ", theme::muted()), + Span::styled( + if state.git.is_dirty { "dirty" } else { "clean" }, + if state.git.is_dirty { + theme::accent() + } else { + theme::muted() + }, + ), + ])); + lines.push(Line::raw("")); + if state.git.changed_files.is_empty() { + lines.push(Line::from(vec![ + Span::styled("Changed files ", theme::muted()), + Span::styled("none", theme::primary()), + ])); + } else { + lines.push(Line::from(vec![Span::styled( + "Changed files", + theme::section_title(), + )])); + for file in state.git.changed_files.iter().take(10) { + lines.push(Line::from(vec![ + Span::styled("• ", theme::accent()), + Span::styled(file.clone(), theme::primary()), + ])); + } + } + lines +} + +fn test_lines(state: &AppState) -> Vec> { + let mut lines = vec![Line::from(vec![ + Span::styled("Test runs", theme::section_title()), + Span::styled( + " normalized test results will accumulate here", + theme::muted(), + ), + ])]; + if state.tests.recent_runs.is_empty() { + lines.push(Line::raw("")); + lines.push(Line::from(vec![Span::styled( + "No test runs observed yet.", + theme::primary(), + )])); + lines.push(Line::from(vec![Span::styled( + "Future adapters should normalize test results here.", + theme::muted(), + )])); + return lines; + } + + for run in state.tests.recent_runs.iter().rev().take(8) { + lines.push(Line::from(vec![ + Span::styled(format!("[{:?}] ", run.status), theme::accent()), + Span::styled(run.runner.clone(), theme::primary()), + Span::raw(" "), + Span::styled( + format!("pass:{} fail:{}", run.pass_count, run.fail_count), + theme::muted(), + ), + ])); + } + lines +} + +fn render_tabs(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + let tabs = DashboardTab::all() + .iter() + .map(|tab| { + let active = *tab == state.ui.dashboard_tab; + let label = format!(" {} ", tab.title()); + if active { + Span::styled(label, theme::status_badge(theme::ACCENT)) + } else { + Span::styled(label, theme::muted()) + } + }) + .collect::>(); + + let mut content = Vec::new(); + for (index, tab) in tabs.into_iter().enumerate() { + if index > 0 { + content.push(Span::raw(" ")); + } + content.push(tab); + } + content.push(Span::raw(" ")); + content.push(Span::styled("Left/Right", theme::accent())); + content.push(Span::styled(" switch tabs", theme::muted())); + + frame.render_widget( + Paragraph::new(Line::from(content)).block(Block::default()), + area, + ); +} + +fn render_context(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + let summary = match state.ui.dashboard_tab { + DashboardTab::Services => { + format!("{} tracked services", state.services.registry.len()) + } + DashboardTab::Processes => { + format!("{} process snapshots", state.processes.snapshots.len()) + } + DashboardTab::Logs => { + format!("{} buffered log lines", state.logs.recent.len()) + } + DashboardTab::Git => { + format!( + "branch {} | {} changed files", + state + .git + .branch + .clone() + .unwrap_or_else(|| "unknown".to_string()), + state.git.changed_files.len() + ) + } + DashboardTab::Tests => { + format!("{} recorded test runs", state.tests.recent_runs.len()) + } + }; + + let line = Line::from(vec![ + Span::styled(state.ui.dashboard_tab.title(), theme::accent()), + Span::styled(" ", theme::muted()), + Span::styled(summary, theme::muted()), + ]); + frame.render_widget(Paragraph::new(line), area); +} diff --git a/src/ui/views/event_stream.rs b/src/ui/views/event_stream.rs new file mode 100644 index 0000000..263c414 --- /dev/null +++ b/src/ui/views/event_stream.rs @@ -0,0 +1,92 @@ +use ratatui::layout::Rect; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use ratatui::Frame; + +use crate::domain::{AppState, TimelineKind}; +use crate::shared::time::format_timestamp; +use crate::ui::theme; + +pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState, focused: bool) { + let lines = build_timeline_lines(state, area.height.saturating_sub(2) as usize); + + frame.render_widget( + Paragraph::new(lines) + .block( + Block::default() + .title(Span::styled(" Event Stream ", theme::panel_title(focused))) + .borders(Borders::ALL) + .border_style(theme::pane_border(focused)) + .style(theme::primary().bg(theme::BG_BASE)), + ) + .wrap(Wrap { trim: false }), + area, + ); +} + +fn build_timeline_lines(state: &AppState, limit: usize) -> Vec> { + let mut collapsed: Vec = Vec::new(); + + for entry in state.timeline.entries.iter().rev() { + if let Some(last) = collapsed.last_mut() { + if last.kind == entry.kind && last.message == entry.message { + last.count += 1; + last.last_seen = entry.at; + continue; + } + } + collapsed.push(CollapsedEntry { + at: entry.at, + last_seen: entry.at, + kind: entry.kind, + message: entry.message.clone(), + count: 1, + }); + if collapsed.len() >= limit { + break; + } + } + + if collapsed.is_empty() { + return vec![Line::from(vec![Span::styled( + "No events yet. Run a command to populate the timeline.", + theme::muted(), + )])]; + } + + collapsed + .into_iter() + .map(|entry| { + let kind = match entry.kind { + TimelineKind::System => "SYSTEM", + TimelineKind::Ai => "AI", + TimelineKind::Command => "COMMAND", + TimelineKind::Log => "LOG", + TimelineKind::Approval => "APPROVAL", + TimelineKind::Error => "ERROR", + }; + let mut spans = vec![ + Span::styled(format!("{} ", format_timestamp(entry.at)), theme::subtle()), + Span::styled( + format!(" {kind} "), + theme::status_badge(theme::timeline_color(entry.kind)), + ), + Span::raw(" "), + Span::styled(entry.message, theme::primary()), + ]; + if entry.count > 1 { + spans.push(Span::raw(" ")); + spans.push(Span::styled(format!("×{}", entry.count), theme::muted())); + } + Line::from(spans) + }) + .collect() +} + +struct CollapsedEntry { + at: std::time::SystemTime, + last_seen: std::time::SystemTime, + kind: TimelineKind, + message: String, + count: usize, +} diff --git a/src/ui/views/mod.rs b/src/ui/views/mod.rs new file mode 100644 index 0000000..4fc0ff9 --- /dev/null +++ b/src/ui/views/mod.rs @@ -0,0 +1,51 @@ +mod command_pane; +mod dashboard; +mod event_stream; +mod modal; +mod status_bar; + +use ratatui::layout::{Constraint, Direction, Layout}; +use ratatui::Frame; + +use crate::domain::{AppState, FocusTarget}; + +pub fn render(frame: &mut Frame<'_>, state: &AppState) { + let layout = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Length(3), + Constraint::Min(12), + Constraint::Length(state.config.ui.event_stream_height), + ]) + .split(frame.area()); + + status_bar::render(frame, layout[0], state); + + let main = Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Percentage(state.config.ui.main_split_pct), + Constraint::Percentage(100 - state.config.ui.main_split_pct), + ]) + .split(layout[1]); + + command_pane::render( + frame, + main[0], + state, + matches!(state.ui.focus, FocusTarget::CommandPane), + ); + dashboard::render( + frame, + main[1], + state, + matches!(state.ui.focus, FocusTarget::DashboardPane), + ); + event_stream::render( + frame, + layout[2], + state, + matches!(state.ui.focus, FocusTarget::EventStream), + ); + modal::render(frame, state); +} diff --git a/src/ui/views/modal.rs b/src/ui/views/modal.rs new file mode 100644 index 0000000..de3daff --- /dev/null +++ b/src/ui/views/modal.rs @@ -0,0 +1,136 @@ +use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect}; +use ratatui::style::{Modifier, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap}; +use ratatui::Frame; + +use crate::domain::{AppState, ModalState}; +use crate::ui::theme; + +pub fn render(frame: &mut Frame<'_>, state: &AppState) { + let Some(modal) = state.ui.modal.as_ref() else { + return; + }; + + let area = centered_rect(70, 40, frame.area()); + frame.render_widget(Clear, area); + + match modal { + ModalState::Approval(approval_id) => { + let approval = state + .approvals + .pending + .iter() + .find(|request| request.id == *approval_id); + let Some(approval) = approval else { + return; + }; + + let lines = vec![ + Line::from(Span::styled( + format!("{} Action", approval.class.label()), + Style::default() + .fg(theme::WARN) + .add_modifier(Modifier::BOLD), + )), + Line::raw(""), + Line::from(format!( + "Command #{}: {}", + approval.command_id, approval.summary + )), + Line::from(approval.detail.clone()), + Line::raw(""), + Line::from("Press Enter or y to approve."), + Line::from("Press Esc or n to deny."), + ]; + + frame.render_widget( + Paragraph::new(lines) + .alignment(Alignment::Left) + .wrap(Wrap { trim: false }) + .block( + Block::default() + .title("Approval Required") + .borders(Borders::ALL) + .border_style(theme::pane_border(true)), + ), + area, + ); + } + ModalState::Help => { + let lines = vec![ + Line::from(Span::styled( + "Forge Commands", + Style::default() + .fg(theme::ACCENT) + .add_modifier(Modifier::BOLD), + )), + Line::raw(""), + Line::from("/help open this help"), + Line::from("/ai queue an AI assistance request"), + Line::from("/diagnose queue an AI diagnosis request"), + Line::from("/bg run a background command"), + Line::from("/cancel cancel a running command"), + Line::from("/approve approve the current pending action"), + Line::from("/deny deny the current pending action"), + Line::from("/tab next next dashboard tab"), + Line::from("/tab prev previous dashboard tab"), + Line::from("/quit exit Forge"), + Line::raw(""), + Line::from("Keyboard"), + Line::from("Tab cycle pane focus"), + Line::from("Left/Right switch dashboard tabs when dashboard is focused"), + Line::from("Enter run input or confirm modal"), + Line::from("Esc close modal / deny approval"), + Line::from("F1 open help"), + ]; + + frame.render_widget( + Paragraph::new(lines) + .alignment(Alignment::Left) + .wrap(Wrap { trim: false }) + .block( + Block::default() + .title("Help") + .borders(Borders::ALL) + .border_style(theme::pane_border(true)), + ), + area, + ); + } + ModalState::Error(message) => { + frame.render_widget( + Paragraph::new(message.clone()) + .alignment(Alignment::Left) + .wrap(Wrap { trim: false }) + .block( + Block::default() + .title("Error") + .borders(Borders::ALL) + .border_style(Style::default().fg(theme::ERROR)), + ), + area, + ); + } + } +} + +fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect { + let popup_layout = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Percentage((100 - percent_y) / 2), + Constraint::Percentage(percent_y), + Constraint::Percentage((100 - percent_y) / 2), + ]) + .split(area); + + Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Percentage((100 - percent_x) / 2), + Constraint::Percentage(percent_x), + Constraint::Percentage((100 - percent_x) / 2), + ]) + .split(popup_layout[1])[1] +} diff --git a/src/ui/views/status_bar.rs b/src/ui/views/status_bar.rs new file mode 100644 index 0000000..30a9757 --- /dev/null +++ b/src/ui/views/status_bar.rs @@ -0,0 +1,196 @@ +use ratatui::layout::{Constraint, Direction, Layout, Rect}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Borders, Paragraph}; +use ratatui::Frame; + +use crate::domain::AppState; +use crate::ui::theme; + +pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { + let branch = state + .git + .branch + .clone() + .unwrap_or_else(|| "no-branch".to_string()); + let head = state + .git + .head + .clone() + .unwrap_or_else(|| "------".to_string()); + let dirty = if state.git.is_dirty { "dirty" } else { "clean" }; + let mode = if state.ui.modal.is_some() { + "approval" + } else if !state.approvals.pending.is_empty() { + "review" + } else { + "normal" + }; + let focus = match state.ui.focus { + crate::domain::FocusTarget::CommandPane => "command", + crate::domain::FocusTarget::DashboardPane => "dashboard", + crate::domain::FocusTarget::EventStream => "events", + crate::domain::FocusTarget::Modal => "modal", + }; + let (ai_label, ai_color) = match state.ai.status { + crate::domain::AiStatus::Disabled => ("OFF", theme::TEXT_SUBTLE), + crate::domain::AiStatus::Unconfigured => ("SETUP", theme::WARN), + crate::domain::AiStatus::Ready => ("READY", theme::SUCCESS), + crate::domain::AiStatus::Queued => ("QUEUED", theme::INFO), + crate::domain::AiStatus::Running => ("RUN", theme::INFO), + crate::domain::AiStatus::Completed => ("DONE", theme::SUCCESS), + crate::domain::AiStatus::Failed => ("ERROR", theme::ERROR), + }; + let pending_count = state.approvals.pending.len().to_string(); + + let rows = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Length(1), + Constraint::Length(1), + Constraint::Length(1), + ]) + .split(area); + + frame.render_widget( + Block::default() + .borders(Borders::BOTTOM) + .border_style(theme::pane_border(false)), + area, + ); + + let row1 = Line::from(vec![ + Span::styled(" Forge ", theme::status_badge(theme::ACCENT)), + Span::raw(" "), + badge( + "GIT", + dirty, + if state.git.is_dirty { + theme::WARN + } else { + theme::SUCCESS + }, + ), + Span::raw(" "), + badge("MODE", mode, theme::INFO), + Span::raw(" "), + badge("FOCUS", focus, theme::ACCENT), + Span::raw(" "), + badge("AI", ai_label, ai_color), + Span::raw(" "), + badge( + "PENDING", + &pending_count, + if state.approvals.pending.is_empty() { + theme::TEXT_SUBTLE + } else { + theme::WARN + }, + ), + ]); + frame.render_widget(Paragraph::new(row1), rows[0]); + + let row2 = Line::from(vec![ + Span::styled("repo ", theme::muted()), + Span::styled(truncate_end(&state.project.name, 24), theme::primary()), + Span::raw(" "), + Span::styled("branch ", theme::muted()), + Span::styled(truncate_middle(&branch, 32), theme::primary()), + Span::raw(" "), + Span::styled("head ", theme::muted()), + Span::styled(head, theme::primary()), + ]); + frame.render_widget(Paragraph::new(row2), rows[1]); + + let row3 = contextual_hint_line(state); + frame.render_widget(Paragraph::new(row3), rows[2]); +} + +fn badge<'a>(label: &'a str, value: &'a str, bg: ratatui::style::Color) -> Span<'a> { + Span::styled(format!(" {label}:{value} "), theme::status_badge(bg)) +} + +fn truncate_end(value: &str, max_chars: usize) -> String { + if value.chars().count() <= max_chars { + return value.to_string(); + } + let kept = value + .chars() + .take(max_chars.saturating_sub(1)) + .collect::(); + format!("{kept}…") +} + +fn truncate_middle(value: &str, max_chars: usize) -> String { + let count = value.chars().count(); + if count <= max_chars { + return value.to_string(); + } + let side = max_chars.saturating_sub(1) / 2; + let start = value.chars().take(side).collect::(); + let end = value + .chars() + .rev() + .take(side) + .collect::>() + .into_iter() + .rev() + .collect::(); + format!("{start}…{end}") +} + +fn contextual_hint_line(state: &AppState) -> Line<'static> { + match state.ui.modal.as_ref() { + Some(crate::domain::ModalState::Approval(_)) => Line::from(vec![ + Span::styled("Enter", theme::accent()), + Span::styled(" approve", theme::muted()), + Span::raw(" "), + Span::styled("Esc", theme::accent()), + Span::styled(" deny", theme::muted()), + Span::raw(" "), + Span::styled("/help", theme::accent()), + Span::styled(" commands", theme::muted()), + ]), + Some(crate::domain::ModalState::Help) | Some(crate::domain::ModalState::Error(_)) => { + Line::from(vec![ + Span::styled("Esc", theme::accent()), + Span::styled(" close", theme::muted()), + Span::raw(" "), + Span::styled("Enter", theme::accent()), + Span::styled(" dismiss", theme::muted()), + ]) + } + None => match state.ui.focus { + crate::domain::FocusTarget::CommandPane => Line::from(vec![ + Span::styled("Enter", theme::accent()), + Span::styled(" run", theme::muted()), + Span::raw(" "), + Span::styled("Tab", theme::accent()), + Span::styled(" next pane", theme::muted()), + Span::raw(" "), + Span::styled("/help", theme::accent()), + Span::styled(" commands", theme::muted()), + ]), + crate::domain::FocusTarget::DashboardPane => Line::from(vec![ + Span::styled("Left/Right", theme::accent()), + Span::styled(" switch tabs", theme::muted()), + Span::raw(" "), + Span::styled("Tab", theme::accent()), + Span::styled(" next pane", theme::muted()), + Span::raw(" "), + Span::styled("F1", theme::accent()), + Span::styled(" help", theme::muted()), + ]), + crate::domain::FocusTarget::EventStream => Line::from(vec![ + Span::styled("Tab", theme::accent()), + Span::styled(" next pane", theme::muted()), + Span::raw(" "), + Span::styled("F1", theme::accent()), + Span::styled(" help", theme::muted()), + ]), + crate::domain::FocusTarget::Modal => Line::from(vec![ + Span::styled("Esc", theme::accent()), + Span::styled(" close", theme::muted()), + ]), + }, + } +} diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..8f966c7 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,9 @@ +# Test Layout + +`tests/foundation.rs` is currently the active integration-style test entry point for Forge's +foundation coverage. + +`tests/integration/` is reserved for future split-out integration suites, fixtures, or +scenario-specific harnesses once the runtime surface grows beyond a single foundation file. + +The directory is intentionally present so the eventual layout is explicit instead of implicit. diff --git a/tests/foundation.rs b/tests/foundation.rs new file mode 100644 index 0000000..2afa756 --- /dev/null +++ b/tests/foundation.rs @@ -0,0 +1,300 @@ +use std::collections::BTreeMap; +use std::time::SystemTime; + +use forge::app::{AppAction, AppStore, Effect}; +use forge::commands::{parse_input, ParsedInput}; +use forge::config::ForgeConfig; +use forge::domain::{ + AiRequestKind, AppState, ApprovalMode, CommandProvenance, CommandStatus, DashboardTab, + FocusTarget, GitSnapshot, LogEntry, LogSeverity, LogSource, LogStream, ModalState, + ProjectContext, SafetyClass, +}; +use forge::safety::classify_command; +use forge::shared::ids::{CommandId, LogId}; + +#[test] +fn parses_background_shell_execution() { + let parsed = parse_input("cargo test &").expect("background shell command should parse"); + match parsed { + ParsedInput::Execute { + command, + background, + provenance, + } => { + assert_eq!(command, "cargo test"); + assert!(background); + assert!(matches!(provenance, CommandProvenance::UserInput)); + } + other => panic!("unexpected parse result: {:?}", other), + } +} + +#[test] +fn parses_supported_slash_commands() { + assert!(matches!(parse_input("/quit").unwrap(), ParsedInput::Quit)); + assert!(matches!(parse_input("/exit").unwrap(), ParsedInput::Quit)); + assert!(matches!(parse_input("/clear").unwrap(), ParsedInput::Clear)); + assert!(matches!( + parse_input("/tab next").unwrap(), + ParsedInput::NextTab + )); + assert!(matches!( + parse_input("/next-tab").unwrap(), + ParsedInput::NextTab + )); + assert!(matches!( + parse_input("/tab prev").unwrap(), + ParsedInput::PrevTab + )); + assert!(matches!( + parse_input("/prev-tab").unwrap(), + ParsedInput::PrevTab + )); + assert!(matches!( + parse_input("/approve").unwrap(), + ParsedInput::ApprovePending + )); + assert!(matches!( + parse_input("/deny").unwrap(), + ParsedInput::DenyPending + )); + + match parse_input("/bg cargo run").unwrap() { + ParsedInput::Execute { + command, + background, + provenance, + } => { + assert_eq!(command, "cargo run"); + assert!(background); + assert!(matches!(provenance, CommandProvenance::SlashCommand)); + } + other => panic!("unexpected parse result: {:?}", other), + } + + match parse_input("/ai summarize logs").unwrap() { + ParsedInput::AiPrompt { prompt, kind } => { + assert_eq!(prompt, "summarize logs"); + assert!(matches!(kind, AiRequestKind::Assist)); + } + other => panic!("unexpected parse result: {:?}", other), + } + + match parse_input("/diagnose failing test").unwrap() { + ParsedInput::AiPrompt { prompt, kind } => { + assert_eq!(prompt, "failing test"); + assert!(matches!(kind, AiRequestKind::Diagnose)); + } + other => panic!("unexpected parse result: {:?}", other), + } +} + +#[test] +fn parses_cancel_slash_command() { + let parsed = parse_input("/cancel 42").expect("cancel slash command should parse"); + match parsed { + ParsedInput::Cancel(id) => assert_eq!(id.0, 42), + other => panic!("unexpected parse result: {:?}", other), + } +} + +#[test] +fn parses_help_slash_command() { + let parsed = parse_input("/help").expect("help slash command should parse"); + match parsed { + ParsedInput::Help => {} + other => panic!("unexpected parse result: {:?}", other), + } +} + +#[test] +fn safety_classifier_marks_destructive_commands() { + let class = classify_command("rm -rf build"); + assert!(matches!(class, SafetyClass::Destructive)); +} + +#[test] +fn store_help_command_opens_modal() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Help)); + + assert!(effects.is_empty()); + assert!(matches!(store.state().ui.modal, Some(ModalState::Help))); + assert!(matches!(store.state().ui.focus, FocusTarget::Modal)); +} + +#[test] +fn store_executes_passive_shell_command_immediately() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Execute { + command: "pwd".to_string(), + background: false, + provenance: CommandProvenance::UserInput, + })); + + assert_eq!(effects.len(), 1); + let command = store + .state() + .commands + .records + .last() + .expect("command record should exist"); + assert_eq!(command.raw, "pwd"); + assert!(matches!(command.status, CommandStatus::Queued)); +} + +#[test] +fn store_routes_caution_commands_to_inline_review() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Execute { + command: "cargo test".to_string(), + background: false, + provenance: CommandProvenance::UserInput, + })); + + assert_eq!(effects.len(), 1); + let approval = store + .state() + .approvals + .pending + .last() + .expect("approval should be queued"); + assert!(matches!(approval.mode, ApprovalMode::InlineReview)); + let command = store + .state() + .commands + .records + .last() + .expect("command record should exist"); + assert!(matches!(command.status, CommandStatus::PendingReview)); +} + +#[test] +fn store_routes_risky_commands_to_modal_approval() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Execute { + command: "echo hi > /tmp/forge-test.txt".to_string(), + background: false, + provenance: CommandProvenance::UserInput, + })); + + assert_eq!(effects.len(), 1); + let approval = store + .state() + .approvals + .pending + .last() + .expect("approval should be queued"); + assert!(matches!(approval.mode, ApprovalMode::ModalConfirm)); + assert!(matches!( + store.state().ui.modal, + Some(ModalState::Approval(_)) + )); +} + +#[test] +fn store_ai_prompt_reports_unavailable_provider() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::AiPrompt { + prompt: "explain the failure".to_string(), + kind: AiRequestKind::Diagnose, + })); + + assert!(matches!(effects.as_slice(), [Effect::RunAiRequest(_)])); + assert_eq!(store.state().ai.requests.len(), 1); + assert!(store.state().ai.active_request.is_some()); + assert!(matches!( + store.state().ai.requests[0].kind, + AiRequestKind::Diagnose + )); +} + +#[test] +fn store_clear_resets_input_and_visible_logs() { + let mut store = test_store(); + store.state_mut().ui.input_buffer = "pwd".to_string(); + store.state_mut().logs.recent.push(LogEntry { + id: LogId(1), + ts: SystemTime::now(), + source: LogSource::Command(CommandId(1)), + stream: LogStream::Stdout, + service_id: None, + command_id: Some(CommandId(1)), + severity: LogSeverity::Info, + raw: "hello".to_string(), + fields: BTreeMap::new(), + }); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Clear)); + + assert!(effects.is_empty()); + assert!(store.state().ui.input_buffer.is_empty()); + assert!(store.state().logs.recent.is_empty()); +} + +#[test] +fn store_quit_requests_shutdown() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Quit)); + + assert!(store.state().app.should_quit); + assert!(matches!(effects.as_slice(), [Effect::Shutdown])); +} + +#[test] +fn store_tab_commands_cycle_dashboard_tabs() { + let mut store = test_store(); + + let next_effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::NextTab)); + assert!(next_effects.is_empty()); + assert!(matches!( + store.state().ui.dashboard_tab, + DashboardTab::Processes + )); + + let prev_effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::PrevTab)); + assert!(prev_effects.is_empty()); + assert!(matches!( + store.state().ui.dashboard_tab, + DashboardTab::Services + )); +} + +#[test] +fn store_cancel_command_emits_effect() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Cancel(CommandId(42)))); + + assert!(matches!( + effects.as_slice(), + [Effect::CancelCommand(CommandId(42))] + )); +} + +#[test] +fn store_approve_without_pending_shows_notice() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::ApprovePending)); + + assert!(effects.is_empty()); + assert!(store + .state() + .notifications + .items + .last() + .is_some_and(|notice| notice.message.contains("no pending approvals"))); +} + +fn test_store() -> AppStore { + let config = ForgeConfig::default(); + let state = AppState::new(config, ProjectContext::default(), GitSnapshot::default()); + AppStore::new(state) +} diff --git a/tests/integration/.gitkeep b/tests/integration/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/integration/.gitkeep @@ -0,0 +1 @@ +