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(triage): back off during managed backend outages
lorenzozaneefc15b3a719b2
diff --git a/crates/openhuman-core/src/agent/schemas.rs b/crates/openhuman-core/src/agent/schemas.rsindex d0421f1a4f..f2b65458ea 100644--- a/crates/openhuman-core/src/agent/schemas.rs+++ b/crates/openhuman-core/src/agent/schemas.rs@@ -436,6 +436,12 @@ fn handle_triage_evaluate(params: Map<String, Value>) -> ControllerFuture {"dry_run": dry_run,}))}+ crate::agent::triage::TriageOutcome::Terminal { reason } => Ok(serde_json::json!({+ "decision": "terminal",+ "resolution_path": "terminal",+ "reason": reason,+ "dry_run": dry_run,+ })),}})}diff --git a/crates/openhuman-core/src/agent/triage/evaluator.rs b/crates/openhuman-core/src/agent/triage/evaluator.rsindex 4dc46194fe..308af64dc7 100644--- a/crates/openhuman-core/src/agent/triage/evaluator.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator.rs@@ -11,7 +11,7 @@//!//! local fallback//! ├── ok ──► resolution_path = LocalFallback-//! └── failed ──► TriageOutcome::Deferred { until_ms, reason }+//! └── failed ──► TriageOutcome::Terminal { reason }//! ```//!//! Non-transient cloud failures (auth, malformed prompt, model not@@ -34,6 +34,12 @@ mod outcome;mod prompt;pub use arm::TRIGGER_TRIAGE_AGENT_ID;+#[cfg(test)]+pub(crate) use chain::begin_outage_attempt;+#[cfg(test)]+pub(crate) use chain::record_outage;+#[cfg(test)]+pub(crate) use chain::run_triage_with_arms_for_test_with_state;pub use chain::{run_triage, run_triage_with_arms};pub use outcome::{TriageOutcome, TriageResolutionPath, TriageRun};diff --git a/crates/openhuman-core/src/agent/triage/evaluator/chain.rs b/crates/openhuman-core/src/agent/triage/evaluator/chain.rsindex c41cac160f..505862520f 100644--- a/crates/openhuman-core/src/agent/triage/evaluator/chain.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator/chain.rs@@ -1,6 +1,8 @@//! The tiered cloud → retry → local fallback orchestration.+use std::collections::HashMap;use std::future::Future;+use std::sync::{Mutex, OnceLock};use std::time::Duration;use anyhow::Context;@@ -26,12 +28,25 @@ const RETRY_AFTER_CAP: Duration = Duration::from_millis(30_000);/// bounded; long enough for a wedged TCP connection to give up.const TRANSIENT_BACKOFF: Duration = Duration::from_millis(500);-/// How far in the future a Deferred outcome asks the caller to retry.-/// A short tick mirrors the issue's "next tick retries the whole-/// chain" language — long enough to shed a thundering herd, short-/// enough that user-visible latency on transient outages stays in the-/// tens of seconds.-const DEFER_WAKEUP_MS: i64 = 30_000;+const OUTAGE_BACKOFF_BASE_MS: i64 = 30_000;+const OUTAGE_BACKOFF_CAP_MS: i64 = 15 * 60_000;+const OUTAGE_FAILURE_LIMIT: u32 = 8;++#[derive(Debug, Default)]+pub(crate) struct OutageState {+ pub(crate) consecutive_failures: u32,+ pub(crate) next_attempt_ms: i64,+ pub(crate) in_flight: bool,+ pub(crate) generation: u64,+}++pub(crate) type RetryState = Mutex<HashMap<String, OutageState>>;++static TRIAGE_RETRY_STATE: OnceLock<RetryState> = OnceLock::new();++fn retry_state() -> &'static RetryState {+ TRIAGE_RETRY_STATE.get_or_init(RetryState::default)+}/// Run the triage classifier with the full tiered fallback chain.///@@ -39,8 +54,10 @@ const DEFER_WAKEUP_MS: i64 = 30_000;/// 2. Try cloud; on 429 / transient, sleep and retry once./// 3. On a second 429 / transient, build the local provider and/// fall back to it (acquiring the global LLM permit).-/// 4. On local failure, return `TriageOutcome::Deferred` so the-/// caller (typically a trigger-handler RPC) can reschedule.+/// 4. If no local arm exists, return `TriageOutcome::Terminal` so the+/// caller does not create another fixed-interval cloud invocation.+/// 5. On local failure, return `TriageOutcome::Deferred` so the+/// caller can retry when a local arm is available.pub async fn run_triage(envelope: &TriggerEnvelope) -> anyhow::Result<TriageOutcome> {let config = Config::load_or_init().await@@ -50,7 +67,7 @@ pub async fn run_triage(envelope: &TriggerEnvelope) -> anyhow::Result<TriageOutc.context("resolving provider for triage turn")?;let local = build_local_provider_with_config(&config);- let outcome = run_triage_with_arms_inner(cloud, local, envelope, || {+ let outcome = run_triage_with_arms_inner(cloud, local, envelope, Some(retry_state()), || {crate::cron::scheduler_gate::wait_for_capacity()}).await;@@ -71,7 +88,7 @@ pub async fn run_triage_with_arms(local: Option<ResolvedProvider>,envelope: &TriggerEnvelope,) -> anyhow::Result<TriageOutcome> {- run_triage_with_arms_inner(cloud, local, envelope, || {+ run_triage_with_arms_inner(cloud, local, envelope, Some(retry_state()), || {crate::cron::scheduler_gate::wait_for_capacity()}).await@@ -87,7 +104,17 @@ pub async fn run_triage_with_arms_for_test(local: Option<ResolvedProvider>,envelope: &TriggerEnvelope,) -> anyhow::Result<TriageOutcome> {- run_triage_with_arms_inner(cloud, local, envelope, || async { None }).await+ run_triage_with_arms_inner(cloud, local, envelope, None, || async { None }).await+}++#[cfg(test)]+pub(crate) async fn run_triage_with_arms_for_test_with_state(+ cloud: ResolvedProvider,+ local: Option<ResolvedProvider>,+ envelope: &TriggerEnvelope,+ state: &RetryState,+) -> anyhow::Result<TriageOutcome> {+ run_triage_with_arms_inner(cloud, local, envelope, Some(state), || async { None }).await}/// Core implementation of the tiered cloud→retry→local fallback.@@ -100,12 +127,38 @@ async fn run_triage_with_arms_inner<F, Fut>(cloud: ResolvedProvider,local: Option<ResolvedProvider>,envelope: &TriggerEnvelope,+ retry_state: Option<&RetryState>,acquire_permit: F,) -> anyhow::Result<TriageOutcome>whereF: FnOnce() -> Fut,Fut: Future<Output = Option<LlmPermit>>,{+ let retry_key = format!("{}:{}", cloud.provider_name, cloud.model);+ let retry_generation = if local.is_none() {+ if let Some(state) = retry_state {+ match begin_outage_attempt(Some(state), &retry_key) {+ Some(generation) => Some(generation),+ None => {+ let defer_until_ms = state+ .lock()+ .expect("triage retry state lock poisoned")+ .get(&retry_key)+ .map(|outage| outage.next_attempt_ms.max(now_ms() + 1_000))+ .unwrap_or_else(|| now_ms() + OUTAGE_BACKOFF_BASE_MS);+ return Ok(TriageOutcome::Deferred {+ defer_until_ms,+ reason: "managed backend paused; retry window not reached".to_string(),+ });+ }+ }+ } else {+ None+ }+ } else {+ None+ };+// Track whether the cloud arm bailed because of user budget so the// eventual Deferred reason explains *why* we're sitting idle rather// than the generic "both arms failed" copy.@@ -119,8 +172,14 @@ where// ── Cloud arm ──────────────────────────────────────────────────match try_arm(&cloud, envelope, TriageResolutionPath::Cloud).await {- Ok(run) => return Ok(TriageOutcome::Decision(run)),- Err(ArmError::Fatal(err)) => return Err(err),+ Ok(run) => {+ clear_outage(retry_state, &retry_key, retry_generation);+ return Ok(TriageOutcome::Decision(run));+ }+ Err(ArmError::Fatal(err)) => {+ clear_outage(retry_state, &retry_key, retry_generation);+ return Err(err);+ }Err(ArmError::BudgetExhausted(err)) => {tracing::warn!(source = %envelope.source.slug(),@@ -161,8 +220,14 @@ wheretokio::time::sleep(sleep_ms).await;match try_arm(&cloud, envelope, TriageResolutionPath::CloudAfterRetry).await {- Ok(run) => return Ok(TriageOutcome::Decision(run)),- Err(ArmError::Fatal(err)) => return Err(err),+ Ok(run) => {+ clear_outage(retry_state, &retry_key, retry_generation);+ return Ok(TriageOutcome::Decision(run));+ }+ Err(ArmError::Fatal(err)) => {+ clear_outage(retry_state, &retry_key, retry_generation);+ return Err(err);+ }Err(ArmError::BudgetExhausted(err)) => {tracing::warn!(source = %envelope.source.slug(),@@ -191,7 +256,7 @@ where// Exhausted cloud budget — fall through to local.tracing::warn!("[triage::evaluator] cloud retry budget exhausted; \- falling back to local arm"+ evaluating fallback");}}@@ -200,9 +265,9 @@ where// ── Local fallback ─────────────────────────────────────────────let Some(local) = local else {- // No local arm available at all (runtime disabled, no model- // configured) — the only honest outcome is a deferral so the- // next tick retries the whole chain.+ // No local arm is available (runtime disabled, no model configured).+ // This event has no executable fallback, so returning Deferred would+ // invite callers to repeat the same cloud outage indefinitely.//// `reason` is part of `TriageOutcome::Deferred` and may be// forwarded into telemetry / UI, so it must stay a stable,@@ -231,10 +296,23 @@ where} else {"cloud retry exhausted; local arm unavailable".to_string()};- return Ok(TriageOutcome::Deferred {- defer_until_ms: now_ms().saturating_add(DEFER_WAKEUP_MS),- reason,- });+ if cloud_budget_exhausted.is_some() || cloud_safety_flagged.is_some() {+ clear_outage(retry_state, &retry_key, retry_generation);+ return Ok(TriageOutcome::Terminal { reason });+ }++ return match record_outage(retry_state, &retry_key, retry_generation) {+ Some(TriageOutcome::Terminal { reason }) => Ok(TriageOutcome::Terminal { reason }),+ Some(TriageOutcome::Deferred {+ defer_until_ms,+ reason,+ }) => Ok(TriageOutcome::Deferred {+ defer_until_ms,+ reason,+ }),+ Some(TriageOutcome::Decision(_)) => unreachable!("outage recording cannot decide"),+ None => Ok(TriageOutcome::Terminal { reason }),+ };};// Hold the global LLM permit for the lifetime of the local turn —@@ -242,7 +320,10 @@ wherelet _gate_permit = acquire_permit().await;match try_arm(&local, envelope, TriageResolutionPath::LocalFallback).await {- Ok(run) => Ok(TriageOutcome::Decision(run)),+ Ok(run) => {+ clear_outage(retry_state, &retry_key, retry_generation);+ Ok(TriageOutcome::Decision(run))+ }Err(ArmError::Fatal(err))| Err(ArmError::BudgetExhausted(err))| Err(ArmError::SafetyFlagged(err))@@ -273,12 +354,12 @@ where.or(cloud_safety_flagged.as_ref()).map(|e| e.to_string()).unwrap_or_default(),- defer_ms = DEFER_WAKEUP_MS,+ defer_ms = OUTAGE_BACKOFF_BASE_MS,reason = %reason,"both arms failed; deferring");Ok(TriageOutcome::Deferred {- defer_until_ms: now_ms().saturating_add(DEFER_WAKEUP_MS),+ defer_until_ms: now_ms().saturating_add(OUTAGE_BACKOFF_BASE_MS),reason,})}@@ -288,3 +369,59 @@ wherefn now_ms() -> i64 {chrono::Utc::now().timestamp_millis()}++fn clear_outage(state: Option<&RetryState>, key: &str, generation: Option<u64>) {+ if let Some(state) = state {+ let mut states = state.lock().expect("triage retry state lock poisoned");+ if states+ .get(key)+ .is_some_and(|outage| Some(outage.generation) == generation)+ {+ states.remove(key);+ }+ }+}++pub(crate) fn begin_outage_attempt(state: Option<&RetryState>, key: &str) -> Option<u64> {+ let state = state?;+ let mut states = state.lock().expect("triage retry state lock poisoned");+ let outage = states.entry(key.to_string()).or_default();+ if outage.in_flight || outage.next_attempt_ms > now_ms() {+ return None;+ }+ outage.in_flight = true;+ outage.generation = outage.generation.wrapping_add(1).max(1);+ Some(outage.generation)+}++pub(crate) fn record_outage(+ state: Option<&RetryState>,+ key: &str,+ generation: Option<u64>,+) -> Option<TriageOutcome> {+ let state = state?;+ let mut states = state.lock().expect("triage retry state lock poisoned");+ let outage = states.get_mut(key)?;+ if !outage.in_flight || Some(outage.generation) != generation {+ return None;+ }+ outage.in_flight = false;+ outage.consecutive_failures = outage.consecutive_failures.saturating_add(1);+ if outage.consecutive_failures >= OUTAGE_FAILURE_LIMIT {+ let failures = outage.consecutive_failures;+ states.remove(key);+ return Some(TriageOutcome::Terminal {+ reason: format!("managed backend outage reached retry limit ({failures})"),+ });+ }++ let exponent = outage.consecutive_failures.saturating_sub(1).min(10);+ let delay_ms = OUTAGE_BACKOFF_BASE_MS+ .saturating_mul(1_i64 << exponent)+ .min(OUTAGE_BACKOFF_CAP_MS);+ outage.next_attempt_ms = now_ms().saturating_add(delay_ms);+ Some(TriageOutcome::Deferred {+ defer_until_ms: outage.next_attempt_ms,+ reason: format!("managed backend outage; retry {delay_ms}ms backoff"),+ })+}diff --git a/crates/openhuman-core/src/agent/triage/evaluator/outcome.rs b/crates/openhuman-core/src/agent/triage/evaluator/outcome.rsindex a305d9840a..14c8e9889b 100644--- a/crates/openhuman-core/src/agent/triage/evaluator/outcome.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator/outcome.rs@@ -38,9 +38,8 @@ pub struct TriageRun {pub resolution_path: TriageResolutionPath,}-/// Outcome of [`run_triage`]. Either a parsed decision or a-/// deferral asking the caller to retry the whole chain after-/// `defer_until_ms` (Unix epoch millis).+/// Outcome of [`run_triage`]. Either a parsed decision, a retryable+/// deferral, or a terminal outcome when no fallback exists.#[derive(Debug, Clone)]pub enum TriageOutcome {Decision(TriageRun),@@ -51,13 +50,19 @@ pub enum TriageOutcome {/// Short human-readable reason — already scrubbed; safe to log.reason: String,},+ /// No local fallback is configured and the cloud retry budget is+ /// exhausted. Callers must record this state instead of scheduling+ /// another fixed-interval model invocation.+ Terminal {+ reason: String,+ },}impl TriageOutcome {pub fn into_decision(self) -> Option<TriageRun> {match self {TriageOutcome::Decision(run) => Some(run),- TriageOutcome::Deferred { .. } => None,+ TriageOutcome::Deferred { .. } | TriageOutcome::Terminal { .. } => None,}}}diff --git a/crates/openhuman-core/src/agent/triage/evaluator_deferral_tests.rs b/crates/openhuman-core/src/agent/triage/evaluator_deferral_tests.rsindex 575bacbac9..d661678777 100644--- a/crates/openhuman-core/src/agent/triage/evaluator_deferral_tests.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator_deferral_tests.rs@@ -1,7 +1,51 @@use super::*;+#[test]+fn outage_backoff_is_exponential_and_has_terminal_limit() {+ let state = std::sync::Mutex::new(std::collections::HashMap::new());+ let delays = [30_000, 60_000, 120_000, 240_000, 480_000, 900_000, 900_000];++ for delay in delays {+ let generation = begin_outage_attempt(Some(&state), "stub-cloud").expect("attempt");+ let outcome =+ record_outage(Some(&state), "stub-cloud", Some(generation)).expect("backoff outcome");+ match outcome {+ TriageOutcome::Deferred { reason, .. } => {+ assert!(reason.contains(&format!("{delay}ms backoff")));+ }+ TriageOutcome::Decision(_) | TriageOutcome::Terminal { .. } => {+ panic!("outage should remain retryable before the limit")+ }+ }+ state+ .lock()+ .expect("test state lock")+ .get_mut("stub-cloud")+ .expect("recorded outage")+ .next_attempt_ms = 0;+ }++ let generation = begin_outage_attempt(Some(&state), "stub-cloud").expect("attempt");+ let outcome =+ record_outage(Some(&state), "stub-cloud", Some(generation)).expect("terminal outcome");+ assert!(matches!(outcome, TriageOutcome::Terminal { .. }));+}++#[test]+fn outage_state_isolated_by_model() {+ let state = std::sync::Mutex::new(std::collections::HashMap::new());+ let generation = begin_outage_attempt(Some(&state), "managed:model-a").expect("attempt");+ let first =+ record_outage(Some(&state), "managed:model-a", Some(generation)).expect("first outage");+ assert!(matches!(first, TriageOutcome::Deferred { .. }));+ let generation = begin_outage_attempt(Some(&state), "managed:model-b").expect("attempt");+ assert!(record_outage(Some(&state), "managed:model-b", Some(generation)).is_some());+ let states = state.lock().expect("test state lock");+ assert_eq!(states.len(), 2, "models must not share outage windows");+}+#[tokio::test]-async fn cloud_safety_flagged_without_local_returns_deferred_not_err() {+async fn cloud_safety_flagged_without_local_returns_terminal_not_err() {AgentDefinitionRegistry::init_global_builtins().expect("init_global_builtins");let counter = StdArc::new(AtomicUsize::new(0));let counter_for_stub = StdArc::clone(&counter);@@ -17,16 +61,18 @@ async fn cloud_safety_flagged_without_local_returns_deferred_not_err() {let outcome = run_triage_with_arms_for_test(cloud_arm(), None, &envelope()).await- .expect("safety-flagged with no local must Defer, not Err");+ .expect("safety-flagged with no local must be terminal, not Err");match outcome {- TriageOutcome::Deferred { reason, .. } => {+ TriageOutcome::Terminal { reason } => {assert!(reason.to_lowercase().contains("prompt-guard"),"deferral reason should name the prompt-guard cause: {reason}");}- TriageOutcome::Decision(_) => panic!("expected Deferred"),+ TriageOutcome::Decision(_) | TriageOutcome::Deferred { .. } => {+ panic!("expected Terminal")+ }}assert_eq!(counter.load(Ordering::SeqCst),@@ -36,7 +82,7 @@ async fn cloud_safety_flagged_without_local_returns_deferred_not_err() {}#[tokio::test]-async fn no_local_arm_returns_deferred_after_cloud_exhaustion() {+async fn no_local_arm_returns_terminal_after_cloud_exhaustion() {AgentDefinitionRegistry::init_global_builtins().expect("init_global_builtins");let counter = StdArc::new(AtomicUsize::new(0));let counter_for_stub = StdArc::clone(&counter);@@ -52,16 +98,18 @@ async fn no_local_arm_returns_deferred_after_cloud_exhaustion() {let outcome = run_triage_with_arms_for_test(cloud_arm(), None, &envelope()).await- .expect("Deferred is Ok");+ .expect("Terminal is Ok");match outcome {- TriageOutcome::Deferred { reason, .. } => {+ TriageOutcome::Terminal { reason } => {assert!(reason.contains("local arm unavailable"),"reason should explain the missing local arm: {reason}");}- TriageOutcome::Decision(_) => panic!("expected Deferred"),+ TriageOutcome::Decision(_) | TriageOutcome::Deferred { .. } => {+ panic!("expected Terminal")+ }}assert_eq!(counter.load(Ordering::SeqCst),@@ -70,6 +118,39 @@ async fn no_local_arm_returns_deferred_after_cloud_exhaustion() {);}+#[tokio::test]+async fn repeated_no_local_failures_back_off_before_calling_cloud_again() {+ AgentDefinitionRegistry::init_global_builtins().expect("init_global_builtins");+ let counter = StdArc::new(AtomicUsize::new(0));+ let counter_for_stub = StdArc::clone(&counter);+ let state = std::sync::Mutex::new(std::collections::HashMap::new());++ let _guard = mock_agent_run_turn(move |_req| {+ let counter = StdArc::clone(&counter_for_stub);+ async move {+ counter.fetch_add(1, Ordering::SeqCst);+ Err("HTTP 503 Service Unavailable".to_string())+ }+ })+ .await;++ let first = run_triage_with_arms_for_test_with_state(cloud_arm(), None, &envelope(), &state)+ .await+ .expect("first outage result");+ assert!(matches!(first, TriageOutcome::Deferred { .. }));+ assert_eq!(counter.load(Ordering::SeqCst), 2, "initial call plus retry");++ let second = run_triage_with_arms_for_test_with_state(cloud_arm(), None, &envelope(), &state)+ .await+ .expect("backoff result");+ assert!(matches!(second, TriageOutcome::Deferred { .. }));+ assert_eq!(+ counter.load(Ordering::SeqCst),+ 2,+ "an open backoff window must not invoke the cloud again"+ );+}+#[tokio::test]async fn double_cloud_parse_failure_falls_through_to_local_fallback() {// Regression for #2322: two malformed cloud replies used to turn the@@ -116,7 +197,7 @@ async fn double_cloud_parse_failure_falls_through_to_local_fallback() {}#[tokio::test]-async fn double_cloud_parse_failure_without_local_returns_deferred_not_err() {+async fn double_cloud_parse_failure_without_local_returns_terminal_not_err() {AgentDefinitionRegistry::init_global_builtins().expect("init_global_builtins");let counter = StdArc::new(AtomicUsize::new(0));let counter_for_stub = StdArc::clone(&counter);@@ -132,16 +213,18 @@ async fn double_cloud_parse_failure_without_local_returns_deferred_not_err() {let outcome = run_triage_with_arms_for_test(cloud_arm(), None, &envelope()).await- .expect("malformed cloud retry with no local must Defer, not Err");+ .expect("malformed cloud retry with no local must be terminal, not Err");match outcome {- TriageOutcome::Deferred { reason, .. } => {+ TriageOutcome::Terminal { reason } => {assert!(reason.contains("local arm unavailable"),"reason should explain the missing local arm: {reason}");}- TriageOutcome::Decision(_) => panic!("expected Deferred"),+ TriageOutcome::Decision(_) | TriageOutcome::Deferred { .. } => {+ panic!("expected Terminal")+ }}assert_eq!(counter.load(Ordering::SeqCst),diff --git a/crates/openhuman-core/src/agent/triage/evaluator_fallback_chain_tests.rs b/crates/openhuman-core/src/agent/triage/evaluator_fallback_chain_tests.rsindex 772ea075b3..4df4358fe9 100644--- a/crates/openhuman-core/src/agent/triage/evaluator_fallback_chain_tests.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator_fallback_chain_tests.rs@@ -353,7 +353,9 @@ async fn cloud_then_local_failure_returns_deferred() {"reason should reference the upstream failure: {reason}");}- TriageOutcome::Decision(_) => panic!("expected Deferred, got Decision"),+ TriageOutcome::Decision(_) | TriageOutcome::Terminal { .. } => {+ panic!("expected Deferred, got another terminal outcome")+ }}assert_eq!(counter.load(Ordering::SeqCst), 3, "1 + retry + local = 3");}@@ -493,7 +495,7 @@ async fn cloud_budget_exhausted_on_retry_falls_through_to_local() {}#[tokio::test]-async fn cloud_budget_exhausted_without_local_returns_deferred_not_err() {+async fn cloud_budget_exhausted_without_local_returns_terminal_not_err() {AgentDefinitionRegistry::init_global_builtins().expect("init_global_builtins");let counter = StdArc::new(AtomicUsize::new(0));let counter_for_stub = StdArc::clone(&counter);@@ -512,16 +514,18 @@ async fn cloud_budget_exhausted_without_local_returns_deferred_not_err() {let outcome = run_triage_with_arms_for_test(cloud_arm(), None, &envelope()).await- .expect("budget-exhausted with no local must be Deferred, not Err");+ .expect("budget-exhausted with no local must be terminal, not Err");match outcome {- TriageOutcome::Deferred { reason, .. } => {+ TriageOutcome::Terminal { reason } => {assert!(reason.to_lowercase().contains("budget"),"deferral reason should name the budget cause: {reason}");}- TriageOutcome::Decision(_) => panic!("expected Deferred, got Decision"),+ TriageOutcome::Decision(_) | TriageOutcome::Deferred { .. } => {+ panic!("expected Terminal, got another outcome")+ }}assert_eq!(counter.load(Ordering::SeqCst),@@ -563,7 +567,9 @@ async fn cloud_safety_flagged_then_local_flagged_defers_not_errs() {"deferral reason should name the prompt-guard cause: {reason}");}- TriageOutcome::Decision(_) => panic!("expected Deferred, got Decision"),+ TriageOutcome::Decision(_) | TriageOutcome::Terminal { .. } => {+ panic!("expected Deferred, got another terminal outcome")+ }}assert_eq!(counter.load(Ordering::SeqCst),diff --git a/crates/openhuman-core/src/desktop/notifications/rpc.rs b/crates/openhuman-core/src/desktop/notifications/rpc.rsindex 2dd8356803..1b38735d43 100644--- a/crates/openhuman-core/src/desktop/notifications/rpc.rs+++ b/crates/openhuman-core/src/desktop/notifications/rpc.rs@@ -228,6 +228,13 @@ pub async fn handle_ingest(params: Map<String, Value>) -> Result<Value, String>"[notification_intel] triage deferred");}+ Ok(TriageOutcome::Terminal { reason }) => {+ tracing::warn!(+ id = %id_for_triage,+ reason = %reason,+ "[notification_intel] triage reached terminal state"+ );+ }Err(e) => {tracing::warn!(id = %id_for_triage,diff --git a/crates/openhuman-core/src/integrations/task_sources/route.rs b/crates/openhuman-core/src/integrations/task_sources/route.rsindex abbe5ad1c6..8f023cfdbc 100644--- a/crates/openhuman-core/src/integrations/task_sources/route.rs+++ b/crates/openhuman-core/src/integrations/task_sources/route.rs@@ -101,6 +101,14 @@ async fn dispatch_triage(source: &TaskSource, enriched: &EnrichedTask) -> Result"[task_sources:route] triage deferred (task stays in the ledger)");}+ TriageOutcome::Terminal { reason } => {+ tracing::warn!(+ source_id = %source.id,+ external_id = %task.external_id,+ reason = %reason,+ "[task_sources:route] triage reached terminal state"+ );+ }}Ok(())}diff --git a/crates/openhuman-core/src/memory/sync/composio/bus/trigger_subscriber.rs b/crates/openhuman-core/src/memory/sync/composio/bus/trigger_subscriber.rsindex b4fba420a9..0bdcfc452a 100644--- a/crates/openhuman-core/src/memory/sync/composio/bus/trigger_subscriber.rs+++ b/crates/openhuman-core/src/memory/sync/composio/bus/trigger_subscriber.rs@@ -238,6 +238,13 @@ impl EventHandler<DomainEvent> for ComposioTriggerSubscriber {"[composio][triage] run_triage deferred");}+ Ok(TriageOutcome::Terminal { reason }) => {+ tracing::warn!(+ label = %envelope.display_label,+ reason = %reason,+ "[composio][triage] run_triage reached terminal state"+ );+ }Err(e) => {// Route through the central observability classifier// so user-config / budget-exhausted / provider-statediff --git a/crates/openhuman-core/src/skills/webhooks/bus.rs b/crates/openhuman-core/src/skills/webhooks/bus.rsindex 44b3ff10cb..932c12a70d 100644--- a/crates/openhuman-core/src/skills/webhooks/bus.rs+++ b/crates/openhuman-core/src/skills/webhooks/bus.rs@@ -331,6 +331,9 @@ async fn run_agent_trigger(defer_until_ms,reason,} => Ok(format!("Triage deferred until {defer_until_ms}: {reason}")),+ crate::agent::triage::TriageOutcome::Terminal { reason } => {+ Err(format!("triage reached terminal state: {reason}"))+ }}}diff --git a/crates/openhuman-core/src/skills/webhooks/ops.rs b/crates/openhuman-core/src/skills/webhooks/ops.rsindex d862b8d1d3..1e5d944ed6 100644--- a/crates/openhuman-core/src/skills/webhooks/ops.rs+++ b/crates/openhuman-core/src/skills/webhooks/ops.rs@@ -236,6 +236,14 @@ pub async fn trigger_agent(}),format!("webhooks.trigger_agent deferred for {source}/{caller_id}"),)),+ crate::agent::triage::TriageOutcome::Terminal { reason } => Ok(RpcOutcome::single_log(+ serde_json::json!({+ "decision": "terminal",+ "resolution_path": "terminal",+ "reason": reason,+ }),+ format!("webhooks.trigger_agent failed terminally for {source}/{caller_id}: {reason}"),+ )),}}diff --git a/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs b/tests/raw_coverage/inference_agent_raw_coverage_e2e.rsindex cc8a107615..1e9f3f8b5c 100644--- a/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs+++ b/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs@@ -2059,16 +2059,14 @@ async fn agent_triage_evaluator_covers_native_dispatch_decision_and_deferred_pat&TriggerEnvelope::from_cron("job-coverage", "daily", "done"),).await- .expect("budget becomes deferred without local arm");+ .expect("budget becomes terminal without local arm");match deferred {- TriageOutcome::Deferred {- defer_until_ms,- reason,- } => {- assert!(defer_until_ms > chrono::Utc::now().timestamp_millis());+ TriageOutcome::Terminal { reason } => {assert_eq!(reason, "cloud budget exhausted; local arm unavailable");}- TriageOutcome::Decision(_) => panic!("budget exhaustion should defer"),+ TriageOutcome::Decision(_) | TriageOutcome::Deferred { .. } => {+ panic!("budget exhaustion should be terminal")+ }}let attempts = Arc::new(AtomicUsize::new(0));