Skip to main content

recall_echo/
init.rs

1//! Initialize the recall-echo memory system.
2//!
3//! Creates the directory structure and template files needed for
4//! four-layer memory (graph, curated, short-term, long-term), hooks, and LLM provider config.
5
6use std::fs;
7use std::io::{self, BufRead, Write as _};
8use std::path::Path;
9
10use crate::config::{self, Config, LlmSection, Provider};
11use crate::error::RecallError;
12use crate::paths;
13
14// ANSI color helpers
15const GREEN: &str = "\x1b[32m";
16const YELLOW: &str = "\x1b[33m";
17const RED: &str = "\x1b[31m";
18const BOLD: &str = "\x1b[1m";
19const DIM: &str = "\x1b[2m";
20const RESET: &str = "\x1b[0m";
21
22const MEMORY_TEMPLATE: &str = "# Memory\n\n\
23<!-- recall-echo: Curated memory. Distilled facts, preferences, patterns. -->\n\
24<!-- Keep under 200 lines. Only write confirmed, stable information. -->\n";
25
26const ARCHIVE_TEMPLATE: &str = "# Conversation Archive\n\n\
27| # | Date | Session | Topics | Messages | Duration |\n\
28|---|------|---------|--------|----------|----------|\n";
29
30enum Status {
31    Created,
32    Exists,
33    Error,
34}
35
36fn print_status(status: Status, msg: &str) {
37    match status {
38        Status::Created => eprintln!("  {GREEN}✓{RESET} {msg}"),
39        Status::Exists => eprintln!("  {YELLOW}~{RESET} {msg}"),
40        Status::Error => eprintln!("  {RED}✗{RESET} {msg}"),
41    }
42}
43
44fn ensure_dir(path: &Path) {
45    if !path.exists() {
46        if let Err(e) = fs::create_dir_all(path) {
47            print_status(
48                Status::Error,
49                &format!("Failed to create {}: {e}", path.display()),
50            );
51        }
52    }
53}
54
55fn write_if_not_exists(path: &Path, content: &str, label: &str) {
56    if path.exists() {
57        print_status(
58            Status::Exists,
59            &format!("{label} already exists — preserved"),
60        );
61    } else {
62        match fs::write(path, content) {
63            Ok(()) => print_status(Status::Created, &format!("Created {label}")),
64            Err(e) => print_status(Status::Error, &format!("Failed to create {label}: {e}")),
65        }
66    }
67}
68
69/// Prompt for LLM provider selection during init.
70/// Returns None if stdin is not a terminal (non-interactive).
71fn prompt_provider(reader: &mut dyn BufRead) -> Option<Provider> {
72    // Check if stdin is a terminal
73    if !atty_check() {
74        // Non-interactive: default to claude-code if detected, else anthropic
75        return if paths::detect_claude_code().is_some() {
76            Some(Provider::ClaudeCode)
77        } else {
78            Some(Provider::Anthropic)
79        };
80    }
81
82    let is_cc = paths::detect_claude_code().is_some();
83    let default_label = if is_cc { "3" } else { "1" };
84
85    eprintln!("\n{BOLD}LLM provider for entity extraction:{RESET}");
86    eprintln!(
87        "  {BOLD}1{RESET}) anthropic   {DIM}— Claude API{}",
88        if !is_cc { " (default)" } else { "" }
89    );
90    eprintln!("  {BOLD}2{RESET}) ollama      {DIM}— Local models via Ollama{RESET}");
91    eprintln!(
92        "  {BOLD}3{RESET}) claude-code {DIM}— Uses `claude -p` subprocess{}",
93        if is_cc { " (default)" } else { "" }
94    );
95    eprintln!(
96        "  {BOLD}4{RESET}) skip        {DIM}— Configure later with `recall-echo config`{RESET}"
97    );
98    eprint!("\n  Choice [{default_label}]: ");
99    io::stderr().flush().ok();
100
101    let mut input = String::new();
102    if reader.read_line(&mut input).is_err() {
103        return None;
104    }
105
106    match input.trim() {
107        "" => {
108            if is_cc {
109                Some(Provider::ClaudeCode)
110            } else {
111                Some(Provider::Anthropic)
112            }
113        }
114        "1" | "anthropic" => Some(Provider::Anthropic),
115        "2" | "ollama" => Some(Provider::Openai),
116        "3" | "claude-code" => Some(Provider::ClaudeCode),
117        "4" | "skip" => None,
118        _ => {
119            let default = if is_cc {
120                Provider::ClaudeCode
121            } else {
122                Provider::Anthropic
123            };
124            eprintln!("  {YELLOW}~{RESET} Unknown choice, defaulting to {default}");
125            Some(default)
126        }
127    }
128}
129
130/// Configure LLM provider. Returns true if the chosen provider is claude-code
131/// (indicating this is likely a Claude Code user).
132fn configure_llm(reader: &mut dyn BufRead, memory_dir: &Path) -> bool {
133    if !config::exists(memory_dir) {
134        if let Some(provider) = prompt_provider(reader) {
135            let is_cc = provider == Provider::ClaudeCode;
136            let cfg = Config {
137                llm: LlmSection {
138                    provider: provider.clone(),
139                    model: String::new(),
140                    api_base: String::new(),
141                },
142                ..Config::default()
143            };
144            match config::save(memory_dir, &cfg) {
145                Ok(()) => {
146                    let display_name = match &provider {
147                        Provider::Anthropic => "anthropic",
148                        Provider::Openai => "ollama (openai-compat)",
149                        Provider::ClaudeCode => "claude-code",
150                    };
151                    print_status(
152                        Status::Created,
153                        &format!("Created .recall-echo.toml (provider: {display_name})"),
154                    );
155                }
156                Err(e) => print_status(Status::Error, &format!("Failed to write config: {e}")),
157            }
158            return is_cc;
159        }
160        print_status(
161            Status::Exists,
162            "Skipped LLM config — run `recall-echo config set provider <name>` later",
163        );
164    } else {
165        print_status(
166            Status::Exists,
167            ".recall-echo.toml already exists — preserved",
168        );
169        // Check existing config
170        let cfg = config::load(memory_dir);
171        return cfg.llm.provider == Provider::ClaudeCode;
172    }
173    false
174}
175
176/// Initialize the graph store in memory/graph/.
177fn init_graph(memory_dir: &Path) {
178    let graph_dir = memory_dir.join("graph");
179    if graph_dir.exists() {
180        print_status(Status::Exists, "graph/ already exists — preserved");
181        return;
182    }
183
184    match tokio::runtime::Runtime::new() {
185        Ok(rt) => match rt.block_on(crate::graph::GraphMemory::open(&graph_dir)) {
186            Ok(_) => print_status(Status::Created, "Created graph/ (SurrealDB + fastembed)"),
187            Err(e) => print_status(Status::Error, &format!("Failed to init graph: {e}")),
188        },
189        Err(e) => print_status(Status::Error, &format!("Failed to start runtime: {e}")),
190    }
191}
192
193/// Auto-configure Claude Code hooks (settings.json).
194/// Returns true if hooks were configured.
195/// Hooks always go in ~/.claude/settings.json regardless of where entity_root is.
196fn configure_hooks(_entity_root: &Path) -> bool {
197    let claude_dir = match paths::detect_claude_code() {
198        Some(dir) => dir,
199        None => return false,
200    };
201
202    let settings_path = claude_dir.join("settings.json");
203    let recall_bin = std::env::current_exe()
204        .ok()
205        .and_then(|p| p.to_str().map(String::from))
206        .unwrap_or_else(|| "recall-echo".into());
207
208    let archive_cmd = format!("{recall_bin} archive-session");
209    let checkpoint_cmd = format!("{recall_bin} checkpoint --trigger precompact");
210    let consume_cmd = format!("{recall_bin} consume");
211
212    // Load existing settings or start fresh
213    let mut settings: serde_json::Value = if settings_path.exists() {
214        fs::read_to_string(&settings_path)
215            .ok()
216            .and_then(|s| serde_json::from_str(&s).ok())
217            .unwrap_or_else(|| serde_json::json!({}))
218    } else {
219        serde_json::json!({})
220    };
221
222    let hooks = settings.as_object_mut().and_then(|o| {
223        o.entry("hooks")
224            .or_insert_with(|| serde_json::json!({}))
225            .as_object_mut()
226    });
227
228    let hooks = match hooks {
229        Some(h) => h,
230        None => {
231            print_status(Status::Error, "Could not parse settings.json hooks");
232            return false;
233        }
234    };
235
236    let mut changed = false;
237
238    // Add SessionStart hook if not already present
239    // Fires once per session (on startup or resume) — injects EPHEMERAL.md
240    // into context via stdout. Skips `clear` (user reset) and `compact`
241    // (we just recovered from a compaction, no prior session to surface).
242    if !hook_exists(hooks, "SessionStart", &consume_cmd) {
243        let arr = hooks
244            .entry("SessionStart")
245            .or_insert_with(|| serde_json::json!([]))
246            .as_array_mut();
247        if let Some(arr) = arr {
248            arr.push(serde_json::json!({
249                "matcher": "startup|resume",
250                "hooks": [{"type": "command", "command": consume_cmd}]
251            }));
252            changed = true;
253        }
254    }
255
256    // Add SessionEnd hook if not already present
257    if !hook_exists(hooks, "SessionEnd", &archive_cmd) {
258        let arr = hooks
259            .entry("SessionEnd")
260            .or_insert_with(|| serde_json::json!([]))
261            .as_array_mut();
262        if let Some(arr) = arr {
263            arr.push(serde_json::json!({
264                "hooks": [{"type": "command", "command": archive_cmd}]
265            }));
266            changed = true;
267        }
268    }
269
270    // Add PreCompact hook if not already present
271    if !hook_exists(hooks, "PreCompact", &checkpoint_cmd) {
272        let arr = hooks
273            .entry("PreCompact")
274            .or_insert_with(|| serde_json::json!([]))
275            .as_array_mut();
276        if let Some(arr) = arr {
277            arr.push(serde_json::json!({
278                "hooks": [{"type": "command", "command": checkpoint_cmd}]
279            }));
280            changed = true;
281        }
282    }
283
284    if changed {
285        match serde_json::to_string_pretty(&settings) {
286            Ok(content) => match fs::write(&settings_path, content) {
287                Ok(()) => {
288                    print_status(
289                        Status::Created,
290                        "Configured SessionStart + SessionEnd + PreCompact hooks in settings.json",
291                    );
292                    return true;
293                }
294                Err(e) => print_status(
295                    Status::Error,
296                    &format!("Failed to write settings.json: {e}"),
297                ),
298            },
299            Err(e) => print_status(Status::Error, &format!("Failed to serialize settings: {e}")),
300        }
301    } else {
302        print_status(Status::Exists, "Hooks already configured in settings.json");
303        return true;
304    }
305
306    false
307}
308
309/// Check if a hook command already exists in a hook event array.
310fn hook_exists(
311    hooks: &serde_json::Map<String, serde_json::Value>,
312    event: &str,
313    command: &str,
314) -> bool {
315    if let Some(arr) = hooks.get(event).and_then(|v| v.as_array()) {
316        for group in arr {
317            if let Some(inner) = group.get("hooks").and_then(|h| h.as_array()) {
318                for hook in inner {
319                    if let Some(cmd) = hook.get("command").and_then(|c| c.as_str()) {
320                        // Match on the base command name, not the full path
321                        if cmd.contains("recall-echo archive-session")
322                            && command.contains("archive-session")
323                        {
324                            return true;
325                        }
326                        if cmd.contains("recall-echo checkpoint") && command.contains("checkpoint")
327                        {
328                            return true;
329                        }
330                        if cmd.contains("recall-echo consume") && command.contains("consume") {
331                            return true;
332                        }
333                    }
334                }
335            }
336        }
337    }
338    false
339}
340
341/// Check if stderr is a terminal (for interactive prompts).
342fn atty_check() -> bool {
343    use std::io::IsTerminal;
344    std::io::stderr().is_terminal()
345}
346
347/// Initialize memory structure at the given entity root.
348///
349/// Creates:
350/// ```text
351/// {entity_root}/memory/
352/// ├── MEMORY.md
353/// ├── EPHEMERAL.md
354/// ├── ARCHIVE.md
355/// ├── .recall-echo.toml
356/// └── conversations/
357/// ```
358pub fn run(entity_root: &Path) -> Result<(), RecallError> {
359    let stdin = io::stdin();
360    let mut reader = stdin.lock();
361    run_with_reader(entity_root, &mut reader)
362}
363
364/// Testable init with injectable reader.
365pub fn run_with_reader(entity_root: &Path, reader: &mut dyn BufRead) -> Result<(), RecallError> {
366    if !entity_root.exists() {
367        return Err(RecallError::NotInitialized(format!(
368            "Directory not found: {}\n  Create the directory first, or run from a valid path.",
369            entity_root.display()
370        )));
371    }
372
373    eprintln!("\n{BOLD}recall-echo{RESET} — initializing memory system\n");
374
375    let memory_dir = entity_root.join("memory");
376    let conversations_dir = memory_dir.join("conversations");
377    ensure_dir(&memory_dir);
378    ensure_dir(&conversations_dir);
379
380    // Write MEMORY.md (never overwrite)
381    write_if_not_exists(&memory_dir.join("MEMORY.md"), MEMORY_TEMPLATE, "MEMORY.md");
382
383    // Write EPHEMERAL.md (never overwrite)
384    write_if_not_exists(&memory_dir.join("EPHEMERAL.md"), "", "EPHEMERAL.md");
385
386    // Write ARCHIVE.md (never overwrite)
387    write_if_not_exists(
388        &memory_dir.join("ARCHIVE.md"),
389        ARCHIVE_TEMPLATE,
390        "ARCHIVE.md",
391    );
392
393    // Initialize graph store
394    init_graph(&memory_dir);
395
396    // Configure LLM provider if no config exists yet
397    let is_claude_code = configure_llm(reader, &memory_dir);
398
399    // Auto-configure Claude Code hooks if applicable
400    let hooks_configured = if is_claude_code {
401        configure_hooks(entity_root)
402    } else {
403        false
404    };
405
406    // Summary
407    eprintln!("\n{BOLD}Setup complete.{RESET} Memory system is ready.\n");
408    eprintln!("  Layer 1 (MEMORY.md)     — Curated facts, always in context");
409    eprintln!("  Layer 2 (EPHEMERAL.md)  — Rolling window of recent sessions (FIFO, max 5)");
410    eprintln!("  Layer 3 (Archive)       — Full conversations in memory/conversations/");
411    eprintln!("  Layer 0 (Graph)         — Knowledge graph with semantic search");
412    eprintln!();
413    eprintln!("  Run `recall-echo status` to check memory health.");
414    eprintln!("  Run `recall-echo config show` to view configuration.");
415    if hooks_configured {
416        eprintln!("  Hooks configured — archiving happens automatically.");
417    }
418    eprintln!();
419
420    Ok(())
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426    use std::io::Cursor;
427
428    #[test]
429    fn init_creates_directories_and_files() {
430        let tmp = tempfile::tempdir().unwrap();
431        let root = tmp.path().to_path_buf();
432        let mut reader = Cursor::new(b"4\n" as &[u8]); // skip provider prompt
433
434        run_with_reader(&root, &mut reader).unwrap();
435
436        assert!(root.join("memory/MEMORY.md").exists());
437        assert!(root.join("memory/EPHEMERAL.md").exists());
438        assert!(root.join("memory/ARCHIVE.md").exists());
439        assert!(root.join("memory/conversations").exists());
440    }
441
442    #[test]
443    fn init_is_idempotent() {
444        let tmp = tempfile::tempdir().unwrap();
445        let root = tmp.path().to_path_buf();
446        let mut reader = Cursor::new(b"4\n" as &[u8]);
447
448        run_with_reader(&root, &mut reader).unwrap();
449        fs::write(root.join("memory/MEMORY.md"), "custom content").unwrap();
450
451        let mut reader2 = Cursor::new(b"4\n" as &[u8]);
452        run_with_reader(&root, &mut reader2).unwrap();
453        let content = fs::read_to_string(root.join("memory/MEMORY.md")).unwrap();
454        assert_eq!(content, "custom content");
455    }
456
457    #[test]
458    fn init_fails_if_root_missing() {
459        let mut reader = Cursor::new(b"" as &[u8]);
460        let result = run_with_reader(Path::new("/nonexistent/path"), &mut reader);
461        assert!(result.is_err());
462    }
463
464    #[test]
465    fn hook_exists_recognizes_consume_command() {
466        let hooks_json: serde_json::Value = serde_json::json!({
467            "SessionStart": [{
468                "matcher": "startup|resume",
469                "hooks": [{"type": "command", "command": "/usr/local/bin/recall-echo consume"}]
470            }]
471        });
472        let hooks = hooks_json.as_object().unwrap();
473        assert!(hook_exists(hooks, "SessionStart", "recall-echo consume"));
474        assert!(!hook_exists(hooks, "SessionEnd", "recall-echo consume"));
475    }
476
477    #[test]
478    fn hook_exists_distinguishes_archive_from_consume() {
479        let hooks_json: serde_json::Value = serde_json::json!({
480            "SessionEnd": [{
481                "hooks": [{"type": "command", "command": "recall-echo archive-session"}]
482            }]
483        });
484        let hooks = hooks_json.as_object().unwrap();
485        assert!(hook_exists(
486            hooks,
487            "SessionEnd",
488            "recall-echo archive-session"
489        ));
490    }
491
492    #[test]
493    fn archive_template_has_header() {
494        let tmp = tempfile::tempdir().unwrap();
495        let mut reader = Cursor::new(b"4\n" as &[u8]);
496        run_with_reader(tmp.path(), &mut reader).unwrap();
497        let content = fs::read_to_string(tmp.path().join("memory/ARCHIVE.md")).unwrap();
498        assert!(content.contains("# Conversation Archive"));
499        assert!(content.contains("| # | Date"));
500    }
501}