pond-db 0.16.1

Lossless storage and search for sessions from any AI agent client
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
//! `pond schedule`: register `pond sync -q --no-wait` with the OS scheduler.
//!
//! macOS uses launchd ONLY (cron on macOS runs without the user's GUI
//! context, trips TCC folder-access denials, and silently drops jobs that
//! span sleep). Linux prefers systemd user timers (`Persistent=true` catches
//! up after downtime) and falls back to a fenced crontab block. Windows uses
//! Task Scheduler: the task Execs `pondw.exe`, pond's windowless launcher,
//! and the task XML provides the settings that align it with the
//! launchd/systemd posture (battery-friendly, catch-up after missed runs).
//!
//! The scheduled job is `pond sync -q --no-wait`: NOT `--yes`, so an
//! unattended run can never auto-enable freshly-detected adapters, and
//! `--no-wait` so a tick that lands while another sync holds the per-store
//! lock skips cleanly (exit 0) instead of queueing behind it.
//!
//! Bin-only module: OS-scheduler integration has no library callers.

use anyhow::{Context, Result};
use clap::{Subcommand, ValueEnum};
use pond::output::{dim, line, line_err, paint};
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub(crate) enum ScheduleEvery {
    #[value(name = "5m")]
    M5,
    #[value(name = "15m")]
    M15,
    #[value(name = "1h")]
    H1,
    #[value(name = "6h")]
    H6,
    #[value(name = "1d")]
    D1,
}

impl ScheduleEvery {
    pub(crate) fn secs(self) -> u32 {
        match self {
            Self::M5 => 300,
            Self::M15 => 900,
            Self::H1 => 3_600,
            Self::H6 => 21_600,
            Self::D1 => 86_400,
        }
    }

    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::M5 => "5m",
            Self::M15 => "15m",
            Self::H1 => "1h",
            Self::H6 => "6h",
            Self::D1 => "1d",
        }
    }

    fn from_secs(secs: u32) -> Option<Self> {
        [Self::M5, Self::M15, Self::H1, Self::H6, Self::D1]
            .into_iter()
            .find(|every| every.secs() == secs)
    }
}

#[derive(Debug, Subcommand)]
pub(crate) enum ScheduleCmd {
    /// Register the schedule (idempotent: safe to re-run).
    ///
    /// Re-running with a different `--every` replaces the existing
    /// registration; re-running with the same one is a no-op.
    #[command(after_long_help = "Examples:
  pond schedule start              every 5 minutes (the default)
  pond schedule start --every 1h
  pond schedule start --every 1d")]
    Start {
        /// How often to run `pond sync -q --no-wait`.
        #[arg(long, value_enum, default_value_t = ScheduleEvery::M5)]
        every: ScheduleEvery,
    },
    /// Remove the schedule.
    ///
    /// Succeeds (exit 0) when nothing was registered.
    Stop,
    /// Show whether a schedule is active.
    ///
    /// Exit 0 when active, 1 when not configured.
    Status,
    /// Show recent scheduled-sync output.
    Logs {
        /// Number of trailing log lines to print.
        #[arg(long, default_value_t = 50)]
        lines: usize,
    },
}

/// One scheduler probe's answer, shared by the `pond status` text line and
/// the JSON document (which needs the fields structured, not pre-rendered).
pub(crate) struct ScheduleSnapshot {
    pub line: String,
    pub active: bool,
    pub backend: Option<&'static str>,
    pub every: Option<ScheduleEvery>,
}

// ===========================================================================
// Shared across all platforms
// ===========================================================================

/// Internal state of the OS scheduler for the pond-sync registration.
enum State {
    Active {
        backend: &'static str,
        every: Option<ScheduleEvery>,
    },
    Inactive,
}
use State::{Active, Inactive};

fn render_state(state: &State) -> String {
    match state {
        Active { backend, every } => format!(
            "{}  active ({backend}{})",
            paint("schedule", dim()),
            every
                .map(|every| format!(", every {}", every.label()))
                .unwrap_or_default(),
        ),
        Inactive => format!(
            "{}  not configured - run `pond schedule start` to sync automatically",
            paint("schedule", dim()),
        ),
    }
}

/// The log file path: `<pond_state_dir>/sync.log`. Single source of truth
/// used by both platform modules and the shared `logs()` function.
pub(crate) fn log_path() -> PathBuf {
    crate::syncstate::pond_state_dir().join("sync.log")
}

pub(crate) fn status_line() -> String {
    status_snapshot().line
}

pub(crate) fn status_snapshot() -> ScheduleSnapshot {
    match platform_probe() {
        Ok(state) => {
            let (active, backend, every) = match &state {
                Active { backend, every } => (true, Some(*backend), *every),
                Inactive => (false, None, None),
            };
            ScheduleSnapshot {
                line: render_state(&state),
                active,
                backend,
                every,
            }
        }
        Err(_) => ScheduleSnapshot {
            line: format!(
                "{}  unknown (scheduler probe failed)",
                paint("schedule", dim())
            ),
            active: false,
            backend: None,
            every: None,
        },
    }
}

pub(crate) fn run(command: ScheduleCmd, config: Option<PathBuf>) -> Result<()> {
    match command {
        ScheduleCmd::Start { every } => platform_start(every, &config_file(config)),
        ScheduleCmd::Stop => platform_stop(),
        ScheduleCmd::Status => {
            let state = platform_probe()?;
            line(&render_state(&state))?;
            if let Active { .. } = state {
                line(&format!(
                    "{}      {}  (pond schedule logs)",
                    paint("logs", dim()),
                    crate::config::display(&crate::config::url_for_path(log_path())?),
                ))?;
                Ok(())
            } else {
                std::process::exit(1);
            }
        }
        ScheduleCmd::Logs { lines } => logs(lines),
    }
}

/// Print the last `lines` lines of the sync log. On Linux+systemd, delegates
/// to journalctl; everywhere else reads the log file the wrapper writes.
pub(crate) fn logs(lines: usize) -> Result<()> {
    // Linux + systemd: the unit output goes to the journal, not a file.
    #[cfg(target_os = "linux")]
    if unix::systemd_timer_enabled() {
        let status = std::process::Command::new("journalctl")
            .args([
                "--user",
                "-u",
                "pond-sync.service",
                "-n",
                &lines.to_string(),
                "--no-pager",
            ])
            .status()
            .context("failed to run journalctl")?;
        if !status.success() {
            anyhow::bail!("journalctl exited {status}");
        }
        return Ok(());
    }

    let path = log_path();
    line_err(&paint(
        &format!(
            "log file: {}",
            crate::config::display(&crate::config::url_for_path(&path)?)
        ),
        dim(),
    ))?;
    let text = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            line("(no log yet - the first scheduled run hasn't happened)")?;
            return Ok(());
        }
        Err(error) => {
            return Err(error).with_context(|| format!("failed to read {}", path.display()));
        }
    };
    let all: Vec<&str> = text.lines().collect();
    let tail = all.len().saturating_sub(lines);
    for entry in &all[tail..] {
        line(entry)?;
    }
    Ok(())
}

