recursive-agent 0.6.0

A minimal, orthogonal, self-improving coding agent kernel in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
//! Persistent memory tools: `remember`, `recall`, `forget`.
//!
//! Also provides a scratchpad (working memory) layer: `scratchpad_set`,
//! `scratchpad_get`, `scratchpad_delete`, `scratchpad_list`. The scratchpad
//! is stored in `<workspace>/.recursive/scratchpad.json` and its contents
//! are injected into the system prompt as a summary.
//!
//! Notes are stored in `<workspace>/.recursive/memory.json` (or
//! `~/.recursive/memory.json` if `RECURSIVE_MEMORY_GLOBAL=1`).
//! Schema:
//! ```json
//! { "notes": [ { "id": "N1", "tags": ["rust"], "text": "...", "ts": "..." } ] }
//! ```

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use crate::error::{Error, Result};
use crate::llm::ToolSpec;
use crate::memory::{EmbeddingProvider, MemoryEntry, NoopEmbedding, NoopVectorStore, VectorStore};
use crate::tools::Tool;

/// A single memory note.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Note {
    pub id: String,
    #[serde(default)]
    pub tags: Vec<String>,
    pub text: String,
    pub ts: String,
}

/// The on-disk store.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MemoryStore {
    pub notes: Vec<Note>,
}

impl MemoryStore {
    /// Load from a path, returning an empty store if the file doesn't exist.
    fn load(path: &std::path::Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let raw = std::fs::read_to_string(path).map_err(|e| Error::Tool {
            name: "memory".into(),
            message: format!("failed to read memory file: {e}"),
        })?;
        serde_json::from_str(&raw).map_err(|e| Error::Tool {
            name: "memory".into(),
            message: format!("malformed memory file: {e}"),
        })
    }

    /// Save to disk, creating parent directories if needed.
    fn save(&self, path: &std::path::Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| Error::Tool {
                name: "memory".into(),
                message: format!("failed to create memory directory: {e}"),
            })?;
        }
        let raw = serde_json::to_string_pretty(self).map_err(|e| Error::Tool {
            name: "memory".into(),
            message: format!("failed to serialize memory: {e}"),
        })?;
        std::fs::write(path, raw).map_err(|e| Error::Tool {
            name: "memory".into(),
            message: format!("failed to write memory file: {e}"),
        })?;
        Ok(())
    }

    /// Generate the next monotonic ID.
    fn next_id(&self) -> String {
        let max = self
            .notes
            .iter()
            .filter_map(|n| n.id.strip_prefix('N'))
            .filter_map(|s| s.parse::<u32>().ok())
            .max()
            .unwrap_or(0);
        format!("N{}", max + 1)
    }

    /// Add a note, returning its ID.
    fn add(&mut self, text: String, tags: Vec<String>) -> String {
        let id = self.next_id();
        let ts = chrono_now_rfc3339();
        self.notes.push(Note {
            id: id.clone(),
            tags,
            text,
            ts,
        });
        id
    }

    /// Remove a note by ID. Returns true if found.
    fn remove(&mut self, id: &str) -> bool {
        let before = self.notes.len();
        self.notes.retain(|n| n.id != id);
        self.notes.len() < before
    }

    /// Search notes by query (case-insensitive substring in text or tags)
    /// or by exact tag match. Returns up to `limit` results, most recent first.
    fn search(&self, query: Option<&str>, tag: Option<&str>, limit: usize) -> Vec<&Note> {
        let mut results: Vec<&Note> = self
            .notes
            .iter()
            .filter(|n| {
                let matches_query = query.map_or(true, |q| {
                    let q_lower = q.to_lowercase();
                    n.text.to_lowercase().contains(&q_lower)
                        || n.tags.iter().any(|t| t.to_lowercase().contains(&q_lower))
                });
                let matches_tag = tag.map_or(true, |t| n.tags.iter().any(|nt| nt == t));
                matches_query && matches_tag
            })
            .collect();
        // Most recent first (reverse chronological)
        results.reverse();
        results.truncate(limit);
        results
    }
}

