orch-cli 0.110.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
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
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
//! Job scheduler — replaces `jobs_tick.sh`.
//!
//! Reads job definitions from `jobs.yml`, checks cron schedules against
//! the current time, and creates tasks for due jobs. Handles catch-up
//! for missed schedules (capped at 24h).
//!
//! Job types:
//! - `task`: creates a task (GitHub Issue or internal SQLite) and lets the engine dispatch it
//! - `bash`: runs a shell command directly (no LLM)
//! - `self-review`: analyzes task metrics and creates self-improvement issues
//!
//! For task jobs, the `external` field controls where the task is created:
//! - `external: false` (default): Creates an internal SQLite task
//! - `external: true`: Creates a GitHub Issue

pub mod cron;

use crate::backends::{ExternalBackend, ExternalId};
use crate::channels::notification::TaskNotification;
use crate::channels::transport::Transport;
use crate::config;
use crate::engine::tasks::jobs::cron as crate_cron;
use crate::engine::tasks::unblock;
use crate::engine::tasks::unblock::Unblocked;
use crate::github::http::has_status;
use crate::store::TaskStore;
use crate::store::{JobState, TaskStatus};
use crate::sys::cmd as cmd_mod;
use crate::sys::home;
use ::cron::Schedule;
use anyhow::Context;
use dashmap::{DashMap, DashSet};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Output, Stdio};
use std::result;
use std::str::FromStr;
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use tokio::process::Command;
use tokio::task;
use tokio::time;

// Note: self-review analysis is now performed by scheduled tasks configured
// in `.orch.yml` and executed as regular `task` jobs. Hardcoded self-review
// logic was removed to keep this module a generic job dispatcher.

/// A scheduled job definition (from jobs.yml).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Job {
    pub id: String,
    #[serde(default = "default_job_type")]
    pub r#type: String,
    pub schedule: String,
    #[serde(default)]
    pub task: Option<TaskTemplate>,
    #[serde(default)]
    pub command: Option<String>,
    #[serde(default)]
    pub dir: Option<String>,
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    #[serde(default = "default_external")]
    pub external: bool, // true = GitHub Issue, false (default) = internal SQLite task
    /// Send a Telegram notification when this job completes or fails.
    /// Uses `channels.telegram.chat_id` from config unless `notify_target` overrides it.
    #[serde(default)]
    pub notify: bool,
    /// Override the Telegram chat_id for this job's completion notification.
    /// Only used when `notify: true`. Falls back to `channels.telegram.chat_id`.
    #[serde(default)]
    pub notify_target: Option<String>,
    /// `Some(false)` runs this job's agent outside the OS sandbox, for a job that drives an app
    /// over Apple Events, which no sandboxed process may send. Unset follows the project
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sandbox: Option<bool>,
    /// Path to the `prompts/jobs/*.md` file this job was loaded from, if any.
    ///
    /// `None` means the job was defined inline in `.orch.yml` / `config.yml`.
    /// Set by `scan_prompt_jobs`; skipped during serialization so it never
    /// leaks into config files.
    #[serde(skip)]
    pub prompt_file: Option<PathBuf>,
}

/// Template for creating a task from a job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskTemplate {
    pub title: String,
    #[serde(default)]
    pub body: String,
    /// Path to a file (typically markdown) whose contents are used as the
    /// task body. Resolved relative to the directory of the config file
    /// that defines this job. Mutually exclusive with `body`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,
    #[serde(default)]
    pub labels: Vec<String>,
    #[serde(default)]
    pub agent: Option<String>,
}

/// Resolve the body for a task template, reading from `prompt` if set.
///
/// `base_dir` is the directory containing the jobs config file (used to
/// resolve relative `prompt` paths).
pub fn resolve_template_body(template: &TaskTemplate, base_dir: &Path) -> anyhow::Result<String> {
    match template.prompt.as_deref() {
        Some(rel) => {
            let path = Path::new(rel);
            let full = if path.is_absolute() {
                path.to_path_buf()
            } else {
                base_dir.join(path)
            };
            fs::read_to_string(&full)
                .with_context(|| format!("reading prompt file {}", full.display()))
        }
        None => Ok(template.body.clone()),
    }
}

/// Working directory for a bash job, resolved against the project `base_dir`
fn resolve_job_dir(job: &Job, base_dir: &Path) -> PathBuf {
    match job.dir.as_deref().map(Path::new) {
        None => base_dir.to_path_buf(),
        Some(path) if path.is_absolute() => path.to_path_buf(),
        Some(path) => base_dir.join(path),
    }
}

fn default_job_type() -> String {
    "task".to_string()
}

fn default_enabled() -> bool {
    true
}

fn default_external() -> bool {
    false // Default to internal (SQLite) tasks
}

/// Top-level config structure (for reading jobs from .orch.yml / config.yml).
#[derive(Debug, Serialize, Deserialize)]
struct ConfigFile {
    #[serde(default)]
    jobs: Vec<Job>,
    // Capture all other fields so we can round-trip them
    #[serde(flatten)]
    other: serde_norway::Mapping,
}

/// Resolve the config file that contains jobs.
///
/// Priority:
/// 1. `.orch.yml` in the current directory (project config)
/// 2. `.orch.yml` in any registered project directory (from global config)
/// 3. `~/.orch/config.yml` (global config)
pub fn resolve_jobs_path() -> PathBuf {
    // 1. Check cwd
    let project = PathBuf::from(".orch.yml");
    if project.exists() {
        return project;
    }

    // 2. Check registered project directories (handles brew service running from /)
    if let Ok(paths) = config::get_project_paths() {
        for path_str in &paths {
            let candidate = PathBuf::from(path_str).join(".orch.yml");
            if candidate.exists() {
                return candidate;
            }
        }
    }

    // 3. Fall back to global config
    home::config_path().unwrap_or_else(|_| PathBuf::from(".orch/config.yml"))
}

/// Load jobs from the orch config file plus any markdown prompt files
/// discovered under `<base_dir>/prompts/jobs/*.md`.
///
/// Inline `jobs:` in `.orch.yml` and discovered prompt files are merged;
/// duplicate ids across the two sources are rejected.
pub fn load_jobs(path: &PathBuf) -> anyhow::Result<Vec<Job>> {
    let base_dir = path
        .parent()
        .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
    let mut jobs: Vec<Job> = if path.exists() {
        let content =
            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        let file: ConfigFile = serde_norway::from_str(&content)
            .with_context(|| format!("parsing {}", path.display()))?;
        file.jobs
    } else {
        vec![]
    };

    let scanned = scan_prompt_jobs(&base_dir)?;
    let mut seen: HashSet<String> = jobs.iter().map(|j| j.id.clone()).collect();
    for job in scanned {
        if !seen.insert(job.id.clone()) {
            anyhow::bail!(
                "duplicate job id '{}' — defined in both '{}' and prompts/jobs/",
                job.id,
                path.display()
            );
        }
        jobs.push(job);
    }

    for job in &jobs {
        validate_job(job, &base_dir)?;
    }
    Ok(jobs)
}

fn validate_job(job: &Job, base_dir: &Path) -> anyhow::Result<()> {
    let expanded = crate_cron::expand_alias(&job.schedule)
        .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
    let normalized = crate_cron::normalize_dow(&expanded);
    let full_expr = format!("0 {normalized} *");
    Schedule::from_str(&full_expr)
        .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
    if let Some(template) = job.task.as_ref() {
        if template.prompt.is_some() && !template.body.is_empty() {
            anyhow::bail!(
                "job '{}': set either 'task.body' or 'task.prompt', not both",
                job.id
            );
        }
        if let Some(rel) = template.prompt.as_deref() {
            let candidate = Path::new(rel);
            let full = if candidate.is_absolute() {
                candidate.to_path_buf()
            } else {
                base_dir.join(candidate)
            };
            if !full.exists() {
                anyhow::bail!(
                    "job '{}': prompt file not found: {}",
                    job.id,
                    full.display()
                );
            }
        }
    }
    Ok(())
}

/// Frontmatter schema for `prompts/jobs/*.md` files.
#[derive(Debug, Deserialize)]
struct JobFrontmatter {
    id: String,
    schedule: String,
    title: String,
    #[serde(default = "default_job_type")]
    r#type: String,
    #[serde(default = "default_enabled")]
    enabled: bool,
    #[serde(default = "default_external")]
    external: bool,
    #[serde(default)]
    labels: Vec<String>,
    #[serde(default)]
    agent: Option<String>,
    #[serde(default)]
    notify: bool,
    #[serde(default)]
    notify_target: Option<String>,
    #[serde(default)]
    command: Option<String>,
    #[serde(default)]
    dir: Option<String>,
    #[serde(default)]
    sandbox: Option<bool>,
}