/// The config file pinned into a registration. clap already resolved
/// `--config-file` and `POND_CONFIG_FILE` into `explicit` on every caller
/// path, so only the XDG default remains to apply. Absolutized against the
/// invoking shell's cwd: the pinned path is re-read from the scheduler's
/// working directory, which is not ours to assume - a relative pin would
/// silently miss there and the scheduled sync would run on built-in defaults.
pub(crate) fn config_file(explicit: Option<PathBuf>) -> PathBuf {
    let path = crate::config_path(explicit);
    std::path::absolute(&path).unwrap_or(path)
}

pub(crate) const CONFIG_FILE_SOURCES: &str =
    "--config-file or POND_CONFIG_FILE, falling back to $XDG_CONFIG_HOME/pond/config.toml";
pub(crate) const STATE_DIR_SOURCES: &str = "XDG_STATE_HOME, falling back to $HOME/.local/state";

/// Registration entry point for `pond init`, which calls it after the config
/// write with the config path it resolved (a `--config-file` passed to init
/// must pin into the unit, and clap's parsed value is invisible from here).
pub(crate) fn start(every: ScheduleEvery, explicit: PathBuf) -> Result<()> {
    platform_start(every, &config_file(Some(explicit)))
}

/// Paths are embedded verbatim in plist XML, a systemd quoted `Environment=`
/// value, a crontab line (where % means newline), and Task Scheduler XML
/// (where %VAR% runtime-expands with no escape syntax) - none of which the
/// templates escape. Reject the exotic characters up front instead of writing
/// a silently broken registration. `sources` names where the path resolved
/// from: the bad character may come from a fallback (`$HOME`), where "unset
/// the env var" would be a dead-end instruction. Also called by `pond init`
/// as soon as the schedule is chosen, so a doomed registration fails before
/// the config write and first sync, not after them.
pub(crate) fn reject_unembeddable(what: &str, path: &Path, sources: &str) -> Result<()> {
    let text = path.display().to_string();
    if text.contains(['<', '>', '&', '"', '%', '\n', '\r']) {
        anyhow::bail!(
            "{what} {text:?} contains a character (< > & \" % or a newline) that cannot be \
             embedded in a scheduler registration; it resolves from {sources} - use a \
             simpler absolute path and re-run `pond schedule start`"
        );
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Platform dispatchers
// ---------------------------------------------------------------------------

#[cfg(windows)]
fn platform_probe() -> Result<State> {
    windows::probe()
}
#[cfg(unix)]
fn platform_probe() -> Result<State> {
    unix::probe()
}
#[cfg(not(any(unix, windows)))]
fn platform_probe() -> Result<State> {
    Ok(Inactive)
}

// Task Scheduler's Exec action carries no environment block, so the Windows
// backend pins its paths as `pondw` arguments instead of env vars.
#[cfg(windows)]
fn platform_start(every: ScheduleEvery, config_file: &Path) -> Result<()> {
    windows::start(every, config_file)
}
#[cfg(unix)]
fn platform_start(every: ScheduleEvery, config_file: &Path) -> Result<()> {
    unix::start(every, config_file)
}
#[cfg(not(any(unix, windows)))]
fn platform_start(_every: ScheduleEvery, _config_file: &Path) -> Result<()> {
    anyhow::bail!("pond schedule is not supported on this platform yet")
}

#[cfg(windows)]
fn platform_stop() -> Result<()> {
    windows::stop()
}
#[cfg(unix)]
fn platform_stop() -> Result<()> {
    unix::stop()
}
#[cfg(not(any(unix, windows)))]
fn platform_stop() -> Result<()> {
    anyhow::bail!("pond schedule is not supported on this platform yet")
}

// ===========================================================================
// Platform: unix (launchd / systemd / cron)
// ===========================================================================

#[cfg(unix)]
mod unix {
    use std::path::{Path, PathBuf};
    use std::process::{Command, Stdio};

    use anyhow::{Context, Result, bail};

    use super::{ScheduleEvery, State};
    use State::{Active, Inactive};

    const LAUNCHD_LABEL: &str = "sh.pond.sync";
    const CRON_FENCE_BEGIN: &str = "# BEGIN POND SYNC (maintained by pond; do not edit)";
    const CRON_FENCE_END: &str = "# END POND SYNC";

    pub(super) fn probe() -> Result<State> {
        match std::env::consts::OS {
            "macos" => probe_launchd(),
            "linux" => {
                if systemd_timer_enabled() {
                    return Ok(Active {
                        backend: "systemd",
                        every: read_systemd_interval(),
                    });
                }
                if let Some(entry) = read_cron_fence_entry()? {
                    return Ok(Active {
                        backend: "cron",
                        every: cron_entry_interval(&entry),
                    });
                }
                Ok(Inactive)
            }
            _ => Ok(Inactive),
        }
    }

    /// Register the schedule. Shared by `pond schedule start` and the
    /// `pond init` schedule section (which calls it after the config write).
    pub(super) fn start(every: ScheduleEvery, config_file: &Path) -> Result<()> {
        let bin = pond_bin();
        let log = super::log_path();
        if let Some(parent) = log.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create {}", parent.display()))?;
        }
        // The scheduler daemon never sources shell rc files, so a shell-only
        // XDG_STATE_HOME would put the scheduled sync's flock and last-sync
        // record in a different state dir than manual syncs - splitting the
        // single-flight lock. Pin the registration-time resolution into the
        // job's environment (same precedent as the baked-in log path). The
        // config file is pinned for the same reason: a scheduled sync that
        // read a different config would run with different adapters and a
        // different [embeddings].enabled than a manual one.
        let state = crate::syncstate::state_root();
        super::reject_unembeddable("state dir", &state, super::STATE_DIR_SOURCES)?;
        super::reject_unembeddable("config file", config_file, super::CONFIG_FILE_SOURCES)?;
        match std::env::consts::OS {
            "macos" => start_launchd(&bin, every, &log, &state, config_file),
            "linux" => {
                if systemd_user_available() {
                    // Switching schedulers must not leave the other one
                    // firing: a systemd start strips any cron fence.
                    remove_cron_fence()?;
                    start_systemd(&bin, every, &state, config_file)
                } else {
                    stop_systemd()?;
                    start_cron(&bin, every, &log, &state, config_file)
                }
            }
            other => bail!("pond schedule is not supported on {other} yet"),
        }
    }

    pub(super) fn stop() -> Result<()> {
        let removed = match std::env::consts::OS {
            "macos" => stop_launchd()?,
            "linux" => {
                let systemd = stop_systemd()?;
                let cron = remove_cron_fence()?;
                systemd || cron
            }
            other => bail!("pond schedule is not supported on {other} yet"),
        };
        if removed {
            pond::output::line("schedule removed")?;
        } else {
            pond::output::line("nothing was scheduled")?;
        }
        Ok(())
    }

    /// True when the systemd pond-sync.timer is enabled. Exposed `pub(super)`
    /// so the parent module's shared `logs()` can delegate to journalctl on
    /// Linux+systemd without duplicating the probe.
    pub(super) fn systemd_timer_enabled() -> bool {
        Command::new("systemctl")
            .args(["--user", "is-enabled", "pond-sync.timer"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|status| status.success())
            .unwrap_or(false)
    }

    /// The binary path baked into the scheduler registration. Prefer the
    /// `pond` on PATH: that's a stable symlink that survives upgrades.
    /// `current_exe()` is the fallback - on Homebrew it resolves into a
    /// versioned Cellar path that the next upgrade deletes.
    fn pond_bin() -> PathBuf {
        crate::find_on_path("pond")
            .unwrap_or_else(|| std::env::current_exe().unwrap_or_else(|_| PathBuf::from("pond")))
    }

    // ----- launchd (macOS) -------------------------------------------------

    fn plist_path() -> Result<PathBuf> {
        let home = std::env::var_os("HOME").context("HOME is not set")?;
        Ok(PathBuf::from(home)
            .join("Library/LaunchAgents")
            .join(format!("{LAUNCHD_LABEL}.plist")))
    }

    fn plist_body(
        bin: &Path,
        every: ScheduleEvery,
        log: &Path,
        state: &Path,
        config_file: &Path,
    ) -> String {
        format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- created and maintained by pond; edits may be replaced -->
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>{LAUNCHD_LABEL}</string>
	<key>ProgramArguments</key>
	<array>
		<string>{bin}</string>
		<string>sync</string>
		<string>-q</string>
		<string>--no-wait</string>
	</array>
	<key>EnvironmentVariables</key>
	<dict>
		<key>XDG_STATE_HOME</key>
		<string>{state}</string>
		<key>POND_CONFIG_FILE</key>
		<string>{config_file}</string>
	</dict>
	<key>StartInterval</key>
	<integer>{secs}</integer>
	<key>StandardOutPath</key>
	<string>{log}</string>
	<key>StandardErrorPath</key>
	<string>{log}</string>
	<key>ProcessType</key>
	<string>Background</string>
</dict>
</plist>
"#,
            bin = bin.display(),
            secs = every.secs(),
            log = log.display(),
            state = state.display(),
            config_file = config_file.display(),
        )
    }

    fn launchd_registered(uid: &str) -> bool {
        Command::new("launchctl")
            .args(["print", &format!("gui/{uid}/{LAUNCHD_LABEL}")])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|status| status.success())
            .unwrap_or(false)
    }

    fn start_launchd(
        bin: &Path,
        every: ScheduleEvery,
        log: &Path,
        state: &Path,
        config_file: &Path,
    ) -> Result<()> {
        let plist = plist_path()?;
        let body = plist_body(bin, every, log, state, config_file);
        let uid = current_uid()?;
        let unchanged = std::fs::read_to_string(&plist)
            .map(|existing| existing == body)
            .unwrap_or(false);
        if unchanged && launchd_registered(&uid) {
            pond::output::line(&format!("already scheduled (every {})", every.label()))?;
            return Ok(());
        }
        if let Some(parent) = plist.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create {}", parent.display()))?;
        }
        std::fs::write(&plist, &body)
            .with_context(|| format!("failed to write {}", plist.display()))?;
        // bootout-then-bootstrap is the modern reload; bootout fails benignly
        // when nothing is registered yet, so its result is ignored.
        let _ = Command::new("launchctl")
            .args(["bootout", &format!("gui/{uid}/{LAUNCHD_LABEL}")])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
        let output = Command::new("launchctl")
            .args(["bootstrap", &format!("gui/{uid}")])
            .arg(&plist)
            .output()
            .context("failed to run launchctl bootstrap")?;
        if !output.status.success() {
            bail!(
                "launchctl bootstrap exited {}: {} - remove {} and retry, or load it manually with `launchctl bootstrap gui/{uid} {}`",
                output.status,
                String::from_utf8_lossy(&output.stderr).trim(),
                plist.display(),
                plist.display(),
            );
        }
        pond::output::line(&super::render_state(&super::State::Active {
            backend: "launchd",
            every: Some(every),
        }))?;
        pond::output::line(&format!(
            "{}      {}  (pond schedule logs)",
            pond::output::paint("logs", pond::output::dim()),
            crate::config::display(&crate::config::url_for_path(log)?),
        ))?;
        Ok(())
    }

    fn stop_launchd() -> Result<bool> {
        let plist = plist_path()?;
        let uid = current_uid()?;
        let was_registered = launchd_registered(&uid);
        let _ = Command::new("launchctl")
            .args(["bootout", &format!("gui/{uid}/{LAUNCHD_LABEL}")])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
        // Remove unconditionally: a missing plist means nothing to clean up,
        // not an error.
        let had_plist = match std::fs::remove_file(&plist) {
            Ok(()) => true,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,
            Err(error) => {
                return Err(error).with_context(|| format!("failed to remove {}", plist.display()));
            }
        };
        Ok(was_registered || had_plist)
    }

    fn probe_launchd() -> Result<State> {
        let uid = current_uid()?;
        if !launchd_registered(&uid) {
            return Ok(Inactive);
        }
        let every = std::fs::read_to_string(plist_path()?)
            .ok()
            .and_then(|body| plist_interval(&body));
        Ok(Active {
            backend: "launchd",
            every,
        })
    }

    /// Pull `<integer>N</integer>` following the StartInterval key out of a
    /// plist pond wrote. String surgery, not a plist parser: the input is
    /// pond's own template.
    fn plist_interval(body: &str) -> Option<ScheduleEvery> {
        let after = body.split("<key>StartInterval</key>").nth(1)?;
        let start = after.find("<integer>")? + "<integer>".len();
        let end = after.find("</integer>")?;
        let secs: u32 = after.get(start..end)?.trim().parse().ok()?;
        ScheduleEvery::from_secs(secs)
    }

    fn current_uid() -> Result<String> {
        let output = Command::new("id")
            .arg("-u")
            .output()
            .context("failed to run `id -u`")?;
        if !output.status.success() {
            bail!("`id -u` exited {}", output.status);
        }
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
    }

    // ----- systemd user timers (Linux) -------------------------------------

    fn systemd_user_available() -> bool {
        Command::new("systemctl")
            .args(["--user", "list-timers"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|status| status.success())
            .unwrap_or(false)
    }

    fn systemd_unit_dir() -> PathBuf {
        std::env::var_os("XDG_CONFIG_HOME")
            .map(PathBuf::from)
            .filter(|path| path.is_absolute())
            .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))
            .unwrap_or_else(|| PathBuf::from(".config"))
            .join("systemd/user")
    }

    fn systemd_service_body(bin: &Path, state: &Path, config_file: &Path) -> String {
        format!(
            "# created and maintained by pond; edits may be replaced\n\
             [Unit]\n\
             Description=pond sync\n\n\
             [Service]\n\
             Type=oneshot\n\
             Environment=\"XDG_STATE_HOME={}\"\n\
             Environment=\"POND_CONFIG_FILE={}\"\n\
             ExecStart={} sync -q --no-wait\n",
            state.display(),
            config_file.display(),
            bin.display(),
        )
    }

    fn systemd_timer_body(every: ScheduleEvery) -> String {
        format!(
            "# created and maintained by pond; edits may be replaced\n\
             [Unit]\n\
             Description=pond sync every {}\n\n\
             [Timer]\n\
             OnBootSec=2m\n\
             OnUnitActiveSec={}s\n\
             Persistent=true\n\n\
             [Install]\n\
             WantedBy=timers.target\n",
            every.label(),
            every.secs(),
        )
    }

    fn start_systemd(
        bin: &Path,
        every: ScheduleEvery,
        state: &Path,
        config_file: &Path,
    ) -> Result<()> {
        let dir = systemd_unit_dir();
        std::fs::create_dir_all(&dir)
            .with_context(|| format!("failed to create {}", dir.display()))?;
        let service_path = dir.join("pond-sync.service");
        let timer_path = dir.join("pond-sync.timer");
        let service = systemd_service_body(bin, state, config_file);
        let timer = systemd_timer_body(every);
        let unchanged = std::fs::read_to_string(&service_path)
            .map(|existing| existing == service)
            .unwrap_or(false)
            && std::fs::read_to_string(&timer_path)
                .map(|existing| existing == timer)
                .unwrap_or(false);
        if unchanged && systemd_timer_enabled() {
            pond::output::line(&format!("already scheduled (every {})", every.label()))?;
            return Ok(());
        }
        std::fs::write(&service_path, service)
            .with_context(|| format!("failed to write {}", service_path.display()))?;
        std::fs::write(&timer_path, timer)
            .with_context(|| format!("failed to write {}", timer_path.display()))?;
        for args in [
            vec!["--user", "daemon-reload"],
            vec!["--user", "enable", "--now", "pond-sync.timer"],
        ] {
            let output = Command::new("systemctl")
                .args(&args)
                .output()
                .context("failed to run systemctl")?;
            if !output.status.success() {
                bail!(
                    "systemctl {} exited {}: {}",
                    args.join(" "),
                    output.status,
                    String::from_utf8_lossy(&output.stderr).trim(),
                );
            }
        }
        pond::output::line(&super::render_state(&super::State::Active {
            backend: "systemd",
            every: Some(every),
        }))?;
        pond::output::line(&format!(
            "{}      journalctl --user -u pond-sync.service  (pond schedule logs)",
            pond::output::paint("logs", pond::output::dim()),
        ))?;
        Ok(())
    }

    fn stop_systemd() -> Result<bool> {
        let dir = systemd_unit_dir();
        let service_path = dir.join("pond-sync.service");
        let timer_path = dir.join("pond-sync.timer");
        let was_enabled = systemd_timer_enabled();
        if was_enabled {
            let _ = Command::new("systemctl")
                .args(["--user", "disable", "--now", "pond-sync.timer"])
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
        }
        // Remove unconditionally; a missing unit is not an error.
        let mut removed_units = false;
        for path in [&service_path, &timer_path] {
            match std::fs::remove_file(path) {
                Ok(()) => removed_units = true,
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                Err(error) => {
                    return Err(error)
                        .with_context(|| format!("failed to remove {}", path.display()));
                }
            }
        }
        if removed_units {
            let _ = Command::new("systemctl")
                .args(["--user", "daemon-reload"])
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
        }
        Ok(was_enabled || removed_units)
    }

    fn read_systemd_interval() -> Option<ScheduleEvery> {
        let body = std::fs::read_to_string(systemd_unit_dir().join("pond-sync.timer")).ok()?;
        let line = body
            .lines()
            .find_map(|line| line.trim().strip_prefix("OnUnitActiveSec="))?;
        let secs: u32 = line.trim().trim_end_matches('s').parse().ok()?;
        ScheduleEvery::from_secs(secs)
    }

    // ----- crontab fence (Linux without systemd) ---------------------------

    /// The cron line for one cadence. The minute is randomized once at
    /// registration so a fleet of pond installs doesn't synchronize load on
    /// a shared object store at :00.
    fn cron_entry(
        bin: &Path,
        every: ScheduleEvery,
        log: &Path,
        minute: u32,
        state: &Path,
        config_file: &Path,
    ) -> String {
        let command = format!(
            "XDG_STATE_HOME=\"{}\" POND_CONFIG_FILE=\"{}\" {} sync -q --no-wait >> {} 2>&1",
            state.display(),
            config_file.display(),
            bin.display(),
            log.display()
        );
        let schedule = match every {
            ScheduleEvery::M5 => format!("{}-59/5 * * * *", minute % 5),
            ScheduleEvery::M15 => {
                let m = minute % 15;
                format!("{m},{},{},{} * * * *", m + 15, m + 30, m + 45)
            }
            ScheduleEvery::H1 => format!("{} * * * *", minute % 60),
            ScheduleEvery::H6 => format!("{} */6 * * *", minute % 60),
            ScheduleEvery::D1 => format!("{} 3 * * *", minute % 60),
        };
        format!("{schedule} {command}")
    }

    /// Reverse-map a fence entry's schedule fields back onto a cadence for
    /// `status`. `None` for a hand-edited entry pond doesn't recognize.
    fn cron_entry_interval(entry: &str) -> Option<ScheduleEvery> {
        let fields: Vec<&str> = entry.split_whitespace().take(5).collect();
        if fields.len() < 5 {
            return None;
        }
        match (fields[0], fields[1]) {
            (minute, "*") if minute.contains('/') => Some(ScheduleEvery::M5),
            (minute, "*") if minute.contains(',') => Some(ScheduleEvery::M15),
            (_, "*") => Some(ScheduleEvery::H1),
            (minute, "*/6") if !minute.contains(',') && !minute.contains('/') => {
                Some(ScheduleEvery::H6)
            }
            (minute, _) if !minute.contains(',') && !minute.contains('/') => {
                Some(ScheduleEvery::D1)
            }
            _ => None,
        }
    }

    fn read_crontab() -> Result<String> {
        let output = Command::new("crontab")
            .arg("-l")
            .output()
            .context("failed to run `crontab -l`")?;
        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).into_owned())
        } else {
            // `crontab -l` exits nonzero when the user has no crontab yet.
            Ok(String::new())
        }
    }

    fn write_crontab(body: &str) -> Result<()> {
        use std::io::Write;
        let mut child = Command::new("crontab")
            .arg("-")
            .stdin(Stdio::piped())
            .spawn()
            .context("failed to run `crontab -`")?;
        child
            .stdin
            .take()
            .context("crontab stdin unavailable")?
            .write_all(body.as_bytes())
            .context("failed to write crontab")?;
        let status = child.wait().context("crontab did not exit")?;
        if !status.success() {
            bail!("`crontab -` exited {status}");
        }
        Ok(())
    }

    /// Drop the fenced pond block (and the fence markers) from a crontab.
    fn strip_cron_fence(text: &str) -> String {
        let mut out = String::with_capacity(text.len());
        let mut inside = false;
        for line in text.lines() {
            if line.trim() == CRON_FENCE_BEGIN {
                inside = true;
                continue;
            }
            if line.trim() == CRON_FENCE_END {
                inside = false;
                continue;
            }
            if !inside {
                out.push_str(line);
                out.push('\n');
            }
        }
        out
    }

    fn fence_block(entry: &str) -> String {
        format!("{CRON_FENCE_BEGIN}\n{entry}\n{CRON_FENCE_END}\n")
    }

    /// Pull pond's fenced cron entry out of a crontab body.
    fn fence_entry_in(text: &str) -> Option<String> {
        let after = text.split(CRON_FENCE_BEGIN).nth(1)?;
        let block = after.split(CRON_FENCE_END).next().unwrap_or_default();
        block
            .lines()
            .map(str::trim)
            .find(|line| !line.is_empty() && !line.starts_with('#'))
            .map(str::to_owned)
    }

    fn read_cron_fence_entry() -> Result<Option<String>> {
        Ok(fence_entry_in(&read_crontab()?))
    }

    fn start_cron(
        bin: &Path,
        every: ScheduleEvery,
        log: &Path,
        state: &Path,
        config_file: &Path,
    ) -> Result<()> {
        let existing = read_crontab()?;
        // The command-shape check keeps this a real idempotence test: a fence
        // entry written by an older pond (`sync -q` without `--no-wait`, or
        // without the pinned state dir or config file) must re-register, not be
        // kept as "already scheduled".
        if let Some(entry) = fence_entry_in(&existing)
            && cron_entry_interval(&entry) == Some(every)
            && entry.contains(&bin.display().to_string())
            && entry.contains("--no-wait")
            && entry.contains("XDG_STATE_HOME=")
            && entry.contains("POND_CONFIG_FILE=")
        {
            pond::output::line(&format!("already scheduled (every {})", every.label()))?;
            return Ok(());
        }
        let entry = cron_entry(bin, every, log, fastrand::u32(0..60), state, config_file);
        let mut body = strip_cron_fence(&existing);
        if !body.is_empty() && !body.ends_with('\n') {
            body.push('\n');
        }
        body.push_str(&fence_block(&entry));
        write_crontab(&body)?;
        pond::output::line(&super::render_state(&super::State::Active {
            backend: "cron",
            every: Some(every),
        }))?;
        pond::output::line(&format!(
            "{}      {}  (pond schedule logs)",
            pond::output::paint("logs", pond::output::dim()),
            crate::config::display(&crate::config::url_for_path(log)?),
        ))?;
        Ok(())
    }

    fn remove_cron_fence() -> Result<bool> {
        let existing = read_crontab()?;
        if !existing.contains(CRON_FENCE_BEGIN) {
            return Ok(false);
        }
        write_crontab(&strip_cron_fence(&existing))?;
        Ok(true)
    }

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

        const BIN: &str = "/usr/local/bin/pond";
        const LOG: &str = "/tmp/sync.log";
        const STATE: &str = "/home/user/.local/state";
        const CONFIG: &str = "/home/user/.config/pond/config.toml";

        #[test]
        fn cron_entries_reverse_map_to_their_cadence() {
            let bin = Path::new(BIN);
            let log = Path::new(LOG);
            let state = Path::new(STATE);
            let config_file = Path::new(CONFIG);
            for every in [
                ScheduleEvery::M5,
                ScheduleEvery::M15,
                ScheduleEvery::H1,
                ScheduleEvery::H6,
                ScheduleEvery::D1,
            ] {
                for minute in [0, 7, 59] {
                    let entry = cron_entry(bin, every, log, minute, state, config_file);
                    assert_eq!(cron_entry_interval(&entry), Some(every), "entry: {entry}");
                }
            }
        }

        /// A scheduled sync must read the config a manual one reads: without
        /// the pin, a shell-set POND_CONFIG_FILE (or XDG_CONFIG_HOME) makes the
        /// two diverge - different adapters, different [embeddings].enabled.
        #[test]
        fn every_template_pins_the_config_file() {
            let (bin, log, state, config_file) = (
                Path::new(BIN),
                Path::new(LOG),
                Path::new(STATE),
                Path::new(CONFIG),
            );
            let plist = plist_body(bin, ScheduleEvery::M5, log, state, config_file);
            assert!(
                plist.contains(&format!(
                    "<key>POND_CONFIG_FILE</key>\n\t\t<string>{CONFIG}</string>"
                )),
                "{plist}"
            );
            let service = systemd_service_body(bin, state, config_file);
            assert!(
                service.contains(&format!("Environment=\"POND_CONFIG_FILE={CONFIG}\"\n")),
                "{service}"
            );
            let entry = cron_entry(bin, ScheduleEvery::M5, log, 7, state, config_file);
            assert!(
                entry.contains(&format!("POND_CONFIG_FILE=\"{CONFIG}\"")),
                "{entry}"
            );
            // The pinned env has to precede the binary, or cron runs the sync
            // without it.
            assert!(entry.find("POND_CONFIG_FILE=") < entry.find(BIN), "{entry}");
        }
    }
}

