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
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
// SPF Smart Gateway - Configuration
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Loads SPF rules, tiers, formulas, blocked paths. Defaults stored in LMDB.
//
// BLOCK I ADDITION: TransformerConfig struct (after MeshConfig pattern)
// BLOCK NN-A: Added .claude.json, .mcp.json, .config/anthropic/, .anthropic/ to blocked_paths
// BLOCK SEC-2: Added .qwen/, .xlaude/ agent config dirs + LIVE/CONFIG/ directory protection

use serde::{Deserialize, Serialize, Deserializer};
use std::path::Path;

/// Master SPF configuration loaded from CONFIG LMDB
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpfConfig {
    pub version: String,
    pub enforce_mode: EnforceMode,
    pub allowed_paths: Vec<String>,
    pub blocked_paths: Vec<String>,
    pub require_read_before_edit: bool,
    pub max_write_size: usize,
    pub tiers: TierConfig,
    pub formula: FormulaConfig,
    pub complexity_weights: ComplexityWeights,
    pub dangerous_commands: Vec<String>,
    pub git_force_patterns: Vec<String>,
    // ================================================================
    // COMMAND WHITELIST FIELDS — Default-Deny Bash Security (BLOCK-01)
    // Empty defaults = everything blocked until configured.
    // Populated from LMDB commands DB by load_full_config() (BLOCK-02).
    // Enforced by Stage 0 in validate_bash() (BLOCK-03).
    // ================================================================
    #[serde(default)]
    pub allowed_commands_user: std::collections::HashMap<String, CommandPerm>,
    #[serde(default)]
    pub allowed_commands_sandbox: std::collections::HashMap<String, CommandPerm>,
    #[serde(default)]
    pub user_fs_paths: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum EnforceMode {
    Soft,
    Max,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TierConfig {
    pub simple: TierThreshold,
    pub light: TierThreshold,
    pub medium: TierThreshold,
    pub critical: TierThreshold,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TierThreshold {
    pub max_c: u64,
    pub analyze_percent: u8,
    pub build_percent: u8,
    pub requires_approval: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormulaConfig {
    /// W_eff: effective working memory in tokens
    pub w_eff: f64,
    /// Euler's number
    pub e: f64,
    /// C = (basic ^ basic_power) + (deps ^ deps_power) + (complex ^ complex_power) + (files * files_mult)
    pub basic_power: u32,
    pub deps_power: u32,
    pub complex_power: u32,
    pub files_multiplier: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplexityWeights {
    pub edit: ToolWeight,
    pub write: ToolWeight,
    pub bash_dangerous: ToolWeight,
    pub bash_git: ToolWeight,
    pub bash_piped: ToolWeight,
    pub bash_simple: ToolWeight,
    pub read: ToolWeight,
    pub search: ToolWeight,
    pub unknown: ToolWeight,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolWeight {
    pub basic: u64,
    pub dependencies: u64,
    pub complex: u64,
    pub files: u64,
}

// ============================================================================
// COMMAND PERMISSION MODEL — Default-Deny Bash Security (BLOCK-01)
// Per-command R/W/X flags for whitelist enforcement.
// Stored in LMDB commands DB (BLOCK-02), checked by Stage 0 (BLOCK-03).
// ============================================================================

/// Per-command permission flags for whitelist enforcement.
/// Controls what operations a whitelisted command can perform.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct CommandPerm {
    pub read: bool,     // Can read files, list dirs, query info
    pub write: bool,    // Can modify, create, delete files
    pub execute: bool,  // Can spawn subprocesses (-exec, system())
}

impl CommandPerm {
    pub fn read_only() -> Self {
        Self { read: true, write: false, execute: false }
    }
    pub fn read_write() -> Self {
        Self { read: true, write: true, execute: false }
    }
    pub fn full() -> Self {
        Self { read: true, write: true, execute: true }
    }
}

impl Default for SpfConfig {
    fn default() -> Self {
        Self {
            version: "1.0.0".to_string(),
            enforce_mode: EnforceMode::Max,
            allowed_paths: {
                let home = crate::paths::actual_home().to_string_lossy();
                vec![
                    format!("{}/", home),
                ]
            },
            blocked_paths: {
                let root = crate::paths::spf_root().to_string_lossy();
                let home = crate::paths::actual_home().to_string_lossy();
                let mut paths = vec![
                    crate::paths::system_pkg_path(),
                    format!("{}/src/", root),
                    format!("{}/LIVE/SPF_FS/blobs/", root),
                    format!("{}/Cargo.toml", root),
                    format!("{}/Cargo.lock", root),
                    format!("{}/.claude/", home),
                    // BLOCK NN-A: Claude/Anthropic config files — ZERO AI write access
                    format!("{}/.claude.json", home),
                    format!("{}/.mcp.json", home),
                    format!("{}/.config/anthropic/", home),
                    format!("{}/.anthropic/", home),
                    // BLOCK SEC-2: External agent config directories — prevent config hijack
                    // Blocks both home-level and SPFsmartGATE-level agent configs.
                    // Prevents any AI agent from creating/modifying CLI routing files
                    // that could redirect MCP tool calls to a different gate instance.
                    format!("{}/.qwen/", home),
                    format!("{}/.qwen/", root),
                    format!("{}/.xlaude/", home),
                    format!("{}/.xlaude/", root),
                    // BLOCK SEC-2: Runtime config directory — protect gate behavior configs
                    // Contains http.json, mesh.json, transformer.json, network.json,
                    // whitelist-config.json — all control gate pipeline behavior.
                    format!("{}/LIVE/CONFIG/", root),
                    // System config and state — ZERO AI write access
                    format!("{}/LIVE/CONFIG.DB", root),
                    format!("{}/LIVE/LMDB5/", root),
                    format!("{}/LIVE/state/", root),
                    format!("{}/LIVE/storage/", root),
                    format!("{}/hooks/", root),
                    format!("{}/scripts/", root),
                ];
                if cfg!(target_os = "windows") {
                    paths.extend([
                        r"C:\Windows".to_string(),
                        r"C:\Program Files".to_string(),
                        r"C:\Program Files (x86)".to_string(),
                    ]);
                } else {
                    paths.extend([
                        "/tmp".to_string(),
                        "/etc".to_string(),
                        "/usr".to_string(),
                        "/system".to_string(),
                    ]);
                }
                paths
            },
            require_read_before_edit: true,
            max_write_size: 100_000,
            tiers: TierConfig {
                simple: TierThreshold { max_c: 500, analyze_percent: 40, build_percent: 60, requires_approval: true },
                light: TierThreshold { max_c: 2000, analyze_percent: 60, build_percent: 40, requires_approval: true },
                medium: TierThreshold { max_c: 10000, analyze_percent: 75, build_percent: 25, requires_approval: true },
                critical: TierThreshold { max_c: u64::MAX, analyze_percent: 95, build_percent: 5, requires_approval: true },
            },
            formula: FormulaConfig {
                w_eff: 40000.0,
                e: std::f64::consts::E,
                basic_power: 1,      // ^1 per SPF protocol
                deps_power: 7,       // ^7 per SPF protocol
                complex_power: 10,   // ^10 per SPF protocol
                files_multiplier: 10, // ×10 per SPF protocol
            },
            // Weights scaled for formula: C = basic^1 + deps^7 + complex^10 + files×10
            // deps^7: 2→128, 3→2187, 4→16384, 5→78125
            // complex^10: 1→1, 2→1024
            complexity_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 },
            },
            dangerous_commands: vec![
                "rm -rf /".to_string(),
                "rm -rf ~".to_string(),
                "dd if=".to_string(),
                "> /dev/".to_string(),
                "chmod 777".to_string(),
                "curl | sh".to_string(),
                "wget | sh".to_string(),
                "curl|sh".to_string(),
                "wget|sh".to_string(),
            ],
            git_force_patterns: vec![
                "--force".to_string(),
                "--hard".to_string(),
                "-f".to_string(),
            ],
            // COMMAND WHITELIST DEFAULTS — EMPTY = DEFAULT-DENY (BLOCK-01)
            allowed_commands_user: std::collections::HashMap::new(),
            allowed_commands_sandbox: std::collections::HashMap::new(),
            user_fs_paths: vec![],
        }
    }
}

impl SpfConfig {
    /// Load config from JSON file, falling back to defaults
    pub fn load(path: &Path) -> anyhow::Result<Self> {
        if path.exists() {
            let content = std::fs::read_to_string(path)?;
            let config: Self = serde_json::from_str(&content)?;
            Ok(config)
        } else {
            log::warn!("Config not found at {:?}, using defaults", path);
            Ok(Self::default())
        }
    }

    /// Save config to JSON file
    pub fn save(&self, path: &Path) -> anyhow::Result<()> {
        let content = serde_json::to_string_pretty(self)?;
        std::fs::write(path, content)?;
        Ok(())
    }

    /// Get tier for a given complexity value
    /// CRITICAL tier requires explicit user approval. Lower tiers protected by other layers.
    pub fn get_tier(&self, c: u64) -> (&str, u8, u8, bool) {
        if c < self.tiers.simple.max_c {
            ("SIMPLE", self.tiers.simple.analyze_percent, self.tiers.simple.build_percent, self.tiers.simple.requires_approval)
        } else if c < self.tiers.light.max_c {
            ("LIGHT", self.tiers.light.analyze_percent, self.tiers.light.build_percent, self.tiers.light.requires_approval)
        } else if c < self.tiers.medium.max_c {
            ("MEDIUM", self.tiers.medium.analyze_percent, self.tiers.medium.build_percent, self.tiers.medium.requires_approval)
        } else {
            ("CRITICAL", self.tiers.critical.analyze_percent, self.tiers.critical.build_percent, self.tiers.critical.requires_approval)
        }
    }

    /// Check if a path is blocked (with canonicalization to prevent traversal bypass)
    /// FAIL-CLOSED: if canonicalize fails, try parent dir (for new files).
    /// If parent also fails, assume blocked.
    pub fn is_path_blocked(&self, path: &str) -> bool {
        let canonical = match std::fs::canonicalize(path) {
            Ok(p) => p.to_string_lossy().to_string(),
            Err(_) => {
                if path.contains("..") {
                    return true; // Traversal in unresolvable path = always blocked
                }
                // Path doesn't exist yet — try resolving parent directory.
                // Handles new file creation in valid directories (e.g. write to sandbox).
                match std::path::Path::new(path).parent() {
                    Some(parent) => match std::fs::canonicalize(parent) {
                        Ok(p) => {
                            let filename = std::path::Path::new(path)
                                .file_name()
                                .map(|f| f.to_string_lossy().to_string())
                                .unwrap_or_default();
                            format!("{}/{}", p.to_string_lossy(), filename)
                        }
                        Err(_) => return true, // Parent unresolvable = blocked (fail-closed)
                    },
                    None => return true, // No parent = blocked (fail-closed)
                }
            }
        };
        self.blocked_paths.iter().any(|blocked| canonical.starts_with(blocked))
    }

    /// Check if a path is allowed (with canonicalization to prevent traversal bypass)
    /// FAIL-CLOSED: if canonicalize fails, path is NOT allowed. Period.
    /// Cannot confirm path is in an allowed location = deny.
    pub fn is_path_allowed(&self, path: &str) -> bool {
        let canonical = match std::fs::canonicalize(path) {
            Ok(p) => p.to_string_lossy().to_string(),
            Err(_) => {
                // FAIL-CLOSED: unresolvable path is never confirmed allowed.
                // This covers: traversal attacks, symlink tricks, non-existent
                // paths, encoded variants, null bytes — all denied.
                // For new file creation: validate_write uses is_write_allowed()
                // (hardcoded sandbox) as primary check, not this function.
                return false;
            }
        };
        self.allowed_paths.iter().any(|allowed| canonical.starts_with(allowed))
    }
}

// ============================================================================
// HTTP API CONFIGURATION
// ============================================================================

/// HTTP transport configuration — loaded from LIVE/CONFIG/http.json
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpConfig {
    pub transport: String,
    pub port: u16,
    pub bind: String,
    pub tls_enabled: bool,
    pub tls_cert: String,
    pub tls_key: String,
    pub auth_mode: String,
    pub api_key: String,
}

impl Default for HttpConfig {
    fn default() -> Self {
        Self {
            transport: "both".to_string(),
            port: 3900,
            // SEC-4: Default to localhost — external access requires explicit config.
            // Prevents accidental exposure on public interfaces.
            bind: "127.0.0.1".to_string(),
            tls_enabled: true,
            tls_cert: "tls/cert.pem".to_string(),
            tls_key: "tls/key.pem".to_string(),
            auth_mode: "both".to_string(),
            api_key: String::new(),
        }
    }
}

impl HttpConfig {
    /// Load HTTP config from JSON file, falling back to defaults
    pub fn load(path: &Path) -> anyhow::Result<Self> {
        if path.exists() {
            let content = std::fs::read_to_string(path)?;
            let config: Self = serde_json::from_str(&content)?;
            Ok(config)
        } else {
            log::warn!("HTTP config not found at {:?}, using defaults", path);
            Ok(Self::default())
        }
    }
}

// ============================================================================
// MESH CONFIGURATION — Agent identity, role, team, discovery
// ============================================================================

/// Dual-mode role — parsed from mesh.json "role" field.
/// Shared between config.rs (MeshConfig), identity.rs (PeerInfo), and mesh.rs (PeerChannel).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash)]
pub enum AgentRole {
    /// Human-facing director — manages thinkers and workers
    #[serde(rename = "orchestrator")]
    Orchestrator,
    /// Co-problem-solver — shares live context with other thinkers
    #[serde(rename = "thinker")]
    Thinker,
    /// Pure executor — receives tasks, runs them, returns results
    #[serde(rename = "worker")]
    Worker,
}

impl<'de> Deserialize<'de> for AgentRole {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        match s.to_lowercase().as_str() {
            "orchestrator" | "coordinator" | "agent" | "director" => Ok(AgentRole::Orchestrator),
            "thinker" | "problem-solver" => Ok(AgentRole::Thinker),
            "worker" | "executor" => Ok(AgentRole::Worker),
            _ => Ok(AgentRole::Orchestrator), // Unknown role defaults to Orchestrator
        }
    }
}

impl std::fmt::Display for AgentRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AgentRole::Orchestrator => write!(f, "orchestrator"),
            AgentRole::Thinker => write!(f, "thinker"),
            AgentRole::Worker => write!(f, "worker"),
        }
    }
}