/// Get an RFC 3339 timestamp string.
fn chrono_now_rfc3339() -> String {
    // Use std::time to build a simple UTC timestamp without chrono dependency.
    let dur = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let secs = dur.as_secs();
    // Format as ISO 8601 / RFC 3339
    let days = secs / 86400;
    let time_secs = secs % 86400;
    let hours = time_secs / 3600;
    let minutes = (time_secs % 3600) / 60;
    let seconds = time_secs % 60;

    // Compute year/month/day from days since epoch (simplified)
    let (year, month, day) = days_to_date(days);
    format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
        year, month, day, hours, minutes, seconds
    )
}

/// Convert days since Unix epoch to (year, month, day).
/// Uses a simple leap-year-aware algorithm.
fn days_to_date(mut days: u64) -> (u64, u64, u64) {
    // Start from 1970-01-01
    let mut year: u64 = 1970;
    loop {
        let days_in_year = if is_leap(year) { 366 } else { 365 };
        if days < days_in_year {
            break;
        }
        days -= days_in_year;
        year += 1;
    }
    let months_days: [u64; 12] = if is_leap(year) {
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };
    let mut month: u64 = 1;
    for &md in &months_days {
        if days < md {
            break;
        }
        days -= md;
        month += 1;
    }
    let day = days + 1; // 1-indexed
    (year, month, day)
}

fn is_leap(year: u64) -> bool {
    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}

/// Determine the memory file path based on workspace and env var.
pub fn memory_path(workspace: &std::path::Path) -> PathBuf {
    if std::env::var("RECURSIVE_MEMORY_GLOBAL").as_deref() == Ok("1") {
        if let Some(home) = std::env::var_os("HOME") {
            return PathBuf::from(home).join(".recursive").join("memory.json");
        }
    }
    workspace.join(".recursive").join("memory.json")
}

/// Load the memory store from the workspace-relative path.
pub fn load_memory(workspace: &std::path::Path) -> Result<MemoryStore> {
    let path = memory_path(workspace);
    MemoryStore::load(&path)
}

/// Build a memory summary string for injection into the system prompt.
/// Returns the top N most recent notes as a formatted block, or empty
/// string if no notes exist.
pub fn memory_summary(workspace: &std::path::Path, limit: usize) -> String {
    let store = match load_memory(workspace) {
        Ok(s) => s,
        Err(_) => return String::new(),
    };
    if store.notes.is_empty() {
        return String::new();
    }
    let mut lines: Vec<String> = Vec::new();
    lines.push(format!(
        "# Memory (top {} most recent notes; use `recall` for more)",
        limit
    ));
    // Most recent first
    let mut notes: Vec<&Note> = store.notes.iter().collect();
    notes.reverse();
    for note in notes.iter().take(limit) {
        let tags_str = if note.tags.is_empty() {
            String::new()
        } else {
            format!(" [{}]", note.tags.join(","))
        };
        // Truncate long text for the summary
        let text_preview = if note.text.len() > 120 {
            format!("{}...", crate::truncate_str(&note.text, 117))
        } else {
            note.text.clone()
        };
        lines.push(format!("- {}{} {}", note.id, tags_str, text_preview));
    }
    lines.join("\n")
}

// ---------------------------------------------------------------------------
// Tool implementations
// ---------------------------------------------------------------------------

pub struct Remember {
    workspace: PathBuf,
    /// Mutex for thread-safe access to the memory file.
    lock: Mutex<()>,
    /// Optional vector store for semantic indexing.
    vector_store: Arc<dyn VectorStore>,
    /// Optional embedding provider for generating vectors.
    embedding_provider: Arc<dyn EmbeddingProvider>,
}

impl Remember {
    pub fn new(workspace: impl Into<PathBuf>) -> Self {
        Self {
            workspace: workspace.into(),
            lock: Mutex::new(()),
            vector_store: Arc::new(NoopVectorStore::new()),
            embedding_provider: Arc::new(NoopEmbedding),
        }
    }

