The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(composio): stop the contract gate disabling itself over time
M3gA-Minded370fd531e2
diff --git a/crates/openhuman-core/src/integrations/composio/contract_gate.rs b/crates/openhuman-core/src/integrations/composio/contract_gate.rsindex 5beb35b794..e26a3b5905 100644--- a/crates/openhuman-core/src/integrations/composio/contract_gate.rs+++ b/crates/openhuman-core/src/integrations/composio/contract_gate.rs@@ -53,31 +53,37 @@ use crate::integrations::composio::providers::toolkit_from_slug;/// the same contract and the action would never execute — causing an infinite/// loop ("same tool call 3× in a row" guard).///-/// A global [`OnceLock`] map tracks how many *unique gate instances* have-/// consulted each slug for the "first time". After 3+ fresh instances have all-/// surfaced the same contract, the next instance auto-proceeds: the model has-/// clearly been given the schema and needs execution, not another schema dump.+/// A global [`OnceLock`] map tracks, per slug, how many times the contract has+/// been surfaced **with no execution in between**. After+/// [`AUTO_PROCEED_THRESHOLD`] consecutive surfaces the next instance+/// auto-proceeds: the model has clearly been given the schema and needs+/// execution, not another schema dump.///-/// The threshold is generous (3+ instances = at least 3 surfaced contracts in-/// different sub-agent iterations) so that the normal surface-once-then-execute-/// path within a single spawn is never disrupted.+/// The streak resets on any execution, so the normal+/// surface-once-then-execute path never moves it and a slug cannot accumulate+/// its way to the threshold over a long session (#6407).#[derive(Default)]pub struct ContractGate {seen: Mutex<HashSet<String>>,}-/// Process-wide consult counter: tracks how many unique [`ContractGate`]-/// instances have consulted each slug for the first time. Used by the-/// auto-proceed safety net (#5119) to detect the re-delegation pattern where-/// fresh tools keep surfacing the same contract without ever executing.+/// Process-wide surface streak: how many times each slug's contract has been+/// surfaced **without a following execution**. Used by the auto-proceed safety+/// net (#5119) to detect the re-delegation pattern where fresh tools keep+/// surfacing the same contract without ever executing.+///+/// The streak is bumped only by [`record_surface`] and cleared by+/// [`clear_surface_streak`] as soon as the action executes, so it measures a+/// *current run* rather than a lifetime total. It counted first consults and+/// never reset before (#6407), which meant ordinary use eventually pushed every+/// slug past the threshold and permanently disabled the #4853 surfacing.static GLOBAL_FIRST_CONSULT_COUNT: OnceLock<Mutex<HashMap<String, u32>>> = OnceLock::new();-/// After this many unique fresh gate instances have all surfaced the same-/// contract as "first time", the next instance auto-proceeds. Set conservatively-/// high (3+ instances) so the normal surface-once-then-execute pattern within a-/// single spawn is never affected: the threshold fires only when the model has-/// been shown the schema in at least 3 separate sub-agent iterations without-/// any of them advancing to execution.+/// After this many consecutive surfaces of the same contract with no execution+/// in between, the next fresh gate instance auto-proceeds. Set conservatively+/// high (3) so the normal surface-once-then-execute pattern is never affected:+/// any execution clears the streak, so the threshold is reached only when the+/// model has been shown the schema three times running without advancing.const AUTO_PROCEED_THRESHOLD: u32 = 3;impl ContractGate {@@ -120,24 +126,20 @@ impl ContractGate {return GateConsultOutcome::Proceed;}- // 2. Increment the global first-time consult counter.- let global_count = {- let mut map = GLOBAL_FIRST_CONSULT_COUNT- .get_or_init(|| Mutex::new(HashMap::new()))- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- let entry = map.entry(norm).or_insert(0);- *entry += 1;- *entry- };+ // 2. Read the streak of surfaces that have not yet led to an execution.+ // Reading rather than incrementing here is what keeps the counter+ // meaning what its name says: it is bumped at the point the contract+ // is actually surfaced (`record_surface`) and cleared the moment the+ // action executes (`clear_surface_streak`), both in `consult`.+ let streak = surface_streak(&norm);// 3. Auto-proceed safety net.- if global_count > AUTO_PROCEED_THRESHOLD {+ if streak >= AUTO_PROCEED_THRESHOLD {tracing::warn!(target: "composio",slug = %slug,- global_count,- "[composio][contract-gate] auto-proceeding after {global_count} fresh instances surfaced this contract without execution"+ global_count = streak,+ "[composio][contract-gate] auto-proceeding after {streak} consecutive surfaces of this contract without execution");return GateConsultOutcome::AutoProceed;}@@ -146,6 +148,49 @@ impl ContractGate {}}+/// Current run of surfaces for `slug` that have not been followed by an+/// execution. Read-only: the streak moves in [`record_surface`] and+/// [`clear_surface_streak`].+fn surface_streak(norm_slug: &str) -> u32 {+ GLOBAL_FIRST_CONSULT_COUNT+ .get_or_init(|| Mutex::new(HashMap::new()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .get(norm_slug)+ .copied()+ .unwrap_or(0)+}++/// Count one surface of `slug`'s contract that has not yet produced an+/// execution. Only the surfacing path calls this, so a call that executed+/// without ever being bounced never moves the safety net closer to firing.+fn record_surface(slug: &str) {+ let norm = slug.to_ascii_uppercase();+ let mut map = GLOBAL_FIRST_CONSULT_COUNT+ .get_or_init(|| Mutex::new(HashMap::new()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ *map.entry(norm).or_insert(0) += 1;+}++/// Clear `slug`'s surface streak because the action is about to execute.+///+/// This is the half that was missing (#6407). The safety net exists to break a+/// surface-but-never-execute loop, so an execution is exactly the event that+/// proves the loop is not happening. Without this the counter only ever rose:+/// after enough separate, healthy turns each spawned a fresh gate, every slug+/// eventually crossed the threshold and the #4853 contract surfacing was dead+/// for that slug for the rest of the process — the gate silently turning itself+/// off rather than doing its job.+fn clear_surface_streak(slug: &str) {+ let norm = slug.to_ascii_uppercase();+ GLOBAL_FIRST_CONSULT_COUNT+ .get_or_init(|| Mutex::new(HashMap::new()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .remove(&norm);+}+/// Outcome from [`ContractGate::gate_consult`].enum GateConsultOutcome {/// This is the first time this gate instance has seen this slug. The@@ -197,11 +242,17 @@ pub enum GateDecision {/// Every fresh gate sees each slug for the "first time" and surfaces the/// full contract — so the action never executes, looping forever.///-/// A process-wide consult counter tracks how many fresh gate instances have-/// consulted each slug. After [`AUTO_PROCEED_THRESHOLD`] (3+) fresh instances-/// have surfaced the same contract, the gate auto-proceeds: the model has-/// been given the schema across multiple iterations without advancing, and-/// the next call should execute instead of surfacing the contract again.+/// A process-wide streak counts how many times each slug's contract has been+/// surfaced with no execution in between. After [`AUTO_PROCEED_THRESHOLD`]+/// consecutive surfaces the gate auto-proceeds: the model has been given the+/// schema repeatedly without advancing, and the next call should execute+/// instead of surfacing the contract again.+///+/// Any execution clears the streak (#6407), so the net tracks a live loop+/// rather than a lifetime total. Counting every first consult and never+/// resetting meant a slug used normally across enough turns eventually crossed+/// the threshold for good, after which this gate stopped surfacing anything for+/// that slug — the safety net quietly disabling the feature it guards.pub async fn consult(gate: &ContractGate,config: &Config,@@ -220,6 +271,9 @@ pub async fn consult(slug = %action_slug,"[composio][contract-gate] auto-proceeding after threshold; executing without surfacing");+ // The net has done its job for this slug; let the next genuine+ // surface-loop earn the threshold again instead of latching on.+ clear_surface_streak(action_slug);return GateDecision::Proceed;}// Already surfaced by this gate instance → proceed.@@ -229,6 +283,7 @@ pub async fn consult(slug = %action_slug,"[composio][contract-gate] contract already surfaced this turn; proceeding");+ clear_surface_streak(action_slug);return GateDecision::Proceed;}// First time for this gate instance → check if we need to surface.@@ -244,6 +299,7 @@ pub async fn consult(slug = %action_slug,"[composio][contract-gate] args already satisfy the live contract; proceeding without surfacing");+ clear_surface_streak(action_slug);return GateDecision::Proceed;}tracing::debug!(@@ -253,6 +309,9 @@ pub async fn consult(required_arg_count = contract.required_args.len(),"[composio][contract-gate] surfacing full contract before first execute");+ // This is the only path that moves the safety net: a surface that has+ // not (yet) been followed by an execution.+ record_surface(action_slug);return GateDecision::Surface(format_contract(action_slug, &contract));}@@ -261,6 +320,7 @@ pub async fn consult(slug = %action_slug,"[composio][contract-gate] no live contract available; proceeding without gating");+ clear_surface_streak(action_slug);GateDecision::Proceed}diff --git a/crates/openhuman-core/src/integrations/composio/contract_gate_tests.rs b/crates/openhuman-core/src/integrations/composio/contract_gate_tests.rsindex 810d9efa8e..a9366dbc2a 100644--- a/crates/openhuman-core/src/integrations/composio/contract_gate_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/contract_gate_tests.rs@@ -340,3 +340,125 @@ async fn fresh_gates_eventually_auto_proceed() {"gate 4 must auto-proceed after 3+ fresh instances surfaced the same slug");}++// ── #6407: the safety net must not latch on ─────────────────────────────────++/// Args that DO satisfy [`full_contract`], so the gate executes without ever+/// surfacing — the ordinary healthy call.+fn conforming_args() -> serde_json::Value {+ serde_json::json!({ "query": "subject:\"quarterly report\"" })+}++#[tokio::test]+async fn healthy_calls_never_push_a_slug_past_the_threshold() {+ // Regression for #6407. The counter used to be bumped on every *first+ // consult* by a fresh gate and never reset, so calls that executed+ // perfectly — never surfacing anything — still walked the slug toward the+ // threshold. Each sub-agent spawn builds a fresh gate, so after four+ // ordinary turns the slug was permanently past it and the #4853 surfacing+ // was dead for the rest of the process: a model that genuinely needed the+ // schema was auto-proceeded instead of being given it.+ let toolkit = "healthykit";+ let slug = "HEALTHYKIT_FETCH_EMAILS";+ seed_live_catalog_cache(toolkit, vec![full_contract(slug, toolkit)]);+ let config = Config::default();++ // Well past AUTO_PROCEED_THRESHOLD: every call is a fresh gate whose args+ // already conform, so nothing is ever surfaced.+ for i in 1..=6 {+ let gate = ContractGate::new();+ assert!(+ matches!(+ consult(&gate, &config, slug, &conforming_args()).await,+ GateDecision::Proceed+ ),+ "conforming call {i} should execute without surfacing"+ );+ }++ // The gate must still do its job for a model that actually guessed.+ let guesser = ContractGate::new();+ assert!(+ matches!(+ consult(&guesser, &config, slug, &guessing_args()).await,+ GateDecision::Surface(_)+ ),+ "after healthy calls that never surfaced anything, a guessing call must \+ still get the contract — the safety net must not have been armed by \+ executions (#6407)"+ );+}++#[tokio::test]+async fn an_execution_clears_the_surface_streak() {+ // The net counts *consecutive* surfaces without an execution. An execution+ // proves the surface-but-never-execute loop is not happening, so the streak+ // must start over rather than accumulate across unrelated turns.+ let toolkit = "streakkit";+ let slug = "STREAKKIT_FETCH_EMAILS";+ seed_live_catalog_cache(toolkit, vec![full_contract(slug, toolkit)]);+ let config = Config::default();++ // Two fresh gates surface (streak 1, 2) — one short of the threshold.+ for i in 1..=2 {+ let gate = ContractGate::new();+ assert!(+ matches!(+ consult(&gate, &config, slug, &guessing_args()).await,+ GateDecision::Surface(_)+ ),+ "gate {i} should surface"+ );+ }++ // A conforming call executes, which clears the streak.+ let executor = ContractGate::new();+ assert!(matches!(+ consult(&executor, &config, slug, &conforming_args()).await,+ GateDecision::Proceed+ ));++ // Two more surfaces are therefore 1 and 2 again, not 3 and 4: neither may+ // trip the net. Without the reset the second of these would auto-proceed.+ for i in 1..=2 {+ let gate = ContractGate::new();+ assert!(+ matches!(+ consult(&gate, &config, slug, &guessing_args()).await,+ GateDecision::Surface(_)+ ),+ "post-execution surface {i} must still surface: the streak restarted \+ when the action executed (#6407)"+ );+ }+}++#[tokio::test]+async fn the_net_still_fires_on_a_genuine_surface_loop() {+ // The #5119 protection must survive the #6407 fix: consecutive surfaces+ // with no execution between them still reach the threshold.+ let toolkit = "loopkit";+ let slug = "LOOPKIT_FETCH_EMAILS";+ seed_live_catalog_cache(toolkit, vec![full_contract(slug, toolkit)]);+ let config = Config::default();++ for i in 1..=3 {+ let gate = ContractGate::new();+ assert!(+ matches!(+ consult(&gate, &config, slug, &guessing_args()).await,+ GateDecision::Surface(_)+ ),+ "gate {i} in the loop should surface"+ );+ }++ let gate4 = ContractGate::new();+ assert!(+ matches!(+ consult(&gate4, &config, slug, &guessing_args()).await,+ GateDecision::Proceed+ ),+ "three consecutive surfaces with no execution must still arm the net"+ );+}