// ===========================================================================
// Platform: windows (Task Scheduler)
// ===========================================================================

#[cfg(windows)]
mod windows {
    //! Windows Task Scheduler backend. The action is `pondw.exe` (see its own
    //! module doc), carrying the log path and the pinned state dir as arguments
    //! because an `Exec` action has neither an environment block nor a
    //! `StandardOutPath`. The task XML supplies the launchd/systemd-equivalent
    //! posture: battery-friendly, `StartWhenAvailable` for catch-up after
    //! downtime.

    use std::path::PathBuf;
    use std::process::Command;

    use anyhow::{Context, Result, bail};

    use super::{ScheduleEvery, State};
    use State::{Active, Inactive};

    const TASK_NAME: &str = "pond-sync";

    /// The registered task's XML, or `None` when no such task exists.
    fn query_xml() -> Result<Option<String>> {
        let output = Command::new("schtasks")
            .args(["/Query", "/TN", TASK_NAME, "/XML", "ONE"])
            .output()
            .context("failed to run schtasks /Query")?;
        Ok(output
            .status
            .success()
            .then(|| decode_console(&output.stdout)))
    }

    /// Probe existence + cadence in a single `schtasks /Query /XML ONE` call.
    pub(super) fn probe() -> Result<State> {
        let Some(xml) = query_xml()? else {
            return Ok(Inactive);
        };
        Ok(Active {
            backend: "task-scheduler",
            every: parse_interval_from_xml(&xml),
        })
    }

