vce 0.1.1

A stateful virtual OS engine with an embeddable machine and shell API
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
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
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
//! The supported embedding API: machine construction, configuration, state
//! observation, and sessions.

use engine::{ActorId, Engine, EventType, ObjectEvent, SubscriptionId, Timestamp, VirtualPath};
use os::linux::Linux;
use os::macos::MacOS;
use os::unix::user::UserId;
use os::windows::Windows;
use os::{FileMode, HostIdentity, OperatingSystem, OsError, UnixFlavor};

use crate::{CommandOutput, Session, SessionError, ShellChoice};

/// A semantic feature exposed by a machine profile's structured API.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Capability {
    /// Account and group inspection and configuration.
    Identity,
    /// Service inspection and configuration.
    Services,
    /// Firewall profile and rule inspection and configuration.
    FirewallRules,
    /// File ownership and mode inspection and atomic creation.
    FileMetadata,
    /// Commands can be promoted to structured failures on nonzero status.
    CheckedCommandExecution,
    /// Sessions expose cooperative cancellation and wall-clock deadlines.
    SessionCancellation,
    /// Process enumeration and control.
    Processes,
    /// Installed package inspection.
    Packages,
    /// Available package-update inspection.
    PackageUpdates,
    /// Startup-item inspection and configuration.
    StartupEntries,
    /// Scheduled-task inspection and configuration.
    ScheduledTasks,
    /// Authentication, password, and lockout policy.
    AuthenticationPolicy,
    /// Audit policy and records.
    Audit,
    /// Platform file ACLs.
    FileAcls,
    /// Windows registry objects.
    Registry,
    /// macOS preference domains.
    Preferences,
}

/// Public account state, independent of VCE's internal OS representation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Account {
    /// Login name.
    pub name: String,
    /// Numeric user or account id.
    pub id: u32,
    /// Numeric primary group id.
    pub primary_group_id: u32,
    /// Display or GECOS name.
    pub full_name: String,
    /// Home-directory path.
    pub home: String,
    /// Login-shell path.
    pub shell: String,
    /// Whether authentication is locked.
    pub password_locked: bool,
}

/// Public group state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Group {
    /// Group name.
    pub name: String,
    /// Numeric group id.
    pub id: u32,
    /// Supplementary member names.
    pub members: Vec<String>,
}

/// Public service state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Service {
    /// Unit or service name.
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// Current runtime state.
    pub state: String,
    /// Startup state such as `enabled` or `disabled`.
    pub start_type: String,
}

/// Public firewall-rule state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FirewallRule {
    /// Destination port.
    pub port: u16,
    /// Transport protocol.
    pub protocol: String,
    /// Policy action.
    pub action: String,
    /// Traffic direction.
    pub direction: String,
}

/// Public Unix file metadata.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileMetadata {
    /// Owning account name.
    pub owner: String,
    /// Owning group name.
    pub group: String,
    /// Unix permission and special bits.
    pub mode: FileMode,
    /// Logical byte size.
    pub size: u64,
}

/// Public process state read from the selected OS's process namespace.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Process {
    /// OS-assigned process id.
    pub pid: u32,
    /// Account that launched the process.
    pub user: String,
    /// Executable name.
    pub executable: String,
    /// Arguments after the executable name.
    pub arguments: String,
    /// OS lifecycle state.
    pub state: String,
    /// Working directory at launch.
    pub cwd: String,
}

/// Windows password and account-lockout policy.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PasswordPolicy {
    /// Minimum password length.
    pub min_length: u32,
    /// Maximum password age in days.
    pub max_age_days: u32,
    /// Minimum password age in days.
    pub min_age_days: u32,
    /// Remembered password count.
    pub history: u32,
    /// Whether complexity rules are enabled.
    pub complexity: bool,
    /// Whether reversible password storage is enabled.
    pub reversible_encryption: bool,
    /// Failed logons before lockout; zero disables lockout.
    pub lockout_threshold: u32,
    /// Lockout duration in minutes.
    pub lockout_duration: u32,
    /// Lockout observation window in minutes.
    pub lockout_window: u32,
}

/// One Windows audit-policy category.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AuditCategory {
    /// Native category name.
    pub name: String,
    /// Whether successful events are audited.
    pub success: bool,
    /// Whether failed events are audited.
    pub failure: bool,
}

/// One Windows registry value from the real hive-file tree.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RegistryValue {
    /// Registry value name.
    pub name: String,
    /// Native type such as `REG_SZ` or `REG_DWORD`.
    pub value_type: String,
    /// Text representation stored by VCE's registry model.
    pub data: String,
}

/// A scalar value in a macOS preference plist.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PreferenceValue {
    /// String preference.
    String(String),
    /// Integer preference.
    Integer(i64),
    /// Boolean preference.
    Boolean(bool),
}

/// A supported virtual operating-system profile.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OsKind {
    /// Ubuntu-flavored Linux.
    Linux,
    /// Modern macOS.
    MacOS,
    /// Windows 10 Pro.
    Windows,
}

/// Builds a deterministic VCE machine.
///
/// The builder defaults to user `demo`, host `vce`, and the virtual epoch.
/// Applications should normally set all three explicitly from their own
/// scenario or product configuration.
#[derive(Clone, Debug)]
pub struct MachineBuilder {
    kind: OsKind,
    username: String,
    hostname: String,
    boot_time: Timestamp,
}

impl MachineBuilder {
    /// Creates a builder for one OS profile.
    pub fn new(kind: OsKind) -> Self {
        Self {
            kind,
            username: "demo".to_owned(),
            hostname: "vce".to_owned(),
            boot_time: Timestamp::ZERO,
        }
    }

    /// Sets the initial standard account name.
    ///
    /// VCE normalizes this to the target OS's portable account-name form.
    pub fn username(mut self, username: impl Into<String>) -> Self {
        self.username = username.into();
        self
    }

