mahbot 0.11.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
//! Automation persistence and fire routing for the Assistant session: the
//! `add_automation` / `list_automations` / `remove_automation` tools and the periodic sweep that
//! routes due automations back into the Assistant's own session as user-role messages.
//!
//! An automation optionally carries a [`StoredTrigger`] — one custom tool plus its arguments —
//! which at fire time runs as the automation's owner in the owner's personal workspace, and only
//! what the check reported decides whether the Assistant is woken at all. A check stopped by its
//! time limit is not a verdict: nothing is delivered and the occurrence is retried after a
//! cool-down. Every other non-clean outcome is a broken check and takes the automation with it.
//! A check whose own process exited is judged by the status it gave, and a stored check that
//! cannot be read is a check that cannot run.

use std::collections::HashSet;
use std::fmt::Write as _;
use std::sync::LazyLock;
use std::time::Duration;

use anyhow::Context as _;
use anyhow::Result;
use chrono::{DateTime, Duration as ChronoDuration};

use crate::Workspace;
use crate::db;
use crate::tools::custom::CallRefusal;
use crate::tools::shell::ProgramOutcome;
use crate::util::UnwrapPoison;

crate::define_store! {
    pub(crate) static AUTOMATIONS: AutomationStore,
    expect = "AUTOMATIONS not initialized — call init_all_stores() first",
}

crate::columns! {
    AUTOMATION_COLUMNS [AUTOMATION] {
        ID                  => "id",
        SESSION_ID          => "session_id",
        USER_NAME           => "user_name",
        KIND                => "kind",
        TEXT                => "text",
        TRIGGER             => "trigger",
        ROLE                => "role",
        IDENTIFIER          => "identifier",
        WORKSPACE           => "workspace",
        INTERVAL_SECONDS    => "interval_seconds",
        NEXT_FIRE_AT        => "next_fire_at",
        UNFINISHED_ATTEMPTS => "unfinished_attempts",
    }
}

#[derive(Debug, Clone)]
pub(crate) struct Automation {
    pub id: String,
    pub session_id: String,
    /// The raw (un-escaped) user the automation belongs to.
    pub user_name: String,
    pub kind: String,
    pub text: String,
    pub trigger: Option<StoredTrigger>,
    pub role: Option<String>,
    pub identifier: Option<String>,
    /// The folder the role's launch runs in (a managed workspace name, a `personal:{user}` key,
    /// or an absolute path); `None` = the owner's personal folder.
    pub workspace: Option<String>,
    pub interval_seconds: Option<i64>,
    /// RFC3339 UTC next fire time: the moment the pending occurrence is due for. A retry never
    /// moves it.
    pub next_fire_at: String,
    /// Attempts in a row that did not finish in time; drives the one-time "not producing a
    /// result" notice and the LATE note of the report that finally arrives.
    pub unfinished_attempts: i64,
}

impl Automation {
    /// The automation's custom-role target as the listing surfaces show it, with the branch and
    /// folder only when recorded. `None` for an automation that wakes the Assistant.
    pub(crate) fn role_target(&self) -> Option<String> {
        let role = self.role.as_deref()?;
        let mut out = format!("addressed to custom role \"{role}\"");
        if let Some(identifier) = &self.identifier {
            let _ = write!(out, " (branch \"{identifier}\")");
        }
        if let Some(workspace) = &self.workspace {
            let _ = write!(out, " in {workspace}");
        }
        Some(out)
    }
}

/// The custom role an automation is addressed to (none wakes the Assistant, as before).
pub(crate) struct AutomationTarget {
    pub role: String,
    pub identifier: Option<String>,
    pub workspace: Option<String>,
}

/// An automation's trigger: one custom tool plus the arguments it receives.
///
/// The tool is named exactly as a `custom` call names it and must be one the owner can call; one
/// tool per automation — no chains. Arguments are stored as the tool's declared parameters,
/// already coerced to their declared types.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub(crate) struct Trigger {
    pub tool: String,
    /// Defaulted so a row written without the key still decodes; the product always stores it.
    #[serde(default)]
    pub args: serde_json::Map<String, serde_json::Value>,
}

impl Trigger {
    fn encode(&self) -> String {
        serde_json::to_string(self).expect("a trigger is always serializable")
    }

    /// The trigger as the assistant sees it — the tool's name and its arguments as compact
    /// JSON, nothing but the name when it has none.
    fn render(&self) -> String {
        if self.args.is_empty() {
            return self.tool.clone();
        }
        let args = serde_json::to_string(&self.args)
            .expect("a trigger's arguments are always serializable");
        format!("{} {args}", self.tool)
    }
}

/// The `trigger` column's content for one automation: the check that was stored there, or a
/// value that cannot be read as one. A stored check that cannot be read is a check that cannot
/// run — it wakes the assistant with the reason and takes the automation with it, rather than
/// quietly becoming a plain automation that keeps firing with its check dropped.
#[derive(Debug, Clone)]
pub(crate) enum StoredTrigger {
    /// The decoded check: the tool to run and the arguments it receives.
    Tool(Trigger),
    /// A value in the column that is not a stored check.
    Unreadable,
}

/// What the notice and the `<user-automations>` summary show in place of a stored check that
/// cannot be read.
const UNREADABLE_TRIGGER: &str = "(unreadable stored check)";

impl StoredTrigger {
    /// Decode a stored `trigger` column value. Only this module writes the column, so a value
    /// that does not decode is not a state the product produces — it reads as
    /// [`Self::Unreadable`] all the same, because the fire path's rule is about what can be read.
    fn decode(raw: &str) -> Self {
        match serde_json::from_str(raw) {
            Ok(trigger) => Self::Tool(trigger),
            Err(_) => Self::Unreadable,
        }
    }

    /// How a stored trigger is shown to the assistant — the confirmation when it is armed, the
    /// `list_automations` line and the `<user-automations>` summary: the tool's name followed by
    /// its arguments, nothing but the name when it has none, and a marker when there is nothing
    /// readable to show.
    pub(crate) fn render(&self) -> String {
        match self {
            Self::Tool(trigger) => trigger.render(),
            Self::Unreadable => UNREADABLE_TRIGGER.to_string(),
        }
    }

    /// The check's tool name alone — the automation card's headline — or the marker.
    pub(crate) fn name(&self) -> &str {
        match self {
            Self::Tool(trigger) => &trigger.tool,
            Self::Unreadable => UNREADABLE_TRIGGER,
        }
    }
}

fn automation_from_row(row: &db::Row) -> Result<Automation, ::turso::Error> {
    Ok(Automation {
        id: row.get(COL_AUTOMATION_ID)?,
        session_id: row.get(COL_AUTOMATION_SESSION_ID)?,
        user_name: row.get(COL_AUTOMATION_USER_NAME)?,
        kind: row.get(COL_AUTOMATION_KIND)?,
        text: row.get(COL_AUTOMATION_TEXT)?,
        trigger: stored_trigger(row)?,
        role: row.get(COL_AUTOMATION_ROLE)?,
        identifier: row.get(COL_AUTOMATION_IDENTIFIER)?,
        workspace: row.get(COL_AUTOMATION_WORKSPACE)?,
        interval_seconds: row.get(COL_AUTOMATION_INTERVAL_SECONDS)?,
        next_fire_at: row.get(COL_AUTOMATION_NEXT_FIRE_AT)?,
        unfinished_attempts: row.get(COL_AUTOMATION_UNFINISHED_ATTEMPTS)?,
    })
}

/// Read a row's `trigger` column: `None` when it is NULL, otherwise the stored check. Only text
/// can be the stored check this product writes, so anything else reads as
/// [`StoredTrigger::Unreadable`] — which must not fail the sweep or leave the automation firing
/// with its check dropped.
fn stored_trigger(row: &db::Row) -> Result<Option<StoredTrigger>, ::turso::Error> {
    match row.get_value(COL_AUTOMATION_TRIGGER)? {
        db::Value::Null => Ok(None),
        db::Value::Text(raw) => Ok(Some(StoredTrigger::decode(&raw))),
        _ => Ok(Some(StoredTrigger::Unreadable)),
    }
}

/// Maximum number of active automations allowed per session.
const MAX_ACTIVE_AUTOMATIONS: i64 = 50;

/// Upper bound on an automation's whole stored trigger, in characters. Keeps an over-large
/// trigger from bloating the notification envelope or the `<user-automations>` summary.
const MAX_AUTOMATION_TRIGGER_CHARS: usize = 2000;

/// Upper bound on a periodic interval (~292 years): keeps the total swept advance within a
/// representable [`DateTime`] range, so the O(1) periodic skip saturates instead of overflowing.
/// Also rejects absurd intervals as caller errors at creation.
const MAX_PERIOD_SECS: i64 = i64::MAX / 1_000_000_000;

/// The sweep's tick: how long the loop waits between passes. The first tick after start is also
/// the overdue scan.
const SWEEP_TICK: Duration = Duration::from_secs(1);

/// A firing later than its scheduled time by more than this is MISSED, and its notice says so:
/// 30 sweep ticks. One tick can overrun (its due batch is fired one automation at a time, each
/// with a durable write), so a firing past the bound did not come from a routine tick.
#[expect(clippy::cast_possible_wrap)] // 30 ticks fit i64 by many orders
const MISSED_FIRING_TOLERANCE: ChronoDuration =
    ChronoDuration::seconds(30 * SWEEP_TICK.as_secs() as i64);

/// Cool-down before an occurrence whose attempt did not finish in time is tried again: short
/// enough that a starved machine gets the check back quickly, long enough that retries cannot
/// pile up into a burst.
const RETRY_COOLDOWN_SECS: i64 = 60;

/// Consecutive attempts that did not finish in time before the assistant is told — once — that
/// the check is not producing a result.
const UNFINISHED_NOTICE_ATTEMPTS: i64 = 3;

/// Whether a firing at `now` was MISSED — the scheduled time had already passed by more than
/// [`MISSED_FIRING_TOLERANCE`] when it fired. `scheduled` is the time the firing belongs to: the
/// value as it stood before the state advance.
///
/// Fail-soft: a scheduled time that cannot be read as a time is not a missed firing, and neither
/// is one still in the future — a firing error would leave a due automation re-firing every tick.
fn is_missed_firing(now: &str, scheduled: &str) -> bool {
    let (Ok(now), Ok(scheduled)) = (
        db::parse_utc_timestamp(now),
        db::parse_utc_timestamp(scheduled),
    ) else {
        return false;
    };
    now.signed_duration_since(scheduled) > MISSED_FIRING_TOLERANCE
}

/// How the firing a notice belongs to was timed, as the notice says it.
enum Timing {
    /// On time: the occurrence fired when it was scheduled to.
    Due,
    /// Fired long after the automation was due — the product was not running then.
    Missed,
    /// Earlier attempts at this occurrence did not finish and the report that finally arrived
    /// is late for it.
    Late,
}

/// The opening line of the notices that carry the automation's own text: what the automation is
/// and how its firing was timed. Exactly one timing statement, so a report that arrives after
/// retries is announced as late instead of stacking a second lateness note. Every timing names
/// the occurrence's own due moment, which no retry moves.
fn automation_line(automation: &Automation, timing: &Timing) -> String {
    let asset = match timing {
        Timing::Due => "automation_due.md",
        Timing::Missed => "automation_missed.md",
        Timing::Late => "automation_late.md",
    };
    crate::prompt::substitute(
        &crate::prompt::load_prompt(asset),
        &[
            ("{{text}}", &automation.text),
            ("{{fire_at}}", &automation.next_fire_at),
        ],
    )
}

