remem-ai 0.3.0

Persistent memory for Claude Code — single binary, zero subprocesses
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
use anyhow::Result;
use rusqlite::Connection;

use crate::memory::{insert_memory, insert_memory_full};

/// Minimum content length to be worth promoting.
const MIN_DECISION_LEN: usize = 30;
const MIN_LEARNED_LEN: usize = 30;
const MIN_PREFERENCE_LEN: usize = 10;

/// Max title length — leaves room for FTS matching.
const MAX_TITLE_LEN: usize = 120;

/// Generate a stable topic_key from text for UPSERT dedup.
pub fn slugify_for_topic(text: &str, max_len: usize) -> String {
    slugify(text, max_len)
}

fn slugify(text: &str, max_len: usize) -> String {
    let slug: String = text
        .to_lowercase()
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c
            } else if c == '-' || c == '_' || c == ' ' {
                '-'
            } else if !c.is_ascii() {
                c
            } else {
                '-'
            }
        })
        .collect();
    let mut result = String::with_capacity(slug.len());
    let mut last_dash = false;
    for c in slug.chars() {
        if c == '-' {
            if !last_dash && !result.is_empty() {
                result.push('-');
            }
            last_dash = true;
        } else {
            result.push(c);
            last_dash = false;
        }
    }
    let trimmed = result.trim_end_matches('-');
    if trimmed.len() <= max_len {
        trimmed.to_string()
    } else {
        trimmed.chars().take(max_len).collect()
    }
}

/// Build a keyword-rich title from the content itself.
/// Falls back to request prefix only if content is too short.
fn build_title(content: &str, request: &str, label: &str) -> String {
    // Use the content itself as the title source (not request).
    // Truncate to MAX_TITLE_LEN with word-boundary awareness.
    let source = if content.len() >= 20 { content } else { request };
    if source.is_empty() {
        return format!("Session {label}");
    }
    let truncated = truncate_at_boundary(source, MAX_TITLE_LEN - label.len() - 5);
    format!("{truncated}{label}")
}

/// Build a keyword-rich title for a single item in a multi-item list.
fn build_item_title(item: &str, label: &str, _index: usize) -> String {
    let truncated = truncate_at_boundary(item, MAX_TITLE_LEN - label.len() - 5);
    format!("{truncated}{label}")
}

/// Truncate text at a word or sentence boundary, preserving keywords.
fn truncate_at_boundary(text: &str, max_len: usize) -> String {
    let text = text.trim();
    if text.len() <= max_len {
        return text.to_string();
    }
    // Find a good break point: prefer sentence-end, then word boundary.
    let slice = &text[..max_len];
    // Try to break at sentence end.
    for sep in ['', '', ';', '.', '', ','] {
        if let Some(pos) = slice.rfind(sep) {
            if pos > max_len / 2 {
                return text[..pos + sep.len_utf8()].trim().to_string();
            }
        }
    }
    // Break at word boundary (space or CJK char boundary).
    if let Some(pos) = slice.rfind(' ') {
        if pos > max_len / 2 {
            return text[..pos].to_string();
        }
    }
    // Hard truncate at char boundary.
    text.chars().take(max_len).collect()
}

/// Build content with request as lightweight context, not the primary text.
/// The content body is the decision/learned text itself, with request as a one-line header.
fn build_content(body: &str, request: &str) -> String {
    if request.is_empty() {
        body.to_string()
    } else {
        // Request as a compact context line, body is the primary content.
        format!("[Context: {}]\n\n{}", truncate_at_boundary(request, 150), body)
    }
}

/// Split a multi-line text block into individual items.
/// Recognizes bullet points, numbered lists, and semicolons.
fn split_into_items(text: &str) -> Vec<String> {
    let mut items = Vec::new();
    let mut current = String::new();

    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let is_new_item = trimmed.starts_with("")
            || trimmed.starts_with("- ")
            || trimmed.starts_with("* ")
            || trimmed.starts_with("· ")
            || trimmed
                .chars()
                .next()
                .map(|c| c.is_ascii_digit())
                .unwrap_or(false)
                && trimmed.contains(". ");

        if is_new_item {
            if !current.trim().is_empty() {
                items.push(current.trim().to_string());
            }
            let content = trimmed
                .trim_start_matches(|c: char| c == '' || c == '-' || c == '*' || c == '·')
                .trim_start();
            let content = if content
                .chars()
                .next()
                .map(|c| c.is_ascii_digit())
                .unwrap_or(false)
            {
                content
                    .find(". ")
                    .map(|pos| &content[pos + 2..])
                    .unwrap_or(content)
            } else {
                content
            };
            current = content.to_string();
        } else {
            if !current.is_empty() {
                current.push(' ');
            }
            current.push_str(trimmed);
        }
    }
    if !current.trim().is_empty() {
        items.push(current.trim().to_string());
    }

    if items.len() <= 1 {
        let original = text.trim();
        let semi_split: Vec<String> = original
            .split('')
            .flat_map(|s| s.split(';'))
            .map(|s| s.trim().to_string())
            .filter(|s| s.len() >= MIN_DECISION_LEN)
            .collect();
        if semi_split.len() > 1 {
            return semi_split;
        }
    }

    items
}