    /// Inject a vector store + embedding provider for semantic indexing.
    ///
    /// When set, every `remember` call will also embed the text and upsert the
    /// vector into the store, enabling semantic `recall` queries.
    pub fn with_vector_store(
        mut self,
        store: Arc<dyn VectorStore>,
        embedding: Arc<dyn EmbeddingProvider>,
    ) -> Self {
        self.vector_store = store;
        self.embedding_provider = embedding;
        self
    }
}

#[async_trait]
impl Tool for Remember {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "remember".into(),
            description: "Save a note to persistent memory. The note will be available in future sessions via `recall` or injected into the system prompt.".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "text": {
                        "type": "string",
                        "description": "The note text to remember"
                    },
                    "tags": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Optional tags for categorising the note"
                    }
                },
                "required": ["text"]
            }),
        }
    }

    fn side_effect_class(&self) -> crate::tools::ToolSideEffect {
        crate::tools::ToolSideEffect::Mutating
    }

    async fn execute(&self, arguments: Value) -> Result<String> {
        let text = arguments["text"]
            .as_str()
            .ok_or_else(|| Error::BadToolArgs {
                name: "remember".into(),
                message: "missing required parameter: text".to_string(),
            })?
            .to_string();

        let tags: Vec<String> = arguments["tags"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();

        let _guard = self.lock.lock().unwrap();
        let path = memory_path(&self.workspace);
        let mut file_store = MemoryStore::load(&path)?;
        let id = file_store.add(text.clone(), tags.clone());
        file_store.save(&path)?;
        drop(_guard);

        // Also index in the vector store if one is configured.
        let ts = chrono::Utc::now().to_rfc3339();
        let entry = MemoryEntry {
            id: id.clone(),
            text: text.clone(),
            tags,
            ts,
        };
        let vector = self.embedding_provider.embed(&text).await;
        if let Err(e) = self.vector_store.upsert(&entry, vector).await {
            tracing::warn!(error = %e, note_id = %id, "remember: vector upsert failed");
        }

        Ok(format!("saved note {id}"))
    }
}

pub struct Recall {
    workspace: PathBuf,
    /// Optional vector store for semantic retrieval.
    vector_store: Arc<dyn VectorStore>,
    /// Optional embedding provider for query vectorisation.
    embedding_provider: Arc<dyn EmbeddingProvider>,
}

impl Recall {
    pub fn new(workspace: impl Into<PathBuf>) -> Self {
        Self {
            workspace: workspace.into(),
            vector_store: Arc::new(NoopVectorStore::new()),
            embedding_provider: Arc::new(NoopEmbedding),
        }
    }

    /// Inject a vector store + embedding provider for semantic retrieval.
    ///
    /// When set, `recall` will embed the query and perform cosine-similarity
    /// search instead of keyword substring search.
    pub fn with_vector_store(
        mut self,
        store: Arc<dyn VectorStore>,
        embedding: Arc<dyn EmbeddingProvider>,
    ) -> Self {
        self.vector_store = store;
        self.embedding_provider = embedding;
        self
    }
}