impl Default for AgentRole {
    fn default() -> Self { Self::Orchestrator }
}

/// Mesh transport configuration — loaded from LIVE/CONFIG/mesh.json
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeshConfig {
    /// Enable mesh networking
    pub enabled: bool,
    /// Agent's role in the mesh team
    pub role: AgentRole,
    /// Team name this agent belongs to
    pub team: String,
    /// Agent display name (human-readable)
    pub name: String,
    /// Capabilities this agent exposes to mesh peers
    pub capabilities: Vec<String>,
    /// Discovery mode: "auto" (mDNS + DHT), "local" (mDNS only), "manual" (groups only)
    pub discovery: String,
    /// ALPN protocol identifier
    pub alpn: String,
    /// QUIC bind port (0 = random, >0 = fixed — needed for peer JSON addr configs)
    #[serde(default)]
    pub port: u16,
}

impl Default for MeshConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            role: AgentRole::Orchestrator,  // legacy "agent" maps here
            team: "default".to_string(),
            name: String::new(),
            capabilities: vec!["tools".to_string()],
            discovery: "auto".to_string(),
            alpn: "/spf/mesh/1".to_string(),
            port: 0,
        }
    }
}

impl MeshConfig {
    /// Load mesh config from JSON file, falling back to defaults
    pub fn load(path: &Path) -> anyhow::Result<Self> {
        if path.exists() {
            let content = std::fs::read_to_string(path)?;
            let config: Self = serde_json::from_str(&content)?;
            Ok(config)
        } else {
            Ok(Self::default())
        }
    }
}