/// The timing a notice states. Only a report can be late: a report that settles
/// an occurrence whose earlier attempts did not finish says so instead of the
/// missed-firing note, and a broken check's notice reads as it always has.
fn trigger_timing(automation: &Automation, missed: bool, reported: bool) -> Timing {
    if reported && automation.unfinished_attempts > 0 {
        Timing::Late
    } else if missed {
        Timing::Missed
    } else {
        Timing::Due
    }
}

/// Format an RFC3339 timestamp for display as `"{local} local time ({utc} UTC)"`.
pub(crate) fn format_fire_time(timestamp: &str) -> Result<String> {
    let dt = DateTime::parse_from_rfc3339(timestamp)?;
    let local = dt
        .with_timezone(&chrono::Local)
        .format("%Y-%m-%d %H:%M:%S %Z");
    let utc = dt.with_timezone(&chrono::Utc).format("%Y-%m-%d %H:%M:%S");
    Ok(format!("{local} local time ({utc} UTC)"))
}

/// Validate an automation's optional custom-role target before it is stored: only the
/// administrator may address an automation to a custom role, the role must exist, the branch
/// identifier and folder must resolve to what will be stored, and a role-addressed automation's
/// text is the launch message — so it must not be empty and cannot carry a check. Returns the
/// role, branch identifier and folder address to store.
async fn validate_automation_target(
    user_name: &str,
    text: &str,
    target: Option<AutomationTarget>,
    has_trigger: bool,
) -> Result<(Option<String>, Option<String>, Option<String>)> {
    let Some(target) = target else {
        return Ok((None, None, None));
    };
    anyhow::ensure!(
        crate::users::is_admin_name(user_name),
        "usage: only the administrator may address an automation to a custom role"
    );
    anyhow::ensure!(
        crate::custom_role::get(&target.role).await?.is_some(),
        "no custom role named '{}'",
        target.role
    );
    let identifier = target
        .identifier
        .map(|id| id.trim().to_string())
        .filter(|id| !id.is_empty());
    if let Some(id) = &identifier {
        crate::custom_role::validate_identifier(id)?;
    }
    let workspace = match target
        .workspace
        .map(|w| w.trim().to_string())
        .filter(|w| !w.is_empty())
    {
        None => None,
        Some(raw) => Some(
            crate::launch::launch_workspace(Some(raw.as_str()))
                .await?
                .name,
        ),
    };
    anyhow::ensure!(
        !has_trigger,
        "usage: a role-addressed automation's text IS the role's launch message, so its \
         check cannot be combined with a role target"
    );
    anyhow::ensure!(
        !text.trim().is_empty(),
        "usage: a role-addressed automation's text is the role's launch message, so it must not be empty"
    );
    Ok((Some(target.role), identifier, workspace))
}

/// The session an automation call actually acts on: a custom-role caller's automations
/// live on the owner's Assistant session, the caller's own id otherwise.
/// A custom role runs at the owner's strength, and a plain automation it arms is still an owner
/// automation delivered to the assistant — so `add`/`list`/`remove` resolve the owner's assistant
/// session for such a caller, never the role's own branch (which would hold an automation it
/// could never see or cancel).
#[must_use]
pub(crate) fn owner_automation_session(agent_id: &str, user_name: &str) -> String {
    if crate::session::is_custom_role_agent_id(agent_id) {
        crate::session::assistant_agent_id(user_name)
    } else {
        agent_id.to_string()
    }
}

/// Create a new automation for a session.
///
/// Exactly one of `fire_at` (one-shot) or `interval_seconds` (periodic) must be provided.
/// One-shot fire times are normalized to RFC3339 UTC and must be in the future; periodic
/// intervals must be at least 5 seconds. At most [`MAX_ACTIVE_AUTOMATIONS`] active automations
/// may exist per session.
///
/// `target` addresses the automation to a custom role instead of the Assistant: only the
/// administrator may do that, the role must exist, and the automation carries no trigger — its
/// text IS the role's launch message.
pub(crate) async fn add_automation(
    session_id: &str,
    user_name: &str,
    text: &str,
    fire_at: Option<&str>,
    interval_seconds: Option<u64>,
    trigger: Option<Trigger>,
    target: Option<AutomationTarget>,
) -> Result<Automation> {
    // A role-addressed automation the owner's own Assistant never sees belongs on the
    // assistant's session: a custom role may hold the automation tools, but a plain automation
    // it arms is still an owner automation.
    let session_id = owner_automation_session(session_id, user_name);

    // Validate the target before touching the DB: a broken target must never be
    // armed. A role-addressed automation's text is the launch message, so a trigger
    // can never ride along and the text must be non-empty.
    let (role, identifier, workspace) =
        validate_automation_target(user_name, text, target, trigger.is_some()).await?;

    // Validate an optional trigger before touching the DB: the whole stored
    // trigger — the tool's name together with its arguments — is bounded.
    let encoded_trigger = trigger.as_ref().map(Trigger::encode);
    if let Some(encoded) = &encoded_trigger {
        anyhow::ensure!(
            encoded.chars().count() <= MAX_AUTOMATION_TRIGGER_CHARS,
            "Automation trigger too long: the stored trigger — the tool name plus its arguments as JSON — is limited to {MAX_AUTOMATION_TRIGGER_CHARS} characters; shorten the arguments"
        );
    }

    let normalized_fire_at = fire_at
        .map(|f| {
            db::parse_utc_timestamp(f)
                .map(|dt| dt.to_rfc3339())
                .with_context(|| format!("Invalid RFC3339/ISO-8601 fire time: {f} — pass a UTC timestamp like 2026-08-28T10:30:00Z"))
        })
        .transpose()?;

    let (kind, interval_secs, next_fire_at) = match (&normalized_fire_at, interval_seconds) {
        (Some(fire), None) => {
            anyhow::ensure!(
                db::parse_utc_timestamp(fire)? > db::parse_utc_timestamp(&db::now())?,
                "Cannot set an automation for a time in the past: pass a future RFC3339/ISO-8601 UTC time (convert the user's local time to UTC)"
            );
            ("one-shot", None, fire.clone())
        }
        (None, Some(interval)) => {
            anyhow::ensure!(
                interval >= 5,
                "Period must be at least 5 seconds: raise `interval_seconds`"
            );
            let interval_secs = i64::try_from(interval)
                .ok()
                .filter(|v| *v <= MAX_PERIOD_SECS)
                .with_context(|| "Period must be at most 292 years")?;
            // Periodic: first fire one interval from now (no immediate fire, no backlog
            // payout). An absurd interval saturates to a far-future time rather than panicking
            // on a DateTime overflow.
            let start = db::parse_utc_timestamp(&db::now())?;
            let next = start
                .checked_add_signed(ChronoDuration::seconds(interval_secs))
                .unwrap_or(DateTime::<chrono::Utc>::MAX_UTC);
            ("periodic", Some(interval_secs), next.to_rfc3339())
        }
        _ => anyhow::bail!(
            "Exactly one of fire_at or interval_seconds must be provided: pass `fire_at` for a one-shot automation or `interval_seconds` for a periodic one, never both"
        ),
    };

    let rows = store()
        .conn
        .query(
            "SELECT COUNT(*) FROM automations WHERE session_id = ?1 AND status = 'active'",
            db::params![session_id.as_str()],
        )
        .await?;
    let count: i64 = rows.first().map(|r| r.get(0)).transpose()?.unwrap_or(0);
    anyhow::ensure!(
        count < MAX_ACTIVE_AUTOMATIONS,
        "Automation limit reached (maximum {MAX_ACTIVE_AUTOMATIONS} active automations): remove one with `remove_automation` before adding another"
    );

    let id = crate::generate_id();
    let created_at = db::now();
    store()
        .conn
        .execute(
            "INSERT INTO automations \
             (id, session_id, user_name, kind, text, fire_at, interval_seconds, next_fire_at, status, created_at, trigger, role, identifier, workspace) \
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'active', ?9, ?10, ?11, ?12, ?13)",
            db::params![
                id.clone(),
                session_id.as_str(),
                user_name,
                kind,
                text,
                normalized_fire_at.clone(),
                interval_secs,
                next_fire_at.clone(),
                created_at.clone(),
                encoded_trigger.clone(),
                role.clone(),
                identifier.clone(),
                workspace.clone(),
            ],
        )
        .await?;

    Ok(Automation {
        id,
        session_id,
        user_name: user_name.to_string(),
        kind: kind.to_string(),
        text: text.to_string(),
        trigger: trigger.map(StoredTrigger::Tool),
        role,
        identifier,
        workspace,
        interval_seconds: interval_secs,
        next_fire_at,
        unfinished_attempts: 0,
    })
}

pub(crate) async fn list_automations(session_id: &str) -> Result<Vec<Automation>> {
    let sql = format!(
        "SELECT {AUTOMATION_COLUMNS} FROM automations \
         WHERE session_id = ?1 AND status = 'active' \
         ORDER BY next_fire_at ASC"
    );
    let rows = store().conn.query(&sql, db::params![session_id]).await?;
    Ok(rows
        .iter()
        .map(automation_from_row)
        .collect::<Result<_, _>>()?)
}

/// List the active automations for a user across all their sessions, ordered by next fire time
/// — the user-wide view backing the Assistant's system-prompt automation snapshot.
pub(crate) async fn list_user_automations(user_name: &str) -> Result<Vec<Automation>> {
    let sql = format!(
        "SELECT {AUTOMATION_COLUMNS} FROM automations \
         WHERE user_name = ?1 AND status = 'active' \
         ORDER BY next_fire_at ASC"
    );
    let rows = store().conn.query(&sql, db::params![user_name]).await?;
    Ok(rows
        .iter()
        .map(automation_from_row)
        .collect::<Result<_, _>>()?)
}

/// Every active automation of every owner, ordered by owner name, then next fire time, then id
/// — the read backing the automations page. The id settles ties, so rows sharing an owner and a
/// fire time keep the same order from read to read.
pub(crate) async fn list_all_active_automations() -> Result<Vec<Automation>> {
    let sql = format!(
        "SELECT {AUTOMATION_COLUMNS} FROM automations \
         WHERE status = 'active' \
         ORDER BY user_name ASC, next_fire_at ASC, id ASC"
    );
    let rows = store().conn.query(&sql, db::params![]).await?;
    Ok(rows
        .iter()
        .map(automation_from_row)
        .collect::<Result<_, _>>()?)
}

pub(crate) async fn remove_automation(session_id: &str, id: &str) -> Result<Option<Automation>> {
    let sql = format!(
        "SELECT {AUTOMATION_COLUMNS} FROM automations \
         WHERE id = ?1 AND session_id = ?2 AND status = 'active'"
    );
    let rows = store()
        .conn
        .query(&sql, db::params![id, session_id])
        .await?;
    let Some(row) = rows.first() else {
        return Ok(None);
    };
    let automation = automation_from_row(row)?;
    // The SELECT and the UPDATE are separate statements, so a concurrent second removal can
    // pass the SELECT too and report it twice; the UPDATE is idempotent, so the duplicate report
    // is not a wrong outcome.
    store()
        .conn
        .execute(
            "UPDATE automations SET status = 'removed' WHERE id = ?1 AND session_id = ?2",
            db::params![id, session_id],
        )
        .await?;
    Ok(Some(automation))
}

