use std::collections::HashSet;
use std::path::PathBuf;
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use uuid::Uuid;
use second_brain_core::schema::{Conversation, Memory, MemoryType};
use crate::{Adapter, ConversationSource, ExtractedEntity, IngestResult};
pub struct ClaudeCodeAdapter {
base_path: PathBuf,
machine_id: String,
}
impl ClaudeCodeAdapter {
pub fn new(machine_id: String) -> Self {
let base_path = dirs_home().join(".claude");
Self {
base_path,
machine_id,
}
}
pub fn with_path(base_path: PathBuf, machine_id: String) -> Self {
Self {
base_path,
machine_id,
}
}
#[allow(clippy::type_complexity)]
fn parse_conversation_file(
&self,
path: &PathBuf,
) -> Result<(
Vec<Memory>,
Vec<(ExtractedEntity, Uuid)>,
Option<DateTime<Utc>>,
)> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("reading conversation file: {}", path.display()))?;
let mut memories = Vec::new();
let mut all_entities: Vec<(ExtractedEntity, Uuid)> = Vec::new();
let mut seen_entities: HashSet<String> = HashSet::new();
let mut first_timestamp: Option<DateTime<Utc>> = None;
let source_id = path.to_string_lossy().to_string();
for line in content.lines() {
if line.trim().is_empty() {
continue;
}
let msg: serde_json::Value = match serde_json::from_str(line) {
Ok(v) => v,
Err(_) => continue,
};
let msg_type = msg.get("type").and_then(|t| t.as_str()).unwrap_or("");
if first_timestamp.is_none()
&& let Some(ts) = msg.get("timestamp").and_then(|t| t.as_str())
{
first_timestamp = DateTime::parse_from_rfc3339(ts)
.map(|dt| dt.with_timezone(&Utc))
.ok();
}
if msg_type != "assistant" {
continue;
}
let message = match msg.get("message") {
Some(m) => m,
None => continue,
};
let content_blocks = match message.get("content").and_then(|c| c.as_array()) {
Some(blocks) => blocks,
None => continue,
};
for block in content_blocks {
let block_type = block.get("type").and_then(|t| t.as_str()).unwrap_or("");
let text = match block_type {
"text" => block.get("text").and_then(|t| t.as_str()),
_ => None,
};
if let Some(text) = text {
let chunks = chunk_text(text);
for chunk in chunks {
if !is_memorable(&chunk) {
continue;
}
let memory_type = classify_memory(&chunk);
let memory = Memory::new(
chunk.clone(),
memory_type,
"claude-code".to_string(),
source_id.clone(),
);
let memory_id = memory.id;
memories.push(memory);
for entity in extract_entities(&chunk) {
let key = entity.name.to_lowercase();
if seen_entities.insert(key) {
all_entities.push((entity, memory_id));
}
}
}
}
}
}
Ok((memories, all_entities, first_timestamp))
}
}
impl Adapter for ClaudeCodeAdapter {
fn name(&self) -> &str {
"claude-code"
}
fn discover_conversations(&self) -> Result<Vec<ConversationSource>> {
let projects_dir = self.base_path.join("projects");
let mut sources = Vec::new();
if !projects_dir.exists() {
return Ok(sources);
}
let mut dirs = vec![projects_dir];
while let Some(dir) = dirs.pop() {
for entry in std::fs::read_dir(&dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
dirs.push(path);
} else if path.extension().is_some_and(|e| e == "jsonl") {
sources.push(ConversationSource {
id: path.to_string_lossy().to_string(),
path: path.to_string_lossy().to_string(),
source_name: "claude-code".to_string(),
machine_id: self.machine_id.clone(),
});
}
}
}
Ok(sources)
}
fn ingest_conversation(&self, source: &ConversationSource) -> Result<IngestResult> {
let path = PathBuf::from(&source.path);
let (memories, entities, started_at) = self.parse_conversation_file(&path)?;
let project_dir = path
.parent()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()));
let conversation = Conversation {
id: Uuid::new_v4(),
source: "claude-code".to_string(),
machine_id: source.machine_id.clone(),
started_at: started_at.unwrap_or_else(Utc::now),
project_path: project_dir.clone(),
};
let mut memories = memories;
for mem in &mut memories {
mem.project_path = project_dir.clone();
}
let entity_count = entities.len();
Ok(IngestResult {
conversation,
memories,
entities,
entities_extracted: entity_count,
})
}
}
fn dirs_home() -> PathBuf {
std::env::var("HOME")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("/tmp"))
}
fn chunk_text(text: &str) -> Vec<String> {
let mut chunks = Vec::new();
let mut current = String::new();
for paragraph in text.split("\n\n") {
let trimmed = paragraph.trim();
if trimmed.is_empty() {
continue;
}
if current.len() + trimmed.len() > 1500 && !current.is_empty() {
chunks.push(std::mem::take(&mut current));
}
if !current.is_empty() {
current.push_str("\n\n");
}
current.push_str(trimmed);
if current.len() >= 800 {
chunks.push(std::mem::take(&mut current));
}
}
if !current.is_empty() {
chunks.push(current);
}
if chunks.is_empty() && !text.trim().is_empty() {
chunks.push(text.trim().to_string());
}
chunks
}
fn is_memorable(text: &str) -> bool {
let trimmed = text.trim();
if trimmed.len() < 80 {
return false;
}
let code_block_count = trimmed.matches("```").count() / 2;
if code_block_count > 8 {
return false;
}
let lines: Vec<&str> = trimmed.lines().collect();
let non_code_lines: Vec<&str> = lines
.iter()
.filter(|l| {
let t = l.trim();
!t.is_empty()
&& !t.starts_with("```")
&& !t.starts_with('\t')
&& !t.starts_with("//")
&& !t.starts_with(" ")
})
.copied()
.collect();
let word_count = trimmed.split_whitespace().count();
if non_code_lines.len() < 2 && word_count < 15 {
return false;
}
let lower = trimmed.to_lowercase();
let first_line_lower = non_code_lines
.first()
.map(|l| l.trim().to_lowercase())
.unwrap_or_default();
if is_noise_opening(&first_line_lower) && !has_substance(&lower) {
return false;
}
let noise_count = count_noise_phrases(&lower);
if noise_count >= 2 {
return false;
}
if noise_count == 1 && non_code_lines.len() < 4 {
return false;
}
if is_pure_narration(&lower) && non_code_lines.len() < 5 {
return false;
}
true
}
fn is_noise_opening(first_line: &str) -> bool {
let patterns = [
"let me ",
"i'll ",
"i will ",
"now let me",
"now i'll",
"let's ",
"good question",
"good, ",
"good ",
"great, ",
"perfect",
"excellent",
"alright",
"ok, ",
"okay, ",
"sure, ",
"certainly",
"absolutely",
"interesting",
"i see",
"i notice",
"i can see",
"looking at",
"checking ",
"exploring ",
"examining ",
"navigating ",
"reading ",
];
patterns.iter().any(|p| first_line.starts_with(p))
}
fn has_substance(text: &str) -> bool {
let markers = [
"because",
"the fix",
"the solution",
"the issue",
"the problem",
"decided",
"trade-off",
"tradeoff",
"architecture",
"we chose",
"root cause",
"the reason",
"this means",
"this works",
"the approach",
"conclusion",
"in summary",
];
markers.iter().any(|m| text.contains(m))
}
fn count_noise_phrases(text: &str) -> usize {
let phrases = [
"let me check",
"let me look",
"let me explore",
"let me examine",
"let me navigate",
"let me read",
"let me search",
"let me find",
"let me verify",
"let me investigate",
"let me continue",
"let me review",
"let me start by",
"let me run",
"i'll check",
"i'll look",
"i'll explore",
"i'll examine",
"i'll search",
"i'll read",
"i'll investigate",
"i'll start by",
"i'll run",
"now let me",
];
phrases.iter().filter(|p| text.contains(*p)).count()
}
fn is_pure_narration(text: &str) -> bool {
let patterns = [
"i have the project context",
"i have a complete picture",
"mark the exploration task",
"mark the task",
"committed changes:",
"let me mark",
"task done",
"task complete",
];
patterns.iter().any(|p| text.contains(p))
}
fn classify_memory(text: &str) -> MemoryType {
let lower = text.to_lowercase();
let task_markers = [
"todo:",
"todo ",
"fixme",
"action item",
"remaining:",
"left to do",
"need to implement",
"needs to be done",
"next step:",
"next steps:",
"backlog:",
];
if task_markers.iter().any(|m| lower.contains(m)) {
return MemoryType::Task;
}
let decision_markers = [
"decided",
"chose",
"went with",
"picked",
"agreed",
"choosing",
"selected",
"switched to",
"we'll use",
"we'll go with",
"the decision",
"opting for",
];
if decision_markers.iter().any(|m| lower.contains(m)) {
return MemoryType::Decision;
}
let architecture_markers = [
"architecture",
"data model",
"schema design",
"the approach is",
"system design",
"component design",
"abstraction",
"design pattern",
"data flow",
"the pattern",
"module structure",
"separation of concern",
];
if architecture_markers.iter().any(|m| lower.contains(m)) {
return MemoryType::Architecture;
}
let debugging_markers = [
"root cause",
"the bug",
"the issue is",
"the problem is",
"stack trace",
"error was",
"the fix is",
"debugging",
"regression",
"crash",
"panicked",
"segfault",
];
if debugging_markers.iter().any(|m| lower.contains(m)) {
return MemoryType::Debugging;
}
if lower.contains('?') {
let interrogative = [
"how ",
"what ",
"why ",
"whether ",
"should we",
"could we",
"where ",
"when ",
"which ",
];
if interrogative.iter().any(|m| lower.contains(m)) {
return MemoryType::Question;
}
}
let procedural_markers = [
"to do this",
"steps:",
"step 1",
"first,",
"then,",
"finally,",
"run ",
"install ",
"execute",
"command:",
"configure",
"set up",
"to fix",
"solution:",
"you need to",
"you can ",
"you should",
"here's how",
];
if procedural_markers.iter().any(|m| lower.contains(m)) {
return MemoryType::Procedural;
}
let episodic_markers = [
"migrated",
"deployed",
"shipped",
"found that",
"discovered",
"realized",
"confirmed",
"concluded",
];
if episodic_markers.iter().any(|m| lower.contains(m)) {
return MemoryType::Episodic;
}
MemoryType::Semantic
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_task() {
assert_eq!(
classify_memory("TODO: implement the retry logic for failed sync batches"),
MemoryType::Task
);
assert_eq!(
classify_memory(
"There's a FIXME in the auth module that needs addressing before release"
),
MemoryType::Task
);
assert_eq!(
classify_memory(
"Action item from the review: add rate limiting to the ingest endpoint"
),
MemoryType::Task
);
}
#[test]
fn classifies_decision() {
assert_eq!(
classify_memory(
"We decided to use KuzuDB instead of Neo4j because it embeds and needs no separate server"
),
MemoryType::Decision
);
assert_eq!(
classify_memory("Chose axum over actix-web for the HTTP framework"),
MemoryType::Decision
);
assert_eq!(
classify_memory(
"Went with a daemon architecture so only one process holds the DB lock"
),
MemoryType::Decision
);
}
#[test]
fn classifies_architecture() {
assert_eq!(
classify_memory(
"The architecture uses a single daemon that owns the database and serves queries over HTTP"
),
MemoryType::Architecture
);
assert_eq!(
classify_memory(
"The data model separates memories from entities with MENTIONS relations between them"
),
MemoryType::Architecture
);
assert_eq!(
classify_memory("The design pattern here is event sourcing via the SyncLog table"),
MemoryType::Architecture
);
}
#[test]
fn classifies_debugging() {
assert_eq!(
classify_memory(
"The root cause was a race condition in the file watcher debounce logic"
),
MemoryType::Debugging
);
assert_eq!(
classify_memory(
"The issue is that KuzuDB returns an error when the embedding array is empty"
),
MemoryType::Debugging
);
assert_eq!(
classify_memory(
"The bug manifests as a 413 error because axum has a default 2MB body limit"
),
MemoryType::Debugging
);
}
#[test]
fn classifies_question() {
assert_eq!(
classify_memory(
"How should we handle the case where the LLM is unreachable during consolidation?"
),
MemoryType::Question
);
assert_eq!(
classify_memory(
"What happens when two machines sync conflicting edits to the same memory?"
),
MemoryType::Question
);
}
#[test]
fn classifies_procedural() {
assert_eq!(
classify_memory(
"To fix the auth issue you need to regenerate the token and update the environment variable"
),
MemoryType::Procedural
);
assert_eq!(
classify_memory(
"Steps: first install the dependency, then configure the TOML file, finally restart the daemon"
),
MemoryType::Procedural
);
}
#[test]
fn classifies_episodic() {
assert_eq!(
classify_memory(
"Deployed the new sync module to the Raspberry Pi and it handled 50k records without issues"
),
MemoryType::Episodic
);
assert_eq!(
classify_memory(
"Discovered that the embedding model outputs 384 dimensions, not 1536 as documented"
),
MemoryType::Episodic
);
}
#[test]
fn classifies_semantic_fallback() {
assert_eq!(
classify_memory(
"KuzuDB stores graph data in a columnar format optimized for analytical queries"
),
MemoryType::Semantic
);
assert_eq!(
classify_memory(
"BGE-small-en-v1.5 produces 384-dimensional vectors suitable for semantic search"
),
MemoryType::Semantic
);
}
#[test]
fn rejects_short_text() {
assert!(!is_memorable("short"));
assert!(!is_memorable("This is under eighty characters for sure."));
}
#[test]
fn rejects_noise_openings_without_substance() {
assert!(!is_memorable(
"Let me check the file structure to understand what we're working with here. I'll explore the codebase now."
));
assert!(!is_memorable(
"I'll look at the configuration files and see what's going on in the project directory structure for this."
));
assert!(!is_memorable(
"Looking at the codebase now. Let me navigate through the directory to find the relevant source files we need."
));
}
#[test]
fn keeps_noise_opening_with_substance() {
assert!(is_memorable(
"Let me explain the root cause of this bug. The issue is that the token expiry check uses less-than instead of less-than-or-equal, which means tokens expire one second early. The fix is straightforward."
));
}
#[test]
fn rejects_multiple_noise_phrases() {
assert!(!is_memorable(
"Let me check the logs. I'll also look at the configuration. Let me explore the routes to understand the full picture of this system."
));
}
#[test]
fn rejects_pure_narration() {
assert!(!is_memorable(
"Task complete. Committed changes: updated the auth middleware to fix the token validation."
));
assert!(!is_memorable(
"Let me mark the exploration task as done now that we've reviewed all the relevant files in the project."
));
}
#[test]
fn keeps_architectural_decisions() {
assert!(is_memorable(
"We decided to use a daemon architecture because KuzuDB takes an exclusive file lock. Only one process can open the database at a time, so we need a single daemon that owns the DB and serves everything else over HTTP."
));
}
#[test]
fn keeps_debugging_insights() {
assert!(is_memorable(
"Found that the 413 error was caused by axum's default 2MB body limit. The sync payload for 115k records exceeds that. The fix is adding DefaultBodyLimit::max(64MB) to the router layer."
));
}
#[test]
fn keeps_technical_explanations() {
assert!(is_memorable(
"The paginated export uses raw sequence order instead of sort_for_import because sorting reorders records by type, which breaks cursor-based pagination. The cursor tracks sequence numbers, so records must stay in sequence order."
));
}
#[test]
fn rejects_code_heavy_blocks() {
let mostly_code = "Here's the fix:\n```rust\nfn main() {\n println!(\"hello\");\n}\n```\n```rust\nfn other() {\n println!(\"world\");\n}\n```\n```rust\nfn third() {}\n```\n```rust\nfn fourth() {}\n```\n```rust\nfn fifth() {}\n```\n```rust\nfn sixth() {}\n```\n```rust\nfn seventh() {}\n```\n```rust\nfn eighth() {}\n```\n```rust\nfn ninth() {}\n```";
assert!(!is_memorable(mostly_code));
}
#[test]
fn rejects_single_noise_phrase_short_message() {
assert!(!is_memorable(
"Let me verify that the build works correctly before we move on to testing."
));
}
}
const TECH_NAMES: &[&str] = &[
"rust",
"python",
"javascript",
"typescript",
"go",
"java",
"c++",
"ruby",
"swift",
"kotlin",
"react",
"vue",
"angular",
"svelte",
"next.js",
"nuxt",
"django",
"flask",
"fastapi",
"express",
"axum",
"actix",
"tokio",
"serde",
"docker",
"kubernetes",
"k8s",
"terraform",
"ansible",
"nginx",
"apache",
"redis",
"postgres",
"postgresql",
"mysql",
"sqlite",
"mongodb",
"kuzudb",
"neo4j",
"elasticsearch",
"kafka",
"rabbitmq",
"nats",
"grpc",
"graphql",
"rest",
"websocket",
"ssh",
"tailscale",
"wireguard",
"git",
"github",
"gitlab",
"linux",
"ubuntu",
"debian",
"macos",
"windows",
"arm64",
"aarch64",
"x86",
"onnx",
"pytorch",
"tensorflow",
"huggingface",
"openai",
"anthropic",
"claude",
"gpt",
"llm",
"mcp",
"lsp",
"systemd",
"cron",
"tmux",
"vim",
"neovim",
"cargo",
"npm",
"pip",
"uv",
"bun",
"deno",
"node.js",
"node",
"aws",
"gcp",
"azure",
"s3",
"ec2",
"lambda",
"cloudflare",
"raspberry pi",
"pi",
"jetson",
"esp32",
"arduino",
"toml",
"yaml",
"json",
"jsonl",
"csv",
"protobuf",
"msgpack",
];
fn extract_entities(text: &str) -> Vec<ExtractedEntity> {
let mut entities = Vec::new();
let mut seen = HashSet::new();
let lower = text.to_lowercase();
for &tech in TECH_NAMES {
if lower.contains(tech) {
let key = tech.to_lowercase();
if seen.insert(key) {
entities.push(ExtractedEntity {
name: tech.to_string(),
entity_type: "technology".to_string(),
});
}
}
}
for word in text.split_whitespace() {
let clean = word.trim_matches(|c: char| {
!c.is_alphanumeric() && c != '/' && c != '.' && c != '-' && c != '_'
});
if clean.contains('/') && clean.contains('.') {
let ext_match = clean.rsplit('.').next().unwrap_or("");
let is_source_file = matches!(
ext_match,
"rs" | "py"
| "ts"
| "tsx"
| "js"
| "jsx"
| "go"
| "java"
| "rb"
| "sh"
| "toml"
| "json"
| "yaml"
| "yml"
| "md"
| "sql"
| "html"
| "css"
);
if is_source_file {
let key = clean.to_lowercase();
if seen.insert(key) {
entities.push(ExtractedEntity {
name: clean.to_string(),
entity_type: "file_path".to_string(),
});
}
}
}
}
entities
}