boxlite 0.10.1

Embeddable virtual machine runtime for secure, isolated code execution
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
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
//! Core data types for box lifecycle management.

use chrono::{DateTime, Utc};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;

pub use crate::litebox::{BoxState, BoxStatus, HealthStatus};
use crate::runtime::id::BoxID;
use crate::runtime::options::{NetworkConfig, NetworkMode, PortProtocol};
/// Re-exported here so the CLI can reach volume metadata the same way it
/// reaches [`ImageInfo`] (`boxlite::runtime::types::VolumeInfo`). The type
/// itself lives with the store in [`crate::volumes`].
pub use crate::volumes::VolumeInfo;

// ============================================================================
// RESOURCE LIMIT TYPES (C-NEWTYPE: Semantic newtypes for distinct concepts)
// ============================================================================

/// Byte size for memory and file size limits.
///
/// Using a dedicated type prevents mixing bytes with counts or other units.
/// Provides convenient constructors for common size notations.
///
/// # Example
///
/// ```
/// use boxlite::runtime::types::Bytes;
///
/// let size = Bytes::from_mib(512);
/// assert_eq!(size.as_bytes(), 512 * 1024 * 1024);
///
/// // From raw bytes
/// let exact = Bytes::from_bytes(1_000_000);
/// assert_eq!(exact.as_bytes(), 1_000_000);
/// ```
#[derive(
    Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct Bytes(pub u64);

impl Bytes {
    /// Create from raw byte count.
    #[inline]
    pub const fn from_bytes(bytes: u64) -> Self {
        Self(bytes)
    }

    /// Create from kibibytes (1 KiB = 1024 bytes).
    #[inline]
    pub const fn from_kib(kib: u64) -> Self {
        Self(kib * 1024)
    }

    /// Create from mebibytes (1 MiB = 1024² bytes).
    #[inline]
    pub const fn from_mib(mib: u64) -> Self {
        Self(mib * 1024 * 1024)
    }

    /// Create from gibibytes (1 GiB = 1024³ bytes).
    #[inline]
    pub const fn from_gib(gib: u64) -> Self {
        Self(gib * 1024 * 1024 * 1024)
    }

    /// Get the raw byte count.
    #[inline]
    pub const fn as_bytes(&self) -> u64 {
        self.0
    }

    /// Get size in kibibytes (truncating).
    #[inline]
    pub const fn as_kib(&self) -> u64 {
        self.0 / 1024
    }

    /// Get size in mebibytes (truncating).
    #[inline]
    pub const fn as_mib(&self) -> u64 {
        self.0 / (1024 * 1024)
    }
}

impl From<u64> for Bytes {
    fn from(bytes: u64) -> Self {
        Self(bytes)
    }
}

impl From<Bytes> for u64 {
    fn from(b: Bytes) -> Self {
        b.0
    }
}

impl fmt::Display for Bytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.0 >= 1024 * 1024 * 1024 && self.0.is_multiple_of(1024 * 1024 * 1024) {
            write!(f, "{} GiB", self.0 / (1024 * 1024 * 1024))
        } else if self.0 >= 1024 * 1024 && self.0.is_multiple_of(1024 * 1024) {
            write!(f, "{} MiB", self.0 / (1024 * 1024))
        } else if self.0 >= 1024 && self.0.is_multiple_of(1024) {
            write!(f, "{} KiB", self.0 / 1024)
        } else {
            write!(f, "{} bytes", self.0)
        }
    }
}

/// Duration in seconds for CPU time limits.
///
/// Using a dedicated type prevents mixing seconds with milliseconds or counts.
///
/// # Example
///
/// ```
/// use boxlite::runtime::types::Seconds;
///
/// let timeout = Seconds::from_minutes(5);
/// assert_eq!(timeout.as_seconds(), 300);
///
/// let short = Seconds::from_seconds(30);
/// assert_eq!(short.as_seconds(), 30);
/// ```
#[derive(
    Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct Seconds(pub u64);

impl Seconds {
    /// Create from raw seconds.
    #[inline]
    pub const fn from_seconds(s: u64) -> Self {
        Self(s)
    }

    /// Create from minutes.
    #[inline]
    pub const fn from_minutes(m: u64) -> Self {
        Self(m * 60)
    }

    /// Create from hours.
    #[inline]
    pub const fn from_hours(h: u64) -> Self {
        Self(h * 60 * 60)
    }

