remem-ai 0.5.65

Persistent memory for Claude Code and Codex — single binary, automatic context
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
use std::collections::BTreeSet;

use anyhow::{Context, Result};
use rusqlite::{params, Connection, OptionalExtension};

use crate::db;
use crate::graph_candidate::ParsedGraphCandidate;
use crate::memory::format::{xml_escape_attr, xml_escape_text};

#[derive(Debug, Clone)]
struct GraphSourceObservation {
    id: i64,
    observation_type: String,
    text: String,
    files_read: Vec<String>,
    files_modified: Vec<String>,
    evidence_event_ids: Vec<i64>,
    confidence: f64,
}

#[derive(Debug, Clone)]
struct GraphSourceEvent {
    id: i64,
    text: String,
}

pub(super) struct GraphObservationBatch {
    pub(super) from_event_id: i64,
    pub(super) to_event_id: i64,
    pub(super) evidence_event_ids: Vec<i64>,
    source_events: Vec<GraphSourceEvent>,
    observations: Vec<GraphSourceObservation>,
}

pub(super) fn load_graph_observation_batch(
    conn: &Connection,
    task: &db::ExtractionTask,
) -> Result<Option<GraphObservationBatch>> {
    let Some(session_row_id) = task.session_row_id else {
        return Ok(None);
    };
    let Some(high_watermark) = task.high_watermark_event_id else {
        return Ok(None);
    };
    let cursor = task.cursor_event_id.unwrap_or(0);
    if high_watermark <= cursor {
        return Ok(None);
    }

    let mut stmt = conn.prepare(
        "SELECT id,
                COALESCE(observation_type, type, 'discovery') AS observation_type,
                COALESCE(text, narrative, title, '') AS text,
                files_read,
                files_modified,
                evidence_event_ids,
                COALESCE(confidence, 0.5) AS confidence
         FROM observations
         WHERE session_row_id = ?1
           AND evidence_event_ids IS NOT NULL
           AND text IS NOT NULL
         ORDER BY id ASC",
    )?;
    let rows = stmt
        .query_map(params![session_row_id], |row| {
            Ok((
                row.get::<_, i64>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, Option<String>>(3)?,
                row.get::<_, Option<String>>(4)?,
                row.get::<_, String>(5)?,
                row.get::<_, f64>(6)?,
            ))
        })?
        .collect::<Result<Vec<_>, _>>()?;

    let mut observations = Vec::new();
    let mut evidence_set = BTreeSet::new();
    for (
        id,
        observation_type,
        text,
        files_read_json,
        files_modified_json,
        evidence_json,
        confidence,
    ) in rows
    {
        let event_ids: Vec<i64> = serde_json::from_str(&evidence_json)
            .with_context(|| format!("observation {id} has malformed evidence_event_ids"))?;
        let in_range = event_ids
            .iter()
            .any(|event_id| *event_id > cursor && *event_id <= high_watermark);
        if !in_range {
            continue;
        }
        for event_id in &event_ids {
            evidence_set.insert(*event_id);
        }
        observations.push(GraphSourceObservation {
            id,
            observation_type,
            text,
            files_read: parse_observation_file_list(id, "files_read", files_read_json)?,
            files_modified: parse_observation_file_list(id, "files_modified", files_modified_json)?,
            evidence_event_ids: event_ids,
            confidence,
        });
    }

    if observations.is_empty() || evidence_set.is_empty() {
        return Ok(None);
    }
    let from_event_id = *evidence_set.iter().next().unwrap_or(&0);
    let to_event_id = *evidence_set.iter().next_back().unwrap_or(&0);
    let evidence_event_ids = evidence_set.into_iter().collect::<Vec<_>>();
    let source_events = load_graph_source_events(conn, &evidence_event_ids)?;
    Ok(Some(GraphObservationBatch {
        from_event_id,
        to_event_id,
        evidence_event_ids,
        source_events,
        observations,
    }))
}