    /// Register (or replace, via `/F`) the Task Scheduler job. Shared by
    /// `pond schedule start` and the `pond init` schedule section.
    pub(super) fn start(every: ScheduleEvery, config_file: &std::path::Path) -> Result<()> {
        let bin = pond_bin();
        if !bin.is_file() {
            bail!(
                "could not resolve the pond binary to register ({}); run \
                 `pond schedule start` from an installed pond",
                bin.display()
            );
        }
        let launcher = pondw_bin(&bin)?;
        let log = super::log_path();
        // state_root is what we pin into --state-dir; pond_state_dir is the
        // directory where the log, lock, and last-sync record live.
        let state_root = crate::syncstate::state_root();
        let pond_state = crate::syncstate::pond_state_dir();
        std::fs::create_dir_all(&pond_state)
            .with_context(|| format!("failed to create {}", pond_state.display()))?;

        // Gate every path that lands in the XML: Task Scheduler expands %VAR%
        // inside <Command> and <Arguments> at runtime with NO escape syntax.
        // The shared gate's wider character set costs nothing here, and each
        // entry names its own source so the error points at the actual knob.
        for (what, path, sources) in [
            (
                "launcher",
                launcher.as_path(),
                "the installed pond binary's directory",
            ),
            ("pond binary", bin.as_path(), "the installed pond location"),
            (
                "sync log",
                log.as_path(),
                "the state dir (--state-dir or XDG_STATE_HOME)",
            ),
            (
                "state dir",
                state_root.as_path(),
                "--state-dir or XDG_STATE_HOME",
            ),
            ("config file", config_file, super::CONFIG_FILE_SOURCES),
        ] {
            super::reject_unembeddable(what, path, sources)?;
        }

        let arguments = task_arguments(&log, &bin, &state_root, config_file);

        // The pin is registration-time: a later shell-only override splits the
        // lock and last-sync record between the scheduled and manual syncs, and
        // the task will not follow it.
        if std::env::var_os("XDG_STATE_HOME").is_some() {
            pond::output::line(&format!(
                "note: XDG_STATE_HOME is set; the task is pinned to {} and will not follow later changes",
                state_root.display()
            ))?;
        }

        // Already-scheduled no-op: same action, same cadence. Compared on the
        // decoded element text, not the escaped form we wrote, because Task
        // Scheduler re-serializes the XML it stores and need not escape a quote
        // in element content. A mismatch only costs an idempotent re-register.
        let launcher_str = launcher.display().to_string();
        if let Some(xml) = query_xml()?
            && between(&xml, "<Command>", "</Command>")
                .map(xml_unescape)
                .as_deref()
                == Some(launcher_str.as_str())
            && between(&xml, "<Arguments>", "</Arguments>")
                .map(xml_unescape)
                .as_deref()
                == Some(arguments.as_str())
            && parse_interval_from_xml(&xml) == Some(every)
        {
            pond::output::line(&format!("already scheduled (every {})", every.label()))?;
            return Ok(());
        }

        // Write the XML task definition to a temp file; schtasks /Create /XML
        // requires a file path. Pass the PathBuf directly to avoid to_str()
        // panics on non-UTF-8 paths. The bytes MUST be UTF-16LE with a BOM:
        // schtasks reads a BOM-less file through the ANSI code page, so a
        // UTF-8 write would mojibake any non-ASCII state path (e.g. a
        // non-ASCII Windows username) into a task action pointing at a
        // nonexistent launcher - registration "succeeds" and every tick
        // silently does nothing. UTF-16LE+BOM matches the declaration in
        // `task_xml` and the encoding Task Scheduler's own XML export produces.
        let xml = task_xml(&launcher, &arguments, every);
        let tmp_xml = pond_state.join("pond-sync-task.xml.tmp");
        std::fs::write(&tmp_xml, utf16le_bom(&xml))
            .with_context(|| format!("failed to write {}", tmp_xml.display()))?;
        let create_result = Command::new("schtasks")
            .args(["/Create", "/TN", TASK_NAME, "/XML"])
            .arg(&tmp_xml)
            .arg("/F")
            .output()
            .context("failed to run schtasks /Create");
        let _ = std::fs::remove_file(&tmp_xml); // best-effort temp cleanup

        let output = create_result?;
        if !output.status.success() {
            bail!(
                "schtasks /Create failed: {}",
                decode_console(&output.stderr).trim()
            );
        }

        // The pre-pondw action chain, when this is an upgrade. Removed only
        // once the new task exists: a failed /Create must leave the old one
        // working.
        for stale in ["pond-sync.cmd", "pond-sync.vbs"] {
            let _ = std::fs::remove_file(pond_state.join(stale));
        }

        pond::output::line(&super::render_state(&super::State::Active {
            backend: "task-scheduler",
            every: Some(every),
        }))?;
        pond::output::line(&format!(
            "{}      {}  (pond schedule logs)",
            pond::output::paint("logs", pond::output::dim()),
            crate::config::display(&crate::config::url_for_path(log)?),
        ))?;
        Ok(())
    }