    /// Get the raw seconds count.
    #[inline]
    pub const fn as_seconds(&self) -> u64 {
        self.0
    }

    /// Get duration in minutes (truncating).
    #[inline]
    pub const fn as_minutes(&self) -> u64 {
        self.0 / 60
    }
}

impl From<u64> for Seconds {
    fn from(s: u64) -> Self {
        Self(s)
    }
}

impl From<Seconds> for u64 {
    fn from(s: Seconds) -> Self {
        s.0
    }
}

impl fmt::Display for Seconds {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.0 >= 3600 && self.0.is_multiple_of(3600) {
            write!(f, "{} hours", self.0 / 3600)
        } else if self.0 >= 60 && self.0.is_multiple_of(60) {
            write!(f, "{} minutes", self.0 / 60)
        } else {
            write!(f, "{} seconds", self.0)
        }
    }
}

// ============================================================================
// CONTAINER ID
// ============================================================================

/// Container identifier (64-character lowercase hex).
///
/// Follows the OCI convention: SHA256 hash encoded as 64 lowercase hex characters.
/// This format matches Docker/containerd container IDs.
///
/// # Example
///
/// ```
/// use boxlite::runtime::types::ContainerID;
///
/// let id = ContainerID::new();
/// assert_eq!(id.as_str().len(), 64);
/// assert_eq!(id.short().len(), 12);
/// ```
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ContainerID(String);

impl ContainerID {
    /// Length of full container ID (64 hex chars = 256 bits).
    pub const FULL_LENGTH: usize = 64;

    /// Length of short container ID for display (12 hex chars).
    pub const SHORT_LENGTH: usize = 12;

    /// Generate a new random container ID.
    ///
    /// Uses SHA256 of 32 random bytes to produce a 64-char hex string.
    pub fn new() -> Self {
        let mut random_bytes = [0u8; 32];
        rand::rng().fill_bytes(&mut random_bytes);

        let mut hasher = Sha256::new();
        hasher.update(random_bytes);
        let result = hasher.finalize();

        Self(hex::encode(result))
    }

    /// Parse a ContainerID from an existing string.
    ///
    /// Returns `None` if the string is not a valid 64-char lowercase hex string.
    pub fn parse(s: &str) -> Option<Self> {
        if Self::is_valid(s) {
            Some(Self(s.to_string()))
        } else {
            None
        }
    }

    /// Check if a string is a valid container ID format.
    pub fn is_valid(s: &str) -> bool {
        s.len() == Self::FULL_LENGTH
            && s.chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase())
    }

    /// Get the full container ID as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Get the short form (first 12 characters) for display.
    pub fn short(&self) -> &str {
        &self.0[..Self::SHORT_LENGTH]
    }
}

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

impl fmt::Display for ContainerID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl fmt::Debug for ContainerID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ContainerID({})", self.short())
    }
}

impl AsRef<str> for ContainerID {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Second-based lifecycle policy for an existing box.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BoxLifecyclePolicy {
    /// Idle time before AutoStop; `0` disables AutoStop.
    pub auto_stop: u32,
    /// Stopped time before AutoDelete; `0` disables AutoDelete.
    pub auto_delete: u32,
    /// Whether the box should automatically resume when accessed after AutoStop.
    pub auto_resume: bool,
}

impl BoxLifecyclePolicy {
    pub fn validate(&self) -> boxlite_shared::errors::BoxliteResult<()> {
        if self.auto_delete > 0 && self.auto_delete <= self.auto_stop {
            return Err(boxlite_shared::errors::BoxliteError::Config(
                "auto_delete must be greater than auto_stop".into(),
            ));
        }
        Ok(())
    }
}

/// A concrete host listener published to a guest port.
///
/// Unlike request-side [`crate::runtime::options::PortSpec`], every field here
/// describes a binding that the network backend has already resolved.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PublishedPort {
    /// Guest port receiving traffic from the host listener.
    pub guest_port: u16,

    /// Concrete host address bound by the network backend.
    pub host_ip: String,

    /// Concrete host port bound by the network backend.
    pub host_port: u16,

    /// Transport protocol used by the publication.
    pub protocol: PortProtocol,
}

/// Network configuration for outbound (guest → internet) traffic.
///
/// Records whether the guest can reach external hosts and which hosts are
/// allowed when [`mode`][Self::mode] is [`NetworkMode::Enabled`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutboundNetworkInfo {
    pub mode: NetworkMode,
    /// Empty means unrestricted outbound access.
    #[serde(default)]
    pub allow_net: Vec<String>,
}

