Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(memory): correct schema definitions for vault and pipeline operations

Steven Enamakel18f385f4f4b8
diff --git a/crates/openhuman-core/src/bin/fleet.rs b/crates/openhuman-core/src/bin/fleet.rs
index d36881fe46..8067805350 100644
--- a/crates/openhuman-core/src/bin/fleet.rs
+++ b/crates/openhuman-core/src/bin/fleet.rs
@@ -749,239 +749,6 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}
-// ---------------------------------------------------------------------------
-// Tests — pure logic (no child processes / network).
-// ---------------------------------------------------------------------------
-
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn port_assignment_is_sequential_from_base() {
- assert_eq!(port_for_index(7900, 0), Some(7900));
- assert_eq!(port_for_index(7900, 5), Some(7905));
- }
-
- #[test]
- fn port_assignment_detects_overflow() {
- assert_eq!(port_for_index(u16::MAX, 1), None);
- }
-
- #[test]
- fn workspace_is_user_scoped_under_root() {
- let ws = workspace_for(Path::new("/srv/fleet"), "alice");
- assert_eq!(ws, PathBuf::from("/srv/fleet/alice"));
- }
-
- #[test]
- fn action_dir_is_user_scoped_outside_workspace_tree() {
- let root = Path::new("/srv/fleet");
- let workspace = workspace_for(root, "alice");
- let action_dir = action_dir_for(root, "alice");
-
- assert_eq!(
- action_dir,
- PathBuf::from("/srv/fleet/.tenant-action-dirs/alice")
- );
- assert!(!action_dir.starts_with(&workspace));
- }
-
- #[test]
- fn user_id_validation_rejects_path_escapes() {
- assert!(is_valid_user_id("alice"));
- assert!(is_valid_user_id("user_42-x"));
- assert!(!is_valid_user_id(""));
- assert!(!is_valid_user_id("../etc"));
- assert!(!is_valid_user_id("a/b"));
- assert!(!is_valid_user_id("a.b"));
- }
-
- #[test]
- fn provision_assigns_distinct_ports_and_edge_tokens() {
- let root = PathBuf::from("/tmp/ws");
- let users = vec!["alice".to_string(), "bob".to_string()];
- let (instances, edge_auth, minted) = provision(&users, &root, 7900).unwrap();
-
- assert_eq!(instances.len(), 2);
- assert_eq!(instances["alice"].port, 7900);
- assert_eq!(instances["bob"].port, 7901);
- assert_eq!(instances["alice"].workspace_dir, root.join("alice"));
- assert_eq!(
- instances["alice"].action_dir,
- root.join(".tenant-action-dirs").join("alice")
- );
- assert_ne!(instances["alice"].action_dir, instances["bob"].action_dir);
- assert_ne!(instances["alice"].core_bearer, instances["bob"].core_bearer);
- assert_eq!(instances["alice"].rpc_url(), "http://127.0.0.1:7900/rpc");
-
- // Every minted edge token resolves back to exactly its user.
- assert_eq!(edge_auth.len(), 2);
- for (user_id, token) in &minted {
- assert_eq!(edge_auth.user_for(token), Some(user_id.as_str()));
- }
- }
-
- #[test]
- fn provision_rejects_duplicate_and_invalid_users() {
- let root = PathBuf::from("/tmp/ws");
- assert!(provision(&["a".into(), "a".into()], &root, 7900).is_err());
- assert!(provision(&["../x".into()], &root, 7900).is_err());
- }
-
- #[test]
- fn bearer_parsing_requires_bearer_prefix() {
- let mut h = HeaderMap::new();
- h.insert(
- axum::http::header::AUTHORIZATION,
- "Bearer edge-123".parse().unwrap(),
- );
- assert_eq!(bearer_from_headers(&h), Some(EdgeToken::new("edge-123")));
-
- let mut lower = HeaderMap::new();
- lower.insert(
- axum::http::header::AUTHORIZATION,
- "bearer edge-456".parse().unwrap(),
- );
- assert_eq!(
- bearer_from_headers(&lower),
- Some(EdgeToken::new("edge-456"))
- );
-
- let mut h2 = HeaderMap::new();
- h2.insert(
- axum::http::header::AUTHORIZATION,
- "edge-123".parse().unwrap(),
- );
- assert_eq!(bearer_from_headers(&h2), None);
- }
-
- #[test]
- fn readiness_body_requires_jsonrpc_result() {
- assert!(readiness_body_succeeded(&serde_json::json!({
- "jsonrpc": "2.0",
- "id": "fleet-ready",
- "result": {"tier": "supervised"}
- })));
-
- assert!(!readiness_body_succeeded(&serde_json::json!({
- "jsonrpc": "2.0",
- "id": "fleet-ready",
- "error": {"code": -32000, "message": "config unavailable"}
- })));
-
- assert!(!readiness_body_succeeded(&serde_json::json!({
- "jsonrpc": "2.0",
- "id": "fleet-ready"
- })));
- }
-
- #[cfg(unix)]
- #[test]
- fn edge_token_output_is_written_0600() {
- use std::os::unix::fs::PermissionsExt as _;
-
- let dir = tempfile::tempdir().unwrap();
- let path = dir.path().join("edge-tokens.txt");
- write_edge_tokens(
- &path,
- &[("alice".to_string(), EdgeToken::new("edge-secret"))],
- )
- .unwrap();
-
- let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
- assert_eq!(mode, 0o600);
- assert_eq!(
- std::fs::read_to_string(path).unwrap(),
- "alice edge-secret\n"
- );
- }
-
- #[cfg(unix)]
- #[test]
- fn edge_token_output_rejects_symlinks() {
- use std::os::unix::fs::symlink;
-
- let dir = tempfile::tempdir().unwrap();
- let target = dir.path().join("attacker-readable.txt");
- std::fs::write(&target, "unchanged").unwrap();
- let output = dir.path().join("edge-tokens.txt");
- symlink(&target, &output).unwrap();
-
- assert!(write_edge_tokens(
- &output,
- &[("alice".to_string(), EdgeToken::new("edge-secret"))],
- )
- .is_err());
- assert_eq!(std::fs::read_to_string(target).unwrap(), "unchanged");
- }
-
- #[cfg(unix)]
- #[test]
- fn edge_token_output_rejects_preowned_files() {
- let dir = tempfile::tempdir().unwrap();
- let output = dir.path().join("edge-tokens.txt");
- std::fs::write(&output, "attacker keeps this inode").unwrap();
-
- assert!(write_edge_tokens(
- &output,
- &[("alice".to_string(), EdgeToken::new("edge-secret"))],
- )
- .is_err());
- assert_eq!(
- std::fs::read_to_string(output).unwrap(),
- "attacker keeps this inode"
- );
- }
-
- #[test]
- fn fleet_cors_allows_tauri_loopback_and_extra_origins() {
- assert!(is_fleet_origin_allowed_with_extra(
- "tauri://localhost",
- None
- ));
- assert!(is_fleet_origin_allowed_with_extra(
- "http://127.0.0.1:1420",
- None
- ));
- assert!(is_fleet_origin_allowed_with_extra(
- "https://fleet.example",
- Some("https://fleet.example")
- ));
- assert!(!is_fleet_origin_allowed_with_extra(
- "https://evil.example",
- Some("https://fleet.example")
- ));
- }
-
- #[test]
- fn fleet_cors_headers_echo_allowed_origin_only() {
- let allowed = with_fleet_cors_headers(
- StatusCode::NO_CONTENT.into_response(),
- Some("tauri://localhost"),
- );
- assert_eq!(
- allowed
- .headers()
- .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
- .and_then(|value| value.to_str().ok()),
- Some("tauri://localhost")
- );
- assert_eq!(
- allowed
- .headers()
- .get(header::ACCESS_CONTROL_ALLOW_HEADERS)
- .and_then(|value| value.to_str().ok()),
- Some("Content-Type, Authorization")
- );
-
- let rejected = with_fleet_cors_headers(
- StatusCode::NO_CONTENT.into_response(),
- Some("https://evil.example"),
- );
- assert!(rejected
- .headers()
- .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
- .is_none());
- }
-}
+#[path = "fleet_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/bin/fleet_tests.rs b/crates/openhuman-core/src/bin/fleet_tests.rs
new file mode 100644
index 0000000000..07389d2b88
--- /dev/null
+++ b/crates/openhuman-core/src/bin/fleet_tests.rs
@@ -0,0 +1,230 @@
+use super::*;
+
+#[test]
+fn port_assignment_is_sequential_from_base() {
+ assert_eq!(port_for_index(7900, 0), Some(7900));
+ assert_eq!(port_for_index(7900, 5), Some(7905));
+}
+
+#[test]
+fn port_assignment_detects_overflow() {
+ assert_eq!(port_for_index(u16::MAX, 1), None);
+}
+
+#[test]
+fn workspace_is_user_scoped_under_root() {
+ let ws = workspace_for(Path::new("/srv/fleet"), "alice");
+ assert_eq!(ws, PathBuf::from("/srv/fleet/alice"));
+}
+
+#[test]
+fn action_dir_is_user_scoped_outside_workspace_tree() {
+ let root = Path::new("/srv/fleet");
+ let workspace = workspace_for(root, "alice");
+ let action_dir = action_dir_for(root, "alice");
+
+ assert_eq!(
+ action_dir,
+ PathBuf::from("/srv/fleet/.tenant-action-dirs/alice")
+ );
+ assert!(!action_dir.starts_with(&workspace));
+}
+
+#[test]
+fn user_id_validation_rejects_path_escapes() {
+ assert!(is_valid_user_id("alice"));
+ assert!(is_valid_user_id("user_42-x"));
+ assert!(!is_valid_user_id(""));
+ assert!(!is_valid_user_id("../etc"));
+ assert!(!is_valid_user_id("a/b"));
+ assert!(!is_valid_user_id("a.b"));
+}
+
+#[test]
+fn provision_assigns_distinct_ports_and_edge_tokens() {
+ let root = PathBuf::from("/tmp/ws");
+ let users = vec!["alice".to_string(), "bob".to_string()];
+ let (instances, edge_auth, minted) = provision(&users, &root, 7900).unwrap();
+
+ assert_eq!(instances.len(), 2);
+ assert_eq!(instances["alice"].port, 7900);
+ assert_eq!(instances["bob"].port, 7901);
+ assert_eq!(instances["alice"].workspace_dir, root.join("alice"));
+ assert_eq!(
+ instances["alice"].action_dir,
+ root.join(".tenant-action-dirs").join("alice")
+ );
+ assert_ne!(instances["alice"].action_dir, instances["bob"].action_dir);
+ assert_ne!(instances["alice"].core_bearer, instances["bob"].core_bearer);
+ assert_eq!(instances["alice"].rpc_url(), "http://127.0.0.1:7900/rpc");
+
+ // Every minted edge token resolves back to exactly its user.
+ assert_eq!(edge_auth.len(), 2);
+ for (user_id, token) in &minted {
+ assert_eq!(edge_auth.user_for(token), Some(user_id.as_str()));
+ }
+}
+
+#[test]
+fn provision_rejects_duplicate_and_invalid_users() {
+ let root = PathBuf::from("/tmp/ws");
+ assert!(provision(&["a".into(), "a".into()], &root, 7900).is_err());
+ assert!(provision(&["../x".into()], &root, 7900).is_err());
+}
+
+#[test]
+fn bearer_parsing_requires_bearer_prefix() {
+ let mut h = HeaderMap::new();
+ h.insert(
+ axum::http::header::AUTHORIZATION,
+ "Bearer edge-123".parse().unwrap(),
+ );
+ assert_eq!(bearer_from_headers(&h), Some(EdgeToken::new("edge-123")));
+
+ let mut lower = HeaderMap::new();
+ lower.insert(
+ axum::http::header::AUTHORIZATION,
+ "bearer edge-456".parse().unwrap(),
+ );
+ assert_eq!(
+ bearer_from_headers(&lower),
+ Some(EdgeToken::new("edge-456"))
+ );
+
+ let mut h2 = HeaderMap::new();
+ h2.insert(
+ axum::http::header::AUTHORIZATION,
+ "edge-123".parse().unwrap(),
+ );
+ assert_eq!(bearer_from_headers(&h2), None);
+}
+
+#[test]
+fn readiness_body_requires_jsonrpc_result() {
+ assert!(readiness_body_succeeded(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": "fleet-ready",
+ "result": {"tier": "supervised"}
+ })));
+
+ assert!(!readiness_body_succeeded(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": "fleet-ready",
+ "error": {"code": -32000, "message": "config unavailable"}
+ })));
+
+ assert!(!readiness_body_succeeded(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": "fleet-ready"
+ })));
+}
+
+#[cfg(unix)]
+#[test]
+fn edge_token_output_is_written_0600() {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("edge-tokens.txt");
+ write_edge_tokens(
+ &path,
+ &[("alice".to_string(), EdgeToken::new("edge-secret"))],
+ )
+ .unwrap();
+
+ let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600);
+ assert_eq!(
+ std::fs::read_to_string(path).unwrap(),
+ "alice edge-secret\n"
+ );
+}
+
+#[cfg(unix)]
+#[test]
+fn edge_token_output_rejects_symlinks() {
+ use std::os::unix::fs::symlink;
+
+ let dir = tempfile::tempdir().unwrap();
+ let target = dir.path().join("attacker-readable.txt");
+ std::fs::write(&target, "unchanged").unwrap();
+ let output = dir.path().join("edge-tokens.txt");
+ symlink(&target, &output).unwrap();
+
+ assert!(write_edge_tokens(
+ &output,
+ &[("alice".to_string(), EdgeToken::new("edge-secret"))],
+ )
+ .is_err());
+ assert_eq!(std::fs::read_to_string(target).unwrap(), "unchanged");
+}
+
+#[cfg(unix)]
+#[test]
+fn edge_token_output_rejects_preowned_files() {
+ let dir = tempfile::tempdir().unwrap();
+ let output = dir.path().join("edge-tokens.txt");
+ std::fs::write(&output, "attacker keeps this inode").unwrap();
+
+ assert!(write_edge_tokens(
+ &output,
+ &[("alice".to_string(), EdgeToken::new("edge-secret"))],
+ )
+ .is_err());
+ assert_eq!(
+ std::fs::read_to_string(output).unwrap(),
+ "attacker keeps this inode"
+ );
+}
+
+#[test]
+fn fleet_cors_allows_tauri_loopback_and_extra_origins() {
+ assert!(is_fleet_origin_allowed_with_extra(
+ "tauri://localhost",
+ None
+ ));
+ assert!(is_fleet_origin_allowed_with_extra(
+ "http://127.0.0.1:1420",
+ None
+ ));
+ assert!(is_fleet_origin_allowed_with_extra(
+ "https://fleet.example",
+ Some("https://fleet.example")
+ ));
+ assert!(!is_fleet_origin_allowed_with_extra(
+ "https://evil.example",
+ Some("https://fleet.example")
+ ));
+}
+
+#[test]
+fn fleet_cors_headers_echo_allowed_origin_only() {
+ let allowed = with_fleet_cors_headers(
+ StatusCode::NO_CONTENT.into_response(),
+ Some("tauri://localhost"),
+ );
+ assert_eq!(
+ allowed
+ .headers()
+ .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
+ .and_then(|value| value.to_str().ok()),
+ Some("tauri://localhost")
+ );
+ assert_eq!(
+ allowed
+ .headers()
+ .get(header::ACCESS_CONTROL_ALLOW_HEADERS)
+ .and_then(|value| value.to_str().ok()),
+ Some("Content-Type, Authorization")
+ );
+
+ let rejected = with_fleet_cors_headers(
+ StatusCode::NO_CONTENT.into_response(),
+ Some("https://evil.example"),
+ );
+ assert!(rejected
+ .headers()
+ .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
+ .is_none());
+}
+}
diff --git a/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs b/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs
index 2bd0d463a8..395027f2e7 100644
--- a/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs
+++ b/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs
@@ -17,7 +17,7 @@ use super::state_file::{
load_stored_app_state, load_stored_app_state_unlocked, save_stored_app_state_unlocked,
APP_STATE_FILE_LOCK,
};
-use super::types::{AppStateSnapshot, RuntimeSnapshot, StoredAppState, StoredAppStatePatch};
+use super::types::{AppStateSnapshot, StoredAppState, StoredAppStatePatch};
use super::LOG_PREFIX;
use crate::api::rest::user_id_from_profile_payload;
use crate::config::rpc as config_rpc;
diff --git a/crates/openhuman-core/src/integrations/composio/schemas/definitions.rs b/crates/openhuman-core/src/integrations/composio/schemas/definitions.rs
new file mode 100644
index 0000000000..6f25cd1017
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/composio/schemas/definitions.rs
@@ -0,0 +1,568 @@
+//! [`schemas`]: the `ControllerSchema` definition for every `composio.*`
+//! RPC method. Purely declarative — one big `match` from method name to its
+//! namespace/description/inputs/outputs.
+
+use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
+
+
+pub fn schemas(function: &str) -> ControllerSchema {
+ match function {
+ "list_toolkits" => ControllerSchema {
+ namespace: "composio",
+ function: "list_toolkits",
+ description: "List the Composio toolkits currently enabled on the backend allowlist.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "toolkits",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Toolkit slugs enabled by the backend (e.g. gmail, notion).",
+ required: true,
+ }],
+ },
+ "list_capabilities" => ControllerSchema {
+ namespace: "composio",
+ function: "list_capabilities",
+ description: "List OpenHuman's built-in Composio capability matrix without requiring a signed-in Composio session.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "capabilities",
+ ty: TypeSchema::Json,
+ comment: "Array of capability rows describing native providers, curated catalogs, sync, trigger, and memory-ingest support.",
+ required: true,
+ }],
+ },
+ "list_agent_ready_toolkits" => ControllerSchema {
+ namespace: "composio",
+ function: "list_agent_ready_toolkits",
+ description:
+ "List every toolkit slug that ships an agent-ready curated catalog. Connected \
+ toolkits not in this list should be surfaced in the UI as preview / agent \
+ integration coming soon. See issue #2283.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "toolkits",
+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),
+ comment: "Sorted toolkit slugs with curated catalogs (e.g. gmail, notion, one_drive, excel, todoist).",
+ required: true,
+ }],
+ },
+ "list_connections" => ControllerSchema {
+ namespace: "composio",
+ function: "list_connections",
+ description:
+ "List the caller's active Composio OAuth connections filtered to the allowlist.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "connections",
+ ty: TypeSchema::Json,
+ comment: "Array of {id, toolkit, status, createdAt} objects.",
+ required: true,
+ }],
+ },
+ "authorize" => ControllerSchema {
+ namespace: "composio",
+ function: "authorize",
+ description: "Begin an OAuth handoff for a toolkit and return the hosted connect URL.",
+ inputs: vec![
+ FieldSchema {
+ name: "toolkit",
+ ty: TypeSchema::String,
+ comment: "Toolkit slug to authorize (must be in the backend allowlist).",
+ required: true,
+ },
+ FieldSchema {
+ name: "extra_params",
+ ty: TypeSchema::Json,
+ comment: "Optional JSON object of additional auth fields forwarded to Composio \
+ (e.g. {\"waba_id\": \"...\") for toolkits that require them). \
+ The core may also add toolkit-specific OAuth scope hints such as \
+ Gmail's oauth_scopes value. Reserved keys (toolkit, toolkit_version, \
+ auth, client_id) are rejected.",
+ required: false,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "connectUrl",
+ ty: TypeSchema::String,
+ comment: "Composio-hosted OAuth URL to open in a browser.",
+ required: true,
+ },
+ FieldSchema {
+ name: "connectionId",
+ ty: TypeSchema::String,
+ comment: "New Composio connection id created by this authorize call.",
+ required: true,
+ },
+ ],
+ },
+ "delete_connection" => ControllerSchema {
+ namespace: "composio",
+ function: "delete_connection",
+ description: "Delete a Composio connection and optionally remove source-scoped memory.",
+ inputs: vec![
+ FieldSchema {
+ name: "connection_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the connection to delete.",
+ required: true,
+ },
+ FieldSchema {
+ name: "clear_memory",
+ ty: TypeSchema::Bool,
+ comment: "When true, delete memory chunks ingested from this connection.",
+ required: false,
+ },
+ ],
+ outputs: vec![
+ FieldSchema {
+ name: "deleted",
+ ty: TypeSchema::Bool,
+ comment: "True when the backend confirmed the deletion.",
+ required: true,
+ },
+ FieldSchema {
+ name: "memory_chunks_deleted",
+ ty: TypeSchema::U64,
+ comment: "Number of memory chunks deleted for this connection.",
+ required: true,
+ },
+ ],
+ },
+ "list_tools" => ControllerSchema {
+ namespace: "composio",
+ function: "list_tools",
+ description:
+ "List OpenAI-function-calling tool schemas for one or more Composio toolkits.",
+ inputs: vec![
+ FieldSchema {
+ name: "toolkits",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Optional list of toolkit slugs to filter by. Omit to get all.",
+ required: false,
+ },
+ FieldSchema {
+ name: "tags",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
+ TypeSchema::String,
+ )))),
+ comment: "Optional Composio action tags to filter by (OR semantics — \
+ multiple tags broaden the result). Case-insensitive.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "tools",
+ ty: TypeSchema::Json,
+ comment: "Array of OpenAI function-calling tool schemas.",
+ required: true,
+ }],
+ },
+ "execute" => ControllerSchema {
+ namespace: "composio",
+ function: "execute",
+ description: "Execute a Composio action (tool slug) against a connected account.",
+ inputs: vec![
+ FieldSchema {
+ name: "tool",
+ ty: TypeSchema::String,
+ comment: "Composio action slug, e.g. GMAIL_SEND_EMAIL.",
+ required: true,
+ },
+ FieldSchema {
+ name: "arguments",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Tool-specific arguments conforming to the tool's JSON schema.",
+ required: false,
+ },
+ FieldSchema {
+ name: "connection_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Optional Composio connection id to target a specific account when multiple are connected for the same toolkit. Omit to use the default (oldest active).",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Execution envelope: { data, successful, error?, costUsd }.",
+ required: true,
+ }],
+ },
+ "list_github_repos" => ControllerSchema {
+ namespace: "composio",
+ function: "list_github_repos",
+ description:
+ "List repositories available through the caller's authorized GitHub Composio connection.",
+ inputs: vec![FieldSchema {
+ name: "connection_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment:
+ "Optional GitHub connection id. If omitted, backend picks the first active GitHub connection.",
+ required: false,
+ }],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Payload: { connectionId, repositories:[{ owner, repo, fullName, ... }] }.",
+ required: true,
+ }],
+ },
+ "create_trigger" => ControllerSchema {
+ namespace: "composio",
+ function: "create_trigger",
+ description:
+ "Create a Composio trigger instance for a connected account. For GitHub triggers, pass owner/repo in trigger_config.",
+ inputs: vec![
+ FieldSchema {
+ name: "slug",
+ ty: TypeSchema::String,
+ comment: "Trigger slug, e.g. GITHUB_PULL_REQUEST_EVENT.",
+ required: true,
+ },
+ FieldSchema {
+ name: "connection_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Optional connected account id. Backend resolves from slug toolkit when omitted.",
+ required: false,
+ },
+ FieldSchema {
+ name: "trigger_config",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment:
+ "Trigger config object. For GitHub, include owner/repo or repoFullName.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Payload: { triggerId, status? }.",
+ required: true,
+ }],
+ },
+ "get_user_profile" => ControllerSchema {
+ namespace: "composio",
+ function: "get_user_profile",
+ description:
+ "Fetch a normalized user profile for a Composio connection by dispatching to \
+ the toolkit's native provider implementation.",
+ inputs: vec![FieldSchema {
+ name: "connection_id",
+ ty: TypeSchema::String,
+ comment: "Composio connection id (from list_connections / authorize).",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "profile",
+ ty: TypeSchema::Json,
+ comment: "Normalized profile: { toolkit, connectionId, displayName?, email?, \
+ username?, avatarUrl?, extras }.",
+ required: true,
+ }],
+ },
+ "refresh_all_identities" => ControllerSchema {
+ namespace: "composio",
+ function: "refresh_all_identities",
+ description:
+ "Re-fetch user profile for every active Composio connection and persist as \
+ IdentityKind-tagged rows in user_profile (#1365). Best-effort per connection \
+ — failures don't abort the others.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "report",
+ ty: TypeSchema::Json,
+ comment: "{ refreshed, failed, skippedNoProvider, skippedInactive, \
+ rowsWritten } — aggregate counts; per-connection trail in envelope \
+ messages.",
+ required: true,
+ }],
+ },
+ "sync" => ControllerSchema {
+ namespace: "composio",
+ function: "sync",
+ description:
+ "Run a sync pass for a Composio connection by dispatching to the toolkit's \
+ native provider implementation. Persists results into the memory layer.",
+ inputs: vec![
+ FieldSchema {
+ name: "connection_id",
+ ty: TypeSchema::String,
+ comment: "Composio connection id (from list_connections / authorize).",
+ required: true,
+ },
+ FieldSchema {
+ name: "reason",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment:
+ "Optional reason: 'manual' (default), 'periodic', 'connection_created'.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "outcome",
+ ty: TypeSchema::Json,
+ comment: "SyncOutcome: { toolkit, connectionId, reason, itemsIngested, \
+ startedAtMs, finishedAtMs, summary, details }.",
+ required: true,
+ }],
+ },
+ "list_trigger_history" => ControllerSchema {
+ namespace: "composio",
+ function: "list_trigger_history",
+ description:
+ "List recent ComposeIO trigger events archived by the core and report the daily JSONL archive paths.",
+ inputs: vec![FieldSchema {
+ name: "limit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Maximum number of archived trigger events to return.",
+ required: false,
+ }],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Trigger history payload: { archive_dir, current_day_file, entries }.",
+ required: true,
+ }],
+ },
+ "get_user_scopes" => ControllerSchema {
+ namespace: "composio",
+ function: "get_user_scopes",
+ description:
+ "Read the per-toolkit user scope preference (read/write/admin) used to gate \
+ composio_execute. Defaults to {read:true, write:true, admin:false} when no \
+ pref is stored.",
+ inputs: vec![FieldSchema {
+ name: "toolkit",
+ ty: TypeSchema::String,
+ comment: "Toolkit slug, e.g. 'gmail' or 'notion'.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "pref",
+ ty: TypeSchema::Json,
+ comment: "Scope pref: { read: bool, write: bool, admin: bool }.",
+ required: true,
+ }],
+ },
+ "set_user_scopes" => ControllerSchema {
+ namespace: "composio",
+ function: "set_user_scopes",
+ description:
+ "Persist a per-toolkit user scope preference. The agent will only be able to \
+ invoke composio actions whose classified scope is enabled here.",
+ inputs: vec![
+ FieldSchema {
+ name: "toolkit",
+ ty: TypeSchema::String,
+ comment: "Toolkit slug, e.g. 'gmail' or 'notion'.",
+ required: true,
+ },
+ FieldSchema {
+ name: "read",
+ ty: TypeSchema::Bool,
+ comment: "Allow read-classified actions (GET / FETCH / LIST / SEARCH).",
+ required: true,
+ },
+ FieldSchema {
+ name: "write",
+ ty: TypeSchema::Bool,
+ comment: "Allow write-classified actions (SEND / CREATE / UPDATE).",
+ required: true,
+ },
+ FieldSchema {
+ name: "admin",
+ ty: TypeSchema::Bool,
+ comment: "Allow admin-classified actions (DELETE / TRASH / SHARE).",
+ required: true,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "pref",
+ ty: TypeSchema::Json,
+ comment: "Stored scope pref: { read, write, admin }.",
+ required: true,
+ }],
+ },
+ "list_available_triggers" => ControllerSchema {
+ namespace: "composio",
+ function: "list_available_triggers",
+ description:
+ "List the catalog of triggers the caller can enable for a toolkit. \
+ For GitHub, pass `connection_id` to fan out into per-repo entries.",
+ inputs: vec![
+ FieldSchema {
+ name: "toolkit",
+ ty: TypeSchema::String,
+ comment: "Toolkit slug, e.g. 'gmail' or 'github'.",
+ required: true,
+ },
+ FieldSchema {
+ name: "connection_id",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment:
+ "Optional connection id. Optional for most toolkits; pass when \
+ requesting GitHub per-repo catalog entries.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "triggers",
+ ty: TypeSchema::Json,
+ comment:
+ "Array of {slug, scope, defaultConfig?, requiredConfigKeys?, repo?}.",
+ required: true,
+ }],
+ },
+ "list_triggers" => ControllerSchema {
+ namespace: "composio",
+ function: "list_triggers",
+ description: "List the user's currently enabled Composio triggers.",
+ inputs: vec![FieldSchema {
+ name: "toolkit",
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment: "Optional toolkit slug to filter by.",
+ required: false,
+ }],
+ outputs: vec![FieldSchema {
+ name: "triggers",
+ ty: TypeSchema::Json,
+ comment:
+ "Array of {id, slug, toolkit, connectionId, triggerConfig?, state?}.",
+ required: true,
+ }],
+ },
+ "enable_trigger" => ControllerSchema {
+ namespace: "composio",
+ function: "enable_trigger",
+ description:
+ "Enable a single Composio trigger on a connection the caller owns.",
+ inputs: vec![
+ FieldSchema {
+ name: "connection_id",
+ ty: TypeSchema::String,
+ comment: "Connection id to attach the trigger to.",
+ required: true,
+ },
+ FieldSchema {
+ name: "slug",
+ ty: TypeSchema::String,
+ comment: "Trigger slug, e.g. 'GMAIL_NEW_GMAIL_MESSAGE'.",
+ required: true,
+ },
+ FieldSchema {
+ name: "trigger_config",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
+ comment: "Optional trigger config object.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Payload: {triggerId, slug, connectionId}.",
+ required: true,
+ }],
+ },
+ "disable_trigger" => ControllerSchema {
+ namespace: "composio",
+ function: "disable_trigger",
+ description: "Disable (delete) a Composio trigger owned by the caller.",
+ inputs: vec![FieldSchema {
+ name: "trigger_id",
+ ty: TypeSchema::String,
+ comment: "Identifier of the trigger to delete.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "deleted",
+ ty: TypeSchema::Bool,
+ comment: "True when the backend confirmed deletion.",
+ required: true,
+ }],
+ },
+ "get_mode" => ControllerSchema {
+ namespace: "composio",
+ function: "get_mode",
+ description:
+ "Read the current Composio routing mode and whether a direct-mode API key is stored. \
+ Never returns the key itself.",
+ inputs: vec![],
+ outputs: vec![
+ FieldSchema {
+ name: "mode",
+ ty: TypeSchema::String,
+ comment: "Current mode: 'backend' (default) or 'direct'.",
+ required: true,
+ },
+ FieldSchema {
+ name: "api_key_set",
+ ty: TypeSchema::Bool,
+ comment: "True if a direct-mode Composio API key is in the encrypted keychain.",
+ required: true,
+ },
+ ],
+ },
+ "set_api_key" => ControllerSchema {
+ namespace: "composio",
+ function: "set_api_key",
+ description:
+ "Persist a user-provided Composio API key for direct mode in the encrypted \
+ keychain. Optionally flip composio.mode to 'direct' atomically. The key is \
+ NEVER logged or returned — only its length is recorded in tracing.",
+ inputs: vec![
+ FieldSchema {
+ name: "api_key",
+ ty: TypeSchema::String,
+ comment: "The Composio API key from https://app.composio.dev/api-keys.",
+ required: true,
+ },
+ FieldSchema {
+ name: "activate_direct",
+ ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
+ comment: "When true, also set composio.mode = 'direct'. Default false.",
+ required: false,
+ },
+ ],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "{ stored: bool, mode: string } — current mode after the operation.",
+ required: true,
+ }],
+ },
+ "clear_api_key" => ControllerSchema {
+ namespace: "composio",
+ function: "clear_api_key",
+ description:
+ "Remove the stored direct-mode Composio API key and reset composio.mode \
+ back to 'backend'.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "{ cleared: bool, mode: 'backend' }.",
+ required: true,
+ }],
+ },
+ _other => ControllerSchema {
+ namespace: "composio",
+ function: "unknown",
+ description: "Unknown composio controller function.",
+ inputs: vec![FieldSchema {
+ name: "function",
+ ty: TypeSchema::String,
+ comment: "Unknown function requested for schema lookup.",
+ required: true,
+ }],
+ outputs: vec![FieldSchema {
+ name: "error",
+ ty: TypeSchema::String,
+ comment: "Lookup error details.",
+ required: true,
+ }],
+ },
+ }
+}
diff --git a/crates/openhuman-core/src/memory/schema/definitions.rs b/crates/openhuman-core/src/memory/schema/definitions.rs
index 1b0a21d822..3c52e30452 100644
--- a/crates/openhuman-core/src/memory/schema/definitions.rs
+++ b/crates/openhuman-core/src/memory/schema/definitions.rs
@@ -9,16 +9,16 @@ use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
pub(crate) const NAMESPACE: &str = "memory_tree";
/// Lookup the [`ControllerSchema`] for a single `memory_tree` function name.
-#[path = "schema_schema_part_01.rs"]
-mod schema_schema_part_01;
-#[path = "schema_schema_part_02.rs"]
-mod schema_schema_part_02;
+#[path = "tree_operations_schema.rs"]
+mod tree_operations_schema;
+#[path = "vault_and_pipeline_schema.rs"]
+mod vault_and_pipeline_schema;
pub fn schemas(function: &str) -> ControllerSchema {
- if let Some(schema) = schema_schema_part_01::lookup(function) {
+ if let Some(schema) = tree_operations_schema::lookup(function) {
return schema;
}
- if let Some(schema) = schema_schema_part_02::lookup(function) {
+ if let Some(schema) = vault_and_pipeline_schema::lookup(function) {
return schema;
}
ControllerSchema {
diff --git a/crates/openhuman-core/src/memory/schema/schema_schema_part_01.rs b/crates/openhuman-core/src/memory/schema/tree_operations_schema.rs
similarity index 100%
rename from crates/openhuman-core/src/memory/schema/schema_schema_part_01.rs
rename to crates/openhuman-core/src/memory/schema/tree_operations_schema.rs
diff --git a/crates/openhuman-core/src/memory/schema/schema_schema_part_02.rs b/crates/openhuman-core/src/memory/schema/vault_and_pipeline_schema.rs
similarity index 100%
rename from crates/openhuman-core/src/memory/schema/schema_schema_part_02.rs
rename to crates/openhuman-core/src/memory/schema/vault_and_pipeline_schema.rs
diff --git a/crates/openhuman-core/src/memory/tree/tree/rpc/stall.rs b/crates/openhuman-core/src/memory/tree/tree/rpc/stall.rs
new file mode 100644
index 0000000000..2391838496
--- /dev/null
+++ b/crates/openhuman-core/src/memory/tree/tree/rpc/stall.rs
@@ -0,0 +1,232 @@
+//! Pure derivations used by [`super::pipeline_status`]: the disk-size walk,
+//! the #5324 queue-stall verdict, and the `(status, reason)` precedence rule.
+//! Kept side-effect-free (besides the disk walk and its own logging) so the
+//! unit tests can exercise the precedence rules without spinning up a store.
+
+/// Recursive byte-count of files under `root`. Returns `0` when the root
+/// does not exist or any traversal error occurs (best-effort; the status
+/// panel is a UI convenience, not an audit surface).
+pub(super) fn compute_dir_size_bytes(root: &std::path::Path) -> u64 {
+ if !root.exists() {
+ return 0;
+ }
+ let mut total: u64 = 0;
+ for entry in walkdir::WalkDir::new(root).follow_links(false) {
+ match entry {
+ Ok(e) if e.file_type().is_file() => {
+ if let Ok(meta) = e.metadata() {
+ total = total.saturating_add(meta.len());
+ }
+ }
+ Ok(_) => {}
+ Err(err) => {
+ // Both `err.path()` and `walkdir::Error`'s `Display` impl
+ // embed the absolute on-disk path (which lives under the
+ // user's home directory), so we redact: log only whether a
+ // path was attached and the underlying `io::ErrorKind`.
+ // That's enough for diagnosis while keeping the user's
+ // workspace layout out of the log file.
+ log::warn!(
+ "[memory-tree][rpc] pipeline_status: dir walk error has_path={} kind={:?}",
+ err.path().is_some(),
+ err.io_error().map(|e| e.kind())
+ );
+ }
+ }
+ }
+ total
+}
+
+/// #5324: how long the queue may hold eligible work without settling a single
+/// job before the pipeline is reported as `degraded` rather than
+/// `running`/`idle`.
+///
+/// A working pipeline settles jobs continuously, so this is idle time, not
+/// backlog depth — a deep-but-draining backfill never approaches it. Six hours
+/// is far outside a normal flush window (minutes) yet well inside the "broken
+/// for a month" window the issue describes, so it cannot fire on a busy
+/// machine or a laptop that was asleep for an hour.
+pub(crate) const QUEUE_STALL_THRESHOLD_MS: i64 = 6 * 60 * 60 * 1000;
+
+/// The #5324 stall verdict on its own: eligible work has been waiting for at
+/// least [`QUEUE_STALL_THRESHOLD_MS`] without any job settling. Shared by the
+/// status precedence below and by the `queue_stalled` flag the response
+/// carries, so the two cannot disagree (openhuman#6025 review).
+pub(crate) fn queue_is_stalled(queue_idle_ms: Option<i64>) -> bool {
+ queue_idle_ms.is_some_and(|idle| idle >= QUEUE_STALL_THRESHOLD_MS)
+}
+
+/// Pure derivation of `(status, reason)` from raw signals. Split out so the
+/// unit tests can exercise the precedence rules without spinning up a
+/// store.
+///
+/// `queue_idle_ms` is how long the queue has held eligible work without
+/// settling any job, or `None` when no eligible work is waiting (or the
+/// metric could not be read).
+///
+/// `pub(super)` — reused verbatim by tests declared directly under `rpc`.
+pub(super) fn derive_pipeline_status(
+ is_paused: bool,
+ mode: tinymemory_api::host::SchedulerGateMode,
+ is_syncing: bool,
+ failed: u64,
+ failed_unrecoverable: u64,
+ total_chunks: u64,
+ degraded: &crate::memory::tree::health::DegradedState,
+ queue_idle_ms: Option<i64>,
+) -> (String, Option<String>) {
+ if is_paused {
+ return (
+ "paused".to_string(),
+ Some(format!("scheduler gate mode = {}", mode.as_str())),
+ );
+ }
+ // Host storage is unusable (EIO/ENOSPC/EROFS on the memory_tree path). This
+ // is a foundational, unrecoverable error — the DB can't even open, so it
+ // outranks the per-content recall/structure degradation below AND fires
+ // regardless of `total_chunks` (on a dead disk we may not be able to count
+ // chunks at all). Only the user can fix it (reseat/replace/free storage);
+ // the actionable remediation text rides the `StorageUnavailable`
+ // remediation key surfaced by the doctor's `first_blocking_cause`.
+ if degraded.storage {
+ return (
+ "error".to_string(),
+ Some("memory storage unavailable — check your disk / SD card".to_string()),
+ );
+ }
+ // #3365: split the failed bucket by class. Only an UNRECOVERABLE failure
+ // (budget / auth / dim-mismatch) is a hard `error` the user must act on —
+ // it stays parked and can't self-heal. Transient failures are auto-requeued
+ // by `requeue_transient_failed`, so they must NOT escalate to `error`; they
+ // fall through to `degraded` ("failed, retrying") below. This fixes the prior
+ // `failed > 0 → error` that flashed a scary error for a job about to retry.
+ if failed_unrecoverable > 0 {
+ return (
+ "error".to_string(),
+ Some(format!(
+ "{failed_unrecoverable} unrecoverable failure(s) need action"
+ )),
+ );
+ }
+ // #5324: the queue is accepting work but not draining it. This is the
+ // "silently broken for a month" shape — new files keep getting detected
+ // and queued, health checks keep reporting `ok` because the process is
+ // alive, and nothing ever becomes searchable memory. Liveness is not
+ // output, so a queue whose oldest ready job has been waiting past the
+ // threshold reports `degraded`, never `running`/`idle`.
+ //
+ // Sits below `error` (a typed unrecoverable failure is the more specific
+ // diagnosis and carries its own remediation) and above the recall/structure
+ // degradation, and is deliberately NOT gated on `total_chunks` — a queue
+ // that never drained has no chunks to gate on, which is exactly the case
+ // that must not read as `idle`.
+ if queue_is_stalled(queue_idle_ms) {
+ let hours = queue_idle_ms.unwrap_or(0) / (60 * 60 * 1000);
+ return (
+ "degraded".to_string(),
+ Some(format!(
+ "queue has not completed any job in {hours}h — memory is not growing"
+ )),
+ );
+ }
+ // #002 (FR-005): "degraded" sits below error but above syncing/running —
+ // the pipeline is making progress, but recall/structure is reduced (or some
+ // jobs failed transiently and are retrying) and the user should be told why.
+ // Beats syncing/running so a half-working sync isn't reported as plain
+ // "running"/"syncing".
+ //
+ // Only fires when there are chunks: degraded recall/structure is only
+ // meaningful when there's actual content affected. An empty workspace with
+ // a misconfigured embedder should show "idle" (nothing to recall) rather
+ // than "degraded" (recall is broken for existing content).
+ //
+ // `failed` here is transient-only — any unrecoverable failure returned
+ // `error` above, so a non-zero `failed` at this point means jobs that will
+ // be auto-requeued.
+ if (degraded.is_degraded() || failed > 0) && total_chunks > 0 {
+ let mut parts: Vec<String> = Vec::new();
+ if degraded.semantic_recall {
+ parts.push("semantic recall disabled".to_string());
+ }
+ if degraded.structure {
+ parts.push("wiki structure incomplete".to_string());
+ }
+ if failed > 0 {
+ parts.push(format!("{failed} job(s) failed, retrying"));
+ }
+ return ("degraded".to_string(), Some(parts.join("; ")));
+ }
+ if is_syncing {
+ return ("syncing".to_string(), None);
+ }
+ if total_chunks > 0 {
+ return ("running".to_string(), None);
+ }
+ ("idle".to_string(), None)
+}
+
+/// #5324: how long the queue has been sitting on eligible work without
+/// finishing anything, or `None` when there is no eligible work waiting.
+///
+/// This is the "queued but never processed" signal. Getting the predicate
+/// right matters more than it looks, because the naive versions produce false
+/// alarms for exactly the heavy users this issue is about:
+///
+/// - **Not** `MIN(created_at_ms)` over all `ready` rows. `mark_deferred` parks
+/// a backing-off job by leaving `status = 'ready'` and pushing
+/// `available_at_ms` forward, so deferred work would count as waiting when
+/// it is deliberately asleep.
+/// - **Not** the age of the oldest eligible row either. A re-embed backfill
+/// enqueues thousands of rows in one burst; six hours into a perfectly
+/// healthy drain of a 68k-chunk workspace, the oldest un-drained row is by
+/// definition hours old. That would flag the exact case the issue's reporter
+/// was in — a big, slow, *working* backfill — as broken.
+///
+/// So the measure is **idle time, not backlog age**: how long since the queue
+/// last settled *any* job. A pipeline making progress refreshes
+/// `completed_at_ms` continuously no matter how deep the backlog is, while a
+/// pipeline whose jobs all fail unrecoverably or whose worker never runs goes
+/// quiet. `completed_at_ms` is stamped on failure as well as success, so a
+/// fast-failing pipeline reports `error` (via `failed_unrecoverable`) rather
+/// than being mislabelled as stalled.
+///
+/// Returns `Some(idle_ms)` only when eligible work is actually waiting — an
+/// idle queue with nothing to do is not stalled, it is done. When nothing has
+/// ever settled (fresh workspace whose worker has never run), idle time falls
+/// back to how long the oldest eligible job has been waiting.
+///
+/// Derived from a snapshot rather than read on its own, so the eligible count
+/// and the timestamps it is measured against come from one instant. Reading
+/// them separately is what makes an idle window appear across a settle that
+/// happened between two queries.
+///
+/// `pub(super)` — reused verbatim by tests declared directly under `rpc`.
+pub(super) fn queue_idle_ms(
+ queue: &crate::memory::api::provider::types::QueueStats,
+ now_ms: i64,
+) -> Option<i64> {
+ // Nothing eligible is waiting ⇒ nothing is being held up.
+ if queue.eligible_now == 0 {
+ return None;
+ }
+ let (last_settled_ms, oldest_eligible_ms) = (queue.last_completed_ms, queue.oldest_eligible_ms);
+ // Idle time is "how long since the queue last made progress on the work
+ // that is waiting *now*" — so start the clock at the LATER of the last
+ // settle and the oldest eligible job's arrival. Using `last_settled_ms`
+ // alone (`.or`) mis-reads a real shape: if the queue drained everything,
+ // sat empty for days, then a fresh job arrives, the stale completion is
+ // hours/days old while the new work is seconds old. Taking the max means
+ // freshly-enqueued work starts its own idle window instead of inheriting
+ // an ancient completion, so a just-arrived job can't be flagged `degraded`
+ // before the worker has had a chance to touch it. Fall back to the oldest
+ // eligible job's wait when the queue has never settled a job at all.
+ let reference_ms = match (last_settled_ms, oldest_eligible_ms) {
+ (Some(last_settled), Some(oldest_eligible)) => Some(last_settled.max(oldest_eligible)),
+ (Some(last_settled), None) => Some(last_settled),
+ (None, Some(oldest_eligible)) => Some(oldest_eligible),
+ (None, None) => None,
+ };
+ // Clamp at zero: clock skew / a future-dated row must read as "just now",
+ // never as a negative age.
+ reference_ms.map(|since| (now_ms - since).max(0))
+}