File size: 33,007 Bytes
1269259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
// SPF Smart Gateway - Configuration LMDB
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// LMDB-backed configuration storage. Replaces config.json with persistent,
// transactional storage. Supports hot-reload without restart.
//
// Database: SPF_CONFIG
// Storage: ~/SPFsmartGATE/LIVE/CONFIG/CONFIG.DB/

use anyhow::{anyhow, Result};
use heed::types::*;
use heed::{Database, Env, EnvOpenOptions};
use serde::{Deserialize, Serialize};
use std::path::Path;

// Import config types from canonical source (config.rs) - NO DUPLICATES
use crate::config::{
    EnforceMode, TierThreshold, TierConfig, FormulaConfig,
    ToolWeight, ComplexityWeights, SpfConfig,
    CommandPerm, // BLOCK-01: Per-command R/W/X permission struct
};

const MAX_DB_SIZE: usize = 10 * 1024 * 1024; // 10MB - config is small

/// LMDB-backed SPF configuration storage
pub struct SpfConfigDb {
    env: Env,
    /// Main config store: namespace:key → JSON value
    config: Database<Str, Str>,
    /// Path rules: "allowed:path" or "blocked:path" → bool
    paths: Database<Str, SerdeBincode<bool>>,
    /// Dangerous patterns: pattern → severity (1-10)
    patterns: Database<Str, SerdeBincode<u8>>,
    // ================================================================
    // COMMAND WHITELISTS — Default-Deny Bash Security (BLOCK-02)
    // Key format: "user_fs:{cmd}" or "sandbox:{cmd}" → CommandPerm
    // ================================================================
    /// Command whitelists: "user_fs:cmd" or "sandbox:cmd" → CommandPerm
    commands: Database<Str, SerdeBincode<CommandPerm>>,
}

// ============================================================================
// IMPLEMENTATION
// ============================================================================

impl SpfConfigDb {
    /// Open or create config LMDB at given path
    pub fn open(path: &Path) -> Result<Self> {
        std::fs::create_dir_all(path)?;

        let env = unsafe {
            EnvOpenOptions::new()
                .map_size(MAX_DB_SIZE)
                .max_dbs(9) // Was 8 — added commands DB (BLOCK-02)
                .open(path)?
        };

        let mut wtxn = env.write_txn()?;
        let config = env.create_database(&mut wtxn, Some("config"))?;
        let paths = env.create_database(&mut wtxn, Some("paths"))?;
        let patterns = env.create_database(&mut wtxn, Some("patterns"))?;
        let commands = env.create_database(&mut wtxn, Some("commands"))?; // BLOCK-02
        wtxn.commit()?;

        log::info!("SPF Config LMDB opened at {:?}", path);
        Ok(Self { env, config, paths, patterns, commands })
    }

    // ========================================================================
    // CORE CONFIG OPERATIONS
    // ========================================================================

    /// Get a config value by namespace and key
    pub fn get(&self, namespace: &str, key: &str) -> Result<Option<String>> {
        let full_key = format!("{}:{}", namespace, key);
        let rtxn = self.env.read_txn()?;
        Ok(self.config.get(&rtxn, &full_key)?.map(|s| s.to_string()))
    }

    /// Set a config value
    pub fn set(&self, namespace: &str, key: &str, value: &str) -> Result<()> {
        let full_key = format!("{}:{}", namespace, key);
        let mut wtxn = self.env.write_txn()?;
        self.config.put(&mut wtxn, &full_key, value)?;
        wtxn.commit()?;
        Ok(())
    }

    /// Get typed config value (deserialize from JSON)
    pub fn get_typed<T: for<'de> Deserialize<'de>>(&self, namespace: &str, key: &str) -> Result<Option<T>> {
        match self.get(namespace, key)? {
            Some(json) => Ok(Some(serde_json::from_str(&json)?)),
            None => Ok(None),
        }
    }