#[async_trait]
impl Tool for Recall {
    fn side_effect_class(&self) -> crate::tools::ToolSideEffect {
        crate::tools::ToolSideEffect::ReadOnly
    }

    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "recall".into(),
            description: "Search persistent memory for notes matching a query or tag. Returns up to `limit` results, most recent first.".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Case-insensitive substring to search for in note text or tags"
                    },
                    "tag": {
                        "type": "string",
                        "description": "Exact tag to filter by"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum number of results (default 10)",
                        "default": 10
                    }
                }
            }),
        }
    }

    async fn execute(&self, arguments: Value) -> Result<String> {
        let query = arguments["query"].as_str().unwrap_or("");
        let tag = arguments["tag"].as_str();
        let limit = arguments["limit"].as_i64().unwrap_or(10) as usize;

        // Try vector search first; fall back to file-based keyword search
        // when the vector store or embedding provider is a no-op.
        let query_vec = self.embedding_provider.embed(query).await;
        let use_vector = !query_vec.is_empty();

        if use_vector || tag.is_none() {
            // Use the vector store (semantic or keyword fallback inside the store).
            match self.vector_store.search(query_vec, query, limit).await {
                Ok(entries) if !entries.is_empty() => {
                    // Apply tag filter if requested.
                    let filtered: Vec<_> = entries
                        .iter()
                        .filter(|e| tag.map_or(true, |t| e.tags.iter().any(|et| et == t)))
                        .take(limit)
                        .collect();
                    if !filtered.is_empty() {
                        let lines: Vec<String> = filtered
                            .iter()
                            .map(|e| {
                                let tags_str = if e.tags.is_empty() {
                                    String::new()
                                } else {
                                    format!(" [{}]", e.tags.join(","))
                                };
                                format!("{}{} {}", e.id, tags_str, e.text)
                            })
                            .collect();
                        return Ok(lines.join("\n"));
                    }
                }
                Ok(_) => {}
                Err(e) => {
                    tracing::warn!(error = %e, "recall: vector search failed, falling back to file");
                }
            }
        }

        // File-based fallback (or when only tag filter is used).
        let path = memory_path(&self.workspace);
        let file_store = MemoryStore::load(&path)?;
        let query_opt = if query.is_empty() { None } else { Some(query) };
        let results = file_store.search(query_opt, tag, limit);

        if results.is_empty() {
            return Ok("no matching notes found".to_string());
        }

        let lines: Vec<String> = results
            .iter()
            .map(|n| {
                let tags_str = if n.tags.is_empty() {
                    String::new()
                } else {
                    format!(" [{}]", n.tags.join(","))
                };
                format!("{}{} {}", n.id, tags_str, n.text)
            })
            .collect();

        Ok(lines.join("\n"))
    }
}

pub struct Forget {
    workspace: PathBuf,
    lock: Mutex<()>,
}

impl Forget {
    pub fn new(workspace: impl Into<PathBuf>) -> Self {
        Self {
            workspace: workspace.into(),
            lock: Mutex::new(()),
        }
    }
}

#[async_trait]
impl Tool for Forget {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "forget".into(),
            description: "Remove a note from persistent memory by its ID.".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "id": {
                        "type": "string",
                        "description": "The ID of the note to remove (e.g. N3)"
                    }
                },
                "required": ["id"]
            }),
        }
    }

    async fn execute(&self, arguments: Value) -> Result<String> {
        let id = arguments["id"]
            .as_str()
            .ok_or_else(|| Error::BadToolArgs {
                name: "forget".into(),
                message: "missing required parameter: id".to_string(),
            })?
            .to_string();

        let _guard = self.lock.lock().unwrap();
        let path = memory_path(&self.workspace);
        let mut store = MemoryStore::load(&path)?;
        if store.remove(&id) {
            store.save(&path)?;
            Ok(format!("removed {id}"))
        } else {
            Ok(format!("no such id: {id}"))
        }
    }
}

// ---------------------------------------------------------------------------
// Scratchpad (working memory)
// ---------------------------------------------------------------------------

/// A single scratchpad entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScratchpadEntry {
    pub key: String,
    pub value: String,
}

/// The on-disk scratchpad store.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Scratchpad {
    pub entries: Vec<ScratchpadEntry>,
}

impl Scratchpad {
    /// Load from a path, returning an empty scratchpad if the file doesn't exist.
    fn load(path: &std::path::Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let raw = std::fs::read_to_string(path).map_err(|e| Error::Tool {
            name: "scratchpad".into(),
            message: format!("failed to read scratchpad file: {e}"),
        })?;
        serde_json::from_str(&raw).map_err(|e| Error::Tool {
            name: "scratchpad".into(),
            message: format!("malformed scratchpad file: {e}"),
        })
    }