    /// Sets the virtual machine's host/computer name.
    pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
        self.hostname = hostname.into();
        self
    }

    /// Sets the deterministic virtual boot time.
    pub const fn boot_time(mut self, boot_time: Timestamp) -> Self {
        self.boot_time = boot_time;
        self
    }

    /// Boots the configured machine.
    pub fn build(self) -> Result<Machine, MachineError> {
        let identity = HostIdentity::new(self.username.clone(), self.hostname);
        if identity.is_reserved_username() {
            return Err(MachineError::InvalidConfiguration(format!(
                "'{}' is a reserved system account name",
                identity.username()
            )));
        }
        let default_user = identity.username().to_owned();
        let inner = match self.kind {
            OsKind::Linux => MachineInner::Linux(
                Linux::with_identity(&identity, self.boot_time)
                    .map_err(|error| identity_boot_error(&identity, error))?,
            ),
            OsKind::MacOS => MachineInner::MacOS(
                MacOS::with_identity(&identity, self.boot_time)
                    .map_err(|error| identity_boot_error(&identity, error))?,
            ),
            OsKind::Windows => MachineInner::Windows(
                Windows::with_identity(&identity, self.boot_time)
                    .map_err(|error| identity_boot_error(&identity, error))?,
            ),
        };
        Ok(Machine {
            inner,
            default_user,
            hostname: identity.hostname().to_owned(),
        })
    }
}

fn identity_boot_error(identity: &HostIdentity, error: OsError) -> MachineError {
    match &error {
        OsError::UserAlreadyExists(value) | OsError::GroupAlreadyExists(value)
            if value == identity.username() =>
        {
            MachineError::InvalidConfiguration(format!(
                "'{}' conflicts with a built-in account or group",
                identity.username()
            ))
        }
        _ => error.into(),
    }
}

enum MachineInner {
    Linux(Linux),
    MacOS(MacOS),
    Windows(Windows),
}

/// A booted, stateful VCE machine.
///
/// `Machine` is the ownership boundary for embedding VCE. It retains the OS
/// across sessions and exposes configuration, generic Engine observation,
/// subscriptions, and authenticated shell sessions without requiring an
/// application to depend on VCE's layer crates separately.
pub struct Machine {
    inner: MachineInner,
    default_user: String,
    hostname: String,
}

impl Machine {
    /// Starts a machine builder.
    pub fn builder(kind: OsKind) -> MachineBuilder {
        MachineBuilder::new(kind)
    }

    /// The selected OS profile.
    pub const fn os_kind(&self) -> OsKind {
        match self.inner {
            MachineInner::Linux(_) => OsKind::Linux,
            MachineInner::MacOS(_) => OsKind::MacOS,
            MachineInner::Windows(_) => OsKind::Windows,
        }
    }

    /// The semantic structured capabilities implemented by this profile.
    pub fn capabilities(&self) -> Vec<Capability> {
        let mut capabilities = vec![
            Capability::CheckedCommandExecution,
            Capability::FileMetadata,
            Capability::SessionCancellation,
        ];
        match self.os_kind() {
            OsKind::Linux => capabilities.extend([
                Capability::Identity,
                Capability::Services,
                Capability::FirewallRules,
                Capability::Processes,
            ]),
            OsKind::MacOS => capabilities.extend([
                Capability::Identity,
                Capability::Processes,
                Capability::Preferences,
            ]),
            OsKind::Windows => capabilities.retain(|capability| {
                matches!(
                    capability,
                    Capability::CheckedCommandExecution | Capability::SessionCancellation
                )
            }),
        }
        if self.os_kind() == OsKind::Windows {
            capabilities.extend([
                Capability::Processes,
                Capability::AuthenticationPolicy,
                Capability::Audit,
                Capability::Registry,
            ]);
        }
        capabilities.sort_unstable();
        capabilities
    }

    /// Whether this profile implements a semantic structured capability.
    pub fn supports(&self, capability: Capability) -> bool {
        self.capabilities().contains(&capability)
    }

    /// Returns a structured error unless this OS implements `capability`.
    pub fn require(&self, capability: Capability) -> Result<(), MachineError> {
        if self.supports(capability) {
            Ok(())
        } else {
            Err(MachineError::UnsupportedCapability {
                capability,
                os: self.os_kind(),
            })
        }
    }

    /// All Unix accounts, sorted by numeric id.
    pub fn accounts(&self) -> Result<Vec<Account>, MachineError> {
        let unix = match &self.inner {
            MachineInner::Linux(os) => os.unix(),
            MachineInner::MacOS(os) => os.unix(),
            MachineInner::Windows(_) => {
                return Err(MachineError::UnsupportedCapability {
                    capability: Capability::Identity,
                    os: self.os_kind(),
                });
            }
        };
        Ok(unix
            .users()
            .users()
            .into_iter()
            .map(|user| Account {
                name: user.name().to_owned(),
                id: user.uid().get(),
                primary_group_id: user.primary_group().get(),
                full_name: user.gecos().to_owned(),
                home: user.home().to_owned(),
                shell: user.shell().to_owned(),
                password_locked: matches!(
                    user.password(),
                    os::unix::password::PasswordState::Locked
                ),
            })
            .collect())
    }

    /// All Unix groups, sorted by numeric id.
    pub fn groups(&self) -> Result<Vec<Group>, MachineError> {
        let unix = match &self.inner {
            MachineInner::Linux(os) => os.unix(),
            MachineInner::MacOS(os) => os.unix(),
            MachineInner::Windows(_) => {
                return Err(MachineError::UnsupportedCapability {
                    capability: Capability::Identity,
                    os: self.os_kind(),
                });
            }
        };
        Ok(unix
            .groups()
            .groups()
            .into_iter()
            .map(|group| Group {
                name: group.name().to_owned(),
                id: group.gid().get(),
                members: group
                    .members()
                    .iter()
                    .filter_map(|uid| unix.users().get(*uid))
                    .map(|user| user.name().to_owned())
                    .collect(),
            })
            .collect())
    }

