second-brain-adapters 0.12.0

Conversation parsers for second-brain: Claude Code and Cursor JSONL adapters
Documentation
use std::cell::RefCell;
use std::path::Path;

use chrono::{DateTime, Utc};
use second_brain_core::session_dates::SessionEvidence;

use crate::claude_code::{Transcript, read_transcript};
use crate::claude_memory::is_note;

/// Reads session times from the transcripts and note files on this machine.
/// Only the last transcript read is kept, because the backfill asks in
/// source_id order and holding every transcript would not fit in memory.
#[derive(Default)]
pub struct TranscriptEvidence {
    last: RefCell<Option<(String, Option<Transcript>)>>,
}

impl TranscriptEvidence {
    fn with_transcript<T>(
        &self,
        path: &str,
        read: impl FnOnce(&Transcript) -> Option<T>,
    ) -> Option<T> {
        let mut last = self.last.borrow_mut();
        if last.as_ref().is_none_or(|(cached, _)| cached != path) {
            let parsed = std::fs::read_to_string(path)
                .ok()
                .map(|content| read_transcript(&content));
            *last = Some((path.to_string(), parsed));
        }
        last.as_ref()
            .and_then(|(_, transcript)| transcript.as_ref())
            .and_then(read)
    }
}

impl SessionEvidence for TranscriptEvidence {
    /// A raw's first paragraph is matched rather than its whole text, because
    /// raws ingested by an older chunker span different paragraph runs than
    /// today's, while every chunker starts a chunk on a trimmed paragraph.
    /// The earliest matching line wins, erring towards older.
    fn line_time(&self, transcript: &str, text: &str) -> Option<DateTime<Utc>> {
        let first_paragraph = text.split("\n\n").next().unwrap_or("").trim();
        if first_paragraph.is_empty() {
            return None;
        }
        self.with_transcript(transcript, |t| {
            t.assistant_texts
                .iter()
                .find(|block| block.text.contains(first_paragraph))
                .and_then(|block| block.at)
        })
    }

    fn first_time(&self, transcript: &str) -> Option<DateTime<Utc>> {
        self.with_transcript(transcript, |t| t.first_timestamp)
    }

    fn note_modified_at(&self, path: &str) -> Option<DateTime<Utc>> {
        let path = Path::new(path);
        if is_note(path) {
            modified_at(path)
        } else {
            None
        }
    }
}

pub(crate) fn modified_at(path: &Path) -> Option<DateTime<Utc>> {
    std::fs::metadata(path)
        .and_then(|meta| meta.modified())
        .ok()
        .map(DateTime::<Utc>::from)
}