pmdaemon 0.1.4

PMDaemon - A high-performance, cross-platform process manager built in Rust with advanced port management and monitoring capabilities
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
//! Process management types and utilities

use crate::config::ProcessConfig;
use crate::error::{Error, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::process::Stdio;
use tokio::fs::File;
use tokio::process::{Child, Command};
use tracing::{debug, error, info, warn};
use uuid::Uuid;

/// Unique identifier for a process
pub type ProcessId = Uuid;

/// Current state of a process
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ProcessState {
    /// Process is starting up
    Starting,
    /// Process is running normally
    Online,
    /// Process is stopping
    Stopping,
    /// Process has stopped
    Stopped,
    /// Process has errored
    Errored,
    /// Process is being restarted
    Restarting,
}

impl std::fmt::Display for ProcessState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ProcessState::Starting => write!(f, "starting"),
            ProcessState::Online => write!(f, "online"),
            ProcessState::Stopping => write!(f, "stopping"),
            ProcessState::Stopped => write!(f, "stopped"),
            ProcessState::Errored => write!(f, "errored"),
            ProcessState::Restarting => write!(f, "restarting"),
        }
    }
}

/// Process status information for external consumption.
///
/// This struct represents the current status and metrics of a managed process.
/// It's designed to be serializable for API responses and contains all the
/// information needed for monitoring and display purposes.
///
/// # Examples
///
/// ```rust
/// use pmdaemon::process::{ProcessStatus, ProcessState};
/// use uuid::Uuid;
///
/// // ProcessStatus is typically obtained from Process::status()
/// // This example shows the structure for documentation purposes
/// let status = ProcessStatus {
///     id: Uuid::new_v4(),
///     name: "my-app".to_string(),
///     state: ProcessState::Online,
///     pid: Some(1234),
///     uptime: None,
///     restarts: 0,
///     cpu_usage: 15.5,
///     memory_usage: 128 * 1024 * 1024, // 128MB
///     exit_code: None,
///     error: None,
///     namespace: "default".to_string(),
///     instance: None,
///     assigned_port: Some(3000),
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessStatus {
    /// Unique process identifier (UUID)
    pub id: ProcessId,

    /// Human-readable process name
    pub name: String,

    /// Current process state (starting, online, stopped, etc.)
    pub state: ProcessState,

    /// System process ID (PID) if the process is currently running
    pub pid: Option<u32>,

    /// Process start time (UTC) for uptime calculation
    pub uptime: Option<DateTime<Utc>>,

    /// Total number of times this process has been restarted
    pub restarts: u32,

    /// Current CPU usage as a percentage (0.0-100.0)
    pub cpu_usage: f32,

    /// Current memory usage in bytes
    pub memory_usage: u64,

    /// Exit code from the last process termination
    pub exit_code: Option<i32>,

    /// Error message if the process is in an error state
    pub error: Option<String>,

    /// Namespace for logical process grouping
    pub namespace: String,

    /// Instance number for cluster mode (0-based)
    pub instance: Option<u32>,

    /// Port assigned to this process (if any)
    pub assigned_port: Option<u16>,
}

