eclipse-core 0.14.0

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
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
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
//! `eclipse cron`: prompts that run on a timer.
//!
//! Three files, all under one root: `<root>/cron/jobs.toml` says what should run and when,
//! `<root>/state/cron.json` remembers what did, and `<root>/cron/runs/<job>/<ms>.md` is what came
//! back. The jobs file is yours to edit — the tool and the CLI write the same format — and a
//! hand-edit is never lost: nothing here rewrites blocks it was not asked to touch.
//!
//! Time is the hard part. A schedule of "daily 07:30" means 07:30 where the person is, not
//! 07:30 UTC, and the project takes no date-time dependency, so local time comes from `libc`
//! (offset at an instant, and the civil calendar) with a pure-Rust civil-date conversion that is
//! also what the tests use. An interval schedule never consults a calendar at all.
//!
//! Nothing here runs an agent: [`due`] decides, and the caller runs. That keeps the decision
//! testable with a clock the test controls, and keeps the core free of a dependency cycle
//! (runtime depends on this, not the other way round).

use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// Where jobs live: `<root>/cron/jobs.toml`.
pub fn jobs_path(root: &Path) -> PathBuf {
    root.join("cron").join("jobs.toml")
}

/// Where a job's run history goes: `<root>/cron/runs/<name>/`.
/// Every job's run logs: `<root>/cron/runs`, before a job name is appended.
pub fn runs_root(root: &Path) -> PathBuf {
    root.join("cron").join("runs")
}

pub fn runs_dir(root: &Path, name: &str) -> PathBuf {
    root.join("cron").join("runs").join(name)
}

/// Where `<root>/state/cron.json` — the record of what ran — lives.
pub fn state_path(root: &Path) -> PathBuf {
    root.join("state").join("cron.json")
}

/// A named job: what to say, when to say it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Job {
    pub name: String,
    pub schedule: Schedule,
    pub prompt: String,
    pub enabled: bool,
    /// Run this route and no other. `None` follows the config's chain.
    pub route: Option<String>,
    /// This job's workspace: the file tools are confined to it, `shell` runs in it, and the
    /// `AGENT.md` walk begins there. `None` keeps whatever `[tools] workspace_root` says. The
    /// directory is checked at `add`; `~/` is expanded at both ends.
    pub workdir: Option<String>,
    /// Skills to load before the prompt runs.
    pub skills: Vec<String>,
    /// Write the reply here too (`/abs/path` or `~/path`). `None` writes only the run log.
    pub deliver: Option<String>,
    /// Demand a shape: a path to a JSON schema, or the schema itself. `None` falls back to
    /// `[agent] output_schema`. The schema rides in the request as `response_format`; a reply
    /// that is not a JSON document fails the job, which is what `run --schema` does too.
    pub schema: Option<String>,
}

/// When a job fires.
///
/// Deliberately small: four shapes a person can hold in their head, and no cron syntax to
/// mis-remember. `every 30m` is an interval; the rest name a moment in local time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Schedule {
    /// Every N seconds, counted from the last start.
    Every(u64),
    Daily {
        hour: u32,
        minute: u32,
    },
    /// `weekday` is 0 = Sunday, matching `localtime`'s `tm_wday`.
    Weekly {
        weekday: u32,
        hour: u32,
        minute: u32,
    },
}

/// A minute is the floor: anything finer is a busy loop wearing a schedule's clothes, and the
/// timer that drives these ticks wakes once a minute anyway.
pub const MIN_EVERY_SECS: u64 = 60;

const WEEKDAYS: [&str; 7] = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];

impl Schedule {
    /// What the file said, as someone would write it back.
    pub fn describe(&self) -> String {
        match self {
            Schedule::Every(secs) if *secs % 3600 == 0 => format!("every {}h", secs / 3600),
            Schedule::Every(secs) if *secs % 60 == 0 => format!("every {}m", secs / 60),
            Schedule::Every(secs) => format!("every {secs}s"),
            Schedule::Daily { hour, minute } => format!("daily {hour:02}:{minute:02}"),
            Schedule::Weekly {
                weekday,
                hour,
                minute,
            } => format!(
                "weekly {} {hour:02}:{minute:02}",
                WEEKDAYS[(*weekday as usize).min(6)]
            ),
        }
    }

    pub fn parse(text: &str) -> Result<Schedule> {
        let t = text.trim();
        let lower = t.to_ascii_lowercase();
        if lower == "hourly" {
            return Ok(Schedule::Every(3600));
        }
        if let Some(rest) = lower.strip_prefix("every ") {
            return parse_every(rest.trim(), text);
        }
        if let Some(rest) = lower.strip_prefix("daily ") {
            let (hour, minute) = parse_clock(rest.trim(), text)?;
            return Ok(Schedule::Daily { hour, minute });
        }
        if let Some(rest) = lower.strip_prefix("weekly ") {
            let mut parts = rest.split_whitespace();
            let day = parts.next().unwrap_or("");
            let clock = parts.next().unwrap_or("");
            if parts.next().is_some() {
                return Err(bad_schedule(text));
            }
            let weekday = WEEKDAYS
                .iter()
                .position(|d| *d == day)
                .ok_or_else(|| bad_schedule(text))? as u32;
            let (hour, minute) = parse_clock(clock, text)?;
            return Ok(Schedule::Weekly {
                weekday,
                hour,
                minute,
            });
        }
        Err(bad_schedule(text))
    }

    /// The first moment this schedule fires strictly after `after_ms`, in epoch milliseconds.
    ///
    /// For an interval this is arithmetic. For a named moment it is a search in local time,
    /// which is why it can take up to eight days: a weekly job whose moment passed a minute ago
    /// is due next week, not now.
    pub fn next_due(&self, after_ms: i64) -> i64 {
        match *self {
            // Saturating rather than wrapping: the parse above refuses an interval that cannot be
            // multiplied out, but a `next_due` that reported a negative moment would be worse than
            // one that reported the end of time (`#406`).
            Schedule::Every(secs) => after_ms.saturating_add((secs as i64).saturating_mul(1000)),
            Schedule::Daily { hour, minute } => next_matching(after_ms, None, hour, minute),
            Schedule::Weekly {
                weekday,
                hour,
                minute,
            } => next_matching(after_ms, Some(weekday), hour, minute),
        }
    }
}

fn bad_schedule(text: &str) -> Error {
    Error::Config(format!(
        "unrecognised schedule {text:?}. Write `every 30m`, `hourly`, `daily 07:30` or \
         `weekly mon 09:00`"
    ))
}

fn parse_every(rest: &str, original: &str) -> Result<Schedule> {
    let (number, unit) = match rest.char_indices().find(|(_, c)| !c.is_ascii_digit()) {
        Some((i, _)) => rest.split_at(i),
        None => (rest, ""),
    };
    let n: u64 = number.parse().map_err(|_| bad_schedule(original))?;
    // `#406`: unchecked multiplication, and a release build has no overflow checks —
    // `every 144115188075855873d` wrapped to exactly 86_400 seconds and passed as `every 1d`.
    // A debug build panicked instead. Both are the same bug seen from two builds.
    let per_second = match unit {
        "s" => 1u64,
        "m" => 60,
        "h" => 3_600,
        "d" => 86_400,
        _ => return Err(bad_schedule(original)),
    };
    let secs = n.checked_mul(per_second).ok_or_else(|| {
        Error::Config(format!(
            "`every {rest}` is longer than this machine can count; the longest interval is \
             `every {}d`",
            i64::MAX as u64 / 1000 / 86_400
        ))
    })?;
    // `next_due` multiplies seconds by 1000 in an `i64`; past this the schedule could not be
    // represented, and `cron list` is one of the callers.
    if secs > i64::MAX as u64 / 1000 {
        return Err(Error::Config(format!(
            "`every {rest}` is longer than this machine can count; the longest interval is \
             `every {}d`",
            i64::MAX as u64 / 1000 / 86_400
        )));
    }
    if secs < MIN_EVERY_SECS {
        return Err(Error::Config(format!(
            "`every {rest}` is finer than a minute, which is a busy loop rather than a schedule; \
             the shortest interval is `every 1m`"
        )));
    }
    Ok(Schedule::Every(secs))
}

