sapphire-agent 0.4.1

A personal AI assistant agent with Matrix/Discord channels, Anthropic backend, and a sapphire-workspace memory layer
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
use crate::provider::ToolSpec;
use crate::tools::Tool;
use anyhow::{Context, Result};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use sapphire_workspace::{FtsQuery, VectorQuery, WorkspaceState};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::path::Path;
use std::sync::{Arc, Mutex};

// ---------------------------------------------------------------------------
// Shared helper
// ---------------------------------------------------------------------------

fn lock(state: &Mutex<WorkspaceState>) -> std::sync::MutexGuard<'_, WorkspaceState> {
    state.lock().expect("WorkspaceState mutex poisoned")
}

// ---------------------------------------------------------------------------
// memory
// ---------------------------------------------------------------------------

/// Validate a `category` or `slug` segment: non-empty, no path separators,
/// no parent-dir components, no leading dot.
fn validate_segment(kind: &str, value: &str) -> Result<()> {
    if value.is_empty() {
        anyhow::bail!("{kind} must not be empty");
    }
    if value == "." || value == ".." {
        anyhow::bail!("{kind} must not be '.' or '..'");
    }
    if value.starts_with('.') {
        anyhow::bail!("{kind} must not start with '.'");
    }
    if value.contains('/') || value.contains('\\') || value.contains('\0') {
        anyhow::bail!("{kind} must not contain path separators: {value:?}");
    }
    Ok(())
}

const MEMORY_CATEGORY_GUIDE: &str = "Category is mandatory and free-form, but prefer these conventions: \
     'daily' (date-stamped daily logs, slug = YYYY-MM-DD), \
     'dictionary' (short term/definition lookups for names, acronyms, jargon), \
     'knowledge' (longer-form facts, procedures, decisions, learnings — default when unsure). \
     Other categories (e.g. 'recipe', 'project') may be introduced freely.";

fn memory_entry_path(
    state: &Mutex<WorkspaceState>,
    category: &str,
    slug: &str,
) -> Result<(String, std::path::PathBuf)> {
    validate_segment("category", category)?;
    validate_segment("slug", slug)?;
    let rel = format!("memory/{category}/{slug}.md");
    let abs = lock(state).workspace.root.join(&rel);
    Ok((rel, abs))
}

/// YAML frontmatter tracked on each memory entry file.
#[derive(Debug, Default, Serialize, Deserialize)]
struct MemoryMeta {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    created_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    updated_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    last_read_at: Option<DateTime<Utc>>,
    #[serde(default)]
    read_count: u64,
}

/// Parse a memory file into `(meta, body)`. Files without frontmatter yield
/// a default `MemoryMeta` and the full raw content as body (enables seamless
/// migration of pre-existing files).
fn parse_memory_file(raw: &str) -> (MemoryMeta, String) {
    match crate::frontmatter::split(raw) {
        Some((fm, body)) => {
            let meta: MemoryMeta = serde_yaml::from_str(fm).unwrap_or_default();
            let body = body
                .trim_start_matches(|c: char| c == '\n' || c == '\r')
                .to_string();
            (meta, body)
        }
        None => (MemoryMeta::default(), raw.to_string()),
    }
}

/// Serialize `(meta, body)` back into a Markdown file with YAML frontmatter.
fn serialize_memory_file(meta: &MemoryMeta, body: &str) -> Result<String> {
    let fm = serde_yaml::to_string(meta).context("failed to serialize memory frontmatter")?;
    let body_trimmed = body.trim_start_matches(|c: char| c == '\n' || c == '\r');
    Ok(format!("---\n{fm}---\n\n{body_trimmed}"))
}

fn memory_entry_schema(include_content: bool) -> serde_json::Value {
    let mut props = serde_json::Map::new();
    props.insert(
        "category".into(),
        json!({
            "type": "string",
            "description": "Category directory under memory/, e.g. \"knowledge\", \"dictionary\", \"daily\"."
        }),
    );
    props.insert(
        "slug".into(),
        json!({
            "type": "string",
            "description": "File stem (without .md), e.g. \"sapphire-agent-memory-design\" or \"2026-04-10\"."
        }),
    );
    let mut required = vec!["category", "slug"];
    if include_content {
        props.insert(
            "content".into(),
            json!({
                "type": "string",
                "description": "Full file content."
            }),
        );
        required.push("content");
    }
    json!({
        "type": "object",
        "properties": props,
        "required": required,
    })
}

