car-scheduler 0.34.0

Task scheduling and background execution for Common Agent Runtime
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
//! Durable OS-level scheduling — survive a daemon/app restart.
//!
//! The in-process [`Executor`](crate::Executor) drives tasks with tokio timers:
//! if the daemon is down when a task is due, the run is simply missed. This
//! module delegates the *trigger* to the operating system's own scheduler
//! (`launchd` on macOS, `crontab` on Linux, **Windows Task Scheduler** via
//! `schtasks` on Windows), which fires a command even when no CAR process is
//! running. That command — supplied by the caller (typically a `car`/`car-server`
//! invocation that runs the task once) — is what re-enters CAR.
//!
//! The rendering ([`render_launchd_plist`](OsScheduleSpec::render_launchd_plist),
//! [`render_crontab_line`](OsScheduleSpec::render_crontab_line),
//! [`render_schtasks_xml`](OsScheduleSpec::render_schtasks_xml)) is pure and
//! platform-independent, so it is unit-tested directly. The install layer
//! ([`install`](OsScheduleSpec::install) / [`uninstall`] / [`list_installed`])
//! is cfg-gated per OS and shells out.

use std::collections::BTreeSet;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use crate::task::{Task, TaskTrigger};

/// Prefix for every CAR-managed OS schedule label / crontab tag, so install,
/// uninstall, and list only ever touch entries CAR created.
pub const LABEL_PREFIX: &str = "ai.parslee.car.task.";

/// Errors from rendering or installing an OS schedule.
#[derive(Debug, thiserror::Error)]
pub enum OsScheduleError {
    /// The task's trigger can't map to a recurring OS schedule (Once / Manual /
    /// FileWatch have no cron/launchd analogue here).
    #[error("trigger {0:?} is not OS-schedulable (use Interval or Cron)")]
    NotSchedulable(TaskTrigger),
    /// The schedule is valid but not expressible on this backend (e.g. a
    /// sub-minute interval under cron).
    #[error("schedule not expressible: {0}")]
    UnsupportedSchedule(String),
    /// A command value (program/arg/working_dir/log_path) is empty or carries a
    /// control character that could break out of a crontab line.
    #[error("invalid command value: {0}")]
    InvalidValue(String),
    /// This OS has no supported backend.
    #[error("no OS scheduling backend for this platform")]
    UnsupportedPlatform,
    /// A `launchctl` / `crontab` invocation failed.
    #[error("{0} failed: {1}")]
    Command(String, String),
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

/// How the OS should fire the command.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum OsTrigger {
    /// Every N seconds (launchd `StartInterval`; cron only when N is a whole
    /// number of minutes that divides cleanly).
    Interval { seconds: u64 },
    /// A standard 5-field cron expression (`min hour dom month dow`).
    Cron { expr: String },
}

/// A fully-resolved OS schedule: the command to run and when.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OsScheduleSpec {
    /// Unique label (`ai.parslee.car.task.<id>`). The launchd `Label` and the
    /// crontab tag.
    pub label: String,
    /// Absolute path to the program the OS runs (e.g. the `car` binary).
    pub program: String,
    /// Arguments passed to `program` (e.g. `["task", "run", "<id>"]`).
    #[serde(default)]
    pub args: Vec<String>,
    /// Working directory for the run, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub working_dir: Option<String>,
    /// File to redirect stdout/stderr to, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub log_path: Option<String>,
    /// When to fire.
    pub trigger: OsTrigger,
}

impl OsScheduleSpec {
    /// Build a schedule that runs `program args...` on the cadence of `task`.
    /// The caller owns the command: `program` is the binary the OS launches and
    /// `args` is what re-enters CAR to run this task once.
    ///
    /// Note: the OS-schedule layer does not consult `task.enabled` — installing a
    /// schedule for a disabled task still registers it with the OS. Enable/disable
    /// is the in-process executor's concern; uninstall to stop OS firing.
    pub fn from_task(
        task: &Task,
        program: impl Into<String>,
        args: Vec<String>,
    ) -> Result<Self, OsScheduleError> {
        let trigger = match task.trigger {
            TaskTrigger::Interval => OsTrigger::Interval {
                seconds: crate::task::parse_interval(&task.schedule).round().max(1.0) as u64,
            },
            TaskTrigger::Cron => OsTrigger::Cron {
                expr: task.schedule.trim().to_string(),
            },
            // Spell the non-schedulable triggers out (rather than `_`) so a new
            // TaskTrigger variant forces a decision here instead of silently
            // becoming "not schedulable".
            t @ (TaskTrigger::Once | TaskTrigger::FileWatch | TaskTrigger::Manual) => {
                return Err(OsScheduleError::NotSchedulable(t))
            }
        };
        let program = program.into();
        validate_command_value("program", &program)?;
        for arg in &args {
            validate_command_value("arg", arg)?;
        }
        if let OsTrigger::Cron { expr } = &trigger {
            validate_cron(expr)?;
        }
        Ok(Self {
            label: format!("{LABEL_PREFIX}{}", task.id),
            program,
            args,
            working_dir: None,
            log_path: None,
            trigger,
        })
    }

    /// Validate every command value (program, args, working_dir, log_path) for
    /// emptiness and control characters. The render paths call this so that a
    /// spec constructed directly (bypassing [`from_task`](Self::from_task), or
    /// with `working_dir`/`log_path` set afterward) can't smuggle a newline into
    /// a crontab line — crontab parses line-by-line, so an embedded `\n` would
    /// inject a second, attacker-controlled entry.
    fn validate_values(&self) -> Result<(), OsScheduleError> {
        validate_command_value("program", &self.program)?;
        for arg in &self.args {
            validate_command_value("arg", arg)?;
        }
        if let Some(dir) = &self.working_dir {
            validate_command_value("working_dir", dir)?;
        }
        if let Some(log) = &self.log_path {
            validate_command_value("log_path", log)?;
        }
        Ok(())
    }

    /// Render a macOS `launchd` property list. `StartInterval` for an interval
    /// trigger; `StartCalendarInterval` for the cron subset launchd can express
    /// (plain integers and `*` per field — step/list/range expressions return
    /// [`OsScheduleError::UnsupportedSchedule`]).
    pub fn render_launchd_plist(&self) -> Result<String, OsScheduleError> {
        self.validate_values()?;
        let mut body = String::new();
        body.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        body.push_str("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n");
        body.push_str("<plist version=\"1.0\">\n<dict>\n");
        body.push_str("  <key>Label</key>\n");
        body.push_str(&format!("  <string>{}</string>\n", xml_escape(&self.label)));
        body.push_str("  <key>ProgramArguments</key>\n  <array>\n");
        body.push_str(&format!(
            "    <string>{}</string>\n",
            xml_escape(&self.program)
        ));
        for arg in &self.args {
            body.push_str(&format!("    <string>{}</string>\n", xml_escape(arg)));
        }
        body.push_str("  </array>\n");

        match &self.trigger {
            OsTrigger::Interval { seconds } => {
                body.push_str("  <key>StartInterval</key>\n");
                body.push_str(&format!("  <integer>{seconds}</integer>\n"));
            }
            OsTrigger::Cron { expr } => {
                body.push_str("  <key>StartCalendarInterval</key>\n");
                body.push_str(&render_calendar_interval(expr)?);
            }
        }

        if let Some(dir) = &self.working_dir {
            body.push_str("  <key>WorkingDirectory</key>\n");
            body.push_str(&format!("  <string>{}</string>\n", xml_escape(dir)));
        }
        if let Some(log) = &self.log_path {
            body.push_str("  <key>StandardOutPath</key>\n");
            body.push_str(&format!("  <string>{}</string>\n", xml_escape(log)));
            body.push_str("  <key>StandardErrorPath</key>\n");
            body.push_str(&format!("  <string>{}</string>\n", xml_escape(log)));
        }
        // Don't fire on load — only on the schedule. (For StartInterval, launchd
        // would otherwise run once immediately at load.)
        body.push_str("  <key>RunAtLoad</key>\n  <false/>\n");
        body.push_str("</dict>\n</plist>\n");
        Ok(body)
    }