    /// Save to disk, creating parent directories if needed.
    fn save(&self, path: &std::path::Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| Error::Tool {
                name: "scratchpad".into(),
                message: format!("failed to create scratchpad directory: {e}"),
            })?;
        }
        let raw = serde_json::to_string_pretty(self).map_err(|e| Error::Tool {
            name: "scratchpad".into(),
            message: format!("failed to serialize scratchpad: {e}"),
        })?;
        std::fs::write(path, raw).map_err(|e| Error::Tool {
            name: "scratchpad".into(),
            message: format!("failed to write scratchpad file: {e}"),
        })?;
        Ok(())
    }

    /// Set a key-value pair (insert or update).
    fn set(&mut self, key: String, value: String) {
        // Replace existing entry with the same key, or add new one.
        if let Some(existing) = self.entries.iter_mut().find(|e| e.key == key) {
            existing.value = value;
        } else {
            self.entries.push(ScratchpadEntry { key, value });
        }
    }

    /// Get the value for a key.
    fn get(&self, key: &str) -> Option<&str> {
        self.entries
            .iter()
            .find(|e| e.key == key)
            .map(|e| e.value.as_str())
    }

    /// Delete an entry by key. Returns true if found.
    fn delete(&mut self, key: &str) -> bool {
        let before = self.entries.len();
        self.entries.retain(|e| e.key != key);
        self.entries.len() < before
    }

    /// List all keys.
    fn keys(&self) -> Vec<&str> {
        self.entries.iter().map(|e| e.key.as_str()).collect()
    }
}

/// Determine the scratchpad file path. Lives under the per-user data
/// dir so it doesn't pollute the project tree:
/// `~/.recursive/workspaces/<ws-hash>/scratchpad.json`.
pub fn scratchpad_path(workspace: &std::path::Path) -> PathBuf {
    crate::paths::user_scratchpad_path(workspace)
        .unwrap_or_else(|_| workspace.join(".recursive").join("scratchpad.json"))
}

/// Load the scratchpad from the workspace-relative path.
pub fn load_scratchpad(workspace: &std::path::Path) -> Result<Scratchpad> {
    let path = scratchpad_path(workspace);
    Scratchpad::load(&path)
}

/// Build a scratchpad summary string for injection into the system prompt.
/// Returns a formatted block of all key-value pairs, or empty string if
/// the scratchpad is empty.
pub fn scratchpad_summary(workspace: &std::path::Path) -> String {
    let pad = match load_scratchpad(workspace) {
        Ok(p) => p,
        Err(_) => return String::new(),
    };
    if pad.entries.is_empty() {
        return String::new();
    }
    let mut lines: Vec<String> = Vec::new();
    lines.push("# Working Memory (scratchpad)".to_string());
    for entry in &pad.entries {
        // Truncate long values for the summary
        let value_preview = if entry.value.len() > 200 {
            format!("{}...", crate::truncate_str(&entry.value, 197))
        } else {
            entry.value.clone()
        };
        lines.push(format!("- {}: {}", entry.key, value_preview));
    }
    lines.join("\n")
}

/// Migrate old-format scratchpad data (if any) to the new format.
/// Currently a no-op placeholder for future migration logic.
pub fn migrate_scratchpad(_workspace: &std::path::Path) -> Result<()> {
    // No old format to migrate from yet.
    Ok(())
}

// ---------------------------------------------------------------------------
// WorkingMemoryTool: exposes scratchpad operations as tools
// ---------------------------------------------------------------------------

pub struct WorkingMemoryTool {
    workspace: PathBuf,
    lock: Mutex<()>,
}

impl WorkingMemoryTool {
    pub fn new(workspace: impl Into<PathBuf>) -> Self {
        Self {
            workspace: workspace.into(),
            lock: Mutex::new(()),
        }
    }
}