    pub(super) fn stop() -> Result<()> {
        let output = Command::new("schtasks")
            .args(["/Delete", "/TN", TASK_NAME, "/F"])
            .output()
            .context("failed to run schtasks /Delete")?;
        if output.status.success() {
            // Leave the log in place; it stays readable via
            // `pond schedule logs`.
            pond::output::line("schedule removed")?;
            return Ok(());
        }
        // Delete failed. Disambiguate TOCTOU: if the task is now gone (it
        // wasn't there, or was removed concurrently) report nothing-was-scheduled;
        // if it still exists the failure is genuine.
        match probe()? {
            Inactive => pond::output::line("nothing was scheduled")?,
            Active { .. } => {
                bail!(
                    "schtasks /Delete failed: {}",
                    decode_console(&output.stderr).trim()
                );
            }
        }
        Ok(())
    }

    /// Quote a path for the task's command line. Trailing backslashes are
    /// doubled: `CommandLineToArgvW` reads `\"` as an escaped quote, so
    /// `"C:\dir\"` would swallow the closing quote and run on to end of line -
    /// a state dir set to `C:\dir\` would otherwise register a task that fails
    /// or writes somewhere else on every tick.
    fn quote_arg(path: &std::path::Path) -> String {
        let text = path.display().to_string();
        let trailing = text.len() - text.trim_end_matches('\\').len();
        format!("\"{text}{}\"", "\\".repeat(trailing))
    }

