| 1 | //! Model capture proposes candidates. It cannot review or delete user memory. |
| 2 | //! The trusted Context Lens owns approval, correction and forgetting controls. |
| 3 | use super::spec::{ |
| 4 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 5 | }; |
| 6 | use async_trait::async_trait; |
| 7 | use codewhale_runtime::native_memory::{MemoryScope, NativeMemoryStore}; |
| 8 | use serde::Deserialize; |
| 9 | use serde_json::{Value, json}; |
| 10 | |
| 11 | #[derive(Deserialize)] |
| 12 | #[serde(deny_unknown_fields)] |
| 13 | struct Input { |
| 14 | action: Option<String>, |
| 15 | note: Option<String>, |
| 16 | replaces: Option<String>, |
| 17 | evidence: Option<String>, |
| 18 | scope: Option<String>, |
| 19 | limit: Option<u64>, |
| 20 | } |
| 21 | pub struct RememberTool; |
| 22 | #[async_trait] |
| 23 | impl ToolSpec for RememberTool { |
| 24 | fn name(&self) -> &'static str { |
| 25 | "remember" |
| 26 | } |
| 27 | fn description(&self) -> &'static str { |
| 28 | "Propose a durable memory or correction for review in Context Lens. A successful capture is a candidate, not active knowledge. Do not store secrets, transient task state or private reasoning. Existing memory is never silently replaced or deleted by this tool. action=list returns up to limit current notes with their exact text for `replaces`." |
| 29 | } |
| 30 | fn input_schema(&self) -> Value { |
| 31 | json!({"type":"object","additionalProperties":false,"properties":{ |
| 32 | "action":{"type":"string","enum":["append","revise","list"],"default":"append"}, |
| 33 | "note":{"type":"string","minLength":1,"maxLength":8192}, |
| 34 | "scope":{"type":"string","enum":["global","workspace"]}, |
| 35 | "replaces":{"type":"string","description":"Exact current note, required for a correction."}, |
| 36 | "evidence":{"type":"string","description":"Why the proposed correction is supported."}, |
| 37 | "limit":{"type":"integer","minimum":1,"maximum":20,"default":8,"description":"list only."} |
| 38 | }}) |
| 39 | } |
| 40 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 41 | vec![ToolCapability::WritesFiles] |
| 42 | } |
| 43 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 44 | ApprovalRequirement::Auto |
| 45 | } |
| 46 | fn is_read_only_for(&self, input: &Value) -> bool { |
| 47 | input.get("action").and_then(Value::as_str) == Some("list") |
| 48 | } |
| 49 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 50 | let input: Input = serde_json::from_value(input).map_err(|error| { |
| 51 | ToolError::invalid_input(format!("invalid memory proposal: {error}")) |
| 52 | })?; |
| 53 | let path = context |
| 54 | .memory_path |
| 55 | .clone() |
| 56 | .ok_or_else(|| ToolError::execution_failed("memory is disabled"))?; |
| 57 | let store = NativeMemoryStore::from_global_path(&path) |
| 58 | .ok_or_else(|| ToolError::execution_failed("native memory store is not configured"))?; |
| 59 | let workspace = context.workspace.clone(); |
| 60 | let action = input.action.unwrap_or_else(|| "append".into()); |
| 61 | if !matches!(action.as_str(), "append" | "revise" | "list") { |
| 62 | return Err(ToolError::invalid_input( |
| 63 | "Only append, revise and list are supported. Forgetting requires the user's Context Lens control.", |
| 64 | )); |
| 65 | } |
| 66 | if action == "list" { |
| 67 | let scope = match input.scope.as_deref() { |
| 68 | None => None, |
| 69 | Some("global") => Some(MemoryScope::Global), |
| 70 | Some("workspace") => Some(MemoryScope::Workspace), |
| 71 | Some(_) => { |
| 72 | return Err(ToolError::invalid_input( |
| 73 | "scope must be global or workspace", |
| 74 | )); |
| 75 | } |
| 76 | }; |
| 77 | let limit = input.limit.unwrap_or(8).clamp(1, 20) as usize; |
| 78 | let hits = tokio::task::spawn_blocking(move || { |
| 79 | let workspace_id = NativeMemoryStore::workspace_id(&workspace)?; |
| 80 | store.list_in_workspace(scope, workspace_id.as_deref(), Some(&workspace), limit + 1) |
| 81 | }) |
| 82 | .await |
| 83 | .map_err(|_| ToolError::execution_failed("memory worker stopped"))? |
| 84 | .map_err(|error| ToolError::execution_failed(format!("memory list failed: {error}")))?; |
| 85 | return Ok(super::native_memory::output(hits, limit)); |
| 86 | } |
| 87 | let note = input |
| 88 | .note |
| 89 | .filter(|s| !s.trim().is_empty()) |
| 90 | .ok_or_else(|| ToolError::invalid_input("a note is required"))?; |
| 91 | let scope = match input.scope.as_deref().unwrap_or("workspace") { |
| 92 | "global" => MemoryScope::Global, |
| 93 | "workspace" => MemoryScope::Workspace, |
| 94 | _ => { |
| 95 | return Err(ToolError::invalid_input( |
| 96 | "scope must be global or workspace", |
| 97 | )); |
| 98 | } |
| 99 | }; |
| 100 | let hit=tokio::task::spawn_blocking(move||{ |
| 101 | let workspace_id=if scope==MemoryScope::Workspace { |
| 102 | Some(NativeMemoryStore::workspace_id(&workspace).map_err(|error|ToolError::execution_failed(format!("workspace identity unavailable: {error}")))? |
| 103 | .ok_or_else(||ToolError::execution_failed("workspace memory needs a git origin; explicitly select global for a user preference"))?) |
| 104 | } else {None}; |
| 105 | let result=if action=="revise" { |
| 106 | let from=input.replaces.as_deref().filter(|s|!s.trim().is_empty()).ok_or_else(||ToolError::invalid_input("replaces is required"))?; |
| 107 | let evidence=input.evidence.as_deref().filter(|s|!s.trim().is_empty()).ok_or_else(||ToolError::invalid_input("evidence is required"))?; |
| 108 | store.revise(scope,workspace_id.as_deref(),from,¬e,evidence) |
| 109 | } else {store.remember(scope,workspace_id.as_deref(),¬e)}; |
| 110 | result.map_err(|error|ToolError::execution_failed(format!("memory proposal was rejected or could not be stored: {error}; no active memory was changed"))) |
| 111 | }).await.map_err(|_|ToolError::execution_failed("memory worker stopped"))??; |
| 112 | Ok(ToolResult::success(format!("Memory candidate #{} is available for review in Context Lens. It is not active context; existing knowledge is unchanged.",hit.id)) |
| 113 | .with_metadata(json!({"memory_backend":"native","memory_schema":2,"memory_id":hit.id,"candidate":true,"untrusted":true}))) |
| 114 | } |
| 115 | } |
| 116 | #[cfg(test)] |
| 117 | mod tests { |
| 118 | use super::*; |
| 119 | use codewhale_memory::{Access, Status}; |
| 120 | #[tokio::test] |
| 121 | async fn disabled_capture_does_not_create_store() { |
| 122 | let temp = tempfile::tempdir().unwrap(); |
| 123 | let mut context = ToolContext::new(temp.path()); |
| 124 | context.memory_path = None; |
| 125 | assert!( |
| 126 | RememberTool |
| 127 | .execute( |
| 128 | json!({"note":"Keep constraints explicit","scope":"global"}), |
| 129 | &context |
| 130 | ) |
| 131 | .await |
| 132 | .is_err() |
| 133 | ); |
| 134 | assert!(!temp.path().join("memory").exists()); |
| 135 | } |
| 136 | #[tokio::test] |
| 137 | async fn capture_is_reviewable_not_recalled() { |
| 138 | let temp = tempfile::tempdir().unwrap(); |
| 139 | let mut context = ToolContext::new(temp.path()); |
| 140 | let root = temp.path().join("memory"); |
| 141 | context.memory_path = Some(root.join("global/MEMORY.md")); |
| 142 | let result = RememberTool |
| 143 | .execute( |
| 144 | json!({"note":"Keep constraints explicit","scope":"global"}), |
| 145 | &context, |
| 146 | ) |
| 147 | .await |
| 148 | .unwrap(); |
| 149 | assert!(result.success); |
| 150 | let native = NativeMemoryStore::new(&root); |
| 151 | assert!(native.search("constraints", 10).unwrap().is_empty()); |
| 152 | let store = native.open_structured().unwrap(); |
| 153 | let access = Access::operator(vec![NativeMemoryStore::owner_scope()]).unwrap(); |
| 154 | assert_eq!( |
| 155 | store.list(&access, None, 10).unwrap()[0].status, |
| 156 | Status::Candidate |
| 157 | ); |
| 158 | assert!(!root.join("global/MEMORY.md").exists()); |
| 159 | } |
| 160 | #[tokio::test] |
| 161 | async fn rejected_correction_reports_the_store_reason_and_list_is_bounded() { |
| 162 | let temp = tempfile::tempdir().unwrap(); |
| 163 | let mut context = ToolContext::new(temp.path()); |
| 164 | context.memory_path = Some(temp.path().join("memory/global/MEMORY.md")); |
| 165 | let error = RememberTool |
| 166 | .execute( |
| 167 | json!({"action":"revise","note":"new","replaces":"missing","evidence":"seen","scope":"global"}), |
| 168 | &context, |
| 169 | ) |
| 170 | .await |
| 171 | .unwrap_err(); |
| 172 | assert!( |
| 173 | error.to_string().contains("exactly one active note"), |
| 174 | "{error}" |
| 175 | ); |
| 176 | let list = json!({"action":"list","scope":"global","limit":3}); |
| 177 | assert!(RememberTool.is_read_only_for(&list)); |
| 178 | let listed = RememberTool.execute(list, &context).await.unwrap(); |
| 179 | assert!(listed.content.contains("No bounded memory matches.")); |
| 180 | } |
| 181 | #[tokio::test] |
| 182 | async fn list_limits_eligible_notes_and_reports_when_more_remain() { |
| 183 | use codewhale_memory::{MemoryBackend, Snapshot}; |
| 184 | |
| 185 | let temp = tempfile::tempdir().unwrap(); |
| 186 | let root = temp.path().join("memory"); |
| 187 | let mut context = ToolContext::new(temp.path()); |
| 188 | context.memory_path = Some(root.join("global/MEMORY.md")); |
| 189 | let native = NativeMemoryStore::new(&root); |
| 190 | let empty = RememberTool |
| 191 | .execute(json!({"action":"list"}), &context) |
| 192 | .await |
| 193 | .unwrap(); |
| 194 | assert_eq!(empty.metadata.unwrap()["count"], 0); |
| 195 | assert!(!root.exists()); |
| 196 | for note in ["Use cedar.", "Use birch.", "Use spruce."] { |
| 197 | native.remember(MemoryScope::Global, None, note).unwrap(); |
| 198 | } |
| 199 | let access = Access::operator(vec![NativeMemoryStore::owner_scope()]).unwrap(); |
| 200 | let mut store = native.open_structured().unwrap(); |
| 201 | let ordered = store.list(&access, None, 3).unwrap(); |
| 202 | let list = json!({"action":"list","scope":"global","limit":1}); |
| 203 | for (index, memory) in ordered.iter().enumerate().skip(1) { |
| 204 | store |
| 205 | .approve( |
| 206 | &access, |
| 207 | &memory.id, |
| 208 | memory.revision, |
| 209 | None, |
| 210 | &Snapshot::default(), |
| 211 | ) |
| 212 | .unwrap(); |
| 213 | let listed = RememberTool.execute(list.clone(), &context).await.unwrap(); |
| 214 | let metadata = listed.metadata.unwrap(); |
| 215 | assert_eq!(metadata["count"], 1); |
| 216 | assert_eq!(metadata["truncated"], index > 1); |
| 217 | assert!(listed.content.contains(&ordered[1].draft.body)); |
| 218 | assert!(!listed.content.contains(&ordered[0].draft.body)); |
| 219 | assert!(!listed.content.contains(&ordered[2].draft.body)); |
| 220 | } |
| 221 | } |
| 222 | #[tokio::test] |
| 223 | async fn listing_checks_workspace_dependency_freshness() { |
| 224 | use codewhale_memory::{MemoryBackend, policy, workspace}; |
| 225 | |
| 226 | let temp = tempfile::tempdir().unwrap(); |
| 227 | let mut context = ToolContext::new(temp.path()); |
| 228 | let native = NativeMemoryStore::new(temp.path().join("memory")); |
| 229 | context.memory_path = Some(native.global_path()); |
| 230 | let id = NativeMemoryStore::workspace_id(temp.path()) |
| 231 | .unwrap() |
| 232 | .unwrap(); |
| 233 | let access = |
| 234 | Access::operator(vec![NativeMemoryStore::workspace_scope(&id).unwrap()]).unwrap(); |
| 235 | native |
| 236 | .remember(MemoryScope::Workspace, Some(&id), "Fixture note.") |
| 237 | .unwrap(); |
| 238 | let mut store = native.open_structured().unwrap(); |
| 239 | let mut draft = store.list(&access, None, 1).unwrap().remove(0).draft; |
| 240 | draft.body = "This note tracks file state.".into(); |
| 241 | draft |
| 242 | .dependencies |
| 243 | .insert("note.txt".into(), policy::sha256(b"first")); |
| 244 | std::fs::write(temp.path().join("note.txt"), "first").unwrap(); |
| 245 | let memory = store |
| 246 | .capture(&access, "file-dependent-note", draft) |
| 247 | .unwrap() |
| 248 | .memory; |
| 249 | let snapshot = workspace::snapshot(temp.path(), ["note.txt".to_owned()]).unwrap(); |
| 250 | store |
| 251 | .approve(&access, &memory.id, memory.revision, None, &snapshot) |
| 252 | .unwrap(); |
| 253 | let list = json!({"action":"list","scope":"workspace"}); |
| 254 | assert!( |
| 255 | RememberTool |
| 256 | .execute(list.clone(), &context) |
| 257 | .await |
| 258 | .unwrap() |
| 259 | .content |
| 260 | .contains("freshness=current") |
| 261 | ); |
| 262 | std::fs::write(temp.path().join("note.txt"), "second").unwrap(); |
| 263 | assert!( |
| 264 | RememberTool |
| 265 | .execute(list, &context) |
| 266 | .await |
| 267 | .unwrap() |
| 268 | .content |
| 269 | .contains("freshness=stale_or_unknown") |
| 270 | ); |
| 271 | } |
| 272 | |
| 273 | #[tokio::test] |
| 274 | async fn forged_review_field_is_rejected() { |
| 275 | let temp = tempfile::tempdir().unwrap(); |
| 276 | let context = ToolContext::new(temp.path()); |
| 277 | assert!( |
| 278 | RememberTool |
| 279 | .execute(json!({"note":"claim","approved":true}), &context) |
| 280 | .await |
| 281 | .is_err() |
| 282 | ); |
| 283 | } |
| 284 | } |
| 285 |