fn parse_clock(text: &str, original: &str) -> Result<(u32, u32)> {
    let (h, m) = text.split_once(':').ok_or_else(|| bad_schedule(original))?;
    let hour: u32 = h.trim().parse().map_err(|_| bad_schedule(original))?;
    let minute: u32 = m.trim().parse().map_err(|_| bad_schedule(original))?;
    if hour > 23 || minute > 59 || h.trim().len() > 2 || m.trim().len() > 2 {
        return Err(Error::Config(format!(
            "{text:?} is not a time of day; write it as HH:MM in 24 hours, e.g. `07:30`"
        )));
    }
    Ok((hour, minute))
}

/// The next local wall-clock moment of `hour:minute`, on `weekday` when one is named.
///
/// Walks forward a day at a time in the civil calendar rather than adding 86_400_000ms, so that
/// a day with 23 or 25 hours in it (a DST boundary) lands on the same wall-clock time instead of
/// drifting an hour. Eight days covers "this weekday, an instant ago" plus a DST shift.
fn next_matching(after_ms: i64, weekday: Option<u32>, hour: u32, minute: u32) -> i64 {
    let (y, mo, d, ..) = local_parts(after_ms);
    for skip in 0..=8 {
        let (yy, mm, dd) = civil_add_days(y, mo, d, skip);
        let candidate = local_moment_ms(yy, mm, dd, hour, minute);
        if candidate <= after_ms {
            continue;
        }
        if let Some(want) = weekday {
            if weekday_of(candidate) != want {
                continue;
            }
        }
        return candidate;
    }
    // Unreachable in practice: eight consecutive days contain every weekday, and the candidate
    // for a day at least two ahead is always in the future.
    after_ms + 7 * 86_400_000
}

// ---------------------------------------------------------------------------------------------
// Local time
// ---------------------------------------------------------------------------------------------

/// Offset of local time from UTC at an instant, in seconds east. Zero without a C library.
#[cfg(unix)]
fn local_offset_secs(ms: i64) -> i64 {
    let secs = ms.div_euclid(1000) as libc::time_t;
    // SAFETY: `localtime_r` writes into the `tm` we hand it and reads nothing else; the pointer
    // is valid for the call.
    unsafe {
        let mut tm: libc::tm = std::mem::zeroed();
        if libc::localtime_r(&secs, &mut tm).is_null() {
            return 0;
        }
        tm.tm_gmtoff as i64
    }
}

#[cfg(not(unix))]
fn local_offset_secs(_ms: i64) -> i64 {
    0
}

/// `(year, month, day, hour, minute)` in local time.
pub fn local_parts(ms: i64) -> (i32, u32, u32, u32, u32) {
    let offset = local_offset_secs(ms);
    let local_secs = ms.div_euclid(1000) + offset;
    let days = local_secs.div_euclid(86_400);
    let rem = local_secs.rem_euclid(86_400);
    let (y, m, d) = civil_from_days(days);
    (y, m, d, (rem / 3600) as u32, ((rem % 3600) / 60) as u32)
}

/// Epoch milliseconds for a local wall-clock moment.
///
/// Two passes: guess the offset at the naive instant, then re-read the offset at the guessed
/// instant. They differ only across a DST change, and the second pass is what makes "07:30"
/// mean 07:30 on both sides of one.
fn local_moment_ms(y: i32, mo: u32, d: u32, hour: u32, minute: u32) -> i64 {
    let naive = days_from_civil(y, mo, d) * 86_400 + hour as i64 * 3600 + minute as i64 * 60;
    let first = naive - local_offset_secs(naive * 1000);
    let second = naive - local_offset_secs(first * 1000);
    second * 1000
}

/// Which day of the week a local instant falls on: 0 = Sunday.
pub fn weekday_of(ms: i64) -> u32 {
    let offset = local_offset_secs(ms);
    let days = (ms.div_euclid(1000) + offset).div_euclid(86_400);
    // 1970-01-01 was a Thursday.
    (days + 4).rem_euclid(7) as u32
}

