SPFsmartGATE / src /config.rs
JosephStoneCellAI's picture
Upload 45 files
1269259 verified
// 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());
}
}