boxferry-runtime 0.1.1

Runtime-neutral observation and reconstruction for BoxFerry
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
//! Runtime-independent effective-state observations.

use std::{error::Error, fmt};

use boxferry_model::{
    HealthcheckCommand, HealthcheckDuration, HealthcheckRetries, Identifier, ImageReference, Mount, NetworkAttachment,
    Port, ProtectedString, RestartPolicy, SourceId,
};

/// Container implementation from which a snapshot was obtained.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RuntimeImplementation {
    /// Docker Engine or a compatible Docker API implementation.
    Docker,
    /// Podman or the Podman service API.
    Podman,
    /// Another explicitly named runtime implementation.
    Other(Identifier),
}

impl RuntimeImplementation {
    /// Returns the stable implementation name used in diagnostics.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Docker => "docker",
            Self::Podman => "podman",
            Self::Other(name) => name.as_str(),
        }
    }
}

/// Effective command arguments observed from a container or image.
///
/// Runtime inspection cannot recover whether the original definition used shell or exec syntax.
/// Arguments are therefore retained as an effective exec vector and are sensitive by default.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum EffectiveCommand {
    /// Effective argument vector, redacted from debug output.
    Exec(Vec<ProtectedString>),
    /// The runtime reported an explicitly empty command.
    Empty,
}

impl EffectiveCommand {
    /// Creates an effective argument vector whose values are sensitive by default.
    #[must_use]
    pub fn exec<I, S>(arguments: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self::Exec(
            arguments
                .into_iter()
                .map(|argument| ProtectedString::sensitive(argument.into()))
                .collect(),
        )
    }

    /// Returns the effective argument vector, or `None` for an explicit empty command.
    #[must_use]
    pub fn arguments(&self) -> Option<&[ProtectedString]> {
        match self {
            Self::Exec(arguments) => Some(arguments),
            Self::Empty => None,
        }
    }
}

/// One effective runtime environment value.
///
/// Values from inspection are sensitive by default because environment data frequently contains
/// credentials. Callers must explicitly expose the value when mapping or rendering authorized
/// output.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RuntimeEnvironmentVariable {
    name: Identifier,
    value: ProtectedString,
}

/// One effective runtime metadata label.
///
/// Inspection exposes only the merged effective value; it does not prove whether the value came
/// from image metadata, a container-create request, or runtime-generated orchestration metadata.
/// Values are therefore sensitive by default until an output caller explicitly exposes them.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RuntimeMetadataLabel {
    name: Identifier,
    value: ProtectedString,
}

impl RuntimeMetadataLabel {
    /// Creates a sensitive effective metadata label.
    #[must_use]
    pub fn new(name: Identifier, value: impl Into<String>) -> Self {
        Self {
            name,
            value: ProtectedString::sensitive(value),
        }
    }

    /// Returns the opaque metadata-label name.
    #[must_use]
    pub const fn name(&self) -> &Identifier {
        &self.name
    }

    /// Returns the protected effective metadata-label value.
    #[must_use]
    pub const fn value(&self) -> &ProtectedString {
        &self.value
    }
}

impl RuntimeEnvironmentVariable {
    /// Creates a sensitive effective environment value.
    #[must_use]
    pub fn new(name: Identifier, value: impl Into<String>) -> Self {
        Self {
            name,
            value: ProtectedString::sensitive(value),
        }
    }

    /// Returns the environment-variable name.
    #[must_use]
    pub const fn name(&self) -> &Identifier {
        &self.name
    }

    /// Returns the protected effective value.
    #[must_use]
    pub const fn value(&self) -> &ProtectedString {
        &self.value
    }
}

/// Effective regular health-check configuration observed from a container or image.
///
/// An empty value records that the native adapter inspected the field and found no regular health
/// check. Commands and their arguments remain sensitive by default through [`ProtectedString`].
/// Podman's separate startup-healthcheck family is intentionally not represented here.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct RuntimeHealthcheck {
    command: Option<HealthcheckCommand>,
    disabled: Option<bool>,
    interval: Option<HealthcheckDuration>,
    timeout: Option<HealthcheckDuration>,
    retries: Option<HealthcheckRetries>,
    start_period: Option<HealthcheckDuration>,
    start_interval: Option<HealthcheckDuration>,
}