    /// All installed Linux services, read from unit, wants, and runtime files.
    pub fn services(&self) -> Result<Vec<Service>, MachineError> {
        let MachineInner::Linux(os) = &self.inner else {
            return Err(MachineError::UnsupportedCapability {
                capability: Capability::Services,
                os: self.os_kind(),
            });
        };
        let actor = Some(self.admin_actor()?);
        let state = os.unix().service_state()?;
        state
            .unit_names(actor)?
            .into_iter()
            .map(|name| {
                Ok(Service {
                    description: state.description(actor, &name),
                    state: state.state(actor, &name),
                    start_type: state.start_type(actor, &name),
                    name,
                })
            })
            .collect()
    }

    /// The Linux UFW rules, read from `/etc/ufw/user.rules`.
    pub fn firewall_rules(&self) -> Result<Vec<FirewallRule>, MachineError> {
        let MachineInner::Linux(os) = &self.inner else {
            return Err(MachineError::UnsupportedCapability {
                capability: Capability::FirewallRules,
                os: self.os_kind(),
            });
        };
        Ok(os
            .unix()
            .firewall()?
            .rules(Some(self.admin_actor()?))?
            .into_iter()
            .map(|rule| FirewallRule {
                port: rule.port,
                protocol: rule.protocol,
                action: rule.action,
                direction: if rule.direction.is_empty() {
                    "in".to_owned()
                } else {
                    rule.direction
                },
            })
            .collect())
    }

    /// Reads authoritative Unix ownership, mode, and size for a path.
    pub fn file_metadata(&self, path: &str) -> Result<FileMetadata, MachineError> {
        let unix = match &self.inner {
            MachineInner::Linux(os) => os.unix(),
            MachineInner::MacOS(os) => os.unix(),
            MachineInner::Windows(_) => {
                return Err(MachineError::UnsupportedCapability {
                    capability: Capability::FileMetadata,
                    os: self.os_kind(),
                });
            }
        };
        let path: VirtualPath = path.parse()?;
        let actor = Some(self.admin_actor()?);
        let object = self.engine().lookup(actor, &path)?;
        let metadata = self.engine().metadata(actor, object)?;
        let attrs = unix.attrs(object)?;
        let owner = metadata
            .owner()
            .and_then(os::unix::user::UserId::from_actor)
            .and_then(|uid| unix.users().get(uid))
            .map_or_else(|| "UNKNOWN".to_owned(), |user| user.name().to_owned());
        let group = unix
            .groups()
            .get(attrs.gid)
            .map_or_else(|| "UNKNOWN".to_owned(), |group| group.name().to_owned());
        Ok(FileMetadata {
            owner,
            group,
            mode: attrs.mode,
            size: self.engine().size(actor, object)?,
        })
    }

    /// Lists process records from the selected OS's own process namespace.
    ///
    /// This facade does not make processes an Engine concept: Unix and
    /// Windows allocate and maintain their namespaces, while VCE only maps
    /// those records into a stable embedding shape.
    pub fn processes(&self) -> Result<Vec<Process>, MachineError> {
        let actor = Some(self.admin_actor()?);
        let namespace = match &self.inner {
            MachineInner::Linux(os) => os.unix().namespace("processes")?,
            MachineInner::MacOS(os) => os.unix().namespace("processes")?,
            MachineInner::Windows(os) => os.processes()?.id(),
        };
        os::process::reconcile(self.engine(), actor, namespace)?;
        Ok(os::process::list(self.engine(), actor, namespace)?
            .into_iter()
            .map(|(_, process)| Process {
                pid: process.pid,
                user: process.user,
                executable: process.executable,
                arguments: process.arguments,
                state: process.state,
                cwd: process.cwd,
            })
            .collect())
    }

    /// Reads Windows password and lockout policy from the SAM registry hive.
    pub fn password_policy(&self) -> Result<PasswordPolicy, MachineError> {
        let MachineInner::Windows(os) = &self.inner else {
            return Err(MachineError::UnsupportedCapability {
                capability: Capability::AuthenticationPolicy,
                os: self.os_kind(),
            });
        };
        let policy = os.policy();
        Ok(PasswordPolicy {
            min_length: policy.min_length,
            max_age_days: policy.max_age_days,
            min_age_days: policy.min_age_days,
            history: policy.history,
            complexity: policy.complexity,
            reversible_encryption: policy.reversible_encryption,
            lockout_threshold: policy.lockout_threshold,
            lockout_duration: policy.lockout_duration,
            lockout_window: policy.lockout_window,
        })
    }

    /// Reads Windows audit categories from the SECURITY registry hive.
    pub fn audit_policy(&self) -> Result<Vec<AuditCategory>, MachineError> {
        let MachineInner::Windows(os) = &self.inner else {
            return Err(MachineError::UnsupportedCapability {
                capability: Capability::Audit,
                os: self.os_kind(),
            });
        };
        let policy = os.audit_policy();
        Ok([
            ("System", policy.system),
            ("Logon/Logoff", policy.logon),
            ("Account Management", policy.account_management),
            ("Account Logon", policy.account_logon),
            ("Policy Change", policy.policy_change),
            ("Privilege Use", policy.privilege_use),
            ("Object Access", policy.object_access),
        ]
        .into_iter()
        .map(|(name, (success, failure))| AuditCategory {
            name: name.to_owned(),
            success,
            failure,
        })
        .collect())
    }