/// Internal process representation for lifecycle management.
///
/// This struct represents a managed process with full lifecycle control capabilities.
/// It contains both the configuration and runtime state, including the actual system
/// process handle for direct control operations.
///
/// # Examples
///
/// ```rust,no_run
/// use pmdaemon::{Process, ProcessConfig};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let config = ProcessConfig::builder()
///     .name("my-app")
///     .script("node")
///     .args(vec!["server.js"])
///     .build()?;
///
/// let mut process = Process::new(config);
///
/// // Start the process
/// process.start().await?;
///
/// // Check if it's running
/// if process.is_running() {
///     println!("Process is running with PID: {:?}", process.pid());
/// }
///
/// // Get status for monitoring
/// let status = process.status();
/// println!("Process {} is {}", status.name, status.state);
///
/// // Stop the process
/// process.stop().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Process {
    /// Unique identifier for this process instance
    pub id: ProcessId,

    /// Process configuration defining how it should run
    pub config: ProcessConfig,

    /// Current process state (starting, online, stopped, etc.)
    pub state: ProcessState,

    /// System process handle for direct control (if running)
    pub child: Option<Child>,

    /// Timestamp when the process was last started
    pub started_at: Option<DateTime<Utc>>,

    /// Total number of times this process has been restarted
    pub restarts: u32,

    /// Exit code from the last process termination
    pub exit_code: Option<i32>,

    /// Error message if the process is in an error state
    pub error: Option<String>,

    /// Instance number for cluster mode (0-based)
    pub instance: Option<u32>,

    /// Port assigned to this process by the port manager
    pub assigned_port: Option<u16>,

    /// Stored PID for processes restored from disk (when child handle is unavailable)
    pub stored_pid: Option<u32>,

    /// Real-time monitoring data (CPU, memory, etc.)
    pub monitoring: ProcessMonitoring,
}

/// Real-time monitoring data for a process.
///
/// This struct contains the current resource usage metrics for a process,
/// updated periodically by the monitoring system. It's used internally
/// for tracking performance and enforcing resource limits.
///
/// # Examples
///
/// ```rust
/// use pmdaemon::process::ProcessMonitoring;
/// use chrono::Utc;
///
/// let mut monitoring = ProcessMonitoring::default();
///
/// // Update with current metrics
/// monitoring.cpu_usage = 25.5;
/// monitoring.memory_usage = 128 * 1024 * 1024; // 128MB
/// monitoring.last_update = Some(Utc::now());
/// ```
#[derive(Debug, Default)]
pub struct ProcessMonitoring {
    /// Current CPU usage as a percentage (0.0-100.0)
    pub cpu_usage: f32,

    /// Current memory usage in bytes
    pub memory_usage: u64,

    /// Timestamp of the last monitoring update
    pub last_update: Option<DateTime<Utc>>,
}

impl Process {
    /// Create a new process instance from configuration.
    ///
    /// Creates a new process in the `Stopped` state with a unique ID.
    /// The process is not started automatically - call `start()` to begin execution.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pmdaemon::{Process, ProcessConfig};
    ///
    /// let config = ProcessConfig::builder()
    ///     .name("my-app")
    ///     .script("node")
    ///     .args(vec!["server.js"])
    ///     .build()
    ///     .unwrap();
    ///
    /// let process = Process::new(config);
    /// assert_eq!(process.state, pmdaemon::ProcessState::Stopped);
    /// ```
    pub fn new(config: ProcessConfig) -> Self {
        Self {
            id: Uuid::new_v4(),
            config,
            state: ProcessState::Stopped,
            child: None,
            started_at: None,
            restarts: 0,
            exit_code: None,
            error: None,
            instance: None,
            assigned_port: None,
            stored_pid: None,
            monitoring: ProcessMonitoring::default(),
        }
    }

    /// Get current process status for monitoring and API responses.
    ///
    /// Returns a `ProcessStatus` struct containing all current process information
    /// including state, resource usage, and metadata. This is the primary method
    /// for obtaining process information for external consumption.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pmdaemon::{Process, ProcessConfig, ProcessState};
    ///
    /// let config = ProcessConfig::builder()
    ///     .name("my-app")
    ///     .script("echo")
    ///     .build()
    ///     .unwrap();
    ///
    /// let process = Process::new(config);
    /// let status = process.status();
    ///
    /// assert_eq!(status.name, "my-app");
    /// assert_eq!(status.state, ProcessState::Stopped);
    /// assert_eq!(status.restarts, 0);
    /// ```
    pub fn status(&self) -> ProcessStatus {
        ProcessStatus {
            id: self.id,
            name: self.config.name.clone(),
            state: self.state,
            pid: self.child.as_ref().and_then(|c| c.id()).or(self.stored_pid),
            uptime: self.started_at,
            restarts: self.restarts,
            cpu_usage: self.monitoring.cpu_usage,
            memory_usage: self.monitoring.memory_usage,
            exit_code: self.exit_code,
            error: self.error.clone(),
            namespace: self.config.namespace.clone(),
            instance: self.instance,
            assigned_port: self.assigned_port,
        }
    }