impl RuntimeHealthcheck {
    /// Creates an observed absence of regular health-check configuration.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            command: None,
            disabled: None,
            interval: None,
            timeout: None,
            retries: None,
            start_period: None,
            start_interval: None,
        }
    }

    /// Returns whether inspection proved that no regular health-check field is configured.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.command.is_none()
            && self.disabled.is_none()
            && self.interval.is_none()
            && self.timeout.is_none()
            && self.retries.is_none()
            && self.start_period.is_none()
            && self.start_interval.is_none()
    }

    /// Records the effective regular health-check command.
    pub fn set_command(&mut self, command: HealthcheckCommand) {
        self.command = Some(command);
    }

    /// Returns the effective regular health-check command.
    #[must_use]
    pub const fn command(&self) -> Option<&HealthcheckCommand> {
        self.command.as_ref()
    }

    /// Records an explicit disabled state.
    pub fn set_disabled(&mut self, disabled: bool) {
        self.disabled = Some(disabled);
    }

    /// Returns the explicit disabled state.
    #[must_use]
    pub const fn disabled(&self) -> Option<bool> {
        self.disabled
    }

    /// Records the effective interval between regular checks.
    pub fn set_interval(&mut self, interval: HealthcheckDuration) {
        self.interval = Some(interval);
    }

    /// Returns the effective interval between regular checks.
    #[must_use]
    pub const fn interval(&self) -> Option<&HealthcheckDuration> {
        self.interval.as_ref()
    }

    /// Records the effective timeout of one regular check.
    pub fn set_timeout(&mut self, timeout: HealthcheckDuration) {
        self.timeout = Some(timeout);
    }

    /// Returns the effective timeout of one regular check.
    #[must_use]
    pub const fn timeout(&self) -> Option<&HealthcheckDuration> {
        self.timeout.as_ref()
    }

    /// Records the effective regular-check retry count.
    pub fn set_retries(&mut self, retries: HealthcheckRetries) {
        self.retries = Some(retries);
    }

    /// Returns the effective regular-check retry count.
    #[must_use]
    pub const fn retries(&self) -> Option<&HealthcheckRetries> {
        self.retries.as_ref()
    }

    /// Records the effective regular health-check start period.
    pub fn set_start_period(&mut self, start_period: HealthcheckDuration) {
        self.start_period = Some(start_period);
    }

    /// Returns the effective regular health-check start period.
    #[must_use]
    pub const fn start_period(&self) -> Option<&HealthcheckDuration> {
        self.start_period.as_ref()
    }

    /// Records the effective start interval where the native runtime exposes equivalent semantics.
    pub fn set_start_interval(&mut self, start_interval: HealthcheckDuration) {
        self.start_interval = Some(start_interval);
    }

    /// Returns the effective start interval.
    #[must_use]
    pub const fn start_interval(&self) -> Option<&HealthcheckDuration> {
        self.start_interval.as_ref()
    }
}

/// Optional runtime creation-command evidence.
///
/// Arguments are sensitive by default and never override contradictory effective inspection
/// fields. The evidence can contribute provenance without being present at all.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CreationEvidence {
    source_id: SourceId,
    arguments: Vec<ProtectedString>,
}

impl CreationEvidence {
    /// Creates optional evidence with sensitive command arguments.
    #[must_use]
    pub fn new<I, S>(source_id: SourceId, arguments: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            source_id,
            arguments: arguments
                .into_iter()
                .map(|argument| ProtectedString::sensitive(argument.into()))
                .collect(),
        }
    }

    /// Returns the stable, caller-redacted evidence identity.
    #[must_use]
    pub const fn source_id(&self) -> &SourceId {
        &self.source_id
    }

    /// Returns the protected creation arguments.
    #[must_use]
    pub fn arguments(&self) -> &[ProtectedString] {
        &self.arguments
    }
}

/// Effective image configuration used to classify container overrides.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ImageObservation {
    source_id: SourceId,
    command: Option<EffectiveCommand>,
    environment: Option<Vec<RuntimeEnvironmentVariable>>,
    labels: Option<Vec<RuntimeMetadataLabel>>,
    user: Option<ProtectedString>,
    working_directory: Option<ProtectedString>,
    healthcheck: Option<RuntimeHealthcheck>,
}