/// Days since the Unix epoch for a proleptic Gregorian date (Howard Hinnant's algorithm, which
/// every date library ends up reimplementing).
fn days_from_civil(y: i32, m: u32, d: u32) -> i64 {
    let y = if m <= 2 { y - 1 } else { y } as i64;
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let mp = (m as i64 + 9) % 12;
    let doy = (153 * mp + 2) / 5 + d as i64 - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

/// The inverse of [`days_from_civil`]; `pub(crate)` because the install record writes its
/// timestamp in the same calendar rather than carrying a second copy of it.
pub(crate) fn civil_from_days(z: i64) -> (i32, u32, u32) {
    let z = z + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
    ((if m <= 2 { y + 1 } else { y }) as i32, m, d)
}

fn civil_add_days(y: i32, m: u32, d: u32, days: i64) -> (i32, u32, u32) {
    civil_from_days(days_from_civil(y, m, d) + days)
}

// ---------------------------------------------------------------------------------------------
// The jobs file
// ---------------------------------------------------------------------------------------------

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawFile {
    #[serde(default, rename = "job")]
    jobs: Vec<RawJob>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawJob {
    name: String,
    schedule: String,
    prompt: String,
    enabled: Option<bool>,
    route: Option<String>,
    workdir: Option<String>,
    #[serde(default)]
    skills: Vec<String>,
    deliver: Option<String>,
    schema: Option<String>,
}

/// Read `<root>/cron/jobs.toml`. A missing file is not an error: it is a machine with no jobs.
pub fn load(root: &Path) -> Result<Vec<Job>> {
    Ok(load_reporting(root)?.0)
}

/// Read `<root>/cron/jobs.toml` and say which blocks are unusable.
///
/// `#405`: one malformed block used to be an `Err` for the whole file, so a typo in a job nobody
/// was looking at stopped every other job, and a failed systemd unit was the only trace. The docs
/// invite hand-editing, so a bad block is skipped and named instead. The *file* still has to parse:
/// a TOML syntax error is the file's shape, not one job's, and the parse error already names a
/// line number.
pub fn load_reporting(root: &Path) -> Result<(Vec<Job>, Vec<String>)> {
    let path = jobs_path(root);
    let text = match std::fs::read_to_string(&path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((Vec::new(), Vec::new())),
        Err(e) => return Err(Error::io(&path, e)),
    };
    let raw: RawFile = toml::from_str(&text).map_err(|e| Error::Parse {
        path: path.clone(),
        message: e.to_string(),
    })?;
    let mut jobs: Vec<Job> = Vec::new();
    let mut problems: Vec<String> = Vec::new();
    for r in raw.jobs {
        // The name is what a reader needs to find the block again, and it is the one field that is
        // allowed to be missing — say `job 3` then, rather than a bare `""`.
        let label = if r.name.trim().is_empty() {
            format!("job #{}", jobs.len() + problems.len() + 1)
        } else {
            format!("job `{}`", r.name)
        };
        match build_job(r, &jobs) {
            Ok(job) => jobs.push(job),
            Err(e) => problems.push(format!("{label} was skipped: {e}")),
        }
    }
    Ok((jobs, problems))
}

/// One `[[job]]` block, or the reason it cannot be run. Split out so a bad block can be skipped
/// with its own message instead of failing the file (`#405`).
fn build_job(r: RawJob, jobs: &[Job]) -> Result<Job> {
    if r.name.trim().is_empty() {
        return Err(Error::Config("it has an empty name".into()));
    }
    validate_job_name(&r.name)?;
    if r.prompt.trim().is_empty() {
        return Err(Error::Config(format!(
            "`{}` has an empty prompt; a timer with nothing to say is not a job",
            r.name
        )));
    }
    if jobs.iter().any(|j: &Job| j.name == r.name) {
        return Err(Error::Config(format!(
            "another job is already named `{}`; the name is how a run is recorded and how you \
             refer to it",
            r.name
        )));
    }
    // The schedule error names the job it came from, because a list of twelve blocks and one
    // `unrecognised schedule "evry 5m"` is a search (`#405`).
    let schedule =
        Schedule::parse(&r.schedule).map_err(|e| Error::Config(format!("`{}`: {e}", r.name)))?;
    Ok(Job {
        name: r.name,
        schedule,
        prompt: r.prompt,
        enabled: r.enabled.unwrap_or(true),
        route: r.route,
        workdir: r.workdir,
        skills: r.skills,
        deliver: r.deliver,
        schema: r.schema,
    })
}

/// Names become directory names, so they are held to the same alphabet as profile names.
pub fn validate_job_name(name: &str) -> Result<()> {
    let ok = !name.is_empty()
        && name.len() <= 64
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if ok {
        Ok(())
    } else {
        Err(Error::Config(format!(
            "invalid job name {name:?}: letters, digits, `-` and `_`, because it names a \
             directory the runs are kept in"
        )))
    }
}

fn block_for(job: &Job) -> String {
    let mut s = String::from("[[job]]\n");
    s.push_str(&format!("name = {}\n", quote(&job.name)));
    s.push_str(&format!("schedule = {}\n", quote(&job.schedule.describe())));
    if !job.enabled {
        s.push_str("enabled = false\n");
    }
    if let Some(route) = &job.route {
        s.push_str(&format!("route = {}\n", quote(route)));
    }
    if let Some(workdir) = &job.workdir {
        s.push_str(&format!("workdir = {}\n", quote(workdir)));
    }
    if !job.skills.is_empty() {
        let list: Vec<String> = job.skills.iter().map(|s| quote(s)).collect();
        s.push_str(&format!("skills = [{}]\n", list.join(", ")));
    }
    if let Some(deliver) = &job.deliver {
        s.push_str(&format!("deliver = {}\n", quote(deliver)));
    }
    if let Some(schema) = &job.schema {
        s.push_str(&format!("schema = {}\n", quote(schema)));
    }
    s.push_str(&format!("prompt = {}\n", quote(&job.prompt)));
    s
}

/// A TOML basic string, escaped. Enough for names, paths and prompts; the file is meant to be
/// read by a person, so multi-line prompts still come out as one long line and are edited by
/// hand when they need to be.
fn quote(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '\r' => out.push_str("\\r"),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

/// Append a job to the file, creating it with a one-line explanation if it does not exist.
///
/// Appending never touches what is already there, so comments and hand-formatting survive a
/// job being added by the tool.
pub fn append_job(root: &Path, job: &Job) -> Result<()> {
    validate_job_name(&job.name)?;
    let existing = load(root)?;
    if existing.iter().any(|j| j.name == job.name) {
        return Err(Error::Config(format!(
            "a job named `{}` already exists; remove it first, or pick another name",
            job.name
        )));
    }
    let path = jobs_path(root);
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
    }
    let mut text = match std::fs::read_to_string(&path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(Error::io(&path, e)),
    };
    if text.trim().is_empty() {
        text.push_str("# Prompts that run on a timer. `eclipse cron list` reads this file,\n");
        text.push_str("# `eclipse cron run` is what the systemd timer invokes.\n");
    } else if !text.ends_with('\n') {
        text.push('\n');
    }
    text.push('\n');
    text.push_str(&block_for(job));
    // `#408`: `jobs.toml` is hand-edited, so a half-written one is somebody's work lost and a job
    // list that no longer parses. Write beside and rename.
    crate::atomic::write_file_atomically(&path, &text).map_err(|e| Error::io(&path, e))
}

/// Remove a job by name, leaving every other block exactly as it was.
pub fn remove_job(root: &Path, name: &str) -> Result<bool> {
    let path = jobs_path(root);
    let text = match std::fs::read_to_string(&path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(e) => return Err(Error::io(&path, e)),
    };
    let kept = drop_block(&text, name);
    match kept {
        None => Ok(false),
        Some(new_text) => {
            crate::atomic::write_file_atomically(&path, &new_text)
                .map_err(|e| Error::io(&path, e))?;
            Ok(true)
        }
    }
}

/// Replace a job's `[[job]]` block in place, leaving every other byte of the file alone.
///
/// This is what `pause` and `resume` need: rewriting the whole file from the parsed jobs would
/// be correct and would also delete the comments and formatting a person put next to their
/// other jobs.
pub fn replace_job(root: &Path, job: &Job) -> Result<()> {
    let path = jobs_path(root);
    let text = std::fs::read_to_string(&path).map_err(|e| Error::io(&path, e))?;
    let updated = with_block_replaced(&text, job)
        .ok_or_else(|| Error::Config(format!("no job named `{}`", job.name)))?;
    crate::atomic::write_file_atomically(&path, &updated).map_err(|e| Error::io(&path, e))
}

fn with_block_replaced(text: &str, job: &Job) -> Option<String> {
    let lines: Vec<&str> = text.lines().collect();
    let mut out: Vec<String> = Vec::new();
    let mut found = false;
    let mut i = 0;
    while i < lines.len() {
        if lines[i].trim() == "[[job]]" {
            let mut end = i + 1;
            while end < lines.len() && lines[end].trim() != "[[job]]" {
                end += 1;
            }
            let block = &lines[i..end];
            let is_ours = block.iter().any(|l| {
                l.trim_start()
                    .strip_prefix("name")
                    .map(|rest| rest.trim_start().starts_with('='))
                    .unwrap_or(false)
                    && l.contains(&quote(&job.name))
            });
            if is_ours && !found {
                found = true;
                for line in block_for(job).lines() {
                    out.push(line.to_string());
                }
            } else {
                out.extend(block.iter().map(|l| l.to_string()));
            }
            i = end;
            continue;
        }
        out.push(lines[i].to_string());
        i += 1;
    }
    if !found {
        return None;
    }
    let mut s = out.join("\n");
    if text.ends_with('\n') {
        s.push('\n');
    }
    Some(s)
}

/// The file with `name`'s `[[job]]` block cut out, or `None` when it holds no such block.
///
/// Blocks are found by the `[[job]]` line that opens them and the `name = "…"` line inside, so a
/// comment above a block stays with the block that follows it rather than orphaning onto the
/// next one.
fn drop_block(text: &str, name: &str) -> Option<String> {
    let lines: Vec<&str> = text.lines().collect();
    let mut out: Vec<&str> = Vec::new();
    let mut found = false;
    let mut i = 0;
    while i < lines.len() {
        if lines[i].trim() == "[[job]]" {
            let mut end = i + 1;
            while end < lines.len() && lines[end].trim() != "[[job]]" {
                end += 1;
            }
            let block = &lines[i..end];
            let is_ours = block.iter().any(|l| {
                l.trim_start()
                    .strip_prefix("name")
                    .map(|rest| rest.trim_start().starts_with('='))
                    .unwrap_or(false)
                    && l.contains(&quote(name))
            });
            if is_ours {
                found = true;
                // Swallow the blank line that separated it from the block below, if any.
                let mut stop = end;
                while stop < lines.len() && lines[stop].trim().is_empty() {
                    stop += 1;
                }
                i = stop;
                continue;
            }
            out.extend_from_slice(block);
            i = end;
            continue;
        }
        out.push(lines[i]);
        i += 1;
    }
    if !found {
        return None;
    }
    let mut s = out.join("\n");
    if text.ends_with('\n') {
        s.push('\n');
    }
    Some(s)
}

// ---------------------------------------------------------------------------------------------
// What ran
// ---------------------------------------------------------------------------------------------

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct JobState {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_started_ms: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_finished_ms: Option<i64>,
    /// `ok`, or the first line of what went wrong.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_outcome: Option<String>,
    #[serde(default)]
    pub runs: u64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct State {
    #[serde(default)]
    pub jobs: BTreeMap<String, JobState>,
}

impl State {
    pub fn get(&self, name: &str) -> JobState {
        self.jobs.get(name).cloned().unwrap_or_default()
    }
}

pub fn load_state(root: &Path) -> Result<State> {
    let path = state_path(root);
    let text = match std::fs::read_to_string(&path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(State::default()),
        Err(e) => return Err(Error::io(&path, e)),
    };
    if text.trim().is_empty() {
        return Ok(State::default());
    }
    serde_json::from_str(&text).map_err(|e| Error::Parse {
        path,
        message: e.to_string(),
    })
}

pub fn save_state(root: &Path, state: &State) -> Result<()> {
    let path = state_path(root);
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
    }
    let text = serde_json::to_string_pretty(state)
        .map_err(|e| Error::Config(format!("cannot encode cron state: {e}")))?;
    // Write beside and rename: a tick that dies mid-write must not leave the record half a
    // record, because the next tick reads it to decide what is due. The scratch name used to be a
    // fixed `state.json.tmp`, which two ticks share (`#408`).
    crate::atomic::write_file_atomically(&path, &text).map_err(|e| Error::io(&path, e))
}

/// The jobs that should run now.
///
/// A job that has never run is due immediately when its schedule is an interval — the timer was
/// just installed, and waiting half an hour to prove it works is not useful — and at its next
/// named moment otherwise, so that installing a timer at noon does not execute a 07:30 briefing
/// on the spot.
///
/// That second case needs an anchor, and asking every caller to remember [`seed_first_seen`] is how
/// a `daily` job came to never fire at all (`#561`). So the first sighting is seeded here: a job
/// this tick has no history for is anchored at this tick, `due` still answers "not yet", and the
/// next tick has something to measure from. The state is `&mut` for that reason alone.
pub fn due<'a>(jobs: &'a [Job], state: &mut State, now_ms: i64) -> Vec<&'a Job> {
    seed_first_seen(jobs, state, now_ms);
    jobs.iter()
        .filter(|j| j.enabled)
        .filter(|j| {
            let entry = state.jobs.get(&j.name);
            let last = entry.and_then(|e| e.last_started_ms);
            match (last, j.schedule) {
                (None, Schedule::Every(_)) => true,
                (None, _) => false,
                (Some(last), schedule) => now_ms >= schedule.next_due(last),
            }
        })
        .collect()
}