// ============================================================================
// BLOCK I — TRANSFORMER CONFIGURATION
// Follows MeshConfig pattern: struct + Default + load()
// Loaded from LIVE/CONFIG/transformer.json
// ============================================================================

/// Transformer runtime configuration — loaded from LIVE/CONFIG/transformer.json
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransformerConfig {
    /// Enable transformer runtime
    pub enabled: bool,
    /// Path to writer model checkpoint (relative to LIVE/MODELS/)
    pub writer_checkpoint: String,
    /// Path to researcher model checkpoint (relative to LIVE/MODELS/)
    pub researcher_checkpoint: String,
    /// Model dimension (embedding size)
    pub d_model: usize,
    /// Number of attention heads
    pub n_heads: usize,
    /// Number of transformer layers
    pub n_layers: usize,
    /// Vocabulary size (BPE merge count + special tokens)
    pub vocab_size: usize,
    /// Maximum sequence length
    pub max_seq_len: usize,
    /// Feed-forward hidden dimension (typically 4 × d_model)
    pub d_ff: usize,
    /// Learning rate for online training
    pub learning_rate: f64,
    /// Batch size for training (number of gate signals per batch)
    pub batch_size: usize,
    /// Enable online learning (train while serving)
    pub online_learning: bool,
    /// EWC lambda — elastic weight consolidation strength (0.0 = disabled)
    pub ewc_lambda: f64,
    /// Experience replay buffer size
    pub replay_buffer_size: usize,
    /// Temperature for generation (0.0 = greedy, 1.0 = full sampling)
    pub temperature: f64,
}