impl ImageObservation {
    /// Creates an image observation with no assumed fields.
    #[must_use]
    pub const fn new(source_id: SourceId) -> Self {
        Self {
            source_id,
            command: None,
            environment: None,
            labels: None,
            user: None,
            working_directory: None,
            healthcheck: None,
        }
    }

    /// Returns the stable, caller-redacted image identity.
    #[must_use]
    pub const fn source_id(&self) -> &SourceId {
        &self.source_id
    }

    /// Records the image's effective command default.
    pub fn set_command(&mut self, command: EffectiveCommand) {
        self.command = Some(command);
    }

    /// Returns the observed command default, if the adapter supplied it.
    #[must_use]
    pub const fn command(&self) -> Option<&EffectiveCommand> {
        self.command.as_ref()
    }

    /// Records the complete ordered image environment defaults, including an empty collection.
    pub fn set_environment(&mut self, environment: Vec<RuntimeEnvironmentVariable>) {
        self.environment = Some(environment);
    }

    /// Returns the observed environment defaults, if the adapter supplied them.
    #[must_use]
    pub fn environment(&self) -> Option<&[RuntimeEnvironmentVariable]> {
        self.environment.as_deref()
    }

    /// Records the complete deterministic image metadata-label map, including an empty map.
    pub fn set_labels(&mut self, labels: Vec<RuntimeMetadataLabel>) {
        self.labels = Some(labels);
    }

    /// Returns the observed image metadata labels, if the adapter supplied them.
    #[must_use]
    pub fn labels(&self) -> Option<&[RuntimeMetadataLabel]> {
        self.labels.as_deref()
    }

    /// Records a non-empty image user default as sensitive runtime data.
    pub fn set_user(&mut self, user: impl Into<String>) {
        self.user = Some(ProtectedString::sensitive(user));
    }

    /// Returns the observed image user default.
    #[must_use]
    pub const fn user(&self) -> Option<&ProtectedString> {
        self.user.as_ref()
    }

    /// Records a non-empty image working-directory default as sensitive runtime data.
    pub fn set_working_directory(&mut self, working_directory: impl Into<String>) {
        self.working_directory = Some(ProtectedString::sensitive(working_directory));
    }

    /// Returns the observed image working-directory default.
    #[must_use]
    pub const fn working_directory(&self) -> Option<&ProtectedString> {
        self.working_directory.as_ref()
    }

    /// Records the complete effective regular health-check configuration, including its absence.
    pub fn set_healthcheck(&mut self, healthcheck: RuntimeHealthcheck) {
        self.healthcheck = Some(healthcheck);
    }

    /// Returns the observed regular health-check configuration, if the adapter supplied it.
    #[must_use]
    pub const fn healthcheck(&self) -> Option<&RuntimeHealthcheck> {
        self.healthcheck.as_ref()
    }
}

/// Effective state and relationships of one runtime container.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContainerObservation {
    source_id: SourceId,
    name: Identifier,
    image: Option<ImageReference>,
    image_source_id: Option<SourceId>,
    command: Option<EffectiveCommand>,
    restart_policy: Option<RestartPolicy>,
    environment: Option<Vec<RuntimeEnvironmentVariable>>,
    labels: Option<Vec<RuntimeMetadataLabel>>,
    user: Option<ProtectedString>,
    working_directory: Option<ProtectedString>,
    healthcheck: Option<RuntimeHealthcheck>,
    read_only_root_filesystem: Option<bool>,
    ports: Vec<Port>,
    mounts: Vec<Mount>,
    networks: Vec<NetworkAttachment>,
    pod_source_id: Option<SourceId>,
    creation_evidence: Option<CreationEvidence>,
}

impl ContainerObservation {
    /// Creates an empty container observation for an explicitly named resource.
    #[must_use]
    pub const fn new(source_id: SourceId, name: Identifier) -> Self {
        Self {
            source_id,
            name,
            image: None,
            image_source_id: None,
            command: None,
            restart_policy: None,
            environment: None,
            labels: None,
            user: None,
            working_directory: None,
            healthcheck: None,
            read_only_root_filesystem: None,
            ports: Vec::new(),
            mounts: Vec::new(),
            networks: Vec::new(),
            pod_source_id: None,
            creation_evidence: None,
        }
    }

    /// Returns the stable, caller-redacted container identity.
    #[must_use]
    pub const fn source_id(&self) -> &SourceId {
        &self.source_id
    }

