runner-manager-platform 0.4.35

Process, filesystem, machine-scoped secret store, service, and OS adapters for runner-manager.
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
// owner: a1-wsl-platform-adapter

//! The one Windows login task that keeps a managed WSL distribution alive,
//! and the four operations on it: render, register, query, remove.
//!
//! # What the task promises, and what it does not
//!
//! WSL distributions are registered **per user**, so nothing that runs before
//! a user logs on can start one. The 2026-09-06 review closed exactly this
//! defect: an earlier design promised boot availability that Windows cannot
//! deliver. So this is a `LogonTrigger` task for one named principal, and
//! `02-target-architecture.md` states the consequence in the product's own
//! words — *"unattended Linux availability after that user's logon, not before
//! any interactive logon after a Windows reboot"*.
//!
//! # There is no shell text in the action, at any layer
//!
//! The other half of that review closed a design that composed `systemctl` and
//! a keep-alive through a shell string. The action here is
//!
//! ```text
//! <Command>...\bin\runner-manager-wsl-supervisor.exe</Command>
//! <Arguments>...\bin\runner-manager-wsl.exe wsl-host supervise --distribution Ubuntu ...</Arguments>
//! ```
//!
//! Both paths are **version-independent**. An update swaps the two files in
//! place and leaves the document as it was, so the task never has to be
//! registered again — and registering is the one step that can need
//! administrator rights, because a task created from an elevated prompt keeps
//! an ACL that refuses replacement from an ordinary one. Up to 0.4.34 the
//! paths carried the version, so every update was a new document, a new
//! `/Create`, and an `Access is denied` on every host first set up elevated.
//! [`LifecycleTask::is_registered_as`] is the comparison that lets `wsl
//! install` skip the registration when nothing in the document changed.
//!
//! Task Scheduler has no `Arguments` *vector* — the element is a single string
//! that Windows splits with `CommandLineToArgvW` — so
//! [`LifecycleTask::action_arguments`] builds the vector and
//! [`LifecycleTask::rendered_arguments`] quotes each element with the same
//! function the service installer uses. A distribution called `My Ubuntu` is
//! therefore `"My Ubuntu"` in the document and one argument again on the way
//! out. What is *not* there is a `cmd /c`, a `&&`, a `;`, or anything else a
//! shell would interpret, and `no_shell_text_reaches_the_task_document` is the
//! test that keeps it that way.
//!
//! `wsl-host supervise` is the hidden Windows companion. It starts the
//! Linux-only `wsl-host hold`, restarts that child when the named distribution
//! is recovered, and owns the bounded recovery watchdog. Running in the
//! distribution owner's interactive token is essential: an SCM service under
//! LocalSystem cannot see another account's WSL registrations.
//!
//! # A task this did not create is never touched
//!
//! The name is derived from the distribution, so two workstations agree on it
//! and a re-run updates the task rather than accumulating copies. That same
//! determinism means the name could collide with something an operator made by
//! hand — and on the target workstation there *is* a hand-created task doing
//! this job today (`01-current-architecture.md`). So every mutating operation
//! reads the task back first and refuses unless its description carries
//! [`PRODUCT_MARKER`]. `wsl detach` removing somebody else's keep-alive task
//! would be precisely the destructive behaviour the review renamed the command
//! to avoid.

use std::ffi::OsString;
use std::path::{Path, PathBuf};

use super::WslError;
use super::discovery::{
    decode_console_output, escaped_name_with_digest, validate_distribution_name,
};
use super::exec::{CommandRequest, CommandRunner};
use super::probe::{LINUX_USER, WslExecutable, locate_in_system32};
use crate::service::{TaskPrincipal, quote_argument, xml_escape, xml_value};

/// The prefix every product-owned lifecycle task name starts with.
pub const LIFECYCLE_TASK_PREFIX: &str = "runner-manager-wsl";

/// The string that says a task is this product's.
///
/// It is in the task's `Description`, which Task Scheduler round-trips
/// verbatim through `/Query /XML`, so ownership survives an export and import
/// and does not depend on parsing the action.
pub const PRODUCT_MARKER: &str = "runner-manager-wsl-lifecycle/v1";

/// The revision of the task document, carried in its description.
///
/// `wsl install` re-registers a task only when the registered document differs
/// from the one it would write (see [`LifecycleTask::is_registered_as`]), and
/// that comparison reads the program, its arguments and the account (through
/// [`LifecycleTask::definition_stamp`]), not every setting. So a release that
/// changes anything else in the document (a
/// trigger, a setting, the run level) must raise this number, or hosts that
/// already have the task keep the old document.
///
/// Revision 2 is the version-independent companion paths.
pub const TASK_DEFINITION_REVISION: u32 = 2;

/// The hidden Linux command the task runs.
///
/// `02-target-architecture.md`: it "verifies systemd, starts the existing unit
/// by argument-vector process execution, and then remains alive with
/// signal-aware shutdown so WSL does not retire the distribution".
pub const HOLD_ARGUMENTS: [&str; 2] = ["wsl-host", "hold"];

// ---------------------------------------------------------------------------
// Identity
// ---------------------------------------------------------------------------

/// The stable, per-distribution name of the product's lifecycle task.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LifecycleTaskIdentity {
    distribution: String,
    name: String,
}

impl LifecycleTaskIdentity {
    /// Derives the task identity for a distribution.
    ///
    /// # The name is escaped *and* hashed, and both halves are load-bearing
    ///
    /// See [`escaped_name_with_digest`], which is also what
    /// [`super::record`] names its files with: escaping alone would map
    /// `Debian GNU/Linux` and `Debian GNU:Linux` onto one task, which is two
    /// distributions quietly sharing one keep-alive.
    ///
    /// # Errors
    ///
    /// [`WslError::InvalidName`] for a name that cannot be used at all.
    pub fn for_distribution(distribution: &str) -> Result<Self, WslError> {
        validate_distribution_name(distribution)?;
        Ok(Self {
            distribution: distribution.to_string(),
            name: format!(
                "{LIFECYCLE_TASK_PREFIX}-{}",
                escaped_name_with_digest(distribution)
            ),
        })
    }

    /// The distribution this task keeps alive.
    #[must_use]
    pub fn distribution(&self) -> &str {
        &self.distribution
    }

    /// The Task Scheduler name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The description a document carries: the marker, and the task's
    /// [`LifecycleTask::definition_stamp`].
    fn description(&self, stamp: &str) -> String {
        format!(
            "Keeps the WSL distribution \"{}\" running so its runner-manager service can \
             accept jobs after this account logs on. Created and owned by runner-manager \
             ({PRODUCT_MARKER}, {stamp}); remove it with `runner-manager wsl detach \
             --distribution {}`.",
            self.distribution, self.distribution
        )
    }
}

