SPFsmartGATE / src /bin /jsonl_to_tlog.rs
JosephStoneCellAI's picture
Upload 3 files
6e5855e verified
// jsonl_to_tlog — Convert pruned_memories.jsonl to tlog LMDB format
// Copyright 2026 Joseph Stone — All Rights Reserved
//
// Reads ConsolidatedExample JSONL, converts to TrainingSignal format,
// and writes to LMDB tlog:* keys for spf_transformer_train().
//
// Usage: cargo run --bin jsonl_to_tlog -- <input.jsonl>
//
// Output: LIVE/LMDB5/LMDB5.DB state DB (tlog:* keys)
use anyhow::Result;
use heed::types::*;
use heed::{Database, EnvOpenOptions};
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
// ============================================================================
// TrainingSignal — matches gate_training.rs EXACTLY
// ============================================================================
#[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, Deserialize, 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,
}
// ============================================================================
// Conversion: ConsolidatedExample → TrainingSignal
// ============================================================================
impl ConsolidatedExample {
/// Convert to TrainingSignal for FLINT training
fn to_training_signal(&self) -> TrainingSignal {
// Map 20-level label to TrainingSignal fields
let (allowed, user_override, false_positive) = match self.label {
// Negative labels = blocked
-10..=-1 => (false, false, self.label <= -3),
// Positive labels = allowed
1..=10 => (true, self.label >= 9, false),
// Should never happen (NO ZERO)
_ => (true, false, false),
};
// Map label to evil_score (higher negative = higher evil)
let evil_score = if self.label < 0 {
(-self.label as f32) * 0.07 // -10 → 0.7, -3 → 0.21
} else {
0.0
};
TrainingSignal {
tool: self.tool.clone(),
source: format!("memory:{}", self.category),
allowed,
status: if allowed { "allowed" } else { "blocked" }.to_string(),
duration_ms: (self.signal_strength * 10.0) as u64, // scale signal to duration
timestamp: format!("{}", SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis()),
user_override,
false_positive,
recent_call_count: self.occurrence_count.min(u32::MAX as u64) as u32,
preceding_tools: vec![self.category.clone()],
evil_score,
}
}
}
const MAX_DB_SIZE: usize = 1024 * 1024 * 1024; // 1GB
fn main() -> Result<()> {
// Find input file
let input_path = std::env::args().nth(1)
.unwrap_or_else(|| "LIVE/TMP/stoneshell-brain/training_data/raw/pruned_memories.jsonl".to_string());
let lmdb_path = "/data/data/com.termux/files/home/SPFsmartGATE/LIVE/LMDB5/LMDB5.DB";
println!("[*] jsonl_to_tlog — JSONL to tlog LMDB converter");
println!("[*] Input: {}", input_path);
println!("[*] LMDB: {}", lmdb_path);
// Open LMDB
let env = unsafe {
EnvOpenOptions::new()
.map_size(MAX_DB_SIZE)
.max_dbs(8)
.open(Path::new(lmdb_path))?
};
let state_db: Database<Str, SerdeBincode<String>> = env.open_database(&env.read_txn()?, Some("state"))?
.ok_or_else(|| anyhow::anyhow!("state sub-DB not found"))?;
// Read JSONL
let file = File::open(&input_path)?;
let reader = BufReader::new(file);
let mut count = 0;
let mut error_count = 0;
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64;
for line in reader.lines() {
let line = line?;
if line.trim().is_empty() { continue; }
match serde_json::from_str::<ConsolidatedExample>(&line) {
Ok(example) => {
let signal = example.to_training_signal();
let json = serde_json::to_string(&signal)?;
// Write to LMDB state DB as tlog: timestamp
let tlog_key = format!("tlog:{}", now + count);
let mut wtxn = env.write_txn()?;
state_db.put(&mut wtxn, &tlog_key, &json)?;
wtxn.commit()?;
count += 1;
if count % 500 == 0 {
println!(" Converted: {} entries", count);
}
}
Err(e) => {
error_count += 1;
if error_count <= 5 {
println!(" Error parsing line {}: {}", count + error_count, e);
}
}
}
}
println!("\n[=] Conversion complete");
println!(" Entries converted: {}", count);
println!(" Errors: {}", error_count);
println!(" tlog keys written: tlog:* in {}", lmdb_path);
println!("\n Next: Run 'spf_transformer_train()' to train FLINT on these signals");
Ok(())
}