use std::collections::HashSet;
use std::path::{Path, PathBuf};
use second_brain_core::schema::MemoryType;
use sha2::{Digest, Sha256};
use uuid::Uuid;
use crate::IngestResult;
use crate::document::{Document, v5, versioned};
use crate::git::Checkout;
use crate::session_evidence::modified_at;
pub const SOURCE: &str = "repo-instructions";
pub const FILES: &[&str] = &["CLAUDE.md", "AGENTS.md", ".claude/CLAUDE.md"];
pub fn instruction_files(checkout: &Checkout) -> Vec<PathBuf> {
let mut seen = HashSet::new();
FILES
.iter()
.map(|rel| checkout.root().join(rel))
.filter(|path| std::fs::metadata(path).is_ok_and(|m| m.is_file()))
.filter(|path| seen.insert(path.canonicalize().unwrap_or_else(|_| path.clone())))
.collect()
}
pub fn instructions_result(
checkout: &Checkout,
path: &Path,
machine_id: &str,
after: Option<Uuid>,
) -> Option<IngestResult> {
let text = std::fs::read_to_string(path).ok()?;
let body = text.trim();
if body.is_empty() {
return None;
}
let root = checkout.root();
let relative = path.strip_prefix(root).unwrap_or(path);
let digest = format!("{:x}", Sha256::digest(text.as_bytes()));
let location = path.display();
Some(
Document {
content: format!("{} for {}\n\n{body}", relative.display(), root.display()),
memory_id: v5(&versioned(&format!("{SOURCE}:{location}:{digest}"), after)),
memory_type: MemoryType::Procedural,
source: SOURCE,
source_id: path.to_string_lossy().to_string(),
conversation_id: v5(&format!("{SOURCE}:{location}")),
at: modified_at(path),
project: checkout.project_slug(),
machine_id,
}
.into_result(),
)
}