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
chore(composio): remove unused error mapping, argument preparation, and calendar defaulting modules
Steven Enamakeld3d7555afffd
diff --git a/crates/openhuman-core/src/integrations/composio/error_mapping.rs b/crates/openhuman-core/src/integrations/composio/error_mapping.rsdeleted file mode 100644index 153e5b8cf7..0000000000--- a/crates/openhuman-core/src/integrations/composio/error_mapping.rs+++ /dev/null@@ -1,312 +0,0 @@-//! Classify and format Composio tool failures so validation, scope, and-//! upstream-provider errors are not surfaced as generic gateway (502) failures.-//!-//! Issue #1797 — Composio support found tool-level failures on their side while-//! OpenHuman was bucketing them as HTTP 502 / gateway instability.--/// Stable, grep-friendly error classes for metrics and UI routing.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum ComposioErrorClass {- Validation,- InsufficientScope,- /// The connection lacks permission to enable/manage triggers — a 403 whose- /// body does **not** mention "scope" (so [`Self::InsufficientScope`] never- /// matches it). Distinct so the user gets reconnect guidance. See #2913.- TriggerPermission,- RateLimited,- /// Composio answered the execute call with an HTTP 404/410 — the action- /// endpoint or slug is unknown (or the endpoint is deprecated/Gone), NOT a- /// broken connection. Distinct so the user is told their integration is- /// still connected and is **not** advised to re-authenticate a healthy- /// account. See #3219 (direct-mode sent the lowercase toolkit slug to the- /// wrong execute path → 404/410 → misclassified as [`Self::ComposioPlatform`]).- ActionNotFound,- UpstreamProvider,- ComposioPlatform,- Gateway,- Other,-}--impl ComposioErrorClass {- pub fn as_str(self) -> &'static str {- match self {- Self::Validation => "validation",- Self::InsufficientScope => "insufficient_scope",- Self::TriggerPermission => "trigger_permission",- Self::RateLimited => "rate_limited",- Self::ActionNotFound => "action_not_found",- Self::UpstreamProvider => "upstream_provider",- Self::ComposioPlatform => "composio_platform",- Self::Gateway => "gateway",- Self::Other => "other",- }- }-}--pub fn classify_composio_error(tool: &str, message: &str) -> ComposioErrorClass {- let lower = message.to_ascii_lowercase();- // EARLY status arm (#3219): a Composio HTTP 404/410 means the action- // endpoint/slug is unknown or deprecated — NOT a broken connection. It must- // win over the substring arms below, because the 404 body frequently carries- // the phrase "connection error, try to authenticate" that- // `is_composio_platform_shape` would otherwise match, telling the user to- // re-authenticate a perfectly healthy connection.- let class = if is_action_not_found_shape(&lower) {- ComposioErrorClass::ActionNotFound- } else if is_validation_shape(&lower) {- ComposioErrorClass::Validation- } else if is_insufficient_scope_shape(&lower) {- ComposioErrorClass::InsufficientScope- } else if is_trigger_permission_shape(&lower) {- ComposioErrorClass::TriggerPermission- } else if is_rate_limited_shape(&lower) {- ComposioErrorClass::RateLimited- } else if is_gateway_transport_shape(&lower) && !is_embedded_provider_failure(&lower) {- ComposioErrorClass::Gateway- } else if is_composio_platform_shape(&lower) {- ComposioErrorClass::ComposioPlatform- } else if tool.starts_with("GMAIL_")- || tool.starts_with("SLACK_")- || tool.starts_with("NOTION_")- || tool.starts_with("GOOGLECALENDAR_")- {- ComposioErrorClass::UpstreamProvider- } else {- ComposioErrorClass::Other- };- tracing::debug!(- tool = %tool,- class = class.as_str(),- "[composio][classify] error classified"- );- class-}--pub fn format_provider_error(tool: &str, raw: &str) -> String {- let class = classify_composio_error(tool, raw);- let detail = raw.trim();- let body = match class {- ComposioErrorClass::Validation => format!("Invalid arguments for `{tool}`: {detail}"),- ComposioErrorClass::InsufficientScope => format_insufficient_scope_message(tool, detail),- ComposioErrorClass::TriggerPermission => format_trigger_permission_message(tool),- ComposioErrorClass::RateLimited => format_rate_limited_message(tool, detail),- ComposioErrorClass::ActionNotFound => format_action_not_found_message(tool),- ComposioErrorClass::UpstreamProvider => {- format!("`{tool}` failed at the connected provider: {detail}")- }- ComposioErrorClass::ComposioPlatform => {- format!("Composio connection issue for `{tool}`: {detail}")- }- ComposioErrorClass::Gateway => {- format!("Temporary gateway error while calling `{tool}`: {detail}")- }- ComposioErrorClass::Other => format!("`{tool}` failed: {detail}"),- };- prefix_class(class, &body)-}--pub fn remap_transport_error(tool: &str, raw: &str) -> String {- let detail = extract_transport_detail(raw);- let class = if is_embedded_provider_failure(&detail) {- classify_composio_error(tool, &detail)- } else if is_gateway_transport_shape(raw) {- ComposioErrorClass::Gateway- } else {- classify_composio_error(tool, raw)- };- let body = match class {- ComposioErrorClass::InsufficientScope => format_insufficient_scope_message(tool, &detail),- ComposioErrorClass::TriggerPermission => format_trigger_permission_message(tool),- ComposioErrorClass::RateLimited => format_rate_limited_message(tool, &detail),- ComposioErrorClass::ActionNotFound => format_action_not_found_message(tool),- ComposioErrorClass::Gateway => format!(- "Temporary gateway error while calling `{tool}`: {}",- summarize_gateway(raw)- ),- ComposioErrorClass::Validation => format!("Invalid arguments for `{tool}`: {detail}"),- ComposioErrorClass::UpstreamProvider => {- format!("`{tool}` failed at the connected provider: {detail}")- }- ComposioErrorClass::ComposioPlatform => {- format!("Composio connection issue for `{tool}`: {detail}")- }- ComposioErrorClass::Other => format!("`{tool}` failed: {detail}"),- };- prefix_class(class, &body)-}--fn prefix_class(class: ComposioErrorClass, body: &str) -> String {- format!("[composio:error:{}] {}", class.as_str(), body)-}--/// Derive the lowercase toolkit slug from a Composio tool/trigger identifier.-///-/// Identifiers are upper-snake-case (e.g. `GMAIL_NEW_GMAIL_MESSAGE`); the leading-/// segment names the toolkit, so this returns e.g. `gmail`. `str::split('_').next()`-/// always yields `Some(_)` for `&str` input (empty input yields `Some("")`), so-/// `unwrap_or_default()` is a safe, equivalent terminator.-fn derive_toolkit_slug(tool: &str) -> String {- tool.split('_')- .next()- .unwrap_or_default()- .to_ascii_lowercase()-}--fn format_insufficient_scope_message(tool: &str, detail: &str) -> String {- let toolkit = derive_toolkit_slug(tool);- format!(- "`{tool}` was rejected because the connected {toolkit} account is missing required \- permissions ({detail}). Reconnect the integration in Connections → \- {toolkit} and grant the scopes requested during OAuth."- )-}--/// Build the trigger-permission guidance message (issue #2913).-///-/// The toolkit slug is derived from the tool/trigger identifier the same way-/// [`format_insufficient_scope_message`] does (e.g. `GMAIL_NEW_GMAIL_MESSAGE`-/// → `gmail`), so the copy is branded and points the user at reconnecting.-fn format_trigger_permission_message(tool: &str) -> String {- let toolkit = derive_toolkit_slug(tool);- format!(- "Couldn't enable this trigger: the connected {toolkit} account doesn't have \- permission to manage triggers. Reconnect {toolkit} in Connections → \- {toolkit} and grant the permissions requested during OAuth, then try again."- )-}--/// Build the action-not-found guidance (issue #3219).-///-/// Deliberately does **not** echo the raw provider `detail`: a Composio 404-/// body often literally reads "connection error, try to authenticate", and-/// surfacing that verbatim would re-introduce the exact misleading re-auth-/// nudge this class exists to suppress. The raw text is still captured in the-/// `tracing::debug!` line in [`classify_composio_error`] for diagnosis.-fn format_action_not_found_message(tool: &str) -> String {- let toolkit = derive_toolkit_slug(tool);- format!(- "`{tool}` couldn't run: Composio reported this action as not found. Your {toolkit} \- integration is still connected and working — this is not a sign-in problem. The action \- name is likely out of date or Composio's API changed; try again with the current action \- name, or report this if it keeps happening."- )-}--fn format_rate_limited_message(tool: &str, detail: &str) -> String {- format!(- "`{tool}` hit an upstream rate limit ({detail}). Wait a minute and retry, or reduce \- call frequency — this is not an OpenHuman gateway outage."- )-}--fn is_validation_shape(lower: &str) -> bool {- lower.contains("invalid arguments")- || lower.contains("missing required")- || lower.contains("must not be empty")- || lower.contains("required field")- || lower.contains("bad request")- || lower.contains("invalid date")- || lower.contains("rfc 3339")- || lower.contains("timemax")- || lower.contains("timemin")-}--fn is_insufficient_scope_shape(lower: &str) -> bool {- lower.contains("insufficient authentication scopes")- || lower.contains("insufficient scope")- || lower.contains("insufficient permissions")- || (lower.contains("403") && lower.contains("scope"))- || lower.contains("invalid oauth scope")-}--/// Heuristic for a trigger-permission denial (issue #2913).-///-/// The backend 403 body reads "You do not have permission to enable triggers on-/// this connection" — note it has **no** "scope" token, so-/// [`is_insufficient_scope_shape`] never matches. We require a forbidden signal-/// (`403`/`forbidden`) AND a permission-denied phrase AND trigger context, so a-/// generic 403 won't be miscategorised.-fn is_trigger_permission_shape(lower: &str) -> bool {- let forbidden = lower.contains("403") || lower.contains("forbidden");- let permission_denied = lower.contains("do not have permission")- || lower.contains("not have permission")- || lower.contains("permission denied")- || lower.contains("not permitted")- || lower.contains("not allowed");- let trigger_context = lower.contains("trigger");- forbidden && permission_denied && trigger_context-}--fn is_rate_limited_shape(lower: &str) -> bool {- lower.contains("rate limit")- || lower.contains("rate_limit")- || lower.contains("ratelimited")- || lower.contains("too many requests")- || lower.contains("429")-}--/// True when the message carries a Composio HTTP 404 or 410 status (#3219).-///-/// Both `response_error` shapes (`HTTP 404` and `HTTP 404: <body>`) and the-/// wrapped v3/v2 fallback string keep the literal `HTTP <code>` token, so a-/// substring scan is reliable. Scoped to 404 (action/endpoint unknown) and 410-/// (endpoint Gone/deprecated) on purpose — other 4xx/5xx keep their existing-/// validation / scope / rate-limit / gateway classifications.-fn is_action_not_found_shape(lower: &str) -> bool {- lower.contains("http 404") || lower.contains("http 410")-}--fn is_composio_platform_shape(lower: &str) -> bool {- lower.contains("connection error, try to authenticate")- || lower.contains("not enabled")- || lower.contains("not connected")- || lower.contains("token revoked")-}--fn is_gateway_transport_shape(lower: &str) -> bool {- lower.contains("backend returned 502")- || lower.contains("502 bad gateway")- || lower.contains("backend returned 503")- || lower.contains("backend returned 504")- || lower.contains("(502 ")- || lower.contains("(503 ")- || lower.contains("(504 ")-}--fn is_embedded_provider_failure(lower: &str) -> bool {- is_validation_shape(lower)- || is_insufficient_scope_shape(lower)- || is_trigger_permission_shape(lower)- || is_rate_limited_shape(lower)- || is_action_not_found_shape(lower)- || is_composio_platform_shape(lower)- || lower.contains("composio")- || lower.contains("google")- || lower.contains("slack")- || lower.contains("notion")- || lower.contains("gmail")- || lower.contains("fetch_type")- || lower.contains("timemax")- || lower.contains("timemin")-}--fn extract_transport_detail(raw: &str) -> String {- raw.split_once(": ")- .map(|(_, tail)| tail.to_string())- .unwrap_or_else(|| raw.to_string())-}--fn summarize_gateway(raw: &str) -> String {- if let Some(idx) = raw.find("Backend returned ") {- let rest = &raw[idx..];- if let Some(colon) = rest.rfind(": ") {- return rest[colon + 2..].trim().to_string();- }- return rest.trim().to_string();- }- raw.trim().to_string()-}--#[cfg(test)]-#[path = "error_mapping_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/error_mapping_tests.rs b/crates/openhuman-core/src/integrations/composio/error_mapping_tests.rsdeleted file mode 100644index 1b80710239..0000000000--- a/crates/openhuman-core/src/integrations/composio/error_mapping_tests.rs+++ /dev/null@@ -1,221 +0,0 @@-use super::{- classify_composio_error, derive_toolkit_slug, format_provider_error, remap_transport_error,- ComposioErrorClass,-};--// ── derive_toolkit_slug (issue #2913 nitpick — shared slug extraction) ──--#[test]-fn derive_toolkit_slug_extracts_leading_segment_lowercased() {- assert_eq!(derive_toolkit_slug("GMAIL_NEW_GMAIL_MESSAGE"), "gmail");-}--#[test]-fn derive_toolkit_slug_single_segment_is_lowercased() {- assert_eq!(derive_toolkit_slug("SLACK"), "slack");-}--#[test]-fn derive_toolkit_slug_empty_input_returns_empty_not_fallback() {- // Behavior-parity guard: `"".split('_').next()` yields `Some("")`, so the- // `unwrap_or("integration")` fallback does NOT apply — preserve that exactly.- assert_eq!(derive_toolkit_slug(""), "");-}--#[test]-fn classifies_gmail_insufficient_scope() {- let msg = "HTTP 403: Request had insufficient authentication scopes.";- assert_eq!(- classify_composio_error("GMAIL_FETCH_EMAILS", msg),- ComposioErrorClass::InsufficientScope- );-}--#[test]-fn formats_gmail_insufficient_scope_as_missing_permissions_not_disconnected() {- let mapped = format_provider_error(- "GMAIL_SEND_EMAIL",- "HTTP 403: Request had insufficient authentication scopes.",- );- assert!(mapped.contains("[composio:error:insufficient_scope]"));- assert!(mapped.contains("connected gmail account is missing required permissions"));- assert!(mapped.contains("Connections → gmail"));- assert!(mapped.contains("gmail"));- assert!(!mapped.contains("not connected"));- assert!(!mapped.contains("Settings → Skills"));-}--#[test]-fn classifies_slack_rate_limit() {- let msg = "Slack API error: ratelimited";- assert_eq!(- classify_composio_error("SLACK_FETCH_CONVERSATION_HISTORY", msg),- ComposioErrorClass::RateLimited- );-}--#[test]-fn embedded_provider_failure_in_502_body_is_not_gateway() {- let raw = "Backend returned 502 Bad Gateway for POST https://api.example.com/agent-integrations/composio/execute: \- timeMax must be RFC 3339 timestamp";- let mapped = remap_transport_error("GOOGLECALENDAR_EVENTS_LIST", raw);- assert!(- mapped.contains("[composio:error:"),- "expected classified prefix, got: {mapped}"- );- assert!(- !mapped.contains("[composio:error:gateway]"),- "provider-shaped 502 body must not be labeled gateway: {mapped}"- );-}--#[test]-fn true_gateway_stays_gateway_class() {- let raw = "Backend returned 502 Bad Gateway for POST https://api.example.com/x: upstream down";- let mapped = remap_transport_error("GMAIL_SEND_EMAIL", raw);- assert!(- mapped.contains("[composio:error:gateway]"),- "expected gateway class, got: {mapped}"- );-}--// ── HTTP 404/410 action-not-found vs auth (issue #3219) ────────────────--#[test]-fn classifies_http_404_with_auth_phrase_as_action_not_found_not_platform() {- // The exact #3219 shape: a 404 whose body carries the misleading- // "connection error, try to authenticate" phrase. Status must win.- let msg = "HTTP 404: connection error, try to authenticate";- assert_eq!(- classify_composio_error("GMAIL_SEND_EMAIL", msg),- ComposioErrorClass::ActionNotFound- );-}--#[test]-fn classifies_http_410_gone_as_action_not_found() {- let msg = "HTTP 410: This endpoint is deprecated";- assert_eq!(- classify_composio_error("GOOGLEDOCS_UPDATE_DOCUMENT", msg),- ComposioErrorClass::ActionNotFound- );-}--#[test]-fn action_not_found_message_does_not_recommend_reauth() {- let mapped = format_provider_error(- "GMAIL_SEND_EMAIL",- "HTTP 404: connection error, try to authenticate",- );- let lower = mapped.to_lowercase();- assert!(mapped.contains("[composio:error:action_not_found]"));- assert!(lower.contains("still connected"));- // Must NOT echo the misleading provider phrase or nudge re-auth/reconnect.- assert!(- !lower.contains("authenticate"),- "must not surface the re-auth phrase: {mapped}"- );- assert!(- !lower.contains("reconnect"),- "must not tell the user to reconnect a healthy connection: {mapped}"- );- assert!(- !mapped.contains("Connections →"),- "must not show the re-auth CTA: {mapped}"- );-}--#[test]-fn genuine_auth_phrase_without_http_status_stays_platform() {- // Same phrase, but with NO 4xx status — a real platform/connection issue- // must still classify as ComposioPlatform.- let msg = "connection error, try to authenticate";- assert_eq!(- classify_composio_error("GMAIL_SEND_EMAIL", msg),- ComposioErrorClass::ComposioPlatform- );-}--#[test]-fn wrapped_v3_v2_404_fallback_classifies_as_action_not_found() {- // The real transport string after both v3 and v2 fail — the wrapped form- // produced by `execute_action`, fed through `remap_transport_error`.- let raw = "Composio execute failed on v3 (Composio v3 action execution failed: \- HTTP 404: connection error, try to authenticate) and v2 fallback \- (Composio v2 action execution failed: HTTP 410: Gone)";- let mapped = remap_transport_error("GMAIL_SEND_EMAIL", raw);- assert!(- mapped.contains("[composio:error:action_not_found]"),- "wrapped 404/410 must map to action_not_found, got: {mapped}"- );- assert!(- !mapped.to_lowercase().contains("authenticate"),- "wrapped path must not surface the re-auth phrase: {mapped}"- );-}--// ── Trigger-permission denial (issue #2913) ───────────────────────────--#[test]-fn classifies_trigger_permission_from_403_without_scope() {- // The backend 403 body does NOT contain the word "scope", so it must be- // classified as TriggerPermission rather than InsufficientScope or Other.- let raw = "Backend returned 403 Forbidden for POST \- https://api.example.com/agent-integrations/composio/triggers: \- You do not have permission to enable triggers on this connection";- assert_eq!(- classify_composio_error("GMAIL_NEW_GMAIL_MESSAGE", raw),- ComposioErrorClass::TriggerPermission- );-}--#[test]-fn trigger_permission_is_not_classified_as_insufficient_scope() {- let raw = "403 Forbidden: You do not have permission to enable triggers on this connection";- // Regression guard: the scope heuristic requires the literal "scope" token,- // which this message lacks — so it must not be InsufficientScope.- assert_ne!(- classify_composio_error("GMAIL_NEW_GMAIL_MESSAGE", raw),- ComposioErrorClass::InsufficientScope- );-}--#[test]-fn formats_trigger_permission_as_actionable_reconnect_guidance() {- let raw = "Backend returned 403 Forbidden for POST \- https://api.example.com/agent-integrations/composio/triggers: \- You do not have permission to enable triggers on this connection";- let mapped = format_provider_error("GMAIL_NEW_GMAIL_MESSAGE", raw);- assert!(- mapped.contains("[composio:error:trigger_permission]"),- "expected trigger_permission class prefix, got: {mapped}"- );- // Branded, actionable copy that points the user at reconnecting.- assert!(- mapped.contains("gmail"),- "expected toolkit branding: {mapped}"- );- assert!(- mapped.contains("Connections → gmail"),- "expected reconnect guidance: {mapped}"- );- assert!(- mapped.to_lowercase().contains("permission"),- "expected permission wording: {mapped}"- );- // Must not leak the raw backend blob as the message.- assert!(- !mapped.contains("Backend returned 403"),- "raw backend blob leaked: {mapped}"- );-}--#[test]-fn generic_403_without_trigger_context_is_not_trigger_permission() {- // A 403 with no "trigger" context must not be miscategorised.- let raw = "403 Forbidden: you do not have permission to read this file";- assert_ne!(- classify_composio_error("GMAIL_FETCH_EMAILS", raw),- ComposioErrorClass::TriggerPermission- );-}diff --git a/crates/openhuman-core/src/integrations/composio/execute_prepare.rs b/crates/openhuman-core/src/integrations/composio/execute_prepare.rsdeleted file mode 100644index f74218125f..0000000000--- a/crates/openhuman-core/src/integrations/composio/execute_prepare.rs+++ /dev/null@@ -1,163 +0,0 @@-//! Normalize and validate Composio action arguments before dispatch (#1797).--use serde_json::{json, Map, Value};--pub fn prepare_execute_arguments(tool: &str, arguments: Option<Value>) -> Result<Value, String> {- let tool = tool.trim();- let mut args = match arguments {- Some(Value::Object(map)) => Value::Object(map),- Some(Value::Null) | None => Value::Object(Map::new()),- Some(other) => {- return Err(format!(- "composio: `{tool}` arguments must be a JSON object, got {}",- other- ));- }- };-- if tool.starts_with("GOOGLECALENDAR_") {- normalize_calendar_time_bounds(&mut args)?;- }- if tool == "NOTION_FETCH_DATA" {- ensure_notion_fetch_type(&mut args)?;- }- if tool == "GMAIL_SEND_EMAIL" {- validate_gmail_send_email(&args)?;- }- if tool == "GMAIL_ADD_LABEL_TO_EMAIL" {- validate_gmail_add_label(&args)?;- }-- Ok(args)-}--fn normalize_calendar_time_bounds(args: &mut Value) -> Result<(), String> {- let Some(obj) = args.as_object_mut() else {- return Ok(());- };- for key in ["timeMin", "timeMax", "time_min", "time_max"] {- if let Some(v) = obj.get(key).cloned() {- if let Some(normalized) = normalize_rfc3339_bound(&v) {- obj.insert(key.to_string(), Value::String(normalized));- } else if v.is_string() {- return Err(format!(- "GOOGLECALENDAR time bound `{key}` must be an RFC 3339 timestamp \- (e.g. 2026-05-14T00:00:00Z), not a bare date"- ));- }- }- }- Ok(())-}--fn normalize_rfc3339_bound(value: &Value) -> Option<String> {- let s = value.as_str()?.trim();- if s.is_empty() {- return None;- }- if s.contains('T') {- return Some(s.to_string());- }- // A bare date like `2026-05-14` is promoted to RFC 3339 midnight UTC.- // Parse explicitly so impossible dates such as `2026-99-99` are rejected- // up front instead of being passed through to Google Calendar.- if chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").is_ok() {- return Some(format!("{s}T00:00:00Z"));- }- None-}--fn ensure_notion_fetch_type(args: &mut Value) -> Result<(), String> {- let Some(obj) = args.as_object_mut() else {- return Ok(());- };- let has_fetch_type = obj- .get("fetch_type")- .or_else(|| obj.get("fetchType"))- .and_then(|v| v.as_str())- .map(str::trim)- .is_some_and(|s| !s.is_empty());- if has_fetch_type {- return Ok(());- }- let inferred = obj- .get("filter")- .and_then(|f| f.get("value").or_else(|| f.get("property")))- .and_then(|v| v.as_str())- .map(str::trim)- .filter(|s| !s.is_empty())- .map(|v| match v {- "page" | "pages" => "pages",- "database" | "databases" => "databases",- other => other,- })- .unwrap_or("pages");- tracing::debug!(- fetch_type = %inferred,- "[composio][prepare] NOTION_FETCH_DATA: inferred fetch_type"- );- obj.insert("fetch_type".to_string(), json!(inferred));- Ok(())-}--fn validate_gmail_send_email(args: &Value) -> Result<(), String> {- let Some(obj) = args.as_object() else {- return Err("GMAIL_SEND_EMAIL: arguments must be an object".to_string());- };- let recipient = obj- .get("to")- .or_else(|| obj.get("recipient_email"))- .or_else(|| obj.get("recipientEmail"))- .and_then(|v| v.as_str())- .map(str::trim)- .filter(|s| !s.is_empty());- if recipient.is_some() {- return Ok(());- }- Err(- "GMAIL_SEND_EMAIL: `to` (or `recipient_email`) is required — cannot send without a recipient"- .to_string(),- )-}--fn validate_gmail_add_label(args: &Value) -> Result<(), String> {- let Some(obj) = args.as_object() else {- return Err("GMAIL_ADD_LABEL_TO_EMAIL: arguments must be an object".to_string());- };- let message_id = obj- .get("message_id")- .or_else(|| obj.get("messageId"))- .and_then(|v| v.as_str())- .map(str::trim)- .filter(|s| !s.is_empty());- if message_id.is_none() {- return Err("GMAIL_ADD_LABEL_TO_EMAIL: `message_id` is required".to_string());- }- let add = non_empty_string_array(obj.get("add_label_ids").or_else(|| obj.get("addLabelIds")));- let remove = non_empty_string_array(- obj.get("remove_label_ids")- .or_else(|| obj.get("removeLabelIds")),- );- if add || remove {- return Ok(());- }- Err(- "GMAIL_ADD_LABEL_TO_EMAIL: provide at least one non-empty label in `add_label_ids` or \- `remove_label_ids`"- .to_string(),- )-}--fn non_empty_string_array(value: Option<&Value>) -> bool {- match value {- Some(Value::Array(items)) => items- .iter()- .any(|v| v.as_str().map(str::trim).is_some_and(|s| !s.is_empty())),- Some(Value::String(s)) => !s.trim().is_empty(),- _ => false,- }-}--#[cfg(test)]-#[path = "execute_prepare_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/execute_prepare_tests.rs b/crates/openhuman-core/src/integrations/composio/execute_prepare_tests.rsdeleted file mode 100644index 574e26c974..0000000000--- a/crates/openhuman-core/src/integrations/composio/execute_prepare_tests.rs+++ /dev/null@@ -1,41 +0,0 @@-use serde_json::json;--use super::prepare_execute_arguments;--#[test]-fn calendar_bare_date_becomes_rfc3339() {- let args = json!({- "timeMin": "2026-05-14",- "timeMax": "2026-05-15"- });- let prepared = prepare_execute_arguments("GOOGLECALENDAR_EVENTS_LIST", Some(args)).unwrap();- assert_eq!(prepared["timeMin"], "2026-05-14T00:00:00Z");- assert_eq!(prepared["timeMax"], "2026-05-15T00:00:00Z");-}--#[test]-fn notion_fetch_data_infers_fetch_type_from_filter() {- let args = json!({- "filter": { "value": "page", "property": "object" },- "page_size": 25- });- let prepared = prepare_execute_arguments("NOTION_FETCH_DATA", Some(args)).unwrap();- assert_eq!(prepared["fetch_type"], "pages");-}--#[test]-fn gmail_send_requires_recipient() {- let err = prepare_execute_arguments("GMAIL_SEND_EMAIL", Some(json!({ "subject": "hi" })))- .unwrap_err();- assert!(err.contains("recipient") || err.contains("`to`"));-}--#[test]-fn gmail_add_label_requires_label_ids() {- let err = prepare_execute_arguments(- "GMAIL_ADD_LABEL_TO_EMAIL",- Some(json!({ "message_id": "m1", "add_label_ids": [], "remove_label_ids": [] })),- )- .unwrap_err();- assert!(err.contains("add_label_ids") || err.contains("remove_label_ids"));-}diff --git a/crates/openhuman-core/src/integrations/composio/googlecalendar_args.rs b/crates/openhuman-core/src/integrations/composio/googlecalendar_args.rsindex 09b65880c3..6190972005 100644--- a/crates/openhuman-core/src/integrations/composio/googlecalendar_args.rs+++ b/crates/openhuman-core/src/integrations/composio/googlecalendar_args.rs@@ -1,43 +1,9 @@-//! Default-args transformer for Composio Google Calendar list/find slugs.+//! Host time-zone lookup for Google Calendar defaults.//!-//! Background (issue #1714): when the agent asks Composio for calendar-//! events on behalf of the user, the per-call argument object is built-//! inside the agent loop (model-constructed) or by a direct call site.-//! Both historically went out with UTC-encoded `timeMin` / `timeMax` and no-//! `timeZone` / `singleEvents` field.-//!-//! Two practical consequences for users in non-UTC timezones (real-//! report: IST user with an event stored against `Asia/Riyadh` (GST)):-//!-//! 1. Without `singleEvents = true`, the Google Calendar API returns the-//! parent recurring-event entry, not the individual day's occurrence-//! — and our downstream filter is keyed on the occurrence's-//! `start.dateTime`. The user's recurring 12 PM IST stand-up never-//! shows up because the response is the never-occurring template.-//!-//! 2. Without `timeZone`, the API normalises returned `start.dateTime`-//! / `end.dateTime` against the *calendar's* default zone, which is-//! not necessarily the requester's local zone. Our display + window-//! filter both expect the requester's local zone, so events stored-//! against a different zone slide outside the window.-//!-//! The fix is to default both fields at the *execute* boundary so the-//! agent's prompt template and any direct call site all benefit — no per-call-site discipline required.-//! Callers that pass either field explicitly win; we never overwrite-//! user-supplied intent.--use serde_json::Value;--/// Composio action slugs whose arguments accept (and benefit from)-/// `timeZone` + `singleEvents` defaulting. Kept short on purpose: only-/// the slugs that take a `timeMin`/`timeMax` window go in here.-///-/// Adding a new slug is the right move when (a) it accepts both fields-/// and (b) at least one production call site has been observed to fire-/// it without an explicit zone in production. Speculative additions-/// just expand the transformer's blast radius for zero current win.-pub(crate) const TZ_DEFAULTING_SLUGS: &[&str] =- &["GOOGLECALENDAR_EVENTS_LIST", "GOOGLECALENDAR_FIND_EVENT"];+//! The defaulting itself (`timeZone` + `singleEvents` for calendar list/find+//! actions, issue #1714) is `tinyconnectors::execute::apply_calendar_query_defaults`.+//! It takes the zone as a parameter because reading the machine's zone is host+//! business; this is that lookup./// Resolve the host's IANA zone name (`Asia/Kolkata`, `America/Los_Angeles`)./// Falls back to `"UTC"` when the host can't resolve a zone — e.g. CI@@ -58,61 +24,6 @@ pub(crate) fn current_iana_timezone() -> String {}}-/// If `slug` is one of the [`TZ_DEFAULTING_SLUGS`] and `arguments` is a-/// JSON object, insert `singleEvents = true` and `timeZone = <iana>` —-/// but only when those keys are absent. Returns the (possibly-/// mutated) argument value.-///-/// Non-object payloads pass through untouched. The caller may pass-/// `None`/`null` to mean "no args supplied yet"; we treat that as an-/// empty object so the defaults still apply.-pub(crate) fn apply_calendar_query_defaults(- slug: &str,- arguments: Option<Value>,- iana: &str,-) -> Option<Value> {- if !TZ_DEFAULTING_SLUGS.contains(&slug) {- tracing::debug!(- target: "composio",- slug,- "[composio][googlecalendar] slug not in tz-defaulting allowlist; pass-through"- );- return arguments;- }- // Convert `None` to an empty object — the Composio backend treats- // missing args + `{}` identically, so this just gives us a place to- // hang our defaults without changing observable behaviour for- // existing no-arg callers.- let synthesised_object = arguments.is_none();- let mut value = arguments.unwrap_or_else(|| Value::Object(Default::default()));- let Some(map) = value.as_object_mut() else {- tracing::debug!(- target: "composio",- slug,- "[composio][googlecalendar] non-object payload; pass-through unchanged"- );- return Some(value);- };- let injected_time_zone = !map.contains_key("timeZone");- if injected_time_zone {- map.insert("timeZone".to_string(), Value::String(iana.to_string()));- }- let injected_single_events = !map.contains_key("singleEvents");- if injected_single_events {- map.insert("singleEvents".to_string(), Value::Bool(true));- }- tracing::debug!(- target: "composio",- slug,- iana,- synthesised_object,- injected_time_zone,- injected_single_events,- "[composio][googlecalendar] applied calendar query defaults"- );- Some(value)-}-#[cfg(test)]#[path = "googlecalendar_args_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/googlecalendar_args_tests.rs b/crates/openhuman-core/src/integrations/composio/googlecalendar_args_tests.rsindex e2aaa2e8d6..64eef21876 100644--- a/crates/openhuman-core/src/integrations/composio/googlecalendar_args_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/googlecalendar_args_tests.rs@@ -1,118 +1,6 @@-//! Tests for the Google Calendar default-args transformer in [`super`].-//!-//! See `googlecalendar_args.rs` for the bug background (#1714 — events-//! stored against a non-requester zone slipped outside the query window-//! because we shipped no `timeZone` / `singleEvents` defaults).+//! Tests for the host time-zone lookup in [`super`].-use serde_json::json;--use super::{apply_calendar_query_defaults, current_iana_timezone, TZ_DEFAULTING_SLUGS};--#[test]-fn injects_tz_and_single_events_when_absent() {- let args = apply_calendar_query_defaults(- "GOOGLECALENDAR_EVENTS_LIST",- Some(json!({- "connectionId": "conn-1",- "timeMin": "2026-05-14T00:00:00+05:30",- "timeMax": "2026-05-14T23:59:59+05:30",- "maxResults": 20- })),- "Asia/Kolkata",- )- .expect("transformer must return a payload");-- assert_eq!(args["timeZone"], "Asia/Kolkata");- assert_eq!(args["singleEvents"], true);- assert_eq!(- args["connectionId"], "conn-1",- "must not perturb caller-supplied fields"- );-}--#[test]-fn does_not_overwrite_caller_supplied_time_zone() {- // A power-user / direct call path may pass an explicit zone that- // differs from the host. We must respect it, not silently swap to- // host zone — the caller has more context than the host clock.- let args = apply_calendar_query_defaults(- "GOOGLECALENDAR_EVENTS_LIST",- Some(json!({- "timeZone": "America/Los_Angeles",- "timeMin": "2026-05-14T00:00:00-07:00",- })),- "Asia/Kolkata",- )- .unwrap();-- assert_eq!(args["timeZone"], "America/Los_Angeles");- assert_eq!(args["singleEvents"], true);-}--#[test]-fn does_not_overwrite_caller_supplied_single_events() {- let args = apply_calendar_query_defaults(- "GOOGLECALENDAR_EVENTS_LIST",- Some(json!({- "singleEvents": false,- })),- "UTC",- )- .unwrap();-- assert_eq!(args["singleEvents"], false);- assert_eq!(args["timeZone"], "UTC");-}--#[test]-fn none_args_become_object_with_defaults() {- let args = apply_calendar_query_defaults("GOOGLECALENDAR_EVENTS_LIST", None, "Europe/London")- .expect("None must coerce to a populated default object");-- assert!(args.is_object());- assert_eq!(args["timeZone"], "Europe/London");- assert_eq!(args["singleEvents"], true);-}--#[test]-fn non_calendar_slug_is_untouched() {- // The transformer must be a no-op for any slug not in the- // allowlist — we never want to inject TZ semantics into, say,- // gmail/notion/github args.- let original = json!({- "to": "[email protected]",- "subject": "hi",- });- let passed =- apply_calendar_query_defaults("GMAIL_SEND_EMAIL", Some(original.clone()), "Asia/Kolkata")- .unwrap();-- assert_eq!(passed, original);-}--#[test]-fn non_object_payload_is_untouched() {- // Defensive: if a caller hands us a stray scalar/array, don't- // synthesize an object — that would mask a real bug at the call- // site. Pass it through and let the backend's schema check reject.- let passed = apply_calendar_query_defaults(- "GOOGLECALENDAR_EVENTS_LIST",- Some(json!(["unexpected"])),- "Asia/Kolkata",- )- .unwrap();-- assert_eq!(passed, json!(["unexpected"]));-}--#[test]-fn slug_allowlist_covers_known_window_taking_actions() {- // Sanity-check the allowlist content. EVENTS_LIST is the- // user-visible "today/tomorrow" entry point; FIND_EVENT is the- // sibling slug the model also picks for natural-language queries.- assert!(TZ_DEFAULTING_SLUGS.contains(&"GOOGLECALENDAR_EVENTS_LIST"));- assert!(TZ_DEFAULTING_SLUGS.contains(&"GOOGLECALENDAR_FIND_EVENT"));-}+use super::current_iana_timezone;#[test]fn current_iana_timezone_returns_non_empty_string() {diff --git a/crates/openhuman-core/src/integrations/composio/mod.rs b/crates/openhuman-core/src/integrations/composio/mod.rsindex b430d2e994..79c3504af6 100644--- a/crates/openhuman-core/src/integrations/composio/mod.rs+++ b/crates/openhuman-core/src/integrations/composio/mod.rs@@ -42,9 +42,7 @@ pub mod client;pub mod connected_integrations;pub mod contract_gate;pub(crate) mod direct_auth;-pub mod error_mapping;pub mod execute_dispatch;-pub mod execute_prepare;pub mod googlecalendar_args;pub mod identity;pub mod identity_store;@@ -54,7 +52,6 @@ pub mod periodic;pub mod profile_md;pub mod providers;pub mod schemas;-pub mod task_window;pub mod tools;pub mod trigger_history;pub mod types;diff --git a/crates/openhuman-core/src/integrations/composio/ops/triggers.rs b/crates/openhuman-core/src/integrations/composio/ops/triggers.rsindex be1753d93a..19185b8e0a 100644--- a/crates/openhuman-core/src/integrations/composio/ops/triggers.rs+++ b/crates/openhuman-core/src/integrations/composio/ops/triggers.rs@@ -151,8 +151,8 @@ pub async fn composio_enable_trigger(// Enabling is the one trigger call a user drives directly from a// settings screen, so its failures are mapped to something a person can// act on ("reconnect GitHub") rather than the provider's own wording.- let class = super::super::error_mapping::classify_composio_error(slug, &e);- let mapped = super::super::error_mapping::format_provider_error(slug, &e);+ let class = tinyconnectors::execute::classify_composio_error(slug, &e);+ let mapped = tinyconnectors::execute::format_provider_error(slug, &e);tracing::warn!(slug = %slug,connection_id = %connection_id,diff --git a/crates/openhuman-core/src/integrations/composio/task_window.rs b/crates/openhuman-core/src/integrations/composio/task_window.rsdeleted file mode 100644index 053a2bd57f..0000000000--- a/crates/openhuman-core/src/integrations/composio/task_window.rs+++ /dev/null@@ -1,358 +0,0 @@-//! Recency-window narrowing for Composio **task-fetch** actions.-//!-//! Background: the `morning_briefing` agent fetches the user's open tasks via-//! `composio_execute` against whichever task manager they connected. Left-//! unbounded those calls return the *entire* backlog; the brief only wants-//! what was created/changed in the last 24h. The cron runner installs a-//! [`crate::agent::harness::current_task_recency_window`] for the-//! brief turn, and this module applies it inside the `composio_execute`-//! handler.-//!-//! Two layers, both gated on the task-local window being present AND the slug-//! appearing in [`spec_for`]:-//!-//! 1. **Best-effort server-side narrowing** ([`apply_window_args`]): inject an-//! ordering / `*_since` argument the provider understands, when the caller-//! didn't supply one. Caller-supplied values always win. This only reduces-//! payload size / improves ordering — correctness never depends on it.-//! 2. **Authoritative client-side post-filter** ([`filter_response`]): drop-//! rows whose timestamp predates `now - window`. This is the enforcement.-//! Mirrors the proven `sync_depth_days` floor in the native sync providers-//! (e.g. `memory_sync::composio::providers::linear::provider`).-//!-//! Scope is intentionally narrow: only slugs with a *verified* response shape-//! are listed. An unknown slug degrades to "no filtering" — never a crash and never a-//! silently-emptied result. An unrecognized envelope or an unparseable-//! timestamp is treated as "keep", so a wrong field-map degrades to no-op.-//!-//! `markdownFormatted` note: in backend mode the response often carries a-//! server-rendered markdown string that the tool surface prefers over `data`.-//! When the post-filter removes rows it clears `markdown_formatted` so the-//! agent reads the *filtered* JSON instead of the stale full-backlog markdown.--use chrono::{DateTime, Utc};-use serde_json::Value;--use super::types::ComposioExecuteResponse;--/// How a provider encodes a task timestamp, so the post-filter can compare it.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum TsFormat {- /// RFC3339 / ISO-8601 string, e.g. `2026-06-21T10:00:00.000Z`.- Iso8601,- /// Unix epoch **milliseconds**, as a JSON string or number (ClickUp).- EpochMillis,-}--/// Per-slug knowledge needed to narrow + filter a task-fetch response.-struct TaskWindowSpec {- /// Candidate key-paths to the items array inside `resp.data`. The first- /// path that resolves to a JSON array wins (providers differ in whether- /// they nest under `data`, `results`, `nodes`, …). An empty path means- /// `resp.data` is itself the array.- items_paths: &'static [&'static [&'static str]],- /// Timestamp fields on each item, checked in order. A row is **kept** if- /// *any* listed field parses to a time `>= floor`. A row whose fields are- /// all missing/unparseable is also kept (we never drop on ambiguity).- ts_fields: &'static [(&'static str, TsFormat)],- /// Optional static ordering arg to inject (key, value) when absent.- order_arg: Option<(&'static str, &'static str)>,-}--/// Verified task-fetch slugs. Keep this list to slugs whose response shape is-/// confirmed (repo-proven or docs-verified). See module docs.-fn spec_for(slug: &str) -> Option<TaskWindowSpec> {- match slug {- // Linear — repo-proven request (`orderBy:"updatedAt"`) and response- // shape. Linear returns GraphQL connections (`{issues:{nodes:[...]}}`)- // that Composio may re-wrap under `data` / `data.data`; the items and- // timestamp paths mirror `providers::linear::sync::{extract_issues,- // extract_issue_updated}` so we catch every nesting (else we'd hit the- // no-array pass-through and leave the backlog unfiltered).- "LINEAR_LIST_LINEAR_ISSUES" | "LINEAR_SEARCH_ISSUES" => Some(TaskWindowSpec {- items_paths: &[- &["data", "issues", "nodes"],- &["data", "data", "nodes"],- &["data", "nodes"],- &["nodes"],- &["issues", "nodes"],- &["data", "results"],- &["results"],- &["data", "issues"],- &["issues"],- ],- ts_fields: &[- ("updatedAt", TsFormat::Iso8601),- ("data.updatedAt", TsFormat::Iso8601),- ("updated_at", TsFormat::Iso8601),- ("data.updated_at", TsFormat::Iso8601),- ],- order_arg: Some(("orderBy", "updatedAt")),- }),- // ClickUp — repo-proven request (`order_by:"updated"`) and response- // shape, mirroring `providers::clickup::sync::{extract_tasks,- // extract_task_updated}` (envelope `data.tasks` / `tasks` /- // `data.data.tasks`; timestamp `date_updated` epoch-ms, possibly- // wrapped or camelCased by Composio).- "CLICKUP_GET_FILTERED_TEAM_TASKS" | "CLICKUP_GET_TASKS" => Some(TaskWindowSpec {- items_paths: &[- &["data", "tasks"],- &["tasks"],- &["data", "data", "tasks"],- &["data", "results"],- &["results"],- ],- ts_fields: &[- ("date_updated", TsFormat::EpochMillis),- ("data.date_updated", TsFormat::EpochMillis),- ("dateUpdated", TsFormat::EpochMillis),- ("data.dateUpdated", TsFormat::EpochMillis),- ],- order_arg: Some(("order_by", "updated")),- }),- // Notion — docs-verified: every page carries `last_edited_time` and- // `created_time`; query results live under `results` (Composio may- // re-wrap under `data` / `data.data`).- "NOTION_QUERY_DATABASE_WITH_FILTER" => Some(TaskWindowSpec {- items_paths: &[- &["results"],- &["data", "results"],- &["data", "data", "results"],- ],- ts_fields: &[- ("last_edited_time", TsFormat::Iso8601),- ("created_time", TsFormat::Iso8601),- ("data.last_edited_time", TsFormat::Iso8601),- ("data.created_time", TsFormat::Iso8601),- ],- order_arg: None,- }),- // Asana — docs-verified server-side `modified_since` (injected in- // apply_window_args). Items live under `data` (Composio may re-wrap as- // `data.data`); each row carries `modified_at` / `created_at`, possibly- // `data`-wrapped.- // CONFIRM-AT-RUNTIME: item timestamp field names via composio_list_tools.- "ASANA_GET_MULTIPLE_TASKS" => Some(TaskWindowSpec {- items_paths: &[&["data", "data"], &["data"]],- ts_fields: &[- ("modified_at", TsFormat::Iso8601),- ("created_at", TsFormat::Iso8601),- ("data.modified_at", TsFormat::Iso8601),- ("data.created_at", TsFormat::Iso8601),- ],- order_arg: None,- }),- // Todoist — `TODOIST_GET_ALL_TASKS` (returns incomplete tasks; the- // brief's catalog slug, fixed from the non-existent- // `TODOIST_GET_ACTIVE_TASKS`). No server-side narrowing: GET tasks does- // NOT accept a `filter` query (that lives on the separate- // `TODOIST_FILTER_TASKS` / `/tasks/filter` endpoint), so enforcement is- // pure post-filter. Todoist's v1 task object timestamps are `added_at`- // (creation) and `updated_at` (modification) — keying on both gives- // created-or-modified semantics. `created_at` is kept as a harmless- // defensive fallback (extra fields only ever keep, never drop).- // CONFIRM-AT-RUNTIME: response envelope via composio_list_tools (Todoist- // is not a native sync provider, so there's no repo extractor to mirror).- "TODOIST_GET_ALL_TASKS" => Some(TaskWindowSpec {- items_paths: &[- &["tasks"],- &["data", "tasks"],- &["results"],- &["data", "results"],- &["data"],- &[],- ],- ts_fields: &[- ("added_at", TsFormat::Iso8601),- ("updated_at", TsFormat::Iso8601),- ("created_at", TsFormat::Iso8601),- ("data.added_at", TsFormat::Iso8601),- ("data.updated_at", TsFormat::Iso8601),- ("data.created_at", TsFormat::Iso8601),- ],- order_arg: None,- }),- _ => None,- }-}--/// Inject best-effort server-side narrowing args for a task-fetch slug, when-/// the task-recency window is active. Caller-supplied keys are never-/// overwritten. Unknown slugs pass through untouched.-pub(crate) fn apply_window_args(- slug: &str,- arguments: Option<Value>,- since: DateTime<Utc>,-) -> Option<Value> {- let Some(spec) = spec_for(slug) else {- return arguments;- };-- let mut value = arguments.unwrap_or_else(|| Value::Object(Default::default()));- let Some(map) = value.as_object_mut() else {- // Non-object payload (unexpected) — leave it for the backend to reject.- return Some(value);- };-- if let Some((key, val)) = spec.order_arg {- map.entry(key.to_string())- .or_insert_with(|| Value::String(val.to_string()));- }-- // Asana takes a dynamic `modified_since` rather than a static order arg.- if slug == "ASANA_GET_MULTIPLE_TASKS" {- map.entry("modified_since".to_string())- .or_insert_with(|| Value::String(since.to_rfc3339()));- }-- // Todoist has no server-side narrowing here: `TODOIST_GET_ALL_TASKS`- // (GET /tasks) does not accept a `filter` query — that belongs to the- // separate `TODOIST_FILTER_TASKS` (`/tasks/filter`) endpoint. Recency is- // enforced entirely by the post-filter on `added_at`/`updated_at`.-- tracing::debug!(- target: "composio",- slug,- since = %since.to_rfc3339(),- "[composio][task-window] applied server-side narrowing args"- );- Some(value)-}--/// Drop task rows older than `since` from a successful response.-///-/// No-op when: the response failed, the slug isn't recognized, the items-/// array can't be located, or nothing was actually removed. When rows *are*-/// removed, `markdown_formatted` is cleared so the agent consumes the filtered-/// `data` rather than stale server-rendered markdown.-pub(crate) fn filter_response(- slug: &str,- mut resp: ComposioExecuteResponse,- since: DateTime<Utc>,-) -> ComposioExecuteResponse {- if !resp.successful {- return resp;- }- let Some(spec) = spec_for(slug) else {- return resp;- };-- let Some(path) = spec- .items_paths- .iter()- .find(|p| array_at(&resp.data, p).is_some())- .copied()- else {- tracing::debug!(- target: "composio",- slug,- "[composio][task-window] no items array located; pass-through"- );- return resp;- };-- // Safe: `find` above guaranteed this path resolves to an array.- let items = array_at(&resp.data, path).expect("path resolved above");- let total = items.len();- let kept: Vec<Value> = items- .iter()- .filter(|item| keep_item(item, spec.ts_fields, since))- .cloned()- .collect();- let removed = total - kept.len();-- if removed == 0 {- return resp;- }-- if let Some(slot) = array_at_mut(&mut resp.data, path) {- *slot = kept;- }- // Stale server-rendered markdown reflects the full backlog — force the- // tool surface to fall back to the filtered JSON envelope.- resp.markdown_formatted = None;-- tracing::debug!(- target: "composio",- slug,- kept = total - removed,- total,- since = %since.to_rfc3339(),- "[composio][task-window] post-filtered task results to recency window"- );- resp-}--/// Keep a row if any of its timestamp fields parses to `>= floor`. A row with-/// no parseable timestamp field is kept (never dropped on ambiguity).-///-/// Field names may be dotted (`data.updatedAt`) to reach Composio-wrapped rows-/// — mirrors `providers::pick_str`, which the native sync extractors use for-/// exactly these `data.`-nested envelopes.-fn keep_item(item: &Value, ts_fields: &[(&str, TsFormat)], floor: DateTime<Utc>) -> bool {- let mut saw_timestamp = false;- for (field, fmt) in ts_fields {- if let Some(raw) = field_at(item, field) {- if let Some(ts) = parse_ts(raw, *fmt) {- saw_timestamp = true;- if ts >= floor {- return true;- }- }- }- }- // No usable timestamp at all → conservatively keep.- !saw_timestamp-}--/// Resolve a possibly-dotted field path (`updatedAt`, `data.updatedAt`) within-/// a single item object. Each segment is an object key.-fn field_at<'a>(item: &'a Value, dotted: &str) -> Option<&'a Value> {- let mut cur = item;- for seg in dotted.split('.') {- cur = cur.get(seg)?;- }- Some(cur)-}--/// Parse a JSON timestamp value in the given format. Returns `None` on any-/// shape we don't recognize so the caller treats it as ambiguous (keep).-fn parse_ts(raw: &Value, fmt: TsFormat) -> Option<DateTime<Utc>> {- match fmt {- TsFormat::Iso8601 => raw- .as_str()- .and_then(|s| DateTime::parse_from_rfc3339(s.trim()).ok())- .map(|dt| dt.with_timezone(&Utc)),- TsFormat::EpochMillis => {- let ms = match raw {- Value::String(s) => s.trim().parse::<i64>().ok(),- Value::Number(n) => n.as_i64(),- _ => None,- }?;- DateTime::from_timestamp_millis(ms)- }- }-}--/// Resolve `path` (a slice of object keys) to an array within `root`.-/// An empty path means `root` itself must be the array.-fn array_at<'a>(root: &'a Value, path: &[&str]) -> Option<&'a Vec<Value>> {- let mut cur = root;- for key in path {- cur = cur.get(*key)?;- }- cur.as_array()-}--/// Mutable counterpart to [`array_at`].-fn array_at_mut<'a>(root: &'a mut Value, path: &[&str]) -> Option<&'a mut Vec<Value>> {- let mut cur = root;- for key in path {- cur = cur.get_mut(*key)?;- }- cur.as_array_mut()-}--#[cfg(test)]-#[path = "task_window_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/task_window_tests.rs b/crates/openhuman-core/src/integrations/composio/task_window_tests.rsdeleted file mode 100644index 96d14b7010..0000000000--- a/crates/openhuman-core/src/integrations/composio/task_window_tests.rs+++ /dev/null@@ -1,267 +0,0 @@-//! Tests for the task-recency window narrowing + post-filter.--use super::*;-use chrono::TimeZone;-use serde_json::json;--fn floor() -> DateTime<Utc> {- // Fixed "now - 24h" floor for deterministic comparisons.- Utc.with_ymd_and_hms(2026, 6, 20, 9, 0, 0).unwrap()-}--fn ok_resp(data: Value) -> ComposioExecuteResponse {- ComposioExecuteResponse {- data,- successful: true,- error: None,- cost_usd: 0.0,- markdown_formatted: None,- }-}--// ── post-filter: ClickUp (epoch-millis string) ──────────────────────--#[test]-fn clickup_drops_rows_older_than_floor() {- let old_ms = (floor().timestamp_millis() - 1).to_string();- let new_ms = (floor().timestamp_millis() + 60_000).to_string();- let resp = ok_resp(json!({- "data": { "tasks": [- { "id": "old", "date_updated": old_ms },- { "id": "new", "date_updated": new_ms },- ]}- }));- let out = filter_response("CLICKUP_GET_FILTERED_TEAM_TASKS", resp, floor());- let tasks = out.data["data"]["tasks"].as_array().unwrap();- assert_eq!(tasks.len(), 1);- assert_eq!(tasks[0]["id"], "new");-}--#[test]-fn clickup_keeps_row_exactly_on_floor() {- let on_ms = floor().timestamp_millis().to_string();- let resp = ok_resp(json!({ "tasks": [{ "id": "edge", "date_updated": on_ms }] }));- let out = filter_response("CLICKUP_GET_FILTERED_TEAM_TASKS", resp, floor());- assert_eq!(out.data["tasks"].as_array().unwrap().len(), 1);-}--// ── post-filter: Linear (ISO-8601, GraphQL `nodes` envelope) ─────────--#[test]-fn linear_filters_iso_timestamps_under_nodes() {- let resp = ok_resp(json!({- "nodes": [- { "id": "old", "updatedAt": "2026-06-19T09:00:00.000Z" },- { "id": "new", "updatedAt": "2026-06-20T12:00:00.000Z" },- ]- }));- let out = filter_response("LINEAR_LIST_LINEAR_ISSUES", resp, floor());- let nodes = out.data["nodes"].as_array().unwrap();- assert_eq!(nodes.len(), 1);- assert_eq!(nodes[0]["id"], "new");-}--#[test]-fn linear_filters_graphql_connection_under_data_issues_nodes() {- // Real Linear/Composio shape: { data: { issues: { nodes: [...] } } }.- // Regression for the no-array pass-through that left the backlog unfiltered.- let resp = ok_resp(json!({- "data": { "issues": { "nodes": [- { "id": "old", "updatedAt": "2026-06-19T09:00:00.000Z" },- { "id": "new", "updatedAt": "2026-06-20T12:00:00.000Z" },- ]}}- }));- let out = filter_response("LINEAR_LIST_LINEAR_ISSUES", resp, floor());- let nodes = out.data["data"]["issues"]["nodes"].as_array().unwrap();- assert_eq!(nodes.len(), 1);- assert_eq!(nodes[0]["id"], "new");-}--#[test]-fn filters_data_wrapped_row_timestamps() {- // Composio sometimes wraps each row under `data` — the timestamp must- // still be read (else stale rows survive as "no timestamp → keep").- let resp = ok_resp(json!({- "tasks": [- { "data": { "id": "old", "date_updated": "0" } },- { "data": { "id": "new",- "date_updated": (floor().timestamp_millis()+1).to_string() } },- ]- }));- let out = filter_response("CLICKUP_GET_FILTERED_TEAM_TASKS", resp, floor());- let tasks = out.data["tasks"].as_array().unwrap();- assert_eq!(tasks.len(), 1);- assert_eq!(tasks[0]["data"]["id"], "new");-}--// ── post-filter: Notion (keep if EITHER timestamp is fresh) ──────────--#[test]-fn notion_keeps_page_when_either_timestamp_fresh() {- let resp = ok_resp(json!({- "results": [- // created long ago but recently edited → keep- { "id": "edited", "created_time": "2026-01-01T00:00:00.000Z",- "last_edited_time": "2026-06-20T10:00:00.000Z" },- // both stale → drop- { "id": "stale", "created_time": "2026-01-01T00:00:00.000Z",- "last_edited_time": "2026-01-02T00:00:00.000Z" },- ]- }));- let out = filter_response("NOTION_QUERY_DATABASE_WITH_FILTER", resp, floor());- let results = out.data["results"].as_array().unwrap();- assert_eq!(results.len(), 1);- assert_eq!(results[0]["id"], "edited");-}--// ── post-filter: Todoist (added_at / updated_at) ────────────────────--#[test]-fn todoist_drops_tasks_added_before_floor() {- // Real Todoist v1 field is `added_at` (not created_at).- let resp = ok_resp(json!({- "tasks": [- { "id": "old", "added_at": "2026-06-19T09:00:00.000Z" },- { "id": "new", "added_at": "2026-06-20T12:00:00.000Z" },- ]- }));- let out = filter_response("TODOIST_GET_ALL_TASKS", resp, floor());- let tasks = out.data["tasks"].as_array().unwrap();- assert_eq!(tasks.len(), 1);- assert_eq!(tasks[0]["id"], "new");-}--#[test]-fn todoist_keeps_task_updated_in_window_even_if_added_earlier() {- // created-or-modified: added long ago but updated recently → keep.- let resp = ok_resp(json!({- "tasks": [- { "id": "touched", "added_at": "2026-01-01T00:00:00.000Z",- "updated_at": "2026-06-20T12:00:00.000Z" },- { "id": "stale", "added_at": "2026-01-01T00:00:00.000Z",- "updated_at": "2026-01-02T00:00:00.000Z" },- ]- }));- let out = filter_response("TODOIST_GET_ALL_TASKS", resp, floor());- let tasks = out.data["tasks"].as_array().unwrap();- assert_eq!(tasks.len(), 1);- assert_eq!(tasks[0]["id"], "touched");-}--#[test]-fn todoist_handles_bare_array_and_data_wrapped_rows() {- // Composio may return a bare array and/or wrap each row under `data`.- let resp = ok_resp(json!([- { "data": { "id": "old", "added_at": "2026-01-01T00:00:00.000Z" } },- { "data": { "id": "new", "added_at": "2026-06-20T12:00:00.000Z" } },- ]));- let out = filter_response("TODOIST_GET_ALL_TASKS", resp, floor());- let tasks = out.data.as_array().unwrap();- assert_eq!(tasks.len(), 1);- assert_eq!(tasks[0]["data"]["id"], "new");-}--// ── conservative behaviors ──────────────────────────────────────────--#[test]-fn rows_without_timestamp_are_kept() {- let resp = ok_resp(json!({ "tasks": [{ "id": "no_ts" }] }));- let out = filter_response("CLICKUP_GET_FILTERED_TEAM_TASKS", resp, floor());- assert_eq!(out.data["tasks"].as_array().unwrap().len(), 1);-}--#[test]-fn unparseable_timestamp_is_kept() {- let resp = ok_resp(json!({ "tasks": [{ "id": "junk", "date_updated": "not-a-number" }] }));- let out = filter_response("CLICKUP_GET_FILTERED_TEAM_TASKS", resp, floor());- assert_eq!(out.data["tasks"].as_array().unwrap().len(), 1);-}--#[test]-fn unknown_slug_is_untouched() {- let resp = ok_resp(json!({ "tasks": [{ "id": "x", "date_updated": "0" }] }));- let out = filter_response("GMAIL_FETCH_EMAILS", resp, floor());- assert_eq!(out.data["tasks"].as_array().unwrap().len(), 1);-}--#[test]-fn failed_response_is_untouched() {- let old_ms = "0".to_string();- let mut resp = ok_resp(json!({ "tasks": [{ "id": "old", "date_updated": old_ms }] }));- resp.successful = false;- let out = filter_response("CLICKUP_GET_FILTERED_TEAM_TASKS", resp, floor());- assert_eq!(out.data["tasks"].as_array().unwrap().len(), 1);-}--#[test]-fn missing_items_array_is_pass_through() {- let resp = ok_resp(json!({ "unexpected": "shape" }));- let out = filter_response("CLICKUP_GET_FILTERED_TEAM_TASKS", resp, floor());- assert_eq!(out.data["unexpected"], "shape");-}--// ── markdown_formatted invalidation ─────────────────────────────────--#[test]-fn markdown_cleared_only_when_rows_removed() {- // Rows removed → markdown dropped so agent reads filtered JSON.- let mut resp = ok_resp(json!({ "tasks": [- { "id": "old", "date_updated": "0" },- { "id": "new", "date_updated": (floor().timestamp_millis()+1).to_string() },- ]}));- resp.markdown_formatted = Some("| old | new | full backlog |".into());- let out = filter_response("CLICKUP_GET_FILTERED_TEAM_TASKS", resp, floor());- assert!(out.markdown_formatted.is_none());-- // Nothing removed → markdown preserved.- let mut resp2 = ok_resp(json!({ "tasks": [- { "id": "new", "date_updated": (floor().timestamp_millis()+1).to_string() },- ]}));- resp2.markdown_formatted = Some("kept".into());- let out2 = filter_response("CLICKUP_GET_FILTERED_TEAM_TASKS", resp2, floor());- assert_eq!(out2.markdown_formatted.as_deref(), Some("kept"));-}--// ── apply_window_args ───────────────────────────────────────────────--#[test]-fn injects_order_arg_when_absent() {- let out = apply_window_args("LINEAR_LIST_LINEAR_ISSUES", None, floor()).unwrap();- assert_eq!(out["orderBy"], "updatedAt");-}--#[test]-fn caller_supplied_order_arg_wins() {- let args = json!({ "order_by": "created" });- let out = apply_window_args("CLICKUP_GET_FILTERED_TEAM_TASKS", Some(args), floor()).unwrap();- assert_eq!(out["order_by"], "created");-}--#[test]-fn asana_gets_modified_since_injected() {- let out = apply_window_args("ASANA_GET_MULTIPLE_TASKS", Some(json!({})), floor()).unwrap();- assert_eq!(out["modified_since"], floor().to_rfc3339());-}--#[test]-fn apply_window_args_noop_for_unknown_slug() {- let out = apply_window_args("GMAIL_FETCH_EMAILS", Some(json!({ "a": 1 })), floor());- assert_eq!(out.unwrap(), json!({ "a": 1 }));-}--#[test]-fn todoist_gets_no_server_side_narrowing() {- // GET /tasks has no `filter` param (that's the /tasks/filter endpoint),- // so we must NOT inject one — enforcement is pure post-filter.- let out = apply_window_args(- "TODOIST_GET_ALL_TASKS",- Some(json!({ "limit": 50 })),- floor(),- )- .unwrap();- assert!(- out.get("filter").is_none(),- "must not inject a filter param"- );- assert_eq!(out["limit"], 50, "caller args preserved");-}diff --git a/crates/openhuman-core/src/integrations/composio/trigger_history.rs b/crates/openhuman-core/src/integrations/composio/trigger_history.rsindex 48b05ebb51..197192d2dd 100644--- a/crates/openhuman-core/src/integrations/composio/trigger_history.rs+++ b/crates/openhuman-core/src/integrations/composio/trigger_history.rs@@ -1,272 +1,43 @@-//! Persistent ComposeIO trigger history.+//! Process-global handle to the persistent Composio trigger archive.//!-//! Stores every incoming ComposeIO trigger as a JSONL record partitioned by-//! UTC day under `<workspace>/state/triggers/YYYY-MM-DD.jsonl`.+//! The archive itself (daily JSONL under `<workspace>/state/triggers/`, exclusive+//! file locking on append, newest-first reads that skip corrupt lines) is+//! `tinyconnectors::triggers::TriggerArchive`. What stays here is the+//! host lifecycle: one archive per process, opened once at startup and read by+//! the trigger subscriber.-use std::fs::{self, OpenOptions};-use std::io::{BufRead, BufReader, Write};-use std::path::{Path, PathBuf};-#[cfg(windows)]-use std::sync::Mutex;+use std::path::PathBuf;use std::sync::{Arc, OnceLock};-use chrono::Utc;-#[cfg(not(windows))]-use fs2::FileExt;+use tinyconnectors::triggers::TriggerArchive;-use super::types::{ComposioTriggerHistoryEntry, ComposioTriggerHistoryResult};--static GLOBAL_TRIGGER_HISTORY: OnceLock<Arc<ComposioTriggerHistoryStore>> = OnceLock::new();--/// Process-local write serializer for Windows, where `fs2::FileExt::lock_exclusive`-/// is unavailable. This ensures concurrent `record_trigger` calls do not race and-/// produce malformed JSONL lines.-#[cfg(windows)]-static WINDOWS_TRIGGER_WRITE_LOCK: OnceLock<Mutex<()>> = OnceLock::new();--const TRIGGER_ARCHIVE_DIR: &str = "triggers";+static GLOBAL_TRIGGER_HISTORY: OnceLock<Arc<TriggerArchive>> = OnceLock::new();+/// Open the archive under `<workspace_dir>/state/triggers` and install it as the+/// process-global store. Idempotent for the same workspace; a different+/// workspace after initialization is an error.pub fn init_global(workspace_dir: PathBuf) -> Result<(), String> {- let expected_archive_dir = workspace_dir.join("state").join(TRIGGER_ARCHIVE_DIR);- if let Some(existing) = GLOBAL_TRIGGER_HISTORY.get() {- if existing.archive_dir == expected_archive_dir {- return Ok(());- }-- return Err(format!(- "[composio][history] global store already initialized for {} while attempting {}",- existing.archive_dir.display(),- expected_archive_dir.display()- ));- }-- let store = Arc::new(ComposioTriggerHistoryStore::new(&workspace_dir)?);- match GLOBAL_TRIGGER_HISTORY.set(store.clone()) {- Ok(()) => Ok(()),- Err(_) => {- if let Some(existing) = GLOBAL_TRIGGER_HISTORY.get() {- if existing.archive_dir == store.archive_dir {- return Ok(());- }-- return Err(format!(- "[composio][history] global store already initialized for {} while attempting {}",- existing.archive_dir.display(),- store.archive_dir.display()- ));- }-- Err(format!(- "[composio][history] failed to initialize global store for {}",- store.archive_dir.display()- ))- }- }-}--pub fn global() -> Option<Arc<ComposioTriggerHistoryStore>> {- GLOBAL_TRIGGER_HISTORY.get().cloned()-}--pub struct ComposioTriggerHistoryStore {- archive_dir: PathBuf,-}--impl ComposioTriggerHistoryStore {- pub fn new(workspace_dir: &Path) -> Result<Self, String> {- let archive_dir = workspace_dir.join("state").join(TRIGGER_ARCHIVE_DIR);- fs::create_dir_all(&archive_dir).map_err(|error| {- format!(- "[composio][history] failed to create archive directory {}: {error}",- archive_dir.display()- )- })?;-+ let state_dir = workspace_dir.join("state");+ let archive = Arc::new(+ TriggerArchive::open(&state_dir)+ .map_err(|error| format!("[composio][history] {error}"))?,+ );+ let installed = GLOBAL_TRIGGER_HISTORY.get_or_init(|| archive.clone());+ if installed.archive_dir() == archive.archive_dir() {tracing::debug!(- archive_dir = %archive_dir.display(),+ archive_dir = %archive.archive_dir().display(),"[composio][history] archive initialized");-- Ok(Self { archive_dir })- }-- pub fn record_trigger(- &self,- toolkit: &str,- trigger: &str,- metadata_id: &str,- metadata_uuid: &str,- payload: &serde_json::Value,- ) -> Result<ComposioTriggerHistoryEntry, String> {- let entry = ComposioTriggerHistoryEntry {- received_at_ms: now_ms(),- toolkit: toolkit.to_string(),- trigger: trigger.to_string(),- metadata_id: metadata_id.to_string(),- metadata_uuid: metadata_uuid.to_string(),- payload: payload.clone(),- };-- let path = self.current_day_file_path();- let line = serde_json::to_string(&entry)- .map_err(|error| format!("[composio][history] failed to serialize trigger: {error}"))?;-- let mut file = OpenOptions::new()- .create(true)- .append(true)- .open(&path)- .map_err(|error| {- format!(- "[composio][history] failed to open archive file {}: {error}",- path.display()- )- })?;-- #[cfg(windows)]- let _windows_guard = WINDOWS_TRIGGER_WRITE_LOCK- .get_or_init(|| Mutex::new(()))- .lock()- .map_err(|_| {- format!(- "[composio][history] windows write mutex poisoned for archive file {}",- path.display()- )- })?;-- #[cfg(not(windows))]- file.lock_exclusive().map_err(|error| {- format!(- "[composio][history] failed to lock archive file {}: {error}",- path.display()- )- })?;-- let write_result = writeln!(file, "{line}")- .and_then(|_| file.flush())- .map_err(|error| {- format!(- "[composio][history] failed to append archive file {}: {error}",- path.display()- )- });-- #[cfg(not(windows))]- let unlock_result = file.unlock().map_err(|error| {- format!(- "[composio][history] failed to unlock archive file {}: {error}",- path.display()- )- });-- write_result?;- #[cfg(not(windows))]- unlock_result?;-- tracing::debug!(- toolkit = %entry.toolkit,- trigger = %entry.trigger,- metadata_id = %entry.metadata_id,- archive_file = %path.display(),- "[composio][history] trigger archived"- );-- Ok(entry)- }-- pub fn list_recent(&self, limit: usize) -> Result<ComposioTriggerHistoryResult, String> {- let limit = limit.max(1);- let mut day_files = self.list_day_files()?;- day_files.sort_by(|left, right| right.cmp(left));-- let mut entries = Vec::new();- for file in day_files {- let mut file_entries = self.read_day_file(&file)?;- file_entries.reverse();- for entry in file_entries {- entries.push(entry);- if entries.len() >= limit {- break;- }- }- if entries.len() >= limit {- break;- }- }-- Ok(ComposioTriggerHistoryResult {- archive_dir: self.archive_dir.display().to_string(),- current_day_file: self.current_day_file_path().display().to_string(),- entries,- })- }-- fn list_day_files(&self) -> Result<Vec<PathBuf>, String> {- let dir = fs::read_dir(&self.archive_dir).map_err(|error| {- format!(- "[composio][history] failed to read archive directory {}: {error}",- self.archive_dir.display()- )- })?;-- Ok(dir- .filter_map(|entry| entry.ok().map(|value| value.path()))- .filter(|path| path.extension().is_some_and(|ext| ext == "jsonl"))- .collect())- }-- fn read_day_file(&self, path: &Path) -> Result<Vec<ComposioTriggerHistoryEntry>, String> {- let file = OpenOptions::new().read(true).open(path).map_err(|error| {- format!(- "[composio][history] failed to open archive file {}: {error}",- path.display()- )- })?;-- let reader = BufReader::new(file);- let mut entries = Vec::new();-- for line in reader.lines() {- let line = match line {- Ok(line) if !line.trim().is_empty() => line,- Ok(_) => continue,- Err(error) => {- tracing::warn!(- archive_file = %path.display(),- error = %error,- "[composio][history] failed to read line"- );- continue;- }- };-- match serde_json::from_str::<ComposioTriggerHistoryEntry>(&line) {- Ok(entry) => entries.push(entry),- Err(error) => {- tracing::warn!(- archive_file = %path.display(),- error = %error,- "[composio][history] failed to parse archived trigger line"- );- }- }- }-- Ok(entries)- }-- fn current_day_file_path(&self) -> PathBuf {- self.archive_dir- .join(format!("{}.jsonl", Utc::now().format("%Y-%m-%d")))+ return Ok(());}+ Err(format!(+ "[composio][history] global store already initialized for {} while attempting {}",+ installed.archive_dir().display(),+ archive.archive_dir().display()+ ))}-fn now_ms() -> u64 {- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|duration| duration.as_millis() as u64)- .unwrap_or(0)+/// The process-global archive, if [`init_global`] has run.+pub fn global() -> Option<Arc<TriggerArchive>> {+ GLOBAL_TRIGGER_HISTORY.get().cloned()}--#[cfg(test)]-#[path = "trigger_history_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/trigger_history_tests.rs b/crates/openhuman-core/src/integrations/composio/trigger_history_tests.rsdeleted file mode 100644index aaa1d9a716..0000000000--- a/crates/openhuman-core/src/integrations/composio/trigger_history_tests.rs+++ /dev/null@@ -1,88 +0,0 @@-use super::*;--#[test]-fn archives_triggers_in_daily_jsonl_and_lists_latest_first() {- let temp = tempfile::tempdir().expect("tempdir");- let workspace = temp.path().join("workspace");- fs::create_dir_all(&workspace).expect("workspace dir");-- let store = ComposioTriggerHistoryStore::new(&workspace).expect("store");- store- .record_trigger(- "gmail",- "GMAIL_NEW_GMAIL_MESSAGE",- "id-1",- "uuid-1",- &serde_json::json!({ "subject": "hello" }),- )- .expect("record first");- store- .record_trigger(- "notion",- "NOTION_NEW_PAGE",- "id-2",- "uuid-2",- &serde_json::json!({ "title": "roadmap" }),- )- .expect("record second");-- let history = store.list_recent(10).expect("list");- assert_eq!(history.entries.len(), 2);- assert_eq!(history.entries[0].metadata_id, "id-2");- assert_eq!(history.entries[1].metadata_id, "id-1");- assert!(PathBuf::from(&history.current_day_file).exists());-}--#[test]-fn list_recent_with_limit_one() {- let temp = tempfile::tempdir().expect("tempdir");- let workspace = temp.path().join("workspace");- fs::create_dir_all(&workspace).expect("workspace dir");-- let store = ComposioTriggerHistoryStore::new(&workspace).expect("store");- store- .record_trigger("gmail", "NEW_MSG", "id-1", "uuid-1", &serde_json::json!({}))- .expect("record");- store- .record_trigger("slack", "NEW_MSG", "id-2", "uuid-2", &serde_json::json!({}))- .expect("record");-- let history = store.list_recent(1).expect("list");- assert_eq!(history.entries.len(), 1);- assert_eq!(history.entries[0].metadata_id, "id-2");-}--#[test]-fn list_recent_empty_store() {- let temp = tempfile::tempdir().expect("tempdir");- let workspace = temp.path().join("workspace");- fs::create_dir_all(&workspace).expect("workspace dir");-- let store = ComposioTriggerHistoryStore::new(&workspace).expect("store");- let history = store.list_recent(10).expect("list");- assert!(history.entries.is_empty());-}--#[test]-fn record_trigger_returns_entry_with_correct_fields() {- let temp = tempfile::tempdir().expect("tempdir");- let workspace = temp.path().join("workspace");- fs::create_dir_all(&workspace).expect("workspace dir");-- let store = ComposioTriggerHistoryStore::new(&workspace).expect("store");- let entry = store- .record_trigger(- "github",- "PR_OPENED",- "pr-42",- "uuid-42",- &serde_json::json!({"pr": 42}),- )- .expect("record");-- assert_eq!(entry.toolkit, "github");- assert_eq!(entry.trigger, "PR_OPENED");- assert_eq!(entry.metadata_id, "pr-42");- assert_eq!(entry.metadata_uuid, "uuid-42");- assert!(entry.received_at_ms > 0);-}