    /// The `<Arguments>` line: the launcher's own `--log`, then the pond
    /// command line it runs.
    fn task_arguments(
        log: &std::path::Path,
        bin: &std::path::Path,
        state_root: &std::path::Path,
        config_file: &std::path::Path,
    ) -> String {
        format!(
            "--log {log} -- {bin} sync -q --no-wait --state-dir {state} --config-file {config}",
            log = quote_arg(log),
            bin = quote_arg(bin),
            state = quote_arg(state_root),
            config = quote_arg(config_file),
        )
    }

    /// Generate Task Scheduler XML for the pond-sync task.
    ///
    /// The `<Action>` runs `pondw.exe`, pond's windowless launcher: a
    /// console-subsystem binary in an interactive `Exec` action flashes a
    /// window on every tick, and a fire-and-forget shim would report its own
    /// exit code instead of the sync's.
    fn task_xml(launcher: &std::path::Path, arguments: &str, every: ScheduleEvery) -> String {
        let trigger = match every {
            ScheduleEvery::D1 => "    <CalendarTrigger>\n\
                 \x20\x20\x20\x20  <StartBoundary>2000-01-01T03:00:00</StartBoundary>\n\
                 \x20\x20\x20\x20  <Enabled>true</Enabled>\n\
                 \x20\x20\x20\x20  <ScheduleByDay>\
                 <DaysInterval>1</DaysInterval>\
                 </ScheduleByDay>\n\
                 \x20\x20\x20\x20</CalendarTrigger>"
                .to_owned(),
            _ => {
                let interval = match every {
                    ScheduleEvery::M5 => "PT5M",
                    ScheduleEvery::M15 => "PT15M",
                    ScheduleEvery::H1 => "PT1H",
                    ScheduleEvery::H6 => "PT6H",
                    ScheduleEvery::D1 => unreachable!(),
                };
                format!(
                    "    <TimeTrigger>\n\
                     \x20\x20\x20\x20  <Repetition>\n\
                     \x20\x20\x20\x20    <Interval>{interval}</Interval>\n\
                     \x20\x20\x20\x20    <StopAtDurationEnd>false</StopAtDurationEnd>\n\
                     \x20\x20\x20\x20  </Repetition>\n\
                     \x20\x20\x20\x20  <StartBoundary>2000-01-01T00:00:00</StartBoundary>\n\
                     \x20\x20\x20\x20  <Enabled>true</Enabled>\n\
                     \x20\x20\x20\x20</TimeTrigger>"
                )
            }
        };
        // Task Scheduler expands %VAR% in <Command> and <Arguments> at runtime;
        // the % gate in start() clears every embedded path before we get here.
        let launcher_str = xml_escape(&launcher.display().to_string());
        let arguments = xml_escape(arguments);
        format!(
            "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n\
             <Task version=\"1.2\" \
             xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n\
             \x20\x20<RegistrationInfo>\n\
             \x20\x20  <Description>pond sync (managed by pond; do not edit)</Description>\n\
             \x20\x20</RegistrationInfo>\n\
             \x20\x20<Triggers>\n\
             {trigger}\n\
             \x20\x20</Triggers>\n\
             \x20\x20<Settings>\n\
             \x20\x20  <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n\
             \x20\x20  <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n\
             \x20\x20  <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n\
             \x20\x20  <StartWhenAvailable>true</StartWhenAvailable>\n\
             \x20\x20  <Hidden>true</Hidden>\n\
             \x20\x20  <ExecutionTimeLimit>PT1H</ExecutionTimeLimit>\n\
             \x20\x20  <Priority>7</Priority>\n\
             \x20\x20</Settings>\n\
             \x20\x20<Actions Context=\"Author\">\n\
             \x20\x20  <Exec>\n\
             \x20\x20    <Command>{launcher_str}</Command>\n\
             \x20\x20    <Arguments>{arguments}</Arguments>\n\
             \x20\x20  </Exec>\n\
             \x20\x20</Actions>\n\
             </Task>\n"
        )
    }

