// SPF Smart Gateway - Unified Dispatch Protocol // Copyright 2026 Joseph Stone - All Rights Reserved // // Foundation layer for ALL tool routing. // Every transport (stdio, HTTP, mesh, voice) converges here. // Zero dependencies on pipelines, mesh, or any higher layer. // // REFACTOR: gate::process() called at entry before handle_tool_call. // Gate is the door. handle_tool_call is pure execution — no gate inside. // source from request flows through gate so decisions are source-aware. // // Design: Listener pattern. Layers register as listeners. // dispatch::call() notifies them. Dispatch never imports them. // // BLOCK I ADDITIONS: Source::Transformer, Source::Pipeline variants // BLOCK S ADDITIONS: Timed try_lock, poisoned mutex recovery, SERVER_BUSY response // BLOCK U ADDITIONS: catch_unwind for listeners, blocked param in on_response // FL-1A: Source-aware lock — Stdio=blocking, others=timed try_lock (Block S) // FL-1C: FLINT intercept — pre-execution brain query, post-execution store/enrich use crate::http::ServerState; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::sync::Arc; use std::time::{Duration, Instant}; // ============================================================================ // CONSTANTS // ============================================================================ pub const GATE_BLOCKED: &str = "blocked"; pub const GATE_ALLOWED: &str = "ok"; pub const GATE_BUSY: &str = "busy"; const LOCK_TIMEOUT: Duration = Duration::from_secs(5); const LOCK_RETRY_INTERVAL_MS: u64 = 50; // ============================================================================ // PROTOCOL TYPES // ============================================================================ #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Source { Stdio, Http, Mesh { peer_key: String }, Transformer { role: String, model_id: String }, Pipeline { stream_id: String, peer_key: String }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ToolRequest { pub source: Source, pub tool: String, pub args: Value, pub timestamp: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ToolResponse { pub tool: String, pub result: Value, pub duration_ms: u64, pub status: String, } // ============================================================================ // LISTENER TRAIT // ============================================================================ pub trait DispatchListener: Send + Sync { fn on_request(&self, req: &ToolRequest); fn on_response(&self, req: &ToolRequest, resp: &ToolResponse, blocked: bool); } // ============================================================================ // DISPATCH — gate first, then execution // ============================================================================ /// Unified dispatch. All transports call this. /// Gate fires BEFORE handle_tool_call — gate is the door. /// /// Flow: /// 1. Build request /// 2. Notify listeners (pre-gate observation) /// 3. FLINT intercept (pre-execution — brain context query) /// 4. Acquire session lock (source-aware: Stdio=blocking, others=timed) /// 5. gate::process() — source-aware check /// 6. If blocked → return blocked response /// 7. If allowed → handle_tool_call (pure execution) /// 8. FLINT process result (post-execution — store, enrich) /// 9. Notify listeners with result pub fn call(state: &Arc, source: Source, tool: &str, args: &Value) -> ToolResponse { let start = Instant::now(); let timestamp = chrono::Utc::now().to_rfc3339(); let request = ToolRequest { source, tool: tool.to_string(), args: args.clone(), timestamp, }; // Notify listeners pre-gate (observation of what was attempted) for listener in &state.listeners { if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { listener.on_request(&request); })) { eprintln!("[SPF-DISPATCH] Listener panic on_request for {}: {:?}", tool, e); } } // ── FL-1C: FLINT pre-execution intercept ───────────────────────────────── // Runs BEFORE session lock — brain Mutex is independent, zero contention. // FLINT observes and queries context. Does NOT gate — gate gates. let flint_ctx = crate::flint_memory::flint_intercept(tool, args); // ── FL-1A: Source-aware lock strategy ───────────────────────────────────── // Stdio: blocking lock — MCP protocol has no retry mechanism. // Single-threaded stdin reader, guaranteed to complete. // All others: timed try_lock with Block S timeout + SERVER_BUSY. // Concurrent transports (HTTP, Mesh, Pipeline) need graceful timeout. let session_lock = match &request.source { Source::Stdio => { // Stdio: blocking lock — always succeeds (handles poison) match state.session.lock() { Ok(guard) => Some(guard), Err(poisoned) => { eprintln!("[SPF-DISPATCH] Session mutex poisoned — recovering for {}", tool); Some(poisoned.into_inner()) } } } _ => { // All others: timed try_lock (Block S) — SERVER_BUSY on timeout let mut acquired = None; let lock_start = Instant::now(); loop { match state.session.try_lock() { Ok(guard) => { acquired = Some(guard); break; } Err(std::sync::TryLockError::Poisoned(poisoned)) => { eprintln!("[SPF-DISPATCH] Session mutex poisoned — recovering for {}", tool); acquired = Some(poisoned.into_inner()); break; } Err(std::sync::TryLockError::WouldBlock) => { if lock_start.elapsed() >= LOCK_TIMEOUT { break; } std::thread::sleep(Duration::from_millis(LOCK_RETRY_INTERVAL_MS)); } } } let wait_ms = lock_start.elapsed().as_millis(); if wait_ms > 100 { eprintln!("[SPF-DISPATCH] Session lock contention — {} waited {}ms", tool, wait_ms); } acquired } }; // If lock timed out → SERVER_BUSY let mut session = match session_lock { Some(guard) => guard, None => { let elapsed = start.elapsed().as_millis() as u64; eprintln!("[SPF-DISPATCH] SESSION_BUSY — {} timed out after {}ms", tool, elapsed); let response = ToolResponse { tool: tool.to_string(), result: serde_json::json!({ "type": "text", "text": "SERVER_BUSY: Session locked by another transport. Try again." }), duration_ms: elapsed, status: GATE_BUSY.to_string(), }; for listener in &state.listeners { if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { listener.on_response(&request, &response, false); })) { eprintln!("[SPF-DISPATCH] Listener panic on_response for {}: {:?}", tool, e); } } return response; } }; // ── GATE ENTRY — fires before any execution ─────────────────────────────── let entry_params = crate::mcp::extract_gate_params(args); let gate_decision = crate::gate::process( tool, &entry_params, &state.config, &*session, &request.source ); let result = if !gate_decision.allowed { // Blocked — record and return immediately, no execution session.record_manifest(tool, gate_decision.complexity.c, "BLOCKED", gate_decision.errors.first().map(|s| s.as_str())); let _ = state.storage.save_session(&session); serde_json::json!({ "type": "text", "text": gate_decision.message, "_blocked": true }) } else { // Allowed — execute through handle_tool_call (pure execution, no gate inside) crate::mcp::handle_tool_call( tool, args, request.source.clone(), &gate_decision, &state.config, &mut session, &state.storage, &state.config_db, &state.tmp_db, &state.fs_db, &state.agent_db, &state.pub_key_hex, &state.mesh_tx, &state.peers, &state.transformer, &state.transformer_config, &state.network_config, &state.pool_state, &state.pipeline, &state.browser, &state.ws_browser_channels, state.http_port, &state.tracked_peers, &state.orchestrator_state, &state.endpoint, &state.tokio_handle, ) }; drop(session); // ── FL-1C: FLINT post-execution processing ─────────────────────────────── // Runs AFTER session lock dropped — stores high-value results, enriches. // Brain and agent_state locks are independent — zero contention. let result = crate::flint_memory::flint_process_result( tool, &result, &flint_ctx, &state.agent_db ); let duration_ms = start.elapsed().as_millis() as u64; let blocked = result.get("_blocked").and_then(|v| v.as_bool()).unwrap_or(false); let status = if blocked { GATE_BLOCKED } else { GATE_ALLOWED }; let response = ToolResponse { tool: tool.to_string(), result, duration_ms, status: status.to_string(), }; // Notify listeners with result for listener in &state.listeners { if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { listener.on_response(&request, &response, blocked); })) { eprintln!("[SPF-DISPATCH] Listener panic on_response for {}: {:?}", tool, e); } } response } // ============================================================================ // TESTS // ============================================================================ #[cfg(test)] mod tests { use super::*; #[test] fn lock_constants_valid() { assert!(LOCK_TIMEOUT.as_secs() > 0, "LOCK_TIMEOUT must be positive"); assert!(LOCK_RETRY_INTERVAL_MS > 0, "LOCK_RETRY_INTERVAL_MS must be positive"); let attempts = LOCK_TIMEOUT.as_millis() / LOCK_RETRY_INTERVAL_MS as u128; assert!(attempts >= 10, "Should attempt at least 10 retries, got {}", attempts); assert!(attempts <= 500, "Should not exceed 500 retries, got {}", attempts); } #[test] fn busy_response_structure() { let response = ToolResponse { tool: "spf_read".to_string(), result: serde_json::json!({ "type": "text", "text": "SERVER_BUSY: Session locked by another transport. Try again." }), duration_ms: 5001, status: "busy".to_string(), }; assert_eq!(response.status, "busy"); assert_eq!(response.tool, "spf_read"); let text = response.result["text"].as_str().unwrap(); assert!(text.starts_with("SERVER_BUSY:")); } #[test] fn source_variants_serialize() { let stdio = Source::Stdio; let json = serde_json::to_string(&stdio).unwrap(); assert!(json.contains("Stdio")); let http = Source::Http; let json = serde_json::to_string(&http).unwrap(); assert!(json.contains("Http")); let mesh = Source::Mesh { peer_key: "abc123".to_string() }; let json = serde_json::to_string(&mesh).unwrap(); assert!(json.contains("abc123")); let transformer = Source::Transformer { role: "writer".to_string(), model_id: "spf_writer_v1".to_string(), }; let json = serde_json::to_string(&transformer).unwrap(); assert!(json.contains("writer")); assert!(json.contains("spf_writer_v1")); let pipeline = Source::Pipeline { stream_id: "stream_001".to_string(), peer_key: "peer_abc".to_string(), }; let json = serde_json::to_string(&pipeline).unwrap(); assert!(json.contains("stream_001")); assert!(json.contains("peer_abc")); } #[test] fn source_variants_deserialize_roundtrip() { let transformer = Source::Transformer { role: "researcher".to_string(), model_id: "spf_researcher_v1".to_string(), }; let json = serde_json::to_string(&transformer).unwrap(); let back: Source = serde_json::from_str(&json).unwrap(); match back { Source::Transformer { role, model_id } => { assert_eq!(role, "researcher"); assert_eq!(model_id, "spf_researcher_v1"); } _ => panic!("Expected Source::Transformer"), } let pipeline = Source::Pipeline { stream_id: "s42".to_string(), peer_key: "pk99".to_string(), }; let json = serde_json::to_string(&pipeline).unwrap(); let back: Source = serde_json::from_str(&json).unwrap(); match back { Source::Pipeline { stream_id, peer_key } => { assert_eq!(stream_id, "s42"); assert_eq!(peer_key, "pk99"); } _ => panic!("Expected Source::Pipeline"), } } #[test] fn original_variants_unchanged() { let sources = vec![ Source::Stdio, Source::Http, Source::Mesh { peer_key: "key".to_string() }, ]; for src in sources { let json = serde_json::to_string(&src).unwrap(); let _back: Source = serde_json::from_str(&json).unwrap(); // If this compiles and runs, existing variants still work } } #[test] fn tool_request_with_new_sources() { let req = ToolRequest { source: Source::Transformer { role: "writer".to_string(), model_id: "v1".to_string(), }, tool: "spf_read".to_string(), args: serde_json::json!({"file_path": "/test"}), timestamp: "2026-02-28T00:00:00Z".to_string(), }; let json = serde_json::to_string(&req).unwrap(); let back: ToolRequest = serde_json::from_str(&json).unwrap(); assert_eq!(back.tool, "spf_read"); match back.source { Source::Transformer { role, .. } => assert_eq!(role, "writer"), _ => panic!("Wrong source variant"), } } // ====== BLOCK U TESTS — Listener registration, panic safety, blocked status ====== use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; struct MockListener { request_count: AtomicU32, response_count: AtomicU32, last_blocked: AtomicBool, } impl MockListener { fn new() -> Self { Self { request_count: AtomicU32::new(0), response_count: AtomicU32::new(0), last_blocked: AtomicBool::new(false), } } } impl DispatchListener for MockListener { fn on_request(&self, _req: &ToolRequest) { self.request_count.fetch_add(1, Ordering::SeqCst); } fn on_response(&self, _req: &ToolRequest, _resp: &ToolResponse, blocked: bool) { self.response_count.fetch_add(1, Ordering::SeqCst); self.last_blocked.store(blocked, Ordering::SeqCst); } } struct PanicListener; impl DispatchListener for PanicListener { fn on_request(&self, _req: &ToolRequest) { panic!("PanicListener intentional panic on request"); } fn on_response(&self, _req: &ToolRequest, _resp: &ToolResponse, _blocked: bool) { panic!("PanicListener intentional panic on response"); } } #[test] fn listener_receives_pre_and_post() { let listener = MockListener::new(); let req = ToolRequest { source: Source::Stdio, tool: "spf_read".to_string(), args: serde_json::json!({}), timestamp: "2026-02-28T00:00:00Z".to_string(), }; let resp = ToolResponse { tool: "spf_read".to_string(), result: serde_json::json!({"type": "text", "text": "ok"}), duration_ms: 10, status: GATE_ALLOWED.to_string(), }; // Simulate dispatch calling on_request then on_response listener.on_request(&req); listener.on_response(&req, &resp, false); assert_eq!(listener.request_count.load(Ordering::SeqCst), 1); assert_eq!(listener.response_count.load(Ordering::SeqCst), 1); assert!(!listener.last_blocked.load(Ordering::SeqCst)); } #[test] fn listener_panic_does_not_crash() { let listener = PanicListener; let req = ToolRequest { source: Source::Stdio, tool: "spf_read".to_string(), args: serde_json::json!({}), timestamp: "2026-02-28T00:00:00Z".to_string(), }; let resp = ToolResponse { tool: "spf_read".to_string(), result: serde_json::json!({"type": "text", "text": "ok"}), duration_ms: 10, status: GATE_ALLOWED.to_string(), }; // catch_unwind should prevent crash — exactly as dispatch::call() does let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { listener.on_request(&req); })); assert!(result.is_err(), "Panic should be caught on request"); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { listener.on_response(&req, &resp, false); })); assert!(result.is_err(), "Panic should be caught on response"); // Test passes = server didn't crash } #[test] fn listener_receives_blocked_status() { let listener = MockListener::new(); let req = ToolRequest { source: Source::Http, tool: "spf_write".to_string(), args: serde_json::json!({"file_path": "/etc/passwd"}), timestamp: "2026-02-28T00:00:00Z".to_string(), }; // Gate-blocked response let blocked_resp = ToolResponse { tool: "spf_write".to_string(), result: serde_json::json!({"type": "text", "text": "BLOCKED: path not allowed", "_blocked": true}), duration_ms: 5, status: GATE_BLOCKED.to_string(), }; listener.on_response(&req, &blocked_resp, true); assert!(listener.last_blocked.load(Ordering::SeqCst), "Listener should receive blocked=true"); // Gate-allowed response let allowed_resp = ToolResponse { tool: "spf_read".to_string(), result: serde_json::json!({"type": "text", "text": "file contents"}), duration_ms: 12, status: GATE_ALLOWED.to_string(), }; listener.on_response(&req, &allowed_resp, false); assert!(!listener.last_blocked.load(Ordering::SeqCst), "Listener should receive blocked=false"); } }