minni 0.1.1

Local memory, task, and codebase indexing tool for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;

const JOURNAL_FILE: &str = "journal.json";
const MAX_ENTRIES: usize = 50; // Keep last 50 entries

/// Journal entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JournalEntry {
    pub timestamp: String,
    pub entry_type: EntryType,
    pub git_branch: Option<String>,
    pub git_commit: Option<String>,
    pub commit_message: Option<String>,
    pub files_changed: Vec<FileChange>,
    pub symbols_modified: Vec<String>,
    pub user_note: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntryType {
    Commit,
    Manual,
    Session,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileChange {
    pub path: String,
    pub added: u32,
    pub removed: u32,
    pub symbols: Vec<String>,
}

/// Journal file contents.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Journal {
    pub project_name: String,
    pub entries: Vec<JournalEntry>,
}

/// Journal manager.
pub struct JournalManager {
    project_root: PathBuf,
    journal_path: PathBuf,
}

impl JournalManager {
    pub fn new(project_root: &Path) -> Self {
        let journal_path = project_root.join(".minni").join(JOURNAL_FILE);
        Self {
            project_root: project_root.to_path_buf(),
            journal_path,
        }
    }

    /// Load existing journal or create new one
    pub fn load(&self) -> Result<Journal> {
        if self.journal_path.exists() {
            let content = std::fs::read_to_string(&self.journal_path)
                .context("Failed to read journal file")?;
            serde_json::from_str(&content).context("Failed to parse journal")
        } else {
            Ok(Journal {
                project_name: self.get_project_name(),
                entries: vec![],
            })
        }
    }

    /// Save journal to disk
    pub fn save(&self, journal: &Journal) -> Result<()> {
        let content = serde_json::to_string_pretty(journal)?;
        std::fs::write(&self.journal_path, content)?;
        Ok(())
    }

    /// Record a git commit - called by post-commit hook
    pub fn record_commit(&self) -> Result<JournalEntry> {
        let mut journal = self.load()?;

        let entry = JournalEntry {
            timestamp: chrono::Utc::now().to_rfc3339(),
            entry_type: EntryType::Commit,
            git_branch: self.get_git_branch(),
            git_commit: self.get_git_commit(),
            commit_message: self.get_commit_message(),
            files_changed: self.get_commit_changes()?,
            symbols_modified: vec![], // Could parse from diff
            user_note: None,
        };

        journal.entries.push(entry.clone());

        // Trim to max entries
        if journal.entries.len() > MAX_ENTRIES {
            journal.entries = journal
                .entries
                .split_off(journal.entries.len() - MAX_ENTRIES);
        }

        self.save(&journal)?;
        Ok(entry)
    }

    /// Add a manual note to the journal
    pub fn add_note(&self, note: &str) -> Result<JournalEntry> {
        let mut journal = self.load()?;

        let entry = JournalEntry {
            timestamp: chrono::Utc::now().to_rfc3339(),
            entry_type: EntryType::Manual,
            git_branch: self.get_git_branch(),
            git_commit: self.get_git_commit(),
            commit_message: None,
            files_changed: vec![],
            symbols_modified: vec![],
            user_note: Some(note.to_string()),
        };

        journal.entries.push(entry.clone());

        if journal.entries.len() > MAX_ENTRIES {
            journal.entries = journal
                .entries
                .split_off(journal.entries.len() - MAX_ENTRIES);
        }

        self.save(&journal)?;
        Ok(entry)
    }

    /// Get recent journal for AI context
    pub fn get_recent(&self, count: usize) -> Result<Vec<JournalEntry>> {
        let journal = self.load()?;
        let start = journal.entries.len().saturating_sub(count);
        Ok(journal.entries[start..].to_vec())
    }