    /// Check if process is running
    pub fn is_running(&self) -> bool {
        matches!(self.state, ProcessState::Online | ProcessState::Starting)
    }

    /// Set process state
    pub fn set_state(&mut self, state: ProcessState) {
        self.state = state;
        if state == ProcessState::Online && self.started_at.is_none() {
            self.started_at = Some(Utc::now());
        }
    }

    /// Start the process
    pub async fn start(&mut self) -> Result<()> {
        self.start_with_logs(None, None).await
    }

    /// Start the process with optional log file redirection.
    ///
    /// This is the core method for starting a process. It spawns the configured
    /// command with all specified arguments, environment variables, and working
    /// directory. Output can be redirected to log files or captured for processing.
    ///
    /// # Arguments
    ///
    /// * `out_log` - Optional path for stdout redirection
    /// * `err_log` - Optional path for stderr redirection
    ///
    /// # Process Lifecycle
    ///
    /// 1. Validates the process is not already running
    /// 2. Sets state to `Starting`
    /// 3. Configures the command with args, environment, and working directory
    /// 4. Sets up stdio redirection (files or pipes)
    /// 5. Spawns the process
    /// 6. Sets state to `Online` on success or `Errored` on failure
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use pmdaemon::{Process, ProcessConfig};
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let config = ProcessConfig::builder()
    ///     .name("my-app")
    ///     .script("node")
    ///     .args(vec!["server.js"])
    ///     .build()?;
    ///
    /// let mut process = Process::new(config);
    ///
    /// // Start with log redirection
    /// let out_log = Some(PathBuf::from("/var/log/myapp-out.log"));
    /// let err_log = Some(PathBuf::from("/var/log/myapp-err.log"));
    /// process.start_with_logs(out_log, err_log).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Process is already running
    /// - Command/script is not found
    /// - Log files cannot be created
    /// - Process spawn fails for any reason
    pub async fn start_with_logs(
        &mut self,
        out_log: Option<PathBuf>,
        err_log: Option<PathBuf>,
    ) -> Result<()> {
        if self.is_running() {
            return Err(Error::ProcessAlreadyRunning(self.config.name.clone()));
        }

        info!("Starting process: {}", self.config.name);
        self.set_state(ProcessState::Starting);

        // Prepare command
        let mut cmd = Command::new(&self.config.script);

        // Add arguments
        if !self.config.args.is_empty() {
            cmd.args(&self.config.args);
        }

        // Set working directory
        if let Some(cwd) = &self.config.cwd {
            cmd.current_dir(cwd);
        }

        // Set environment variables
        if !self.config.env.is_empty() {
            for (key, value) in &self.config.env {
                cmd.env(key, value);
            }
        }

        // Configure stdio with log file redirection
        if let Some(out_path) = out_log {
            // Create/open stdout log file
            let stdout_file = File::create(&out_path)
                .await
                .map_err(|e| Error::config(format!("Failed to create stdout log file: {}", e)))?;
            cmd.stdout(stdout_file.into_std().await);
            debug!("Redirecting stdout to: {:?}", out_path);
        } else {
            cmd.stdout(Stdio::piped());
        }

        if let Some(err_path) = err_log {
            // Create/open stderr log file
            let stderr_file = File::create(&err_path)
                .await
                .map_err(|e| Error::config(format!("Failed to create stderr log file: {}", e)))?;
            cmd.stderr(stderr_file.into_std().await);
            debug!("Redirecting stderr to: {:?}", err_path);
        } else {
            cmd.stderr(Stdio::piped());
        }

        cmd.stdin(Stdio::null());

        // Configure process to run independently (detached from parent)
        #[cfg(unix)]
        {
            #[allow(unused_imports)]
            use std::os::unix::process::CommandExt;
            cmd.process_group(0); // Create new process group to detach from parent
        }

        #[cfg(windows)]
        {
            use std::os::windows::process::CommandExt;
            cmd.creation_flags(0x00000008); // CREATE_NO_WINDOW flag to detach
        }

        // Spawn the process
        match cmd.spawn() {
            Ok(child) => {
                info!(
                    "Process {} started with PID: {}",
                    self.config.name,
                    child.id().unwrap_or(0)
                );
                // Store the child process handle
                self.child = Some(child);
                self.set_state(ProcessState::Online);
                self.error = None;

                // Note: Process is now detached and will continue running independently
                debug!(
                    "Process {} detached and running independently",
                    self.config.name
                );
                Ok(())
            }
            Err(e) => {
                error!("Failed to start process {}: {}", self.config.name, e);
                self.set_state(ProcessState::Errored);
                self.error = Some(format!("Failed to start: {}", e));
                Err(Error::ProcessStartFailed {
                    name: self.config.name.clone(),
                    reason: e.to_string(),
                })
            }
        }
    }