fn load_graph_source_events(
    conn: &Connection,
    evidence_event_ids: &[i64],
) -> Result<Vec<GraphSourceEvent>> {
    let mut stmt = conn.prepare(
        "SELECT COALESCE(
                    CASE
                        WHEN b.content_encoding = 'plain' THEN CAST(b.content_bytes AS TEXT)
                        ELSE NULL
                    END,
                    e.content_text,
                    ''
                ) AS content
         FROM captured_events e
         LEFT JOIN event_blobs b ON b.id = e.content_blob_id
         WHERE e.id = ?1",
    )?;
    let mut events = Vec::new();
    for event_id in evidence_event_ids {
        if let Some(text) = stmt
            .query_row(params![event_id], |row| row.get(0))
            .optional()?
        {
            events.push(GraphSourceEvent {
                id: *event_id,
                text,
            });
        }
    }
    Ok(events)
}

fn parse_observation_file_list(
    observation_id: i64,
    field: &str,
    raw: Option<String>,
) -> Result<Vec<String>> {
    let Some(raw) = raw.as_deref().map(str::trim).filter(|raw| !raw.is_empty()) else {
        return Ok(Vec::new());
    };
    serde_json::from_str::<Vec<String>>(raw)
        .with_context(|| format!("observation {observation_id} has malformed {field}"))
}