#[async_trait]
impl Tool for WorkingMemoryTool {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "scratchpad_set".into(),
            description: "Store a value in working memory (scratchpad) under a key. Use this to remember intermediate results, decisions, or context across steps. The scratchpad contents are injected into the system prompt.".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "key": {
                        "type": "string",
                        "description": "The key to store under"
                    },
                    "value": {
                        "type": "string",
                        "description": "The value to store"
                    }
                },
                "required": ["key", "value"]
            }),
        }
    }

    async fn execute(&self, arguments: Value) -> Result<String> {
        let key = arguments["key"]
            .as_str()
            .ok_or_else(|| Error::BadToolArgs {
                name: "scratchpad_set".into(),
                message: "missing required parameter: key".to_string(),
            })?
            .to_string();
        let value = arguments["value"]
            .as_str()
            .ok_or_else(|| Error::BadToolArgs {
                name: "scratchpad_set".into(),
                message: "missing required parameter: value".to_string(),
            })?
            .to_string();

        let _guard = self.lock.lock().unwrap();
        let path = scratchpad_path(&self.workspace);
        let mut pad = Scratchpad::load(&path)?;
        pad.set(key.clone(), value);
        pad.save(&path)?;
        Ok(format!("scratchpad key '{key}' set"))
    }
}

/// Helper: dispatch scratchpad operations based on the tool name.
/// This is used by the multi-tool approach where one struct handles
/// multiple tool names.
pub struct ScratchpadGet {
    workspace: PathBuf,
}

impl ScratchpadGet {
    pub fn new(workspace: impl Into<PathBuf>) -> Self {
        Self {
            workspace: workspace.into(),
        }
    }
}

#[async_trait]
impl Tool for ScratchpadGet {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "scratchpad_get".into(),
            description: "Retrieve a value from working memory (scratchpad) by key.".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "key": {
                        "type": "string",
                        "description": "The key to retrieve"
                    }
                },
                "required": ["key"]
            }),
        }
    }

    async fn execute(&self, arguments: Value) -> Result<String> {
        let key = arguments["key"]
            .as_str()
            .ok_or_else(|| Error::BadToolArgs {
                name: "scratchpad_get".into(),
                message: "missing required parameter: key".to_string(),
            })?
            .to_string();

        let path = scratchpad_path(&self.workspace);
        let pad = Scratchpad::load(&path)?;
        match pad.get(&key) {
            Some(value) => Ok(value.to_string()),
            None => Ok(format!("no such key: {key}")),
        }
    }
}

pub struct ScratchpadDelete {
    workspace: PathBuf,
    lock: Mutex<()>,
}

impl ScratchpadDelete {
    pub fn new(workspace: impl Into<PathBuf>) -> Self {
        Self {
            workspace: workspace.into(),
            lock: Mutex::new(()),
        }
    }
}

#[async_trait]
impl Tool for ScratchpadDelete {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "scratchpad_delete".into(),
            description: "Delete a key from working memory (scratchpad).".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "key": {
                        "type": "string",
                        "description": "The key to delete"
                    }
                },
                "required": ["key"]
            }),
        }
    }

    async fn execute(&self, arguments: Value) -> Result<String> {
        let key = arguments["key"]
            .as_str()
            .ok_or_else(|| Error::BadToolArgs {
                name: "scratchpad_delete".into(),
                message: "missing required parameter: key".to_string(),
            })?
            .to_string();

        let _guard = self.lock.lock().unwrap();
        let path = scratchpad_path(&self.workspace);
        let mut pad = Scratchpad::load(&path)?;
        if pad.delete(&key) {
            pad.save(&path)?;
            Ok(format!("scratchpad key '{key}' deleted"))
        } else {
            Ok(format!("no such key: {key}"))
        }
    }
}

pub struct ScratchpadList {
    workspace: PathBuf,
}

impl ScratchpadList {
    pub fn new(workspace: impl Into<PathBuf>) -> Self {
        Self {
            workspace: workspace.into(),
        }
    }
}

#[async_trait]
impl Tool for ScratchpadList {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "scratchpad_list".into(),
            description: "List all keys currently stored in working memory (scratchpad).".into(),
            parameters: json!({
                "type": "object",
                "properties": {}
            }),
        }
    }

    async fn execute(&self, _arguments: Value) -> Result<String> {
        let path = scratchpad_path(&self.workspace);
        let pad = Scratchpad::load(&path)?;
        let keys = pad.keys();
        if keys.is_empty() {
            return Ok("scratchpad is empty".to_string());
        }
        Ok(keys.join("\n"))
    }
}