    /// Render a single crontab line tagged with the label so install/uninstall
    /// can find it. An interval trigger maps to `*/M` (or hourly/daily) only
    /// when the period divides evenly; otherwise
    /// [`OsScheduleError::UnsupportedSchedule`].
    pub fn render_crontab_line(&self) -> Result<String, OsScheduleError> {
        self.validate_values()?;
        let schedule = match &self.trigger {
            OsTrigger::Cron { expr } => {
                validate_cron(expr)?;
                expr.clone()
            }
            OsTrigger::Interval { seconds } => interval_to_cron(*seconds)?,
        };
        let mut cmd = shell_quote(&self.program);
        for arg in &self.args {
            cmd.push(' ');
            cmd.push_str(&shell_quote(arg));
        }
        if let Some(dir) = &self.working_dir {
            cmd = format!("cd {} && {cmd}", shell_quote(dir));
        }
        if let Some(log) = &self.log_path {
            cmd = format!("{cmd} >> {} 2>&1", shell_quote(log));
        }
        // Trailing tag comment is how `uninstall`/`list` recognize our lines.
        Ok(format!("{schedule} {cmd} # {}", self.label))
    }

    /// Path of the launchd agent plist for this label.
    pub fn launchd_plist_path(&self) -> PathBuf {
        launch_agents_dir().join(format!("{}.plist", self.label))
    }

    /// Render a Windows Task Scheduler task-definition XML (`schtasks /Create
    /// /XML`). Pure and platform-independent, so it is unit-tested directly like
    /// the launchd/crontab renderers.
    ///
    /// Interval triggers map to a `TimeTrigger` with an indefinite `Repetition`
    /// (whole-minute cadence only — Task Scheduler's floor, same as cron). Cron
    /// triggers map to a `TimeTrigger` (hourly) or `CalendarTrigger`
    /// (daily/weekly/monthly) for the concrete-value subset Task Scheduler can
    /// express; anything richer (per-field lists/ranges/steps, both
    /// day-of-month AND day-of-week, month filters on a daily/weekly schedule)
    /// returns [`OsScheduleError::UnsupportedSchedule`] — install on
    /// cron/launchd, or use the in-daemon timer.
    ///
    /// `log_path` is not applied by this backend — Task Scheduler has no native
    /// stdout/stderr redirect, and the `from_task` install path never sets it.
    /// The program runs via a direct `Exec` action.
    pub fn render_schtasks_xml(&self) -> Result<String, OsScheduleError> {
        self.validate_values()?;
        let trigger = render_schtasks_trigger(&self.trigger)?;

        let mut args = String::new();
        for (i, a) in self.args.iter().enumerate() {
            if i > 0 {
                args.push(' ');
            }
            args.push_str(&windows_arg_quote(a));
        }

        let mut body = String::new();
        body.push_str("<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n");
        body.push_str("<Task version=\"1.2\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n");
        body.push_str("  <RegistrationInfo>\n");
        body.push_str(&format!(
            "    <Description>CAR task {}</Description>\n",
            xml_escape(&self.label)
        ));
        body.push_str("  </RegistrationInfo>\n");
        body.push_str("  <Triggers>\n");
        body.push_str(&trigger);
        body.push_str("  </Triggers>\n");
        body.push_str("  <Principals>\n    <Principal id=\"Author\">\n");
        body.push_str("      <LogonType>InteractiveToken</LogonType>\n");
        body.push_str("      <RunLevel>LeastPrivilege</RunLevel>\n");
        body.push_str("    </Principal>\n  </Principals>\n");
        body.push_str("  <Settings>\n");
        body.push_str("    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n");
        body.push_str("    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n");
        body.push_str("    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n");
        body.push_str("    <StartWhenAvailable>true</StartWhenAvailable>\n");
        body.push_str("    <Enabled>true</Enabled>\n");
        // PT0S = no execution time limit.
        body.push_str("    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\n");
        body.push_str("  </Settings>\n");
        body.push_str("  <Actions Context=\"Author\">\n    <Exec>\n");
        body.push_str(&format!(
            "      <Command>{}</Command>\n",
            xml_escape(&self.program)
        ));
        if !self.args.is_empty() {
            body.push_str(&format!(
                "      <Arguments>{}</Arguments>\n",
                xml_escape(&args)
            ));
        }
        if let Some(dir) = &self.working_dir {
            body.push_str(&format!(
                "      <WorkingDirectory>{}</WorkingDirectory>\n",
                xml_escape(dir)
            ));
        }
        body.push_str("    </Exec>\n  </Actions>\n</Task>\n");
        Ok(body)
    }
}

/// Validate a 5-field cron expression's shape (field count + characters). Does
/// not evaluate ranges — just rejects obviously malformed input early.
fn validate_cron(expr: &str) -> Result<(), OsScheduleError> {
    let fields: Vec<&str> = expr.split_whitespace().collect();
    if fields.len() != 5 {
        return Err(OsScheduleError::UnsupportedSchedule(format!(
            "expected a 5-field cron expression, got {} field(s): {expr:?}",
            fields.len()
        )));
    }
    for f in fields {
        if !f
            .chars()
            .all(|c| c.is_ascii_digit() || matches!(c, '*' | '/' | ',' | '-'))
        {
            return Err(OsScheduleError::UnsupportedSchedule(format!(
                "cron field {f:?} has unsupported characters"
            )));
        }
    }
    Ok(())
}

/// Expand one cron field into the explicit set of values it matches, or `None`
/// for `*` (unconstrained). Supports `*`, a plain integer, step `*/N` (and
/// `lo-hi/N`), comma lists `a,b,c`, and ranges `a-b`. Values outside `[min,max]`
/// are rejected. This is what lets launchd express `*/N`: launchd itself can't,
/// but it ORs an *array* of `StartCalendarInterval` dicts, so we expand the field
/// to its value set and emit one dict per value — semantically identical to cron.
fn expand_cron_field(field: &str, min: i64, max: i64) -> Result<Option<Vec<i64>>, OsScheduleError> {
    if field == "*" {
        return Ok(None);
    }
    let bad = |m: &str| OsScheduleError::UnsupportedSchedule(m.to_string());
    let mut out = std::collections::BTreeSet::new();
    for part in field.split(',') {
        let (base, step, has_step) = match part.split_once('/') {
            Some((b, s)) => {
                let n: i64 = s
                    .parse()
                    .map_err(|_| bad(&format!("bad step in cron field {part:?}")))?;
                if n <= 0 {
                    return Err(bad(&format!("cron step must be positive: {part:?}")));
                }
                (b, n, true)
            }
            None => (part, 1, false),
        };
        let (lo, hi) = if base == "*" {
            (min, max)
        } else if let Some((a, b)) = base.split_once('-') {
            (
                a.parse()
                    .map_err(|_| bad(&format!("bad range in cron field {part:?}")))?,
                b.parse()
                    .map_err(|_| bad(&format!("bad range in cron field {part:?}")))?,
            )
        } else {
            let v: i64 = base
                .parse()
                .map_err(|_| bad(&format!("bad value in cron field {part:?}")))?;
            // Vixie/cronie treat a bare `N/step` as `N-max/step` (e.g. `5/10` on
            // the minute field = 5,15,25,…), NOT the single value {N}. Match that
            // so a launchd render doesn't fire less often than the verbatim
            // crontab line for the same input.
            if has_step {
                (v, max)
            } else {
                (v, v)
            }
        };
        if lo < min || hi > max || lo > hi {
            return Err(bad(&format!(
                "cron field {part:?} out of range [{min},{max}]"
            )));
        }
        let mut v = lo;
        while v <= hi {
            out.insert(v);
            v += step;
        }
    }
    Ok(Some(out.into_iter().collect()))
}