    /// Returns the neutral service name selected by the runtime adapter.
    #[must_use]
    pub const fn name(&self) -> &Identifier {
        &self.name
    }

    /// Records the effective image reference and optional linked image observation.
    pub fn set_image(&mut self, image: ImageReference, image_source_id: Option<SourceId>) {
        self.image = Some(image);
        self.image_source_id = image_source_id;
    }

    /// Returns the effective image reference.
    #[must_use]
    pub const fn image(&self) -> Option<&ImageReference> {
        self.image.as_ref()
    }

    /// Returns the linked image-observation identity used for override reconstruction.
    #[must_use]
    pub const fn image_source_id(&self) -> Option<&SourceId> {
        self.image_source_id.as_ref()
    }

    /// Records the effective container command.
    pub fn set_command(&mut self, command: EffectiveCommand) {
        self.command = Some(command);
    }

    /// Returns the effective command, if the adapter supplied it.
    #[must_use]
    pub const fn command(&self) -> Option<&EffectiveCommand> {
        self.command.as_ref()
    }

    /// Records the effective container-level automatic restart policy.
    pub fn set_restart_policy(&mut self, restart_policy: RestartPolicy) {
        self.restart_policy = Some(restart_policy);
    }

    /// Returns the effective container-level automatic restart policy, if supplied.
    #[must_use]
    pub const fn restart_policy(&self) -> Option<RestartPolicy> {
        self.restart_policy
    }

    /// Records the complete ordered effective environment, including an empty collection.
    pub fn set_environment(&mut self, environment: Vec<RuntimeEnvironmentVariable>) {
        self.environment = Some(environment);
    }

    /// Returns the effective environment, if the adapter supplied it.
    #[must_use]
    pub fn environment(&self) -> Option<&[RuntimeEnvironmentVariable]> {
        self.environment.as_deref()
    }

    /// Records the complete deterministic effective metadata-label map, including an empty map.
    pub fn set_labels(&mut self, labels: Vec<RuntimeMetadataLabel>) {
        self.labels = Some(labels);
    }

    /// Returns the effective metadata labels, if the adapter supplied them.
    #[must_use]
    pub fn labels(&self) -> Option<&[RuntimeMetadataLabel]> {
        self.labels.as_deref()
    }

    /// Records a non-empty effective container user as sensitive runtime data.
    pub fn set_user(&mut self, user: impl Into<String>) {
        self.user = Some(ProtectedString::sensitive(user));
    }

    /// Returns the effective container user, if the adapter supplied one.
    #[must_use]
    pub const fn user(&self) -> Option<&ProtectedString> {
        self.user.as_ref()
    }

    /// Records a non-empty effective container working directory as sensitive runtime data.
    pub fn set_working_directory(&mut self, working_directory: impl Into<String>) {
        self.working_directory = Some(ProtectedString::sensitive(working_directory));
    }

    /// Returns the effective container working directory, if supplied.
    #[must_use]
    pub const fn working_directory(&self) -> Option<&ProtectedString> {
        self.working_directory.as_ref()
    }

    /// Records the complete effective regular health-check configuration, including its absence.
    pub fn set_healthcheck(&mut self, healthcheck: RuntimeHealthcheck) {
        self.healthcheck = Some(healthcheck);
    }

    /// Returns the observed regular health-check configuration, if the adapter supplied it.
    #[must_use]
    pub const fn healthcheck(&self) -> Option<&RuntimeHealthcheck> {
        self.healthcheck.as_ref()
    }

    /// Records the effective read-only-root-filesystem choice.
    pub fn set_read_only_root_filesystem(&mut self, read_only: bool) {
        self.read_only_root_filesystem = Some(read_only);
    }

    /// Returns the effective read-only-root-filesystem choice, if supplied.
    #[must_use]
    pub const fn read_only_root_filesystem(&self) -> Option<bool> {
        self.read_only_root_filesystem
    }

    /// Appends one observed published port.
    pub fn add_port(&mut self, port: Port) {
        self.ports.push(port);
    }

    /// Returns observed ports in runtime response order.
    #[must_use]
    pub fn ports(&self) -> &[Port] {
        &self.ports
    }

    /// Appends one observed storage relationship.
    pub fn add_mount(&mut self, mount: Mount) {
        self.mounts.push(mount);
    }