// ---------------------------------------------------------------------------
// The document
// ---------------------------------------------------------------------------

/// Everything needed to render the task.
#[derive(Debug, Clone)]
pub struct LifecycleTask {
    identity: LifecycleTaskIdentity,
    principal: TaskPrincipal,
    wsl_executable: PathBuf,
    linux_binary: String,
    recovery_root: Option<PathBuf>,
    windows_supervisor: Option<PathBuf>,
    windows_child: Option<PathBuf>,
}

impl LifecycleTask {
    /// Builds the task for one distribution and one Windows account.
    #[must_use]
    pub fn new(
        identity: LifecycleTaskIdentity,
        principal: TaskPrincipal,
        wsl_executable: &WslExecutable,
        linux_binary: impl Into<String>,
    ) -> Self {
        Self {
            identity,
            principal,
            wsl_executable: wsl_executable.path().to_path_buf(),
            linux_binary: linux_binary.into(),
            recovery_root: None,
            windows_supervisor: None,
            windows_child: None,
        }
    }

    /// Give the hold process the Windows directory used for recovery state.
    #[must_use]
    pub fn with_recovery_root(mut self, path: PathBuf) -> Self {
        self.recovery_root = Some(path);
        self
    }

    /// Run the keep-alive through a Windows process in the owning user's
    /// session. That process can both hold the guest open and recover a WSL
    /// transport which LocalSystem cannot see.
    #[must_use]
    pub fn with_windows_supervisor(mut self, supervisor: PathBuf, child: PathBuf) -> Self {
        self.windows_supervisor = Some(supervisor);
        self.windows_child = Some(child);
        self
    }

    /// Which task this is.
    #[must_use]
    pub fn identity(&self) -> &LifecycleTaskIdentity {
        &self.identity
    }

    /// The account it runs as.
    #[must_use]
    pub fn principal(&self) -> &TaskPrincipal {
        &self.principal
    }

    /// The program the task starts.
    #[must_use]
    pub fn command(&self) -> &Path {
        self.windows_supervisor
            .as_deref()
            .unwrap_or(&self.wsl_executable)
    }

    /// The action's argument **vector**.
    ///
    /// The same shape [`super::probe::LinuxCommand`] builds for every other
    /// invocation, which is deliberate: the task starts the distribution the
    /// same way the provisioning transaction does, so there is one thing to
    /// get right rather than two.
    #[must_use]
    pub fn action_arguments(&self) -> Vec<String> {
        if self.windows_supervisor.is_some() {
            let mut argv = vec![
                self.windows_child
                    .as_ref()
                    .expect("a Windows supervisor always has a child")
                    .to_string_lossy()
                    .into_owned(),
                "wsl-host".to_string(),
                "supervise".to_string(),
                "--distribution".to_string(),
                self.identity.distribution.clone(),
                "--linux-binary".to_string(),
                self.linux_binary.clone(),
            ];
            if let Some(root) = &self.recovery_root {
                argv.push("--shared-root".to_string());
                argv.push(root.to_string_lossy().into_owned());
            }
            return argv;
        }
        let mut argv = vec![
            "--distribution".to_string(),
            self.identity.distribution.clone(),
            "--user".to_string(),
            LINUX_USER.to_string(),
            "--exec".to_string(),
            self.linux_binary.clone(),
        ];
        argv.extend(
            HOLD_ARGUMENTS
                .iter()
                .map(|argument| (*argument).to_string()),
        );
        if let Some(root) = &self.recovery_root {
            argv.push("--shared-root".to_string());
            argv.push(root.to_string_lossy().into_owned());
        }
        argv
    }