    /// Stop the process gracefully
    pub async fn stop(&mut self) -> Result<()> {
        if !self.is_running() {
            return Ok(());
        }

        info!("Stopping process: {}", self.config.name);
        self.set_state(ProcessState::Stopping);

        if let Some(mut child) = self.child.take() {
            // Try graceful shutdown first
            #[cfg(unix)]
            {
                use nix::sys::signal::{self, Signal};
                use nix::unistd::Pid;

                if let Some(pid) = child.id() {
                    let pid = Pid::from_raw(pid as i32);
                    if let Err(e) = signal::kill(pid, Signal::SIGTERM) {
                        warn!(
                            "Failed to send SIGTERM to process {}: {}",
                            self.config.name, e
                        );
                    } else {
                        debug!("Sent SIGTERM to process {}", self.config.name);
                    }
                }
            }

            // Wait for graceful shutdown with timeout
            let timeout = tokio::time::Duration::from_secs(10);
            match tokio::time::timeout(timeout, child.wait()).await {
                Ok(Ok(exit_status)) => {
                    info!(
                        "Process {} stopped gracefully with exit code: {:?}",
                        self.config.name,
                        exit_status.code()
                    );
                    self.exit_code = exit_status.code();
                }
                Ok(Err(e)) => {
                    error!(
                        "Error waiting for process {} to stop: {}",
                        self.config.name, e
                    );
                    return Err(Error::ProcessStopFailed {
                        name: self.config.name.clone(),
                        reason: e.to_string(),
                    });
                }
                Err(_) => {
                    warn!(
                        "Process {} did not stop gracefully, killing forcefully",
                        self.config.name
                    );
                    if let Err(e) = child.kill().await {
                        error!("Failed to kill process {}: {}", self.config.name, e);
                        return Err(Error::ProcessStopFailed {
                            name: self.config.name.clone(),
                            reason: e.to_string(),
                        });
                    }
                    if let Ok(exit_status) = child.wait().await {
                        self.exit_code = exit_status.code();
                    }
                }
            }
        }

        self.set_state(ProcessState::Stopped);
        self.started_at = None;
        Ok(())
    }

    /// Restart the process
    pub async fn restart(&mut self) -> Result<()> {
        info!("Restarting process: {}", self.config.name);
        self.set_state(ProcessState::Restarting);

        // Stop if running
        if self.is_running() {
            self.stop().await?;
        }

        // Increment restart counter
        self.restarts += 1;

        // Start again
        self.start().await
    }

