// BLOCK 0 — Memory Extraction & Pruning Utility (v4) // Copyright 2026 Joseph Stone — All Rights Reserved // // Compiles and runs against LIVE LMDB5 to extract, consolidate, and output // training data. Handles bincode-serialized MemoryEntry properly. // // KEY DESIGN: Duplicates multiply weight, not get discarded. // Same action repeated = stronger signal. // // 20-LEVEL LABEL SCALE: -10 (worst) to +10 (best), NO ZERO // Labels map to MSE regression targets for FLINT fine-tuning. // // WEIGHT RANGE: 1-8x (critical — clamped, never exceeds range) // // Usage: cargo run --bin prune_memories // // Outputs: // raw/pruned_memories.jsonl — consolidated training survivors // raw/archived_memories.jsonl — expired/TTL-cleaned entries (parked) // raw/memory_catalog.jsonl — categorized + tagged for brain re-index // raw/brain_index_pruned.jsonl — brain-ready format for spf_brain_index // // Outputs: // pruned_memories.jsonl — consolidated training survivors // archived_memories.jsonl — expired/TTL-cleaned entries (parked) // memory_catalog.jsonl — categorized + tagged for brain re-index use anyhow::Result; use heed::types::*; use heed::{Database, EnvOpenOptions}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap}; use std::fs; use std::hash::Hasher; use std::io::Write; use std::path::Path; use std::time::{SystemTime, UNIX_EPOCH}; // ============================================================================ // Structs copied EXACTLY from source (agent_state.rs, gate_training.rs) // ============================================================================ #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash)] pub enum MemoryType { Preference, Fact, Instruction, Context, Working, Pinned, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct MemoryEntry { pub id: String, pub content: String, pub memory_type: MemoryType, pub tags: Vec, pub source: String, pub created_at: u64, pub last_accessed: u64, pub access_count: u64, pub relevance: f64, pub expires_at: u64, } /// TrainingSignal — matches gate_training.rs EXACTLY (no `weight` field) #[derive(Debug, Clone, Deserialize, Serialize)] pub struct TrainingSignal { pub tool: String, pub source: String, pub allowed: bool, pub status: String, pub duration_ms: u64, pub timestamp: String, pub user_override: bool, pub false_positive: bool, pub recent_call_count: u32, pub preceding_tools: Vec, #[serde(default)] pub evil_score: f32, } // ============================================================================ // Output: consolidated training example — portable format for any model // ============================================================================ #[derive(Debug, Clone, Serialize)] pub struct ConsolidatedExample { /// Signed label: -3 (strongest avoid) to +2 (strong use). NO ZERO. pub label: i32, /// Training weight: 1.0 × occurrence_count. Scales with repetition. pub weight: f32, /// Tool or action name pub tool: String, /// Context: what happened, relevant details pub context: String, /// Outcome: "allowed", "blocked", or free text for memories pub outcome: String, /// Source: "tlog" (gate decision) or "memory" (agent memory) pub source_type: String, /// Memory category: edge_case, gate_context, user_intent, code_structure, reference pub category: String, /// How many occurrences were consolidated into this entry pub occurrence_count: u64, /// How many times this pattern was observed (for traceability) pub signal_strength: f64, } // ============================================================================ // Output: memory catalog for brain re-index // ============================================================================ #[derive(Debug, Clone, Serialize)] pub struct MemoryCatalog { pub id: String, pub content: String, pub category: String, pub tags: Vec, pub source_type: String, pub memory_type: String, pub relevance: f64, } // ============================================================================ // Constants // ============================================================================ const MAX_DB_SIZE: usize = 1024 * 1024 * 1024; // 1GB const OUTPUT_DIR: &str = "/data/data/com.termux/files/home/SPFsmartGATE/LIVE/TMP/stoneshell-brain/training_data"; // ============================================================================ // LABEL & WEIGHT FUNCTIONS // ============================================================================ /// Signed label for training signals. NO ZERO — every signal pushes. /// 20 levels: -10 (worst) to +10 (best) with improved granularity. fn label_for_training_signal(sig: &TrainingSignal) -> i32 { if sig.false_positive && sig.evil_score > 0.95 { return -10; } if sig.evil_score > 0.95 { return -10; } if sig.evil_score > 0.90 { return -9; } if sig.evil_score > 0.85 { return -8; } if sig.evil_score > 0.80 { return -7; } if sig.evil_score > 0.75 { return -6; } if sig.evil_score > 0.70 || (sig.false_positive && sig.evil_score > 0.70) { return -5; } if sig.evil_score > 0.65 { return -4; } if sig.evil_score > 0.60 || sig.false_positive { return -3; } if sig.evil_score > 0.40 || sig.false_positive || (sig.user_override && !sig.allowed) { return -2; } if !sig.allowed { return -1; } if sig.user_override { return 2; } // bare user override 1 // regular allow — low positive } /// Base training weight for a single signal fn weight_for_signal(sig: &TrainingSignal) -> f32 { if sig.evil_score > 0.95 { return 8.0; } if sig.evil_score > 0.90 { return 7.5; } if sig.evil_score > 0.85 { return 7.0; } if sig.evil_score > 0.80 { return 6.5; } if sig.evil_score > 0.75 { return 6.0; } if sig.evil_score > 0.70 { return 5.5; } if sig.evil_score > 0.65 { return 5.0; } if sig.evil_score > 0.60 { return 4.5; } if sig.evil_score > 0.40 { return 4.0; } if sig.false_positive { return 4.0; } if sig.user_override { return 2.0; } 1.0 } /// Inferred label for memory entries (no explicit signal fields) /// Maps MemoryType to 20-level scale fn label_for_memory(mem: &MemoryEntry) -> i32 { match mem.memory_type { MemoryType::Pinned => 10, // Highest positive — permanent knowledge MemoryType::Instruction => 9, // User directive — high trust MemoryType::Fact => 5, // Known fact — moderate positive MemoryType::Preference => 4, // User preference — positive MemoryType::Context => 3, // Contextual — mild positive MemoryType::Working => 0, // expired TTL — goes to archive (NO LABEL) } } /// BAD DATA LOOP SAFETY: If a +1 signal degrades (denied/fails), flip to -1. #[allow(dead_code)] fn degrade_positive(old_label: i32, outcome_failed: bool) -> i32 { if old_label > 0 && outcome_failed { return -1; // +1 or +2 → -1 (block), skip zero } old_label } /// Clamp weight to valid training range [1-8x]. Critical: values outside range /// break FLINT training. Max range is -10 to +10 for labels, 1-8x for weights. fn clamp_weight(w: f32) -> f32 { w.max(1.0).min(8.0) } // ================================================================================ // TODO: degrade_positive() usage — belongs in BLOCK 0 AUTO (live pruning) // NOT wired in prune_memories.rs (batch tool) — wire into flint_memory.rs instead // Trigger: When recalled memory leads to: gate block, tool failure, or user correction // Rule: low-level negatives accumulating = bad data loop. Must flip to -1. // ================================================================================ /// Value score for ranking memories (not training weight) fn score_memory(mem: &MemoryEntry) -> f64 { let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as f64 + 1.0; let recency = (mem.last_accessed as f64 / now) * 0.3; let relevance = mem.relevance * 0.3; let access = (mem.access_count as f64).min(10.0) * 0.1; let type_bonus = match mem.memory_type { MemoryType::Pinned => 3.0, MemoryType::Instruction => 2.0, MemoryType::Fact | MemoryType::Preference => 1.0, _ => 0.5, }; recency + relevance + access + type_bonus } /// Content hash for grouping exact duplicates fn content_hash(content: &str) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); h.write(content.as_bytes()); h.finish() } /// Categorize a memory entry for the brain catalog /// Priority: Pinned (reference) → Instruction/Preference (user_intent) → Fact (reference) → Gate/SPF tags (gate_context) → Code tags (code_structure) → context fn categorize_memory(mem: &MemoryEntry) -> &'static str { // Pinned facts and references — highest priority (label 10) if matches!(mem.memory_type, MemoryType::Pinned) { return "reference"; } // User preferences and instructions (label 9, 4) if matches!(mem.memory_type, MemoryType::Preference | MemoryType::Instruction) { return "user_intent"; } // Fact memories (label 5) if matches!(mem.memory_type, MemoryType::Fact) { return "reference"; } // Gate/SPF context — check tags AFTER memory_type if mem.tags.iter().any(|t| t.contains("gate") || t.contains("gateway") || t.contains("spf")) { return "gate_context"; } // Code structure knowledge if mem.tags.iter().any(|t| t.starts_with("tool:") || t.contains("code") || t.contains("function")) { return "code_structure"; } // Everything else is contextual "context" } /// Consolidate duplicate memories: count occurrences → scale weight /// Returns deduped entries plus consolidated data fn consolidate_duplicates(mems: &[MemoryEntry]) -> Vec<(&MemoryEntry, u64, f64)> { // Group by content hash let mut groups: BTreeMap> = BTreeMap::new(); for mem in mems { let h = content_hash(&mem.content); groups.entry(h).or_default().push(mem); } // For each group: pick the best representative (highest score), count occurrences groups.into_iter().map(|(_hash, members)| { let count = members.len() as u64; // Best representative = highest score let best = members.iter().max_by(|a, b| { score_memory(a).partial_cmp(&score_memory(b)).unwrap_or(std::cmp::Ordering::Equal) }).unwrap(); // Consolidated score: base_score × log(occurrences) for diminishing returns // but still meaningful: 5 copies = ~1.6x, 50 copies = ~3.9x, 100 copies = ~4.6x let base_score = score_memory(best); let consolidated_score = base_score * (1.0 + (count as f64).ln()); (*best, count, consolidated_score) }).collect() } fn find_lmdb_path() -> Result { let candidates = [ "LIVE/LMDB5/LMDB5.DB", "/data/data/com.termux/files/home/SPFsmartGATE/LIVE/LMDB5/LMDB5.DB", ]; for p in candidates { if Path::new(p).exists() { return Ok(p.to_string()); } } Err(anyhow::anyhow!( "LMDB5.DB not found. Run from SPFsmartGATE/ directory." )) } // ============================================================================ // MAIN // ============================================================================ fn main() -> Result<()> { let lmdb_path = find_lmdb_path()?; println!("[*] Opening LMDB at {}", lmdb_path); let env = unsafe { EnvOpenOptions::new() .map_size(MAX_DB_SIZE) .max_dbs(8) .open(Path::new(&lmdb_path))? }; // Open sub-DBs let rtxn = env.read_txn()?; let memory_db: Database> = env.open_database(&rtxn, Some("memory"))? .ok_or_else(|| anyhow::anyhow!("memory sub-DB not found"))?; let state_db: Database = env.open_database(&rtxn, Some("state"))? .ok_or_else(|| anyhow::anyhow!("state sub-DB not found"))?; // ======================================================================== // DUMP // ======================================================================== println!("[*] Dumping memories..."); let mut all_memories: Vec = Vec::new(); for result in memory_db.iter(&rtxn)? { let (_, entry) = result?; all_memories.push(entry); } println!(" Found {} memories", all_memories.len()); println!("[*] Dumping tlog:* state keys..."); let mut all_tlogs: Vec = Vec::new(); for result in state_db.iter(&rtxn)? { let (key, value) = result?; if key.starts_with("tlog:") { if let Ok(signal) = serde_json::from_str::(value) { all_tlogs.push(signal); } } } println!(" Found {} tlog entries", all_tlogs.len()); // ======================================================================== // 01: Expire TTL cleanup (separate expired from active) // ======================================================================== println!("\n[01] Expire TTL cleanup..."); let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); let _before = all_memories.len(); let mut expired_memories: Vec = Vec::new(); all_memories.retain(|m| { if m.expires_at != 0 && m.expires_at < now { expired_memories.push(m.clone()); false } else { true } }); println!(" Expired: {}. Active: {}.", expired_memories.len(), all_memories.len()); // ======================================================================== // 02: Consolidate duplicates (multiples → weight, not discard) // ======================================================================== println!("\n[02] Consolidate duplicates (multiples → signal weight)..."); let consolidated = consolidate_duplicates(&all_memories); // Separate by category let mut edge: Vec<(&MemoryEntry, u64, f64)> = Vec::new(); let mut gate: Vec<(&MemoryEntry, u64, f64)> = Vec::new(); let mut regular: Vec<(&MemoryEntry, u64, f64)> = Vec::new(); for (mem, count, score) in consolidated { let cat = categorize_memory(mem); match cat { "gate_context" => gate.push((mem, count, score)), _ if matches!(mem.memory_type, MemoryType::Pinned | MemoryType::Instruction) || score > 5.0 || mem.access_count > 5 => { edge.push((mem, count, score)); } _ => regular.push((mem, count, score)), } } println!(" Before: {} memories", all_memories.len()); println!(" Unique patterns: {}", edge.len() + gate.len() + regular.len()); println!(" Duplicates collapsed: {}", all_memories.len() - (edge.len() + gate.len() + regular.len())); println!(" Edge (high-value): {}", edge.len()); println!(" Gate context: {}", gate.len()); println!(" Regular: {}", regular.len()); // ======================================================================== // 03: Build consolidated training examples // ======================================================================== println!("\n[03] Building consolidated examples..."); let mut pruned: Vec = Vec::new(); // Tlogs: explicit labels from TrainingSignal for sig in &all_tlogs { let label = label_for_training_signal(sig); let weight = weight_for_signal(sig); let outcome = if sig.allowed { "allowed" } else { "blocked" }.to_string(); let context = format!( "Tool: {}. Source: {}. Duration: {}ms. Overrides: {}. Preceding: {}.", sig.tool, sig.source, sig.duration_ms, if sig.user_override { "yes" } else { "no" }, sig.preceding_tools.join(", ") ); pruned.push(ConsolidatedExample { label, weight, tool: sig.tool.clone(), context, outcome, source_type: "tlog".to_string(), category: "gate_decision".to_string(), occurrence_count: 1, signal_strength: weight as f64 * (1.0 + sig.evil_score as f64), }); } // Edge memories: highest priority, full inclusion for (mem, count, consolidated_score) in &edge { let label = label_for_memory(mem); if label == 0 { continue; } let cat = categorize_memory(mem); // Weight: occurrence count scaled, clamped to 1-8x range let raw_weight = (*count as f32).log2().min(3.0); // log2(8)=3, cap at 8x pruned.push(ConsolidatedExample { label, weight: clamp_weight(raw_weight + 1.0), // +1 base, up to 8x tool: match mem.memory_type { MemoryType::Instruction => "instruction".to_string(), MemoryType::Pinned => "pinned_fact".to_string(), _ => "memory".to_string(), }, context: mem.tags.join(", "), outcome: mem.content.clone(), source_type: "memory".to_string(), category: cat.to_string(), occurrence_count: *count, signal_strength: *consolidated_score, }); } // Gate memories: full inclusion (first baseline needs all data) for (mem, count, consolidated_score) in &gate { let label = label_for_memory(mem); if label == 0 { continue; } let cat = categorize_memory(mem); let raw_weight = (*count as f32).log2().min(3.0); pruned.push(ConsolidatedExample { label, weight: clamp_weight(raw_weight + 1.0), tool: "gate_context".to_string(), context: mem.tags.join(", "), outcome: mem.content.clone(), source_type: "memory".to_string(), category: cat.to_string(), occurrence_count: *count, signal_strength: *consolidated_score, }); } // Regular memories: full inclusion for (mem, count, consolidated_score) in ®ular { let label = label_for_memory(mem); if label == 0 { continue; } let cat = categorize_memory(mem); let raw_weight = (*count as f32).log2().min(3.0); pruned.push(ConsolidatedExample { label, weight: clamp_weight(raw_weight + 1.0), tool: "memory".to_string(), context: mem.tags.join(", "), outcome: mem.content.clone(), source_type: "memory".to_string(), category: cat.to_string(), occurrence_count: *count, signal_strength: *consolidated_score, }); } // Sort by signal_strength (highest = most important first) pruned.sort_by(|a, b| b.signal_strength.partial_cmp(&a.signal_strength) .unwrap_or(std::cmp::Ordering::Equal)); // ======================================================================== // 04: Build memory catalog for brain re-index // ======================================================================== println!("\n[04] Building memory catalog for brain re-index..."); let catalog: Vec = all_memories.iter() .map(|m| MemoryCatalog { id: m.id.clone(), content: m.content.clone(), category: categorize_memory(m).to_string(), tags: m.tags.clone(), source_type: m.source.clone(), memory_type: format!("{:?}", m.memory_type), relevance: m.relevance, }) .collect(); // ======================================================================== // 05: Write output files // ======================================================================== println!("\n[05] Writing output files..."); let raw_dir = format!("{}/raw", OUTPUT_DIR); fs::create_dir_all(&raw_dir)?; // Consolidated training survivors let out_path = format!("{}/raw/pruned_memories.jsonl", OUTPUT_DIR); let mut w = std::io::BufWriter::new(fs::File::create(&out_path)?); for entry in &pruned { serde_json::to_writer(&mut w, entry)?; w.write_all(b"\n")?; } drop(w); println!(" Training data: {} entries → {}", pruned.len(), out_path); // Archived (expired/TTL-cleaned, parked not deleted) let archive_path = format!("{}/raw/archived_memories.jsonl", OUTPUT_DIR); let mut aw = std::io::BufWriter::new(fs::File::create(&archive_path)?); for mem in &expired_memories { serde_json::to_writer(&mut aw, &serde_json::json!({ "id": mem.id, "type": format!("{:?}", mem.memory_type), "content": mem.content, "tags": mem.tags, "relevance": mem.relevance, "archived": "ttl_expired" }))?; aw.write_all(b"\n")?; } drop(aw); println!(" Archive: {} entries → {}", expired_memories.len(), archive_path); // Memory catalog for brain re-index let catalog_path = format!("{}/raw/memory_catalog.jsonl", OUTPUT_DIR); let mut cw = std::io::BufWriter::new(fs::File::create(&catalog_path)?); for entry in &catalog { serde_json::to_writer(&mut cw, entry)?; cw.write_all(b"\n")?; } drop(cw); println!(" Catalog: {} entries → {}", catalog.len(), catalog_path); // ======================================================================== // 06: Index pruned memories to brain // ======================================================================== println!("\n[06] Indexing training data to brain..."); let brain_index_path = format!("{}/raw/brain_index_pruned.jsonl", OUTPUT_DIR); let mut bw = std::io::BufWriter::new(fs::File::create(&brain_index_path)?); for entry in &pruned { // Format for brain: text = context + outcome + tool + category let text = format!( "[{}] {} | {} | {} | {}", entry.source_type, entry.category, entry.tool, entry.context, entry.outcome ); serde_json::to_writer(&mut bw, &serde_json::json!({ "text": text, "label": entry.label, "weight": entry.weight, "tool": entry.tool, "source": entry.source_type }))?; bw.write_all(b"\n")?; } drop(bw); println!(" Brain index: {} entries → {}", pruned.len(), brain_index_path); println!(" NOTE: Run 'spf_brain_index' tool on this file to add to brain collection"); // ======================================================================== // 07: Archive raw memories for future improved pruning // ======================================================================== println!("\n[07] Archiving raw memories for future pruning..."); let catalog_path = format!("{}/raw/memory_catalog.jsonl", OUTPUT_DIR); println!(" Raw archive: {} entries at {}", catalog.len(), catalog_path); println!(" Safe for future improved pruning methods"); // ======================================================================== // 08: Prepare for FLINT training (tlog conversion) // ======================================================================== println!("\n[08] FLINT training preparation..."); println!(" Training entries: {}", pruned.len()); println!(" Format: ConsolidatedExample (JSONL) → tlog:* LMDB keys"); println!(" Next step: Run jsonl_to_tlog tool to convert + inject into LMDB"); println!(" Then: spf_transformer_train() will read native tlog entries"); // ======================================================================== // Summary // ======================================================================== let mut by_label: HashMap = HashMap::new(); for e in &pruned { *by_label.entry(e.label).or_default() += 1; } let by_source: HashMap<&str, usize> = pruned.iter() .fold(HashMap::new(), |mut m, e| { *m.entry(e.source_type.as_str()).or_default() += 1; m }); let by_category: HashMap<&str, usize> = pruned.iter() .fold(HashMap::new(), |mut m, e| { *m.entry(e.category.as_str()).or_default() += 1; m }); println!("\n[=] BLOCK 0 — MEMORY CONSOLIDATION COMPLETE"); println!(" Consolidated examples: {}", pruned.len()); println!(" Archived (TTL expired): {}", expired_memories.len()); println!(" Memory catalog entries: {}", catalog.len()); println!("\n By source:"); for (k, v) in &by_source { println!(" {}: {}", k, v); } println!("\n By category:"); for (k, v) in &by_category { println!(" {}: {}", k, v); } println!("\n By label (20-level scale):"); for &lbl in &[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] { if let Some(c) = by_label.get(&lbl) { println!(" {:>3}: {}", lbl, c); } } // Weight amplification summary let total_occurrences: u64 = pruned.iter().map(|e| e.occurrence_count).sum(); let avg_weight: f64 = pruned.iter().map(|e| e.weight as f64).sum::() / pruned.len() as f64; let max_weight = pruned.iter().max_by(|a, b| a.weight.partial_cmp(&b.weight).unwrap()).map(|e| e.weight).unwrap(); let max_dups = pruned.iter().max_by(|a, b| a.occurrence_count.cmp(&b.occurrence_count)).map(|e| e.occurrence_count).unwrap(); println!("\n Weight amplification from duplicates:"); println!(" Total occurrences consolidated: {}", total_occurrences); println!(" Avg weight per example: {:.2}", avg_weight); println!(" Max weight (single entry): {:.2}", max_weight); println!(" Max occurrence count: {}", max_dups); println!(" RULE: NO ZERO. Weight zero floors to +1. If +1 degrades, flips to -1 (skip zero)."); Ok(()) }