    /// The vector, quoted into the single string Task Scheduler stores.
    #[must_use]
    pub fn rendered_arguments(&self) -> String {
        self.action_arguments()
            .iter()
            .map(|argument| quote_argument(argument))
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// `definition N, fingerprint XXXXXXXXXXXXXXXX`: the document revision and
    /// a digest of the program, its arguments and the account, carried in the
    /// description.
    ///
    /// # Why a digest rather than the values themselves
    ///
    /// `schtasks /Query /XML` writes to a pipe in the console's code page, not
    /// in the UTF-16 its own header declares (measured on Windows 11), so a
    /// profile path, an account or a distribution name outside that code page
    /// comes back altered. A comparison of the values would then fail on every
    /// update and send every update back to the `/Create` that needs
    /// administrator rights. The stamp is ASCII and survives the trip.
    #[must_use]
    pub fn definition_stamp(&self) -> String {
        use sha2::{Digest, Sha256};
        let mut digest = Sha256::new();
        for part in [
            self.command().to_string_lossy().as_ref(),
            self.rendered_arguments().as_str(),
            self.principal.user_id(),
        ] {
            digest.update(part.as_bytes());
            digest.update([0]);
        }
        let digest = hex::encode(digest.finalize());
        format!(
            "definition {TASK_DEFINITION_REVISION}, fingerprint {}",
            &digest[..16]
        )
    }

    /// The description the document carries.
    #[must_use]
    pub fn description(&self) -> String {
        self.identity.description(&self.definition_stamp())
    }

    /// Whether `registered` already is this task, so that registering it again
    /// would change nothing.
    ///
    /// This is what keeps an update from needing administrator rights: when
    /// the answer is yes, `wsl install` does not call `schtasks /Create` at
    /// all, and `/Create` is the call Windows refuses an ordinary token for a
    /// task that an elevated prompt created.
    ///
    /// Compared: ownership, whether it is enabled, the
    /// [`definition_stamp`](Self::definition_stamp) in its description, and --
    /// when they are ASCII and so survive the export unaltered -- the program
    /// and its argument string as well, which also catches an action edited by
    /// hand. A task an operator disabled is not "already this task":
    /// re-registering it is how `wsl install` has always repaired that.
    #[must_use]
    pub fn is_registered_as(&self, registered: &RegisteredTask) -> bool {
        let command = self.command().to_string_lossy();
        let arguments = self.rendered_arguments();
        let action_matches = !(command.is_ascii() && arguments.is_ascii())
            || (registered.command().eq_ignore_ascii_case(&command)
                && registered.arguments() == arguments);
        registered.is_product_owned()
            && registered.enabled()
            && registered.description().contains(&self.definition_stamp())
            && action_matches
    }

    /// The Task Scheduler document.
    #[must_use]
    pub fn xml(&self) -> String {
        let user = xml_escape(self.principal.user_id());
        let mut out = String::new();
        out.push_str("<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n");
        out.push_str(
            "<Task version=\"1.4\" \
             xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n",
        );
        out.push_str("  <RegistrationInfo>\n");
        out.push_str(&format!(
            "    <Description>{}</Description>\n",
            xml_escape(&self.description())
        ));
        out.push_str(&format!(
            "    <URI>\\{}</URI>\n",
            xml_escape(self.identity.name())
        ));
        out.push_str("  </RegistrationInfo>\n");

        out.push_str("  <Triggers>\n    <LogonTrigger>\n");
        out.push_str("      <Enabled>true</Enabled>\n");
        out.push_str(&format!("      <UserId>{user}</UserId>\n"));
        out.push_str("    </LogonTrigger>\n  </Triggers>\n");

        // `LeastPrivilege` is the whole of Windows' answer to "this task does
        // not need administrator": `wsl.exe` needs no elevation to start a
        // distribution the logged-on user owns, and the systemd unit inside it
        // is root's business, not Windows'.
        out.push_str("  <Principals>\n    <Principal id=\"Author\">\n");
        out.push_str(&format!("      <UserId>{user}</UserId>\n"));
        out.push_str("      <LogonType>InteractiveToken</LogonType>\n");
        out.push_str("      <RunLevel>LeastPrivilege</RunLevel>\n");
        out.push_str("    </Principal>\n  </Principals>\n");

        out.push_str("  <Settings>\n");
        // One hold process per distribution. A second would keep the same
        // distribution alive twice and tell an operator nothing new.
        out.push_str("    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n");
        out.push_str("    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n");
        out.push_str("    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n");
        out.push_str("    <AllowHardTerminate>true</AllowHardTerminate>\n");
        out.push_str("    <StartWhenAvailable>true</StartWhenAvailable>\n");
        out.push_str("    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n");
        out.push_str("    <IdleSettings>\n");
        out.push_str("      <StopOnIdleEnd>false</StopOnIdleEnd>\n");
        out.push_str("      <RestartOnIdle>false</RestartOnIdle>\n");
        out.push_str("    </IdleSettings>\n");
        out.push_str("    <AllowStartOnDemand>true</AllowStartOnDemand>\n");
        out.push_str("    <Enabled>true</Enabled>\n");
        out.push_str("    <Hidden>false</Hidden>\n");
        out.push_str("    <RunOnlyIfIdle>false</RunOnlyIfIdle>\n");
        out.push_str("    <WakeToRun>false</WakeToRun>\n");
        // The hold has no natural end, so a limit here would be a scheduled
        // kill of the thing that keeps the distribution up.
        out.push_str("    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\n");
        out.push_str("    <Priority>7</Priority>\n");
        out.push_str("    <RestartOnFailure>\n");
        out.push_str("      <Interval>PT1M</Interval>\n");
        out.push_str("      <Count>5</Count>\n");
        out.push_str("    </RestartOnFailure>\n");
        out.push_str("  </Settings>\n");

        out.push_str("  <Actions Context=\"Author\">\n    <Exec>\n");
        out.push_str(&format!(
            "      <Command>{}</Command>\n",
            xml_escape(&self.command().to_string_lossy())
        ));
        out.push_str(&format!(
            "      <Arguments>{}</Arguments>\n",
            xml_escape(&self.rendered_arguments())
        ));
        out.push_str("    </Exec>\n  </Actions>\n");
        out.push_str("</Task>\n");
        out
    }
}

// ---------------------------------------------------------------------------
// Reading a task back
// ---------------------------------------------------------------------------

/// What Task Scheduler says about a task that is registered.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegisteredTask {
    name: String,
    command: String,
    arguments: String,
    account: Option<String>,
    description: String,
    enabled: bool,
    running: bool,
}

impl RegisteredTask {
    /// Reads the fields this module cares about out of a `/Query /XML`
    /// document.
    #[must_use]
    pub fn from_document(name: &str, document: &str, running: bool) -> Self {
        Self {
            name: name.to_string(),
            command: xml_value(document, "Command").unwrap_or_default(),
            arguments: xml_value(document, "Arguments").unwrap_or_default(),
            account: xml_value(document, "UserId"),
            description: xml_value(document, "Description").unwrap_or_default(),
            enabled: task_is_enabled(document),
            running,
        }
    }

    /// The Task Scheduler name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The program it starts.
    #[must_use]
    pub fn command(&self) -> &str {
        &self.command
    }

    /// The single argument string it stores.
    #[must_use]
    pub fn arguments(&self) -> &str {
        &self.arguments
    }

    /// The account, when the document names one.
    #[must_use]
    pub fn account(&self) -> Option<&str> {
        self.account.as_deref()
    }

    /// Its description.
    #[must_use]
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Whether it is enabled.
    #[must_use]
    pub fn enabled(&self) -> bool {
        self.enabled
    }

    /// Whether Task Scheduler reports it as running.
    ///
    /// **Read from localised output**, exactly as
    /// [`crate::service`]'s Windows backend reads it, and for the same reason:
    /// `schtasks /Query /FO CSV` prints its `Status` column in the machine's
    /// display language and there is no locale-independent equivalent short of
    /// COM. On a non-English Windows this is `false` for a task that is in fact
    /// running. The authority for "is the Linux host healthy" is the Linux
    /// service's own status, never this. `wsl install` does branch on it, and
    /// only where a wrong `false` is harmless: it runs `/Run` on a current
    /// task that already runs, which `IgnoreNew` makes a no-op, and it skips
    /// restarting a task it re-registered, which leaves the old companion
    /// running until the next logon rather than doing anything to it.
    #[must_use]
    pub fn running(&self) -> bool {
        self.running
    }

    /// Whether this product created it.
    ///
    /// The gate on every mutation. See the module documentation: the name is
    /// derived, so it can collide with a hand-made task, and the marker is
    /// what tells the two apart.
    #[must_use]
    pub fn is_product_owned(&self) -> bool {
        self.description.contains(PRODUCT_MARKER)
    }
}

/// Whether the *task* is enabled, which is not the first `<Enabled>` in the
/// document.
///
/// A task has an `<Enabled>` inside its trigger and another inside its
/// `<Settings>`, in that order, and it is the second one that Task Scheduler
/// turns to `false` when an operator disables the task. Reading the first
/// would report a task somebody switched off in `taskschd.msc` as enabled,
/// which is the opposite of what a status line is for.
///
/// A document with no `<Settings>` at all — a hand-made task, or a fragment —
/// is read as enabled, which is what an absent setting means to Windows.
fn task_is_enabled(document: &str) -> bool {
    let settings = document
        .find("<Settings>")
        .map_or(document, |start| &document[start..]);
    xml_value(settings, "Enabled").as_deref() != Some("false")
}

// ---------------------------------------------------------------------------
// The control
// ---------------------------------------------------------------------------

/// Registering, reading and removing the product's lifecycle task.
///
/// Everything goes through a [`CommandRunner`], so the whole of this — the
/// argument vectors, the idempotent replacement, the foreign-task refusal and
/// the non-destructive removal — is testable on a CI leg that has no Task
/// Scheduler at all.
#[derive(Debug)]
pub struct LifecycleTaskControl<'runner> {
    runner: &'runner dyn CommandRunner,
    schtasks: PathBuf,
}

