feat: add memory management tools and utility commands

This commit is contained in:
asepharyana
2026-07-11 20:44:15 +07:00
parent 08490532d2
commit fe82840c03
13 changed files with 535 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
use std::fs;
use std::path::PathBuf;
use serde_json::{json, Value};
use anyhow::{Result, anyhow};
use super::super::Tool;
use super::super::ToolCtx;
use super::super::resolve_path;
use super::helpers::arg_str;
pub struct Delete;
impl Tool for Delete {
fn name(&self) -> &'static str {
"delete"
}
fn description(&self) -> &'static str {
"Delete a file or empty directory. Will not delete non-empty directories."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Path to the file or directory to delete (relative to workspace root)"
}
},
"required": ["path"]
})
}
fn run(&self, ctx: &ToolCtx, args: &Value) -> Result<String> {
let rel = arg_str(args, "path")?;
let path: PathBuf = resolve_path(&ctx.workspaces, &rel)?;
if !path.exists() {
return Ok(format!("path '{}' does not exist (resolved to {})", rel, path.display()));
}
let metadata = path.metadata()
.map_err(|e| anyhow!("failed to read metadata for '{}': {}", rel, e))?;
if metadata.is_dir() {
let is_empty = fs::read_dir(&path)
.map_err(|e| anyhow!("failed to read directory '{}': {}", rel, e))?
.next()
.is_none();
if is_empty {
fs::remove_dir(&path)
.map_err(|e| anyhow!("failed to remove directory '{}': {}", rel, e))?;
Ok(format!("removed empty directory {}", rel))
} else {
anyhow::bail!("directory '{}' is not empty (refusing to delete)", rel);
}
} else {
fs::remove_file(&path)
.map_err(|e| anyhow!("failed to delete '{}': {}", rel, e))?;
Ok(format!("deleted {}", rel))
}
}
}
+1
View File
@@ -1,3 +1,4 @@
pub mod delete;
pub mod edit;
pub mod helpers;
pub mod read;
+41
View File
@@ -0,0 +1,41 @@
use serde_json::{json, Value};
use anyhow::{Result, anyhow};
use super::super::Tool;
use super::super::ToolCtx;
use crate::model::memory::Memory;
pub struct Forget;
impl Tool for Forget {
fn name(&self) -> &'static str {
"forget"
}
fn description(&self) -> &'static str {
"Remove a specific memory entry by its name. Use recall first to find the exact name if unsure."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name of the memory to remove (use recall to find exact names)"
}
},
"required": ["name"]
})
}
fn run(&self, ctx: &ToolCtx, args: &Value) -> Result<String> {
let name = args.get("name")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("missing required argument: name"))?;
Memory::remove(&ctx.memory_dir, name)
.map_err(|e| anyhow!("failed to remove memory '{}': {}", name, e))?;
Ok(format!("removed memory '{}'", name))
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod forget;
pub mod recall;
pub mod remember;
+65
View File
@@ -0,0 +1,65 @@
use serde_json::{json, Value};
use anyhow::{Result, anyhow};
use super::super::Tool;
use super::super::ToolCtx;
use crate::model::memory::Memory;
pub struct Recall;
impl Tool for Recall {
fn name(&self) -> &'static str {
"recall"
}
fn description(&self) -> &'static str {
"Read memory entries. Pass a name to read a specific entry, or omit name to list all entries in the memory index. The memory index is also automatically injected into your system prompt."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Optional: exact name of a specific memory entry to read. If omitted, lists all entries."
}
}
})
}
fn run(&self, ctx: &ToolCtx, args: &Value) -> Result<String> {
if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
if name.is_empty() {
return list_all(ctx);
}
let memory = Memory::read(&ctx.memory_dir, name)
.map_err(|e| anyhow!("memory '{}' not found: {}", name, e))?;
Ok(format!(
"---\nname: {}\ndescription: {}\nkind: {}\nlifecycle: {}\n---\n\n{}",
memory.name,
memory.description,
memory.kind,
memory.lifecycle,
memory.content,
))
} else {
list_all(ctx)
}
}
}
fn list_all(ctx: &ToolCtx) -> Result<String> {
let names = Memory::list(&ctx.memory_dir);
if names.is_empty() {
return Ok("(no memory entries)".to_string());
}
let mut lines = format!("Memory index ({} entries):\n", names.len());
for name in &names {
if let Ok(mem) = Memory::read(&ctx.memory_dir, name) {
lines.push_str(&format!("- {} [{}]: {}\n", name, mem.kind, mem.description));
} else {
lines.push_str(&format!("- {}\n", name));
}
}
Ok(lines)
}
+79
View File
@@ -0,0 +1,79 @@
use serde_json::{json, Value};
use anyhow::{Result, anyhow};
use super::super::Tool;
use super::super::ToolCtx;
use crate::model::memory::Memory;
pub struct Remember;
impl Tool for Remember {
fn name(&self) -> &'static str {
"remember"
}
fn description(&self) -> &'static str {
"Save a piece of information to persistent project memory. Memory entries are injected into future conversations via the system prompt, so use this to record conventions, preferences, and important context."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Short unique name for the memory (kebab-case, e.g. 'testing-conventions')"
},
"description": {
"type": "string",
"description": "One-line summary shown in the memory index"
},
"content": {
"type": "string",
"description": "The memory content body"
},
"kind": {
"type": "string",
"description": "Type of memory: 'project', 'reference', 'lesson', or 'feedback'",
"enum": ["project", "reference", "lesson", "feedback"]
}
},
"required": ["name", "description", "content", "kind"]
})
}
fn run(&self, ctx: &ToolCtx, args: &Value) -> Result<String> {
let name = args.get("name")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("missing required argument: name"))?;
let description = args.get("description")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("missing required argument: description"))?;
let content = args.get("content")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("missing required argument: content"))?;
let kind = args.get("kind")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("missing required argument: kind"))?;
if Memory::slugify(name).is_none() {
anyhow::bail!("invalid memory name: must produce a valid slug (alphanumeric + hyphens, 1-80 chars)");
}
let now = chrono::Utc::now().timestamp_millis();
let memory = Memory {
name: name.to_string(),
description: description.to_string(),
content: content.to_string(),
kind: kind.to_string(),
created_at: now,
updated_at: now,
outcome: None,
lifecycle: "new".to_string(),
};
memory.write(&ctx.memory_dir)
.map_err(|e| anyhow!("failed to write memory '{}': {}", name, e))?;
Ok(format!("saved memory '{}' ({})", name, kind))
}
}
+11
View File
@@ -8,11 +8,13 @@ pub mod git_cred;
pub mod git_operator;
pub mod git_worktree;
pub mod internet;
pub mod memory;
pub mod plan;
pub mod search;
pub mod seqthink;
pub mod shell;
pub mod shell_filter;
pub mod utility;
pub mod workflow;
pub trait Tool: Send + Sync {
@@ -116,6 +118,7 @@ pub fn all_tools() -> Vec<Box<dyn Tool>> {
Box::new(super::tool::fs::read::Read),
Box::new(super::tool::fs::write::Write),
Box::new(super::tool::fs::edit::Edit),
Box::new(super::tool::fs::delete::Delete),
Box::new(super::tool::search::Grep),
Box::new(super::tool::search::Glob),
Box::new(super::tool::bash_tools::BashOutput),
@@ -131,6 +134,14 @@ pub fn all_tools() -> Vec<Box<dyn Tool>> {
Box::new(super::tool::internet::fetch::Fetch),
Box::new(super::tool::internet::download::Download),
Box::new(super::tool::internet::search::Search),
Box::new(super::tool::memory::remember::Remember),
Box::new(super::tool::memory::forget::Forget),
Box::new(super::tool::memory::recall::Recall),
Box::new(super::tool::utility::cd::Cd),
Box::new(super::tool::utility::dir_list::DirList),
Box::new(super::tool::utility::dir_cache_update::DirCacheUpdate),
Box::new(super::tool::utility::pong::Pong),
Box::new(super::tool::utility::todowrite::Todowrite),
]
}
+47
View File
@@ -0,0 +1,47 @@
use serde_json::{json, Value};
use anyhow::{Result, anyhow};
use super::super::Tool;
use super::super::ToolCtx;
pub struct Cd;
impl Tool for Cd {
fn name(&self) -> &'static str {
"cd"
}
fn description(&self) -> &'static str {
"Check if a directory exists within the workspace and print its resolved path. Use this to verify a directory path before running other commands there."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Directory path (relative to workspace root)"
}
},
"required": ["path"]
})
}
fn run(&self, ctx: &ToolCtx, args: &Value) -> Result<String> {
let rel = args.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("missing required argument: path"))?;
let path = super::super::resolve_path(&ctx.workspaces, rel)?;
if !path.exists() {
return Ok(format!("path '{}' does not exist (resolved to {})", rel, path.display()));
}
if !path.is_dir() {
return Ok(format!("path '{}' is not a directory (resolved to {})", rel, path.display()));
}
let canon = path.canonicalize().unwrap_or(path);
Ok(format!("{}", canon.display()))
}
}
+64
View File
@@ -0,0 +1,64 @@
use serde_json::{json, Value};
use anyhow::{Result, anyhow};
use super::super::Tool;
use super::super::ToolCtx;
pub struct DirCacheUpdate;
impl Tool for DirCacheUpdate {
fn name(&self) -> &'static str {
"dir_cache_update"
}
fn description(&self) -> &'static str {
"Update the cached directory listing for a path. The directory cache is used by other tools for faster path resolution."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Directory path to cache (relative to workspace root)"
}
},
"required": ["path"]
})
}
fn run(&self, ctx: &ToolCtx, args: &Value) -> Result<String> {
let rel = args.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("missing required argument: path"))?;
let path = super::super::resolve_path(&ctx.workspaces, rel)?;
if !path.exists() {
return Ok(format!("path '{}' does not exist (resolved to {})", rel, path.display()));
}
let entries = walk_directory(&path);
let count = entries.len();
let dc = ctx.dir_cache.clone();
let rt = tokio::runtime::Handle::try_current()
.map_err(|e| anyhow!("no tokio runtime available: {}", e))?;
rt.block_on(async move {
let cache = dc.write().await;
cache.set(entries).await;
});
Ok(format!("cached {} entries for {}", count, rel))
}
}
fn walk_directory(path: &std::path::Path) -> Vec<std::path::PathBuf> {
let mut result = Vec::new();
if let Ok(entries) = std::fs::read_dir(path) {
for entry in entries.flatten() {
result.push(entry.path());
}
}
result
}
+67
View File
@@ -0,0 +1,67 @@
use std::fs;
use serde_json::{json, Value};
use anyhow::{Result, anyhow};
use super::super::Tool;
use super::super::ToolCtx;
pub struct DirList;
impl Tool for DirList {
fn name(&self) -> &'static str {
"dir_list"
}
fn description(&self) -> &'static str {
"List files and directories in a directory. Use this to explore the workspace structure."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Directory path to list (relative to workspace root)"
}
},
"required": ["path"]
})
}
fn run(&self, ctx: &ToolCtx, args: &Value) -> Result<String> {
let rel = args.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("missing required argument: path"))?;
let path = super::super::resolve_path(&ctx.workspaces, rel)?;
if !path.exists() {
return Ok(format!("path '{}' does not exist (resolved to {})", rel, path.display()));
}
if !path.is_dir() {
return Ok(format!("path '{}' is not a directory (resolved to {})", rel, path.display()));
}
let entries: Vec<String> = fs::read_dir(&path)
.map_err(|e| anyhow!("failed to read directory '{}': {}", rel, e))?
.filter_map(|e| e.ok())
.map(|e| {
let name = e.file_name().to_string_lossy().to_string();
let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);
if is_dir {
format!("{}/", name)
} else {
name
}
})
.collect();
let canon = path.canonicalize().unwrap_or(path);
let header = format!("{} entries in {}:\n", entries.len(), canon.display());
if entries.is_empty() {
Ok(format!("{} (empty directory)", header.trim()))
} else {
Ok(header + &entries.join("\n"))
}
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod cd;
pub mod dir_cache_update;
pub mod dir_list;
pub mod pong;
pub mod todowrite;
+35
View File
@@ -0,0 +1,35 @@
use serde_json::{json, Value};
use anyhow::Result;
use super::super::Tool;
use super::super::ToolCtx;
pub struct Pong;
impl Tool for Pong {
fn name(&self) -> &'static str {
"pong"
}
fn description(&self) -> &'static str {
"Simple connectivity check. Echoes back any input for health checks and latency testing."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "Message to echo back"
}
}
})
}
fn run(&self, _ctx: &ToolCtx, args: &Value) -> Result<String> {
let msg = args.get("message")
.and_then(|v| v.as_str())
.unwrap_or("pong");
Ok(format!("pong: {}", msg))
}
}
+54
View File
@@ -0,0 +1,54 @@
use std::fs;
use std::path::PathBuf;
use serde_json::{json, Value};
use anyhow::{Result, anyhow};
use super::super::Tool;
use super::super::ToolCtx;
pub struct Todowrite;
impl Tool for Todowrite {
fn name(&self) -> &'static str {
"todowrite"
}
fn description(&self) -> &'static str {
"Append a task to the session todo list. The todo persists in the session directory and is visible in the Todo panel."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"task": {
"type": "string",
"description": "Task description to add"
}
},
"required": ["task"]
})
}
fn run(&self, ctx: &ToolCtx, args: &Value) -> Result<String> {
let task = args.get("task")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("missing required argument: task"))?;
let path: PathBuf = ctx.session_dir.join("todo.md");
let now = chrono::Utc::now();
let timestamp = now.format("%Y-%m-%d %H:%M:%S");
let line = format!("- [ ] {} ({})\n", task, timestamp);
fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.map_err(|e| anyhow!("failed to open todo.md: {}", e))?
.write_all(line.as_bytes())
.map_err(|e| anyhow!("failed to write to todo.md: {}", e))?;
Ok(format!("added task to todo.md: {}", task))
}
}
use std::io::Write;