/// Network configuration for inbound (internet → guest) traffic.
///
/// Records whether the guest's exposed ports/preview are publicly reachable.
/// `allow_net` is always empty today — an inbound allowlist is not yet
/// enforced by any layer.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct InboundNetworkInfo {
    pub mode: NetworkMode,
    #[serde(default)]
    pub allow_net: Vec<String>,
}

/// Public network metadata for a box.
///
/// Deserialization accepts the pre-split flat shape (`{"mode", "allow_net"}`)
/// and folds it into `outbound`, so JSON produced before the outbound/inbound
/// split still loads. Serialization emits both shapes for the same reason.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "NetworkInfoWire")]
pub struct NetworkInfo {
    /// Guest egress: whether the box can reach out, and to where.
    pub outbound: OutboundNetworkInfo,

    /// External reachability: whether the box's exposed ports/preview are
    /// public. Its `allow_net` is always empty today (see
    /// [`InboundNetworkInfo::allow_net`]).
    pub inbound: InboundNetworkInfo,

    /// Concrete publications for the current runtime lifecycle.
    ///
    /// `None` means this handle does not know the current bindings. `Some([])`
    /// means there are no active publications.
    #[serde(default)]
    pub published_ports: Option<Vec<PublishedPort>>,

    /// Mirror of `outbound.mode`, kept so pre-split readers keep compiling.
    ///
    /// Deprecated: read `outbound.mode`. Derived — set it through
    /// [`NetworkInfo::new`] rather than by hand, so the two cannot disagree.
    pub mode: NetworkMode,

    /// Mirror of `outbound.allow_net`, kept so pre-split readers keep
    /// compiling.
    ///
    /// Deprecated: read `outbound.allow_net`.
    pub allow_net: Vec<String>,
}

impl NetworkInfo {
    /// Build metadata for both directions, filling the deprecated flat
    /// mirrors from `outbound`.
    pub fn new(
        outbound: OutboundNetworkInfo,
        inbound: InboundNetworkInfo,
        published_ports: Option<Vec<PublishedPort>>,
    ) -> Self {
        Self {
            mode: outbound.mode.clone(),
            allow_net: outbound.allow_net.clone(),
            outbound,
            inbound,
            published_ports,
        }
    }
}

/// Deserialization shape for [`NetworkInfo`], accepting both the nested
/// directions and the pre-split flat fields. A payload carrying only
/// `mode`/`allow_net` predates the split and described egress, so it folds
/// into `outbound`.
#[derive(Deserialize)]
struct NetworkInfoWire {
    #[serde(default)]
    outbound: Option<OutboundNetworkInfo>,
    #[serde(default)]
    inbound: Option<InboundNetworkInfo>,
    #[serde(default)]
    published_ports: Option<Vec<PublishedPort>>,
    #[serde(default)]
    mode: Option<NetworkMode>,
    #[serde(default)]
    allow_net: Option<Vec<String>>,
}

impl From<NetworkInfoWire> for NetworkInfo {
    fn from(wire: NetworkInfoWire) -> Self {
        let outbound = wire.outbound.unwrap_or_else(|| OutboundNetworkInfo {
            mode: wire.mode.unwrap_or_default(),
            allow_net: wire.allow_net.unwrap_or_default(),
        });
        Self::new(
            outbound,
            wire.inbound.unwrap_or_default(),
            wire.published_ports,
        )
    }
}

