limitless-cli 1.0.0

A beginner-friendly environment diagnostic tool
Documentation
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
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
//! Port watcher for Limitless CLI.
//!
//! Detects which well-known development ports are already occupied and
//! resolves each one to a PID and a process name. Results are cached for a
//! short TTL because listening sockets do not change rapidly.
//!
//! # Platform strategy
//!
//! - **Windows** — a single `netstat -ano` scan finds `LISTENING` sockets,
//!   then one `tasklist /FO CSV /NH` call maps PIDs to process names.
//! - **Linux/macOS** — a single `lsof -iTCP -sTCP:LISTEN -P -n` scan returns
//!   command, PID and port together. On Linux this falls back to parsing
//!   `/proc/net/tcp{,6}` (ports only) when `lsof` is missing.
//! - **Fallback** — if the command-line scan produces nothing (for example
//!   due to a permission error), the requested ports are probed in parallel
//!   with a bind attempt, reporting PID/name as unknown.

use std::collections::HashMap;
use std::net::TcpListener;
use std::process::Command;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};

use crate::models::{CheckStatus, DiagnosticResult};

/// Ports most commonly used by dev servers and debuggers.
pub const DEFAULT_DEV_PORTS: &[u16] = &[3000, 5000, 8000, 8080, 9000];

/// Ports whose occupation blocks infrastructure (databases, web services).
pub const CRITICAL_PORTS: &[u16] = &[80, 443, 5432, 3306, 27017];

/// How long a scan result stays fresh before the watcher re-scans.
pub const CACHE_TTL: Duration = Duration::from_secs(30);

// ---------------------------------------------------------------------------
// Status classification
// ---------------------------------------------------------------------------

/// A blocked port is a hard failure when it is a known infrastructure port
/// or a privileged port (< 1024); otherwise it is a warning.
pub fn status_for_port(port: u16) -> CheckStatus {
    if CRITICAL_PORTS.contains(&port) || port < 1024 {
        CheckStatus::Fail
    } else {
        CheckStatus::Warn
    }
}

// ---------------------------------------------------------------------------
// Platform parsers (pure, unit-testable)
// ---------------------------------------------------------------------------

/// Parses `netstat -ano` output, returning `(port, pid)` for every
/// `LISTENING` TCP socket. Non-listening and non-TCP lines are ignored.
///
/// ```
/// use limitless_cli::modules::port_watcher::parse_netstat;
/// let netstat = "\
///   TCP    0.0.0.0:3000          0.0.0.0:0              LISTENING       9921
///   TCP    127.0.0.1:8080        0.0.0.0:0              LISTENING       12345
///   TCP    [::]:135              0.0.0.0:0              LISTENING       1234
///   TCP    127.0.0.1:50001       0.0.0.0:0              ESTABLISHED     55
/// ";
/// let found = parse_netstat(netstat);
/// assert!(found.contains(&(3000, 9921)));
/// assert!(!found.into_iter().any(|(port, _)| port == 50001));
/// ```
pub fn parse_netstat(output: &str) -> Vec<(u16, u32)> {
    let mut out = Vec::new();
    for line in output.lines() {
        let upper = line.to_ascii_uppercase();
        if !(upper.contains("LISTENING") || upper.contains("LISTEN")) {
            continue;
        }
        let fields: Vec<&str> = line.split_whitespace().collect();
        let Some(local) = fields.iter().find(|f| f.contains(':')) else {
            continue;
        };
        let Some(port) = local.rsplit(':').next().and_then(|s| s.parse::<u16>().ok()) else {
            continue;
        };
        let Some(pid) = fields.last().and_then(|s| s.parse::<u32>().ok()) else {
            continue;
        };
        out.push((port, pid));
    }
    out.sort_unstable();
    out.dedup();
    out
}

/// Splits a quoted CSV row such as `"node.exe","9921","Console","1","30,292 K"`.
fn parse_csv_row(line: &str) -> Vec<String> {
    let mut fields = Vec::new();
    let mut current = String::new();
    let mut in_quotes = false;
    for ch in line.chars() {
        match ch {
            '"' => in_quotes = !in_quotes,
            ',' if !in_quotes => {
                fields.push(current.trim().to_string());
                current.clear();
            }
            other => current.push(other),
        }
    }
    fields.push(current.trim().to_string());
    fields
}