    /// Check if the process is still alive
    pub async fn check_status(&mut self) -> Result<bool> {
        if let Some(child) = &mut self.child {
            match child.try_wait() {
                Ok(Some(exit_status)) => {
                    // Process has exited
                    info!(
                        "Process {} exited with status: {:?}",
                        self.config.name,
                        exit_status.code()
                    );
                    self.exit_code = exit_status.code();
                    self.set_state(ProcessState::Stopped);
                    self.child = None;
                    self.started_at = None;
                    Ok(false)
                }
                Ok(None) => {
                    // Process is still running
                    Ok(true)
                }
                Err(e) => {
                    error!("Error checking process {} status: {}", self.config.name, e);
                    self.set_state(ProcessState::Errored);
                    self.error = Some(format!("Status check failed: {}", e));
                    self.child = None;
                    Ok(false)
                }
            }
        } else {
            Ok(false)
        }
    }

    /// Get the process PID if running
    pub fn pid(&self) -> Option<u32> {
        self.child.as_ref().and_then(|c| c.id())
    }

    /// Set the assigned port for this process
    pub fn set_assigned_port(&mut self, port: Option<u16>) {
        self.assigned_port = port;
    }

    /// Set the instance number for this process
    pub fn set_instance(&mut self, instance: Option<u32>) {
        self.instance = instance;
    }

    /// Set the stored PID for this process (used when restoring from disk)
    pub fn set_stored_pid(&mut self, pid: Option<u32>) {
        self.stored_pid = pid;
    }

    /// Set the process ID (used when restoring from disk)
    pub fn set_id(&mut self, id: ProcessId) {
        self.id = id;
    }

    /// Update monitoring data
    pub fn update_monitoring(&mut self, cpu_usage: f32, memory_usage: u64) {
        self.monitoring.cpu_usage = cpu_usage;
        self.monitoring.memory_usage = memory_usage;
        self.monitoring.last_update = Some(Utc::now());
    }

    /// Get uptime in seconds
    pub fn uptime_seconds(&self) -> Option<i64> {
        self.started_at
            .map(|start| (Utc::now() - start).num_seconds())
    }

    /// Check if process should be auto-restarted
    pub fn should_auto_restart(&self) -> bool {
        self.config.autorestart
            && self.state == ProcessState::Stopped
            && self.config.max_restarts > self.restarts
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::ProcessConfig;
    use pretty_assertions::assert_eq;

    fn create_test_config() -> ProcessConfig {
        ProcessConfig::builder()
            .name("test-process")
            .script("echo")
            .args(vec!["hello", "world"])
            .build()
            .unwrap()
    }

    #[test]
    fn test_process_state_display() {
        assert_eq!(ProcessState::Starting.to_string(), "starting");
        assert_eq!(ProcessState::Online.to_string(), "online");
        assert_eq!(ProcessState::Stopping.to_string(), "stopping");
        assert_eq!(ProcessState::Stopped.to_string(), "stopped");
        assert_eq!(ProcessState::Errored.to_string(), "errored");
        assert_eq!(ProcessState::Restarting.to_string(), "restarting");
    }

    #[test]
    fn test_process_state_serialization() {
        let state = ProcessState::Online;
        let serialized = serde_json::to_string(&state).unwrap();
        assert_eq!(serialized, "\"online\"");

        let deserialized: ProcessState = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized, ProcessState::Online);
    }

    #[test]
    fn test_process_monitoring_default() {
        let monitoring = ProcessMonitoring::default();
        assert_eq!(monitoring.cpu_usage, 0.0);
        assert_eq!(monitoring.memory_usage, 0);
        assert!(monitoring.last_update.is_none());
    }

    #[test]
    fn test_process_new() {
        let config = create_test_config();
        let process = Process::new(config.clone());

        assert_eq!(process.config.name, "test-process");
        assert_eq!(process.config.script, "echo");
        assert_eq!(process.config.args, vec!["hello", "world"]);
        assert_eq!(process.state, ProcessState::Stopped);
        assert!(process.child.is_none());
        assert!(process.started_at.is_none());
        assert_eq!(process.restarts, 0);
        assert!(process.exit_code.is_none());
        assert!(process.error.is_none());
        assert!(process.instance.is_none());
        assert!(process.assigned_port.is_none());
    }