    /// Reads every value directly under a Windows registry key.
    pub fn registry_values(
        &self,
        hive: &str,
        path: &str,
    ) -> Result<Vec<RegistryValue>, MachineError> {
        let MachineInner::Windows(os) = &self.inner else {
            return Err(MachineError::UnsupportedCapability {
                capability: Capability::Registry,
                os: self.os_kind(),
            });
        };
        let actor = Some(self.admin_actor()?);
        let registry = os.registry()?;
        let Some(key) = registry.key(actor, hive, path)? else {
            return Ok(Vec::new());
        };
        Ok(registry
            .values(actor, key)?
            .into_iter()
            .map(|value| RegistryValue {
                name: value.name,
                value_type: value.value_type,
                data: value.data,
            })
            .collect())
    }

    /// Reads a macOS preference domain from its actual plist file.
    pub fn preferences(
        &self,
        domain: &str,
    ) -> Result<std::collections::BTreeMap<String, PreferenceValue>, MachineError> {
        let MachineInner::MacOS(os) = &self.inner else {
            return Err(MachineError::UnsupportedCapability {
                capability: Capability::Preferences,
                os: self.os_kind(),
            });
        };
        let user = os
            .unix()
            .users()
            .by_name(&self.default_user)
            .ok_or_else(|| MachineError::Login("default macOS account is missing".to_owned()))?;
        let preferences =
            os::macos::preferences::Preferences::new(os.unix(), user.uid(), user.home());
        Ok(preferences
            .domain(Some(self.admin_actor()?), domain)?
            .unwrap_or_default()
            .into_iter()
            .map(|(key, value)| (key, preference_from_os(value)))
            .collect())
    }

    /// The account created when this machine booted.
    pub fn default_user(&self) -> &str {
        &self.default_user
    }

    /// The OS profile's user-facing name.
    pub fn display_name(&self) -> String {
        match &self.inner {
            MachineInner::Linux(os) => os.display_name(),
            MachineInner::MacOS(os) => os.display_name(),
            MachineInner::Windows(os) => os.display_name(),
        }
    }

    /// The virtual host or computer name supplied at boot.
    pub fn hostname(&self) -> &str {
        &self.hostname
    }

    /// The generic Engine holding this machine's authoritative state.
    ///
    /// This is the stable low-level observation surface for applications
    /// that need object metadata or event correlation. Prefer shell commands
    /// and [`Machine::configuration`] for OS-semantic changes.
    pub fn engine(&self) -> &Engine {
        match &self.inner {
            MachineInner::Linux(os) => os.engine(),
            MachineInner::MacOS(os) => os.engine(),
            MachineInner::Windows(os) => os.engine(),
        }
    }