/// Public metadata about a box (returned by list operations).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoxInfo {
    /// Unique box identifier.
    pub id: BoxID,

    /// User-defined name (optional).
    pub name: Option<String>,

    /// Current lifecycle status.
    pub status: BoxStatus,

    /// Creation timestamp (UTC).
    pub created_at: DateTime<Utc>,

    /// Last state change timestamp (UTC).
    pub last_updated: DateTime<Utc>,

    /// Process ID of the VMM subprocess (None if not running).
    pub pid: Option<u32>,

    /// Image reference or rootfs path.
    pub image: String,

    /// Allocated CPU count.
    pub cpus: u8,

    /// Allocated memory in MiB.
    pub memory_mib: u32,

    /// Network configuration and current runtime publication metadata.
    ///
    /// Local producers always populate this field. `None` indicates metadata
    /// from an older or remote producer that did not include `network`.
    #[serde(default)]
    pub network: Option<NetworkInfo>,

    /// User-defined labels for filtering and organization.
    pub labels: HashMap<String, String>,

    /// Idle time in seconds before AutoStop. `0` disables AutoStop.
    pub auto_stop: u32,

    /// Time in seconds after a successful stop before AutoDelete. `0` disables it.
    pub auto_delete: u32,

    /// Whether the box should automatically resume when accessed after AutoStop.
    pub auto_resume: bool,

    /// Health status.
    pub health_status: HealthStatus,

    /// Exit code of the container's init process, when the box stopped
    /// because its main command exited (docker semantics).
    pub exit_code: Option<i32>,

    /// When the box most recently entered [`BoxStatus::Running`] (docker's
    /// `State.StartedAt`); `None` when no service-level start was recorded.
    /// The value survives stop and reboot as lifecycle history. When
    /// [`Self::pid`] is present, the timestamp describes that live PID.
    ///
    /// This is BoxLite's service-level start timestamp. It does not report when
    /// the configured user task becomes ready, exits, or completes. Those are
    /// workload lifecycle outcomes. The cloud runner reads this timestamp to
    /// confirm a start whose job-completion callback was lost. Serde default
    /// keeps metadata from an older producer
    /// readable.
    #[serde(default)]
    pub started_at: Option<DateTime<Utc>>,

    /// When the box was last active, as recorded by the control plane from
    /// toolbox and proxy traffic — the clock AutoStop measures idleness
    /// against. `None` when no activity has been recorded yet.
    ///
    /// Local runtimes never report this: AutoStop needs an idle sweeper they
    /// do not have, so they record no activity. Serde default keeps metadata
    /// from an older producer readable.
    #[serde(default)]
    pub last_activity_at: Option<DateTime<Utc>>,
}

impl BoxInfo {
    /// Create BoxInfo from config and state.
    pub fn new(config: &crate::litebox::config::BoxConfig, state: &BoxState) -> Self {
        use crate::runtime::constants::vm_defaults::{DEFAULT_CPUS, DEFAULT_MEMORY_MIB};
        use crate::runtime::options::RootfsSpec;

        let network_config =
            NetworkConfig::from_specs(&config.options.network, &config.options.inbound_network);

        Self {
            id: config.id.clone(),
            name: config.name.clone(),
            status: state.status,
            created_at: config.created_at,
            last_updated: state.last_updated,
            pid: state.pid,
            image: match &config.options.rootfs {
                RootfsSpec::Image(r) => r.clone(),
                RootfsSpec::RootfsPath(p) => format!("rootfs:{}", p),
            },
            cpus: config.options.cpus.unwrap_or(DEFAULT_CPUS),
            memory_mib: config.options.memory_mib.unwrap_or(DEFAULT_MEMORY_MIB),
            network: Some(NetworkInfo::new(
                OutboundNetworkInfo {
                    mode: network_config.outbound.mode,
                    allow_net: network_config.outbound.allow_net,
                },
                InboundNetworkInfo {
                    mode: network_config.inbound.mode,
                    allow_net: network_config.inbound.allow_net,
                },
                crate::litebox::ports::resolved_from_state(config, state),
            )),
            labels: HashMap::new(),
            // Local runtimes do not sweep lifecycle deadlines, but metadata keeps
            // the configured values so callers can inspect the effective policy.
            auto_stop: config.options.auto_stop.unwrap_or(0),
            auto_delete: config.options.effective_auto_delete(),
            auto_resume: config.options.auto_resume.unwrap_or(true),
            health_status: state.health_status,
            exit_code: state.exit_code,
            started_at: state.started_at,
            // Activity is recorded by the control plane, not by a local box.
            last_activity_at: None,
        }
    }
}

impl PartialEq for BoxInfo {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
            && self.status == other.status
            && self.created_at == other.created_at
            && self.pid == other.pid
            && self.image == other.image
            && self.cpus == other.cpus
            && self.memory_mib == other.memory_mib
            && self.network == other.network
            && self.labels == other.labels
            && self.auto_stop == other.auto_stop
            && self.auto_delete == other.auto_delete
            && self.auto_resume == other.auto_resume
            && self.health_status == other.health_status
    }
}

// ============================================================================
// BOX STATE INFO (Docker-like State object)
// ============================================================================

