diff --git a/.gitignore b/.gitignore index 264a04e..a93c69d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,14 @@ target/ __pycache__/ *.jsonl + +# Devenv +.devenv* +devenv.local.nix +devenv.local.yaml + +# direnv +.direnv + +# pre-commit +.pre-commit-config.yaml diff --git a/Cargo.lock b/Cargo.lock index a715295..e508ff4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,21 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +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" @@ -58,6 +73,130 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + +[[package]] +name = "atomic" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bit-set" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[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.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "clap" version = "4.6.7" @@ -89,7 +228,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -104,17 +243,348 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags 2.13.2", + "crossterm_winapi", + "derive_more", + "document-features", + "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 = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "csscolorparser" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2a7d3066da2de787b7f032c736763eb7ae5d355f81a68bab2675a96008b0bf" +dependencies = [ + "lab", + "phf", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "deltae" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4" + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + [[package]] name = "equivalent" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fancy-regex" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b95f7c0680e4142284cf8b22c14a476e87d61b004a3a0861872b32ef7ead40a2" +dependencies = [ + "bit-set", + "regex", +] + +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "finl_unicode" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456" + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown", +] [[package]] name = "heck" @@ -122,6 +592,18 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "indexmap" version = "2.14.2" @@ -130,6 +612,30 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.10", ] [[package]] @@ -138,24 +644,251 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "kasuari" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f14c90e40a6133f4805b83542a7ed7364f56070b447f56e7f4e90297122209" +dependencies = [ + "hashbrown", + "portable-atomic", + "thiserror 2.0.21", +] + +[[package]] +name = "lab" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf36173d4167ed999940f804952e6b08197cae5ad5d572eb4db150ce8ad5d58f" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libsqlite3-sys" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "line-clipping" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[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.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "mac_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d0581a75c45969c63afd2bb87b1d8b25cfcc556c7a918cf9bb13b0fe8d2381" +dependencies = [ + "nix 0.31.3", + "windows-sys", +] + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memmem" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64a92489e2744ce060c349162be1c5f33c6969234104dbd99ddb5feb08b8c15" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys", +] + +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell_polyfill" version = "1.70.2" @@ -168,12 +901,212 @@ version = "0.1.0" dependencies = [ "anyhow", "clap", + "crossterm", + "indexmap", "libc", + "quick-xml", + "ratatui", + "rusqlite", "serde", "serde_json", "toml", + "unicode-width", ] +[[package]] +name = "ordered-float" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951" +dependencies = [ + "num-traits", +] + +[[package]] +name = "palette" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" +dependencies = [ + "approx", + "libm", + "palette_derive", + "palette_math", +] + +[[package]] +name = "palette_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be" +dependencies = [ + "by_address", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "palette_math" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" +dependencies = [ + "libm", +] + +[[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 = "pest" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ec53fd1d256900a9a771bf2720d42cef6f8bc91b4e25065fbd291e3e7222576" +dependencies = [ + "memchr", + "pest_stack_guard", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adcf794fd301ddc20818a6b4de85ed507f4b45300245cec948982e69e12e3bd7" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3073afae5db334c25dea9fc3e230a4f191e920c1df080cb9c0b37c9ce1dbb41" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pest_meta" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bc7f614b3742541642af1685faaa910bf6333e3cd3729c2cccd118146a57327" +dependencies = [ + "pest", +] + +[[package]] +name = "pest_stack_guard" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ac6154fd4418b8f0b82532c59c26f303f9ca59a64c883e8ce3971fd82733439" +dependencies = [ + "psm", + "stacker", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -183,6 +1116,25 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -192,6 +1144,242 @@ 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 = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "ratatui" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d" +dependencies = [ + "instability", + "ratatui-core", + "ratatui-crossterm", + "ratatui-macros", + "ratatui-termina", + "ratatui-termwiz", + "ratatui-widgets", + "serde", +] + +[[package]] +name = "ratatui-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" +dependencies = [ + "bitflags 2.13.2", + "compact_str", + "critical-section", + "hashbrown", + "itertools", + "kasuari", + "lru", + "palette", + "serde", + "strum", + "thiserror 2.0.21", + "unicode-segmentation", + "unicode-truncate", + "unicode-width", +] + +[[package]] +name = "ratatui-crossterm" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" +dependencies = [ + "cfg-if", + "crossterm", + "instability", + "ratatui-core", +] + +[[package]] +name = "ratatui-macros" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed7dc68daa7498a43e4d68e0eb078427e10c38fbcfbb1e42d955f1fa2140d814" +dependencies = [ + "ratatui-core", + "ratatui-widgets", +] + +[[package]] +name = "ratatui-termina" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0bf912d9e66f057a759d92e386a280ea886b352ab757d6ac4d653c7ed2c43c2" +dependencies = [ + "instability", + "ratatui-core", + "termina", +] + +[[package]] +name = "ratatui-termwiz" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf03e0380b7744054d6cb74224fe3adf062a029754933f575ca1e3b4c2ce977" +dependencies = [ + "ratatui-core", + "termwiz", +] + +[[package]] +name = "ratatui-widgets" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1" +dependencies = [ + "bitflags 2.13.2", + "hashbrown", + "indoc", + "instability", + "itertools", + "line-clipping", + "ratatui-core", + "serde", + "strum", + "time", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "rusqlite" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4edff0039f148731aee2fd80f76dbfeb12d204ab3d1c544838d34e02151049b" +dependencies = [ + "bitflags 2.13.2", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -219,7 +1407,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -244,12 +1432,150 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[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 = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867" +dependencies = [ + "cc", + "rsqlite-vfs", +] + +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys", +] + +[[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.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.10" @@ -261,12 +1587,150 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "termina" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9048a889effe34a5cddee0af7f53285198b16dca3be510858d38dfdb3e62a04e" +dependencies = [ + "bitflags 2.13.2", + "parking_lot", + "rustix", + "signal-hook", + "windows-sys", +] + +[[package]] +name = "terminfo" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ea810f0692f9f51b382fff5893887bb4580f5fa246fde546e0b13e7fcee662" +dependencies = [ + "fnv", + "nom", + "phf", + "phf_codegen", +] + +[[package]] +name = "termios" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411c5bf740737c7918b8b1fe232dca4dc9f8e754b8ad5e20966814001ed0ac6b" +dependencies = [ + "libc", +] + +[[package]] +name = "termwiz" +version = "0.23.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4676b37242ccbd1aabf56edb093a4827dc49086c0ffd764a5705899e0f35f8f7" +dependencies = [ + "anyhow", + "base64", + "bitflags 2.13.2", + "fancy-regex", + "filedescriptor", + "finl_unicode", + "fixedbitset", + "hex", + "lazy_static", + "libc", + "log", + "memmem", + "nix 0.29.0", + "num-derive", + "num-traits", + "ordered-float", + "pest", + "pest_derive", + "phf", + "sha2", + "signal-hook", + "siphasher", + "terminfo", + "termios", + "thiserror 1.0.69", + "ucd-trie", + "unicode-segmentation", + "vtparse", + "wezterm-bidi", + "wezterm-blob-leases", + "wezterm-color-types", + "wezterm-dynamic", + "wezterm-input-types", + "winapi", +] + +[[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.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[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 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + [[package]] name = "toml" version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" dependencies = [ + "indexmap", "serde", "serde_spanned", "toml_datetime", @@ -302,18 +1766,239 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + [[package]] name = "utf8parse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" +dependencies = [ + "atomic", + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vtparse" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9b2acfb050df409c972a37d3b8e08cdea3bddb0c09db9d53137e504cfabed0" +dependencies = [ + "utf8parse", +] + +[[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.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wezterm-bidi" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0a6e355560527dd2d1cf7890652f4f09bb3433b6aadade4c9b5ed76de5f3ec" +dependencies = [ + "log", + "wezterm-dynamic", +] + +[[package]] +name = "wezterm-blob-leases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "692daff6d93d94e29e4114544ef6d5c942a7ed998b37abdc19b17136ea428eb7" +dependencies = [ + "getrandom 0.3.4", + "mac_address", + "sha2", + "thiserror 1.0.69", + "uuid", +] + +[[package]] +name = "wezterm-color-types" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7de81ef35c9010270d63772bebef2f2d6d1f2d20a983d27505ac850b8c4b4296" +dependencies = [ + "csscolorparser", + "deltae", + "lazy_static", + "wezterm-dynamic", +] + +[[package]] +name = "wezterm-dynamic" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f2ab60e120fd6eaa68d9567f3226e876684639d22a4219b313ff69ec0ccd5ac" +dependencies = [ + "log", + "ordered-float", + "strsim", + "thiserror 1.0.69", + "wezterm-dynamic-derive", +] + +[[package]] +name = "wezterm-dynamic-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c0cf2d539c645b448eaffec9ec494b8b19bd5077d9e58cb1ae7efece8d575b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "wezterm-input-types" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7012add459f951456ec9d6c7e6fc340b1ce15d6fc9629f8c42853412c029e57e" +dependencies = [ + "bitflags 1.3.2", + "euclid", + "lazy_static", + "serde", + "wezterm-dynamic", +] + +[[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" @@ -338,6 +2023,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 429c41b..5a12b14 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,13 @@ description = "Orchestrator that runs many hx coding agents" [dependencies] anyhow = "1" clap = { version = "4", features = ["derive"] } +crossterm = "0.29.0" +indexmap = { version = "2.14.2", features = ["serde"] } libc = "0.2" +quick-xml = "0.42.0" +ratatui = "0.30.2" +rusqlite = { version = "0.42.0", features = ["bundled"] } serde = { version = "1", features = ["derive"] } serde_json = "1" -toml = "0.8" +toml = { version = "0.8", features = ["preserve_order"] } +unicode-width = "0.2" diff --git a/README.md b/README.md index f1a6152..4eec846 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,37 @@ kind = "cmd" command = "python3 /work/adapters/gitea.py" ``` +## State-machine sessions and the TUI + +`orch` without a subcommand opens the TUI: sessions overview (`enter` on a row opens the session detail, `esc` goes +back; `t` full test output, `d` diff, `l` event transcript, `o` open the worktree in hx). It reads `.hx/orch.db` of the +current directory. `orch session --repo . --machine task --name NAME [--profile P]` creates a session and runs it. +Machines are TOML files in `.hx/machines/` or `~/.hx/machines/` (examples in `examples/machines/`). A `computer` step +with `report = "junit"` writes its JUnit XML to `$ORCH_REPORT` (also available as `{{report}}` in `cmd`); orch parses +it into counts and failing tests. See ORCHESTRATOR.md for the whole design. + +A running session can be steered from the session screen, also when `orch session` runs in another terminal: `i` +interrupt (the agent stops, you reply with a hint), `m` message to the agent, `s` force a state, `k` kill (type +`yes`; goes to `on_abort`), and `r` re-plan from the start state while the loop detector box shows (the last test +runs failed on the same tests). On the goal screen `j/k` selects a decision and `v` vetoes it: the agent is told and +the session goes back to `code`. The commands go through the database (`commands` table) and the runner picks them +up within a fraction of a second, even in the middle of a shell command. A machine can set limits: + + [budget] + wall_secs = 5400 # time spent working, waiting for you does not count + cost = 5.0 # US dollars + compact_at = 85 # percent of the context window; hx gets `hx/compact` + +Passing wall time or cost sends the session to `on_budget` (or fails it when the machine has none). + +The goal lives in the same database: `orch goal "sentence"`, `orch check NAME CMD [--owner sN]` (an acceptance +check: pass = exit 0), `orch checks [--owner sN | --main]`. `g` in the TUI opens the goal view (task graph, critical +path, decisions, checks; `e` edit goal, `+` add check, `R` run all checks on main). `orch session --after s1,s2` makes +a session wait until those have merged. Only one session at a time runs the state that ends in `merged` (first come, +first served); after each merge all checks run again on main in a clean worktree. Machine steps get `ORCH_DB`, +`ORCH_REPO` and `ORCH_SESSION`, and `{{repo}}` in `cmd`; the example machines merge with +`git -C {{repo}} merge --ff-only {{branch}}` in `mark-merged`. + ## More - [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema) diff --git a/devenv.lock b/devenv.lock new file mode 100644 index 0000000..730edfa --- /dev/null +++ b/devenv.lock @@ -0,0 +1,65 @@ +{ + "nodes": { + "devenv": { + "locked": { + "dir": "src/modules", + "lastModified": 1794562632, + "narHash": "sha256-MOb8lrEUUki0Kxe+LNLuhj3DbPsjcurZWq3eG3R0Z9U=", + "owner": "cachix", + "repo": "devenv", + "rev": "6c954cc1c04f1d0b2f6ad689c9dffd835fa4d928", + "type": "github" + }, + "original": { + "dir": "src/modules", + "owner": "cachix", + "repo": "devenv", + "type": "github" + } + }, + "nixpkgs": { + "inputs": { + "nixpkgs-src": "nixpkgs-src" + }, + "locked": { + "lastModified": 1793043970, + "narHash": "sha256-m14odYTdkBUEkJOiEYs2zjGjn8fcjvdCJsm45+k084U=", + "owner": "cachix", + "repo": "devenv-nixpkgs", + "rev": "d97234e58d4e90e3bf77c082fc3b546e51200938", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "rolling", + "repo": "devenv-nixpkgs", + "type": "github" + } + }, + "nixpkgs-src": { + "flake": false, + "locked": { + "lastModified": 1792812153, + "narHash": "sha256-T2+XBfNbf9pecLUWS4+RtuVNZ3W8K5taG5QdV71mWlk=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "674a2028661e550a97400c1cc992b9cca9a668a1", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "devenv": "devenv", + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} \ No newline at end of file diff --git a/devenv.nix b/devenv.nix new file mode 100644 index 0000000..9667893 --- /dev/null +++ b/devenv.nix @@ -0,0 +1,13 @@ +{ + pkgs, + lib, + config, + inputs, + ... +}: + +{ + packages = with pkgs; [ + sqlite + ]; +} diff --git a/devenv.yaml b/devenv.yaml new file mode 100644 index 0000000..3dcab58 --- /dev/null +++ b/devenv.yaml @@ -0,0 +1,18 @@ +# yaml-language-server: $schema=https://devenv.sh/devenv.schema.json +inputs: + nixpkgs: + url: github:cachix/devenv-nixpkgs/rolling + +# If you're using non-OSS software, you can set allow_unfree to true. +# allow_unfree: true + +# If you're not willing to allow unsupported packages: +# allow_unsupported_system: false + +# If you're willing to use a package that's vulnerable +# permitted_insecure_packages: +# - "openssl-1.1.1w" + +# If you have more than one devenv you can merge them +#imports: +# - ./backend diff --git a/examples/machines/docs.toml b/examples/machines/docs.toml new file mode 100644 index 0000000..f4a26e0 --- /dev/null +++ b/examples/machines/docs.toml @@ -0,0 +1,66 @@ +name = "docs" +on_abort = "aborted" +on_budget = "escalated" + +[[state]] +name = "plan" +kind = "start" +steps = [ { name = "draft-plan", run = "agent", sets = "planning", prompt = "plan" } ] +catch = { PlanInvalid = "plan" } +next = "write" + +[[state]] +name = "write" +steps = [ { name = "write", run = "agent", sets = "writing", prompt = "implement" } ] +catch = { ToolDenied = "review" } +next = "lint" + +[[state]] +name = "lint" +steps = [ { name = "markdownlint", run = "computer", sets = "linting", cmd = "markdownlint ." } ] +catch = { LintFailed = "write" } +next = "links" + +[[state]] +name = "links" +steps = [ { name = "check links", run = "computer", sets = "checking links", cmd = "lychee --offline ." } ] +catch = { LinksBroken = "write" } +retry = { LinksBroken = { max = 3, then = "escalated" } } +next = "review" + +[[state]] +name = "review" +kind = "gate" +steps = [ + { name = "open-diff", run = "computer" }, + { name = "wait-approval", run = "human", sets = "waiting" }, +] +catch = { ChangesRequested = "write" } +next = "merge" + +[[state]] +name = "merge" +kind = "exit" +steps = [ + { name = "rebase-main", run = "computer", cmd = "git rebase main" }, + { name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" }, +] +catch = { RebaseConflict = "write" } +end = "merged" + +[[state]] +name = "escalated" +kind = "exit" +only_on = ["LinksBroken x3", "budget"] +steps = [ + { name = "snapshot-worktree", run = "computer" }, + { name = "notify", run = "computer", sets = "needs you" }, +] +end = "escalated" + +[[state]] +name = "aborted" +kind = "abort" +only_on = ["abort"] +steps = [ { name = "remove-worktree", run = "computer", sets = "aborted" } ] +end = "aborted" diff --git a/examples/machines/e2e.toml b/examples/machines/e2e.toml new file mode 100644 index 0000000..56026c8 --- /dev/null +++ b/examples/machines/e2e.toml @@ -0,0 +1,73 @@ +name = "e2e" +on_abort = "aborted" +on_budget = "escalated" + +[[state]] +name = "plan" +kind = "start" +steps = [ { name = "draft-plan", run = "agent", sets = "planning", prompt = "plan" } ] +catch = { PlanInvalid = "plan" } +next = "code" + +[[state]] +name = "code" +steps = [ { name = "edit", run = "agent", sets = "coding", prompt = "implement" } ] +catch = { ToolDenied = "review" } +next = "stack-up" + +[[state]] +name = "stack-up" +steps = [ { name = "compose up", run = "computer", sets = "starting stack", cmd = "docker compose up -d --wait" } ] +catch = { StackFailed = "code" } +next = "e2e" + +[[state]] +name = "e2e" +steps = [ { name = "cargo test e2e", run = "computer", sets = "testing", cmd = "cargo test --test e2e {{scope}}", report = "junit" } ] +catch = { TestsFailed = "stack-down" } +retry = { TestsFailed = { max = 3, then = "escalated" } } +next = "stack-down" + +[[state]] +name = "stack-down" +steps = [ { name = "compose down", run = "computer", sets = "stopping stack", cmd = "docker compose down -v" } ] +catch = { TeardownFailed = "escalated" } +next = "review" + +[[state]] +name = "review" +kind = "gate" +steps = [ + { name = "open-diff", run = "computer" }, + { name = "wait-approval", run = "human", sets = "waiting" }, +] +catch = { ChangesRequested = "code" } +next = "merge" + +[[state]] +name = "merge" +kind = "exit" +steps = [ + { name = "rebase-main", run = "computer", cmd = "git rebase main" }, + { name = "run-acceptance", run = "computer", cmd = "orch checks --owner {{session}}" }, + { name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" }, +] +catch = { RebaseConflict = "code" } +end = "merged" + +[[state]] +name = "escalated" +kind = "exit" +only_on = ["TestsFailed x3", "budget"] +steps = [ + { name = "snapshot-worktree", run = "computer" }, + { name = "notify", run = "computer", sets = "needs you" }, +] +end = "escalated" + +[[state]] +name = "aborted" +kind = "abort" +only_on = ["abort"] +steps = [ { name = "remove-worktree", run = "computer", sets = "aborted" } ] +end = "aborted" diff --git a/examples/machines/migration.toml b/examples/machines/migration.toml new file mode 100644 index 0000000..ad794a6 --- /dev/null +++ b/examples/machines/migration.toml @@ -0,0 +1,76 @@ +name = "migration" +on_abort = "aborted" +on_budget = "escalated" + +[[state]] +name = "plan" +kind = "start" +steps = [ { name = "draft-plan", run = "agent", sets = "planning", prompt = "plan" } ] +catch = { PlanInvalid = "plan" } +next = "code" + +[[state]] +name = "code" +steps = [ { name = "edit", run = "agent", sets = "coding", prompt = "implement" } ] +catch = { ToolDenied = "review" } +next = "up" + +[[state]] +name = "up" +steps = [ { name = "migrate up", run = "computer", sets = "migrating", cmd = "sqlx migrate run" } ] +catch = { MigrationFailed = "code" } +next = "down" + +[[state]] +name = "down" +steps = [ { name = "migrate down", run = "computer", sets = "reverting", cmd = "sqlx migrate revert" } ] +catch = { RevertFailed = "code" } +next = "test" + +[[state]] +name = "test" +steps = [ + { name = "migrate up again", run = "computer", cmd = "sqlx migrate run" }, + { name = "cargo test", run = "computer", sets = "testing", cmd = "cargo test {{scope}}", report = "junit" }, +] +catch = { TestsFailed = "code" } +retry = { TestsFailed = { max = 3, then = "escalated" } } +next = "review" + +[[state]] +name = "review" +kind = "gate" +steps = [ + { name = "open-diff", run = "computer" }, + { name = "wait-approval", run = "human", sets = "waiting" }, +] +catch = { ChangesRequested = "code" } +next = "merge" + +[[state]] +name = "merge" +kind = "exit" +steps = [ + { name = "rebase-main", run = "computer", cmd = "git rebase main" }, + { name = "run-acceptance", run = "computer", cmd = "orch checks --owner {{session}}" }, + { name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" }, +] +catch = { RebaseConflict = "code" } +end = "merged" + +[[state]] +name = "escalated" +kind = "exit" +only_on = ["TestsFailed x3", "budget"] +steps = [ + { name = "snapshot-worktree", run = "computer" }, + { name = "notify", run = "computer", sets = "needs you" }, +] +end = "escalated" + +[[state]] +name = "aborted" +kind = "abort" +only_on = ["abort"] +steps = [ { name = "remove-worktree", run = "computer", sets = "aborted" } ] +end = "aborted" diff --git a/examples/machines/task.toml b/examples/machines/task.toml new file mode 100644 index 0000000..d5b6762 --- /dev/null +++ b/examples/machines/task.toml @@ -0,0 +1,76 @@ +name = "task" +on_abort = "aborted" +on_budget = "escalated" + +[budget] +wall_secs = 5400 # 90 min of work, not counting time spent waiting for you +cost = 5.0 # US dollars +compact_at = 85 # percent of the context window + +[[state]] +name = "plan" +kind = "start" +steps = [ + { name = "read-goal", run = "computer", cmd = "orch goal --export" }, + { name = "draft-plan", run = "agent", sets = "planning", prompt = "plan" }, +] +catch = { PlanInvalid = "plan" } +next = "code" + +[[state]] +name = "code" +steps = [ { name = "edit", run = "agent", sets = "coding", prompt = "implement" } ] +# ORCHESTRATOR.md maps ToolDenied to a "waiting" state that the file never defines; review is the human gate. +catch = { ToolDenied = "review" } +next = "build" + +[[state]] +name = "build" +steps = [ { name = "cargo build", run = "computer", sets = "building", cmd = "cargo build" } ] +catch = { BuildFailed = "code" } +next = "test" + +[[state]] +name = "test" +steps = [ { name = "cargo test", run = "computer", sets = "testing", cmd = "cargo test {{scope}}", report = "junit" } ] +catch = { TestsFailed = "code" } +retry = { TestsFailed = { max = 3, then = "escalated" } } +next = "review" + +[[state]] +name = "review" +kind = "gate" +steps = [ + { name = "open-diff", run = "computer" }, + { name = "wait-approval", run = "human", sets = "waiting" }, +] +catch = { ChangesRequested = "code" } +next = "merge" + +[[state]] +name = "merge" +kind = "exit" +steps = [ + { name = "rebase-main", run = "computer", cmd = "git rebase main" }, + { name = "run-acceptance", run = "computer", cmd = "orch checks --owner {{session}}" }, + { name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" }, +] +catch = { RebaseConflict = "code" } +end = "merged" + +[[state]] +name = "escalated" +kind = "exit" +only_on = ["TestsFailed x3", "budget"] +steps = [ + { name = "snapshot-worktree", run = "computer" }, + { name = "notify", run = "computer", sets = "needs you" }, +] +end = "escalated" + +[[state]] +name = "aborted" +kind = "abort" +only_on = ["abort"] +steps = [ { name = "remove-worktree", run = "computer", sets = "aborted" } ] +end = "aborted" diff --git a/src/acp.rs b/src/acp.rs new file mode 100644 index 0000000..f0fae9c --- /dev/null +++ b/src/acp.rs @@ -0,0 +1,257 @@ +//! ACP client (ORCHESTRATOR.md section 5): JSON-RPC 2.0, one JSON object per line, over the stdio of +//! `hx serve --acp`. Standard ACP messages (`initialize`, `session/new`, `session/update`, +//! `session/request_permission`) plus the custom `hx/*` messages. `hx/step` is acknowledged at once; the +//! outcome arrives later as the `hx/step_result` notification. + +use crate::profile::Profile; +use crate::run::hx_env; +use anyhow::{Context, Result, anyhow, bail}; +use serde_json::{Value, json}; +use std::io::{BufRead, Write}; +use std::os::unix::process::CommandExt; +use std::path::Path; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +/// Receives what hx reports while a step runs. +pub trait Sink { + /// Notifications: `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`, `session/update`. + fn notify(&mut self, method: &str, params: &Value) -> Result<()>; + /// `session/request_permission`: returns the chosen `optionId`, or None to cancel the request. + fn permission(&mut self, params: &Value) -> Option; + /// Called about every 100 ms while a step runs: what the user or the budgets want hx to be told. + fn poll(&mut self) -> Poll { + Poll::default() + } +} + +/// What to send to a running step. +#[derive(Default, Debug, PartialEq)] +pub struct Poll { + /// User hints, sent as `hx/message`. + pub messages: Vec, + /// `hx/interrupt`: finish the current tool call, then stop (the step result still arrives). + pub interrupt: bool, + /// `hx/compact`: compact the context now. + pub compact: bool, +} + +const POLL_EVERY: Duration = Duration::from_millis(100); + +#[derive(Debug, PartialEq)] +pub struct StepResult { + /// done | blocked | needs_input + pub status: String, + pub catch: Option, + /// Why a step is `blocked` without a catch; `"limit"` means hx hit a limit passed in `hx/step`. + pub reason: Option, + pub question: Option, + pub summary: String, +} + +pub struct Acp { + child: Child, + stdin: ChildStdin, + rx: mpsc::Receiver, + next_id: u64, + session: String, +} + +impl Acp { + /// Starts `hx serve --acp --cwd --session ` and opens an ACP session. + pub fn spawn(p: &Profile, worktree: &Path, id: &str) -> Result { + let mut parts = p.hx.split_whitespace(); + let mut cmd = Command::new(parts.next().context("empty hx command")?); + cmd.args(parts) + .args(["serve", "--acp", "--cwd"]) + .arg(worktree) + .args(["--session", id]); + // same cleared environment as the batch runner: orch's secrets never reach the agent + cmd.env_clear().envs(hx_env(std::env::vars(), p)); + if let Some(h) = &p.home { + cmd.env("HOME", h); + } + let log = std::fs::File::create(format!("{}.agent.log", worktree.display()))?; + let mut child = cmd + .current_dir(worktree) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::from(log)) + .process_group(0) // own group: kill takes hx and its tool children together + .spawn() + .with_context(|| format!("spawn {}", p.hx))?; + let stdin = child.stdin.take().expect("piped"); + let out = child.stdout.take().expect("piped"); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + for l in std::io::BufReader::new(out).lines().map_while(Result::ok) { + if let Ok(v) = serde_json::from_str::(&l) + && tx.send(v).is_err() + { + break; + } + } + }); + let mut a = Self { + child, + stdin, + rx, + next_id: 1, + session: String::new(), + }; + a.request( + "initialize", + json!({"protocolVersion": 1, "clientCapabilities": {}}), + )?; + let new = a.request("session/new", json!({"cwd": worktree, "mcpServers": []}))?; + a.session = new["sessionId"].as_str().unwrap_or(id).to_string(); + Ok(a) + } + + fn send(&mut self, v: Value) -> Result<()> { + let mut line = v.to_string(); + line.push('\n'); + self.stdin + .write_all(line.as_bytes()) + .and_then(|()| self.stdin.flush()) + .context("write to hx (did it exit?)") + } + + /// Sends a request and returns its result. Only used for the handshake, before any step runs, so + /// nothing hx sends in between has a sink to go to and is dropped. + fn request(&mut self, method: &str, params: Value) -> Result { + let id = self.next_id; + self.next_id += 1; + self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))?; + loop { + let m = self.recv()?; + if m.get("method").is_none() && m["id"] == json!(id) { + if let Some(e) = m.get("error") { + bail!("hx {method}: {}", e["message"].as_str().unwrap_or("error")); + } + return Ok(m["result"].clone()); + } + self.dispatch(&m, None)?; + } + } + + fn recv(&mut self) -> Result { + self.rx + .recv() + .map_err(|_| anyhow!("hx closed its output (exited or crashed)")) + } + + /// Handles one message that is not the response we wait for. Returns a step result if it was one. + fn dispatch(&mut self, m: &Value, sink: Option<&mut dyn Sink>) -> Result> { + let Some(method) = m["method"].as_str() else { + return Ok(None); // a late response (e.g. the ack of hx/step) + }; + // ACP reserves a leading `_` for custom methods: `_hx/intent` is the same as `hx/intent` + let method = method + .strip_prefix('_') + .filter(|r| r.starts_with("hx/")) + .unwrap_or(method); + let params = &m["params"]; + if m.get("id").is_some() { + // a request from hx + let reply = if method == "session/request_permission" { + let chosen = sink.and_then(|s| s.permission(params)); + let outcome = match chosen { + Some(o) => json!({"outcome": "selected", "optionId": o}), + None => json!({"outcome": "cancelled"}), + }; + json!({"jsonrpc": "2.0", "id": m["id"], "result": {"outcome": outcome}}) + } else { + json!({"jsonrpc": "2.0", "id": m["id"], "error": {"code": -32601, "message": format!("unsupported: {method}")}}) + }; + self.send(reply)?; + return Ok(None); + } + if method == "hx/step_result" { + let s = |k: &str| params[k].as_str().map(String::from); + return Ok(Some(StepResult { + status: s("status").unwrap_or_default(), + catch: s("catch"), + reason: s("reason"), + question: s("question"), + summary: s("summary").unwrap_or_default(), + })); + } + if let Some(s) = sink { + s.notify(method, params)?; + } + Ok(None) + } + + /// Runs one agent step and waits for its `hx/step_result`. + pub fn step( + &mut self, + prompt: &str, + instruction: &str, + context: Value, + limits: Value, + sink: &mut dyn Sink, + ) -> Result { + let id = self.next_id; + self.next_id += 1; + self.send( + json!({"jsonrpc": "2.0", "id": id, "method": "hx/step", "params": { + "sessionId": self.session, "prompt": prompt, "instruction": instruction, + "context": context, "limits": limits, + }}), + )?; + let mut last_poll = Instant::now(); + let mut interrupted = false; + loop { + // poll on a timer, also while hx streams without a pause (a recv timeout alone would starve it) + if last_poll.elapsed() >= POLL_EVERY { + last_poll = Instant::now(); + let p = sink.poll(); + for text in p.messages { + self.notify( + "hx/message", + json!({"sessionId": self.session, "text": text}), + )?; + } + if p.interrupt && !interrupted { + interrupted = true; + self.notify("hx/interrupt", json!({"sessionId": self.session}))?; + } + if p.compact { + self.notify("hx/compact", json!({"sessionId": self.session}))?; + } + } + let m = match self.rx.recv_timeout(POLL_EVERY) { + Ok(m) => m, + Err(mpsc::RecvTimeoutError::Timeout) => continue, + Err(mpsc::RecvTimeoutError::Disconnected) => { + bail!("hx closed its output (exited or crashed)") + } + }; + if m.get("method").is_none() && m["id"] == json!(id) { + if let Some(e) = m.get("error") { + bail!( + "hx/step rejected: {}", + e["message"].as_str().unwrap_or("error") + ); + } + continue; // the ack + } + if let Some(r) = self.dispatch(&m, Some(&mut *sink))? { + return Ok(r); + } + } + } + + fn notify(&mut self, method: &str, params: Value) -> Result<()> { + self.send(json!({"jsonrpc": "2.0", "method": method, "params": params})) + } +} + +impl Drop for Acp { + fn drop(&mut self) { + crate::state::kill_group(self.child.id()); + let _ = self.child.wait(); + } +} diff --git a/src/budget.rs b/src/budget.rs new file mode 100644 index 0000000..bed76ee --- /dev/null +++ b/src/budget.rs @@ -0,0 +1,292 @@ +//! Budgets and the loop detector (ORCHESTRATOR.md section 4), as pure functions over a session's events. +//! The runner uses them to stop a session; the session screen uses them to show how close it is. + +use crate::db::Event; +use crate::machine::BudgetCfg; +use std::collections::{BTreeSet, HashMap}; + +/// Seconds the session spent working: from its first event to its end (or now), minus the time it sat in the +/// Needs-you queue. Waiting for you must not eat the wall-time budget. +pub fn active_secs(evs: &[&Event], now_ms: u64) -> u64 { + // work starts with the first state; time blocked on dependencies before that is not work + let Some(first) = evs.iter().find(|e| e.kind == "state") else { + return 0; + }; + let end = match evs.last() { + Some(e) if e.kind == "end" => e.at, + _ => now_ms, + }; + let mut open: HashMap = HashMap::new(); // need id -> when it was put in the queue + let mut waited = 0; + for e in evs { + let id = e.payload["id"].as_i64().unwrap_or(-1); + match e.kind.as_str() { + "need" => { + open.insert(id, e.at); + } + "answer" => { + if let Some(at) = open.remove(&id) { + waited += e.at.saturating_sub(at); + } + } + _ => {} + } + } + waited += open.values().map(|at| end.saturating_sub(*at)).sum::(); + end.saturating_sub(first.at).saturating_sub(waited) / 1000 +} + +/// Cost so far: the last `usage` event carries the running total. +pub fn cost(evs: &[&Event]) -> f64 { + evs.iter() + .rev() + .find(|e| e.kind == "usage") + .and_then(|e| e.payload["cost"].as_f64()) + .unwrap_or(0.0) +} + +/// Context window use in percent, from the last `usage` event. +pub fn ctx_pct(evs: &[&Event]) -> Option { + let e = evs.iter().rev().find(|e| e.kind == "usage")?; + let (used, limit) = ( + e.payload["ctx_used"].as_u64()?, + e.payload["ctx_limit"].as_u64()?, + ); + Some((used * 100).checked_div(limit)?.min(100) as u8) +} + +#[derive(Debug, PartialEq)] +pub struct Exceeded { + pub what: &'static str, + pub used: String, + pub limit: String, +} + +pub fn exceeded(evs: &[&Event], cfg: &BudgetCfg, now_ms: u64) -> Option { + if let Some(limit) = cfg.wall_secs { + let used = active_secs(evs, now_ms); + if used > limit { + return Some(Exceeded { + what: "wall time", + used: format!("{}m", used / 60), + limit: format!("{}m", limit / 60), + }); + } + } + if let Some(limit) = cfg.cost { + let used = cost(evs); + if used > limit { + return Some(Exceeded { + what: "cost", + used: format!("${used:.2}"), + limit: format!("${limit:.2}"), + }); + } + } + None +} + +#[derive(Debug, PartialEq)] +pub struct LoopInfo { + /// Test runs in a row that failed on exactly the same tests. + pub runs: usize, + /// How many tests that is. + pub tests: usize, + /// The file the agent edited most since the loop began. + pub file: Option, +} + +fn failing(e: &Event) -> BTreeSet { + e.payload["failures"] + .as_array() + .into_iter() + .flatten() + .filter_map(|f| f["name"].as_str().map(String::from)) + .collect() +} + +/// After a failed test run: do the last runs fail on the same set of tests? Two in a row is a loop (the agent +/// tried a fix and got the same failures), a run that passes or fails differently ends it. +pub fn looping(evs: &[&Event]) -> Option { + let runs: Vec<&&Event> = evs.iter().filter(|e| e.kind == "test").collect(); + let last = failing(runs.last()?); + if last.is_empty() { + return None; + } + let n = runs.iter().rev().take_while(|r| failing(r) == last).count(); + if n < 2 { + return None; + } + let since = runs[runs.len() - n].id; + let mut edits: HashMap<&str, u64> = HashMap::new(); + for e in evs.iter().filter(|e| e.kind == "edit" && e.id > since) { + let touched = + e.payload["added"].as_u64().unwrap_or(0) + e.payload["removed"].as_u64().unwrap_or(0); + *edits + .entry(e.payload["path"].as_str().unwrap_or_default()) + .or_default() += touched.max(1); + } + let file = edits + .into_iter() + .max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(a.0))) + .map(|(p, _)| p.to_string()); + Some(LoopInfo { + runs: n, + tests: last.len(), + file, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn ev(id: i64, at: u64, kind: &str, payload: serde_json::Value) -> Event { + Event { + id, + session: "s1".into(), + at, + kind: kind.into(), + payload, + } + } + + fn refs(v: &[Event]) -> Vec<&Event> { + v.iter().collect() + } + + fn test_run(id: i64, names: &[&str]) -> Event { + let f: Vec<_> = names.iter().map(|n| json!({"name": n})).collect(); + ev( + id, + id as u64 * 1000, + "test", + json!({"passed": 3, "failed": names.len(), "failures": f}), + ) + } + + #[test] + fn time_in_the_queue_does_not_count_as_work() { + let evs = [ + ev(1, 0, "state", json!({})), + ev(2, 60_000, "need", json!({"id": 5})), + ev(3, 660_000, "answer", json!({"id": 5})), // waited ten minutes + ev(4, 720_000, "step", json!({})), + ]; + assert_eq!(active_secs(&refs(&evs), 720_000), 120); + // still waiting: the open item counts as waiting until now + assert_eq!(active_secs(&refs(&evs[..2]), 3_600_000), 60); + // a finished session stops at its end, not at now + let done = [ + ev(1, 0, "state", json!({})), + ev(2, 30_000, "end", json!({})), + ]; + assert_eq!(active_secs(&refs(&done), 9_999_999), 30); + assert_eq!(active_secs(&[], 5), 0); + } + + #[test] + fn limits_trip_on_time_and_cost() { + let evs = [ + ev(1, 0, "state", json!({})), + ev( + 2, + 10_000, + "usage", + json!({"cost": 5.25, "ctx_used": 142, "ctx_limit": 200}), + ), + ]; + let r = refs(&evs); + assert_eq!(cost(&r), 5.25); + assert_eq!(ctx_pct(&r), Some(71)); + let none = BudgetCfg::default(); + assert_eq!( + exceeded(&r, &none, 999_999_999), + None, + "no limits, no budget stop" + ); + let cost_cap = BudgetCfg { + cost: Some(5.0), + ..none.clone() + }; + assert_eq!( + exceeded(&r, &cost_cap, 0), + Some(Exceeded { + what: "cost", + used: "$5.25".into(), + limit: "$5.00".into() + }) + ); + let wall = BudgetCfg { + wall_secs: Some(60), + ..none + }; + assert_eq!(exceeded(&r, &wall, 30_000), None); + let e = exceeded(&r, &wall, 600_000).unwrap(); + assert_eq!( + (e.what, e.used.as_str(), e.limit.as_str()), + ("wall time", "10m", "1m") + ); + } + + #[test] + fn same_failing_tests_twice_is_a_loop() { + let evs = [ + ev( + 0, + 0, + "edit", + json!({"path": "src/old.rs", "added": 50, "removed": 0}), + ), // before the first of the identical runs: not part of the loop + test_run(1, &["a::x", "a::y"]), + test_run(3, &["a::y", "a::x"]), + ev( + 4, + 4000, + "edit", + json!({"path": "src/token.rs", "added": 6, "removed": 2}), + ), + ev( + 5, + 5000, + "edit", + json!({"path": "src/token.rs", "added": 1, "removed": 1}), + ), + ev( + 6, + 6000, + "edit", + json!({"path": "src/mod.rs", "added": 1, "removed": 0}), + ), + test_run(7, &["a::x", "a::y"]), + ]; + let l = looping(&refs(&evs)).expect("loop"); + assert_eq!((l.runs, l.tests), (3, 2)); + assert_eq!( + l.file.as_deref(), + Some("src/token.rs"), + "edits before the loop do not count" + ); + } + + #[test] + fn different_or_fixed_failures_are_no_loop() { + // fix 1 changed which tests fail: progress, not a loop + let evs = [test_run(1, &["a::x", "a::y"]), test_run(2, &["a::x"])]; + assert_eq!(looping(&refs(&evs)), None); + // the last run passed + let evs = [ + test_run(1, &["a::x"]), + test_run(2, &["a::x"]), + test_run(3, &[]), + ]; + assert_eq!(looping(&refs(&evs)), None); + // only one run so far + assert_eq!(looping(&refs(&[test_run(1, &["a::x"])])), None); + assert_eq!(looping(&[]), None); + // a loop without edits has no file to blame + let evs = [test_run(1, &["a::x"]), test_run(2, &["a::x"])]; + assert_eq!(looping(&refs(&evs)).unwrap().file, None); + } +} diff --git a/src/checks.rs b/src/checks.rs new file mode 100644 index 0000000..7d50bad --- /dev/null +++ b/src/checks.rs @@ -0,0 +1,159 @@ +//! Acceptance checks (ORCHESTRATOR.md section 2): shell commands, pass = exit 0. A goal is done when every +//! check is green on main, so results on main are what the goal view shows; a session can also run its own +//! checks on its branch before merging (`run-acceptance` step) without touching the recorded result. + +use crate::db::{CheckRow, Db}; +use crate::run::{git, tail}; +use anyhow::Result; +use serde_json::json; +use std::path::Path; +use std::process::Command; + +/// Pseudo session id for goal-level events (check results on main). +pub const GOAL: &str = "goal"; + +pub struct Outcome { + pub check: CheckRow, + pub pass: bool, + pub exit: Option, + pub output: String, +} + +/// Runs the checks in `dir`. `owner` limits to one session's checks. `record` stores the result as the check's +/// status on main; it is only for runs that really are on main. +pub fn run(db: &Db, dir: &Path, owner: Option<&str>, record: bool) -> Result> { + let mut out = vec![]; + for c in db.checks()? { + if owner.is_some() && c.owner.as_deref() != owner { + continue; + } + let o = Command::new("sh") + .args(["-c", &format!("({}) 2>&1", c.cmd)]) + .current_dir(dir) + .output()?; + let (pass, exit) = (o.status.success(), o.status.code()); + let output = tail(&o.stdout, 2000); + if record { + db.set_check_result(c.id, pass)?; + } + let session = owner.unwrap_or(GOAL); + db.emit( + session, + "check", + json!({ + "name": c.name, "pass": pass, "exit": exit, + "where": if record { "main" } else { "branch" }, + "output": if pass { String::new() } else { output.clone() }, + }), + )?; + out.push(Outcome { + check: c, + pass, + exit, + output, + }); + } + Ok(out) +} + +/// All checks, recorded, in a clean detached worktree of the repo's HEAD (main after a merge). The +/// user's own checkout is never touched. +pub fn run_on_main(db: &Db, repo: &Path) -> Result> { + if db.checks()?.is_empty() { + return Ok(vec![]); + } + let tmp = repo.join(format!(".hx/main-check-{}", crate::state::now_ms())); + let lock_path = repo.join(".git/orch-worktree.lock"); + { + let _l = crate::lock::lock(&lock_path)?; // git races on its own locks + git( + repo, + &[ + "worktree", + "add", + "--detach", + &tmp.to_string_lossy(), + "HEAD", + ], + )?; + } + let res = run(db, &tmp, None, true); + let _l = crate::lock::lock(&lock_path)?; + let _ = git( + repo, + &["worktree", "remove", "--force", &tmp.to_string_lossy()], + ); + res +} + +#[cfg(test)] +mod tests { + use super::*; + + fn repo(tag: &str) -> (std::path::PathBuf, Db) { + let dir = std::env::temp_dir().join(format!("orch-checks-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + git(&dir, &["init", "-q", "-b", "main"]).unwrap(); + std::fs::write(dir.join("present.txt"), "x").unwrap(); + git(&dir, &["add", "-A"]).unwrap(); + git(&dir, &["commit", "-qm", "init"]).unwrap(); + let db = Db::open(&dir.join(".hx/orch.db")).unwrap(); + (dir, db) + } + + #[test] + fn main_run_records_in_a_clean_worktree_and_leaves_the_checkout_alone() { + let (dir, db) = repo("main"); + db.add_check("file present", "test -f present.txt", None) + .unwrap(); + db.add_check("untracked junk absent", "test ! -f junk.txt", Some("s1")) + .unwrap(); + db.add_check("always red", "echo nope; exit 3", None) + .unwrap(); + // junk in the user's checkout must not be visible to the checks: they run in a clean worktree + std::fs::write(dir.join("junk.txt"), "dirty").unwrap(); + let r = run_on_main(&db, &dir).unwrap(); + assert_eq!( + r.iter().map(|o| o.pass).collect::>(), + [true, true, false] + ); + assert_eq!(r[2].exit, Some(3)); + let rows = db.checks().unwrap(); + let st: Vec<_> = rows + .iter() + .map(|c| c.last_status.as_deref().unwrap()) + .collect(); + assert_eq!(st, ["pass", "pass", "fail"]); + assert!(rows[0].last_run_at.is_some()); + assert!(dir.join("junk.txt").exists(), "checkout untouched"); + let leftovers: Vec<_> = std::fs::read_dir(dir.join(".hx")) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_string_lossy().starts_with("main-check")) + .collect(); + assert!(leftovers.is_empty(), "temporary worktree removed"); + let ev = db.events(Some(GOAL), 0).unwrap(); + assert_eq!(ev.len(), 3); + assert_eq!(ev[2].payload["output"], "nope\n"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn branch_run_filters_by_owner_and_does_not_record() { + let (dir, db) = repo("branch"); + db.add_check("mine", "true", Some("s1")).unwrap(); + db.add_check("theirs", "false", Some("s2")).unwrap(); + db.add_check("unowned", "false", None).unwrap(); + let r = run(&db, &dir, Some("s1"), false).unwrap(); + assert_eq!(r.len(), 1); + assert!(r[0].pass); + assert!(db.checks().unwrap().iter().all(|c| c.last_status.is_none())); + assert_eq!( + db.events(Some("s1"), 0).unwrap()[0].payload["where"], + "branch" + ); + assert_eq!(db.events(Some(GOAL), 0).unwrap().len(), 0); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/db.rs b/src/db.rs new file mode 100644 index 0000000..639eac7 --- /dev/null +++ b/src/db.rs @@ -0,0 +1,632 @@ +//! Per-goal SQLite file (`.hx/orch.db`, ORCHESTRATOR.md section 6). The `events` table is append-only; every +//! view is rebuilt from it plus the machine files. Each thread opens its own connection (WAL + busy timeout). +// shortcut: checks/decisions tables exist but have no accessors yet; milestones 7 and 8 add them. +#![allow(dead_code)] + +use anyhow::{Context, Result}; +use rusqlite::{Connection, OptionalExtension, params}; +use serde_json::Value; +use std::path::Path; + +const SCHEMA: &str = " +create table if not exists goal(text text not null, created_at integer not null); +create table if not exists checks( + id integer primary key, name text not null, cmd text not null, owner_session text, + last_status text, last_run_at integer); +create table if not exists tasks( + id text primary key, name text not null, subtitle text not null default '', + machine text not null, depends_on text not null default '[]'); +create table if not exists sessions( + id text primary key, task_id text not null, branch text not null, worktree text not null, + pid integer, current_state text not null default '', status text not null default 'queued'); +create table if not exists events( + id integer primary key autoincrement, session_id text not null, at integer not null, + kind text not null, payload text not null default '{}'); +create index if not exists events_session on events(session_id, id); +create table if not exists decisions( + session_id text not null, text text not null, state text not null, at integer not null, + vetoed integer not null default 0); +create table if not exists commands( + id integer primary key autoincrement, session_id text not null, kind text not null, + payload text not null default '{}', at integer not null, done integer not null default 0); +create table if not exists merge_queue( + ticket integer primary key autoincrement, session_id text not null unique); +create table if not exists needs( + id integer primary key autoincrement, session_id text not null, kind text not null, + payload text not null default '{}', created_at integer not null, answer text, + done integer not null default 0); +"; + +pub struct Db { + conn: Connection, + path: std::path::PathBuf, +} + +/// An acceptance check: a shell command, pass = exit 0. `last_status` is the result on main. +#[derive(Clone, Debug, PartialEq)] +pub struct CheckRow { + pub id: i64, + pub name: String, + pub cmd: String, + pub owner: Option, + /// pass | fail, None until the first run + pub last_status: Option, + pub last_run_at: Option, +} + +/// A choice an agent reported with `hx/decision`. +#[derive(Clone, Debug, PartialEq)] +pub struct DecisionRow { + pub id: i64, + pub session: String, + pub text: String, + pub state: String, + pub at: u64, + pub vetoed: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Event { + pub id: i64, + pub session: String, + /// Milliseconds since the epoch. + pub at: u64, + pub kind: String, + pub payload: Value, +} + +/// One item of the Needs-you queue: a `human` step, a permission request or an agent question. The runner +/// writes it and waits; the TUI (or anything else with the database) writes the answer. +#[derive(Clone, Debug, PartialEq)] +pub struct NeedRow { + pub id: i64, + pub session: String, + /// review | permission | input + pub kind: String, + pub payload: Value, + /// Milliseconds since the epoch. + pub at: u64, + pub answer: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Task { + pub id: String, + pub name: String, + pub subtitle: String, + pub machine: String, + pub depends_on: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Session { + pub id: String, + pub task_id: String, + pub branch: String, + pub worktree: String, + pub pid: Option, + pub state: String, + /// queued, running, or the machine's `end` value (merged, escalated, aborted) or `failed`. + pub status: String, +} + +impl Db { + pub fn open(path: &Path) -> Result { + if let Some(d) = path.parent() { + std::fs::create_dir_all(d)?; + } + let conn = Connection::open(path).with_context(|| path.display().to_string())?; + conn.busy_timeout(std::time::Duration::from_secs(5))?; + conn.pragma_update(None, "journal_mode", "WAL")?; + conn.execute_batch(SCHEMA)?; + Ok(Self { + conn, + path: path.to_path_buf(), + }) + } + + /// Where this database lives; exported to machine steps as `ORCH_DB`. + pub fn path(&self) -> &Path { + &self.path + } + + pub fn add_check(&self, name: &str, cmd: &str, owner: Option<&str>) -> Result { + self.conn.execute( + "insert into checks(name, cmd, owner_session) values (?1, ?2, ?3)", + params![name, cmd, owner], + )?; + Ok(self.conn.last_insert_rowid()) + } + + pub fn checks(&self) -> Result> { + let mut q = self.conn.prepare( + "select id, name, cmd, owner_session, last_status, last_run_at from checks order by id", + )?; + let rows = q.query_map([], |r| { + Ok(CheckRow { + id: r.get(0)?, + name: r.get(1)?, + cmd: r.get(2)?, + owner: r.get(3)?, + last_status: r.get(4)?, + last_run_at: r.get::<_, Option>(5)?.map(|v| v as u64), + }) + })?; + Ok(rows.collect::>()?) + } + + pub fn set_check_result(&self, id: i64, pass: bool) -> Result<()> { + self.conn.execute( + "update checks set last_status = ?2, last_run_at = ?3 where id = ?1", + params![ + id, + if pass { "pass" } else { "fail" }, + crate::state::now_ms() as i64 + ], + )?; + Ok(()) + } + + pub fn decisions(&self) -> Result> { + let mut q = self.conn.prepare( + "select rowid, session_id, text, state, at, vetoed from decisions order by rowid", + )?; + let rows = q.query_map([], |r| { + Ok(DecisionRow { + id: r.get(0)?, + session: r.get(1)?, + text: r.get(2)?, + state: r.get(3)?, + at: r.get::<_, i64>(4)? as u64, + vetoed: r.get::<_, i64>(5)? != 0, + }) + })?; + Ok(rows.collect::>()?) + } + + /// Joins the merge queue (once) and returns the ticket; lower tickets merge first. + pub fn queue_join(&self, session: &str) -> Result { + self.conn.execute( + "insert or ignore into merge_queue(session_id) values (?1)", + [session], + )?; + Ok(self.conn.query_row( + "select ticket from merge_queue where session_id = ?1", + [session], + |r| r.get(0), + )?) + } + + /// The session at the head of the merge queue. + pub fn queue_head(&self) -> Result> { + Ok(self + .conn + .query_row( + "select session_id from merge_queue order by ticket limit 1", + [], + |r| r.get(0), + ) + .optional()?) + } + + /// 1 = head of the queue. + pub fn queue_position(&self, session: &str) -> Result { + let n: i64 = self.conn.query_row( + "select count(*) from merge_queue where ticket <= + (select ticket from merge_queue where session_id = ?1)", + [session], + |r| r.get(0), + )?; + Ok(n as usize) + } + + pub fn queue_leave(&self, session: &str) -> Result<()> { + self.conn + .execute("delete from merge_queue where session_id = ?1", [session])?; + Ok(()) + } + + /// A command for a running session (`message`, `interrupt`, `goto`, `abort`, `veto`). The runner, which may be + /// another process, picks it up the next time it polls. + pub fn add_command(&self, session: &str, kind: &str, payload: &Value) -> Result { + self.conn.execute( + "insert into commands(session_id, kind, payload, at) values (?1, ?2, ?3, ?4)", + params![ + session, + kind, + payload.to_string(), + crate::state::now_ms() as i64 + ], + )?; + Ok(self.conn.last_insert_rowid()) + } + + /// Takes the session's unprocessed commands, oldest first, and marks them processed. + pub fn take_commands(&self, session: &str) -> Result> { + let mut q = self.conn.prepare( + "select id, kind, payload from commands where session_id = ?1 and done = 0 order by id", + )?; + let rows: Vec<(i64, String, String)> = q + .query_map([session], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))? + .collect::>()?; + for (id, ..) in &rows { + self.conn + .execute("update commands set done = 1 where id = ?1", [id])?; + } + Ok(rows + .into_iter() + .map(|(_, k, p)| (k, serde_json::from_str(&p).unwrap_or(Value::Null))) + .collect()) + } + + /// Marks a decision as vetoed; false if it does not exist or was already vetoed. + pub fn veto_decision(&self, id: i64) -> Result { + let n = self.conn.execute( + "update decisions set vetoed = 1 where rowid = ?1 and vetoed = 0", + [id], + )?; + Ok(n == 1) + } + + pub fn set_goal(&self, text: &str) -> Result<()> { + self.conn.execute("delete from goal", [])?; + self.conn.execute( + "insert into goal(text, created_at) values (?1, ?2)", + params![text, crate::state::now() as i64], + )?; + Ok(()) + } + + pub fn goal(&self) -> Result> { + Ok(self + .conn + .query_row("select text from goal limit 1", [], |r| r.get(0)) + .optional()?) + } + + /// Next free session id: s1, s2, ... + pub fn next_session_id(&self) -> Result { + let n: i64 = self.conn.query_row( + "select coalesce(max(cast(substr(id, 2) as integer)), 0) from sessions", + [], + |r| r.get(0), + )?; + Ok(format!("s{}", n + 1)) + } + + pub fn add_task(&self, t: &Task) -> Result<()> { + self.conn.execute( + "insert into tasks(id, name, subtitle, machine, depends_on) values (?1, ?2, ?3, ?4, ?5)", + params![ + t.id, + t.name, + t.subtitle, + t.machine, + serde_json::to_string(&t.depends_on)? + ], + )?; + Ok(()) + } + + pub fn tasks(&self) -> Result> { + let mut q = self.conn.prepare( + "select id, name, subtitle, machine, depends_on from tasks order by cast(substr(id, 2) as integer), id", + )?; + let rows = q.query_map([], |r| { + let deps: String = r.get(4)?; + Ok(Task { + id: r.get(0)?, + name: r.get(1)?, + subtitle: r.get(2)?, + machine: r.get(3)?, + depends_on: serde_json::from_str(&deps).unwrap_or_default(), + }) + })?; + Ok(rows.collect::>()?) + } + + pub fn add_session(&self, s: &Session) -> Result<()> { + self.conn.execute( + "insert into sessions(id, task_id, branch, worktree, pid, current_state, status) values (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![s.id, s.task_id, s.branch, s.worktree, s.pid, s.state, s.status], + )?; + Ok(()) + } + + pub fn session(&self, id: &str) -> Result> { + Ok(self + .conn + .query_row( + "select id, task_id, branch, worktree, pid, current_state, status from sessions where id = ?1", + [id], + session_row, + ) + .optional()?) + } + + pub fn sessions(&self) -> Result> { + let mut q = self.conn.prepare( + "select id, task_id, branch, worktree, pid, current_state, status from sessions order by cast(substr(id, 2) as integer), id", + )?; + Ok(q.query_map([], session_row)? + .collect::>()?) + } + + pub fn set_session(&self, id: &str, state: &str, status: &str) -> Result<()> { + self.conn.execute( + "update sessions set current_state = ?2, status = ?3 where id = ?1", + params![id, state, status], + )?; + Ok(()) + } + + pub fn set_pid(&self, id: &str, pid: Option) -> Result<()> { + self.conn.execute( + "update sessions set pid = ?2 where id = ?1", + params![id, pid], + )?; + Ok(()) + } + + /// Append one event; returns its id. + pub fn emit(&self, session: &str, kind: &str, payload: Value) -> Result { + self.conn.execute( + "insert into events(session_id, at, kind, payload) values (?1, ?2, ?3, ?4)", + params![ + session, + crate::state::now_ms() as i64, + kind, + payload.to_string() + ], + )?; + Ok(self.conn.last_insert_rowid()) + } + + pub fn add_need(&self, session: &str, kind: &str, payload: &Value) -> Result { + self.conn.execute( + "insert into needs(session_id, kind, payload, created_at) values (?1, ?2, ?3, ?4)", + params![ + session, + kind, + payload.to_string(), + crate::state::now_ms() as i64 + ], + )?; + Ok(self.conn.last_insert_rowid()) + } + + const NEED_COLS: &'static str = "id, session_id, kind, payload, created_at, answer"; + + /// Items still waiting for an answer, oldest first. + pub fn pending_needs(&self) -> Result> { + let mut q = self.conn.prepare(&format!( + "select {} from needs where done = 0 and answer is null order by id", + Self::NEED_COLS + ))?; + Ok(q.query_map([], need_row)? + .collect::>()?) + } + + /// An unfinished item of this session with this `payload.key`: after an orchestrator restart the same + /// question must not be asked twice. + pub fn open_need(&self, session: &str, kind: &str, key: &str) -> Result> { + Ok(self + .conn + .query_row( + &format!( + "select {} from needs where session_id = ?1 and kind = ?2 and done = 0 + and json_extract(payload, '$.key') = ?3 order by id desc limit 1", + Self::NEED_COLS + ), + params![session, kind, key], + need_row, + ) + .optional()?) + } + + pub fn need_answer(&self, id: i64) -> Result> { + Ok(self + .conn + .query_row("select answer from needs where id = ?1", [id], |r| r.get(0))?) + } + + /// Answers an item (first answer wins) and returns false if it was already answered. + pub fn answer_need(&self, id: i64, answer: &str) -> Result { + let n = self.conn.execute( + "update needs set answer = ?2 where id = ?1 and answer is null", + params![id, answer], + )?; + Ok(n == 1) + } + + /// The runner took the answer; the item is history now. + pub fn finish_need(&self, id: i64) -> Result<()> { + self.conn + .execute("update needs set done = 1 where id = ?1", [id])?; + Ok(()) + } + + /// A choice an agent reported with `hx/decision`; the goal view lists them for veto. + pub fn add_decision(&self, session: &str, text: &str, state: &str) -> Result<()> { + self.conn.execute( + "insert into decisions(session_id, text, state, at) values (?1, ?2, ?3, ?4)", + params![session, text, state, crate::state::now_ms() as i64], + )?; + Ok(()) + } + + pub fn decision_count(&self, session: &str) -> Result { + let n: i64 = self.conn.query_row( + "select count(*) from decisions where session_id = ?1", + [session], + |r| r.get(0), + )?; + Ok(n as usize) + } + + /// Events oldest first, optionally one session, only those after `after` (event id). + pub fn events(&self, session: Option<&str>, after: i64) -> Result> { + let mut q = self.conn.prepare( + "select id, session_id, at, kind, payload from events + where id > ?1 and (?2 is null or session_id = ?2) order by id", + )?; + let rows = q.query_map(params![after, session], |r| { + let p: String = r.get(4)?; + Ok(Event { + id: r.get(0)?, + session: r.get(1)?, + at: r.get::<_, i64>(2)? as u64, + kind: r.get(3)?, + payload: serde_json::from_str(&p).unwrap_or(Value::Null), + }) + })?; + Ok(rows.collect::>()?) + } + + /// How often `catch` fired in `state` of this session (rebuilt from events, so it survives restarts). + pub fn catch_count(&self, session: &str, state: &str, catch: &str) -> Result { + let n: i64 = self.conn.query_row( + "select count(*) from events where session_id = ?1 and kind = 'catch' + and json_extract(payload, '$.state') = ?2 and json_extract(payload, '$.catch') = ?3", + params![session, state, catch], + |r| r.get(0), + )?; + Ok(n as u32) + } +} + +fn need_row(r: &rusqlite::Row) -> rusqlite::Result { + let p: String = r.get(3)?; + Ok(NeedRow { + id: r.get(0)?, + session: r.get(1)?, + kind: r.get(2)?, + payload: serde_json::from_str(&p).unwrap_or(Value::Null), + at: r.get::<_, i64>(4)? as u64, + answer: r.get(5)?, + }) +} + +fn session_row(r: &rusqlite::Row) -> rusqlite::Result { + Ok(Session { + id: r.get(0)?, + task_id: r.get(1)?, + branch: r.get(2)?, + worktree: r.get(3)?, + pid: r.get(4)?, + state: r.get(5)?, + status: r.get(6)?, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + pub fn temp_db(tag: &str) -> (Db, std::path::PathBuf) { + let d = std::env::temp_dir().join(format!("orch-db-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + (Db::open(&d.join("orch.db")).unwrap(), d) + } + + #[test] + fn roundtrip() { + let (db, dir) = temp_db("rt"); + assert_eq!(db.goal().unwrap(), None); + db.set_goal("ship it").unwrap(); + assert_eq!(db.goal().unwrap().as_deref(), Some("ship it")); + assert_eq!(db.next_session_id().unwrap(), "s1"); + let s = Session { + id: "s1".into(), + task_id: "s1".into(), + branch: "hx/s1-x".into(), + worktree: "/w".into(), + pid: None, + state: String::new(), + status: "queued".into(), + }; + db.add_session(&s).unwrap(); + assert_eq!(db.next_session_id().unwrap(), "s2"); + db.set_session("s1", "plan", "running").unwrap(); + assert_eq!(db.session("s1").unwrap().unwrap().state, "plan"); + db.emit("s1", "catch", json!({"state": "test", "catch": "T"})) + .unwrap(); + let last = db.emit("s1", "state", json!({"to": "code"})).unwrap(); + assert_eq!(db.catch_count("s1", "test", "T").unwrap(), 1); + assert_eq!(db.catch_count("s1", "test", "U").unwrap(), 0); + assert_eq!(db.events(Some("s1"), 0).unwrap().len(), 2); + assert_eq!(db.events(None, last - 1).unwrap().len(), 1); + assert!(db.events(Some("s9"), 0).unwrap().is_empty()); + // checks keep their last result; decisions list in insertion order + let c = db.add_check("build", "true", Some("s1")).unwrap(); + assert_eq!(db.checks().unwrap()[0].last_status, None); + db.set_check_result(c, true).unwrap(); + let ch = &db.checks().unwrap()[0]; + assert_eq!( + (ch.last_status.as_deref(), ch.owner.as_deref()), + (Some("pass"), Some("s1")) + ); + db.add_decision("s1", "use a bucket", "plan").unwrap(); + assert_eq!(db.decisions().unwrap()[0].text, "use a bucket"); + // merge queue is first come, first served, and joining twice keeps the place + assert_eq!(db.queue_head().unwrap(), None); + let (t1, t2) = (db.queue_join("s1").unwrap(), db.queue_join("s2").unwrap()); + assert!(t1 < t2); + assert_eq!(db.queue_join("s1").unwrap(), t1); + assert_eq!(db.queue_head().unwrap().as_deref(), Some("s1")); + assert_eq!( + ( + db.queue_position("s1").unwrap(), + db.queue_position("s2").unwrap() + ), + (1, 2) + ); + db.queue_leave("s1").unwrap(); + assert_eq!(db.queue_head().unwrap().as_deref(), Some("s2")); + db.queue_leave("s2").unwrap(); + // commands: taken once, in order, per session + db.add_command("s1", "message", &json!({"text": "hi"})) + .unwrap(); + db.add_command("s1", "interrupt", &json!({})).unwrap(); + db.add_command("s2", "abort", &json!({})).unwrap(); + let cmds = db.take_commands("s1").unwrap(); + assert_eq!( + cmds.iter().map(|c| c.0.as_str()).collect::>(), + ["message", "interrupt"] + ); + assert_eq!(cmds[0].1["text"], "hi"); + assert!(db.take_commands("s1").unwrap().is_empty()); + assert_eq!(db.take_commands("s2").unwrap().len(), 1); + // a decision can be vetoed once + let d = db.decisions().unwrap()[0].id; + assert!(db.veto_decision(d).unwrap()); + assert!(!db.veto_decision(d).unwrap()); + assert!(db.decisions().unwrap()[0].vetoed); + // needs queue: pending until answered, the first answer wins, finished items disappear + let n = db + .add_need("s1", "review", &json!({"key": "review/ok", "title": "t"})) + .unwrap(); + assert_eq!(db.pending_needs().unwrap().len(), 1); + assert_eq!( + db.open_need("s1", "review", "review/ok") + .unwrap() + .unwrap() + .id, + n + ); + assert!(db.open_need("s1", "review", "other").unwrap().is_none()); + assert_eq!(db.need_answer(n).unwrap(), None); + assert!(db.answer_need(n, "approve").unwrap()); + assert!(!db.answer_need(n, "changes: x").unwrap()); + assert_eq!(db.need_answer(n).unwrap().as_deref(), Some("approve")); + assert!(db.pending_needs().unwrap().is_empty()); + db.finish_need(n).unwrap(); + assert!(db.open_need("s1", "review", "review/ok").unwrap().is_none()); + // reopening sees the same data: restart restores views + drop(db); + let db = Db::open(&dir.join("orch.db")).unwrap(); + assert_eq!(db.sessions().unwrap().len(), 1); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/detail.rs b/src/detail.rs new file mode 100644 index 0000000..287a3ca --- /dev/null +++ b/src/detail.rs @@ -0,0 +1,780 @@ +//! View model of the session detail screen (ORCHESTRATOR.md 7.2, `Session.dc.html`): the machine rendered as +//! text with a live column, the path taken, the last test run, what the agent does now, changed files, budgets. +//! Pure, like `view.rs`: events and the machine file in, lines out. + +use crate::budget; +use crate::db::Event; +use crate::machine::{Kind, RunOn}; +use crate::view::{Input, Status}; +use std::collections::HashMap; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum LineKind { + Header, + Step, + Catch, + End, + Only, + Blank, +} + +/// Which block color a line gets: the current state is highlighted, failed ones are red. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Block { + Done, + Cur, + Fail, + Todo, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct MLine { + pub kind: LineKind, + pub text: String, + /// ` → target` of a catch line, drawn in the state color. + pub to: String, + pub exec: Option, + pub sets: String, + pub live: String, + pub block: Block, + /// A catch that fired: its live text is drawn bold red. + pub hit: bool, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct PathStep { + pub name: String, + pub failed: bool, + pub current: bool, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct FailView { + pub name: String, + pub message: String, + pub location: String, + /// `failed in fix 1 too`, or empty. + pub repeats: String, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct TestRun { + pub step: String, + pub at_ms: u64, + pub passed: u32, + pub failed: u32, + pub skipped: u32, + pub secs: f64, + pub failures: Vec, +} + +#[derive(Clone, PartialEq, Debug, Default)] +pub struct Now { + /// `agent`, `computer` or empty. + pub who: String, + pub line: String, + pub intent: String, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct FileChange { + pub path: String, + pub added: u32, + pub removed: u32, +} + +#[derive(Clone, PartialEq, Debug, Default)] +pub struct Budget { + /// (used, limit) context tokens. + pub ctx: Option<(u64, u64)>, + /// (fix count, max) of the busiest retry loop. + pub retries: Option<(u32, u32)>, + /// Time spent working, not counting time waiting for the user. + pub wall_secs: u64, + pub cost: f64, + /// Limits from the machine's `[budget]`; None = no cap. + pub wall_cap: Option, + pub cost_cap: Option, + pub compact_at: Option, +} + +/// The loop detector fired: the last test runs failed on the same tests. +#[derive(Clone, PartialEq, Debug)] +pub struct LoopView { + pub runs: usize, + pub tests: usize, + /// The file the agent keeps editing. + pub file: Option, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct Detail { + pub id: String, + pub task: String, + pub status: Status, + pub branch: String, + pub worktree: String, + pub pid: Option, + pub machine_file: String, + pub on_abort: Option, + pub on_budget: Option, + pub lines: Vec, + pub path: Vec, + pub test: Option, + pub now: Now, + pub files: Vec, + pub budget: Budget, + pub looping: Option, + /// Every state of the machine, for the force-state key. + pub states: Vec, + /// The start state, where `re-plan` goes. + pub start: String, +} + +/// `6.2s`, `0m59s`, `4m10s`. +pub fn dur(ms: u64) -> String { + if ms < 10_000 { + format!("{:.1}s", ms as f64 / 1000.0) + } else { + let s = ms / 1000; + format!("{}m{:02}s", s / 60, s % 60) + } +} + +/// One stay in a state: from the `state` event to the next one. +struct Visit<'a> { + state: &'a str, + /// (step, ms, ok) + steps: Vec<(&'a str, u64, bool)>, + caught: Option<&'a str>, + test: Option<(u64, u64)>, +} + +fn s<'a>(v: &'a serde_json::Value, k: &str) -> &'a str { + v[k].as_str().unwrap_or_default() +} + +pub fn build(i: &Input, id: &str) -> Option { + let sess = i.sessions.iter().find(|x| x.id == id)?; + let task = i.tasks.iter().find(|t| t.id == sess.task_id)?; + let machine = i.machines.get(&task.machine)?; + let overview = crate::view::build(i); + let status = overview.rows.iter().find(|r| r.id == id)?.status; + let evs: Vec<&Event> = i.events.iter().filter(|e| e.session == id).collect(); + + let mut visits: Vec = vec![]; + for e in &evs { + let p = &e.payload; + match e.kind.as_str() { + "state" => visits.push(Visit { + state: s(p, "to"), + steps: vec![], + caught: None, + test: None, + }), + "step" => { + if let Some(v) = visits.last_mut() { + v.steps + .push((s(p, "step"), p["ms"].as_u64().unwrap_or(0), p["ok"] == true)); + } + } + "catch" => { + if let Some(v) = visits.last_mut() { + v.caught = Some(s(p, "catch")); + } + } + "test" => { + if let Some(v) = visits.last_mut() { + v.test = Some(( + p["passed"].as_u64().unwrap_or(0), + p["failed"].as_u64().unwrap_or(0), + )); + } + } + _ => {} + } + } + let active = matches!(sess.status.as_str(), "running" | "waiting"); + let cur_state = if active { + visits.last().map(|v| v.state) + } else { + None + }; + let last_at = evs.last().map_or(0, |e| e.at); + let hits = |state: &str, catch: &str| { + evs.iter() + .filter(|e| { + e.kind == "catch" + && s(&e.payload, "state") == state + && s(&e.payload, "catch") == catch + }) + .count() as u32 + }; + + let mut lines: Vec = vec![]; + let mut running_step: Option<(&str, RunOn, Option<&str>)> = None; + let line = |kind, text: String| MLine { + kind, + text, + to: String::new(), + exec: None, + sets: String::new(), + live: String::new(), + block: Block::Todo, + hit: false, + }; + // main flow first, then the only_on states, like the machine file reads + let ordered = machine + .states + .iter() + .filter(|st| st.only_on.is_empty()) + .chain(machine.states.iter().filter(|st| !st.only_on.is_empty())); + for st in ordered { + let mine: Vec<&Visit> = visits.iter().filter(|v| v.state == st.name).collect(); + let last = mine.last(); + let is_cur = cur_state == Some(st.name.as_str()); + let block = if is_cur { + Block::Cur + } else if let Some(v) = last { + let died_here = + sess.status == "failed" && visits.last().is_some_and(|l| l.state == st.name); + if v.caught.is_some() || died_here { + Block::Fail + } else { + Block::Done + } + } else { + Block::Todo + }; + let only = !st.only_on.is_empty(); + let bar = if only { "│ " } else { "" }; + if !lines.is_empty() { + lines.push(line(LineKind::Blank, String::new())); + } + if only { + let when = st.only_on.join(", ").replace(" x", " ×"); + lines.push(line(LineKind::Only, format!("│ only on {when}"))); + } + let tag = match st.kind { + Kind::Start => " · start", + Kind::Gate => " · gate", + Kind::Exit => " · exit", + Kind::Abort => " · abort", + Kind::Normal => "", + }; + let mut h = line(LineKind::Header, format!("{bar}{}{tag}", st.name)); + h.block = block; + h.live = match (block, last) { + (Block::Cur, _) if mine.len() > 1 => format!("▶ fix {}", mine.len() - 1), + (Block::Cur, _) => "▶".into(), + (Block::Fail, Some(v)) => match v.test { + Some((p, f)) => format!("✗ {p}/{}", p + f), + None => "✗".into(), + }, + (Block::Done, Some(v)) => { + let total: u64 = v.steps.iter().map(|x| x.1).sum(); + let times = if mine.len() > 1 { + format!(" ×{}", mine.len()) + } else { + String::new() + }; + format!("✓ {}{times}", dur(total)) + } + _ => String::new(), + }; + lines.push(h); + // the step that runs right now: the first one of the current visit without a result + let done_in_visit = if is_cur { + last.map_or(0, |v| v.steps.len()) + } else { + 0 + }; + for (n, step) in st.steps.iter().enumerate() { + let mut l = line(LineKind::Step, format!("{bar} {}", step.name)); + l.exec = Some(step.run); + l.sets = step + .sets + .as_ref() + .map(|x| format!("■ {x}")) + .unwrap_or_default(); + l.block = block; + let rec = last.and_then(|v| v.steps.iter().find(|x| x.0 == step.name)); + l.live = match rec { + Some(&(_, ms, true)) if !is_cur || n < done_in_visit => format!("✓ {}", dur(ms)), + Some(&(_, ms, false)) if !is_cur || n < done_in_visit => format!("✗ {}", dur(ms)), + _ if is_cur && n == done_in_visit => { + running_step = Some((&step.name, step.run, step.cmd.as_deref())); + format!("▶ {}", dur(i.now_ms.saturating_sub(last_at))) + } + _ => String::new(), + }; + lines.push(l); + } + for (c, target) in &st.catch { + let n = hits(&st.name, c); + let mut l = line(LineKind::Catch, format!("{bar} catch {c}")); + l.to = format!(" → {target}"); + l.block = block; + if n > 0 { + l.live = format!("hit {n}×"); + l.hit = true; + } + lines.push(l); + if let Some(r) = st.retry.get(c) { + let mut l = line(LineKind::Catch, format!("{bar} catch {c} ×{}", r.max)); + l.to = format!(" → {}", r.then); + l.block = if n + 1 >= r.max { Block::Fail } else { block }; + if n + 1 == r.max { + l.live = "next".into(); + } + lines.push(l); + } + } + if let (true, Some(end)) = (matches!(st.kind, Kind::Exit | Kind::Abort), &st.end) { + let mut l = line(LineKind::End, format!("{bar} end: {end}")); + l.block = block; + lines.push(l); + } + } + + let mut path: Vec = visits + .iter() + .map(|v| PathStep { + name: v.state.to_string(), + failed: v.caught.is_some(), + current: false, + }) + .collect(); + if let Some(l) = path.last_mut() { + if cur_state.is_some() { + l.current = true; + } else if sess.status == "failed" { + l.failed = true; + } + } + + // test runs, oldest first; failures remember in which earlier runs they failed too + let runs: Vec<&&Event> = evs.iter().filter(|e| e.kind == "test").collect(); + let test = runs.last().map(|e| { + let p = &e.payload; + let mut earlier: HashMap<&str, Vec> = HashMap::new(); + for (n, r) in runs[..runs.len() - 1].iter().enumerate() { + for f in r.payload["failures"].as_array().into_iter().flatten() { + earlier.entry(s(f, "name")).or_default().push(n); + } + } + let failures = p["failures"] + .as_array() + .into_iter() + .flatten() + .map(|f| { + let name = s(f, "name"); + let repeats = match earlier.get(name) { + Some(v) if !v.is_empty() => { + let which: Vec = v + .iter() + .map(|&n| { + if n == 0 { + "the first run".into() + } else { + format!("fix {n}") + } + }) + .collect(); + format!("failed in {} too", which.join(", ")) + } + _ => String::new(), + }; + FailView { + name: name.into(), + message: s(f, "message").into(), + location: s(f, "location").into(), + repeats, + } + }) + .collect(); + TestRun { + step: s(p, "step").into(), + at_ms: e.at, + passed: p["passed"].as_u64().unwrap_or(0) as u32, + failed: p["failed"].as_u64().unwrap_or(0) as u32, + skipped: p["skipped"].as_u64().unwrap_or(0) as u32, + secs: p["secs"].as_f64().unwrap_or(0.0), + failures, + } + }); + + let mut now = Now::default(); + if let Some((name, run, cmd)) = running_step { + match run { + RunOn::Agent => { + now.who = "agent".into(); + now.line = evs + .iter() + .rev() + .find_map(|e| match e.kind.as_str() { + "tool" => Some(s(&e.payload, "title").to_string()), + "edit" => Some(format!( + "edit {} +{} −{}", + s(&e.payload, "path"), + e.payload["added"], + e.payload["removed"] + )), + _ => None, + }) + .unwrap_or_else(|| name.to_string()); + } + RunOn::Computer => { + now.who = "computer".into(); + now.line = cmd.unwrap_or(name).to_string(); + } + RunOn::Human => { + now.who = "human".into(); + now.line = name.to_string(); + } + } + } + now.intent = evs + .iter() + .rev() + .find(|e| e.kind == "intent") + .map(|e| s(&e.payload, "text").to_string()) + .unwrap_or_default(); + + let mut files: Vec = vec![]; + for e in evs.iter().filter(|e| e.kind == "edit") { + let (path, a, r) = ( + s(&e.payload, "path"), + e.payload["added"].as_u64().unwrap_or(0) as u32, + e.payload["removed"].as_u64().unwrap_or(0) as u32, + ); + match files.iter_mut().find(|f| f.path == path) { + Some(f) => { + f.added += a; + f.removed += r; + } + None => files.push(FileChange { + path: path.into(), + added: a, + removed: r, + }), + } + } + + let usage = evs.iter().rev().find(|e| e.kind == "usage"); + let retries = machine + .states + .iter() + .flat_map(|st| { + st.retry + .iter() + .map(move |(c, r)| (st.name.as_str(), c.as_str(), r.max)) + }) + .map(|(st, c, max)| (hits(st, c), max)) + .filter(|&(n, _)| n > 0) + .max_by_key(|&(n, _)| n); + let budget = Budget { + ctx: usage.map(|e| { + ( + e.payload["ctx_used"].as_u64().unwrap_or(0), + e.payload["ctx_limit"].as_u64().unwrap_or(0), + ) + }), + retries, + wall_secs: budget::active_secs(&evs, i.now_ms), + cost: budget::cost(&evs), + wall_cap: machine.budget.wall_secs, + cost_cap: machine.budget.cost, + compact_at: machine.budget.compact_at, + }; + // a loop only matters while the session still runs + let looping = if active { + budget::looping(&evs).map(|l| LoopView { + runs: l.runs, + tests: l.tests, + file: l.file, + }) + } else { + None + }; + + Some(Detail { + id: id.into(), + task: task.name.clone(), + status, + branch: sess.branch.clone(), + worktree: sess.worktree.clone(), + pid: sess.pid, + machine_file: format!("{}.toml", machine.name), + on_abort: machine.on_abort.clone(), + on_budget: machine.on_budget.clone(), + lines, + path, + test, + now, + files, + budget, + looping, + states: machine.states.iter().map(|s| s.name.clone()).collect(), + start: machine.start().name.clone(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::{Session, Task}; + use crate::machine::Machine; + use serde_json::json; + + fn ev(id: i64, kind: &str, payload: serde_json::Value) -> Event { + Event { + id, + session: "s2".into(), + at: 1000 * id as u64, + kind: kind.into(), + payload, + } + } + + fn state(id: i64, from: &str, to: &str) -> Event { + ev(id, "state", json!({"from": from, "to": to})) + } + + fn step(id: i64, st: &str, name: &str, ms: u64, ok: bool) -> Event { + ev( + id, + "step", + json!({"state": st, "step": name, "ms": ms, "ok": ok}), + ) + } + + fn test_run(id: i64, names: &[&str]) -> Event { + let failures: Vec<_> = names + .iter() + .map(|n| json!({"name": n, "message": format!("{n} broke"), "location": "src/a.rs:1"})) + .collect(); + ev( + id, + "test", + json!({"state": "test", "step": "cargo test", "passed": 39, "failed": names.len(), "skipped": 0, "secs": 6.2, "failures": failures}), + ) + } + + fn catch(id: i64) -> Event { + ev( + id, + "catch", + json!({"state": "test", "catch": "TestsFailed"}), + ) + } + + /// plan, code, build, test (2 failing) -> code; again; now in code for the third time. + fn scenario() -> Vec { + vec![ + state(1, "", "plan"), + step(2, "plan", "read-goal", 200, true), + step(3, "plan", "draft-plan", 250_000, true), + state(4, "plan", "code"), + step(5, "code", "edit", 59_000, true), + state(6, "code", "build"), + step(7, "build", "cargo build", 38_000, true), + state(8, "build", "test"), + test_run(9, &["a::one", "a::two"]), + step(10, "test", "cargo test", 6_200, false), + catch(11), + state(12, "test", "code"), + step(13, "code", "edit", 59_000, true), + state(14, "code", "build"), + step(15, "build", "cargo build", 38_000, true), + state(16, "build", "test"), + test_run(17, &["a::one", "a::two"]), + step(18, "test", "cargo test", 6_200, false), + catch(19), + state(20, "test", "code"), + ev(21, "intent", json!({"text": "rotate the key"})), + ev( + 22, + "edit", + json!({"path": "src/auth/token.rs", "added": 6, "removed": 2}), + ), + ev( + 23, + "edit", + json!({"path": "src/auth/token.rs", "added": 4, "removed": 0}), + ), + ev( + 24, + "edit", + json!({"path": "src/auth/mod.rs", "added": 1, "removed": 1}), + ), + ev(25, "tool", json!({"title": "edit src/auth/token.rs"})), + ev( + 26, + "usage", + json!({"ctx_used": 142_000, "ctx_limit": 200_000, "cost": 1.12}), + ), + ] + } + + fn detail(events: &[Event], status: &str, state: &str) -> Detail { + let m = HashMap::from([( + "task".to_string(), + Machine::parse(include_str!("../examples/machines/task.toml")).unwrap(), + )]); + let tasks = [Task { + id: "s2".into(), + name: "oauth".into(), + subtitle: String::new(), + machine: "task".into(), + depends_on: vec![], + }]; + let sessions = [Session { + id: "s2".into(), + task_id: "s2".into(), + branch: "hx/s2-oauth".into(), + worktree: "/wt/s2".into(), + pid: Some(7), + state: state.into(), + status: status.into(), + }]; + build( + &Input { + goal: None, + tasks: &tasks, + sessions: &sessions, + events, + machines: &m, + needs: &[], + checks: &[], + decisions: &[], + now_ms: 36_000, + }, + "s2", + ) + .unwrap() + } + + fn find<'a>(d: &'a Detail, text: &str) -> &'a MLine { + d.lines + .iter() + .find(|l| l.text.trim_end() == text) + .unwrap_or_else(|| panic!("no line {text:?}")) + } + + #[test] + fn machine_lines_follow_the_mockup() { + let d = detail(&scenario(), "running", "code"); + let plan = find(&d, "plan · start"); + assert_eq!((plan.block, plan.live.as_str()), (Block::Done, "✓ 4m10s")); + let draft = find(&d, " draft-plan"); + assert_eq!( + (draft.exec, draft.sets.as_str(), draft.live.as_str()), + (Some(RunOn::Agent), "■ planning", "✓ 4m10s") + ); + let code = find(&d, "code"); + assert_eq!((code.block, code.live.as_str()), (Block::Cur, "▶ fix 2")); + // the running step shows the time since the last event (36s now, last event at 26s) + assert_eq!(find(&d, " edit").live, "▶ 0m10s"); + let build = find(&d, "build"); + assert_eq!(build.live, "✓ 0m38s ×2"); + let test = find(&d, "test"); + assert_eq!((test.block, test.live.as_str()), (Block::Fail, "✗ 39/41")); + let hit = find(&d, " catch TestsFailed"); + assert_eq!( + (hit.live.as_str(), hit.hit, hit.to.as_str()), + ("hit 2×", true, " → code") + ); + let next = find(&d, " catch TestsFailed ×3"); + assert_eq!( + (next.live.as_str(), next.to.as_str()), + ("next", " → escalated") + ); + assert_eq!(find(&d, "review · gate").block, Block::Todo); + assert_eq!(find(&d, "merge · exit").live, ""); + assert_eq!(find(&d, " end: merged").kind, LineKind::End); + // only_on states come last, marked + assert!( + d.lines + .iter() + .any(|l| l.text == "│ only on TestsFailed ×3, budget") + ); + assert!(d.lines.iter().any(|l| l.text == "│ escalated · exit")); + assert!(d.lines.iter().any(|l| l.text == "│ snapshot-worktree")); + // untouched machine order: escalated after merge + let pos = |t: &str| d.lines.iter().position(|l| l.text == t).unwrap(); + assert!(pos("merge · exit") < pos("│ escalated · exit")); + } + + #[test] + fn path_test_run_now_files_budget() { + let d = detail(&scenario(), "running", "code"); + let names: Vec = d + .path + .iter() + .map(|p| format!("{}{}", p.name, if p.failed { " ✗" } else { "" })) + .collect(); + assert_eq!( + names, + [ + "plan", "code", "build", "test ✗", "code", "build", "test ✗", "code" + ] + ); + assert!(d.path.last().unwrap().current); + + let t = d.test.as_ref().unwrap(); + assert_eq!((t.passed, t.failed, t.step.as_str()), (39, 2, "cargo test")); + assert_eq!(t.failures[0].repeats, "failed in the first run too"); + assert_eq!(t.failures[1].location, "src/a.rs:1"); + + assert_eq!(d.now.who, "agent"); + assert_eq!(d.now.line, "edit src/auth/token.rs"); + assert_eq!(d.now.intent, "rotate the key"); + + assert_eq!(d.files.len(), 2); + assert_eq!( + ( + d.files[0].path.as_str(), + d.files[0].added, + d.files[0].removed + ), + ("src/auth/token.rs", 10, 2) + ); + + assert_eq!(d.budget.ctx, Some((142_000, 200_000))); + assert_eq!(d.budget.retries, Some((2, 3))); + assert_eq!(d.budget.wall_secs, 35); + assert!((d.budget.cost - 1.12).abs() < 1e-9); + assert_eq!( + (d.status, d.branch.as_str(), d.pid), + (Status::Fix, "hx/s2-oauth", Some(7)) + ); + assert_eq!(d.on_budget.as_deref(), Some("escalated")); + } + + #[test] + fn third_failure_lists_both_earlier_runs() { + let mut evs = scenario(); + evs.push(test_run(30, &["a::one"])); + let d = detail(&evs, "running", "code"); + assert_eq!( + d.test.unwrap().failures[0].repeats, + "failed in the first run, fix 1 too" + ); + } + + #[test] + fn finished_session_has_no_current_state() { + let evs = vec![ + state(1, "", "plan"), + step(2, "plan", "read-goal", 100, true), + ev(3, "end", json!({"status": "failed", "reason": "boom"})), + ]; + let d = detail(&evs, "failed", "plan"); + assert_eq!(find(&d, "plan · start").block, Block::Fail); + assert!(d.path[0].failed && !d.path[0].current); + assert_eq!(d.now, Now::default()); + assert_eq!(dur(500), "0.5s"); + assert_eq!(dur(65_000), "1m05s"); + } +} diff --git a/src/goal.rs b/src/goal.rs new file mode 100644 index 0000000..cad6694 --- /dev/null +++ b/src/goal.rs @@ -0,0 +1,351 @@ +//! View model of the goal screen (ORCHESTRATOR.md 7.3, `Goal.dc.html`): the goal and its definition of done, +//! the task graph in columns by dependency depth, the critical path, the decisions agents made, the checks. + +use crate::view::{Input, Status, hms}; +use std::collections::HashMap; + +#[derive(Clone, PartialEq, Debug)] +pub struct TaskBox { + pub id: String, + pub name: String, + pub status: Status, + /// `merged`, `queued`, or the state the session is in. + pub detail: String, + pub after: Vec, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct Column { + pub label: String, + pub tasks: Vec, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct DecisionView { + pub id: i64, + pub session: String, + pub text: String, + /// The state the decision was made in. + pub state: String, + /// `plan · 13:22` + pub whence: String, + pub vetoed: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum CheckState { + Pass, + Fail, + /// Never ran on main. + Unknown, +} + +#[derive(Clone, PartialEq, Debug)] +pub struct CheckView { + pub name: String, + pub owner: String, + pub state: CheckState, +} + +#[derive(Clone, PartialEq, Debug, Default)] +pub struct GoalView { + pub goal: String, + pub done_when: String, + pub columns: Vec, + /// `s2 oauth-provider`, in order; the longest chain of unfinished tasks. + pub critical: Vec, + pub decisions: Vec, + pub checks: Vec, + pub green: usize, +} + +/// Length of the dependency chain below a task (0 = no dependencies). Cycles count as 0 instead of looping. +fn depth(id: &str, deps: &HashMap<&str, &Vec>, seen: &mut Vec) -> usize { + if seen.iter().any(|s| s == id) { + return 0; + } + seen.push(id.to_string()); + let d = deps.get(id).map_or(0, |ds| { + ds.iter() + .map(|d| 1 + depth(d, deps, seen)) + .max() + .unwrap_or(0) + }); + seen.pop(); + d +} + +pub fn build(i: &Input) -> GoalView { + let overview = crate::view::build(i); + let deps: HashMap<&str, &Vec> = i + .tasks + .iter() + .map(|t| (t.id.as_str(), &t.depends_on)) + .collect(); + let mut boxes: Vec<(usize, TaskBox)> = vec![]; + for t in i.tasks { + let row = overview.rows.iter().find(|r| r.id == t.id); + let session = i.sessions.iter().find(|s| s.id == t.id); + let status = row.map_or(Status::Blocked, |r| r.status); + let detail = match (status, session) { + (Status::Done, _) => "merged".to_string(), + (_, Some(s)) if !s.state.is_empty() => match row { + Some(r) if !r.retry.is_empty() => format!("{} {}", s.state, r.retry), + _ => s.state.clone(), + }, + _ => "queued".to_string(), + }; + boxes.push(( + depth(&t.id, &deps, &mut vec![]), + TaskBox { + id: t.id.clone(), + name: t.name.clone(), + status, + detail, + after: t.depends_on.clone(), + }, + )); + } + let levels = boxes.iter().map(|b| b.0).max().map_or(0, |m| m + 1); + let columns = (0..levels) + .map(|l| Column { + label: format!("level {l}"), + tasks: boxes + .iter() + .filter(|b| b.0 == l) + .map(|b| b.1.clone()) + .collect(), + }) + .collect(); + + // critical path: longest chain over unfinished tasks only + let open: Vec<&TaskBox> = boxes + .iter() + .map(|b| &b.1) + .filter(|t| t.status != Status::Done) + .collect(); + let mut best: HashMap<&str, (usize, Option<&str>)> = HashMap::new(); + let mut order: Vec<&TaskBox> = open.clone(); + order.sort_by_key(|t| depth(&t.id, &deps, &mut vec![])); // dependencies first + for t in &order { + let prev = t + .after + .iter() + .filter_map(|d| best.get(d.as_str()).map(|(n, _)| (*n, d.as_str()))) + .max_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(a.1))); // longest, then lowest id + best.insert(&t.id, (prev.map_or(1, |p| p.0 + 1), prev.map(|p| p.1))); + } + let end = open + .iter() + .map(|t| t.id.as_str()) + .max_by(|a, b| best[a].0.cmp(&best[b].0).then(b.cmp(a))); + let mut critical = vec![]; + let mut cur = end; + while let Some(id) = cur { + let name = boxes + .iter() + .find(|b| b.1.id == id) + .map_or("", |b| b.1.name.as_str()); + critical.push(format!("{id} {name}")); + cur = best[id].1; + } + critical.reverse(); + + let decisions = i + .decisions + .iter() + .map(|d| DecisionView { + id: d.id, + session: d.session.clone(), + text: d.text.clone(), + state: d.state.clone(), + whence: format!("{} · {}", d.state, &hms(d.at)[..5]), + vetoed: d.vetoed, + }) + .collect(); + let checks: Vec = i + .checks + .iter() + .map(|c| CheckView { + name: c.name.clone(), + owner: c.owner.clone().unwrap_or_else(|| "-".into()), + state: match c.last_status.as_deref() { + Some("pass") => CheckState::Pass, + Some(_) => CheckState::Fail, + None => CheckState::Unknown, + }, + }) + .collect(); + let green = checks + .iter() + .filter(|c| c.state == CheckState::Pass) + .count(); + let done_when = if checks.is_empty() { + "Done = all acceptance checks green on main. None defined yet: orch check NAME CMD." + .to_string() + } else { + format!( + "Done = all {} acceptance checks green on main. The orchestrator re-runs them after every merge.", + checks.len() + ) + }; + GoalView { + goal: i.goal.unwrap_or("no goal set: orch goal \"…\"").to_string(), + done_when, + columns, + critical, + decisions, + checks, + green, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::{CheckRow, DecisionRow, Session, Task}; + use crate::machine::Machine; + + fn task(id: &str, name: &str, after: &[&str]) -> Task { + Task { + id: id.into(), + name: name.into(), + subtitle: String::new(), + machine: "task".into(), + depends_on: after.iter().map(|a| a.to_string()).collect(), + } + } + + fn session(id: &str, state: &str, status: &str) -> Session { + Session { + id: id.into(), + task_id: id.into(), + branch: "b".into(), + worktree: "/w".into(), + pid: None, + state: state.into(), + status: status.into(), + } + } + + fn view( + tasks: &[Task], + sessions: &[Session], + checks: &[CheckRow], + decisions: &[DecisionRow], + ) -> GoalView { + let m = HashMap::from([( + "task".to_string(), + Machine::parse(include_str!("../examples/machines/task.toml")).unwrap(), + )]); + build(&Input { + goal: Some("Move login to OAuth2"), + tasks, + sessions, + events: &[], + machines: &m, + needs: &[], + checks, + decisions, + now_ms: 0, + }) + } + + fn check(name: &str, owner: Option<&str>, st: Option<&str>) -> CheckRow { + CheckRow { + id: 1, + name: name.into(), + cmd: "true".into(), + owner: owner.map(Into::into), + last_status: st.map(Into::into), + last_run_at: None, + } + } + + #[test] + fn graph_columns_critical_path_and_checks() { + let tasks = [ + task("s1", "schema-migrate", &[]), + task("s2", "oauth-provider", &["s1"]), + task("s3", "auth-middleware", &["s1"]), + task("s4", "rate-limiter", &["s1"]), + task("s5", "docs-update", &["s2", "s3"]), + task("s6", "e2e-tests", &["s3", "s4"]), + ]; + let sessions = [ + session("s1", "merge", "merged"), + session("s2", "test", "running"), + session("s3", "review", "waiting"), + session("s4", "build", "running"), + session("s5", "", "queued"), + session("s6", "plan", "running"), + ]; + let checks = [ + check("build", None, Some("pass")), + check("unit", Some("s2"), Some("fail")), + check("e2e", Some("s6"), None), + ]; + let decisions = [DecisionRow { + id: 1, + session: "s4".into(), + text: "token bucket".into(), + state: "plan".into(), + at: 0, + vetoed: false, + }]; + let v = view(&tasks, &sessions, &checks, &decisions); + + fn ids(c: &Column) -> Vec<&str> { + c.tasks.iter().map(|t| t.id.as_str()).collect() + } + assert_eq!(v.columns.len(), 3); + assert_eq!(ids(&v.columns[0]), ["s1"]); + assert_eq!(ids(&v.columns[1]), ["s2", "s3", "s4"]); + assert_eq!(ids(&v.columns[2]), ["s5", "s6"]); + assert_eq!(v.columns[0].label, "level 0"); + let s1 = &v.columns[0].tasks[0]; + assert_eq!((s1.status, s1.detail.as_str()), (Status::Done, "merged")); + let s3 = &v.columns[1].tasks[1]; + assert_eq!( + (s3.status, s3.detail.as_str(), s3.after.clone()), + (Status::Wait, "review", vec!["s1".to_string()]) + ); + let s5 = &v.columns[2].tasks[0]; + assert_eq!((s5.status, s5.detail.as_str()), (Status::Blocked, "queued")); + + // longest chain of unfinished tasks; s1 is merged and not part of it + assert_eq!(v.critical, ["s2 oauth-provider", "s5 docs-update"]); + + assert_eq!((v.green, v.checks.len()), (1, 3)); + assert_eq!( + v.checks.iter().map(|c| c.state).collect::>(), + [CheckState::Pass, CheckState::Fail, CheckState::Unknown] + ); + assert_eq!(v.checks[0].owner, "-"); + assert!( + v.done_when + .starts_with("Done = all 3 acceptance checks green on main") + ); + assert_eq!(v.decisions[0].session, "s4"); + assert!(v.decisions[0].whence.starts_with("plan · ")); + } + + #[test] + fn empty_and_cyclic_goals_do_not_break() { + let v = view(&[], &[], &[], &[]); + assert!(v.columns.is_empty() && v.critical.is_empty()); + assert!(v.done_when.contains("None defined yet")); + // a cycle is a user error, not a hang + let tasks = [task("s1", "a", &["s2"]), task("s2", "b", &["s1"])]; + let sessions = [session("s1", "", "queued"), session("s2", "", "queued")]; + let v = view(&tasks, &sessions, &[], &[]); + assert_eq!(v.columns.iter().map(|c| c.tasks.len()).sum::(), 2); + } + + #[test] + fn all_done_has_no_critical_path() { + let tasks = [task("s1", "a", &[])]; + let sessions = [session("s1", "merge", "merged")]; + assert!(view(&tasks, &sessions, &[], &[]).critical.is_empty()); + } +} diff --git a/src/junit.rs b/src/junit.rs new file mode 100644 index 0000000..4a3ee63 --- /dev/null +++ b/src/junit.rs @@ -0,0 +1,253 @@ +//! JUnit XML test reports (`report = "junit"` steps): counts and the failing tests with message and location. +//! Works with `cargo nextest --message-format junit`, `cargo2junit`, pytest, JUnit itself: it only needs +//! `` with ``/``/`` children. + +use anyhow::{Result, anyhow}; +use quick_xml::Reader; +use quick_xml::escape::resolve_predefined_entity; +use quick_xml::events::{BytesStart, Event}; +use serde::Serialize; + +#[derive(Serialize, Clone, Debug, PartialEq)] +pub struct Failure { + pub name: String, + /// The assertion text: the `message` attribute, else the first line of the failure body. + pub message: String, + /// `file:line` when the report has it, else the first `path.ext:NN` in the failure body. + pub location: String, +} + +#[derive(Serialize, Clone, Debug, Default, PartialEq)] +pub struct Report { + pub passed: u32, + pub failed: u32, + pub skipped: u32, + /// Sum of the test times. + pub secs: f64, + pub failures: Vec, +} + +fn attr(e: &BytesStart, key: &str) -> String { + e.attributes() + .flatten() + .find(|a| a.key.as_ref() == key) + .and_then(|a| { + a.normalized_value(quick_xml::XmlVersion::Implicit1_0) + .ok() + .map(|v| v.into_owned()) + }) + .unwrap_or_default() +} + +/// First `something/with.ext:123` word of a text. +fn find_location(text: &str) -> String { + text.split(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | ',' | '\'' | '"' | '`')) + .map(|w| w.trim_end_matches(':')) + .find(|w| { + let mut it = w.rsplitn(2, ':'); + let (line, file) = (it.next(), it.next()); + // rsplitn on `a.rs:12:5` leaves `a.rs:12` as the file part; accept both shapes + let file = file.unwrap_or("").split(':').next().unwrap_or(""); + line.is_some_and(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit())) + && file.contains('.') + && !file.starts_with('.') + }) + .map(|w| { + // keep file:line, drop a trailing :column + let parts: Vec<&str> = w.split(':').collect(); + if parts.len() >= 3 { + format!("{}:{}", parts[0], parts[1]) + } else { + w.to_string() + } + }) + .unwrap_or_default() +} + +struct Case { + name: String, + file: String, + line: String, + failure: Option<(String, String)>, // (message attr, body) + skipped: bool, +} + +pub fn parse(xml: &str) -> Result { + let mut r = Reader::from_str(xml); + let mut rep = Report::default(); + let mut case: Option = None; + // inside /: collecting the body text + let mut in_failure = false; + loop { + let ev = r + .read_event() + .map_err(|e| anyhow!("bad junit xml at byte {}: {e}", r.buffer_position()))?; + match &ev { + Event::Eof => break, + Event::Start(e) | Event::Empty(e) => { + let empty = matches!(ev, Event::Empty(_)); + match e.local_name().as_ref() { + "testcase" => { + let (class, name) = (attr(e, "classname"), attr(e, "name")); + let name = if class.is_empty() || name.contains("::") { + name + } else { + format!("{class}::{name}") + }; + rep.secs += attr(e, "time").parse::().unwrap_or(0.0); + let c = Case { + name, + file: attr(e, "file"), + line: attr(e, "line"), + failure: None, + skipped: false, + }; + if empty { + rep.passed += 1; + } else { + case = Some(c); + } + } + "failure" | "error" => { + if let Some(c) = &mut case { + c.failure = Some((attr(e, "message"), String::new())); + in_failure = !empty; + } + } + "skipped" => { + if let Some(c) = &mut case { + c.skipped = true; + rep.skipped += 1; + } + } + _ => {} + } + } + Event::Text(t) if in_failure => push_body(&mut case, &t.xml10_content()), + Event::CData(t) if in_failure => push_body(&mut case, &t.xml10_content()), + Event::GeneralRef(g) if in_failure => { + let s = if g.is_char_ref() { + g.resolve_char_ref().ok().flatten().map(String::from) + } else { + resolve_predefined_entity(&g.xml10_content()).map(String::from) + }; + push_body(&mut case, &s.unwrap_or_default()); + } + Event::End(e) => match e.local_name().as_ref() { + "failure" | "error" => in_failure = false, + "testcase" => { + if let Some(c) = case.take() { + match c.failure { + Some((msg, body)) => { + rep.failed += 1; + let message = if msg.trim().is_empty() { + body.lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or("") + .to_string() + } else { + msg + }; + let location = if !c.file.is_empty() && !c.line.is_empty() { + format!("{}:{}", c.file, c.line) + } else { + find_location(&format!("{message} {body}")) + }; + rep.failures.push(Failure { + name: c.name, + message, + location, + }); + } + None if c.skipped => {} + None => rep.passed += 1, + } + } + } + _ => {} + }, + _ => {} + } + } + Ok(rep) +} + +fn push_body(case: &mut Option, s: &str) { + if let Some(Case { + failure: Some((_, body)), + .. + }) = case + { + body.push_str(s); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const XML: &str = r#" + + + + + + +thread 'main' panicked at src/auth/token.rs:142:9: +assertion failed + + + + expected Err(Expired), got Ok(Claims { sub: "u_17" }) + at src/auth/token.rs:188:5 + + + +"#; + + #[test] + fn counts_failures_and_locations() { + let r = parse(XML).unwrap(); + assert_eq!((r.passed, r.failed, r.skipped), (2, 2, 1)); + assert!((r.secs - 4.5).abs() < 1e-9); + assert_eq!( + r.failures[0], + Failure { + name: "auth::token::refresh_rotates_secret".into(), + message: "assertion `left != right` failed: key id unchanged after refresh".into(), + location: "src/auth/token.rs:142".into(), + } + ); + // message from the body (entities resolved), classname dropped when the name has a path already + assert_eq!(r.failures[1].name, "auth::token::expired_token_rejected"); + assert_eq!( + r.failures[1].message, + "expected Err(Expired), got Ok(Claims { sub: \"u_17\" })" + ); + assert_eq!(r.failures[1].location, "src/auth/token.rs:188"); + } + + #[test] + fn file_and_line_attributes_win() { + let r = parse( + r#""#, + ) + .unwrap(); + assert_eq!(r.failures[0].location, "a/b.rs:7"); + assert_eq!((r.passed, r.failed), (0, 1)); + } + + #[test] + fn empty_and_broken_input() { + assert_eq!(parse("").unwrap(), Report::default()); + assert!(parse("").is_err()); + } + + #[test] + fn locations() { + assert_eq!(find_location("panicked at src/a.rs:12:5:"), "src/a.rs:12"); + assert_eq!(find_location("see lib.rs:3"), "lib.rs:3"); + assert_eq!(find_location("no location 12:30 here"), ""); + } +} diff --git a/src/machine.rs b/src/machine.rs new file mode 100644 index 0000000..65b0259 --- /dev/null +++ b/src/machine.rs @@ -0,0 +1,365 @@ +//! Machine files: TOML state machines that drive one session (see ORCHESTRATOR.md section 3). +// shortcut: nothing calls this yet; the session runner (milestone 2) does. Remove then. +#![allow(dead_code)] + +use anyhow::{Context, Result, bail, ensure}; +use indexmap::IndexMap; +use serde::Deserialize; +use std::path::{Path, PathBuf}; + +#[derive(Deserialize, Clone, Copy, PartialEq, Eq, Debug, Default)] +#[serde(rename_all = "lowercase")] +pub enum Kind { + Start, + #[default] + Normal, + Gate, + Exit, + Abort, +} + +#[derive(Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq, Debug)] +#[serde(rename_all = "lowercase")] +pub enum RunOn { + Computer, + Agent, + Human, +} + +#[derive(Deserialize, Clone, Debug)] +#[serde(deny_unknown_fields)] +pub struct Step { + pub name: String, + pub run: RunOn, + /// Shell command (`computer`); supports {{session}} {{scope}} {{worktree}} {{branch}}. + pub cmd: Option, + /// Status label shown as `■