/// Mark every ACTIVE automation addressed to `role_name` as `'removed'`; returns the number
/// changed.
#[expect(clippy::cast_possible_truncation)] // u64 row count fits usize on all supported targets
pub(crate) async fn delete_automations_for_role(role_name: &str) -> Result<usize> {
    let changed = store()
        .conn
        .execute(
            "UPDATE automations SET status = 'removed' WHERE role = ?1 AND status = 'active'",
            db::params![role_name],
        )
        .await?;
    Ok(changed as usize)
}

/// Soft-delete an automation regardless of its status (idempotent). Unlike
/// [`remove_automation`] this has no `status = 'active'` gate, so it also deletes an
/// already-fired one-shot. Used whenever a check is broken — a run that failed and one that
/// could not run alike, never one that merely ran past its time limit.
async fn delete_automation_after_run(automation: &Automation) -> Result<()> {
    store()
        .conn
        .execute(
            "UPDATE automations SET status = 'removed' WHERE id = ?1 AND session_id = ?2",
            db::params![automation.id.as_str(), automation.session_id.as_str()],
        )
        .await?;
    Ok(())
}

/// The due automations at `now`, ordered by next fire time: every occurrence that is due and
/// whose retry cool-down, if it is waiting for one, has passed. A waiting automation is not due
/// before its `retry_at`, and no other automation's wait holds it back.
///
/// The read and each automation's later state advance are separate statements, so a second sweep
/// overlapping this one can fire the same automation twice; a triggered automation's attempt slot
/// ([`claim_attempt_slot`]) makes a repeated firing of the same occurrence a no-op.
async fn due_automations(now: &str) -> Result<Vec<Automation>> {
    let sql = format!(
        "SELECT {AUTOMATION_COLUMNS} FROM automations \
         WHERE status = 'active' AND next_fire_at <= ?1 \
         AND (retry_at IS NULL OR retry_at <= ?1) \
         ORDER BY next_fire_at ASC"
    );
    let rows = store().conn.query(&sql, db::params![now]).await?;
    Ok(rows
        .iter()
        .map(automation_from_row)
        .collect::<Result<_, _>>()?)
}

/// Route a due automation into the Assistant's own session and settle it.
///
/// A role-addressed automation wakes that custom role instead; the Assistant wakes otherwise — a
/// triggered automation takes its attempt slot and runs its custom tool (see
/// [`fire_trigger_automation`]); a plain one delivers its text as the notice. The notice is a
/// user-role message into the calling assistant's own session (`automation.session_id`, resolved
/// directly — never re-derived from the id, which would double-escape colliding user names). A
/// plain or role-addressed one-shot is terminalized (`status='fired'`) and a periodic one advances
/// `next_fire_at` past every missed whole period.
async fn fire_automation(automation: &Automation) -> Result<()> {
    if automation.role.is_some() {
        return fire_custom_role_automation(automation).await;
    }
    // Judged at the firing instant — the scheduled time before the firing moves anything —
    // never when the notice is composed: a slow check, or a notice delivered late although the
    // firing was on time, is not a missed firing.
    let missed = is_missed_firing(&db::now(), &automation.next_fire_at);
    match &automation.trigger {
        Some(trigger) => {
            fire_trigger_automation(automation, trigger, missed);
            Ok(())
        }
        None => fire_plain_automation(automation, missed).await,
    }
}

/// Wake the custom role an automation is addressed to, with the automation's text as the launch
/// message. A role that has since been deleted removes the automation and tells the owner through
/// his Assistant: a broken automation must never keep firing. A store failure is not a verdict
/// about the role — the automation stays armed and the next sweep retries.
///
/// Any other launch failure of a ONE-SHOT automation is terminal: it is removed and the owner is
/// told why. A PERIODIC automation instead advances its state like a completed fire and stays
/// armed, so a transient failure loses no automation and retries at its next scheduled time.
async fn fire_custom_role_automation(automation: &Automation) -> Result<()> {
    let role = automation.role.as_deref().unwrap_or_default();
    let (reason, removed) = if crate::custom_role::get(role).await?.is_none() {
        ("the custom role no longer exists".to_string(), true)
    } else {
        // The launch runs in the folder the automation was armed for; one that no longer
        // resolves is a launch failure like any other.
        let launched = async {
            let workspace =
                crate::launch::launch_workspace(automation.workspace.as_deref()).await?;
            crate::launch::custom_role(
                role,
                &automation.text,
                automation.identifier.as_deref(),
                &workspace,
                crate::agent::message_router::AnsweredFor::Nobody,
            )
            .await
        }
        .await;
        match launched {
            Ok(_) => {
                // The launch is already persisted durably before it is routed (see
                // `launch::custom_role`), so the state advance runs after, as on the plain path.
                advance_automation_state(automation, &db::now()).await?;
                return Ok(());
            }
            Err(e) if crate::db::is_store_error(&e) => {
                // A store failure says nothing about the role: leave the automation armed and let
                // the next sweep retry, instead of disarming a working one on a transient error.
                tracing::warn!(
                    automation = %automation.id,
                    role = %role,
                    error = %e,
                    "Store failure launching a custom-role automation — automation left armed"
                );
                return Err(e);
            }
            Err(e) => {
                tracing::warn!(
                    automation = %automation.id,
                    role = %role,
                    error = %e,
                    "Failed to launch a custom role automation"
                );
                if automation.kind == "one-shot" {
                    (e.to_string(), true)
                } else {
                    // A periodic automation must survive a transient launch failure: advance
                    // its state like a completed fire so it retries at its next scheduled time
                    // instead of every sweep tick.
                    advance_automation_state(automation, &db::now()).await?;
                    (e.to_string(), false)
                }
            }
        }
    };
    if removed {
        delete_automation_after_run(automation).await?;
    }
    let workspace_line = match &automation.workspace {
        Some(workspace) => format!(" in {workspace}"),
        None => String::new(),
    };
    let outcome = if removed {
        "The automation was removed."
    } else {
        "The automation stays armed and will fire again at its next scheduled time."
    };
    let content = crate::prompt::substitute(
        &crate::prompt::load_prompt("automation_role_notification.md"),
        &[
            ("{{text}}", &automation.text),
            ("{{role}}", role),
            ("{{workspace_line}}", &workspace_line),
            ("{{reason}}", &reason),
            ("{{outcome}}", outcome),
        ],
    );
    deliver_automation_notification(automation, content).await;
    Ok(())
}

/// Deliver a plain (untriggered) automation notice and advance its state. The durable envelope
/// is persisted BEFORE advancing state (see [`deliver_automation_notification`]): a crash between
/// the two replays the notice at boot and leaves the automation due, so it is never lost.
async fn fire_plain_automation(automation: &Automation, missed: bool) -> Result<()> {
    let now = db::now();
    let content = crate::prompt::substitute(
        &crate::prompt::load_prompt("automation_notification.md"),
        &[(
            "{{automation_line}}",
            &automation_line(automation, &trigger_timing(automation, missed, false)),
        )],
    );
    deliver_automation_notification(automation, content).await;
    advance_automation_state(automation, &now).await?;
    Ok(())
}

/// Deliver an automation's notice into the calling assistant's session, logging a lost durable
/// copy against the automation it came from.
///
/// Delivery is sourced from the stored raw user and session id, so the notice targets the right
/// personal session regardless of agent-ID escaping.
async fn deliver_automation_notification(automation: &Automation, content: String) {
    if let Err(e) = crate::agent::message_router::deliver_assistant_notice(
        &automation.session_id,
        &automation.user_name,
        content,
    )
    .await
    {
        tracing::warn!(
            automation = %automation.id,
            error = %e,
            "Failed to persist automation delivery — routing best-effort"
        );
    }
}

/// Advance an automation's stored state past `now`: one-shot → `status='fired'`; periodic →
/// `next_fire_at` past every missed whole period, so a schedule that waited out retries resumes
/// on its own grid instead of replaying them. The retry state goes with it: the attempt that got
/// here completed. Both writes take an active row only, so an automation removed while its check
/// ran stays removed.
async fn advance_automation_state(automation: &Automation, now: &str) -> Result<()> {
    if automation.kind == "one-shot" {
        store()
            .conn
            .execute(
                "UPDATE automations SET status = 'fired', retry_at = NULL, unfinished_attempts = 0 \
                 WHERE id = ?1 AND status = 'active'",
                db::params![automation.id.as_str()],
            )
            .await?;
    } else {
        let next = next_periodic_fire(
            now,
            &automation.next_fire_at,
            periodic_interval(automation)?,
        )?;
        store()
            .conn
            .execute(
                "UPDATE automations SET next_fire_at = ?1, retry_at = NULL, unfinished_attempts = 0 \
                 WHERE id = ?2 AND status = 'active'",
                db::params![next, automation.id.as_str()],
            )
            .await?;
    }
    Ok(())
}

/// The interval a periodic automation advances by, refusing a stored row with no valid one.
fn periodic_interval(automation: &Automation) -> Result<i64> {
    let interval = automation.interval_seconds.unwrap_or(0);
    anyhow::ensure!(
        interval > 0,
        "Periodic automation {} has no valid interval",
        automation.id
    );
    Ok(interval)
}

/// Automations whose check is running in this process, keyed by id — the guard keeping one
/// attempt at a time.
static ATTEMPTS_IN_FLIGHT: LazyLock<std::sync::Mutex<HashSet<String>>> =
    LazyLock::new(|| std::sync::Mutex::new(HashSet::new()));

/// Take the automation's one in-process attempt slot. `None` while a previous attempt is still
/// running; the returned slot frees it on drop, including when a spawned task is dropped
/// unpolled, because the slot is taken before the spawn. Nothing here is durable: a restarted
/// process has no attempt in flight, so the automation is simply due again.
fn claim_attempt_slot(automation_id: &str) -> Option<AttemptSlot> {
    let inserted = ATTEMPTS_IN_FLIGHT
        .lock()
        .unwrap_poison()
        .insert(automation_id.to_string());
    inserted.then(|| AttemptSlot(automation_id.to_string()))
}

fn attempt_in_flight(automation_id: &str) -> bool {
    ATTEMPTS_IN_FLIGHT
        .lock()
        .unwrap_poison()
        .contains(automation_id)
}

struct AttemptSlot(String);

impl Drop for AttemptSlot {
    fn drop(&mut self) {
        ATTEMPTS_IN_FLIGHT.lock().unwrap_poison().remove(&self.0);
    }
}

/// Fire a triggered automation: take its attempt slot and spawn a detached task that runs the
/// stored check and settles the attempt.
///
/// The slot is taken before the spawn, so however slow the check is — and whether or not the task
/// is ever polled — the sweep cannot start a second attempt for the same automation. The rest of
/// the sweep is unaffected: a waiting automation holds back nothing but itself.
///
/// `missed` is the firing's lateness, decided before the check starts: how long the check itself
/// takes is not lateness.
fn fire_trigger_automation(automation: &Automation, trigger: &StoredTrigger, missed: bool) {
    let Some(slot) = claim_attempt_slot(&automation.id) else {
        return;
    };
    tokio::spawn(run_automation_trigger_task(
        slot,
        automation.clone(),
        trigger.clone(),
        missed,
    ));
}