    /// Returns a privileged configuration view over this machine.
    ///
    /// Configuration is not scenario generation: the embedding application
    /// decides *what* machine it wants, while this API performs the actual OS
    /// changes against VCE state.
    pub fn configuration(&self) -> Configuration<'_> {
        Configuration { machine: self }
    }

    /// Reads a file as the machine administrator.
    ///
    /// Returns `None` when `path` does not exist or identifies an object that
    /// has no file content, such as a directory.
    pub fn read_file(&self, path: &str) -> Result<Option<Vec<u8>>, MachineError> {
        let path: VirtualPath = path.parse()?;
        let object = match self.engine().lookup(Some(self.admin_actor()?), &path) {
            Ok(object) => object,
            Err(engine::Error::PathNotFound(_)) => return Ok(None),
            Err(error) => return Err(error.into()),
        };
        Ok(self.engine().read(Some(self.admin_actor()?), object)?)
    }

    /// Returns whether a path exists for the machine administrator.
    pub fn path_exists(&self, path: &str) -> bool {
        let Ok(path) = path.parse::<VirtualPath>() else {
            return false;
        };
        let Ok(actor) = self.admin_actor() else {
            return false;
        };
        self.engine().lookup(Some(actor), &path).is_ok()
    }

    /// Subscribes synchronously to committed Engine events.
    pub fn subscribe(
        &self,
        filter: impl Into<Option<EventType>>,
        callback: impl FnMut(&ObjectEvent) + Send + Sync + 'static,
    ) -> SubscriptionId {
        self.engine().subscribe(filter, callback)
    }

    /// Removes an event subscription.
    pub fn unsubscribe(&self, subscription: SubscriptionId) {
        self.engine().unsubscribe(subscription);
    }

    /// The current virtual machine time.
    pub fn time(&self) -> Timestamp {
        self.engine().time()
    }

    /// Advances virtual machine time deterministically.
    pub fn advance_time(&self, duration: std::time::Duration) {
        self.engine().advance_time(duration);
    }

    /// Authenticates an account and opens a persistent shell session.
    ///
    /// `None` chooses that account's Unix login shell or PowerShell on
    /// Windows.
    pub fn login(
        &self,
        username: &str,
        password: &str,
        shell: Option<ShellChoice>,
    ) -> Result<Session<'_>, MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => self.login_unix(os, username, password, shell),
            MachineInner::MacOS(os) => self.login_unix(os, username, password, shell),
            MachineInner::Windows(os) => {
                let actor = crate::login_windows(os, username, Some(password), false)
                    .map_err(MachineError::Login)?;
                Ok(Session::windows(
                    os,
                    actor,
                    shell.unwrap_or_else(Session::default_windows_choice),
                )?)
            }
        }
    }

    /// Opens a session for the boot-time standard account.
    ///
    /// Fresh VCE accounts use their username as their initial password.
    pub fn session(&self, shell: Option<ShellChoice>) -> Result<Session<'_>, MachineError> {
        self.login(&self.default_user, &self.default_user, shell)
    }

    /// Runs the built-in interactive logon screen and opens a shell session.
    pub fn interactive_session(
        &self,
        shell: Option<ShellChoice>,
    ) -> Result<Session<'_>, MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => {
                let credentials = crate::login_screen::run(
                    os.unix(),
                    &os.display_name(),
                    &self.hostname,
                    &self.default_user,
                )
                .map_err(MachineError::Login)?;
                let choice = shell.unwrap_or_else(|| Session::default_choice(&credentials));
                Ok(Session::unix(os.unix(), credentials, choice)?)
            }
            MachineInner::MacOS(os) => {
                let credentials = crate::login_screen::run(
                    os.unix(),
                    &os.display_name(),
                    &self.hostname,
                    &self.default_user,
                )
                .map_err(MachineError::Login)?;
                let choice = shell.unwrap_or_else(|| Session::default_choice(&credentials));
                Ok(Session::unix(os.unix(), credentials, choice)?)
            }
            MachineInner::Windows(os) => {
                let actor = crate::login_screen::run_windows(
                    os,
                    &os.display_name(),
                    &self.hostname,
                    &self.default_user,
                )
                .map_err(MachineError::Login)?;
                Ok(Session::windows(
                    os,
                    actor,
                    shell.unwrap_or_else(Session::default_windows_choice),
                )?)
            }
        }
    }

    fn login_unix<'a>(
        &'a self,
        os: &'a impl UnixFlavor,
        username: &str,
        password: &str,
        shell: Option<ShellChoice>,
    ) -> Result<Session<'a>, MachineError> {
        let credentials = crate::login_with_password(os.unix(), username, password)?;
        let choice = shell.unwrap_or_else(|| Session::default_choice(&credentials));
        Ok(Session::unix(os.unix(), credentials, choice)?)
    }

    fn admin_actor(&self) -> Result<ActorId, MachineError> {
        match &self.inner {
            MachineInner::Linux(_) | MachineInner::MacOS(_) => Ok(UserId::ROOT.actor_id()),
            MachineInner::Windows(os) => os
                .users()
                .by_name("Administrator")
                .map(|user| ActorId::new(u64::from(user.rid())))
                .ok_or_else(|| MachineError::Login("Administrator account is missing".to_owned())),
        }
    }

    fn configuration_session(&self) -> Result<Session<'_>, MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => configuration_unix_session(os.unix(), ShellChoice::Bash),
            MachineInner::MacOS(os) => configuration_unix_session(os.unix(), ShellChoice::Zsh),
            MachineInner::Windows(os) => Ok(Session::windows(
                os,
                self.admin_actor()?,
                ShellChoice::PowerShell,
            )?),
        }
    }

    // --- OS-semantic methods for embedding applications ---

    /// Adds a Unix user to the machine.
    ///
    /// This directly manipulates the user database, equivalent to `useradd`.
    /// Only works on Linux and macOS.
    #[allow(clippy::too_many_arguments)]
    pub fn add_user(
        &self,
        username: &str,
        uid: u32,
        gid: u32,
        full_name: &str,
        home_dir: &str,
        shell: &str,
        password: &str,
    ) -> Result<(), MachineError> {
        use os::unix::group::GroupId;
        use os::unix::password::PasswordState;
        use os::unix::user::{UnixUser, UserId};

        let user = UnixUser::new(
            username,
            UserId::new(uid),
            GroupId::new(gid),
            full_name,
            home_dir,
            shell,
            PasswordState::hashed(password),
        );
        match &self.inner {
            MachineInner::Linux(os) => {
                if os.unix().groups().get(GroupId::new(gid)).is_none() {
                    return Err(OsError::UnknownGroupId(gid).into());
                }
                os.unix().users().add(user)?;
                os::setup::rerender_accounts(os.unix())?;
                Ok(())
            }
            MachineInner::MacOS(os) => {
                if os.unix().groups().get(GroupId::new(gid)).is_none() {
                    return Err(OsError::UnknownGroupId(gid).into());
                }
                os.unix().users().add(user)?;
                os::setup::rerender_accounts(os.unix())?;
                Ok(())
            }
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "add_user is not available on Windows",
            )),
        }
    }

    /// Removes a Unix user from the machine.
    ///
    /// Only works on Linux and macOS.
    pub fn delete_user(&self, username: &str) -> Result<(), MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => {
                os.unix().users().delete(username);
                os::setup::rerender_accounts(os.unix())?;
                Ok(())
            }
            MachineInner::MacOS(os) => {
                os.unix().users().delete(username);
                os::setup::rerender_accounts(os.unix())?;
                Ok(())
            }
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "delete_user is not available on Windows",
            )),
        }
    }

    /// Checks whether a Unix user exists.
    pub fn user_exists(&self, username: &str) -> bool {
        match &self.inner {
            MachineInner::Linux(os) => os.unix().users().by_name(username).is_some(),
            MachineInner::MacOS(os) => os.unix().users().by_name(username).is_some(),
            MachineInner::Windows(_) => false,
        }
    }

    /// Adds a Unix group to the machine.
    ///
    /// Only works on Linux and macOS.
    /// If the group already exists, this is a no-op.
    pub fn add_group(&self, name: &str, gid: u32) -> Result<(), MachineError> {
        use os::unix::group::{GroupId, UnixGroup};

        let group = UnixGroup::new(name, GroupId::new(gid), []);
        match &self.inner {
            MachineInner::Linux(os) => {
                // Check if group already exists
                if os.unix().groups().by_name(name).is_some() {
                    return Ok(());
                }
                os.unix().groups().add(group)?;
                os::setup::rerender_accounts(os.unix())?;
                Ok(())
            }
            MachineInner::MacOS(os) => {
                // Check if group already exists
                if os.unix().groups().by_name(name).is_some() {
                    return Ok(());
                }
                os.unix().groups().add(group)?;
                os::setup::rerender_accounts(os.unix())?;
                Ok(())
            }
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "add_group is not available on Windows",
            )),
        }
    }

    /// Adds a user to a group.
    ///
    /// Only works on Linux and macOS.
    pub fn add_user_to_group(&self, username: &str, group_name: &str) -> Result<(), MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => {
                let unix = os.unix();
                let user = unix
                    .users()
                    .by_name(username)
                    .ok_or_else(|| MachineError::Login(format!("user '{username}' not found")))?;
                let group = unix.groups().by_name(group_name).ok_or_else(|| {
                    MachineError::Login(format!("group '{group_name}' not found"))
                })?;
                unix.groups().add_member(group.gid(), user.uid())?;
                os::setup::rerender_accounts(unix)?;
                Ok(())
            }
            MachineInner::MacOS(os) => {
                let unix = os.unix();
                let user = unix
                    .users()
                    .by_name(username)
                    .ok_or_else(|| MachineError::Login(format!("user '{username}' not found")))?;
                let group = unix.groups().by_name(group_name).ok_or_else(|| {
                    MachineError::Login(format!("group '{group_name}' not found"))
                })?;
                unix.groups().add_member(group.gid(), user.uid())?;
                os::setup::rerender_accounts(unix)?;
                Ok(())
            }
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "add_user_to_group is not available on Windows",
            )),
        }
    }

    /// Checks whether a user is a member of a group.
    pub fn user_in_group(&self, username: &str, group_name: &str) -> bool {
        match &self.inner {
            MachineInner::Linux(os) => {
                let unix = os.unix();
                let Some(user) = unix.users().by_name(username) else {
                    return false;
                };
                let Some(group) = unix.groups().by_name(group_name) else {
                    return false;
                };
                user.primary_group() == group.gid() || group.members().contains(&user.uid())
            }
            MachineInner::MacOS(os) => {
                let unix = os.unix();
                let Some(user) = unix.users().by_name(username) else {
                    return false;
                };
                let Some(group) = unix.groups().by_name(group_name) else {
                    return false;
                };
                user.primary_group() == group.gid() || group.members().contains(&user.uid())
            }
            MachineInner::Windows(_) => false,
        }
    }

    /// Enables or disables UFW on Linux.
    pub fn set_firewall_enabled(&self, enabled: bool) -> Result<(), MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => {
                os.unix()
                    .firewall()?
                    .set_enabled(Some(self.admin_actor()?), enabled)?;
                Ok(())
            }
            MachineInner::MacOS(_) => Err(MachineError::Unsupported(
                "use the macOS application-firewall API or socketfilterfw",
            )),
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "set_firewall_enabled is not available on Windows",
            )),
        }
    }

    /// Checks whether the firewall is enabled.
    pub fn firewall_enabled(&self) -> Result<bool, MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => {
                let enabled = os
                    .unix()
                    .firewall()?
                    .is_enabled(Some(self.admin_actor()?))?;
                Ok(enabled)
            }
            MachineInner::MacOS(_) => Err(MachineError::Unsupported(
                "use the macOS application-firewall API or socketfilterfw",
            )),
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "firewall_enabled is not available on Windows",
            )),
        }
    }

    /// Sets the file permission mode on a Unix file.
    pub fn set_file_mode(&self, path: &str, mode: FileMode) -> Result<(), MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => {
                os::setup::set_file_mode(os.unix(), Some(self.admin_actor()?), path, mode)?;
                Ok(())
            }
            MachineInner::MacOS(os) => {
                os::setup::set_file_mode(os.unix(), Some(self.admin_actor()?), path, mode)?;
                Ok(())
            }
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "set_file_mode is not available on Windows",
            )),
        }
    }

    /// Re-renders account files (/etc/passwd, /etc/group, /etc/shadow)
    /// from the live databases.
    ///
    /// Only works on Linux and macOS.
    pub fn rerender_accounts(&self) -> Result<(), MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => {
                os::setup::rerender_accounts(os.unix())?;
                Ok(())
            }
            MachineInner::MacOS(os) => {
                os::setup::rerender_accounts(os.unix())?;
                Ok(())
            }
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "rerender_accounts is not available on Windows",
            )),
        }
    }

    /// Gets the file permission mode for a Unix file.
    ///
    /// Returns the FileMode (e.g., 600, 644, 755) for the specified path.
    /// Only works on Linux and macOS.
    pub fn file_mode(&self, path: &str) -> Result<FileMode, MachineError> {
        if self.os_kind() == OsKind::Windows {
            return Err(MachineError::Unsupported(
                "Unix file modes are unavailable on Windows",
            ));
        }
        let path: VirtualPath = path.parse()?;
        let object = self.engine().lookup(Some(self.admin_actor()?), &path)?;
        let metadata = self.engine().metadata(Some(self.admin_actor()?), object)?;

        // Extract the UnixAttrs from the authorization to get the mode
        let attrs = os::unix::attrs::UnixAttrs::from_authorization(metadata.authorization())
            .map_err(|reason| MachineError::Os(OsError::InvalidUnixAttrs(object, reason)))?;

        Ok(attrs.mode)
    }

    /// Installs a systemd service unit.
    ///
    /// Creates the unit definition file, sets its state, and enables/disables it.
    /// Only works on Linux.
    pub fn install_service(
        &self,
        name: &str,
        description: &str,
        state: &str,
        enabled: bool,
    ) -> Result<(), MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => {
                os.unix().service_state()?.install_unit(
                    Some(self.admin_actor()?),
                    name,
                    description,
                    state,
                    enabled,
                )?;
                Ok(())
            }
            MachineInner::MacOS(_) => Err(MachineError::Unsupported(
                "install_service is not available on macOS",
            )),
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "install_service is not available on Windows",
            )),
        }
    }

    /// Sets the state of a systemd service (active/inactive).
    pub fn set_service_state(&self, name: &str, state: &str) -> Result<(), MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => {
                os.unix()
                    .service_state()?
                    .set_state(Some(self.admin_actor()?), name, state)?;
                Ok(())
            }
            MachineInner::MacOS(_) => Err(MachineError::Unsupported(
                "set_service_state is not available on macOS",
            )),
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "set_service_state is not available on Windows",
            )),
        }
    }

    /// Sets the start type of a systemd service (enabled/disabled).
    pub fn set_service_start_type(&self, name: &str, start_type: &str) -> Result<(), MachineError> {
        match &self.inner {
            MachineInner::Linux(os) => {
                os.unix().service_state()?.set_start_type(
                    Some(self.admin_actor()?),
                    name,
                    start_type,
                )?;
                Ok(())
            }
            MachineInner::MacOS(_) => Err(MachineError::Unsupported(
                "set_service_start_type is not available on macOS",
            )),
            MachineInner::Windows(_) => Err(MachineError::Unsupported(
                "set_service_start_type is not available on Windows",
            )),
        }
    }
}

