Skip to main content

recall_echo/
archive.rs

1//! Conversation archival — converts conversations into persistent markdown archives.
2//!
3//! Supports two input paths:
4//! 1. **JSONL hook** — called directly by Claude Code SessionEnd hook (standalone)
5//! 2. **Pulse-null** — called with in-memory Messages (behind feature flag)
6//!
7//! Both converge into `archive_conversation()` which writes the markdown file,
8//! updates ARCHIVE.md, and appends to EPHEMERAL.md.
9
10use std::fmt::Write as _;
11use std::fs;
12use std::path::Path;
13
14use crate::config;
15use crate::conversation::{self, Conversation};
16use crate::ephemeral::{self, EphemeralEntry};
17use crate::error::RecallError;
18use crate::frontmatter::Frontmatter;
19use crate::summarize;
20use crate::tags;
21
22/// Session metadata provided by the caller.
23#[derive(Debug, Clone)]
24pub struct SessionMetadata {
25    pub session_id: String,
26    pub started_at: Option<String>,
27    pub ended_at: Option<String>,
28    pub entity_name: String,
29}
30
31/// Result of archiving a conversation — used by callers for graph ingestion.
32pub struct ArchiveResult {
33    pub log_number: u32,
34    pub full_content: String,
35    pub session_id: String,
36}
37
38/// Scan conversations/ for highest conversation-NNN number. Returns 0 if none.
39#[must_use]
40pub fn highest_conversation_number(conversations_dir: &Path) -> u32 {
41    let entries = match fs::read_dir(conversations_dir) {
42        Ok(e) => e,
43        Err(_) => return 0,
44    };
45
46    let mut max = 0u32;
47    for entry in entries.flatten() {
48        let name = entry.file_name();
49        let name = name.to_string_lossy();
50        if let Some(num_str) = name
51            .strip_prefix("conversation-")
52            .and_then(|s| s.strip_suffix(".md"))
53        {
54            if let Ok(n) = num_str.parse::<u32>() {
55                if n > max {
56                    max = n;
57                }
58            }
59        }
60    }
61
62    max
63}
64
65/// Append an entry to ARCHIVE.md (markdown table row).
66pub fn append_index(
67    archive_path: &Path,
68    log_num: u32,
69    date: &str,
70    session_id: &str,
71    topics: &[String],
72    message_count: u32,
73    duration: &str,
74) -> Result<(), RecallError> {
75    use std::io::Write;
76
77    let needs_header = if archive_path.exists() {
78        fs::read_to_string(archive_path)
79            .unwrap_or_default()
80            .trim()
81            .is_empty()
82    } else {
83        true
84    };
85
86    let mut file = fs::OpenOptions::new()
87        .create(true)
88        .append(true)
89        .open(archive_path)?;
90
91    if needs_header {
92        writeln!(file, "# Conversation Archive\n")?;
93        writeln!(
94            file,
95            "| # | Date | Session | Topics | Messages | Duration |"
96        )?;
97        writeln!(
98            file,
99            "|---|------|---------|--------|----------|----------|"
100        )?;
101    }
102
103    let topics_str = if topics.is_empty() {
104        "\u{2014}".to_string()
105    } else {
106        topics.join(", ")
107    };
108
109    writeln!(
110        file,
111        "| {log_num:03} | {date} | {session_id} | {topics_str} | {message_count} | {duration} |"
112    )?;
113
114    Ok(())
115}
116
117// ---------------------------------------------------------------------------
118// Core archive function — works with Conversation (universal path)
119// ---------------------------------------------------------------------------
120
121/// Archive a conversation from internal types.
122///
123/// This is the core archive function. All input paths (JSONL, pulse-null)
124/// converge here after converting to a Conversation.
125///
126/// Returns an ArchiveResult with the log number and content (for graph ingestion).
127pub fn archive_conversation(
128    memory_dir: &Path,
129    conv: &Conversation,
130    summary: &summarize::ConversationSummary,
131    source: &str,
132) -> Result<ArchiveResult, RecallError> {
133    let conversations_dir = memory_dir.join("conversations");
134    let archive_index = memory_dir.join("ARCHIVE.md");
135    let ephemeral_path = memory_dir.join("EPHEMERAL.md");
136
137    if !conversations_dir.exists() {
138        return Err(RecallError::NotInitialized(
139            "conversations/ directory not found. Run init first.".into(),
140        ));
141    }
142
143    // Skip empty sessions
144    if conv.user_message_count == 0 {
145        return Ok(ArchiveResult {
146            log_number: 0,
147            full_content: String::new(),
148            session_id: conv.session_id.clone(),
149        });
150    }
151
152    let next_num = highest_conversation_number(&conversations_dir) + 1;
153
154    let now = conversation::utc_now();
155    let date = conversation::date_from_timestamp(&now);
156    let duration = match (&conv.first_timestamp, &conv.last_timestamp) {
157        (Some(start), Some(end)) => conversation::calculate_duration(start, end),
158        _ => "unknown".to_string(),
159    };
160    let total_messages = conv.total_messages();
161
162    // Build frontmatter
163    let fm = Frontmatter {
164        log: next_num,
165        date: now.clone(),
166        session_id: conv.session_id.clone(),
167        message_count: total_messages,
168        duration: duration.clone(),
169        source: source.to_string(),
170        topics: summary.topics.clone(),
171    };
172
173    // Convert conversation to markdown
174    let md_body = conversation::conversation_to_markdown(conv, next_num);
175
176    // Extract tags
177    let conv_tags = tags::extract_tags(&conv.entries);
178    let tags_section = tags::format_tags_section(&conv_tags);
179
180    // Add summary section if available
181    let summary_section = if !summary.summary.is_empty() {
182        let mut s = format!("## Summary\n\n{}\n\n", summary.summary);
183        if !summary.decisions.is_empty() {
184            s.push_str("**Decisions**:\n");
185            for d in &summary.decisions {
186                let _ = writeln!(s, "- {d}");
187            }
188            s.push('\n');
189        }
190        if !summary.action_items.is_empty() {
191            s.push_str("**Action Items**:\n");
192            for a in &summary.action_items {
193                let _ = writeln!(s, "- {a}");
194            }
195            s.push('\n');
196        }
197        s
198    } else {
199        String::new()
200    };
201
202    let full_content = format!(
203        "{}\n\n{}{}\n{}",
204        fm.render(),
205        summary_section,
206        md_body,
207        tags_section
208    );
209
210    // Write conversation file
211    let conv_file = conversations_dir.join(format!("conversation-{next_num:03}.md"));
212    fs::write(&conv_file, &full_content)?;
213
214    // Append to ARCHIVE.md index
215    append_index(
216        &archive_index,
217        next_num,
218        &date,
219        &conv.session_id,
220        &summary.topics,
221        total_messages,
222        &duration,
223    )?;
224
225    // Append to EPHEMERAL.md
226    let entry = EphemeralEntry {
227        session_id: conv.session_id.clone(),
228        date: now,
229        duration,
230        message_count: total_messages,
231        archive_file: format!("conversation-{next_num:03}.md"),
232        summary: summary.summary.clone(),
233    };
234    ephemeral::append_entry(&ephemeral_path, &entry)?;
235    let cfg = config::load_from_dir(memory_dir);
236    ephemeral::trim_to_limit(&ephemeral_path, cfg.ephemeral.max_entries)?;
237
238    eprintln!("recall-echo: archived conversation-{next_num:03}.md ({total_messages} messages)");
239
240    Ok(ArchiveResult {
241        log_number: next_num,
242        full_content,
243        session_id: conv.session_id.clone(),
244    })
245}
246
247/// Ingest an archive result into the knowledge graph.
248pub fn graph_ingest(memory_dir: &Path, result: &ArchiveResult) {
249    if result.log_number == 0 {
250        return;
251    }
252    let rt = match client_runtime() {
253        Ok(rt) => rt,
254        Err(e) => {
255            eprintln!("recall-echo: graph runtime error: {e}");
256            return;
257        }
258    };
259    if let Err(e) = rt.block_on(crate::graph_bridge::ingest_into_graph(
260        memory_dir,
261        &result.full_content,
262        &result.session_id,
263        Some(result.log_number),
264    )) {
265        eprintln!("recall-echo: graph ingestion warning: {e}");
266    }
267}
268
269/// A runtime for a client-side command: a handful of socket round-trips, plus
270/// whatever the daemon does on our behalf. One thread is enough — the worker
271/// pool of a multi-thread runtime exists to be idle here.
272fn client_runtime() -> std::io::Result<tokio::runtime::Runtime> {
273    tokio::runtime::Builder::new_current_thread()
274        .enable_all()
275        .build()
276}
277
278/// The pipeline documents to sync, or `None` when auto-sync is off, no
279/// `docs_dir` is configured, or there is no graph to sync into.
280fn pipeline_docs_to_sync(memory_dir: &Path) -> Option<crate::graph::types::PipelineDocuments> {
281    let cfg = config::load_from_dir(memory_dir);
282    let pipeline = match cfg.pipeline {
283        Some(ref p) if p.auto_sync == Some(true) => p,
284        _ => return None,
285    };
286
287    let docs_dir = match pipeline.docs_dir {
288        Some(ref d) => {
289            let path = std::path::PathBuf::from(shellexpand_path(d));
290            if !path.exists() {
291                eprintln!(
292                    "recall-echo: pipeline docs_dir not found: {}",
293                    path.display()
294                );
295                return None;
296            }
297            path
298        }
299        None => {
300            eprintln!("recall-echo: pipeline auto_sync enabled but no docs_dir configured");
301            return None;
302        }
303    };
304
305    if !memory_dir.join("graph").exists() {
306        return None;
307    }
308    Some(read_pipeline_docs(&docs_dir))
309}
310
311/// Sync pipeline documents into the graph (if auto_sync enabled).
312///
313/// Non-blocking: logs warnings on failure but never fails the caller.
314pub fn pipeline_sync_on_archive(memory_dir: &Path) {
315    let Some(docs) = pipeline_docs_to_sync(memory_dir) else {
316        return;
317    };
318    let rt = match client_runtime() {
319        Ok(rt) => rt,
320        Err(e) => {
321            eprintln!("recall-echo: pipeline sync runtime error: {e}");
322            return;
323        }
324    };
325    report_pipeline_sync(rt.block_on(crate::graph_bridge::sync_pipeline_into_graph(
326        memory_dir, docs,
327    )));
328}
329
330/// Async version of pipeline_sync_on_archive for use in async contexts (pulse-null).
331#[cfg(feature = "pulse-null")]
332async fn pipeline_sync_on_archive_async(memory_dir: &Path) {
333    let Some(docs) = pipeline_docs_to_sync(memory_dir) else {
334        return;
335    };
336    report_pipeline_sync(crate::graph_bridge::sync_pipeline_into_graph(memory_dir, docs).await);
337}
338
339fn report_pipeline_sync(result: Result<crate::graph::types::PipelineSyncReport, RecallError>) {
340    match result {
341        Ok(report) => {
342            if report.entities_created > 0
343                || report.entities_updated > 0
344                || report.entities_archived > 0
345            {
346                eprintln!(
347                    "recall-echo: pipeline synced — +{} created, ~{} updated, -{} archived",
348                    report.entities_created, report.entities_updated, report.entities_archived
349                );
350            }
351        }
352        Err(e) => eprintln!("recall-echo: pipeline sync warning: {e}"),
353    }
354}
355
356fn read_pipeline_docs(docs_dir: &Path) -> crate::graph::types::PipelineDocuments {
357    crate::graph::types::PipelineDocuments {
358        learning: read_opt_file(docs_dir, "LEARNING.md"),
359        thoughts: read_opt_file(docs_dir, "THOUGHTS.md"),
360        curiosity: read_opt_file(docs_dir, "CURIOSITY.md"),
361        reflections: read_opt_file(docs_dir, "REFLECTIONS.md"),
362        praxis: read_opt_file(docs_dir, "PRAXIS.md"),
363    }
364}
365
366fn read_opt_file(dir: &Path, name: &str) -> String {
367    fs::read_to_string(dir.join(name)).unwrap_or_default()
368}
369
370fn shellexpand_path(path: &str) -> String {
371    if let Some(rest) = path.strip_prefix("~/") {
372        if let Ok(home) = std::env::var("HOME") {
373            return format!("{home}/{rest}");
374        }
375    }
376    path.to_string()
377}
378
379// ---------------------------------------------------------------------------
380// JSONL path — for Claude Code hooks (standalone, no LLM)
381// ---------------------------------------------------------------------------
382
383/// Archive a session from a JSONL transcript file.
384///
385/// Parses JSONL, generates algorithmic summary, archives, and optionally
386/// ingests into the knowledge graph. Both graph steps are daemon requests, so
387/// the hook pays for one warm store and one embedding-model load, not two.
388pub fn archive_from_jsonl(
389    base_dir: &Path,
390    session_id: &str,
391    transcript_path: &str,
392) -> Result<u32, RecallError> {
393    let conv = crate::jsonl::parse_transcript(transcript_path, session_id)?;
394    let summary = summarize::algorithmic_summary(&conv);
395    let result = archive_conversation(base_dir, &conv, &summary, "jsonl")?;
396    let log_number = result.log_number;
397
398    graph_ingest(base_dir, &result);
399    pipeline_sync_on_archive(base_dir);
400
401    Ok(log_number)
402}
403
404/// Main archive-session flow, called from the SessionEnd hook.
405/// Reads hook input from stdin.
406pub fn run_from_hook() -> Result<(), RecallError> {
407    let hook_input = crate::jsonl::read_hook_input()?;
408    run_with_hook_input(&hook_input)
409}
410
411/// Archive the session named by a hook input.
412///
413/// Sessions run with --no-session-persistence never write a transcript.
414/// A missing file is a normal no-op for the hook, not an error — failing
415/// here makes the entire `claude -p` invocation exit nonzero.
416pub fn run_with_hook_input(hook_input: &crate::jsonl::HookInput) -> Result<(), RecallError> {
417    if !Path::new(&hook_input.transcript_path).exists() {
418        eprintln!(
419            "recall-echo: no transcript at {} (session not persisted), nothing to archive",
420            hook_input.transcript_path
421        );
422        return Ok(());
423    }
424    let base_dir = crate::paths::claude_dir()?;
425    archive_from_jsonl(
426        &base_dir,
427        &hook_input.session_id,
428        &hook_input.transcript_path,
429    )?;
430    Ok(())
431}
432
433/// Archive all unarchived JSONL transcripts found under ~/.claude/projects/.
434pub fn archive_all_unarchived() -> Result<(), RecallError> {
435    let base = crate::paths::claude_dir()?;
436    archive_all_with_base(&base)
437}
438
439pub fn archive_all_with_base(base: &Path) -> Result<(), RecallError> {
440    let conversations_dir = base.join("conversations");
441    if !conversations_dir.exists() {
442        return Err(RecallError::NotInitialized(
443            "conversations/ directory not found. Run `recall-echo init` first.".into(),
444        ));
445    }
446
447    let archived_sessions = collect_archived_sessions(&conversations_dir);
448
449    let projects_dir = base.join("projects");
450    if !projects_dir.exists() {
451        eprintln!("No projects directory found \u{2014} nothing to archive.");
452        return Ok(());
453    }
454
455    let mut jsonl_files = find_jsonl_files(&projects_dir);
456    jsonl_files.sort_by_key(|p| {
457        fs::metadata(p)
458            .and_then(|m| m.modified())
459            .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
460    });
461
462    let mut archived_count = 0;
463    let mut skipped_count = 0;
464
465    for jsonl_path in &jsonl_files {
466        let session_id = match jsonl_path.file_stem().and_then(|s| s.to_str()) {
467            Some(id) => id.to_string(),
468            None => continue,
469        };
470
471        if archived_sessions.contains(&session_id) {
472            skipped_count += 1;
473            continue;
474        }
475
476        let path_str = jsonl_path.to_string_lossy().to_string();
477        match archive_from_jsonl(base, &session_id, &path_str) {
478            Ok(_) => archived_count += 1,
479            Err(e) => {
480                eprintln!("recall-echo: skipping {session_id} \u{2014} {e}");
481            }
482        }
483    }
484
485    eprintln!(
486        "recall-echo: archived {archived_count} conversation{}, skipped {skipped_count} already archived",
487        if archived_count == 1 { "" } else { "s" }
488    );
489
490    Ok(())
491}
492
493fn collect_archived_sessions(conversations_dir: &Path) -> std::collections::HashSet<String> {
494    let mut sessions = std::collections::HashSet::new();
495    if let Ok(entries) = fs::read_dir(conversations_dir) {
496        for entry in entries.flatten() {
497            let name = entry.file_name();
498            let name = name.to_string_lossy();
499            if name.starts_with("conversation-") && name.ends_with(".md") {
500                if let Ok(content) = fs::read_to_string(entry.path()) {
501                    for line in content.lines().take(15) {
502                        if let Some(sid) = line.strip_prefix("session_id: ") {
503                            sessions.insert(sid.trim().trim_matches('"').to_string());
504                            break;
505                        }
506                    }
507                }
508            }
509        }
510    }
511    sessions
512}
513
514fn find_jsonl_files(dir: &Path) -> Vec<std::path::PathBuf> {
515    let mut files = Vec::new();
516    if let Ok(entries) = fs::read_dir(dir) {
517        for entry in entries.flatten() {
518            let path = entry.path();
519            if path.is_dir() {
520                files.extend(find_jsonl_files(&path));
521            } else if path.extension().is_some_and(|e| e == "jsonl") {
522                files.push(path);
523            }
524        }
525    }
526    files
527}
528
529// ---------------------------------------------------------------------------
530// Pulse-null path — behind feature flag
531// ---------------------------------------------------------------------------
532
533/// Archive a session from pulse-null in-memory messages.
534///
535/// Converts Messages to Conversation, uses LLM for summarization if available,
536/// and optionally ingests into the knowledge graph.
537#[cfg(feature = "pulse-null")]
538pub async fn archive_session(
539    memory_dir: &Path,
540    messages: &[pulse_system_types::llm::Message],
541    metadata: &SessionMetadata,
542    provider: Option<&dyn pulse_system_types::llm::LmProvider>,
543) -> Result<u32, RecallError> {
544    let mut conv = crate::pulse_null::messages_to_conversation(messages, &metadata.session_id);
545    conv.first_timestamp = metadata.started_at.clone();
546    conv.last_timestamp = metadata.ended_at.clone();
547
548    let summary = summarize::extract_with_fallback(provider, &conv).await;
549    let result = archive_conversation(memory_dir, &conv, &summary, "session")?;
550    let log_number = result.log_number;
551
552    // Graph ingestion (async path — no need for Runtime)
553    if log_number > 0 {
554        if let Err(e) = crate::graph_bridge::ingest_into_graph(
555            memory_dir,
556            &result.full_content,
557            &result.session_id,
558            Some(log_number),
559        )
560        .await
561        {
562            eprintln!("recall-echo: graph ingestion warning: {e}");
563        }
564        pipeline_sync_on_archive_async(memory_dir).await;
565    }
566
567    Ok(log_number)
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573
574    #[test]
575    fn highest_from_empty_dir() {
576        let tmp = tempfile::tempdir().unwrap();
577        assert_eq!(highest_conversation_number(tmp.path()), 0);
578    }
579
580    #[test]
581    fn highest_from_sequential_files() {
582        let tmp = tempfile::tempdir().unwrap();
583        fs::write(tmp.path().join("conversation-001.md"), "").unwrap();
584        fs::write(tmp.path().join("conversation-002.md"), "").unwrap();
585        fs::write(tmp.path().join("conversation-003.md"), "").unwrap();
586        assert_eq!(highest_conversation_number(tmp.path()), 3);
587    }
588
589    #[test]
590    fn highest_with_gaps() {
591        let tmp = tempfile::tempdir().unwrap();
592        fs::write(tmp.path().join("conversation-001.md"), "").unwrap();
593        fs::write(tmp.path().join("conversation-010.md"), "").unwrap();
594        assert_eq!(highest_conversation_number(tmp.path()), 10);
595    }
596
597    #[test]
598    fn highest_ignores_non_matching() {
599        let tmp = tempfile::tempdir().unwrap();
600        fs::write(tmp.path().join("conversation-003.md"), "").unwrap();
601        fs::write(tmp.path().join("notes.md"), "").unwrap();
602        fs::write(tmp.path().join("conversation-bad.md"), "").unwrap();
603        assert_eq!(highest_conversation_number(tmp.path()), 3);
604    }
605
606    #[test]
607    fn append_index_creates_header_and_appends() {
608        let tmp = tempfile::tempdir().unwrap();
609        let index = tmp.path().join("ARCHIVE.md");
610
611        append_index(
612            &index,
613            1,
614            "2026-03-05",
615            "abc123",
616            &["auth".to_string()],
617            34,
618            "45m",
619        )
620        .unwrap();
621        append_index(
622            &index,
623            2,
624            "2026-03-05",
625            "def456",
626            &["ci".to_string(), "tests".to_string()],
627            22,
628            "20m",
629        )
630        .unwrap();
631
632        let content = fs::read_to_string(&index).unwrap();
633        assert!(content.contains("# Conversation Archive"));
634        assert!(content.contains("| 001 | 2026-03-05 | abc123 | auth | 34 | 45m |"));
635        assert!(content.contains("| 002 | 2026-03-05 | def456 | ci, tests | 22 | 20m |"));
636    }
637
638    #[test]
639    fn append_index_to_existing_file() {
640        let tmp = tempfile::tempdir().unwrap();
641        let index = tmp.path().join("ARCHIVE.md");
642        fs::write(
643            &index,
644            "# Conversation Archive\n\n| # | Date | Session | Topics | Messages | Duration |\n|---|------|---------|--------|----------|----------|\n| 001 | 2026-03-05 | abc | test | 10 | 5m |\n",
645        )
646        .unwrap();
647
648        append_index(&index, 2, "2026-03-05", "def", &[], 20, "10m").unwrap();
649
650        let content = fs::read_to_string(&index).unwrap();
651        assert!(content.contains("| 002 | 2026-03-05 | def | \u{2014} | 20 | 10m |"));
652        assert_eq!(content.matches("# Conversation Archive").count(), 1);
653    }
654
655    #[test]
656    fn archive_conversation_basic() {
657        let tmp = tempfile::tempdir().unwrap();
658        let memory = tmp.path();
659        fs::create_dir_all(memory.join("conversations")).unwrap();
660
661        let conv = Conversation {
662            session_id: "test-abc".to_string(),
663            first_timestamp: Some("2026-03-05T14:30:00Z".to_string()),
664            last_timestamp: Some("2026-03-05T15:00:00Z".to_string()),
665            user_message_count: 1,
666            assistant_message_count: 1,
667            entries: vec![
668                conversation::ConversationEntry::UserMessage("Let's build something".to_string()),
669                conversation::ConversationEntry::AssistantText("Sure, let's do it.".to_string()),
670            ],
671        };
672
673        let summary = summarize::ConversationSummary {
674            summary: "Built something cool".to_string(),
675            topics: vec!["building".to_string()],
676            decisions: vec![],
677            action_items: vec![],
678        };
679
680        let result = archive_conversation(memory, &conv, &summary, "test").unwrap();
681        assert_eq!(result.log_number, 1);
682        assert!(memory.join("conversations/conversation-001.md").exists());
683
684        let content = fs::read_to_string(memory.join("conversations/conversation-001.md")).unwrap();
685        assert!(content.contains("session_id: \"test-abc\""));
686        assert!(content.contains("source: \"test\""));
687        assert!(content.contains("Built something cool"));
688    }
689
690    #[test]
691    fn archive_conversation_skips_empty() {
692        let tmp = tempfile::tempdir().unwrap();
693        let memory = tmp.path();
694        fs::create_dir_all(memory.join("conversations")).unwrap();
695
696        let conv = Conversation::new("empty");
697        let summary = summarize::ConversationSummary::default();
698
699        let result = archive_conversation(memory, &conv, &summary, "test").unwrap();
700        assert_eq!(result.log_number, 0);
701    }
702
703    #[test]
704    fn hook_missing_transcript_exits_ok() {
705        let hook_input = crate::jsonl::HookInput {
706            session_id: "no-persist".into(),
707            transcript_path: "/nonexistent/path/transcript.jsonl".into(),
708            _cwd: None,
709            _hook_event_name: None,
710        };
711        // --no-session-persistence sessions have no transcript: must be Ok, not Err.
712        assert!(run_with_hook_input(&hook_input).is_ok());
713    }
714}