/// Render the `StartCalendarInterval` value for the launchd plist. A cron with no
/// step/list expands to a single `<dict>`; a `*/N`-style cadence expands to an
/// `<array>` of dicts (which launchd ORs) — one per matching value combination.
/// This is the normalization that makes `*/30`-style schedules work on macOS
/// (#72): the same cron input renders here for launchd and passes through
/// verbatim for crontab.
fn render_calendar_interval(expr: &str) -> Result<String, OsScheduleError> {
    validate_cron(expr)?;
    let fields: Vec<&str> = expr.split_whitespace().collect();
    // POSIX cron ORs day-of-month and day-of-week when both are constrained
    // ("the 5th OR a Monday"); launchd ANDs every key in a StartCalendarInterval
    // dict ("the 5th AND a Monday"). Emitting both would silently change the
    // firing days, so refuse rather than mis-render — cron can still express it.
    if fields[2] != "*" && fields[4] != "*" {
        return Err(OsScheduleError::UnsupportedSchedule(
            "launchd can't express cron's OR of day-of-month and day-of-week; install on Linux/cron or split into two schedules".into(),
        ));
    }
    let keys = ["Minute", "Hour", "Day", "Month", "Weekday"];
    let ranges = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 6)];
    // Each constrained field → (key, its value set). `*` fields are omitted.
    let mut constrained: Vec<(&str, Vec<i64>)> = Vec::new();
    for ((field, key), (min, max)) in fields.iter().zip(keys).zip(ranges) {
        if let Some(vals) = expand_cron_field(field, min, max)? {
            constrained.push((key, vals));
        }
    }
    // An all-`*` cron ("* * * * *") means every minute → no calendar constraint.
    if constrained.is_empty() {
        return Err(OsScheduleError::UnsupportedSchedule(
            "an all-`*` cron has no calendar constraint; use Interval { seconds: 60 }".into(),
        ));
    }
    // Cartesian product of the constrained fields → one dict per combination.
    // Cap the fan-out so a pathological expr (e.g. `*/1 *`) can't emit thousands
    // of dicts — 366 covers "every minute of an hour × a few hours" comfortably.
    let total: usize = constrained.iter().map(|(_, v)| v.len()).product();
    if total > 366 {
        return Err(OsScheduleError::UnsupportedSchedule(format!(
            "schedule expands to {total} launchd calendar entries (>366); use Interval, or a coarser cadence"
        )));
    }
    let mut combos: Vec<Vec<(&str, i64)>> = vec![vec![]];
    for (key, vals) in &constrained {
        let mut next = Vec::with_capacity(combos.len() * vals.len());
        for combo in &combos {
            for v in vals {
                let mut c = combo.clone();
                c.push((key, *v));
                next.push(c);
            }
        }
        combos = next;
    }
    let render_dict = |combo: &[(&str, i64)]| {
        let mut d = String::from("  <dict>\n");
        for (key, v) in combo {
            d.push_str(&format!(
                "    <key>{key}</key>\n    <integer>{v}</integer>\n"
            ));
        }
        d.push_str("  </dict>\n");
        d
    };
    if combos.len() == 1 {
        Ok(render_dict(&combos[0]))
    } else {
        let mut arr = String::from("  <array>\n");
        for combo in &combos {
            arr.push_str(&render_dict(combo));
        }
        arr.push_str("  </array>\n");
        Ok(arr)
    }
}

/// Map an interval in seconds to a cron schedule, only when it divides evenly
/// enough to keep predictable spacing. Cron's floor is one minute.
fn interval_to_cron(seconds: u64) -> Result<String, OsScheduleError> {
    if seconds < 60 || !seconds.is_multiple_of(60) {
        return Err(OsScheduleError::UnsupportedSchedule(format!(
            "cron granularity is whole minutes; {seconds}s is not (use launchd StartInterval on macOS)"
        )));
    }
    let mins = seconds / 60;
    if mins < 60 {
        // `*/M` is only evenly spaced across the hour boundary when M divides 60.
        if 60 % mins == 0 {
            return Ok(format!("*/{mins} * * * *"));
        }
        return Err(OsScheduleError::UnsupportedSchedule(format!(
            "{mins}-minute interval doesn't divide 60 evenly (1,2,3,4,5,6,10,12,15,20,30 do); spacing would be irregular"
        )));
    }
    if mins == 60 {
        return Ok("0 * * * *".to_string());
    }
    if mins.is_multiple_of(60) {
        let hours = mins / 60;
        if hours < 24 && 24 % hours == 0 {
            return Ok(format!("0 */{hours} * * *"));
        }
        if hours == 24 {
            return Ok("0 0 * * *".to_string());
        }
        return Err(OsScheduleError::UnsupportedSchedule(format!(
            "{hours}-hour interval doesn't divide 24 evenly"
        )));
    }
    Err(OsScheduleError::UnsupportedSchedule(format!(
        "{seconds}s isn't expressible as an evenly-spaced cron schedule; use launchd StartInterval"
    )))
}

// ---------------------------------------------------------------------------
// Windows Task Scheduler rendering (pure — install/list/uninstall shell out to
// `schtasks` below, gated to Windows). See `render_schtasks_xml`.
// ---------------------------------------------------------------------------

/// Quote one argument for a Task Scheduler `<Arguments>` string: wrap in double
/// quotes when it contains whitespace or a quote, doubling any inner quote.
fn windows_arg_quote(arg: &str) -> String {
    if arg.chars().any(|c| c == ' ' || c == '\t' || c == '"') {
        format!("\"{}\"", arg.replace('"', "\"\""))
    } else {
        arg.to_string()
    }
}

/// Interval seconds → whole minutes. Task Scheduler's repetition floor is one
/// minute (same as cron); sub-minute stays on the in-daemon timer.
fn interval_to_minutes(seconds: u64) -> Result<u64, OsScheduleError> {
    if seconds < 60 || !seconds.is_multiple_of(60) {
        return Err(OsScheduleError::UnsupportedSchedule(format!(
            "Task Scheduler repetition granularity is whole minutes; {seconds}s is not (use the in-daemon timer for sub-minute)"
        )));
    }
    Ok(seconds / 60)
}

/// Render the `<Triggers>` body (a single `TimeTrigger`/`CalendarTrigger`).
fn render_schtasks_trigger(trigger: &OsTrigger) -> Result<String, OsScheduleError> {
    // Fixed base date — the day is irrelevant: interval/hourly repeat, and
    // calendar triggers select by DaysOfWeek/DaysOfMonth, not this boundary.
    const BASE_DATE: &str = "2000-01-01";
    match trigger {
        OsTrigger::Interval { seconds } => {
            let mins = interval_to_minutes(*seconds)?;
            let mut t = String::new();
            t.push_str("    <TimeTrigger>\n");
            t.push_str(&format!(
                "      <StartBoundary>{BASE_DATE}T00:00:00</StartBoundary>\n"
            ));
            t.push_str("      <Enabled>true</Enabled>\n");
            t.push_str("      <Repetition>\n");
            t.push_str(&format!("        <Interval>PT{mins}M</Interval>\n"));
            t.push_str("        <StopAtDurationEnd>false</StopAtDurationEnd>\n");
            t.push_str("      </Repetition>\n");
            t.push_str("    </TimeTrigger>\n");
            Ok(t)
        }
        OsTrigger::Cron { expr } => render_schtasks_cron(expr, BASE_DATE),
    }
}