impl Default for TransformerConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            writer_checkpoint: "writer_v1.spfc".to_string(),
            researcher_checkpoint: "researcher_v1.spfc".to_string(),
            // SPF Writer/Researcher spec: ~5M params
            d_model: 256,
            n_heads: 8,
            n_layers: 6,
            vocab_size: 8192,
            max_seq_len: 512,
            d_ff: 1024,        // 4 × d_model
            learning_rate: 1e-4,
            batch_size: 32,
            online_learning: true,
            ewc_lambda: 0.4,
            replay_buffer_size: 10000,
            temperature: 0.7,
        }
    }
}

impl TransformerConfig {
    /// Load transformer config from JSON file, falling back to defaults
    pub fn load(path: &Path) -> anyhow::Result<Self> {
        if path.exists() {
            let content = std::fs::read_to_string(path)?;
            let config: Self = serde_json::from_str(&content)?;
            Ok(config)
        } else {
            Ok(Self::default())
        }
    }

    /// Estimated parameter count for this configuration
    /// Rough formula: embedding + (n_layers × (4×d_model² + 2×d_model×d_ff)) + output
    pub fn estimated_params(&self) -> usize {
        let embedding = self.vocab_size * self.d_model;
        let pos_embedding = self.max_seq_len * self.d_model;
        // Per layer: self-attn (4 × d_model²) + cross-attn (4 × d_model²) + FFN (2 × d_model × d_ff) + norms
        let per_layer = 4 * self.d_model * self.d_model   // self-attention Q/K/V/O
            + 4 * self.d_model * self.d_model               // cross-attention Q/K/V/O
            + 2 * self.d_model * self.d_ff                   // FFN w1 + w2
            + 4 * self.d_model;                              // layer norms (approx)
        let output = self.d_model * self.vocab_size;
        embedding + pos_embedding + self.n_layers * per_layer + output
    }