/// Runtime state information (like Docker's State object).
///
/// Contains dynamic state that changes during the box lifecycle.
/// This is separate from BoxInfo which includes static configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoxStateInfo {
    /// Current lifecycle status.
    pub status: BoxStatus,

    /// Whether the box is currently running.
    pub running: bool,

    /// Process ID of the VMM subprocess (None if not running).
    pub pid: Option<u32>,

    /// Init exit code, when the box stopped because its command exited.
    pub exit_code: Option<i32>,
}

impl BoxStateInfo {
    /// Create BoxStateInfo from internal BoxState.
    pub fn new(state: &BoxState) -> Self {
        Self {
            status: state.status,
            running: state.status.is_running(),
            pid: state.pid,
            exit_code: state.exit_code,
        }
    }
}

impl From<&BoxInfo> for BoxStateInfo {
    /// Build state view from public BoxInfo (e.g. for CLI templates).
    /// Equivalent to `BoxStateInfo::new(state)` when the same box is BoxInfo.
    fn from(info: &BoxInfo) -> Self {
        Self {
            status: info.status,
            running: info.status.is_running(),
            pid: info.pid,
            exit_code: info.exit_code,
        }
    }
}

// ============================================================================
// IMAGE INFO
// ============================================================================

/// Public metadata about a cached image.
///
/// Designed to provide all necessary information  without exposing internal storage details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageInfo {
    /// Full image reference (e.g., "docker.io/library/alpine:latest")
    pub reference: String,

    /// Parsed repository name (e.g. "docker.io/library/alpine")
    pub repository: String,

    /// Parsed image tag (e.g. "latest")
    pub tag: String,

    /// Image ID (Manifest Digest)
    pub id: String,

    /// When this image was pulled/cached locally.
    /// Note: This is NOT the image build time (which requires reading config blob).
    pub cached_at: DateTime<Utc>,

    /// Image size in bytes (if available)
    pub size: Option<Bytes>,
}

// ============================================================================
// BOX CONFIG (Podman-style separation)
// ============================================================================

// BoxMetadata is replaced by BoxConfig + BoxState
// Old BoxMetadata struct removed - use BoxConfig + BoxState instead

#[cfg(test)]
mod tests {
    use super::*;
    use crate::litebox::config::{BoxConfig, ContainerRuntimeConfig};
    use crate::runtime::options::{BoxOptions, RootfsSpec};
    use std::path::PathBuf;

    fn published_ports(info: &BoxInfo) -> Option<&[PublishedPort]> {
        info.network
            .as_ref()
            .and_then(|network| network.published_ports.as_deref())
    }

    /// JSON written before the outbound/inbound split carried a flat
    /// `mode`/`allow_net` pair describing egress. It must still load.
    #[test]
    fn network_info_deserializes_the_pre_split_flat_shape() {
        let network: NetworkInfo = serde_json::from_str(
            r#"{"mode":"disabled","allow_net":["api.example.com"],"published_ports":null}"#,
        )
        .expect("pre-split network metadata must still deserialize");

        assert_eq!(network.outbound.mode, NetworkMode::Disabled);
        assert_eq!(
            network.outbound.allow_net,
            vec!["api.example.com".to_string()]
        );
        // The direction the pre-split shape could not express takes its default.
        assert_eq!(network.inbound, InboundNetworkInfo::default());
        // And the deprecated mirrors follow outbound.
        assert_eq!(network.mode, NetworkMode::Disabled);
        assert_eq!(network.allow_net, vec!["api.example.com".to_string()]);
    }

    /// Readers that predate the split look for top-level `mode`/`allow_net`,
    /// so serialization has to keep emitting them alongside the directions.
    #[test]
    fn network_info_serializes_both_shapes() {
        let network = NetworkInfo::new(
            OutboundNetworkInfo {
                mode: NetworkMode::Enabled,
                allow_net: vec!["api.example.com".to_string()],
            },
            InboundNetworkInfo {
                mode: NetworkMode::Disabled,
                allow_net: Vec::new(),
            },
            None,
        );

        let value = serde_json::to_value(&network).unwrap();

        assert_eq!(value["outbound"]["mode"], "enabled");
        assert_eq!(value["inbound"]["mode"], "disabled");
        assert_eq!(value["mode"], "enabled");
        assert_eq!(value["allow_net"][0], "api.example.com");
    }