/// What one trigger evaluation produced, as the notification and the automation's state see it.
enum TriggerOutcome {
    /// The check ran and reported nothing at all — the automation stays armed, nothing is
    /// delivered.
    Silent,
    /// The check ran and reported something: the run's own outcome.
    Ran(ProgramOutcome),
    /// The check could not run at all: the reason the assistant is shown.
    CouldNotRun(String),
    /// The check was still running when its time limit stopped it: not a verdict about the
    /// check, so nothing is delivered and the occurrence stays pending.
    Unfinished,
}

impl TriggerOutcome {
    /// The wake decision over one finished run: only a clean run that reported nothing stays
    /// silent. Everything else wakes the assistant — except a run the ceiling stopped, which the
    /// retry rule settles.
    fn from_run(outcome: ProgramOutcome) -> Self {
        if outcome.timed_out() {
            return Self::Unfinished;
        }
        if outcome.success && !outcome.has_output {
            Self::Silent
        } else {
            Self::Ran(outcome)
        }
    }
}

/// Run one trigger: resolve the named custom tool for the automation's owner — the same
/// availability rule, catalogue lookup and argument contract a normal `custom` call applies, with
/// arguments the tool does not declare refused rather than ignored — then run it in the owner's
/// personal workspace through the managed runtime.
///
/// The run's own outcome alone drives the verdict ([`TriggerOutcome::from_run`]).
async fn run_trigger(ws: &Workspace, user: &str, trigger: &Trigger) -> TriggerOutcome {
    let call =
        match crate::tools::custom::resolve_tool_call(user, &trigger.tool, &trigger.args, true)
            .await
        {
            Ok(call) => call,
            Err(CallRefusal::Unavailable { .. }) => {
                return TriggerOutcome::CouldNotRun(format!(
                    "the custom tool \"{}\" is no longer available to you",
                    trigger.tool
                ));
            }
            Err(CallRefusal::Name { .. } | CallRefusal::NotUsable { .. }) => {
                return TriggerOutcome::CouldNotRun(format!(
                    "the custom tool \"{}\" is no longer usable",
                    trigger.tool
                ));
            }
            Err(CallRefusal::Arguments(e)) => {
                return TriggerOutcome::CouldNotRun(format!(
                    "the stored arguments no longer fit \"{}\" — {e}",
                    trigger.tool
                ));
            }
        };

    let Some(bun) = crate::tools::bun::bun_binary_path() else {
        return TriggerOutcome::CouldNotRun("the managed bun runtime is unavailable".to_string());
    };
    TriggerOutcome::from_run(
        crate::tools::shell::run_program_outcome(
            ws.as_path(),
            &bun,
            &[call.path.display().to_string(), call.payload()],
        )
        .await,
    )
}

/// Run a triggered automation's stored check in the owner's personal workspace and settle the
/// attempt (see [`settle_trigger_attempt`]). The slot is held until this task finishes.
async fn run_automation_trigger_task(
    _slot: AttemptSlot,
    automation: Automation,
    trigger: StoredTrigger,
    missed: bool,
) {
    let outcome = match &trigger {
        StoredTrigger::Tool(check) => {
            let ws = crate::users::personal_workspace_struct(&automation.user_name);
            run_trigger(&ws, &automation.user_name, check).await
        }
        // A stored check that cannot be read is a check that cannot run: nothing is run, and
        // the reason goes to the assistant with the automation.
        StoredTrigger::Unreadable => {
            TriggerOutcome::CouldNotRun("the stored check cannot be read".to_string())
        }
    };

    if let Err(e) = settle_trigger_attempt(&automation, &trigger, outcome, missed).await {
        // The occurrence is untouched: its due time stands and no cool-down was set, so the
        // next sweep runs the check again.
        tracing::warn!(automation = %automation.id, error = %e, "Failed to settle an automation check");
    }
}

/// Settle one finished attempt against its automation. A check that reported — or ran cleanly and
/// said nothing — delivers what it produced and lets the automation resume its normal schedule. A
/// broken check soft-deletes the automation and delivers why. An attempt that did not finish in
/// time delivers nothing and keeps the occurrence pending.
async fn settle_trigger_attempt(
    automation: &Automation,
    trigger: &StoredTrigger,
    outcome: TriggerOutcome,
    missed: bool,
) -> Result<()> {
    match &outcome {
        TriggerOutcome::Unfinished => return defer_trigger_attempt(automation, trigger).await,
        TriggerOutcome::Silent | TriggerOutcome::Ran(ProgramOutcome { success: true, .. }) => {}
        TriggerOutcome::Ran(_) | TriggerOutcome::CouldNotRun(_) => {
            // Track whether the delete actually committed — the notification must not claim a
            // deletion that didn't happen.
            let deletion = delete_automation_after_run(automation).await;
            if let Some(content) =
                trigger_notification(automation, trigger, &outcome, Some(&deletion), missed)
            {
                deliver_automation_notification(automation, content).await;
            }
            // A deletion that did not commit leaves the automation due, so the broken check would
            // notify on every sweep. Advancing bounds it to one more firing per occurrence.
            if deletion.is_err() {
                advance_automation_state(automation, &db::now()).await?;
            }
            return Ok(());
        }
    }
    // Delivered before the state advance, so a crash in between replays the report rather than
    // losing it.
    if let Some(content) = trigger_notification(automation, trigger, &outcome, None, missed) {
        deliver_automation_notification(automation, content).await;
    }
    advance_automation_state(automation, &db::now()).await
}

/// Keep the occurrence pending after an attempt that did not finish in time: nothing is
/// delivered, the check is retried after the cool-down, and the third attempt in a row says once
/// that the check is not producing a result.
///
/// `next_fire_at` is left alone — it is the occurrence's own due moment, which a late report is
/// announced with — so the wait lives in `retry_at`. The write is guarded on the occurrence the
/// attempt ran for, so a concurrent reschedule is never overwritten.
async fn defer_trigger_attempt(automation: &Automation, trigger: &StoredTrigger) -> Result<()> {
    let attempt = automation.unfinished_attempts + 1;
    let retry_at = (db::parse_utc_timestamp(&db::now())?
        + ChronoDuration::seconds(RETRY_COOLDOWN_SECS))
    .to_rfc3339();
    let changed = store()
        .conn
        .execute(
            "UPDATE automations SET retry_at = ?1, unfinished_attempts = ?2 \
             WHERE id = ?3 AND session_id = ?4 AND status = 'active' AND next_fire_at = ?5",
            db::params![
                retry_at,
                attempt,
                automation.id.as_str(),
                automation.session_id.as_str(),
                automation.next_fire_at.as_str(),
            ],
        )
        .await?;
    if changed == 0 {
        return Ok(());
    }
    // The counter is what makes the notice one-time, so it is written before the notice goes
    // out: a crash in the gap loses one notice rather than repeating it.
    if attempt == UNFINISHED_NOTICE_ATTEMPTS {
        let content = crate::prompt::substitute(
            &crate::prompt::load_prompt("automation_trigger_unfinished.md"),
            &[
                ("{{text}}", &automation.text),
                ("{{trigger}}", &trigger.render()),
            ],
        );
        deliver_automation_notification(automation, content).await;
    }
    Ok(())
}

/// Decide the delivery for a finished trigger evaluation: `None` stays silent (the check reported
/// nothing, or did not finish in time); `Some` is the rendered `<automation-notification>` with the
/// automation's text, the trigger, the status line, the deletion note and the check's output.
/// `deletion` carries the result of [`delete_automation_after_run`], `None` when none was
/// attempted; `missed` is the firing's lateness.
fn trigger_notification(
    automation: &Automation,
    trigger: &StoredTrigger,
    outcome: &TriggerOutcome,
    deletion: Option<&Result<()>>,
    missed: bool,
) -> Option<String> {
    let (status, output) = match outcome {
        TriggerOutcome::Silent | TriggerOutcome::Unfinished => return None,
        TriggerOutcome::Ran(outcome) => {
            let status = if outcome.success {
                format!("The check exited successfully ({}).", outcome.detail)
            } else {
                format!("The check FAILED ({}).", outcome.detail)
            };
            let shown = if !outcome.output.is_empty() {
                crate::util::truncate_sandwich(
                    &outcome.output,
                    crate::util::TOOL_OUTPUT_BUDGET_BYTES,
                    "check output",
                )
            } else if outcome.has_output {
                // Escape-only output: reported, so it woke the assistant, but nothing readable
                // survives the ANSI strip — the notice must not call that "no output".
                "(output was not printable)".to_string()
            } else {
                "(no output)".to_string()
            };
            (status, format!("\n\n{shown}"))
        }
        TriggerOutcome::CouldNotRun(reason) => {
            (format!("The check could not run: {reason}."), String::new())
        }
    };
    let deletion_line = match deletion {
        None => String::new(),
        Some(Ok(())) => crate::prompt::load_prompt("automation_trigger_deletion.md"),
        Some(Err(_)) => crate::prompt::load_prompt("automation_trigger_deletion_failed.md"),
    };
    // Only a delivered result can be late for its occurrence — a broken check's notice reads
    // as it always has.
    let reported = matches!(outcome, TriggerOutcome::Ran(run) if run.success);
    let timing = trigger_timing(automation, missed, reported);
    Some(crate::prompt::substitute(
        &crate::prompt::load_prompt("automation_trigger_notification.md"),
        &[
            ("{{automation_line}}", &automation_line(automation, &timing)),
            ("{{trigger}}", &trigger.render()),
            ("{{trigger_status}}", &status),
            ("{{trigger_deletion}}", &deletion_line),
            ("{{trigger_output}}", &output),
        ],
    ))
}

/// Compute the next fire time for a periodic automation: advance `next_fire` past
/// `now` by whole periods (O(1), saturating on overflow). Never loops over
/// downtime and never panics on an absurd interval.
fn next_periodic_fire(now: &str, next_fire: &str, interval_secs: i64) -> Result<String> {
    let now_dt = db::parse_utc_timestamp(now)?;
    let next = db::parse_utc_timestamp(next_fire)?;
    let elapsed = now_dt.signed_duration_since(next).num_seconds();
    let to_skip = elapsed.div_euclid(interval_secs).saturating_add(1);
    // Cap the single advance (interval × skipped periods) so it stays within a
    // representable DateTime range and cannot overflow/panic the sweep.
    let add_secs = interval_secs.saturating_mul(to_skip).min(MAX_PERIOD_SECS);
    let next = next
        .checked_add_signed(ChronoDuration::seconds(add_secs))
        .unwrap_or(DateTime::<chrono::Utc>::MAX_UTC);
    Ok(next.to_rfc3339())
}

/// The automations a sweep pass may start, up to `batch_limit`: those due and not
/// already running here. A running check is skipped before the batch is cut, so
/// a long check never takes a slot from a waiting automation; the automation's own slot
/// ([`claim_attempt_slot`]) stays the authority on never starting twice.
fn startable(due: Vec<Automation>, batch_limit: usize) -> Vec<Automation> {
    due.into_iter()
        .filter(|automation| !attempt_in_flight(&automation.id))
        .take(batch_limit)
        .collect()
}