/// What [`LifecycleTaskControl::detach`] did, and what it deliberately did not.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Detached {
    /// Whether there was a task to remove.
    pub removed: bool,
    /// The task's name, whether or not it was there.
    pub name: String,
}

impl<'runner> LifecycleTaskControl<'runner> {
    /// Uses the host's `schtasks.exe`.
    #[must_use]
    pub fn new(runner: &'runner dyn CommandRunner) -> Self {
        Self {
            runner,
            schtasks: locate_in_system32("schtasks.exe"),
        }
    }

    /// Uses a named `schtasks.exe`, for a test.
    #[must_use]
    pub fn with_executable(
        runner: &'runner dyn CommandRunner,
        schtasks: impl Into<PathBuf>,
    ) -> Self {
        Self {
            runner,
            schtasks: schtasks.into(),
        }
    }

    /// What Task Scheduler holds under this name, if anything.
    ///
    /// # Errors
    ///
    /// [`WslError::Spawn`] when `schtasks.exe` cannot be started at all.
    pub fn query(
        &self,
        identity: &LifecycleTaskIdentity,
    ) -> Result<Option<RegisteredTask>, WslError> {
        let output = self.schtasks(&["/Query", "/TN", identity.name(), "/XML", "ONE"])?;
        if !output.success() {
            // `schtasks` reports "no such task" and "Task Scheduler is broken"
            // with the same non-zero exit and no distinct code, and the
            // sentence that would tell them apart is localised. Reading it as
            // absence is what an operator with no task should see -- but it is
            // only safe because nothing destructive trusts it on its own:
            // [`Self::register`] asks [`Self::exists`] for a second, export-free
            // opinion before it replaces anything.
            return Ok(None);
        }
        let document = decode_console_output(output.stdout()).into_text();
        Ok(Some(RegisteredTask::from_document(
            identity.name(),
            &document,
            self.is_running(identity),
        )))
    }

    /// Registers the task, replacing a previous registration of the same task.
    ///
    /// Idempotent: running it twice leaves one task whose definition is the
    /// current one. `schtasks /Create … /F` is what makes the replacement
    /// atomic from Task Scheduler's point of view — there is no window in
    /// which the task is absent.
    ///
    /// # Errors
    ///
    /// [`WslError::ForeignTask`] when a task of this name exists and is not
    /// this product's, or exists but cannot be exported and so cannot be shown
    /// to be this product's; [`WslError::TaskControl`] when `schtasks` refused;
    /// [`WslError::Record`] when the document could not be written to a
    /// temporary file for `schtasks /XML` to read.
    pub fn register(&self, task: &LifecycleTask) -> Result<(), WslError> {
        let identity = task.identity();
        match self.query(identity)? {
            Some(existing) if !existing.is_product_owned() => {
                return Err(WslError::ForeignTask {
                    name: identity.name().to_string(),
                    detail: format!(
                        "a task of this name already exists, its description does not identify \
                         it as this product's ({PRODUCT_MARKER}), and it starts `{}`. Rename or \
                         remove it yourself if it is the hand-created keep-alive this feature \
                         replaces.",
                        existing.command()
                    ),
                });
            }
            Some(_) => {}
            // `query` reads *any* `/Query /XML` failure as absence, and
            // `/Create ... /F` replaces rather than refuses -- so a task that
            // exists but cannot be exported would be overwritten by the very
            // call the marker guard above exists to prevent. Ask again in the
            // one form that answers "is there one" without an export, and
            // refuse when the two answers disagree.
            None if self.exists(identity) => {
                return Err(WslError::ForeignTask {
                    name: identity.name().to_string(),
                    detail: format!(
                        "a task of this name exists but Task Scheduler would not export its \
                         definition, so it cannot be shown to be this product's \
                         ({PRODUCT_MARKER}) and registering would replace it. Inspect it in \
                         `taskschd.msc`, and rename or remove it yourself if it is the \
                         hand-created keep-alive this feature replaces."
                    ),
                });
            }
            None => {}
        }

        let directory = tempfile::tempdir().map_err(|error| WslError::Record {
            operation: "write",
            path: PathBuf::from("<the scheduled-task document>"),
            detail: error.to_string(),
        })?;
        let document = directory.path().join("task.xml");
        write_utf16(&document, &task.xml()).map_err(|error| WslError::Record {
            operation: "write",
            path: document.clone(),
            detail: error.to_string(),
        })?;

        let output = self.schtasks(&[
            "/Create",
            "/TN",
            identity.name(),
            "/XML",
            &document.to_string_lossy(),
            "/F",
        ])?;
        if !output.success() {
            return Err(self.task_error("register", identity.name(), &output.diagnostic()));
        }
        Ok(())
    }

    /// Removes the product's task, and nothing else.
    ///
    /// This is the whole of `wsl detach`'s Windows half. It does not
    /// unregister the WSL distribution, stop or uninstall the Linux service,
    /// remove a credential, or delete any Linux data — it cannot, because the
    /// only program it runs is `schtasks.exe`.
    ///
    /// # Errors
    ///
    /// [`WslError::ForeignTask`] when the task is not this product's, and
    /// [`WslError::TaskControl`] when `schtasks` refused to delete it.
    pub fn detach(&self, identity: &LifecycleTaskIdentity) -> Result<Detached, WslError> {
        let Some(existing) = self.query(identity)? else {
            return Ok(Detached {
                removed: false,
                name: identity.name().to_string(),
            });
        };
        if !existing.is_product_owned() {
            return Err(WslError::ForeignTask {
                name: identity.name().to_string(),
                detail: format!(
                    "a task of this name exists but its description does not identify it as \
                     this product's ({PRODUCT_MARKER}), so `detach` will not remove it."
                ),
            });
        }
        let output = self.schtasks(&["/Delete", "/TN", identity.name(), "/F"])?;
        if !output.success() {
            return Err(self.task_error("remove", identity.name(), &output.diagnostic()));
        }
        Ok(Detached {
            removed: true,
            name: identity.name().to_string(),
        })
    }

    /// Starts the task now, rather than at the next logon.
    ///
    /// # Errors
    ///
    /// [`WslError::NoSuchTask`] when nothing is registered,
    /// [`WslError::ForeignTask`] when the registration is not this product's,
    /// and [`WslError::TaskControl`] when `schtasks` refused.
    pub fn start(&self, identity: &LifecycleTaskIdentity) -> Result<(), WslError> {
        self.require_ours("start", identity)?;
        let output = self.schtasks(&["/Run", "/TN", identity.name()])?;
        if !output.success() {
            return Err(self.task_error("start", identity.name(), &output.diagnostic()));
        }
        Ok(())
    }

