File size: 30,144 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
// SPF Smart Gateway - Main Entry Point
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// CLI and MCP stdio server. All tool calls route through this gateway.
// Usage:
//   spf-smart-gate serve                                        # Run MCP server (stdio)
//   spf-smart-gate gate <tool> <params>                         # One-shot gate check
//   spf-smart-gate status                                       # Show gateway status
//   spf-smart-gate session                                      # Show session state
//   spf-smart-gate fs-import <virtual_path> <device_file>       # Import file to LMDB
//   spf-smart-gate fs-export <virtual_path> <device_file>       # Export file from LMDB
//   spf-smart-gate config-import <json_file>                    # Import config to CONFIG.DB
//   spf-smart-gate config-export <json_file>                    # Export config from CONFIG.DB
//   spf-smart-gate whitelist-add <context> <command> [--perm]   # Add command to whitelist (BLOCK-04)
//   spf-smart-gate whitelist-remove <context> <command>         # Remove from whitelist (BLOCK-04)
//   spf-smart-gate whitelist-list                               # List whitelists (BLOCK-04)
//   spf-smart-gate whitelist-add-path <path>                    # Add user FS path (BLOCK-04)

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use spf_smart_gate::{
    agent_state::AgentStateDb, calculate, config, config::CommandPerm,
    config_db::SpfConfigDb, fs::SpfFs,
    gate, mcp, paths, session::Session, storage::SpfStorage,
    utf8_safe, worker,
};
use std::path::PathBuf;

fn default_storage_path() -> PathBuf {
    paths::spf_root().join("LIVE/SESSION/SESSION.DB")
}

#[derive(Parser)]
#[command(name = "spf-smart-gate")]
#[command(author = "Joseph Stone")]
#[command(version = "3.0.0")]
#[command(about = "SPF Smart Gateway - MCP command gateway with LMDB-backed configuration")]
struct Cli {
    /// Session storage directory (LIVE/SESSION/SESSION.DB)
    #[arg(short, long, default_value_os_t = default_storage_path())]
    storage: PathBuf,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Run MCP server (stdio JSON-RPC, optional HTTP API)
    Serve {
        /// Enable HTTP API on this port (e.g. --http-port 3900)
        #[arg(long)]
        http_port: Option<u16>,
    },

    /// Run as headless worker node (transformer-driven, no stdio MCP)
    Worker {
        /// Model role: writer or researcher
        #[arg(long, default_value = "writer")]
        role: String,
        /// Override checkpoint path
        #[arg(long)]
        checkpoint: Option<String>,
        /// Max concurrent pipeline tasks
        #[arg(long, default_value = "4")]
        max_concurrent: usize,
    },

    /// One-shot gate check — runs through SPF gate, returns allow/block
    Gate {
        /// Tool name (Read, Write, Edit, Bash, etc.)
        tool: String,

        /// Parameters as JSON string
        params: String,
    },

    /// Calculate complexity without executing
    Calculate {
        /// Tool name
        tool: String,

        /// Parameters as JSON string
        params: String,
    },

    /// Show gateway status
    Status,

    /// Show full session state
    Session,

    /// Reset session (fresh start)
    Reset,

    /// Initialize/verify LMDB config (auto-runs on startup)
    InitConfig,

    /// Refresh path rules in CONFIG.DB for current system.
    /// Only updates allowed_paths and blocked_paths.
    /// Preserves all other config (tiers, formula, weights, etc.)
    RefreshPaths {
        /// Show what would change without writing
        #[arg(long)]
        dry_run: bool,
    },

    /// Import a device file into LMDB virtual filesystem.
    /// /home/agent/* paths route to LMDB5.DB (AgentStateDb).
    /// All other paths route to SPF_FS.DB.
    FsImport {
        /// Virtual path (e.g. /home/agent/.claude.json)
        virtual_path: String,

        /// Device file to read from
        device_file: PathBuf,

        /// Dry run — show what would happen without writing
        #[arg(long)]
        dry_run: bool,
    },

    /// Export a file from LMDB virtual filesystem to device.
    /// /home/agent/* paths read from LMDB5.DB (AgentStateDb).
    /// All other paths read from SPF_FS.DB.
    FsExport {
        /// Virtual path (e.g. /home/agent/.claude.json)
        virtual_path: String,

        /// Device file to write to
        device_file: PathBuf,
    },

