| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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}; |
|
|
| |
| |
| |
|
|
| #[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<String>, |
| pub source: String, |
| pub created_at: u64, |
| pub last_accessed: u64, |
| pub access_count: u64, |
| pub relevance: f64, |
| pub expires_at: u64, |
| } |
|
|
| |
| #[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<String>, |
| #[serde(default)] |
| pub evil_score: f32, |
| } |
|
|
| |
| |
| |
|
|
| #[derive(Debug, Clone, Serialize)] |
| pub struct ConsolidatedExample { |
| |
| pub label: i32, |
| |
| pub weight: f32, |
| |
| pub tool: String, |
| |
| pub context: String, |
| |
| pub outcome: String, |
| |
| pub source_type: String, |
| |
| pub category: String, |
| |
| pub occurrence_count: u64, |
| |
| pub signal_strength: f64, |
| } |
|
|
| |
| |
| |
|
|
| #[derive(Debug, Clone, Serialize)] |
| pub struct MemoryCatalog { |
| pub id: String, |
| pub content: String, |
| pub category: String, |
| pub tags: Vec<String>, |
| pub source_type: String, |
| pub memory_type: String, |
| pub relevance: f64, |
| } |
|
|
| |
| |
| |
|
|
| const MAX_DB_SIZE: usize = 1024 * 1024 * 1024; |
| const OUTPUT_DIR: &str = "/data/data/com.termux/files/home/SPFsmartGATE/LIVE/TMP/stoneshell-brain/training_data"; |
|
|
| |
| |
| |
|
|
| |
| |
| 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; } |
| 1 |
| } |
|
|
| |
| 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 |
| } |
|
|
| |
| |
| fn label_for_memory(mem: &MemoryEntry) -> i32 { |
| match mem.memory_type { |
| MemoryType::Pinned => 10, |
| MemoryType::Instruction => 9, |
| MemoryType::Fact => 5, |
| MemoryType::Preference => 4, |
| MemoryType::Context => 3, |
| MemoryType::Working => 0, |
| } |
| } |
|
|
| |
| #[allow(dead_code)] |
| fn degrade_positive(old_label: i32, outcome_failed: bool) -> i32 { |
| if old_label > 0 && outcome_failed { |
| return -1; |
| } |
| old_label |
| } |
|
|
| |
| |
| fn clamp_weight(w: f32) -> f32 { |
| w.max(1.0).min(8.0) |
| } |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| 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 |
| } |
|
|
| |
| fn content_hash(content: &str) -> u64 { |
| let mut h = std::collections::hash_map::DefaultHasher::new(); |
| h.write(content.as_bytes()); |
| h.finish() |
| } |
|
|
| |
| |
| fn categorize_memory(mem: &MemoryEntry) -> &'static str { |
| |
| if matches!(mem.memory_type, MemoryType::Pinned) { |
| return "reference"; |
| } |
| |
| if matches!(mem.memory_type, MemoryType::Preference | MemoryType::Instruction) { |
| return "user_intent"; |
| } |
| |
| if matches!(mem.memory_type, MemoryType::Fact) { |
| return "reference"; |
| } |
| |
| if mem.tags.iter().any(|t| t.contains("gate") || t.contains("gateway") || t.contains("spf")) { |
| return "gate_context"; |
| } |
| |
| if mem.tags.iter().any(|t| t.starts_with("tool:") || t.contains("code") || t.contains("function")) { |
| return "code_structure"; |
| } |
| |
| "context" |
| } |
|
|
| |
| |
| fn consolidate_duplicates(mems: &[MemoryEntry]) -> Vec<(&MemoryEntry, u64, f64)> { |
| |
| let mut groups: BTreeMap<u64, Vec<&MemoryEntry>> = BTreeMap::new(); |
| for mem in mems { |
| let h = content_hash(&mem.content); |
| groups.entry(h).or_default().push(mem); |
| } |
|
|
| |
| groups.into_iter().map(|(_hash, members)| { |
| let count = members.len() as u64; |
| |
| let best = members.iter().max_by(|a, b| { |
| score_memory(a).partial_cmp(&score_memory(b)).unwrap_or(std::cmp::Ordering::Equal) |
| }).unwrap(); |
|
|
| |
| |
| 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<String> { |
| 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." |
| )) |
| } |
|
|
| |
| |
| |
|
|
| 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))? |
| }; |
|
|
| |
| let rtxn = env.read_txn()?; |
| let memory_db: Database<Str, SerdeBincode<MemoryEntry>> = |
| env.open_database(&rtxn, Some("memory"))? |
| .ok_or_else(|| anyhow::anyhow!("memory sub-DB not found"))?; |
| let state_db: Database<Str, Str> = |
| env.open_database(&rtxn, Some("state"))? |
| .ok_or_else(|| anyhow::anyhow!("state sub-DB not found"))?; |
|
|
| |
| |
| |
| println!("[*] Dumping memories..."); |
| let mut all_memories: Vec<MemoryEntry> = 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<TrainingSignal> = 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::<TrainingSignal>(value) { |
| all_tlogs.push(signal); |
| } |
| } |
| } |
| println!(" Found {} tlog entries", all_tlogs.len()); |
|
|
| |
| |
| |
| 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<MemoryEntry> = 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()); |
|
|
| |
| |
| |
| println!("\n[02] Consolidate duplicates (multiples → signal weight)..."); |
| let consolidated = consolidate_duplicates(&all_memories); |
|
|
| |
| 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()); |
|
|
| |
| |
| |
| println!("\n[03] Building consolidated examples..."); |
| let mut pruned: Vec<ConsolidatedExample> = Vec::new(); |
|
|
| |
| 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), |
| }); |
| } |
|
|
| |
| for (mem, count, consolidated_score) in &edge { |
| 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: 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, |
| }); |
| } |
|
|
| |
| 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, |
| }); |
| } |
|
|
| |
| 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, |
| }); |
| } |
|
|
| |
| pruned.sort_by(|a, b| b.signal_strength.partial_cmp(&a.signal_strength) |
| .unwrap_or(std::cmp::Ordering::Equal)); |
|
|
| |
| |
| |
| println!("\n[04] Building memory catalog for brain re-index..."); |
| let catalog: Vec<MemoryCatalog> = 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(); |
|
|
| |
| |
| |
| println!("\n[05] Writing output files..."); |
| let raw_dir = format!("{}/raw", OUTPUT_DIR); |
| fs::create_dir_all(&raw_dir)?; |
|
|
| |
| 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); |
|
|
| |
| 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); |
|
|
| |
| 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); |
|
|
| |
| |
| |
| 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 { |
| |
| 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"); |
|
|
| |
| |
| |
| 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"); |
|
|
| |
| |
| |
| 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"); |
|
|
| |
| |
| |
| let mut by_label: HashMap<i32, usize> = 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); |
| } |
| } |
|
|
| |
| 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::<f64>() / 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(()) |
| } |
|
|