    /// Ends a running instance. Returns whether one was running.
    ///
    /// # Errors
    ///
    /// As [`LifecycleTaskControl::start`].
    pub fn stop(&self, identity: &LifecycleTaskIdentity) -> Result<bool, WslError> {
        let existing = self.require_ours("stop", identity)?;
        if !existing.running() {
            return Ok(false);
        }
        let output = self.schtasks(&["/End", "/TN", identity.name()])?;
        if !output.success() {
            return Err(self.task_error("stop", identity.name(), &output.diagnostic()));
        }
        Ok(true)
    }

    fn require_ours(
        &self,
        operation: &'static str,
        identity: &LifecycleTaskIdentity,
    ) -> Result<RegisteredTask, WslError> {
        let Some(existing) = self.query(identity)? else {
            return Err(WslError::NoSuchTask {
                name: identity.name().to_string(),
            });
        };
        if !existing.is_product_owned() {
            return Err(WslError::ForeignTask {
                name: identity.name().to_string(),
                detail: format!(
                    "a task of this name exists but is not this product's ({PRODUCT_MARKER}), \
                     so it will not be used to {operation} anything."
                ),
            });
        }
        Ok(existing)
    }

    fn schtasks(&self, arguments: &[&str]) -> Result<super::exec::CommandOutput, WslError> {
        let request =
            CommandRequest::new(&self.schtasks).args(arguments.iter().map(OsString::from));
        self.runner.run(&request)
    }

    /// The plain, headerless CSV listing of one task, when Task Scheduler holds
    /// one and answered.
    ///
    /// It answers from the task store rather than from an XML export, so it
    /// still says yes for a task [`Self::query`] cannot read back. `schtasks`
    /// failing to run at all is read as "nothing", which leaves a caller
    /// exactly where it stood before this second opinion existed.
    ///
    /// One function for both callers so that the two questions asked of this
    /// listing — is there a task, and is it running — cannot drift onto
    /// different `schtasks` invocations.
    fn query_csv(&self, identity: &LifecycleTaskIdentity) -> Option<super::exec::CommandOutput> {
        let output = self
            .schtasks(&["/Query", "/TN", identity.name(), "/FO", "CSV", "/NH"])
            .ok()?;
        output.success().then_some(output)
    }

    /// Whether Task Scheduler holds anything at all under this name.
    ///
    /// Reads an exit status rather than a message, so it is unaffected by the
    /// console's language.
    fn exists(&self, identity: &LifecycleTaskIdentity) -> bool {
        self.query_csv(identity).is_some()
    }

    /// Whether Task Scheduler reports the task as running. See
    /// [`RegisteredTask::running`] for why this is best-effort.
    fn is_running(&self, identity: &LifecycleTaskIdentity) -> bool {
        let Some(output) = self.query_csv(identity) else {
            return false;
        };
        decode_console_output(output.stdout())
            .into_text()
            .lines()
            .filter_map(|line| line.rsplit(',').next())
            .any(|status| {
                status
                    .trim()
                    .trim_matches('"')
                    .eq_ignore_ascii_case("running")
            })
    }

    fn task_error(&self, operation: &'static str, name: &str, detail: &str) -> WslError {
        if detail.to_ascii_lowercase().contains("access is denied") {
            return WslError::NeedsElevation {
                operation,
                name: name.to_string(),
                detail: detail.to_string(),
            };
        }
        WslError::TaskControl {
            operation,
            name: name.to_string(),
            detail: detail.to_string(),
        }
    }
}