    /// Import config from JSON file into CONFIG.DB
    ConfigImport {
        /// JSON config file to import
        json_file: PathBuf,

        /// Dry run — show what would happen without writing
        #[arg(long)]
        dry_run: bool,
    },

    /// Export CONFIG.DB state to JSON file
    ConfigExport {
        /// Device file to write JSON to
        json_file: PathBuf,
    },

    // ================================================================
    // COMMAND WHITELIST MANAGEMENT — CLI ONLY (BLOCK-04)
    // NOT exposed as MCP tools — AI cannot modify its own whitelist.
    // Changes take effect on next SPF restart.
    // ================================================================

    /// Add a command to whitelist
    WhitelistAdd {
        /// Context: "user" or "sandbox"
        context: String,
        /// Command name (e.g., "grep", "cargo")
        command: String,
        /// Permission level: "read", "read-write", "full"
        #[arg(long, default_value = "read")]
        perm: String,
    },

    /// Remove a command from whitelist
    WhitelistRemove {
        /// Context: "user" or "sandbox"
        context: String,
        /// Command name
        command: String,
    },

    /// List all whitelisted commands
    WhitelistList,

    /// Add a user filesystem path (where user FS whitelist commands can operate)
    WhitelistAddPath {
        /// Path to allow (e.g., ~/projects/)
        path: String,
    },
}

