dev-prune 1.22.0

Universal, lockfile-safe workspace pruner and background dependency cleaner
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
// Copyright 2026 VKrishna04
// SPDX-License-Identifier: Apache-2.0

// Windows Task Scheduler integration.

use crate::constants::{WINDOWS_TASK_NAME as TASK_NAME, WINDOWS_WINDOWLESS_BIN};
use crate::daemon::{DaemonStatus, get_exe_path};
use crate::spawn;
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

/// Builds the schtasks command arguments for installation.
pub fn build_install_command(exe_path: &str, interval_days: u64) -> Vec<String> {
    vec![
        "/Create".to_string(),
        "/SC".to_string(),
        "DAILY".to_string(),
        "/MO".to_string(),
        // schtasks rejects `/SC DAILY /MO` values outside 1–365 outright, so an
        // oversized interval must be capped here or the install fails with a
        // localised error the caller cannot interpret.
        interval_days.clamp(1, 365).to_string(),
        "/TN".to_string(),
        TASK_NAME.to_string(),
        "/TR".to_string(),
        // `--yes` is required: a scheduled task has no console, so a prompt would
        // read EOF and abort the run.
        format!("\"{}\" run --yes --daemon", exe_path),
        "/F".to_string(),
    ]
}

/// Builds the schtasks arguments for a sessionless (S4U) installation.
///
/// `/RU <account> /NP` registers the task to run whether the user is logged on or not,
/// without storing a password (an S4U logon). Such a task runs in a non-interactive
/// session — without it, every firing of the console binary flashes a black window at
/// whoever is logged in, which reads as malware to anyone watching their own screen.
pub fn build_install_command_windowless(
    exe_path: &str,
    interval_days: u64,
    account: &str,
) -> Vec<String> {
    let mut args = build_install_command(exe_path, interval_days);
    args.extend(["/RU".to_string(), account.to_string(), "/NP".to_string()]);
    args
}

/// The account to register the S4U task under, as `DOMAIN\user`.
fn current_account() -> Option<String> {
    let user = std::env::var("USERNAME").ok().filter(|s| !s.is_empty())?;
    Some(match std::env::var("USERDOMAIN") {
        Ok(domain) if !domain.is_empty() => format!("{domain}\\{user}"),
        _ => user,
    })
}

/// Marker recording that this machine's scheduler refused the S4U registration.
///
/// Some policies deny S4U logons to non-elevated callers, and a filesystem that cannot
/// hold the windowless twin refuses that route too. Without the marker, every setup
/// pass would re-try the upgrade, fail, and re-register the visible task — churning the
/// scheduler on every single `devp` invocation.
fn windowless_refused_marker() -> Option<PathBuf> {
    crate::config::Registry::config_dir()
        .ok()
        .map(|dir| dir.join(crate::constants::SCHEDULER_WINDOWLESS_REFUSED_MARKER))
}