    /// Format journal as markdown for AI consumption
    pub fn to_markdown(&self, count: usize) -> Result<String> {
        let entries = self.get_recent(count)?;
        let mut md = String::new();

        md.push_str(&format!(
            "# Project Journal: {}\n\n",
            self.get_project_name()
        ));

        if entries.is_empty() {
            md.push_str("No journal entries yet.\n");
            return Ok(md);
        }

        for entry in entries.iter().rev() {
            md.push_str(&format!("## {}\n", entry.timestamp));

            match entry.entry_type {
                EntryType::Commit => {
                    if let Some(ref msg) = entry.commit_message {
                        md.push_str(&format!("**Commit:** {}\n", msg));
                    }
                    if let Some(ref commit) = entry.git_commit {
                        md.push_str(&format!("**SHA:** `{}`\n", &commit[..7.min(commit.len())]));
                    }
                }
                EntryType::Manual => {
                    md.push_str("**Note**\n");
                }
                EntryType::Session => {
                    md.push_str("**Session marker**\n");
                }
            }

            if let Some(ref branch) = entry.git_branch {
                md.push_str(&format!("**Branch:** {}\n", branch));
            }

            if !entry.files_changed.is_empty() {
                md.push_str("\n**Files changed:**\n");
                for fc in &entry.files_changed {
                    let symbols = if fc.symbols.is_empty() {
                        String::new()
                    } else {
                        format!(" ({})", fc.symbols.join(", "))
                    };
                    md.push_str(&format!(
                        "- `{}` +{} -{}{}\n",
                        fc.path, fc.added, fc.removed, symbols
                    ));
                }
            }

            if let Some(ref note) = entry.user_note {
                md.push_str(&format!("\n{}\n", note));
            }

            md.push_str("\n---\n\n");
        }

        Ok(md)
    }

    /// Clear journal
    pub fn clear(&self) -> Result<()> {
        let journal = Journal {
            project_name: self.get_project_name(),
            entries: vec![],
        };
        self.save(&journal)
    }

    // Git helpers
    fn get_git_branch(&self) -> Option<String> {
        Command::new("git")
            .args(["rev-parse", "--abbrev-ref", "HEAD"])
            .current_dir(&self.project_root)
            .output()
            .ok()
            .and_then(|o| {
                if o.status.success() {
                    Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
                } else {
                    None
                }
            })
    }