pub(super) fn graph_candidate_blocked_by_memory_candidates(
    conn: &Connection,
    task: &db::ExtractionTask,
    batch: &GraphObservationBatch,
) -> Result<Option<String>> {
    let Some(session_row_id) = task.session_row_id else {
        return Ok(None);
    };
    let high_watermark = task.high_watermark_event_id.unwrap_or(batch.to_event_id);
    let incomplete_memory_task: Option<(i64, String)> = conn
        .query_row(
            "SELECT id, status
             FROM extraction_tasks
             WHERE host_id = ?1
               AND project_id = ?2
               AND session_row_id = ?3
               AND task_kind = 'memory_candidate'
               AND COALESCE(high_watermark_event_id, 0) >= ?4
               AND COALESCE(cursor_event_id, 0) < ?4
               AND status != 'done'
             ORDER BY id ASC
             LIMIT 1",
            params![
                task.host_id,
                task.project_id,
                session_row_id,
                high_watermark
            ],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .optional()?;
    if let Some((task_id, status)) = incomplete_memory_task {
        return Ok(Some(format!(
            "memory_candidate task {task_id} is {status}; graph extraction waits for memory extraction completion"
        )));
    }

    let pending_memory_candidates = count_pending_memory_candidates_with_evidence_overlap(
        conn,
        task.project_id,
        &batch.evidence_event_ids,
    )?;
    if pending_memory_candidates > 0 {
        return Ok(Some(format!(
            "{pending_memory_candidates} memory candidate(s) for this evidence range are pending review"
        )));
    }

    Ok(None)
}

fn count_pending_memory_candidates_with_evidence_overlap(
    conn: &Connection,
    project_id: i64,
    evidence_event_ids: &[i64],
) -> Result<i64> {
    let evidence_event_ids = evidence_event_ids.iter().copied().collect::<BTreeSet<_>>();
    let mut stmt = conn.prepare(
        "SELECT id, evidence_event_ids
         FROM memory_candidates
         WHERE project_id = ?1
           AND review_status = 'pending_review'
           AND evidence_event_ids IS NOT NULL",
    )?;
    let rows = stmt
        .query_map(params![project_id], |row| {
            Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
        })?
        .collect::<Result<Vec<_>, _>>()?;

    let mut count = 0;
    for (candidate_id, candidate_evidence_json) in rows {
        let candidate_event_ids = serde_json::from_str::<Vec<i64>>(&candidate_evidence_json)
            .with_context(|| {
                format!("memory candidate {candidate_id} has malformed evidence_event_ids")
            })?;
        if candidate_event_ids
            .iter()
            .any(|event_id| evidence_event_ids.contains(event_id))
        {
            count += 1;
        }
    }
    Ok(count)
}

pub(super) fn graph_candidate_has_source_support(
    candidate: &ParsedGraphCandidate,
    batch: &GraphObservationBatch,
) -> bool {
    let candidate_evidence = candidate
        .evidence_event_ids
        .iter()
        .copied()
        .collect::<BTreeSet<_>>();
    let observation_supported = batch
        .observations
        .iter()
        .filter(|observation| {
            observation
                .evidence_event_ids
                .iter()
                .any(|event_id| candidate_evidence.contains(event_id))
        })
        .any(|observation| refs_supported_by_observation(candidate, observation));
    let cited_events_supported = candidate.evidence_event_ids.iter().all(|event_id| {
        let event_text = batch
            .source_events
            .iter()
            .find(|event| event.id == *event_id)
            .map(|event| event.text.as_str());
        let event_text_supported =
            event_text.is_some_and(|text| refs_supported_by_event(candidate, *event_id, text));
        event_text_supported
            || batch.observations.iter().any(|observation| {
                observation.evidence_event_ids.contains(event_id)
                    && structured_file_evidence_supports_cited_event(
                        candidate,
                        *event_id,
                        event_text,
                        observation,
                    )
            })
    });
    observation_supported && cited_events_supported
}

fn refs_supported_by_observation(
    candidate: &ParsedGraphCandidate,
    observation: &GraphSourceObservation,
) -> bool {
    ref_supported_by_observation(&candidate.from_ref, observation)
        && ref_supported_by_observation(&candidate.to_ref, observation)
}

fn ref_supported_by_observation(reference: &str, observation: &GraphSourceObservation) -> bool {
    parse_episode_ref_id(reference)
        .is_some_and(|episode_id| observation.evidence_event_ids.contains(&episode_id))
        || ref_supported_by_text(reference, &observation_support_text(observation))
}

fn structured_file_evidence_supports_cited_event(
    candidate: &ParsedGraphCandidate,
    event_id: i64,
    event_text: Option<&str>,
    observation: &GraphSourceObservation,
) -> bool {
    candidate.edge_type == "touches_file"
        && event_text
            .is_some_and(|text| ref_supported_by_event(&candidate.from_ref, event_id, text))
        && ref_supported_by_structured_files(&candidate.to_ref, observation)
}

fn ref_supported_by_structured_files(
    reference: &str,
    observation: &GraphSourceObservation,
) -> bool {
    observation
        .files_read
        .iter()
        .chain(observation.files_modified.iter())
        .any(|file| ref_supported_by_text(reference, file))
}

fn observation_support_text(observation: &GraphSourceObservation) -> String {
    let mut text = observation.text.clone();
    for file in observation
        .files_read
        .iter()
        .chain(observation.files_modified.iter())
    {
        text.push('\n');
        text.push_str(file);
    }
    text
}

fn refs_supported_by_event(candidate: &ParsedGraphCandidate, event_id: i64, text: &str) -> bool {
    ref_supported_by_event(&candidate.from_ref, event_id, text)
        && ref_supported_by_event(&candidate.to_ref, event_id, text)
}

fn ref_supported_by_text(reference: &str, text: &str) -> bool {
    let haystack = text.to_ascii_lowercase();
    reference_support_needles(reference)
        .into_iter()
        .any(|needle| contains_support_needle(&haystack, &needle))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SupportBoundary {
    Word,
    Entity,
    Path,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct SupportNeedle {
    text: String,
    boundary: SupportBoundary,
}

fn reference_support_needles(reference: &str) -> Vec<SupportNeedle> {
    let reference = reference.trim();
    if let Some(path) = reference.strip_prefix("file:") {
        return vec![
            SupportNeedle {
                text: path.trim_start_matches("./").to_string(),
                boundary: SupportBoundary::Path,
            },
            SupportNeedle {
                text: path.to_string(),
                boundary: SupportBoundary::Path,
            },
        ];
    }
    if let Some(entity) = reference.strip_prefix("entity:") {
        return vec![
            SupportNeedle {
                text: entity.to_string(),
                boundary: SupportBoundary::Entity,
            },
            SupportNeedle {
                text: entity.replace(['_', '-'], " "),
                boundary: SupportBoundary::Entity,
            },
        ];
    }
    if let Some(memory_id) = reference.strip_prefix("memory:") {
        return vec![
            SupportNeedle {
                text: reference.to_string(),
                boundary: SupportBoundary::Word,
            },
            SupportNeedle {
                text: format!("memory {memory_id}"),
                boundary: SupportBoundary::Word,
            },
        ];
    }
    if let Some(episode_id) = reference.strip_prefix("episode:") {
        return vec![
            SupportNeedle {
                text: reference.to_string(),
                boundary: SupportBoundary::Word,
            },
            SupportNeedle {
                text: format!("event {episode_id}"),
                boundary: SupportBoundary::Word,
            },
        ];
    }
    vec![SupportNeedle {
        text: reference.to_string(),
        boundary: SupportBoundary::Word,
    }]
}

fn contains_support_needle(haystack: &str, needle: &SupportNeedle) -> bool {
    let needle_text = needle.text.trim().to_ascii_lowercase();
    !needle_text.is_empty()
        && haystack.match_indices(&needle_text).any(|(start, _)| {
            let end = start + needle_text.len();
            support_boundary_before(haystack, start, needle.boundary)
                && support_boundary_after(haystack, end, needle.boundary)
        })
}

fn support_boundary_before(haystack: &str, start: usize, boundary: SupportBoundary) -> bool {
    haystack[..start]
        .chars()
        .next_back()
        .is_none_or(|ch| is_support_boundary(ch, boundary))
}

fn support_boundary_after(haystack: &str, end: usize, boundary: SupportBoundary) -> bool {
    let mut chars = haystack[end..].chars();
    let Some(ch) = chars.next() else {
        return true;
    };
    if boundary == SupportBoundary::Path
        && ch == '.'
        && chars
            .next()
            .is_some_and(|next| next.is_ascii_alphanumeric())
    {
        return false;
    }
    is_support_boundary(ch, boundary)
}

fn is_support_boundary(ch: char, boundary: SupportBoundary) -> bool {
    if ch.is_ascii_alphanumeric() || ch == '_' {
        return false;
    }
    match boundary {
        SupportBoundary::Word => true,
        SupportBoundary::Entity => !matches!(ch, '-' | '/' | '.'),
        SupportBoundary::Path => !matches!(ch, '-' | '/'),
    }
}

fn ref_supported_by_event(reference: &str, event_id: i64, text: &str) -> bool {
    parse_episode_ref_id(reference).is_some_and(|episode_id| episode_id == event_id)
        || ref_supported_by_text(reference, text)
}

fn parse_episode_ref_id(reference: &str) -> Option<i64> {
    reference
        .strip_prefix("episode:")
        .and_then(|raw| raw.trim().parse::<i64>().ok())
        .filter(|id| *id > 0)
}

pub(super) fn build_graph_candidate_prompt(
    task: &db::ExtractionTask,
    batch: &GraphObservationBatch,
) -> String {
    let mut prompt = format!(
        "Task: graph_candidate\nProject: {}\nHost: {}\nSession: {}\nCovered evidence events: {}..{}\n\n",
        task.project,
        task.host,
        task.session_id.as_deref().unwrap_or("<unknown>"),
        batch.from_event_id,
        batch.to_event_id
    );
    for observation in &batch.observations {
        let evidence = observation
            .evidence_event_ids
            .iter()
            .map(i64::to_string)
            .collect::<Vec<_>>()
            .join(",");
        prompt.push_str(&format!(
            "<observation id=\"{}\" type=\"{}\" confidence=\"{}\" evidence_event_ids=\"{}\">\n",
            observation.id,
            xml_escape_attr(&observation.observation_type),
            observation.confidence,
            xml_escape_attr(&evidence)
        ));
        prompt.push_str(&xml_escape_text(&observation.text));
        if !observation.files_read.is_empty() {
            prompt.push_str("\n<files_read>\n");
            for file in &observation.files_read {
                prompt.push_str(&xml_escape_text(file));
                prompt.push('\n');
            }
            prompt.push_str("</files_read>\n");
        }
        if !observation.files_modified.is_empty() {
            prompt.push_str("\n<files_modified>\n");
            for file in &observation.files_modified {
                prompt.push_str(&xml_escape_text(file));
                prompt.push('\n');
            }
            prompt.push_str("</files_modified>\n");
        }
        prompt.push_str("\n</observation>\n\n");
    }
    prompt
}

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

    #[test]
    fn support_matching_uses_ref_boundaries() {
        assert!(!ref_supported_by_text(
            "memory:1",
            "Memory 10 mentions Worker."
        ));
        assert!(ref_supported_by_text(
            "memory:1",
            "Memory 1 mentions Worker."
        ));
        assert!(!ref_supported_by_text(
            "entity:Worker",
            "Changed src/worker.rs"
        ));
        assert!(ref_supported_by_text(
            "entity:Worker",
            "The Worker entity is mentioned."
        ));
        assert!(!ref_supported_by_text(
            "file:src/worker.rs",
            "Changed src/worker.rs.bak"
        ));
        assert!(ref_supported_by_text(
            "file:src/worker.rs",
            "Changed src/worker.rs."
        ));
    }
}