mirror of
https://github.com/outbackdingo/optimclaw.git
synced 2026-08-26 15:40:18 +00:00
Add proactivity features: memory CLI, session pruning, self-repair notifications, slash commands, status diagnostics, context warnings
Closes the proactivity gap with six features: - Memory CLI (`ironclaw memory search/read/write/tree/status`) for direct workspace access without starting the full agent - Session pruning background task that evicts idle sessions (configurable TTL, default 7 days) - Self-repair notifications broadcast recovery results through channel manager instead of silent logging - `/heartbeat`, `/summarize`, `/suggest` slash commands for manual heartbeat trigger, thread summarization, and next-step suggestions - `ironclaw status` diagnostics command checking DB, session, secrets, embeddings, WASM tools, channels, heartbeat, and MCP servers - Context pressure warning that notifies users before auto-compaction fires Co-Authored-By: Claude Opus 4.6 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
1c9f9db420
commit
f3c85f57fc
@@ -0,0 +1,268 @@
|
||||
//! Memory/workspace CLI commands.
|
||||
//!
|
||||
//! Exposes the workspace system for direct CLI use without starting the agent.
|
||||
|
||||
use std::io::Read;
|
||||
use std::sync::Arc;
|
||||
|
||||
use clap::Subcommand;
|
||||
|
||||
use crate::workspace::{EmbeddingProvider, SearchConfig, Workspace};
|
||||
|
||||
#[derive(Subcommand, Debug, Clone)]
|
||||
pub enum MemoryCommand {
|
||||
/// Search workspace memory (hybrid full-text + semantic)
|
||||
Search {
|
||||
/// Search query
|
||||
query: String,
|
||||
|
||||
/// Maximum number of results
|
||||
#[arg(short, long, default_value = "5")]
|
||||
limit: usize,
|
||||
},
|
||||
|
||||
/// Read a file from the workspace
|
||||
Read {
|
||||
/// File path (e.g., "MEMORY.md", "daily/2024-01-15.md")
|
||||
path: String,
|
||||
},
|
||||
|
||||
/// Write content to a workspace file
|
||||
Write {
|
||||
/// File path (e.g., "notes/idea.md")
|
||||
path: String,
|
||||
|
||||
/// Content to write (omit to read from stdin)
|
||||
content: Option<String>,
|
||||
|
||||
/// Append instead of overwrite
|
||||
#[arg(short, long)]
|
||||
append: bool,
|
||||
},
|
||||
|
||||
/// Show workspace directory tree
|
||||
Tree {
|
||||
/// Root path to start from
|
||||
#[arg(default_value = "")]
|
||||
path: String,
|
||||
|
||||
/// Maximum depth to traverse
|
||||
#[arg(short, long, default_value = "3")]
|
||||
depth: usize,
|
||||
},
|
||||
|
||||
/// Show workspace status (document count, index health)
|
||||
Status,
|
||||
}
|
||||
|
||||
/// Run a memory command.
|
||||
pub async fn run_memory_command(
|
||||
cmd: MemoryCommand,
|
||||
pool: deadpool_postgres::Pool,
|
||||
embeddings: Option<Arc<dyn EmbeddingProvider>>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut workspace = Workspace::new("default", pool);
|
||||
if let Some(emb) = embeddings {
|
||||
workspace = workspace.with_embeddings(emb);
|
||||
}
|
||||
|
||||
match cmd {
|
||||
MemoryCommand::Search { query, limit } => search(&workspace, &query, limit).await,
|
||||
MemoryCommand::Read { path } => read(&workspace, &path).await,
|
||||
MemoryCommand::Write {
|
||||
path,
|
||||
content,
|
||||
append,
|
||||
} => write(&workspace, &path, content, append).await,
|
||||
MemoryCommand::Tree { path, depth } => tree(&workspace, &path, depth).await,
|
||||
MemoryCommand::Status => status(&workspace).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn search(workspace: &Workspace, query: &str, limit: usize) -> anyhow::Result<()> {
|
||||
let config = SearchConfig::default().with_limit(limit.min(50));
|
||||
let results = workspace.search_with_config(query, config).await?;
|
||||
|
||||
if results.is_empty() {
|
||||
println!("No results found for: {}", query);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("Found {} result(s) for \"{}\":\n", results.len(), query);
|
||||
|
||||
for (i, result) in results.iter().enumerate() {
|
||||
let score_bar = score_indicator(result.score);
|
||||
println!("{}. [{}] (score: {:.3})", i + 1, score_bar, result.score);
|
||||
|
||||
// Show a content preview (first 200 chars)
|
||||
let preview = truncate_content(&result.content, 200);
|
||||
for line in preview.lines() {
|
||||
println!(" {}", line);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read(workspace: &Workspace, path: &str) -> anyhow::Result<()> {
|
||||
match workspace.read(path).await {
|
||||
Ok(doc) => {
|
||||
println!("{}", doc.content);
|
||||
}
|
||||
Err(crate::error::WorkspaceError::DocumentNotFound { .. }) => {
|
||||
anyhow::bail!("File not found: {}", path);
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn write(
|
||||
workspace: &Workspace,
|
||||
path: &str,
|
||||
content: Option<String>,
|
||||
append: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
let content = match content {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
// Read from stdin
|
||||
let mut buf = String::new();
|
||||
std::io::stdin().read_to_string(&mut buf)?;
|
||||
buf
|
||||
}
|
||||
};
|
||||
|
||||
if append {
|
||||
workspace.append(path, &content).await?;
|
||||
println!("Appended to {}", path);
|
||||
} else {
|
||||
workspace.write(path, &content).await?;
|
||||
println!("Wrote to {}", path);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tree(workspace: &Workspace, path: &str, max_depth: usize) -> anyhow::Result<()> {
|
||||
let root = if path.is_empty() { "." } else { path };
|
||||
println!("{}/", root);
|
||||
print_tree(workspace, path, "", max_depth, 0).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn print_tree(
|
||||
workspace: &Workspace,
|
||||
path: &str,
|
||||
prefix: &str,
|
||||
max_depth: usize,
|
||||
current_depth: usize,
|
||||
) -> anyhow::Result<()> {
|
||||
if current_depth >= max_depth {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let entries = workspace.list(path).await?;
|
||||
let count = entries.len();
|
||||
|
||||
for (i, entry) in entries.iter().enumerate() {
|
||||
let is_last = i == count - 1;
|
||||
let connector = if is_last { "└── " } else { "├── " };
|
||||
let child_prefix = if is_last { " " } else { "│ " };
|
||||
|
||||
if entry.is_directory {
|
||||
println!("{}{}{}/", prefix, connector, entry.name());
|
||||
Box::pin(print_tree(
|
||||
workspace,
|
||||
&entry.path,
|
||||
&format!("{}{}", prefix, child_prefix),
|
||||
max_depth,
|
||||
current_depth + 1,
|
||||
))
|
||||
.await?;
|
||||
} else {
|
||||
println!("{}{}{}", prefix, connector, entry.name());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn status(workspace: &Workspace) -> anyhow::Result<()> {
|
||||
let all_paths = workspace.list_all().await?;
|
||||
let file_count = all_paths.len();
|
||||
|
||||
// Count directories by collecting unique parent paths
|
||||
let mut dirs: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
for path in &all_paths {
|
||||
if let Some(parent) = path.rsplit_once('/') {
|
||||
dirs.insert(parent.0.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
println!("Workspace Status");
|
||||
println!(" User: {}", workspace.user_id());
|
||||
println!(" Files: {}", file_count);
|
||||
println!(" Directories: {}", dirs.len());
|
||||
|
||||
// Check key files
|
||||
let key_files = [
|
||||
"MEMORY.md",
|
||||
"HEARTBEAT.md",
|
||||
"IDENTITY.md",
|
||||
"SOUL.md",
|
||||
"AGENTS.md",
|
||||
"USER.md",
|
||||
];
|
||||
println!("\n Identity files:");
|
||||
for path in &key_files {
|
||||
let exists = workspace.exists(path).await.unwrap_or(false);
|
||||
let marker = if exists { "+" } else { "-" };
|
||||
println!(" [{}] {}", marker, path);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn truncate_content(s: &str, max_len: usize) -> String {
|
||||
if s.len() <= max_len {
|
||||
s.to_string()
|
||||
} else {
|
||||
format!("{}...", &s[..max_len])
|
||||
}
|
||||
}
|
||||
|
||||
fn score_indicator(score: f32) -> &'static str {
|
||||
if score > 0.8_f32 {
|
||||
"=====>"
|
||||
} else if score > 0.5_f32 {
|
||||
"====>"
|
||||
} else if score > 0.3_f32 {
|
||||
"===>"
|
||||
} else if score > 0.1_f32 {
|
||||
"==>"
|
||||
} else {
|
||||
"=>"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_score_indicator() {
|
||||
assert_eq!(score_indicator(0.9_f32), "=====>");
|
||||
assert_eq!(score_indicator(0.6_f32), "====>");
|
||||
assert_eq!(score_indicator(0.4_f32), "===>");
|
||||
assert_eq!(score_indicator(0.2_f32), "==>");
|
||||
assert_eq!(score_indicator(0.05_f32), "=>");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_truncate_content() {
|
||||
assert_eq!(truncate_content("hello", 10), "hello");
|
||||
assert_eq!(truncate_content("hello world", 5), "hello...");
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,19 @@
|
||||
//! - Managing configuration (`config list`, `config get`, `config set`)
|
||||
//! - Managing WASM tools (`tool install`, `tool list`, `tool remove`)
|
||||
//! - Managing MCP servers (`mcp add`, `mcp auth`, `mcp list`, `mcp test`)
|
||||
//! - Querying workspace memory (`memory search`, `memory read`, `memory write`)
|
||||
//! - Checking system health (`status`)
|
||||
|
||||
mod config;
|
||||
mod mcp;
|
||||
pub mod memory;
|
||||
pub mod status;
|
||||
mod tool;
|
||||
|
||||
pub use config::{ConfigCommand, run_config_command};
|
||||
pub use mcp::{McpCommand, run_mcp_command};
|
||||
pub use memory::{MemoryCommand, run_memory_command};
|
||||
pub use status::run_status_command;
|
||||
pub use tool::{ToolCommand, run_tool_command};
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
@@ -79,6 +85,13 @@ pub enum Command {
|
||||
/// Manage MCP servers (hosted tool providers)
|
||||
#[command(subcommand)]
|
||||
Mcp(McpCommand),
|
||||
|
||||
/// Query and manage workspace memory
|
||||
#[command(subcommand)]
|
||||
Memory(MemoryCommand),
|
||||
|
||||
/// Show system health and diagnostics
|
||||
Status,
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
//! System health and diagnostics CLI command.
|
||||
//!
|
||||
//! Checks database connectivity, session validity, embeddings,
|
||||
//! WASM runtime, tool count, and channel availability.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::settings::Settings;
|
||||
|
||||
/// Run the status command, printing system health info.
|
||||
pub async fn run_status_command() -> anyhow::Result<()> {
|
||||
let settings = Settings::load();
|
||||
|
||||
println!("IronClaw Status");
|
||||
println!("===============\n");
|
||||
|
||||
// Version
|
||||
println!(
|
||||
" Version: {} v{}",
|
||||
env!("CARGO_PKG_NAME"),
|
||||
env!("CARGO_PKG_VERSION")
|
||||
);
|
||||
|
||||
// Database
|
||||
let db_url_set = settings.database_url.is_some() || std::env::var("DATABASE_URL").is_ok();
|
||||
print!(" Database: ");
|
||||
if db_url_set {
|
||||
// Try to connect
|
||||
match check_database().await {
|
||||
Ok(()) => println!("connected"),
|
||||
Err(e) => println!("error ({})", e),
|
||||
}
|
||||
} else {
|
||||
println!("not configured");
|
||||
}
|
||||
|
||||
// Session / Auth
|
||||
print!(" Session: ");
|
||||
let session_path = crate::llm::session::default_session_path();
|
||||
if session_path.exists() {
|
||||
println!("found ({})", session_path.display());
|
||||
} else {
|
||||
println!("not found (run `ironclaw setup`)");
|
||||
}
|
||||
|
||||
// Secrets
|
||||
print!(" Secrets: ");
|
||||
let secrets_configured = settings.secrets_master_key_source != crate::settings::KeySource::None
|
||||
|| std::env::var("SECRETS_MASTER_KEY").is_ok()
|
||||
|| crate::secrets::keychain::has_master_key();
|
||||
if secrets_configured {
|
||||
println!("configured ({:?})", settings.secrets_master_key_source);
|
||||
} else {
|
||||
println!("not configured");
|
||||
}
|
||||
|
||||
// Embeddings
|
||||
print!(" Embeddings: ");
|
||||
let emb_enabled = settings.embeddings.enabled
|
||||
|| std::env::var("OPENAI_API_KEY").is_ok()
|
||||
|| std::env::var("EMBEDDING_ENABLED")
|
||||
.map(|v| v == "true")
|
||||
.unwrap_or(false);
|
||||
if emb_enabled {
|
||||
println!(
|
||||
"enabled (provider: {}, model: {})",
|
||||
settings.embeddings.provider, settings.embeddings.model
|
||||
);
|
||||
} else {
|
||||
println!("disabled");
|
||||
}
|
||||
|
||||
// WASM tools
|
||||
print!(" WASM Tools: ");
|
||||
let tools_dir = settings
|
||||
.wasm
|
||||
.tools_dir
|
||||
.clone()
|
||||
.unwrap_or_else(default_tools_dir);
|
||||
if tools_dir.exists() {
|
||||
let count = count_wasm_files(&tools_dir);
|
||||
println!("{} installed ({})", count, tools_dir.display());
|
||||
} else {
|
||||
println!("directory not found ({})", tools_dir.display());
|
||||
}
|
||||
|
||||
// WASM channels
|
||||
print!(" Channels: ");
|
||||
let channels_dir = settings
|
||||
.channels
|
||||
.wasm_channels_dir
|
||||
.clone()
|
||||
.unwrap_or_else(default_channels_dir);
|
||||
let mut channel_info = vec!["cli".to_string()];
|
||||
if settings.channels.http_enabled {
|
||||
channel_info.push(format!(
|
||||
"http:{}",
|
||||
settings.channels.http_port.unwrap_or(3000)
|
||||
));
|
||||
}
|
||||
if channels_dir.exists() {
|
||||
let wasm_count = count_wasm_files(&channels_dir);
|
||||
if wasm_count > 0 {
|
||||
channel_info.push(format!("{} wasm", wasm_count));
|
||||
}
|
||||
}
|
||||
println!("{}", channel_info.join(", "));
|
||||
|
||||
// Heartbeat
|
||||
print!(" Heartbeat: ");
|
||||
let hb_enabled = settings.heartbeat.enabled
|
||||
|| std::env::var("HEARTBEAT_ENABLED")
|
||||
.map(|v| v == "true")
|
||||
.unwrap_or(false);
|
||||
if hb_enabled {
|
||||
println!("enabled (interval: {}s)", settings.heartbeat.interval_secs);
|
||||
} else {
|
||||
println!("disabled");
|
||||
}
|
||||
|
||||
// MCP servers
|
||||
print!(" MCP Servers: ");
|
||||
match crate::tools::mcp::config::load_mcp_servers().await {
|
||||
Ok(servers) => {
|
||||
let enabled = servers.servers.iter().filter(|s| s.enabled).count();
|
||||
let total = servers.servers.len();
|
||||
println!("{} enabled / {} configured", enabled, total);
|
||||
}
|
||||
Err(_) => println!("none configured"),
|
||||
}
|
||||
|
||||
// Settings path
|
||||
println!("\n Settings: {}", Settings::default_path().display());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn check_database() -> anyhow::Result<()> {
|
||||
let _ = dotenvy::dotenv();
|
||||
let settings = Settings::load();
|
||||
let url = std::env::var("DATABASE_URL")
|
||||
.ok()
|
||||
.or(settings.database_url)
|
||||
.ok_or_else(|| anyhow::anyhow!("no URL"))?;
|
||||
|
||||
let config: deadpool_postgres::Config = deadpool_postgres::Config {
|
||||
url: Some(url),
|
||||
..Default::default()
|
||||
};
|
||||
let pool = config
|
||||
.create_pool(
|
||||
Some(deadpool_postgres::Runtime::Tokio1),
|
||||
tokio_postgres::NoTls,
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("pool error: {}", e))?;
|
||||
|
||||
let client = tokio::time::timeout(std::time::Duration::from_secs(5), pool.get())
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("timeout"))?
|
||||
.map_err(|e| anyhow::anyhow!("{}", e))?;
|
||||
|
||||
client
|
||||
.execute("SELECT 1", &[])
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{}", e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn count_wasm_files(dir: &std::path::Path) -> usize {
|
||||
std::fs::read_dir(dir)
|
||||
.map(|entries| {
|
||||
entries
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.path().extension().is_some_and(|ext| ext == "wasm"))
|
||||
.count()
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn default_tools_dir() -> PathBuf {
|
||||
dirs::home_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join(".ironclaw")
|
||||
.join("tools")
|
||||
}
|
||||
|
||||
fn default_channels_dir() -> PathBuf {
|
||||
dirs::home_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join(".ironclaw")
|
||||
.join("channels")
|
||||
}
|
||||
Reference in New Issue
Block a user