    /// Set typed config value (serialize to JSON)
    pub fn set_typed<T: Serialize>(&self, namespace: &str, key: &str, value: &T) -> Result<()> {
        let json = serde_json::to_string(value)?;
        self.set(namespace, key, &json)
    }

    // ========================================================================
    // PATH RULES
    // ========================================================================

    /// Add an allowed path
    pub fn allow_path(&self, path: &str) -> Result<()> {
        let key = format!("allowed:{}", path);
        let mut wtxn = self.env.write_txn()?;
        self.paths.put(&mut wtxn, &key, &true)?;
        wtxn.commit()?;
        Ok(())
    }

    /// Add a blocked path
    pub fn block_path(&self, path: &str) -> Result<()> {
        let key = format!("blocked:{}", path);
        let mut wtxn = self.env.write_txn()?;
        self.paths.put(&mut wtxn, &key, &true)?;
        wtxn.commit()?;
        Ok(())
    }

    /// Remove a path rule
    pub fn remove_path_rule(&self, rule_type: &str, path: &str) -> Result<bool> {
        let key = format!("{}:{}", rule_type, path);
        let mut wtxn = self.env.write_txn()?;
        let deleted = self.paths.delete(&mut wtxn, &key)?;
        wtxn.commit()?;
        Ok(deleted)
    }