    /// Returns observed mounts in runtime response order.
    #[must_use]
    pub fn mounts(&self) -> &[Mount] {
        &self.mounts
    }

    /// Appends one observed network relationship with all aliases in runtime response order.
    pub fn add_network(&mut self, network: NetworkAttachment) {
        self.networks.push(network);
    }

    /// Returns observed network relationships in runtime response order.
    #[must_use]
    pub fn networks(&self) -> &[NetworkAttachment] {
        &self.networks
    }

    /// Records the containing Podman pod observation, if any.
    pub fn set_pod_source_id(&mut self, source_id: SourceId) {
        self.pod_source_id = Some(source_id);
    }

    /// Returns the containing pod identity.
    #[must_use]
    pub const fn pod_source_id(&self) -> Option<&SourceId> {
        self.pod_source_id.as_ref()
    }

    /// Attaches optional creation-command evidence without changing effective values.
    pub fn set_creation_evidence(&mut self, evidence: CreationEvidence) {
        self.creation_evidence = Some(evidence);
    }

    /// Returns optional creation-command evidence.
    #[must_use]
    pub const fn creation_evidence(&self) -> Option<&CreationEvidence> {
        self.creation_evidence.as_ref()
    }
}

/// One inspected runtime network.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NetworkObservation {
    source_id: SourceId,
    name: Identifier,
}

impl NetworkObservation {
    /// Creates a runtime network observation.
    #[must_use]
    pub const fn new(source_id: SourceId, name: Identifier) -> Self {
        Self { source_id, name }
    }

    /// Returns the stable, caller-redacted network identity.
    #[must_use]
    pub const fn source_id(&self) -> &SourceId {
        &self.source_id
    }

    /// Returns the neutral resource name selected by the runtime adapter.
    #[must_use]
    pub const fn name(&self) -> &Identifier {
        &self.name
    }
}

/// One inspected runtime volume.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VolumeObservation {
    source_id: SourceId,
    name: Identifier,
}

impl VolumeObservation {
    /// Creates a runtime volume observation.
    #[must_use]
    pub const fn new(source_id: SourceId, name: Identifier) -> Self {
        Self { source_id, name }
    }

    /// Returns the stable, caller-redacted volume identity.
    #[must_use]
    pub const fn source_id(&self) -> &SourceId {
        &self.source_id
    }

    /// Returns the neutral resource name selected by the runtime adapter.
    #[must_use]
    pub const fn name(&self) -> &Identifier {
        &self.name
    }
}

/// One inspected Podman pod and its ordered container relationships.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PodObservation {
    source_id: SourceId,
    name: Identifier,
    members: Vec<SourceId>,
    creation_evidence: Option<CreationEvidence>,
}

impl PodObservation {
    /// Creates an empty pod observation.
    #[must_use]
    pub const fn new(source_id: SourceId, name: Identifier) -> Self {
        Self {
            source_id,
            name,
            members: Vec::new(),
            creation_evidence: None,
        }
    }

    /// Returns the stable, caller-redacted pod identity.
    #[must_use]
    pub const fn source_id(&self) -> &SourceId {
        &self.source_id
    }

    /// Returns the pod name selected by the runtime adapter.
    #[must_use]
    pub const fn name(&self) -> &Identifier {
        &self.name
    }

    /// Appends one member container identity in runtime response order.
    pub fn add_member(&mut self, source_id: SourceId) {
        self.members.push(source_id);
    }

    /// Returns member container identities in runtime response order.
    #[must_use]
    pub fn members(&self) -> &[SourceId] {
        &self.members
    }

    /// Attaches optional creation-command evidence without changing effective values.
    pub fn set_creation_evidence(&mut self, evidence: CreationEvidence) {
        self.creation_evidence = Some(evidence);
    }

    /// Returns optional pod creation-command evidence.
    #[must_use]
    pub const fn creation_evidence(&self) -> Option<&CreationEvidence> {
        self.creation_evidence.as_ref()
    }
}

/// A complete caller-selected set of related runtime observations.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RuntimeSnapshot {
    application_name: Identifier,
    implementation: RuntimeImplementation,
    containers: Vec<ContainerObservation>,
    images: Vec<ImageObservation>,
    networks: Vec<NetworkObservation>,
    volumes: Vec<VolumeObservation>,
    pods: Vec<PodObservation>,
}