/// Fire up to `batch_limit` due automations, continuing past individual failures so
/// one bad automation cannot block the rest of the sweep.
async fn run_automation_sweep(batch_limit: usize) -> Result<()> {
    let due = startable(due_automations(&db::now()).await?, batch_limit);
    let mut fired = 0usize;
    let mut failed = 0usize;
    for automation in due {
        match fire_automation(&automation).await {
            Ok(()) => fired += 1,
            Err(e) => {
                failed += 1;
                tracing::warn!(automation = %automation.id, error = %e, "Failed to fire automation");
            }
        }
    }
    if fired > 0 || failed > 0 {
        tracing::debug!(fired, failed, "automation sweep complete");
    }
    Ok(())
}

/// Cancellable automation-sweep loop: sleep, then fire due automations on each tick.
/// The first tick acts as the boot-time overdue scan.
pub async fn run_automation_sweep_loop() {
    loop {
        if !crate::shutdown::sleep_or_shutdown_or_drain(SWEEP_TICK).await {
            break;
        }
        if let Err(e) = run_automation_sweep(50).await {
            tracing::warn!(error = %e, "automation sweep failed");
        }
    }
}

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

    /// A firing is MISSED only when it lands well past its scheduled time: a
    /// routine tick's own delay never counts, and a scheduled time that cannot
    /// be read is not a miss either — that would fail the firing of an automation
    /// that stays due, re-firing it every tick.
    #[test]
    fn missed_firing_needs_a_firing_far_past_its_scheduled_time() {
        let scheduled = "2026-09-04T12:00:00+00:00";
        assert!(!is_missed_firing("2026-09-04T12:00:00+00:00", scheduled));
        assert!(!is_missed_firing("2026-09-04T12:00:05+00:00", scheduled));
        assert!(!is_missed_firing("2026-09-04T12:00:30+00:00", scheduled));
        assert!(
            is_missed_firing("2026-09-04T12:01:00+00:00", scheduled),
            "a firing a minute late is past the tolerance"
        );
        assert!(
            is_missed_firing("2026-09-04T23:00:00+00:00", scheduled),
            "an overnight gap must be reported as missed"
        );
        assert!(!is_missed_firing("2026-09-04T12:00:00+00:00", "not-a-time"));
        assert!(!is_missed_firing("2026-09-04T11:00:00+00:00", scheduled));
    }

    /// The opening line is what the notice says about its own timing: today's
    /// wording when the firing happened on time, the missed statement with the
    /// scheduled time when it fired late, and the late statement — one of the
    /// two, never both — naming the occurrence when a retried check finally reported.
    #[test]
    fn automation_line_states_exactly_one_timing() {
        let automation = trigger_automation();
        assert_eq!(
            automation_line(&automation, &Timing::Due),
            "Your automation \"check the thing\" is due now \
             (scheduled for 2026-09-04T12:00:00+00:00)."
        );
        let missed = automation_line(&automation, &Timing::Missed);
        assert!(missed.contains("was MISSED"), "got: {missed}");
        assert!(
            missed.contains("2026-09-04T12:00:00+00:00"),
            "the scheduled time must be named: {missed}"
        );
        assert!(
            missed.contains("Tell the user"),
            "the assistant must be told to pass it on: {missed}"
        );
        assert!(
            !missed.contains("due now"),
            "a missed firing must not read as current: {missed}"
        );

        let due_at = "2026-09-04T12:00:00+00:00";
        let late = automation_line(&automation, &Timing::Late);
        assert!(late.contains("LATE"), "got: {late}");
        assert!(
            late.contains(due_at),
            "the moment it was due for must be named: {late}"
        );
        assert!(
            !late.contains("MISSED") && !late.contains("due now"),
            "a late report is one statement, not a stack of lateness: {late}"
        );
    }

    /// The sweep's one-step advance: 25s past a 10s-periodic fire lands on the
    /// next whole period (not per-period looping, so long downtime costs one
    /// step), and an interval near `i64::MAX` saturates to a far-future fire time
    /// instead of panicking the sweep on a `DateTime` add.
    #[test]
    fn next_periodic_fire_advances_in_one_step_and_saturates_absurd_interval() {
        let out = next_periodic_fire("2026-08-28T00:00:25Z", "2026-08-28T00:00:00Z", 10).unwrap();
        assert_eq!(out, "2026-08-28T00:00:30+00:00");

        let out =
            next_periodic_fire("2026-08-28T00:00:00Z", "2026-08-28T00:00:00Z", i64::MAX).unwrap();
        let parsed = db::parse_utc_timestamp(&out).unwrap();
        assert!(
            parsed > db::parse_utc_timestamp("2026-08-28T00:00:00Z").unwrap(),
            "advance must move past now, got {out}"
        );
    }

    #[tokio::test]
    async fn add_automation_rejects_past_one_shot() {
        let err = add_automation(
            "session-a",
            "alice",
            "remind me",
            Some("2020-01-01T00:00:00Z"),
            None,
            None,
            None,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("past"), "got: {err}");
    }

    /// The periodic interval is bounded at both ends: below the floor is refused,
    /// and so is one no `DateTime` can add.
    #[tokio::test]
    async fn add_automation_bounds_the_periodic_interval() {
        let err = add_automation("session-a", "alice", "remind me", None, Some(4), None, None)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("at least 5 seconds"), "got: {err}");

        let err = add_automation(
            "session-a",
            "alice",
            "remind me",
            None,
            Some(u64::MAX),
            None,
            None,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("at most 292 years"), "got: {err}");
    }

    #[tokio::test]
    async fn add_automation_requires_exactly_one_of_fire_at_or_interval() {
        // Neither provided.
        let err = add_automation("session-a", "alice", "remind me", None, None, None, None)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("Exactly one"), "got: {err}");

        // Both provided.
        let err = add_automation(
            "session-a",
            "alice",
            "remind me",
            Some("2099-01-01T00:00:00Z"),
            Some(60),
            None,
            None,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("Exactly one"), "got: {err}");
    }

    #[tokio::test]
    async fn add_automation_enforces_active_cap() {
        crate::util::test::init_test_stores().await;
        let session = "cap-session";
        for i in 0..MAX_ACTIVE_AUTOMATIONS {
            let fire = format!("2099-01-01T00:00:{i:02}Z");
            add_automation(
                session,
                "alice",
                &format!("automation {i}"),
                Some(&fire),
                None,
                None,
                None,
            )
            .await
            .unwrap();
        }
        let err = add_automation(
            session,
            "alice",
            "one too many",
            Some("2099-01-01T00:01:00Z"),
            None,
            None,
            None,
        )
        .await
        .unwrap_err();
        assert!(
            err.to_string()
                .contains(&format!("maximum {MAX_ACTIVE_AUTOMATIONS}")),
            "got: {err}"
        );
    }

    /// A trigger's args, as the map `json!` builds for them.
    fn args_of(value: &serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
        value.as_object().cloned().unwrap_or_default()
    }

    /// The stored trigger — the tool's name together with its arguments — is
    /// bounded as a whole, so a short-name/over-long-args trigger and a
    /// long-name/empty-args one are both refused.
    #[tokio::test]
    async fn add_automation_rejects_overlong_trigger() {
        crate::util::test::init_test_stores().await;
        let overlong = |trigger: Trigger| async move {
            add_automation(
                "session-a",
                "alice",
                "remind me",
                Some("2099-01-01T00:00:00Z"),
                None,
                Some(trigger),
                None,
            )
            .await
            .unwrap_err()
            .to_string()
        };

        let err = overlong(Trigger {
            tool: "weather".to_string(),
            args: args_of(
                &serde_json::json!({ "city": "x".repeat(MAX_AUTOMATION_TRIGGER_CHARS + 1) }),
            ),
        })
        .await;
        assert!(err.contains("too long"), "got: {err}");

        // The name counts too: these arguments alone are far inside the bound.
        let err = overlong(Trigger {
            tool: "x".repeat(MAX_AUTOMATION_TRIGGER_CHARS),
            args: args_of(&serde_json::json!({ "city": "Minsk" })),
        })
        .await;
        assert!(err.contains("too long"), "got: {err}");
    }

    fn weather_trigger() -> Trigger {
        let mut args = serde_json::Map::new();
        args.insert("city".to_string(), serde_json::json!("Minsk"));
        Trigger {
            tool: "weather".to_string(),
            args,
        }
    }

    fn trigger_automation() -> Automation {
        Automation {
            id: "automation-trigger".to_string(),
            session_id: "assistant:alice".to_string(),
            user_name: "alice".to_string(),
            kind: "periodic".to_string(),
            text: "check the thing".to_string(),
            trigger: Some(StoredTrigger::Tool(weather_trigger())),
            role: None,
            identifier: None,
            workspace: None,
            interval_seconds: Some(60),
            next_fire_at: "2026-09-04T12:00:00+00:00".to_string(),
            unfinished_attempts: 0,
        }
    }

    /// A finished run as the wake decision and the notice see it: `output` is
    /// what survives the ANSI strip, `has_output` what the raw streams emitted.
    fn ran(success: bool, detail: &str, output: &str, has_output: bool) -> ProgramOutcome {
        ProgramOutcome {
            success,
            detail: detail.to_string(),
            output: output.to_string(),
            has_output,
            stop: None,
        }
    }

    /// One notice per outcome, and every notch of its wording: a clean run's success line with
    /// its output and today's due-now line, escape-only output reported as reported, a check that
    /// could not run with its reason and the deletion note, and a late firing announced as missed
    /// on every outcome a firing produces.
    #[test]
    fn trigger_notification_renders_each_outcome() {
        let automation = trigger_automation();
        let trigger = StoredTrigger::Tool(weather_trigger());

        let content = trigger_notification(
            &automation,
            &trigger,
            &TriggerOutcome::Ran(ran(true, "exit status 0", "all good", true)),
            None,
            false,
        )
        .unwrap();
        assert!(content.contains("<automation-notification>"));
        assert!(content.contains("check the thing"));
        assert!(content.contains("weather {\"city\":\"Minsk\"}"));
        assert!(content.contains("exited successfully (exit status 0)"));
        assert!(content.contains("all good"));
        assert!(
            !content.contains("DELETED"),
            "clean path must not report a deletion"
        );
        assert!(
            content.contains("is due now (scheduled for 2026-09-04T12:00:00+00:00)."),
            "a firing on time keeps today's wording: {content}"
        );

        // Output that strips away to nothing is still reported, so the notice must not label
        // it "no output".
        let content = trigger_notification(
            &automation,
            &trigger,
            &TriggerOutcome::Ran(ran(true, "exit status 0", "", true)),
            None,
            false,
        )
        .unwrap();
        assert!(content.contains("not printable"), "got: {content}");
        assert!(!content.contains("(no output)"), "got: {content}");

        let content = trigger_notification(
            &automation,
            &trigger,
            &TriggerOutcome::CouldNotRun("the custom tool \"weather\" is no longer usable".into()),
            Some(&Ok(())),
            false,
        )
        .unwrap();
        assert!(
            content.contains("no longer usable"),
            "the reason must reach the assistant: {content}"
        );
        assert!(content.contains("weather {\"city\":\"Minsk\"}"));
        assert!(content.contains("DELETED"), "got: {content}");
        assert!(
            !content.contains("FAILED"),
            "a check that never ran did not fail: {content}"
        );

        for outcome in [
            TriggerOutcome::Ran(ran(true, "exit status 0", "all good", true)),
            TriggerOutcome::Ran(ran(false, "exit status 2", "boom", true)),
            TriggerOutcome::CouldNotRun("the managed bun runtime is unavailable".to_string()),
        ] {
            let content =
                trigger_notification(&automation, &trigger, &outcome, None, true).unwrap();
            assert!(content.contains("was MISSED"), "got: {content}");
            assert!(
                content.contains("2026-09-04T12:00:00+00:00"),
                "got: {content}"
            );
            assert!(!content.contains("due now"), "got: {content}");
        }
    }

    /// The reversal the trigger exists for: only a clean run that reported nothing stays silent.
    #[test]
    fn wake_decision_reads_only_whether_the_run_reported_anything() {
        let silent = |outcome| matches!(outcome, TriggerOutcome::Silent);
        assert!(
            silent(TriggerOutcome::from_run(ran(
                true,
                "exit status 0",
                "",
                false
            ))),
            "a clean run that said nothing must not wake"
        );
        // Any output wakes — including output that merely resembles a credential.
        assert!(!silent(TriggerOutcome::from_run(ran(
            true,
            "exit status 0",
            "key: sk-live-1234",
            true
        ))));
        assert!(!silent(TriggerOutcome::from_run(ran(
            true,
            "exit status 0",
            "",
            true
        ))));
        assert!(!silent(TriggerOutcome::from_run(ran(
            false,
            "exit status 2",
            "",
            false
        ))));
    }

    /// A broken check's notice reads as it always has, even when it settles an occurrence that
    /// waited through retries: no lateness note. Only a delivered result can be late, and the
    /// moment it names is the occurrence's own scheduled time, never the retry instant.
    #[test]
    fn a_broken_check_after_retries_is_not_late_and_names_its_scheduled_time() {
        let automation = Automation {
            unfinished_attempts: 3,
            ..trigger_automation()
        };
        let trigger = StoredTrigger::Tool(weather_trigger());
        for outcome in [
            TriggerOutcome::Ran(ran(false, "exit status 2", "boom", true)),
            TriggerOutcome::CouldNotRun("the managed bun runtime is unavailable".to_string()),
        ] {
            let content =
                trigger_notification(&automation, &trigger, &outcome, Some(&Ok(())), true)
                    .expect("a broken check always notifies");
            assert!(!content.contains("LATE"), "got: {content}");
            assert!(
                content.contains("was MISSED — it was scheduled for 2026-09-04T12:00:00+00:00"),
                "the occurrence's own scheduled time must be named: {content}"
            );
        }
    }

    /// A failed check always wakes, empty output included, and the notice
    /// reports whether the automation was actually removed.
    #[test]
    fn trigger_notification_wakes_on_failure_and_reports_the_deletion_outcome() {
        let automation = trigger_automation();
        let trigger = StoredTrigger::Tool(weather_trigger());
        let outcome = TriggerOutcome::Ran(ran(false, "exit status 2", "", false));

        let deleted =
            trigger_notification(&automation, &trigger, &outcome, Some(&Ok(())), false).unwrap();
        assert!(deleted.contains("FAILED (exit status 2)"), "got: {deleted}");
        assert!(deleted.contains("(no output)"), "got: {deleted}");
        assert!(deleted.contains("DELETED"), "got: {deleted}");

        let failed = trigger_notification(
            &automation,
            &trigger,
            &outcome,
            Some(&Err(anyhow::anyhow!("db down"))),
            false,
        )
        .unwrap();
        assert!(failed.contains("FAILED"), "got: {failed}");
        assert!(failed.contains("delete"), "got: {failed}");
        assert!(
            !failed.contains("was DELETED"),
            "must not claim a successful deletion: {failed}"
        );
    }

    /// An automations row's status, for the fire-time assertions that a non-clean
    /// check took the automation out of service.
    async fn automation_status(id: &str) -> String {
        store()
            .conn
            .query(
                "SELECT status FROM automations WHERE id = ?1",
                db::params![id],
            )
            .await
            .unwrap()
            .first()
            .map(|r| r.get(0))
            .transpose()
            .unwrap()
            .expect("automation row must exist")
    }

    /// The moment the automation's retried occurrence may run, `None` when nothing
    /// is waiting — read straight from the row, as the sweep's own filter is.
    async fn automation_retry_at(id: &str) -> Option<String> {
        store()
            .conn
            .query(
                "SELECT retry_at FROM automations WHERE id = ?1",
                db::params![id],
            )
            .await
            .unwrap()
            .first()
            .map(|row| row.get::<Option<String>>(0))
            .transpose()
            .unwrap()
            .flatten()
    }

    /// The row as the next sweep would read it.
    async fn active_automation(session_id: &str, id: &str) -> Automation {
        list_automations(session_id)
            .await
            .unwrap()
            .into_iter()
            .find(|automation| automation.id == id)
            .expect("an active automation row")
    }

    async fn is_due(id: &str) -> bool {
        due_automations(&db::now())
            .await
            .unwrap()
            .iter()
            .any(|automation| automation.id == id)
    }

    fn seconds_from_now(timestamp: &str) -> i64 {
        db::parse_utc_timestamp(timestamp)
            .unwrap()
            .signed_duration_since(db::parse_utc_timestamp(&db::now()).unwrap())
            .num_seconds()
    }

    /// Make the automation's occurrence overdue, as a sweep's read would find it.
    async fn make_overdue(id: &str) {
        store()
            .conn
            .execute(
                "UPDATE automations SET next_fire_at = ?1 WHERE id = ?2",
                db::params!["2020-01-01T00:00:00+00:00", id],
            )
            .await
            .unwrap();
    }

    /// One attempt at a time, and a waiting automation holds back nothing but itself:
    /// an automation whose check is running has no second attempt, a deferred
    /// occurrence is not due before its cool-down, and every other automation keeps
    /// firing at its own due time meanwhile.
    #[tokio::test]
    async fn one_attempt_at_a_time_and_a_waiting_automation_waits_only_for_itself() {
        let session = "assistant:automation-one-attempt-it";
        let (waiting, _rx) = arm_trigger_automation(
            session,
            "automation-waiting",
            "no_such_automation_tool",
            serde_json::Map::new(),
        )
        .await;
        let neighbour = add_automation(
            session,
            "automation-neighbour",
            "the other check",
            None,
            Some(3600),
            Some(weather_trigger()),
            None,
        )
        .await
        .expect("arm a second triggered automation");
        make_overdue(&waiting.id).await;
        make_overdue(&neighbour.id).await;
        assert!(
            is_due(&waiting.id).await && is_due(&neighbour.id).await,
            "both occurrences are due"
        );

        // The attempt in flight holds the automation's only slot: a second one never
        // starts, however long the check runs.
        let slot =
            claim_attempt_slot(&waiting.id).expect("the attempt takes the automation's slot");
        assert!(
            claim_attempt_slot(&waiting.id).is_none(),
            "a second attempt of the same automation must not start"
        );
        drop(slot);

        let due = active_automation(session, &waiting.id).await;
        settle_trigger_attempt(
            &due,
            &StoredTrigger::Tool(weather_trigger()),
            TriggerOutcome::Unfinished,
            false,
        )
        .await
        .unwrap();
        let deferred = active_automation(session, &waiting.id).await;
        let retry_at = automation_retry_at(&waiting.id)
            .await
            .expect("a wait is recorded");
        let retry_in = seconds_from_now(&retry_at);
        assert!(
            (50..=70).contains(&retry_in),
            "the retry must be about a minute out, got {retry_in}s"
        );
        assert_eq!(
            deferred.next_fire_at, due.next_fire_at,
            "the wait never moves the occurrence's own due moment"
        );
        assert!(
            !is_due(&waiting.id).await,
            "a waiting automation is not due before its retry"
        );
        assert!(
            is_due(&neighbour.id).await,
            "a waiting automation must not hold back the others"
        );

        // Once the cool-down has passed the occurrence is due again — with no
        // state but the row's, so a restart in between changes nothing.
        store()
            .conn
            .execute(
                "UPDATE automations SET retry_at = ?1 WHERE id = ?2",
                db::params!["2020-01-01T00:00:00+00:00", waiting.id.as_str()],
            )
            .await
            .unwrap();
        assert!(
            is_due(&waiting.id).await,
            "the retry becomes due when its cool-down passes"
        );
        crate::agent::message_router::unregister_agent(session);
    }

    /// The whole chain, from a program the ceiling really stops to the notice
    /// the retry finally produces: the stop keeps the automation (nothing delivered,
    /// a retry about a minute out, the occurrence's own due moment intact) and
    /// the report of the later attempt arrives late, naming that moment.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_check_stopped_by_its_ceiling_keeps_the_automation_and_its_report_is_late() {
        let session = "assistant:automation-ceiling-it";
        let (automation, mut rx) = arm_trigger_automation(
            session,
            "automation-ceiling",
            "no_such_automation_tool",
            serde_json::Map::new(),
        )
        .await;
        let due_at = automation.next_fire_at.clone();
        let trigger = StoredTrigger::Tool(weather_trigger());
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let ws = crate::workspace::test_ws(tmp.path());

        let stopped = crate::tools::shell::run_program_outcome_within(
            ws.as_path(),
            std::path::Path::new("/bin/sh"),
            &["-c".to_string(), "echo started; sleep 30".to_string()],
            Duration::from_secs(1),
        )
        .await;
        assert!(
            stopped.timed_out(),
            "the one-second ceiling must stop the run"
        );
        settle_trigger_attempt(
            &automation,
            &trigger,
            TriggerOutcome::from_run(stopped),
            false,
        )
        .await
        .unwrap();

        assert!(
            rx.try_recv().is_err(),
            "nothing is delivered for an attempt that did not finish"
        );
        // A restart between the two attempts keeps everything the report needs:
        // the wait lives in the row read back here, and a fresh process has no
        // attempt in flight.
        assert!(
            !attempt_in_flight(&automation.id),
            "a restarted process has no attempt in flight"
        );
        let waiting = active_automation(session, &automation.id).await;
        assert_eq!(
            automation_status(&automation.id).await,
            "active",
            "a one-shot whose check did not finish is not consumed"
        );
        assert_eq!(waiting.unfinished_attempts, 1);
        assert_eq!(waiting.next_fire_at, due_at);
        assert!(
            seconds_from_now(
                &automation_retry_at(&automation.id)
                    .await
                    .expect("a wait is recorded")
            ) > 0,
            "the occurrence is kept and its retry is scheduled"
        );

        // The retry reports: one notification, late, for the occurrence's own
        // due moment. A retried firing is past the missed-firing tolerance too,
        // so the two lateness statements must not stack.
        settle_trigger_attempt(
            &waiting,
            &trigger,
            TriggerOutcome::Ran(ran(true, "exit status 0", "found it", true)),
            true,
        )
        .await
        .unwrap();
        let job = rx.try_recv().expect("the late report must be delivered");
        assert!(job.content.contains("LATE"), "got: {}", job.content);
        assert!(
            !job.content.contains("MISSED"),
            "one lateness statement, not two: {}",
            job.content
        );
        assert!(
            job.content.contains(&due_at),
            "the moment it was due for must be named: {}",
            job.content
        );
        assert!(job.content.contains("found it"));
        crate::agent::message_router::unregister_agent(session);
    }

    /// A failed run is a broken check, not a check that did not finish: it
    /// removes the automation, says FAILED, and leaves nothing due to re-fire.
    #[tokio::test]
    async fn a_failed_check_removes_the_automation_and_never_refires() {
        let session = "assistant:automation-failed-it";
        let (automation, mut rx) = arm_trigger_automation(
            session,
            "automation-failed",
            "no_such_automation_tool",
            serde_json::Map::new(),
        )
        .await;
        make_overdue(&automation.id).await;
        let due = active_automation(session, &automation.id).await;

        settle_trigger_attempt(
            &due,
            &StoredTrigger::Tool(weather_trigger()),
            TriggerOutcome::Ran(ran(false, "exit status 2", "boom", true)),
            false,
        )
        .await
        .unwrap();

        let job = rx.try_recv().expect("a broken check must notify");
        assert!(
            job.content.contains("FAILED (exit status 2)"),
            "got: {}",
            job.content
        );
        assert!(job.content.contains("DELETED"), "got: {}", job.content);
        assert_eq!(automation_status(&automation.id).await, "removed");
        assert!(
            !is_due(&automation.id).await,
            "a broken check must never re-fire"
        );
        crate::agent::message_router::unregister_agent(session);
    }

    /// A sweep pass skips an automation whose check is already running before it cuts
    /// its batch, so a long check never takes a slot from a waiting automation; the
    /// automation's own slot stays the authority on not starting twice.
    #[test]
    fn a_running_check_does_not_take_a_sweep_slot() {
        let running = Automation {
            id: "automation-slot-running".to_string(),
            ..trigger_automation()
        };
        let waiting = Automation {
            id: "automation-slot-waiting".to_string(),
            ..trigger_automation()
        };
        let slot = claim_attempt_slot(&running.id).expect("the running check holds its slot");

        let picked = startable(vec![running.clone(), waiting.clone()], 1);
        assert_eq!(picked.len(), 1, "the batch keeps its full size");
        assert_eq!(
            picked[0].id, waiting.id,
            "the running check is skipped, not counted"
        );
        assert!(
            !attempt_in_flight(&waiting.id),
            "picking an automation takes no slot; its firing does"
        );
        drop(slot);
    }

    /// Three attempts in a row that did not finish wake the assistant once, with
    /// a notice that says the check is not producing a result — and the automation
    /// keeps being retried without repeating the notice until an attempt
    /// completes, which starts the count over.
    #[tokio::test]
    async fn three_unfinished_attempts_notify_once_and_the_automation_keeps_retrying() {
        let session = "assistant:automation-stuck-it";
        let trigger = StoredTrigger::Tool(weather_trigger());
        let mut automation =
            arm_periodic_trigger_automation(session, "automation-stuck", 3600).await;
        let mut rx = crate::agent::message_router::register_agent(session);

        for attempt in 1..=4 {
            settle_trigger_attempt(&automation, &trigger, TriggerOutcome::Unfinished, false)
                .await
                .unwrap();
            automation = active_automation(session, &automation.id).await;
            assert_eq!(automation.unfinished_attempts, attempt);
            if attempt == UNFINISHED_NOTICE_ATTEMPTS {
                let job = rx
                    .try_recv()
                    .expect("the third unfinished attempt must notify");
                assert!(
                    job.content.contains("not producing a result"),
                    "got: {}",
                    job.content
                );
                assert!(
                    !job.content.contains("DELETED"),
                    "this is not the deletion notice: {}",
                    job.content
                );
            } else {
                assert!(rx.try_recv().is_err(), "attempt {attempt} must stay silent");
            }
        }
        assert_eq!(
            automation_status(&automation.id).await,
            "active",
            "a check that never finishes never removes its automation"
        );

        // A completing attempt clears the count, so the notice needs three more
        // unfinished attempts in a row and does not fire again before that.
        settle_trigger_attempt(&automation, &trigger, TriggerOutcome::Silent, false)
            .await
            .unwrap();
        automation = active_automation(session, &automation.id).await;
        assert_eq!(automation.unfinished_attempts, 0);
        assert!(
            automation_retry_at(&automation.id).await.is_none(),
            "a completed check leaves no wait"
        );
        for attempt in 1..UNFINISHED_NOTICE_ATTEMPTS {
            settle_trigger_attempt(&automation, &trigger, TriggerOutcome::Unfinished, false)
                .await
                .unwrap();
            automation = active_automation(session, &automation.id).await;
            assert_eq!(
                automation.unfinished_attempts, attempt,
                "the count restarted"
            );
            assert!(
                rx.try_recv().is_err(),
                "the count restarted, so no notice arrives yet"
            );
        }
        crate::agent::message_router::unregister_agent(session);
    }

    /// A periodic automation whose check completes resumes its normal schedule from
    /// the occurrence the retries settled: no burst of the occurrences missed
    /// while it waited, and no stale retry state left behind.
    #[tokio::test]
    async fn a_completed_check_resumes_the_periodic_schedule() {
        let session = "assistant:automation-resume-it";
        let automation = arm_periodic_trigger_automation(session, "automation-resume", 60).await;
        let mut rx = crate::agent::message_router::register_agent(session);
        let trigger = StoredTrigger::Tool(weather_trigger());
        // Long overdue, as an occurrence that waited out retries is: the resume
        // has to advance past every period missed meanwhile in one step.
        make_overdue(&automation.id).await;
        let due = active_automation(session, &automation.id).await;
        let due_at = due.next_fire_at.clone();

        settle_trigger_attempt(&due, &trigger, TriggerOutcome::Unfinished, false)
            .await
            .unwrap();
        let retry = active_automation(session, &automation.id).await;
        assert!(
            automation_retry_at(&automation.id).await.is_some(),
            "a waiting automation records the retry it owes"
        );
        settle_trigger_attempt(&retry, &trigger, TriggerOutcome::Silent, false)
            .await
            .unwrap();

        let resumed = active_automation(session, &automation.id).await;
        assert!(automation_retry_at(&automation.id).await.is_none());
        assert_eq!(resumed.unfinished_attempts, 0);
        let next_in = seconds_from_now(&resumed.next_fire_at);
        assert!(
            (0..=60).contains(&next_in),
            "the next occurrence is one period out at most, got {next_in}s"
        );
        let due = db::parse_utc_timestamp(&due_at).unwrap();
        let next = db::parse_utc_timestamp(&resumed.next_fire_at).unwrap();
        assert_eq!(
            next.signed_duration_since(due).num_seconds() % 60,
            0,
            "the schedule resumes on its own grid: {} from {due_at}",
            resumed.next_fire_at
        );
        assert!(
            rx.try_recv().is_err(),
            "a silent check must not wake the assistant"
        );
        crate::agent::message_router::unregister_agent(session);
    }

    /// Arm a periodic trigger automation for `owner`, firing every `period_secs`,
    /// under the agent `session_id`.
    async fn arm_periodic_trigger_automation(
        session_id: &str,
        owner: &str,
        period_secs: u64,
    ) -> Automation {
        seed_owner(owner).await;
        add_automation(
            session_id,
            owner,
            "poll the thing",
            None,
            Some(period_secs),
            Some(weather_trigger()),
            None,
        )
        .await
        .expect("arm a periodic trigger automation")
    }

    /// Arm one one-shot trigger automation for `owner` under the agent `session_id`
    /// and return it with the receiver its notification will be routed to.
    async fn arm_trigger_automation(
        session_id: &str,
        owner: &str,
        tool: &str,
        args: serde_json::Map<String, serde_json::Value>,
    ) -> (
        Automation,
        tokio::sync::mpsc::UnboundedReceiver<crate::agent::message_router::AgentJob>,
    ) {
        seed_owner(owner).await;
        let rx = crate::agent::message_router::register_agent(session_id);
        let automation = add_automation(
            session_id,
            owner,
            "poll the thing",
            Some("2099-01-01T00:00:00Z"),
            None,
            Some(Trigger {
                tool: tool.to_string(),
                args,
            }),
            None,
        )
        .await
        .expect("arm the trigger automation");
        (automation, rx)
    }

    /// The initialized user store with a row for `name`: availability is settled
    /// against it, so every automation owner needs one.
    async fn seed_owner(name: &str) -> &'static crate::users::UserStore {
        crate::util::test::init_management_test_stores().await;
        let store = crate::users::USER_STORE
            .get()
            .expect("user store initialized");
        store.add_user(name).await.unwrap();
        store
    }

    /// Write `name.ts` into the catalogue folder the tests read (the admin's
    /// `shared/`), removed again when the guard drops.
    fn catalogue_probe(name: &str, header: &str) -> ProbeFile {
        let dir =
            crate::users::personal_workspace_path(crate::users::ADMIN_USER_NAME).join("shared");
        std::fs::create_dir_all(&dir).expect("create the shared folder");
        let probe = ProbeFile(dir.join(format!("{name}.ts")));
        std::fs::write(&probe.0, header).expect("write the probe tool");
        probe
    }

    /// Fire `automation`, wait for the notification the assistant must receive, and
    /// assert the automation was taken out of service. Returns the notification.
    async fn fire_and_collect_notification(
        automation: &Automation,
        session_id: &str,
        rx: &mut tokio::sync::mpsc::UnboundedReceiver<crate::agent::message_router::AgentJob>,
    ) -> String {
        fire_automation(automation).await.unwrap();
        let job = tokio::time::timeout(std::time::Duration::from_secs(30), rx.recv())
            .await
            .expect("check resolution must finish in time")
            .expect("a check that could not run must notify");
        crate::agent::message_router::unregister_agent(session_id);
        assert!(job.content.contains("DELETED"), "got: {}", job.content);
        assert_eq!(
            automation_status(&automation.id).await,
            "removed",
            "a check that cannot run must not re-fire"
        );
        job.content
    }

    /// Fire-time integration: a plain automation routes its notice into the
    /// assistant's session and terminalizes the one-shot.
    #[tokio::test]
    async fn fire_plain_automation_delivers_its_text_and_terminalizes_the_one_shot() {
        crate::util::test::init_management_test_stores().await;
        // A registered receiver captures the routed job deterministically —
        // no consumer loop (and no agent run) is spawned.
        let mut rx = crate::agent::message_router::register_agent("assistant:automation-plain-it");
        let automation = add_automation(
            "assistant:automation-plain-it",
            "automation-plain",
            "check the deploy",
            Some("2099-01-01T00:00:00Z"),
            None,
            None,
            None,
        )
        .await
        .unwrap();

        fire_automation(&automation).await.unwrap();

        let job = rx.recv().await.expect("plain automation notice must route");
        assert!(job.content.contains("<automation-notification>"));
        assert!(job.content.contains("check the deploy"));
        assert!(
            !job.content.contains("MISSED"),
            "a firing on time must not claim it was missed: {}",
            job.content
        );
        crate::agent::message_router::unregister_agent("assistant:automation-plain-it");

        assert_eq!(
            automation_status(&automation.id).await,
            "fired",
            "one-shot must be terminalized"
        );
    }

    /// Fire-time integration: an automation the sweep reaches long after its
    /// scheduled time — a start after the product was down, a machine that was
    /// suspended — reaches the user as missed, naming the occurrence that was
    /// due rather than the next one the state advance has already written.
    #[tokio::test]
    async fn fire_late_automation_says_the_firing_was_missed() {
        crate::util::test::init_management_test_stores().await;
        let session = "assistant:automation-late-it";
        let mut rx = crate::agent::message_router::register_agent(session);
        let automation = add_automation(
            session,
            "automation-late",
            "check the deploy",
            None,
            Some(3600),
            None,
            None,
        )
        .await
        .unwrap();
        // Make it due with its scheduled time long past, and fire the row the
        // sweep's own read selects.
        store()
            .conn
            .execute(
                "UPDATE automations SET next_fire_at = ?1 WHERE id = ?2",
                db::params!["2020-01-01T00:00:00Z", automation.id.as_str()],
            )
            .await
            .unwrap();
        let due = due_automations(&db::now()).await.unwrap();
        let stored = due
            .iter()
            .find(|candidate| candidate.id == automation.id)
            .expect("the automation must be due");

        fire_automation(stored).await.unwrap();

        let job = rx.recv().await.expect("late automation notice must route");
        crate::agent::message_router::unregister_agent(session);
        assert!(
            job.content
                .contains("scheduled for 2020-01-01T00:00:00Z, which had already passed"),
            "the occurrence that was missed must be the one named: {}",
            job.content
        );
        assert_eq!(
            automation_status(&automation.id).await,
            "active",
            "a periodic automation survives its firing"
        );
    }

    /// A role target with no branch and no workspace.
    fn role_target(role: &str) -> AutomationTarget {
        AutomationTarget {
            role: role.to_string(),
            identifier: None,
            workspace: None,
        }
    }

    /// The refusal from arming a role-addressed automation under `user`.
    async fn try_arm_role(user: &str, role: &str, trigger: Option<Trigger>) -> String {
        add_automation(
            "assistant:role-target-it",
            user,
            "run it",
            Some("2099-01-01T00:00:00Z"),
            None,
            trigger,
            Some(role_target(role)),
        )
        .await
        .unwrap_err()
        .to_string()
    }

    /// Arming a role-addressed automation fails closed: only the admin may address a
    /// role, the role must exist, and the automation's text (the role's launch
    /// message) cannot also carry a trigger.
    #[tokio::test]
    async fn add_automation_validates_a_role_target_before_storing_it() {
        crate::util::test::init_test_stores().await;

        let err = try_arm_role("alice", "analyst", None).await;
        assert!(err.contains("only the administrator"), "got: {err}");

        let err = try_arm_role(crate::users::ADMIN_USER_NAME, "no_such_role", None).await;
        assert!(
            err.contains("no custom role named 'no_such_role'"),
            "got: {err}"
        );

        crate::custom_role::create(
            "automation_role_probe",
            "do it",
            &[],
            crate::custom_role::CustomRoleBehavior::Continuous,
        )
        .await
        .unwrap();
        let err = try_arm_role(
            crate::users::ADMIN_USER_NAME,
            "automation_role_probe",
            Some(weather_trigger()),
        )
        .await;
        assert!(
            err.contains("cannot be combined with a role target"),
            "got: {err}"
        );
    }

    /// Fire-time integration: an automation addressed to a custom role launches that
    /// role's branch with the automation's text as its launch message, then
    /// terminalizes the one-shot.
    #[tokio::test]
    async fn fire_role_automation_launches_the_role_and_terminalizes_the_automation() {
        crate::util::test::init_management_test_stores().await;
        crate::custom_role::create(
            "automation_runner",
            "do the thing",
            &[],
            crate::custom_role::CustomRoleBehavior::Continuous,
        )
        .await
        .unwrap();
        let automation = add_automation(
            &crate::session::assistant_agent_id(crate::users::ADMIN_USER_NAME),
            crate::users::ADMIN_USER_NAME,
            "run the runner",
            Some("2099-01-01T00:00:00Z"),
            None,
            None,
            Some(role_target("automation_runner")),
        )
        .await
        .unwrap();

        let branch = crate::session::custom_role_agent_id("automation_runner", None);
        let mut rx = crate::agent::message_router::register_agent(&branch);
        fire_automation(&automation).await.unwrap();
        let job = rx
            .recv()
            .await
            .expect("the role's branch must receive the launch message");
        crate::agent::message_router::unregister_agent(&branch);
        assert_eq!(job.content, "run the runner");
        assert_eq!(
            automation_status(&automation.id).await,
            "fired",
            "one-shot must be terminalized"
        );
    }

    /// Fire-time integration: a role deleted after arming takes its automation with
    /// it — the owner is told through his Assistant and the automation is removed.
    #[tokio::test]
    async fn fire_role_automation_reports_a_deleted_role_and_removes_the_automation() {
        crate::util::test::init_management_test_stores().await;
        crate::custom_role::create(
            "automation_vanishing",
            "do the thing",
            &[],
            crate::custom_role::CustomRoleBehavior::Continuous,
        )
        .await
        .unwrap();
        let automation = add_automation(
            &crate::session::assistant_agent_id(crate::users::ADMIN_USER_NAME),
            crate::users::ADMIN_USER_NAME,
            "wake the role",
            Some("2099-01-01T00:00:00Z"),
            None,
            None,
            Some(role_target("automation_vanishing")),
        )
        .await
        .unwrap();
        // Remove the record out of band, leaving the armed automation behind.
        crate::custom_role::CUSTOM_ROLES
            .get()
            .expect("custom role store")
            .conn
            .execute(
                "DELETE FROM custom_roles WHERE name = ?1",
                db::params!["automation_vanishing"],
            )
            .await
            .unwrap();

        let mut rx = crate::agent::message_router::register_agent(&automation.session_id);
        fire_automation(&automation).await.unwrap();
        let job = rx.recv().await.expect("the owner must be told");
        crate::agent::message_router::unregister_agent(&automation.session_id);
        assert!(job.content.contains("<automation-notification>"));
        assert!(
            job.content.contains("automation_vanishing"),
            "got: {}",
            job.content
        );
        assert!(
            job.content.contains("no longer exists"),
            "got: {}",
            job.content
        );
        assert_eq!(automation_status(&automation.id).await, "removed");
    }

    /// `delete_automations_for_role` soft-deletes exactly the role's ACTIVE automations.
    #[tokio::test]
    async fn delete_automations_for_role_soft_deletes_only_its_active_automations() {
        crate::util::test::init_management_test_stores().await;
        crate::custom_role::create(
            "automation_cleanup",
            "done",
            &[],
            crate::custom_role::CustomRoleBehavior::Continuous,
        )
        .await
        .unwrap();
        let automation = add_automation(
            &crate::session::assistant_agent_id(crate::users::ADMIN_USER_NAME),
            crate::users::ADMIN_USER_NAME,
            "one",
            Some("2099-01-01T00:00:00Z"),
            None,
            None,
            Some(role_target("automation_cleanup")),
        )
        .await
        .unwrap();
        // A plain automation of another owner must survive.
        let plain = add_automation(
            "assistant:automation-cleanup-it",
            "automation-cleanup-user",
            "two",
            Some("2099-01-01T00:00:00Z"),
            None,
            None,
            None,
        )
        .await
        .unwrap();

        assert_eq!(
            delete_automations_for_role("automation_cleanup")
                .await
                .unwrap(),
            1
        );
        assert_eq!(automation_status(&automation.id).await, "removed");
        assert_eq!(automation_status(&plain.id).await, "active");
        // Idempotent: nothing left to remove.
        assert_eq!(
            delete_automations_for_role("automation_cleanup")
                .await
                .unwrap(),
            0
        );
    }

    /// Fire-time integration: a check that cannot run is a notice that says why
    /// and an automation that goes with it — a tool the catalogue no longer has,
    /// a grant taken away between arming and firing, arguments the tool's
    /// rewritten header no longer declares, and a stored check that cannot be
    /// read at all.
    #[tokio::test]
    async fn fire_trigger_automation_reports_each_unrunnable_check_and_removes_the_automation() {
        let (automation, mut rx) = arm_trigger_automation(
            "assistant:automation-gone-it",
            crate::users::ADMIN_USER_NAME,
            "no_such_automation_tool",
            serde_json::Map::new(),
        )
        .await;
        let content =
            fire_and_collect_notification(&automation, "assistant:automation-gone-it", &mut rx)
                .await;
        assert!(content.contains("<automation-notification>"));
        assert!(content.contains("poll the thing"));
        assert!(
            content.contains("no_such_automation_tool"),
            "got: {content}"
        );
        assert!(content.contains("no longer usable"), "got: {content}");

        // A grant taken away between arming and firing is its own refusal: the
        // tool itself stays fine — it is only the grant that goes.
        let owner = "revoked_grant_guest";
        let users = seed_owner(owner).await;
        users
            .add_grant(owner, "automation_grant_probe")
            .await
            .unwrap();
        let (automation, mut rx) = arm_trigger_automation(
            "assistant:automation-revoked-it",
            owner,
            "automation_grant_probe",
            serde_json::Map::new(),
        )
        .await;
        let _probe = catalogue_probe("automation_grant_probe", "// @description Probe.\n");
        users
            .remove_grant(owner, "automation_grant_probe")
            .await
            .unwrap();
        let content =
            fire_and_collect_notification(&automation, "assistant:automation-revoked-it", &mut rx)
                .await;
        assert!(
            content.contains("no longer available to you"),
            "got: {content}"
        );

        // The tool's header no longer declares the parameter the trigger stored.
        let (automation, mut rx) = arm_trigger_automation(
            "assistant:automation-args-it",
            crate::users::ADMIN_USER_NAME,
            "automation_args_probe",
            args_of(&serde_json::json!({ "city": "Minsk" })),
        )
        .await;
        let _probe = catalogue_probe("automation_args_probe", "// @description Probe.\n");
        let content =
            fire_and_collect_notification(&automation, "assistant:automation-args-it", &mut rx)
                .await;
        assert!(content.contains("no longer fit"), "got: {content}");
        assert!(
            content.contains("[ignored arguments: city]"),
            "got: {content}"
        );

        // Replace the stored check with a value that is not one, and make the
        // automation due so the sweep's own read path is what fires it.
        let session = "assistant:automation-unreadable-it";
        let (automation, mut rx) = arm_trigger_automation(
            session,
            crate::users::ADMIN_USER_NAME,
            "automation_unreadable_probe",
            serde_json::Map::new(),
        )
        .await;
        store()
            .conn
            .execute(
                "UPDATE automations SET trigger = ?1, next_fire_at = ?2 WHERE id = ?3",
                db::params![
                    "not a stored check",
                    "2020-01-01T00:00:00Z",
                    automation.id.as_str()
                ],
            )
            .await
            .unwrap();
        let due = due_automations(&db::now()).await.unwrap();
        let stored = due
            .iter()
            .find(|candidate| candidate.id == automation.id)
            .expect("the automation must be due");

        let content = fire_and_collect_notification(stored, session, &mut rx).await;
        assert!(content.contains("cannot be read"), "got: {content}");
        assert!(
            content.contains("unreadable stored check"),
            "the notice must show a marker where the check would be: {content}"
        );
    }
}