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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// SPF Smart Gateway - Network Pool Management (Block NP)
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Network pool: NetAdmin orchestrates up to 8 workers over iroh QUIC mesh.
// NetAdmin = orchestrator AND Worker-0 (does work locally too).
// Workers accept task assignments, execute, report proof of work back.
//
// Pool is a governance + role-enforcement layer on top of existing mesh.rs
// transport. Tasks flow through Source::Mesh → gate → handle_tool_call.
//
// Architecture:
//   PoolState (Arc<Mutex<Vec<PoolEntry>>>) — shared across all MCP handlers
//   WorkerStatus — Idle | Busy { task_id, since }
//   ProofOfWork  — verifiable receipt: task_id, worker, tool, duration, result_hash
//
// Proof of work receipt is logged to session.record_manifest_detailed():
//   command = task_id, targets = [worker_name, tool, duration_ms as string]
//
// Depends on: config.rs (NetworkConfig, PoolPeer), sha2 + hex (Cargo.toml)

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::sync::{Arc, Mutex};
use std::time::Instant;

use crate::config::PoolPeer;

// ============================================================================
// WORKER STATUS — idle or executing a task
// ============================================================================

/// Current execution status of a pool worker.
#[derive(Debug, Clone)]
pub enum WorkerStatus {
    /// Worker is available to accept a new task.
    Idle,
    /// Worker is executing a task. task_id identifies the active task.
    Busy {
        task_id: String,
        since: Instant,
    },
}

impl WorkerStatus {
    /// Returns true if this worker can accept a new task.
    pub fn is_idle(&self) -> bool {
        matches!(self, WorkerStatus::Idle)
    }

    /// Returns the active task_id if Busy, None if Idle.
    pub fn task_id(&self) -> Option<&str> {
        match self {
            WorkerStatus::Busy { task_id, .. } => Some(task_id.as_str()),
            WorkerStatus::Idle => None,
        }
    }

    /// Elapsed seconds since task was assigned (0 if Idle).
    pub fn elapsed_secs(&self) -> u64 {
        match self {
            WorkerStatus::Busy { since, .. } => since.elapsed().as_secs(),
            WorkerStatus::Idle => 0,
        }
    }
}

// ============================================================================
// POOL ENTRY — one slot in the pool per peer
// ============================================================================

/// A single worker entry in the pool — peer info + current status.
pub struct PoolEntry {
    /// Static peer configuration (name, key_hex, port, capabilities)
    pub peer: PoolPeer,
    /// Current execution status
    pub status: WorkerStatus,
}

// ============================================================================
// POOL STATE — shared across all MCP handlers via Arc<ServerState>
// ============================================================================

/// Shared network pool state. Wrapped in Arc for cross-thread access.
/// One PoolState per NetAdmin node. Workers have no PoolState (pool_state = None).
pub struct PoolState {
    /// Worker entries — one per configured peer
    entries: Mutex<Vec<PoolEntry>>,
    /// Hard cap enforced at assignment time
    pool_size: u8,
}

impl PoolState {
    /// Create a new pool from the peer list in NetworkConfig.
    /// All workers start Idle.
    pub fn new(peers: &[PoolPeer], pool_size: u8) -> Arc<Self> {
        let entries = peers
            .iter()
            .map(|p| PoolEntry {
                peer: p.clone(),
                status: WorkerStatus::Idle,
            })
            .collect();
        Arc::new(Self {
            entries: Mutex::new(entries),
            pool_size: pool_size.min(8),
        })
    }

    /// Snapshot of all workers for spf_pool_status.
    /// Returns: Vec of (name, status_str, Option<task_id>, elapsed_secs)
    pub fn status_snapshot(&self) -> Vec<(String, String, Option<String>, u64)> {
        let entries = self.entries.lock().unwrap();
        entries
            .iter()
            .map(|e| {
                let status_str = if e.status.is_idle() {
                    "idle".to_string()
                } else {
                    "busy".to_string()
                };
                let task_id = e.status.task_id().map(|s| s.to_string());
                let elapsed = e.status.elapsed_secs();
                (e.peer.name.clone(), status_str, task_id, elapsed)
            })
            .collect()
    }