impl RuntimeSnapshot {
    /// Creates an empty snapshot without reading a runtime or ambient state.
    #[must_use]
    pub const fn new(application_name: Identifier, implementation: RuntimeImplementation) -> Self {
        Self {
            application_name,
            implementation,
            containers: Vec::new(),
            images: Vec::new(),
            networks: Vec::new(),
            volumes: Vec::new(),
            pods: Vec::new(),
        }
    }

    /// Returns the neutral application name selected by the caller.
    #[must_use]
    pub const fn application_name(&self) -> &Identifier {
        &self.application_name
    }

    /// Returns the runtime implementation that produced this snapshot.
    #[must_use]
    pub const fn implementation(&self) -> &RuntimeImplementation {
        &self.implementation
    }

    /// Adds a uniquely identified container observation.
    ///
    /// # Errors
    ///
    /// Returns [`RuntimeSnapshotError`] for duplicate source identities or container names.
    pub fn add_container(&mut self, container: ContainerObservation) -> Result<(), RuntimeSnapshotError> {
        self.ensure_source_unique(container.source_id())?;
        Self::ensure_name_unique(
            "container",
            container.name(),
            self.containers.iter().map(ContainerObservation::name),
        )?;
        self.containers.push(container);
        Ok(())
    }

    /// Returns containers in caller-selected discovery order.
    #[must_use]
    pub fn containers(&self) -> &[ContainerObservation] {
        &self.containers
    }

    /// Adds a uniquely identified image observation.
    ///
    /// # Errors
    ///
    /// Returns [`RuntimeSnapshotError`] for a duplicate source identity.
    pub fn add_image(&mut self, image: ImageObservation) -> Result<(), RuntimeSnapshotError> {
        self.ensure_source_unique(image.source_id())?;
        self.images.push(image);
        Ok(())
    }

    /// Returns images in caller-selected discovery order.
    #[must_use]
    pub fn images(&self) -> &[ImageObservation] {
        &self.images
    }

    /// Adds a uniquely identified and named network observation.
    ///
    /// # Errors
    ///
    /// Returns [`RuntimeSnapshotError`] for duplicate source identities or network names.
    pub fn add_network(&mut self, network: NetworkObservation) -> Result<(), RuntimeSnapshotError> {
        self.ensure_source_unique(network.source_id())?;
        Self::ensure_name_unique(
            "network",
            network.name(),
            self.networks.iter().map(NetworkObservation::name),
        )?;
        self.networks.push(network);
        Ok(())
    }

    /// Returns networks in caller-selected discovery order.
    #[must_use]
    pub fn networks(&self) -> &[NetworkObservation] {
        &self.networks
    }

    /// Adds a uniquely identified and named volume observation.
    ///
    /// # Errors
    ///
    /// Returns [`RuntimeSnapshotError`] for duplicate source identities or volume names.
    pub fn add_volume(&mut self, volume: VolumeObservation) -> Result<(), RuntimeSnapshotError> {
        self.ensure_source_unique(volume.source_id())?;
        Self::ensure_name_unique(
            "volume",
            volume.name(),
            self.volumes.iter().map(VolumeObservation::name),
        )?;
        self.volumes.push(volume);
        Ok(())
    }

    /// Returns volumes in caller-selected discovery order.
    #[must_use]
    pub fn volumes(&self) -> &[VolumeObservation] {
        &self.volumes
    }

    /// Adds a uniquely identified and named pod observation.
    ///
    /// # Errors
    ///
    /// Returns [`RuntimeSnapshotError`] for duplicate source identities or pod names.
    pub fn add_pod(&mut self, pod: PodObservation) -> Result<(), RuntimeSnapshotError> {
        self.ensure_source_unique(pod.source_id())?;
        Self::ensure_name_unique("pod", pod.name(), self.pods.iter().map(PodObservation::name))?;
        self.pods.push(pod);
        Ok(())
    }

    /// Returns pods in caller-selected discovery order.
    #[must_use]
    pub fn pods(&self) -> &[PodObservation] {
        &self.pods
    }

    fn ensure_source_unique(&self, source_id: &SourceId) -> Result<(), RuntimeSnapshotError> {
        if self.source_ids().any(|candidate| candidate == source_id) {
            return Err(RuntimeSnapshotError::DuplicateSourceIdentity {
                source_id: source_id.clone(),
            });
        }
        Ok(())
    }