    /// Estimated memory usage in bytes (weights + Adam states)
    /// weights × 4 bytes × 3 (params + momentum + variance)
    pub fn estimated_memory_bytes(&self) -> usize {
        self.estimated_params() * 4 * 3
    }
}

// ============================================================================
// BLOCK NP — NETWORK POOL CONFIGURATION
// Follows MeshConfig/TransformerConfig pattern: struct + Default + load()
// Loaded from LIVE/CONFIG/network.json
// NetAdmin: orchestrates pool, assigns tasks, monitors workers (also does work)
// Worker: accepts assignments from NetAdmin, executes, reports proof of work
// ============================================================================

/// Role of this node in the network pool.
/// NetAdmin orchestrates AND works. Worker accepts assignments only.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum NodeRole {
    NetAdmin,
    Worker,
}

impl Default for NodeRole {
    fn default() -> Self {
        NodeRole::Worker
    }
}

/// A peer node in the network pool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PoolPeer {
    /// Human-readable name (e.g. "ALPHA", "CHARLIE")
    pub name: String,
    /// Ed25519 public key hex — must match team.keys for mesh trust
    pub key_hex: String,
    /// QUIC port the peer listens on
    pub port: u16,
    /// Capabilities this worker exposes (e.g. ["tools", "web", "brain"])
    #[serde(default)]
    pub capabilities: Vec<String>,
}