/// Translate the concrete-value cron subset Task Scheduler can express into a
/// trigger. Each field must be `*` or a single value; multi-valued fields,
/// both day-of-month AND day-of-week, and month filters on daily/weekly
/// schedules are refused (rather than mis-rendered).
fn render_schtasks_cron(expr: &str, base_date: &str) -> Result<String, OsScheduleError> {
    validate_cron(expr)?;
    let f: Vec<&str> = expr.split_whitespace().collect();
    let single = |field: &str,
                  min: i64,
                  max: i64,
                  name: &str|
     -> Result<Option<i64>, OsScheduleError> {
        match expand_cron_field(field, min, max)? {
            None => Ok(None),
            Some(v) if v.len() == 1 => Ok(Some(v[0])),
            Some(_) => Err(OsScheduleError::UnsupportedSchedule(format!(
                "Task Scheduler can't express a multi-valued {name} field ({field:?}) in one trigger; use the in-daemon timer or split the schedule"
            ))),
        }
    };
    let minute = single(f[0], 0, 59, "minute")?;
    let hour = single(f[1], 0, 23, "hour")?;
    let dom = single(f[2], 1, 31, "day-of-month")?;
    let month = single(f[3], 1, 12, "month")?;
    let dow = single(f[4], 0, 6, "day-of-week")?;

    let minute = minute.ok_or_else(|| {
        OsScheduleError::UnsupportedSchedule(
            "a `*` minute means every minute; use Interval { seconds: 60 } instead".into(),
        )
    })?;

    if dom.is_some() && dow.is_some() {
        return Err(OsScheduleError::UnsupportedSchedule(
            "Task Scheduler can't express cron's OR of day-of-month and day-of-week; split into two schedules".into(),
        ));
    }

    let mut t = String::new();
    // `M * * * *` — every hour at minute M. A day/month constraint needs a
    // concrete hour, so refuse it here.
    let Some(hour) = hour else {
        if dom.is_some() || dow.is_some() || month.is_some() {
            return Err(OsScheduleError::UnsupportedSchedule(
                "a `*` hour with a day/month constraint isn't expressible here; pin the hour"
                    .into(),
            ));
        }
        t.push_str("    <TimeTrigger>\n");
        t.push_str(&format!(
            "      <StartBoundary>{base_date}T00:{minute:02}:00</StartBoundary>\n"
        ));
        t.push_str("      <Enabled>true</Enabled>\n");
        t.push_str("      <Repetition>\n");
        t.push_str("        <Interval>PT1H</Interval>\n");
        t.push_str("        <StopAtDurationEnd>false</StopAtDurationEnd>\n");
        t.push_str("      </Repetition>\n");
        t.push_str("    </TimeTrigger>\n");
        return Ok(t);
    };

    t.push_str("    <CalendarTrigger>\n");
    t.push_str(&format!(
        "      <StartBoundary>{base_date}T{hour:02}:{minute:02}:00</StartBoundary>\n"
    ));
    t.push_str("      <Enabled>true</Enabled>\n");
    if let Some(d) = dow {
        if month.is_some() {
            return Err(OsScheduleError::UnsupportedSchedule(
                "a month filter on a weekly (day-of-week) schedule isn't expressible here".into(),
            ));
        }
        t.push_str("      <ScheduleByWeek>\n        <DaysOfWeek>\n");
        t.push_str(&format!("          <{}/>\n", weekday_name(d)));
        t.push_str("        </DaysOfWeek>\n        <WeeksInterval>1</WeeksInterval>\n");
        t.push_str("      </ScheduleByWeek>\n");
    } else if let Some(d) = dom {
        t.push_str("      <ScheduleByMonth>\n        <DaysOfMonth>\n");
        t.push_str(&format!("          <Day>{d}</Day>\n"));
        t.push_str("        </DaysOfMonth>\n        <Months>\n");
        match month {
            Some(m) => t.push_str(&format!("          <{}/>\n", month_name(m))),
            None => {
                for m in 1..=12 {
                    t.push_str(&format!("          <{}/>\n", month_name(m)));
                }
            }
        }
        t.push_str("        </Months>\n      </ScheduleByMonth>\n");
    } else {
        if month.is_some() {
            return Err(OsScheduleError::UnsupportedSchedule(
                "a month filter on a daily schedule isn't expressible here; add a day-of-month"
                    .into(),
            ));
        }
        t.push_str("      <ScheduleByDay>\n        <DaysInterval>1</DaysInterval>\n      </ScheduleByDay>\n");
    }
    t.push_str("    </CalendarTrigger>\n");
    Ok(t)
}

fn weekday_name(dow: i64) -> &'static str {
    // cron 0 = Sunday .. 6 = Saturday; validated to 0..=6 upstream.
    match dow {
        0 => "Sunday",
        1 => "Monday",
        2 => "Tuesday",
        3 => "Wednesday",
        4 => "Thursday",
        5 => "Friday",
        _ => "Saturday",
    }
}

fn month_name(m: i64) -> &'static str {
    match m {
        1 => "January",
        2 => "February",
        3 => "March",
        4 => "April",
        5 => "May",
        6 => "June",
        7 => "July",
        8 => "August",
        9 => "September",
        10 => "October",
        11 => "November",
        _ => "December",
    }
}

/// Insert or remove a tagged line in an existing crontab body. Pure so the
/// crontab-editing logic is testable without touching the real crontab.
///
/// All lines bearing `# <label>` are first removed (idempotent replace); then,
/// unless `remove`, `line` is appended. Returns the new crontab text.
pub fn apply_crontab_edit(existing: &str, label: &str, line: Option<&str>) -> String {
    let tag = format!("# {label}");
    let mut out: Vec<String> = existing
        .lines()
        .filter(|l| !l.trim_end().ends_with(&tag))
        .map(|l| l.to_string())
        .collect();
    if let Some(line) = line {
        out.push(line.to_string());
    }
    let mut body = out.join("\n");
    if !body.is_empty() && !body.ends_with('\n') {
        body.push('\n');
    }
    body
}

/// Reject an empty command value or one carrying a control character. The
/// newline check is the load-bearing one: crontab parses line-by-line, so a
/// `\n` in any embedded value would split one logical entry into a second,
/// caller-controlled crontab line (command injection). `\r` and other control
/// chars are refused for the same class of reason and because they're never
/// legitimate in a program path or argument here.
pub(crate) fn validate_command_value(what: &str, value: &str) -> Result<(), OsScheduleError> {
    if value.is_empty() {
        return Err(OsScheduleError::InvalidValue(format!("{what} is empty")));
    }
    if let Some(c) = value.chars().find(|c| c.is_control()) {
        return Err(OsScheduleError::InvalidValue(format!(
            "{what} contains a control character (U+{:04X})",
            c as u32
        )));
    }
    Ok(())
}

/// Minimal XML text escaping for plist string values.
fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

/// Single-quote a token for a `/bin/sh` command line (cron runs via the shell).
fn shell_quote(s: &str) -> String {
    if !s.is_empty()
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '/' | '.' | '=' | ':'))
    {
        return s.to_string();
    }
    format!("'{}'", s.replace('\'', r"'\''"))
}

/// `~/Library/LaunchAgents` (macOS) — also the search dir for `list_installed`.
fn launch_agents_dir() -> PathBuf {
    home_dir().join("Library").join("LaunchAgents")
}

fn home_dir() -> PathBuf {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("/tmp"))
}

// ---------------------------------------------------------------------------
// Install layer (side-effecting, cfg-gated per OS).
// ---------------------------------------------------------------------------