    fn get_git_commit(&self) -> Option<String> {
        Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&self.project_root)
            .output()
            .ok()
            .and_then(|o| {
                if o.status.success() {
                    Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
                } else {
                    None
                }
            })
    }

    fn get_commit_message(&self) -> Option<String> {
        Command::new("git")
            .args(["log", "-1", "--format=%s"])
            .current_dir(&self.project_root)
            .output()
            .ok()
            .and_then(|o| {
                if o.status.success() {
                    Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
                } else {
                    None
                }
            })
    }

    fn get_commit_changes(&self) -> Result<Vec<FileChange>> {
        // Get files changed in last commit with stats
        let output = Command::new("git")
            .args(["diff", "--numstat", "HEAD~1", "HEAD"])
            .current_dir(&self.project_root)
            .output()?;

        if !output.status.success() {
            // Might be first commit, try different approach
            let output = Command::new("git")
                .args(["diff", "--numstat", "--cached", "HEAD"])
                .current_dir(&self.project_root)
                .output()?;

            if !output.status.success() {
                return Ok(vec![]);
            }
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut changes = vec![];

        for line in stdout.lines() {
            let parts: Vec<&str> = line.split('\t').collect();
            if parts.len() >= 3 {
                let added = parts[0].parse().unwrap_or(0);
                let removed = parts[1].parse().unwrap_or(0);
                let path = parts[2].to_string();

                // Try to extract symbols from the file
                let symbols = self.extract_symbols_from_diff(&path);

                changes.push(FileChange {
                    path,
                    added,
                    removed,
                    symbols,
                });
            }
        }

        Ok(changes)
    }

    fn extract_symbols_from_diff(&self, file_path: &str) -> Vec<String> {
        // Get function names from diff hunks
        let output = Command::new("git")
            .args(["diff", "-U0", "HEAD~1", "HEAD", "--", file_path])
            .current_dir(&self.project_root)
            .output()
            .ok();

        let mut symbols = vec![];

        if let Some(output) = output {
            if output.status.success() {
                let stdout = String::from_utf8_lossy(&output.stdout);
                for line in stdout.lines() {
                    // Git diff shows function context in @@ ... @@ lines
                    if line.starts_with("@@") {
                        if let Some(func) = extract_function_from_hunk(line) {
                            if !symbols.contains(&func) {
                                symbols.push(func);
                            }
                        }
                    }
                }
            }
        }

        symbols
    }

    fn get_project_name(&self) -> String {
        self.project_root
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| "unknown".to_string())
    }

    /// Install git hooks for auto-journaling
    pub fn install_hooks(&self) -> Result<()> {
        let git_dir = self.project_root.join(".git");
        if !git_dir.exists() {
            anyhow::bail!("Not a git repository");
        }

        let hooks_dir = git_dir.join("hooks");
        std::fs::create_dir_all(&hooks_dir)?;

        // Post-commit hook
        let post_commit = hooks_dir.join("post-commit");
        let hook_content = r#"#!/bin/sh
# Minni auto-journaling hook
if command -v minni &> /dev/null; then
    minni journal record 2>/dev/null || true
fi
"#;

        // Check if hook exists and append if needed
        if post_commit.exists() {
            let existing = std::fs::read_to_string(&post_commit)?;
            if !existing.contains("minni journal record") {
                let mut new_content = existing;
                new_content.push_str(
                    "\n# Minni auto-journaling\nminni journal record 2>/dev/null || true\n",
                );
                std::fs::write(&post_commit, new_content)?;
            }
        } else {
            std::fs::write(&post_commit, hook_content)?;
        }

        // Make executable
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&post_commit)?.permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&post_commit, perms)?;
        }

        Ok(())
    }

    /// Uninstall git hooks
    pub fn uninstall_hooks(&self) -> Result<()> {
        let post_commit = self
            .project_root
            .join(".git")
            .join("hooks")
            .join("post-commit");

        if post_commit.exists() {
            let content = std::fs::read_to_string(&post_commit)?;
            // Remove minni lines
            let new_content: Vec<&str> = content
                .lines()
                .filter(|l| !l.contains("minni journal") && !l.contains("Minni auto-journaling"))
                .collect();

            if new_content
                .iter()
                .all(|l| l.trim().is_empty() || l.starts_with("#!"))
            {
                // Only shebang left, remove the file
                std::fs::remove_file(&post_commit)?;
            } else {
                std::fs::write(&post_commit, new_content.join("\n"))?;
            }
        }

        Ok(())
    }
}

/// Extract function name from git diff hunk header
fn extract_function_from_hunk(line: &str) -> Option<String> {
    // Format: @@ -start,count +start,count @@ optional function context
    let parts: Vec<&str> = line.splitn(4, "@@").collect();
    if parts.len() >= 3 {
        let context = parts[2].trim();
        if !context.is_empty() {
            // Extract just the function name
            // Common patterns: "fn name", "def name", "function name", "pub fn name"
            let words: Vec<&str> = context.split_whitespace().collect();
            for (i, word) in words.iter().enumerate() {
                if *word == "fn" || *word == "def" || *word == "function" || *word == "func" {
                    if let Some(name) = words.get(i + 1) {
                        // Clean up the name (remove parens, etc)
                        let clean = name.split('(').next().unwrap_or(name);
                        return Some(clean.to_string());
                    }
                }
            }
            // Fallback: return first identifier-like word
            if let Some(first) = words.first() {
                if first
                    .chars()
                    .next()
                    .map(|c| c.is_alphabetic())
                    .unwrap_or(false)
                {
                    return Some(first.to_string());
                }
            }
        }
    }
    None
}