/// Auto-promote session summary fields to memories.
/// Splits multi-item decisions/learned into individual memories.
/// Returns number of memories created/updated.
pub fn promote_summary_to_memories(
    conn: &Connection,
    session_id: &str,
    project: &str,
    request: Option<&str>,
    decisions: Option<&str>,
    learned: Option<&str>,
    preferences: Option<&str>,
) -> Result<usize> {
    let request_text = request.unwrap_or("").trim();
    let mut count = 0;

    if let Some(text) = decisions {
        let text = text.trim();
        if text.len() >= MIN_DECISION_LEN {
            let items = split_into_items(text);
            if items.len() > 1 {
                for (i, item) in items.iter().enumerate() {
                    if item.len() < MIN_DECISION_LEN {
                        continue;
                    }
                    let title = build_item_title(item, "decision", i);
                    let content = build_content(item, request_text);
                    let topic_key =
                        format!("auto-decision-{}-{}", slugify(request_text, 40), i + 1);
                    insert_memory(
                        conn,
                        Some(session_id),
                        project,
                        Some(&topic_key),
                        &title,
                        &content,
                        "decision",
                        None,
                    )?;
                    count += 1;
                }
            } else {
                let title = build_title(text, request_text, "decisions");
                let content = build_content(text, request_text);
                let topic_key = format!("auto-decision-{}", slugify(request_text, 50));
                insert_memory(
                    conn,
                    Some(session_id),
                    project,
                    Some(&topic_key),
                    &title,
                    &content,
                    "decision",
                    None,
                )?;
                count += 1;
            }
        }
    }

    if let Some(text) = learned {
        let text = text.trim();
        if text.len() >= MIN_LEARNED_LEN {
            let items = split_into_items(text);
            if items.len() > 1 {
                for (i, item) in items.iter().enumerate() {
                    if item.len() < MIN_LEARNED_LEN {
                        continue;
                    }
                    let title = build_item_title(item, "learned", i);
                    let content = build_content(item, request_text);
                    let topic_key =
                        format!("auto-discovery-{}-{}", slugify(request_text, 40), i + 1);
                    insert_memory(
                        conn,
                        Some(session_id),
                        project,
                        Some(&topic_key),
                        &title,
                        &content,
                        "discovery",
                        None,
                    )?;
                    count += 1;
                }
            } else {
                let title = build_title(text, request_text, "learned");
                let content = build_content(text, request_text);
                let topic_key = format!("auto-discovery-{}", slugify(request_text, 50));
                insert_memory(
                    conn,
                    Some(session_id),
                    project,
                    Some(&topic_key),
                    &title,
                    &content,
                    "discovery",
                    None,
                )?;
                count += 1;
            }
        }
    }

    if let Some(text) = preferences {
        let text = text.trim();
        if text.len() >= MIN_PREFERENCE_LEN {
            let title = build_title(text, "", "preference");
            let topic_key = format!("auto-preference-{}", slugify(text, 50));
            insert_memory_full(
                conn,
                Some(session_id),
                project,
                Some(&topic_key),
                &title,
                text,
                "preference",
                None,
                None,
                "global",
            )?;
            count += 1;
        }
    }

    if count > 0 {
        crate::log::info(
            "promote",
            &format!(
                "promoted {} memories from summary project={}",
                count, project
            ),
        );
    }

    Ok(count)
}

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

    #[test]
    fn test_split_into_items_bullets() {
        let text = "• Use RwLock for concurrent reads\n• Switch to trigram tokenizer\n• Set compression threshold=100";
        let items = split_into_items(text);
        assert_eq!(items.len(), 3);
        assert!(items[0].contains("RwLock"));
    }

    #[test]
    fn test_split_into_items_dashes() {
        let text = "- First decision about architecture\n- Second decision about testing\n- Third one";
        let items = split_into_items(text);
        assert_eq!(items.len(), 3);
    }

    #[test]
    fn test_split_into_items_single_line() {
        let text = "Switched from unicode61 to trigram tokenizer for better CJK support";
        let items = split_into_items(text);
        assert_eq!(items.len(), 1);
    }

    #[test]
    fn test_split_into_items_semicolons() {
        let text = "Use RwLock for concurrent reads; Switch to trigram tokenizer for CJK; Set compression threshold to 100 observations";
        let items = split_into_items(text);
        assert_eq!(items.len(), 3);
    }

    #[test]
    fn test_build_title_from_content() {
        let title = build_title(
            "Use RwLock instead of Mutex for concurrent read support",
            "Optimize search and concurrency",
            "decision",
        );
        // Title should be derived from content, not request
        assert!(title.contains("RwLock"));
        assert!(title.contains("— decision"));
    }

    #[test]
    fn test_build_title_fallback_to_request() {
        let title = build_title("short", "Optimize search and concurrency", "decision");
        // Short content falls back to request
        assert!(title.contains("Optimize"));
    }

    #[test]
    fn test_build_content_no_boilerplate() {
        let content = build_content(
            "Use RwLock instead of Mutex for concurrent read support",
            "Optimize search",
        );
        // Content should NOT have **Request**: or **Decisions**: boilerplate
        assert!(!content.contains("**Request**"));
        assert!(!content.contains("**Decisions**"));
        // Should have compact context header
        assert!(content.contains("[Context:"));
        assert!(content.contains("RwLock"));
    }

    #[test]
    fn test_truncate_at_boundary() {
        let text = "Use RwLock instead of Mutex for concurrent read support in the database layer";
        let truncated = truncate_at_boundary(text, 40);
        assert!(truncated.len() <= 45); // Allow slight overshoot for word boundary
        assert!(!truncated.ends_with(' '));
    }

    #[test]
    fn test_truncate_cjk() {
        let text = "使用 RwLock 替代 Mutex 实现并发读支持。数据库层需要高并发";
        let truncated = truncate_at_boundary(text, 30);
        // Should break at sentence boundary '。'
        assert!(truncated.contains("") || truncated.len() <= 35);
    }

    #[test]
    fn test_promote_multi_decisions() {
        let conn = rusqlite::Connection::open_in_memory().unwrap();
        setup_memory_schema(&conn);

        let decisions = "• Use RwLock instead of Mutex for concurrent read support\n\
                         • Switch to trigram tokenizer for CJK text search\n\
                         • Set compression threshold to 100 observations";
        let count = promote_summary_to_memories(
            &conn,
            "session-1",
            "test/proj",
            Some("Optimize search and concurrency"),
            Some(decisions),
            None,
            None,
        )
        .unwrap();
        assert_eq!(count, 3);

        // Verify titles are content-derived, not request-derived
        let memories = crate::memory::get_recent_memories(&conn, "test/proj", 10).unwrap();
        let titles: Vec<&str> = memories.iter().map(|m| m.title.as_str()).collect();
        assert!(
            titles.iter().any(|t| t.contains("RwLock")),
            "title should contain keyword from content: {:?}",
            titles
        );
        assert!(
            titles.iter().any(|t| t.contains("trigram")),
            "title should contain keyword from content: {:?}",
            titles
        );
    }

    #[test]
    fn test_promote_multi_learned() {
        let conn = rusqlite::Connection::open_in_memory().unwrap();
        setup_memory_schema(&conn);

        let learned = "- FTS5 trigram tokenizer handles CJK without word boundaries\n\
                       - WAL mode allows concurrent reads with single writer";
        let count = promote_summary_to_memories(
            &conn,
            "session-1",
            "test/proj",
            Some("Research storage"),
            None,
            Some(learned),
            None,
        )
        .unwrap();
        assert_eq!(count, 2);
    }

    #[test]
    fn test_promote_content_format() {
        let conn = rusqlite::Connection::open_in_memory().unwrap();
        setup_memory_schema(&conn);

        let decisions = "Switched from unicode61 to trigram tokenizer for better CJK support";
        promote_summary_to_memories(
            &conn,
            "session-1",
            "test/proj",
            Some("Fix search"),
            Some(decisions),
            None,
            None,
        )
        .unwrap();

        let memories = crate::memory::get_recent_memories(&conn, "test/proj", 10).unwrap();
        assert_eq!(memories.len(), 1);
        // Content should use compact format, not **Request**/**Decisions** boilerplate
        assert!(
            !memories[0].text.contains("**Request**"),
            "content should not have boilerplate: {}",
            memories[0].text
        );
        assert!(
            memories[0].text.contains("[Context:"),
            "content should have compact context: {}",
            memories[0].text
        );
    }
}