/// Where an OS schedule landed after [`OsScheduleSpec::install`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstalledSchedule {
    pub label: String,
    /// `"launchd"` or `"cron"`.
    pub backend: String,
    /// The plist path (launchd) or the crontab line (cron).
    pub detail: String,
}

#[cfg(target_os = "macos")]
impl OsScheduleSpec {
    /// Write the plist to `~/Library/LaunchAgents` and load it with `launchctl`.
    /// Idempotent: an existing agent for this label is unloaded and replaced.
    pub fn install(&self) -> Result<InstalledSchedule, OsScheduleError> {
        let plist = self.render_launchd_plist()?;
        let dir = launch_agents_dir();
        std::fs::create_dir_all(&dir)?;
        let path = self.launchd_plist_path();
        // Replace any prior load before rewriting the file.
        let _ = run_cmd("launchctl", &["unload".into(), path_str(&path)]);
        std::fs::write(&path, plist)?;
        run_cmd("launchctl", &["load".into(), "-w".into(), path_str(&path)])?;
        Ok(InstalledSchedule {
            label: self.label.clone(),
            backend: "launchd".into(),
            detail: path.display().to_string(),
        })
    }
}

#[cfg(target_os = "macos")]
pub fn uninstall(label: &str) -> Result<bool, OsScheduleError> {
    let path = launch_agents_dir().join(format!("{label}.plist"));
    if !path.exists() {
        return Ok(false);
    }
    let _ = run_cmd("launchctl", &["unload".into(), path_str(&path)]);
    std::fs::remove_file(&path)?;
    Ok(true)
}

#[cfg(target_os = "macos")]
pub fn list_installed() -> Result<Vec<String>, OsScheduleError> {
    let dir = launch_agents_dir();
    let mut labels = Vec::new();
    if let Ok(entries) = std::fs::read_dir(&dir) {
        for entry in entries.flatten() {
            if let Some(stem) = entry.path().file_stem().and_then(|s| s.to_str()) {
                if stem.starts_with(LABEL_PREFIX) {
                    labels.push(stem.to_string());
                }
            }
        }
    }
    labels.sort();
    Ok(labels)
}

#[cfg(all(unix, not(target_os = "macos")))]
impl OsScheduleSpec {
    /// Replace any prior crontab line for this label and append the new one via
    /// `crontab -`. Idempotent.
    pub fn install(&self) -> Result<InstalledSchedule, OsScheduleError> {
        let line = self.render_crontab_line()?;
        let existing = current_crontab();
        let updated = apply_crontab_edit(&existing, &self.label, Some(&line));
        write_crontab(&updated)?;
        Ok(InstalledSchedule {
            label: self.label.clone(),
            backend: "cron".into(),
            detail: line,
        })
    }
}

#[cfg(all(unix, not(target_os = "macos")))]
pub fn uninstall(label: &str) -> Result<bool, OsScheduleError> {
    let existing = current_crontab();
    let tag = format!("# {label}");
    let had = existing.lines().any(|l| l.trim_end().ends_with(&tag));
    if had {
        let updated = apply_crontab_edit(&existing, label, None);
        write_crontab(&updated)?;
    }
    Ok(had)
}

#[cfg(all(unix, not(target_os = "macos")))]
pub fn list_installed() -> Result<Vec<String>, OsScheduleError> {
    let mut labels: Vec<String> = current_crontab()
        .lines()
        .filter_map(|l| l.rsplit_once("# ").map(|(_, tag)| tag.trim().to_string()))
        .filter(|tag| tag.starts_with(LABEL_PREFIX))
        .collect();
    labels.sort();
    labels.dedup();
    Ok(labels)
}

#[cfg(all(unix, not(target_os = "macos")))]
fn current_crontab() -> String {
    std::process::Command::new("crontab")
        .arg("-l")
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
        .unwrap_or_default()
}

#[cfg(all(unix, not(target_os = "macos")))]
fn write_crontab(body: &str) -> Result<(), OsScheduleError> {
    use std::io::Write;
    let mut child = std::process::Command::new("crontab")
        .arg("-")
        .stdin(std::process::Stdio::piped())
        .spawn()?;
    child
        .stdin
        .take()
        .ok_or_else(|| OsScheduleError::Command("crontab".into(), "no stdin".into()))?
        .write_all(body.as_bytes())?;
    let status = child.wait()?;
    if !status.success() {
        return Err(OsScheduleError::Command(
            "crontab".into(),
            format!("exited with {status}"),
        ));
    }
    Ok(())
}

// --- Windows: Task Scheduler backend via `schtasks` (car#510) ---------------

#[cfg(target_os = "windows")]
impl OsScheduleSpec {
    /// Register (or replace) this schedule with Windows Task Scheduler via
    /// `schtasks /Create /TN <label> /XML <file> /F`. `/F` makes it idempotent
    /// (overwrites an existing task of the same name).
    pub fn install(&self) -> Result<InstalledSchedule, OsScheduleError> {
        let xml = self.render_schtasks_xml()?;
        // schtasks reads a file; write it as UTF-16LE (the declared encoding) so
        // a non-ASCII program path/arg round-trips. Temp file, removed after.
        let path = std::env::temp_dir().join(format!("{}.xml", self.label));
        write_utf16le(&path, &xml)?;
        let res = run_schtasks(&[
            "/Create",
            "/TN",
            &self.label,
            "/XML",
            &path.to_string_lossy(),
            "/F",
        ]);
        let _ = std::fs::remove_file(&path);
        res?;
        Ok(InstalledSchedule {
            label: self.label.clone(),
            backend: "schtasks".into(),
            detail: xml,
        })
    }
}

#[cfg(target_os = "windows")]
pub fn uninstall(label: &str) -> Result<bool, OsScheduleError> {
    // `/Delete` errors if the task is absent — probe first so uninstall of a
    // non-existent schedule returns Ok(false), matching the other backends.
    if !schtasks_task_exists(label)? {
        return Ok(false);
    }
    run_schtasks(&["/Delete", "/TN", label, "/F"])?;
    Ok(true)
}

#[cfg(target_os = "windows")]
pub fn list_installed() -> Result<Vec<String>, OsScheduleError> {
    // CSV, no header: the first column is the (backslash-prefixed) task name.
    let out = std::process::Command::new("schtasks")
        .args(["/Query", "/FO", "CSV", "/NH"])
        .output()?;
    if !out.status.success() {
        return Err(OsScheduleError::Command(
            "schtasks".into(),
            String::from_utf8_lossy(&out.stderr).trim().to_string(),
        ));
    }
    let text = String::from_utf8_lossy(&out.stdout);
    let mut labels: Vec<String> = text
        .lines()
        .filter_map(|l| {
            let first = l.split(',').next()?.trim().trim_matches('"');
            let name = first.strip_prefix('\\').unwrap_or(first);
            name.starts_with(LABEL_PREFIX).then(|| name.to_string())
        })
        .collect();
    labels.sort();
    labels.dedup();
    Ok(labels)
}

#[cfg(target_os = "windows")]
fn schtasks_task_exists(label: &str) -> Result<bool, OsScheduleError> {
    let out = std::process::Command::new("schtasks")
        .args(["/Query", "/TN", label])
        .output()?;
    Ok(out.status.success())
}

#[cfg(target_os = "windows")]
fn run_schtasks(args: &[&str]) -> Result<(), OsScheduleError> {
    let out = std::process::Command::new("schtasks").args(args).output()?;
    if !out.status.success() {
        return Err(OsScheduleError::Command(
            "schtasks".into(),
            String::from_utf8_lossy(&out.stderr).trim().to_string(),
        ));
    }
    Ok(())
}