    /// A payload carrying both shapes must not lose the nested one.
    #[test]
    fn network_info_prefers_the_nested_shape_over_the_flat_mirrors() {
        let network: NetworkInfo = serde_json::from_str(
            r#"{"outbound":{"mode":"disabled","allow_net":[]},
                "inbound":{"mode":"enabled","allow_net":[]},
                "mode":"enabled","allow_net":["stale.example.com"]}"#,
        )
        .unwrap();

        assert_eq!(network.outbound.mode, NetworkMode::Disabled);
        assert_eq!(network.inbound.mode, NetworkMode::Enabled);
        // Mirrors are re-derived from outbound, never trusted from the payload.
        assert_eq!(network.mode, NetworkMode::Disabled);
        assert!(network.allow_net.is_empty());
    }

    #[test]
    fn lifecycle_policy_enforces_public_sentinels_and_ordering() {
        assert!(
            BoxLifecyclePolicy {
                auto_stop: 0,
                auto_delete: 0,
                auto_resume: true,
            }
            .validate()
            .is_ok()
        );
        assert!(
            BoxLifecyclePolicy {
                auto_stop: 900,
                auto_delete: 0,
                auto_resume: true,
            }
            .validate()
            .is_ok()
        );
        assert!(
            BoxLifecyclePolicy {
                auto_stop: 900,
                auto_delete: 900,
                auto_resume: true,
            }
            .validate()
            .is_err()
        );
        assert!(
            BoxLifecyclePolicy {
                auto_stop: 900,
                auto_delete: 901,
                auto_resume: true,
            }
            .validate()
            .is_ok()
        );
    }
    #[test]
    fn test_config_state_to_info() {
        let now = Utc::now();
        let box_id = BoxID::parse("01HJK4TNRPQSXYZ8WM6NCVT9R5").unwrap();
        let config = BoxConfig {
            id: box_id,
            name: None,
            created_at: now,
            container: ContainerRuntimeConfig {
                id: ContainerID::new(),
            },
            options: BoxOptions {
                rootfs: RootfsSpec::Image("python:3.11".to_string()),
                cpus: Some(4),
                memory_mib: Some(1024),
                ..Default::default()
            },
            engine_kind: crate::vmm::VmmKind::Libkrun,
            box_home: PathBuf::from("/tmp/box"),
        };

        let mut state = BoxState::new();
        state.set_pid(Some(12345));
        let _ = state.transition_to(BoxStatus::Running);

        let info = BoxInfo::new(&config, &state);

        assert_eq!(info.id, config.id);
        assert_eq!(info.status, state.status);
        assert_eq!(info.created_at, config.created_at);
        assert_eq!(info.pid, state.pid);
        assert_eq!(info.image, "python:3.11");
        assert_eq!(info.cpus, 4);
        assert_eq!(info.memory_mib, 1024);
        assert!(
            published_ports(&info).is_some_and(<[PublishedPort]>::is_empty),
            "a box with no requested mappings is known-empty"
        );
    }

    #[test]
    fn box_info_reports_network_configuration_and_resolved_empty_publications() {
        let config = BoxConfig {
            id: BoxID::parse("01HJK4TNRPQSXYZ8WM6NCVT9R5").unwrap(),
            name: None,
            created_at: Utc::now(),
            container: ContainerRuntimeConfig {
                id: ContainerID::new(),
            },
            options: BoxOptions {
                network: crate::runtime::options::NetworkSpec::Enabled {
                    allow_net: vec!["api.example.com".to_string()],
                },
                ..Default::default()
            },
            engine_kind: crate::vmm::VmmKind::Libkrun,
            box_home: PathBuf::from("/tmp/box"),
        };

        let info = BoxInfo::new(&config, &BoxState::new());
        let network = info.network.as_ref().expect("local network metadata");

        assert_eq!(
            network.outbound.mode,
            crate::runtime::options::NetworkMode::Enabled
        );
        assert_eq!(
            network.outbound.allow_net,
            vec!["api.example.com".to_string()]
        );
        assert_eq!(
            network.inbound.mode,
            crate::runtime::options::NetworkMode::Enabled
        );
        assert_eq!(network.published_ports, Some(Vec::new()));

        let serialized = serde_json::to_value(&info).unwrap();
        assert_eq!(serialized["network"]["outbound"]["mode"], "enabled");
        assert_eq!(serialized["network"]["inbound"]["mode"], "enabled");
        assert_eq!(
            serialized["network"]["published_ports"],
            serde_json::json!([])
        );
        assert!(serialized.get("ports").is_none());
        assert!(serialized.get("ports_resolved").is_none());

        let mut legacy = serialized;
        legacy.as_object_mut().unwrap().remove("network");
        let legacy: BoxInfo = serde_json::from_value(legacy).unwrap();
        assert!(legacy.network.is_none());
    }

    #[test]
    fn box_info_port_resolution_tracks_lifecycle_certainty() {
        let temp_dir = tempfile::tempdir().unwrap();
        let pid = std::process::id();
        let start_time = crate::util::process_start_time(pid).expect("current process start time");
        std::fs::write(
            temp_dir.path().join("shim.pid"),
            format!("{pid}\n{start_time}\nservices-mux-v1\n"),
        )
        .unwrap();

        let config = BoxConfig {
            id: BoxID::parse("01HJK4TNRPQSXYZ8WM6NCVT9R5").unwrap(),
            name: None,
            created_at: Utc::now(),
            container: ContainerRuntimeConfig {
                id: ContainerID::new(),
            },
            options: BoxOptions {
                ports: vec![crate::runtime::options::PortSpec {
                    host_port: None,
                    guest_port: 3000,
                    protocol: crate::runtime::options::PortProtocol::Tcp,
                    host_ip: Some("0.0.0.0".to_string()),
                }],
                ..Default::default()
            },
            engine_kind: crate::vmm::VmmKind::Libkrun,
            box_home: temp_dir.path().to_path_buf(),
        };
        let mut state = BoxState::new();
        state.set_pid(Some(pid));
        state.transition_to(BoxStatus::Running).unwrap();

        let info = BoxInfo::new(&config, &state);
        assert!(published_ports(&info).is_none());
        assert_eq!(
            serde_json::to_value(&info).unwrap()["network"]["published_ports"],
            serde_json::Value::Null,
            "BoxInfo must distinguish unresolved bindings from confirmed-empty bindings"
        );

        state.transition_to(BoxStatus::Stopping).unwrap();
        let stopping = BoxInfo::new(&config, &state);
        assert!(
            published_ports(&stopping).is_none(),
            "a stopping lifecycle may still own active mappings"
        );
        state.transition_to(BoxStatus::Stopped).unwrap();
        let stopped_with_live_shim = BoxInfo::new(&config, &state);
        assert!(published_ports(&stopped_with_live_shim).is_none());

        std::fs::write(temp_dir.path().join("shim.pid"), format!("{pid}\n")).unwrap();
        let stopped_with_legacy_shim = BoxInfo::new(&config, &state);
        assert!(
            published_ports(&stopped_with_legacy_shim).is_none(),
            "an alive legacy shim is uncertain, never confirmed-empty"
        );

        std::fs::remove_file(temp_dir.path().join("shim.pid")).unwrap();
        let stopped = BoxInfo::new(&config, &state);
        assert!(
            published_ports(&stopped).is_some_and(<[PublishedPort]>::is_empty),
            "a stopped box is known-empty"
        );

        state.status = BoxStatus::Unknown;
        let unknown = BoxInfo::new(&config, &state);
        assert!(
            published_ports(&unknown).is_none(),
            "unknown lifecycle state cannot prove that mappings are absent"
        );
    }

    #[test]
    fn test_container_id_new() {
        let id1 = ContainerID::new();
        let id2 = ContainerID::new();

        // IDs should be 64 characters
        assert_eq!(id1.as_str().len(), ContainerID::FULL_LENGTH);
        assert_eq!(id2.as_str().len(), ContainerID::FULL_LENGTH);

        // IDs should be unique
        assert_ne!(id1, id2);

        // IDs should be lowercase hex
        assert!(
            id1.as_str()
                .chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase())
        );
    }

    #[test]
    fn test_container_id_short() {
        let id = ContainerID::new();

        // Short form should be 12 characters
        assert_eq!(id.short().len(), ContainerID::SHORT_LENGTH);

        // Short form should be prefix of full ID
        assert!(id.as_str().starts_with(id.short()));
    }

    #[test]
    fn test_container_id_from_str() {
        // Valid ID
        let valid = "a".repeat(64);
        assert!(ContainerID::parse(&valid).is_some());

        // Invalid: too short
        assert!(ContainerID::parse("abc123").is_none());

        // Invalid: uppercase
        let uppercase = "A".repeat(64);
        assert!(ContainerID::parse(&uppercase).is_none());

        // Invalid: non-hex
        let non_hex = "g".repeat(64);
        assert!(ContainerID::parse(&non_hex).is_none());
    }

    #[test]
    fn test_container_id_display() {
        let id = ContainerID::new();
        let display = format!("{}", id);
        assert_eq!(display, id.as_str());
    }

    #[test]
    fn test_container_id_debug() {
        let id = ContainerID::new();
        let debug = format!("{:?}", id);
        assert!(debug.contains(id.short()));
        assert!(debug.starts_with("ContainerID("));
    }

    // ========================================================================
    // Bytes tests
    // ========================================================================

    #[test]
    fn test_bytes_constructors() {
        assert_eq!(Bytes::from_bytes(1000).as_bytes(), 1000);
        assert_eq!(Bytes::from_kib(1).as_bytes(), 1024);
        assert_eq!(Bytes::from_mib(1).as_bytes(), 1024 * 1024);
        assert_eq!(Bytes::from_gib(1).as_bytes(), 1024 * 1024 * 1024);
    }

    #[test]
    fn test_bytes_conversions() {
        let size = Bytes::from_mib(512);
        assert_eq!(size.as_kib(), 512 * 1024);
        assert_eq!(size.as_mib(), 512);

        // Truncating division
        let odd_size = Bytes::from_bytes(1500);
        assert_eq!(odd_size.as_kib(), 1); // 1500 / 1024 = 1
    }

    #[test]
    fn test_bytes_from_u64() {
        let b: Bytes = 1024u64.into();
        assert_eq!(b.as_bytes(), 1024);

        let raw: u64 = Bytes::from_mib(1).into();
        assert_eq!(raw, 1024 * 1024);
    }

    #[test]
    fn test_bytes_display() {
        assert_eq!(format!("{}", Bytes::from_gib(2)), "2 GiB");
        assert_eq!(format!("{}", Bytes::from_mib(512)), "512 MiB");
        assert_eq!(format!("{}", Bytes::from_kib(64)), "64 KiB");
        assert_eq!(format!("{}", Bytes::from_bytes(500)), "500 bytes");

        // Non-even values show in smaller unit
        assert_eq!(format!("{}", Bytes::from_bytes(1500)), "1500 bytes");
    }

    #[test]
    fn test_bytes_ordering() {
        assert!(Bytes::from_mib(1) < Bytes::from_mib(2));
        assert!(Bytes::from_gib(1) > Bytes::from_mib(512));
    }

    #[test]
    fn test_bytes_default() {
        assert_eq!(Bytes::default().as_bytes(), 0);
    }

    // ========================================================================
    // Seconds tests
    // ========================================================================

    #[test]
    fn test_seconds_constructors() {
        assert_eq!(Seconds::from_seconds(30).as_seconds(), 30);
        assert_eq!(Seconds::from_minutes(5).as_seconds(), 300);
        assert_eq!(Seconds::from_hours(1).as_seconds(), 3600);
    }

    #[test]
    fn test_seconds_conversions() {
        let duration = Seconds::from_hours(2);
        assert_eq!(duration.as_minutes(), 120);
        assert_eq!(duration.as_seconds(), 7200);

        // Truncating division
        let odd_duration = Seconds::from_seconds(90);
        assert_eq!(odd_duration.as_minutes(), 1); // 90 / 60 = 1
    }

    #[test]
    fn test_seconds_from_u64() {
        let s: Seconds = 300u64.into();
        assert_eq!(s.as_seconds(), 300);

        let raw: u64 = Seconds::from_minutes(5).into();
        assert_eq!(raw, 300);
    }

    #[test]
    fn test_seconds_display() {
        assert_eq!(format!("{}", Seconds::from_hours(2)), "2 hours");
        assert_eq!(format!("{}", Seconds::from_minutes(30)), "30 minutes");
        assert_eq!(format!("{}", Seconds::from_seconds(45)), "45 seconds");

        // Non-even values show in seconds
        assert_eq!(format!("{}", Seconds::from_seconds(90)), "90 seconds");
    }

    #[test]
    fn test_seconds_ordering() {
        assert!(Seconds::from_seconds(30) < Seconds::from_minutes(1));
        assert!(Seconds::from_hours(1) > Seconds::from_minutes(30));
    }

    #[test]
    fn test_seconds_default() {
        assert_eq!(Seconds::default().as_seconds(), 0);
    }
}