    /// Check if path is allowed (with canonicalization to prevent traversal bypass)
    pub fn is_path_allowed(&self, path: &str) -> Result<bool> {
        let canonical = match std::fs::canonicalize(path) {
            Ok(p) => p.to_string_lossy().to_string(),
            Err(_) => {
                if path.contains("..") {
                    return Ok(false); // Traversal in unresolvable path = never allowed
                }
                path.to_string()
            }
        };
        let rtxn = self.env.read_txn()?;
        let iter = self.paths.iter(&rtxn)?;

        for result in iter {
            let (key, _) = result?;
            if key.starts_with("allowed:") {
                let allowed_path = &key[8..]; // Skip "allowed:"
                if canonical.starts_with(allowed_path) {
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }

    /// Check if path is blocked (matches any blocked prefix)
    pub fn is_path_blocked(&self, path: &str) -> Result<bool> {
        let canonical = match std::fs::canonicalize(path) {
            Ok(p) => p.to_string_lossy().to_string(),
            Err(_) => {
                if path.contains("..") {
                    return Ok(true); // Traversal in unresolvable path = always blocked
                }
                path.to_string()
            }
        };

        let rtxn = self.env.read_txn()?;
        let iter = self.paths.iter(&rtxn)?;

        for result in iter {
            let (key, _) = result?;
            if key.starts_with("blocked:") {
                let blocked_path = &key[8..]; // Skip "blocked:"
                if canonical.starts_with(blocked_path) {
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }

    /// List all path rules
    pub fn list_path_rules(&self) -> Result<Vec<(String, String)>> {
        let rtxn = self.env.read_txn()?;
        let iter = self.paths.iter(&rtxn)?;

        let mut rules = Vec::new();
        for result in iter {
            let (key, _) = result?;
            if let Some((rule_type, path)) = key.split_once(':') {
                rules.push((rule_type.to_string(), path.to_string()));
            }
        }
        Ok(rules)
    }

    // ========================================================================
    // DANGEROUS PATTERNS
    // ========================================================================

    /// Add a dangerous pattern with severity (1-10)
    pub fn add_dangerous_pattern(&self, pattern: &str, severity: u8) -> Result<()> {
        let mut wtxn = self.env.write_txn()?;
        self.patterns.put(&mut wtxn, pattern, &severity.min(10))?;
        wtxn.commit()?;
        Ok(())
    }

    /// Check if command matches any dangerous pattern, returns severity
    pub fn check_dangerous(&self, command: &str) -> Result<Option<u8>> {
        let rtxn = self.env.read_txn()?;
        let iter = self.patterns.iter(&rtxn)?;

        let mut max_severity: Option<u8> = None;
        for result in iter {
            let (pattern, severity) = result?;
            if command.contains(pattern) {
                max_severity = Some(max_severity.map_or(severity, |s| s.max(severity)));
            }
        }
        Ok(max_severity)
    }

    /// List all dangerous patterns
    pub fn list_dangerous_patterns(&self) -> Result<Vec<(String, u8)>> {
        let rtxn = self.env.read_txn()?;
        let iter = self.patterns.iter(&rtxn)?;

        let mut patterns = Vec::new();
        for result in iter {
            let (pattern, severity) = result?;
            patterns.push((pattern.to_string(), severity));
        }
        Ok(patterns)
    }

    // ========================================================================
    // COMMAND WHITELISTS — Default-Deny Bash Security (BLOCK-02)
    // Key format: "{context}:{cmd}" where context is "user_fs" or "sandbox"
    // Follows same put/get/iter pattern as path rules above.
    // ========================================================================

    /// Add a command to a whitelist context ("user_fs" or "sandbox")
    pub fn add_command(&self, context: &str, cmd: &str, perm: CommandPerm) -> Result<()> {
        let key = format!("{}:{}", context, cmd);
        let mut wtxn = self.env.write_txn()?;
        self.commands.put(&mut wtxn, &key, &perm)?;
        wtxn.commit()?;
        Ok(())
    }

    /// Remove a command from a whitelist context
    pub fn remove_command(&self, context: &str, cmd: &str) -> Result<bool> {
        let key = format!("{}:{}", context, cmd);
        let mut wtxn = self.env.write_txn()?;
        let deleted = self.commands.delete(&mut wtxn, &key)?;
        wtxn.commit()?;
        Ok(deleted)
    }

    /// List all commands in a whitelist context ("user_fs" or "sandbox")
    pub fn list_commands(&self, context: &str) -> Result<Vec<(String, CommandPerm)>> {
        let prefix = format!("{}:", context);
        let rtxn = self.env.read_txn()?;
        let iter = self.commands.iter(&rtxn)?;

        let mut cmds = Vec::new();
        for result in iter {
            let (key, perm) = result?;
            if key.starts_with(&prefix) {
                let cmd_name = &key[prefix.len()..];
                cmds.push((cmd_name.to_string(), perm));
            }
        }
        Ok(cmds)
    }

    /// Add a user filesystem path (stored in config DB as JSON array)
    pub fn add_user_fs_path(&self, path: &str) -> Result<()> {
        let mut paths = self.list_user_fs_paths()?;
        if !paths.contains(&path.to_string()) {
            paths.push(path.to_string());
            self.set_typed("spf", "user_fs_paths", &paths)?;
        }
        Ok(())
    }

    /// Remove a user filesystem path
    pub fn remove_user_fs_path(&self, path: &str) -> Result<bool> {
        let mut paths = self.list_user_fs_paths()?;
        let before = paths.len();
        paths.retain(|p| p != path);
        if paths.len() < before {
            self.set_typed("spf", "user_fs_paths", &paths)?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// List user filesystem paths
    pub fn list_user_fs_paths(&self) -> Result<Vec<String>> {
        Ok(self.get_typed::<Vec<String>>("spf", "user_fs_paths")?
            .unwrap_or_default())
    }

    // ========================================================================
    // TIER CONFIG
    // ========================================================================

    /// Get tier config
    pub fn get_tiers(&self) -> Result<TierConfig> {
        self.get_typed::<TierConfig>("spf", "tiers")?
            .ok_or_else(|| anyhow!("Tier config not found"))
    }

    /// Set tier config
    pub fn set_tiers(&self, tiers: &TierConfig) -> Result<()> {
        self.set_typed("spf", "tiers", tiers)
    }

    /// Get tier for complexity value
    /// CRITICAL requires approval. Lower tiers protected by Build Anchor + path blocking + content inspection.
    pub fn get_tier_for_c(&self, c: u64) -> Result<(&'static str, u8, u8, bool)> {
        let tiers = self.get_tiers()?;

        if c < tiers.simple.max_c {
            Ok(("SIMPLE", tiers.simple.analyze_percent, tiers.simple.build_percent, tiers.simple.requires_approval))
        } else if c < tiers.light.max_c {
            Ok(("LIGHT", tiers.light.analyze_percent, tiers.light.build_percent, tiers.light.requires_approval))
        } else if c < tiers.medium.max_c {
            Ok(("MEDIUM", tiers.medium.analyze_percent, tiers.medium.build_percent, tiers.medium.requires_approval))
        } else {
            Ok(("CRITICAL", tiers.critical.analyze_percent, tiers.critical.build_percent, tiers.critical.requires_approval))
        }
    }

    // ========================================================================
    // FORMULA CONFIG
    // ========================================================================

    /// Get formula config
    pub fn get_formula(&self) -> Result<FormulaConfig> {
        self.get_typed::<FormulaConfig>("spf", "formula")?
            .ok_or_else(|| anyhow!("Formula config not found"))
    }

    /// Set formula config
    pub fn set_formula(&self, formula: &FormulaConfig) -> Result<()> {
        self.set_typed("spf", "formula", formula)
    }

    // ========================================================================
    // COMPLEXITY WEIGHTS
    // ========================================================================

    /// Get complexity weights
    pub fn get_weights(&self) -> Result<ComplexityWeights> {
        self.get_typed::<ComplexityWeights>("spf", "weights")?
            .ok_or_else(|| anyhow!("Complexity weights not found"))
    }

    /// Set complexity weights
    pub fn set_weights(&self, weights: &ComplexityWeights) -> Result<()> {
        self.set_typed("spf", "weights", weights)
    }

    /// Get weight for a specific tool
    pub fn get_tool_weight(&self, tool: &str) -> Result<ToolWeight> {
        let weights = self.get_weights()?;
        Ok(match tool.to_lowercase().as_str() {
            "edit" => weights.edit,
            "write" => weights.write,
            "bash_dangerous" => weights.bash_dangerous,
            "bash_git" => weights.bash_git,
            "bash_piped" => weights.bash_piped,
            "bash_simple" | "bash" => weights.bash_simple,
            "read" => weights.read,
            "search" | "glob" | "grep" => weights.search,
            _ => weights.unknown,
        })
    }

    // ========================================================================
    // ENFORCE MODE
    // ========================================================================

    /// Get enforce mode
    pub fn get_enforce_mode(&self) -> Result<EnforceMode> {
        self.get_typed::<EnforceMode>("spf", "enforce_mode")?
            .ok_or_else(|| anyhow!("Enforce mode not found"))
    }

    /// Set enforce mode
    pub fn set_enforce_mode(&self, mode: &EnforceMode) -> Result<()> {
        self.set_typed("spf", "enforce_mode", mode)
    }

    // ========================================================================
    // MIGRATION
    // ========================================================================

    /// Initialize with defaults (call once on first run)
    pub fn init_defaults(&self) -> Result<()> {
        // Only init if not already initialized
        if self.get("spf", "version")?.is_some() {
            return Ok(());
        }

        self.set("spf", "version", "1.0.0")?;
        self.set_enforce_mode(&EnforceMode::Max)?;
        self.set("spf", "require_read_before_edit", "true")?;
        self.set("spf", "max_write_size", "100000")?;

        // Default tiers — CRITICAL requires approval, lower tiers protected by other layers
        self.set_tiers(&TierConfig {
            simple: TierThreshold { max_c: 500, analyze_percent: 40, build_percent: 60, requires_approval: false },
            light: TierThreshold { max_c: 2000, analyze_percent: 60, build_percent: 40, requires_approval: false },
            medium: TierThreshold { max_c: 10000, analyze_percent: 75, build_percent: 25, requires_approval: false },
            critical: TierThreshold { max_c: u64::MAX, analyze_percent: 95, build_percent: 5, requires_approval: true },
        })?;

        // Default formula
        self.set_formula(&FormulaConfig {
            w_eff: 40000.0,
            e: std::f64::consts::E,
            basic_power: 1,
            deps_power: 7,
            complex_power: 10,
            files_multiplier: 10,
        })?;

        // Default weights
        self.set_weights(&ComplexityWeights {
            edit: ToolWeight { basic: 10, dependencies: 2, complex: 1, files: 1 },
            write: ToolWeight { basic: 20, dependencies: 2, complex: 1, files: 1 },
            bash_dangerous: ToolWeight { basic: 50, dependencies: 5, complex: 2, files: 1 },
            bash_git: ToolWeight { basic: 30, dependencies: 3, complex: 1, files: 1 },
            bash_piped: ToolWeight { basic: 20, dependencies: 3, complex: 1, files: 1 },
            bash_simple: ToolWeight { basic: 10, dependencies: 1, complex: 0, files: 1 },
            read: ToolWeight { basic: 5, dependencies: 1, complex: 0, files: 1 },
            search: ToolWeight { basic: 8, dependencies: 2, complex: 0, files: 1 },
            unknown: ToolWeight { basic: 20, dependencies: 3, complex: 1, files: 1 },
        })?;

        // Default allowed paths — resolved dynamically from paths module
        let home = crate::paths::actual_home().to_string_lossy();
        self.allow_path(&format!("{}/", home))?;

        // Default blocked paths — resolved dynamically from paths module
        let root = crate::paths::spf_root().to_string_lossy();
        self.block_path("/tmp")?;
        self.block_path("/etc")?;
        self.block_path("/usr")?;
        self.block_path("/system")?;
        self.block_path(&crate::paths::system_pkg_path())?;
        self.block_path(&format!("{}/src/", root))?;
        self.block_path(&format!("{}/LIVE/SPF_FS/blobs/", root))?;
        self.block_path(&format!("{}/Cargo.toml", root))?;
        self.block_path(&format!("{}/Cargo.lock", root))?;
        self.block_path(&format!("{}/.claude/", home))?;
        // System config and state — ZERO AI write access
        self.block_path(&format!("{}/LIVE/CONFIG.DB", root))?;
        self.block_path(&format!("{}/LIVE/LMDB5/", root))?;
        self.block_path(&format!("{}/LIVE/state/", root))?;
        self.block_path(&format!("{}/LIVE/storage/", root))?;
        self.block_path(&format!("{}/hooks/", root))?;
        self.block_path(&format!("{}/scripts/", root))?;

        // Default dangerous patterns
        self.add_dangerous_pattern("rm -rf /", 10)?;
        self.add_dangerous_pattern("rm -rf ~", 10)?;
        self.add_dangerous_pattern("dd if=", 9)?;
        self.add_dangerous_pattern("> /dev/", 9)?;
        self.add_dangerous_pattern("chmod 777", 7)?;
        self.add_dangerous_pattern("curl | sh", 8)?;
        self.add_dangerous_pattern("wget | sh", 8)?;
        self.add_dangerous_pattern("curl|sh", 8)?;
        self.add_dangerous_pattern("wget|sh", 8)?;

        log::info!("SPF Config LMDB initialized with defaults");
        Ok(())
    }

    /// Sync tier approval policy on every boot.
    /// Source of truth is THIS code — LMDB stores runtime state, code defines policy.
    /// Change the values here → next boot picks them up. No version tracking needed.
    pub fn sync_tier_approval(&self) -> Result<()> {
        let mut tiers = self.get_tiers()?;
        let mut changed = false;

        // === APPROVAL POLICY (edit here to change) ===
        let policy: [(&str, bool); 4] = [
            ("SIMPLE",   true),
            ("LIGHT",    true),
            ("MEDIUM",   true),
            ("CRITICAL", true),
        ];

        let tier_refs = [
            &mut tiers.simple,
            &mut tiers.light,
            &mut tiers.medium,
            &mut tiers.critical,
        ];

        for (i, (name, required)) in policy.iter().enumerate() {
            if tier_refs[i].requires_approval != *required {
                log::info!("SPF sync: {} requires_approval {} → {}", name, tier_refs[i].requires_approval, required);
                tier_refs[i].requires_approval = *required;
                changed = true;
            }
        }

        if changed {
            self.set_tiers(&tiers)?;
            log::info!("SPF tier approval policy synced");
        }

        // Keep version current
        self.set("spf", "version", "3.0.0")?;

        Ok(())
    }

    // ========================================================================
    // BLOCKED PATHS SYNC — Config Governance Protection
    // Runs every boot. Ensures ALL config/governance files are write-protected
    // even if LMDB is reset or paths were missed in init_defaults().
    // block_path() is idempotent — safe to call every boot.
    // ========================================================================

    /// Sync critical blocked paths on every boot.
    /// Source of truth is THIS code — ensures config governance files
    /// are ALWAYS write-protected regardless of LMDB state.
    pub fn sync_blocked_paths(&self) -> Result<()> {
        let root = crate::paths::spf_root().to_string_lossy().to_string();
        let home = crate::paths::actual_home().to_string_lossy().to_string();

        let critical_paths = [
            // === CONFIG GOVERNANCE — ZERO AI write access ===
            // CLAUDE.md files — behavioral rules for AI
            format!("{}/CLAUDE.md", root),
            format!("{}/LIVE/CLAUDE.md", root),
            format!("{}/LIVE/PROJECTS/PROJECTS/CLAUDE.md", root),
            // Claude config files
            format!("{}/.claude.json", root),
            format!("{}/.claude.json", home),
            format!("{}/.claude/", home),
            // HARDCODE-RULES — project governance
            format!("{}/LIVE/PROJECTS/PROJECTS/HARDCODE-RULES.md", root),
            // CONFIG folder — whitelist-config.json and all config jsons
            format!("{}/LIVE/CONFIG/", root),
            // === SOURCE CODE — VIEW ONLY ===
            format!("{}/src/", root),
            format!("{}/Cargo.toml", root),
            format!("{}/Cargo.lock", root),
            // === SYSTEM INFRASTRUCTURE ===
            format!("{}/hooks/", root),
            format!("{}/scripts/", root),
            format!("{}/LIVE/CONFIG.DB", root),
            format!("{}/LIVE/LMDB5/", root),
            format!("{}/LIVE/SPF_FS/blobs/", root),
            format!("{}/LIVE/state/", root),
            format!("{}/LIVE/storage/", root),
            // === SYSTEM PATHS ===
            "/tmp".to_string(),
            "/etc".to_string(),
            "/usr".to_string(),
            "/system".to_string(),
            crate::paths::system_pkg_path(),
        ];

        for path in &critical_paths {
            self.block_path(path)?;
        }

        log::info!("SPF blocked paths synced: {} critical paths enforced", critical_paths.len());
        Ok(())
    }

    // ========================================================================
    // COMMAND WHITELIST MIGRATION — Default-Deny Bash Security (BLOCK-02)
    // Called once on boot from load_full_config(). Seeds default whitelists
    // for existing installs by inverting the blacklist.
    // Fresh installs: commands DB stays empty = everything blocked.
    // ========================================================================

    /// Sync command whitelists on boot.
    /// - If commands DB empty AND dangerous_commands exist → migrate (invert blacklist)
    /// - If commands DB empty AND no dangerous_commands → fresh install, stay empty
    /// - If commands DB populated → do nothing (user has configured)
    pub fn sync_command_whitelist(&self) -> Result<()> {
        // Check if commands DB already has entries
        let rtxn = self.env.read_txn()?;
        let count = self.commands.stat(&rtxn)?.entries;
        drop(rtxn);

        if count > 0 {
            // Already configured — do nothing
            return Ok(());
        }

        // Check if dangerous patterns exist (indicates existing install, not fresh)
        let patterns = self.list_dangerous_patterns()?;
        if patterns.is_empty() {
            // Fresh install — stay empty (default-deny)
            log::info!("SPF whitelist: fresh install, commands DB empty (default-deny)");
            return Ok(());
        }

        // ================================================================
        // MIGRATION: Existing install detected — seed default whitelists
        // by inverting the blacklist. Conservative: read-only for user_fs,
        // appropriate R/W/X for sandbox build tools.
        // ================================================================

        log::info!("SPF whitelist: migrating from blacklist to whitelist...");

        // USER_FS: Read-only commands that are CURRENTLY ALLOWED on user FS.
        // Mirrors validate.rs enforcement exactly:
        //   EXCLUDED (in user_fs_blocked): ls, cat, find, head, tail, stat, file,
        //     du, tree, strings, xxd, hexdump, readlink, realpath, ln
        //   EXCLUDED (bypass vectors): wc, printf
        //   EXCLUDED (write-capable): sed, awk, rm, cp, mv, mkdir, touch, chmod, dd, tee
        //   EXCLUDED (interpreters): python, perl, ruby, node, curl, wget
        // What remains: safe read-only utilities that are currently allowed.
        let user_fs_read: &[&str] = &[
            "echo", "grep", "git", "date", "uname", "whoami", "pwd",
            "env", "which", "sort", "uniq", "tr", "cut", "jq",
            "diff", "sha256sum", "md5sum", "basename", "dirname", "type",
        ];
        for cmd in user_fs_read {
            self.add_command("user_fs", cmd, CommandPerm::read_only())?;
        }

        // SANDBOX: Build tools + common commands with appropriate permissions
        let sandbox_full: &[(&str, CommandPerm)] = &[
            // Build tools — full R/W/X
            ("cargo",  CommandPerm::full()),
            ("rustc",  CommandPerm::full()),
            ("gcc",    CommandPerm::full()),
            ("make",   CommandPerm::full()),
            ("cmake",  CommandPerm::full()),
            ("npm",    CommandPerm::full()),
            ("node",   CommandPerm::full()),
            ("python", CommandPerm::full()),
            ("python3", CommandPerm::full()),
            ("pip",    CommandPerm::full()),
            // Version control — read + write (no execute)
            ("git",    CommandPerm::read_write()),
            // Archive tools — read + write
            ("tar",    CommandPerm::read_write()),
            ("gzip",   CommandPerm::read_write()),
            ("unzip",  CommandPerm::read_write()),
            // File operations — read + write
            ("cp",     CommandPerm::read_write()),
            ("mv",     CommandPerm::read_write()),
            ("rm",     CommandPerm::read_write()),
            ("mkdir",  CommandPerm::read_write()),
            ("touch",  CommandPerm::read_write()),
            ("chmod",  CommandPerm::read_write()),
            ("ln",     CommandPerm::read_write()),
            ("tee",    CommandPerm::read_write()),
            ("sed",    CommandPerm::read_write()),
            ("sort",   CommandPerm::read_write()),
            // Search — read + execute (find -exec)
            ("find",   CommandPerm { read: true, write: false, execute: true }),
            ("awk",    CommandPerm { read: true, write: false, execute: true }),
            // Read-only tools
            ("cat",    CommandPerm::read_only()),
            ("head",   CommandPerm::read_only()),
            ("tail",   CommandPerm::read_only()),
            ("grep",   CommandPerm::read_only()),
            ("ls",     CommandPerm::read_only()),
            ("echo",   CommandPerm::read_only()),
            ("printf", CommandPerm::read_only()),
            ("diff",   CommandPerm::read_only()),
            ("wc",     CommandPerm::read_only()),
            ("jq",     CommandPerm::read_only()),
            ("xxd",    CommandPerm::read_only()),
            // Network — read-only in sandbox (download OK, no pipe-to-shell)
            ("curl",   CommandPerm::read_only()),
            ("wget",   CommandPerm::read_only()),
        ];
        for (cmd, perm) in sandbox_full {
            self.add_command("sandbox", cmd, *perm)?;
        }

        // USER_FS_PATHS: Where user FS whitelist commands can operate.
        // Mirrors current allowed_paths from init_defaults() — home directory.
        // Blocked paths (blocked_paths) still enforced separately.
        let home = crate::paths::actual_home().to_string_lossy().to_string();
        self.add_user_fs_path(&format!("{}/", home))?;

        log::info!(
            "SPF whitelist: migration complete — {} user_fs cmds, {} sandbox cmds, user_fs_paths seeded",
            user_fs_read.len(), sandbox_full.len()
        );

        Ok(())
    }

    /// Get database stats
    pub fn stats(&self) -> Result<(u64, u64, u64)> {
        let rtxn = self.env.read_txn()?;
        let config_stat = self.config.stat(&rtxn)?;
        let paths_stat = self.paths.stat(&rtxn)?;
        let patterns_stat = self.patterns.stat(&rtxn)?;
        Ok((config_stat.entries as u64, paths_stat.entries as u64, patterns_stat.entries as u64))
    }

    /// Get database stats including commands count
    pub fn stats_full(&self) -> Result<(u64, u64, u64, u64)> {
        let rtxn = self.env.read_txn()?;
        let config_stat = self.config.stat(&rtxn)?;
        let paths_stat = self.paths.stat(&rtxn)?;
        let patterns_stat = self.patterns.stat(&rtxn)?;
        let commands_stat = self.commands.stat(&rtxn)?;
        Ok((config_stat.entries as u64, paths_stat.entries as u64,
            patterns_stat.entries as u64, commands_stat.entries as u64))
    }

    // ========================================================================
    // FULL CONFIG ASSEMBLY (for main.rs - single source of truth)
    // ========================================================================

    /// Load full SpfConfig from LMDB. Auto-initializes if empty.
    /// This is the PRIMARY config loading method - replaces JSON file loading.
    pub fn load_full_config(&self) -> Result<SpfConfig> {
        // Ensure defaults exist, then sync approval policy from code
        self.init_defaults()?;
        self.sync_tier_approval()?;
        // Sync blocked paths — ensure ALL config/governance files are protected
        self.sync_blocked_paths()?;
        // Sync command whitelists — migrate if needed (BLOCK-02)
        self.sync_command_whitelist()?;

        // Collect path rules
        let path_rules = self.list_path_rules()?;
        let mut allowed_paths = Vec::new();
        let mut blocked_paths = Vec::new();
        for (rule_type, path) in path_rules {
            match rule_type.as_str() {
                "allowed" => allowed_paths.push(path),
                "blocked" => blocked_paths.push(path),
                _ => {}
            }
        }

        // Collect dangerous commands
        let dangerous_commands: Vec<String> = self.list_dangerous_patterns()?
            .into_iter()
            .map(|(pattern, _)| pattern)
            .collect();

        // Collect command whitelists (BLOCK-02)
        let user_cmds = self.list_commands("user_fs")?;
        let sandbox_cmds = self.list_commands("sandbox")?;
        let user_fs_paths = self.list_user_fs_paths()?;

        // Get scalar values
        let version = self.get("spf", "version")?.unwrap_or_else(|| "1.0.0".to_string());
        let require_read = self.get("spf", "require_read_before_edit")?
            .map(|s| s == "true").unwrap_or(true);
        let max_write = self.get("spf", "max_write_size")?
            .and_then(|s| s.parse().ok()).unwrap_or(100_000);

        // Assemble config (types are now identical - no conversion needed)
        Ok(SpfConfig {
            version,
            enforce_mode: self.get_enforce_mode()?,
            allowed_paths,
            blocked_paths,
            require_read_before_edit: require_read,
            max_write_size: max_write,
            tiers: self.get_tiers()?,
            formula: self.get_formula()?,
            complexity_weights: self.get_weights()?,
            dangerous_commands,
            git_force_patterns: vec![
                "--force".to_string(),
                "--hard".to_string(),
                "-f".to_string(),
            ],
            // Command whitelists assembled from LMDB (BLOCK-02)
            allowed_commands_user: user_cmds.into_iter().collect(),
            allowed_commands_sandbox: sandbox_cmds.into_iter().collect(),
            user_fs_paths,
        })
    }
}