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
211    // Load existing settings or start fresh
212    let mut settings: serde_json::Value = if settings_path.exists() {
213        fs::read_to_string(&settings_path)
214            .ok()
215            .and_then(|s| serde_json::from_str(&s).ok())
216            .unwrap_or_else(|| serde_json::json!({}))
217    } else {
218        serde_json::json!({})
219    };
220
221    let hooks = settings.as_object_mut().and_then(|o| {
222        o.entry("hooks")
223            .or_insert_with(|| serde_json::json!({}))
224            .as_object_mut()
225    });
226
227    let hooks = match hooks {
228        Some(h) => h,
229        None => {
230            print_status(Status::Error, "Could not parse settings.json hooks");
231            return false;
232        }
233    };
234
235    let mut changed = false;
236
237    // Add SessionEnd hook if not already present
238    if !hook_exists(hooks, "SessionEnd", &archive_cmd) {
239        let arr = hooks
240            .entry("SessionEnd")
241            .or_insert_with(|| serde_json::json!([]))
242            .as_array_mut();
243        if let Some(arr) = arr {
244            arr.push(serde_json::json!({
245                "hooks": [{"type": "command", "command": archive_cmd}]
246            }));
247            changed = true;
248        }
249    }
250
251    // Add PreCompact hook if not already present
252    if !hook_exists(hooks, "PreCompact", &checkpoint_cmd) {
253        let arr = hooks
254            .entry("PreCompact")
255            .or_insert_with(|| serde_json::json!([]))
256            .as_array_mut();
257        if let Some(arr) = arr {
258            arr.push(serde_json::json!({
259                "hooks": [{"type": "command", "command": checkpoint_cmd}]
260            }));
261            changed = true;
262        }
263    }
264
265    if changed {
266        match serde_json::to_string_pretty(&settings) {
267            Ok(content) => match fs::write(&settings_path, content) {
268                Ok(()) => {
269                    print_status(
270                        Status::Created,
271                        "Configured SessionEnd + PreCompact hooks in settings.json",
272                    );
273                    return true;
274                }
275                Err(e) => print_status(
276                    Status::Error,
277                    &format!("Failed to write settings.json: {e}"),
278                ),
279            },
280            Err(e) => print_status(Status::Error, &format!("Failed to serialize settings: {e}")),
281        }
282    } else {
283        print_status(Status::Exists, "Hooks already configured in settings.json");
284        return true;
285    }
286
287    false
288}
289
290/// Check if a hook command already exists in a hook event array.
291fn hook_exists(
292    hooks: &serde_json::Map<String, serde_json::Value>,
293    event: &str,
294    command: &str,
295) -> bool {
296    if let Some(arr) = hooks.get(event).and_then(|v| v.as_array()) {
297        for group in arr {
298            if let Some(inner) = group.get("hooks").and_then(|h| h.as_array()) {
299                for hook in inner {
300                    if let Some(cmd) = hook.get("command").and_then(|c| c.as_str()) {
301                        // Match on the base command name, not the full path
302                        if cmd.contains("recall-echo archive-session")
303                            && command.contains("archive-session")
304                        {
305                            return true;
306                        }
307                        if cmd.contains("recall-echo checkpoint") && command.contains("checkpoint")
308                        {
309                            return true;
310                        }
311                    }
312                }
313            }
314        }
315    }
316    false
317}
318
319/// Check if stderr is a terminal (for interactive prompts).
320fn atty_check() -> bool {
321    use std::io::IsTerminal;
322    std::io::stderr().is_terminal()
323}
324
325/// Initialize memory structure at the given entity root.
326///
327/// Creates:
328/// ```text
329/// {entity_root}/memory/
330/// ├── MEMORY.md
331/// ├── EPHEMERAL.md
332/// ├── ARCHIVE.md
333/// ├── .recall-echo.toml
334/// └── conversations/
335/// ```
336pub fn run(entity_root: &Path) -> Result<(), RecallError> {
337    let stdin = io::stdin();
338    let mut reader = stdin.lock();
339    run_with_reader(entity_root, &mut reader)
340}
341
342/// Testable init with injectable reader.
343pub fn run_with_reader(entity_root: &Path, reader: &mut dyn BufRead) -> Result<(), RecallError> {
344    if !entity_root.exists() {
345        return Err(RecallError::NotInitialized(format!(
346            "Directory not found: {}\n  Create the directory first, or run from a valid path.",
347            entity_root.display()
348        )));
349    }
350
351    eprintln!("\n{BOLD}recall-echo{RESET} — initializing memory system\n");
352
353    let memory_dir = entity_root.join("memory");
354    let conversations_dir = memory_dir.join("conversations");
355    ensure_dir(&memory_dir);
356    ensure_dir(&conversations_dir);
357
358    // Write MEMORY.md (never overwrite)
359    write_if_not_exists(&memory_dir.join("MEMORY.md"), MEMORY_TEMPLATE, "MEMORY.md");
360
361    // Write EPHEMERAL.md (never overwrite)
362    write_if_not_exists(&memory_dir.join("EPHEMERAL.md"), "", "EPHEMERAL.md");
363
364    // Write ARCHIVE.md (never overwrite)
365    write_if_not_exists(
366        &memory_dir.join("ARCHIVE.md"),
367        ARCHIVE_TEMPLATE,
368        "ARCHIVE.md",
369    );
370
371    // Initialize graph store
372    init_graph(&memory_dir);
373
374    // Configure LLM provider if no config exists yet
375    let is_claude_code = configure_llm(reader, &memory_dir);
376
377    // Auto-configure Claude Code hooks if applicable
378    let hooks_configured = if is_claude_code {
379        configure_hooks(entity_root)
380    } else {
381        false
382    };
383
384    // Summary
385    eprintln!("\n{BOLD}Setup complete.{RESET} Memory system is ready.\n");
386    eprintln!("  Layer 1 (MEMORY.md)     — Curated facts, always in context");
387    eprintln!("  Layer 2 (EPHEMERAL.md)  — Rolling window of recent sessions (FIFO, max 5)");
388    eprintln!("  Layer 3 (Archive)       — Full conversations in memory/conversations/");
389    eprintln!("  Layer 0 (Graph)         — Knowledge graph with semantic search");
390    eprintln!();
391    eprintln!("  Run `recall-echo status` to check memory health.");
392    eprintln!("  Run `recall-echo config show` to view configuration.");
393    if hooks_configured {
394        eprintln!("  Hooks configured — archiving happens automatically.");
395    }
396    eprintln!();
397
398    Ok(())
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404    use std::io::Cursor;
405
406    #[test]
407    fn init_creates_directories_and_files() {
408        let tmp = tempfile::tempdir().unwrap();
409        let root = tmp.path().to_path_buf();
410        let mut reader = Cursor::new(b"4\n" as &[u8]); // skip provider prompt
411
412        run_with_reader(&root, &mut reader).unwrap();
413
414        assert!(root.join("memory/MEMORY.md").exists());
415        assert!(root.join("memory/EPHEMERAL.md").exists());
416        assert!(root.join("memory/ARCHIVE.md").exists());
417        assert!(root.join("memory/conversations").exists());
418    }
419
420    #[test]
421    fn init_is_idempotent() {
422        let tmp = tempfile::tempdir().unwrap();
423        let root = tmp.path().to_path_buf();
424        let mut reader = Cursor::new(b"4\n" as &[u8]);
425
426        run_with_reader(&root, &mut reader).unwrap();
427        fs::write(root.join("memory/MEMORY.md"), "custom content").unwrap();
428
429        let mut reader2 = Cursor::new(b"4\n" as &[u8]);
430        run_with_reader(&root, &mut reader2).unwrap();
431        let content = fs::read_to_string(root.join("memory/MEMORY.md")).unwrap();
432        assert_eq!(content, "custom content");
433    }
434
435    #[test]
436    fn init_fails_if_root_missing() {
437        let mut reader = Cursor::new(b"" as &[u8]);
438        let result = run_with_reader(Path::new("/nonexistent/path"), &mut reader);
439        assert!(result.is_err());
440    }
441
442    #[test]
443    fn archive_template_has_header() {
444        let tmp = tempfile::tempdir().unwrap();
445        let mut reader = Cursor::new(b"4\n" as &[u8]);
446        run_with_reader(tmp.path(), &mut reader).unwrap();
447        let content = fs::read_to_string(tmp.path().join("memory/ARCHIVE.md")).unwrap();
448        assert!(content.contains("# Conversation Archive"));
449        assert!(content.contains("| # | Date"));
450    }
451}