#[cfg(target_os = "windows")]
fn write_utf16le(path: &std::path::Path, s: &str) -> Result<(), OsScheduleError> {
    use std::io::Write;
    let mut bytes = Vec::with_capacity(s.len() * 2 + 2);
    bytes.extend_from_slice(&[0xFF, 0xFE]); // UTF-16LE BOM
    for u in s.encode_utf16() {
        bytes.extend_from_slice(&u.to_le_bytes());
    }
    std::fs::File::create(path)?.write_all(&bytes)?;
    Ok(())
}

// --- Platforms with no OS scheduling backend --------------------------------

#[cfg(not(any(
    target_os = "macos",
    all(unix, not(target_os = "macos")),
    target_os = "windows"
)))]
impl OsScheduleSpec {
    pub fn install(&self) -> Result<InstalledSchedule, OsScheduleError> {
        Err(OsScheduleError::UnsupportedPlatform)
    }
}

#[cfg(not(any(
    target_os = "macos",
    all(unix, not(target_os = "macos")),
    target_os = "windows"
)))]
pub fn uninstall(_label: &str) -> Result<bool, OsScheduleError> {
    Err(OsScheduleError::UnsupportedPlatform)
}

#[cfg(not(any(
    target_os = "macos",
    all(unix, not(target_os = "macos")),
    target_os = "windows"
)))]
pub fn list_installed() -> Result<Vec<String>, OsScheduleError> {
    Err(OsScheduleError::UnsupportedPlatform)
}

#[cfg(target_os = "macos")]
fn path_str(p: &std::path::Path) -> String {
    p.display().to_string()
}