/// Give every job a state entry the first time a tick sees it (`#561`).
///
/// A calendar schedule is due *relative to its last fire*, and a job added a minute ago has none —
/// so `due` answered "never" for `daily`, `weekly` and cron jobs, `cron add` and the dashboard's
/// form both produced a job that could not run, and `next_due_for` kept promising a next time that
/// rolled forward on every tick. The first sighting is the seed: an unrun calendar job is anchored
/// at the moment it was first seen, so its next named moment is its first fire and a 07:30 briefing
/// installed at noon runs tomorrow morning rather than never.
///
/// An interval job is left with no anchor on purpose: `due` fires it at once, which is the rule for
/// a schedule that only needs "now" to be meaningful.
///
/// Returns the names it seeded — the tick has to *save* the state for this to hold, and saying so
/// is also how the caller knows whether there is anything to write at all.
pub fn seed_first_seen(jobs: &[Job], state: &mut State, now_ms: i64) -> Vec<String> {
    let mut seeded = Vec::new();
    for job in jobs.iter().filter(|j| j.enabled) {
        if state.jobs.contains_key(&job.name) {
            continue;
        }
        let mut entry = JobState::default();
        if !matches!(job.schedule, Schedule::Every(_)) {
            entry.last_started_ms = Some(now_ms);
        }
        state.jobs.insert(job.name.clone(), entry);
        seeded.push(job.name.clone());
    }
    seeded
}

/// When a job fires next, given what has run. `None` for a disabled job.
pub fn next_due_for(job: &Job, state: &State, now_ms: i64) -> Option<i64> {
    if !job.enabled {
        return None;
    }
    match state.jobs.get(&job.name).and_then(|e| e.last_started_ms) {
        None => match job.schedule {
            Schedule::Every(_) => Some(now_ms),
            schedule => Some(schedule.next_due(now_ms)),
        },
        Some(last) => {
            let mut next = job.schedule.next_due(last);
            // A tick that was missed while the machine was off is due at the next tick, not a
            // burst of catch-up runs: one prompt per job per tick.
            if next < now_ms && matches!(job.schedule, Schedule::Every(_)) {
                next = now_ms;
            }
            Some(next)
        }
    }
}

// ---------------------------------------------------------------------------------------------
// The tick lock
// ---------------------------------------------------------------------------------------------

/// How long a lock may be ignored before it is taken as abandoned.
///
/// A run that hangs cannot be waited on forever by a timer that fires every minute; after this
/// the next tick takes the lock and says so in its output. Long enough that a slow model call
/// is not cut off, short enough that a wedged tick does not stop the schedule for a day.
pub const STALE_LOCK_MS: u64 = 30 * 60 * 1000;

/// Held for the duration of one tick, so two timers (a systemd one and a hand-run one) cannot
/// run the same job twice.
pub struct Lock {
    path: PathBuf,
    /// True when this tick took over an abandoned lock, so it can say so.
    pub took_over_stale: bool,
    /// What this holder last wrote. The file's mtime is the staleness signal and its content is
    /// "this holder is still here", so a `Drop` that removes the file has to know whether the file
    /// is still the one it wrote (`#407`).
    stamp: String,
}

impl Lock {
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Say this tick is still working, between jobs.
    ///
    /// `#407`: staleness is judged from the file's mtime, which was set once and never refreshed,
    /// so a tick that legitimately ran past `STALE_LOCK_MS` was taken for an abandoned one — the
    /// next minute's tick took the lock and ran the jobs this one had not reached yet, in both.
    /// Returns false when the file is no longer ours, which means another tick has taken over and
    /// this one must stop rather than fight over jobs.
    pub fn touch(&mut self, now_ms: i64) -> bool {
        if std::fs::read_to_string(&self.path).ok().as_deref() != Some(self.stamp.as_str()) {
            return false;
        }
        let next = format!("{now_ms}\n");
        if std::fs::write(&self.path, &next).is_err() {
            return false;
        }
        self.stamp = next;
        true
    }
}

impl Drop for Lock {
    fn drop(&mut self) {
        // Only the lock this tick still holds. A tick whose lock was taken over used to delete the
        // new holder's file on the way out, which let a third tick start beside it (`#407`).
        if std::fs::read_to_string(&self.path).ok().as_deref() == Some(self.stamp.as_str()) {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

pub fn lock(root: &Path, now_ms: i64) -> Result<Option<Lock>> {
    let path = root.join("state").join("cron.lock");
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
    }
    match std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
    {
        Ok(mut f) => {
            use std::io::Write;
            let stamp = format!("{now_ms}\n");
            let _ = write!(f, "{stamp}");
            Ok(Some(Lock {
                path,
                took_over_stale: false,
                stamp,
            }))
        }
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
            // `saturating_sub` clamps at the type's bounds, not at zero: a lock written a few
            // milliseconds ahead of our clock came out as a negative age, cast to u64 it read as
            // 584 years old, and every tick took it over. Clamp here, and where the clock cannot
            // be read at all, refuse — a lock of unknown age is a lock.
            let age = std::fs::metadata(&path)
                .and_then(|m| m.modified())
                .ok()
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|d| now_ms.saturating_sub(d.as_millis() as i64).max(0) as u64)
                .unwrap_or(0);
            if age < STALE_LOCK_MS {
                return Ok(None);
            }
            let stamp = format!("{now_ms}\n");
            std::fs::write(&path, &stamp).map_err(|e| Error::io(&path, e))?;
            Ok(Some(Lock {
                path,
                took_over_stale: true,
                stamp,
            }))
        }
        Err(e) => Err(Error::io(&path, e)),
    }
}

/// The run log for one execution: `<root>/cron/runs/<job>/<ms>.md`.
pub fn write_run(root: &Path, job: &str, started_ms: i64, body: &str) -> Result<PathBuf> {
    let dir = runs_dir(root, job);
    std::fs::create_dir_all(&dir).map_err(|e| Error::io(&dir, e))?;
    let path = dir.join(format!("{started_ms}.md"));
    std::fs::write(&path, body).map_err(|e| Error::io(&path, e))?;
    Ok(path)
}

/// The most recent runs of a job, newest first.
pub fn recent_runs(root: &Path, job: &str, limit: usize) -> Vec<PathBuf> {
    let dir = runs_dir(root, job);
    let Ok(entries) = std::fs::read_dir(&dir) else {
        return Vec::new();
    };
    let mut paths: Vec<PathBuf> = entries
        .flatten()
        .map(|e| e.path())
        .filter(|p| p.extension().map(|e| e == "md").unwrap_or(false))
        .collect();
    paths.sort();
    paths.reverse();
    paths.truncate(limit);
    paths
}

// ---------------------------------------------------------------------------------------------
// A job as a surface reads it
// ---------------------------------------------------------------------------------------------

/// How much of a run's text a surface is handed. A job that answers in ten thousand words is a
/// job whose log is an essay; the page shows the beginning and says the rest is on disk in
/// `path`, rather than shipping a megabyte of JSON to a browser to render four lines of it.
pub const RUN_TEXT_CAP: usize = 4000;

/// How much of a run's first line fits in a table: enough to know what happened, short enough to
/// sit in one row. The rest is in [`RunView::text`].
pub const ANSWER_CAP: usize = 160;

/// One job, plus what has run and when it fires next.
///
/// This is the shape `cron list --json` prints and the dashboard renders. It is deliberately not
/// the file's shape: the store's keys (`[[job]]` in TOML) stay where they are so a field renamed
/// for a page cannot move a key in a file somebody wrote by hand.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct JobView {
    pub name: String,
    /// As [`Schedule::parse`] accepts it back — the same string an editor shows and submits, so a
    /// page never has to know that `hourly` and `every 1h` are one schedule.
    pub schedule: String,
    pub enabled: bool,
    pub prompt: String,
    pub route: Option<String>,
    pub workdir: Option<String>,
    pub skills: Vec<String>,
    pub deliver: Option<String>,
    pub schema: Option<String>,
    /// The next fire, or `None` for a disabled job.
    pub next_ms: Option<i64>,
    pub last_started_ms: Option<i64>,
    pub last_finished_ms: Option<i64>,
    /// `ok`, `failed`, or the first line of what went wrong.
    pub last_outcome: Option<String>,
    pub runs: u64,
}