/// Split a markdown file into (frontmatter, body). Returns `None` if the file
/// does not start with a `---` fence.
fn split_frontmatter(content: &str) -> Option<(&str, &str)> {
    let rest = content
        .strip_prefix("---\n")
        .or_else(|| content.strip_prefix("---\r\n"))?;
    let end = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"))?;
    let fm = &rest[..end];
    let after = &rest[end..];
    let body = after
        .strip_prefix("\n---\n")
        .or_else(|| after.strip_prefix("\n---\r\n"))
        .unwrap_or(after);
    Some((fm, body.trim_start_matches('\n')))
}

/// Scan `<base_dir>/prompts/jobs/*.md` for job-defining markdown files.
pub fn scan_prompt_jobs(base_dir: &Path) -> anyhow::Result<Vec<Job>> {
    let dir = base_dir.join("prompts").join("jobs");
    if !dir.is_dir() {
        return Ok(vec![]);
    }
    let mut entries: Vec<PathBuf> = fs::read_dir(&dir)
        .with_context(|| format!("reading {}", dir.display()))?
        .filter_map(result::Result::ok)
        .map(|e| e.path())
        .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("md"))
        .collect();
    entries.sort();

    let mut jobs = Vec::with_capacity(entries.len());
    for path in entries {
        let content =
            fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
        let Some((fm, body)) = split_frontmatter(&content) else {
            continue; // No frontmatter → treat as a plain prompt referenced from .orch.yml
        };
        let meta: JobFrontmatter = serde_norway::from_str(fm)
            .with_context(|| format!("parsing frontmatter in {}", path.display()))?;
        jobs.push(Job {
            id: meta.id,
            r#type: meta.r#type,
            schedule: meta.schedule,
            task: Some(TaskTemplate {
                title: meta.title,
                body: body.to_string(),
                prompt: None,
                labels: meta.labels,
                agent: meta.agent,
            }),
            command: meta.command,
            dir: meta.dir,
            enabled: meta.enabled,
            external: meta.external,
            notify: meta.notify,
            notify_target: meta.notify_target,
            sandbox: meta.sandbox,
            prompt_file: Some(path.clone()),
        });
    }
    Ok(jobs)
}

/// Whether the job that started `task_id` turns the sandbox off. The jobs are read from the main
/// checkout, which the agent cannot write, so only a merged change can turn it off
pub async fn sandbox_off_for(
    store: &TaskStore,
    repo: &str,
    project_dir: &Path,
    task_id: &str,
) -> bool {
    let mut states = store.list_job_states(repo).await.unwrap_or_default();
    overlay_pending_job_states(repo, &mut states);
    let Some(job_id) = states
        .into_iter()
        .find(|s| s.active_task_id.as_deref() == Some(task_id))
        .map(|s| s.job_id)
    else {
        return false;
    };

    let path = project_dir.join(".orch.yml");
    let Ok(Ok(jobs)) = task::spawn_blocking(move || load_jobs(&path)).await else {
        return false;
    };

    jobs.iter()
        .any(|j| j.id == job_id && j.sandbox == Some(false))
}

/// Save jobs back to the config file, preserving all other keys.
pub fn save_jobs(path: &PathBuf, jobs: &[Job]) -> anyhow::Result<()> {
    // Read the existing file to preserve non-jobs keys
    let mut file: ConfigFile = if path.exists() {
        let content =
            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        serde_norway::from_str(&content).with_context(|| format!("parsing {}", path.display()))?
    } else {
        ConfigFile {
            jobs: vec![],
            other: serde_norway::Mapping::new(),
        }
    };

    // Only persist inline jobs (those without a prompt_file source).
    // Prompt-based jobs live in prompts/jobs/*.md and must not be duplicated
    // into .orch.yml — doing so causes a "duplicate job id" error on the next
    // load_jobs call.
    file.jobs = jobs
        .iter()
        .filter(|j| j.prompt_file.is_none())
        .cloned()
        .collect();
    let content = serde_norway::to_string(&file)?;
    fs::write(path, content).with_context(|| format!("writing {}", path.display()))?;
    Ok(())
}

/// Update the `enabled:` field in the YAML frontmatter of a prompt-based job
/// file, preserving all other content unchanged.
///
/// The function rewrites only the `enabled:` line inside the opening `---`
/// fence.  If the field is absent it is inserted before the closing `---`.
pub fn set_frontmatter_enabled(path: &Path, enabled: bool) -> anyhow::Result<()> {
    let original =
        fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;

    let value = if enabled { "true" } else { "false" };

    // Replace an existing `enabled: <anything>` line inside the frontmatter.
    // We only touch the first YAML block (between the opening and first closing
    // `---` fences) to avoid accidentally rewriting the body.
    let rewritten = rewrite_frontmatter_enabled(&original, value);
    fs::write(path, rewritten).with_context(|| format!("writing {}", path.display()))?;
    Ok(())
}

