runner-manager-platform 0.4.7

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
// 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>C:\Windows\System32\wsl.exe</Command>
//! <Arguments>--distribution Ubuntu --user root --exec /usr/local/bin/runner-manager wsl-host hold</Arguments>
//! ```
//!
//! 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 hold` is a hidden Linux-only command that starts the existing
//! systemd unit by argument-vector process execution and then stays alive.
//! Naming it here is this crate's whole contribution to the lifecycle: the
//! Linux side of it belongs to the CLI.
//!
//! # 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 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 the document carries, which also carries the marker.
    #[must_use]
    pub fn description(&self) -> 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}); 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,
}

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(),
        }
    }

    /// 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.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> {
        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()),
        );
        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(" ")
    }

    /// 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.identity.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.wsl_executable.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. Nothing in the provisioning transaction branches on it — the
    /// authority for "is the Linux host healthy" is the Linux service's own
    /// status — so it is a display value and only that.
    #[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_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"));
    }
}