#[cfg(target_os = "macos")]
fn run_cmd(bin: &str, args: &[String]) -> Result<(), OsScheduleError> {
    let output = std::process::Command::new(bin).args(args).output()?;
    if !output.status.success() {
        return Err(OsScheduleError::Command(
            bin.to_string(),
            String::from_utf8_lossy(&output.stderr).trim().to_string(),
        ));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Reconciliation — reap orphaned OS schedules whose backing task is gone or no
// longer OS-schedulable.
// ---------------------------------------------------------------------------

/// Outcome of a [`reconcile`] pass.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ReconcileReport {
    /// Labels uninstalled because no live OS-schedulable task backs them.
    pub removed: Vec<String>,
    /// Installed CAR labels left in place (still backed by a schedulable task).
    pub kept: usize,
    /// Per-label uninstall failures (`"<label>: <error>"`). Best-effort: one
    /// failure doesn't abort the pass.
    pub errors: Vec<String>,
}

/// The OS-schedule label for `task` if its trigger is still OS-schedulable
/// (`interval`/`cron`); `None` for `once`/`manual`/`file_watch`. The labels a
/// reconcile pass keeps are exactly these.
pub fn schedulable_label(task: &Task) -> Option<String> {
    matches!(task.trigger, TaskTrigger::Interval | TaskTrigger::Cron)
        .then(|| format!("{LABEL_PREFIX}{}", task.id))
}

/// The set of labels that should stay installed for `tasks`. Pure — the
/// testable core of reconciliation.
pub fn schedulable_labels(tasks: &[Task]) -> BTreeSet<String> {
    tasks.iter().filter_map(schedulable_label).collect()
}

/// Of the `installed` labels, the CAR-managed ones (our prefix) not in `keep`.
/// Foreign labels are never returned, so reconciliation can't touch a schedule
/// CAR didn't create. Pure.
pub fn labels_to_remove(installed: &[String], keep: &BTreeSet<String>) -> Vec<String> {
    installed
        .iter()
        .filter(|l| l.starts_with(LABEL_PREFIX) && !keep.contains(*l))
        .cloned()
        .collect()
}

/// Uninstall every CAR-managed OS schedule not in `keep`. Best-effort: a failed
/// uninstall is recorded in [`ReconcileReport::errors`] and the pass continues.
/// On a platform with no scheduling backend this is a no-op (empty report).
///
/// `keep` is the set of labels that *should* remain — typically
/// [`schedulable_labels`] over the live [`TaskStore`](crate::TaskStore). For the
/// keep set to be authoritative, a schedule must only be installed for a task
/// that also lives in the store; the FFI install path enforces that by
/// persisting the task on install, so a label with no stored task is normally a
/// genuine orphan (its task was deleted), not an unpersisted-but-valid one.
///
/// Caveat: this function trusts `keep` — it does not itself read the store, so
/// it can't tell a legitimately-empty keep set from one produced by a failed
/// store read. Callers must distinguish those *before* calling (the FFI
/// `reconcile_os_schedules` uses [`TaskStore::try_list`](crate::TaskStore::try_list)
/// and refuses to reap on a read error). A store that is readable-but-empty
/// while CAR schedules exist (e.g. a restore that recovered `~/Library/LaunchAgents`
/// but not `~/.car/tasks`) will still reap — an accepted residual of the
/// store-is-authoritative design.
pub fn reconcile(keep: &BTreeSet<String>) -> Result<ReconcileReport, OsScheduleError> {
    let installed = match list_installed() {
        Ok(v) => v,
        // No backend on this platform → nothing to reconcile.
        Err(OsScheduleError::UnsupportedPlatform) => return Ok(ReconcileReport::default()),
        Err(e) => return Err(e),
    };
    let mut report = ReconcileReport {
        kept: installed.iter().filter(|l| keep.contains(*l)).count(),
        ..Default::default()
    };
    for label in labels_to_remove(&installed, keep) {
        match uninstall(&label) {
            Ok(_) => report.removed.push(label),
            Err(e) => report.errors.push(format!("{label}: {e}")),
        }
    }
    Ok(report)
}

/// Reconcile installed OS schedules against a live task list — the boot/daemon
/// entry point. Removes schedules whose task was deleted or whose trigger is no
/// longer OS-schedulable.
pub fn reconcile_with_tasks(tasks: &[Task]) -> Result<ReconcileReport, OsScheduleError> {
    reconcile(&schedulable_labels(tasks))
}

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

    fn spec(trigger: OsTrigger) -> OsScheduleSpec {
        OsScheduleSpec {
            label: "ai.parslee.car.task.abc123".into(),
            program: "/usr/local/bin/car".into(),
            args: vec!["task".into(), "run".into(), "abc123".into()],
            working_dir: None,
            log_path: Some("/tmp/car/abc123.log".into()),
            trigger,
        }
    }

    #[test]
    fn from_task_rejects_non_recurring_triggers() {
        let t = Task::new("x", "p").with_trigger(TaskTrigger::Manual, "");
        assert!(matches!(
            OsScheduleSpec::from_task(&t, "car", vec![]),
            Err(OsScheduleError::NotSchedulable(TaskTrigger::Manual))
        ));
        let once = Task::new("x", "p"); // defaults to Manual; force Once
        let mut once = once;
        once.trigger = TaskTrigger::Once;
        assert!(OsScheduleSpec::from_task(&once, "car", vec![]).is_err());
    }

    #[test]
    fn from_task_maps_interval_and_cron() {
        let iv = Task::new("x", "p").with_trigger(TaskTrigger::Interval, "5m");
        let s = OsScheduleSpec::from_task(&iv, "car", vec!["run".into()]).unwrap();
        assert_eq!(s.trigger, OsTrigger::Interval { seconds: 300 });
        assert_eq!(s.label, format!("{LABEL_PREFIX}{}", iv.id));

        let cr = Task::new("x", "p").with_trigger(TaskTrigger::Cron, "0 9 * * 1");
        let s = OsScheduleSpec::from_task(&cr, "car", vec![]).unwrap();
        assert_eq!(
            s.trigger,
            OsTrigger::Cron {
                expr: "0 9 * * 1".into()
            }
        );
    }

    #[test]
    fn launchd_interval_uses_start_interval() {
        let plist = spec(OsTrigger::Interval { seconds: 300 })
            .render_launchd_plist()
            .unwrap();
        assert!(plist.contains("<key>StartInterval</key>"));
        assert!(plist.contains("<integer>300</integer>"));
        assert!(plist.contains("<string>ai.parslee.car.task.abc123</string>"));
        assert!(plist.contains("<string>/usr/local/bin/car</string>"));
        assert!(plist.contains("<key>StandardErrorPath</key>"));
        assert!(plist.contains("<key>RunAtLoad</key>\n  <false/>"));
    }

    #[test]
    fn launchd_cron_renders_calendar_interval() {
        let plist = spec(OsTrigger::Cron {
            expr: "30 9 * * *".into(),
        })
        .render_launchd_plist()
        .unwrap();
        assert!(plist.contains("<key>StartCalendarInterval</key>"));
        assert!(plist.contains("<key>Minute</key>\n    <integer>30</integer>"));
        assert!(plist.contains("<key>Hour</key>\n    <integer>9</integer>"));
        // `*` day/month/weekday are omitted.
        assert!(!plist.contains("<key>Day</key>"));
    }

    #[test]
    fn launchd_cron_expands_step_expressions_to_an_array() {
        // #72: `*/15` used to be rejected; it now expands to an array of 4
        // StartCalendarInterval dicts (minutes 0/15/30/45), which launchd ORs.
        let plist = spec(OsTrigger::Cron {
            expr: "*/15 * * * *".into(),
        })
        .render_launchd_plist()
        .unwrap();
        assert!(plist.contains("<key>StartCalendarInterval</key>"));
        assert!(
            plist.contains("<array>"),
            "step expr should render an array"
        );
        for m in ["0", "15", "30", "45"] {
            assert!(
                plist.contains(&format!("<integer>{m}</integer>")),
                "missing minute {m}"
            );
        }
        // Exactly 4 Minute entries, no Hour/Day constraint (all `*`).
        assert_eq!(plist.matches("<key>Minute</key>").count(), 4);
        assert!(!plist.contains("<key>Hour</key>"));
    }

    #[test]
    fn launchd_n_step_matches_vixie_not_single_value() {
        // Vixie/cronie: `5/10` on minutes = 5,15,25,35,45,55 (N-max/step), NOT {5}.
        // The launchd render must match so it doesn't fire less often than the
        // verbatim crontab line for the same input.
        let plist = spec(OsTrigger::Cron {
            expr: "5/10 * * * *".into(),
        })
        .render_launchd_plist()
        .unwrap();
        for m in ["5", "15", "25", "35", "45", "55"] {
            assert!(
                plist.contains(&format!("<integer>{m}</integer>")),
                "missing minute {m}"
            );
        }
        assert_eq!(plist.matches("<key>Minute</key>").count(), 6);
    }

    #[test]
    fn launchd_cron_single_value_stays_a_dict() {
        // A plain cron (no step/list) still renders as one dict, not an array.
        let plist = spec(OsTrigger::Cron {
            expr: "30 9 * * *".into(),
        })
        .render_launchd_plist()
        .unwrap();
        // The StartCalendarInterval value is a single dict (not an array). Note
        // the plist always has an <array> for ProgramArguments, so check the
        // calendar section specifically.
        assert!(plist.contains("<key>StartCalendarInterval</key>\n  <dict>"));
        assert!(plist.contains("<key>Minute</key>\n    <integer>30</integer>"));
        assert!(plist.contains("<key>Hour</key>\n    <integer>9</integer>"));
    }

    #[test]
    fn launchd_cron_rejects_all_star() {
        let err = spec(OsTrigger::Cron {
            expr: "* * * * *".into(),
        })
        .render_launchd_plist()
        .unwrap_err();
        assert!(matches!(err, OsScheduleError::UnsupportedSchedule(_)));
    }

    #[test]
    fn crontab_line_for_cron_is_verbatim_and_tagged() {
        let line = spec(OsTrigger::Cron {
            expr: "0 9 * * 1".into(),
        })
        .render_crontab_line()
        .unwrap();
        assert!(line.starts_with("0 9 * * 1 "));
        assert!(line.contains("/usr/local/bin/car task run abc123"));
        assert!(line.ends_with("# ai.parslee.car.task.abc123"));
        assert!(line.contains(">> /tmp/car/abc123.log 2>&1"));
    }

    #[test]
    fn interval_to_cron_divisors() {
        assert_eq!(interval_to_cron(300).unwrap(), "*/5 * * * *");
        assert_eq!(interval_to_cron(60).unwrap(), "*/1 * * * *");
        assert_eq!(interval_to_cron(1800).unwrap(), "*/30 * * * *");
        assert_eq!(interval_to_cron(3600).unwrap(), "0 * * * *");
        assert_eq!(interval_to_cron(7200).unwrap(), "0 */2 * * *");
        assert_eq!(interval_to_cron(86400).unwrap(), "0 0 * * *");
    }

    #[test]
    fn interval_to_cron_rejects_inexpressible() {
        assert!(interval_to_cron(30).is_err()); // sub-minute
        assert!(interval_to_cron(90).is_err()); // not whole minutes
        assert!(interval_to_cron(2520).is_err()); // 42 min, doesn't divide 60
        assert!(interval_to_cron(18000).is_err()); // 5h, doesn't divide 24
    }

    #[test]
    fn crontab_edit_replaces_idempotently() {
        let label = "ai.parslee.car.task.x";
        let base = "MAILTO=me\n0 0 * * * /bin/true # ai.parslee.car.task.x\n@reboot /bin/other\n";
        // Replace: the old tagged line is gone, the new one present, untagged kept.
        let line = "*/5 * * * * /usr/bin/car run x # ai.parslee.car.task.x";
        let out = apply_crontab_edit(base, label, Some(line));
        assert_eq!(out.matches("# ai.parslee.car.task.x").count(), 1);
        assert!(out.contains("*/5 * * * * /usr/bin/car run x"));
        assert!(out.contains("MAILTO=me"));
        assert!(out.contains("@reboot /bin/other"));

        // Remove: drops our line, leaves the rest.
        let removed = apply_crontab_edit(&out, label, None);
        assert!(!removed.contains("car run x"));
        assert!(removed.contains("@reboot /bin/other"));
    }

    #[test]
    fn shell_quote_escapes_specials() {
        assert_eq!(shell_quote("car"), "car");
        assert_eq!(shell_quote("/usr/bin/car"), "/usr/bin/car");
        assert_eq!(shell_quote("a b"), "'a b'");
        assert_eq!(shell_quote("it's"), r"'it'\''s'");
    }

    #[test]
    fn xml_escape_handles_entities() {
        assert_eq!(xml_escape("a & b < c"), "a &amp; b &lt; c");
    }

    #[test]
    fn schedulable_labels_only_includes_interval_and_cron() {
        let iv = Task::new("a", "p").with_trigger(TaskTrigger::Interval, "5m");
        let cr = Task::new("b", "p").with_trigger(TaskTrigger::Cron, "0 9 * * *");
        let manual = Task::new("c", "p"); // defaults to Manual
        let mut once = Task::new("d", "p");
        once.trigger = TaskTrigger::Once;

        let labels = schedulable_labels(&[iv.clone(), cr.clone(), manual, once]);
        assert_eq!(labels.len(), 2);
        assert!(labels.contains(&format!("{LABEL_PREFIX}{}", iv.id)));
        assert!(labels.contains(&format!("{LABEL_PREFIX}{}", cr.id)));
    }

    #[test]
    fn labels_to_remove_reaps_only_orphaned_car_labels() {
        let keep: BTreeSet<String> = [format!("{LABEL_PREFIX}live")].into_iter().collect();
        let installed = vec![
            format!("{LABEL_PREFIX}live"),          // backed by a task → kept
            format!("{LABEL_PREFIX}gone"),          // no task → reaped
            "com.example.someone-else".to_string(), // foreign → never touched
        ];
        let remove = labels_to_remove(&installed, &keep);
        assert_eq!(remove, vec![format!("{LABEL_PREFIX}gone")]);
    }

    #[test]
    fn labels_to_remove_empty_keep_reaps_all_car_labels_but_not_foreign() {
        let installed = vec![
            format!("{LABEL_PREFIX}x"),
            format!("{LABEL_PREFIX}y"),
            "other.tool.job".to_string(),
        ];
        let remove = labels_to_remove(&installed, &BTreeSet::new());
        assert_eq!(remove.len(), 2);
        assert!(!remove.iter().any(|l| l == "other.tool.job"));
    }

    #[test]
    fn crontab_rejects_newline_injection() {
        let mut s = spec(OsTrigger::Cron {
            expr: "0 9 * * *".into(),
        });
        s.args = vec!["x\n*/1 * * * * /bin/evil".into()];
        let err = s.render_crontab_line().unwrap_err();
        assert!(matches!(err, OsScheduleError::InvalidValue(_)));
        // The plist path rejects it too (defense in depth, even though XML is
        // structurally safe).
        assert!(matches!(
            s.render_launchd_plist().unwrap_err(),
            OsScheduleError::InvalidValue(_)
        ));
    }

    #[test]
    fn empty_program_rejected_at_construction() {
        let t = Task::new("x", "p").with_trigger(TaskTrigger::Interval, "5m");
        assert!(matches!(
            OsScheduleSpec::from_task(&t, "", vec![]),
            Err(OsScheduleError::InvalidValue(_))
        ));
    }

    #[test]
    fn launchd_rejects_dom_and_dow_both_constrained() {
        // cron "9am on the 5th OR a Monday" can't be ANDed by launchd.
        let err = spec(OsTrigger::Cron {
            expr: "0 9 5 * 1".into(),
        })
        .render_launchd_plist()
        .unwrap_err();
        assert!(matches!(err, OsScheduleError::UnsupportedSchedule(_)));
        // But cron renders it fine (OR semantics).
        assert!(spec(OsTrigger::Cron {
            expr: "0 9 5 * 1".into()
        })
        .render_crontab_line()
        .is_ok());
        // Only one of dom/dow constrained is still fine for launchd.
        assert!(spec(OsTrigger::Cron {
            expr: "0 9 5 * *".into()
        })
        .render_launchd_plist()
        .is_ok());
    }

    // --- Windows Task Scheduler XML (car#510) -------------------------------

    #[test]
    fn schtasks_interval_renders_repetition() {
        let xml = spec(OsTrigger::Interval { seconds: 300 })
            .render_schtasks_xml()
            .unwrap();
        assert!(xml.contains("<TimeTrigger>"), "{xml}");
        assert!(xml.contains("<Interval>PT5M</Interval>"), "{xml}");
        assert!(xml.contains("schemas.microsoft.com/windows/2004/02/mit/task"));
        assert!(xml.contains("<Command>"));
    }

    #[test]
    fn schtasks_interval_rejects_sub_minute() {
        let err = spec(OsTrigger::Interval { seconds: 30 })
            .render_schtasks_xml()
            .unwrap_err();
        assert!(matches!(err, OsScheduleError::UnsupportedSchedule(_)));
    }

    #[test]
    fn schtasks_daily_cron_renders_schedule_by_day() {
        let xml = spec(OsTrigger::Cron {
            expr: "30 9 * * *".into(),
        })
        .render_schtasks_xml()
        .unwrap();
        assert!(xml.contains("<CalendarTrigger>"), "{xml}");
        assert!(
            xml.contains("<StartBoundary>2000-01-01T09:30:00</StartBoundary>"),
            "{xml}"
        );
        assert!(xml.contains("<ScheduleByDay>"), "{xml}");
    }

    #[test]
    fn schtasks_weekly_cron_renders_day_of_week() {
        // Monday (cron dow=1) at 09:00.
        let xml = spec(OsTrigger::Cron {
            expr: "0 9 * * 1".into(),
        })
        .render_schtasks_xml()
        .unwrap();
        assert!(xml.contains("<ScheduleByWeek>"), "{xml}");
        assert!(xml.contains("<Monday/>"), "{xml}");
    }

    #[test]
    fn schtasks_monthly_cron_renders_day_of_month() {
        // 5th of every month at 09:00.
        let xml = spec(OsTrigger::Cron {
            expr: "0 9 5 * *".into(),
        })
        .render_schtasks_xml()
        .unwrap();
        assert!(xml.contains("<ScheduleByMonth>"), "{xml}");
        assert!(xml.contains("<Day>5</Day>"), "{xml}");
        assert!(
            xml.contains("<January/>") && xml.contains("<December/>"),
            "all months: {xml}"
        );
    }

    #[test]
    fn schtasks_hourly_cron_renders_time_trigger_with_hourly_repetition() {
        // Minute 5 of every hour.
        let xml = spec(OsTrigger::Cron {
            expr: "5 * * * *".into(),
        })
        .render_schtasks_xml()
        .unwrap();
        assert!(xml.contains("<TimeTrigger>"), "{xml}");
        assert!(
            xml.contains("<StartBoundary>2000-01-01T00:05:00</StartBoundary>"),
            "{xml}"
        );
        assert!(xml.contains("<Interval>PT1H</Interval>"), "{xml}");
    }

    #[test]
    fn schtasks_rejects_dom_and_dow_both_constrained() {
        let err = spec(OsTrigger::Cron {
            expr: "0 9 5 * 1".into(),
        })
        .render_schtasks_xml()
        .unwrap_err();
        assert!(matches!(err, OsScheduleError::UnsupportedSchedule(_)));
    }

    #[test]
    fn schtasks_rejects_multivalued_field() {
        // A minute list can't be one Task Scheduler trigger here.
        let err = spec(OsTrigger::Cron {
            expr: "0,30 9 * * *".into(),
        })
        .render_schtasks_xml()
        .unwrap_err();
        assert!(matches!(err, OsScheduleError::UnsupportedSchedule(_)));
    }

    #[test]
    fn schtasks_arguments_are_quoted_and_escaped() {
        let mut s = spec(OsTrigger::Interval { seconds: 60 });
        s.args = vec!["task".into(), "run".into(), "id with space".into()];
        let xml = s.render_schtasks_xml().unwrap();
        // Space-bearing arg is quoted; XML entities escaped in the joined string.
        assert!(xml.contains("&quot;id with space&quot;"), "{xml}");
    }

    /// Live round-trip against the real Task Scheduler service. `--ignored`
    /// because it registers (and removes) an actual, harmless task.
    #[cfg(target_os = "windows")]
    #[test]
    #[ignore = "registers a real Task Scheduler entry; run explicitly on Windows"]
    fn schtasks_install_list_uninstall_roundtrip() {
        let mut s = spec(OsTrigger::Interval { seconds: 3600 });
        // Unique label per process so repeat/parallel runs don't collide.
        s.label = format!("{LABEL_PREFIX}itest_{}", std::process::id());
        s.program = "cmd.exe".into();
        s.args = vec!["/C".into(), "rem".into()];
        s.working_dir = None;
        s.log_path = None;

        let installed = s.install().expect("install should succeed");
        assert_eq!(installed.backend, "schtasks");

        let listed = list_installed().expect("list should succeed");
        assert!(
            listed.iter().any(|l| l == &s.label),
            "installed label {} not in {listed:?}",
            s.label
        );

        assert!(uninstall(&s.label).expect("uninstall should succeed"));
        // Second uninstall is a no-op (task already gone).
        assert!(!uninstall(&s.label).expect("second uninstall should succeed"));
    }
}