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
refactor(security): consolidate policy command module into a single file
Steven Enamakel8fa8831a2890
diff --git a/crates/openhuman-core/src/desktop/app_state/ops/current_user.rs b/crates/openhuman-core/src/desktop/app_state/ops/current_user.rsnew file mode 100644index 0000000000..14c45a3b30--- /dev/null+++ b/crates/openhuman-core/src/desktop/app_state/ops/current_user.rs@@ -0,0 +1,561 @@+//! The current-user cache: the positive cache (last `/auth/me` answer),+//! the negative cache (recent availability failures and their backoff),+//! and the blocking/background refresh paths that keep both in sync with+//! the backend. [`current_user_fetch`](super::current_user_fetch) does the+//! actual HTTP call; [`current_user_generation`](super::current_user_generation)+//! owns sign-out invalidation of these caches; [`staleness`](super::staleness)+//! reports how old the data being served is.++use super::current_user_fetch::{fetch_current_user, sanitize_snapshot_user};+use super::current_user_generation::{+ clear_current_user_failure_unless_stale, current_user_generation,+ note_current_user_success_unless_stale, record_current_user_failure_unless_stale,+};+use super::auth_timeout::{auth_fetch_timeout, current_user_backoff_base};+use super::LOG_PREFIX;+use crate::api::config::effective_backend_api_url;+use crate::config::Config;+use log::debug;+use once_cell::sync::Lazy;+use parking_lot::Mutex;+use serde_json::Value;+use std::time::{Duration, Instant};++/// How long a positive `/auth/me` answer is served without asking the+/// backend again.+const CURRENT_USER_REFRESH_TTL: Duration = Duration::from_secs(5);+/// Ceiling on the negative-cache backoff. Modest on purpose: this window is+/// time during which a recovered backend still will not be noticed, so it+/// trades a bounded amount of staleness for not stalling every poll. At the+/// cap a 5s poll loop attempts roughly one live fetch per twelve polls+/// instead of one per poll.+const CURRENT_USER_BACKOFF_MAX: Duration = Duration::from_secs(60);++/// The positive cache: the last successful `/auth/me` answer, keyed on+/// `(api_base, token)`.+pub(super) static CURRENT_USER_CACHE: Lazy<Mutex<Option<CachedCurrentUser>>> =+ Lazy::new(|| Mutex::new(None));+/// Negative counterpart to [`CURRENT_USER_CACHE`]: the last *availability*+/// failure against `auth_get_me`, so a client whose backend is unreachable stops+/// re-paying [`auth_fetch_timeout`] on every snapshot poll.+///+/// Kept separate from the positive cache rather than folded into it because the+/// two have different lifetimes and different readers —+/// [`peek_cached_current_user_identity`] must keep serving the last known+/// identity throughout an outage, and it reads only the positive cache.+pub(super) static CURRENT_USER_FAILURE: Lazy<Mutex<Option<CurrentUserFailure>>> =+ Lazy::new(|| Mutex::new(None));++#[derive(Debug, Clone)]+pub(super) struct CachedCurrentUser {+ pub(super) api_base: String,+ pub(super) token: String,+ pub(super) fetched_at: Instant,+ pub(super) user: Value,+}++#[derive(Debug, Clone)]+pub(super) enum CurrentUserFetchError {+ Rejected(String),+ TransientResponse(String),+ FetchFailed(String),+ /// A recorded availability failure replayed from the backoff window+ /// instead of going to the network (see+ /// [`suppressed_current_user_failure`]).+ ///+ /// Carries the original error so callers that only want the message behave+ /// exactly as before, plus the two numbers that distinguish "the backend+ /// just failed" from "we did not ask the backend". Without this the+ /// snapshot caller logs a replay — which costs microseconds and makes no+ /// request — with the same `WARN … refresh failed` wording as a real 5s+ /// timeout, so a healthy backoff reads in the logs like a hammering loop.+ /// That misreading is what #5930 was filed on.+ Suppressed {+ inner: Box<CurrentUserFetchError>,+ /// Length of the failure run that opened the window.+ consecutive: u32,+ /// How long until the next live attempt is allowed.+ retry_in: Duration,+ },+}++impl CurrentUserFetchError {+ pub(super) fn message(&self) -> &str {+ match self {+ CurrentUserFetchError::Rejected(message)+ | CurrentUserFetchError::TransientResponse(message)+ | CurrentUserFetchError::FetchFailed(message) => message,+ CurrentUserFetchError::Suppressed { inner, .. } => inner.message(),+ }+ }+}++impl CurrentUserFetchError {+ /// Whether this failure says the *backend was not reachable or not healthy*,+ /// as opposed to saying something about our credentials.+ ///+ /// Only these are worth backing off. A [`Rejected`](Self::Rejected) is the+ /// backend answering, in time, that the token is no good — it drives the+ /// deferred-session cleanup at the snapshot caller, and replaying it from a+ /// cache would either delay that cleanup or, worse, hand the caller a+ /// different variant than the one the backend actually produced.+ pub(super) fn is_availability_failure(&self) -> bool {+ match self {+ CurrentUserFetchError::TransientResponse(_) | CurrentUserFetchError::FetchFailed(_) => {+ true+ }+ CurrentUserFetchError::Rejected(_) => false,+ // Defensive: a replay is not a new observation, and recording it+ // would extend the window on evidence the backend never supplied.+ // `fetch_current_user_cached` returns this variant before it can+ // reach the recorder, so this arm should never actually run.+ CurrentUserFetchError::Suppressed { .. } => false,+ }+ }+}++/// The last availability failure against `auth_get_me`, keyed the same way the+/// positive cache is so that changing environment or signing in as someone else+/// bypasses it rather than inheriting someone else's outage.+#[derive(Debug, Clone)]+pub(super) struct CurrentUserFailure {+ pub(super) api_base: String,+ pub(super) token: String,+ pub(super) failed_at: Instant,+ /// Failures in an unbroken run, counted from 1. Drives the backoff width.+ pub(super) consecutive: u32,+ /// Replayed verbatim while the window is open, so a caller that matches on+ /// the variant sees what the backend really produced.+ pub(super) error: CurrentUserFetchError,+}++/// How long a run of `consecutive` failures suppresses the next live attempt.+///+/// Doubles from [`current_user_backoff_base`] and saturates at+/// [`CURRENT_USER_BACKOFF_MAX`]. `consecutive` is 1-based; 0 is treated as 1 so+/// the function has no surprising zero-length window.+fn current_user_backoff(consecutive: u32) -> Duration {+ let steps = consecutive.saturating_sub(1).min(16);+ current_user_backoff_base()+ .saturating_mul(2u32.saturating_pow(steps))+ .min(CURRENT_USER_BACKOFF_MAX)+}++/// The recorded failure for `(api_base, token)` if its backoff window is still+/// open, in which case the caller should return it instead of going to the+/// network.+fn suppressed_current_user_failure(+ api_base: &str,+ token: &str,+) -> Option<(CurrentUserFetchError, u32, Duration)> {+ let failure = CURRENT_USER_FAILURE.lock();+ let entry = failure.as_ref()?;+ if entry.api_base != api_base || entry.token != token {+ return None;+ }+ let window = current_user_backoff(entry.consecutive);+ let elapsed = entry.failed_at.elapsed();+ (elapsed < window).then(|| (entry.error.clone(), entry.consecutive, window - elapsed))+}++/// Record an availability failure, extending the run when it is the same+/// `(api_base, token)` and starting a new one when it is not.+///+/// A [`CurrentUserFetchError::Rejected`] is ignored — see+/// [`CurrentUserFetchError::is_availability_failure`].+fn record_current_user_failure(api_base: &str, token: &str, error: CurrentUserFetchError) {+ if !error.is_availability_failure() {+ return;+ }+ let mut failure = CURRENT_USER_FAILURE.lock();+ record_current_user_failure_locked(&mut failure, api_base, token, error);+}++/// Forget any recorded failure, so the next poll goes straight to the network.+///+/// Called on every success and on sign-out. Missing either one is the failure+/// mode that matters here: a stale record outliving its cause keeps the app on+/// the stored snapshot after the backend has already come back.+pub(super) fn clear_current_user_failure() {+ *CURRENT_USER_FAILURE.lock() = None;+}++/// Record the timeout path's failure.+///+/// The timeout is applied by the snapshot caller, wrapping the whole of+/// `fetch_current_user_cached`, so when it fires that future is **dropped+/// mid-flight** and nothing inside it runs — including the failure recording on+/// its error path. Without this call the backoff would never engage for the one+/// case #5624 is actually about, which is timeouts rather than returned errors.+///+/// Takes the generation read before the timeout started, for the same reason the+/// refresh does: a sign-out during those `auth_fetch_timeout()` seconds means this+/// outage belongs to an identity that no longer exists, and recording it would+/// suppress the first poll of the next session.+fn note_current_user_timeout(generation: u64, config: &Config, token: &str) {+ record_current_user_failure_unless_stale(+ generation,+ ¤t_user_api_base(config),+ token,+ CurrentUserFetchError::FetchFailed(format!(+ "request timed out after {}s",+ auth_fetch_timeout().as_secs()+ )),+ );+}++/// The cache key both the positive and negative current-user caches are keyed+/// on. Factored out so the snapshot caller, which records the timeout path, and+/// the fetch itself cannot drift apart on how the base URL is normalised.+pub(super) fn current_user_api_base(config: &Config) -> String {+ effective_backend_api_url(&config.api_url)+ .trim()+ .trim_end_matches('/')+ .to_string()+}++pub(super) async fn fetch_current_user_cached(+ config: &Config,+ token: &str,+ allow_cache: bool,+ generation: u64,+) -> Result<Option<Value>, CurrentUserFetchError> {+ let api_base = current_user_api_base(config);++ if allow_cache {+ if let Some((user, age)) = cached_current_user(&api_base, token) {+ if age < CURRENT_USER_REFRESH_TTL {+ debug!(+ "{LOG_PREFIX} using cached current user age_ms={}",+ age.as_millis()+ );+ return Ok(Some(user));+ }+ // Stale-while-revalidate. The entry has expired, but we already+ // know who this is — serve that and re-confirm it behind the poll+ // instead of making the shell wait on a WAN round trip to be told+ // the same thing. Blocking here is what put a floor of one round+ // trip under every `app_state_snapshot` (#6180: 732 calls in 3.5h,+ // not one of them under 500ms).+ //+ // The refresh cadence is unchanged by this: `refresh_current_user_now`+ // stamps `fetched_at` when the request goes out, not when it lands,+ // so the round trip is not folded into the next TTL window and the+ // poll after this one expires on the same schedule it always did.+ // Stamping at completion would have quietly halved the cadence —+ // see the note there (#6190 review). The snapshot keeps reporting+ // the true age of the data it is serving in+ // `current_user_stale_seconds`.+ //+ // Only the expired-entry path revalidates in the background. With+ // no entry at all the shell has no identity to render, so that+ // first fetch after login still blocks, below.+ spawn_current_user_refresh(config, token, generation);+ debug!(+ "{LOG_PREFIX} serving expired current user age_ms={} while refreshing behind the poll",+ age.as_millis()+ );+ return Ok(Some(user));+ }++ // Nothing fresh to serve, so this poll would normally go to the network+ // — and if the backend is unreachable it would sit there for the full+ // `auth_fetch_timeout` before the caller gives up and uses the stored+ // snapshot anyway. Replay the recorded failure instead while its window+ // is open. The caller's behaviour is unchanged (it already falls back on+ // `Err`); it just does so in microseconds. Gated on `allow_cache` for+ // the same reason the positive cache is: a pending-backend-validation+ // pass is explicitly asking for a live answer.+ if let Some((error, consecutive, remaining)) =+ suppressed_current_user_failure(&api_base, token)+ {+ debug!(+ "{LOG_PREFIX} skipping current user refresh; backend failed {consecutive}x, \+ retrying in {}ms",+ remaining.as_millis()+ );+ // Wrapped rather than returned bare so the caller can tell a replay+ // from a live failure. Both fall back to the stored snapshot, but+ // only one of them made a request, and logging them identically is+ // what made a working backoff read as a hammering loop (#5930).+ return Err(CurrentUserFetchError::Suppressed {+ inner: Box::new(error),+ consecutive,+ retry_in: remaining,+ });+ }+ }++ refresh_current_user_now(config, token, generation, RefreshOrigin::Blocking).await+}++/// The cached user for this identity and how old it is, if the cache holds one.+///+/// Reads under one lock and hands back an owned copy, so no caller holds+/// `CURRENT_USER_CACHE` across a decision — the freshness test and the+/// stale-while-revalidate branch below both need the same read.+fn cached_current_user(api_base: &str, token: &str) -> Option<(Value, Duration)> {+ let cache = CURRENT_USER_CACHE.lock();+ let entry = cache.as_ref()?;+ (entry.api_base == api_base && entry.token == token)+ .then(|| (entry.user.clone(), entry.fetched_at.elapsed()))+}++/// Single-flight gate for the background refresh.+///+/// An async mutex held by the spawned task for its lifetime, taken with+/// `try_lock` so a poll that finds a refresh already running simply declines to+/// start a second one rather than queueing behind it. Same gate, same reason as+/// [`RUNTIME_SNAPSHOT_REBUILD`]: without it every overlapping poll launches its+/// own fetch. Using a guard rather than a flag means a panicking refresh+/// releases the gate instead of wedging it shut for the life of the process.+static CURRENT_USER_REFRESH_INFLIGHT: Lazy<tokio::sync::Mutex<()>> =+ Lazy::new(|| tokio::sync::Mutex::new(()));++/// Refresh the cached current user without making the caller wait for it.+///+/// Declines to start when the backoff window from an earlier failure is still+/// open — a background refresh would re-pay exactly the timeout that window+/// exists to avoid (#5624) — and when a previous poll's refresh is still in+/// flight.+fn spawn_current_user_refresh(config: &Config, token: &str, generation: u64) {+ if let Some((error, consecutive, remaining)) =+ suppressed_current_user_failure(¤t_user_api_base(config), token)+ {+ // Logged here because the stale-while-revalidate return above means an+ // outage no longer reaches the replay branch in+ // `fetch_current_user_cached` — without this line a backend that has+ // been down for minutes leaves no trace at all in the snapshot logs.+ // `debug!`, not `warn!`: no request was made and nothing waited on it+ // (#5930).+ debug!(+ "{LOG_PREFIX} not refreshing current user behind the poll; backend failed \+ {consecutive}x, retrying in {}ms: {}",+ remaining.as_millis(),+ error.message()+ );+ return;+ }+ let gate: &'static tokio::sync::Mutex<()> = &CURRENT_USER_REFRESH_INFLIGHT;+ let Ok(guard) = gate.try_lock() else {+ return;+ };++ let config = config.clone();+ let token = token.to_string();+ tokio::spawn(async move {+ let _guard = guard;+ // Bounded by the same budget the blocking path spends, so a hung+ // backend cannot leave the gate closed for longer than one window.+ match tokio::time::timeout(+ auth_fetch_timeout(),+ refresh_current_user_now(&config, &token, generation, RefreshOrigin::Background),+ )+ .await+ {+ Ok(Ok(_)) => {}+ // The stale entry stands and the failure is recorded, so the next+ // poll takes the backoff path. Not a failure of any user-visible+ // operation — nothing was waiting on this.+ Ok(Err(error)) => debug!(+ "{LOG_PREFIX} background current user refresh failed; serving stale entry: {}",+ error.message()+ ),+ Err(_) => {+ debug!(+ "{LOG_PREFIX} background current user refresh timed out after {}s; serving stale entry",+ auth_fetch_timeout().as_secs()+ );+ // The generation is captured from when the refresh was launched and+ // guards the timeout record against sign-out racing the timeout.+ note_current_user_timeout(generation, &config, &token);+ }+ }+ });+}++/// Where a refresh was started from, which decides whether its answer may still+/// be committed by the time it lands.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+enum RefreshOrigin {+ /// The caller is still awaiting this refresh and still holds the identity+ /// it asked for, so the answer is authoritative by construction.+ Blocking,+ /// Detached from the poll that started it, and therefore able to outlive+ /// the identity it was started for — a logout and re-login, or an+ /// environment switch, can land in between.+ Background,+}++/// Go to the backend, then reconcile the caches and freshness stamps with what+/// came back. The blocking half of [`fetch_current_user_cached`], split out so+/// the background refresh runs exactly the same path rather than a parallel+/// copy of it that could drift.+async fn refresh_current_user_now(+ config: &Config,+ token: &str,+ generation: u64,+ origin: RefreshOrigin,+) -> Result<Option<Value>, CurrentUserFetchError> {+ let api_base = current_user_api_base(config);+ // The TTL clock starts when the request goes out, not when it lands.+ //+ // `fetched_at` is what `CURRENT_USER_REFRESH_TTL` is measured against, and+ // the poll loop schedules itself from the previous *response*. Stamping at+ // completion would therefore fold the round trip into the next window: a+ // refresh taking `L` leaves the following poll only `TTL - L` from expiry,+ // it reads the entry as fresh, and the refresh after that is skipped+ // entirely — halving the cadence as a side effect of not blocking (#6190+ // review). Stamping at initiation keeps the wall-clock refresh cadence+ // exactly what it was before this path became non-blocking; the only thing+ // that changed is who waits for it.+ //+ // It also errs the safe way. The data itself arrives at `started_at + L`,+ // so calling it `started_at` slightly *overstates* its age and expires the+ // entry sooner — never later. `note_current_user_success` below is the+ // stamp that answers "how old is the data we are showing", and it stays at+ // completion, because that is when the data actually arrived.+ let started_at = Instant::now();+ let fetched = match fetch_current_user(config, token).await {+ Ok(user) => sanitize_snapshot_user(user),+ Err(error) => {+ if !record_current_user_failure_unless_stale(+ generation,+ &api_base,+ token,+ error.clone(),+ ) {+ debug!("{LOG_PREFIX} discarding current user failure that raced sign-out");+ }+ return Err(error);+ }+ };+ // A detached refresh can land after the app has moved to another identity,+ // and every write below is process-global. Committing then would regress+ // the cache to the previous user — and `peek_cached_current_user_identity`+ // reads that slot WITHOUT a key check (#926), so the regressed entry would+ // be embedded in the agent's prompts as the current user. The keyed reads+ // in `fetch_current_user_cached` would merely miss; that one would be+ // wrong.+ //+ // The check and the commit share ONE lock acquisition, and nothing between+ // them can suspend or release it. Validating through a separate read would+ // leave a window in which a blocking refresh for a newer identity commits+ // after this one has already decided it is current — narrow, but the+ // runtime is multi-threaded, so "narrow" is not "impossible".+ //+ // The generation check (against sign-out) and the identity check (against+ // a subsequent login the background refresh missed) are applied under the+ // same lock. Sign-out bumps the generation before clearing the caches, so+ // a refresh that read the old token before sign-out will read the old+ // generation and fail the check — the cache it would restore was already+ // cleared.+ //+ // The failure and freshness stamps stay OUTSIDE this scope: they take their+ // own locks, and this module's rule is that `LAST_CURRENT_USER_SUCCESS` is+ // never nested inside `CURRENT_USER_CACHE`. They therefore run *after* the+ // commit rather than before it, which is also what lets a discarded refresh+ // leave the newer identity's `CURRENT_USER_FAILURE` record alone —+ // `clear_current_user_failure` is unkeyed and would otherwise wipe it. The+ // stamp is only ever read as an age in seconds, so moving it to the far+ // side of the commit cannot change an observable answer.+ //+ // When sign-out wins the generation race, the failure and success records+ // are untouched — they were already cleared by `forget_current_user_caches`,+ // and this refresh has no business touching them either.+ let committed = {+ let mut cache = CURRENT_USER_CACHE.lock();+ let generation_mismatch = current_user_generation() != generation;+ if generation_mismatch {+ debug!(+ "{LOG_PREFIX} discarding current user refresh that raced sign-out; \+ generation bumped while in flight"+ );+ false+ } else {+ let moved_on = cache+ .as_ref()+ .is_some_and(|entry| entry.api_base != api_base || entry.token != token);+ if origin == RefreshOrigin::Background && moved_on {+ false+ } else {+ match fetched.clone() {+ Some(user) => {+ debug!("{LOG_PREFIX} refreshed current user from backend");+ *cache = Some(CachedCurrentUser {+ api_base: api_base.clone(),+ token: token.to_string(),+ fetched_at: started_at,+ user,+ });+ }+ None => {+ debug!("{LOG_PREFIX} backend returned empty current user; clearing cache");+ *cache = None;+ }+ }+ true+ }+ }+ };++ if !committed {+ debug!(+ "{LOG_PREFIX} discarding background current user refresh; the cache moved to \+ another identity while it was in flight"+ );+ return Ok(fetched);+ }++ // Keep all post-fetch records behind the same generation checks as the+ // positive cache. A logout (or a subsequent login) can land after the+ // cache commit and must not have its failure/success records overwritten.+ clear_current_user_failure_unless_stale(generation);+ if fetched.is_some() {+ note_current_user_success_unless_stale(generation, &api_base, token);+ }++ Ok(fetched)+}++/// Synchronous, network-free peek at the cached `auth_get_me` response,+/// returning only the identifying fields the prompt layer is allowed to+/// embed (`id`, `name`, `email`). Tokens stay locked behind the JWT+/// helpers — never returned through this path. See issue #926.+///+/// Returns `None` when no `auth_get_me` call has populated the cache+/// yet (CLI-only flows, fresh installs, signed-out sessions). The+/// cache TTL is **ignored** here intentionally — for prompt rendering+/// a slightly stale identity is fine; the freshness check only+/// matters for the snapshot RPC that fronts the React shell.+pub fn peek_cached_current_user_identity() -> Option<crate::agent::prompts::UserIdentity>+{+ let cache = CURRENT_USER_CACHE.lock();+ let entry = cache.as_ref()?;+ let user = entry.user.as_object()?;++ let pluck = |key: &str| -> Option<String> {+ user.get(key)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ };++ let id = pluck("id")+ .or_else(|| pluck("user_id"))+ .or_else(|| pluck("userId"));+ let name = pluck("name")+ .or_else(|| pluck("displayName"))+ .or_else(|| pluck("display_name"))+ .or_else(|| pluck("full_name"))+ .or_else(|| pluck("fullName"));+ let email = pluck("email");++ let identity = crate::agent::prompts::UserIdentity { id, name, email };+ if identity.is_empty() {+ None+ } else {+ Some(identity)+ }+}diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rsnew file mode 100644index 0000000000..2dd9fe10f4--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs@@ -0,0 +1,341 @@+//! The process-wide connected-integrations cache: [`CachedIntegrations`],+//! [`INTEGRATIONS_CACHE`], its readers/invalidation+//! ([`cached_active_integrations`], [`cached_active_integrations_including_expired`],+//! [`invalidate_connected_integrations_cache`]), and the reconciliation+//! helpers ([`connected_set_hash`], [`sync_cache_with_connections`]) that+//! keep it in sync with a fresh backend `list_connections` response.++use crate::agent::context::prompt::ConnectedIntegration;+use crate::config::Config;++use std::collections::{HashMap, HashSet};+use std::sync::{LazyLock, RwLock};+use std::time::{Duration, Instant};++// ── Prompt integration discovery ────────────────────────────────────++/// Defensive TTL on the integrations cache.+///+/// Background: the primary invalidation path is the+/// `ComposioConnectionCreated` → `wait_for_connection_active` bus flow+/// (see [`super::bus::ComposioConnectionCreatedSubscriber`]), which+/// polls the backend for up to 60 s after `composio_authorize` returns+/// a `connectUrl`. On Windows the OAuth round-trip can exceed that+/// window (Defender SmartScreen, slower browser launch, extra consent+/// dialogs), so the invalidation call never fires and the chat+/// runtime's cache stays frozen on the pre-connect snapshot even+/// though the Settings UI polls `composio_list_connections` every 5 s+/// and shows the user as "Connected".+///+/// The cross-platform defenses we layer on top:+/// 1. [`composio_list_connections`] diff-invalidates the cache whenever+/// the backend's active-toolkit set diverges from what's cached,+/// so a running UI keeps the chat cache in sync within one poll+/// interval.+/// 2. This TTL caps worst-case staleness at 60 s regardless of+/// whether the UI is open, the bus fires, or the user reconnected+/// out-of-band.+pub(crate) const CACHE_TTL: Duration = Duration::from_secs(60);++/// Cached entry: the integrations list plus the timestamp we wrote it.+#[derive(Clone)]+pub(crate) struct CachedIntegrations {+ pub(crate) entries: Vec<ConnectedIntegration>,+ pub(crate) cached_at: Instant,+}++/// Process-wide cache for connected integrations, keyed by the config+/// identity (the `config_path` string) so different user contexts don't+/// collide. Each entry is populated on first fetch and returned on+/// subsequent calls until explicitly invalidated or the TTL expires.+pub(crate) static INTEGRATIONS_CACHE: LazyLock<RwLock<HashMap<String, CachedIntegrations>>> =+ LazyLock::new(|| RwLock::new(HashMap::new()));++/// Crate-wide test serialization lock for all tests that mutate or read+/// the process-global `INTEGRATIONS_CACHE`. Defined here so it is shared+/// by every `cfg(test)` module in this crate (ops_tests, tools_tests, …).+/// Poison-recovery (`unwrap_or_else`) keeps a panicking test from+/// permanently blocking later ones.+#[cfg(test)]+pub(crate) fn composio_cache_test_lock() -> std::sync::MutexGuard<'static, ()> {+ static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();+ LOCK.get_or_init(|| std::sync::Mutex::new(()))+ .lock()+ .unwrap_or_else(|e| e.into_inner())+}++/// Derive a stable cache key from a [`Config`]. We use the stringified+/// `config_path` because it uniquely identifies a user context (it+/// resolves to the per-user openhuman dir).+pub(crate) fn cache_key(config: &Config) -> String {+ config.config_path.display().to_string()+}++/// Clear cached connected integrations so the next call to+/// [`fetch_connected_integrations`] hits the backend again.+///+/// Called by [`super::bus::ComposioConnectionCreatedSubscriber`] when a+/// new OAuth connection completes, by [`composio_list_connections`]+/// when it observes a divergence between the backend response and the+/// cached snapshot, and from tests. Clears the entire map because the+/// callers don't carry a config reference.+pub fn invalidate_connected_integrations_cache() {+ if let Ok(mut guard) = INTEGRATIONS_CACHE.write() {+ let entries = guard.len();+ guard.clear();+ tracing::info!(+ cached_keys = entries,+ "[composio][integrations] cache invalidated"+ );+ }+}++/// Read-only snapshot of the currently cached connected integrations for+/// the given config, or [`None`] when the cache is empty, expired, or+/// the lock is held by a writer.+///+/// Designed for hot-path callers that want a cheap "what does the cache+/// already say?" probe without triggering a backend fetch. The agent+/// harness uses this on every turn to detect mid-session connection+/// changes — it relies on the desktop UI's 5 s `composio_list_connections`+/// poll (which calls into [`fetch_connected_integrations`] and+/// repopulates this cache) plus the event-driven invalidation path to+/// keep the cache current.+///+/// `try_read` (not `read`) so a writer in progress — e.g. the UI poll+/// repopulating the cache — never blocks a turn. Worst case the agent+/// sees `None` for one turn while the writer holds the lock; the next+/// turn picks up the value naturally.+///+/// TTL is enforced defensively: entries older than [`CACHE_TTL`] are+/// treated as missing even though they're still in the map (a stale+/// entry would otherwise pin the agent to a frozen view if every+/// invalidation path silently failed).+pub fn cached_active_integrations(config: &Config) -> Option<Vec<ConnectedIntegration>> {+ read_cached_integrations(config, false)+}++/// Like [`cached_active_integrations`] but returns the last cached snapshot+/// even when it has aged past [`CACHE_TTL`].+///+/// Intended ONLY as a transient-failure fallback: when a live fetch reports+/// `Unavailable`/times out, preserving the last-known integrations is strictly+/// better than collapsing the delegation surface to an empty set (which drops+/// `delegate_to_integrations_agent` and silently disables channel tool-calling).+/// Without this, a backend blip that lands just after the 60 s TTL expiry still+/// wipes tool-calling despite having a perfectly good previous snapshot. A fresh+/// fetch repopulates the cache the moment the backend recovers, so the stale+/// window is bounded by the outage, not by this call.+pub fn cached_active_integrations_including_expired(+ config: &Config,+) -> Option<Vec<ConnectedIntegration>> {+ read_cached_integrations(config, true)+}++/// Shared reader for the integrations cache. `allow_expired` bypasses the+/// [`CACHE_TTL`] freshness check for the transient-failure fallback path.+fn read_cached_integrations(+ config: &Config,+ allow_expired: bool,+) -> Option<Vec<ConnectedIntegration>> {+ let key = cache_key(config);+ let guard = match INTEGRATIONS_CACHE.try_read() {+ Ok(g) => g,+ Err(_) => {+ tracing::trace!(+ key = %key,+ "[composio][integrations_cache] cached_active_integrations:lock_contended"+ );+ return None;+ }+ };+ let Some(cached) = guard.get(&key) else {+ tracing::trace!(+ key = %key,+ "[composio][integrations_cache] cached_active_integrations:miss"+ );+ return None;+ };+ let age = cached.cached_at.elapsed();+ if !allow_expired && age > CACHE_TTL {+ tracing::trace!(+ key = %key,+ age_ms = age.as_millis() as u64,+ ttl_ms = CACHE_TTL.as_millis() as u64,+ "[composio][integrations_cache] cached_active_integrations:expired"+ );+ return None;+ }+ // Surface a *very* stale fallback so an unusually long backend outage is+ // observable rather than silently pinning the agent to an ancient snapshot.+ if allow_expired && age > 5 * CACHE_TTL {+ tracing::warn!(+ key = %key,+ age_ms = age.as_millis() as u64,+ ttl_ms = CACHE_TTL.as_millis() as u64,+ "[composio][integrations_cache] serving a heavily-stale integrations snapshot on transient-failure fallback (backend outage?)"+ );+ }+ tracing::trace!(+ key = %key,+ entries = cached.entries.len(),+ age_ms = age.as_millis() as u64,+ allow_expired,+ "[composio][integrations_cache] cached_active_integrations:hit"+ );+ Some(cached.entries.clone())+}++/// Stable hash of the *routing-relevant* slice of a connected-integrations+/// snapshot.+///+/// Two snapshots produce the same hash iff they would synthesise the+/// same `delegate_<toolkit>` tool set in the orchestrator's+/// function-calling schema. The hash is:+///+/// - **Order-independent** — callers don't need to sort the input.+/// - **Description-insensitive** — Composio catalogue text edits don't+/// trigger a refresh. The schema's tool-description field still+/// picks up new text on the next *real* (membership-changing)+/// refresh, so descriptions are never permanently stale.+/// - **Process-local** — [`std::collections::hash_map::DefaultHasher`]+/// is randomly seeded per process. Fine because we only compare+/// hashes within one process lifetime.+///+/// Only `connected == true` entries contribute. Unconnected toolkits are+/// stripped by [`super::super::tools::orchestrator_tools::collect_orchestrator_tools`]+/// anyway, so churn among the unconnected set never changes the agent's+/// surface and shouldn't trigger a refresh.+pub fn connected_set_hash(integrations: &[ConnectedIntegration]) -> u64 {+ use std::collections::hash_map::DefaultHasher;+ use std::hash::{Hash, Hasher};++ let mut pairs: Vec<(&str, Vec<&str>)> = integrations+ .iter()+ .filter(|i| i.connected)+ .map(|i| {+ let mut ids: Vec<&str> = i+ .connections+ .iter()+ .map(|c| c.connection_id.as_str())+ .collect();+ ids.sort();+ (i.toolkit.as_str(), ids)+ })+ .collect();+ pairs.sort_by(|a, b| a.0.cmp(b.0));++ let mut hasher = DefaultHasher::new();+ pairs.hash(&mut hasher);+ hasher.finish()+}++/// Collect the set of toolkit slugs marked `connected` in a snapshot.+///+/// Exposed to [`sync_cache_with_connections`] so it can diff the live+/// backend connection list against what the chat runtime currently+/// believes is connected.+fn connected_toolkit_set(integrations: &[ConnectedIntegration]) -> HashSet<String> {+ integrations+ .iter()+ .filter(|i| i.connected)+ .map(|i| i.toolkit.clone())+ .collect()+}++/// Reconcile the process-wide integrations cache with a fresh backend+/// `list_connections` response.+///+/// Called from [`composio_list_connections`], which the desktop UI+/// polls every 5 s (see `app/src/lib/composio/hooks.ts`). When the set+/// of ACTIVE/CONNECTED toolkits in the response differs from what's in+/// the cache, we invalidate so the chat runtime re-fetches on its next+/// `fetch_connected_integrations` call. This keeps tool availability+/// in chat in sync with the badge the user sees in Settings, even when+/// the primary event-bus invalidation path misses (e.g. Windows OAuth+/// flows that overrun the 60 s readiness poll).+pub(crate) fn sync_cache_with_connections(connections: &[super::types::ComposioConnection]) {+ let live_active: HashSet<String> = connections+ .iter()+ .filter(|c| c.is_active())+ .map(|c| c.normalized_toolkit())+ .filter(|toolkit| !toolkit.is_empty())+ .collect();++ // Collect active connection IDs per toolkit to detect multi-account changes+ let live_ids: std::collections::HashMap<String, Vec<String>> = {+ let mut ids: std::collections::HashMap<String, Vec<String>> =+ std::collections::HashMap::new();+ for c in connections.iter().filter(|c| c.is_active()) {+ let tk = c.normalized_toolkit();+ if !tk.is_empty() {+ ids.entry(tk).or_default().push(c.id.clone());+ }+ }+ for v in ids.values_mut() {+ v.sort();+ }+ ids+ };++ // Read once to decide whether any cache entry is out of sync. We+ // clone out the keys + connected sets so we can release the read+ // lock before taking the write lock.+ let divergent_keys: Vec<(String, HashSet<String>, HashSet<String>)> = {+ let Ok(guard) = INTEGRATIONS_CACHE.read() else {+ return;+ };+ guard+ .iter()+ .filter_map(|(key, cached)| {+ let cached_set = connected_toolkit_set(&cached.entries);+ // Also check per-toolkit connection IDs (not just counts)+ let ids_match = cached.entries.iter().all(|i| {+ let mut cached_ids: Vec<&str> = i+ .connections+ .iter()+ .map(|c| c.connection_id.as_str())+ .collect();+ cached_ids.sort();+ let empty = Vec::new();+ let live = live_ids.get(&i.toolkit).unwrap_or(&empty);+ cached_ids.len() == live.len()+ && cached_ids+ .iter()+ .zip(live.iter())+ .all(|(a, b)| *a == b.as_str())+ });+ if cached_set != live_active || !ids_match {+ Some((key.clone(), cached_set, live_active.clone()))+ } else {+ None+ }+ })+ .collect()+ };++ if divergent_keys.is_empty() {+ tracing::debug!(+ live_connected = live_active.len(),+ "[composio][integrations] list_connections matches cache — no invalidation needed"+ );+ return;+ }++ if let Ok(mut guard) = INTEGRATIONS_CACHE.write() {+ for (key, cached_set, live_set) in divergent_keys {+ // Diff logging — makes Windows-timing regressions easy to+ // catch in user-supplied debug dumps without leaking any+ // PII (toolkit slugs are public strings like "gmail").+ let added: Vec<&String> = live_set.difference(&cached_set).collect();+ let removed: Vec<&String> = cached_set.difference(&live_set).collect();+ tracing::info!(+ key = %key,+ ?added,+ ?removed,+ "[composio][integrations] cache diverges from backend — invalidating"+ );+ guard.remove(&key);+ }+ }+}diff --git a/crates/openhuman-core/src/security/policy/mod.rs b/crates/openhuman-core/src/security/policy/mod.rsindex b4d4d155ed..13a16cec2e 100644--- a/crates/openhuman-core/src/security/policy/mod.rs+++ b/crates/openhuman-core/src/security/policy/mod.rs@@ -2,7 +2,6 @@ mod command_checks;mod enforcement;mod path_checks;-#[path = "policy_command.rs"]mod policy_command;mod types;diff --git a/crates/openhuman-core/src/security/policy/policy_command.rs b/crates/openhuman-core/src/security/policy/policy_command.rsdeleted file mode 100644index 1cf74ae840..0000000000--- a/crates/openhuman-core/src/security/policy/policy_command.rs+++ /dev/null@@ -1,2 +0,0 @@-include!("policy_command_part_01.rs");-include!("policy_command_part_02.rs");diff --git a/crates/openhuman-core/src/security/policy/policy_command_part_01.rs b/crates/openhuman-core/src/security/policy/policy_command_part_01.rsdeleted file mode 100644index a3c1b61e65..0000000000--- a/crates/openhuman-core/src/security/policy/policy_command_part_01.rs+++ /dev/null@@ -1,666 +0,0 @@-use super::CommandClass;--/// Environment variable names that can trigger arbitrary command execution-/// when supplied as a leading inline assignment on an otherwise-allowed-/// command. Each name here is either a hook variable that a downstream tool-/// will spawn as a subprocess (`GIT_PAGER`, `GIT_SSH_COMMAND`, `EDITOR`,-/// `LESS`/`LESSOPEN`, `MANPAGER`, `BROWSER`, `BAT_PAGER`), a runtime-/// configuration knob that affects how Python or the shell evaluate user-/// input (`PYTHONSTARTUP`, `BASH_ENV`, `ENV`, `PROMPT_COMMAND`), or a loader-/// override that lets an attacker inject a library into the next process-/// (`LD_PRELOAD`, `LD_LIBRARY_PATH`, `LD_AUDIT`, `DYLD_INSERT_LIBRARIES`,-/// `DYLD_LIBRARY_PATH`, `DYLD_FORCE_FLAT_NAMESPACE`).-///-/// `PATH` and `SHELL` are listed so an inline override cannot redirect-/// resolution of any allowed binary to an attacker-controlled path. `IFS`-/// is listed because the shell uses it for word splitting and a malicious-/// value can hide command boundaries from later parsers.-const DANGEROUS_ENV_PREFIXES: &[&str] = &[- "BASH_ENV",- "BAT_PAGER",- "BROWSER",- "DYLD_FORCE_FLAT_NAMESPACE",- "DYLD_INSERT_LIBRARIES",- "DYLD_LIBRARY_PATH",- "EDITOR",- "ENV",- "GIT_EDITOR",- "GIT_EXTERNAL_DIFF",- "GIT_EXTERNAL_FILTER",- "GIT_PAGER",- "GIT_SSH",- "GIT_SSH_COMMAND",- "IFS",- "LD_AUDIT",- "LD_LIBRARY_PATH",- "LD_PRELOAD",- "LESS",- "LESSCLOSE",- "LESSOPEN",- "MANOPT",- "MANPAGER",- "PAGER",- "PATH",- "PROMPT_COMMAND",- "PS1",- "PS2",- "PS3",- "PS4",- "PYTHONPATH",- "PYTHONSTARTUP",- "SHELL",- "VISUAL",-];--/// Returns true if `s` starts with one or more inline env assignments and any-/// of the assigned names are in [`DANGEROUS_ENV_PREFIXES`].-///-/// Now superseded by [`has_leading_env_assignment`] for the-/// allowlist check (which rejects ANY leading env assignment), but kept-/// for callers that specifically want the dangerous-only signal —-/// notably tests that pin the old DANGEROUS_ENV_PREFIXES rejection-/// shape.-///-/// The allowlist validation in [`SecurityPolicy::is_command_allowed`] uses-/// [`skip_env_assignments`] to look past the env prefix before matching the-/// command name. That leaves a class of attacks where the bare command (e.g.-/// `git log`) is allowlisted but the env prefix mutates how it executes (e.g.-/// `GIT_PAGER=<cmd> git log` — `git` spawns `<cmd>` as its pager). Because-/// the prefix is stripped before allowlisting and the shell evaluates the-/// prefix at execution time, the bypass lands without ever touching a-/// blocked command name.-///-/// Treating any dangerous prefix as a denial keeps the allowlist-/// semantically meaningful without having to enumerate every shape of every-/// downstream tool's hook surface.-pub(super) fn has_dangerous_env_prefix(s: &str) -> bool {- let mut rest = s.trim_start();- loop {- let Some(word) = rest.split_whitespace().next() else {- return false;- };- if !word.contains('=') {- return false;- }- if !word- .chars()- .next()- .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')- {- return false;- }- let (name, _) = word.split_once('=').unwrap_or((word, ""));- let upper = name.to_ascii_uppercase();- if DANGEROUS_ENV_PREFIXES.contains(&upper.as_str()) {- return true;- }- rest = rest[word.len()..].trim_start();- }-}--/// Returns true if `s` starts with at least one inline env-var-/// assignment of the shape `NAME=...`, where `NAME` begins with an ASCII-/// letter or underscore. Catches the entire `GIT_SSH=…`, `SSH_ASKPASS=…`,-/// `LD_PRELOAD=…`, `IFS=…` family — including names we haven't enumerated-/// in [`DANGEROUS_ENV_PREFIXES`] — by treating ANY leading assignment as-/// suspect. The allowlist already names every command we want to permit;-/// nothing in that list needs the operator to set an env var at invoke-/// time, so the broader gate has no false-positive surface on the-/// approved path.-///-/// Used by [`SecurityPolicy::is_command_allowed`] as a structural guard-/// alongside the existing dangerous-prefix check.-pub(super) fn has_leading_env_assignment(s: &str) -> bool {- let Some(word) = s.split_whitespace().next() else {- return false;- };- let Some((name, _value)) = word.split_once('=') else {- return false;- };- if name.is_empty() {- return false;- }- // Identifier shape: first char letter or `_`, the rest alphanumeric- // or `_`. Anything else (e.g. `foo[bar]=`) is not a shell assignment.- let mut chars = name.chars();- let first = match chars.next() {- Some(c) => c,- None => return false,- };- if !(first.is_ascii_alphabetic() || first == '_') {- return false;- }- if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {- return false;- }- true-}--/// Skip leading environment variable assignments (e.g. `FOO=bar cmd args`).-/// Returns the remainder starting at the first non-assignment word.-pub(super) fn skip_env_assignments(s: &str) -> &str {- let mut rest = s;- loop {- let Some(word) = rest.split_whitespace().next() else {- return rest;- };- // Environment assignment: contains '=' and starts with a letter or underscore- if word.contains('=')- && word- .chars()- .next()- .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')- {- // Advance past this word- rest = rest[word.len()..].trim_start();- } else {- return rest;- }- }-}--pub(super) fn command_basename(command: &str) -> &str {- command.split(['/', '\\']).next_back().unwrap_or(command)-}--pub(super) fn normalized_command_name(command: &str) -> String {- let command = command_basename(command).to_ascii_lowercase();- command- .strip_suffix(".exe")- .unwrap_or(command.as_str())- .to_string()-}--fn is_python_command(command: &str) -> bool {- let command = normalized_command_name(command);- command == "python"- || command == "pythonw"- || command- .strip_prefix("pythonw")- .and_then(|suffix| suffix.chars().next())- .is_some_and(|ch| ch.is_ascii_digit())- || command- .strip_prefix("python")- .and_then(|suffix| suffix.chars().next())- .is_some_and(|ch| ch.is_ascii_digit())-}--pub(super) fn is_command_executor(command: &str) -> bool {- let command = normalized_command_name(command);- is_python_command(command.as_str())- || matches!(- command.as_str(),- "xargs"- | "awk"- | "gawk"- | "mawk"- | "nawk"- | "perl"- | "ruby"- | "bash"- | "sh"- | "dash"- | "zsh"- | "ksh"- | "fish"- | "env"- // JS/TS runtimes (the `node_exec`/`npm_exec` shell equivalents)- | "node"- | "nodejs"- | "deno"- | "bun"- // Windows / PowerShell arbitrary-code launchers + LOLBins- | "iex"- | "invoke-expression"- | "cmd"- | "pwsh"- | "powershell"- | "wscript"- | "cscript"- | "mshta"- | "rundll32"- | "start-process"- )-}--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum QuoteState {- None,- Single,- Double,-}--/// Split a shell command into sub-commands by unquoted separators.-///-/// Separators:-/// - `;` and newline-/// - `|`-/// - `&&`, `||`-///-/// Characters inside single or double quotes are treated as literals, so-/// `sqlite3 db "SELECT 1; SELECT 2;"` remains a single segment.-pub(super) fn split_unquoted_segments(command: &str) -> Vec<String> {- let mut segments = Vec::new();- let mut current = String::new();- let mut quote = QuoteState::None;- let mut escaped = false;- let mut chars = command.chars().peekable();-- let push_segment = |segments: &mut Vec<String>, current: &mut String| {- let trimmed = current.trim();- if !trimmed.is_empty() {- segments.push(trimmed.to_string());- }- current.clear();- };-- while let Some(ch) = chars.next() {- match quote {- QuoteState::Single => {- if ch == '\'' {- quote = QuoteState::None;- }- current.push(ch);- }- QuoteState::Double => {- if escaped {- escaped = false;- current.push(ch);- continue;- }- if ch == '\\' {- escaped = true;- current.push(ch);- continue;- }- if ch == '"' {- quote = QuoteState::None;- }- current.push(ch);- }- QuoteState::None => {- if escaped {- escaped = false;- current.push(ch);- continue;- }- if ch == '\\' {- escaped = true;- current.push(ch);- continue;- }-- match ch {- '\'' => {- quote = QuoteState::Single;- current.push(ch);- }- '"' => {- quote = QuoteState::Double;- current.push(ch);- }- ';' | '\n' => push_segment(&mut segments, &mut current),- '|' => {- if chars.next_if_eq(&'|').is_some() {- // Consume full `||`; both characters are separators.- }- push_segment(&mut segments, &mut current);- }- '&' => {- if chars.next_if_eq(&'&').is_some() {- // `&&` is a separator; single `&` is handled separately.- push_segment(&mut segments, &mut current);- } else {- current.push(ch);- }- }- _ => current.push(ch),- }- }- }- }-- let trimmed = current.trim();- if !trimmed.is_empty() {- segments.push(trimmed.to_string());- }-- segments-}--/// Detect a single unquoted `&` operator (background/chain). `&&` is allowed.-///-/// We treat any standalone `&` as unsafe in policy validation because it can-/// chain hidden sub-commands and escape foreground timeout expectations.-pub(super) fn contains_unquoted_single_ampersand(command: &str) -> bool {- let mut quote = QuoteState::None;- let mut escaped = false;- let mut chars = command.chars().peekable();-- while let Some(ch) = chars.next() {- match quote {- QuoteState::Single => {- if ch == '\'' {- quote = QuoteState::None;- }- }- QuoteState::Double => {- if escaped {- escaped = false;- continue;- }- if ch == '\\' {- escaped = true;- continue;- }- if ch == '"' {- quote = QuoteState::None;- }- }- QuoteState::None => {- if escaped {- escaped = false;- continue;- }- if ch == '\\' {- escaped = true;- continue;- }- match ch {- '\'' => quote = QuoteState::Single,- '"' => quote = QuoteState::Double,- '&' if chars.next_if_eq(&'&').is_none() => {- return true;- }- _ => {}- }- }- }- }-- false-}--/// Like [`contains_unquoted_single_ampersand`] but ignores file-descriptor-/// duplication redirects, where the `&` is part of a redirect operator rather-/// than a background/separator: `2>&1`, `>&2` (prev char `>`), and `&>file`-/// (next char `>`). Used by [`has_hidden_execution`] so a benign `… 2>&1` —-/// which `classify_command` already accounts for as a `Write` redirect — is not-/// mistaken for a backgrounded command and hard-blocked after the human-/// approved it. A standalone `&` (e.g. `cmd &`, `a & b`) still returns true,-/// since it can run a second command `classify_command` wouldn't see.-fn contains_unquoted_background_ampersand(command: &str) -> bool {- let mut quote = QuoteState::None;- let mut escaped = false;- let mut prev = '\0';- let mut chars = command.chars().peekable();-- while let Some(ch) = chars.next() {- match quote {- QuoteState::Single => {- if ch == '\'' {- quote = QuoteState::None;- }- }- QuoteState::Double => {- if escaped {- escaped = false;- prev = ch;- continue;- }- if ch == '\\' {- escaped = true;- prev = ch;- continue;- }- if ch == '"' {- quote = QuoteState::None;- }- }- QuoteState::None => {- if escaped {- escaped = false;- prev = ch;- continue;- }- if ch == '\\' {- escaped = true;- prev = ch;- continue;- }- match ch {- '\'' => quote = QuoteState::Single,- '"' => quote = QuoteState::Double,- '&' => {- if chars.next_if_eq(&'&').is_some() {- // `&&` logical AND — consume both, not background.- } else {- let next = chars.peek().copied().unwrap_or('\0');- // Skip fd-dup redirects: `2>&1`/`>&2` (prev `>`) and- // `&>file` (next `>`).- if prev != '>' && next != '>' {- return true;- }- }- }- _ => {}- }- }- }- prev = ch;- }-- false-}--/// Detect an unquoted character in a shell command.-pub(super) fn contains_unquoted_char(command: &str, target: char) -> bool {- let mut quote = QuoteState::None;- let mut escaped = false;-- for ch in command.chars() {- match quote {- QuoteState::Single => {- if ch == '\'' {- quote = QuoteState::None;- }- }- QuoteState::Double => {- if escaped {- escaped = false;- continue;- }- if ch == '\\' {- escaped = true;- continue;- }- if ch == '"' {- quote = QuoteState::None;- continue;- }- }- QuoteState::None => {- if escaped {- escaped = false;- continue;- }- if ch == '\\' {- escaped = true;- continue;- }- match ch {- '\'' => quote = QuoteState::Single,- '"' => quote = QuoteState::Double,- _ if ch == target => return true,- _ => {}- }- }- }- }-- false-}--/// Provably read-only command bases (cross-platform union). A base **not** in-/// this set — and not a recognized network/destructive/executor command, nor a-/// read-only verb of git/npm/cargo — falls through to [`CommandClass::Write`]-/// (the classifier is fail-closed). Conservative on purpose: anything that can-/// write a file under a common flag is intentionally omitted (`sort -o`, `tee`).-const READ_ONLY_BASES: &[&str] = &[- // POSIX inspection / read-only coreutils- "ls",- "cat",- "pwd",- "echo",- "wc",- "head",- "tail",- "date",- "grep",- "egrep",- "fgrep",- "rg",- "which",- "whoami",- "id",- "hostname",- "uname",- "printenv",- "stat",- "file",- "du",- "df",- "tree",- "realpath",- "readlink",- "dirname",- "basename",- "cmp",- "true",- "false",- "sleep",- "seq",- "tty",- "groups",- "locale",- "ps",- "top",- "free",- "uptime",- "lsblk",- "lscpu",- "cut",- // NOTE: OS-native launchers (`open`, `xdg-open`, `start`) are deliberately- // NOT in the read-only set. `classify_command` only sees the base command,- // not its args, and these launchers can open arbitrary `https://` URLs and- // custom URI handlers — i.e. trigger outbound network / system actions — so- // treating them as `Read` (no approval) is too broad. App launching now- // goes through the dedicated `launch_app` tool, which is scoped to named- // applications only and carries no shell-arg ambiguity.- // Windows cmd / PowerShell read verbs + common aliases- "dir",- "type",- "where",- "whereis",- "get-childitem",- "gci",- "get-content",- "gc",- "get-location",- "gl",- "select-string",- "sls",- "measure-object",- "get-item",- "gi",- "test-path",- "resolve-path",- "get-command",- "gcm",- "get-process",-];--/// Commands that reach the network. Always-ask in every acting tier.-const NETWORK_BASES: &[&str] = &[- "curl",- "wget",- "ssh",- "scp",- "sftp",- "rsync",- "nc",- "ncat",- "netcat",- "telnet",- "ftp",- "tftp",- "socat",- // Windows / PowerShell- "invoke-webrequest",- "iwr",- "invoke-restmethod",- "irm",- "start-bitstransfer",- "bitsadmin",-];--/// Catastrophic / irreversible / privilege / system-control bases. Always-ask-/// in every acting tier (Full included). Coarse on the broad Windows verbs-/// (`reg`/`net`/`sc`) — over-prompting there is the safe default.-const DESTRUCTIVE_BASES: &[&str] = &[- // POSIX privilege / disk / system-control- "sudo",- "su",- "doas",- "dd",- "mkfs",- "fdisk",- "sfdisk",- "parted",- "wipefs",- "shred",- "shutdown",- "reboot",- "halt",- "poweroff",- "init",- "telinit",- "mount",- "umount",- "swapoff",- "iptables",- "ip6tables",- "nft",- "ufw",- "firewall-cmd",- "useradd",- "userdel",- "usermod",- "groupadd",- "groupdel",- "passwd",- "chpasswd",- "visudo",- "modprobe",- "insmod",- "rmmod",- // Windows / PowerShell- "format",- "diskpart",- "bcdedit",- "takeown",- "cipher",- "vssadmin",- "reg",- "regedit",- "runas",- "sc",- "net",- "set-executionpolicy",- "stop-computer",- "restart-computer",- "clear-disk",- "format-volume",- "remove-partition",- "disable-computerrestore",-];diff --git a/crates/openhuman-core/src/security/policy/policy_command_part_02.rs b/crates/openhuman-core/src/security/policy/policy_command_part_02.rsdeleted file mode 100644index f1a9c1a1f7..0000000000--- a/crates/openhuman-core/src/security/policy/policy_command_part_02.rs+++ /dev/null@@ -1,196 +0,0 @@--/// Git subcommands that only read repository state. Anything else — including-/// `commit`/`push`/`branch`/`config`/unknown/bare `git` — is fail-closed to-/// `Write`.-const GIT_READ_VERBS: &[&str] = &[- "status",- "log",- "diff",- "show",- "remote",- "describe",- "blame",- "ls-files",- "ls-tree",- "rev-parse",- "cat-file",- "shortlog",- "reflog",- "rev-list",- "name-rev",- "var",- "check-ignore",- "check-attr",- "verify-commit",- "count-objects",- "fsck",- "whatchanged",- "grep",- "version",- "help",-];--/// npm/pnpm/yarn read-only subcommands. `install`/`run`/`test`/`exec` (which-/// run arbitrary scripts) and unknown verbs are fail-closed to `Write`.-const NODE_PKG_READ_VERBS: &[&str] = &[- "ls", "list", "view", "info", "outdated", "ping", "whoami", "help", "why", "audit", "doctor",-];--/// cargo read-only subcommands. `build`/`run`/`test`/`check` compile and may-/// run build scripts, so they are fail-closed to `Write`.-const CARGO_READ_VERBS: &[&str] = &["tree", "metadata", "search", "info", "version", "help"];--/// Detect a pacman *install/upgrade* from its bundled operation flag.-///-/// pacman packs its operation and modifiers into a single flag (`-Syu`, `-Ss`),-/// and `args` reach us already lowercased — so the `-S` (sync) operation is-/// indistinguishable from a literal `-s` by case alone. We therefore key off-/// the *modifier* letters instead of a blanket `starts_with("-s")`, which would-/// over-match every read-only `-S` query: a `-S`-family flag mutates the host-/// only when it carries none of pacman's read-only query modifiers — search-/// (`s`), info (`i`), list (`l`), groups (`g`) or print (`p`). So `-S pkg`,-/// `-Sy`, `-Syu` are installs while `-Ss`/`-Si`/`-Sl`/`-Sg`/`-Sp` are reads.-fn is_pacman_install(args: &[String]) -> bool {- args.iter().any(|a| {- a.strip_prefix("-s")- .is_some_and(|modifiers| !modifiers.contains(['s', 'i', 'l', 'g', 'p']))- })-}--/// Detect a package-manager *install* invocation. These mutate the host /-/// global environment, so they are the always-ask `Install` bucket (even in-/// Full) — the same gate the dedicated `install_tool` enforces, applied to the-/// shell escape hatch. Project-local installs (`npm install` without `-g`,-/// `cargo add`) are ordinary `Write`s and are deliberately NOT matched here.-/// `args` are already lowercased by the caller.-fn is_install_command(base: &str, args: &[String]) -> bool {- let has = |needle: &str| args.iter().any(|a| a == needle);- let first_is = |verb: &str| args.first().map(String::as_str) == Some(verb);- match base {- // System package managers.- "apt" | "apt-get" | "dnf" | "yum" | "zypper" => has("install"),- "pacman" => is_pacman_install(args),- "apk" => has("add"),- "brew" | "snap" | "flatpak" | "winget" | "choco" | "scoop" => has("install"),- // Language package managers — host/global-modifying installs only.- "pip" | "pip3" | "pipx" | "gem" | "go" | "cargo" => first_is("install"),- "npm" | "pnpm" => {- (has("install") || has("i") || has("add")) && (has("-g") || has("--global"))- }- "yarn" => has("global"),- _ => false,- }-}--/// Classify a single already-split shell segment. `base` is the normalized-/// (lowercased, `.exe`-stripped, basename-only) program name; `args` are the-/// lowercased remaining words; `joined` is the lowercased segment used for-/// pattern matching. Fail-closed: an unrecognized base resolves to `Write`.-pub(super) fn classify_segment(base: &str, args: &[String], joined: &str) -> CommandClass {- // Catastrophic patterns first — they win regardless of the base command.- if joined.contains("rm -rf /") || joined.contains("rm -fr /") || joined.contains(":(){:|:&};:")- {- return CommandClass::Destructive;- }- if DESTRUCTIVE_BASES.contains(&base) {- return CommandClass::Destructive;- }- if NETWORK_BASES.contains(&base) {- return CommandClass::Network;- }- // Package installs mutate the host → always-ask Install bucket (closes the- // shell escape hatch around `install_tool`).- if is_install_command(base, args) {- return CommandClass::Install;- }- // Interpreters / code executors run arbitrary code. Fail-closed to Write- // (not Destructive) so Full can still run code while Supervised prompts.- if is_command_executor(base) {- return CommandClass::Write;- }- // `find` is read-only unless it executes commands, deletes, or writes- // files. -fprintf / -fprint / -fprint0 / -fls write their output to a- // named file rather than stdout — an arbitrary-path write that side-steps- // the gated file-write tools (and their workspace confinement), so they- // must be classified Write (approval-gated) alongside -delete.- //- // `args` is built with `split_whitespace()`, which keeps shell quotes that- // the shell itself strips before `find` runs — `find . '-fprint' out`- // arrives as the literal `'-fprint'`. Trim surrounding single/double quotes- // before matching so a quoted predicate cannot slip the write past the gate.- if base == "find" {- if args.iter().any(|a| {- matches!(- a.trim_matches(|c| c == '\'' || c == '"'),- "-exec"- | "-execdir"- | "-ok"- | "-okdir"- | "-delete"- | "-fprintf"- | "-fprint"- | "-fprint0"- | "-fls"- )- }) {- return CommandClass::Write;- }- return CommandClass::Read;- }- // Verb-sensitive VCS / package tools.- if base == "git" {- return verb_class(args, GIT_READ_VERBS);- }- if matches!(base, "npm" | "pnpm" | "yarn") {- return verb_class(args, NODE_PKG_READ_VERBS);- }- if base == "cargo" {- return verb_class(args, CARGO_READ_VERBS);- }- if READ_ONLY_BASES.contains(&base) {- return CommandClass::Read;- }- // Fail closed: unknown or known-mutating base → Write.- CommandClass::Write-}--/// `Read` when the first subcommand word is in `read_verbs`, else fail-closed-/// `Write`. Mirrors the `args.first()` verb check used by `command_risk_level`.-fn verb_class(args: &[String], read_verbs: &[&str]) -> CommandClass {- match args.first().map(String::as_str) {- Some(verb) if read_verbs.contains(&verb) => CommandClass::Read,- _ => CommandClass::Write,- }-}--/// Structural-safety guard for the harness-gated command flow (Option 2). Even-/// after a human approves a command, a hidden subshell / command substitution /-/// output redirect / `tee` / background `&` could smuggle a *different* command-/// past the approval summary, so these are refused outside Full (which is-/// trusted to use redirects and pipes). Mirrors the structural checks in-/// [`SecurityPolicy::is_command_allowed`].-/// Detect shell structure that can **hide execution** from `classify_command`,-/// which only inspects the base command of each `;`/`&&`/`|` segment. Command-/// and process substitution and backticks run an *inner* command classification-/// can't see (`echo $(rm -rf ~)` classifies as `echo` = Read and would run-/// unprompted), and a trailing `&` detaches a process past the gate — so these-/// stay hard-blocked outside Full.-///-/// Deliberately NOT flagged here: plain redirects (`>`, `2>&1`, `2>/dev/null`),-/// `tee`, and `${VAR}` expansion. `classify_command` already lifts a redirect /-/// `tee` to `Write`, so the gate prompts and — once the human approves — the-/// command MUST actually run. Re-blocking an approved `… 2>&1` here was the bug-/// that made Supervised mode unusable: every command the agent wrote carried a-/// `2>&1`, got approved, then silently failed this in-tool guard and never ran.-pub(super) fn has_hidden_execution(command: &str) -> bool {- // The backtick check is deliberately NOT quote-aware: any backtick in the- // command string is blocked, even inside a double-quoted literal. Over-- // blocking is the safe direction here. (By contrast the `&` case below is- // quote-aware via `contains_unquoted_background_ampersand`, because that one- // must still allow benign fd-dup redirects like `2>&1`.)- command.contains('`')- || command.contains("$(")- || command.contains("<(")- || command.contains(">(")- || contains_unquoted_background_ampersand(command)-}