/// Parses `tasklist /FO CSV /NH` output into a `pid -> process name` map.
///
/// ```
/// use limitless_cli::modules::port_watcher::parse_tasklist;
/// let tasks = "\
/// \"node.exe\",\"9921\",\"Console\",\"1\",\"30,292 K\"
/// \"python.exe\",\"12345\",\"Console\",\"1\",\"11,240 K\"
/// ";
/// let names = parse_tasklist(tasks);
/// assert_eq!(names.get(&9921).map(String::as_str), Some("node.exe"));
/// assert_eq!(names.get(&12345).map(String::as_str), Some("python.exe"));
/// ```
pub fn parse_tasklist(output: &str) -> HashMap<u32, String> {
    let mut names = HashMap::new();
    for line in output.lines() {
        let fields = parse_csv_row(line);
        if !line.starts_with('"') || fields.len() < 2 {
            continue;
        }
        let (name, pid) = (
            fields[0].trim_matches('"').to_string(),
            fields[1].trim_matches('"'),
        );
        if let Ok(pid) = pid.parse::<u32>() {
            names.insert(pid, name);
        }
    }
    names
}

/// Parses `lsof -iTCP -sTCP:LISTEN -P -n` output, returning
/// `(port, pid, command)` triples.
///
/// ```
/// use limitless_cli::modules::port_watcher::parse_lsof;
/// let lsof = "\
/// COMMAND     PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
/// node      9921 aseem   21u  IPv4 12345      0t0  TCP *:3000 (LISTEN)
/// python    12345 aseem   22u  IPv6 67890      0t0  TCP [::]:8080 (LISTEN)
/// bash       7777 aseem    4u  IPv4 11111      0t0  TCP 127.0.0.1:5432 (LISTEN)
/// ";
/// let found = parse_lsof(lsof);
/// assert!(found.contains(&(3000, 9921, "node".to_string())));
/// assert!(found.contains(&(8080, 12345, "python".to_string())));
/// ```
pub fn parse_lsof(output: &str) -> Vec<(u16, u32, String)> {
    let mut out = Vec::new();
    for line in output.lines() {
        let fields: Vec<&str> = line.split_whitespace().collect();
        if fields.len() < 2 {
            continue;
        }
        let Ok(pid) = fields[1].parse::<u32>() else {
            continue; // header or informational line
        };
        let command = fields[0].to_string();
        let Some(port) = fields.iter().rev().find_map(|field| {
            field
                .rsplit(':')
                .next()
                .and_then(|s| s.trim_end_matches("(LISTEN)").parse::<u16>().ok())
        }) else {
            continue;
        };
        out.push((port, pid, command));
    }
    out.sort_unstable_by_key(|(port, _, _)| *port);
    out.dedup();
    out
}

/// Parses `/proc/net/tcp` / `/proc/net/tcp6` output, returning occupied
/// ports for sockets in listening state. Format is hex encoded:
/// `local_address` like `0100007F:0BB8` (port 0x0BB8 = 3000), `st` `0A` is
/// `LISTEN`. PIDs are not recoverable from these files, so callers that use
/// this fallback report pid `0` / `unknown`.
///
/// ```
/// use limitless_cli::modules::port_watcher::parse_proc_net_tcp;
/// let tcp = "\
///   sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
///     0: 0100007F:0BB8 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 12345 1 0000000000000000 100 0 0 10 0
///     1: 0100007F:D940 0100007F:0BB8 01 00000000:00000000 00:00000000 00000000     0        0 54321 1 0000000000000000 20 4 30 10 -1
/// ";
/// let found = parse_proc_net_tcp(tcp);
/// assert_eq!(found, vec![3000]);
/// ```
pub fn parse_proc_net_tcp(output: &str) -> Vec<u16> {
    let mut out = Vec::new();
    for line in output.lines() {
        let fields: Vec<&str> = line.split_whitespace().collect();
        if fields.len() < 4 {
            continue;
        }
        if fields[3] != "0A" {
            continue; // only LISTEN state
        }
        let Some((_, hex_port)) = fields[1].rsplit_once(':') else {
            continue;
        };
        if let Ok(port) = u16::from_str_radix(hex_port, 16) {
            out.push(port);
        }
    }
    out.sort_unstable();
    out.dedup();
    out
}

// ---------------------------------------------------------------------------
// Platform scans
// ---------------------------------------------------------------------------