/// Removes every refusal marker from `dir`, whatever it is called.
///
/// Matching the `scheduler-*-refused` family rather than one filename is what retires
/// the spelling an older release used, so a rename cannot strand an empty file in the
/// config directory of every machine that upgrades. Split out from `install` so it can
/// be tested against a real directory without going near the scheduler.
fn sweep_refusal_markers(dir: &Path) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if name.starts_with("scheduler-") && name.ends_with("-refused") {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

/// Marker recording that this machine's scheduler refused the power-settings
/// re-registration. Same contract as the windowless marker: without it, every settled
/// setup pass would retry the XML round-trip against a scheduler that has already said
/// no, churning the task on every single `devp` invocation.
fn power_refused_marker() -> Option<PathBuf> {
    crate::config::Registry::config_dir()
        .ok()
        .map(|dir| dir.join(crate::constants::SCHEDULER_POWER_REFUSED_MARKER))
}

/// Rewrite a task definition so a laptop actually runs it, or `None` if it already
/// would.
///
/// A task registered through `schtasks /Create` flags gets Windows' power defaults,
/// and all three of them are wrong for a background pruner on a laptop: the task
/// refuses to start on battery (every attempt ends 0x800710E0 and nothing is logged
/// anywhere the user looks), a pass already running is killed the moment the charger
/// is pulled, and a trigger that fires while the lid is closed is skipped for the
/// whole interval rather than caught up on wake. `schtasks` has no flag for any of
/// the three, so the only route is this XML round-trip. `WakeToRun` is deliberately
/// left alone: catching up on wake is helpful, waking the machine to prune is not.
///
/// `StartWhenAvailable` is absent from a default registration (absent means false),
/// so it is inserted rather than flipped when missing.
fn patch_power_settings_xml(xml: &str) -> Option<String> {
    let mut patched = xml.to_string();
    let mut changed = false;
    for (gated, lifted) in [
        (
            "<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>",
            "<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>",
        ),
        (
            "<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>",
            "<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>",
        ),
        (
            "<StartWhenAvailable>false</StartWhenAvailable>",
            "<StartWhenAvailable>true</StartWhenAvailable>",
        ),
    ] {
        if patched.contains(gated) {
            patched = patched.replace(gated, lifted);
            changed = true;
        }
    }
    if !patched.contains("<StartWhenAvailable>")
        && let Some(pos) = patched.find("<Settings>")
    {
        patched.insert_str(
            pos + "<Settings>".len(),
            "\n    <StartWhenAvailable>true</StartWhenAvailable>",
        );
        changed = true;
    }
    changed.then_some(patched)
}

/// Encode a document the way `schtasks /Create /XML` expects to read it back.
///
/// The export declares `encoding="UTF-16"` in its first line, so the import refuses a
/// UTF-8 body under that declaration. Mirror of [`decode_schtasks_xml`].
fn encode_schtasks_xml(xml: &str) -> Vec<u8> {
    let mut bytes = vec![0xFF, 0xFE];
    for unit in xml.encode_utf16() {
        bytes.extend_from_slice(&unit.to_le_bytes());
    }
    bytes
}

/// Re-register the task with the power gates lifted, keeping everything else —
/// trigger time, logon type, binary — exactly as it is.
///
/// Export, patch, re-import: the exported XML carries the `<StartBoundary>`, so unlike
/// a fresh `/SC DAILY` registration this never moves the task's time-of-day. A task
/// that already has the right settings, or no task at all, is left untouched. A
/// scheduler that refuses the re-import keeps the working (if gated) task and writes
/// the refusal marker so settled passes stop asking.
pub fn apply_power_settings() -> Result<()> {
    let Some(xml) = task_xml() else {
        return Ok(());
    };
    let Some(patched) = patch_power_settings_xml(&xml) else {
        if let Some(marker) = power_refused_marker() {
            let _ = std::fs::remove_file(marker);
        }
        return Ok(());
    };
    let dir = crate::config::Registry::config_dir()?;
    let patch_file = dir.join(crate::constants::SCHEDULER_POWER_PATCH_FILE);
    std::fs::write(&patch_file, encode_schtasks_xml(&patched))
        .context("Failed to write the patched task definition")?;
    let output = spawn::command("schtasks")
        .args([
            "/Create",
            "/TN",
            TASK_NAME,
            "/XML",
            &patch_file.to_string_lossy(),
            "/F",
        ])
        .output();
    let _ = std::fs::remove_file(&patch_file);
    match output {
        Ok(out) if out.status.success() => {
            if let Some(marker) = power_refused_marker() {
                let _ = std::fs::remove_file(marker);
            }
            Ok(())
        }
        Ok(out) => {
            if let Some(marker) = power_refused_marker() {
                let _ = std::fs::write(marker, "");
            }
            anyhow::bail!(
                "The scheduler refused the power-settings update: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            )
        }
        Err(e) => {
            if let Some(marker) = power_refused_marker() {
                let _ = std::fs::write(marker, "");
            }
            Err(e).context("Failed to execute schtasks")
        }
    }
}

/// True when the installed task still carries the power gates and this machine has not
/// already refused the re-registration that lifts them. `ensure_daemon` uses this to
/// fix tasks registered by versions that did not know the defaults were hostile to
/// laptops — which is every version before the one that added this.
pub fn wants_power_upgrade() -> bool {
    if power_refused_marker().is_some_and(|m| m.exists()) {
        return false;
    }
    // No readable definition means nothing to patch — and never a reason to guess.
    task_xml().is_some_and(|xml| patch_power_settings_xml(&xml).is_some())
}

/// The windowless twin's path, beside the binary the scheduler would otherwise run.
fn windowless_twin_path(exe_path: &Path) -> PathBuf {
    exe_path.with_file_name(WINDOWS_WINDOWLESS_BIN)
}

/// The `devpw.exe` that shipped with the running binary, if this delivery carries one.
///
/// It is a build target, so it sits beside whatever is executing right now — the
/// unzipped archive, `~/.cargo/bin`, the directory an installer wrote. A delivery that
/// predates it, or one that only unpacks the two console names, simply has no twin here
/// and `install` falls through to its next registration tier.
fn shipped_windowless_binary() -> Option<PathBuf> {
    let shipped = std::env::current_exe()
        .ok()?
        .with_file_name(WINDOWS_WINDOWLESS_BIN);
    shipped.is_file().then_some(shipped)
}

/// Put `devpw.exe` beside `exe_path`, returning its path once it is there.
///
/// The twin is *placed*, never generated. An earlier release built it on the machine by
/// reading its own image, rewriting the PE subsystem field and writing the result out
/// under a new name — a program emitting a modified executable copy of itself and then
/// registering it for persistence, which is what a dropper does and what Sophos
/// quarantined the binary for. The subsystem now comes from the linker instead, so the
/// only thing left to do here is the same hard-link-or-staged-copy every other managed
/// file gets.
fn ensure_windowless_twin(exe_path: &Path) -> Option<PathBuf> {
    // Almost always the managed copy under the config directory, because `get_exe_path`
    // resolves there first. The exception is a machine where that copy could not be made,
    // and then `exe_path` is wherever the package manager put the binary — which for
    // WinGet and Scoop is a directory they version and replace whole on upgrade. A twin
    // written there is orphaned by the next upgrade while the scheduled task still names
    // it, so the daemon runs a release the user thinks they replaced. Refusing costs the
    // windowless route only; `install` falls through to the S4U registration below it.
    if crate::channel::Channel::detect().replaces_its_directory()
        && crate::setup::managed_exe_path().is_ok_and(|managed| managed != exe_path)
    {
        return None;
    }
    place_windowless_twin(
        &shipped_windowless_binary()?,
        &windowless_twin_path(exe_path),
    )
}

/// Copy `shipped` to `twin`, or confirm the copy already there is the same release.
///
/// Split out from `ensure_windowless_twin` so it can be tested against two real paths: the
/// caller's half depends on where this process happens to be running from, which under a
/// test harness is not something a test may assume.
fn place_windowless_twin(shipped: &Path, twin: &Path) -> Option<PathBuf> {
    // Running out of the managed directory already: the shipped twin *is* the twin.
    if shipped == twin {
        return Some(twin.to_path_buf());
    }
    if twin.is_file() {
        if crate::setup::same_contents(twin, shipped) {
            return Some(twin.to_path_buf());
        }
        // A twin strictly newer than the shipped copy stays. The self-update now
        // reconciles the twin against the release directly, so the devpw beside the
        // running binary can be the *older* of the two, and replacing a freshly
        // downloaded twin with it would quietly undo the upgrade it came from.
        if twin_outranks_shipped(twin, shipped) {
            return Some(twin.to_path_buf());
        }
        // An upgrade replaced the shipped binary, so the placed one is a previous
        // release that the scheduled task still names. Removing it first and only
        // then placing the replacement used to fail outright on Windows CI runners:
        // a moment where the antivirus scanner has the freshly-written `.exe` open is
        // enough to fail `remove_file`, and the twin was left stale with nothing
        // retrying the swap. Staging beside it and renaming over it never needs the
        // old file to be deletable, only replaceable.
        return stage_and_replace(shipped, twin);
    }
    if std::fs::hard_link(shipped, twin).is_ok() {
        return Some(twin.to_path_buf());
    }
    // Never `fs::copy` onto a name that exists: the usual reason `hard_link` fails is
    // that a concurrent pass created it as a hard link to `shipped`, and `fs::copy`
    // opens its destination with `O_TRUNC` — truncating a hard link empties the shared
    // inode, destroying the very file being copied. `setup::ensure_twin_of` records the
    // CI outage that taught this.
    if twin.is_file() {
        return Some(twin.to_path_buf());
    }
    stage_and_replace(shipped, twin)
}

/// Put `shipped` at `twin` via a staging file renamed into place, replacing whatever
/// is at `twin` already.
///
/// Renaming over an existing file only needs it to be replaceable, not first
/// deletable, unlike a `remove_file` followed by `hard_link`, which fails outright
/// the moment something else (an antivirus scan, a concurrent pass) briefly has the
/// old file open.
fn stage_and_replace(shipped: &Path, twin: &Path) -> Option<PathBuf> {
    let staging = twin.with_extension("new");
    let staged =
        std::fs::hard_link(shipped, &staging).is_ok() || std::fs::copy(shipped, &staging).is_ok();
    if staged && std::fs::rename(&staging, twin).is_ok() {
        return Some(twin.to_path_buf());
    }
    let _ = std::fs::remove_file(&staging);
    // The rename loses only to a concurrent pass that placed its own copy, which serves
    // exactly as well.
    twin.is_file().then(|| twin.to_path_buf())
}

/// Whether the placed twin's build stamp is strictly newer than the shipped copy's.
///
/// A twin with no readable stamp never outranks anything, and a shipped copy with no
/// stamp is outranked by any stamped twin: unstamped means built before stamping
/// existed, which is as old as a build can be.
fn twin_outranks_shipped(twin: &Path, shipped: &Path) -> bool {
    let stamp = |p: &Path| {
        std::fs::read(p)
            .ok()
            .and_then(|b| crate::commands::trust::version_from_stamp(&b))
    };
    let Some(twin_v) = stamp(twin) else {
        return false;
    };
    match stamp(shipped) {
        None => true,
        Some(shipped_v) => {
            crate::commands::update::compare_versions(&twin_v, &shipped_v)
                == Some(std::cmp::Ordering::Greater)
        }
    }
}

/// Refresh the windowless twin after an upgrade, when one is in use.
///
/// The scheduled task names `devpw.exe`, so replacing the managed binary alone would
/// leave the daemon running the previous release forever. Only refreshes a twin that
/// already exists — creating one is the installer's decision, not a side effect of
/// every settled setup pass.
pub fn refresh_windowless_twin() {
    let exe_path = get_exe_path();
    if windowless_twin_path(&exe_path).is_file() {
        let _ = ensure_windowless_twin(&exe_path);
    }
}

/// Installs the Windows Task Scheduler task.
///
/// Three registrations, in order of preference, so no failure ever costs the machine
/// the daemon itself:
///
/// 1. The windowless twin (`devpw.exe`), as a plain interactive task. Nothing can
///    flash — the binary has no console to show — and the task runs in the user's own
///    session, so mapped network drives and everything else a logon session carries
///    keep working.
/// 2. The console binary under an S4U logon (`/RU <account> /NP`), which runs in a
///    non-interactive session: still no window, but no network credentials either.
/// 3. The console binary as a plain interactive task — visible, but functional.
pub fn install(interval_days: u64) -> Result<()> {
    let exe_path = get_exe_path();

    // Every path out of this function ends by either writing the refusal marker or
    // clearing it, so start from neither.
    if let Ok(dir) = crate::config::Registry::config_dir() {
        sweep_refusal_markers(&dir);
    }

    if let Some(twin) = ensure_windowless_twin(&exe_path) {
        let args = build_install_command(&twin.to_string_lossy(), interval_days);
        if let Ok(output) = spawn::command("schtasks").args(&args).output()
            && output.status.success()
        {
            // A machine that once refused may have been elevated or unlocked since;
            // the marker must not outlive the refusal it records.
            if let Some(marker) = windowless_refused_marker() {
                let _ = std::fs::remove_file(marker);
            }
            // Registration worked; the gates are a should-fix, not a must. A refusal
            // here is remembered and reported by the next setup pass, never fatal.
            let _ = apply_power_settings();
            return Ok(());
        }
    }

    let exe_str = exe_path.to_string_lossy();
    if let Some(account) = current_account() {
        let args = build_install_command_windowless(&exe_str, interval_days, &account);
        if let Ok(output) = spawn::command("schtasks").args(&args).output()
            && output.status.success()
        {
            // No window here either, but no logon session's credentials. The marker
            // still records that the *preferred* route failed, so settled passes stop
            // retrying it; an elevated `devp daemon on` retries regardless.
            if let Some(marker) = windowless_refused_marker() {
                let _ = std::fs::write(marker, "");
            }
            let _ = apply_power_settings();
            return Ok(());
        }
    }
    if let Some(marker) = windowless_refused_marker() {
        let _ = std::fs::write(marker, "");
    }

    let args = build_install_command(&exe_str, interval_days);
    let output = spawn::command("schtasks")
        .args(&args)
        .output()
        .context("Failed to execute schtasks")?;

    if output.status.success() {
        let _ = apply_power_settings();
        Ok(())
    } else {
        anyhow::bail!(
            "Failed to install task: {}",
            String::from_utf8_lossy(&output.stderr)
        )
    }
}

/// Uninstalls the Windows Task Scheduler task.
pub fn uninstall() -> Result<()> {
    let output = spawn::command("schtasks")
        .args(["/Delete", "/TN", TASK_NAME, "/F"])
        .output()
        .context("Failed to execute schtasks")?;

    if output.status.success() {
        return Ok(());
    }
    // A delete that failed because there was nothing to delete is the state the
    // caller asked for. The error text is localised, so instead of matching it,
    // ask the scheduler whether the task exists now — `devp uninstall` used to
    // fail outright on a machine where setup had never managed to register it.
    if matches!(status(), Ok(DaemonStatus::NotInstalled)) {
        return Ok(());
    }
    anyhow::bail!(
        "Failed to uninstall task: {}",
        String::from_utf8_lossy(&output.stderr)
    )
}

/// Decide the task's state from the output of a task-list query.
///
/// Split out from [`status`] so the parsing is testable without a scheduler, and kept
/// deliberately free of any English text: `schtasks` localises its messages, so matching
/// on them reports `Unknown` on every non-English Windows — which in turn makes setup
/// skip the scheduler forever on those machines.
///
/// The task *name* is not localised, so that is what this looks for. Rows are CSV with
/// the name first, e.g. `"\DevPrune","14/02/2026 09:00:00","Ready"`.
fn classify_query(succeeded: bool, stdout: &str, stderr: &str) -> DaemonStatus {
    if !succeeded {
        // Enumerating every task should not fail. If it did, the answer is genuinely
        // unknown — an access-denied here must not be read as "absent", or every run
        // would try to reinstall a task that is already there.
        let reason = stderr.trim();
        return DaemonStatus::Unknown(if reason.is_empty() {
            "schtasks query failed without a message".to_string()
        } else {
            reason.to_string()
        });
    }

    let found = stdout.lines().any(|line| {
        line.split(',')
            .next()
            .map(|name| name.trim().trim_matches('"'))
            .is_some_and(|name| name.eq_ignore_ascii_case(&format!("\\{TASK_NAME}")))
    });

    if found {
        DaemonStatus::Installed
    } else {
        DaemonStatus::NotInstalled
    }
}

/// Checks the status of the Windows Task Scheduler task.
pub fn status() -> Result<DaemonStatus> {
    // Enumerate rather than query by name: a by-name query that fails cannot be told
    // apart from a task that is absent without reading a localised error string.
    let output = spawn::command("schtasks")
        .args(["/Query", "/FO", "CSV", "/NH"])
        .output()
        .context("Failed to execute schtasks")?;

    Ok(classify_query(
        output.status.success(),
        &String::from_utf8_lossy(&output.stdout),
        &String::from_utf8_lossy(&output.stderr),
    ))
}

/// Decode the bytes `schtasks /XML` writes.
///
/// It emits UTF-16LE with a byte-order mark, not the console codepage every other
/// `schtasks` query uses. Read as UTF-8 the whole document comes back as text separated
/// by NUL bytes, which no `find` on an element name will ever match — a silent empty
/// answer rather than a visible failure.
fn decode_schtasks_xml(bytes: &[u8]) -> String {
    if bytes.starts_with(&[0xFF, 0xFE]) {
        let (pairs, _odd_tail) = bytes[2..].as_chunks::<2>();
        let units: Vec<u16> = pairs.iter().map(|&pair| u16::from_le_bytes(pair)).collect();
        String::from_utf16_lossy(&units)
    } else {
        String::from_utf8_lossy(bytes).into_owned()
    }
}

/// Pull the executable out of a task definition.
///
/// `<Actions><Exec><Command>` holds the program on its own — `schtasks` splits the `/TR`
/// string into `Command` and `Arguments` when it registers the task — and element names
/// are not localised, unlike the field labels `/V /FO LIST` prints.
fn parse_registered_command(xml: &str) -> Option<std::path::PathBuf> {
    let start = xml.find("<Command>")? + "<Command>".len();
    let end = start + xml[start..].find("</Command>")?;
    let command = xml[start..end].trim().trim_matches('"').trim();
    if command.is_empty() {
        return None;
    }
    // `&` is the only one of the five predefined entities that can appear in a Windows
    // path, but decoding all of them costs nothing and `&amp;` must come last or it would
    // re-expand the ampersands the others just produced.
    let unescaped = command
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&apos;", "'")
        .replace("&amp;", "&");
    Some(std::path::PathBuf::from(unescaped))
}

/// The registered task's definition, if the task exists and can be read.
fn task_xml() -> Option<String> {
    let output = spawn::command("schtasks")
        .args(["/Query", "/TN", TASK_NAME, "/XML", "ONE"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    Some(decode_schtasks_xml(&output.stdout))
}

/// The binary the registered task will run, if the task exists and can be read.
pub fn registered_exe_path() -> Option<std::path::PathBuf> {
    parse_registered_command(&task_xml()?)
}

/// Whether a task definition runs with the interactive token — the logon type whose
/// console window flashes at the logged-in user every time the task fires.
fn parse_is_interactive(xml: &str) -> Option<bool> {
    let start = xml.find("<LogonType>")? + "<LogonType>".len();
    let end = start + xml[start..].find("</LogonType>")?;
    Some(xml[start..end].trim() == "InteractiveToken")
}

/// True when the installed task would flash a console window and this machine has not
/// already refused the S4U registration that fixes it. `ensure_daemon` uses this to
/// upgrade tasks registered by versions that only knew the interactive logon, or that
/// predate the windowless twin.
pub fn wants_windowless_upgrade() -> bool {
    let Some(xml) = task_xml() else {
        // No readable definition means no task to upgrade — re-registering a task
        // that cannot be read would be guessing.
        return false;
    };
    // A task already pointing at `devpw.exe` cannot flash regardless of logon type;
    // there is nothing left to upgrade to.
    if parse_registered_command(&xml).is_some_and(|exe| {
        exe.file_name()
            .is_some_and(|name| name.eq_ignore_ascii_case(WINDOWS_WINDOWLESS_BIN))
    }) {
        return false;
    }
    if windowless_refused_marker().is_some_and(|m| m.exists()) {
        return false;
    }
    // An S4U task registered by an earlier release shows no window but is sessionless;
    // the twin route restores mapped drives too, so it is still an upgrade — an
    // interactive console task doubly so.
    parse_is_interactive(&xml).is_some()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_install_command() {
        let cmd = build_install_command("C:\\test\\dev-prune.exe", 2);
        assert_eq!(
            cmd,
            vec![
                "/Create",
                "/SC",
                "DAILY",
                "/MO",
                "2",
                "/TN",
                "DevPrune",
                "/TR",
                "\"C:\\test\\dev-prune.exe\" run --yes --daemon",
                "/F"
            ]
        );
    }

    #[test]
    fn test_build_install_command_honours_interval() {
        let cmd = build_install_command("dev-prune.exe", 7);
        assert_eq!(cmd[4], "7");
    }

    #[test]
    fn the_sweep_takes_every_spelling_of_the_marker_and_leaves_the_rest() {
        let dir = tempfile::tempdir().unwrap();
        let unrelated = dir.path().join("repos.json");
        let current = dir
            .path()
            .join(crate::constants::SCHEDULER_WINDOWLESS_REFUSED_MARKER);
        // What 1.14.0 wrote.
        let legacy = dir.path().join("scheduler-hidden-refused");
        for path in [&unrelated, &current, &legacy] {
            std::fs::write(path, "").unwrap();
        }

        sweep_refusal_markers(dir.path());

        assert!(unrelated.exists(), "the sweep must not touch the registry");
        assert!(!current.exists());
        assert!(
            !legacy.exists(),
            "an upgrade must not strand the old spelling"
        );
    }

    #[test]
    fn the_windowless_command_adds_the_password_less_run_as_and_nothing_else() {
        let visible = build_install_command("dev-prune.exe", 2);
        let windowless = build_install_command_windowless("dev-prune.exe", 2, "PC\\krish");
        assert_eq!(windowless[..visible.len()], visible[..]);
        assert_eq!(windowless[visible.len()..], ["/RU", "PC\\krish", "/NP"]);
    }

    #[test]
    fn the_interactive_logon_is_recognised_and_the_s4u_one_is_not() {
        assert_eq!(
            parse_is_interactive("<LogonType>InteractiveToken</LogonType>"),
            Some(true)
        );
        assert_eq!(
            parse_is_interactive("<LogonType>S4U</LogonType>"),
            Some(false)
        );
        // A definition without the element answers nothing — the caller must not
        // re-register a task it cannot read.
        assert_eq!(parse_is_interactive("<Task></Task>"), None);
    }

    #[test]
    fn an_interval_schtasks_would_reject_is_clamped_into_range() {
        // `/SC DAILY /MO` accepts 1–365; outside that, task creation fails outright.
        assert_eq!(build_install_command("dev-prune.exe", 0)[4], "1");
        assert_eq!(build_install_command("dev-prune.exe", 400)[4], "365");
    }

    /// Bytes carrying a synthetic build stamp, the shape `version_from_stamp` reads.
    fn stamped(version: &str) -> Vec<u8> {
        format!("{}{version}/end", crate::constants::VERSION_STAMP_MARK).into_bytes()
    }

    #[test]
    fn a_newer_placed_twin_survives_a_refresh_from_an_older_shipped_copy() {
        let dir = tempfile::tempdir().unwrap();
        let shipped = dir.path().join("shipped-devpw.exe");
        let twin = dir.path().join("devpw.exe");
        std::fs::write(&shipped, stamped("1.18.0")).unwrap();
        std::fs::write(&twin, stamped("1.21.0")).unwrap();

        let placed = place_windowless_twin(&shipped, &twin).unwrap();

        assert_eq!(placed, twin);
        // The self-update downloads the twin directly now, so the devpw beside the
        // running binary can be the older of the two. Refreshing from it must not
        // quietly undo the upgrade the download just made.
        assert_eq!(std::fs::read(&twin).unwrap(), stamped("1.21.0"));
    }

    #[test]
    fn an_older_placed_twin_is_still_replaced() {
        let dir = tempfile::tempdir().unwrap();
        let shipped = dir.path().join("shipped-devpw.exe");
        let twin = dir.path().join("devpw.exe");
        std::fs::write(&shipped, stamped("1.21.0")).unwrap();
        std::fs::write(&twin, stamped("1.18.0")).unwrap();

        place_windowless_twin(&shipped, &twin).unwrap();

        assert_eq!(std::fs::read(&twin).unwrap(), stamped("1.21.0"));
    }

    #[test]
    fn a_missing_stamp_never_outranks_and_is_always_outranked() {
        let dir = tempfile::tempdir().unwrap();
        let with_stamp = dir.path().join("stamped.exe");
        let without = dir.path().join("plain.exe");
        std::fs::write(&with_stamp, stamped("1.21.0")).unwrap();
        std::fs::write(&without, b"built before stamping existed").unwrap();

        assert!(
            !twin_outranks_shipped(&without, &with_stamp),
            "an unstamped twin outranks nothing"
        );
        assert!(
            twin_outranks_shipped(&with_stamp, &without),
            "an unstamped shipped copy is older than any stamped twin"
        );
    }

    /// One CSV row as `schtasks /FO CSV /NH` emits it.
    fn row(name: &str) -> String {
        format!("\"{name}\",\"14/02/2026 09:00:00\",\"Ready\"\n")
    }

    #[test]
    fn the_task_is_found_by_name_in_the_listing() {
        let listing = format!("{}{}", row("\\SomeOtherTask"), row("\\DevPrune"));
        assert!(matches!(
            classify_query(true, &listing, ""),
            DaemonStatus::Installed
        ));
    }

    #[test]
    fn an_absent_task_reads_as_not_installed_not_unknown() {
        let listing = row("\\SomeOtherTask");
        assert!(matches!(
            classify_query(true, &listing, ""),
            DaemonStatus::NotInstalled
        ));
    }

    #[test]
    fn a_localised_scheduler_still_answers_correctly() {
        // The whole point of enumerating: nothing here is English, and the task name
        // is the one column Windows does not translate.
        let listing = "\"\\DevPrune\",\"14.02.2026 09:00:00\",\"Bereit\"\n";
        assert!(matches!(
            classify_query(true, listing, ""),
            DaemonStatus::Installed
        ));
    }

    #[test]
    fn a_similarly_named_task_is_not_mistaken_for_ours() {
        let listing = format!("{}{}", row("\\DevPruneOld"), row("\\Foo\\DevPrune"));
        assert!(matches!(
            classify_query(true, &listing, ""),
            DaemonStatus::NotInstalled
        ));
    }

    #[test]
    fn a_failed_query_is_unknown_rather_than_absent() {
        // Reading access-denied as "absent" would make every run reinstall a task that
        // is already there, and fail every time.
        let status = classify_query(false, "", "ERROR: Access is denied.");
        match status {
            DaemonStatus::Unknown(why) => assert!(why.contains("Access is denied")),
            other => panic!("expected Unknown, got {other}"),
        }
    }

    #[test]
    fn a_silent_failure_still_explains_itself() {
        match classify_query(false, "", "   ") {
            DaemonStatus::Unknown(why) => assert!(!why.is_empty()),
            other => panic!("expected Unknown, got {other}"),
        }
    }

    /// The shape `schtasks /XML ONE` actually returns, trimmed to the part that matters.
    const TASK_XML: &str = r#"<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <Actions Context="Author">
    <Exec>
      <Command>"C:\Users\a\AppData\Roaming\dev-prune\bin\dev-prune.exe"</Command>
      <Arguments>run --yes --daemon</Arguments>
    </Exec>
  </Actions>
</Task>"#;

    #[test]
    fn the_registered_binary_is_read_out_of_the_task_definition() {
        assert_eq!(
            parse_registered_command(TASK_XML),
            Some(std::path::PathBuf::from(
                "C:\\Users\\a\\AppData\\Roaming\\dev-prune\\bin\\dev-prune.exe"
            ))
        );
    }

    #[test]
    fn the_arguments_are_not_mistaken_for_part_of_the_path() {
        let path = parse_registered_command(TASK_XML).unwrap();
        assert!(!path.to_string_lossy().contains("--daemon"));
    }

    #[test]
    fn an_escaped_ampersand_in_the_path_survives() {
        let xml = "<Command>\"C:\\a &amp; b\\dev-prune.exe\"</Command>";
        assert_eq!(
            parse_registered_command(xml),
            Some(std::path::PathBuf::from("C:\\a & b\\dev-prune.exe"))
        );
    }

    #[test]
    fn a_document_without_an_exec_action_answers_nothing() {
        assert!(parse_registered_command("<Task><Actions /></Task>").is_none());
        assert!(parse_registered_command("<Command></Command>").is_none());
    }

    #[test]
    fn utf16_output_is_decoded_rather_than_read_as_nul_separated_bytes() {
        let mut bytes = vec![0xFF, 0xFE];
        for unit in "<Command>\"C:\\x.exe\"</Command>".encode_utf16() {
            bytes.extend_from_slice(&unit.to_le_bytes());
        }
        let decoded = decode_schtasks_xml(&bytes);
        assert!(!decoded.contains('\0'));
        assert_eq!(
            parse_registered_command(&decoded),
            Some(std::path::PathBuf::from("C:\\x.exe"))
        );
    }

    #[test]
    fn output_without_a_bom_is_still_readable() {
        assert_eq!(
            decode_schtasks_xml(b"<Command>x</Command>"),
            "<Command>x</Command>"
        );
    }

    #[test]
    fn the_twin_lives_beside_the_managed_binary_under_the_reserved_name() {
        let twin = windowless_twin_path(Path::new(r"C:\cfg\bin\dev-prune.exe"));
        assert_eq!(twin, Path::new(r"C:\cfg\bin\devpw.exe"));
    }

    /// A delivery that carries no `devpw.exe` must not be answered by inventing one —
    /// `install` has two further tiers that still work without it.
    #[test]
    fn a_missing_shipped_twin_places_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let shipped = dir.path().join("nowhere").join(WINDOWS_WINDOWLESS_BIN);
        let twin = dir.path().join(WINDOWS_WINDOWLESS_BIN);
        assert!(place_windowless_twin(&shipped, &twin).is_none());
        assert!(!twin.exists());
    }

    #[test]
    fn the_shipped_twin_is_placed_verbatim_and_refreshed_when_it_is_a_previous_release() {
        let ship_dir = tempfile::tempdir().unwrap();
        let managed = tempfile::tempdir().unwrap();
        let shipped = ship_dir.path().join(WINDOWS_WINDOWLESS_BIN);
        let twin = managed.path().join(WINDOWS_WINDOWLESS_BIN);
        std::fs::write(&shipped, b"release one").unwrap();

        assert_eq!(place_windowless_twin(&shipped, &twin).unwrap(), twin);
        assert_eq!(std::fs::read(&twin).unwrap(), b"release one");

        // Idempotent: an unchanged release must not rewrite the file.
        assert_eq!(place_windowless_twin(&shipped, &twin).unwrap(), twin);
        assert_eq!(std::fs::read(&twin).unwrap(), b"release one");

        // An upgrade replaces the shipped binary; the placed copy is stale and the
        // scheduled task still names it, so it must be replaced rather than trusted.
        std::fs::write(&shipped, b"release two, which is longer").unwrap();
        assert_eq!(place_windowless_twin(&shipped, &twin).unwrap(), twin);
        assert_eq!(
            std::fs::read(&twin).unwrap(),
            b"release two, which is longer"
        );
        assert!(!twin.with_extension("new").exists(), "no staging debris");
    }

    /// The twin is byte-for-byte what shipped. Nothing here edits an executable, which is
    /// the whole point of making it a build target.
    #[test]
    fn placing_the_twin_never_alters_a_byte_of_it() {
        let ship_dir = tempfile::tempdir().unwrap();
        let managed = tempfile::tempdir().unwrap();
        let shipped = ship_dir.path().join(WINDOWS_WINDOWLESS_BIN);
        let twin = managed.path().join(WINDOWS_WINDOWLESS_BIN);
        let image: Vec<u8> = (0u16..4096).map(|b| (b % 251) as u8).collect();
        std::fs::write(&shipped, &image).unwrap();

        place_windowless_twin(&shipped, &twin).unwrap();
        assert_eq!(std::fs::read(&twin).unwrap(), image);
        assert_eq!(std::fs::read(&shipped).unwrap(), image);
    }

    /// Running out of the managed directory already: there is nothing to place, and in
    /// particular nothing that could truncate the file onto itself.
    #[test]
    fn a_twin_that_is_already_the_shipped_file_is_left_alone() {
        let dir = tempfile::tempdir().unwrap();
        let twin = dir.path().join(WINDOWS_WINDOWLESS_BIN);
        std::fs::write(&twin, b"the one and only").unwrap();
        assert_eq!(place_windowless_twin(&twin, &twin).unwrap(), twin);
        assert_eq!(std::fs::read(&twin).unwrap(), b"the one and only");
    }

    /// A default registration as `schtasks /Query /XML ONE` exports it, verbatim from a
    /// real machine: both battery gates present and true, `StartWhenAvailable` absent.
    const GATED_TASK_XML: &str = r#"<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <Principals>
    <Principal id="Author">
      <LogonType>InteractiveToken</LogonType>
    </Principal>
  </Principals>
  <Settings>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
  </Settings>
  <Triggers>
    <CalendarTrigger>
      <StartBoundary>2026-08-22T09:44:00</StartBoundary>
      <ScheduleByDay>
        <DaysInterval>2</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Actions Context="Author">
    <Exec>
      <Command>"C:\Users\a\AppData\Roaming\dev-prune\bin\devpw.exe"</Command>
      <Arguments>run --yes --daemon</Arguments>
    </Exec>
  </Actions>
</Task>"#;

    #[test]
    fn a_default_registration_gets_all_three_power_gates_lifted() {
        let patched = patch_power_settings_xml(GATED_TASK_XML).unwrap();
        assert!(patched.contains("<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"));
        assert!(patched.contains("<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>"));
        // Absent means false, so the element has to be *inserted*, not flipped.
        assert!(patched.contains("<StartWhenAvailable>true</StartWhenAvailable>"));
        assert!(!patched.contains(">true</DisallowStartIfOnBatteries>"));
        assert!(!patched.contains(">true</StopIfGoingOnBatteries>"));
    }

    #[test]
    fn the_patch_touches_nothing_but_the_power_settings() {
        let patched = patch_power_settings_xml(GATED_TASK_XML).unwrap();
        // The trigger time is the whole reason this is a patch and not a fresh
        // `/SC DAILY` registration, which would move it to "now".
        assert!(patched.contains("<StartBoundary>2026-08-22T09:44:00</StartBoundary>"));
        assert!(patched.contains("<DaysInterval>2</DaysInterval>"));
        assert!(patched.contains("<LogonType>InteractiveToken</LogonType>"));
        assert!(patched.contains("devpw.exe"));
        assert!(patched.contains("run --yes --daemon"));
    }

    #[test]
    fn an_already_lifted_task_is_left_alone() {
        let patched = patch_power_settings_xml(GATED_TASK_XML).unwrap();
        // Re-running the patch over its own output must answer "nothing to do", or
        // every settled setup pass would re-register the task forever.
        assert!(patch_power_settings_xml(&patched).is_none());
    }

    #[test]
    fn an_explicit_false_start_when_available_is_flipped_not_duplicated() {
        let xml = "<Settings><StartWhenAvailable>false</StartWhenAvailable></Settings>";
        let patched = patch_power_settings_xml(xml).unwrap();
        assert_eq!(patched.matches("<StartWhenAvailable>").count(), 1);
        assert!(patched.contains("<StartWhenAvailable>true</StartWhenAvailable>"));
    }

    #[test]
    fn a_definition_without_a_settings_block_is_not_guessed_at() {
        // Nothing to flip and nowhere to insert: the answer is "no change", not a
        // mangled document handed to `schtasks /Create`.
        assert!(patch_power_settings_xml(TASK_XML).is_none());
    }

    #[test]
    fn the_encoder_round_trips_through_the_decoder() {
        // What `apply_power_settings` writes must be exactly what a later
        // `task_xml()` reads back, BOM included.
        let bytes = encode_schtasks_xml(GATED_TASK_XML);
        assert!(bytes.starts_with(&[0xFF, 0xFE]));
        assert_eq!(decode_schtasks_xml(&bytes), GATED_TASK_XML);
    }

    #[test]
    fn the_upgrade_predicate_stops_once_the_task_names_the_twin() {
        // The XML shape install() produces when the twin registration wins.
        let xml = "<Command>\"C:\\cfg\\bin\\devpw.exe\"</Command>";
        let registered = parse_registered_command(xml).unwrap();
        assert!(
            registered
                .file_name()
                .is_some_and(|n| n.eq_ignore_ascii_case(WINDOWS_WINDOWLESS_BIN))
        );
    }
}