fn configuration_unix_session(
    unix: &os::UnixOs,
    shell: ShellChoice,
) -> Result<Session<'_>, MachineError> {
    let root = unix
        .users()
        .by_name("root")
        .ok_or_else(|| MachineError::Login("root account is missing".to_owned()))?;
    let credentials =
        os::Credentials::login(root.clone(), unix.groups().memberships_of(root.uid()));
    Ok(Session::unix(unix, credentials, shell)?)
}

/// Privileged machine configuration for an embedding application.
pub struct Configuration<'machine> {
    machine: &'machine Machine,
}

impl Configuration<'_> {
    /// Opens a persistent administrative shell session.
    ///
    /// Linux uses Bash as root, macOS uses Zsh as root, and Windows uses
    /// PowerShell as the built-in Administrator. This bypasses interactive
    /// login intentionally: it is machine construction authority, not a
    /// player login.
    pub fn session(&self) -> Result<Session<'_>, MachineError> {
        self.machine.configuration_session()
    }

    /// Writes or replaces a root-owned Unix system file, creating parents.
    pub fn write_file(
        &self,
        path: &str,
        content: impl AsRef<[u8]>,
        mode: FileMode,
    ) -> Result<(), MachineError> {
        if self.machine.os_kind() == OsKind::Windows {
            return Err(MachineError::Unsupported(
                "Unix file modes are unavailable on Windows",
            ));
        }
        os::setup::write_system_file(
            self.machine.engine(),
            Some(UserId::ROOT.actor_id()),
            path,
            content.as_ref(),
            mode,
        )?;
        Ok(())
    }

    /// Creates or replaces a Unix file with bytes, owner, group, and mode as
    /// one atomic mutation. Missing parent directories are root-owned 0755.
    pub fn write_file_with_metadata(
        &self,
        path: &str,
        content: impl AsRef<[u8]>,
        owner: &str,
        group: &str,
        mode: FileMode,
    ) -> Result<(), MachineError> {
        let unix = match &self.machine.inner {
            MachineInner::Linux(os) => os.unix(),
            MachineInner::MacOS(os) => os.unix(),
            MachineInner::Windows(_) => {
                return Err(MachineError::UnsupportedCapability {
                    capability: Capability::FileMetadata,
                    os: self.machine.os_kind(),
                });
            }
        };
        os::setup::write_file_with_metadata(
            unix,
            Some(self.machine.admin_actor()?),
            path,
            content.as_ref(),
            owner,
            group,
            mode,
        )?;
        Ok(())
    }

    /// Appends bytes to a root-owned Unix system file, creating parents.
    pub fn append_file(&self, path: &str, content: impl AsRef<[u8]>) -> Result<(), MachineError> {
        if self.machine.os_kind() == OsKind::Windows {
            return Err(MachineError::Unsupported(
                "Unix system-file configuration is unavailable on Windows",
            ));
        }
        os::setup::append_system_file(
            self.machine.engine(),
            Some(UserId::ROOT.actor_id()),
            path,
            content.as_ref(),
        )?;
        Ok(())
    }

    /// Changes a Unix file's permission mode.
    pub fn set_mode(&self, path: &str, mode: FileMode) -> Result<(), MachineError> {
        let unix = match &self.machine.inner {
            MachineInner::Linux(os) => os.unix(),
            MachineInner::MacOS(os) => os.unix(),
            MachineInner::Windows(_) => {
                return Err(MachineError::Unsupported(
                    "Unix file modes are unavailable on Windows",
                ));
            }
        };
        os::setup::set_file_mode(unix, Some(UserId::ROOT.actor_id()), path, mode)?;
        Ok(())
    }

    /// Runs one privileged command through the OS's default administrative
    /// shell and captures its result.
    ///
    /// This is the general OS-configuration escape hatch: account, package,
    /// firewall, and service changes use the same commands and state paths a
    /// user session uses.
    pub fn run(&self, command: &str) -> Result<CommandOutput, MachineError> {
        Ok(self.session()?.execute(command)?)
    }

    /// Runs one privileged command and promotes a nonzero shell status into
    /// a structured error that retains stdout, stderr, and the exit status.
    pub fn run_checked(&self, command: &str) -> Result<CommandOutput, MachineError> {
        let output = self.run(command)?;
        if output.success() {
            Ok(output)
        } else {
            Err(MachineError::CommandFailed(output))
        }
    }

    /// Replaces Windows password and lockout policy in its SAM registry keys.
    pub fn set_password_policy(&self, policy: &PasswordPolicy) -> Result<(), MachineError> {
        let MachineInner::Windows(os) = &self.machine.inner else {
            return Err(MachineError::UnsupportedCapability {
                capability: Capability::AuthenticationPolicy,
                os: self.machine.os_kind(),
            });
        };
        os.set_policy(os::windows::PasswordPolicy {
            min_length: policy.min_length,
            max_age_days: policy.max_age_days,
            min_age_days: policy.min_age_days,
            history: policy.history,
            complexity: policy.complexity,
            reversible_encryption: policy.reversible_encryption,
            lockout_threshold: policy.lockout_threshold,
            lockout_duration: policy.lockout_duration,
            lockout_window: policy.lockout_window,
        });
        Ok(())
    }

    /// Replaces Windows audit policy in its SECURITY registry keys.
    pub fn set_audit_policy(&self, categories: &[AuditCategory]) -> Result<(), MachineError> {
        let MachineInner::Windows(os) = &self.machine.inner else {
            return Err(MachineError::UnsupportedCapability {
                capability: Capability::Audit,
                os: self.machine.os_kind(),
            });
        };
        let setting = |name: &str| {
            categories
                .iter()
                .find(|category| category.name.eq_ignore_ascii_case(name))
                .map_or((false, false), |category| {
                    (category.success, category.failure)
                })
        };
        os.set_audit_policy(os::windows::AuditPolicy {
            system: setting("System"),
            logon: setting("Logon/Logoff"),
            account_management: setting("Account Management"),
            account_logon: setting("Account Logon"),
            policy_change: setting("Policy Change"),
            privilege_use: setting("Privilege Use"),
            object_access: setting("Object Access"),
        });
        Ok(())
    }

    /// Sets one Windows registry value in the real hive-file tree.
    pub fn set_registry_value(
        &self,
        hive: &str,
        path: &str,
        name: &str,
        value_type: &str,
        data: &str,
    ) -> Result<(), MachineError> {
        let MachineInner::Windows(os) = &self.machine.inner else {
            return Err(MachineError::UnsupportedCapability {
                capability: Capability::Registry,
                os: self.machine.os_kind(),
            });
        };
        os.registry()?.set_value(
            Some(self.machine.admin_actor()?),
            hive,
            path,
            name,
            value_type,
            data,
        )?;
        Ok(())
    }

    /// Sets one macOS preference key in the same plist used by `defaults`.
    pub fn set_preference(
        &self,
        domain: &str,
        key: &str,
        value: PreferenceValue,
    ) -> Result<(), MachineError> {
        let MachineInner::MacOS(os) = &self.machine.inner else {
            return Err(MachineError::UnsupportedCapability {
                capability: Capability::Preferences,
                os: self.machine.os_kind(),
            });
        };
        let user = os
            .unix()
            .users()
            .by_name(&self.machine.default_user)
            .ok_or_else(|| MachineError::Login("default macOS account is missing".to_owned()))?;
        os::macos::preferences::Preferences::new(os.unix(), user.uid(), user.home()).set(
            Some(self.machine.admin_actor()?),
            domain,
            key,
            preference_to_os(value),
        )?;
        Ok(())
    }
}