pub fn view(job: &Job, state: &State, now_ms: i64) -> JobView {
    let s = state.get(&job.name);
    JobView {
        name: job.name.clone(),
        schedule: job.schedule.describe(),
        enabled: job.enabled,
        prompt: job.prompt.clone(),
        route: job.route.clone(),
        workdir: job.workdir.clone(),
        skills: job.skills.clone(),
        deliver: job.deliver.clone(),
        schema: job.schema.clone(),
        next_ms: next_due_for(job, state, now_ms),
        last_started_ms: s.last_started_ms,
        last_finished_ms: s.last_finished_ms,
        last_outcome: s.last_outcome,
        runs: s.runs,
    }
}

/// Every job, in the order the file has them, as a surface reads them.
pub fn views(root: &Path, now_ms: i64) -> Result<Vec<JobView>> {
    let state = load_state(root)?;
    Ok(load(root)?
        .iter()
        .map(|job| view(job, &state, now_ms))
        .collect())
}

/// One run of a job, as a surface reads it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RunView {
    pub at_ms: i64,
    /// The same moment for a person, in local time.
    pub at: String,
    /// The first non-empty line of the answer — what a table column shows.
    pub answer: String,
    /// The whole text, capped at [`RUN_TEXT_CAP`] characters.
    pub text: String,
    /// How long the whole text is, so a truncated `text` says so instead of just stopping.
    pub chars: usize,
    pub truncated: bool,
    pub path: String,
}

/// `2026-11-29 07:30`, in local time.
pub fn iso_local(ms: i64) -> String {
    let (y, mo, d, h, mi) = local_parts(ms);
    format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02}")
}

/// The newest runs of one job, read off the files the tick wrote.
pub fn runs(root: &Path, job: &str, limit: usize) -> Vec<RunView> {
    recent_runs(root, job, limit)
        .into_iter()
        .map(|path| {
            let body = std::fs::read_to_string(&path).unwrap_or_default();
            let at_ms = path
                .file_stem()
                .and_then(|s| s.to_str())
                .and_then(|s| s.parse::<i64>().ok())
                .unwrap_or(0);
            // Everything after the first `---` is the answer; before it is the header the tick
            // wrote (`# name — when`, the schedule, the route it took).
            // One line, short enough to sit in a table cell: a job whose answer opens with a
            // paragraph of prose still has to fit beside a schedule and a date. What is cut is
            // marked, and the whole thing is in `text`.
            let first = body
                .split_once("---\n")
                .map(|(_, rest)| rest)
                .unwrap_or(&body)
                .lines()
                .find(|l| !l.trim().is_empty())
                .unwrap_or("(no output)")
                .trim();
            let answer = if first.chars().count() > ANSWER_CAP {
                let mut cut: String = first.chars().take(ANSWER_CAP).collect();
                cut.push('…');
                cut
            } else {
                first.to_string()
            };
            let chars = body.chars().count();
            let text: String = if chars > RUN_TEXT_CAP {
                body.chars().take(RUN_TEXT_CAP).collect()
            } else {
                body.clone()
            };
            RunView {
                at_ms,
                at: iso_local(at_ms),
                answer,
                text,
                chars,
                truncated: chars > RUN_TEXT_CAP,
                path: path.display().to_string(),
            }
        })
        .collect()
}

// ---------------------------------------------------------------------------------------------
// What a surface may write
// ---------------------------------------------------------------------------------------------

fn yes() -> bool {
    true
}

/// A job as a surface submits it: `cron add`'s arguments, or a page's form.
///
/// One struct and one set of checks, because the two front ends must not disagree about what a job
/// is. `enabled` is the only field a create does not have to mention; everything else is the
/// caller's, and the errors are the parsers' own words so the two surfaces say the same sentence.
#[derive(Debug, Clone, Deserialize)]
pub struct Draft {
    pub name: String,
    pub schedule: String,
    pub prompt: String,
    #[serde(default)]
    pub deliver: Option<String>,
    #[serde(default)]
    pub route: Option<String>,
    #[serde(default)]
    pub workdir: Option<String>,
    #[serde(default)]
    pub skills: Vec<String>,
    #[serde(default)]
    pub schema: Option<String>,
    #[serde(default = "yes")]
    pub enabled: bool,
}

impl Default for Draft {
    fn default() -> Self {
        Self {
            name: String::new(),
            schedule: String::new(),
            prompt: String::new(),
            deliver: None,
            route: None,
            workdir: None,
            skills: Vec::new(),
            schema: None,
            enabled: true,
        }
    }
}

impl Draft {
    /// The job this describes, or why it does not describe one.
    ///
    /// A prompt is required and a schedule is parsed here rather than at 07:30 in a log nobody
    /// reads; a `workdir` is checked to be a directory for the same reason — a workspace that is a
    /// typo is a job whose files land somewhere else, or nowhere.
    pub fn to_job(&self) -> Result<Job> {
        validate_job_name(&self.name)?;
        if self.prompt.trim().is_empty() {
            return Err(Error::Config("a job needs a prompt".to_string()));
        }
        let schedule = Schedule::parse(&self.schedule)?;
        if let Some(dir) = &self.workdir {
            let path = expand_tilde(dir);
            if !path.is_dir() {
                return Err(Error::Config(format!(
                    "`{dir}` is not a directory, so the job would have no workspace"
                )));
            }
        }
        Ok(Job {
            name: self.name.clone(),
            schedule,
            prompt: self.prompt.clone(),
            enabled: self.enabled,
            route: self.route.clone(),
            workdir: self.workdir.clone(),
            skills: self.skills.clone(),
            deliver: self.deliver.clone(),
            schema: self.schema.clone(),
        })
    }

    /// The same job as [`Draft`], for editing: what an editor loads into its form.
    pub fn from_job(job: &Job) -> Self {
        Self {
            name: job.name.clone(),
            schedule: job.schedule.describe(),
            prompt: job.prompt.clone(),
            deliver: job.deliver.clone(),
            route: job.route.clone(),
            workdir: job.workdir.clone(),
            skills: job.skills.clone(),
            schema: job.schema.clone(),
            enabled: job.enabled,
        }
    }
}

/// `~/x` and `$HOME/x` as the path they mean.
///
/// The tick resolves a job's own directory the same way (`cron_cli::expand_path`), so a `workdir`
/// that is a directory when it is checked is a directory when it is used.
pub fn expand_tilde(text: &str) -> PathBuf {
    if let Some(rest) = text.strip_prefix("~/") {
        if let Some(home) = crate::config::process_env("HOME") {
            return PathBuf::from(home).join(rest);
        }
    }
    PathBuf::from(text)
}

