vipune 0.12.0

A minimal memory layer for AI agents
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
//! Command handlers for vipune CLI.

use crate::errors::Error;
use crate::memory::lifecycle::{MemoryImportance, MemoryStatus, MemoryType};
use crate::memory::{MemoryStore, UpdateParams};
use crate::memory_types::{AddResult, IngestPolicy};
use crate::output::*;
use crate::{config, embedding::EmbeddingEngine, temporal};
use std::process::ExitCode;

pub(crate) struct SearchContext {
    pub(crate) query: String,
    pub(crate) limit: usize,
    pub(crate) recency: Option<f64>,
    pub(crate) hybrid: bool,
    pub(crate) no_hybrid: bool,
    pub(crate) memory_type: Option<String>,
    pub(crate) status: Option<String>,
    pub(crate) include_candidates: bool,
    pub(crate) no_touch: bool,
}

pub(crate) fn handle_validate(text: &str, model_id: &str, json: bool) -> Result<ExitCode, Error> {
    let engine = EmbeddingEngine::new(model_id)?;
    let token_count = engine.token_count(text)?;

    if token_count > crate::embedding::MAX_EMBEDDING_TOKENS {
        return Err(Error::ContentTooLong {
            token_count,
            max_tokens: crate::embedding::MAX_EMBEDDING_TOKENS,
        });
    }

    if json {
        print_json(&ValidateResponse {
            token_count,
            max_tokens: crate::embedding::MAX_EMBEDDING_TOKENS,
            within_limit: true,
        });
    } else {
        println!(
            "Token count: {}/{} — within limit",
            token_count,
            crate::embedding::MAX_EMBEDDING_TOKENS
        );
    }

    Ok(ExitCode::SUCCESS)
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn handle_add(
    store: &mut MemoryStore,
    project_id: &str,
    text: &str,
    metadata: Option<&str>,
    force: bool,
    memory_type: &str,
    status: &str,
    importance: &str,
    supersedes: Option<&str>,
    json: bool,
) -> Result<ExitCode, Error> {
    let memory_type_val = MemoryType::from_str(memory_type)?;
    let status_val = MemoryStatus::from_str(status)?;
    let importance_val = MemoryImportance::from_str(importance)?;
    if !status_val.is_valid_for_insert() {
        return Err(Error::InvalidInput(format!(
            "Status '{}' is not valid for new memory insertion. Must be 'active' or 'candidate'.",
            status
        )));
    }

    if supersedes.is_some() && force {
        return Err(Error::InvalidInput(
            "Cannot use both --supersedes and --force flags together".to_string(),
        ));
    }

    if let Some(old_id) = supersedes {
        let new_id = store.supersede(project_id, text, metadata, memory_type_val, old_id)?;

        if json {
            print_json(&AddResponse {
                status: "superseded".to_string(),
                id: new_id,
            });
        } else {
            println!("Superseded memory {} with new memory", old_id);
        }
        return Ok(ExitCode::SUCCESS);
    }

    let policy = if force {
        IngestPolicy::Force
    } else {
        IngestPolicy::ConflictAware
    };

    let _ = importance_val; // validated; persistence lands with the importance column (sub-issue 2)

    match store.ingest_with_type_status(
        project_id,
        text,
        metadata,
        policy,
        memory_type_val,
        status_val,
    )? {
        AddResult::Added { id } => {
            if json {
                print_json(&AddResponse {
                    status: "added".to_string(),
                    id,
                });
            } else {
                println!("Added memory: {}", id);
            }
            Ok(ExitCode::SUCCESS)
        }
        AddResult::Conflicts {
            proposed,
            conflicts,
        } => {
            if json {
                let conflict_responses: Vec<ConflictMemoryResponse> = conflicts
                    .into_iter()
                    .map(|c| ConflictMemoryResponse {
                        id: c.id,
                        content: c.content,
                        similarity: c.similarity,
                    })
                    .collect();
                print_json(&ConflictsResponse {
                    status: "conflicts".to_string(),
                    proposed,
                    conflicts: conflict_responses,
                });
            } else {
                println!(
                    "Conflicts detected: {} similar memory/memories found",
                    conflicts.len()
                );
                println!("Proposed: {}", proposed);
                println!("Use --force to add anyway");
                for conflict in conflicts {
                    println!("  {} (similarity: {:.3})", conflict.id, conflict.similarity);
                    println!("    {}", conflict.content);
                }
            }
            Ok(ExitCode::from(2))
        }
    }
}

pub(crate) fn handle_search(
    store: &mut MemoryStore,
    project_id: &str,
    opts: &SearchContext,
    config: &config::Config,
    json: bool,
) -> Result<ExitCode, Error> {
    let recency_weight = opts.recency.unwrap_or(config.recency_weight);
    temporal::validate_recency_weight(recency_weight)?;

    let type_vec: Option<Vec<String>> = opts
        .memory_type
        .as_ref()
        .map(|t| t.split(',').map(|s| s.trim().to_string()).collect());
    let type_strs: Option<Vec<&str>> = type_vec
        .as_ref()
        .map(|v| v.iter().map(|s| s.as_str()).collect());

    let status_vec: Option<Vec<String>> = if opts.include_candidates {
        Some(vec!["active".to_string(), "candidate".to_string()])
    } else {
        opts.status
            .as_ref()
            .map(|s| s.split(',').map(|s| s.trim().to_string()).collect())
    };
    let status_strs: Option<Vec<&str>> = status_vec
        .as_ref()
        .map(|v| v.iter().map(|s| s.as_str()).collect());

    let use_hybrid = (opts.hybrid || config.hybrid) && !opts.no_hybrid;
    let search_options = crate::memory::SearchOptions {
        memory_types: type_strs,
        statuses: status_strs,
    };
    let memories = if use_hybrid {
        store.search_hybrid(
            project_id,
            &opts.query,
            opts.limit,
            recency_weight,
            search_options,
        )?
    } else {
        store.search(
            project_id,
            &opts.query,
            opts.limit,
            recency_weight,
            search_options,
        )?
    };

    if !opts.no_touch {
        let ids: Vec<&str> = memories.iter().map(|m| m.id.as_str()).collect();
        if !ids.is_empty() {
            if let Err(e) = store.db.touch_memories(&ids) {
                eprintln!("warning: failed to update retrieval stats: {}", e);
            }
        }
    }

    if json {
        let results: Vec<SearchResultItem> = memories
            .into_iter()
            .map(|m| SearchResultItem {
                id: m.id,
                content: m.content,
                similarity: m.similarity.unwrap_or(0.0),
                created_at: m.created_at,
                retrieval_count: m.retrieval_count,
                last_retrieved_at: m.last_retrieved_at,
                memory_type: m.memory_type,
                status: m.status,
                importance: m.importance,
            })
            .collect();
        print_json(&SearchResponse { results });
    } else {
        for memory in memories {
            let score = memory.similarity.unwrap_or(0.0);
            println!(
                "{} [score: {:.2}]\n  {}\n",
                memory.id, score, memory.content
            );
        }
    }
    Ok(ExitCode::SUCCESS)
}

pub(crate) fn handle_get(
    store: &mut MemoryStore,
    id: &str,
    project_id: &str,
    no_touch: bool,
    json: bool,
) -> Result<ExitCode, Error> {
    let memory = store
        .get(id, project_id)?
        .ok_or_else(|| Error::NotFound("memory not found".to_string()))?;

    if !no_touch {
        if let Err(e) = store.db.touch_memories(&[id]) {
            eprintln!("warning: failed to update retrieval stats: {}", e);
        }
    }

    if json {
        print_json(&GetResponse {
            id: memory.id.clone(),
            content: memory.content.clone(),
            project_id: memory.project_id,
            metadata: memory.metadata,
            created_at: memory.created_at,
            updated_at: memory.updated_at,
            retrieval_count: memory.retrieval_count,
            last_retrieved_at: memory.last_retrieved_at.clone(),
            memory_type: memory.memory_type,
            status: memory.status,
            importance: memory.importance,
        });
    } else {
        println!("ID: {}", memory.id);
        println!("Content: {}", memory.content);
        println!("Project: {}", memory.project_id);
        if let Some(meta) = &memory.metadata {
            println!("Metadata: {}", meta);
        }
        println!("Created: {}", memory.created_at);
        println!("Updated: {}", memory.updated_at);
    }
    Ok(ExitCode::SUCCESS)
}

pub(crate) fn handle_list(
    store: &mut MemoryStore,
    project_id: &str,
    limit: usize,
    memory_type: Option<&str>,
    status: Option<&str>,
    include_candidates: bool,
    json: bool,
) -> Result<ExitCode, Error> {
    let type_vec: Option<Vec<String>> =
        memory_type.map(|t| t.split(',').map(|s| s.trim().to_string()).collect());
    let type_strs: Option<Vec<&str>> = type_vec
        .as_ref()
        .map(|v| v.iter().map(|s| s.as_str()).collect());
    let type_slice: Option<&[&str]> = type_strs.as_deref();

    let status_vec: Option<Vec<String>> = if include_candidates {
        Some(vec!["active".to_string(), "candidate".to_string()])
    } else {
        status.map(|s| s.split(',').map(|s| s.trim().to_string()).collect())
    };
    let status_strs: Option<Vec<&str>> = status_vec
        .as_ref()
        .map(|v| v.iter().map(|s| s.as_str()).collect());
    let status_slice: Option<&[&str]> = status_strs.as_deref();

    let memories = store.list(project_id, limit, type_slice, status_slice)?;
    if json {
        let items: Vec<ListItem> = memories
            .into_iter()
            .map(|m| ListItem {
                id: m.id,
                content: m.content,
                created_at: m.created_at,
                retrieval_count: m.retrieval_count,
                last_retrieved_at: m.last_retrieved_at,
                memory_type: m.memory_type,
                status: m.status,
                importance: m.importance,
            })
            .collect();
        print_json(&ListResponse { memories: items });
    } else {
        for memory in memories {
            println!("{}: {}", memory.id, memory.content);
        }
    }
    Ok(ExitCode::SUCCESS)
}

pub(crate) fn handle_delete(
    store: &mut MemoryStore,
    id: &str,
    project_id: &str,
    json: bool,
) -> Result<ExitCode, Error> {
    let deleted = store.delete(id, project_id)?;
    if deleted {
        if json {
            print_json(&DeleteResponse {
                status: "deleted".to_string(),
                id: id.to_string(),
            });
        } else {
            println!("Deleted memory: {}", id);
        }
        Ok(ExitCode::SUCCESS)
    } else {
        Err(Error::NotFound("memory not found".to_string()))
    }
}

pub(crate) fn handle_update(
    store: &mut MemoryStore,
    id: &str,
    project_id: &str,
    args: UpdateParams<'_>,
    json: bool,
) -> Result<ExitCode, Error> {
    store.update(id, project_id, args)?;
    if json {
        print_json(&UpdateResponse {
            status: "updated".to_string(),
            id: id.to_string(),
        });
    } else {
        println!("Updated memory: {}", id);
    }
    Ok(ExitCode::SUCCESS)
}

pub(crate) fn handle_version(json: bool) -> Result<ExitCode, Error> {
    if json {
        print_json(&serde_json::json!({
            "version": env!("CARGO_PKG_VERSION"),
            "name": env!("CARGO_PKG_NAME")
        }));
    } else {
        println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
    }
    Ok(ExitCode::SUCCESS)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::MemoryStore;

    /// Assert GetResponse carries the telemetry fields so `get --json` exposes them.
    #[test]
    fn test_get_response_serializes_retrieval_telemetry() {
        let response = GetResponse {
            id: "mem-1".to_string(),
            content: "a memory".to_string(),
            project_id: "proj".to_string(),
            metadata: None,
            created_at: "2024-01-15T10:30:00Z".to_string(),
            updated_at: "2024-01-15T10:30:00Z".to_string(),
            retrieval_count: 5,
            last_retrieved_at: Some("2024-01-15T10:30:00Z".to_string()),
            memory_type: "fact".to_string(),
            status: "active".to_string(),
            importance: "medium".to_string(),
        };
        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"retrieval_count\":5"));
        assert!(json.contains("\"last_retrieved_at\":\"2024-01-15T10:30:00Z\""));
        assert!(json.contains("\"importance\":\"medium\""));

        // Null case: never-retrieved memory.
        let response = GetResponse {
            retrieval_count: 0,
            last_retrieved_at: None,
            ..response
        };
        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"retrieval_count\":0"));
        assert!(json.contains("\"last_retrieved_at\":null"));
    }

    /// End-to-end: `get --json` on a touched memory returns the telemetry fields,
    /// and `--no-touch` leaves the counter untouched.
    #[test]
    fn test_get_json_surfaces_retrieval_telemetry() {
        let mut store = MemoryStore::test_store();
        let AddResult::Added { id } = store
            .ingest("proj", "a memory with telemetry", None, IngestPolicy::Force)
            .unwrap()
        else {
            panic!("expected Added")
        };

        // Simulate one retrieval so the counter is non-trivial.
        let ids: Vec<&str> = vec![id.as_str()];
        store.db.touch_memories(&ids).unwrap();

        let memory = store.get(&id, "proj").unwrap().expect("memory exists");
        let response = GetResponse {
            id: memory.id,
            content: memory.content,
            project_id: memory.project_id,
            metadata: memory.metadata,
            created_at: memory.created_at,
            updated_at: memory.updated_at,
            retrieval_count: memory.retrieval_count,
            last_retrieved_at: memory.last_retrieved_at,
            memory_type: memory.memory_type,
            status: memory.status,
            importance: memory.importance,
        };
        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"retrieval_count\":1"));
        assert!(
            json.contains("\"last_retrieved_at\":\"")
                && !json.contains("\"last_retrieved_at\":null")
        );
    }
}