    fn ensure_name_unique<'a>(
        kind: &'static str,
        name: &Identifier,
        existing: impl Iterator<Item = &'a Identifier>,
    ) -> Result<(), RuntimeSnapshotError> {
        if existing.into_iter().any(|candidate| candidate == name) {
            return Err(RuntimeSnapshotError::DuplicateResource {
                kind,
                name: name.as_str().to_owned(),
            });
        }
        Ok(())
    }

    fn source_ids(&self) -> impl Iterator<Item = &SourceId> {
        self.containers
            .iter()
            .map(ContainerObservation::source_id)
            .chain(self.images.iter().map(ImageObservation::source_id))
            .chain(self.networks.iter().map(NetworkObservation::source_id))
            .chain(self.volumes.iter().map(VolumeObservation::source_id))
            .chain(self.pods.iter().map(PodObservation::source_id))
    }
}

/// Invalid runtime snapshot structure.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RuntimeSnapshotError {
    /// Two top-level observations used the same caller-selected source identity.
    DuplicateSourceIdentity {
        /// Duplicate stable, caller-redacted identity.
        source_id: SourceId,
    },
    /// Two resources of one kind used the same neutral name.
    DuplicateResource {
        /// Runtime resource kind.
        kind: &'static str,
        /// Duplicate neutral name.
        name: String,
    },
}

impl fmt::Display for RuntimeSnapshotError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DuplicateSourceIdentity { source_id } => {
                write!(formatter, "duplicate runtime source identity `{}`", source_id.as_str())
            }
            Self::DuplicateResource { kind, name } => write!(formatter, "duplicate runtime {kind} `{name}`"),
        }
    }
}

impl Error for RuntimeSnapshotError {}

#[cfg(test)]
mod tests {
    use boxferry_model::{Identifier, SourceId};

    use super::{
        ContainerObservation, CreationEvidence, EffectiveCommand, RuntimeEnvironmentVariable, RuntimeImplementation,
        RuntimeMetadataLabel, RuntimeSnapshot,
    };

    #[test]
    fn inspected_values_are_redacted_by_default() -> Result<(), String> {
        let command = EffectiveCommand::exec(["server", "--password=never-print-this"]);
        let environment = RuntimeEnvironmentVariable::new(id("PASSWORD")?, "never-print-this");
        let label = RuntimeMetadataLabel::new(id("com.example.token")?, "never-print-this");
        let mut container = ContainerObservation::new(source("runtime:podman:container:web")?, id("web")?);
        container.set_user("never-print-this");
        container.set_working_directory("/never-print-this");
        let evidence = CreationEvidence::new(
            source("runtime:podman:create:web")?,
            ["--env", "PASSWORD=never-print-this"],
        );

        for debug in [
            format!("{command:?}"),
            format!("{environment:?}"),
            format!("{label:?}"),
            format!("{container:?}"),
            format!("{evidence:?}"),
        ] {
            assert!(!debug.contains("never-print-this"));
            assert!(debug.contains("[REDACTED]"));
        }
        Ok(())
    }

    #[test]
    fn snapshot_rejects_ambiguous_source_identities_and_names() -> Result<(), String> {
        let mut snapshot = RuntimeSnapshot::new(id("example")?, RuntimeImplementation::Podman);
        snapshot
            .add_container(ContainerObservation::new(source("runtime:container:web")?, id("web")?))
            .map_err(|error| error.to_string())?;

        let duplicate_source = snapshot
            .add_container(ContainerObservation::new(
                source("runtime:container:web")?,
                id("worker")?,
            ))
            .err()
            .ok_or("duplicate source must fail")?;
        assert!(duplicate_source.to_string().contains("source identity"));

        let duplicate_name = snapshot
            .add_container(ContainerObservation::new(
                source("runtime:container:web-2")?,
                id("web")?,
            ))
            .err()
            .ok_or("duplicate name must fail")?;
        assert!(duplicate_name.to_string().contains("container `web`"));
        Ok(())
    }

    fn id(value: &str) -> Result<Identifier, String> {
        Identifier::new(value).map_err(|error| error.to_string())
    }

    fn source(value: &str) -> Result<SourceId, String> {
        SourceId::new(value).map_err(|error| error.to_string())
    }
}