/// Turn a job on or off, in place. `false` when no job has that name.
pub fn set_enabled(root: &Path, name: &str, enabled: bool) -> Result<Option<Job>> {
    let jobs = load(root)?;
    let Some(mut job) = jobs.into_iter().find(|j| j.name == name) else {
        return Ok(None);
    };
    if job.enabled == enabled {
        return Ok(Some(job));
    }
    job.enabled = enabled;
    replace_job(root, &job)?;
    // Loading it back is the check that the file it wrote is a file this build can read.
    Ok(load(root)?.into_iter().find(|j| j.name == name))
}

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

    fn job(name: &str, schedule: &str) -> Job {
        Job {
            name: name.into(),
            schedule: Schedule::parse(schedule).unwrap(),
            prompt: "say something".into(),
            enabled: true,
            route: None,
            workdir: None,
            skills: Vec::new(),
            deliver: None,
            schema: None,
        }
    }

    /// A directory no other test in this run can be using, removed when the test ends.
    fn temp_root() -> crate::scratch::Scratch<PathBuf> {
        // Unique by construction: `tempfile` picks the name. It used to be
        // `eclipse-cron-test-<pid>-<ms>-<n>` because parallel threads of one process could hand two
        // tests the same name and they would delete each other's files; a `TempDir` gives the same
        // guarantee and removes itself, which the hand-built path did not — one directory per cron
        // test, each with a `cron/jobs.toml`, was left in `$TMPDIR` after every run.
        crate::scratch::Scratch::dir("eclipse-cron-test-")
    }

    #[test]
    fn the_four_shapes_of_a_schedule_round_trip() {
        for (text, want) in [
            ("every 30m", Schedule::Every(1800)),
            ("every 2h", Schedule::Every(7200)),
            ("hourly", Schedule::Every(3600)),
            (
                "daily 07:30",
                Schedule::Daily {
                    hour: 7,
                    minute: 30,
                },
            ),
            (
                "weekly mon 09:00",
                Schedule::Weekly {
                    weekday: 1,
                    hour: 9,
                    minute: 0,
                },
            ),
        ] {
            let parsed = Schedule::parse(text).unwrap();
            assert_eq!(parsed, want, "{text}");
            assert_eq!(Schedule::parse(&parsed.describe()).unwrap(), want);
        }
    }

    #[test]
    fn a_schedule_that_is_not_one_says_what_ones_exist() {
        for bad in [
            "",
            "30m",
            "every",
            "every 30",
            "every 30x",
            "daily",
            "daily 7",
            "daily 25:00",
            "weekly 9am",
        ] {
            let err = Schedule::parse(bad).unwrap_err().to_string();
            assert!(
                err.contains("unrecognised schedule") || err.contains("not a time of day"),
                "{bad}: {err}"
            );
        }
    }

    #[test]
    fn a_sub_minute_interval_is_refused_as_a_busy_loop() {
        let err = Schedule::parse("every 30s").unwrap_err().to_string();
        assert!(err.contains("shortest interval is `every 1m`"), "{err}");
    }

    #[test]
    fn a_daily_schedule_lands_on_that_wall_clock_time_tomorrow_at_the_latest() {
        let now = 1_700_000_000_000i64; // 2023-11-14T22:13:20Z
        let s = Schedule::parse("daily 07:30").unwrap();
        let next = s.next_due(now);
        assert!(next > now);
        assert!(next - now <= 86_400_000, "within a day: {}", next - now);
        let (_, _, _, hour, minute) = local_parts(next);
        assert_eq!((hour, minute), (7, 30), "it fires at 07:30 local, not UTC");
    }

    #[test]
    fn a_weekly_schedule_lands_on_the_named_day() {
        let now = 1_700_000_000_000i64;
        let s = Schedule::parse("weekly wed 09:00").unwrap();
        let next = s.next_due(now);
        assert!(next > now);
        assert!(next - now <= 8 * 86_400_000);
        assert_eq!(weekday_of(next), 3, "a Wednesday");
        let (_, _, _, hour, minute) = local_parts(next);
        assert_eq!((hour, minute), (9, 0));
    }

    #[test]
    fn civil_dates_survive_leap_days_and_month_ends() {
        assert_eq!(days_from_civil(1970, 1, 1), 0);
        assert_eq!(civil_from_days(0), (1970, 1, 1));
        assert_eq!(
            days_from_civil(2024, 2, 29) + 1,
            days_from_civil(2024, 3, 1)
        );
        assert_eq!(civil_add_days(2024, 2, 28, 1), (2024, 2, 29));
        assert_eq!(civil_add_days(2024, 12, 31, 1), (2025, 1, 1));
        for d in [-1000i64, -1, 0, 1, 20_000, 30_000] {
            let (y, m, day) = civil_from_days(d);
            assert_eq!(days_from_civil(y, m, day), d, "round trip at {d}");
        }
    }

    #[test]
    fn a_new_interval_job_runs_at_once_and_a_new_named_job_waits_for_its_hour() {
        let mut state = State::default();
        let now = 1_700_000_000_000i64;
        let every = job("tick", "every 30m");
        let daily = job("brief", "daily 07:30");
        let jobs = vec![every, daily];
        let due_now = due(&jobs, &mut state, now);
        assert_eq!(due_now.len(), 1, "only the interval job");
        assert_eq!(due_now[0].name, "tick");
    }

    #[test]
    fn an_interval_job_is_due_again_only_after_its_interval() {
        let mut state = State::default();
        let now = 1_700_000_000_000i64;
        let jobs = vec![job("tick", "every 30m")];
        state.jobs.insert(
            "tick".into(),
            JobState {
                last_started_ms: Some(now - 29 * 60 * 1000),
                ..Default::default()
            },
        );
        assert!(
            due(&jobs, &mut state, now).is_empty(),
            "29 minutes is not 30"
        );
        state.jobs.insert(
            "tick".into(),
            JobState {
                last_started_ms: Some(now - 31 * 60 * 1000),
                ..Default::default()
            },
        );
        assert_eq!(due(&jobs, &mut state, now).len(), 1);
    }

    /// `#561`: a `daily` job that had never run was due *never*. `due` wanted a `last_started_ms`,
    /// nothing wrote one for a job that had not run, and the only writer was the runner — which
    /// could not run a job that was never due. Every job added by `cron add` or by the dashboard's
    /// form was dead, while `cron list` promised a next time that rolled forward on each tick.
    #[test]
    fn a_new_daily_job_fires_at_its_next_named_moment() {
        let mut state = State::default();
        let now = 1_700_000_000_000i64;
        let jobs = vec![job("brief", "daily 07:30")];
        let next = jobs[0].schedule.next_due(now);
        assert!(next > now, "the next 07:30 is ahead of this moment");

        assert!(due(&jobs, &mut state, now).is_empty(), "not on the spot");
        assert!(
            due(&jobs, &mut state, next - 1).is_empty(),
            "not a millisecond early"
        );
        let fired = due(&jobs, &mut state, next);
        assert_eq!(
            fired.len(),
            1,
            "the job fires at the moment `cron list` promised"
        );
        assert_eq!(fired[0].name, "brief");
    }

    /// The anchor is written once. A seed recomputed on every tick would move it forward each time
    /// and the job would still never fire — the shape this bug actually had.
    #[test]
    fn the_anchor_a_new_job_is_given_is_not_moved_by_a_later_tick() {
        let mut state = State::default();
        let jobs = vec![job("brief", "daily 07:30")];
        due(&jobs, &mut state, 1_000_000_000_000);
        assert_eq!(
            state.get("brief").last_started_ms,
            Some(1_000_000_000_000),
            "the first sighting is the anchor"
        );
        due(&jobs, &mut state, 1_500_000_000_000);
        assert_eq!(
            state.get("brief").last_started_ms,
            Some(1_000_000_000_000),
            "a later tick left it alone"
        );
        assert_eq!(
            next_due_for(&jobs[0], &state, 1_500_000_000_000),
            Some(jobs[0].schedule.next_due(1_000_000_000_000))
        );
    }

    #[test]
    fn a_disabled_job_is_never_due_and_has_no_next_time() {
        let mut state = State::default();
        let mut j = job("tick", "every 1m");
        j.enabled = false;
        state.jobs.insert(
            "tick".into(),
            JobState {
                last_started_ms: Some(0),
                ..Default::default()
            },
        );
        let jobs = vec![j.clone()];
        assert!(due(&jobs, &mut state, 1_700_000_000_000).is_empty());
        assert_eq!(next_due_for(&j, &state, 1_700_000_000_000), None);
    }

    #[test]
    fn a_jobs_schema_survives_the_file_it_is_written_to() {
        let root = temp_root();
        let mut shaped = job("shaped", "daily 07:30");
        // An inline schema, TOML-quoted: the same string `--schema` and the `cronjob_manage` tool
        // hand over, and the one the runner then hands to `resolve_schema`.
        shaped.schema = Some(r#"{"type":"object","required":["headline"]}"#.into());
        shaped.deliver = Some("~/notes/shaped.json".into());
        append_job(&root, &shaped).unwrap();

        let text = std::fs::read_to_string(jobs_path(&root)).unwrap();
        assert!(
            text.contains("schema = \"{\\\"type\\\":\\\"object\\\""),
            "the schema is a TOML string, escaped: {text}"
        );

        let jobs = load(&root).unwrap();
        assert_eq!(jobs.len(), 1);
        assert_eq!(jobs[0].schema, shaped.schema);
        // And a block without one still reads: `schema` is optional, not a new requirement.
        assert_eq!(job("plain", "every 1m").schema, None);
    }

    #[test]
    fn the_jobs_file_is_appended_to_and_a_block_cut_out_without_touching_the_rest() {
        let root = temp_root();
        let first = job("first", "every 1m");
        let mut second = job("second", "daily 08:00");
        second.deliver = Some("~/notes/brief.md".into());
        second.skills = vec!["release-check".into()];
        append_job(&root, &first).unwrap();
        append_job(&root, &second).unwrap();

        let text = std::fs::read_to_string(jobs_path(&root)).unwrap();
        assert!(text.contains("[[job]]"));
        assert!(text.contains("deliver = \"~/notes/brief.md\""));

        let jobs = load(&root).unwrap();
        assert_eq!(jobs.len(), 2);
        assert_eq!(jobs[1].skills, ["release-check"]);
        assert_eq!(jobs[1].schedule, Schedule::Daily { hour: 8, minute: 0 });

        assert!(remove_job(&root, "first").unwrap());
        let jobs = load(&root).unwrap();
        assert_eq!(jobs.len(), 1);
        assert_eq!(jobs[0].name, "second");
        assert!(!remove_job(&root, "nope").unwrap());
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn replacing_a_block_keeps_the_file_around_it() {
        let root = temp_root();
        append_job(&root, &job("one", "every 1m")).unwrap();
        append_job(&root, &job("two", "every 2m")).unwrap();
        let path = jobs_path(&root);
        let before = std::fs::read_to_string(&path).unwrap();
        std::fs::write(&path, format!("{before}\n# keep me\n")).unwrap();

        let mut paused = job("one", "every 1m");
        paused.enabled = false;
        replace_job(&root, &paused).unwrap();

        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.contains("# keep me"), "the comment survives");
        assert!(text.contains("enabled = false"), "the change landed");
        let jobs = load(&root).unwrap();
        assert!(!jobs[0].enabled);
        assert!(jobs[1].enabled);
        assert!(replace_job(&root, &job("ghost", "every 1m")).is_err());
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn two_jobs_cannot_share_a_name() {
        let root = temp_root();
        append_job(&root, &job("same", "every 1m")).unwrap();
        let err = append_job(&root, &job("same", "every 2m"))
            .unwrap_err()
            .to_string();
        assert!(err.contains("already exists"), "{err}");
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn a_job_with_an_empty_prompt_is_refused() {
        let root = temp_root();
        std::fs::create_dir_all(root.join("cron")).unwrap();
        std::fs::write(
            jobs_path(&root),
            "[[job]]\nname = \"x\"\nschedule = \"every 1m\"\nprompt = \"  \"\n",
        )
        .unwrap();
        // A job that cannot run is refused, not invented — and since `#405` one such block is a
        // skipped job with a report rather than a failure for the whole file.
        let (jobs, problems) = load_reporting(&root).unwrap();
        assert!(jobs.is_empty(), "a job with nothing to say is not a job");
        assert_eq!(problems.len(), 1, "{problems:?}");
        assert!(problems[0].contains("empty prompt"), "{problems:?}");
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn an_unknown_key_is_refused_rather_than_silently_ignored() {
        let root = temp_root();
        std::fs::create_dir_all(root.join("cron")).unwrap();
        std::fs::write(
            jobs_path(&root),
            "[[job]]\nname = \"x\"\nschedule = \"every 1m\"\nprompt = \"p\"\nsechdule = \"every 2m\"\n",
        )
        .unwrap();
        assert!(load(&root).is_err(), "a typo in a key must not pass");
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn state_round_trips_and_a_missing_file_is_empty_state() {
        let root = temp_root();
        assert!(load_state(&root).unwrap().jobs.is_empty());
        let mut state = State::default();
        state.jobs.insert(
            "tick".into(),
            JobState {
                last_started_ms: Some(5),
                last_finished_ms: Some(6),
                last_outcome: Some("ok".into()),
                runs: 1,
            },
        );
        save_state(&root, &state).unwrap();
        let back = load_state(&root).unwrap();
        assert_eq!(back.get("tick").runs, 1);
        assert_eq!(back.get("tick").last_outcome.as_deref(), Some("ok"));
        let _ = std::fs::remove_dir_all(&root);
    }

    /// `#405`: one malformed block used to be an `Err` for the whole file, so a typo in a job
    /// nobody was looking at stopped every other job — and the only trace was a failed systemd
    /// unit. A bad block is skipped, named, and the rest still run. The schedule error has to carry
    /// the job's own name: `unrecognised schedule "evry 5m"` in a file of twelve blocks is a hunt.
    #[test]
    fn a_broken_job_is_skipped_and_named_instead_of_stopping_every_job() {
        let root = temp_root();
        std::fs::create_dir_all(root.join("cron")).unwrap();
        std::fs::write(
            jobs_path(&root),
            "[[job]]\nname = \"good\"\nschedule = \"every 1h\"\nprompt = \"say something\"\n\n\
             [[job]]\nname = \"typo\"\nschedule = \"evry 5m\"\nprompt = \"never mind\"\n",
        )
        .unwrap();

        let (jobs, problems) = load_reporting(&root).unwrap();
        assert_eq!(jobs.len(), 1, "the good job still loads: {problems:?}");
        assert_eq!(jobs[0].name, "good");
        assert_eq!(problems.len(), 1, "{problems:?}");
        assert!(
            problems[0].contains("typo"),
            "the problem names the job, not just the schedule: {problems:?}"
        );
        assert!(
            problems[0].contains("evry 5m"),
            "and quotes what it could not parse: {problems:?}"
        );
        // The plain reader is the same list, without the report.
        assert_eq!(load(&root).unwrap().len(), 1);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// `#406`: `every <N>d` multiplied without checking, and a release build has no overflow
    /// checks — `every 144115188075855873d` wrapped to exactly 86 400 seconds and passed as
    /// `every 1d`, i.e. a schedule somebody wrote as "never" silently ran daily.
    #[test]
    fn an_interval_too_large_to_count_is_refused_not_wrapped() {
        assert!(
            Schedule::parse("every 144115188075855873d").is_err(),
            "an interval that wraps is refused"
        );
        assert!(Schedule::parse("every 99999999999999999999d").is_err());
        assert_eq!(
            Schedule::parse("every 2h").unwrap(),
            Schedule::Every(7_200),
            "an ordinary interval still parses"
        );
        // And the arithmetic that would have wrapped is saturating, so a `next_due` on an
        // interval nobody can represent reports the end of time rather than a moment in the past.
        let unrepresentable = Schedule::Every(i64::MAX as u64 / 1000 + 1);
        assert_eq!(unrepresentable.next_due(0), i64::MAX);
        assert_eq!(
            Schedule::Every(3_600).next_due(0),
            3_600_000,
            "and is exact for a real one"
        );
    }

    /// `#407`: staleness is the lock file's mtime, which was written once and never refreshed, so
    /// a tick that legitimately ran past the stale mark was taken for an abandoned one. The next
    /// minute's tick then started with its own list and ran the jobs the first had not reached —
    /// and when the first finished, its `Drop` deleted the *second* tick's file.
    #[test]
    fn a_long_tick_stays_alive_and_a_tick_that_lost_the_lock_does_not_delete_it() {
        let root = temp_root();
        let now = crate::session::now_ms() as i64;
        let mut tick = lock(&root, now).unwrap().expect("first tick takes it");
        let path = tick.path().to_path_buf();

        // Proof of life keeps it fresh: the file's mtime moves and the content is still ours.
        assert!(tick.touch(now + 60_000), "a live tick can say so");
        let modified = std::fs::metadata(&path).and_then(|m| m.modified()).unwrap();
        let fresh = std::time::SystemTime::now()
            .duration_since(modified)
            .expect("the file is not from the future");
        assert!(
            fresh.as_secs() < 60,
            "touching refreshes the mtime, which is what staleness reads"
        );

        // Another tick takes the lock over. Ours is now a stale view of a file it does not own:
        // it cannot touch it, and its `Drop` must leave the new holder's file alone.
        std::fs::write(&path, "999999999999\n").unwrap();
        assert!(!tick.touch(now + 120_000), "a taken-over tick stops");
        drop(tick);
        assert!(
            path.exists(),
            "the new holder's lock survives the old tick's Drop"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn a_second_tick_does_not_take_the_lock_and_an_abandoned_one_does() {
        let root = temp_root();
        let now = crate::session::now_ms() as i64;
        let held = lock(&root, now).unwrap().expect("first tick takes it");
        assert!(lock(&root, now).unwrap().is_none(), "second tick waits");
        drop(held);
        assert!(
            lock(&root, now).unwrap().is_some(),
            "the lock is released when the tick ends"
        );

        // Pretend the process died holding it: age the file past the stale mark.
        let path = root.join("state").join("cron.lock");
        drop(std::fs::File::create(&path).unwrap());
        let old =
            std::time::SystemTime::now() - std::time::Duration::from_millis(STALE_LOCK_MS + 5_000);
        filetime_set(&path, old);
        let taken = lock(&root, now)
            .unwrap()
            .expect("a stale lock is taken over");
        assert!(taken.took_over_stale);
        let _ = std::fs::remove_dir_all(&root);
    }

    fn filetime_set(path: &Path, when: std::time::SystemTime) {
        // No dependency for this: `utimensat` through libc, unix only. Elsewhere the test is a
        // no-op and the stale-lock path is covered by the branch above.
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStrExt;
            let c = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
            let times = [
                libc::timespec {
                    tv_sec: when
                        .duration_since(std::time::UNIX_EPOCH)
                        .map(|d| d.as_secs() as i64)
                        .unwrap_or(0),
                    tv_nsec: 0,
                },
                libc::timespec {
                    tv_sec: when
                        .duration_since(std::time::UNIX_EPOCH)
                        .map(|d| d.as_secs() as i64)
                        .unwrap_or(0),
                    tv_nsec: 0,
                },
            ];
            // SAFETY: a valid C string and an array of exactly two timespecs, as the call
            // requires.
            unsafe {
                libc::utimensat(libc::AT_FDCWD, c.as_ptr(), times.as_ptr(), 0);
            }
        }
        #[cfg(not(unix))]
        let _ = (path, when);
    }

    #[test]
    fn runs_are_written_newest_first() {
        let root = temp_root();
        for ms in [1, 2, 3] {
            write_run(&root, "tick", ms, "hello").unwrap();
        }
        let runs = recent_runs(&root, "tick", 10);
        assert_eq!(runs.len(), 3);
        assert!(runs[0].to_string_lossy().contains("3.md"), "newest first");
        assert_eq!(recent_runs(&root, "nothing", 10).len(), 0);
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn a_job_name_becomes_a_directory_so_it_is_held_to_an_alphabet() {
        for bad in ["..", "a/b", "with space", ""] {
            assert!(validate_job_name(bad).is_err(), "{bad:?} must be refused");
        }
        assert!(validate_job_name("nightly-backup_2").is_ok());
    }

    #[test]
    fn a_view_carries_the_next_fire_and_what_last_ran() {
        let root = temp_root();
        let job = job("brief", "every 30m");
        append_job(&root, &job).unwrap();
        let now = 1_700_000_000_000_i64;

        let fresh = views(&root, now).unwrap();
        assert_eq!(fresh.len(), 1);
        assert_eq!(fresh[0].schedule, "every 30m");
        // Never run and an interval: due immediately, which is what `due` says too.
        assert_eq!(fresh[0].next_ms, Some(now));
        assert_eq!(fresh[0].last_outcome, None);
        assert_eq!(fresh[0].runs, 0);

        let mut state = load_state(&root).unwrap();
        let entry = state.jobs.entry("brief".into()).or_default();
        entry.last_started_ms = Some(now);
        entry.last_finished_ms = Some(now + 1000);
        entry.last_outcome = Some("ok".into());
        entry.runs = 3;
        save_state(&root, &state).unwrap();

        let after = views(&root, now + 1000).unwrap();
        assert_eq!(after[0].runs, 3);
        assert_eq!(after[0].last_outcome.as_deref(), Some("ok"));
        assert_eq!(after[0].next_ms, Some(now + 30 * 60 * 1000));
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn a_schedule_a_job_is_shown_with_is_the_one_an_editor_can_submit_back() {
        for text in [
            "every 30m",
            "every 2h",
            "hourly",
            "daily 07:30",
            "weekly mon 09:00",
        ] {
            let draft = Draft {
                name: "brief".into(),
                schedule: text.into(),
                prompt: "p".into(),
                ..Default::default()
            };
            let job = draft.to_job().unwrap();
            // What the view shows is what comes back to `to_job` as the same schedule.
            let shown = Draft::from_job(&job);
            assert_eq!(shown.schedule, job.schedule.describe());
            let again = shown.to_job().unwrap();
            assert_eq!(again.schedule, job.schedule, "{text} did not round-trip");
        }
        // And the one that means an hour twice says so once: `hourly` is `every 1h`.
        let hourly = Schedule::parse("hourly").unwrap();
        assert_eq!(hourly.describe(), "every 1h");
    }

    #[test]
    fn a_draft_refuses_a_job_nothing_could_run() {
        let base = Draft {
            name: "brief".into(),
            schedule: "hourly".into(),
            prompt: "p".into(),
            ..Default::default()
        };
        assert!(base.to_job().is_ok());

        let empty_prompt = Draft {
            prompt: "  \n ".into(),
            ..base.clone()
        };
        assert!(empty_prompt
            .to_job()
            .unwrap_err()
            .to_string()
            .contains("prompt"));

        let bad_schedule = Draft {
            schedule: "every tuesday".into(),
            ..base.clone()
        };
        assert_eq!(
            bad_schedule.to_job().unwrap_err().to_string(),
            Schedule::parse("every tuesday").unwrap_err().to_string(),
            "the parser's own sentence, not a paraphrase"
        );

        let bad_name = Draft {
            name: "a/b".into(),
            ..base.clone()
        };
        assert!(bad_name.to_job().is_err());

        let missing_dir = Draft {
            workdir: Some("/nonexistent/eclipse-cron-test".into()),
            ..base
        };
        let why = missing_dir.to_job().unwrap_err().to_string();
        assert!(why.contains("not a directory"), "{why}");
    }

    #[test]
    fn a_draft_keeps_being_enabled_unless_it_says_otherwise() {
        // A create that says nothing about `enabled` gets a job that fires: the default belongs in
        // the shared struct, not in whichever front end remembered to set it.
        let draft: Draft = serde_json::from_value(serde_json::json!({
            "name": "brief",
            "schedule": "hourly",
            "prompt": "p",
        }))
        .unwrap();
        assert!(draft.enabled);
        assert!(draft.to_job().unwrap().enabled);
    }

    #[test]
    fn a_run_reads_back_with_its_answer_and_how_much_more_there_is() {
        let root = temp_root();
        let header = "# brief — 2026-11-30 07:30\n\nschedule every 30m\n\n---\n\n";
        write_run(
            &root,
            "brief",
            1_700_000_000_000,
            &format!("{header}it ran\n"),
        )
        .unwrap();

        let long = format!("{header}{}", "x".repeat(RUN_TEXT_CAP + 500));
        write_run(&root, "brief", 1_700_000_100_000, &long).unwrap();

        let runs = runs(&root, "brief", 5);
        assert_eq!(runs.len(), 2);
        // Newest first, and the answer is the first line after the tick's header.
        assert_eq!(runs[0].at_ms, 1_700_000_100_000);
        assert_eq!(
            runs[0].answer.chars().count(),
            ANSWER_CAP + 1,
            "the answer is the first line, cut at the cap and marked"
        );
        assert!(runs[0].answer.ends_with('…'), "{}", runs[0].answer);
        assert!(runs[0].answer.starts_with("xxx"));
        assert!(runs[0].truncated, "a capped text must say it is capped");
        assert_eq!(runs[0].chars, long.chars().count());
        assert_eq!(runs[0].text.chars().count(), RUN_TEXT_CAP);

        assert_eq!(runs[1].answer, "it ran");
        assert!(!runs[1].truncated);
        assert_eq!(runs[1].at, iso_local(1_700_000_000_000));
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn a_job_switched_off_leaves_its_prompt_and_schedule_where_they_were() {
        let root = temp_root();
        append_job(&root, &job("brief", "every 30m")).unwrap();
        let off = set_enabled(&root, "brief", false)
            .unwrap()
            .expect("the job");
        assert!(!off.enabled);

        let on_disk = load(&root).unwrap();
        assert_eq!(on_disk.len(), 1);
        assert_eq!(on_disk[0].prompt, "say something");
        assert_eq!(on_disk[0].schedule, Schedule::parse("every 30m").unwrap());
        assert!(!on_disk[0].enabled);
        // A disabled job is not due and has no next fire, which is what the pane shows.
        assert!(due(&on_disk, &mut State::default(), 1_700_000_000_000).is_empty());
        assert_eq!(
            next_due_for(&on_disk[0], &State::default(), 1_700_000_000_000),
            None
        );

        assert!(set_enabled(&root, "nothing", false).unwrap().is_none());
        assert!(set_enabled(&root, "brief", true).unwrap().unwrap().enabled);
        let _ = std::fs::remove_dir_all(&root);
    }
}