use std::collections::HashSet;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use sha2::{Digest, Sha256};
use uuid::Uuid;
use second_brain_core::redact::redact_for_store;
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(
content: &str,
source_id: &str,
conversation_id: Uuid,
) -> (
Vec<Memory>,
Vec<(ExtractedEntity, Uuid)>,
Option<DateTime<Utc>>,
) {
let transcript = read_transcript(content);
let mut memories = Vec::new();
let mut all_entities: Vec<(ExtractedEntity, Uuid)> = Vec::new();
let mut seen_entities: HashSet<String> = HashSet::new();
for chunk in transcript.screened_chunks() {
if !chunk.kept() {
continue;
}
let memory_type = classify_memory(&chunk.text);
let mut memory = Memory::new(
chunk.text.clone(),
memory_type,
"claude-code".to_string(),
source_id.to_string(),
);
memory.id = raw_memory_id(conversation_id, &chunk.text);
memory.session_at = chunk.at;
let memory_id = memory.id;
memories.push(memory);
for entity in extract_entities(&chunk.text) {
let key = entity.name.to_lowercase();
if seen_entities.insert(key) {
all_entities.push((entity, memory_id));
}
}
}
(memories, all_entities, transcript.first_timestamp)
}
}
pub fn session_key(content: &str) -> Option<String> {
let mut session: Option<String> = None;
let mut agent: Option<String> = None;
for line in content.lines() {
let wants_session = session.is_none() && line.contains("\"sessionId\"");
let wants_agent = agent.is_none() && line.contains("\"agentId\"");
if !wants_session && !wants_agent {
continue;
}
let Ok(msg) = serde_json::from_str::<serde_json::Value>(line) else {
continue;
};
let field = |name: &str| {
msg.get(name)
.and_then(|v| v.as_str())
.filter(|v| !v.is_empty())
.map(str::to_string)
};
if wants_session {
session = field("sessionId");
}
if wants_agent {
agent = field("agentId");
}
}
let session = session?;
Some(match agent {
Some(agent) => format!("{session}/{agent}"),
None => session,
})
}
fn session_key_or_stem(path: &Path, content: &str) -> String {
session_key(content).unwrap_or_else(|| {
path.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default()
})
}
pub fn conversation_id(session_key: &str) -> Uuid {
Uuid::new_v5(
&Uuid::NAMESPACE_OID,
format!("claude-code:{session_key}").as_bytes(),
)
}
pub fn raw_memory_id(conversation_id: Uuid, chunk_text: &str) -> Uuid {
let digest = Sha256::digest(chunk_text.as_bytes());
Uuid::new_v5(&conversation_id, hex(&digest).as_bytes())
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
pub(crate) struct AssistantText {
pub(crate) at: Option<DateTime<Utc>>,
pub(crate) text: String,
pub(crate) turn_final: bool,
}
pub(crate) struct Transcript {
pub(crate) first_timestamp: Option<DateTime<Utc>>,
pub(crate) assistant_texts: Vec<AssistantText>,
}
impl Transcript {
pub(crate) fn screened_chunks(&self) -> Vec<ScreenedChunk> {
self.assistant_texts
.iter()
.flat_map(|block| {
chunk_text(&block.text)
.into_iter()
.map(|text| ScreenedChunk {
failed: failed_rules(&text),
text,
at: block.at,
turn_final: block.turn_final,
})
})
.collect()
}
}
#[derive(Debug, Clone)]
pub struct ScreenedChunk {
pub text: String,
pub at: Option<DateTime<Utc>>,
pub turn_final: bool,
pub failed: Vec<FilterRule>,
}
impl ScreenedChunk {
pub fn kept(&self) -> bool {
self.failed.is_empty()
}
}
pub fn screen_transcript(content: &str) -> Vec<ScreenedChunk> {
read_transcript(content).screened_chunks()
}
const HARNESS_PREFIXES: [&str; 4] = [
"<local-command",
"<command-name>",
"<command-message>",
"Caveat:",
];
fn strip_system_reminders(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(start) = rest.find("<system-reminder>") {
out.push_str(&rest[..start]);
match rest[start..].find("</system-reminder>") {
Some(end) => rest = &rest[start + end + "</system-reminder>".len()..],
None => {
rest = "";
break;
}
}
}
out.push_str(rest);
out
}
fn is_typed_prompt(text: &str) -> bool {
let text = strip_system_reminders(text);
let text = text.trim();
!text.is_empty() && !HARNESS_PREFIXES.iter().any(|p| text.starts_with(p))
}
fn starts_turn(msg: &serde_json::Value) -> bool {
if msg.get("isMeta").and_then(|m| m.as_bool()) == Some(true) {
return false;
}
match msg.get("type").and_then(|t| t.as_str()) {
Some("user") => match msg.get("message").and_then(|m| m.get("content")) {
Some(serde_json::Value::String(text)) => is_typed_prompt(text),
Some(serde_json::Value::Array(blocks)) => {
if blocks
.iter()
.any(|b| b.get("type").and_then(|t| t.as_str()) == Some("tool_result"))
{
return false;
}
let text: Vec<&str> = blocks
.iter()
.filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("text"))
.filter_map(|b| b.get("text").and_then(|t| t.as_str()))
.collect();
is_typed_prompt(&text.join("\n"))
}
_ => false,
},
Some("attachment") => {
let attachment = msg.get("attachment");
attachment
.and_then(|a| a.get("type"))
.and_then(|t| t.as_str())
== Some("queued_command")
&& attachment
.and_then(|a| a.get("prompt"))
.and_then(|p| p.as_str())
.is_some_and(|p| !strip_system_reminders(p).trim().is_empty())
}
_ => false,
}
}
pub(crate) fn read_transcript(content: &str) -> Transcript {
let mut transcript = Transcript {
first_timestamp: None,
assistant_texts: Vec::new(),
};
let mut last_in_turn: Option<usize> = None;
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 at = msg
.get("timestamp")
.and_then(|t| t.as_str())
.and_then(|ts| DateTime::parse_from_rfc3339(ts).ok())
.map(|dt| dt.with_timezone(&Utc));
if transcript.first_timestamp.is_none() {
transcript.first_timestamp = at;
}
if starts_turn(&msg) {
if let Some(i) = last_in_turn.take() {
transcript.assistant_texts[i].turn_final = true;
}
continue;
}
if msg.get("type").and_then(|t| t.as_str()) != Some("assistant") {
continue;
}
let Some(blocks) = msg
.get("message")
.and_then(|m| m.get("content"))
.and_then(|c| c.as_array())
else {
continue;
};
for block in blocks {
if block.get("type").and_then(|t| t.as_str()) != Some("text") {
continue;
}
if let Some(text) = block.get("text").and_then(|t| t.as_str()) {
if !text.trim().is_empty() {
last_in_turn = Some(transcript.assistant_texts.len());
}
transcript.assistant_texts.push(AssistantText {
at,
text: redact_for_store(text),
turn_final: false,
});
}
}
}
if let Some(i) = last_in_turn {
transcript.assistant_texts[i].turn_final = true;
}
transcript
}
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 session_key(&self, path: &Path, content: &str) -> Option<String> {
Some(session_key_or_stem(path, content))
}
fn ingest_conversation(&self, source: &ConversationSource) -> Result<IngestResult> {
let path = PathBuf::from(&source.path);
let content = std::fs::read_to_string(&path)
.with_context(|| format!("reading conversation file: {}", path.display()))?;
let conversation_id = conversation_id(&session_key_or_stem(&path, &content));
let (memories, entities, started_at) =
Self::parse_conversation(&content, &path.to_string_lossy(), conversation_id);
let project_dir = crate::project_slug(&self.base_path.join("projects"), &path);
let conversation = Conversation {
id: conversation_id,
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
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FilterRule {
TooShort,
CodeHeavy,
TooFewWords,
NoiseOpening,
NoisePhrases,
Narration,
}
impl FilterRule {
pub fn name(self) -> &'static str {
match self {
FilterRule::TooShort => "too_short",
FilterRule::CodeHeavy => "code_heavy",
FilterRule::TooFewWords => "too_few_words",
FilterRule::NoiseOpening => "noise_opening",
FilterRule::NoisePhrases => "noise_phrases",
FilterRule::Narration => "narration",
}
}
}
#[cfg(test)]
fn is_memorable(text: &str) -> bool {
failed_rules(text).is_empty()
}
fn failed_rules(text: &str) -> Vec<FilterRule> {
let mut failed = Vec::new();
let trimmed = text.trim();
if trimmed.len() < 80 {
failed.push(FilterRule::TooShort);
}
let code_block_count = trimmed.matches("```").count() / 2;
if code_block_count > 8 {
failed.push(FilterRule::CodeHeavy);
}
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 {
failed.push(FilterRule::TooFewWords);
}
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) {
failed.push(FilterRule::NoiseOpening);
}
let noise_count = count_noise_phrases(&lower);
if noise_count >= 2 || (noise_count == 1 && non_code_lines.len() < 4) {
failed.push(FilterRule::NoisePhrases);
}
if is_pure_narration(&lower) && non_code_lines.len() < 5 {
failed.push(FilterRule::Narration);
}
failed
}
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
}
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",
];
pub 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
}
#[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 lists_every_rule_a_chunk_fails() {
assert_eq!(
failed_rules("Let me check the logs. Task complete."),
vec![
FilterRule::TooShort,
FilterRule::TooFewWords,
FilterRule::NoiseOpening,
FilterRule::NoisePhrases,
FilterRule::Narration,
]
);
}
#[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."
));
}
}