fn main() -> Result<()> {
    // Initialize logging — suppress iroh transport noise, keep SPF diagnostics
    // Override with RUST_LOG env var for full verbosity: RUST_LOG=info ./spf-smart-gate serve
    let _ = env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn,spf_smart_gate=info")).try_init();

    let cli = Cli::parse();

    // Ensure storage directory exists
    std::fs::create_dir_all(&cli.storage)
        .with_context(|| format!("Failed to create storage dir {:?}", cli.storage))?;

    // Open SPF_CONFIG LMDB and load config (SINGLE SOURCE OF TRUTH)
    let config_db_path = paths::spf_root().join("LIVE/CONFIG/CONFIG.DB");
    let config_db = SpfConfigDb::open(&config_db_path)
        .with_context(|| format!("Failed to open SPF_CONFIG LMDB at {:?}", config_db_path))?;

    let config = config_db.load_full_config()
        .with_context(|| "Failed to load config from LMDB")?;

    // Open SPF_STATE storage
    let storage = SpfStorage::open(&cli.storage)
        .with_context(|| format!("Failed to open storage at {:?}", cli.storage))?;

    // Load or create session
    let session = storage.load_session()?.unwrap_or_else(Session::new);

    match &cli.command {
        Commands::Serve { http_port } => {
            // Load HTTP config from LIVE/CONFIG/http.json (defaults if missing)
            let mut http_config = config::HttpConfig::load(
                &paths::spf_root().join("LIVE/CONFIG/http.json")
            ).unwrap_or_default();

            // CLI --http-port overrides config file
            if let Some(port) = http_port {
                http_config.port = *port;
                if http_config.transport == "stdio" {
                    http_config.transport = "both".to_string();
                }
            }

            // SPF_API_KEY env var overrides config file
            if let Ok(key) = std::env::var("SPF_API_KEY") {
                if !key.is_empty() {
                    http_config.api_key = key;
                }
            }

            // Auto-generate API key if none configured
              if http_config.api_key.is_empty() {
                use rand::Rng;
                let key_bytes: [u8; 32] = rand::rng().random();
                http_config.api_key = hex::encode(key_bytes);
                // Save back to config file so key persists across restarts
                let config_path = paths::spf_root().join("LIVE/CONFIG/http.json");
                if let Some(parent) = config_path.parent() {
                    std::fs::create_dir_all(parent).ok();
                }
                if let Ok(json) = serde_json::to_string_pretty(&http_config) {
                    std::fs::write(&config_path, json).ok();
                }
                eprintln!("[SPF] Generated API key: {}", http_config.api_key);
            }

            // Run MCP server — blocks forever, consumes session & storage
            mcp::run(config, config_db, session, storage, http_config);
            // Unreachable
        }

        Commands::Worker { role, checkpoint, max_concurrent } => {
            // Load transformer config
            let transformer_config = config::TransformerConfig::load(
                &paths::spf_root().join("LIVE/CONFIG/transformer.json")
            ).unwrap_or_default();

            // Build worker config from CLI args
            let worker_config = worker::WorkerConfig {
                role: role.clone(),
                checkpoint_override: checkpoint.clone(),
                max_concurrent: *max_concurrent,
                ..Default::default()
            };

            // Initialize transformer (load checkpoint if available)
            let transformer_state = worker::init_transformer(&transformer_config, &worker_config)
                .expect("Failed to initialize transformer");
            let transformer = std::sync::Arc::new(std::sync::RwLock::new(transformer_state));

            // Load HTTP config for monitoring endpoints
            let http_config = config::HttpConfig::load(
                &paths::spf_root().join("LIVE/CONFIG/http.json")
            ).unwrap_or_default();

            // Build ServerState (same pattern as Serve, with transformer)
            mcp::run_worker(config, config_db, session, storage, http_config,
                transformer, transformer_config, worker_config);
            // Unreachable
        }

        Commands::Gate { tool, params } => {
            let params: calculate::ToolParams = serde_json::from_str(params)
                .with_context(|| format!("Invalid params JSON: {}", params))?;

            let decision = gate::process(tool, &params, &config, &session, &spf_smart_gate::dispatch::Source::Stdio);

            println!("{}", serde_json::to_string_pretty(&decision)?);

            if !decision.allowed {
                std::process::exit(1);
            }

            // Save session after gate call
            storage.save_session(&session)?;
        }

        Commands::Calculate { tool, params } => {
            let params: calculate::ToolParams = serde_json::from_str(params)
                .with_context(|| format!("Invalid params JSON: {}", params))?;

            let result = calculate::calculate(tool, &params, &config);

            println!("{}", serde_json::to_string_pretty(&result)?);

            // Save session after calculate
            storage.save_session(&session)?;
        }

        Commands::Status => {
            println!("SPF Smart Gateway v3.0.0");
            println!("Mode: {:?}", config.enforce_mode);
            println!("Storage: {:?}", cli.storage);
            println!("Config: LMDB (CONFIG/CONFIG.DB)");
            println!();
            println!("Session: {}", session.status_summary());
            println!();
            println!("Tiers:");
            println!("  SIMPLE   < 500    | 40% analyze / 60% build");
            println!("  LIGHT    < 2000   | 60% analyze / 40% build");
            println!("  MEDIUM   < 10000  | 75% analyze / 25% build");
            println!("  CRITICAL > 10000  | 95% analyze / 5% build (requires approval)");
            println!();
            println!("Formula: a_optimal(C) = {} x (1 - 1/ln(C + e))", config.formula.w_eff);
            println!("Complexity: C = basic^1 + deps^7 + complex^10 + files x 10");
        }

        Commands::Session => {
            println!("{}", serde_json::to_string_pretty(&session)?);
        }

        Commands::Reset => {
            let new_session = Session::new();
            storage.save_session(&new_session)?;
            println!("Session reset.");
        }

        Commands::InitConfig => {
            // Config is already initialized via load_full_config() above
            // This command now just confirms the LMDB state
            let (config_count, paths_count, patterns_count) = config_db.stats()?;
            println!("SPF_CONFIG LMDB initialized at {:?}", config_db_path);
            println!("  Config entries: {}", config_count);
            println!("  Path rules: {}", paths_count);
            println!("  Dangerous patterns: {}", patterns_count);
            println!();
            println!("Config is stored in LMDB, not JSON files.");
            println!("Use MCP tools or direct LMDB access to modify.");
        }

        Commands::RefreshPaths { dry_run } => {
            let root = paths::spf_root().to_string_lossy().to_string();
            let home = paths::actual_home().to_string_lossy().to_string();
            let sys_pkg = spf_smart_gate::paths::system_pkg_path();

            // Build new path sets from current system
            let new_allowed: Vec<String> = vec![
                format!("{}/", home),
            ];
            let new_blocked: Vec<String> = vec![
                "/tmp".to_string(),
                "/etc".to_string(),
                "/usr".to_string(),
                "/system".to_string(),
                sys_pkg,
                format!("{}/src/", root),
                format!("{}/LIVE/SPF_FS/blobs/", root),
                format!("{}/Cargo.toml", root),
                format!("{}/Cargo.lock", root),
                format!("{}/.claude/", home),
            ];

            // Show current state
            let current_rules = config_db.list_path_rules()?;
            let cur_allowed: Vec<&str> = current_rules.iter()
                .filter(|(t, _)| t == "allowed").map(|(_, p)| p.as_str()).collect();
            let cur_blocked: Vec<&str> = current_rules.iter()
                .filter(|(t, _)| t == "blocked").map(|(_, p)| p.as_str()).collect();

            println!("=== SPF Refresh Paths ===");
            println!("SPF_ROOT: {}", root);
            println!("HOME:     {}", home);
            println!();
            println!("CURRENT allowed ({}):", cur_allowed.len());
            for p in &cur_allowed { println!("  + {}", p); }
            println!("CURRENT blocked ({}):", cur_blocked.len());
            for p in &cur_blocked { println!("  - {}", p); }
            println!();
            println!("NEW allowed ({}):", new_allowed.len());
            for p in &new_allowed { println!("  + {}", p); }
            println!("NEW blocked ({}):", new_blocked.len());
            for p in &new_blocked { println!("  - {}", p); }

            if *dry_run {
                println!();
                println!("[DRY RUN] No changes written.");
            } else {
                // Remove all existing path rules
                for (rule_type, path) in &current_rules {
                    config_db.remove_path_rule(rule_type, path)?;
                }
                // Write new rules
                for p in &new_allowed {
                    config_db.allow_path(p)?;
                }
                for p in &new_blocked {
                    config_db.block_path(p)?;
                }
                println!();
                println!("Path rules updated. {} allowed, {} blocked.",
                    new_allowed.len(), new_blocked.len());
                println!("All other config preserved (tiers, formula, weights, etc.)");
            }
        }

        // ====================================================================
        // LMDB VIRTUAL FILESYSTEM IMPORT/EXPORT
        // Routes /home/agent/* to LMDB5.DB, everything else to SPF_FS.DB
        // ====================================================================

        Commands::FsImport { virtual_path, device_file, dry_run } => {
            let data = std::fs::read(device_file)
                .with_context(|| format!("Failed to read device file: {:?}", device_file))?;

            println!("fs-import: {:?} -> {}", device_file, virtual_path);
            println!("  Size: {} bytes", data.len());

            if *dry_run {
                println!("  [DRY RUN] No changes made.");
                return Ok(());
            }

            // Route to correct LMDB based on virtual path
            if virtual_path.starts_with("/home/agent/") {
                // LMDB5.DB — Agent config and state files
                let relative = virtual_path.strip_prefix("/home/agent/").unwrap_or(virtual_path);
                let agent_db_path = paths::spf_root().join("LIVE/LMDB5/LMDB5.DB");
                let agent_db = AgentStateDb::open(&agent_db_path)
                    .with_context(|| format!("Failed to open LMDB5 at {:?}", agent_db_path))?;

                let content = utf8_safe::encode_for_lmdb(&data);
                let key = format!("file:{}", relative);
                agent_db.set_state(&key, &content)
                    .with_context(|| format!("Failed to store in LMDB5: {}", key))?;

                // Verify
                let stored = agent_db.get_state(&key)?
                    .ok_or_else(|| anyhow::anyhow!("Write succeeded but read-back failed: {}", key))?;

                println!("  Target: LMDB5.DB (AgentState)");
                println!("  Key: {}", key);
                println!("  Stored: {} bytes", stored.len());
                println!("  OK");
            } else {
                // SPF_FS.DB — System virtual filesystem
                let fs_path = paths::spf_root().join("LIVE/SPF_FS");
                let spf_fs = SpfFs::open(&fs_path)
                    .with_context(|| format!("Failed to open SPF_FS at {:?}", fs_path))?;

                spf_fs.write(virtual_path, &data)
                    .with_context(|| format!("Failed to write to virtual path: {}", virtual_path))?;

                // Verify
                let meta = spf_fs.stat(virtual_path)?
                    .ok_or_else(|| anyhow::anyhow!("Write succeeded but stat failed for: {}", virtual_path))?;

                println!("  Target: SPF_FS.DB");
                println!("  Written: {} bytes (version {})", meta.size, meta.version);
                if let Some(ref checksum) = meta.checksum {
                    println!("  Checksum: {}", &checksum[..16]);
                }
                println!("  OK");
            }
        }

        Commands::FsExport { virtual_path, device_file } => {
            // Route to correct LMDB based on virtual path
            let data: Vec<u8> = if virtual_path.starts_with("/home/agent/") {
                // LMDB5.DB — Agent config and state files
                let relative = virtual_path.strip_prefix("/home/agent/").unwrap_or(virtual_path);
                let agent_db_path = paths::spf_root().join("LIVE/LMDB5/LMDB5.DB");
                let agent_db = AgentStateDb::open(&agent_db_path)
                    .with_context(|| format!("Failed to open LMDB5 at {:?}", agent_db_path))?;

                let key = format!("file:{}", relative);
                let content = agent_db.get_state(&key)?
                    .ok_or_else(|| anyhow::anyhow!("Not found in LMDB5: {}", key))?;

                println!("  Source: LMDB5.DB (AgentState)");
                println!("  Key: {}", key);
                content.into_bytes()
            } else {
                // SPF_FS.DB — System virtual filesystem
                let fs_path = paths::spf_root().join("LIVE/SPF_FS");
                let spf_fs = SpfFs::open(&fs_path)
                    .with_context(|| format!("Failed to open SPF_FS at {:?}", fs_path))?;

                println!("  Source: SPF_FS.DB");
                spf_fs.read(virtual_path)
                    .with_context(|| format!("Failed to read virtual path: {}", virtual_path))?
            };

            // Ensure parent directory exists on device
            if let Some(parent) = device_file.parent() {
                std::fs::create_dir_all(parent)?;
            }

            std::fs::write(device_file, &data)
                .with_context(|| format!("Failed to write device file: {:?}", device_file))?;

            println!("fs-export: {} -> {:?}", virtual_path, device_file);
            println!("  Size: {} bytes", data.len());
            println!("  OK");
        }

        // ====================================================================
        // CONFIG.DB IMPORT/EXPORT
        // ====================================================================

        Commands::ConfigImport { json_file, dry_run } => {
            let json_str = std::fs::read_to_string(json_file)
                .with_context(|| format!("Failed to read config file: {:?}", json_file))?;

            let json: serde_json::Value = serde_json::from_str(&json_str)
                .with_context(|| "Invalid JSON in config file")?;

            println!("config-import: {:?}", json_file);

            // Enforce mode
            if let Some(mode) = json.get("enforce_mode").and_then(|v| v.as_str()) {
                println!("  enforce_mode: {}", mode);
                if !dry_run {
                    let mode = serde_json::from_value(json["enforce_mode"].clone())?;
                    config_db.set_enforce_mode(&mode)?;
                }
            }

            // Tiers
            if let Some(tiers_val) = json.get("tiers") {
                println!("  tiers: present");
                if !dry_run {
                    let tiers = serde_json::from_value(tiers_val.clone())?;
                    config_db.set_tiers(&tiers)?;
                }
            }

            // Formula
            if let Some(formula_val) = json.get("formula") {
                println!("  formula: present");
                if !dry_run {
                    let formula = serde_json::from_value(formula_val.clone())?;
                    config_db.set_formula(&formula)?;
                }
            }

            // Weights
            if let Some(weights_val) = json.get("weights") {
                println!("  weights: present");
                if !dry_run {
                    let weights = serde_json::from_value(weights_val.clone())?;
                    config_db.set_weights(&weights)?;
                }
            }

            // Allowed paths
            if let Some(paths) = json.get("allowed_paths").and_then(|v| v.as_array()) {
                println!("  allowed_paths: {} entries", paths.len());
                if !dry_run {
                    for path in paths {
                        if let Some(p) = path.as_str() {
                            config_db.allow_path(p)?;
                        }
                    }
                }
            }

            // Blocked paths
            if let Some(paths) = json.get("blocked_paths").and_then(|v| v.as_array()) {
                println!("  blocked_paths: {} entries", paths.len());
                if !dry_run {
                    for path in paths {
                        if let Some(p) = path.as_str() {
                            config_db.block_path(p)?;
                        }
                    }
                }
            }

            // Dangerous patterns
            if let Some(patterns) = json.get("dangerous_patterns").and_then(|v| v.as_object()) {
                println!("  dangerous_patterns: {} entries", patterns.len());
                if !dry_run {
                    for (pattern, severity) in patterns {
                        let sev = severity.as_u64().unwrap_or(5) as u8;
                        config_db.add_dangerous_pattern(pattern, sev)?;
                    }
                }
            }

            // Scalar config values
            if let Some(obj) = json.get("config").and_then(|v| v.as_object()) {
                println!("  config scalars: {} entries", obj.len());
                if !dry_run {
                    for (key, value) in obj {
                        if let Some(v) = value.as_str() {
                            config_db.set("spf", key, v)?;
                        }
                    }
                }
            }

            if *dry_run {
                println!("  [DRY RUN] No changes made.");
            } else {
                let (config_count, paths_count, patterns_count) = config_db.stats()?;
                println!("  Imported. DB now: {} configs, {} paths, {} patterns", config_count, paths_count, patterns_count);
            }
            println!("  OK");
        }

        Commands::ConfigExport { json_file } => {
            // Collect all config state
            let path_rules = config_db.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.clone()),
                    "blocked" => blocked_paths.push(path.clone()),
                    _ => {}
                }
            }

            let dangerous_patterns = config_db.list_dangerous_patterns()?;
            let mut patterns_map = serde_json::Map::new();
            for (pattern, severity) in &dangerous_patterns {
                patterns_map.insert(pattern.clone(), serde_json::json!(severity));
            }

            let export = serde_json::json!({
                "version": config.version,
                "enforce_mode": config.enforce_mode,
                "tiers": config.tiers,
                "formula": config.formula,
                "weights": config.complexity_weights,
                "allowed_paths": allowed_paths,
                "blocked_paths": blocked_paths,
                "dangerous_patterns": patterns_map,
                "config": {
                    "require_read_before_edit": config.require_read_before_edit.to_string(),
                    "max_write_size": config.max_write_size.to_string(),
                }
            });

            // Ensure parent directory exists
            if let Some(parent) = json_file.parent() {
                std::fs::create_dir_all(parent)?;
            }

            let json_str = serde_json::to_string_pretty(&export)?;
            std::fs::write(json_file, &json_str)
                .with_context(|| format!("Failed to write config export: {:?}", json_file))?;

            println!("config-export: -> {:?}", json_file);
            println!("  {} configs, {} path rules, {} patterns",
                path_rules.len(), allowed_paths.len() + blocked_paths.len(), dangerous_patterns.len());
            println!("  {} bytes written", json_str.len());
            println!("  OK");
        }

        // ====================================================================
        // COMMAND WHITELIST MANAGEMENT — CLI ONLY (BLOCK-04)
        // NOT exposed as MCP tools — AI cannot modify its own whitelist.
        // Changes take effect on next SPF restart.
        // ====================================================================

        Commands::WhitelistAdd { context, command, perm } => {
            let ctx = match context.as_str() {
                "user" => "user_fs",
                "sandbox" => "sandbox",
                _ => { eprintln!("Context must be 'user' or 'sandbox'"); std::process::exit(1); }
            };
            let permission = match perm.as_str() {
                "read" => CommandPerm::read_only(),
                "read-write" => CommandPerm::read_write(),
                "full" => CommandPerm::full(),
                _ => { eprintln!("Perm must be 'read', 'read-write', or 'full'"); std::process::exit(1); }
            };
            config_db.add_command(ctx, command, permission)?;
            println!("Added: {}:{} = R:{} W:{} X:{}", ctx, command, permission.read, permission.write, permission.execute);
            println!("Restart SPF for changes to take effect.");
        }

        Commands::WhitelistRemove { context, command } => {
            let ctx = match context.as_str() {
                "user" => "user_fs",
                "sandbox" => "sandbox",
                _ => { eprintln!("Context must be 'user' or 'sandbox'"); std::process::exit(1); }
            };
            let removed = config_db.remove_command(ctx, command)?;
            if removed {
                println!("Removed: {}:{}", ctx, command);
            } else {
                println!("Not found: {}:{}", ctx, command);
            }
            println!("Restart SPF for changes to take effect.");
        }

        Commands::WhitelistList => {
            println!("=== Command Whitelists ===");
            println!();
            println!("USER FILESYSTEM:");
            for (cmd, perm) in config_db.list_commands("user_fs")? {
                println!("  {} — R:{} W:{} X:{}", cmd, perm.read, perm.write, perm.execute);
            }
            println!();
            println!("SANDBOX:");
            for (cmd, perm) in config_db.list_commands("sandbox")? {
                println!("  {} — R:{} W:{} X:{}", cmd, perm.read, perm.write, perm.execute);
            }
            println!();
            println!("USER FS PATHS:");
            for path in config_db.list_user_fs_paths()? {
                println!("  {}", path);
            }
        }

        Commands::WhitelistAddPath { path } => {
            config_db.add_user_fs_path(path)?;
            println!("Added user FS path: {}", path);
            println!("Restart SPF for changes to take effect.");
        }
    }

    Ok(())
}