// -- memory_add --------------------------------------------------------------

/// Create a new one-file memory entry under `memory/<category>/<slug>.md`.
pub struct MemoryAddTool {
    state: Arc<Mutex<WorkspaceState>>,
    spec: ToolSpec,
}

impl MemoryAddTool {
    pub fn new(state: Arc<Mutex<WorkspaceState>>) -> Self {
        let description = format!(
            "Create a new memory entry at memory/<category>/<slug>.md. \
             Fails if the file already exists (use memory_update to overwrite). \
             Each file holds one self-contained entry retrievable via workspace_search. {MEMORY_CATEGORY_GUIDE}"
        );
        Self {
            state,
            spec: ToolSpec {
                name: "memory_add".into(),
                description: description.into(),
                input_schema: memory_entry_schema(true),
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryAddTool {
    fn spec(&self) -> &ToolSpec {
        &self.spec
    }

    async fn execute(&self, input: &serde_json::Value) -> Result<String> {
        let category = input["category"].as_str().context("missing 'category'")?;
        let slug = input["slug"].as_str().context("missing 'slug'")?;
        let content = input["content"].as_str().context("missing 'content'")?;
        let (rel, abs) = memory_entry_path(&self.state, category, slug)?;
        if abs.exists() {
            anyhow::bail!("{rel} already exists; use memory_update to overwrite");
        }
        let now = Utc::now();
        let meta = MemoryMeta {
            created_at: Some(now),
            updated_at: Some(now),
            last_read_at: None,
            read_count: 0,
        };
        let serialized = serialize_memory_file(&meta, content)?;
        lock(&self.state)
            .write_file(Path::new(&rel), &serialized)
            .with_context(|| format!("Failed to write {rel}"))?;
        Ok(format!("Created {rel}"))
    }
}

// -- memory_update -----------------------------------------------------------

/// Overwrite an existing memory entry.
pub struct MemoryUpdateTool {
    state: Arc<Mutex<WorkspaceState>>,
    spec: ToolSpec,
}

impl MemoryUpdateTool {
    pub fn new(state: Arc<Mutex<WorkspaceState>>) -> Self {
        Self {
            state,
            spec: ToolSpec {
                name: "memory_update".into(),
                description: "Overwrite an existing memory entry at \
                    memory/<category>/<slug>.md. Fails if the file does not exist \
                    (use memory_add to create it)."
                    .into(),
                input_schema: memory_entry_schema(true),
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryUpdateTool {
    fn spec(&self) -> &ToolSpec {
        &self.spec
    }

    async fn execute(&self, input: &serde_json::Value) -> Result<String> {
        let category = input["category"].as_str().context("missing 'category'")?;
        let slug = input["slug"].as_str().context("missing 'slug'")?;
        let content = input["content"].as_str().context("missing 'content'")?;
        let (rel, abs) = memory_entry_path(&self.state, category, slug)?;
        if !abs.exists() {
            anyhow::bail!("{rel} does not exist; use memory_add to create it");
        }
        let raw = std::fs::read_to_string(&abs).with_context(|| format!("Failed to read {rel}"))?;
        let (mut meta, _old_body) = parse_memory_file(&raw);
        let now = Utc::now();
        meta.updated_at = Some(now);
        if meta.created_at.is_none() {
            meta.created_at = Some(now);
        }
        let serialized = serialize_memory_file(&meta, content)?;
        lock(&self.state)
            .write_file(Path::new(&rel), &serialized)
            .with_context(|| format!("Failed to write {rel}"))?;
        Ok(format!("Updated {rel}"))
    }
}

// -- memory_append -----------------------------------------------------------

/// Append to a memory entry, creating it if missing.
pub struct MemoryAppendTool {
    state: Arc<Mutex<WorkspaceState>>,
    spec: ToolSpec,
}

impl MemoryAppendTool {
    pub fn new(state: Arc<Mutex<WorkspaceState>>) -> Self {
        Self {
            state,
            spec: ToolSpec {
                name: "memory_append".into(),
                description: "Append content to the end of a memory entry at \
                    memory/<category>/<slug>.md, creating the file if it does \
                    not exist. Cheaper than memory_read + memory_update when you \
                    just want to tack a new observation onto an existing note. \
                    A blank line is inserted between the existing body and the \
                    new content; add your own Markdown heading if you want a \
                    section break. Frontmatter counters (updated_at) are \
                    maintained automatically."
                    .into(),
                input_schema: memory_entry_schema(true),
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryAppendTool {
    fn spec(&self) -> &ToolSpec {
        &self.spec
    }

    async fn execute(&self, input: &serde_json::Value) -> Result<String> {
        let category = input["category"].as_str().context("missing 'category'")?;
        let slug = input["slug"].as_str().context("missing 'slug'")?;
        let content = input["content"].as_str().context("missing 'content'")?;
        let (rel, abs) = memory_entry_path(&self.state, category, slug)?;
        let now = Utc::now();

        let (meta, new_body, created) = if abs.exists() {
            let raw =
                std::fs::read_to_string(&abs).with_context(|| format!("Failed to read {rel}"))?;
            let (mut meta, old_body) = parse_memory_file(&raw);
            meta.updated_at = Some(now);
            if meta.created_at.is_none() {
                meta.created_at = Some(now);
            }
            let trimmed = old_body.trim_end_matches(|c: char| c == '\n' || c == '\r');
            let new_body = if trimmed.is_empty() {
                content.to_string()
            } else {
                format!("{trimmed}\n\n{content}")
            };
            (meta, new_body, false)
        } else {
            let meta = MemoryMeta {
                created_at: Some(now),
                updated_at: Some(now),
                last_read_at: None,
                read_count: 0,
            };
            (meta, content.to_string(), true)
        };

        let serialized = serialize_memory_file(&meta, &new_body)?;
        lock(&self.state)
            .write_file(Path::new(&rel), &serialized)
            .with_context(|| format!("Failed to write {rel}"))?;
        Ok(if created {
            format!("Created {rel}")
        } else {
            format!("Appended to {rel}")
        })
    }
}

// -- memory_read -------------------------------------------------------------

/// Read a memory entry and bump its access counters.
pub struct MemoryReadTool {
    state: Arc<Mutex<WorkspaceState>>,
    spec: ToolSpec,
}

impl MemoryReadTool {
    pub fn new(state: Arc<Mutex<WorkspaceState>>) -> Self {
        Self {
            state,
            spec: ToolSpec {
                name: "memory_read".into(),
                description: "Read a memory entry at memory/<category>/<slug>.md \
                    and return its body. Side effect: updates the file's \
                    frontmatter (last_read_at = now, read_count += 1) so that \
                    recency and frequency can inform future weighting. \
                    Use file_read instead for a non-tracking read."
                    .into(),
                input_schema: memory_entry_schema(false),
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryReadTool {
    fn spec(&self) -> &ToolSpec {
        &self.spec
    }

    async fn execute(&self, input: &serde_json::Value) -> Result<String> {
        let category = input["category"].as_str().context("missing 'category'")?;
        let slug = input["slug"].as_str().context("missing 'slug'")?;
        let (rel, abs) = memory_entry_path(&self.state, category, slug)?;
        if !abs.exists() {
            anyhow::bail!("{rel} does not exist");
        }
        let raw = std::fs::read_to_string(&abs).with_context(|| format!("Failed to read {rel}"))?;
        let (mut meta, body) = parse_memory_file(&raw);
        meta.last_read_at = Some(Utc::now());
        meta.read_count = meta.read_count.saturating_add(1);
        let serialized = serialize_memory_file(&meta, &body)?;
        if let Err(e) = lock(&self.state).write_file(Path::new(&rel), &serialized) {
            tracing::warn!("memory_read: failed to persist counters for {rel}: {e:#}");
        }
        Ok(body)
    }
}

// -- memory_remove -----------------------------------------------------------

/// Delete a memory entry.
pub struct MemoryRemoveTool {
    state: Arc<Mutex<WorkspaceState>>,
    spec: ToolSpec,
}

impl MemoryRemoveTool {
    pub fn new(state: Arc<Mutex<WorkspaceState>>) -> Self {
        Self {
            state,
            spec: ToolSpec {
                name: "memory_remove".into(),
                description: "Delete a memory entry at memory/<category>/<slug>.md.".into(),
                input_schema: memory_entry_schema(false),
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryRemoveTool {
    fn spec(&self) -> &ToolSpec {
        &self.spec
    }

    async fn execute(&self, input: &serde_json::Value) -> Result<String> {
        let category = input["category"].as_str().context("missing 'category'")?;
        let slug = input["slug"].as_str().context("missing 'slug'")?;
        let (rel, abs) = memory_entry_path(&self.state, category, slug)?;
        if !abs.exists() {
            anyhow::bail!("{rel} does not exist");
        }
        std::fs::remove_file(&abs).with_context(|| format!("Failed to remove {rel}"))?;
        Ok(format!("Removed {rel}"))
    }
}

// ---------------------------------------------------------------------------
// workspace_search
// ---------------------------------------------------------------------------

/// Full-text and semantic search across workspace files.
pub struct WorkspaceSearchTool {
    state: Arc<Mutex<WorkspaceState>>,
    spec: ToolSpec,
}

impl WorkspaceSearchTool {
    pub fn new(state: Arc<Mutex<WorkspaceState>>) -> Self {
        Self {
            state,
            spec: ToolSpec {
                name: "workspace_search".into(),
                description: "Search across all indexed files in the workspace. \
                    Two modes are available: \
                    'fts' (full-text / BM25, always available) and \
                    'semantic' (vector similarity, requires an embedder to be configured — falls back to fts if unavailable). \
                    Returns matching file titles and paths.".into(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "Search query."
                        },
                        "mode": {
                            "type": "string",
                            "description": "Search mode: 'fts' (full-text, default) or 'semantic' (vector similarity).",
                            "enum": ["fts", "semantic"],
                            "default": "fts"
                        },
                        "limit": {
                            "type": "integer",
                            "description": "Maximum number of results (default 10).",
                            "default": 10
                        }
                    },
                    "required": ["query"]
                }),
            },
        }
    }
}

#[async_trait]
impl Tool for WorkspaceSearchTool {
    fn spec(&self) -> &ToolSpec {
        &self.spec
    }

    async fn execute(&self, input: &serde_json::Value) -> Result<String> {
        let query = input["query"].as_str().context("missing 'query'")?;
        let limit = input["limit"].as_u64().unwrap_or(10) as usize;
        let mode = input["mode"].as_str().unwrap_or("fts");

        let state = lock(&self.state);

        if mode == "semantic" {
            if let Some(embedder) = state.embedder() {
                let vq = VectorQuery::new(query, embedder).limit(limit);
                let results = state
                    .retrieve_db()
                    .search_similar(&vq)
                    .context("Vector similarity search failed")?;

                if results.is_empty() {
                    return Ok("No results found.".to_string());
                }
                let lines: Vec<String> = results
                    .iter()
                    .map(|r| format!("- {} [score: {:.4}]", r.path, r.score))
                    .collect();
                return Ok(format!("[semantic]\n{}", lines.join("\n")));
            }
        }

        // FTS (default or fallback)
        let fq = FtsQuery::new(query).limit(limit);
        let results = state
            .retrieve_db()
            .search_fts(&fq)
            .context("FTS search failed")?;

        if results.is_empty() {
            return Ok("No results found.".to_string());
        }

        let header = if mode == "semantic" {
            "[fts — semantic fallback: no embedder configured]\n"
        } else {
            "[fts]\n"
        };
        let lines: Vec<String> = results.iter().map(|r| format!("- {}", r.path)).collect();
        Ok(format!("{}{}", header, lines.join("\n")))
    }
}

// ---------------------------------------------------------------------------
// workspace_sync
// ---------------------------------------------------------------------------

/// Sync the workspace via the configured backend (git commit + push).
pub struct WorkspaceSyncTool {
    state: Arc<Mutex<WorkspaceState>>,
    spec: ToolSpec,
}

impl WorkspaceSyncTool {
    pub fn new(state: Arc<Mutex<WorkspaceState>>) -> Self {
        Self {
            state,
            spec: ToolSpec {
                name: "workspace_sync".into(),
                description: "Sync the workspace: index all files and, if a git \
                    remote is configured, commit and push changes."
                    .into(),
                input_schema: json!({
                    "type": "object",
                    "properties": {}
                }),
            },
        }
    }
}

#[async_trait]
impl Tool for WorkspaceSyncTool {
    fn spec(&self) -> &ToolSpec {
        &self.spec
    }

    async fn execute(&self, _input: &serde_json::Value) -> Result<String> {
        let state = lock(&self.state);

        let (upserted, removed) = state.periodic_sync().context("Failed to sync workspace")?;
        Ok(format!(
            "Synced: {upserted} files indexed, {removed} removed."
        ))
    }
}