/// Rewrite the `enabled:` key inside the first `---` fence block of `content`.
///
/// If the key is present, its value is replaced.  If absent, it is appended
/// just before the closing `---` line.  The rest of the document is unchanged.
fn rewrite_frontmatter_enabled(content: &str, value: &str) -> String {
    // Locate the opening fence.
    let Some(rest) = content
        .strip_prefix("---\n")
        .or_else(|| content.strip_prefix("---\r\n"))
    else {
        // No frontmatter: return unchanged.
        return content.to_string();
    };

    // Find the closing fence.
    let Some(close_pos) = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) else {
        return content.to_string();
    };

    let fm = &rest[..close_pos];
    let after_close = &rest[close_pos..]; // starts with "\n---\n" or "\n---\r\n"

    // Rebuild the frontmatter, replacing or inserting `enabled:`.
    let new_line = format!("enabled: {value}");
    let mut found = false;
    let new_fm: String = fm
        .lines()
        .map(|line| {
            if line == "enabled: true" || line == "enabled: false" || line.starts_with("enabled: ")
            {
                found = true;
                new_line.clone()
            } else {
                line.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join("\n");

    let new_fm = if found {
        new_fm
    } else {
        format!("{new_fm}\n{new_line}")
    };

    format!("---\n{new_fm}{after_close}")
}

/// Returns `true` if the error indicates a "not found" (404) response.
///
/// Used to distinguish permanent task deletion from transient API errors.
/// A 404 should clear `active_task_id`; other errors (rate limit, 5xx,
/// network timeout) should be retried next tick without losing the reference.
fn is_not_found_error(e: &anyhow::Error) -> bool {
    // The status is matched apart from the URL, which holds the issue number
    e.chain().any(|cause| has_status(&cause.to_string(), 404))
}

/// Check all jobs and execute due ones.
///
/// Runtime state (last_run, active_task_id, last_task_status) is stored in
/// SQLite via the `job_state` table, not in the YAML config file.
pub async fn tick(
    jobs_path: &Path,
    backend: &Arc<dyn ExternalBackend>,
    store: Option<&Arc<TaskStore>>,
    repo: &str,
    transport: Option<&Arc<Transport>>,
) -> anyhow::Result<()> {
    let jobs_path_clone = jobs_path.to_path_buf();
    let jobs = match task::spawn_blocking(move || load_jobs(&jobs_path_clone))
        .await
        .map_err(|e| anyhow::anyhow!("load_jobs panicked: {e}"))
        .and_then(|r| r)
    {
        Ok(j) => j,
        Err(e) => {
            tracing::error!(
                path = %jobs_path.display(),
                repo = %repo,
                ?e,
                "job config invalid — skipping scheduler tick for this project"
            );
            return Ok(());
        }
    };
    let now = chrono::Utc::now();

    for job in &jobs {
        if !job.enabled {
            continue;
        }

        // Load runtime state from SQLite
        let mut state = if let Some(s) = store {
            match s.get_job_state(repo, &job.id).await {
                Ok(Some(st)) => st,
                Ok(None) => JobState::new(repo, &job.id),
                Err(e) => {
                    tracing::error!(job_id = job.id, ?e, "failed to load job state, skipping");
                    continue;
                }
            }
        } else {
            JobState::new(repo, &job.id)
        };

        // Retry a lost post-create write even when the job is not due
        if let Some(pending) = pending_job_state(repo, &job.id) {
            state.active_task_id.clone_from(&pending.active_task_id);
            state.last_task_status.clone_from(&pending.last_task_status);
            if let Some(s) = store
                && persist_job_state(s, &pending).await.is_err()
            {
                continue;
            }
        }

        // Check if schedule matches
        let is_due = match &state.last_run {
            Some(last) => match crate_cron::check(&job.schedule, Some(last)) {
                Ok(v) => v,
                Err(e) => {
                    tracing::error!(
                        job_id = job.id,
                        schedule = job.schedule,
                        ?e,
                        "invalid cron expression, skipping"
                    );
                    continue;
                }
            },
            None => match crate_cron::check(&job.schedule, None) {
                Ok(v) => v,
                Err(e) => {
                    tracing::error!(
                        job_id = job.id,
                        schedule = job.schedule,
                        ?e,
                        "invalid cron expression, skipping"
                    );
                    continue;
                }
            },
        };

        if !is_due {
            continue;
        }

        // Check if previous task is still active
        let mut should_clear_task_id = false;
        let mut should_skip = false;
        let mut blocked = false;
        let mut blocked_store_id = None;

        if let Some(ref task_id) = state.active_task_id
            && task_id.is_empty()
        {
            state.active_task_id = None;
        }

        if let Some(ref task_id) = state.active_task_id {
            let task_id_clone = task_id.clone();
            let is_active = if job.external {
                // Check external (GitHub) task
                match backend.get_task(&ExternalId(task_id_clone.clone())).await {
                    Ok(task) => {
                        let status = task.labels.iter().find(|l| l.starts_with("status:"));
                        match status.map(String::as_str) {
                            Some(
                                "status:in_progress"
                                | "status:routed"
                                | "status:new"
                                | "status:needs_review"
                                | "status:in_review"
                                | "status:approved"
                                | "status:waiting",
                            )
                            | None => true, // no status label is treated as active
                            Some("status:blocked") => {
                                blocked = true;
                                false
                            }
                            Some(_) => false, // Done
                        }
                    }
                    Err(e) => {
                        if is_not_found_error(&e) {
                            tracing::warn!(
                                job_id = job.id,
                                task_id = task_id_clone,
                                "active task not found (404), clearing active_task_id"
                            );
                            should_clear_task_id = true;
                            state.last_task_status = Some("error".to_string());
                        } else {
                            tracing::warn!(
                                job_id = job.id,
                                task_id = task_id_clone,
                                ?e,
                                "transient error fetching active task, skipping tick (active_task_id preserved)"
                            );
                            should_skip = true;
                        }
                        false
                    }
                }
            } else {
                // Check internal task via store
                if let Some(s) = store {
                    match s.resolve_task_id(repo, &task_id_clone).await {
                        Ok(Some(store_id)) => match s.get(store_id).await {
                            Ok(task) => match task.status {
                                TaskStatus::New
                                | TaskStatus::Routed
                                | TaskStatus::InProgress
                                | TaskStatus::NeedsReview
                                | TaskStatus::InReview
                                | TaskStatus::Approved
                                | TaskStatus::Waiting => true,
                                TaskStatus::Blocked => {
                                    blocked = true;
                                    blocked_store_id = Some(store_id);
                                    false
                                }
                                TaskStatus::Done => false,
                            },
                            Err(e) => {
                                tracing::warn!(
                                    job_id = job.id,
                                    task_id = task_id_clone,
                                    ?e,
                                    "transient error fetching internal task, skipping tick (active_task_id preserved)"
                                );
                                should_skip = true;
                                false
                            }
                        },
                        Ok(None) => {
                            tracing::warn!(
                                job_id = job.id,
                                task_id = task_id_clone,
                                "internal task not found in store, clearing active_task_id"
                            );
                            should_clear_task_id = true;
                            false
                        }
                        Err(e) => {
                            tracing::warn!(
                                job_id = job.id,
                                task_id = task_id_clone,
                                ?e,
                                "store error resolving internal task, skipping tick (active_task_id preserved)"
                            );
                            should_skip = true;
                            false
                        }
                    }
                } else {
                    should_clear_task_id = true;
                    false
                }
            };

            if is_active {
                tracing::debug!(
                    job_id = job.id,
                    task_id = task_id_clone,
                    external = job.external,
                    "skipping: previous task still active"
                );
                should_skip = true;
            }
        }

        // Apply deferred mutations
        if should_clear_task_id {
            state.active_task_id = None;
        }

        if should_skip {
            continue;
        }

        if blocked
            && job.r#type == "task"
            && let Some(s) = store
            && let Some(task_id) = state.active_task_id.clone()
        {
            let target = BlockedTask {
                task_id: &task_id,
                store_id: blocked_store_id,
            };
            match retry_blocked_task(job, &mut state, backend, s, repo, &target, now).await {
                BlockedRetry::Retried | BlockedRetry::Skip => continue,
                BlockedRetry::CreateNew => {}
            }
        }

        // Claim the slot before last_run so a still-running bash job is skipped
        // without bumping last_run, and a failed last_run write drops the guard
        let bash_guard = if job.r#type == "bash" {
            let Some(guard) = RunningBash::try_acquire(repo, &job.id) else {
                tracing::debug!(job_id = job.id, "skipping: bash job still running");
                continue;
            };
            Some(guard)
        } else {
            None
        };

        tracing::info!(job_id = job.id, r#type = job.r#type, "job due, executing");

        // Persist last_run BEFORE execution to prevent catch-up on restart.
        // On restart the runtime state is loaded from SQLite, so writing
        // last_run here ensures a crash during execution won't cause the
        // job to be considered due again immediately.
        state.last_run = Some(now.format("%Y-%m-%dT%H:%M:%SZ").to_string());
        if let Some(s) = store
            && let Err(e) = s.upsert_job_state(&state).await
        {
            tracing::error!(
                job_id = job.id,
                ?e,
                "failed to persist job state before execution — skipping this tick to preserve restart safety"
            );
            continue; // retry next tick instead of risking duplicate execution
        }

        let base_dir = jobs_path.parent().unwrap_or_else(|| Path::new("."));
        if let Some(guard) = bash_guard {
            spawn_bash_job(
                guard,
                job.clone(),
                state,
                store.cloned(),
                repo.to_string(),
                transport.cloned(),
                base_dir.to_path_buf(),
            );
            continue;
        }

        execute_and_save(job, &mut state, backend, store, repo, transport, base_dir).await;
    }

    Ok(())
}

/// What a due job does with its blocked task
enum BlockedRetry {
    Retried,
    Skip,
    CreateNew,
}

/// The job's active task, found blocked
struct BlockedTask<'a> {
    task_id: &'a str,
    store_id: Option<i64>,
}

/// Unblock the job's blocked task instead of creating another. A PR closed unmerged means a
/// person rejected the work, so that task stays blocked and the job creates a new one
async fn retry_blocked_task(
    job: &Job,
    state: &mut JobState,
    backend: &Arc<dyn ExternalBackend>,
    store: &Arc<TaskStore>,
    repo: &str,
    blocked: &BlockedTask<'_>,
    now: chrono::DateTime<chrono::Utc>,
) -> BlockedRetry {
    let task_id = blocked.task_id;
    let store_id = match blocked.store_id {
        Some(id) => Some(id),
        None => match store.resolve_task_id(repo, task_id).await {
            Ok(id) => id,
            Err(e) => {
                tracing::warn!(
                    job_id = job.id,
                    task_id,
                    ?e,
                    "store error resolving blocked task, skipping tick"
                );
                return BlockedRetry::Skip;
            }
        },
    };

    let pr_number = match store_id {
        Some(id) => match store.get(id).await {
            Ok(task) => task.pr_number,
            Err(e) => {
                tracing::warn!(
                    job_id = job.id,
                    task_id,
                    ?e,
                    "store error reading blocked task, skipping tick"
                );
                return BlockedRetry::Skip;
            }
        },
        None => None,
    };
    if let Some(pr) = pr_number {
        match backend.pull_request_completion(repo, i64::from(pr)).await {
            Ok(Some(pr_state)) if pr_state.closed && !pr_state.merged => {
                tracing::info!(
                    job_id = job.id,
                    task_id,
                    pr_number = pr,
                    "PR closed unmerged, leaving task blocked and creating a new one"
                );
                return BlockedRetry::CreateNew;
            }
            Ok(_) => {}
            Err(e) => {
                tracing::warn!(
                    job_id = job.id,
                    task_id,
                    pr_number = pr,
                    ?e,
                    "failed to read PR state of blocked task, skipping tick"
                );
                return BlockedRetry::Skip;
            }
        }
    }

    // last_run first, so a failed unblock still waits for the next schedule slot
    state.last_run = Some(now.format("%Y-%m-%dT%H:%M:%SZ").to_string());
    if let Err(e) = store.upsert_job_state(state).await {
        tracing::error!(
            job_id = job.id,
            ?e,
            "failed to persist job state before retrying blocked task"
        );
        return BlockedRetry::Skip;
    }

    let task_backend = job.external.then_some(backend);
    let status = match unblock::unblock_task(store, task_backend, repo, task_id, store_id).await {
        Ok(Unblocked::New) => "new",
        Ok(Unblocked::Waiting) => "waiting",
        Err(e) => {
            tracing::error!(
                job_id = job.id,
                task_id,
                ?e,
                "failed to unblock the job's blocked task"
            );
            "error"
        }
    };
    tracing::info!(
        job_id = job.id,
        task_id,
        status,
        "job due, retrying its blocked task"
    );
    state.last_task_status = Some(status.to_string());
    persist_job_state(store, state).await.ok();
    BlockedRetry::Retried
}

/// Bash jobs this process has spawned and not yet finished, keyed by repo and job id
static RUNNING_BASH: LazyLock<DashSet<(String, String)>> = LazyLock::new(DashSet::new);

// Created task id waiting for a successful job_state upsert
static PENDING_JOB_STATE: LazyLock<DashMap<(String, String), JobState>> =
    LazyLock::new(DashMap::new);

const JOB_STATE_PERSIST_ATTEMPTS: u32 = 2;

/// Releases the in-process slot when the spawned bash job ends
struct RunningBash {
    key: (String, String),
}

impl RunningBash {
    fn try_acquire(repo: &str, job_id: &str) -> Option<Self> {
        let key = (repo.to_string(), job_id.to_string());
        if RUNNING_BASH.insert(key.clone()) {
            Some(Self { key })
        } else {
            None
        }
    }
}

impl Drop for RunningBash {
    fn drop(&mut self) {
        RUNNING_BASH.remove(&self.key);
    }
}

fn spawn_bash_job(
    guard: RunningBash,
    job: Job,
    mut state: JobState,
    store: Option<Arc<TaskStore>>,
    repo: String,
    transport: Option<Arc<Transport>>,
    base_dir: PathBuf,
) {
    tokio::spawn(async move {
        let _guard = guard;
        apply_bash_result(&job, &mut state, &base_dir).await;
        if let Some(s) = &store
            && let Err(e) = s.upsert_job_state(&state).await
        {
            tracing::error!(
                job_id = job.id,
                ?e,
                "failed to persist job state after execution"
            );
        }
        notify_job_result(&job, &state, &repo, transport.as_ref());
    });
}

async fn apply_bash_result(job: &Job, state: &mut JobState, base_dir: &Path) {
    let Some(cmd) = job.command.as_deref() else {
        return;
    };
    // Unset `dir` and relative `dir` resolve against `base_dir`, the project dir.
    // The brew service cwd is `/`, so `"."` and `"scripts"` would otherwise run there
    let dir = resolve_job_dir(job, base_dir);
    tracing::info!(job_id = job.id, cmd, dir = %dir.display(), "running bash command");

    // Configurable timeout with 5-minute default. A hung command is killed so
    // the next cron period can start a fresh run
    let timeout_secs: u64 = config::get("jobs.bash_timeout_seconds")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(300);
    let timeout = Duration::from_secs(timeout_secs);

    match run_bash(cmd, &dir, timeout).await {
        Ok(Ok(o)) if o.status.success() => {
            state.last_task_status = Some("done".to_string());
        }
        Ok(Ok(o)) => {
            let stderr = String::from_utf8_lossy(&o.stderr);
            tracing::warn!(
                job_id = job.id,
                code = o.status.code(),
                %stderr,
                "bash command failed"
            );
            state.last_task_status = Some("failed".to_string());
        }
        Ok(Err(e)) => {
            tracing::error!(job_id = job.id, ?e, "bash command error");
            state.last_task_status = Some("failed".to_string());
        }
        Err(_) => {
            tracing::error!(
                job_id = job.id,
                secs = timeout_secs,
                "bash job timed out after {}s, child killed",
                timeout_secs
            );
            state.last_task_status = Some("timeout".to_string());
        }
    }
}

/// Runs `bash -c` under a timeout in its own process group, so a timeout kills the commands bash
/// forked too
async fn run_bash(
    cmd: &str,
    dir: &Path,
    timeout: Duration,
) -> result::Result<anyhow::Result<Output>, time::error::Elapsed> {
    let mut command = Command::new("bash");
    command
        .arg("-c")
        .arg(cmd)
        .current_dir(dir)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    #[cfg(unix)]
    command.process_group(0);

    let child = match command.spawn() {
        Ok(child) => child,
        Err(e) => return Ok(Err(anyhow::anyhow!("failed to execute `bash`: {e}"))),
    };
    let pgid = child.id();
    let out = time::timeout(timeout, child.wait_with_output()).await;

    #[cfg(unix)]
    if out.is_err()
        && let Some(pgid) = pgid
    {
        cmd_mod::kill_process_group(pgid);
    }

    out.map(|r| r.map_err(|e| anyhow::anyhow!("failed to execute `bash`: {e}")))
}

fn job_state_key(repo: &str, job_id: &str) -> (String, String) {
    (repo.to_string(), job_id.to_string())
}

fn pending_job_state(repo: &str, job_id: &str) -> Option<JobState> {
    PENDING_JOB_STATE
        .get(&job_state_key(repo, job_id))
        .map(|entry| (*entry).clone())
}

fn overlay_pending_job_states(repo: &str, states: &mut Vec<JobState>) {
    for entry in PENDING_JOB_STATE.iter() {
        let (key, pending) = entry.pair();
        if key.0 != repo {
            continue;
        }
        if let Some(existing) = states.iter_mut().find(|s| s.job_id == key.1) {
            existing.active_task_id.clone_from(&pending.active_task_id);
            existing
                .last_task_status
                .clone_from(&pending.last_task_status);
        } else {
            states.push(pending.clone());
        }
    }
}

async fn persist_job_state(store: &TaskStore, state: &JobState) -> anyhow::Result<()> {
    let mut last_err = None;
    for attempt in 1..=JOB_STATE_PERSIST_ATTEMPTS {
        match store.upsert_job_state(state).await {
            Ok(()) => {
                PENDING_JOB_STATE.remove(&job_state_key(&state.repo, &state.job_id));
                return Ok(());
            }
            Err(e) => {
                tracing::error!(
                    job_id = %state.job_id,
                    attempt,
                    ?e,
                    "failed to persist job state after execution"
                );
                last_err = Some(e);
            }
        }
    }
    if state.active_task_id.is_some() {
        PENDING_JOB_STATE.insert(job_state_key(&state.repo, &state.job_id), state.clone());
    }
    Err(last_err.expect("job state persist attempted at least once"))
}

/// Run the job and save its state, whose `active_task_id` is how the runner finds the job
/// behind a task, for `sandbox: false`
pub async fn execute_and_save(
    job: &Job,
    state: &mut JobState,
    backend: &Arc<dyn ExternalBackend>,
    store: Option<&Arc<TaskStore>>,
    repo: &str,
    transport: Option<&Arc<Transport>>,
    base_dir: &Path,
) {
    execute_job(job, state, backend, store, repo, transport, base_dir).await;

    if let Some(s) = store {
        persist_job_state(s, state).await.ok();
    }
}

pub async fn execute_job(
    job: &Job,
    state: &mut JobState,
    backend: &Arc<dyn ExternalBackend>,
    store: Option<&Arc<TaskStore>>,
    repo: &str,
    transport: Option<&Arc<Transport>>,
    base_dir: &Path,
) {
    match job.r#type.as_str() {
        "task" => {
            if let Some(ref template) = job.task {
                let body = match resolve_template_body(template, base_dir) {
                    Ok(b) => b,
                    Err(e) => {
                        tracing::error!(job_id = job.id, ?e, "failed to resolve task body");
                        state.last_task_status = Some("failed".to_string());
                        return;
                    }
                };

                if job.external {
                    let mut labels = template.labels.clone();
                    labels.push("scheduled".to_string());
                    labels.push(format!("job:{}", job.id));

                    if let Some(ref agent) = template.agent
                        && !agent.is_empty()
                    {
                        labels.push(format!("agent:{agent}"));
                    }

                    match backend.create_task(&template.title, &body, &labels).await {
                        Ok(ext_id) => {
                            tracing::info!(
                                job_id = job.id,
                                task_id = ext_id.0,
                                "created external task"
                            );
                            state.active_task_id = Some(ext_id.0);
                            state.last_task_status = Some("new".to_string());
                        }
                        Err(e) => {
                            tracing::error!(job_id = job.id, ?e, "failed to create external task");
                            state.last_task_status = Some("failed".to_string());
                        }
                    }
                } else if let Some(s) = store {
                    match s
                        .create_internal(repo, &template.title, &body, "cron", &job.id, None)
                        .await
                    {
                        Ok(internal_id) => {
                            let task_id = format!("internal:{internal_id}");
                            tracing::info!(job_id = job.id, task_id, "created internal task");
                            state.active_task_id = Some(task_id);
                            state.last_task_status = Some("new".to_string());
                        }
                        Err(e) => {
                            tracing::error!(job_id = job.id, ?e, "failed to create internal task");
                            state.last_task_status = Some("failed".to_string());
                        }
                    }
                } else {
                    tracing::error!(
                        job_id = job.id,
                        "no store available for internal task creation"
                    );
                    state.last_task_status = Some("failed".to_string());
                }
            }
        }
        "bash" => {
            apply_bash_result(job, state, base_dir).await;
        }
        // Note: previous versions supported a special-case "self-review"
        // job type with embedded analysis logic. That logic has been removed
        // — self-review work should be configured as a regular `task` job in
        // `.orch.yml` and executed by agents. Unknown job types fall through
        // to the warning handler below.
        other => {
            tracing::warn!(job_id = job.id, r#type = other, "unknown job type");
        }
    }

    notify_job_result(job, state, repo, transport);
}

fn notify_job_result(job: &Job, state: &JobState, repo: &str, transport: Option<&Arc<Transport>>) {
    if job.notify
        && let Some(t) = transport
    {
        let status = state
            .last_task_status
            .as_deref()
            .unwrap_or("unknown")
            .to_string();
        let summary = match status.as_str() {
            "done" => format!("Job `{}` completed successfully.", job.id),
            "failed" => format!("Job `{}` failed.", job.id),
            "new" => format!("Job `{}` created a new task.", job.id),
            other => format!("Job `{}` finished with status: {other}.", job.id),
        };
        // Resolve target chat_id: job override → config default
        let target = job
            .notify_target
            .clone()
            .or_else(|| config::get("channels.telegram.chat_id").ok());
        let notification = TaskNotification {
            task_id: job.id.clone(),
            title: format!("Job: {}", job.id),
            status,
            agent: "scheduler".to_string(),
            duration_seconds: 0.0,
            summary,
            repo: Some(repo.to_string()),
            notify_target: target,
            pr_number: None,
        };
        t.push_notification(notification);
    }
}

// NOTE: self-review analysis is handled by scheduled `task` jobs configured
// in `.orch.yml` and executed by agents. There is no embedded Rust logic
// here — this module remains a generic job dispatcher.

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backends::test_helpers::NoopBackend;
    use crate::backends::{
        Conversation, ExternalTask, MergeState, PullRequestCompletion, Status, TaskReader,
        TaskWriter, Tracker,
    };
    use crate::store::{DepSource, NewDependency};
    use async_trait::async_trait;
    use std::env;
    use std::fs;
    use std::sync::Mutex;
    use tempfile::tempdir;

    fn write_config(dir: &Path, content: &str) -> PathBuf {
        let path = dir.join(".orch.yml");
        fs::write(&path, content).unwrap();
        path
    }

    #[tokio::test]
    async fn run_bash_timeout_kills_the_child() {
        let tmp = tempdir().unwrap();
        let pid_file = tmp.path().join("pid");
        let cmd = format!("sleep 60 & echo $! > {}; wait", pid_file.display());

        let out = run_bash(&cmd, Path::new("."), Duration::from_secs(1)).await;
        assert!(out.is_err(), "expected a timeout");

        let pid: i32 = fs::read_to_string(&pid_file)
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        let mut gone = false;
        for _ in 0..20 {
            if cmd_mod::raw_kill(pid, 0) != 0 {
                gone = true;
                break;
            }
            time::sleep(Duration::from_millis(100)).await;
        }
        assert!(gone, "grandchild {pid} still running after timeout");
    }

    fn bash_job(id: &str, command: String, dir: Option<&str>) -> Job {
        Job {
            id: id.to_string(),
            r#type: "bash".to_string(),
            schedule: "* * * * *".to_string(),
            task: None,
            command: Some(command),
            dir: dir.map(str::to_string),
            enabled: true,
            external: false,
            notify: false,
            notify_target: None,
            sandbox: None,
            prompt_file: None,
        }
    }

    async fn execute_bash(job: &Job, base_dir: &Path) -> JobState {
        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
        let mut state = JobState::new("owner/repo", &job.id);
        execute_job(
            job,
            &mut state,
            &backend,
            None,
            "owner/repo",
            None,
            base_dir,
        )
        .await;
        state
    }

    fn read_recorded_cwd(path: &Path) -> PathBuf {
        let raw = fs::read_to_string(path).expect("bash command should have written cwd.txt");
        fs::canonicalize(raw.trim()).unwrap()
    }

    #[tokio::test]
    async fn bash_job_runs_in_project_dir_not_process_cwd() {
        let project = tempdir().unwrap();
        let process_cwd = fs::canonicalize(env::current_dir().unwrap()).unwrap();
        let project_dir = fs::canonicalize(project.path()).unwrap();
        assert_ne!(
            process_cwd, project_dir,
            "setup: process cwd must differ from the project dir"
        );

        let out_default = project.path().join("cwd-default.txt");
        let job = bash_job(
            "default-dir",
            format!("pwd > '{}'", out_default.display()),
            None,
        );
        let state = execute_bash(&job, project.path()).await;
        assert_eq!(
            state.last_task_status.as_deref(),
            Some("done"),
            "bash job with no dir should succeed in the project dir"
        );
        assert_eq!(
            read_recorded_cwd(&out_default),
            project_dir,
            "bash job with no dir must run in the project dir"
        );

        let scripts = project.path().join("scripts");
        fs::create_dir(&scripts).unwrap();
        let out_relative = project.path().join("cwd-relative.txt");
        let job = bash_job(
            "relative-dir",
            format!("pwd > '{}'", out_relative.display()),
            Some("scripts"),
        );
        let state = execute_bash(&job, project.path()).await;
        assert_eq!(
            state.last_task_status.as_deref(),
            Some("done"),
            "bash job should succeed when relative dir resolves to an existing path"
        );
        assert_eq!(
            read_recorded_cwd(&out_relative),
            fs::canonicalize(&scripts).unwrap(),
            "relative dir must resolve against the project dir"
        );

        let abs = tempdir().unwrap();
        let out_abs = project.path().join("cwd-absolute.txt");
        let job = bash_job(
            "absolute-dir",
            format!("pwd > '{}'", out_abs.display()),
            Some(abs.path().to_str().unwrap()),
        );
        let state = execute_bash(&job, project.path()).await;
        assert_eq!(
            state.last_task_status.as_deref(),
            Some("done"),
            "bash job should succeed when dir is an absolute path"
        );
        assert_eq!(
            read_recorded_cwd(&out_abs),
            fs::canonicalize(abs.path()).unwrap(),
            "absolute dir must be used as-is"
        );
    }

    async fn tick_with_store(path: &Path, store: &Arc<TaskStore>, repo: &str) {
        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
        tick(path, &backend, Some(store), repo, None).await.unwrap();
    }

    async fn wait_for_job_status(
        store: &TaskStore,
        repo: &str,
        job_id: &str,
        want: &str,
    ) -> Option<String> {
        for _ in 0..300 {
            let status = store
                .get_job_state(repo, job_id)
                .await
                .unwrap()
                .and_then(|s| s.last_task_status);
            if status.as_deref() == Some(want) {
                return status;
            }
            time::sleep(Duration::from_millis(50)).await;
        }
        store
            .get_job_state(repo, job_id)
            .await
            .unwrap()
            .and_then(|s| s.last_task_status)
    }

    #[tokio::test]
    async fn bash_job_tick_returns_before_the_command_ends() {
        let tmp = tempdir().unwrap();
        let cfg = write_config(
            tmp.path(),
            r#"
jobs:
  - id: slow
    type: bash
    schedule: "* * * * *"
    command: "sleep 5"
"#,
        );
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let repo = "tick-returns/repo";
        let started = time::Instant::now();
        tick_with_store(&cfg, &store, repo).await;
        assert!(
            started.elapsed() < Duration::from_secs(2),
            "tick waited for the bash command, elapsed {:?}",
            started.elapsed()
        );
        let early = store.get_job_state(repo, "slow").await.unwrap().unwrap();
        assert!(
            early.last_run.is_some(),
            "last_run must be written before the command ends"
        );
        assert_ne!(
            early.last_task_status.as_deref(),
            Some("done"),
            "job state must not already be done when tick returns"
        );
        let status = wait_for_job_status(&store, repo, "slow", "done").await;
        assert_eq!(status.as_deref(), Some("done"));
    }

    #[tokio::test]
    async fn bash_job_tick_starts_only_one_run() {
        let tmp = tempdir().unwrap();
        let log = tmp.path().join("runs.log");
        let go = tmp.path().join("go");
        let cfg = write_config(
            tmp.path(),
            &format!(
                r#"
jobs:
  - id: once
    type: bash
    schedule: "* * * * *"
    command: "echo x >> '{log}'; while [ ! -f '{go}' ]; do sleep 0.05; done"
"#,
                log = log.display(),
                go = go.display(),
            ),
        );
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let repo = "tick-one-run/repo";
        tick_with_store(&cfg, &store, repo).await;

        for _ in 0..100 {
            if log.exists() {
                break;
            }
            time::sleep(Duration::from_millis(20)).await;
        }
        assert!(log.exists(), "first bash job never started");

        let mut state = store
            .get_job_state(repo, "once")
            .await
            .unwrap()
            .expect("last_run written before spawn");
        let past = chrono::Utc::now() - chrono::Duration::minutes(2);
        state.last_run = Some(past.format("%Y-%m-%dT%H:%M:%SZ").to_string());
        store.upsert_job_state(&state).await.unwrap();

        tick_with_store(&cfg, &store, repo).await;
        fs::write(&go, "").unwrap();
        let status = wait_for_job_status(&store, repo, "once", "done").await;
        assert_eq!(status.as_deref(), Some("done"));
        let body = fs::read_to_string(&log).unwrap();
        assert_eq!(
            body.matches('x').count(),
            1,
            "started a second copy: {body:?}"
        );
    }

    #[test]
    fn load_jobs_reads_prompt_from_file() {
        let tmp = tempdir().unwrap();
        fs::create_dir(tmp.path().join("prompts")).unwrap();
        fs::write(tmp.path().join("prompts/hello.md"), "hello from file").unwrap();
        let cfg = write_config(
            tmp.path(),
            r#"
jobs:
  - id: with-prompt
    schedule: "0 9 * * *"
    task:
      title: "Daily"
      prompt: prompts/hello.md
"#,
        );

        let jobs = load_jobs(&cfg).unwrap();
        assert_eq!(jobs.len(), 1);
        let body = resolve_template_body(jobs[0].task.as_ref().unwrap(), tmp.path()).unwrap();
        assert_eq!(body, "hello from file");
    }

    #[test]
    fn load_jobs_rejects_both_body_and_prompt() {
        let tmp = tempdir().unwrap();
        fs::write(tmp.path().join("p.md"), "x").unwrap();
        let cfg = write_config(
            tmp.path(),
            r#"
jobs:
  - id: conflict
    schedule: "0 9 * * *"
    task:
      title: "x"
      body: "inline"
      prompt: p.md
"#,
        );

        let err = load_jobs(&cfg).unwrap_err().to_string();
        assert!(err.contains("not both"), "unexpected error: {err}");
    }

    #[test]
    fn load_jobs_rejects_missing_prompt_file() {
        let tmp = tempdir().unwrap();
        let cfg = write_config(
            tmp.path(),
            r#"
jobs:
  - id: missing
    schedule: "0 9 * * *"
    task:
      title: "x"
      prompt: does-not-exist.md
"#,
        );

        let err = load_jobs(&cfg).unwrap_err().to_string();
        assert!(
            err.contains("prompt file not found"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn resolve_template_body_falls_back_to_inline_body() {
        let tmp = tempdir().unwrap();
        let template = TaskTemplate {
            title: "t".to_string(),
            body: "inline body".to_string(),
            prompt: None,
            labels: vec![],
            agent: None,
        };
        assert_eq!(
            resolve_template_body(&template, tmp.path()).unwrap(),
            "inline body"
        );
    }

    fn write_prompt_job(dir: &Path, name: &str, content: &str) {
        let jobs_dir = dir.join("prompts").join("jobs");
        fs::create_dir_all(&jobs_dir).unwrap();
        fs::write(jobs_dir.join(name), content).unwrap();
    }

    #[test]
    fn scan_prompt_jobs_picks_up_frontmatter_files() {
        let tmp = tempdir().unwrap();
        write_prompt_job(
            tmp.path(),
            "morning.md",
            "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\nlabels: [daily]\nagent: claude\n---\n\nDo morning stuff.\n",
        );
        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
        assert_eq!(jobs.len(), 1);
        assert_eq!(jobs[0].id, "morning");
        assert_eq!(jobs[0].schedule, "0 9 * * *");
        let task = jobs[0].task.as_ref().unwrap();
        assert_eq!(task.title, "Morning");
        assert_eq!(task.body, "Do morning stuff.\n");
        assert_eq!(task.labels, vec!["daily".to_string()]);
        assert_eq!(task.agent.as_deref(), Some("claude"));
    }

    #[test]
    fn load_jobs_merges_inline_and_scanned() {
        let tmp = tempdir().unwrap();
        write_prompt_job(
            tmp.path(),
            "scanned.md",
            "---\nid: scanned\nschedule: '0 9 * * *'\ntitle: Scanned\n---\n\nbody\n",
        );
        let cfg = write_config(
            tmp.path(),
            r#"
jobs:
  - id: inline
    schedule: "0 10 * * *"
    task:
      title: "Inline"
      body: "x"
"#,
        );
        let jobs = load_jobs(&cfg).unwrap();
        let ids: Vec<&str> = jobs.iter().map(|j| j.id.as_str()).collect();
        assert!(ids.contains(&"inline"));
        assert!(ids.contains(&"scanned"));
        assert_eq!(jobs.len(), 2);
    }

    #[test]
    fn load_jobs_rejects_duplicate_id_across_sources() {
        let tmp = tempdir().unwrap();
        write_prompt_job(
            tmp.path(),
            "dup.md",
            "---\nid: dup\nschedule: '0 9 * * *'\ntitle: Dup\n---\n\nbody\n",
        );
        let cfg = write_config(
            tmp.path(),
            r#"
jobs:
  - id: dup
    schedule: "0 10 * * *"
    task:
      title: "Dup inline"
      body: "x"
"#,
        );
        let err = load_jobs(&cfg).unwrap_err().to_string();
        assert!(err.contains("duplicate job id"), "unexpected error: {err}");
    }

    #[tokio::test]
    async fn a_job_run_by_hand_links_its_task_so_sandbox_false_applies() {
        let dir = tempfile::tempdir().unwrap();
        let jobs_dir = dir.path().join("prompts/jobs");
        fs::create_dir_all(&jobs_dir).unwrap();
        fs::write(
            jobs_dir.join("mail.md"),
            "---\nid: mail\nschedule: '0 8 * * *'\ntitle: Mail\nsandbox: false\n---\n\nbody\n",
        )
        .unwrap();
        let job = load_jobs(&dir.path().join(".orch.yml")).unwrap().remove(0);
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
        let mut state = JobState::new("owner/repo", "mail");

        execute_and_save(
            &job,
            &mut state,
            &backend,
            Some(&store),
            "owner/repo",
            None,
            dir.path(),
        )
        .await;

        let task = state
            .active_task_id
            .clone()
            .expect("the run creates a task");
        let saved = store
            .get_job_state("owner/repo", "mail")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(saved.active_task_id.as_deref(), Some(task.as_str()));
        assert!(sandbox_off_for(&store, "owner/repo", dir.path(), &task).await);
    }

    #[tokio::test]
    async fn a_job_with_sandbox_false_turns_it_off_for_its_task_only() {
        let dir = tempfile::tempdir().unwrap();
        let jobs_dir = dir.path().join("prompts/jobs");
        fs::create_dir_all(&jobs_dir).unwrap();
        fs::write(
            jobs_dir.join("mail.md"),
            "---\nid: mail\nschedule: '0 8 * * *'\ntitle: Mail\nsandbox: false\n---\n\nbody\n",
        )
        .unwrap();
        fs::write(
            jobs_dir.join("other.md"),
            "---\nid: other\nschedule: '0 8 * * *'\ntitle: Other\n---\n\nbody\n",
        )
        .unwrap();
        let store = TaskStore::open_memory().await.unwrap();
        for (job, task) in [("mail", "internal:1"), ("other", "internal:2")] {
            let mut state = JobState::new("owner/repo", job);
            state.active_task_id = Some(task.to_string());
            store.upsert_job_state(&state).await.unwrap();
        }

        assert!(sandbox_off_for(&store, "owner/repo", dir.path(), "internal:1").await);
        assert!(!sandbox_off_for(&store, "owner/repo", dir.path(), "internal:2").await);
        assert!(!sandbox_off_for(&store, "owner/repo", dir.path(), "internal:3").await);
    }

    #[test]
    fn scan_prompt_jobs_ignores_files_without_frontmatter() {
        let tmp = tempdir().unwrap();
        write_prompt_job(
            tmp.path(),
            "plain.md",
            "just a prompt body, no frontmatter\n",
        );
        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
        assert_eq!(jobs.len(), 0);
    }

    #[test]
    fn load_jobs_works_without_config_file_when_directory_present() {
        let tmp = tempdir().unwrap();
        write_prompt_job(
            tmp.path(),
            "solo.md",
            "---\nid: solo\nschedule: '0 9 * * *'\ntitle: Solo\n---\n\nbody\n",
        );
        let missing_cfg = tmp.path().join(".orch.yml");
        let jobs = load_jobs(&missing_cfg).unwrap();
        assert_eq!(jobs.len(), 1);
        assert_eq!(jobs[0].id, "solo");
    }

    // ──── Issue #3193: frontmatter `enabled: false` must be respected ────────

    #[test]
    fn scan_prompt_jobs_respects_enabled_false() {
        let tmp = tempdir().unwrap();
        write_prompt_job(
            tmp.path(),
            "disabled.md",
            "---\nid: disabled\nschedule: '0 9 * * *'\ntitle: Disabled\nenabled: false\n---\n\nbody\n",
        );
        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
        assert_eq!(jobs.len(), 1);
        assert!(!jobs[0].enabled, "job should be disabled via frontmatter");
    }

    #[test]
    fn scan_prompt_jobs_sets_prompt_file() {
        let tmp = tempdir().unwrap();
        write_prompt_job(
            tmp.path(),
            "morning.md",
            "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\n---\n\nbody\n",
        );
        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
        assert_eq!(jobs.len(), 1);
        assert!(
            jobs[0].prompt_file.is_some(),
            "prompt_file should be set for frontmatter jobs"
        );
    }

    #[test]
    fn save_jobs_does_not_persist_prompt_based_jobs() {
        let tmp = tempdir().unwrap();
        // A prompt-based job
        write_prompt_job(
            tmp.path(),
            "prompt.md",
            "---\nid: from-prompt\nschedule: '0 9 * * *'\ntitle: Prompt Job\n---\n\nbody\n",
        );
        // An inline job in .orch.yml
        let cfg = write_config(
            tmp.path(),
            "jobs:\n  - id: inline\n    schedule: \"0 10 * * *\"\n    task:\n      title: Inline\n      body: x\n",
        );
        let jobs = load_jobs(&cfg).unwrap();
        assert_eq!(jobs.len(), 2);

        // save_jobs should only write the inline job, not the prompt-based one
        save_jobs(&cfg, &jobs).unwrap();

        let saved = load_jobs(&cfg).unwrap();
        assert_eq!(saved.len(), 2, "both jobs should still be loadable");
        let ids: Vec<&str> = saved.iter().map(|j| j.id.as_str()).collect();
        assert!(ids.contains(&"inline"));
        assert!(ids.contains(&"from-prompt"));
    }

    #[test]
    fn rewrite_frontmatter_enabled_replaces_existing_value() {
        let input = "---\nid: foo\nschedule: daily\nenabled: true\ntitle: Foo\n---\n\nbody\n";
        let out = rewrite_frontmatter_enabled(input, "false");
        assert!(
            out.contains("enabled: false"),
            "should replace enabled: true"
        );
        assert!(!out.contains("enabled: true"), "old value must be gone");
        assert!(out.contains("body"), "body must be preserved");
    }

    #[test]
    fn rewrite_frontmatter_enabled_inserts_when_absent() {
        let input = "---\nid: foo\nschedule: daily\ntitle: Foo\n---\n\nbody\n";
        let out = rewrite_frontmatter_enabled(input, "false");
        assert!(
            out.contains("enabled: false"),
            "should insert enabled: false"
        );
        assert!(out.contains("body"), "body must be preserved");
    }

    #[test]
    fn set_frontmatter_enabled_writes_file() {
        let tmp = tempdir().unwrap();
        let path = tmp.path().join("job.md");
        fs::write(
            &path,
            "---\nid: foo\nschedule: daily\ntitle: Foo\nenabled: true\n---\n\nbody\n",
        )
        .unwrap();
        set_frontmatter_enabled(&path, false).unwrap();
        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("enabled: false"));
        assert!(!content.contains("enabled: true"));
    }

    #[tokio::test]
    async fn tick_keeps_active_task_id_when_the_store_lookup_fails() {
        let tmp = tempdir().unwrap();
        let cfg = write_config(
            tmp.path(),
            r#"
jobs:
  - id: nightly
    type: bash
    schedule: "* * * * *"
    command: "true"
"#,
        );
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let mut state = JobState::new("owner/repo", "nightly");
        state.active_task_id = Some("internal:1".to_string());
        store.upsert_job_state(&state).await.unwrap();
        // Job state still reads, the task lookup now fails with a query error
        sqlx::query("DROP TABLE tasks")
            .execute(store.pool())
            .await
            .unwrap();

        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
        tick(&cfg, &backend, Some(&store), "owner/repo", None)
            .await
            .unwrap();

        let after = store
            .get_job_state("owner/repo", "nightly")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(after.active_task_id.as_deref(), Some("internal:1"));
        assert_eq!(after.last_run, None, "the job must not run again");
    }

    #[tokio::test]
    async fn tick_does_not_create_another_task_when_job_state_write_fails() {
        let tmp = tempdir().unwrap();
        let cfg = write_config(
            tmp.path(),
            r#"
jobs:
  - id: mail
    schedule: "* * * * *"
    sandbox: false
    task:
      title: Mail
      body: body
"#,
        );
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let repo = "issue-4228/lost-persist";
        store.fail_next_job_state_writes(8);

        tick_with_store(&cfg, &store, repo).await;

        let tasks = store.list_all_internal(repo).await.unwrap();
        assert_eq!(tasks.len(), 1, "first tick should create one task");
        let task_id = format!("internal:{}", tasks[0].id);
        let saved = store
            .get_job_state(repo, "mail")
            .await
            .unwrap()
            .expect("last_run written before execute");
        assert_eq!(
            saved.active_task_id, None,
            "the created id must not be in SQLite after the upsert failed"
        );
        assert!(
            sandbox_off_for(&store, repo, tmp.path(), &task_id).await,
            "sandbox:false must still match the created task"
        );

        let mut state = saved;
        let past = chrono::Utc::now() - chrono::Duration::minutes(2);
        state.last_run = Some(past.format("%Y-%m-%dT%H:%M:%SZ").to_string());
        store.upsert_job_state(&state).await.unwrap();

        tick_with_store(&cfg, &store, repo).await;

        let tasks = store.list_all_internal(repo).await.unwrap();
        assert_eq!(
            tasks.len(),
            1,
            "next period must not create another task while persist is outstanding"
        );
        assert!(sandbox_off_for(&store, repo, tmp.path(), &task_id).await);
    }

    /// Backend whose task has fixed labels, recording status moves and creates
    #[derive(Default)]
    struct RecordingBackend {
        labels: Vec<String>,
        pull: Option<PullRequestCompletion>,
        moves: Mutex<Vec<(String, Status)>>,
        creates: Mutex<u32>,
    }

    #[async_trait]
    impl TaskReader for RecordingBackend {
        async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
            let mut task = NoopBackend.get_task(id).await?;
            task.labels.clone_from(&self.labels);
            Ok(task)
        }

        async fn list_by_status(&self, _s: Status) -> anyhow::Result<Vec<ExternalTask>> {
            Ok(vec![])
        }
    }

    #[async_trait]
    impl TaskWriter for RecordingBackend {
        async fn create_task(
            &self,
            _t: &str,
            _b: &str,
            _l: &[String],
        ) -> anyhow::Result<ExternalId> {
            *self.creates.lock().unwrap() += 1;
            Ok(ExternalId("99".into()))
        }

        async fn set_labels(&self, _id: &ExternalId, _l: &[String]) -> anyhow::Result<()> {
            Ok(())
        }

        async fn remove_label(&self, _id: &ExternalId, _l: &str) -> anyhow::Result<()> {
            Ok(())
        }

        async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
            Ok(vec![])
        }

        async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
            self.moves.lock().unwrap().push((id.0.clone(), status));
            Ok(())
        }
    }

    #[async_trait]
    impl Conversation for RecordingBackend {
        async fn post_comment(&self, _id: &ExternalId, _b: &str) -> anyhow::Result<()> {
            Ok(())
        }
    }

    #[async_trait]
    impl MergeState for RecordingBackend {
        async fn pull_request_completion(
            &self,
            _repo: &str,
            _pr_number: i64,
        ) -> anyhow::Result<Option<PullRequestCompletion>> {
            Ok(self.pull.clone())
        }
    }

    #[async_trait]
    impl Tracker for RecordingBackend {
        fn name(&self) -> &'static str {
            "recording"
        }

        async fn health_check(&self) -> anyhow::Result<()> {
            Ok(())
        }
    }

    const TASK_JOB: &str = r#"