    /// Escape XML special characters in element text / attribute values.
    fn xml_escape(s: &str) -> String {
        s.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
    }

    /// Inverse of `xml_escape`, for reading values back out of the XML Task
    /// Scheduler returns. `&amp;` unescapes last so `&amp;quot;` survives as a
    /// literal `&quot;` rather than collapsing into a quote.
    fn xml_unescape(s: &str) -> String {
        s.replace("&quot;", "\"")
            .replace("&gt;", ">")
            .replace("&lt;", "<")
            .replace("&amp;", "&")
    }

    /// Recover the registered cadence from a `schtasks /Query /XML ONE` body.
    fn parse_interval_from_xml(xml: &str) -> Option<ScheduleEvery> {
        // Repetition-based cadences carry <Interval>PT5M</Interval> etc.
        if let Some(interval) = between(xml, "<Interval>", "</Interval>") {
            let secs = if let Some(m) = interval
                .strip_prefix("PT")
                .and_then(|s| s.strip_suffix('M'))
            {
                m.parse::<u32>().ok().map(|m| m * 60)
            } else if let Some(h) = interval
                .strip_prefix("PT")
                .and_then(|s| s.strip_suffix('H'))
            {
                h.parse::<u32>().ok().map(|h| h * 3_600)
            } else {
                return None;
            }?;
            return ScheduleEvery::from_secs(secs);
        }
        // Daily tasks carry <DaysInterval>1</DaysInterval> instead.
        if between(xml, "<DaysInterval>", "</DaysInterval>").is_some() {
            return ScheduleEvery::from_secs(86_400);
        }
        None
    }