/// Writes a task document as UTF-16LE with a byte-order mark.
///
/// `schtasks /XML` reads its input as UTF-16 and the `<?xml … encoding
/// ="UTF-16"?>` declaration this module writes says so; handing it UTF-8 is
/// the one mistake that makes a perfectly good document unreadable.
fn write_utf16(path: &Path, text: &str) -> std::io::Result<()> {
    let mut bytes = vec![0xFF, 0xFE];
    for unit in text.encode_utf16() {
        bytes.extend_from_slice(&unit.to_le_bytes());
    }
    std::fs::write(path, bytes)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::wsl::discovery::{DIGEST_SUFFIX_LENGTH, ESCAPED_NAME_BUDGET};
    use crate::wsl::exec::{CommandOutput, ScriptedRunner};

    fn identity(distribution: &str) -> LifecycleTaskIdentity {
        LifecycleTaskIdentity::for_distribution(distribution).expect("a usable name")
    }

    fn task(distribution: &str) -> LifecycleTask {
        LifecycleTask::new(
            identity(distribution),
            TaskPrincipal::named("IVANPC\\IvanD"),
            &WslExecutable::at("C:\\Windows\\System32\\wsl.exe"),
            "/usr/local/bin/runner-manager",
        )
    }

    fn registered_document(distribution: &str) -> CommandOutput {
        CommandOutput::exited(0, task(distribution).xml(), "")
    }

    // -- Identity ------------------------------------------------------------

    #[test]
    fn the_task_name_is_stable_for_a_distribution() {
        assert_eq!(identity("Ubuntu").name(), identity("Ubuntu").name());
        assert!(
            identity("Ubuntu")
                .name()
                .starts_with("runner-manager-wsl-Ubuntu-")
        );
    }

    #[test]
    fn a_name_task_scheduler_could_not_hold_is_escaped_into_one_that_it_can() {
        let name = identity("Debian GNU/Linux 12").name().to_string();
        for forbidden in ['\\', '/', ':', '*', '?', '"', '<', '>', '|'] {
            assert!(
                !name.contains(forbidden),
                "{name} still contains {forbidden:?}"
            );
        }
        assert!(name.contains("Debian_GNU_Linux_12"), "{name}");
    }

    #[test]
    fn two_distributions_that_escape_alike_still_get_different_tasks() {
        // The reason the digest suffix exists. Without it these two would be
        // one task, and the second `wsl install` would silently retarget the
        // first distribution's keep-alive.
        let first = identity("Debian GNU/Linux");
        let second = identity("Debian GNU:Linux");
        assert_ne!(first.name(), second.name());
        assert!(first.name().contains("Debian_GNU_Linux"));
        assert!(second.name().contains("Debian_GNU_Linux"));
    }

    #[test]
    fn a_very_long_name_is_bounded_and_still_unique() {
        let long = "u".repeat(200);
        let other = format!("{long}x");
        let first = identity(&long);
        let second = identity(&other);
        assert_ne!(first.name(), second.name());
        assert!(
            first.name().len()
                <= LIFECYCLE_TASK_PREFIX.len() + 1 + ESCAPED_NAME_BUDGET + 1 + DIGEST_SUFFIX_LENGTH,
            "{}",
            first.name()
        );
    }

    #[test]
    fn a_distribution_name_that_is_not_usable_never_becomes_a_task_name() {
        assert!(LifecycleTaskIdentity::for_distribution("--shutdown").is_err());
        assert!(LifecycleTaskIdentity::for_distribution("").is_err());
    }

    // -- The document --------------------------------------------------------

    #[test]
    fn the_action_is_the_documented_argument_vector() {
        assert_eq!(
            task("Ubuntu").action_arguments(),
            vec![
                "--distribution",
                "Ubuntu",
                "--user",
                "root",
                "--exec",
                "/usr/local/bin/runner-manager",
                "wsl-host",
                "hold",
            ]
        );
    }

    #[test]
    fn a_name_with_spaces_is_quoted_so_windows_splits_it_back_into_one_argument() {
        let rendered = task("My Ubuntu").rendered_arguments();
        assert!(
            rendered.contains("--distribution \"My Ubuntu\" --user root"),
            "{rendered}"
        );
    }

    #[test]
    fn no_shell_text_reaches_the_task_document() {
        // The P1 the 2026-09-06 review closed: an action that composed
        // `systemctl` and a keep-alive through shell text.
        let document = task("Ubuntu & echo pwned").xml();
        let arguments = xml_value(&document, "Arguments").expect("the document has an action");
        for shell in ["cmd", "powershell", "/c", "&&", "||", ";", "$(", "`"] {
            assert!(
                !arguments.contains(shell),
                "the rendered arguments contain shell text {shell:?}: {arguments}"
            );
        }
        assert_eq!(
            xml_value(&document, "Command").as_deref(),
            Some("C:\\Windows\\System32\\wsl.exe")
        );
        // The `&` in the distribution name survived as data, escaped in the
        // document and quoted in the argument string.
        assert!(document.contains("&amp;"), "{document}");
        assert!(arguments.contains("\"Ubuntu & echo pwned\""), "{arguments}");
    }

    #[test]
    fn the_document_is_a_least_privilege_logon_task_for_the_named_principal() {
        let document = task("Ubuntu").xml();
        assert!(document.contains("<LogonTrigger>"), "{document}");
        assert!(
            document.contains("<RunLevel>LeastPrivilege</RunLevel>"),
            "{document}"
        );
        assert!(
            document.contains("<UserId>IVANPC\\IvanD</UserId>"),
            "{document}"
        );
        // No end to the hold, so no scheduled kill of it.
        assert!(document.contains("<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>"));
    }

    #[test]
    fn the_document_carries_the_ownership_marker_and_names_the_distribution() {
        let document = task("Ubuntu").xml();
        let description = xml_value(&document, "Description").expect("a description");
        assert!(description.contains(PRODUCT_MARKER), "{description}");
        assert!(description.contains("Ubuntu"), "{description}");
        assert!(description.contains("wsl detach"), "{description}");
    }

    #[test]
    fn a_rendered_document_reads_back_as_this_products_task() {
        let document = task("Ubuntu").xml();
        let read = RegisteredTask::from_document("whatever", &document, false);
        assert!(read.is_product_owned());
        assert_eq!(read.account(), Some("IVANPC\\IvanD"));
        assert!(read.enabled());
        assert!(
            read.arguments().contains("wsl-host hold"),
            "{}",
            read.arguments()
        );
    }

    #[test]
    fn a_supervised_task_runs_in_windows_and_carries_the_exact_guest_identity() {
        let supervised = task("Ubuntu")
            .with_recovery_root(PathBuf::from(r"C:\state\wsl-recovery\Ubuntu"))
            .with_windows_supervisor(
                PathBuf::from(r"C:\runner-manager-supervisor.exe"),
                PathBuf::from(r"C:\runner-manager.exe"),
            );
        assert_eq!(
            supervised.command(),
            Path::new(r"C:\runner-manager-supervisor.exe")
        );
        assert_eq!(
            supervised.action_arguments(),
            vec![
                r"C:\runner-manager.exe",
                "wsl-host",
                "supervise",
                "--distribution",
                "Ubuntu",
                "--linux-binary",
                "/usr/local/bin/runner-manager",
                "--shared-root",
                r"C:\state\wsl-recovery\Ubuntu",
            ]
        );
        let document = supervised.xml();
        assert!(
            document.contains(r"C:\runner-manager-supervisor.exe"),
            "{document}"
        );
        assert!(document.contains("wsl-host supervise"), "{document}");
        assert!(!document.contains("wsl.exe</Command>"), "{document}");
    }

    fn supervised(directory: &str) -> LifecycleTask {
        task("Ubuntu")
            .with_recovery_root(PathBuf::from(r"C:\state\wsl-recovery\Ubuntu"))
            .with_windows_supervisor(
                PathBuf::from(format!(r"{directory}\runner-manager-wsl-supervisor.exe")),
                PathBuf::from(format!(r"{directory}\runner-manager-wsl.exe")),
            )
    }

    #[test]
    fn a_registered_copy_of_the_same_document_needs_no_registration() {
        // The whole of the "updates need no administrator" fix rests on this
        // being true: the document an update would write reads back as the one
        // that is already there.
        let desired = supervised(r"C:\state\bin");
        let registered = RegisteredTask::from_document("whatever", &desired.xml(), true);
        assert!(desired.is_registered_as(&registered));

        // Task Scheduler may export the principal as a SID, and the program
        // in whatever case it stored.
        let exported = desired
            .xml()
            .replace(r"IVANPC\IvanD", "S-1-5-21-1-2-3-1001")
            .replace(
                r"<Command>C:\state\bin\runner-manager-wsl-supervisor.exe</Command>",
                r"<Command>c:\STATE\bin\RUNNER-MANAGER-WSL-SUPERVISOR.EXE</Command>",
            );
        assert!(!exported.contains("IVANPC") && !exported.contains(r"<Command>C:\state"));
        let registered = RegisteredTask::from_document("whatever", &exported, true);
        assert!(desired.is_registered_as(&registered));
    }

    #[test]
    fn a_profile_outside_the_console_code_page_still_reads_back_as_this_task() {
        // `schtasks /Query /XML` writes to a pipe in the console code page, so
        // a character outside it comes back as something else. Every update on
        // such a host would otherwise look like a new document and need
        // administrator rights again.
        let desired = task("Ubuntu")
            .with_recovery_root(PathBuf::from(r"C:\Users\Иван\state\wsl-recovery\Ubuntu"))
            .with_windows_supervisor(
                PathBuf::from(r"C:\Users\Иван\state\bin\runner-manager-wsl-supervisor.exe"),
                PathBuf::from(r"C:\Users\Иван\state\bin\runner-manager-wsl.exe"),
            );
        let lossy: String = desired
            .xml()
            .chars()
            .map(|c| if c.is_ascii() { c } else { '?' })
            .collect();
        let registered = RegisteredTask::from_document("whatever", &lossy, true);
        assert!(desired.is_registered_as(&registered));

        let other_stamp = lossy.replace(
            &desired.definition_stamp(),
            "definition 2, fingerprint 0000000000000000",
        );
        assert_ne!(other_stamp, lossy);
        let registered = RegisteredTask::from_document("whatever", &other_stamp, true);
        assert!(!desired.is_registered_as(&registered));
    }

    #[test]
    fn a_document_that_differs_in_anything_compared_is_registered_again() {
        let desired = supervised(r"C:\state\bin");
        let somebody_else = LifecycleTask::new(
            identity("Ubuntu"),
            TaskPrincipal::named(r"IVANPC\Somebody"),
            &WslExecutable::at(r"C:\Windows\System32\wsl.exe"),
            "/usr/local/bin/runner-manager",
        )
        .with_recovery_root(PathBuf::from(r"C:\state\wsl-recovery\Ubuntu"))
        .with_windows_supervisor(
            PathBuf::from(r"C:\state\bin\runner-manager-wsl-supervisor.exe"),
            PathBuf::from(r"C:\state\bin\runner-manager-wsl.exe"),
        );
        let differing = [
            (
                "the versioned 0.4.34 companion paths",
                supervised(r"C:\state\bin")
                    .with_windows_supervisor(
                        PathBuf::from(r"C:\state\bin\runner-manager-wsl-supervisor-0.4.34.exe"),
                        PathBuf::from(r"C:\state\bin\runner-manager-wsl-0.4.34.exe"),
                    )
                    .xml(),
            ),
            (
                "an earlier definition revision",
                desired
                    .xml()
                    .replace(&desired.definition_stamp(), "definition 1"),
            ),
            (
                "a task an operator disabled",
                desired.xml().replace(
                    "\n    <Enabled>true</Enabled>\n",
                    "\n    <Enabled>false</Enabled>\n",
                ),
            ),
            ("another account", somebody_else.xml()),
            (
                "a different recovery root",
                supervised(r"C:\state\bin")
                    .with_recovery_root(PathBuf::from(r"C:\elsewhere\Ubuntu"))
                    .xml(),
            ),
            (
                "an action edited by hand under the same description",
                desired.xml().replace("wsl-recovery", "elsewhere"),
            ),
        ];
        for (what, document) in differing {
            assert_ne!(document, desired.xml(), "{what}: the case must differ");
            let registered = RegisteredTask::from_document("whatever", &document, true);
            assert!(!desired.is_registered_as(&registered), "{what}");
        }

        let foreign = RegisteredTask::from_document(
            "whatever",
            "<Task><RegistrationInfo><Description>mine</Description></RegistrationInfo></Task>",
            false,
        );
        assert!(!desired.is_registered_as(&foreign));
    }

    #[test]
    fn a_task_an_operator_disabled_is_reported_as_disabled() {
        // Task Scheduler leaves the *trigger's* `<Enabled>` alone and turns
        // `<Settings><Enabled>` to `false`, and the trigger's is the first one
        // in the document — so reading the first would report this task as
        // enabled and a status line would say the keep-alive is fine.
        // Anchored on the newline and the settings block's indentation, so
        // that the trigger's own -- more deeply indented -- element is left
        // exactly as Task Scheduler leaves it.
        let disabled = task("Ubuntu").xml().replace(
            "\n    <Enabled>true</Enabled>\n",
            "\n    <Enabled>false</Enabled>\n",
        );
        assert!(
            disabled.contains("      <Enabled>true</Enabled>"),
            "the trigger's own <Enabled> must still be true for this to prove anything"
        );
        assert!(!RegisteredTask::from_document("whatever", &disabled, false).enabled());
        assert!(RegisteredTask::from_document("whatever", &task("Ubuntu").xml(), false).enabled());
    }

    #[test]
    fn a_task_this_product_did_not_write_is_not_product_owned() {
        let hand_made = concat!(
            "<Task><RegistrationInfo><Description>GitHub Actions Linux Runner - Ubuntu WSL",
            "</Description></RegistrationInfo><Actions><Exec><Command>wsl.exe</Command>",
            "<Arguments>-d Ubuntu -u root /bin/sleep infinity</Arguments></Exec></Actions></Task>",
        );
        let read = RegisteredTask::from_document("whatever", hand_made, false);
        assert!(!read.is_product_owned());
    }

    // -- The control ---------------------------------------------------------

    fn control(runner: &ScriptedRunner) -> LifecycleTaskControl<'_> {
        LifecycleTaskControl::with_executable(runner, "schtasks.exe")
    }

    #[test]
    fn registering_writes_a_utf16_document_and_replaces_in_place() {
        let runner = ScriptedRunner::new().always("/Query", CommandOutput::exited(1, "", ""));
        let task = task("Ubuntu");
        control(&runner).register(&task).expect("registered");

        let create = runner
            .recorded()
            .into_iter()
            .find(|request| request.arguments.first().map(String::as_str) == Some("/Create"))
            .expect("a /Create call");
        assert_eq!(create.arguments[1], "/TN");
        assert_eq!(create.arguments[2], task.identity().name());
        assert_eq!(create.arguments[3], "/XML");
        assert_eq!(
            create.arguments[5], "/F",
            "without /F a second `wsl install` fails instead of updating the task"
        );
    }

    #[test]
    fn registering_over_this_products_own_task_is_allowed_and_idempotent() {
        let runner = ScriptedRunner::new()
            .always("/Query", registered_document("Ubuntu"))
            .always("/Create", CommandOutput::exited(0, "SUCCESS", ""));
        control(&runner)
            .register(&task("Ubuntu"))
            .expect("replaced");
        control(&runner)
            .register(&task("Ubuntu"))
            .expect("replaced again");
    }

    #[test]
    fn registering_over_a_task_that_cannot_be_exported_refuses_and_changes_nothing() {
        // `/Create ... /F` replaces, so "the XML query failed" must not be
        // read as "the name is free": a task Task Scheduler will not export --
        // the hand-created keep-alive among them -- would be destroyed by the
        // install that the ownership marker exists to make impossible.
        let runner = ScriptedRunner::new()
            .always(
                "/XML",
                CommandOutput::exited(1, "", "the task image is corrupt"),
            )
            .always(
                "/FO",
                CommandOutput::exited(0, "\"whatever\",\"N/A\",\"Ready\"", ""),
            );
        let error = control(&runner)
            .register(&task("Ubuntu"))
            .expect_err("an unexportable task is not a free name");
        assert!(matches!(error, WslError::ForeignTask { .. }), "{error:?}");
        assert!(
            runner
                .command_lines()
                .iter()
                .all(|line| !line.contains("/Create")),
            "nothing may be written: {:?}",
            runner.command_lines()
        );
    }

    #[test]
    fn registering_over_a_foreign_task_refuses_and_changes_nothing() {
        let hand_made = CommandOutput::exited(
            0,
            concat!(
                "<Task><RegistrationInfo><Description>GitHub Actions Linux Runner - Ubuntu WSL",
                "</Description></RegistrationInfo><Actions><Exec><Command>wsl.exe</Command>",
                "</Exec></Actions></Task>",
            ),
            "",
        );
        let runner = ScriptedRunner::new().always("/Query", hand_made);
        let error = control(&runner)
            .register(&task("Ubuntu"))
            .expect_err("not ours");
        assert!(matches!(error, WslError::ForeignTask { .. }), "{error:?}");
        assert!(
            runner
                .command_lines()
                .iter()
                .all(|line| !line.contains("/Create")),
            "nothing may be written: {:?}",
            runner.command_lines()
        );
    }

    #[test]
    fn detach_removes_only_the_product_task_and_runs_nothing_else() {
        let runner = ScriptedRunner::new()
            .always("/Query", registered_document("Ubuntu"))
            .always("/Delete", CommandOutput::exited(0, "SUCCESS", ""));
        let detached = control(&runner)
            .detach(&identity("Ubuntu"))
            .expect("detached");
        assert!(detached.removed);

        for request in runner.recorded() {
            assert_eq!(
                request.program.to_string_lossy(),
                "schtasks.exe",
                "detach must not run anything but Task Scheduler: {request:?}"
            );
        }
        let lines = runner.command_lines();
        assert!(
            lines.iter().all(|line| !line.contains("wsl.exe")),
            "detach must not reach into the distribution: {lines:?}"
        );
        assert!(
            lines
                .iter()
                .all(|line| !line.contains("--unregister") && !line.contains("systemctl")),
            "detach must not unregister WSL or touch the Linux service: {lines:?}"
        );
    }

    #[test]
    fn detach_without_a_task_is_not_an_error() {
        let runner = ScriptedRunner::new().always("/Query", CommandOutput::exited(1, "", ""));
        let detached = control(&runner)
            .detach(&identity("Ubuntu"))
            .expect("nothing to remove");
        assert!(!detached.removed);
        assert!(
            runner
                .command_lines()
                .iter()
                .all(|line| !line.contains("/Delete"))
        );
    }

    #[test]
    fn detach_refuses_a_foreign_task_rather_than_deleting_it() {
        let runner = ScriptedRunner::new().always(
            "/Query",
            CommandOutput::exited(
                0,
                "<Task><RegistrationInfo><Description>Somebody else's task</Description>\
                 </RegistrationInfo></Task>",
                "",
            ),
        );
        let error = control(&runner)
            .detach(&identity("Ubuntu"))
            .expect_err("not ours");
        assert!(matches!(error, WslError::ForeignTask { .. }), "{error:?}");
        assert!(
            runner
                .command_lines()
                .iter()
                .all(|line| !line.contains("/Delete")),
            "a task this product does not own must not be deleted"
        );
    }

    #[test]
    fn access_denied_is_reported_as_needing_elevation_rather_than_as_a_generic_failure() {
        let runner = ScriptedRunner::new()
            .always("/Query", CommandOutput::exited(1, "", ""))
            .always(
                "/Create",
                CommandOutput::exited(1, "", "ERROR: Access is denied.\n"),
            );
        let error = control(&runner)
            .register(&task("Ubuntu"))
            .expect_err("denied");
        assert!(
            matches!(error, WslError::NeedsElevation { .. }),
            "{error:?}"
        );
    }

    #[test]
    fn starting_a_task_that_is_not_registered_says_so() {
        let runner = ScriptedRunner::new().always("/Query", CommandOutput::exited(1, "", ""));
        let error = control(&runner)
            .start(&identity("Ubuntu"))
            .expect_err("not registered");
        assert!(matches!(error, WslError::NoSuchTask { .. }), "{error:?}");
    }

    #[test]
    fn a_query_reads_a_utf16_document_as_schtasks_really_writes_it() {
        let mut bytes = vec![0xFF, 0xFE];
        for unit in task("Ubuntu").xml().encode_utf16() {
            bytes.extend_from_slice(&unit.to_le_bytes());
        }
        let runner = ScriptedRunner::new()
            .always("/XML ONE", CommandOutput::exited(0, bytes, ""))
            .always(
                "/FO CSV",
                CommandOutput::exited(0, "\"task\",\"N/A\",\"Ready\"\n", ""),
            );
        let found = control(&runner)
            .query(&identity("Ubuntu"))
            .expect("queried")
            .expect("registered");
        assert!(found.is_product_owned());
        assert!(!found.running());
        assert!(found.arguments().contains("wsl-host hold"));
    }

    #[test]
    fn a_running_task_is_reported_from_the_csv_status_column() {
        let runner = ScriptedRunner::new()
            .always("/XML ONE", registered_document("Ubuntu"))
            .always(
                "/FO CSV",
                CommandOutput::exited(0, "\"\\task\",\"N/A\",\"Running\"\n", ""),
            );
        let found = control(&runner)
            .query(&identity("Ubuntu"))
            .expect("queried")
            .expect("registered");
        assert!(found.running());
    }

    // -- The document round-trips through a file -----------------------------

    #[test]
    fn the_document_is_written_as_utf16_little_endian_with_a_byte_order_mark() {
        let directory = tempfile::tempdir().expect("a temporary directory");
        let path = directory.path().join("task.xml");
        write_utf16(&path, &task("Ubuntu").xml()).expect("written");
        let bytes = std::fs::read(&path).expect("readable");
        assert_eq!(&bytes[..2], &[0xFF, 0xFE]);
        let decoded = decode_console_output(&bytes);
        assert_eq!(decoded.text(), task("Ubuntu").xml());
    }

    #[test]
    fn no_credential_shaped_value_can_reach_the_document() {
        // `03-security-and-lifecycle.md` item 3 lists scheduled-task XML among
        // the places the credential document must be absent from. The control
        // is structural -- `LifecycleTask` has no field that could hold one --
        // and this is the test that says so about the rendered result.
        let document = task("Ubuntu").xml().to_ascii_lowercase();
        for shape in [
            "ghu_",
            "ghs_",
            "gho_",
            "github_pat_",
            "access_token",
            "refresh_token",
            "jitconfig",
            "secret",
            "password",
            "credential",
        ] {
            assert!(
                !document.contains(shape),
                "the task document mentions {shape:?}: {document}"
            );
        }
        // `token` on its own is deliberately *not* in that list: Task
        // Scheduler's own `<LogonType>InteractiveToken</LogonType>` contains
        // it, so a substring test for it would fail on a document that is
        // exactly right. The shapes above are credential-shaped; that one is a
        // Windows API word.
        assert!(document.contains("interactivetoken"));
    }
}