    /// Find the first idle worker. Returns its key_hex, or None if all busy.
    /// Respects pool_size — will not exceed cap.
    pub fn find_idle(&self) -> Option<String> {
        let entries = self.entries.lock().unwrap();
        let busy_count = entries.iter().filter(|e| !e.status.is_idle()).count();
        if busy_count >= self.pool_size as usize {
            return None; // Pool at capacity
        }
        entries
            .iter()
            .find(|e| e.status.is_idle())
            .map(|e| e.peer.key_hex.clone())
    }

    /// Find peer info by key_hex. Returns a clone for use in mesh dispatch.
    pub fn get_peer(&self, key_hex: &str) -> Option<PoolPeer> {
        let entries = self.entries.lock().unwrap();
        entries
            .iter()
            .find(|e| e.peer.key_hex == key_hex)
            .map(|e| e.peer.clone())
    }

    /// Find peer info by name (case-insensitive). Returns key_hex.
    pub fn find_by_name(&self, name: &str) -> Option<String> {
        let entries = self.entries.lock().unwrap();
        entries
            .iter()
            .find(|e| e.peer.name.eq_ignore_ascii_case(name))
            .map(|e| e.peer.key_hex.clone())
    }

    /// Mark a worker as Busy. Fails if already Busy or not found.
    /// Returns Err with reason string on failure.
    pub fn borrow(&self, key_hex: &str, task_id: &str) -> Result<(), String> {
        let mut entries = self.entries.lock().unwrap();
        let busy_count = entries.iter().filter(|e| !e.status.is_idle()).count();
        if busy_count >= self.pool_size as usize {
            return Err(format!(
                "Pool at capacity ({}/{}). No workers available.",
                busy_count, self.pool_size
            ));
        }
        match entries.iter_mut().find(|e| e.peer.key_hex == key_hex) {
            None => Err(format!("Worker not found: {}", key_hex)),
            Some(entry) => {
                if !entry.status.is_idle() {
                    Err(format!(
                        "Worker {} is already busy (task: {})",
                        entry.peer.name,
                        entry.status.task_id().unwrap_or("?")
                    ))
                } else {
                    entry.status = WorkerStatus::Busy {
                        task_id: task_id.to_string(),
                        since: Instant::now(),
                    };
                    Ok(())
                }
            }
        }
    }

    /// Mark a worker as Idle. Called when task completes or fails.
    /// Returns the worker name for logging. Err if not found.
    pub fn release(&self, key_hex: &str) -> Result<String, String> {
        let mut entries = self.entries.lock().unwrap();
        match entries.iter_mut().find(|e| e.peer.key_hex == key_hex) {
            None => Err(format!("Worker not found: {}", key_hex)),
            Some(entry) => {
                let name = entry.peer.name.clone();
                entry.status = WorkerStatus::Idle;
                Ok(name)
            }
        }
    }

    /// How many workers are currently Busy.
    pub fn active_count(&self) -> usize {
        let entries = self.entries.lock().unwrap();
        entries.iter().filter(|e| !e.status.is_idle()).count()
    }

    /// Total configured pool size (hard cap).
    pub fn capacity(&self) -> u8 {
        self.pool_size
    }

    /// How many workers are currently Idle.
    pub fn idle_count(&self) -> usize {
        let entries = self.entries.lock().unwrap();
        entries.iter().filter(|e| e.status.is_idle()).count()
    }
}

// ============================================================================
// PROOF OF WORK — verifiable task completion receipt
// ============================================================================

/// Verifiable receipt produced when a task completes.
/// Logged to session.record_manifest_detailed() for audit trail.
/// result_hash = sha256(JSON result) — deterministic, tamper-evident.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProofOfWork {
    /// Unique task identifier
    pub task_id: String,
    /// Human-readable worker name (e.g. "ALPHA")
    pub worker_name: String,
    /// Worker's Ed25519 public key hex
    pub worker_key: String,
    /// Tool that was executed
    pub tool: String,
    /// When the task was assigned
    pub assigned_at: DateTime<Utc>,
    /// When the task completed
    pub completed_at: DateTime<Utc>,
    /// Wall-clock duration in milliseconds
    pub duration_ms: u64,
    /// SHA-256 hex of the JSON result (tamper-evident receipt)
    pub result_hash: String,
}

impl ProofOfWork {
    /// Build a ProofOfWork receipt from task completion data.
    pub fn new(
        task_id: &str,
        worker_name: &str,
        worker_key: &str,
        tool: &str,
        assigned_at: DateTime<Utc>,
        result: &Value,
    ) -> Self {
        let completed_at = Utc::now();
        let duration_ms = (completed_at - assigned_at)
            .num_milliseconds()
            .max(0) as u64;
        Self {
            task_id: task_id.to_string(),
            worker_name: worker_name.to_string(),
            worker_key: worker_key.to_string(),
            tool: tool.to_string(),
            assigned_at,
            completed_at,
            duration_ms,
            result_hash: hash_result(result),
        }
    }

