Skip to main content

second_brain_adapters/
session_evidence.rs

1use std::cell::RefCell;
2use std::path::Path;
3
4use chrono::{DateTime, Utc};
5use second_brain_core::session_dates::SessionEvidence;
6
7use crate::claude_code::{Transcript, read_transcript};
8use crate::claude_memory::is_note;
9
10/// Reads session times from the transcripts and note files on this machine.
11/// Only the last transcript read is kept, because the backfill asks in
12/// source_id order and holding every transcript would not fit in memory.
13#[derive(Default)]
14pub struct TranscriptEvidence {
15    last: RefCell<Option<(String, Option<Transcript>)>>,
16}
17
18impl TranscriptEvidence {
19    fn with_transcript<T>(
20        &self,
21        path: &str,
22        read: impl FnOnce(&Transcript) -> Option<T>,
23    ) -> Option<T> {
24        let mut last = self.last.borrow_mut();
25        if last.as_ref().is_none_or(|(cached, _)| cached != path) {
26            let parsed = std::fs::read_to_string(path)
27                .ok()
28                .map(|content| read_transcript(&content));
29            *last = Some((path.to_string(), parsed));
30        }
31        last.as_ref()
32            .and_then(|(_, transcript)| transcript.as_ref())
33            .and_then(read)
34    }
35}
36
37impl SessionEvidence for TranscriptEvidence {
38    /// A raw's first paragraph is matched rather than its whole text, because
39    /// raws ingested by an older chunker span different paragraph runs than
40    /// today's, while every chunker starts a chunk on a trimmed paragraph.
41    /// The earliest matching line wins, erring towards older.
42    fn line_time(&self, transcript: &str, text: &str) -> Option<DateTime<Utc>> {
43        let first_paragraph = text.split("\n\n").next().unwrap_or("").trim();
44        if first_paragraph.is_empty() {
45            return None;
46        }
47        self.with_transcript(transcript, |t| {
48            t.assistant_texts
49                .iter()
50                .find(|block| block.text.contains(first_paragraph))
51                .and_then(|block| block.at)
52        })
53    }
54
55    fn first_time(&self, transcript: &str) -> Option<DateTime<Utc>> {
56        self.with_transcript(transcript, |t| t.first_timestamp)
57    }
58
59    fn note_modified_at(&self, path: &str) -> Option<DateTime<Utc>> {
60        let path = Path::new(path);
61        if is_note(path) {
62            modified_at(path)
63        } else {
64            None
65        }
66    }
67}
68
69pub(crate) fn modified_at(path: &Path) -> Option<DateTime<Utc>> {
70    std::fs::metadata(path)
71        .and_then(|meta| meta.modified())
72        .ok()
73        .map(DateTime::<Utc>::from)
74}