fn preference_from_os(value: os::macos::plist::PlistValue) -> PreferenceValue {
    match value {
        os::macos::plist::PlistValue::String(value) => PreferenceValue::String(value),
        os::macos::plist::PlistValue::Integer(value) => PreferenceValue::Integer(value),
        os::macos::plist::PlistValue::Boolean(value) => PreferenceValue::Boolean(value),
    }
}

fn preference_to_os(value: PreferenceValue) -> os::macos::plist::PlistValue {
    match value {
        PreferenceValue::String(value) => os::macos::plist::PlistValue::String(value),
        PreferenceValue::Integer(value) => os::macos::plist::PlistValue::Integer(value),
        PreferenceValue::Boolean(value) => os::macos::plist::PlistValue::Boolean(value),
    }
}

/// An error from the supported VCE embedding API.
#[derive(Debug)]
#[non_exhaustive]
pub enum MachineError {
    /// Machine builder input cannot produce a usable standard account.
    InvalidConfiguration(String),
    /// OS construction or mutation failed.
    Os(OsError),
    /// A generic Engine operation failed.
    Engine(engine::Error),
    /// Shell-session construction or use failed.
    Session(SessionError),
    /// Authentication failed before the OS returned a structured error.
    Login(String),
    /// The requested operation has no semantics on this OS profile.
    Unsupported(&'static str),
    /// A semantic operation is not implemented by this OS profile.
    UnsupportedCapability {
        /// The requested semantic feature.
        capability: Capability,
        /// The selected OS profile.
        os: OsKind,
    },
    /// A checked command ran but returned a nonzero status.
    CommandFailed(CommandOutput),
}

impl std::fmt::Display for MachineError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidConfiguration(message) => {
                write!(formatter, "invalid machine configuration: {message}")
            }
            Self::Os(error) => error.fmt(formatter),
            Self::Engine(error) => error.fmt(formatter),
            Self::Session(error) => error.fmt(formatter),
            Self::Login(message) => formatter.write_str(message),
            Self::Unsupported(message) => formatter.write_str(message),
            Self::UnsupportedCapability { capability, os } => {
                write!(formatter, "{capability:?} is not supported by {os:?}")
            }
            Self::CommandFailed(output) => write!(
                formatter,
                "command failed with status {}: {}",
                output.status(),
                output.stderr_text().trim_end()
            ),
        }
    }
}

impl std::error::Error for MachineError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Os(error) => Some(error),
            Self::Engine(error) => Some(error),
            Self::Session(error) => Some(error),
            Self::InvalidConfiguration(_)
            | Self::Login(_)
            | Self::Unsupported(_)
            | Self::UnsupportedCapability { .. }
            | Self::CommandFailed(_) => None,
        }
    }
}

impl From<OsError> for MachineError {
    fn from(error: OsError) -> Self {
        Self::Os(error)
    }
}

impl From<engine::Error> for MachineError {
    fn from(error: engine::Error) -> Self {
        Self::Engine(error)
    }
}

impl From<SessionError> for MachineError {
    fn from(error: SessionError) -> Self {
        Self::Session(error)
    }
}