    /// Substring of `text` strictly between the first `open` and the `close`
    /// that follows it. Returns `None` when either delimiter is absent.
    fn between<'a>(text: &'a str, open: &str, close: &str) -> Option<&'a str> {
        let start = text.find(open)? + open.len();
        let rest = &text[start..];
        let end = rest.find(close)?;
        Some(&rest[..end])
    }

    /// The binary path baked into the task. Prefer `pond.exe` on PATH (a
    /// stable install location that survives upgrades); fall back to this exe.
    fn pond_bin() -> PathBuf {
        crate::find_on_path("pond.exe")
            .or_else(|| crate::find_on_path("pond"))
            .unwrap_or_else(|| std::env::current_exe().unwrap_or_else(|_| PathBuf::from("pond")))
    }

    /// The launcher shipped beside `pond.exe`. `bin` comes from PATH, which
    /// under winget is a symlink in its Links dir with no pondw.exe next to it,
    /// so the running binary's own directory is the fallback.
    fn pondw_bin(bin: &std::path::Path) -> Result<PathBuf> {
        [
            Some(bin.with_file_name("pondw.exe")),
            std::env::current_exe()
                .ok()
                .map(|exe| exe.with_file_name("pondw.exe")),
        ]
        .into_iter()
        .flatten()
        .find(|path| path.is_file())
        .context(
            "pondw.exe not found beside pond.exe: it ships in the release zip and runs \
             the scheduled sync without a console window - reinstall pond and re-run \
             `pond schedule start`",
        )
    }

    /// Decode process output that may be UTF-16 (schtasks `/XML` and some
    /// localized consoles) or UTF-8.
    fn decode_console(bytes: &[u8]) -> String {
        if bytes.len() >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE {
            return decode_utf16le(&bytes[2..]);
        }
        if bytes.iter().take(64).filter(|&&b| b == 0).count() >= 2 {
            return decode_utf16le(bytes);
        }
        String::from_utf8_lossy(bytes).into_owned()
    }

    fn decode_utf16le(bytes: &[u8]) -> String {
        let units: Vec<u16> = bytes
            .chunks_exact(2)
            .map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
            .collect();
        String::from_utf16_lossy(&units)
    }

    /// Encode `text` as UTF-16LE with a BOM - the shape `schtasks /Create
    /// /XML` decodes correctly on every system code page (a BOM-less file is
    /// read as ANSI, mojibaking non-ASCII paths).
    fn utf16le_bom(text: &str) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(2 + text.len() * 2);
        bytes.extend_from_slice(&[0xFF, 0xFE]);
        for unit in text.encode_utf16() {
            bytes.extend_from_slice(&unit.to_le_bytes());
        }
        bytes
    }

    #[cfg(test)]
    mod tests {
        #![allow(clippy::expect_used, clippy::unwrap_used)]
        use super::*;

        /// The action shape `start()` builds, for tests that need one.
        fn fixture() -> (std::path::PathBuf, String) {
            let launcher = std::path::PathBuf::from("C:\\Program Files\\pond\\pondw.exe");
            let arguments = task_arguments(
                std::path::Path::new("C:\\Users\\Adam\\AppData\\Local\\pond\\state\\sync.log"),
                std::path::Path::new("C:\\Program Files\\pond\\pond.exe"),
                std::path::Path::new("C:\\Users\\Adam\\AppData\\Local\\pond\\state"),
                std::path::Path::new("C:\\Users\\Adam\\AppData\\Roaming\\pond\\config.toml"),
            );
            (launcher, arguments)
        }

        #[test]
        fn all_cadences_round_trip_through_task_xml() {
            let (launcher, arguments) = fixture();
            for every in [
                ScheduleEvery::M5,
                ScheduleEvery::M15,
                ScheduleEvery::H1,
                ScheduleEvery::H6,
                ScheduleEvery::D1,
            ] {
                let xml = task_xml(&launcher, &arguments, every);
                let parsed = parse_interval_from_xml(&xml);
                assert_eq!(parsed, Some(every), "cadence {every:?} did not round-trip");
            }
        }

        #[test]
        fn between_finds_content_between_delimiters() {
            assert_eq!(between("<Foo>42</Foo>", "<Foo>", "</Foo>"), Some("42"));
            assert_eq!(between("<A>x</A><B>y</B>", "<B>", "</B>"), Some("y"));
            assert_eq!(between("no match", "<X>", "</X>"), None);
            assert_eq!(between("<Open>missing close", "<Open>", "</Open>"), None);
        }

        #[test]
        fn decode_console_handles_utf8_and_utf16le_bom() {
            assert_eq!(decode_console(b"hello world"), "hello world");
            let text = "hello";
            let mut bytes: Vec<u8> = vec![0xFF, 0xFE];
            for unit in text.encode_utf16() {
                bytes.extend_from_slice(&unit.to_le_bytes());
            }
            assert_eq!(decode_console(&bytes), "hello");
        }

        #[test]
        fn utf16le_bom_leads_with_bom_and_round_trips_non_ascii() {
            // The task XML file MUST carry a UTF-16LE BOM: schtasks reads a
            // BOM-less file as ANSI, mojibaking non-ASCII state paths.
            let text = "C:\\Users\\p\u{f6}nd \u{e9}tat\\pondw.exe";
            let bytes = utf16le_bom(text);
            assert_eq!(&bytes[..2], &[0xFF, 0xFE], "BOM must lead the file");
            assert_eq!(bytes.len(), 2 + text.encode_utf16().count() * 2);
            // decode_console is the module's own BOM-aware reader; the pair
            // must round-trip exactly.
            assert_eq!(decode_console(&bytes), text);
        }

        #[test]
        fn task_xml_execs_the_launcher_and_contains_expected_settings() {
            let (launcher, arguments) = fixture();
            let xml = task_xml(&launcher, &arguments, ScheduleEvery::M5);
            // The launcher IS the action: no wscript, no .cmd, no .vbs.
            assert!(xml.contains("<Command>C:\\Program Files\\pond\\pondw.exe</Command>"));
            assert!(!xml.contains("wscript"));
            // battery + catch-up settings
            assert!(xml.contains("<StartWhenAvailable>true</StartWhenAvailable>"));
            assert!(xml.contains("<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"));
            assert!(xml.contains("<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>"));
            assert!(xml.contains("<Hidden>true</Hidden>"));
        }

        #[test]
        fn a_trailing_separator_does_not_escape_the_closing_quote() {
            // `--state-dir "C:\dir\"` would swallow the quote and run on.
            let args = task_arguments(
                std::path::Path::new("C:\\s\\sync.log"),
                std::path::Path::new("C:\\bin\\pond.exe"),
                std::path::Path::new("C:\\my state\\"),
                std::path::Path::new("C:\\c\\config.toml"),
            );
            assert!(args.contains("--state-dir \"C:\\my state\\\\\""), "{args}");
            // Every quote still pairs off.
            assert_eq!(args.matches('"').count() % 2, 0, "{args}");
        }

        #[test]
        fn task_arguments_pin_the_state_dir_and_quote_spaced_paths() {
            let (_, arguments) = fixture();
            // The pin an Exec action's missing environment block forces.
            assert!(
                arguments.contains("--state-dir \"C:\\Users\\Adam\\AppData\\Local\\pond\\state\""),
                "{arguments}"
            );
            assert!(arguments.contains("sync -q --no-wait"), "{arguments}");
            assert!(
                arguments.contains(
                    "--config-file \"C:\\Users\\Adam\\AppData\\Roaming\\pond\\config.toml\""
                ),
                "{arguments}"
            );
            // Every path is quoted: `C:\Program Files\...` splits otherwise.
            assert!(
                arguments.contains("-- \"C:\\Program Files\\pond\\pond.exe\""),
                "{arguments}"
            );
            assert!(arguments.starts_with("--log \"C:\\"), "{arguments}");
        }

        #[test]
        fn action_survives_the_xml_escape_round_trip() {
            // start()'s already-scheduled no-op compares the DECODED element
            // text, because Task Scheduler re-serializes what it stores and
            // need not escape a quote in element content. Both directions of
            // that comparison have to agree with the escaper.
            let (launcher, arguments) = fixture();
            let xml = task_xml(&launcher, &arguments, ScheduleEvery::M5);
            assert_eq!(
                between(&xml, "<Arguments>", "</Arguments>").map(xml_unescape),
                Some(arguments)
            );
            assert_eq!(
                between(&xml, "<Command>", "</Command>").map(xml_unescape),
                Some(launcher.display().to_string())
            );
        }

        #[test]
        fn xml_unescape_leaves_an_escaped_entity_literal() {
            // &amp; unescapes last, so a literal "&quot;" in a path does not
            // collapse into a quote and desync the no-op comparison.
            assert_eq!(xml_unescape(&xml_escape("a&quot;b")), "a&quot;b");
            assert_eq!(xml_unescape(&xml_escape("a\"<b>&c")), "a\"<b>&c");
        }
    }
}

// ===========================================================================
// Tests shared across all platforms
// ===========================================================================

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used, clippy::unwrap_used)]
    use super::*;

    #[test]
    fn every_round_trips_through_secs_and_labels() {
        for every in [
            ScheduleEvery::M5,
            ScheduleEvery::M15,
            ScheduleEvery::H1,
            ScheduleEvery::H6,
            ScheduleEvery::D1,
        ] {
            assert_eq!(ScheduleEvery::from_secs(every.secs()), Some(every));
        }
        assert_eq!(ScheduleEvery::from_secs(123), None);
    }

    #[test]
    fn unembeddable_paths_are_rejected_before_registration() {
        for bad in [
            "/home/user/a\"b/config.toml",
            "/home/user/100%/config.toml",
            "/home/user/a<b>/config.toml",
            "/home/user/a&b/config.toml",
            "/home/user/a\nb/config.toml",
        ] {
            let error = reject_unembeddable("config file", Path::new(bad), "POND_CONFIG_FILE")
                .err()
                .map(|error| error.to_string())
                .unwrap_or_default();
            assert!(error.contains("config file"), "accepted {bad}");
            assert!(error.contains("POND_CONFIG_FILE"), "{error}");
        }
        assert!(
            reject_unembeddable(
                "config file",
                Path::new("/home/user/.config/pond/config.toml"),
                "POND_CONFIG_FILE"
            )
            .is_ok()
        );
    }

    /// The pinned path is re-read from the scheduler's working directory, so
    /// a relative `--config-file` must leave the registration absolute.
    #[test]
    fn config_pin_is_absolutized() {
        let pinned = config_file(Some(PathBuf::from("relative/config.toml")));
        assert!(pinned.is_absolute(), "{}", pinned.display());
    }
}