    #[test]
    fn test_process_status() {
        let config = create_test_config();
        let mut process = Process::new(config);

        // Set some test data
        process.set_state(ProcessState::Online);
        process.restarts = 5;
        process.update_monitoring(25.5, 1024 * 1024);
        process.set_assigned_port(Some(8080));
        process.set_instance(Some(1));

        let status = process.status();
        assert_eq!(status.name, "test-process");
        assert_eq!(status.state, ProcessState::Online);
        assert_eq!(status.restarts, 5);
        assert_eq!(status.cpu_usage, 25.5);
        assert_eq!(status.memory_usage, 1024 * 1024);
        assert_eq!(status.assigned_port, Some(8080));
        assert_eq!(status.instance, Some(1));
        assert_eq!(status.namespace, "default");
    }

    #[test]
    fn test_process_is_running() {
        let config = create_test_config();
        let mut process = Process::new(config);

        assert!(!process.is_running());

        process.set_state(ProcessState::Starting);
        assert!(process.is_running());

        process.set_state(ProcessState::Online);
        assert!(process.is_running());

        process.set_state(ProcessState::Stopping);
        assert!(!process.is_running());

        process.set_state(ProcessState::Stopped);
        assert!(!process.is_running());

        process.set_state(ProcessState::Errored);
        assert!(!process.is_running());

        process.set_state(ProcessState::Restarting);
        assert!(!process.is_running());
    }

    #[test]
    fn test_process_set_state() {
        let config = create_test_config();
        let mut process = Process::new(config);

        assert!(process.started_at.is_none());

        process.set_state(ProcessState::Online);
        assert_eq!(process.state, ProcessState::Online);
        assert!(process.started_at.is_some());

        // Setting state again shouldn't change started_at
        let original_start = process.started_at;
        process.set_state(ProcessState::Online);
        assert_eq!(process.started_at, original_start);

        process.set_state(ProcessState::Stopped);
        assert_eq!(process.state, ProcessState::Stopped);
        // started_at should remain unchanged when setting to stopped
        assert_eq!(process.started_at, original_start);
    }

    #[test]
    fn test_process_set_assigned_port() {
        let config = create_test_config();
        let mut process = Process::new(config);

        assert!(process.assigned_port.is_none());

        process.set_assigned_port(Some(8080));
        assert_eq!(process.assigned_port, Some(8080));

        process.set_assigned_port(None);
        assert!(process.assigned_port.is_none());
    }

    #[test]
    fn test_process_set_instance() {
        let config = create_test_config();
        let mut process = Process::new(config);

        assert!(process.instance.is_none());

        process.set_instance(Some(1));
        assert_eq!(process.instance, Some(1));

        process.set_instance(None);
        assert!(process.instance.is_none());
    }

    #[test]
    fn test_process_update_monitoring() {
        let config = create_test_config();
        let mut process = Process::new(config);

        assert_eq!(process.monitoring.cpu_usage, 0.0);
        assert_eq!(process.monitoring.memory_usage, 0);
        assert!(process.monitoring.last_update.is_none());

        process.update_monitoring(50.5, 2048);
        assert_eq!(process.monitoring.cpu_usage, 50.5);
        assert_eq!(process.monitoring.memory_usage, 2048);
        assert!(process.monitoring.last_update.is_some());
    }

    #[test]
    fn test_process_uptime_seconds() {
        let config = create_test_config();
        let mut process = Process::new(config);

        assert!(process.uptime_seconds().is_none());

        process.set_state(ProcessState::Online);
        let uptime = process.uptime_seconds();
        assert!(uptime.is_some());
        assert!(uptime.unwrap() >= 0);
    }

