diff --git a/src/openhuman/accessibility/app_fastpaths/music.rs b/src/openhuman/accessibility/app_fastpaths/music.rs index 3e7d414d0..9c58ee420 100644 --- a/src/openhuman/accessibility/app_fastpaths/music.rs +++ b/src/openhuman/accessibility/app_fastpaths/music.rs @@ -517,7 +517,7 @@ pub async fn run(goal: &str, backend: &dyn AutomateBackend) -> AutomateOutcome { } // Song row pressed, but the backend can't confirm the track (non-macOS). (_, None) => { - let unverified = matches!(verified, None); + let unverified = verified.is_none(); steps.push(if unverified { "verify: playback unverified".to_string() } else { diff --git a/src/openhuman/accessibility/ax_interact.rs b/src/openhuman/accessibility/ax_interact.rs index cb3ad21bb..8699911d2 100644 --- a/src/openhuman/accessibility/ax_interact.rs +++ b/src/openhuman/accessibility/ax_interact.rs @@ -115,7 +115,7 @@ pub fn ax_list_elements_filtered(app_name: &str, filter: &str) -> Result Result { .and_then(|v| v.as_str()) .unwrap_or(label) .to_string(); - return Ok(format!("Pressed '{pressed}' in '{app_name}'.")); + Ok(format!("Pressed '{pressed}' in '{app_name}'.")) } #[cfg(target_os = "windows")] { @@ -252,9 +252,9 @@ pub fn ax_set_field_value(app_name: &str, label: &str, value: &str) -> Result Self { - AgentGraph::Default - } -} - impl AgentGraph { /// Build a custom graph selection from a runner fn. Sugar for /// [`AgentGraph::Custom`] so a folder's `graph.rs` reads diff --git a/src/openhuman/agent/harness/run_queue/types.rs b/src/openhuman/agent/harness/run_queue/types.rs index 163d792ad..c394342f3 100644 --- a/src/openhuman/agent/harness/run_queue/types.rs +++ b/src/openhuman/agent/harness/run_queue/types.rs @@ -5,8 +5,10 @@ use std::fmt; /// How a message arriving during an active agent turn should be handled. #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum QueueMode { /// Abort the in-flight turn and start fresh (default, backward-compatible). + #[default] Interrupt, /// Inject the message at the next safe iteration boundary so the agent /// sees it mid-turn without restarting. @@ -24,12 +26,6 @@ pub enum QueueMode { Parallel, } -impl Default for QueueMode { - fn default() -> Self { - Self::Interrupt - } -} - impl fmt::Display for QueueMode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { diff --git a/src/openhuman/agent/harness/session/builder/factory.rs b/src/openhuman/agent/harness/session/builder/factory.rs index fab3c48aa..2e66062e1 100644 --- a/src/openhuman/agent/harness/session/builder/factory.rs +++ b/src/openhuman/agent/harness/session/builder/factory.rs @@ -1159,7 +1159,7 @@ impl Agent { // of agent-conversation recall, suppress the prior-chat and // cross-chat blocks. Defaults to on for None / unset. .with_agent_conversations( - profile.map_or(true, |p| p.include_agent_conversations), + profile.is_none_or(|p| p.include_agent_conversations), ), )) .prompt_builder(prompt_builder) diff --git a/src/openhuman/agent/harness/subagent_runner/ops/graph.rs b/src/openhuman/agent/harness/subagent_runner/ops/graph.rs index 5fe5db0b6..2fc706279 100644 --- a/src/openhuman/agent/harness/subagent_runner/ops/graph.rs +++ b/src/openhuman/agent/harness/subagent_runner/ops/graph.rs @@ -854,22 +854,22 @@ fn mirror_worker_thread( ); } } - ConversationMessage::Chat(c) if c.role == "assistant" => { - if !c.content.trim().is_empty() { - iteration += 1; - append_worker_message( - workspace_dir, - thread_id, - agent_id, - task_id, - c.content.clone(), - "agent", - serde_json::json!({ - "iteration": iteration, - "final": extra_final.is_none(), - }), - ); - } + ConversationMessage::Chat(c) + if c.role == "assistant" && !c.content.trim().is_empty() => + { + iteration += 1; + append_worker_message( + workspace_dir, + thread_id, + agent_id, + task_id, + c.content.clone(), + "agent", + serde_json::json!({ + "iteration": iteration, + "final": extra_final.is_none(), + }), + ); } _ => {} } diff --git a/src/openhuman/agent/tools/delegate_to_personality.rs b/src/openhuman/agent/tools/delegate_to_personality.rs index 72a323960..f90f45a5d 100644 --- a/src/openhuman/agent/tools/delegate_to_personality.rs +++ b/src/openhuman/agent/tools/delegate_to_personality.rs @@ -246,7 +246,7 @@ impl Tool for DelegateToPersonalityTool { run_queue: None, }; - match run_subagent(&definition, &prompt, options).await { + match run_subagent(definition, &prompt, options).await { Ok(outcome) => { tracing::debug!( personality_id = %personality_id, diff --git a/src/openhuman/agent/tools/run_workflow.rs b/src/openhuman/agent/tools/run_workflow.rs index c438f9e3e..f148854f0 100644 --- a/src/openhuman/agent/tools/run_workflow.rs +++ b/src/openhuman/agent/tools/run_workflow.rs @@ -151,7 +151,7 @@ fn reentrancy_key(workflow_id: &str, inputs: &Option) -> Stri match v { serde_json::Value::Object(map) => { let mut sorted: Vec<_> = map.iter().collect(); - sorted.sort_by(|(left, _), (right, _)| left.cmp(right)); + sorted.sort_by_key(|(left, _)| *left); serde_json::Value::Object( sorted .into_iter() diff --git a/src/openhuman/agent/triage/decision.rs b/src/openhuman/agent/triage/decision.rs index 510075441..3965eaee0 100644 --- a/src/openhuman/agent/triage/decision.rs +++ b/src/openhuman/agent/triage/decision.rs @@ -211,13 +211,11 @@ fn last_balanced_brace_object(text: &str) -> Option { } depth += 1; } - b'}' => { - if depth > 0 { - depth -= 1; - if depth == 0 { - if let Some(s) = start.take() { - best = Some((s, i + 1)); - } + b'}' if depth > 0 => { + depth -= 1; + if depth == 0 { + if let Some(s) = start.take() { + best = Some((s, i + 1)); } } } diff --git a/src/openhuman/agent_memory/tools.rs b/src/openhuman/agent_memory/tools.rs index 54a54a2a6..42215af35 100644 --- a/src/openhuman/agent_memory/tools.rs +++ b/src/openhuman/agent_memory/tools.rs @@ -226,7 +226,7 @@ impl Tool for CallMemoryAgentTool { // Synchronous path — block until the memory agent finishes. let started = std::time::Instant::now(); - match run_subagent(&definition, &prompt, options).await { + match run_subagent(definition, &prompt, options).await { Ok(outcome) => { let elapsed = started.elapsed(); log::info!( diff --git a/src/openhuman/agent_orchestration/spawn_parallel_graph.rs b/src/openhuman/agent_orchestration/spawn_parallel_graph.rs index 09fd3c1a3..69f66533e 100644 --- a/src/openhuman/agent_orchestration/spawn_parallel_graph.rs +++ b/src/openhuman/agent_orchestration/spawn_parallel_graph.rs @@ -250,10 +250,7 @@ fn ownership_file_paths(ownership: Option<&str>) -> Result, String> }; let mut paths = Vec::new(); for raw in rest.split([',', '\n']) { - let trimmed = raw - .trim() - .trim_start_matches(|c: char| c == '-' || c == '*') - .trim(); + let trimmed = raw.trim().trim_start_matches(['-', '*']).trim(); if trimmed.is_empty() { continue; } diff --git a/src/openhuman/agent_orchestration/tools/wait_subagent.rs b/src/openhuman/agent_orchestration/tools/wait_subagent.rs index b2b6c83ce..3e9d6dbe9 100644 --- a/src/openhuman/agent_orchestration/tools/wait_subagent.rs +++ b/src/openhuman/agent_orchestration/tools/wait_subagent.rs @@ -265,19 +265,17 @@ impl Tool for WaitSubagentTool { "[wait_subagent] outcome=unknown task_id={}", resolved_task_id ); - Ok(ToolResult::error(format!( - "wait_subagent: no sub-agent was found for that reference. It may have already finished and \ - been collected, or the task_id is wrong." - ))) + Ok(ToolResult::error("wait_subagent: no sub-agent was found for that reference. It may have already finished and \ + been collected, or the task_id is wrong.".to_string())) } Err(WaitError::NotOwned) => { log::debug!( "[wait_subagent] outcome=not_owned task_id={}", resolved_task_id ); - Ok(ToolResult::error(format!( - "wait_subagent: that sub-agent was not started by this agent." - ))) + Ok(ToolResult::error( + "wait_subagent: that sub-agent was not started by this agent.".to_string(), + )) } } } diff --git a/src/openhuman/agent_orchestration/worktree.rs b/src/openhuman/agent_orchestration/worktree.rs index e9e4bdeba..ba1e21890 100644 --- a/src/openhuman/agent_orchestration/worktree.rs +++ b/src/openhuman/agent_orchestration/worktree.rs @@ -241,7 +241,7 @@ pub fn enforce_workspace_path( policy_id = %descriptor.policy_id, "[workspace] workspace_violation_out_of_root" ); - let _ = publish_global(DomainEvent::WorkspaceViolation { + publish_global(DomainEvent::WorkspaceViolation { path: rendered.clone(), }); Err(WorktreeError::OutsideWorkspace(path.to_path_buf())) diff --git a/src/openhuman/approval/redact.rs b/src/openhuman/approval/redact.rs index c2fbed9bc..2af2e4166 100644 --- a/src/openhuman/approval/redact.rs +++ b/src/openhuman/approval/redact.rs @@ -136,7 +136,7 @@ fn scrub_paths(input: &str) -> String { // Skip past the username segment up to the next path // separator (or end of input). let rest = &input[i..]; - match rest.find(|c: char| c == '/' || c == '\\') { + match rest.find(['/', '\\']) { Some(end) => i += end, None => i = input.len(), } diff --git a/src/openhuman/artifacts/types.rs b/src/openhuman/artifacts/types.rs index c4ad739c3..bf0e63c65 100644 --- a/src/openhuman/artifacts/types.rs +++ b/src/openhuman/artifacts/types.rs @@ -4,19 +4,15 @@ use serde::{Deserialize, Serialize}; /// The category of an artifact produced by the agent. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] +#[derive(Default)] pub enum ArtifactKind { Presentation, Document, Image, + #[default] Other, } -impl Default for ArtifactKind { - fn default() -> Self { - Self::Other - } -} - impl ArtifactKind { pub fn as_str(&self) -> &'static str { match self { @@ -42,18 +38,14 @@ impl ArtifactKind { /// Lifecycle status of an artifact. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] +#[derive(Default)] pub enum ArtifactStatus { + #[default] Pending, Ready, Failed, } -impl Default for ArtifactStatus { - fn default() -> Self { - Self::Pending - } -} - impl ArtifactStatus { pub fn as_str(&self) -> &'static str { match self { diff --git a/src/openhuman/channels/providers/web/mod.rs b/src/openhuman/channels/providers/web/mod.rs index 194caea51..b629b4339 100644 --- a/src/openhuman/channels/providers/web/mod.rs +++ b/src/openhuman/channels/providers/web/mod.rs @@ -11,10 +11,7 @@ mod types; #[path = "../web_errors.rs"] mod web_errors; -pub(crate) use web_errors::{ - classify_inference_error, inference_budget_exceeded_user_message, - is_inference_budget_exceeded_error, -}; +pub(crate) use web_errors::classify_inference_error; #[cfg(any(test, debug_assertions))] #[allow(unused_imports)] pub(crate) use web_errors::{ @@ -51,12 +48,8 @@ pub use schemas::{ // Helpers re-exported for tests pub(crate) use ops::{event_session_id_for, key_for}; pub(crate) use progress_bridge::spawn_progress_bridge; -pub(crate) use session::{compose_system_prompt_suffix, locale_reply_directive}; // Schema field helpers re-exported for tests -pub(crate) use schemas::{ - json_output, optional_bool, optional_f64, optional_string, optional_u64, required_string, -}; // Test helpers (debug/test builds only) #[cfg(any(test, debug_assertions))] @@ -64,13 +57,6 @@ pub use ops::set_test_forced_run_chat_task_error; #[cfg(any(test, debug_assertions))] pub use ops::{set_test_run_chat_task_block, TestRunChatTaskBlock}; -#[cfg(any(test, debug_assertions))] -pub(crate) use ops::THREAD_SESSIONS; -#[cfg(any(test, debug_assertions))] -pub(crate) use session::{normalize_model_override, provider_role_for_model_override}; -#[cfg(any(test, debug_assertions))] -pub(crate) use types::WebChatParams; - #[cfg(any(test, debug_assertions))] pub mod test_support { #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/src/openhuman/channels/runtime/dispatch/processor.rs b/src/openhuman/channels/runtime/dispatch/processor.rs index 14709675f..0515f4143 100644 --- a/src/openhuman/channels/runtime/dispatch/processor.rs +++ b/src/openhuman/channels/runtime/dispatch/processor.rs @@ -186,10 +186,8 @@ pub(crate) async fn process_channel_runtime_message( // a fresh agent turn would cancel the parked tool call. Any other text // falls through to the normal dispatch (the user is redirecting). Mirrors // the same intercept in `channels/providers/web.rs:493-525`. - if channel_has_approval_surface(&msg.channel) { - if try_route_approval_reply(&msg).await { - return; - } + if channel_has_approval_surface(&msg.channel) && try_route_approval_reply(&msg).await { + return; } // Fire typing indicator as early as possible — before any async I/O — so the @@ -385,16 +383,14 @@ pub(crate) async fn process_channel_runtime_message( } } } - AgentProgress::ToolCallStarted { tool_name, .. } => { - if accumulated.is_empty() { - let _ = channel - .update_draft( - &reply_target, - &draft_id, - &format!("Working ({})...", tool_name), - ) - .await; - } + AgentProgress::ToolCallStarted { tool_name, .. } if accumulated.is_empty() => { + let _ = channel + .update_draft( + &reply_target, + &draft_id, + &format!("Working ({})...", tool_name), + ) + .await; } _ => {} } diff --git a/src/openhuman/channels/runtime/test_support.rs b/src/openhuman/channels/runtime/test_support.rs index dc63c8926..82c1e7163 100644 --- a/src/openhuman/channels/runtime/test_support.rs +++ b/src/openhuman/channels/runtime/test_support.rs @@ -444,7 +444,7 @@ pub async fn run_dispatch_harness(options: DispatchHarnessOptions) -> DispatchHa inference_url: None, reliability: Arc::new(ReliabilityConfig::default()), provider_runtime_options: ProviderRuntimeOptions::default(), - workspace_dir: Arc::new(PathBuf::from(std::env::temp_dir())), + workspace_dir: Arc::new(std::env::temp_dir()), message_timeout_secs: options.timeout_secs, multimodal: MultimodalConfig::default(), multimodal_files: MultimodalFileConfig::default(), diff --git a/src/openhuman/config/schema/activity_level.rs b/src/openhuman/config/schema/activity_level.rs index d8d5e3465..6e6ec6c91 100644 --- a/src/openhuman/config/schema/activity_level.rs +++ b/src/openhuman/config/schema/activity_level.rs @@ -15,12 +15,14 @@ use serde_repr::{Deserialize_repr, Serialize_repr}; /// - Token budget per background cycle #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr, JsonSchema)] #[repr(u8)] +#[derive(Default)] pub enum AgentActivityLevel { /// No background processing. Syncs only on manual press. Off = 0, /// Sync sources once per day. No proactive messages. Minimal = 1, /// Sync every hour. Daily digest. Suggests actions. (default) + #[default] Moderate = 2, /// Sync every 10 min. Monitors channels, triages, drafts replies. Active = 3, @@ -95,12 +97,6 @@ impl AgentActivityLevel { } } -impl Default for AgentActivityLevel { - fn default() -> Self { - Self::Moderate - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/openhuman/config/schema/capability_providers.rs b/src/openhuman/config/schema/capability_providers.rs index b5d4feac9..3818d9003 100644 --- a/src/openhuman/config/schema/capability_providers.rs +++ b/src/openhuman/config/schema/capability_providers.rs @@ -39,15 +39,11 @@ impl Default for CapabilityProviderConfig { /// Trust state for an external capability provider. #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum CapabilityProviderTrustState { /// Provider metadata is accepted, but capabilities from it are not trusted. + #[default] Untrusted, /// Provider is explicitly trusted by local config. Trusted, } - -impl Default for CapabilityProviderTrustState { - fn default() -> Self { - Self::Untrusted - } -} diff --git a/src/openhuman/config/schema/channels.rs b/src/openhuman/config/schema/channels.rs index 0efaae99d..2cedc6e7a 100644 --- a/src/openhuman/config/schema/channels.rs +++ b/src/openhuman/config/schema/channels.rs @@ -56,14 +56,9 @@ pub enum SandboxBackend { #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] +#[derive(Default)] pub struct ResourceLimitsConfig {} -impl Default for ResourceLimitsConfig { - fn default() -> Self { - Self {} - } -} - #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] pub struct AuditConfig { diff --git a/src/openhuman/config/schema/dashboard.rs b/src/openhuman/config/schema/dashboard.rs index c8ebeee41..9f254aed2 100644 --- a/src/openhuman/config/schema/dashboard.rs +++ b/src/openhuman/config/schema/dashboard.rs @@ -17,6 +17,7 @@ fn default_diagram_viewer_refresh_interval_seconds() -> u64 { #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] +#[derive(Default)] pub struct DashboardConfig { #[serde(default)] pub event_stream: EventStreamConfig, @@ -26,16 +27,6 @@ pub struct DashboardConfig { pub diagram_viewer: DiagramViewerConfig, } -impl Default for DashboardConfig { - fn default() -> Self { - Self { - event_stream: EventStreamConfig::default(), - model_health: ModelHealthConfig::default(), - diagram_viewer: DiagramViewerConfig::default(), - } - } -} - #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] pub struct EventStreamConfig { diff --git a/src/openhuman/config/schema/load/impl_load.rs b/src/openhuman/config/schema/load/impl_load.rs index 800861b8c..bff462778 100644 --- a/src/openhuman/config/schema/load/impl_load.rs +++ b/src/openhuman/config/schema/load/impl_load.rs @@ -13,7 +13,7 @@ use anyhow::{Context, Result}; use std::collections::HashSet; use std::path::Path; use std::sync::{Mutex, OnceLock}; -use tokio::fs::{self, File, OpenOptions}; +use tokio::fs::{self, OpenOptions}; use tokio::io::AsyncWriteExt; static WARNED_WORLD_READABLE_CONFIGS: OnceLock>> = diff --git a/src/openhuman/config/schema/load/mod.rs b/src/openhuman/config/schema/load/mod.rs index 43fd7ef0a..828e5d001 100644 --- a/src/openhuman/config/schema/load/mod.rs +++ b/src/openhuman/config/schema/load/mod.rs @@ -7,18 +7,12 @@ mod impl_load; mod migrate; mod secrets; -pub(crate) use env::EnvLookup; -pub(crate) use env::ProcessEnv; - pub use dirs::{ action_dir_env_override, active_user_marker_path, clear_active_user, default_action_dir, default_projects_dir, default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, - resolve_action_dir, user_openhuman_dir, write_active_user_id, ACTION_DIR_ENV_VAR, - MEMORY_SYNC_INTERVAL_SECS_ENV_VAR, PRE_LOGIN_USER_ID, PROJECTS_DIR_ENV_VAR, + resolve_action_dir, user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID, }; -pub(crate) use dirs::persist_active_workspace_config_dir; - // redact_url_for_log is pub(super) for the schema module; tests inside load // can access it because they are a submodule and use `use super::*`. pub(super) use migrate::redact_url_for_log; diff --git a/src/openhuman/config/schema/local_ai.rs b/src/openhuman/config/schema/local_ai.rs index 08499d874..ca856d807 100644 --- a/src/openhuman/config/schema/local_ai.rs +++ b/src/openhuman/config/schema/local_ai.rs @@ -9,6 +9,7 @@ use serde::{Deserialize, Serialize}; /// method below returns `false` regardless of these values. #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] +#[derive(Default)] pub struct LocalAiUsage { /// When true (and `runtime_enabled`), use the local model for embedding /// generation instead of the cloud backend. @@ -28,17 +29,6 @@ pub struct LocalAiUsage { pub subconscious: bool, } -impl Default for LocalAiUsage { - fn default() -> Self { - Self { - embeddings: false, - heartbeat: false, - learning_reflection: false, - subconscious: false, - } - } -} - #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] pub struct LocalAiConfig { diff --git a/src/openhuman/config/schema/meet.rs b/src/openhuman/config/schema/meet.rs index dbad27675..b78d4da67 100644 --- a/src/openhuman/config/schema/meet.rs +++ b/src/openhuman/config/schema/meet.rs @@ -14,8 +14,10 @@ use serde::{Deserialize, Serialize}; /// Controls whether the bot auto-joins meetings from the calendar. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum AutoJoinPolicy { /// Prompt the user before every join (default). + #[default] AskEachTime, /// Always join without prompting. Always, @@ -23,17 +25,13 @@ pub enum AutoJoinPolicy { Never, } -impl Default for AutoJoinPolicy { - fn default() -> Self { - Self::AskEachTime - } -} - /// Controls whether post-call summaries are generated automatically. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum AutoSummarizePolicy { /// Ask the user after the call ends (default). + #[default] Ask, /// Always generate a summary. Always, @@ -41,28 +39,18 @@ pub enum AutoSummarizePolicy { Never, } -impl Default for AutoSummarizePolicy { - fn default() -> Self { - Self::Ask - } -} - /// Which calendar data source feeds Google Meet detection and auto-join. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum CalendarProvider { /// Composio-based Google Calendar sync (default; broad OAuth scopes). + #[default] Composio, /// Recall.ai Calendar V1 OAuth (less-invasive: read-only events + email). Recall, } -impl Default for CalendarProvider { - fn default() -> Self { - Self::Composio - } -} - #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] pub struct MeetConfig { diff --git a/src/openhuman/config/schema/scheduler_gate.rs b/src/openhuman/config/schema/scheduler_gate.rs index 7c7b3d800..06143a0fa 100644 --- a/src/openhuman/config/schema/scheduler_gate.rs +++ b/src/openhuman/config/schema/scheduler_gate.rs @@ -7,8 +7,10 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum SchedulerGateMode { /// Decide based on power + CPU + deployment-mode signals. + #[default] Auto, /// Always run background AI flat-out (server / power-user setting). AlwaysOn, @@ -26,12 +28,6 @@ impl SchedulerGateMode { } } -impl Default for SchedulerGateMode { - fn default() -> Self { - Self::Auto - } -} - #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] pub struct SchedulerGateConfig { diff --git a/src/openhuman/config/schema/storage_memory.rs b/src/openhuman/config/schema/storage_memory.rs index 5b3685768..6c8220347 100644 --- a/src/openhuman/config/schema/storage_memory.rs +++ b/src/openhuman/config/schema/storage_memory.rs @@ -20,19 +20,12 @@ pub struct StorageProviderSection { #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] +#[derive(Default)] pub struct StorageProviderConfig { #[serde(default)] pub provider: String, } -impl Default for StorageProviderConfig { - fn default() -> Self { - Self { - provider: String::new(), - } - } -} - #[derive(Clone, Serialize, Deserialize, JsonSchema)] #[allow(clippy::struct_excessive_bools)] #[serde(default)] @@ -175,8 +168,10 @@ impl std::fmt::Debug for MemoryConfig { /// local-only and isn't governed by this enum. #[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "lowercase")] +#[derive(Default)] pub enum LlmBackend { /// Route through the OpenHuman backend (default). + #[default] Cloud, /// Use the local Ollama path configured via `llm_extractor_*` / /// `llm_summariser_*`. @@ -202,12 +197,6 @@ impl LlmBackend { } } -impl Default for LlmBackend { - fn default() -> Self { - Self::Cloud - } -} - fn default_llm_backend() -> LlmBackend { LlmBackend::default() } diff --git a/src/openhuman/config/schema/tools/mcp.rs b/src/openhuman/config/schema/tools/mcp.rs index c6adf790f..70c70656e 100644 --- a/src/openhuman/config/schema/tools/mcp.rs +++ b/src/openhuman/config/schema/tools/mcp.rs @@ -122,7 +122,9 @@ pub struct HttpHeader { #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(tag = "kind", rename_all = "snake_case")] +#[derive(Default)] pub enum McpAuthConfig { + #[default] None, BearerToken { token: String, @@ -146,12 +148,6 @@ pub enum McpAuthConfig { }, } -impl Default for McpAuthConfig { - fn default() -> Self { - Self::None - } -} - #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] pub struct McpClientIdentityConfig { diff --git a/src/openhuman/config/schema/tools/mod.rs b/src/openhuman/config/schema/tools/mod.rs index 46c11ad67..72ab773b1 100644 --- a/src/openhuman/config/schema/tools/mod.rs +++ b/src/openhuman/config/schema/tools/mod.rs @@ -12,11 +12,11 @@ pub use http::{CurlConfig, HttpRequestConfig}; pub use integrations::{ ComposioConfig, ComputerControlConfig, IntegrationToggle, IntegrationsConfig, PolymarketClobCredentials, PolymarketConfig, SecretsConfig, COMPOSIO_MODE_BACKEND, - COMPOSIO_MODE_DIRECT, INTEGRATION_MODE_BYO, INTEGRATION_MODE_MANAGED, + COMPOSIO_MODE_DIRECT, }; pub use mcp::{ GitbooksConfig, HttpHeader, McpAuthConfig, McpClientConfig, McpClientIdentityConfig, - McpRegistryAuthConfig, McpServerConfig, + McpServerConfig, }; pub use multimodal::{MultimodalConfig, MultimodalFileConfig}; pub use search::{ diff --git a/src/openhuman/config/schema/update.rs b/src/openhuman/config/schema/update.rs index 5aee47c86..dd0a13236 100644 --- a/src/openhuman/config/schema/update.rs +++ b/src/openhuman/config/schema/update.rs @@ -6,19 +6,15 @@ use serde::{Deserialize, Serialize}; /// How `update.run` should complete after staging a new binary. #[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum UpdateRestartStrategy { /// Request an in-process self-restart immediately after staging. + #[default] SelfReplace, /// Stage the new binary and leave restart to an external supervisor. Supervisor, } -impl Default for UpdateRestartStrategy { - fn default() -> Self { - Self::SelfReplace - } -} - /// Configuration for periodic self-update checks against GitHub Releases. #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(default)] diff --git a/src/openhuman/config/schemas/mod.rs b/src/openhuman/config/schemas/mod.rs index f44ff11f4..1518fa719 100644 --- a/src/openhuman/config/schemas/mod.rs +++ b/src/openhuman/config/schemas/mod.rs @@ -3,7 +3,6 @@ mod helpers; mod schema_defs; pub use controllers::{all_controller_schemas, all_registered_controllers}; -pub use schema_defs::schemas; // Re-export items that schemas_tests.rs accesses via `use super::*`. // The test module is `schemas::tests` so `super::` resolves to `schemas`. diff --git a/src/openhuman/credentials/profiles.rs b/src/openhuman/credentials/profiles.rs index 42938606f..8258f1b9f 100644 --- a/src/openhuman/credentials/profiles.rs +++ b/src/openhuman/credentials/profiles.rs @@ -1263,7 +1263,7 @@ impl AuthProfilesStore { let is_already_exists = e .chain() .find_map(|e| e.downcast_ref::()) - .map_or(false, |ioe| ioe.kind() == std::io::ErrorKind::AlreadyExists); + .is_some_and(|ioe| ioe.kind() == std::io::ErrorKind::AlreadyExists); if is_already_exists { // A lock file recording our own pid can only be a @@ -1374,15 +1374,14 @@ impl AuthProfilesStore { .modified() .ok() .and_then(|mtime| std::time::SystemTime::now().duration_since(mtime).ok()); - let too_old = age.map_or(false, |a| a >= Duration::from_millis(STALE_LOCK_AGE_MS)); + let too_old = age.is_some_and(|a| a >= Duration::from_millis(STALE_LOCK_AGE_MS)); // A pidless lock needs only a short grace: no healthy holder leaves the // file without a `pid=` line for more than the microsecond gap between // `create_new` and the write, so anything older is abandoned. If mtime // is unreadable (clock skew, platform limitation) default to stale — // no legitimate in-flight writer would be undetectable for that long. - let malformed_too_old = age.map_or(true, |a| { - a >= Duration::from_millis(MALFORMED_LOCK_GRACE_MS) - }); + let malformed_too_old = + age.is_none_or(|a| a >= Duration::from_millis(MALFORMED_LOCK_GRACE_MS)); let content = match fs::read_to_string(&self.lock_path) { Ok(s) => s, @@ -1616,7 +1615,7 @@ fn in_process_lock_for(path: &Path) -> &'static Mutex<()> { .unwrap_or_else(|poisoned| poisoned.into_inner()); // Deref the `&mut &'static Mutex<()>` to copy the `'static` reference out, // so the returned handle is not tied to the dropped `map` guard. - *map.entry(key) + map.entry(key) .or_insert_with(|| &*Box::leak(Box::new(Mutex::new(())))) } diff --git a/src/openhuman/cron/scheduler.rs b/src/openhuman/cron/scheduler.rs index 09d9a2003..296cd5146 100644 --- a/src/openhuman/cron/scheduler.rs +++ b/src/openhuman/cron/scheduler.rs @@ -636,9 +636,7 @@ async fn execute_job_with_retry( && !local_unreachable && !permanent_config_halt { - let report_message = last_agent_error - .as_deref() - .unwrap_or_else(|| last_output.as_str()); + let report_message = last_agent_error.as_deref().unwrap_or(last_output.as_str()); crate::core::observability::report_error( report_message, "cron", @@ -1188,29 +1186,28 @@ async fn deliver_if_configured( // Announce delivery — the cron job specifies the exact channel // and target. Used for explicit channel-targeted output. - "announce" => { - if deliver_to_chat { - let channel = delivery.channel.as_deref().ok_or_else(|| { - anyhow::anyhow!("delivery.channel is required for announce mode") - })?; - let target = delivery - .to - .as_deref() - .ok_or_else(|| anyhow::anyhow!("delivery.to is required for announce mode"))?; + "announce" if deliver_to_chat => { + let channel = delivery + .channel + .as_deref() + .ok_or_else(|| anyhow::anyhow!("delivery.channel is required for announce mode"))?; + let target = delivery + .to + .as_deref() + .ok_or_else(|| anyhow::anyhow!("delivery.to is required for announce mode"))?; - tracing::debug!( - job_id = %job.id, - channel = %channel, - target = %target, - "[cron] publishing CronDeliveryRequested event" - ); - publish_global(DomainEvent::CronDeliveryRequested { - job_id: job.id.clone(), - channel: channel.to_string(), - target: target.to_string(), - output: output.to_string(), - }); - } + tracing::debug!( + job_id = %job.id, + channel = %channel, + target = %target, + "[cron] publishing CronDeliveryRequested event" + ); + publish_global(DomainEvent::CronDeliveryRequested { + job_id: job.id.clone(), + channel: channel.to_string(), + target: target.to_string(), + output: output.to_string(), + }); } // No delivery configured — output is stored in last_output only. diff --git a/src/openhuman/cwd_jail/macos.rs b/src/openhuman/cwd_jail/macos.rs index 227c028e3..04f464544 100644 --- a/src/openhuman/cwd_jail/macos.rs +++ b/src/openhuman/cwd_jail/macos.rs @@ -15,6 +15,12 @@ use super::jail::{Jail, JailBackend}; pub struct SeatbeltBackend; +impl Default for SeatbeltBackend { + fn default() -> Self { + Self::new() + } +} + impl SeatbeltBackend { pub fn new() -> Self { Self diff --git a/src/openhuman/desktop_companion/handoff.rs b/src/openhuman/desktop_companion/handoff.rs index 9ac482cb9..5bf413724 100644 --- a/src/openhuman/desktop_companion/handoff.rs +++ b/src/openhuman/desktop_companion/handoff.rs @@ -81,7 +81,7 @@ pub(crate) fn check_handoff_with_items( let matched = if keyword.contains(' ') { lower.contains(keyword) } else { - tokens.iter().any(|t| *t == keyword) + tokens.contains(&keyword) }; if !matched { continue; diff --git a/src/openhuman/desktop_companion/session.rs b/src/openhuman/desktop_companion/session.rs index 3438f4738..ecfec233d 100644 --- a/src/openhuman/desktop_companion/session.rs +++ b/src/openhuman/desktop_companion/session.rs @@ -93,7 +93,7 @@ pub fn start_session( drop(guard); // Publish session-started event for Socket.IO bridge / subscribers. - let _ = crate::core::event_bus::publish_global( + crate::core::event_bus::publish_global( crate::core::event_bus::DomainEvent::CompanionSessionStarted { session_id: session_id.clone(), ttl_secs, @@ -125,7 +125,7 @@ pub fn stop_session( ); drop(guard); - let _ = crate::core::event_bus::publish_global( + crate::core::event_bus::publish_global( crate::core::event_bus::DomainEvent::CompanionSessionEnded { session_id, reason: reason.clone(), @@ -170,7 +170,7 @@ pub fn session_status() -> CompanionSessionStatus { info!( "{LOG_PREFIX} auto-expiring stale session id={stale_id} turns={turn_count}" ); - let _ = crate::core::event_bus::publish_global( + crate::core::event_bus::publish_global( crate::core::event_bus::DomainEvent::CompanionSessionEnded { session_id: stale_id, reason: "ttl_expired".into(), diff --git a/src/openhuman/devices/bus.rs b/src/openhuman/devices/bus.rs index ceefa92d7..d3426374a 100644 --- a/src/openhuman/devices/bus.rs +++ b/src/openhuman/devices/bus.rs @@ -240,7 +240,7 @@ async fn handle_tunnel_frame(channel_id: &str, payload_b64: &str) { }; // Decrypt: nonce(24) || ciphertext+tag at offset 33. let inner_frame = &frame_bytes[33..]; - match { + let res = { // TunnelCipher::open expects version(1)||nonce(24)||ct+tag, but we already // stripped the eph_pub prefix. Reconstruct a plain open call by using // XChaCha20 directly on nonce||ct (inner_frame). @@ -256,7 +256,8 @@ async fn handle_tunnel_frame(channel_id: &str, payload_b64: &str) { aead.decrypt(nonce, &inner_frame[24..]) .map_err(|_| "[devices/bus] AEAD decrypt failed on handshake frame".to_string()) } - } { + }; + match res { Ok(plaintext_bytes) => match String::from_utf8(plaintext_bytes) { Ok(s) => parse_handshake_payload(&s), Err(_) => { diff --git a/src/openhuman/embeddings/ollama.rs b/src/openhuman/embeddings/ollama.rs index 29ce9e008..b90013270 100644 --- a/src/openhuman/embeddings/ollama.rs +++ b/src/openhuman/embeddings/ollama.rs @@ -457,7 +457,7 @@ impl EmbeddingProvider for OllamaEmbedding { // Reconstruct full-length result with zero-vectors for blank positions. let mut result = vec![Vec::new(); texts.len()]; - for ((orig_idx, _), embedding) in live.iter().zip(payload.embeddings.into_iter()) { + for ((orig_idx, _), embedding) in live.iter().zip(payload.embeddings) { result[*orig_idx] = embedding; } diff --git a/src/openhuman/file_state/types.rs b/src/openhuman/file_state/types.rs index 1e93ea65e..fc81bf39b 100644 --- a/src/openhuman/file_state/types.rs +++ b/src/openhuman/file_state/types.rs @@ -42,6 +42,12 @@ pub struct FileStateCoordinator { pub(crate) path_locks: RwLock>>>, } +impl Default for FileStateCoordinator { + fn default() -> Self { + Self::new() + } +} + impl FileStateCoordinator { pub fn new() -> Self { Self { diff --git a/src/openhuman/flows/builder_tools.rs b/src/openhuman/flows/builder_tools.rs index 906b0d457..c0b9127df 100644 --- a/src/openhuman/flows/builder_tools.rs +++ b/src/openhuman/flows/builder_tools.rs @@ -1319,15 +1319,16 @@ impl Tool for DryRunWorkflowTool { .iter() .filter(|step| tool_call_node_ids.contains(step.node_id.as_str())) .flat_map(|step| { - step.diagnostics.iter().filter_map(|diag| { - (diag.location == "args" || diag.location.starts_with("args.")).then(|| { + step.diagnostics + .iter() + .filter(|&diag| (diag.location == "args" || diag.location.starts_with("args."))) + .map(|diag| { json!({ "node_id": step.node_id, "location": diag.location, "expression": diag.expression, }) }) - }) }) .collect(); @@ -1345,8 +1346,10 @@ impl Tool for DryRunWorkflowTool { .iter() .filter(|step| agent_node_ids.contains(step.node_id.as_str())) .flat_map(|step| { - step.diagnostics.iter().filter_map(|diag| { - (diag.location == "prompt").then(|| { + step.diagnostics + .iter() + .filter(|&diag| (diag.location == "prompt")) + .map(|diag| { json!({ "node_id": step.node_id, "location": diag.location, @@ -1355,7 +1358,6 @@ impl Tool for DryRunWorkflowTool { make the prompt a plain instruction.", }) }) - }) }) .collect(); @@ -1370,8 +1372,10 @@ impl Tool for DryRunWorkflowTool { .iter() .filter(|step| agent_node_ids.contains(step.node_id.as_str())) .flat_map(|step| { - step.diagnostics.iter().filter_map(|diag| { - (diag.location == "input_context").then(|| { + step.diagnostics + .iter() + .filter(|&diag| (diag.location == "input_context")) + .map(|diag| { json!({ "node_id": step.node_id, "location": diag.location, @@ -1381,7 +1385,6 @@ impl Tool for DryRunWorkflowTool { trigger), not an expression that resolves to null.", }) }) - }) }) .collect(); diff --git a/src/openhuman/flows/discovery_tools.rs b/src/openhuman/flows/discovery_tools.rs index 1187d72c6..715c63dbf 100644 --- a/src/openhuman/flows/discovery_tools.rs +++ b/src/openhuman/flows/discovery_tools.rs @@ -79,7 +79,7 @@ fn read_string_array(v: &Value, key: &str) -> Vec { .filter_map(|e| e.as_str()) .map(str::trim) .filter(|s| !s.is_empty()) - .map(|s| truncate(s)) + .map(truncate) .collect() }) .unwrap_or_default() diff --git a/src/openhuman/flows/ops.rs b/src/openhuman/flows/ops.rs index e4ab5c7fe..b487efd91 100644 --- a/src/openhuman/flows/ops.rs +++ b/src/openhuman/flows/ops.rs @@ -1443,7 +1443,7 @@ fn title_case_toolkit(toolkit: &str) -> String { return String::new(); } trimmed - .split(|c| c == '_' || c == '-' || c == ' ') + .split(['_', '-', ' ']) .filter(|w| !w.is_empty()) .map(|word| { let mut chars = word.chars(); diff --git a/src/openhuman/flows/types.rs b/src/openhuman/flows/types.rs index 1afc4e836..5c6837650 100644 --- a/src/openhuman/flows/types.rs +++ b/src/openhuman/flows/types.rs @@ -234,8 +234,10 @@ pub struct FlowRun { /// actually saved via `flows_create`, the frontend marks it `Built`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum SuggestionStatus { /// Freshly discovered, awaiting the user's decision. The default. + #[default] New, /// The user dismissed the card; kept for dedupe, never re-surfaced. Dismissed, @@ -243,12 +245,6 @@ pub enum SuggestionStatus { Built, } -impl Default for SuggestionStatus { - fn default() -> Self { - Self::New - } -} - impl SuggestionStatus { /// The stable lowercase token persisted in SQLite / crossed over RPC. pub fn as_str(self) -> &'static str { diff --git a/src/openhuman/inference/local/mod.rs b/src/openhuman/inference/local/mod.rs index 1ae22b92a..2943c2fc4 100644 --- a/src/openhuman/inference/local/mod.rs +++ b/src/openhuman/inference/local/mod.rs @@ -41,7 +41,6 @@ mod ollama; pub(crate) mod process_util; pub mod profile; pub(crate) mod provider; -pub(crate) use model_requirements::{evaluate_context, ContextEligibility, MIN_CONTEXT_TOKENS}; pub(crate) use ollama::{ ollama_base_url, ollama_base_url_from_config, validate_ollama_url, OLLAMA_BASE_URL, }; diff --git a/src/openhuman/inference/local/service/ollama_admin/mod.rs b/src/openhuman/inference/local/service/ollama_admin/mod.rs index 69ebd0ff3..391360255 100644 --- a/src/openhuman/inference/local/service/ollama_admin/mod.rs +++ b/src/openhuman/inference/local/service/ollama_admin/mod.rs @@ -7,8 +7,6 @@ mod server; mod util; // Re-export free functions that form the public/crate API of this module. -pub(crate) use util::interrupted_pull_settle_window_secs; -pub(crate) use util::kill_pid_by_id; pub(crate) use util::test_ollama_connection; #[cfg(test)] diff --git a/src/openhuman/inference/provider/compatible.rs b/src/openhuman/inference/provider/compatible.rs index f902a0c90..1ba0a1a15 100644 --- a/src/openhuman/inference/provider/compatible.rs +++ b/src/openhuman/inference/provider/compatible.rs @@ -388,7 +388,7 @@ pub(crate) fn prompt_cache_for_compatible_slug( // `openai:gpt-5.1` style slug still resolves to the `openai` family. let normalized = slug.trim().to_ascii_lowercase(); let family = normalized - .split(|c| c == ':' || c == '/' || c == '-') + .split([':', '/', '-']) .next() .unwrap_or("") .trim(); diff --git a/src/openhuman/inference/provider/compatible_helpers.rs b/src/openhuman/inference/provider/compatible_helpers.rs index b648605ae..fe7281b4d 100644 --- a/src/openhuman/inference/provider/compatible_helpers.rs +++ b/src/openhuman/inference/provider/compatible_helpers.rs @@ -9,8 +9,7 @@ use super::compatible_parse::{ parse_tool_calls_from_content_json, }; use super::compatible_types::{ - ApiChatResponse, Message, MessageContent, NativeChatRequest, NativeMessage, ResponsesRequest, - ToolCall, + ApiChatResponse, MessageContent, NativeMessage, ResponsesRequest, ToolCall, }; use super::OpenAiCompatibleProvider; diff --git a/src/openhuman/inference/provider/compatible_stream_native.rs b/src/openhuman/inference/provider/compatible_stream_native.rs index 99ec9b6dc..5415fab0f 100644 --- a/src/openhuman/inference/provider/compatible_stream_native.rs +++ b/src/openhuman/inference/provider/compatible_stream_native.rs @@ -4,7 +4,7 @@ use crate::openhuman::inference::provider::ProviderDelta; use super::compatible_dump::dump_response_if_enabled; use super::compatible_repeat::{StreamRepeatDetector, STREAM_REPEAT_THRESHOLD}; use super::compatible_types::{ - ApiChatResponse, ApiUsage, Choice, Function, NativeChatRequest, OpenHumanMeta, ResponseMessage, + ApiChatResponse, ApiUsage, Choice, NativeChatRequest, OpenHumanMeta, ResponseMessage, StreamChunkResponse, StreamingToolCall, ToolCall, }; use super::OpenAiCompatibleProvider; diff --git a/src/openhuman/inference/provider/factory.rs b/src/openhuman/inference/provider/factory.rs index cd57c8bb2..15f2d67ff 100644 --- a/src/openhuman/inference/provider/factory.rs +++ b/src/openhuman/inference/provider/factory.rs @@ -2100,7 +2100,7 @@ pub(super) fn redact_endpoint(url: &str) -> String { if let Some(rest) = trimmed.split_once("://") { let scheme = rest.0; let authority = rest.1.split('/').next().unwrap_or(""); - let host = authority.split('@').last().unwrap_or(authority); + let host = authority.split('@').next_back().unwrap_or(authority); let host_no_query = host.split('?').next().unwrap_or(host); return format!("{}://{}", scheme, host_no_query); } diff --git a/src/openhuman/inference/provider/ops/models.rs b/src/openhuman/inference/provider/ops/models.rs index 628a4d7f7..f4faeda82 100644 --- a/src/openhuman/inference/provider/ops/models.rs +++ b/src/openhuman/inference/provider/ops/models.rs @@ -311,7 +311,7 @@ pub fn parse_models_response(body: &serde_json::Value) -> Result, let is_success_envelope = obj .get("object") .and_then(|value| value.as_str()) - .map_or(true, |object| object.eq_ignore_ascii_case("list")); + .is_none_or(|object| object.eq_ignore_ascii_case("list")); if data_value.is_null() && is_success_envelope { log::info!( diff --git a/src/openhuman/inference/provider/reliable.rs b/src/openhuman/inference/provider/reliable.rs index 822b1c7f0..526bc41a1 100644 --- a/src/openhuman/inference/provider/reliable.rs +++ b/src/openhuman/inference/provider/reliable.rs @@ -21,7 +21,7 @@ //! wrapper stays authoritative for single-attempt retry on the live path. use super::traits::{ - ChatMessage, ChatRequest, ChatResponse, StreamChunk, StreamError, StreamOptions, StreamResult, + ChatMessage, ChatRequest, ChatResponse, StreamChunk, StreamOptions, StreamResult, }; use super::Provider; use crate::openhuman::inference::provider::record_resolved_provider_route; @@ -243,18 +243,19 @@ impl Provider for ReliableProvider { ); // On rate-limit, try rotating API key - if rate_limited && !non_retryable_rate_limit { - if self.rotate_key().is_some() { - tracing::info!( - provider = provider_name, - error = %error_detail, - key_slot = %rotated_key_log_detail( - self.key_index.load(Ordering::Relaxed), - self.api_keys.len() - ), - "Rate limited, rotated API key" - ); - } + if rate_limited + && !non_retryable_rate_limit + && self.rotate_key().is_some() + { + tracing::info!( + provider = provider_name, + error = %error_detail, + key_slot = %rotated_key_log_detail( + self.key_index.load(Ordering::Relaxed), + self.api_keys.len() + ), + "Rate limited, rotated API key" + ); } if non_retryable { @@ -379,18 +380,19 @@ impl Provider for ReliableProvider { &error_detail, ); - if rate_limited && !non_retryable_rate_limit { - if self.rotate_key().is_some() { - tracing::info!( - provider = provider_name, - error = %error_detail, - key_slot = %rotated_key_log_detail( - self.key_index.load(Ordering::Relaxed), - self.api_keys.len() - ), - "Rate limited, rotated API key" - ); - } + if rate_limited + && !non_retryable_rate_limit + && self.rotate_key().is_some() + { + tracing::info!( + provider = provider_name, + error = %error_detail, + key_slot = %rotated_key_log_detail( + self.key_index.load(Ordering::Relaxed), + self.api_keys.len() + ), + "Rate limited, rotated API key" + ); } if non_retryable { @@ -544,18 +546,19 @@ impl Provider for ReliableProvider { &error_detail, ); - if rate_limited && !non_retryable_rate_limit { - if self.rotate_key().is_some() { - tracing::info!( - provider = provider_name, - error = %error_detail, - key_slot = %rotated_key_log_detail( - self.key_index.load(Ordering::Relaxed), - self.api_keys.len() - ), - "Rate limited, rotated API key" - ); - } + if rate_limited + && !non_retryable_rate_limit + && self.rotate_key().is_some() + { + tracing::info!( + provider = provider_name, + error = %error_detail, + key_slot = %rotated_key_log_detail( + self.key_index.load(Ordering::Relaxed), + self.api_keys.len() + ), + "Rate limited, rotated API key" + ); } if non_retryable { @@ -673,18 +676,19 @@ impl Provider for ReliableProvider { &error_detail, ); - if rate_limited && !non_retryable_rate_limit { - if self.rotate_key().is_some() { - tracing::info!( - provider = provider_name, - error = %error_detail, - key_slot = %rotated_key_log_detail( - self.key_index.load(Ordering::Relaxed), - self.api_keys.len() - ), - "Rate limited, rotated API key" - ); - } + if rate_limited + && !non_retryable_rate_limit + && self.rotate_key().is_some() + { + tracing::info!( + provider = provider_name, + error = %error_detail, + key_slot = %rotated_key_log_detail( + self.key_index.load(Ordering::Relaxed), + self.api_keys.len() + ), + "Rate limited, rotated API key" + ); } if non_retryable { diff --git a/src/openhuman/keyring/crypto.rs b/src/openhuman/keyring/crypto.rs index 318b37106..f92bde10f 100644 --- a/src/openhuman/keyring/crypto.rs +++ b/src/openhuman/keyring/crypto.rs @@ -51,7 +51,7 @@ pub(super) fn hex_encode(data: &[u8]) -> String { /// Decode a hex string into bytes. pub(super) fn hex_decode(hex: &str) -> Result, String> { - if hex.len() % 2 != 0 { + if !hex.len().is_multiple_of(2) { return Err("hex string has odd length".to_string()); } (0..hex.len()) diff --git a/src/openhuman/keyring/encrypted_store.rs b/src/openhuman/keyring/encrypted_store.rs index f2930116a..5f75a2cef 100644 --- a/src/openhuman/keyring/encrypted_store.rs +++ b/src/openhuman/keyring/encrypted_store.rs @@ -294,7 +294,7 @@ impl SecretStore { }; let hex_key = read_result.with_context(|| { - let mut msg = format!( + let msg = format!( "Failed to read secret key file at {}", self.key_path.display() ); diff --git a/src/openhuman/learning/extract/heuristics.rs b/src/openhuman/learning/extract/heuristics.rs index 5ac8a7955..ac44cf6fe 100644 --- a/src/openhuman/learning/extract/heuristics.rs +++ b/src/openhuman/learning/extract/heuristics.rs @@ -232,7 +232,7 @@ pub fn record_turn( // ── B. Edit-window detector ─────────────────────────────────────── if let Some(prev_at) = prev_agent_at { let gap = user_timestamp - prev_at; - if gap >= 0.0 && gap < EDIT_WINDOW_SECS { + if (0.0..EDIT_WINDOW_SECS).contains(&gap) { let lower = user_message.to_ascii_lowercase(); // Pattern → (key, value) pairs. let patterns: &[(&str, &str, &str)] = &[ diff --git a/src/openhuman/learning/extract/signature.rs b/src/openhuman/learning/extract/signature.rs index 95d469a52..2d99eb613 100644 --- a/src/openhuman/learning/extract/signature.rs +++ b/src/openhuman/learning/extract/signature.rs @@ -212,7 +212,7 @@ pub fn parse_signature( if loc_idx < sig_lines.len() { let t = sig_lines[loc_idx].trim(); // Skip if already matched as role or employer. - let already_used = role_line_idx.map_or(false, |ri| ri == loc_idx); + let already_used = role_line_idx == Some(loc_idx); if !already_used { if let Some(loc) = extract_location(t) { candidates.push(LearningCandidate { @@ -361,7 +361,7 @@ fn extract_timezone(s: &str) -> Option<&str> { let after = &s[pos + tz.len()..]; let after_ok = after.is_empty() || after.starts_with(|c: char| !c.is_alphabetic()) - || after.starts_with(|c: char| c == '+' || c == '-'); + || after.starts_with(['+', '-']); if before_ok && after_ok { // Grab "UTC+5:30" or "GMT-7" style suffix. if tz.starts_with("UTC") || tz.starts_with("GMT") { @@ -419,10 +419,10 @@ fn extract_employer_pattern(s: &str) -> Option { ", inc", " inc.", " llc", " ltd", " limited", " corp", " co.", ]; for suffix in corp_suffixes { - if lower.ends_with(suffix) || lower.contains(&format!("{suffix} ")) { - if is_plausible_employer(t) { - return Some(clean_employer(t)); - } + if (lower.ends_with(suffix) || lower.contains(&format!("{suffix} "))) + && is_plausible_employer(t) + { + return Some(clean_employer(t)); } } None @@ -442,7 +442,7 @@ fn extract_location(s: &str) -> Option { // City: 2-30 chars, no digits, starts with uppercase. let city_ok = city.len() >= 2 && city.len() <= 30 - && city.chars().next().map_or(false, |c| c.is_uppercase()) + && city.chars().next().is_some_and(|c| c.is_uppercase()) && !city.chars().any(|c| c.is_ascii_digit()); // Region: 2-20 chars. let region_ok = region.len() >= 2 && region.len() <= 20; diff --git a/src/openhuman/learning/schemas.rs b/src/openhuman/learning/schemas.rs index 02eac4c5f..eb5ac116e 100644 --- a/src/openhuman/learning/schemas.rs +++ b/src/openhuman/learning/schemas.rs @@ -1021,10 +1021,8 @@ fn handle_reset_cache(_params: Map) -> ControllerFuture { // Delete all non-Pinned rows. let mut deleted = 0usize; for f in &all { - if f.user_state != UserState::Pinned { - if cache.delete(&f.key).unwrap_or(false) { - deleted += 1; - } + if f.user_state != UserState::Pinned && cache.delete(&f.key).unwrap_or(false) { + deleted += 1; } } diff --git a/src/openhuman/learning/transcript_ingest/extract.rs b/src/openhuman/learning/transcript_ingest/extract.rs index 0d456ad46..6ca539914 100644 --- a/src/openhuman/learning/transcript_ingest/extract.rs +++ b/src/openhuman/learning/transcript_ingest/extract.rs @@ -166,13 +166,13 @@ fn find_phrase_snippet(original: &str, lower: &str, phrases: &[&str]) -> Option< // "I prefer X"). let prefix = &original[..start]; let sentence_start = prefix - .rfind(|c: char| matches!(c, '.' | '!' | '?' | '\n')) + .rfind(['.', '!', '?', '\n']) .map(|i| i + 1) .unwrap_or(0); let tail = &original[sentence_start..]; let mut end = tail.len(); - if let Some(rel) = tail.find(|c: char| matches!(c, '\n')) { + if let Some(rel) = tail.find('\n') { end = end.min(rel); } if let Some(rel) = tail.find(['.', '!', '?']) { diff --git a/src/openhuman/mcp_client/spawn_env.rs b/src/openhuman/mcp_client/spawn_env.rs index c0f4fa9ab..5401992f4 100644 --- a/src/openhuman/mcp_client/spawn_env.rs +++ b/src/openhuman/mcp_client/spawn_env.rs @@ -288,10 +288,9 @@ fn is_executable_file(path: &Path) -> bool { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; - return path - .metadata() + path.metadata() .map(|meta| meta.permissions().mode() & 0o111 != 0) - .unwrap_or(false); + .unwrap_or(false) } #[cfg(not(unix))] { diff --git a/src/openhuman/mcp_registry/ops.rs b/src/openhuman/mcp_registry/ops.rs index 1f34a0e79..5fa9bf4c5 100644 --- a/src/openhuman/mcp_registry/ops.rs +++ b/src/openhuman/mcp_registry/ops.rs @@ -276,7 +276,7 @@ pub async fn mcp_clients_install( server.qualified_name ); - let _ = publish_global(DomainEvent::McpServerInstalled { + publish_global(DomainEvent::McpServerInstalled { server_id: server_id.clone(), qualified_name: server.qualified_name.clone(), }); @@ -418,7 +418,7 @@ pub async fn mcp_clients_connect( let tool_count = tools.len() as u32; - let _ = publish_global(DomainEvent::McpServerConnected { + publish_global(DomainEvent::McpServerConnected { server_id: server_id.trim().to_string(), tool_count, }); @@ -471,7 +471,7 @@ pub async fn mcp_clients_set_enabled( if !enabled { connections::disconnect(&server_id).await; connections::clear_last_error(&server_id).await; - let _ = publish_global(DomainEvent::McpServerDisconnected { + publish_global(DomainEvent::McpServerDisconnected { server_id: server_id.clone(), reason: Some("disabled".to_string()), }); @@ -496,7 +496,7 @@ pub async fn mcp_clients_disconnect(server_id: String) -> Result { let tool_count = tools.len() as u32; - let _ = publish_global(DomainEvent::McpServerConnected { + publish_global(DomainEvent::McpServerConnected { server_id: server_id.to_string(), tool_count, }); @@ -786,7 +786,7 @@ pub async fn mcp_clients_tool_call( let elapsed_ms = start.elapsed().as_millis() as u64; let success = result.is_ok(); - let _ = publish_global(DomainEvent::McpClientToolExecuted { + publish_global(DomainEvent::McpClientToolExecuted { server_id: server_id.trim().to_string(), tool_name: tool_name.trim().to_string(), success, diff --git a/src/openhuman/mcp_registry/registries/mcp_official.rs b/src/openhuman/mcp_registry/registries/mcp_official.rs index a3d07744a..269aad977 100644 --- a/src/openhuman/mcp_registry/registries/mcp_official.rs +++ b/src/openhuman/mcp_registry/registries/mcp_official.rs @@ -610,7 +610,7 @@ impl OfficialServer { .map(|(_, s)| s) .or_else(|| raw.rsplit_once('.').map(|(_, s)| s)) .unwrap_or(raw); - segment.replace('-', " ").replace('_', " ") + segment.replace(['-', '_'], " ") } fn into_summary(self) -> SmitheryServerSummary { diff --git a/src/openhuman/mcp_registry/setup_ops.rs b/src/openhuman/mcp_registry/setup_ops.rs index 8df09d128..363a46537 100644 --- a/src/openhuman/mcp_registry/setup_ops.rs +++ b/src/openhuman/mcp_registry/setup_ops.rs @@ -93,7 +93,7 @@ pub async fn mcp_setup_request_secret( let (r, rx) = setup::mint_request(&key_name).await; - let _ = publish_global(DomainEvent::McpSetupSecretRequested { + publish_global(DomainEvent::McpSetupSecretRequested { ref_id: r.as_str().to_string(), key_name: key_name.clone(), prompt: prompt.clone(), @@ -308,7 +308,7 @@ pub async fn mcp_setup_install_and_connect( store::insert_server(config, &server).map_err(|e| e.to_string())?; store::set_env_values(config, &server_id, &env_map).map_err(|e| e.to_string())?; - let _ = publish_global(DomainEvent::McpServerInstalled { + publish_global(DomainEvent::McpServerInstalled { server_id: server_id.clone(), qualified_name: server.qualified_name.clone(), }); diff --git a/src/openhuman/mcp_registry/store.rs b/src/openhuman/mcp_registry/store.rs index 5d435d763..f9cfa6517 100644 --- a/src/openhuman/mcp_registry/store.rs +++ b/src/openhuman/mcp_registry/store.rs @@ -296,7 +296,7 @@ pub fn update_server_config_conn( } pub fn list_servers(config: &Config) -> Result> { - with_connection(config, |conn| list_servers_conn(conn)) + with_connection(config, list_servers_conn) } pub fn list_servers_conn(conn: &Connection) -> Result> { diff --git a/src/openhuman/mcp_server/http.rs b/src/openhuman/mcp_server/http.rs index 81e04fd5d..d79e8a26c 100644 --- a/src/openhuman/mcp_server/http.rs +++ b/src/openhuman/mcp_server/http.rs @@ -146,7 +146,7 @@ async fn handle_post( record.protocol_version.clone() }; - if protocol_version.as_deref() != Some(expected_protocol.as_str()) { + if protocol_version != Some(expected_protocol.as_str()) { log_request_rejected( "protocol mismatch", Some(session_id), @@ -245,7 +245,7 @@ async fn handle_get(State(state): State, headers: HeaderMap) -> Respon record.protocol_version.clone() }; - if protocol_version.as_deref() != Some(expected_protocol.as_str()) { + if protocol_version != Some(expected_protocol.as_str()) { log_request_rejected( "protocol mismatch", Some(session_id), diff --git a/src/openhuman/mcp_server/tools/dispatch.rs b/src/openhuman/mcp_server/tools/dispatch.rs index 7832d09db..e1b6cf0f1 100644 --- a/src/openhuman/mcp_server/tools/dispatch.rs +++ b/src/openhuman/mcp_server/tools/dispatch.rs @@ -10,8 +10,7 @@ use crate::openhuman::security::{SecurityPolicy, ToolOperation}; use super::super::write_dispatch; use super::params::{build_rpc_params, validate_controller_params}; use super::specs::{ - base_tool_specs, list_tools_result_for_config, list_tools_result_from_specs, searxng_tool_spec, - tool_specs, + base_tool_specs, list_tools_result_for_config, list_tools_result_from_specs, tool_specs, }; use super::types::ToolCallError; diff --git a/src/openhuman/mcp_server/tools/mod.rs b/src/openhuman/mcp_server/tools/mod.rs index acf6f012c..da91c54dc 100644 --- a/src/openhuman/mcp_server/tools/mod.rs +++ b/src/openhuman/mcp_server/tools/mod.rs @@ -13,10 +13,7 @@ mod types; // Public API consumed by the rest of `mcp_server` pub use dispatch::{call_tool, list_tools_result, tool_error, tool_success}; -pub use specs::{ - base_tool_specs, list_tools_result_for_config, list_tools_result_from_specs, searxng_tool_spec, - tool_specs, -}; +pub use specs::tool_specs; pub use types::{McpToolSpec, ToolCallError}; // Re-exports needed by the companion test module via `use super::*`. diff --git a/src/openhuman/meet_agent/brain/text.rs b/src/openhuman/meet_agent/brain/text.rs index 49b30d413..68af30ed0 100644 --- a/src/openhuman/meet_agent/brain/text.rs +++ b/src/openhuman/meet_agent/brain/text.rs @@ -56,7 +56,7 @@ pub(crate) fn strip_for_speech(text: &str) -> String { continue; } let cleaned: String = trimmed - .trim_start_matches(|c: char| c == '-' || c == '*' || c == '#' || c == '>') + .trim_start_matches(['-', '*', '#', '>']) .trim() .chars() .filter(|c| !matches!(c, '*' | '`' | '_' | '#')) @@ -112,7 +112,7 @@ pub(super) fn strip_untagged_reasoning(text: &str) -> String { "responding with", ]; let sentences: Vec<&str> = text - .split_inclusive(|c: char| matches!(c, '.' | '!' | '?')) + .split_inclusive(['.', '!', '?']) .map(str::trim) .filter(|s| !s.is_empty()) .collect(); diff --git a/src/openhuman/memory/chat.rs b/src/openhuman/memory/chat.rs index 1beea7f4d..0f9016f4f 100644 --- a/src/openhuman/memory/chat.rs +++ b/src/openhuman/memory/chat.rs @@ -11,7 +11,7 @@ use std::sync::Arc; use anyhow::Result; use async_trait::async_trait; -use crate::openhuman::config::{Config, DEFAULT_CLOUD_LLM_MODEL}; +use crate::openhuman::config::Config; use crate::openhuman::inference::provider::{ create_chat_model_with_model_id, provider_for_role, UsageInfo, }; diff --git a/src/openhuman/memory/ingest_pipeline.rs b/src/openhuman/memory/ingest_pipeline.rs index 614bd63d1..09e522ea3 100644 --- a/src/openhuman/memory/ingest_pipeline.rs +++ b/src/openhuman/memory/ingest_pipeline.rs @@ -279,7 +279,7 @@ async fn persist( let all_results: Vec<(ScoreResult, i64)> = chunks .iter() - .zip(scores.into_iter()) + .zip(scores) .map(|(chunk, result)| (result, chunk.metadata.timestamp.timestamp_millis())) .collect(); let dropped = all_results.iter().filter(|(r, _)| !r.kept).count(); diff --git a/src/openhuman/memory/read_rpc/admin.rs b/src/openhuman/memory/read_rpc/admin.rs index 04bf74738..e9d2f6339 100644 --- a/src/openhuman/memory/read_rpc/admin.rs +++ b/src/openhuman/memory/read_rpc/admin.rs @@ -85,7 +85,7 @@ pub async fn wipe_all_rpc(config: &Config) -> Result let is_not_found = e .chain() .find_map(|e| e.downcast_ref::()) - .map_or(false, |ioe| ioe.kind() == std::io::ErrorKind::NotFound); + .is_some_and(|ioe| ioe.kind() == std::io::ErrorKind::NotFound); if !is_not_found { log::warn!( "[memory_tree::read::wipe] failed to remove dir={} err={:#}", @@ -213,7 +213,7 @@ pub async fn reset_tree_rpc(config: &Config) -> Result()) - .map_or(false, |ioe| ioe.kind() == std::io::ErrorKind::NotFound); + .is_some_and(|ioe| ioe.kind() == std::io::ErrorKind::NotFound); if !is_not_found { log::warn!( "[memory_tree::read::reset_tree] failed to remove wiki/summaries: {:#}", @@ -245,7 +245,7 @@ pub async fn flush_source_tree_rpc( source_scope: &str, ) -> Result, String> { use crate::openhuman::memory::tree_source::get_or_create_source_tree; - use crate::openhuman::memory_tree::tree::bucket_seal::LabelStrategy; + use crate::openhuman::memory_tree::tree::flush::force_flush_tree; use crate::openhuman::memory_tree::tree::TreeFactory; use std::collections::HashSet; diff --git a/src/openhuman/memory/read_rpc/graph.rs b/src/openhuman/memory/read_rpc/graph.rs index 50beee24d..98f41395c 100644 --- a/src/openhuman/memory/read_rpc/graph.rs +++ b/src/openhuman/memory/read_rpc/graph.rs @@ -371,8 +371,7 @@ fn collect_contacts_graph(cfg: &Config) -> Result<(Vec, Vec = if chunk_ids.is_empty() { Vec::new() } else { - let placeholders = std::iter::repeat("?") - .take(chunk_ids.len()) + let placeholders = std::iter::repeat_n("?", chunk_ids.len()) .collect::>() .join(","); let sql = format!( diff --git a/src/openhuman/memory/schema/mod.rs b/src/openhuman/memory/schema/mod.rs index 156eeeffa..21c62c764 100644 --- a/src/openhuman/memory/schema/mod.rs +++ b/src/openhuman/memory/schema/mod.rs @@ -27,7 +27,6 @@ pub use registry::{all_controller_schemas, all_registered_controllers}; // Re-export the NAMESPACE constant so schema_tests.rs can reference it via // `super::NAMESPACE` the same way the original flat module did. -pub(crate) use definitions::NAMESPACE; #[cfg(test)] #[path = "../schema_tests.rs"] diff --git a/src/openhuman/memory/tree_source/file.rs b/src/openhuman/memory/tree_source/file.rs index 2ef587135..b91ada735 100644 --- a/src/openhuman/memory/tree_source/file.rs +++ b/src/openhuman/memory/tree_source/file.rs @@ -32,7 +32,7 @@ use chrono::{DateTime, Utc}; use crate::openhuman::config::Config; use crate::openhuman::memory_store::content::raw::raw_source_dir; -use crate::openhuman::memory_store::trees::types::{Tree, TreeKind, TreeStatus}; +use crate::openhuman::memory_store::trees::types::Tree; /// Filename of the per-source registry mirror inside `raw//`. pub const SOURCE_FILE_NAME: &str = "_source.md"; diff --git a/src/openhuman/memory_conversations/inverted_index.rs b/src/openhuman/memory_conversations/inverted_index.rs index 57a657719..10986b937 100644 --- a/src/openhuman/memory_conversations/inverted_index.rs +++ b/src/openhuman/memory_conversations/inverted_index.rs @@ -258,7 +258,7 @@ impl InvertedIndex { // Phase 2: verify each candidate by exact substring match. // Count distinct terms per doc for the score. let mut hit_counts: HashMap = HashMap::new(); - for (term, candidates) in terms.iter().zip(per_term.into_iter()) { + for (term, candidates) in terms.iter().zip(per_term) { for doc_id in candidates { let Some(entry) = self.docs[doc_id as usize].as_ref() else { continue; diff --git a/src/openhuman/memory_entities/store.rs b/src/openhuman/memory_entities/store.rs index 74fbf565e..a37deba11 100644 --- a/src/openhuman/memory_entities/store.rs +++ b/src/openhuman/memory_entities/store.rs @@ -5,7 +5,7 @@ //! upserts so the user can hand-edit it in Obsidian without losing edits. use std::fs; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; diff --git a/src/openhuman/memory_queue/worker.rs b/src/openhuman/memory_queue/worker.rs index 6f476dcd2..fea5f15db 100644 --- a/src/openhuman/memory_queue/worker.rs +++ b/src/openhuman/memory_queue/worker.rs @@ -363,7 +363,7 @@ fn settle_job(config: &Config, job: &Job, result: Result) -> Result< job.id, job.kind.as_str() ); - mark_done(config, &job)?; + mark_done(config, job)?; } Ok(JobOutcome::Defer { until_ms, reason }) => { // Defer is normal operation (transient blocker, e.g. rate @@ -382,7 +382,7 @@ fn settle_job(config: &Config, job: &Job, result: Result) -> Result< until_ms, scrub_for_log(&reason) ); - mark_deferred(config, &job, until_ms, &reason)?; + mark_deferred(config, job, until_ms, &reason)?; } Err(err) => { // Preserve the full anyhow cause chain in the persisted @@ -404,7 +404,7 @@ fn settle_job(config: &Config, job: &Job, result: Result) -> Result< typed.map(|f| f.code.as_str()), scrub_for_log(&message) ); - mark_failed_typed(config, &job, &message, typed)?; + mark_failed_typed(config, job, &message, typed)?; } } Ok(()) diff --git a/src/openhuman/memory_search/tools/vector_search.rs b/src/openhuman/memory_search/tools/vector_search.rs index 2c37f4d42..ad04fa412 100644 --- a/src/openhuman/memory_search/tools/vector_search.rs +++ b/src/openhuman/memory_search/tools/vector_search.rs @@ -196,7 +196,7 @@ impl Tool for MemoryVectorSearchTool { .iter() .map(|(idx, score, emb)| MmrCandidate { index: *idx, - embedding: *emb, + embedding: emb, relevance: *score, }) .collect(); diff --git a/src/openhuman/memory_sources/rpc.rs b/src/openhuman/memory_sources/rpc.rs index f19e41606..191011594 100644 --- a/src/openhuman/memory_sources/rpc.rs +++ b/src/openhuman/memory_sources/rpc.rs @@ -214,10 +214,8 @@ pub fn apply_kind_defaults(entry: &mut MemorySourceEntry) { entry.max_items = Some(20); } } - SourceKind::TwitterQuery => { - if entry.since_days.is_none() { - entry.since_days = Some(7); - } + SourceKind::TwitterQuery if entry.since_days.is_none() => { + entry.since_days = Some(7); } // Folder / WebPage / Composio: no defaults to apply here. // Composio defaults are set at upsert time in registry::upsert_composio_source. diff --git a/src/openhuman/memory_sources/sync.rs b/src/openhuman/memory_sources/sync.rs index 5df2b6cf2..402bc1d72 100644 --- a/src/openhuman/memory_sources/sync.rs +++ b/src/openhuman/memory_sources/sync.rs @@ -435,7 +435,7 @@ async fn sync_items_individually( let done = processed.fetch_add(1, Ordering::Relaxed) + 1; let new = ingested.load(Ordering::Relaxed); - if done % 10 == 0 || done == total { + if done.is_multiple_of(10) || done == total { emit_sync_stage( MemorySyncTrigger::Manual, MemorySyncStage::Ingesting, diff --git a/src/openhuman/memory_store/chunks/connection.rs b/src/openhuman/memory_store/chunks/connection.rs index df8bbfcf8..961b92eff 100644 --- a/src/openhuman/memory_store/chunks/connection.rs +++ b/src/openhuman/memory_store/chunks/connection.rs @@ -479,7 +479,7 @@ pub(crate) fn get_or_init_connection(config: &Config) -> Result Result Result Vec { } else { n }; - let piece_lines: Vec<&str> = lines[start..end].iter().copied().collect(); + let piece_lines: Vec<&str> = lines[start..end].to_vec(); let piece = piece_lines.join("\n").trim_end().to_string(); if !piece.is_empty() { pieces.push(piece); diff --git a/src/openhuman/memory_store/content/raw.rs b/src/openhuman/memory_store/content/raw.rs index e8b230b68..12799950e 100644 --- a/src/openhuman/memory_store/content/raw.rs +++ b/src/openhuman/memory_store/content/raw.rs @@ -235,7 +235,7 @@ pub fn slug_account_email(email: &str) -> String { let mut out = String::with_capacity(lower.len() + 8); let mut last_dash = true; let mut chars = lower.chars().peekable(); - while let Some(ch) = chars.next() { + for ch in chars { match ch { '@' => { if !last_dash { diff --git a/src/openhuman/memory_store/safety/pii.rs b/src/openhuman/memory_store/safety/pii.rs index 87390d509..c6ea8792d 100644 --- a/src/openhuman/memory_store/safety/pii.rs +++ b/src/openhuman/memory_store/safety/pii.rs @@ -244,11 +244,11 @@ fn collect_redactions_inner(norm: &str, include_bare_numeric: bool) -> Vec }); // IBAN before credit card: CC can match an IBAN tail of all digits. - push_checksum(&mut hits, norm, &IBAN_RE, PII_IBAN, |s| valid_iban(s)); + push_checksum(&mut hits, norm, &IBAN_RE, PII_IBAN, valid_iban); if include_bare_numeric { // Credit card before bare CPF/CNPJ to avoid catching a 13-19 digit run as CPF/CNPJ. - push_checksum(&mut hits, norm, &CC_RE, PII_CC, |s| valid_luhn(s)); + push_checksum(&mut hits, norm, &CC_RE, PII_CC, valid_luhn); push_checksum(&mut hits, norm, &CNPJ_BARE_RE, PII_CNPJ, |s| { valid_cnpj(digits(s).as_slice()) @@ -266,10 +266,10 @@ fn collect_redactions_inner(norm: &str, include_bare_numeric: bool) -> Vec valid_verhoeff(digits(digits_str).as_slice()) }); - push_checksum(&mut hits, norm, &DNI_RE, PII_DNI, |s| valid_dni_es(s)); - push_checksum(&mut hits, norm, &NIE_RE, PII_DNI, |s| valid_nie_es(s)); - push_checksum(&mut hits, norm, &NINO_RE, PII_NINO, |s| valid_nino(s)); - push_checksum(&mut hits, norm, &SSN_RE, PII_SSN, |s| valid_ssn(s)); + push_checksum(&mut hits, norm, &DNI_RE, PII_DNI, valid_dni_es); + push_checksum(&mut hits, norm, &NIE_RE, PII_DNI, valid_nie_es); + push_checksum(&mut hits, norm, &NINO_RE, PII_NINO, valid_nino); + push_checksum(&mut hits, norm, &SSN_RE, PII_SSN, valid_ssn); push_simple(&mut hits, norm, &RRN_RE, PII_RRN); push_simple(&mut hits, norm, &RFC_RE, PII_RFC); push_simple(&mut hits, norm, &PAN_IN_RE, PII_PAN_IN); @@ -349,7 +349,7 @@ fn dedupe_overlaps(hits: &mut Vec) { }); let mut kept: Vec = Vec::with_capacity(hits.len()); for h in hits.drain(..) { - let overlaps = kept.last().map_or(false, |k| h.start < k.end); + let overlaps = kept.last().is_some_and(|k| h.start < k.end); if !overlaps { kept.push(h); } @@ -547,7 +547,7 @@ fn valid_luhn(s: &str) -> bool { sum += v; alt = !alt; } - sum % 10 == 0 + sum.is_multiple_of(10) } // IBAN mod-97. Steps: strip spaces, move first 4 chars to end, expand letters diff --git a/src/openhuman/memory_store/unified/profile.rs b/src/openhuman/memory_store/unified/profile.rs index fc0384e52..b7822a82b 100644 --- a/src/openhuman/memory_store/unified/profile.rs +++ b/src/openhuman/memory_store/unified/profile.rs @@ -373,7 +373,7 @@ pub fn profile_upsert_full( .cue_families .as_ref() .filter(|m| !m.is_empty()) - .map(|m| serde_json::to_string(m)) + .map(serde_json::to_string) .transpose()?; // Derive class from the facet's own class field or fall back to key prefix. diff --git a/src/openhuman/memory_sync/canonicalize/email.rs b/src/openhuman/memory_sync/canonicalize/email.rs index f9420fec5..18b7ff4e2 100644 --- a/src/openhuman/memory_sync/canonicalize/email.rs +++ b/src/openhuman/memory_sync/canonicalize/email.rs @@ -87,7 +87,7 @@ pub fn canonicalise( if let Some(unsub) = &msg.list_unsubscribe { md.push_str(&format!("List-Unsubscribe: {}\n", unsub)); } - md.push_str("\n"); + md.push('\n'); let cleaned = email_clean::clean_body(msg.body.trim()); if cleaned.is_empty() { md.push('\n'); diff --git a/src/openhuman/memory_sync/composio/providers/gmail/post_process.rs b/src/openhuman/memory_sync/composio/providers/gmail/post_process.rs index dfd4067b4..1e3494ba8 100644 --- a/src/openhuman/memory_sync/composio/providers/gmail/post_process.rs +++ b/src/openhuman/memory_sync/composio/providers/gmail/post_process.rs @@ -128,7 +128,7 @@ pub fn apply_response_level_markdown(data: &mut Value, top_md: &str) { ); return; }; - for (msg, slice) in messages.iter_mut().zip(slices.into_iter()) { + for (msg, slice) in messages.iter_mut().zip(slices) { if let Some(obj) = msg.as_object_mut() { obj.insert("markdownFormatted".to_string(), Value::String(slice)); } diff --git a/src/openhuman/memory_sync/composio/providers/notion/source.rs b/src/openhuman/memory_sync/composio/providers/notion/source.rs index 77626533f..c4e5f52ae 100644 --- a/src/openhuman/memory_sync/composio/providers/notion/source.rs +++ b/src/openhuman/memory_sync/composio/providers/notion/source.rs @@ -270,7 +270,7 @@ impl IncrementalSource for NotionSource { // old per-call `record_requests(1)`. state.record_requests(fetch_count as u32); - for (p, body) in pending.iter_mut().zip(bodies.into_iter()) { + for (p, body) in pending.iter_mut().zip(bodies) { p.markdown_body = body; } } diff --git a/src/openhuman/memory_sync/composio/providers/orchestrator.rs b/src/openhuman/memory_sync/composio/providers/orchestrator.rs index 227171bdc..aa6fa69f6 100644 --- a/src/openhuman/memory_sync/composio/providers/orchestrator.rs +++ b/src/openhuman/memory_sync/composio/providers/orchestrator.rs @@ -55,7 +55,9 @@ fn pages_for_max_items(max_items: u32, page_size: u32) -> u32 { return u32::MAX; } // Widen to u64 before the addition to prevent overflow for large cap values. - (((max_items as u64) + (page_size as u64) - 1) / (page_size as u64)).min(u32::MAX as u64) as u32 + (max_items as u64) + .div_ceil(page_size as u64) + .min(u32::MAX as u64) as u32 } /// Single source of truth for the per-sync `max_items` cap. diff --git a/src/openhuman/memory_sync/sources/github.rs b/src/openhuman/memory_sync/sources/github.rs index 5e4cfd95d..c392aabbb 100644 --- a/src/openhuman/memory_sync/sources/github.rs +++ b/src/openhuman/memory_sync/sources/github.rs @@ -226,7 +226,7 @@ pub async fn run_github_sync( // ── Phase 2: fold cost + ingest in batch order (serial) ── for (batch_idx, ((batch_inputs, batch_labels, batch_basenames), output)) in - batches.into_iter().zip(outputs.into_iter()).enumerate() + batches.into_iter().zip(outputs).enumerate() { let batch_input_tokens: u64 = batch_inputs.iter().map(|i| i.token_count as u64).sum(); @@ -499,7 +499,7 @@ async fn read_items_buffered( child_basenames.push(raw_path); } processed += 1; - if processed % 100 == 0 || processed == total { + if processed.is_multiple_of(100) || processed == total { emit_sync_stage( MemorySyncTrigger::Manual, MemorySyncStage::Ingesting, diff --git a/src/openhuman/memory_tools/capture.rs b/src/openhuman/memory_tools/capture.rs index 11c656699..29eeba875 100644 --- a/src/openhuman/memory_tools/capture.rs +++ b/src/openhuman/memory_tools/capture.rs @@ -98,7 +98,7 @@ impl ToolMemoryCaptureHook { .unwrap_or_else(|| "__unscoped__".to_string()); let mut out = Vec::new(); - for raw_line in trimmed.split(|c: char| matches!(c, '.' | '\n' | ';')) { + for raw_line in trimmed.split(['.', '\n', ';']) { let line = raw_line.trim(); if line.is_empty() { continue; diff --git a/src/openhuman/memory_tools/types.rs b/src/openhuman/memory_tools/types.rs index d2a659ecb..eecda7251 100644 --- a/src/openhuman/memory_tools/types.rs +++ b/src/openhuman/memory_tools/types.rs @@ -25,8 +25,10 @@ use serde::{Deserialize, Serialize}; /// and retrieval (to sort high-priority guidance ahead of advisory notes). #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum ToolMemoryPriority { /// Soft suggestion — surfaced on demand, not eagerly injected. + #[default] Normal, /// Important guidance — eagerly injected at tool-selection time. High, @@ -35,12 +37,6 @@ pub enum ToolMemoryPriority { Critical, } -impl Default for ToolMemoryPriority { - fn default() -> Self { - Self::Normal - } -} - impl ToolMemoryPriority { /// True for priorities that must be eagerly surfaced to the agent /// (Critical/High rules are both pinned into the system prompt and @@ -56,6 +52,7 @@ impl ToolMemoryPriority { /// edicts apart from auto-captured observations. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum ToolMemorySource { /// User explicitly asked the agent to remember this rule. UserExplicit, @@ -63,15 +60,10 @@ pub enum ToolMemorySource { /// repeated correction, etc.). PostTurn, /// Written by another subsystem (e.g. an integration provisioner). + #[default] Programmatic, } -impl Default for ToolMemorySource { - fn default() -> Self { - Self::Programmatic - } -} - /// A single tool-scoped memory rule. /// /// Stored under the `tool-{tool_name}` namespace as a KV entry keyed by diff --git a/src/openhuman/memory_tree/retrieval/drill_down.rs b/src/openhuman/memory_tree/retrieval/drill_down.rs index ef976548e..90034fd95 100644 --- a/src/openhuman/memory_tree/retrieval/drill_down.rs +++ b/src/openhuman/memory_tree/retrieval/drill_down.rs @@ -139,7 +139,7 @@ async fn rerank_by_semantic_similarity( let mut decorated: Vec<(f32, bool, RetrievalHit)> = hits .into_iter() - .zip(embeddings.into_iter()) + .zip(embeddings) .map(|(h, emb)| match emb { Some(v) if v.len() == query_vec.len() => { let sim = cosine_similarity(&query_vec, &v); diff --git a/src/openhuman/memory_tree/score/embed/mod.rs b/src/openhuman/memory_tree/score/embed/mod.rs index aaf5df0fe..5c2143d90 100644 --- a/src/openhuman/memory_tree/score/embed/mod.rs +++ b/src/openhuman/memory_tree/score/embed/mod.rs @@ -110,7 +110,7 @@ const MAX_BATCH_TOKENS: usize = 1_000_000; const CHARS_PER_TOKEN_ESTIMATE: usize = 4; fn estimate_tokens(text: &str) -> usize { - (text.len() + CHARS_PER_TOKEN_ESTIMATE - 1) / CHARS_PER_TOKEN_ESTIMATE + text.len().div_ceil(CHARS_PER_TOKEN_ESTIMATE) } /// Split `texts` into sub-batches that respect the batch API limits: diff --git a/src/openhuman/memory_tree/tree_runtime/engine.rs b/src/openhuman/memory_tree/tree_runtime/engine.rs index 85681dcb0..fc1998c6f 100644 --- a/src/openhuman/memory_tree/tree_runtime/engine.rs +++ b/src/openhuman/memory_tree/tree_runtime/engine.rs @@ -274,7 +274,7 @@ pub async fn rebuild_tree( // re-written above), logging each failure for diagnosis; the rebuild still // returns the resulting status rather than erroring out wholesale. let mut failed: Vec = Vec::new(); - let mut propagate = |id: &str, level: NodeLevel| { + let propagate = |id: &str, level: NodeLevel| { let node_id = id.to_string(); async move { if let Err(e) = propagate_node(config, provider, namespace, &node_id, level).await { diff --git a/src/openhuman/migrations/unify_ai_provider_settings.rs b/src/openhuman/migrations/unify_ai_provider_settings.rs index 70a1c4803..dd46abed6 100644 --- a/src/openhuman/migrations/unify_ai_provider_settings.rs +++ b/src/openhuman/migrations/unify_ai_provider_settings.rs @@ -273,7 +273,7 @@ fn looks_like_openhuman(url: &str) -> bool { let without_scheme = lower.split("://").nth(1).unwrap_or(&lower); // Strip userinfo and take only the host[:port] part before any path. let authority = without_scheme.split('/').next().unwrap_or(""); - let host = authority.split('@').last().unwrap_or(authority); + let host = authority.split('@').next_back().unwrap_or(authority); let host_no_port = host.split(':').next().unwrap_or(host); host_no_port == "api.openhuman.ai" || host_no_port.ends_with(".openhuman.ai") diff --git a/src/openhuman/people/address_book.rs b/src/openhuman/people/address_book.rs index 2d9e3e54c..266184ac3 100644 --- a/src/openhuman/people/address_book.rs +++ b/src/openhuman/people/address_book.rs @@ -160,7 +160,7 @@ mod imp { } }); - store.requestAccessForEntityType_completionHandler(CNEntityType::Contacts, &*block); + store.requestAccessForEntityType_completionHandler(CNEntityType::Contacts, &block); rx.recv().map_err(|_| { AddressBookError::Other("contacts permission callback never fired".into()) @@ -251,7 +251,7 @@ mod imp { let ok = store.enumerateContactsWithFetchRequest_error_usingBlock( &request, Some(&mut error), - &*block, + &block, ); if !ok { let msg = error diff --git a/src/openhuman/people/store.rs b/src/openhuman/people/store.rs index 6dcac89cb..6bf470e7f 100644 --- a/src/openhuman/people/store.rs +++ b/src/openhuman/people/store.rs @@ -453,8 +453,7 @@ impl PeopleStore { let ids: Vec = person_ids.to_vec(); tokio::task::spawn_blocking(move || -> SqlResult>> { let guard = conn.blocking_lock(); - let placeholders = std::iter::repeat("?") - .take(ids.len()) + let placeholders = std::iter::repeat_n("?", ids.len()) .collect::>() .join(","); let sql = format!( diff --git a/src/openhuman/redirect_links/ops.rs b/src/openhuman/redirect_links/ops.rs index d1d13e747..2e4eb5e4c 100644 --- a/src/openhuman/redirect_links/ops.rs +++ b/src/openhuman/redirect_links/ops.rs @@ -43,7 +43,7 @@ fn public_url_regex() -> &'static Regex { /// Strip trailing sentence punctuation (`.`, `,`, `;`, `:`, `!`) so that /// "see https://example.com/path." doesn't capture the period. fn trim_trailing_punct(s: &str) -> &str { - s.trim_end_matches(|c: char| matches!(c, '.' | ',' | ';' | ':' | '!')) + s.trim_end_matches(['.', ',', ';', ':', '!']) } /// Shorten a single URL, persisting it in the global store. Idempotent. diff --git a/src/openhuman/runtime_node/bootstrap.rs b/src/openhuman/runtime_node/bootstrap.rs index df509e8dd..d5256e7d1 100644 --- a/src/openhuman/runtime_node/bootstrap.rs +++ b/src/openhuman/runtime_node/bootstrap.rs @@ -281,7 +281,7 @@ fn resolve_from_system(system: SystemNode) -> Result { .unwrap_or_default(); let version = system .version - .trim_start_matches(|c: char| c == 'v' || c == 'V') + .trim_start_matches(['v', 'V']) .trim() .to_string(); build_resolved(bin_dir, version, NodeSource::System) diff --git a/src/openhuman/runtime_python/downloader.rs b/src/openhuman/runtime_python/downloader.rs index 880ef3826..507ebffde 100644 --- a/src/openhuman/runtime_python/downloader.rs +++ b/src/openhuman/runtime_python/downloader.rs @@ -106,7 +106,7 @@ pub fn select_distribution( .filter(|dist| dist.version >= minimum) // Exclusive upper bound — keeps selection off newer pre-release series // (e.g. 3.15.x betas, which parse as a bare `3.15.0`). - .filter(|dist| maximum.as_ref().map_or(true, |max| dist.version < *max)) + .filter(|dist| maximum.as_ref().is_none_or(|max| dist.version < *max)) .collect::>(); if candidates.is_empty() { diff --git a/src/openhuman/sandbox/docker.rs b/src/openhuman/sandbox/docker.rs index 28f447142..fcaea1588 100644 --- a/src/openhuman/sandbox/docker.rs +++ b/src/openhuman/sandbox/docker.rs @@ -13,8 +13,8 @@ //! spawned command runs sandboxed. use super::types::{ - DockerOverrides, SandboxBackendHandle, SandboxBackendKind, SandboxExecRequest, - SandboxExecResult, SandboxPolicy, SandboxStatus, + SandboxBackendHandle, SandboxBackendKind, SandboxExecRequest, SandboxExecResult, SandboxPolicy, + SandboxStatus, }; use std::process::Stdio; use tokio::process::Command; diff --git a/src/openhuman/sandbox/ops.rs b/src/openhuman/sandbox/ops.rs index 24c1d415f..2dd89eeaf 100644 --- a/src/openhuman/sandbox/ops.rs +++ b/src/openhuman/sandbox/ops.rs @@ -7,10 +7,10 @@ use super::types::{ SandboxPolicy, SandboxStatus, ELEVATED_TOOLS, }; use crate::openhuman::agent::harness::definition::SandboxMode; -use crate::openhuman::config::{DockerRuntimeConfig, RuntimeConfig}; +use crate::openhuman::config::RuntimeConfig; use crate::openhuman::cwd_jail::{self, Jail, NoopBackend}; use std::collections::HashMap; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::Command; use std::time::Duration; diff --git a/src/openhuman/security/policy/policy_command.rs b/src/openhuman/security/policy/policy_command.rs index 6e06304e5..9c893d81c 100644 --- a/src/openhuman/security/policy/policy_command.rs +++ b/src/openhuman/security/policy/policy_command.rs @@ -91,7 +91,7 @@ pub(super) fn has_dangerous_env_prefix(s: &str) -> bool { } let (name, _) = word.split_once('=').unwrap_or((word, "")); let upper = name.to_ascii_uppercase(); - if DANGEROUS_ENV_PREFIXES.iter().any(|d| *d == upper.as_str()) { + if DANGEROUS_ENV_PREFIXES.contains(&upper.as_str()) { return true; } rest = rest[word.len()..].trim_start(); @@ -160,10 +160,7 @@ pub(super) fn skip_env_assignments(s: &str) -> &str { } pub(super) fn command_basename(command: &str) -> &str { - command - .split(|ch| ch == '/' || ch == '\\') - .next_back() - .unwrap_or(command) + command.split(['/', '\\']).next_back().unwrap_or(command) } pub(super) fn normalized_command_name(command: &str) -> String { @@ -372,10 +369,8 @@ pub(super) fn contains_unquoted_single_ampersand(command: &str) -> bool { match ch { '\'' => quote = QuoteState::Single, '"' => quote = QuoteState::Double, - '&' => { - if chars.next_if_eq(&'&').is_none() { - return true; - } + '&' if chars.next_if_eq(&'&').is_none() => { + return true; } _ => {} } diff --git a/src/openhuman/skills/ops_create.rs b/src/openhuman/skills/ops_create.rs index fbadbc195..b271dff22 100644 --- a/src/openhuman/skills/ops_create.rs +++ b/src/openhuman/skills/ops_create.rs @@ -385,11 +385,9 @@ pub(crate) fn create_workflow_inner( // Notify live agent sessions so they pick up the new skill in their // `## Installed Skills` catalogue (see `Agent::refresh_workflows`). - let _ = crate::core::event_bus::publish_global( - crate::core::event_bus::DomainEvent::WorkflowsChanged { - reason: "create".to_string(), - }, - ); + crate::core::event_bus::publish_global(crate::core::event_bus::DomainEvent::WorkflowsChanged { + reason: "create".to_string(), + }); Ok(created) } diff --git a/src/openhuman/skills/ops_install.rs b/src/openhuman/skills/ops_install.rs index 39eecef0f..c24cfe02c 100644 --- a/src/openhuman/skills/ops_install.rs +++ b/src/openhuman/skills/ops_install.rs @@ -396,11 +396,9 @@ pub(crate) async fn install_workflow_from_url_with_home( // Notify live agent sessions so they refresh their `## Installed Skills` // catalogue mid-conversation (see `Agent::refresh_workflows`). - let _ = crate::core::event_bus::publish_global( - crate::core::event_bus::DomainEvent::WorkflowsChanged { - reason: "install".to_string(), - }, - ); + crate::core::event_bus::publish_global(crate::core::event_bus::DomainEvent::WorkflowsChanged { + reason: "install".to_string(), + }); Ok(InstallWorkflowFromUrlOutcome { url: raw_url, @@ -570,11 +568,9 @@ pub fn uninstall_workflow( // Notify live agent sessions to drop the removed skill from their // `## Installed Skills` catalogue (see `Agent::refresh_workflows`). - let _ = crate::core::event_bus::publish_global( - crate::core::event_bus::DomainEvent::WorkflowsChanged { - reason: "uninstall".to_string(), - }, - ); + crate::core::event_bus::publish_global(crate::core::event_bus::DomainEvent::WorkflowsChanged { + reason: "uninstall".to_string(), + }); Ok(UninstallWorkflowOutcome { name: trimmed, diff --git a/src/openhuman/skills/ops_types.rs b/src/openhuman/skills/ops_types.rs index 15eadd38f..ff92ae1f5 100644 --- a/src/openhuman/skills/ops_types.rs +++ b/src/openhuman/skills/ops_types.rs @@ -41,8 +41,10 @@ pub const MAX_WORKFLOW_RESOURCE_BYTES: u64 = 128 * 1024; /// Where the skill was discovered. Determines precedence on name collision. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] +#[derive(Default)] pub enum WorkflowScope { /// Workflow shipped with the user's global config (`~/.openhuman/skills/...`). + #[default] User, /// Workflow shipped with the current workspace (`/.openhuman/skills/...`). /// Requires the trust marker to be loaded. @@ -51,12 +53,6 @@ pub enum WorkflowScope { Legacy, } -impl Default for WorkflowScope { - fn default() -> Self { - Self::User - } -} - /// Parsed frontmatter of a `SKILL.md` file. /// /// Matches the agentskills.io SKILL.md spec: `name` and `description` are @@ -161,7 +157,7 @@ pub(crate) fn extract_tags(fm: &WorkflowFrontmatter, warnings: &mut Vec) .metadata .get("hermes") .and_then(|v| v.as_mapping()) - .and_then(|m| m.get(&serde_yaml::Value::String("tags".to_string()))) + .and_then(|m| m.get(serde_yaml::Value::String("tags".to_string()))) { tags.extend(metadata_string_seq(hermes_tags)); } @@ -185,7 +181,7 @@ pub(crate) fn extract_related_skills(fm: &WorkflowFrontmatter) -> Vec { .metadata .get("hermes") .and_then(|v| v.as_mapping()) - .and_then(|m| m.get(&serde_yaml::Value::String("related_skills".to_string()))) + .and_then(|m| m.get(serde_yaml::Value::String("related_skills".to_string()))) { related.extend(metadata_string_seq(hermes_related)); } diff --git a/src/openhuman/skills/registry.rs b/src/openhuman/skills/registry.rs index a6e78aeea..580d27b7c 100644 --- a/src/openhuman/skills/registry.rs +++ b/src/openhuman/skills/registry.rs @@ -50,7 +50,7 @@ pub enum IdentityMatch { /// preflight gate runs for this skill. Present + `required = true` ⇒ /// the preflight described in [`crate::openhuman::skills::schemas`]'s /// `preflight_github_gate` runs before the orchestrator boots. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct WorkflowGithubConfig { /// When true, the gate runs. When false (default), the gate is /// skipped even if other fields are populated — the gate is opt-in @@ -63,15 +63,6 @@ pub struct WorkflowGithubConfig { pub identity_match: IdentityMatch, } -impl Default for WorkflowGithubConfig { - fn default() -> Self { - Self { - required: false, - identity_match: IdentityMatch::default(), - } - } -} - /// A skill = an agent definition + its declared inputs (parsed from `skill.toml`). #[derive(Debug, Clone, Deserialize)] pub struct WorkflowDefinition { diff --git a/src/openhuman/subconscious/heartbeat/planner/collectors.rs b/src/openhuman/subconscious/heartbeat/planner/collectors.rs index efc27919d..834d5ebd7 100644 --- a/src/openhuman/subconscious/heartbeat/planner/collectors.rs +++ b/src/openhuman/subconscious/heartbeat/planner/collectors.rs @@ -29,7 +29,7 @@ pub(crate) fn collect_cron_reminders(config: &Config, now: DateTime) -> Vec jobs.into_iter() .filter(|job| job.enabled) - .filter(|job| is_reminder_like_job(job)) + .filter(is_reminder_like_job) .filter(|job| { let delta = job.next_run.signed_duration_since(now); delta <= lookahead && delta >= Duration::minutes(-2) diff --git a/src/openhuman/subconscious/heartbeat/planner/plan.rs b/src/openhuman/subconscious/heartbeat/planner/plan.rs index 21eda058c..4f50681ba 100644 --- a/src/openhuman/subconscious/heartbeat/planner/plan.rs +++ b/src/openhuman/subconscious/heartbeat/planner/plan.rs @@ -46,7 +46,7 @@ pub(crate) fn plan_delivery_for_event( } // Wider grace window: heartbeat runs every few minutes, so // tiny post-start windows can miss real meetings. - if until_minutes <= 0 && until_minutes >= -10 { + if (-10..=0).contains(&until_minutes) { return Some(PlannedDelivery { stage: "starting_now", title: format!("Meeting starting now: {}", event.title), @@ -74,7 +74,7 @@ pub(crate) fn plan_delivery_for_event( } // Wider grace window for reminder due state to prevent misses // from tick alignment. - if until_minutes <= 0 && until_minutes >= -10 { + if (-10..=0).contains(&until_minutes) { return Some(PlannedDelivery { stage: "due", title: format!("Reminder due: {}", event.title), diff --git a/src/openhuman/task_sources/types.rs b/src/openhuman/task_sources/types.rs index e6f7a5506..728cc8b51 100644 --- a/src/openhuman/task_sources/types.rs +++ b/src/openhuman/task_sources/types.rs @@ -116,20 +116,16 @@ impl FilterSpec { /// How enriched tasks are routed once fetched. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum SourceTarget { /// Append a todo card AND dispatch a triage turn so an agent may /// start working immediately (triage still gates noise). + #[default] AgentTodoProactive, /// Append a todo card only; never auto-start an agent turn. TodoOnly, } -impl Default for SourceTarget { - fn default() -> Self { - Self::AgentTodoProactive - } -} - /// Why a fetch ran — mirrors the provider `SyncReason` semantics. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] diff --git a/src/openhuman/threads/title.rs b/src/openhuman/threads/title.rs index 77ac60699..898ddff1a 100644 --- a/src/openhuman/threads/title.rs +++ b/src/openhuman/threads/title.rs @@ -118,7 +118,7 @@ pub fn title_from_user_message(message: &str) -> Option { let stripped = collapsed .trim_matches(|c: char| matches!(c, '"' | '\'' | '`')) .trim() - .trim_start_matches(|c: char| matches!(c, '/' | '@' | '#')) + .trim_start_matches(['/', '@', '#']) .trim(); if stripped.is_empty() { return None; diff --git a/src/openhuman/tinyagents/convert.rs b/src/openhuman/tinyagents/convert.rs index 1002052e3..ff16365dc 100644 --- a/src/openhuman/tinyagents/convert.rs +++ b/src/openhuman/tinyagents/convert.rs @@ -136,7 +136,7 @@ fn parse_native_assistant_envelope(text: &str) -> Option<(String, Vec = diff --git a/src/openhuman/tinyagents/mod.rs b/src/openhuman/tinyagents/mod.rs index dbff8c479..2afd5da8c 100644 --- a/src/openhuman/tinyagents/mod.rs +++ b/src/openhuman/tinyagents/mod.rs @@ -1243,7 +1243,7 @@ fn assemble_turn_harness( tool_sets: Vec>>>, allowed: Option>, max_iterations: usize, - on_progress: Option>, + _on_progress: Option>, subagent_scope: Option, context_window: Option, early_exit_tools: &[&str], @@ -1461,11 +1461,8 @@ fn assemble_turn_harness( .iter() .flat_map(|set| set.iter()) .map(|tool| tool.name()) - .filter_map(|name| { - seen_candidates - .insert(name.to_string()) - .then(|| name.to_string()) - }) + .filter(|&name| seen_candidates.insert(name.to_string())) + .map(|name| name.to_string()) .collect(); let mut registered: HashSet = HashSet::new(); for name in candidate_names.iter().map(String::as_str) { diff --git a/src/openhuman/tinyagents/steering_forwarder.rs b/src/openhuman/tinyagents/steering_forwarder.rs index 1a6bea3aa..34ab709cf 100644 --- a/src/openhuman/tinyagents/steering_forwarder.rs +++ b/src/openhuman/tinyagents/steering_forwarder.rs @@ -88,7 +88,7 @@ pub(super) async fn forward_steers(queue: &RunQueue, handle: &SteeringHandle, th delivered, "[run_queue] delivered steer message(s) into running steering handle" ); - let _ = publish_global(DomainEvent::RunQueueMessageDelivered { + publish_global(DomainEvent::RunQueueMessageDelivered { thread_id: thread_label.to_string(), mode: "steer".to_string(), delivered, @@ -121,7 +121,7 @@ pub(super) async fn forward_collects( delivered, "[run_queue] delivered collect message(s) into running steering handle" ); - let _ = publish_global(DomainEvent::RunQueueMessageDelivered { + publish_global(DomainEvent::RunQueueMessageDelivered { thread_id: thread_label.to_string(), mode: "collect".to_string(), delivered, @@ -298,7 +298,7 @@ impl Drop for SteeringForwarderGuard { requeued, "[run_queue] requeued residual steer(s) as next-turn input (guard drop)" ); - let _ = publish_global(DomainEvent::RunQueueSteerRequeued { + publish_global(DomainEvent::RunQueueSteerRequeued { thread_id: thread_label, requeued, }); diff --git a/src/openhuman/tinyplace/agent_tools/help.rs b/src/openhuman/tinyplace/agent_tools/help.rs index ce335ee9d..b3821d19e 100644 --- a/src/openhuman/tinyplace/agent_tools/help.rs +++ b/src/openhuman/tinyplace/agent_tools/help.rs @@ -285,7 +285,7 @@ fn commands_catalog() -> String { for (domain, commands) in by_domain { md.subheading(humanize_key(&domain)); - md.kv(commands.into_iter().map(|(f, d)| (f, d))); + md.kv(commands.into_iter()); } md.build() } diff --git a/src/openhuman/tinyplace/agent_tools/render.rs b/src/openhuman/tinyplace/agent_tools/render.rs index 549523234..10e069366 100644 --- a/src/openhuman/tinyplace/agent_tools/render.rs +++ b/src/openhuman/tinyplace/agent_tools/render.rs @@ -158,7 +158,7 @@ pub fn scalar(value: &Value) -> String { /// Look up a string field on a JSON object, returning `"—"` when missing so /// table cells are never blank. -pub fn field<'a>(obj: &'a Value, key: &str) -> String { +pub fn field(obj: &Value, key: &str) -> String { obj.get(key).map(scalar).unwrap_or_else(|| "—".to_string()) } diff --git a/src/openhuman/tinyplace/manifest.rs b/src/openhuman/tinyplace/manifest.rs index 1f52d8faf..574e27f5f 100644 --- a/src/openhuman/tinyplace/manifest.rs +++ b/src/openhuman/tinyplace/manifest.rs @@ -174,7 +174,7 @@ pub(crate) fn handle_tinyplace_directory_resolve(params: Map) -> } // Directory-card fallback: query by username. - match directory_card_fallback(&client, &name).await { + match directory_card_fallback(client, &name).await { Some(card) => { log::debug!( "{LOG_PREFIX} directory_resolve: found '{name}' via directory card \ @@ -586,7 +586,7 @@ pub(crate) fn handle_tinyplace_registry_register(params: Map) -> Ok(identity) => { log::debug!("{LOG_PREFIX} registry_register free-tier ok username={username}"); let _ = - publish_directory_card_for_identity(&client, signer.as_ref(), &identity).await; + publish_directory_card_for_identity(client, signer.as_ref(), &identity).await; return to_value(serde_json::json!({ "identity": identity })); } Err(e) => match e.payment_required() { @@ -615,7 +615,7 @@ pub(crate) fn handle_tinyplace_registry_register(params: Map) -> if let Some(network) = challenge.network.as_deref() { ensure_cluster_matches(network)?; } - ensure_backend_mint_matches(&client).await?; + ensure_backend_mint_matches(client).await?; let mut extra_metadata = HashMap::new(); extra_metadata.insert("identity".to_string(), format!("@{username}")); @@ -642,9 +642,8 @@ pub(crate) fn handle_tinyplace_registry_register(params: Map) -> log::debug!( "{LOG_PREFIX} registry_register settled username={username} attempt={attempt}" ); - let _ = - publish_directory_card_for_identity(&client, signer.as_ref(), &identity) - .await; + let _ = publish_directory_card_for_identity(client, signer.as_ref(), &identity) + .await; return to_value(serde_json::json!({ "identity": identity, "payment": { "onChainTx": on_chain_tx }, @@ -680,9 +679,8 @@ pub(crate) fn handle_tinyplace_registry_register(params: Map) -> log::debug!( "{LOG_PREFIX} registry_register recovered owned identity username={username}" ); - let _ = - publish_directory_card_for_identity(&client, signer.as_ref(), &identity) - .await; + let _ = publish_directory_card_for_identity(client, signer.as_ref(), &identity) + .await; return to_value(serde_json::json!({ "identity": identity, "payment": { "onChainTx": on_chain_tx }, @@ -916,7 +914,7 @@ pub(crate) fn handle_tinyplace_marketplace_buy_product( if let Some(network) = challenge.network.as_deref() { ensure_cluster_matches(network)?; } - ensure_backend_mint_matches(&client).await?; + ensure_backend_mint_matches(client).await?; let mut extra_metadata = HashMap::new(); extra_metadata.insert("productId".to_string(), product_id.clone()); let fulfilled = fulfill_payment( @@ -1011,7 +1009,7 @@ pub(crate) fn handle_tinyplace_marketplace_buy_identity( if let Some(network) = challenge.network.as_deref() { ensure_cluster_matches(network)?; } - ensure_backend_mint_matches(&client).await?; + ensure_backend_mint_matches(client).await?; let mut extra_metadata = HashMap::new(); extra_metadata.insert("listingId".to_string(), listing_id.clone()); let fulfilled = fulfill_payment( @@ -1118,7 +1116,7 @@ pub(crate) fn handle_tinyplace_marketplace_bid(params: Map) -> Co .place_bid_with_payment( &listing_id, bid, - tinyplace::api::marketplace::IdentityBidPaymentOptions::default(), + tinyplace::api::marketplace::IdentityBidPaymentOptions, ) .await .map_err(map_err)?; @@ -1168,7 +1166,7 @@ pub(crate) fn handle_tinyplace_marketplace_offer(params: Map) -> .marketplace .create_offer_with_payment( offer, - tinyplace::api::marketplace::IdentityOfferPaymentOptions::default(), + tinyplace::api::marketplace::IdentityOfferPaymentOptions, ) .await .map_err(map_err)?; @@ -2927,7 +2925,7 @@ pub(crate) fn handle_tinyplace_signal_get_bundle(params: Map) -> let client = global_state().client().await?; // Resolve the identifier (handle or crypto_id) before the bundle lookup. - let agent_id = resolve_recipient_to_agent_id(&client, &raw_agent_id).await?; + let agent_id = resolve_recipient_to_agent_id(client, &raw_agent_id).await?; log::debug!("{LOG_PREFIX} signal_get_bundle resolved agent_id={agent_id}"); let result = match client.keys.get_bundle(&agent_id).await { @@ -3319,7 +3317,7 @@ pub(crate) fn handle_tinyplace_signal_send_message(params: Map) - // Resolve the recipient identifier (@handle, bare handle, or crypto_id) to // the canonical crypto_id before any key-bundle or directory lookup. - let agent_id = resolve_recipient_to_agent_id(&client, &recipient).await?; + let agent_id = resolve_recipient_to_agent_id(client, &recipient).await?; log::debug!("{LOG_PREFIX} signal_send_message resolved to agent_id={agent_id}"); // Fetch recipient's published key bundle (always needed for the X25519 @@ -5029,7 +5027,7 @@ pub(crate) fn handle_tinyplace_bounties_create(params: Map) -> Co if let Some(network) = challenge.network.as_deref() { ensure_cluster_matches(network)?; } - ensure_backend_mint_matches(&client).await?; + ensure_backend_mint_matches(client).await?; let mut extra_metadata = HashMap::new(); extra_metadata.insert("title".to_string(), request.title.clone()); diff --git a/src/openhuman/tinyplace/signal_store.rs b/src/openhuman/tinyplace/signal_store.rs index 71b33bccd..ae3ea3989 100644 --- a/src/openhuman/tinyplace/signal_store.rs +++ b/src/openhuman/tinyplace/signal_store.rs @@ -487,12 +487,12 @@ impl SessionStore for FileSessionStore { .join("signed_pre_keys") .join(format!("{}.enc", sanitize(&key_id))); self.encrypt_and_write(&path, &json) - .map_err(|e| Error::InvalidArgument(e))?; + .map_err(Error::InvalidArgument)?; // Also persist the active signed pre-key ID. let active_path = self.dir.join("active_signed_pre_key.enc"); self.encrypt_and_write(&active_path, &key_id) - .map_err(|e| Error::InvalidArgument(e))?; + .map_err(Error::InvalidArgument)?; let mut cache = self.cache.lock().await; cache.signed_pre_keys.insert(key_id.clone(), pre_key); @@ -533,7 +533,7 @@ impl SessionStore for FileSessionStore { .join("pre_keys") .join(format!("{}.enc", sanitize(&key_id))); self.encrypt_and_write(&path, &json) - .map_err(|e| Error::InvalidArgument(e))?; + .map_err(Error::InvalidArgument)?; let mut cache = self.cache.lock().await; cache.pre_keys.insert(key_id, pre_key); @@ -561,7 +561,7 @@ impl SessionStore for FileSessionStore { .join("sessions") .join(format!("{}.enc", sanitize(address))); self.encrypt_and_write(&path, &json) - .map_err(|e| Error::InvalidArgument(e))?; + .map_err(Error::InvalidArgument)?; let mut cache = self.cache.lock().await; cache.sessions.insert(address.to_string(), session); diff --git a/src/openhuman/tinyplace/streams.rs b/src/openhuman/tinyplace/streams.rs index d990eede6..9fc7a2ae9 100644 --- a/src/openhuman/tinyplace/streams.rs +++ b/src/openhuman/tinyplace/streams.rs @@ -17,7 +17,6 @@ //! status and the frontend can call `start` again. use std::collections::HashMap; -use std::sync::Arc; use tokio::sync::Mutex; use tokio::task::JoinHandle; diff --git a/src/openhuman/todos/ops.rs b/src/openhuman/todos/ops.rs index aef41bdd5..21798dd93 100644 --- a/src/openhuman/todos/ops.rs +++ b/src/openhuman/todos/ops.rs @@ -600,7 +600,7 @@ fn apply_claim( .find(|c| c.id == card_id) .ok_or_else(|| format!("[todos][ops] claim_card: card '{card_id}' not found on board"))?; - if !expected.iter().any(|s| *s == card.status) { + if !expected.contains(&card.status) { let current = card.status.as_str(); return Err(format!( "[todos][ops] claim_card: card '{card_id}' status is '{current}', \ diff --git a/src/openhuman/tool_registry/denials.rs b/src/openhuman/tool_registry/denials.rs index ef8cd5096..4e6ae832b 100644 --- a/src/openhuman/tool_registry/denials.rs +++ b/src/openhuman/tool_registry/denials.rs @@ -48,7 +48,7 @@ pub fn record(tool_name: &str, policy: &str, action: &str, reason: &str) { } pub fn list(limit: usize) -> Vec { - let limit = limit.min(MAX_DENIALS).max(0); + let limit = limit.min(MAX_DENIALS); let buf = RECENT_DENIALS.lock().unwrap_or_else(|p| p.into_inner()); buf.iter().take(limit).cloned().collect() } diff --git a/src/openhuman/tool_status/ops.rs b/src/openhuman/tool_status/ops.rs index ee81d0201..44a519411 100644 --- a/src/openhuman/tool_status/ops.rs +++ b/src/openhuman/tool_status/ops.rs @@ -11,7 +11,7 @@ //! [`ToolFailureClass::Unknown`] (treated as recoverable so a later retry phase //! can give it one bounded attempt rather than surfacing a dead end). -use super::types::{ClassifiedFailure, FailureCategory, ToolFailureClass}; +use super::types::{ClassifiedFailure, ToolFailureClass}; /// Classify a failed tool call into a user-facing [`ClassifiedFailure`]. /// diff --git a/src/openhuman/tools/impl/browser/screenshot.rs b/src/openhuman/tools/impl/browser/screenshot.rs index 4a723ac42..853e0f627 100644 --- a/src/openhuman/tools/impl/browser/screenshot.rs +++ b/src/openhuman/tools/impl/browser/screenshot.rs @@ -194,9 +194,9 @@ impl ScreenshotTool { let encoded = base64::engine::general_purpose::STANDARD.encode(data); let mut msg = format!("Screenshot saved to: {}\n", output_path.display()); if let Some((w, h)) = shown_dims { - let _ = write!( + let _ = writeln!( msg, - "Downscaled to {w}x{h}px for inline view (coordinates you read are in this {w}x{h} space).\n" + "Downscaled to {w}x{h}px for inline view (coordinates you read are in this {w}x{h} space)." ); } let _ = write!(msg, "data:{mime};base64,{encoded}"); diff --git a/src/openhuman/tools/impl/network/polymarket.rs b/src/openhuman/tools/impl/network/polymarket.rs index a5fc36b43..7a8fcfe88 100644 --- a/src/openhuman/tools/impl/network/polymarket.rs +++ b/src/openhuman/tools/impl/network/polymarket.rs @@ -171,7 +171,6 @@ impl PolymarketTool { let cached_credentials = config .derived_clob_credentials .clone() - .map(PolymarketClobCredentials::from) .filter(PolymarketClobCredentials::is_complete); Self { @@ -613,7 +612,7 @@ impl PolymarketTool { .map_err(anyhow::Error::msg) .context("Failed to load config for persisting Polymarket credentials")?; - config.integrations.polymarket.derived_clob_credentials = Some(creds.clone().into()); + config.integrations.polymarket.derived_clob_credentials = Some(creds.clone()); config .save() .await diff --git a/src/openhuman/tools/impl/system/install_tool.rs b/src/openhuman/tools/impl/system/install_tool.rs index 234da456e..158acb384 100644 --- a/src/openhuman/tools/impl/system/install_tool.rs +++ b/src/openhuman/tools/impl/system/install_tool.rs @@ -57,12 +57,10 @@ fn manager_argv(manager: &str) -> Option<(&'static str, Vec<&'static str>)> { /// Best-effort detection of the host's system package manager. fn detect_system_manager() -> Option<&'static str> { - for m in ["apt-get", "dnf", "yum", "pacman", "apk", "brew", "winget"] { - if find_on_path(m).is_some() { - return Some(m); - } - } - None + ["apt-get", "dnf", "yum", "pacman", "apk", "brew", "winget"] + .into_iter() + .find(|&m| find_on_path(m).is_some()) + .map(|v| v as _) } /// A package name is accepted only if it contains exclusively characters that diff --git a/src/openhuman/tools/impl/system/shell.rs b/src/openhuman/tools/impl/system/shell.rs index a84bf9b23..f707b2205 100644 --- a/src/openhuman/tools/impl/system/shell.rs +++ b/src/openhuman/tools/impl/system/shell.rs @@ -635,13 +635,13 @@ fn prepend_path_dirs<'a>( fn shell_command_needs_python_runtime(command: &str) -> bool { let lower = command.to_ascii_lowercase(); lower - .split(|ch| matches!(ch, ';' | '&' | '|' | '\n' | '\r')) + .split([';', '&', '|', '\n', '\r']) .any(segment_starts_with_python_command) } fn segment_starts_with_python_command(segment: &str) -> bool { let mut tokens = segment.split_whitespace().peekable(); - while let Some(token) = tokens.next() { + for token in tokens { let token = token.trim_matches(|ch| matches!(ch, '(' | ')' | '<' | '>')); if token.is_empty() { continue; diff --git a/src/openhuman/tools/user_filter.rs b/src/openhuman/tools/user_filter.rs index 7071e75cc..f5089418f 100644 --- a/src/openhuman/tools/user_filter.rs +++ b/src/openhuman/tools/user_filter.rs @@ -316,7 +316,7 @@ fn all_filterable_tool_names() -> HashSet<&'static str> { fn family_for_rust_name(name: &str) -> Option<&'static ToolFamily> { TOOL_FAMILIES .iter() - .find(|fam| fam.rust_names.iter().any(|n| *n == name)) + .find(|fam| fam.rust_names.contains(&name)) } /// Expand persisted tool-preference entries into Rust tool `name()` values. diff --git a/src/openhuman/voice/dictation_listener.rs b/src/openhuman/voice/dictation_listener.rs index 677e9f9e5..a3334b47d 100644 --- a/src/openhuman/voice/dictation_listener.rs +++ b/src/openhuman/voice/dictation_listener.rs @@ -13,7 +13,6 @@ use tokio::sync::broadcast; use tokio::task::JoinHandle; use crate::openhuman::config::Config; -use crate::openhuman::voice::hotkey::{self, ActivationMode, HotkeyEvent}; const LOG_PREFIX: &str = "[dictation_listener]"; @@ -122,7 +121,6 @@ pub async fn start_if_enabled(config: &Config) { "{LOG_PREFIX} macOS: skipping rdev hotkey listener — \ handled by Tauri host via tauri-plugin-global-shortcut (issue #2677)" ); - return; } // Non-macOS: start the rdev-based listener. diff --git a/src/openhuman/voice/factory/stt_providers.rs b/src/openhuman/voice/factory/stt_providers.rs index 32bb3abfc..edd8b2fe8 100644 --- a/src/openhuman/voice/factory/stt_providers.rs +++ b/src/openhuman/voice/factory/stt_providers.rs @@ -347,7 +347,7 @@ impl SttProvider for ExternalSttProvider { text: result, provider: self.slug.clone(), }, - &format!("voice-factory: external STT completed via {}", self.slug), + format!("voice-factory: external STT completed via {}", self.slug), )) } } diff --git a/src/openhuman/voice/factory/tts_providers.rs b/src/openhuman/voice/factory/tts_providers.rs index b6bc0cec1..2e4201ad4 100644 --- a/src/openhuman/voice/factory/tts_providers.rs +++ b/src/openhuman/voice/factory/tts_providers.rs @@ -174,7 +174,7 @@ impl TtsProvider for ExternalTtsProvider { visemes: Vec::new(), alignment: None, }, - &format!("voice-factory: external TTS completed via {}", self.slug), + format!("voice-factory: external TTS completed via {}", self.slug), )) } } diff --git a/src/openhuman/voice/schemas/handlers/provider_server.rs b/src/openhuman/voice/schemas/handlers/provider_server.rs index 77fa87c7a..d36352a98 100644 --- a/src/openhuman/voice/schemas/handlers/provider_server.rs +++ b/src/openhuman/voice/schemas/handlers/provider_server.rs @@ -214,8 +214,8 @@ pub(crate) fn handle_voice_update_provider_settings( "endpoint": p.endpoint, "auth_style": p.auth_style.as_str(), "capability": p.capability.as_str(), - "stt_api_style": serde_json::to_value(&p.stt_api_style).unwrap_or_default(), - "tts_api_style": serde_json::to_value(&p.tts_api_style).unwrap_or_default(), + "stt_api_style": serde_json::to_value(p.stt_api_style).unwrap_or_default(), + "tts_api_style": serde_json::to_value(p.tts_api_style).unwrap_or_default(), "default_stt_model": p.default_stt_model, "default_tts_voice": p.default_tts_voice, }) diff --git a/src/openhuman/voice/schemas/helpers.rs b/src/openhuman/voice/schemas/helpers.rs index 67e7d9a61..194a472dc 100644 --- a/src/openhuman/voice/schemas/helpers.rs +++ b/src/openhuman/voice/schemas/helpers.rs @@ -185,6 +185,6 @@ pub(super) fn generate_silent_wav() -> Vec { wav.extend_from_slice(&bits_per_sample.to_le_bytes()); wav.extend_from_slice(b"data"); wav.extend_from_slice(&data_size.to_le_bytes()); - wav.extend(std::iter::repeat(0u8).take(data_size as usize)); + wav.extend(std::iter::repeat_n(0u8, data_size as usize)); wav } diff --git a/src/openhuman/voice/server.rs b/src/openhuman/voice/server.rs index 2796a0b55..eaa354f84 100644 --- a/src/openhuman/voice/server.rs +++ b/src/openhuman/voice/server.rs @@ -553,14 +553,14 @@ fn start_hotkey_listener( // rdev calls TSMGetInputSourceProperty off the main thread; macOS 26 // enforces main-queue-only access and crashes the process. Only the // Fn/Globe key is safe via the Swift globe listener. (#2677) - return Err(format!( + Err(format!( "voice server hotkey '{}' is not supported on macOS — \ only 'fn' (Fn/Globe key) is safe. rdev calls \ TSMGetInputSourceProperty off the main thread on macOS 26, \ causing EXC_BREAKPOINT. Set hotkey = \"fn\" in voice config \ (issue #2677).", hotkey_str - )); + )) } // Non-macOS: rdev-based listener for all keys. diff --git a/src/openhuman/wallet/chains/btc.rs b/src/openhuman/wallet/chains/btc.rs index 6859deb6c..1a5d117bc 100644 --- a/src/openhuman/wallet/chains/btc.rs +++ b/src/openhuman/wallet/chains/btc.rs @@ -277,7 +277,7 @@ pub async fn execute_btc_quote(mut quote: PreparedTransaction) -> Result Result Result { return Err("calldata must be 0x-prefixed hex".to_string()); } let body = &trimmed[2..]; - if body.len() % 2 != 0 { + if !body.len().is_multiple_of(2) { return Err("calldata hex must be byte-aligned".to_string()); } if !body.chars().all(|c| c.is_ascii_hexdigit()) { diff --git a/src/openhuman/wallet/tools/chain_status.rs b/src/openhuman/wallet/tools/chain_status.rs index 7c3fe642f..f8ad35c6c 100644 --- a/src/openhuman/wallet/tools/chain_status.rs +++ b/src/openhuman/wallet/tools/chain_status.rs @@ -5,6 +5,12 @@ use serde_json::json; pub struct WalletChainStatusTool; +impl Default for WalletChainStatusTool { + fn default() -> Self { + Self::new() + } +} + impl WalletChainStatusTool { pub fn new() -> Self { Self diff --git a/src/openhuman/wallet/tools/prepare_transfer.rs b/src/openhuman/wallet/tools/prepare_transfer.rs index d898a988e..c8b78b6f1 100644 --- a/src/openhuman/wallet/tools/prepare_transfer.rs +++ b/src/openhuman/wallet/tools/prepare_transfer.rs @@ -5,6 +5,12 @@ use serde_json::json; pub struct WalletPrepareTransferTool; +impl Default for WalletPrepareTransferTool { + fn default() -> Self { + Self::new() + } +} + impl WalletPrepareTransferTool { pub fn new() -> Self { Self diff --git a/src/openhuman/wallet/tools/status.rs b/src/openhuman/wallet/tools/status.rs index 7da23fd35..b4457db71 100644 --- a/src/openhuman/wallet/tools/status.rs +++ b/src/openhuman/wallet/tools/status.rs @@ -5,6 +5,12 @@ use serde_json::json; pub struct WalletStatusTool; +impl Default for WalletStatusTool { + fn default() -> Self { + Self::new() + } +} + impl WalletStatusTool { pub fn new() -> Self { Self diff --git a/src/openhuman/wallet/tools/tx_query.rs b/src/openhuman/wallet/tools/tx_query.rs index 01d55c4b0..c1284a00d 100644 --- a/src/openhuman/wallet/tools/tx_query.rs +++ b/src/openhuman/wallet/tools/tx_query.rs @@ -48,6 +48,12 @@ fn parse_args(args: serde_json::Value) -> Result { pub struct WalletTxStatusTool; +impl Default for WalletTxStatusTool { + fn default() -> Self { + Self::new() + } +} + impl WalletTxStatusTool { pub fn new() -> Self { Self @@ -93,6 +99,12 @@ impl Tool for WalletTxStatusTool { pub struct WalletTxReceiptTool; +impl Default for WalletTxReceiptTool { + fn default() -> Self { + Self::new() + } +} + impl WalletTxReceiptTool { pub fn new() -> Self { Self @@ -138,6 +150,12 @@ impl Tool for WalletTxReceiptTool { pub struct WalletLookupTxTool; +impl Default for WalletLookupTxTool { + fn default() -> Self { + Self::new() + } +} + impl WalletLookupTxTool { pub fn new() -> Self { Self diff --git a/src/openhuman/web3/bridge/tools.rs b/src/openhuman/web3/bridge/tools.rs index 193446e6e..632f411c9 100644 --- a/src/openhuman/web3/bridge/tools.rs +++ b/src/openhuman/web3/bridge/tools.rs @@ -11,11 +11,23 @@ use crate::openhuman::web3::{execute_tool_schema, ops, to_tool_result}; pub struct Web3BridgeQuoteTool; pub struct Web3BridgeExecuteTool; +impl Default for Web3BridgeQuoteTool { + fn default() -> Self { + Self::new() + } +} + impl Web3BridgeQuoteTool { pub fn new() -> Self { Self } } +impl Default for Web3BridgeExecuteTool { + fn default() -> Self { + Self::new() + } +} + impl Web3BridgeExecuteTool { pub fn new() -> Self { Self diff --git a/src/openhuman/web3/dapp/tools.rs b/src/openhuman/web3/dapp/tools.rs index 3c9af66ad..119e0c910 100644 --- a/src/openhuman/web3/dapp/tools.rs +++ b/src/openhuman/web3/dapp/tools.rs @@ -11,11 +11,23 @@ use crate::openhuman::web3::{execute_tool_schema, ops, to_tool_result}; pub struct Web3DappCallTool; pub struct Web3DappExecuteTool; +impl Default for Web3DappCallTool { + fn default() -> Self { + Self::new() + } +} + impl Web3DappCallTool { pub fn new() -> Self { Self } } +impl Default for Web3DappExecuteTool { + fn default() -> Self { + Self::new() + } +} + impl Web3DappExecuteTool { pub fn new() -> Self { Self diff --git a/src/openhuman/web3/swap/tools.rs b/src/openhuman/web3/swap/tools.rs index 1d6d31dc1..e80016e0e 100644 --- a/src/openhuman/web3/swap/tools.rs +++ b/src/openhuman/web3/swap/tools.rs @@ -14,16 +14,34 @@ pub struct Web3SwapQuoteTool; pub struct Web3SwapExecuteTool; pub struct Web3SwapRoutesTool; +impl Default for Web3SwapQuoteTool { + fn default() -> Self { + Self::new() + } +} + impl Web3SwapQuoteTool { pub fn new() -> Self { Self } } +impl Default for Web3SwapExecuteTool { + fn default() -> Self { + Self::new() + } +} + impl Web3SwapExecuteTool { pub fn new() -> Self { Self } } +impl Default for Web3SwapRoutesTool { + fn default() -> Self { + Self::new() + } +} + impl Web3SwapRoutesTool { pub fn new() -> Self { Self diff --git a/src/openhuman/webview_notifications/types.rs b/src/openhuman/webview_notifications/types.rs index efd749b1e..5a11ab4b4 100644 --- a/src/openhuman/webview_notifications/types.rs +++ b/src/openhuman/webview_notifications/types.rs @@ -27,13 +27,7 @@ pub struct WebviewNotificationEvent { /// v1 ships the plumbing but requires an explicit opt-in so the /// release doesn't suddenly start firing OS toasts for every /// background DM in an idle Slack tab. -#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)] +#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, Default)] pub struct NotificationSettings { pub enabled: bool, } - -impl Default for NotificationSettings { - fn default() -> Self { - Self { enabled: false } - } -} diff --git a/src/openhuman/x402/ops.rs b/src/openhuman/x402/ops.rs index 5a9f72880..57339a0db 100644 --- a/src/openhuman/x402/ops.rs +++ b/src/openhuman/x402/ops.rs @@ -228,7 +228,7 @@ pub async fn handle_402_and_pay( })?; let budget_check = - super::store::with_ledger(|l| l.check_budget(amount)).map_err(|e| X402Error::Wallet(e))?; + super::store::with_ledger(|l| l.check_budget(amount)).map_err(X402Error::Wallet)?; match budget_check { super::store::BudgetCheck::Allowed => {} @@ -504,7 +504,7 @@ async fn build_solana_payment( let memo_data = req .memo_value() .map(|m| m.as_bytes().to_vec()) - .unwrap_or_else(|| random_memo_nonce()); + .unwrap_or_else(random_memo_nonce); // -- account keys (order matters) -- let account_keys: Vec<[u8; 32]> = vec![ @@ -594,7 +594,7 @@ pub(crate) fn build_evm_payment_with_signer( req: &PaymentRequirements, ) -> Result { use ethers_core::types::{Address, U256}; - use ethers_signers::Signer; + use std::str::FromStr; let chain_id = req @@ -845,7 +845,7 @@ fn derive_ata( hasher.update(token_program); hasher.update(mint); hasher.update([bump]); - hasher.update(&ata_program); + hasher.update(ata_program); hasher.update(b"ProgramDerivedAddress"); let candidate: [u8; 32] = hasher.finalize().into(); if curve25519_dalek::edwards::CompressedEdwardsY(candidate) diff --git a/src/openhuman/x402/store.rs b/src/openhuman/x402/store.rs index e321611ed..992291359 100644 --- a/src/openhuman/x402/store.rs +++ b/src/openhuman/x402/store.rs @@ -40,6 +40,7 @@ pub enum PaymentStatus { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[derive(Default)] pub struct SpendingSummary { pub session_total_atomic: u64, pub daily_total_atomic: u64, @@ -49,19 +50,6 @@ pub struct SpendingSummary { pub monthly_count: usize, } -impl Default for SpendingSummary { - fn default() -> Self { - Self { - session_total_atomic: 0, - daily_total_atomic: 0, - monthly_total_atomic: 0, - session_count: 0, - daily_count: 0, - monthly_count: 0, - } - } -} - #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SpendingBudget { diff --git a/src/openhuman/x402/tools.rs b/src/openhuman/x402/tools.rs index dc91d3e43..3fdcb35d4 100644 --- a/src/openhuman/x402/tools.rs +++ b/src/openhuman/x402/tools.rs @@ -21,6 +21,12 @@ const DEFAULT_TIMEOUT_SECS: u64 = 30; pub struct X402RequestTool; +impl Default for X402RequestTool { + fn default() -> Self { + Self::new() + } +} + impl X402RequestTool { pub fn new() -> Self { Self @@ -185,7 +191,7 @@ impl Tool for X402RequestTool { Ok(r) => r, Err(e) => { let _ = store::with_ledger_mut(|l| { - let mut updated = store::PaymentRecord { + let updated = store::PaymentRecord { id: record_id, url: url.clone(), asset: payment_result.asset.clone(),