#[cfg(target_os = "windows")]
fn platform_command_scan() -> Vec<(u16, u32, String)> {
    let output = match Command::new("netstat").arg("-ano").output() {
        Ok(output) => output,
        Err(_) => return Vec::new(),
    };
    if !output.status.success() {
        return Vec::new();
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let listening = parse_netstat(&text);
    if listening.is_empty() {
        return Vec::new();
    }

    let names = match Command::new("tasklist")
        .args(["/FO", "CSV", "/NH"])
        .output()
    {
        Ok(output) => parse_tasklist(&String::from_utf8_lossy(&output.stdout)),
        Err(_) => HashMap::new(),
    };

    listening
        .into_iter()
        .map(|(port, pid)| {
            let raw_name = names
                .get(&pid)
                .cloned()
                .unwrap_or_else(|| "unknown".to_string());
            let name = raw_name
                .strip_suffix(".exe")
                .unwrap_or(&raw_name)
                .to_string();
            (port, pid, name)
        })
        .collect()
}

#[cfg(any(target_os = "macos", target_os = "freebsd"))]
fn platform_command_scan() -> Vec<(u16, u32, String)> {
    let output = match Command::new("lsof")
        .args(["-iTCP", "-sTCP:LISTEN", "-P", "-n"])
        .output()
    {
        Ok(output) => output,
        Err(_) => return Vec::new(),
    };
    if !output.status.success() {
        return Vec::new();
    }
    parse_lsof(&String::from_utf8_lossy(&output.stdout))
}

#[cfg(target_os = "linux")]
fn platform_command_scan() -> Vec<(u16, u32, String)> {
    use std::fs;

    let lsof = Command::new("lsof")
        .args(["-iTCP", "-sTCP:LISTEN", "-P", "-n"])
        .output();
    if let Ok(output) = lsof {
        if output.status.success() {
            let found = parse_lsof(&String::from_utf8_lossy(&output.stdout));
            if !found.is_empty() {
                return found;
            }
        }
    }

    // Fallback: /proc/net/tcp does not leak PIDs, so report unknown.
    let mut ports = Vec::new();
    for proc in ["/proc/net/tcp", "/proc/net/tcp6"] {
        if let Ok(text) = fs::read_to_string(proc) {
            ports.extend(parse_proc_net_tcp(&text));
        }
    }
    ports
        .into_iter()
        .map(|port| (port, 0, "unknown".to_string()))
        .collect()
}

/// Detects whether a single port is already taken via a bind attempt.
pub fn is_port_in_use(port: u16) -> bool {
    TcpListener::bind(("127.0.0.1", port)).is_err()
}

/// Probes several ports in parallel with bind attempts, returning the
/// occupied ones. Used when the command-line scan yields no results, so
/// detection still works under permission errors.
fn parallel_in_use(ports: &[u16]) -> Vec<u16> {
    let shared: Mutex<Vec<u16>> = Mutex::new(Vec::new());
    std::thread::scope(|scope| {
        for chunk in ports.chunks(4) {
            let chunk = chunk.to_vec();
            let shared = &shared;
            scope.spawn(move || {
                let found: Vec<u16> = chunk
                    .into_iter()
                    .filter(|port| is_port_in_use(*port))
                    .collect();
                shared.lock().unwrap().extend(found);
            });
        }
    });
    shared.into_inner().unwrap()
}

/// Full platform scan with a bind-probe fallback for empty results.
fn platform_scan() -> Vec<(u16, u32, String)> {
    let scanned = platform_command_scan();
    if scanned.is_empty() {
        parallel_in_use(DEFAULT_DEV_PORTS)
            .into_iter()
            .map(|port| (port, 0, "unknown".to_string()))
            .collect()
    } else {
        scanned
    }
}

// ---------------------------------------------------------------------------
// Cache-backed watcher
// ---------------------------------------------------------------------------

/// A single blocked port with its classification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortStatus {
    pub port: u16,
    pub pid: u32,
    pub process_name: String,
    pub status: CheckStatus,
}

struct CachedEntry {
    pid: u32,
    process_name: String,
}

/// A `PortWatcher` caches listening-socket scans for a short TTL and can be
/// injected with a mock scanner in tests.
pub struct PortWatcher {
    /// Occupied ports discovered by the last scan.
    cache: Mutex<HashMap<u16, CachedEntry>>,
    /// Freshness stamp for every port the watcher has checked, whether it
    /// turned out to be occupied or free.
    observed: Mutex<HashMap<u16, Instant>>,
    ttl: Duration,
    scanner: Box<dyn Fn() -> Vec<(u16, u32, String)> + Send + Sync>,
}

fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

impl PortWatcher {
    /// A watcher using the real platform scan and the default TTL.
    pub fn new() -> Self {
        Self {
            cache: Mutex::new(HashMap::new()),
            observed: Mutex::new(HashMap::new()),
            ttl: CACHE_TTL,
            scanner: Box::new(platform_scan),
        }
    }

    /// A watcher with an explicit scan function (used by tests).
    pub fn with_scanner(
        ttl: Duration,
        scanner: Box<dyn Fn() -> Vec<(u16, u32, String)> + Send + Sync>,
    ) -> Self {
        Self {
            cache: Mutex::new(HashMap::new()),
            observed: Mutex::new(HashMap::new()),
            ttl,
            scanner,
        }
    }

    /// Clears all cached results, forcing a re-scan on the next call.
    pub fn clear(&self) {
        lock(&self.cache).clear();
        lock(&self.observed).clear();
    }

    /// Returns [`PortStatus`] for every requested port that is occupied,
    /// re-scanning when any requested port is missing or stale.
    pub fn check(&self, ports_to_check: &[u16]) -> Vec<PortStatus> {
        let now = Instant::now();
        let stale = {
            let observed = lock(&self.observed);
            ports_to_check.iter().any(|port| {
                observed
                    .get(port)
                    .is_none_or(|checked_at| now.duration_since(*checked_at) >= self.ttl)
            })
        };

        if stale {
            let scan = (self.scanner)();
            let mut cache = lock(&self.cache);
            let mut observed = lock(&self.observed);
            for port in ports_to_check {
                cache.remove(port);
                observed.insert(*port, now);
            }
            for (port, pid, process_name) in scan {
                observed.insert(port, now);
                cache.insert(port, CachedEntry { pid, process_name });
            }
        }

        let cache = lock(&self.cache);
        ports_to_check
            .iter()
            .filter_map(|port| {
                cache.get(port).map(|entry| PortStatus {
                    port: *port,
                    pid: entry.pid,
                    process_name: entry.process_name.clone(),
                    status: status_for_port(*port),
                })
            })
            .collect()
    }

    /// Convenience wrapper returning `(port, pid, process_name)` triples.
    pub fn find_blocked(&self, ports_to_check: &[u16]) -> Vec<(u16, u32, String)> {
        self.check(ports_to_check)
            .into_iter()
            .map(|status| (status.port, status.pid, status.process_name))
            .collect()
    }
}

impl Default for PortWatcher {
    fn default() -> Self {
        Self::new()
    }
}

fn default_watcher() -> &'static PortWatcher {
    static WATCHER: OnceLock<PortWatcher> = OnceLock::new();
    WATCHER.get_or_init(PortWatcher::new)
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Returns `(port, pid, process_name)` for every checked port that is
/// occupied, using a process-wide cached scan.
pub fn check_blocked_ports(ports_to_check: &[u16]) -> Vec<(u16, u32, String)> {
    default_watcher().find_blocked(ports_to_check)
}

/// Returns `(port, pid)` pairs (PID/name resolution preserved internally)
/// for every occupied port. Kept for tools that only need numbers.
pub fn find_blocked_ports(ports_to_check: &[u16]) -> Vec<(u16, u32)> {
    check_blocked_ports(ports_to_check)
        .into_iter()
        .map(|(port, pid, _)| (port, pid))
        .collect()
}

/// Platform-appropriate remediation for an occupied port.
pub fn port_remediation(port: u16, pid: u32) -> String {
    let kill = if cfg!(windows) {
        format!("taskkill /PID {pid} /F")
    } else {
        format!("kill {pid}")
    };
    format!(
        "Stop the process (e.g. `{kill}`), or configure your app to use another port (e.g. PORT={port})"
    )
}

