| |
| |
| |
| |
| |
| |
| |
| |
|
|
| use serde::{Deserialize, Serialize, Deserializer}; |
| use std::path::Path; |
|
|
| |
| #[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>, |
| |
| |
| |
| |
| |
| |
| #[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 { |
| |
| pub w_eff: f64, |
| |
| pub e: f64, |
| |
| 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, |
| } |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| #[derive(Debug, Clone, Copy, Serialize, Deserialize)] |
| pub struct CommandPerm { |
| pub read: bool, |
| pub write: bool, |
| pub execute: bool, |
| } |
|
|
| 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), |
| |
| format!("{}/.claude.json", home), |
| format!("{}/.mcp.json", home), |
| format!("{}/.config/anthropic/", home), |
| format!("{}/.anthropic/", home), |
| |
| |
| |
| |
| format!("{}/.qwen/", home), |
| format!("{}/.qwen/", root), |
| format!("{}/.xlaude/", home), |
| format!("{}/.xlaude/", root), |
| |
| |
| |
| format!("{}/LIVE/CONFIG/", root), |
| |
| 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, |
| deps_power: 7, |
| complex_power: 10, |
| files_multiplier: 10, |
| }, |
| |
| |
| |
| 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(), |
| ], |
| |
| allowed_commands_user: std::collections::HashMap::new(), |
| allowed_commands_sandbox: std::collections::HashMap::new(), |
| user_fs_paths: vec![], |
| } |
| } |
| } |
|
|
| impl SpfConfig { |
| |
| 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()) |
| } |
| } |
|
|
| |
| pub fn save(&self, path: &Path) -> anyhow::Result<()> { |
| let content = serde_json::to_string_pretty(self)?; |
| std::fs::write(path, content)?; |
| Ok(()) |
| } |
|
|
| |
| |
| 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) |
| } |
| } |
|
|
| |
| |
| |
| 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; |
| } |
| |
| |
| 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, |
| }, |
| None => return true, |
| } |
| } |
| }; |
| self.blocked_paths.iter().any(|blocked| canonical.starts_with(blocked)) |
| } |
|
|
| |
| |
| |
| 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(_) => { |
| |
| |
| |
| |
| |
| return false; |
| } |
| }; |
| self.allowed_paths.iter().any(|allowed| canonical.starts_with(allowed)) |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| #[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, |
| |
| |
| 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 { |
| |
| 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()) |
| } |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash)] |
| pub enum AgentRole { |
| |
| #[serde(rename = "orchestrator")] |
| Orchestrator, |
| |
| #[serde(rename = "thinker")] |
| Thinker, |
| |
| #[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), |
| } |
| } |
| } |
|
|
| 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 } |
| } |
|
|
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct MeshConfig { |
| |
| pub enabled: bool, |
| |
| pub role: AgentRole, |
| |
| pub team: String, |
| |
| pub name: String, |
| |
| pub capabilities: Vec<String>, |
| |
| pub discovery: String, |
| |
| pub alpn: String, |
| |
| #[serde(default)] |
| pub port: u16, |
| } |
|
|
| impl Default for MeshConfig { |
| fn default() -> Self { |
| Self { |
| enabled: true, |
| role: AgentRole::Orchestrator, |
| 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 { |
| |
| 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()) |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
|
|
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct TransformerConfig { |
| |
| pub enabled: bool, |
| |
| pub writer_checkpoint: String, |
| |
| pub researcher_checkpoint: String, |
| |
| pub d_model: usize, |
| |
| pub n_heads: usize, |
| |
| pub n_layers: usize, |
| |
| pub vocab_size: usize, |
| |
| pub max_seq_len: usize, |
| |
| pub d_ff: usize, |
| |
| pub learning_rate: f64, |
| |
| pub batch_size: usize, |
| |
| pub online_learning: bool, |
| |
| pub ewc_lambda: f64, |
| |
| pub replay_buffer_size: usize, |
| |
| 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(), |
| |
| d_model: 256, |
| n_heads: 8, |
| n_layers: 6, |
| vocab_size: 8192, |
| max_seq_len: 512, |
| d_ff: 1024, |
| learning_rate: 1e-4, |
| batch_size: 32, |
| online_learning: true, |
| ewc_lambda: 0.4, |
| replay_buffer_size: 10000, |
| temperature: 0.7, |
| } |
| } |
| } |
|
|
| impl TransformerConfig { |
| |
| 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()) |
| } |
| } |
|
|
| |
| |
| pub fn estimated_params(&self) -> usize { |
| let embedding = self.vocab_size * self.d_model; |
| let pos_embedding = self.max_seq_len * self.d_model; |
| |
| let per_layer = 4 * self.d_model * self.d_model |
| + 4 * self.d_model * self.d_model |
| + 2 * self.d_model * self.d_ff |
| + 4 * self.d_model; |
| let output = self.d_model * self.vocab_size; |
| embedding + pos_embedding + self.n_layers * per_layer + output |
| } |
|
|
| |
| |
| pub fn estimated_memory_bytes(&self) -> usize { |
| self.estimated_params() * 4 * 3 |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| #[serde(rename_all = "lowercase")] |
| pub enum NodeRole { |
| NetAdmin, |
| Worker, |
| } |
|
|
| impl Default for NodeRole { |
| fn default() -> Self { |
| NodeRole::Worker |
| } |
| } |
|
|
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct PoolPeer { |
| |
| pub name: String, |
| |
| pub key_hex: String, |
| |
| pub port: u16, |
| |
| #[serde(default)] |
| pub capabilities: Vec<String>, |
| } |
|
|
| |
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct NetworkConfig { |
| |
| #[serde(default)] |
| pub role: NodeRole, |
| |
| #[serde(default = "default_pool_size")] |
| pub pool_size: u8, |
| |
| #[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 { |
| |
| |
| 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()) |
| } |
| } |
|
|
| |
| pub fn is_netadmin(&self) -> bool { |
| self.role == NodeRole::NetAdmin |
| } |
|
|
| |
| pub fn effective_pool_size(&self) -> u8 { |
| self.pool_size.min(8) |
| } |
| } |
|
|
| |
| |
| |
|
|
| #[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); |
| } |
|
|
| |
| |
| |
|
|
| #[test] |
| fn blocked_paths_include_claude_configs() { |
| let config = SpfConfig::default(); |
| let home = crate::paths::actual_home().to_string_lossy().to_string(); |
| |
| assert!(config.blocked_paths.contains(&format!("{}/.claude/", home))); |
| |
| 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))); |
| } |
|
|
| |
| |
| |
|
|
| #[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(); |
| |
| 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"); |
| |
| 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(); |
| |
| assert!(config.blocked_paths.contains(&format!("{}/LIVE/CONFIG/", root)), |
| "LIVE/CONFIG/ must be blocked to protect runtime configs (http.json, mesh.json, etc.)"); |
| |
| assert!(config.blocked_paths.contains(&format!("{}/LIVE/CONFIG.DB", root)), |
| "CONFIG.DB must remain blocked"); |
| } |
|
|
| |
| |
| |
|
|
| #[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); |
| } |
|
|
| |
| |
| |
|
|
| #[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() { |
| |
| 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()); |
| } |
| } |
|
|