    #[test]
    fn test_process_should_auto_restart() {
        let mut config = create_test_config();
        config.autorestart = true;
        config.max_restarts = 5;

        let mut process = Process::new(config);
        process.set_state(ProcessState::Stopped);

        // Should auto-restart when stopped and under restart limit
        assert!(process.should_auto_restart());

        // Should not auto-restart when at restart limit
        process.restarts = 5;
        assert!(!process.should_auto_restart());

        // Should not auto-restart when autorestart is disabled
        process.restarts = 0;
        process.config.autorestart = false;
        assert!(!process.should_auto_restart());

        // Should not auto-restart when not stopped
        process.config.autorestart = true;
        process.set_state(ProcessState::Online);
        assert!(!process.should_auto_restart());
    }

    #[test]
    fn test_process_pid() {
        let config = create_test_config();
        let process = Process::new(config);

        // Process without child should return None
        assert!(process.pid().is_none());
    }

    #[tokio::test]
    async fn test_process_start_already_running() {
        let config = create_test_config();
        let mut process = Process::new(config);

        // Simulate running state
        process.set_state(ProcessState::Online);

        let result = process.start().await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            Error::ProcessAlreadyRunning(_)
        ));
    }

    #[tokio::test]
    async fn test_process_start_invalid_command() {
        let config = ProcessConfig::builder()
            .name("test-invalid")
            .script("this-command-does-not-exist-12345")
            .build()
            .unwrap();

        let mut process = Process::new(config);
        let result = process.start().await;

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            Error::ProcessStartFailed { .. }
        ));
        assert_eq!(process.state, ProcessState::Errored);
        assert!(process.error.is_some());
    }

    #[tokio::test]
    async fn test_process_stop_not_running() {
        let config = create_test_config();
        let mut process = Process::new(config);

        // Process is not running, stop should succeed
        let result = process.stop().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_process_check_status_no_child() {
        let config = create_test_config();
        let mut process = Process::new(config);

        let result = process.check_status().await;
        assert!(result.is_ok());
        assert!(!result.unwrap()); // Should return false when no child
    }

    #[test]
    fn test_process_status_serialization() {
        let config = create_test_config();
        let process = Process::new(config);
        let status = process.status();

        let serialized = serde_json::to_string(&status).unwrap();
        let deserialized: ProcessStatus = serde_json::from_str(&serialized).unwrap();

        assert_eq!(status.name, deserialized.name);
        assert_eq!(status.state, deserialized.state);
        assert_eq!(status.restarts, deserialized.restarts);
    }

    #[test]
    fn test_restart_counter_increments() {
        let config = create_test_config();
        let mut process = Process::new(config);

        // Initial restart count should be 0
        assert_eq!(process.restarts, 0);
        assert_eq!(process.status().restarts, 0);

        // Manually increment restart counter (simulating restart logic)
        process.restarts += 1;
        assert_eq!(process.restarts, 1);
        assert_eq!(process.status().restarts, 1);

        // Increment again
        process.restarts += 1;
        assert_eq!(process.restarts, 2);
        assert_eq!(process.status().restarts, 2);

        // Increment multiple times
        process.restarts += 3;
        assert_eq!(process.restarts, 5);
        assert_eq!(process.status().restarts, 5);
    }

    #[test]
    fn test_restart_counter_in_status_display() {
        let config = create_test_config();
        let mut process = Process::new(config);

        // Test that restart counter is properly included in status
        for expected_count in 0..=10 {
            process.restarts = expected_count;
            let status = process.status();
            assert_eq!(
                status.restarts, expected_count,
                "Restart count mismatch at iteration {}",
                expected_count
            );
        }
    }

    #[test]
    fn test_restart_counter_persistence() {
        let config = create_test_config();
        let mut process = Process::new(config);

        // Set restart count
        process.restarts = 7;

        // Change state multiple times - restart count should persist
        process.set_state(ProcessState::Starting);
        assert_eq!(process.restarts, 7);

        process.set_state(ProcessState::Online);
        assert_eq!(process.restarts, 7);

        process.set_state(ProcessState::Stopping);
        assert_eq!(process.restarts, 7);

        process.set_state(ProcessState::Stopped);
        assert_eq!(process.restarts, 7);

        // Status should always reflect the current restart count
        assert_eq!(process.status().restarts, 7);
    }
}