/// Network pool configuration — loaded from LIVE/CONFIG/network.json
/// Human-editable. One file per node. No recompile needed after changes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkConfig {
    /// This node's role in the pool
    #[serde(default)]
    pub role: NodeRole,
    /// Maximum concurrent workers in pool (hard cap: 8)
    #[serde(default = "default_pool_size")]
    pub pool_size: u8,
    /// Known worker peers — NetAdmin populates this, Workers leave empty
    #[serde(default)]
    pub peers: Vec<PoolPeer>,
}

fn default_pool_size() -> u8 { 8 }

impl Default for NetworkConfig {
    fn default() -> Self {
        Self {
            role: NodeRole::Worker,
            pool_size: 8,
            peers: vec![],
        }
    }
}

impl NetworkConfig {
    /// Load network config from JSON file, falling back to defaults.
    /// Follows MeshConfig.load() pattern exactly.
    pub fn load(path: &Path) -> anyhow::Result<Self> {
        if path.exists() {
            let content = std::fs::read_to_string(path)?;
            let config: Self = serde_json::from_str(&content)?;
            Ok(config)
        } else {
            Ok(Self::default())
        }
    }

    /// True if this node is the NetAdmin orchestrator.
    pub fn is_netadmin(&self) -> bool {
        self.role == NodeRole::NetAdmin
    }