    /// Format targets slice for session.record_manifest_detailed().
    /// Format: [worker_name, tool, duration_ms]
    pub fn as_manifest_targets(&self) -> Vec<String> {
        vec![
            self.worker_name.clone(),
            self.tool.clone(),
            format!("{}ms", self.duration_ms),
        ]
    }
}

/// SHA-256 hash of a JSON Value for tamper-evident proof of work receipts.
/// Uses canonical JSON (serde_json compact) for determinism.
pub fn hash_result(result: &Value) -> String {
    let json_str = serde_json::to_string(result).unwrap_or_default();
    let mut hasher = Sha256::new();
    hasher.update(json_str.as_bytes());
    hex::encode(hasher.finalize())
}

// ============================================================================
// TASK ASSIGNMENT CONTEXT — tracks an in-flight assignment
// ============================================================================

/// Context for a task currently assigned to a worker.
/// Created by spf_pool_assign, consumed when result returns.
#[derive(Debug, Clone)]
pub struct TaskContext {
    /// Unique task ID (UUID or user-provided)
    pub task_id: String,
    /// Worker key_hex this was assigned to
    pub worker_key: String,
    /// Worker name (human-readable)
    pub worker_name: String,
    /// Tool dispatched to the worker
    pub tool: String,
    /// UTC timestamp of assignment (for duration calculation)
    pub assigned_at: DateTime<Utc>,
}

impl TaskContext {
    /// Create a new task context at assignment time.
    pub fn new(task_id: &str, worker_key: &str, worker_name: &str, tool: &str) -> Self {
        Self {
            task_id: task_id.to_string(),
            worker_key: worker_key.to_string(),
            worker_name: worker_name.to_string(),
            tool: tool.to_string(),
            assigned_at: Utc::now(),
        }
    }

    /// Complete this context into a ProofOfWork receipt.
    pub fn into_proof(self, result: &Value) -> ProofOfWork {
        ProofOfWork::new(
            &self.task_id,
            &self.worker_name,
            &self.worker_key,
            &self.tool,
            self.assigned_at,
            result,
        )
    }
}

// ============================================================================
// TASK ID GENERATION — simple unique IDs without external deps
// ============================================================================

/// Generate a unique task ID using timestamp + thread-local counter.
/// Format: "task-{timestamp_ms}-{counter}"
/// No UUID dependency needed — deterministic and unique within a session.
pub fn new_task_id() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let ts = Utc::now().timestamp_millis();
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("task-{}-{}", ts, n)
}

// ============================================================================
// STARTUP STATUS DISPLAY — NS-1
// Prints clean SPF status once on startup. Re-call on state change.
// Replaces iroh relay WARN spam with a single structured output line.
// ============================================================================