/// Builds a [`DiagnosticResult`] for one blocked port. The status is
/// [`CheckStatus::Fail`] for critical/privileged ports, otherwise
/// [`CheckStatus::Warn`].
///
/// ```
/// use limitless_cli::models::CheckStatus;
/// use limitless_cli::modules::port_watcher::diagnostic_for;
///
/// let d = diagnostic_for(3000, 9921, "node");
/// assert_eq!(d.check_name, "Port 3000");
/// assert_eq!(d.status, CheckStatus::Warn);
/// assert!(d.message.contains("PID 9921 (node)"));
/// assert!(d.remediation.is_some());
/// ```
pub fn diagnostic_for(port: u16, pid: u32, process_name: &str) -> DiagnosticResult {
    let display = if process_name.trim().is_empty() {
        "unknown process"
    } else {
        process_name
    };
    DiagnosticResult::new(
        format!("Port {port}"),
        status_for_port(port),
        format!("Port {port} is occupied by PID {pid} ({display})"),
    )
    .with_remediation(port_remediation(port, pid))
}

/// One [`DiagnosticResult`] per occupied port in `ports_to_check`.
pub fn blocked_port_results(ports_to_check: &[u16]) -> Vec<DiagnosticResult> {
    check_blocked_ports(ports_to_check)
        .into_iter()
        .map(|(port, pid, process_name)| diagnostic_for(port, pid, &process_name))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    // --- Parsers ----------------------------------------------------------

    #[test]
    fn parse_netstat_extracts_port_and_pid() {
        let netstat = "\
  TCP    0.0.0.0:3000          0.0.0.0:0              LISTENING       9921
  TCP    127.0.0.1:8080        0.0.0.0:0              LISTENING       12345
  TCP    [::]:135              0.0.0.0:0              LISTENING       1234
  UDP    0.0.0.0:137           *:*                                   65500
";
        let found = parse_netstat(netstat);
        assert_eq!(found, vec![(135, 1234), (3000, 9921), (8080, 12345)]);
    }

    #[test]
    fn parse_netstat_ignores_non_listening() {
        let netstat = "\
  TCP    127.0.0.1:50001       0.0.0.0:0              ESTABLISHED     55
  TCP    127.0.0.1:50002       0.0.0.0:0              TIME_WAIT       0
";
        assert!(parse_netstat(netstat).is_empty());
    }

    #[test]
    fn parse_tasklist_maps_pids_to_names() {
        let tasks = "\
\"node.exe\",\"9921\",\"Console\",\"1\",\"30,292 K\"
\"python.exe\",\"12345\",\"Console\",\"1\",\"11,240 K\"
INFO: No tasks are running
";
        let names = parse_tasklist(tasks);
        assert_eq!(names.get(&9921).map(String::as_str), Some("node.exe"));
        assert_eq!(names.get(&12345).map(String::as_str), Some("python.exe"));
        assert_eq!(names.len(), 2);
    }

    #[test]
    fn parse_lsof_extracts_command_pid_and_port() {
        let lsof = "\
COMMAND     PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node      9921 aseem   21u  IPv4 12345      0t0  TCP *:3000 (LISTEN)
python    12345 aseem   22u  IPv6 67890      0t0  TCP [::]:8080 (LISTEN)
bash       7777 aseem    4u  IPv4 11111      0t0  TCP 127.0.0.1:5432 (LISTEN)
";
        let found = parse_lsof(lsof);
        assert!(found.contains(&(3000, 9921, "node".to_string())));
        assert!(found.contains(&(8080, 12345, "python".to_string())));
        assert!(found.contains(&(5432, 7777, "bash".to_string())));
        assert_eq!(found.len(), 3);
    }

    #[test]
    fn parse_proc_net_tcp_keeps_only_listening_hex_ports() {
        let tcp = "\
  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
    0: 0100007F:0BB8 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 12345 1 0000000000000000 100 0 0 10 0
    1: 0100007F:D940 0100007F:0BB8 01 00000000:00000000 00:00000000 00000000     0        0 54321 1 0000000000000000 20 4 30 10 -1
    2: 0100007F:1388 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 99999 1 0000000000000000 100 0 0 10 0
";
        assert_eq!(parse_proc_net_tcp(tcp), vec![3000, 5000]);
    }

    // --- Status classification ---------------------------------------------

    #[test]
    fn status_classifies_critical_and_privileged_fail() {
        assert_eq!(status_for_port(3000), CheckStatus::Warn);
        assert_eq!(status_for_port(5432), CheckStatus::Fail);
        assert_eq!(status_for_port(443), CheckStatus::Fail);
        assert_eq!(status_for_port(80), CheckStatus::Fail);
    }

    // --- Diagnostics -------------------------------------------------------

    #[test]
    fn diagnostic_for_builds_message_and_remediation() {
        let d = diagnostic_for(3000, 9921, "node");
        assert_eq!(d.check_name, "Port 3000");
        assert_eq!(d.status, CheckStatus::Warn);
        assert_eq!(d.message, "Port 3000 is occupied by PID 9921 (node)");
        let remediation = d.remediation.unwrap();
        assert!(remediation.contains("9921"));
        assert!(remediation.contains("3000"));
        if cfg!(windows) {
            assert!(remediation.contains("taskkill"));
        } else {
            assert!(remediation.contains("kill 9921"));
        }
    }

    #[test]
    fn diagnostic_for_unknown_process_is_readable() {
        let d = diagnostic_for(8080, 0, "");
        assert!(d.message.contains("unknown process"));
    }

    #[test]
    fn diagnostic_for_critical_port_fails() {
        let d = diagnostic_for(5432, 6880, "postgres");
        assert_eq!(d.status, CheckStatus::Fail);
    }

    // --- Cache behaviour ---------------------------------------------------

    #[test]
    fn watcher_caches_scan_results() {
        let calls = Arc::new(AtomicUsize::new(0));
        let calls_for_scan = Arc::clone(&calls);
        let scanner: Box<dyn Fn() -> Vec<(u16, u32, String)> + Send + Sync> = Box::new(move || {
            calls_for_scan.fetch_add(1, Ordering::SeqCst);
            vec![(3000, 111, "web-server".to_string())]
        });
        let watcher = PortWatcher::with_scanner(Duration::from_secs(60), scanner);

        let first = watcher.find_blocked(&[3000, 8080]);
        let second = watcher.find_blocked(&[3000, 8080]);

        assert_eq!(first, vec![(3000, 111, "web-server".to_string())]);
        assert_eq!(second, first);
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn watcher_rescans_after_clear() {
        let calls = Arc::new(AtomicUsize::new(0));
        let calls_for_scan = Arc::clone(&calls);
        let scanner: Box<dyn Fn() -> Vec<(u16, u32, String)> + Send + Sync> = Box::new(move || {
            calls_for_scan.fetch_add(1, Ordering::SeqCst);
            vec![(5000, 222, "api".to_string())]
        });
        let watcher = PortWatcher::with_scanner(Duration::from_secs(60), scanner);

        let _ = watcher.find_blocked(&[5000]);
        watcher.clear();
        let _ = watcher.find_blocked(&[5000]);

        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn watcher_stale_entry_triggers_rescan() {
        let calls = Arc::new(AtomicUsize::new(0));
        let calls_for_scan = Arc::clone(&calls);
        let scanner: Box<dyn Fn() -> Vec<(u16, u32, String)> + Send + Sync> = Box::new(move || {
            calls_for_scan.fetch_add(1, Ordering::SeqCst);
            vec![(9000, 333, "old".to_string())]
        });
        // Zero TTL makes every entry stale.
        let watcher = PortWatcher::with_scanner(Duration::ZERO, scanner);

        let _ = watcher.find_blocked(&[9000]);
        let _ = watcher.find_blocked(&[9000]);

        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }

    // --- Live bind probing -------------------------------------------------

    #[test]
    fn is_port_in_use_detects_bound_port() {
        let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind ephemeral port");
        let port = listener.local_addr().expect("local addr").port();
        let occupied = is_port_in_use(port);
        drop(listener);
        assert!(occupied);
    }

    #[test]
    fn is_port_in_use_free_after_drop() {
        let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind ephemeral port");
        let port = listener.local_addr().expect("local addr").port();
        drop(listener);
        assert!(!is_port_in_use(port));
    }

    // --- Public free functions on the default watcher ----------------------

    #[test]
    fn check_blocked_ports_runs_without_panicking() {
        // Verifies netstat/tasklist integration runs cleanly on this host.
        let results = check_blocked_ports(DEFAULT_DEV_PORTS);
        for (port, pid, _) in &results {
            assert!(DEFAULT_DEV_PORTS.contains(port));
            assert_ne!(*pid, 0, "port {port} should resolve to a PID");
        }
    }

    #[test]
    fn default_ports_are_well_known_dev_ports() {
        assert_eq!(DEFAULT_DEV_PORTS, &[3000, 5000, 8000, 8080, 9000]);
    }
}