File size: 26,304 Bytes
6e5855e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
// 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<String>,
    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<String>,
    #[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<String>,
    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<u64, Vec<&MemoryEntry>> = 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<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."
    ))
}

// ============================================================================
// 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<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"))?;

    // ========================================================================
    // DUMP
    // ========================================================================
    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());

    // ========================================================================
    // 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<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());

    // ========================================================================
    // 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<ConsolidatedExample> = 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 &regular {
        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<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();

    // ========================================================================
    // 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<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);
        }
    }

    // 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::<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(())
}