/// Print clean SPF network status to stderr.
/// Call once after pool init in mcp::run(), then again when peer state changes.
/// GREEN ● = active/configured   RED ● = no peers / offline
pub fn log_startup_status(peers: &[PoolPeer], role: &str) {
    let green  = "\x1b[32m●\x1b[0m";
    let red    = "\x1b[31m●\x1b[0m";
    let bold   = "\x1b[1m";
    let reset  = "\x1b[0m";

    eprintln!(
        "[SPFsmartGATE] MESH  {}  {}ROLE: {}{}",
        green, bold, role.to_uppercase(), reset
    );

    if peers.is_empty() {
        eprintln!("[SPFsmartGATE] MESH  {}  NO PEERS CONFIGURED", red);
    } else {
        for peer in peers {
            eprintln!(
                "[SPFsmartGATE] PEER  {}  {} — port:{}",
                green, peer.name, peer.port
            );
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{NetworkConfig, PoolPeer};

    fn make_peer(name: &str, key: &str, port: u16) -> PoolPeer {
        PoolPeer {
            name: name.to_string(),
            key_hex: key.to_string(),
            port,
            capabilities: vec!["tools".to_string()],
        }
    }

    fn make_pool(peers: &[PoolPeer]) -> Arc<PoolState> {
        PoolState::new(peers, 8)
    }

    #[test]
    fn pool_starts_all_idle() {
        let peers = vec![make_peer("ALPHA", "aaa", 4901), make_peer("CHARLIE", "bbb", 4902)];
        let pool = make_pool(&peers);
        assert_eq!(pool.idle_count(), 2);
        assert_eq!(pool.active_count(), 0);
    }

    #[test]
    fn borrow_marks_busy() {
        let peers = vec![make_peer("ALPHA", "aaa", 4901)];
        let pool = make_pool(&peers);
        pool.borrow("aaa", "task-1").unwrap();
        assert_eq!(pool.active_count(), 1);
        assert_eq!(pool.idle_count(), 0);
    }

    #[test]
    fn borrow_already_busy_fails() {
        let peers = vec![make_peer("ALPHA", "aaa", 4901)];
        let pool = make_pool(&peers);
        pool.borrow("aaa", "task-1").unwrap();
        let result = pool.borrow("aaa", "task-2");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("already busy"));
    }

    #[test]
    fn release_marks_idle() {
        let peers = vec![make_peer("ALPHA", "aaa", 4901)];
        let pool = make_pool(&peers);
        pool.borrow("aaa", "task-1").unwrap();
        pool.release("aaa").unwrap();
        assert_eq!(pool.idle_count(), 1);
        assert_eq!(pool.active_count(), 0);
    }

    #[test]
    fn find_idle_returns_first_idle() {
        let peers = vec![make_peer("ALPHA", "aaa", 4901), make_peer("CHARLIE", "bbb", 4902)];
        let pool = make_pool(&peers);
        pool.borrow("aaa", "task-1").unwrap();
        let idle = pool.find_idle().unwrap();
        assert_eq!(idle, "bbb");
    }

    #[test]
    fn find_idle_none_when_all_busy() {
        let peers = vec![make_peer("ALPHA", "aaa", 4901)];
        let pool = make_pool(&peers);
        pool.borrow("aaa", "task-1").unwrap();
        assert!(pool.find_idle().is_none());
    }

    #[test]
    fn pool_size_cap_enforced() {
        // Pool with cap=1, two peers
        let peers = vec![make_peer("ALPHA", "aaa", 4901), make_peer("CHARLIE", "bbb", 4902)];
        let pool = PoolState::new(&peers, 1);
        pool.borrow("aaa", "task-1").unwrap();
        // Should fail even though "bbb" is idle — cap reached
        let result = pool.borrow("bbb", "task-2");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("capacity"));
    }

    #[test]
    fn find_by_name_case_insensitive() {
        let peers = vec![make_peer("ALPHA", "aaa", 4901)];
        let pool = make_pool(&peers);
        assert_eq!(pool.find_by_name("alpha").unwrap(), "aaa");
        assert_eq!(pool.find_by_name("ALPHA").unwrap(), "aaa");
        assert_eq!(pool.find_by_name("Alpha").unwrap(), "aaa");
    }

    #[test]
    fn hash_result_is_deterministic() {
        let v = serde_json::json!({"text": "hello", "count": 42});
        let h1 = hash_result(&v);
        let h2 = hash_result(&v);
        assert_eq!(h1, h2);
        assert_eq!(h1.len(), 64); // SHA-256 hex = 64 chars
    }

    #[test]
    fn proof_of_work_fields_correct() {
        let ctx = TaskContext::new("task-1", "aaa", "ALPHA", "spf_read");
        let result = serde_json::json!({"text": "file contents"});
        let pow = ctx.into_proof(&result);
        assert_eq!(pow.task_id, "task-1");
        assert_eq!(pow.worker_name, "ALPHA");
        assert_eq!(pow.worker_key, "aaa");
        assert_eq!(pow.tool, "spf_read");
        assert_eq!(pow.result_hash.len(), 64);
        assert!(pow.duration_ms < 1000); // Should complete in under 1s
    }

    #[test]
    fn new_task_id_is_unique() {
        let id1 = new_task_id();
        let id2 = new_task_id();
        assert_ne!(id1, id2);
        assert!(id1.starts_with("task-"));
        assert!(id2.starts_with("task-"));
    }

    #[test]
    fn network_config_default_integrates() {
        // Verify NetworkConfig::default() works with PoolState::new
        let config = NetworkConfig::default();
        let pool = PoolState::new(&config.peers, config.effective_pool_size());
        assert_eq!(pool.idle_count(), 0); // No peers in default config
        assert_eq!(pool.capacity(), 8);
    }
}