jobs:
  - id: weekly
    schedule: "* * * * *"
    task:
      title: Weekly
      body: body
"#;

    const EXTERNAL_TASK_JOB: &str = r#"
jobs:
  - id: weekly
    schedule: "* * * * *"
    external: true
    task:
      title: Weekly
      body: body
"#;

    /// An internal task of the job in `status`, recorded as its active task
    async fn job_task(store: &TaskStore, repo: &str, status: TaskStatus) -> i64 {
        let id = store
            .create_internal(repo, "Weekly", "body", "cron", "weekly", None)
            .await
            .unwrap();
        store.update_status(id, status).await.unwrap();
        let mut state = JobState::new(repo, "weekly");
        state.active_task_id = Some(format!("internal:{id}"));
        store.upsert_job_state(&state).await.unwrap();
        id
    }

    async fn job_state(store: &TaskStore, repo: &str) -> JobState {
        store.get_job_state(repo, "weekly").await.unwrap().unwrap()
    }

    #[tokio::test]
    async fn due_job_unblocks_its_blocked_internal_task() {
        let tmp = tempdir().unwrap();
        let cfg = write_config(tmp.path(), TASK_JOB);
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let repo = "owner/repo";
        let id = job_task(&store, repo, TaskStatus::Blocked).await;
        store.increment(id, "route_attempts").await.unwrap();
        store.increment(id, "attempts").await.unwrap();

        tick_with_store(&cfg, &store, repo).await;

        let task = store.get(id).await.unwrap();
        assert_eq!(task.status, TaskStatus::New);
        assert_eq!(task.route_attempts, 0);
        assert_eq!(task.attempts, 0);
        let state = job_state(&store, repo).await;
        assert_eq!(state.active_task_id, Some(format!("internal:{id}")));
        assert!(state.last_run.is_some());
        assert_eq!(state.last_task_status.as_deref(), Some("new"));
        assert_eq!(store.list_all_internal(repo).await.unwrap().len(), 1);
    }

    #[tokio::test]
    async fn due_job_moves_its_blocked_external_task_to_new() {
        let tmp = tempdir().unwrap();
        let cfg = write_config(tmp.path(), EXTERNAL_TASK_JOB);
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let repo = "owner/repo";
        let mut state = JobState::new(repo, "weekly");
        state.active_task_id = Some("42".to_string());
        store.upsert_job_state(&state).await.unwrap();
        let recording = Arc::new(RecordingBackend {
            labels: vec!["status:blocked".to_string()],
            ..RecordingBackend::default()
        });
        let backend: Arc<dyn ExternalBackend> = Arc::clone(&recording) as _;

        tick(&cfg, &backend, Some(&store), repo, None)
            .await
            .unwrap();

        assert_eq!(
            *recording.moves.lock().unwrap(),
            vec![("42".to_string(), Status::New)]
        );
        assert_eq!(*recording.creates.lock().unwrap(), 0);
        let state = job_state(&store, repo).await;
        assert_eq!(state.active_task_id.as_deref(), Some("42"));
        assert!(state.last_run.is_some());
    }

    #[tokio::test]
    async fn due_job_creates_a_task_when_the_blocked_task_pr_was_closed_unmerged() {
        let tmp = tempdir().unwrap();
        let cfg = write_config(tmp.path(), TASK_JOB);
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let repo = "owner/repo";
        let id = job_task(&store, repo, TaskStatus::Blocked).await;
        store
            .set_fields_silent(id, &[("pr_number", serde_json::json!(7))])
            .await
            .unwrap();
        let backend: Arc<dyn ExternalBackend> = Arc::new(RecordingBackend {
            pull: Some(PullRequestCompletion {
                merged: false,
                base_ref: "main".into(),
                default_branch: "main".into(),
                approved: false,
                closed: true,
            }),
            ..RecordingBackend::default()
        });

        tick(&cfg, &backend, Some(&store), repo, None)
            .await
            .unwrap();

        assert_eq!(store.get(id).await.unwrap().status, TaskStatus::Blocked);
        let tasks = store.list_all_internal(repo).await.unwrap();
        assert_eq!(tasks.len(), 2);
        let created = tasks.iter().find(|t| t.id != id).unwrap();
        assert_eq!(
            job_state(&store, repo).await.active_task_id,
            Some(format!("internal:{}", created.id))
        );
    }

    #[tokio::test]
    async fn due_job_leaves_a_blocked_task_with_an_open_dependency_waiting() {
        let tmp = tempdir().unwrap();
        let cfg = write_config(tmp.path(), TASK_JOB);
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let repo = "owner/repo";
        let id = job_task(&store, repo, TaskStatus::Blocked).await;
        store
            .replace_dependencies(
                id,
                &[NewDependency {
                    repo: repo.to_string(),
                    number: 9,
                    source: DepSource::Cli,
                }],
            )
            .await
            .unwrap();

        tick_with_store(&cfg, &store, repo).await;

        assert_eq!(store.get(id).await.unwrap().status, TaskStatus::Waiting);
        assert_eq!(store.list_all_internal(repo).await.unwrap().len(), 1);
        let state = job_state(&store, repo).await;
        assert_eq!(state.active_task_id, Some(format!("internal:{id}")));
        assert_eq!(state.last_task_status.as_deref(), Some("waiting"));
    }

    #[tokio::test]
    async fn job_not_due_leaves_its_blocked_task_alone() {
        let tmp = tempdir().unwrap();
        let cfg = write_config(tmp.path(), TASK_JOB);
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let repo = "owner/repo";
        let id = job_task(&store, repo, TaskStatus::Blocked).await;
        store.increment(id, "route_attempts").await.unwrap();
        let mut state = job_state(&store, repo).await;
        let ahead = chrono::Utc::now() + chrono::Duration::minutes(1);
        let last_run = ahead.format("%Y-%m-%dT%H:%M:%SZ").to_string();
        state.last_run = Some(last_run.clone());
        store.upsert_job_state(&state).await.unwrap();

        tick_with_store(&cfg, &store, repo).await;

        let task = store.get(id).await.unwrap();
        assert_eq!(task.status, TaskStatus::Blocked);
        assert_eq!(task.route_attempts, 1);
        assert_eq!(job_state(&store, repo).await.last_run, Some(last_run));
        assert_eq!(store.list_all_internal(repo).await.unwrap().len(), 1);
    }

    #[tokio::test]
    async fn due_job_creates_a_task_after_its_task_is_done() {
        let tmp = tempdir().unwrap();
        let cfg = write_config(tmp.path(), TASK_JOB);
        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let repo = "owner/repo";
        let id = job_task(&store, repo, TaskStatus::Done).await;

        tick_with_store(&cfg, &store, repo).await;

        let tasks = store.list_all_internal(repo).await.unwrap();
        assert_eq!(tasks.len(), 2);
        let created = tasks.iter().find(|t| t.id != id).unwrap();
        assert_eq!(created.status, TaskStatus::New);
        assert_eq!(
            job_state(&store, repo).await.active_task_id,
            Some(format!("internal:{}", created.id))
        );
    }

    #[test]
    fn not_found_error_ignores_a_404_inside_the_issue_number() {
        let transient = anyhow::anyhow!(
            "GitHub API GET https://api.github.com/repos/o/r/issues/1404 failed (500 Internal Server Error): boom"
        );
        assert!(!is_not_found_error(&transient));
        let missing = anyhow::anyhow!(
            "GitHub API GET https://api.github.com/repos/o/r/issues/1404 failed (404 Not Found): Not Found"
        );
        assert!(is_not_found_error(&missing));
    }
}