    /// Effective pool size — enforces hard cap of 8 regardless of config value.
    pub fn effective_pool_size(&self) -> u8 {
        self.pool_size.min(8)
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tier_boundaries() {
        let config = SpfConfig::default();

        assert_eq!(config.get_tier(0).0, "SIMPLE");
        assert_eq!(config.get_tier(499).0, "SIMPLE");
        assert_eq!(config.get_tier(500).0, "LIGHT");
        assert_eq!(config.get_tier(1999).0, "LIGHT");
        assert_eq!(config.get_tier(2000).0, "MEDIUM");
        assert_eq!(config.get_tier(9999).0, "MEDIUM");
        assert_eq!(config.get_tier(10000).0, "CRITICAL");
        assert_eq!(config.get_tier(u64::MAX - 1).0, "CRITICAL");
    }

    #[test]
    fn default_formula_exponents() {
        let config = SpfConfig::default();
        assert_eq!(config.formula.basic_power, 1);
        assert_eq!(config.formula.deps_power, 7);
        assert_eq!(config.formula.complex_power, 10);
        assert_eq!(config.formula.files_multiplier, 10);
        assert_eq!(config.formula.w_eff, 40000.0);
    }

    #[test]
    fn default_enforce_mode_is_max() {
        let config = SpfConfig::default();
        assert_eq!(config.enforce_mode, EnforceMode::Max);
    }

    #[test]
    fn blocked_paths_include_system_dirs() {
        let config = SpfConfig::default();
        assert!(config.is_path_blocked("/tmp"));
        assert!(config.is_path_blocked("/tmp/evil.sh"));
        assert!(config.is_path_blocked("/etc/passwd"));
        assert!(config.is_path_blocked("/usr/bin/something"));
    }

    #[test]
    fn default_whitelists_are_empty() {
        let config = SpfConfig::default();
        assert!(config.allowed_commands_user.is_empty(), "User whitelist must default empty (default-deny)");
        assert!(config.allowed_commands_sandbox.is_empty(), "Sandbox whitelist must default empty (default-deny)");
        assert!(config.user_fs_paths.is_empty(), "User FS paths must default empty");
    }

    #[test]
    fn command_perm_constructors() {
        let r = CommandPerm::read_only();
        assert!(r.read && !r.write && !r.execute);

        let rw = CommandPerm::read_write();
        assert!(rw.read && rw.write && !rw.execute);

        let full = CommandPerm::full();
        assert!(full.read && full.write && full.execute);
    }

    // ================================================================
    // BLOCK NN-A — blocked_paths coverage tests
    // ================================================================

    #[test]
    fn blocked_paths_include_claude_configs() {
        let config = SpfConfig::default();
        let home = crate::paths::actual_home().to_string_lossy().to_string();
        // .claude/ directory (pre-existing)
        assert!(config.blocked_paths.contains(&format!("{}/.claude/", home)));
        // BLOCK NN-A additions
        assert!(config.blocked_paths.contains(&format!("{}/.claude.json", home)));
        assert!(config.blocked_paths.contains(&format!("{}/.mcp.json", home)));
        assert!(config.blocked_paths.contains(&format!("{}/.config/anthropic/", home)));
        assert!(config.blocked_paths.contains(&format!("{}/.anthropic/", home)));
    }

    // ================================================================
    // BLOCK SEC-2 — External agent config + CONFIG directory tests
    // ================================================================

    #[test]
    fn blocked_paths_include_agent_config_dirs() {
        let config = SpfConfig::default();
        let home = crate::paths::actual_home().to_string_lossy().to_string();
        let root = crate::paths::spf_root().to_string_lossy().to_string();
        // .qwen/ — home and root level
        assert!(config.blocked_paths.contains(&format!("{}/.qwen/", home)),
            "Home-level .qwen/ must be blocked to prevent config hijack");
        assert!(config.blocked_paths.contains(&format!("{}/.qwen/", root)),
            "Root-level .qwen/ must be blocked to prevent config hijack");
        // .xlaude/ — home and root level
        assert!(config.blocked_paths.contains(&format!("{}/.xlaude/", home)),
            "Home-level .xlaude/ must be blocked");
        assert!(config.blocked_paths.contains(&format!("{}/.xlaude/", root)),
            "Root-level .xlaude/ must be blocked");
    }

    #[test]
    fn blocked_paths_include_config_directory() {
        let config = SpfConfig::default();
        let root = crate::paths::spf_root().to_string_lossy().to_string();
        // LIVE/CONFIG/ directory — protects runtime JSON configs
        assert!(config.blocked_paths.contains(&format!("{}/LIVE/CONFIG/", root)),
            "LIVE/CONFIG/ must be blocked to protect runtime configs (http.json, mesh.json, etc.)");
        // CONFIG.DB — already existed, verify still present
        assert!(config.blocked_paths.contains(&format!("{}/LIVE/CONFIG.DB", root)),
            "CONFIG.DB must remain blocked");
    }

    // ================================================================
    // BLOCK I — TransformerConfig tests
    // ================================================================

    #[test]
    fn transformer_config_defaults() {
        let tc = TransformerConfig::default();
        assert!(!tc.enabled);
        assert_eq!(tc.d_model, 256);
        assert_eq!(tc.n_heads, 8);
        assert_eq!(tc.n_layers, 6);
        assert_eq!(tc.vocab_size, 8192);
        assert_eq!(tc.max_seq_len, 512);
        assert_eq!(tc.d_ff, 1024);
        assert_eq!(tc.batch_size, 32);
        assert!(tc.online_learning);
        assert!((tc.learning_rate - 1e-4).abs() < 1e-10);
        assert!((tc.ewc_lambda - 0.4).abs() < 1e-10);
        assert!((tc.temperature - 0.7).abs() < 1e-10);
    }

    #[test]
    fn transformer_config_param_estimate() {
        let tc = TransformerConfig::default();
        let params = tc.estimated_params();
        assert!(params > 1_000_000, "Should be >1M params, got {}", params);
        assert!(params < 20_000_000, "Should be <20M params, got {}", params);
    }

    #[test]
    fn transformer_config_memory_estimate() {
        let tc = TransformerConfig::default();
        let mem = tc.estimated_memory_bytes();
        let expected = tc.estimated_params() * 12;
        assert_eq!(mem, expected);
        assert!(mem < 500_000_000, "Memory should be <500MB, got {}MB", mem / 1_000_000);
    }

    #[test]
    fn transformer_config_serialize_roundtrip() {
        let tc = TransformerConfig::default();
        let json = serde_json::to_string_pretty(&tc).unwrap();
        let back: TransformerConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(back.d_model, tc.d_model);
        assert_eq!(back.n_heads, tc.n_heads);
        assert_eq!(back.n_layers, tc.n_layers);
        assert_eq!(back.vocab_size, tc.vocab_size);
        assert_eq!(back.enabled, tc.enabled);
        assert!((back.temperature - tc.temperature).abs() < 1e-10);
    }

    #[test]
    fn transformer_config_custom_values() {
        let json = r#"{
            "enabled": true,
            "writer_checkpoint": "custom_writer.spfc",
            "researcher_checkpoint": "custom_research.spfc",
            "d_model": 512,
            "n_heads": 16,
            "n_layers": 12,
            "vocab_size": 16384,
            "max_seq_len": 1024,
            "d_ff": 2048,
            "learning_rate": 3e-4,
            "batch_size": 64,
            "online_learning": false,
            "ewc_lambda": 0.8,
            "replay_buffer_size": 50000,
            "temperature": 1.0
        }"#;
        let tc: TransformerConfig = serde_json::from_str(json).unwrap();
        assert!(tc.enabled);
        assert_eq!(tc.d_model, 512);
        assert_eq!(tc.n_heads, 16);
        assert_eq!(tc.n_layers, 12);
        assert_eq!(tc.d_ff, 2048);
        assert!(!tc.online_learning);
        assert!((tc.learning_rate - 3e-4).abs() < 1e-10);
    }

