From 6497a96bada75f6d4c30654a2264923199b5e3e9 Mon Sep 17 00:00:00 2001
From: MethodWhite
Date: Tue, 23 Jun 2026 19:59:04 -0400
Subject: [PATCH 1/7] fix: comprehensive audit fixes and QUIC connector
- engine: async shutdown, per-loop max_iterations, saturating ops
- convergence: remove has_feedback guard, fix status labels (completed)
- config: serde(default), deny_unknown_fields, threshold validation
- traits: remove dead SecurityScanner/CodeAnalyzer/IntegrityChecker
- error: remove unused variants (CommandFailed, CommandTimeout, HttpError)
- events: remove unused serde tag, fix event drop log level
- feedback: profile caching, spawn_blocking, clippy line matching
- connector: new QUIC client module (quinn + rustls)
- fs_utils: fix non-Unix cycle detection, tokio process timeout
- agents: log regex failures, skip files >10MB
- handlers: SSRF protection, validate_working_dir, freed calc fix
- Synapsis: remove dead SynapsisConfig (separate project)
- tools: mark stubs, fix descriptions, add max_depth/confirm params
- README: sync with code, document connector
---
.github/workflows/ci.yml | 18 +-
Cargo.lock | 411 +++++++++--
Cargo.toml | 9 +-
README.md | 48 +-
build.rs | 5 +
install.ps1 | 114 +++
install.sh | 132 ++++
mcp-config/cursor.json | 3 +-
mcp-config/opencode.json | 5 +-
src/agents.rs | 57 +-
src/config.rs | 203 ++++--
src/connector.rs | 122 ++++
src/engine.rs | 304 +++++---
src/error.rs | 56 +-
src/events.rs | 30 +-
src/feedback.rs | 151 +++-
src/fs_utils.rs | 303 ++++++++
src/main.rs | 126 ++--
src/mcp.rs | 1490 --------------------------------------
src/mcp/handlers.rs | 578 +++++++++++++++
src/mcp/mod.rs | 254 +++++++
src/mcp/resources.rs | 80 ++
src/profile.rs | 71 +-
src/traits.rs | 45 +-
src/types.rs | 111 ++-
25 files changed, 2828 insertions(+), 1898 deletions(-)
create mode 100644 install.ps1
create mode 100755 install.sh
create mode 100644 src/connector.rs
create mode 100644 src/fs_utils.rs
delete mode 100644 src/mcp.rs
create mode 100644 src/mcp/handlers.rs
create mode 100644 src/mcp/mod.rs
create mode 100644 src/mcp/resources.rs
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index fff9e50..9d7c431 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -7,6 +7,7 @@ on:
env:
CARGO_TERM_COLOR: always
+ RUST_BACKTRACE: full
jobs:
test:
@@ -20,7 +21,19 @@ jobs:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- - run: cargo test
+
+ - name: Compile check
+ run: cargo check 2>&1
+
+ - name: Run tests (verbose)
+ run: cargo test -- --nocapture --test-threads=1 2>&1
+
+ - name: Test summary
+ if: always()
+ run: |
+ echo "### Test Results (${{ matrix.os }})" >> $GITHUB_STEP_SUMMARY
+ echo "- OS: ${{ matrix.os }}" >> $GITHUB_STEP_SUMMARY
+ echo "- Status: ${{ job.status }}" >> $GITHUB_STEP_SUMMARY
fmt:
name: Format
@@ -41,8 +54,7 @@ jobs:
with:
components: clippy
- uses: Swatinem/rust-cache@v2
- - run: cargo clippy --all-targets
- continue-on-error: true
+ - run: cargo clippy --all-targets -- -D warnings
msrv:
name: MSRV (1.86.0)
diff --git a/Cargo.lock b/Cargo.lock
index d5c196c..adaf85d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -49,6 +49,28 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+[[package]]
+name = "aws-lc-rs"
+version = "1.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00"
+dependencies = [
+ "aws-lc-sys",
+ "zeroize",
+]
+
+[[package]]
+name = "aws-lc-sys"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4"
+dependencies = [
+ "cc",
+ "cmake",
+ "dunce",
+ "fs_extra",
+]
+
[[package]]
name = "base64"
version = "0.22.1"
@@ -80,9 +102,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dad887fd958be91b5098c0248def011f4523ab786cd411be668777e55063501f"
dependencies = [
"find-msvc-tools",
+ "jobserver",
+ "libc",
"shlex",
]
+[[package]]
+name = "cesu8"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
+
[[package]]
name = "cfg-if"
version = "1.0.4"
@@ -109,6 +139,35 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "cmake"
+version = "0.1.58"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "combine"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"
+dependencies = [
+ "bytes",
+ "memchr",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
@@ -147,6 +206,12 @@ dependencies = [
"syn",
]
+[[package]]
+name = "dunce"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -163,6 +228,18 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "fastbloom"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4"
+dependencies = [
+ "getrandom 0.3.4",
+ "libm",
+ "rand",
+ "siphasher",
+]
+
[[package]]
name = "fastrand"
version = "2.4.1"
@@ -190,6 +267,12 @@ dependencies = [
"percent-encoding",
]
+[[package]]
+name = "fs_extra"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
+
[[package]]
name = "futures-channel"
version = "0.3.32"
@@ -555,6 +638,60 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+[[package]]
+name = "jni"
+version = "0.21.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"
+dependencies = [
+ "cesu8",
+ "cfg-if",
+ "combine",
+ "jni-sys 0.3.1",
+ "log",
+ "thiserror 1.0.69",
+ "walkdir",
+ "windows-sys 0.45.0",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
+dependencies = [
+ "jni-sys 0.4.1",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
+dependencies = [
+ "jni-sys-macros",
+]
+
+[[package]]
+name = "jni-sys-macros"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
+dependencies = [
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "jobserver"
+version = "0.1.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
+dependencies = [
+ "getrandom 0.3.4",
+ "libc",
+]
+
[[package]]
name = "js-sys"
version = "0.3.102"
@@ -584,6 +721,12 @@ version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
[[package]]
name = "libredox"
version = "0.1.17"
@@ -605,15 +748,6 @@ version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
-[[package]]
-name = "lock_api"
-version = "0.4.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
-dependencies = [
- "scopeguard",
-]
-
[[package]]
name = "log"
version = "0.4.32"
@@ -676,6 +810,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
[[package]]
name = "option-ext"
version = "0.2.0"
@@ -688,46 +828,25 @@ version = "0.2.0"
dependencies = [
"anyhow",
"async-trait",
- "base64",
"chrono",
"dirs",
+ "quinn",
"regex",
"reqwest",
+ "rustls",
+ "rustls-pemfile",
"serde",
"serde_json",
- "serde_yaml",
"tempfile",
"thiserror 1.0.69",
"tokio",
"toml",
"tracing",
"tracing-subscriber",
+ "url",
"uuid",
]
-[[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 = "percent-encoding"
version = "2.3.2"
@@ -804,6 +923,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
dependencies = [
"bytes",
+ "fastbloom",
"getrandom 0.3.4",
"lru-slab",
"rand",
@@ -811,6 +931,7 @@ dependencies = [
"rustc-hash",
"rustls",
"rustls-pki-types",
+ "rustls-platform-verifier",
"slab",
"thiserror 2.0.18",
"tinyvec",
@@ -882,15 +1003,6 @@ dependencies = [
"getrandom 0.3.4",
]
-[[package]]
-name = "redox_syscall"
-version = "0.5.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
-dependencies = [
- "bitflags",
-]
-
[[package]]
name = "redox_users"
version = "0.4.6"
@@ -1010,6 +1122,8 @@ version = "0.23.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b"
dependencies = [
+ "aws-lc-rs",
+ "log",
"once_cell",
"ring",
"rustls-pki-types",
@@ -1018,6 +1132,27 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
+[[package]]
+name = "rustls-pemfile"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "rustls-pki-types"
version = "1.14.1"
@@ -1028,12 +1163,40 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "rustls-platform-verifier"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784"
+dependencies = [
+ "core-foundation",
+ "core-foundation-sys",
+ "jni",
+ "log",
+ "once_cell",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-platform-verifier-android",
+ "rustls-webpki",
+ "security-framework",
+ "security-framework-sys",
+ "webpki-root-certs",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls-platform-verifier-android"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
+
[[package]]
name = "rustls-webpki"
version = "0.103.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
dependencies = [
+ "aws-lc-rs",
"ring",
"rustls-pki-types",
"untrusted",
@@ -1052,10 +1215,45 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
-name = "scopeguard"
-version = "1.2.0"
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "schannel"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "security-framework"
+version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags",
+ "core-foundation",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
[[package]]
name = "semver"
@@ -1127,19 +1325,6 @@ dependencies = [
"serde",
]
-[[package]]
-name = "serde_yaml"
-version = "0.9.34+deprecated"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
-dependencies = [
- "indexmap",
- "itoa",
- "ryu",
- "serde",
- "unsafe-libyaml",
-]
-
[[package]]
name = "sharded-slab"
version = "0.1.7"
@@ -1165,6 +1350,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "siphasher"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"
+
[[package]]
name = "slab"
version = "0.4.12"
@@ -1326,7 +1517,6 @@ dependencies = [
"bytes",
"libc",
"mio",
- "parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
@@ -1447,6 +1637,7 @@ version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
+ "log",
"pin-project-lite",
"tracing-attributes",
"tracing-core",
@@ -1520,12 +1711,6 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
-[[package]]
-name = "unsafe-libyaml"
-version = "0.2.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
-
[[package]]
name = "untrusted"
version = "0.9.0"
@@ -1567,6 +1752,16 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
[[package]]
name = "want"
version = "0.3.1"
@@ -1709,6 +1904,15 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "webpki-root-certs"
+version = "1.0.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "webpki-roots"
version = "1.0.7"
@@ -1718,6 +1922,15 @@ dependencies = [
"rustls-pki-types",
]
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "windows-core"
version = "0.62.2"
@@ -1777,6 +1990,15 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "windows-sys"
+version = "0.45.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
+dependencies = [
+ "windows-targets 0.42.2",
+]
+
[[package]]
name = "windows-sys"
version = "0.48.0"
@@ -1813,6 +2035,21 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "windows-targets"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
+dependencies = [
+ "windows_aarch64_gnullvm 0.42.2",
+ "windows_aarch64_msvc 0.42.2",
+ "windows_i686_gnu 0.42.2",
+ "windows_i686_msvc 0.42.2",
+ "windows_x86_64_gnu 0.42.2",
+ "windows_x86_64_gnullvm 0.42.2",
+ "windows_x86_64_msvc 0.42.2",
+]
+
[[package]]
name = "windows-targets"
version = "0.48.5"
@@ -1861,6 +2098,12 @@ dependencies = [
"windows_x86_64_msvc 0.53.1",
]
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
+
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
@@ -1879,6 +2122,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
+
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
@@ -1897,6 +2146,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+[[package]]
+name = "windows_i686_gnu"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
+
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
@@ -1927,6 +2182,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+[[package]]
+name = "windows_i686_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
+
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
@@ -1945,6 +2206,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
+
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
@@ -1963,6 +2230,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
+
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
@@ -1981,6 +2254,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
+
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
diff --git a/Cargo.toml b/Cargo.toml
index 0423131..54befd9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -2,25 +2,28 @@
name = "oura"
version = "0.2.0"
description = "Oura — MCP server for intelligent iterative looping. The serpent that refines code through endless improvement cycles."
+rust-version = "1.86"
edition = "2021"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
-serde_yaml = "0.9"
toml = "0.8"
-tokio = { version = "1", features = ["full"] }
+tokio = { version = "1", features = ["rt-multi-thread", "sync", "macros", "process", "io-util", "io-std", "net"] }
uuid = { version = "1.0", features = ["v4"] }
chrono = { version = "0.4", features = ["serde"] }
anyhow = "1.0"
thiserror = "1.0"
reqwest = { version = "0.12", features = ["json", "rustls-tls", "blocking"], default-features = false }
+quinn = "0.11"
+rustls = "0.23"
+rustls-pemfile = "2"
regex = "1"
dirs = "5.0"
-base64 = "0.22"
async-trait = "0.1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+url = "2"
[dev-dependencies]
tempfile = "3.0"
diff --git a/README.md b/README.md
index 0d2a4ea..9e287b3 100644
--- a/README.md
+++ b/README.md
@@ -12,20 +12,15 @@
-
+
-
-
## Características
-- **Loop Engine**: iteraciones automáticas con detección de convergencia
+- **Loop Engine**: iteraciones automáticas o manuales con detección de convergencia
- **Feedback multi-fuente**: tests, lint, typecheck, custom
- **Sub-agentes**: Security Auditor, Refactor Engine, Anti-deletion Guard, Code Optimizer
-- **Integración GitHub**: PRs, workflows, actions, auto-commit, multi-repo
-- **Plugin system**: hooks extensibles para eventos del loop
-- **Synapsis bridge**: persistencia en Synapsis memory + task orchestration
- **Config**: TOML + env vars (`OURA_*`)
## Arquitectura
@@ -34,7 +29,7 @@
-Oura está compuesto por **14 módulos** organizados en capas:
+Oura está compuesto por **13 módulos** organizados en capas:
| Capa | Módulos | Responsabilidad |
|------|---------|-----------------|
@@ -63,6 +58,11 @@ export OURA_GITHUB_TOKEN=ghp_xxx
export OURA_GITHUB_OWNER=MethodWhite
export OURA_GITHUB_REPO=my-project
export OURA_MAX_ITERATIONS=50
+export OURA_CONVERGENCE_THRESHOLD=90.0
+export OURA_GITHUB_ENABLED=true
+export OURA_WORKING_DIR=/path/to/project
+export OURA_CONFIG=/custom/path/config.toml
+export OURA_QUIET=1
```
### Config file (`~/.config/oura/config.toml`)
@@ -74,15 +74,18 @@ convergence_threshold = 90.0
feedback_sources = ["test", "lint"]
[github]
-enabled = true
+enabled = false
default_owner = "MethodWhite"
default_repo = "my-project"
-auto_commit = true
-auto_pr = true
-
-[synapsis]
-enabled = true
-endpoint = "http://localhost:7438"
+auto_commit = false
+auto_pr = false
+
+# External MCP connector — call tools on other MCP servers during iteration
+# [connector]
+# enabled = true
+# server_url = "http://localhost:7438"
+# tools = ["synapsis_mem_search"]
+# auto_call = true
```
## Uso con MCP
@@ -104,13 +107,14 @@ Añade a `opencode.json` / `claude-code.json` / `cursor.json`:
| Tool | Descripción |
|------|-------------|
-| `oura_start_loop` | Inicia loop de iteración con goal |
+| `oura_start_loop` | Inicia loop de iteración con goal (manual=true para modo manual con oura_iterate) |
| `oura_iterate` | Ejecuta un paso manual |
| `oura_loop_status` | Estado del loop actual |
| `oura_loop_stop` | Detiene el loop |
| `oura_results` | Resultados acumulados |
| `oura_configure` | Actualiza configuración (maxIterations, threshold, workingDirectory) |
-| `oura_working_dir` | Cambia el directorio de trabajo |
+| `oura_working_dir` | Set the working directory for Oura commands |
+| `oura_connector` | Call a tool on an external MCP server (e.g. Synapsis). Manual or auto via `[connector]` config |
| `oura_plugin_load` | Carga un plugin |
| `oura_plugin_list` | Lista plugins cargados |
| `oura_analyze_security` | Auditoría de seguridad (9 patrones) |
@@ -123,17 +127,17 @@ Añade a `opencode.json` / `claude-code.json` / `cursor.json`:
| `oura_update` | Actualiza Oura desde git + cargo build |
| `oura_profile` | Detecta perfil del proyecto |
| `oura_verify` | Verifica licencias y dependencias |
-| `mcp_call` | Llama a tools de otros servidores MCP |
+| `mcp_call` | HTTP call to another MCP server (low-level; SSRF protected) |
+
## Calidad
| Métrica | Valor |
|---------|-------|
| Tests | 58 pasando |
-| Cobertura clippy | 0 warnings |
+| Clippy | 0 warnings |
| `unwrap()` en producción | 0 |
-| Deuda técnica corregida | ~55 issues |
-| Lenguaje | Rust 1.86+ |
+| Lenguaje | Rust |
| Licencia | MIT |
## Licencia
@@ -143,5 +147,5 @@ MIT — ver [LICENSE](LICENSE).
---
- Hecho con 🐍 por MethodWhite
+ Hecho con 🦀 por MethodWhite
diff --git a/build.rs b/build.rs
index c656aa9..4c118b2 100644
--- a/build.rs
+++ b/build.rs
@@ -18,4 +18,9 @@ fn main() {
println!("cargo:rustc-env=GIT_HEAD={}", git_head);
println!("cargo:rerun-if-changed=.git/HEAD");
+ if let Ok(head) = std::fs::read_to_string(".git/HEAD") {
+ if let Some(ref_path) = head.strip_prefix("ref: ") {
+ println!("cargo:rerun-if-changed=.git/{}", ref_path.trim());
+ }
+ }
}
diff --git a/install.ps1 b/install.ps1
new file mode 100644
index 0000000..ca73efa
--- /dev/null
+++ b/install.ps1
@@ -0,0 +1,114 @@
+#!/usr/bin/env pwsh
+#requires -Version 5.1
+
+param(
+ [string]$Version = "latest",
+ [string]$InstallDir = "${env:ProgramFiles}\Oura",
+ [string]$ConfigDir = "${env:USERPROFILE}\.config\oura"
+)
+
+$Repo = "MethodWhite/oura"
+$Green = "Green"
+$Yellow = "Yellow"
+$Red = "Red"
+$Cyan = "Cyan"
+
+function Log { Write-Host "[✓] $args" -ForegroundColor $Green }
+function Warn { Write-Host "[!] $args" -ForegroundColor $Yellow }
+function Err { Write-Host "[✗] $args" -ForegroundColor $Red; exit 1 }
+function Info { Write-Host "[i] $args" -ForegroundColor $Cyan }
+
+function Detect-Arch {
+ $arch = if ([Environment]::Is64BitOperatingSystem) { "x86_64" } else { "i686" }
+ $env = [Environment]::GetEnvironmentVariable("PROCESSOR_IDENTIFIER")
+ if ($env -match "ARM|AArch64") { $arch = "aarch64" }
+ return $arch
+}
+
+function Get-ReleaseUrl {
+ param([string]$OsArch)
+ if ($Version -eq "latest") {
+ return "https://github.com/$Repo/releases/latest/download/oura-${OsArch}.exe"
+ }
+ return "https://github.com/$Repo/releases/download/$Version/oura-${OsArch}.exe"
+}
+
+function Main {
+ Write-Host ""
+ Write-Host "╔══════════════════════════════════════╗" -ForegroundColor $Cyan
+ Write-Host "║ Oura Installer — 0XFFRice ║" -ForegroundColor $Cyan
+ Write-Host "╚══════════════════════════════════════╝" -ForegroundColor $Cyan
+ Write-Host ""
+
+ $elevated = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+ if (-not $elevated) {
+ Warn "Not running as Administrator. Some installs may fail."
+ Warn "Restart with: Start-Process pwsh -Verb RunAs -ArgumentList '-File install.ps1'"
+ }
+
+ $arch = Detect-Arch
+ $osArch = "${arch}-pc-windows-msvc"
+ $url = Get-ReleaseUrl -OsArch $osArch
+
+ Info "Detected: $osArch"
+ Info "Download: $url"
+
+ $tmpdir = "$env:TEMP\oura-install"
+ New-Item -ItemType Directory -Force -Path $tmpdir | Out-Null
+ $outFile = "$tmpdir\oura.exe"
+
+ try {
+ Invoke-WebRequest -Uri $url -OutFile $outFile -UseBasicParsing -ErrorAction Stop
+ } catch {
+ Err "Download failed: $_"
+ }
+
+ try {
+ $version = & $outFile --version 2>&1
+ if (-not $?) { Err "Binary validation failed" }
+ } catch {
+ Err "Binary validation failed: $_"
+ }
+
+ New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
+ Copy-Item $outFile "$InstallDir\oura.exe" -Force
+ Log "Installed: $InstallDir\oura.exe"
+
+ $userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
+ if ($userPath -notlike "*$InstallDir*") {
+ [Environment]::SetEnvironmentVariable("PATH", "$InstallDir;$userPath", "User")
+ Log "Added to PATH (user scope)"
+ }
+
+ New-Item -ItemType Directory -Force -Path $ConfigDir | Out-Null
+ $configFile = "$ConfigDir\config.toml"
+ if (-not (Test-Path $configFile)) {
+ @"
+[loop_engine]
+max_iterations = 20
+convergence_threshold = 90.0
+feedback_sources = ["test", "lint"]
+
+[github]
+enabled = true
+default_owner = "MethodWhite"
+default_repo = "my-project"
+auto_commit = true
+auto_pr = true
+
+# [synapsis] # Optional: uncomment for Synapsis integration (separate project)
+# enabled = true
+# endpoint = "http://localhost:7438"
+"@ | Out-File -FilePath $configFile -Encoding utf8
+ Log "Config created: $configFile"
+ } else {
+ Warn "Config exists at $configFile — skipping"
+ }
+
+ ""
+ Log "Oura installed successfully!"
+ & "$InstallDir\oura.exe" version 2>$null
+ ""
+}
+
+Main
diff --git a/install.sh b/install.sh
new file mode 100755
index 0000000..a226b7d
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,132 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+REPO="MethodWhite/oura"
+VERSION="${1:-latest}"
+INSTALL_DIR="${OURA_INSTALL_DIR:-/usr/local/bin}"
+CONFIG_DIR="${OURA_CONFIG_DIR:-$HOME/.config/oura}"
+
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+RED='\033[0;31m'
+CYAN='\033[0;36m'
+NC='\033[0m'
+
+log() { printf "${GREEN}[✓]${NC} %s\n" "$*"; }
+warn() { printf "${YELLOW}[!]${NC} %s\n" "$*"; }
+err() { printf "${RED}[✗]${NC} %s\n" "$*"; exit 1; }
+info() { printf "${CYAN}[i]${NC} %s\n" "$*"; }
+
+detect_arch() {
+ local arch
+ arch=$(uname -m)
+ case "$arch" in
+ x86_64|amd64) echo "x86_64" ;;
+ aarch64|arm64) echo "aarch64" ;;
+ *) err "Unsupported architecture: $arch" ;;
+ esac
+}
+
+detect_os() {
+ local os
+ os=$(uname -s)
+ case "$os" in
+ Linux) echo "unknown-linux-gnu" ;;
+ Darwin) echo "apple-darwin" ;;
+ *) err "Unsupported OS: $os" ;;
+ esac
+}
+
+get_release_url() {
+ local os_arch="$1"
+ if [ "$VERSION" = "latest" ]; then
+ echo "https://github.com/$REPO/releases/latest/download/oura-${os_arch}"
+ else
+ echo "https://github.com/$REPO/releases/download/$VERSION/oura-${os_arch}"
+ fi
+}
+
+main() {
+ echo ""
+ printf "${CYAN}╔══════════════════════════════════════╗${NC}\n"
+ printf "${CYAN}║ Oura Installer — 0XFFRice ║${NC}\n"
+ printf "${CYAN}╚══════════════════════════════════════╝${NC}\n"
+ echo ""
+
+ if [ "$(id -u)" -eq 0 ]; then
+ warn "Running as root — installing system-wide to $INSTALL_DIR"
+ else
+ info "Running as user — installing to $INSTALL_DIR"
+ if ! mkdir -p "$INSTALL_DIR" 2>/dev/null; then
+ info "Need sudo to write to $INSTALL_DIR"
+ exec sudo "$0" "$@"
+ fi
+ fi
+
+ local arch vendor os_arch
+ arch=$(detect_arch)
+ vendor=$(detect_os)
+ os_arch="${arch}-${vendor}"
+ local url
+ url=$(get_release_url "$os_arch")
+
+ info "Detected: $os_arch"
+ info "Download: $url"
+
+ local tmpdir
+ tmpdir=$(mktemp -d)
+ trap 'rm -rf "$tmpdir"' EXIT
+
+ if command -v curl &>/dev/null; then
+ curl -fsSL "$url" -o "$tmpdir/oura" || err "Download failed"
+ elif command -v wget &>/dev/null; then
+ wget -q "$url" -O "$tmpdir/oura" || err "Download failed"
+ else
+ err "Need curl or wget"
+ fi
+
+ chmod +x "$tmpdir/oura"
+ "$tmpdir/oura" --version &>/dev/null || err "Binary validation failed"
+
+ mkdir -p "$INSTALL_DIR"
+ cp "$tmpdir/oura" "$INSTALL_DIR/oura"
+ log "Installed: $INSTALL_DIR/oura"
+
+ mkdir -p "$CONFIG_DIR"
+ if [ ! -f "$CONFIG_DIR/config.toml" ]; then
+ cat > "$CONFIG_DIR/config.toml" << 'TOML'
+[loop_engine]
+max_iterations = 20
+convergence_threshold = 90.0
+feedback_sources = ["test", "lint"]
+
+[github]
+enabled = true
+default_owner = "MethodWhite"
+default_repo = "my-project"
+auto_commit = true
+auto_pr = true
+
+# [synapsis] # Optional: uncomment for Synapsis integration (separate project)
+# enabled = true
+# endpoint = "http://localhost:7438"
+TOML
+ log "Config created: $CONFIG_DIR/config.toml"
+ else
+ warn "Config exists at $CONFIG_DIR/config.toml — skipping"
+ fi
+
+ if echo "$PATH" | tr ':' '\n' | grep -qx "$INSTALL_DIR"; then
+ log "Ready to use. Run: oura --help"
+ else
+ warn "$INSTALL_DIR is not in PATH. Add it:"
+ warn " export PATH=\"\$PATH:$INSTALL_DIR\""
+ fi
+
+ echo ""
+ log "Oura installed successfully!"
+ "$INSTALL_DIR/oura" version 2>/dev/null || true
+ echo ""
+}
+
+main "$@"
diff --git a/mcp-config/cursor.json b/mcp-config/cursor.json
index 0d58f9b..0018fc0 100644
--- a/mcp-config/cursor.json
+++ b/mcp-config/cursor.json
@@ -1,6 +1,7 @@
{
- "mcp": {
+ "mcpServers": {
"oura": {
+ "type": "stdio",
"command": "/home/methodwhite/Proyectos/oura/target/release/oura"
}
}
diff --git a/mcp-config/opencode.json b/mcp-config/opencode.json
index 7c10f1d..0018fc0 100644
--- a/mcp-config/opencode.json
+++ b/mcp-config/opencode.json
@@ -2,10 +2,7 @@
"mcpServers": {
"oura": {
"type": "stdio",
- "command": "/home/methodwhite/Proyectos/oura/target/release/oura",
- "env": {
- "SYNAPSIS_ENDPOINT": "http://localhost:7438"
- }
+ "command": "/home/methodwhite/Proyectos/oura/target/release/oura"
}
}
}
diff --git a/src/agents.rs b/src/agents.rs
index 201381f..b5de968 100644
--- a/src/agents.rs
+++ b/src/agents.rs
@@ -88,6 +88,32 @@ const DANGEROUS_PATTERNS: &[DangerousPattern] = &[
),
];
+struct CompiledPattern {
+ type_: &'static str,
+ severity: &'static str,
+ regex: regex::Regex,
+ description: &'static str,
+ recommendation: &'static str,
+ langs: &'static [&'static str],
+}
+
+fn compiled_patterns() -> &'static [CompiledPattern] {
+ static PATTERNS: std::sync::OnceLock> = std::sync::OnceLock::new();
+ PATTERNS.get_or_init(|| {
+ DANGEROUS_PATTERNS.iter().filter_map(|(type_, severity, pattern, description, recommendation, langs)| {
+ match regex::Regex::new(pattern) {
+ Ok(regex) => Some(CompiledPattern {
+ type_, severity, regex, description, recommendation, langs,
+ }),
+ Err(e) => {
+ eprintln!("[Oura] Warning: failed to compile security pattern '{}': {}", type_, e);
+ None
+ }
+ }
+ }).collect()
+ })
+}
+
impl SecurityAuditor {
pub fn new() -> Self {
Self
@@ -95,22 +121,32 @@ impl SecurityAuditor {
pub fn audit(&self, files: &[String]) -> Vec {
let mut entries = vec![];
+ let compiled = compiled_patterns();
for file in files {
- let ext = std::path::Path::new(file)
- .extension()
+ let path = std::path::Path::new(file);
+ if let Ok(meta) = path.metadata() {
+ if meta.len() > 10_000_000 {
+ continue;
+ }
+ }
+
+ let ext = path.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_lowercase();
let content = match fs::read_to_string(file) {
Ok(c) => c,
- Err(_) => continue,
+ Err(e) => {
+ eprintln!("[Oura] SecurityAuditor: skipping unreadable file {}: {}", file, e);
+ continue;
+ }
};
let lines: Vec<&str> = content.lines().collect();
- for (type_, severity, pattern, description, recommendation, langs) in DANGEROUS_PATTERNS
+ for CompiledPattern { type_, severity, regex, description, recommendation, langs } in compiled
{
// Skip pattern if its language list doesn't match the file extension
let ext_match = |ext: &str, langs: &[&str]| -> bool {
@@ -124,22 +160,17 @@ impl SecurityAuditor {
"php" => "php",
"sql" => "sql",
"html" | "htm" | "xhtml" => "html",
- _ => "",
+ _ => return false,
};
- mapped.is_empty() || langs.contains(&mapped)
+ langs.contains(&mapped)
};
if !ext_match(&ext, langs) {
continue;
}
- let re = match Regex::new(pattern) {
- Ok(r) => r,
- Err(_) => continue,
- };
-
for (i, line) in lines.iter().enumerate() {
- if re.is_match(line) {
+ if regex.is_match(line) {
entries.push(SecurityAuditEntry {
type_: type_.to_string(),
severity: severity.to_string(),
@@ -161,7 +192,7 @@ pub struct RefactorEngine;
const CLEAN_CODE_PATTERNS: &[(&str, &str, &str)] = &[
(
- "catch\\s*\\([^)]*\\)\\s*\\{[^}]*\\}",
+ "catch\\s*\\([^)]*\\)\\s*\\{",
"Generic catch clause",
"Type the error or add specific error handling",
),
diff --git a/src/config.rs b/src/config.rs
index bb43681..dec3f44 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -10,17 +10,24 @@ pub struct Config {
#[serde(default)]
pub github: GitHubConfig,
#[serde(default)]
- pub synapsis: SynapsisConfig,
- #[serde(default)]
pub logging: LoggingConfig,
+ #[serde(default)]
+ pub connector: ConnectorConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
pub struct GeneralConfig {
+ #[serde(default)]
pub data_dir: Option,
+ #[serde(default = "default_profile")]
pub profile: String,
}
+fn default_profile() -> String {
+ "default".into()
+}
+
impl Default for GeneralConfig {
fn default() -> Self {
Self {
@@ -30,12 +37,28 @@ impl Default for GeneralConfig {
}
}
+fn default_threshold() -> f64 { 90.0 }
+fn default_feedback_sources() -> Vec { vec!["test".into(), "lint".into()] }
+fn default_max_runtime() -> u64 { 3600 }
+fn default_max_iterations() -> u32 { 20 }
+fn default_pr_prefix() -> String { "[Oura] ".into() }
+fn default_logging_level() -> String { "info".into() }
+fn default_logging_format() -> String { "text".into() }
+fn default_logging_output() -> String { "stderr".into() }
+
#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
pub struct LoopEngineConfig {
+ #[serde(default = "default_max_iterations")]
pub max_iterations: u32,
+ #[serde(default = "default_threshold")]
pub convergence_threshold: f64,
+ #[serde(default = "default_feedback_sources")]
pub feedback_sources: Vec,
+ #[serde(default)]
pub working_directory: Option,
+ #[serde(default = "default_max_runtime")]
+ pub max_runtime_secs: u64,
}
impl Default for LoopEngineConfig {
@@ -45,21 +68,43 @@ impl Default for LoopEngineConfig {
convergence_threshold: 90.0,
feedback_sources: vec!["test".into(), "lint".into()],
working_directory: None,
+ max_runtime_secs: 3600,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
pub struct GitHubConfig {
+ #[serde(default)]
pub enabled: bool,
+ #[serde(default)]
pub default_owner: String,
+ #[serde(default)]
pub default_repo: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub token: Option,
+ #[serde(default)]
pub auto_commit: bool,
+ #[serde(default)]
pub auto_pr: bool,
+ #[serde(default = "default_pr_prefix")]
pub pr_title_prefix: String,
+ #[serde(default)]
pub workflows_enabled: bool,
- pub repos: Vec,
+}
+
+#[allow(dead_code)]
+impl GitHubConfig {
+ pub fn masked_token(&self) -> Option {
+ self.token.as_ref().map(|t| {
+ if t.len() > 8 {
+ format!("{}…{}", &t[..4], &t[t.len()-4..])
+ } else {
+ "********".into()
+ }
+ })
+ }
}
impl Default for GitHubConfig {
@@ -73,55 +118,73 @@ impl Default for GitHubConfig {
auto_pr: false,
pr_title_prefix: "[Oura] ".into(),
workflows_enabled: true,
- repos: vec![],
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct RepoConfig {
- pub owner: String,
- pub repo: String,
- pub branch: String,
- pub base_branch: String,
- pub auto_sync: bool,
- pub workflows: Vec,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct SynapsisConfig {
- pub enabled: bool,
- pub endpoint: String,
- pub mcp_command: String,
+#[serde(deny_unknown_fields)]
+pub struct LoggingConfig {
+ #[serde(default = "default_logging_level")]
+ pub level: String,
+ #[serde(default = "default_logging_format")]
+ pub format: String,
+ #[serde(default = "default_logging_output")]
+ pub output: String,
}
-impl Default for SynapsisConfig {
+impl Default for LoggingConfig {
fn default() -> Self {
Self {
- enabled: true,
- endpoint: "http://localhost:7438".into(),
- mcp_command: "synapsis-mcp".into(),
+ level: "info".into(),
+ format: "text".into(),
+ output: "stderr".into(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct LoggingConfig {
- pub level: String,
- pub format: String,
- pub output: String,
+#[serde(deny_unknown_fields)]
+pub struct ConnectorConfig {
+ #[serde(default)]
+ pub enabled: bool,
+ #[serde(default)]
+ pub transport: String,
+ #[serde(default)]
+ pub server_url: String,
+ #[serde(default)]
+ pub host: String,
+ #[serde(default)]
+ pub port: u16,
+ #[serde(default)]
+ pub endpoint: String,
+ #[serde(default)]
+ pub tools: Vec,
+ #[serde(default)]
+ pub auto_call: bool,
}
-impl Default for LoggingConfig {
+impl Default for ConnectorConfig {
fn default() -> Self {
Self {
- level: "info".into(),
- format: "text".into(),
- output: "stderr".into(),
+ enabled: false,
+ transport: "http".into(),
+ server_url: "http://localhost:7438".into(),
+ host: "127.0.0.1".into(),
+ port: 7439,
+ endpoint: "/message".into(),
+ tools: vec![],
+ auto_call: false,
}
}
}
+fn quiet_eprint(msg: &str) {
+ if std::env::var("OURA_QUIET").is_err() {
+ eprintln!("{}", msg);
+ }
+}
+
impl Config {
pub fn load() -> Self {
let config_paths = vec![
@@ -132,26 +195,31 @@ impl Config {
for path in config_paths.into_iter().flatten() {
if path.exists() {
- let content = std::fs::read_to_string(&path).unwrap_or_default();
+ let content = match std::fs::read_to_string(&path) {
+ Ok(c) => c,
+ Err(e) => {
+ quiet_eprint(&format!("[Oura] Warning: couldn't read config at {}: {}", path.display(), e));
+ quiet_eprint("[Oura] Using default configuration");
+ return Self::apply_env_overrides(Config::default());
+ }
+ };
match toml::from_str(&content) {
Ok(config) => {
- if std::env::var("OURA_QUIET").is_err() && std::env::var("QUIET").is_err() {
- eprintln!("[Oura] Loaded config from: {}", path.display());
- }
+ quiet_eprint(&format!("[Oura] Loaded config from: {}", path.display()));
return Self::apply_env_overrides(config);
}
Err(e) => {
- eprintln!(
+ quiet_eprint(&format!(
"[Oura] Warning: failed to parse config at {}: {}",
path.display(),
e
- );
+ ));
}
}
}
}
- eprintln!("[Oura] Using default configuration");
+ quiet_eprint("[Oura] Using default configuration");
Self::apply_env_overrides(Config::default())
}
@@ -162,8 +230,10 @@ impl Config {
}
}
if let Ok(val) = std::env::var("OURA_CONVERGENCE_THRESHOLD") {
- if let Ok(n) = val.parse() {
- config.loop_engine.convergence_threshold = n;
+ if let Ok(n) = val.parse::() {
+ if n.is_finite() && (0.0..=100.0).contains(&n) {
+ config.loop_engine.convergence_threshold = n;
+ }
}
}
if let Ok(val) = std::env::var("OURA_GITHUB_TOKEN") {
@@ -178,9 +248,6 @@ impl Config {
if let Ok(val) = std::env::var("OURA_GITHUB_ENABLED") {
config.github.enabled = val == "true" || val == "1";
}
- if let Ok(val) = std::env::var("OURA_SYNAPSIS_ENDPOINT") {
- config.synapsis.endpoint = val;
- }
if let Ok(val) = std::env::var("OURA_WORKING_DIR") {
config.loop_engine.working_directory = Some(val);
}
@@ -194,7 +261,7 @@ impl Config {
let config = Config::default();
let toml_str = toml::to_string_pretty(&config)?;
std::fs::write(path, toml_str)?;
- eprintln!("[Oura] Default config written to: {}", path.display());
+ quiet_eprint(&format!("[Oura] Default config written to: {}", path.display()));
Ok(())
}
@@ -222,7 +289,6 @@ mod tests {
assert_eq!(config.loop_engine.max_iterations, 20);
assert_eq!(config.loop_engine.convergence_threshold, 90.0);
assert!(!config.github.enabled);
- assert!(config.synapsis.enabled);
}
#[test]
@@ -238,6 +304,7 @@ mod tests {
assert_eq!(config.max_iterations, 20);
assert_eq!(config.convergence_threshold, 90.0);
assert_eq!(config.feedback_sources, vec!["test", "lint"]);
+ assert_eq!(config.max_runtime_secs, 3600);
}
#[test]
@@ -249,13 +316,6 @@ mod tests {
assert_eq!(config.pr_title_prefix, "[Oura] ");
}
- #[test]
- fn test_synapsis_config_default() {
- let config = SynapsisConfig::default();
- assert!(config.enabled);
- assert_eq!(config.endpoint, "http://localhost:7438");
- }
-
#[test]
fn test_logging_config_default() {
let config = LoggingConfig::default();
@@ -277,6 +337,47 @@ mod tests {
);
}
+ #[test]
+ fn test_config_partial_section() {
+ let toml_str = "[loop_engine]\nmax_iterations = 5\n".to_string();
+ let config: Config = toml::from_str(&toml_str).unwrap();
+ assert_eq!(config.loop_engine.max_iterations, 5);
+ assert_eq!(config.loop_engine.convergence_threshold, 90.0);
+ assert_eq!(config.loop_engine.max_runtime_secs, 3600);
+ }
+
+ #[test]
+ fn test_config_unknown_key_rejected() {
+ let toml_str = "[loop_engine]\nunknown_key = true\nmax_iterations = 5\n".to_string();
+ let result: Result = toml::from_str(&toml_str);
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn test_convergence_threshold_env_nan_rejected() {
+ std::env::set_var("OURA_CONVERGENCE_THRESHOLD", "nan");
+ let config = Config::apply_env_overrides(Config::default());
+ // nan should be rejected, default remains
+ assert_eq!(config.loop_engine.convergence_threshold, 90.0);
+ std::env::remove_var("OURA_CONVERGENCE_THRESHOLD");
+ }
+
+ #[test]
+ fn test_convergence_threshold_env_out_of_range_rejected() {
+ std::env::set_var("OURA_CONVERGENCE_THRESHOLD", "200");
+ let config = Config::apply_env_overrides(Config::default());
+ assert_eq!(config.loop_engine.convergence_threshold, 90.0);
+ std::env::remove_var("OURA_CONVERGENCE_THRESHOLD");
+ }
+
+ #[test]
+ fn test_convergence_threshold_env_valid() {
+ std::env::set_var("OURA_CONVERGENCE_THRESHOLD", "85.5");
+ let config = Config::apply_env_overrides(Config::default());
+ assert_eq!(config.loop_engine.convergence_threshold, 85.5);
+ std::env::remove_var("OURA_CONVERGENCE_THRESHOLD");
+ }
+
#[test]
fn test_apply_env_overrides() {
std::env::set_var("OURA_MAX_ITERATIONS", "50");
diff --git a/src/connector.rs b/src/connector.rs
new file mode 100644
index 0000000..bd05af5
--- /dev/null
+++ b/src/connector.rs
@@ -0,0 +1,122 @@
+use anyhow::{Context, Result};
+use quinn::{ClientConfig, Endpoint, EndpointConfig, TransportConfig};
+use std::sync::Arc;
+use std::time::Duration;
+
+pub struct QuicConnector {
+ endpoint: Endpoint,
+}
+
+impl QuicConnector {
+ pub fn new() -> Result {
+ let mut transport = TransportConfig::default();
+ transport.max_idle_timeout(Some(Duration::from_secs(30).try_into().unwrap()));
+ transport.keep_alive_interval(Some(Duration::from_secs(5)));
+
+ let crypto = rustls::ClientConfig::builder()
+ .dangerous()
+ .with_custom_certificate_verifier(Arc::new(SkipVerification))
+ .with_no_client_auth();
+
+ let quic_config = quinn::crypto::rustls::QuicClientConfig::try_from(crypto)?;
+ let mut client_config = ClientConfig::new(Arc::new(quic_config));
+ client_config.transport_config(Arc::new(transport));
+
+ let socket = std::net::UdpSocket::bind("0.0.0.0:0")?;
+ let mut endpoint = Endpoint::new(
+ EndpointConfig::default(),
+ None::,
+ socket,
+ Arc::new(quinn::TokioRuntime),
+ )?;
+ endpoint.set_default_client_config(client_config);
+
+ Ok(Self { endpoint })
+ }
+
+ pub async fn connect(&self, host: &str, port: u16) -> Result {
+ let addr: std::net::SocketAddr = format!("{}:{}", host, port)
+ .parse()
+ .context("Invalid host:port")?;
+ Ok(self.endpoint.connect(addr, host)?.await?)
+ }
+
+ pub async fn call_tool(
+ &self, host: &str, port: u16,
+ tool_name: &str, arguments: &serde_json::Value,
+ ) -> Result {
+ let conn = self.connect(host, port).await
+ .context("QUIC connection failed")?;
+ let (mut send, mut recv) = conn.open_bi().await
+ .context("Failed to open QUIC stream")?;
+
+ let request = serde_json::json!({
+ "jsonrpc": "2.0", "id": "1", "method": "tools/call",
+ "params": { "name": tool_name, "arguments": arguments }
+ });
+ let body = serde_json::to_vec(&request)?;
+
+ let len = body.len() as u32;
+ send.write_all(&len.to_be_bytes()).await?;
+ send.write_all(&body).await?;
+ let _ = send.finish();
+
+ let mut len_buf = [0u8; 4];
+ recv.read_exact(&mut len_buf).await?;
+ let resp_len = u32::from_be_bytes(len_buf) as usize;
+
+ let mut resp_buf = vec![0u8; resp_len];
+ recv.read_exact(&mut resp_buf).await?;
+
+ Ok(String::from_utf8(resp_buf)?)
+ }
+}
+
+#[derive(Debug)]
+struct SkipVerification;
+
+impl rustls::client::danger::ServerCertVerifier for SkipVerification {
+ fn verify_server_cert(
+ &self,
+ _end_entity: &rustls::pki_types::CertificateDer<'_>,
+ _intermediates: &[rustls::pki_types::CertificateDer<'_>],
+ _server_name: &rustls::pki_types::ServerName<'_>,
+ _ocsp_response: &[u8],
+ _now: rustls::pki_types::UnixTime,
+ ) -> Result {
+ Ok(rustls::client::danger::ServerCertVerified::assertion())
+ }
+
+ fn verify_tls12_signature(
+ &self,
+ _message: &[u8],
+ _cert: &rustls::pki_types::CertificateDer<'_>,
+ _dss: &rustls::DigitallySignedStruct,
+ ) -> Result {
+ Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
+ }
+
+ fn verify_tls13_signature(
+ &self,
+ _message: &[u8],
+ _cert: &rustls::pki_types::CertificateDer<'_>,
+ _dss: &rustls::DigitallySignedStruct,
+ ) -> Result {
+ Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
+ }
+
+ fn supported_verify_schemes(&self) -> Vec {
+ vec![
+ rustls::SignatureScheme::RSA_PKCS1_SHA256,
+ rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
+ rustls::SignatureScheme::RSA_PSS_SHA256,
+ rustls::SignatureScheme::RSA_PKCS1_SHA384,
+ rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
+ rustls::SignatureScheme::RSA_PSS_SHA384,
+ rustls::SignatureScheme::RSA_PKCS1_SHA512,
+ rustls::SignatureScheme::ECDSA_NISTP521_SHA512,
+ rustls::SignatureScheme::RSA_PSS_SHA512,
+ rustls::SignatureScheme::ED25519,
+ ]
+ }
+}
diff --git a/src/engine.rs b/src/engine.rs
index 174f5d4..2f8d82e 100644
--- a/src/engine.rs
+++ b/src/engine.rs
@@ -1,7 +1,8 @@
+use crate::config::{ConnectorConfig, LoopEngineConfig};
use crate::error::{OuraError, Result};
use crate::events::{EventBus, OuraEvent};
-use crate::feedback::{ClippyFeedbackCollector, ProfileFeedbackCollector, TestFeedbackCollector};
-use crate::traits::{CompositeFeedbackCollector, DefaultCommandRunner, FeedbackCollector};
+use crate::feedback::{ClippyFeedbackCollector, ConnectorFeedbackCollector, ProfileFeedbackCollector, TestFeedbackCollector};
+use crate::traits::{CommandRunner, CompositeFeedbackCollector, DefaultCommandRunner, FeedbackCollector};
use crate::types::*;
use chrono::Utc;
use std::sync::{
@@ -11,6 +12,14 @@ use std::sync::{
use tokio::sync::Notify;
use uuid::Uuid;
+fn lock_state(state: &Arc>>) -> Result>> {
+ state.lock().map_err(|e| OuraError::Internal(format!("Lock poisoned: {}", e)))
+}
+
+fn lock_value(mutex: &Arc>) -> Result> {
+ mutex.lock().map_err(|e| OuraError::Internal(format!("Lock poisoned: {}", e)))
+}
+
pub struct LoopEngine {
state: Arc>>,
max_iterations: Arc>,
@@ -27,31 +36,55 @@ impl Drop for LoopEngine {
fn drop(&mut self) {
self.stop_flag.store(true, Ordering::SeqCst);
self.stop_notify.notify_waiters();
+ }
+}
+
+impl LoopEngine {
+ pub async fn shutdown(&mut self) {
+ self.stop_flag.store(true, Ordering::SeqCst);
+ self.stop_notify.notify_waiters();
if let Some(handle) = self.loop_handle.take() {
- handle.abort();
+ tokio::select! {
+ _ = handle => {},
+ _ = tokio::time::sleep(std::time::Duration::from_secs(3)) => {},
+ }
}
}
}
impl LoopEngine {
- pub fn new(max_iterations: u32, convergence_threshold: f64) -> Self {
- let command_runner = Box::new(DefaultCommandRunner);
+ pub fn new(config: &LoopEngineConfig, connector_config: &ConnectorConfig) -> Self {
let mut composite = CompositeFeedbackCollector::new();
- composite.add(Box::new(TestFeedbackCollector::new(
- Box::new(DefaultCommandRunner),
- "cargo test 2>&1".to_string(),
- )));
- composite.add(Box::new(ClippyFeedbackCollector::new(
- Box::new(DefaultCommandRunner),
- "cargo clippy 2>&1".to_string(),
- )));
- composite.add(Box::new(ProfileFeedbackCollector));
+ let make_runner = |dir: &Option| -> Box {
+ match dir {
+ Some(d) => Box::new(DefaultCommandRunner::new_with_dir(std::path::PathBuf::from(d))),
+ None => Box::new(DefaultCommandRunner::new()),
+ }
+ };
+ let runner = make_runner(&config.working_directory);
+ if config.feedback_sources.contains(&"test".to_string()) {
+ composite.add(Box::new(TestFeedbackCollector::new(runner)));
+ }
+ let runner = make_runner(&config.working_directory);
+ if config.feedback_sources.contains(&"lint".to_string()) {
+ composite.add(Box::new(ClippyFeedbackCollector::new(runner)));
+ }
+ if config.feedback_sources.contains(&"profile".to_string()) {
+ let collector = match &config.working_directory {
+ Some(d) => ProfileFeedbackCollector::new_with_dir(std::path::PathBuf::from(d)),
+ None => ProfileFeedbackCollector::new(),
+ };
+ composite.add(Box::new(collector));
+ }
+ if connector_config.enabled && !connector_config.server_url.is_empty() && !connector_config.tools.is_empty() {
+ composite.add(Box::new(ConnectorFeedbackCollector::new(connector_config.clone())));
+ }
Self {
state: Arc::new(Mutex::new(None)),
- max_iterations: Arc::new(Mutex::new(max_iterations)),
- convergence_threshold: Arc::new(Mutex::new(convergence_threshold)),
- max_runtime_secs: Arc::new(Mutex::new(3600)),
+ max_iterations: Arc::new(Mutex::new(config.max_iterations)),
+ convergence_threshold: Arc::new(Mutex::new(config.convergence_threshold)),
+ max_runtime_secs: Arc::new(Mutex::new(config.max_runtime_secs)),
stop_flag: Arc::new(AtomicBool::new(false)),
stop_notify: Arc::new(Notify::new()),
feedback_collector: Arc::new(composite),
@@ -60,6 +93,7 @@ impl LoopEngine {
}
}
+ #[allow(dead_code)]
pub fn with_feedback_collector(
max_iterations: u32,
convergence_threshold: f64,
@@ -82,7 +116,7 @@ impl LoopEngine {
&self.event_bus
}
- pub async fn start(&mut self, goal: &str) -> Result {
+ pub async fn start(&mut self, goal: &str, manual: bool, max_iterations: Option) -> Result {
if let Some(ref handle) = self.loop_handle {
if !handle.is_finished() {
return Err(OuraError::LoopAlreadyRunning);
@@ -92,7 +126,7 @@ impl LoopEngine {
self.stop_flag.store(false, Ordering::SeqCst);
{
- let state_guard = self.state.lock().unwrap();
+ let state_guard = lock_state(&self.state)?;
if let Some(ref state) = *state_guard {
if state.status == "running" {
return Err(OuraError::LoopAlreadyRunning);
@@ -100,10 +134,18 @@ impl LoopEngine {
}
}
+ let max_iter = max_iterations.unwrap_or(*lock_value(&self.max_iterations)?);
+ let threshold = *lock_value(&self.convergence_threshold)?;
+ let runtime = *lock_value(&self.max_runtime_secs)?;
let initial_state = LoopState {
id: Uuid::new_v4().to_string(),
goal: goal.into(),
- config: OuraConfig::default(),
+ config: OuraConfig {
+ max_iterations: max_iter,
+ convergence_threshold: threshold,
+ max_runtime_secs: runtime,
+ ..OuraConfig::default()
+ },
current_iteration: 0,
history: vec![],
status: "running".into(),
@@ -111,7 +153,7 @@ impl LoopEngine {
};
{
- let mut state_guard = self.state.lock().unwrap();
+ let mut state_guard = lock_state(&self.state)?;
*state_guard = Some(initial_state.clone());
}
@@ -121,8 +163,12 @@ impl LoopEngine {
timestamp: Utc::now().to_rfc3339(),
});
+ if manual {
+ return Ok(initial_state);
+ }
+
let state_clone = self.state.clone();
- let max_iter_clone = self.max_iterations.clone();
+ let max_iter_limit = max_iter;
let threshold_clone = self.convergence_threshold.clone();
let runtime_clone = self.max_runtime_secs.clone();
let stop_flag_clone = self.stop_flag.clone();
@@ -133,11 +179,20 @@ impl LoopEngine {
let handle = tokio::spawn(async move {
let loop_start = std::time::Instant::now();
- let max_runtime = *runtime_clone.lock().unwrap();
+ let max_runtime = match runtime_clone.lock() {
+ Ok(guard) => *guard,
+ Err(_) => {
+ tracing::error!("Lock poisoned in runtime");
+ return;
+ }
+ };
loop {
if stop_flag_clone.load(Ordering::SeqCst) {
- let mut state_guard = state_clone.lock().unwrap();
+ let mut state_guard = match state_clone.lock() {
+ Ok(g) => g,
+ Err(_) => { tracing::error!("Lock poisoned"); return; }
+ };
if let Some(ref mut st) = *state_guard {
st.status = "stopped".into();
}
@@ -153,7 +208,10 @@ impl LoopEngine {
}
if max_runtime > 0 && loop_start.elapsed().as_secs() > max_runtime {
- let mut state_guard = state_clone.lock().unwrap();
+ let mut state_guard = match state_clone.lock() {
+ Ok(g) => g,
+ Err(_) => { tracing::error!("Lock poisoned"); return; }
+ };
if let Some(ref mut st) = *state_guard {
st.status = "failed".into();
}
@@ -166,7 +224,10 @@ impl LoopEngine {
}
let iteration_num = {
- let mut state_guard = state_clone.lock().unwrap();
+ let mut state_guard = match state_clone.lock() {
+ Ok(g) => g,
+ Err(_) => { tracing::error!("Lock poisoned"); return; }
+ };
let st = match state_guard.as_mut() {
Some(s) => s,
None => break,
@@ -174,7 +235,7 @@ impl LoopEngine {
if st.status != "running" {
break;
}
- st.current_iteration += 1;
+ st.current_iteration = st.current_iteration.saturating_add(1);
st.current_iteration
};
@@ -184,10 +245,42 @@ impl LoopEngine {
timestamp: Utc::now().to_rfc3339(),
});
- let max_iter = *max_iter_clone.lock().unwrap();
- let threshold = *threshold_clone.lock().unwrap();
+ let threshold = match threshold_clone.lock() {
+ Ok(g) => *g,
+ Err(_) => { tracing::error!("Lock poisoned in threshold"); return; }
+ };
- let feedback_entries = feedback_collector.collect().await;
+ let feedback_entries = {
+ let collect = feedback_collector.collect();
+ tokio::select! {
+ biased;
+ _ = stop_notify_clone.notified() => {
+ let mut state_guard = match state_clone.lock() {
+ Ok(g) => g,
+ Err(_) => { tracing::error!("Lock poisoned"); return; }
+ };
+ if let Some(ref mut st) = *state_guard {
+ st.status = "stopped".into();
+ }
+ event_bus.publish(OuraEvent::LoopStopped {
+ loop_id: loop_id.clone(),
+ iterations: iteration_num,
+ timestamp: Utc::now().to_rfc3339(),
+ });
+ break;
+ }
+ _ = tokio::time::sleep(std::time::Duration::from_secs(600)) => {
+ tracing::error!("Feedback collection timed out after 600s");
+ event_bus.publish(OuraEvent::Error {
+ loop_id: Some(loop_id.clone()),
+ message: "Feedback collection timed out".to_string(),
+ timestamp: Utc::now().to_rfc3339(),
+ });
+ Vec::new()
+ }
+ result = collect => result,
+ }
+ };
event_bus.publish(OuraEvent::FeedbackCollected {
loop_id: loop_id.clone(),
@@ -208,13 +301,11 @@ impl LoopEngine {
let mut score = 100.0 - (error_count * 15.0) - (warning_count * 5.0);
score = score.clamp(0.0, 100.0);
- let has_feedback = !feedback_entries.is_empty();
- let converged = has_feedback
- && (score >= threshold || (error_count == 0.0 && warning_count == 0.0));
+ let converged = score >= threshold;
let status = if converged {
- "converged"
- } else if iteration_num >= max_iter {
+ "completed"
+ } else if iteration_num >= max_iter_limit {
"failed"
} else {
"running"
@@ -239,7 +330,10 @@ impl LoopEngine {
});
{
- let mut state_guard = state_clone.lock().unwrap();
+ let mut state_guard = match state_clone.lock() {
+ Ok(g) => g,
+ Err(_) => { tracing::error!("Lock poisoned in state update"); return; }
+ };
let st = match state_guard.as_mut() {
Some(s) => s,
None => break,
@@ -252,7 +346,7 @@ impl LoopEngine {
final_score: score,
timestamp: Utc::now().to_rfc3339(),
});
- } else if iteration_num >= max_iter {
+ } else if iteration_num >= max_iter_limit {
st.status = "failed".into();
}
st.history.push(result);
@@ -265,7 +359,10 @@ impl LoopEngine {
tokio::select! {
_ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {}
_ = stop_notify_clone.notified() => {
- let mut state_guard = state_clone.lock().unwrap();
+ let mut state_guard = match state_clone.lock() {
+ Ok(g) => g,
+ Err(_) => { tracing::error!("Lock poisoned in stop notify"); return; }
+ };
if let Some(ref mut st) = *state_guard {
st.status = "stopped".into();
}
@@ -291,20 +388,28 @@ impl LoopEngine {
}
}
- let mut state_guard = self
- .state
- .lock()
- .map_err(|_| OuraError::Internal("Lock poisoned".to_string()))?;
- let state = state_guard.as_mut().ok_or(OuraError::NoActiveLoop)?;
+ let iteration_num = {
+ let mut state_guard = self
+ .state
+ .lock()
+ .map_err(|_| OuraError::Internal("Lock poisoned".to_string()))?;
+ let state = state_guard.as_mut().ok_or(OuraError::NoActiveLoop)?;
- if state.status != "running" {
- return Err(OuraError::LoopNotRunning(state.status.clone()));
- }
+ if state.status != "running" {
+ return Err(OuraError::LoopNotRunning(state.status.clone()));
+ }
- state.current_iteration += 1;
- let iteration_num = state.current_iteration;
+ state.current_iteration = state.current_iteration.saturating_add(1);
+ state.current_iteration
+ };
- let feedback_entries = self.feedback_collector.collect().await;
+ let feedback_entries = tokio::time::timeout(
+ std::time::Duration::from_secs(600),
+ self.feedback_collector.collect(),
+ ).await.unwrap_or_else(|_| {
+ tracing::error!("Feedback collection timed out during manual iteration");
+ vec![]
+ });
let error_count = feedback_entries
.iter()
@@ -318,15 +423,13 @@ impl LoopEngine {
let mut score = 100.0 - (error_count * 15.0) - (warning_count * 5.0);
score = score.clamp(0.0, 100.0);
- let has_feedback = !feedback_entries.is_empty();
- let converged = has_feedback
- && (score >= *self.convergence_threshold.lock().unwrap()
- || (error_count == 0.0 && warning_count == 0.0));
+ let threshold = *lock_value(&self.convergence_threshold)?;
+ let converged = score >= threshold;
- let max_iter = *self.max_iterations.lock().unwrap();
+ let max_iter = *lock_value(&self.max_iterations)?;
let status = if converged {
- "converged"
+ "completed"
} else if iteration_num >= max_iter {
"failed"
} else {
@@ -343,6 +446,12 @@ impl LoopEngine {
score,
};
+ let mut state_guard = self
+ .state
+ .lock()
+ .map_err(|_| OuraError::Internal("Lock poisoned".to_string()))?;
+ let state = state_guard.as_mut().ok_or(OuraError::NoActiveLoop)?;
+
if converged {
state.status = "completed".into();
} else if iteration_num >= max_iter {
@@ -353,85 +462,100 @@ impl LoopEngine {
Ok(result)
}
- pub fn stop(&mut self) -> u32 {
+ pub fn stop(&mut self) -> Result {
self.stop_flag.store(true, Ordering::SeqCst);
self.stop_notify.notify_waiters();
- let state_guard = self.state.lock().unwrap();
- state_guard
- .as_ref()
- .map(|s| s.current_iteration)
- .unwrap_or(0)
+ let mut guard = self.state.lock()
+ .map_err(|e| OuraError::Internal(format!("Lock poisoned: {}", e)))?;
+ if let Some(ref mut st) = *guard {
+ st.status = "stopped".into();
+ Ok(st.current_iteration)
+ } else {
+ Ok(0)
+ }
}
- pub fn get_state(&self) -> Option {
- self.state.lock().unwrap().clone()
+ pub fn get_state(&self) -> Result