    // ================================================================
    // BLOCK NP — NetworkConfig tests
    // ================================================================

    #[test]
    fn network_config_default_is_worker() {
        let nc = NetworkConfig::default();
        assert_eq!(nc.role, NodeRole::Worker);
        assert_eq!(nc.pool_size, 8);
        assert!(nc.peers.is_empty());
        assert!(!nc.is_netadmin());
    }

    #[test]
    fn network_config_pool_size_capped_at_8() {
        let mut nc = NetworkConfig::default();
        nc.pool_size = 20;
        assert_eq!(nc.effective_pool_size(), 8);
        nc.pool_size = 4;
        assert_eq!(nc.effective_pool_size(), 4);
        nc.pool_size = 0;
        assert_eq!(nc.effective_pool_size(), 0);
    }

    #[test]
    fn network_config_netadmin_serialize_roundtrip() {
        let json = r#"{
            "role": "netadmin",
            "pool_size": 8,
            "peers": [
                { "name": "ALPHA", "key_hex": "4c327f6d", "port": 4901,
                  "capabilities": ["tools", "web"] }
            ]
        }"#;
        let nc: NetworkConfig = serde_json::from_str(json).unwrap();
        assert_eq!(nc.role, NodeRole::NetAdmin);
        assert!(nc.is_netadmin());
        assert_eq!(nc.peers.len(), 1);
        assert_eq!(nc.peers[0].name, "ALPHA");
        assert_eq!(nc.peers[0].port, 4901);
        assert_eq!(nc.peers[0].capabilities, vec!["tools", "web"]);
    }

    #[test]
    fn network_config_worker_serialize_roundtrip() {
        let json = r#"{"role": "worker", "pool_size": 8, "peers": []}"#;
        let nc: NetworkConfig = serde_json::from_str(json).unwrap();
        assert_eq!(nc.role, NodeRole::Worker);
        assert!(!nc.is_netadmin());
        assert!(nc.peers.is_empty());
    }

    #[test]
    fn network_config_defaults_on_missing_fields() {
        // role and pool_size have serde defaults — partial JSON must still work
        let json = r#"{}"#;
        let nc: NetworkConfig = serde_json::from_str(json).unwrap();
        assert_eq!(nc.role, NodeRole::Worker);
        assert_eq!(nc.pool_size, 8);
        assert!(nc.peers.is_empty());
    }
}