areev-trigger 1.9.4

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

use areev_cal::AreevFacade;
use areev_core::types::{Grain, Trigger, TriggerKind};
use areev_run::{ExecResult, HostToolExecutor};
use areev_store::Areev;
use areev_trigger::{
    clock::FixedClock, Clock, EvalOptions, Evaluator, RunStarter, StartResult,
};
use serde_json::{json, Value};
use std::sync::{Arc, Mutex};

const NS: &str = "ops";
const WF: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90";
/// A second plan hash — what a `SUPERSEDE workflow` re-point looks like from
/// the trigger's side (#128 tests).
const WF2: &str = "b1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90";
const T0: i64 = 1_767_225_600_000; // 2026-01-01T00:00:00Z

/// A connector whose answers a test scripts, recording what it was asked.
struct FakeConnector {
    replies: Mutex<Vec<ExecResult>>,
    requests: Mutex<Vec<Value>>,
}

impl FakeConnector {
    fn new(replies: Vec<ExecResult>) -> Arc<Self> {
        Arc::new(FakeConnector { replies: Mutex::new(replies), requests: Mutex::new(Vec::new()) })
    }
}

impl HostToolExecutor for FakeConnector {
    fn execute(&self, _name: &str, _hash: &str, input: &Value, _idem: &str) -> ExecResult {
        self.requests.lock().unwrap().push(input.clone());
        let mut r = self.replies.lock().unwrap();
        if r.is_empty() {
            ExecResult::Ok(json!({ "items": [] }))
        } else {
            r.remove(0)
        }
    }
}

fn ok(items: Value, cursor: Option<&str>, more: bool) -> ExecResult {
    let mut v = json!({ "items": items, "more": more });
    if let Some(c) = cursor {
        v["cursor"] = json!(c);
    }
    ExecResult::Ok(v)
}

/// A starter that records ids and enforces the duplicate rule the runtime does.
#[derive(Default)]
struct FakeStarter {
    started: Mutex<Vec<String>>,
    /// The workflow reference each firing handed over — what the real starter
    /// hex-decodes, so it is where a scheme prefix would surface (#73).
    workflows: Mutex<Vec<String>>,
}

impl RunStarter for FakeStarter {
    fn start(&self, workflow: &str, run_id: &str, _input: Value) -> StartResult {
        let mut s = self.started.lock().unwrap();
        if s.iter().any(|id| id == run_id) {
            // Exactly what `areev run start` does with an existing id.
            return StartResult::Duplicate;
        }
        s.push(run_id.to_string());
        self.workflows.lock().unwrap().push(workflow.to_string());
        StartResult::Started
    }
}

/// A starter that refuses to start a run for one specific item id (matched
/// against the item's `/id` field in the run input) and behaves like
/// [`FakeStarter`] for everything else — for exercising #129's
/// partial-failure posture. `fail_when` can be cleared mid-test to simulate
/// the underlying cause getting fixed.
#[derive(Default)]
struct FlakyStarter {
    fail_when: Mutex<Option<String>>,
    started: Mutex<Vec<String>>,
}

impl RunStarter for FlakyStarter {
    fn start(&self, _workflow: &str, run_id: &str, input: Value) -> StartResult {
        let mut s = self.started.lock().unwrap();
        if s.iter().any(|id| id == run_id) {
            return StartResult::Duplicate;
        }
        // `input["item"]` IS the connector's item `payload` (the trigger
        // wraps it once, not twice — see `docs/triggers.md` "What the run
        // receives").
        let item_id = input["item"]["id"].as_str().unwrap_or_default();
        if self.fail_when.lock().unwrap().as_deref() == Some(item_id) {
            return StartResult::Failed(format!("simulated refusal for {item_id}"));
        }
        s.push(run_id.to_string());
        StartResult::Started
    }
}

/// A starter that refuses to start a run for one specific FIRING trigger
/// (matched against the run input's `trigger` field) and otherwise starts
/// normally — for exercising #129 at a composite's own firing while its
/// members still start fine.
#[derive(Default)]
struct FailForTrigger {
    trigger: String,
    started: Mutex<Vec<String>>,
}

impl RunStarter for FailForTrigger {
    fn start(&self, _workflow: &str, run_id: &str, input: Value) -> StartResult {
        let mut s = self.started.lock().unwrap();
        if s.iter().any(|id| id == run_id) {
            return StartResult::Duplicate;
        }
        if input["trigger"].as_str() == Some(self.trigger.as_str()) {
            return StartResult::Failed("simulated refusal".into());
        }
        s.push(run_id.to_string());
        StartResult::Started
    }
}

struct Rig {
    _dir: tempfile::TempDir,
    facade: Arc<AreevFacade>,
    clock: Arc<FixedClock>,
    starter: Arc<FakeStarter>,
}

impl Rig {
    fn new() -> Self {
        let dir = tempfile::TempDir::new().unwrap();
        let m = Areev::open(dir.path().join("m.db").to_str().unwrap()).unwrap();
        Rig {
            _dir: dir,
            facade: Arc::new(AreevFacade::new(m)),
            clock: Arc::new(FixedClock::new(T0)),
            starter: Arc::new(FakeStarter::default()),
        }
    }

    fn declare(&self, t: Trigger) -> String {
        let t = t.created_at(T0).namespace(NS);
        self.facade.with_store(|m| m.add(&t)).unwrap().to_hex()
    }

    /// Re-point a declaration by superseding it — what `SUPERSEDE workflow`
    /// followed by re-pointing the trigger looks like from the store's side
    /// (`docs/loop.md`'s apply step). Mints a NEW trigger hash; the caller's
    /// old hash string is untouched.
    fn supersede(&self, old: &str, created_at_ms: i64, t: Trigger) -> String {
        let old_hash = areev_core::error::Hash::from_hex(old).unwrap();
        let mut t = t.created_at(created_at_ms).namespace(NS);
        self.facade.with_store(|m| m.supersede(&old_hash, &mut t)).unwrap().to_hex()
    }

    fn evaluator(&self, connector: Option<Arc<dyn HostToolExecutor>>) -> Evaluator {
        Evaluator {
            facade: Arc::clone(&self.facade),
            clock: Arc::clone(&self.clock) as Arc<dyn areev_trigger::Clock>,
            connector,
            connector_code: None,
            starter: Some(Arc::clone(&self.starter) as Arc<dyn RunStarter>),
            credentials: Default::default(),
            ns: NS.into(),
            principal: "user:test".into(),
        }
    }

    fn state(&self, hash: &str) -> areev_store::TriggerState {
        self.facade.with_store(|m| m.trigger_state(hash)).unwrap().map(|(s, _)| s).unwrap_or_default()
    }
}

fn opts() -> EvalOptions {
    EvalOptions { node: "node-A".into(), ..Default::default() }
}

// ---- clocked triggers -----------------------------------------------------

#[test]
fn an_interval_trigger_fires_then_schedules_its_next() {
    let rig = Rig::new();
    let h = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(120));
    let ev = rig.evaluator(None);

    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.claimed, 1, "a never-evaluated trigger is due immediately");
    assert_eq!(r.runs_started, 1);
    assert!(r.errors.is_empty(), "{:?}", r.errors);

    let st = rig.state(&h);
    assert_eq!(st.next_due_at, Some(T0 + 120_000));
    assert_eq!(st.last_fired_at, Some(T0));
    assert!(st.claimed_by.is_none(), "the lease is released after firing");

    // Immediately again: not due.
    let r2 = ev.run(&opts()).unwrap();
    assert_eq!(r2.claimed, 0);
    assert_eq!(r2.skipped_not_due, 1);

    // After the interval: due again.
    rig.clock.advance(120_000);
    let r3 = ev.run(&opts()).unwrap();
    assert_eq!(r3.claimed, 1);
}

#[test]
fn ingest_only_mode_is_still_idempotent() {
    // Without a runtime wired in nothing executes, but the same item must still
    // not be re-ingested on every poll — an Event's created_at differs per
    // firing, so content addressing alone does not collapse them.
    let rig = Rig::new();
    rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let item = json!([{ "id": "dup", "payload": { "id": "m-1" } }]);
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(item.clone(), Some("c2"), false),
        ok(item, Some("c3"), false),
    ]);
    let ev = Evaluator {
        facade: Arc::clone(&rig.facade),
        clock: Arc::clone(&rig.clock) as Arc<dyn Clock>,
        connector: Some(conn as Arc<dyn HostToolExecutor>),
        connector_code: None,
        starter: None, // ingest-only
        credentials: Default::default(),
        ns: NS.into(),
        principal: "user:test".into(),
    };

    ev.run(&opts()).unwrap(); // seed
    rig.clock.advance(60_000);
    let first = ev.run(&opts()).unwrap();
    rig.clock.advance(60_000);
    let second = ev.run(&opts()).unwrap();

    assert_eq!(first.ingested, 1);
    assert_eq!(first.runs_started, 0, "nothing executes without a runtime");
    assert_eq!(second.ingested, 0, "the replay must not be re-ingested");
    assert_eq!(second.duplicates, 1);
}

#[test]
fn a_disabled_declaration_never_fires() {
    let rig = Rig::new();
    rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60).enabled(false));
    let r = rig.evaluator(None).run(&opts()).unwrap();
    assert_eq!(r.claimed, 0);
    assert_eq!(r.runs_started, 0);
}

#[test]
fn dry_run_reports_what_would_fire_and_touches_nothing() {
    let rig = Rig::new();
    let h = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60));

    let r = rig.evaluator(None).run(&EvalOptions { dry_run: true, ..opts() }).unwrap();
    assert_eq!(r.claimed, 1, "it reports the trigger as due…");
    assert_eq!(r.runs_started, 0, "…without starting anything");
    assert_eq!(rig.state(&h), areev_store::TriggerState::default(), "and writes no state");
}

// ---- polling --------------------------------------------------------------

#[test]
fn the_first_poll_seeds_the_cursor_and_fires_nothing() {
    // Otherwise declaring a mailbox trigger starts a run for every message in
    // history. Zapier primes on activation for exactly this reason.
    let rig = Rig::new();
    let h = rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let conn = FakeConnector::new(vec![ok(
        json!([{ "id": "old-1", "payload": { "id": "old-1" } }]),
        Some("cursor-1"),
        false,
    )]);
    let ev = rig.evaluator(Some(conn.clone() as Arc<dyn HostToolExecutor>));

    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.runs_started, 0, "history must not be replayed on first contact");
    assert_eq!(rig.state(&h).cursor.as_deref(), Some("cursor-1"), "but the position is recorded");
}

#[test]
fn items_after_the_seed_start_one_run_each() {
    let rig = Rig::new();
    let h = rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(
            json!([
                { "id": "a", "payload": { "id": "m-a" } },
                { "id": "b", "payload": { "id": "m-b" } }
            ]),
            Some("c2"),
            false,
        ),
    ]);
    let ev = rig.evaluator(Some(conn.clone() as Arc<dyn HostToolExecutor>));

    ev.run(&opts()).unwrap(); // seed
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();

    assert_eq!(r.items, 2);
    assert_eq!(r.runs_started, 2);
    assert_eq!(rig.state(&h).cursor.as_deref(), Some("c2"));

    // The connector was handed the stored cursor on the second call.
    let reqs = conn.requests.lock().unwrap();
    assert_eq!(reqs[1]["cursor"], json!("c1"));
}

#[test]
fn the_same_item_twice_starts_one_run_and_reports_a_skip() {
    // The idempotency guarantee: connector replay, overlapping cursors, or two
    // nodes racing must never produce two runs for one item.
    let rig = Rig::new();
    rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let item = json!([{ "id": "dup", "payload": { "id": "m-1" } }]);
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(item.clone(), Some("c2"), false),
        ok(item, Some("c3"), false),
    ]);
    let ev = rig.evaluator(Some(conn as Arc<dyn HostToolExecutor>));

    ev.run(&opts()).unwrap(); // seed
    rig.clock.advance(60_000);
    let first = ev.run(&opts()).unwrap();
    rig.clock.advance(60_000);
    let second = ev.run(&opts()).unwrap();

    assert_eq!(first.runs_started, 1);
    assert_eq!(second.runs_started, 0, "the replay must not start a second run");
    assert_eq!(second.duplicates, 1, "and the skip is reported, not hidden");
    assert_eq!(rig.starter.started.lock().unwrap().len(), 1);
}

#[test]
fn a_backlog_drains_at_once_instead_of_waiting_out_the_interval() {
    let rig = Rig::new();
    let h = rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("gmail")
            .interval_secs(3600) // an hour: a cold start must not take a day
            .dedup_key("/id"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(json!([{ "id": "a", "payload": { "id": "a" } }]), Some("c2"), true),
    ]);
    let ev = rig.evaluator(Some(conn as Arc<dyn HostToolExecutor>));

    ev.run(&opts()).unwrap();
    rig.clock.advance(3_600_000);
    let r = ev.run(&opts()).unwrap();

    assert!(r.draining.contains(&h), "a connector reporting more must be flagged");
    assert_eq!(rig.state(&h).next_due_at, Some(rig.clock.now_ms()), "due again immediately");
}

#[test]
fn an_item_with_no_usable_identity_is_reported_not_dropped() {
    let rig = Rig::new();
    rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("gmail")
            .interval_secs(60)
            .dedup_key("/message_id"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        // No `message_id` anywhere: the declared pointer cannot resolve.
        ok(json!([{ "id": "x", "payload": { "subject": "hi" } }]), Some("c2"), false),
    ]);
    let ev = rig.evaluator(Some(conn as Arc<dyn HostToolExecutor>));

    ev.run(&opts()).unwrap();
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();

    assert_eq!(r.runs_started, 0);
    assert_eq!(r.unidentifiable, 1, "an unnameable item is a connector bug, and must show as one");
}

// ---- failure handling -----------------------------------------------------

#[test]
fn a_due_polling_trigger_with_no_connector_fails_loudly() {
    // A poll that silently does nothing is indistinguishable from a healthy
    // source with no new items — the worst possible failure mode.
    let rig = Rig::new();
    rig.declare(Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60));
    let r = rig.evaluator(None).run(&opts()).unwrap();

    assert_eq!(r.runs_started, 0);
    assert_eq!(r.errors.len(), 1);
    assert!(r.errors[0].starts_with("TRG-E003"), "{}", r.errors[0]);
}

#[test]
fn a_failing_connector_backs_off_instead_of_hot_looping() {
    let rig = Rig::new();
    let h = rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let conn = FakeConnector::new(vec![ExecResult::Err {
        cause: areev_run_core::FailCause::ExecutorError,
        detail: "connection refused".into(),
    }]);
    let ev = rig.evaluator(Some(conn as Arc<dyn HostToolExecutor>));

    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.errors.len(), 1);
    assert!(r.errors[0].starts_with("TRG-E004"), "{}", r.errors[0]);

    let st = rig.state(&h);
    assert_eq!(st.consecutive_failures, 1);
    assert!(st.last_error.is_some(), "the reason must be visible in status");
    assert!(
        st.next_due_at.unwrap() >= T0 + 60_000,
        "backed off at least the declared interval, not retried immediately"
    );
    assert!(st.claimed_by.is_none(), "and the lease is released even on failure");
}

#[test]
fn one_broken_trigger_does_not_stop_the_others() {
    let rig = Rig::new();
    rig.declare(Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60));
    rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60));

    let r = rig.evaluator(None).run(&opts()).unwrap();
    assert_eq!(r.errors.len(), 1, "the polling one failed");
    assert_eq!(r.runs_started, 1, "…and the interval one still fired");
}

// ---- claiming -------------------------------------------------------------

#[test]
fn a_held_lease_is_skipped_not_stolen() {
    let rig = Rig::new();
    let h = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60));

    // Another node holds it, not yet expired.
    rig.facade
        .with_store(|m| {
            m.put_trigger_state(
                &h,
                None,
                &areev_store::TriggerState {
                    claimed_by: Some("node-B".into()),
                    lease_until: Some(T0 + 300_000),
                    ..Default::default()
                },
            )
        })
        .unwrap();

    let r = rig.evaluator(None).run(&opts()).unwrap();
    assert_eq!(r.skipped_locked, 1, "losing a race is the steady state, not an error");
    assert_eq!(r.claimed, 0);
    assert!(r.errors.is_empty());
}

#[test]
fn an_expired_lease_is_reclaimed() {
    let rig = Rig::new();
    let h = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60));
    rig.facade
        .with_store(|m| {
            m.put_trigger_state(
                &h,
                None,
                &areev_store::TriggerState {
                    claimed_by: Some("node-B".into()),
                    lease_until: Some(T0 - 1), // already gone
                    fence: 4,
                    ..Default::default()
                },
            )
        })
        .unwrap();

    let r = rig.evaluator(None).run(&opts()).unwrap();
    assert_eq!(r.claimed, 1, "a node that died must not park a trigger forever");
    assert_eq!(rig.state(&h).fence, 5, "and the fence advanced past the dead claim");
}

// ---- visibility -----------------------------------------------------------

#[test]
fn status_reports_a_trigger_that_has_never_fired() {
    let rig = Rig::new();
    rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60));

    let st = rig.evaluator(None).status().unwrap();
    assert_eq!(st.len(), 1);
    assert!(st[0].never_fired, "an unnoticed misconfiguration must be visible");
    assert!(st[0].due);
    assert_eq!(st[0].leased_by, None);
}

#[test]
fn a_firing_is_journaled() {
    let rig = Rig::new();
    let h = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60));
    rig.evaluator(None).run(&opts()).unwrap();

    let obs = rig
        .facade
        .with_store(|m| {
            m.recent_live_scoped(
                &[areev_trigger::eval::TRIGGER_NS.to_string()],
                Some(areev_core::types::GrainType::Observation),
                10,
            )
        })
        .unwrap();
    assert_eq!(obs.len(), 1, "every firing leaves a record");
    assert_eq!(obs[0].get_str("trigger"), Some(h.as_str()));
    assert_eq!(obs[0].get_i64("runs_started"), Some(1));
}

// ---- memory triggers ------------------------------------------------------

fn memory_trigger(where_src: &str) -> Trigger {
    let cond = areev_trigger::predicate::parse_predicate(where_src).unwrap();
    Trigger::new(TriggerKind::Memory, WF)
        .predicate(areev_trigger::predicate::to_value(&cond).unwrap())
}

#[test]
fn a_memory_trigger_seeds_at_the_head_and_ignores_history() {
    // Declaring one on an established memory must not fire once per matching
    // grain already in it.
    let rig = Rig::new();
    for i in 0..5 {
        let f = areev_core::types::Fact::new(&format!("s{i}"), "mg:kind", "invoice")
            .namespace(NS)
            .created_at(T0);
        rig.facade.with_store(|m| m.add(&f)).unwrap();
    }
    rig.declare(memory_trigger(r#"object = "invoice""#));

    let r = rig.evaluator(None).run(&opts()).unwrap();
    assert_eq!(r.runs_started, 0, "history must not fire");
    assert_eq!(r.items, 0);
}

#[test]
fn a_memory_trigger_fires_for_grains_that_appear_after_it() {
    let rig = Rig::new();
    let h = rig.declare(memory_trigger(r#"object = "invoice""#));
    let ev = rig.evaluator(None);

    ev.run(&opts()).unwrap(); // seed at the head

    // Two matching, one not.
    for (s, o) in [("a", "invoice"), ("b", "receipt"), ("c", "invoice")] {
        let f = areev_core::types::Fact::new(s, "mg:kind", o).namespace(NS).created_at(T0);
        rig.facade.with_store(|m| m.add(&f)).unwrap();
    }

    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.items, 2, "only the matching grains are items");
    assert_eq!(r.runs_started, 2);

    // The cursor advanced, so a second pass sees nothing new.
    let again = ev.run(&opts()).unwrap();
    assert_eq!(again.items, 0, "the op cursor must not re-deliver");
    assert!(rig.state(&h).op_cursor.is_some());
}

#[test]
fn a_memory_trigger_uses_the_content_address_as_the_item_identity() {
    // Re-adding identical content is a no-op returning the same hash, so the
    // same grain can never mint two runs even if it is re-added.
    let rig = Rig::new();
    rig.declare(memory_trigger(r#"object = "invoice""#));
    let ev = rig.evaluator(None);
    ev.run(&opts()).unwrap();

    let f = areev_core::types::Fact::new("a", "mg:kind", "invoice").namespace(NS).created_at(T0);
    rig.facade.with_store(|m| m.add(&f)).unwrap();
    let first = ev.run(&opts()).unwrap();
    assert_eq!(first.runs_started, 1);

    rig.facade.with_store(|m| m.add(&f)).unwrap(); // identical content
    let second = ev.run(&opts()).unwrap();
    assert_eq!(second.runs_started, 0, "the same grain must not fire twice");
}

#[test]
fn a_memory_trigger_with_a_boolean_predicate_respects_precedence() {
    let rig = Rig::new();
    rig.declare(memory_trigger(
        r#"(relation = "mg:kind" AND object = "invoice") OR object = "urgent""#,
    ));
    let ev = rig.evaluator(None);
    ev.run(&opts()).unwrap();

    for (s, r, o) in [
        ("a", "mg:kind", "invoice"), // left branch
        ("b", "other", "urgent"),    // right branch
        ("c", "other", "receipt"),   // neither
    ] {
        let f = areev_core::types::Fact::new(s, r, o).namespace(NS).created_at(T0);
        rig.facade.with_store(|m| m.add(&f)).unwrap();
    }

    let out = ev.run(&opts()).unwrap();
    assert_eq!(out.items, 2, "both branches match, the third does not");
}

// ---- composite gates ------------------------------------------------------

fn manual_member() -> Trigger {
    // A member that fires on every pass, so a test can drive the gate directly.
    Trigger::new(TriggerKind::Interval, WF).interval_secs(1)
}

#[test]
fn an_and_gate_waits_for_every_member() {
    let rig = Rig::new();
    let a = rig.declare(manual_member());
    let b = rig.declare(manual_member());

    let cond = areev_trigger::predicate::parse_predicate("invoice = true AND po = true").unwrap();
    let composite = rig.declare(
        Trigger::new(TriggerKind::Composite, WF)
            .member("invoice", &a)
            .member("po", &b)
            .predicate(areev_trigger::predicate::to_value(&cond).unwrap()),
    );

    // Both members are due on the first pass, so the gate completes.
    let r = rig.evaluator(None).run(&opts()).unwrap();
    assert!(r.errors.is_empty(), "{:?}", r.errors);

    let st = rig.state(&composite);
    assert!(st.last_fired_at.is_some(), "an AND gate with both members must fire");
}

#[test]
fn a_gate_naming_an_undeclared_member_is_refused() {
    // It could never be satisfied, so the trigger would be silently dead —
    // exactly the failure mode with no symptom.
    let rig = Rig::new();
    let a = rig.declare(manual_member());
    let b = rig.declare(manual_member());
    let cond =
        areev_trigger::predicate::parse_predicate("invoice = true AND ghost = true").unwrap();
    // TWO members declared, so the composite is otherwise coherent and the
    // undeclared `ghost` in the gate is the only thing wrong with it. With one
    // member it was ALSO "needs at least two members" (TRG-E001), so the test
    // could pass while the gate check it names never ran.
    rig.declare(
        Trigger::new(TriggerKind::Composite, WF)
            .member("invoice", &a)
            .member("po", &b)
            .predicate(areev_trigger::predicate::to_value(&cond).unwrap()),
    );

    let r = rig.evaluator(None).run(&opts()).unwrap();
    // `contains`, not `starts_with`: the report names which declaration is
    // unusable before the reason, which matters once more than one exists.
    assert!(
        r.errors.iter().any(|e| e.contains("TRG-E008")),
        "expected TRG-E008, got {:?}",
        r.errors
    );
}

#[test]
fn a_partial_match_expires_with_its_window() {
    // Monday's A must not pair with Tuesday's B. Argo Events' failure mode,
    // avoided by keying partials with a per-match expiry rather than needing a
    // reset cron.
    let rig = Rig::new();
    let a = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(3600));
    let b = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(86_400));

    let cond = areev_trigger::predicate::parse_predicate("slow = true AND fast = true").unwrap();
    let composite = rig.declare(
        Trigger::new(TriggerKind::Composite, WF)
            .member("fast", &a)
            .member("slow", &b)
            .predicate(areev_trigger::predicate::to_value(&cond).unwrap())
            .window_ms(60_000), // one minute
    );

    let ev = rig.evaluator(None);
    ev.run(&opts()).unwrap(); // both members fire, gate completes
    let fired_once = rig.state(&composite).last_fired_at;
    assert!(fired_once.is_some());

    // Far past the window: any partial left behind must be gone.
    rig.clock.advance(3_600_000);
    ev.run(&opts()).unwrap();
    let st = rig.state(&composite);
    assert!(
        st.partials.values().all(|p| rig.clock.now_ms() - p.started_ms <= 60_000),
        "stale partials must be pruned, found {:?}",
        st.partials
    );
}

#[test]
fn correlation_keeps_unrelated_work_apart() {
    // Two members firing about *different* entities must not satisfy one gate.
    let rig = Rig::new();
    let a = rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("src-a")
            .interval_secs(1)
            .dedup_key("/id"),
    );
    let cond = areev_trigger::predicate::parse_predicate("src = true").unwrap();
    let composite = rig.declare(
        Trigger::new(TriggerKind::Composite, WF)
            .member("src", &a)
            .predicate(areev_trigger::predicate::to_value(&cond).unwrap())
            .correlate("/thread"),
    );

    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(
            json!([
                { "id": "1", "payload": { "id": "1", "thread": "T1" } },
                { "id": "2", "payload": { "id": "2", "thread": "T2" } }
            ]),
            Some("c2"),
            false,
        ),
    ]);
    let ev = rig.evaluator(Some(conn as Arc<dyn HostToolExecutor>));
    ev.run(&opts()).unwrap(); // seed
    rig.clock.advance(1_000);
    ev.run(&opts()).unwrap();

    let st = rig.state(&composite);
    let keys: Vec<_> = st.partials.keys().cloned().collect();
    assert!(
        keys.contains(&"T1".to_string()) || st.last_fired_at.is_some(),
        "correlation values become distinct partial keys, got {keys:?}"
    );
}

#[test]
fn a_once_trigger_fires_exactly_once_and_then_never_again() {
    // `once` means once. After firing, `advance_after_firing` has no next
    // instant to give — and "no next instant" must not be read as "never
    // evaluated, so fire now", which is what an absent `next_due_at` means for
    // every other clocked kind.
    let rig = Rig::new();
    let h = rig.declare(Trigger::new(TriggerKind::Once, WF).at_ms(T0 + 1_000));
    let ev = rig.evaluator(None);

    // Before its instant: not due.
    let early = ev.run(&opts()).unwrap();
    assert_eq!(early.claimed, 0, "a once trigger must wait for its instant");

    // At its instant: fires.
    rig.clock.advance(1_000);
    let fired = ev.run(&opts()).unwrap();
    assert_eq!(fired.claimed, 1);
    assert_eq!(fired.runs_started, 1);

    // Every pass after: nothing, forever.
    for step in 0..5 {
        rig.clock.advance(60_000);
        let again = ev.run(&opts()).unwrap();
        assert_eq!(again.claimed, 0, "re-fired on pass {step}");
        assert_eq!(again.runs_started, 0, "re-fired on pass {step}");
    }
    assert_eq!(rig.state(&h).last_fired_at, Some(T0 + 1_000), "only the first firing counts");
}

#[test]
fn a_cron_trigger_waits_for_its_boundary_rather_than_firing_on_declaration() {
    // `0 9 * * *` must not fire at midnight merely because it was just
    // declared. An absent `next_due_at` means "never evaluated" — for a
    // relative cadence that means fire now, for an absolute schedule it does
    // not.
    let rig = Rig::new(); // clock is at T0 = 2026-01-01T00:00:00Z
    let h = rig.declare(Trigger::new(TriggerKind::Schedule, WF).cron("0 9 * * *"));
    let ev = rig.evaluator(None);

    let early = ev.run(&opts()).unwrap();
    assert_eq!(early.claimed, 0, "midnight is not 9am");

    // 09:00 the same day.
    rig.clock.advance(9 * 3_600_000);
    let fired = ev.run(&opts()).unwrap();
    assert_eq!(fired.claimed, 1, "should fire on the boundary");
    assert!(!rig.state(&h).exhausted, "a recurring schedule is never exhausted");

    // An hour later it is not due again; the next boundary is tomorrow.
    rig.clock.advance(3_600_000);
    assert_eq!(ev.run(&opts()).unwrap().claimed, 0);
}

#[test]
fn an_interval_trigger_still_fires_immediately_on_first_evaluation() {
    // The other half of the same rule: a relative cadence has no baseline to
    // wait out, so it fires at once — the loop gate's behaviour, and what makes
    // a polling trigger seed its cursor promptly.
    let rig = Rig::new();
    rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(3600));
    assert_eq!(rig.evaluator(None).run(&opts()).unwrap().claimed, 1);
}

#[test]
fn display_helpers_do_not_panic_on_a_short_or_non_ascii_workflow() {
    // A declaration can arrive by bundle import from an implementation we did
    // not write, so a `&s[..12]` in a status line is a crash waiting for a
    // grain we never authored.
    let rig = Rig::new();
    for wf in ["ab", "", "日本語のワークフロー"] {
        let t = Trigger::new(TriggerKind::Interval, WF).interval_secs(60).created_at(T0).namespace(NS);
        let mut t = t;
        t.workflow = wf.to_string();
        // `add` is the raw path — `incoherence()` would refuse an empty
        // workflow at the CLI, but a foreign grain never passed through it.
        let _ = rig.facade.with_store(|m| m.add(&t));
    }
    // The point is that this returns rather than panics.
    let status = rig.evaluator(None).status().unwrap();
    assert!(!status.is_empty());
}

// ---- what a firing record has to explain ----------------------------------

/// Every Observation this evaluator has written, newest first.
fn firings(rig: &Rig) -> Vec<areev_core::format::deserialize::DeserializedGrain> {
    rig.facade
        .with_store(|m| {
            m.recent_live_scoped(
                &[areev_trigger::eval::TRIGGER_NS.to_string()],
                Some(areev_core::types::GrainType::Observation),
                10,
            )
        })
        .unwrap()
}

#[test]
fn a_firing_that_identified_nothing_records_why() {
    // Regression: the record carried items/runs_started/duplicates and dropped
    // every count that explains them. "items 5, runs_started 0, duplicates 0"
    // reads as a mystery, and the zero duplicates actively misleads — it says
    // the items were not skipped as duplicates without saying why they were
    // skipped at all.
    let rig = Rig::new();
    rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("gmail")
            .interval_secs(60)
            .dedup_key("/message_id"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(
            json!([
                { "id": "a", "payload": { "subject": "one" } },
                { "id": "b", "payload": { "subject": "two" } }
            ]),
            Some("c2"),
            false,
        ),
    ]);
    let ev = rig.evaluator(Some(conn as Arc<dyn HostToolExecutor>));
    ev.run(&opts()).unwrap();
    rig.clock.advance(60_000);
    ev.run(&opts()).unwrap();

    let obs = firings(&rig);
    let latest = &obs[0];
    assert_eq!(latest.get_i64("items"), Some(2));
    assert_eq!(latest.get_i64("runs_started"), Some(0));
    assert_eq!(
        latest.get_i64("unidentifiable"),
        Some(2),
        "the record must say why two items produced no runs"
    );
}

#[test]
fn an_ordinary_firing_does_not_carry_the_diagnostic_counts() {
    // The counterpart to the above: emitted only when non-zero, so a healthy
    // firing's record stays exactly as small as it was.
    let rig = Rig::new();
    rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60));
    rig.evaluator(None).run(&opts()).unwrap();

    let obs = firings(&rig);
    assert_eq!(obs[0].get_i64("runs_started"), Some(1));
    assert_eq!(obs[0].get_i64("unidentifiable"), None);
    assert_eq!(obs[0].get_i64("ingested"), None);
}

#[test]
fn a_delivery_that_names_nothing_is_still_journaled() {
    // Regression: `deliver` returned before reaching the journal, so a webhook
    // whose payload shape had drifted left no evidence it had ever arrived.
    // That is the case the record is most needed for.
    let rig = Rig::new();
    let h = rig.declare(Trigger::new(TriggerKind::Webhook, WF).dedup_key("/message_id"));
    let ev = rig.evaluator(None);

    let report = ev.deliver(&h, json!({ "subject": "no message_id here" })).unwrap();
    assert_eq!(report.runs_started, 0);
    assert_eq!(report.unidentifiable, 1);

    let obs = firings(&rig);
    assert_eq!(obs.len(), 1, "an unusable delivery still has to leave a record");
    assert_eq!(obs[0].get_str("trigger"), Some(h.as_str()));
    assert_eq!(obs[0].get_i64("unidentifiable"), Some(1));
    assert_eq!(obs[0].get_str("note"), Some("delivered"));
}

#[test]
fn a_composite_naming_an_undeclared_member_is_refused_at_declaration() {
    // Firing already refused this with TRG-E008, but only once the trigger was
    // due — so the declaration sat in the memory looking live. A gate that
    // names a member it does not declare can never be satisfied, and a dead
    // trigger's only symptom is nothing happening.
    let cond =
        areev_trigger::predicate::parse_predicate("invoice = true AND ghost = true").unwrap();
    let t = Trigger::new(TriggerKind::Composite, WF)
        .member("invoice", WF)
        .member("purchase_order", WF)
        .predicate(areev_trigger::predicate::to_value(&cond).unwrap());

    let err = areev_trigger::schedule::validate(&t).unwrap_err();
    assert_eq!(err.code(), "TRG-E008");
    assert!(err.to_string().contains("ghost"), "{err}");

    // The same declaration with every member declared is accepted.
    let ok_cond =
        areev_trigger::predicate::parse_predicate("invoice = true AND purchase_order = true")
            .unwrap();
    let good = Trigger::new(TriggerKind::Composite, WF)
        .member("invoice", WF)
        .member("purchase_order", WF)
        .predicate(areev_trigger::predicate::to_value(&ok_cond).unwrap());
    assert!(areev_trigger::schedule::validate(&good).is_ok());
}

/// A declaration that can never fire is reported as such, not as "waiting".
///
/// #67: an unusable trigger was folded into `not due`, where it is
/// indistinguishable from a healthy one waiting its turn — so the work simply
/// never happened and every report stayed green. Write-path validation alone
/// cannot close this: `Rig::declare` writes straight through the store, which
/// is exactly the shape of a declaration arriving by bundle import from an
/// implementation that validated differently, or one written before the check
/// existed. The evaluator has to notice on its own.
#[test]
fn an_unusable_declaration_is_reported_distinctly_not_as_waiting() {
    let rig = Rig::new();

    // Stored without validation, as a bundle import would be.
    //
    // An UNKNOWN zone name rather than a real one: since #297 a build with
    // zone data evaluates `Asia/Kolkata` perfectly well, so it is no longer
    // an example of an unusable declaration. A name no zone database has is
    // refused in every build — and refusing a typo rather than falling back
    // to UTC is the point: a schedule quietly firing at the wrong hour looks
    // correct.
    let bad = rig.declare(
        Trigger::new(TriggerKind::Schedule, WF)
            .cron("0 9 * * *")
            .config(json!({ "int:timezone": "Mars/Olympus" })),
    );
    let good = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60));

    let ev = rig.evaluator(None);

    let status = ev.status().unwrap();
    let bad_row = status.iter().find(|s| s.trigger == bad).unwrap();
    let why = bad_row.unusable.as_deref().expect("the reason must be reported, not inferred");
    assert!(why.contains("TRG-E006"), "the reason must name the code: {why}");
    assert!(!bad_row.due, "an unusable declaration must never be reported as due");

    // The healthy one is unaffected — this must not become a blanket alarm.
    let good_row = status.iter().find(|s| s.trigger == good).unwrap();
    assert!(good_row.unusable.is_none());
    assert!(good_row.due);

    // And the pass counts it apart from `not due`, with the reason surfaced.
    let report = ev.run(&opts()).unwrap();
    assert_eq!(report.unusable, 1, "an unusable trigger must not hide in not-due");
    assert_eq!(report.claimed, 1, "only the healthy trigger fires");
    assert!(
        report.errors.iter().any(|e| e.contains("TRG-E006")),
        "the reason must reach the operator: {:?}",
        report.errors
    );
}

// ---- declared context (#85) ------------------------------------------------

/// A starter that keeps the input it was handed, so a test can look inside.
#[derive(Default)]
struct CapturingStarter {
    inputs: Mutex<Vec<Value>>,
    run_ids: Mutex<Vec<String>>,
}

impl RunStarter for CapturingStarter {
    fn start(&self, _workflow: &str, run_id: &str, input: Value) -> StartResult {
        self.inputs.lock().unwrap().push(input);
        self.run_ids.lock().unwrap().push(run_id.to_string());
        StartResult::Started
    }
}

/// A trigger naming a `context_query` fires with the saved query's result in
/// the run input — the evaluator assembles it, because it is the one party
/// that already holds the memory the run's own tools cannot open.
#[test]
fn a_context_query_trigger_carries_assembled_context() {
    let rig = Rig::new();
    // Knowledge the run should see, and the saved query that selects it.
    rig.facade
        .with_store(|m| {
            m.add(
                &areev_core::types::Fact::new("acme", "deploy_target", "k8s")
                    .namespace(NS)
                    .created_at(T0),
            )
        })
        .unwrap();
    let ex = areev_cal::CalExecutor::new(areev_cal::CalExecutorConfig::default());
    ex.execute(
        r#"DEFINE QUERY "triage_ctx"() AS { RECALL facts WHERE subject = "acme" AND namespace = "ops" }"#,
        rig.facade.as_ref(),
    )
    .expect("DEFINE QUERY must succeed");

    let h = rig.declare(
        Trigger::new(TriggerKind::Interval, WF).interval_secs(120).context_query("triage_ctx"),
    );
    let starter = Arc::new(CapturingStarter::default());
    let mut ev = rig.evaluator(None);
    ev.starter = Some(Arc::clone(&starter) as Arc<dyn RunStarter>);

    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.runs_started, 1, "errors: {:?}", r.errors);
    let inputs = starter.inputs.lock().unwrap();
    let ctx = &inputs[0]["context"];
    assert!(
        ctx.to_string().contains("deploy_target"),
        "the run input must carry the assembled context: {}",
        inputs[0]
    );
    assert_eq!(inputs[0]["trigger"], json!(h), "the declared payload survives beside it");
}

/// Fail closed: a trigger that declared context must not fire blind. A
/// missing saved query refuses the firing (retried on the evaluator's normal
/// cadence) instead of starting a run without the promised context.
#[test]
fn a_missing_context_query_refuses_the_firing() {
    let rig = Rig::new();
    rig.declare(
        Trigger::new(TriggerKind::Interval, WF).interval_secs(120).context_query("not_defined"),
    );
    let starter = Arc::new(CapturingStarter::default());
    let mut ev = rig.evaluator(None);
    ev.starter = Some(Arc::clone(&starter) as Arc<dyn RunStarter>);

    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.runs_started, 0, "a declared-context trigger must not fire blind");
    assert!(
        r.errors.iter().any(|e| e.contains("not_defined")),
        "the refusal names the query: {:?}",
        r.errors
    );
    assert!(starter.inputs.lock().unwrap().is_empty(), "no run input was handed over");
}

// ---- parameterized declared context (#92) ----------------------------------

/// The declaration binds saved-query parameters from the FIRING ITEM:
/// `--context-query 'thread_ctx($session = /session)'`. The evaluator
/// resolves the pointer against the item's payload and runs the query with
/// that binding, so a message-driven run can carry its own thread.
#[test]
fn a_context_query_binds_parameters_from_the_firing_item() {
    let rig = Rig::new();
    // The thread the firing message belongs to, and a decoy thread that
    // must NOT be selected.
    rig.facade
        .with_store(|m| {
            m.add(
                &areev_core::types::Fact::new("sess-42", "corrects", "invoice-7")
                    .namespace(NS)
                    .created_at(T0),
            )?;
            m.add(
                &areev_core::types::Fact::new("sess-99", "corrects", "invoice-9")
                    .namespace(NS)
                    .created_at(T0),
            )
        })
        .unwrap();
    let ex = areev_cal::CalExecutor::new(areev_cal::CalExecutorConfig::default());
    ex.execute(
        r#"DEFINE QUERY "thread_ctx"($session) AS { RECALL facts WHERE subject = $session AND namespace = "ops" }"#,
        rig.facade.as_ref(),
    )
    .expect("DEFINE QUERY must succeed");

    rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("gmail")
            .interval_secs(60)
            .dedup_key("/id")
            .context_query("thread_ctx($session = /session)"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(
            json!([{ "id": "m-1", "payload": { "id": "m-1", "session": "sess-42" } }]),
            Some("c2"),
            false,
        ),
    ]);
    let starter = Arc::new(CapturingStarter::default());
    let ev = Evaluator {
        facade: Arc::clone(&rig.facade),
        clock: Arc::clone(&rig.clock) as Arc<dyn Clock>,
        connector: Some(conn as Arc<dyn HostToolExecutor>),
        connector_code: None,
        starter: Some(Arc::clone(&starter) as Arc<dyn RunStarter>),
        credentials: Default::default(),
        ns: NS.into(),
        principal: "user:test".into(),
    };

    ev.run(&opts()).unwrap(); // priming poll seeds the cursor
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.runs_started, 1, "errors: {:?}", r.errors);

    let inputs = starter.inputs.lock().unwrap();
    let ctx = inputs[0]["context"].to_string();
    assert!(
        ctx.contains("invoice-7"),
        "the bound thread's fact must be in the context: {}",
        inputs[0]
    );
    assert!(
        !ctx.contains("invoice-9"),
        "the decoy thread must be EXCLUDED — the binding scoped the query: {}",
        inputs[0]
    );
}

/// Fail closed, with `--dedup-key`'s precedent: a pointer that does not
/// resolve against the firing item refuses the firing rather than running
/// the query with a hole in it.
#[test]
fn an_unresolvable_context_pointer_refuses_the_firing() {
    let rig = Rig::new();
    let ex = areev_cal::CalExecutor::new(areev_cal::CalExecutorConfig::default());
    ex.execute(
        r#"DEFINE QUERY "thread_ctx"($session) AS { RECALL facts WHERE subject = $session AND namespace = "ops" }"#,
        rig.facade.as_ref(),
    )
    .unwrap();
    rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("gmail")
            .interval_secs(60)
            .dedup_key("/id")
            .context_query("thread_ctx($session = /session)"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        // No `session` key: the declared pointer cannot resolve.
        ok(json!([{ "id": "m-1", "payload": { "id": "m-1" } }]), Some("c2"), false),
    ]);
    let starter = Arc::new(CapturingStarter::default());
    let ev = Evaluator {
        facade: Arc::clone(&rig.facade),
        clock: Arc::clone(&rig.clock) as Arc<dyn Clock>,
        connector: Some(conn as Arc<dyn HostToolExecutor>),
        connector_code: None,
        starter: Some(Arc::clone(&starter) as Arc<dyn RunStarter>),
        credentials: Default::default(),
        ns: NS.into(),
        principal: "user:test".into(),
    };

    ev.run(&opts()).unwrap();
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.runs_started, 0, "a run must not start with a hole in its context");
    assert!(
        r.errors.iter().any(|e| e.contains("/session")),
        "the refusal names the pointer: {:?}",
        r.errors
    );
    assert!(starter.inputs.lock().unwrap().is_empty());
}

/// A pointer landing on an object or array refuses too — parameters bind
/// scalars, and stringifying a subtree silently would corrupt the query.
#[test]
fn a_non_scalar_context_binding_refuses_the_firing() {
    let rig = Rig::new();
    let ex = areev_cal::CalExecutor::new(areev_cal::CalExecutorConfig::default());
    ex.execute(
        r#"DEFINE QUERY "thread_ctx"($session) AS { RECALL facts WHERE subject = $session AND namespace = "ops" }"#,
        rig.facade.as_ref(),
    )
    .unwrap();
    rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("gmail")
            .interval_secs(60)
            .dedup_key("/id")
            .context_query("thread_ctx($session = /email)"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(
            json!([{ "id": "m-1", "payload": { "id": "m-1", "email": { "from": "a@b.c" } } }]),
            Some("c2"),
            false,
        ),
    ]);
    let starter = Arc::new(CapturingStarter::default());
    let ev = Evaluator {
        facade: Arc::clone(&rig.facade),
        clock: Arc::clone(&rig.clock) as Arc<dyn Clock>,
        connector: Some(conn as Arc<dyn HostToolExecutor>),
        connector_code: None,
        starter: Some(Arc::clone(&starter) as Arc<dyn RunStarter>),
        credentials: Default::default(),
        ns: NS.into(),
        principal: "user:test".into(),
    };

    ev.run(&opts()).unwrap();
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.runs_started, 0);
    assert!(
        r.errors.iter().any(|e| e.contains("scalar")),
        "the refusal says why: {:?}",
        r.errors
    );
}

/// A malformed spelling is refused at authoring time by
/// `schedule::validate` — a trigger that can never fire must not be stored.
#[test]
fn a_malformed_context_query_spelling_is_refused_at_declaration() {
    let t = Trigger::new(TriggerKind::Interval, WF)
        .interval_secs(60)
        .context_query("ctx($session = session)"); // pointer missing '/'
    let err = areev_trigger::schedule::validate(&t).expect_err("must refuse");
    assert!(err.to_string().contains("context_query"), "{err}");
}

// ---- connector blobs (#93) -------------------------------------------------

/// The whole #93 loop: the connector hands back a blob, the EVALUATOR (the
/// party holding the writer) stores it in the CAS, rewrites the payload
/// reference to the address, and attaches a `content_refs` entry to the
/// Event it writes — so the trigger path stores attachments exactly like
/// the host-driven path.
#[test]
fn connector_blobs_land_in_the_cas_and_the_payload_is_rewritten() {
    let rig = Rig::new();
    let h = rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("gmail")
            .interval_secs(60)
            .dedup_key("/id"),
    );
    // "Zm9vYmFy" = b"foobar".
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(
            json!([{
                "id": "m-1",
                "payload": {
                    "id": "m-1",
                    "attachments": [{ "filename": "inv.pdf", "blob": "@0" }],
                },
                "blobs": [{ "filename": "inv.pdf", "mime": "application/pdf", "b64": "Zm9vYmFy" }],
            }]),
            Some("c2"),
            false,
        ),
    ]);
    let starter = Arc::new(CapturingStarter::default());
    let ev = Evaluator {
        facade: Arc::clone(&rig.facade),
        clock: Arc::clone(&rig.clock) as Arc<dyn Clock>,
        connector: Some(conn as Arc<dyn HostToolExecutor>),
        connector_code: None,
        starter: Some(Arc::clone(&starter) as Arc<dyn RunStarter>),
        credentials: Default::default(),
        ns: NS.into(),
        principal: "user:test".into(),
    };

    ev.run(&opts()).unwrap();
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.runs_started, 1, "errors: {:?}", r.errors);

    // The run input carries an ordinary cas:// address, not bytes.
    let inputs = starter.inputs.lock().unwrap();
    let uri = inputs[0]["item"]["attachments"][0]["blob"]
        .as_str()
        .expect("blob ref must be a string")
        .to_string();
    assert!(uri.starts_with("cas://sha256:"), "rewritten to an address: {uri}");
    assert!(
        !inputs[0].to_string().contains("Zm9vYmFy"),
        "the base64 must not reach the run input"
    );

    // The bytes are retrievable by address, and dedup is content-addressed.
    let bytes = rig.facade.with_store(|m| m.get_blob(&uri)).unwrap();
    assert_eq!(bytes, b"foobar");

    // The Event references the blob through content_refs — what keeps it
    // alive through GC and reachable by erasure.
    let run_id = starter.run_ids.lock().unwrap()[0].clone();
    let grains = rig.facade.with_store(|m| m.run_grains(NS, &run_id, 0, 10)).unwrap();
    assert!(
        grains.iter().any(|(_, g)| format!("{:?}", g.fields).contains(&uri)),
        "the ingest Event must carry a content_ref to {uri}; got {} grain(s): {h}",
        grains.len()
    );
}

/// A blob over budget refuses the WHOLE poll — TRG-E011, cursor unmoved —
/// rather than truncating or dropping the attachment: a silently dropped
/// attachment is an invoice posting without evidence, and a lost item is
/// worse.
#[test]
fn an_over_budget_blob_refuses_the_whole_poll_and_keeps_the_cursor() {
    let rig = Rig::new();
    let h = rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("gmail")
            .interval_secs(60)
            .dedup_key("/id"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(
            json!([{
                "id": "m-1",
                "payload": { "id": "m-1", "a": { "blob": "@0" } },
                "blobs": [{ "filename": "big.bin", "b64": "Zm9vYmFy" }],
            }]),
            Some("c2"),
            false,
        ),
    ]);
    let starter = Arc::new(CapturingStarter::default());
    let ev = Evaluator {
        facade: Arc::clone(&rig.facade),
        clock: Arc::clone(&rig.clock) as Arc<dyn Clock>,
        connector: Some(conn as Arc<dyn HostToolExecutor>),
        connector_code: None,
        starter: Some(Arc::clone(&starter) as Arc<dyn RunStarter>),
        credentials: Default::default(),
        ns: NS.into(),
        principal: "user:test".into(),
    };

    ev.run(&opts()).unwrap(); // priming seeds cursor c1
    rig.clock.advance(60_000);
    let tight = EvalOptions { max_blob_bytes_per_item: 3, ..opts() };
    let r = ev.run(&tight).unwrap();
    assert_eq!(r.runs_started, 0);
    assert!(
        r.errors.iter().any(|e| e.contains("TRG-E011")),
        "the refusal carries its code: {:?}",
        r.errors
    );
    let st = rig.state(&h);
    assert_eq!(st.cursor.as_deref(), Some("c1"), "the cursor must not advance past evidence");
    assert!(st.consecutive_failures > 0, "the failure is counted for backoff");
    assert!(starter.inputs.lock().unwrap().is_empty(), "no run started");
}

/// A dangling `"@N"` payload reference is a connector bug, not something to
/// hand to a run: the poll refuses whole.
#[test]
fn a_dangling_blob_reference_refuses_the_poll() {
    let rig = Rig::new();
    let h = rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("gmail")
            .interval_secs(60)
            .dedup_key("/id"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(
            json!([{
                "id": "m-1",
                "payload": { "id": "m-1", "a": { "blob": "@3" } },
                "blobs": [{ "b64": "Zm9vYmFy" }],
            }]),
            Some("c2"),
            false,
        ),
    ]);
    let ev = rig_polling_evaluator(&rig, conn);

    ev.run(&opts()).unwrap();
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.runs_started, 0);
    assert!(r.errors.iter().any(|e| e.contains("TRG-E011")), "{:?}", r.errors);
    assert_eq!(rig.state(&h).cursor.as_deref(), Some("c1"));
}

/// Undecodable base64 refuses too — salvaging a corrupt attachment would
/// store evidence that matches nothing.
#[test]
fn undecodable_blob_base64_refuses_the_poll() {
    let rig = Rig::new();
    rig.declare(
        Trigger::new(TriggerKind::Polling, WF)
            .connector("gmail")
            .interval_secs(60)
            .dedup_key("/id"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(
            json!([{
                "id": "m-1",
                "payload": { "id": "m-1" },
                "blobs": [{ "filename": "x", "b64": "!!! not base64 !!!" }],
            }]),
            Some("c2"),
            false,
        ),
    ]);
    let ev = rig_polling_evaluator(&rig, conn);

    ev.run(&opts()).unwrap();
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();
    assert_eq!(r.runs_started, 0);
    assert!(r.errors.iter().any(|e| e.contains("TRG-E011")), "{:?}", r.errors);
}

/// Shared constructor for the blob failure tests.
fn rig_polling_evaluator(rig: &Rig, conn: Arc<FakeConnector>) -> Evaluator {
    Evaluator {
        facade: Arc::clone(&rig.facade),
        clock: Arc::clone(&rig.clock) as Arc<dyn Clock>,
        connector: Some(conn as Arc<dyn HostToolExecutor>),
        connector_code: None,
        starter: None,
        credentials: Default::default(),
        ns: NS.into(),
        principal: "user:test".into(),
    }
}

// ---- the declaration's own shape (#73) ------------------------------------

#[test]
fn a_prefixed_workflow_reference_still_starts_its_run() {
    // `sha256:<hex>` is accepted on write by every surface, so it has to be
    // readable at fire time. It was not: the evaluator hex-decoded the WHOLE
    // string, so the declaration validated, listed, reported `waiting`, and
    // then died with `FMT-E001: invalid hex hash: Odd number of digits` on the
    // first firing — an hour of debugging for a spelling nothing refused.
    let rig = Rig::new();
    rig.declare(Trigger::new(TriggerKind::Interval, &format!("sha256:{WF}")).interval_secs(60));

    let r = rig.evaluator(None).run(&opts()).unwrap();
    assert_eq!(r.runs_started, 1, "{:?}", r.errors);
    assert!(r.errors.is_empty(), "{:?}", r.errors);
    assert_eq!(
        rig.starter.workflows.lock().unwrap().as_slice(),
        &[WF.to_string()],
        "the starter must be handed the bare address, whatever the declaration spelled"
    );
}

#[test]
fn a_grain_scheme_prefix_is_read_through_too() {
    // `grain:sha256:<hex>` is the vocabulary Recommendation targets use, so a
    // caller reaches for it by analogy. One helper decides, not each call site.
    let rig = Rig::new();
    rig.declare(
        Trigger::new(TriggerKind::Interval, &format!("grain:sha256:{WF}")).interval_secs(60),
    );

    let r = rig.evaluator(None).run(&opts()).unwrap();
    assert_eq!(r.runs_started, 1, "{:?}", r.errors);
    assert_eq!(rig.starter.workflows.lock().unwrap().as_slice(), &[WF.to_string()]);
}

#[test]
fn an_undecodable_workflow_reference_is_unusable_not_waiting() {
    // The other half of the same bug: a reference that is not an address at
    // all must land in `status`'s `unusable` column at declaration time, not
    // sit in `waiting` until a firing discovers it. Stored without validation,
    // as a bundle import from another implementation would be.
    let rig = Rig::new();
    let bad = rig.declare(Trigger::new(TriggerKind::Interval, "not-a-hash").interval_secs(60));

    let ev = rig.evaluator(None);
    let status = ev.status().unwrap();
    let row = status.iter().find(|s| s.trigger == bad).unwrap();
    let why = row.unusable.as_deref().expect("the reason must be reported, not inferred");
    assert!(why.contains("TRG-E002"), "the reason must name the code: {why}");
    assert!(!row.due, "an unusable declaration must never be reported as due");

    let report = ev.run(&opts()).unwrap();
    assert_eq!(report.runs_started, 0);
    assert_eq!(report.unusable, 1);
}

#[test]
fn a_declarations_name_reaches_status_and_is_not_invented_when_absent() {
    // `name` is accepted on write and is what a human uses to identify a
    // trigger, but nothing read it back — so identity fell onto the workflow
    // hash, which is stable only until the plan is re-declared (#73).
    use areev_core::types::Grain as _;
    let rig = Rig::new();
    let named = rig.declare(
        Trigger::new(TriggerKind::Interval, WF)
            .interval_secs(60)
            .extra_field("name", json!("nightly-invoice-sweep")),
    );
    // Blank is absent: a name that renders as nothing is worse than none,
    // because it displaces the hash a reader could otherwise have used.
    let blank = rig.declare(
        Trigger::new(TriggerKind::Interval, WF)
            .interval_secs(90)
            .extra_field("name", json!("   ")),
    );
    let unnamed = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(120));

    let status = rig.evaluator(None).status().unwrap();
    let name_of = |h: &str| {
        status.iter().find(|s| s.trigger == h).unwrap().name.clone()
    };
    assert_eq!(name_of(&named).as_deref(), Some("nightly-invoice-sweep"));
    assert_eq!(name_of(&blank), None);
    assert_eq!(name_of(&unnamed), None);
}

// ---- #128: superseding a trigger must not orphan its cursor or dedup fence

#[test]
fn a_never_superseded_trigger_s_run_id_matches_the_head_hash() {
    // The no-op guarantee (#128): with no supersession, the chain root IS
    // the head, so the run id the evaluator actually mints is
    // byte-identical to `run_id_for` fed the head hash directly — exactly
    // what this crate computed before chain resolution existed.
    let rig = Rig::new();
    let h = rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),
        ok(json!([{ "id": "a", "payload": { "id": "m-a" } }]), Some("c2"), false),
    ]);
    let ev = rig.evaluator(Some(conn as Arc<dyn HostToolExecutor>));
    ev.run(&opts()).unwrap(); // seed
    rig.clock.advance(60_000);
    ev.run(&opts()).unwrap();

    let expected = areev_trigger::eval::run_id_for(&h, Some("gmail"), "m-a");
    let started = rig.starter.started.lock().unwrap();
    assert_eq!(started.as_slice(), &[expected]);
}

#[test]
fn a_never_superseded_trigger_s_status_reports_its_own_hash_as_the_chain_root() {
    // Same no-op guarantee, from `status`'s side: the exposed `chain_root`
    // equals the trigger's own hash until it is ever superseded.
    let rig = Rig::new();
    let h = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60));
    let status = rig.evaluator(None).status().unwrap();
    let row = status.iter().find(|s| s.trigger == h).unwrap();
    assert_eq!(row.chain_root, h);
}

#[test]
fn superseding_a_trigger_keeps_its_cursor_and_dedup_fence() {
    // The issue #128 repro shape: seed -> poll -> supersede -> poll again.
    let rig = Rig::new();
    let h1 = rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let item = json!([{ "id": "m1", "payload": { "id": "m-1" } }]);
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),   // seed
        ok(item.clone(), Some("c2"), false), // first real poll: starts a run
    ]);
    let ev = rig.evaluator(Some(conn.clone() as Arc<dyn HostToolExecutor>));
    ev.run(&opts()).unwrap(); // seed
    rig.clock.advance(60_000);
    let first = ev.run(&opts()).unwrap();
    assert_eq!(first.runs_started, 1, "{:?}", first.errors);
    assert_eq!(rig.state(&h1).cursor.as_deref(), Some("c2"));

    // Applying a loop recommendation re-points the trigger at a new plan —
    // a supersession, minting a NEW content address (`docs/loop.md`).
    let h2 = rig.supersede(
        &h1,
        T0 + 1,
        Trigger::new(TriggerKind::Polling, WF2).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    assert_ne!(h1, h2, "supersede mints a new content address");

    // A third connector reply: if the cursor orphaned, the evaluator would
    // seed again ("newest") and skip everything, rather than asking from c2.
    conn.replies.lock().unwrap().push(ok(item, Some("c3"), false));
    rig.clock.advance(60_000);
    let second = ev.run(&opts()).unwrap();

    let reqs = conn.requests.lock().unwrap();
    assert_eq!(
        reqs.last().unwrap()["cursor"],
        json!("c2"),
        "the poll after supersede must carry the cursor forward, not seed"
    );
    drop(reqs);

    assert!(second.errors.is_empty(), "{:?}", second.errors);
    assert_eq!(
        second.runs_started, 0,
        "the same item replayed after supersede must not start a second run"
    );
    assert_eq!(second.duplicates, 1, "…it must be recognized as a duplicate instead");
}

#[test]
fn legacy_state_from_before_the_fix_is_adopted_under_the_root() {
    // Two supersessions BEFORE evaluating under the new scheme: h2 is the
    // head a pre-#128 evaluator would have kept state under while it was
    // live (between the first and second supersede); h3 is the current
    // head. The root of h3's chain is h1, which — in this simulated
    // "already superseded before the fix" scenario — has NO row of its own.
    let rig = Rig::new();
    let h1 = rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let h2 = rig.supersede(
        &h1,
        T0 + 1,
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let _h3 = rig.supersede(
        &h2,
        T0 + 2,
        Trigger::new(TriggerKind::Polling, WF2).connector("gmail").interval_secs(60).dedup_key("/id"),
    );

    // A pre-#128 evaluator's state row, written under h2 — the exact shape
    // `run()` used to key on before chain resolution existed.
    let legacy = areev_store::TriggerState {
        cursor: Some("legacy-cursor-77".into()),
        last_fired_at: Some(T0),
        next_due_at: Some(T0 + 60_000),
        ..Default::default()
    };
    rig.facade.with_store(|m| m.put_trigger_state(&h2, None, &legacy)).unwrap();
    assert!(
        rig.facade.with_store(|m| m.trigger_state(&h1)).unwrap().is_none(),
        "the root genuinely has no row in this scenario"
    );

    // A reply that only makes sense if the evaluator resumed from the
    // legacy cursor rather than re-seeding.
    let conn = FakeConnector::new(vec![ok(json!([]), Some("legacy-cursor-78"), false)]);
    let ev = rig.evaluator(Some(conn.clone() as Arc<dyn HostToolExecutor>));
    rig.clock.advance(60_000);
    ev.run(&opts()).unwrap();

    let reqs = conn.requests.lock().unwrap();
    assert_eq!(
        reqs[0]["cursor"],
        json!("legacy-cursor-77"),
        "adoption must carry the legacy cursor forward, not seed"
    );
    drop(reqs);

    // Adopted under the ROOT (h1) …
    let (adopted, _raw) = rig.facade.with_store(|m| m.trigger_state(&h1)).unwrap().unwrap();
    assert_eq!(
        adopted.cursor.as_deref(),
        Some("legacy-cursor-78"),
        "the poll that just ran advanced the now-adopted state"
    );
    // … and the legacy row under h2 is gone.
    assert!(
        rig.facade.with_store(|m| m.trigger_state(&h2)).unwrap().is_none(),
        "the legacy row must be removed once adopted"
    );
}

#[test]
fn legacy_run_ids_from_before_the_fix_are_still_recognized_as_duplicates() {
    // Simulates a trigger already superseded once before #128: the run id
    // this item minted was keyed on h2 (root of ITS OWN single-node chain
    // at the time), and after a second supersede to h3, the chain root
    // moves to h1 — so the item's existing run must be found via
    // `chain.legacy()`, not just the root.
    let rig = Rig::new();
    let h1 = rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let h2 = rig.supersede(
        &h1,
        T0 + 1,
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );

    // The item already started a run keyed on h2, the way a pre-#128
    // evaluator would have while h2 was the live head.
    let legacy_run_id = areev_trigger::eval::run_id_for(&h2, Some("gmail"), "m-1");
    let legacy_event = areev_core::types::Event::new(&json!({ "id": "m-1" }).to_string())
        .namespace(NS)
        .extra_field("trigger", json!(h2))
        .extra_field("run_id", json!(legacy_run_id));
    rig.facade.with_store(|m| m.add(&legacy_event)).unwrap();

    let h3 = rig.supersede(
        &h2,
        T0 + 2,
        Trigger::new(TriggerKind::Polling, WF2).connector("gmail").interval_secs(60).dedup_key("/id"),
    );

    let item = json!([{ "id": "m1", "payload": { "id": "m-1" } }]);
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false), // seed
        ok(item, Some("c2"), false),
    ]);
    let ev = rig.evaluator(Some(conn as Arc<dyn HostToolExecutor>));
    ev.run(&opts()).unwrap(); // seed
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();

    assert_eq!(
        r.runs_started, 0,
        "an item already started under a legacy (pre-#128) head must not start again"
    );
    assert_eq!(r.duplicates, 1);
    let _ = h3;
}

#[test]
fn claim_and_release_agree_on_the_key_across_a_supersede() {
    // If `fire`'s claim and release ever disagreed about which hash keys the
    // state row, the release's compare-and-swap would find no row and the
    // pass would report `ClaimLost` — this is what would fail if a call
    // site were left keyed on the head instead of the resolved root.
    let rig = Rig::new();
    let h1 = rig.declare(Trigger::new(TriggerKind::Interval, WF).interval_secs(60));
    rig.evaluator(None).run(&opts()).unwrap();

    let _h2 = rig.supersede(&h1, T0 + 1, Trigger::new(TriggerKind::Interval, WF2).interval_secs(60));
    rig.clock.advance(60_000);
    let r = rig.evaluator(None).run(&opts()).unwrap();

    assert!(r.errors.is_empty(), "a claim/release key mismatch surfaces as ClaimLost: {:?}", r.errors);
    assert_eq!(r.claimed, 1);
    assert_eq!(r.runs_started, 1);
}

// ---- #129: a refused run start must not consume the item ------------------

#[test]
fn a_failed_start_holds_the_cursor_and_backs_off_without_losing_the_gate() {
    let rig = Rig::new();
    let h = rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("gmail").interval_secs(60).dedup_key("/id"),
    );
    let two_items = json!([
        { "id": "ok-1", "payload": { "id": "m-ok" } },
        { "id": "bad-1", "payload": { "id": "m-bad" } }
    ]);
    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false),          // seed
        ok(two_items.clone(), Some("c2"), false),  // first real poll: mixed outcome
    ]);
    let flaky = Arc::new(FlakyStarter {
        fail_when: Mutex::new(Some("m-bad".into())),
        started: Mutex::new(Vec::new()),
    });
    let ev = Evaluator {
        facade: Arc::clone(&rig.facade),
        clock: Arc::clone(&rig.clock) as Arc<dyn Clock>,
        connector: Some(conn.clone() as Arc<dyn HostToolExecutor>),
        connector_code: None,
        starter: Some(Arc::clone(&flaky) as Arc<dyn RunStarter>),
        credentials: Default::default(),
        ns: NS.into(),
        principal: "user:test".into(),
    };

    ev.run(&opts()).unwrap(); // seed
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();

    assert_eq!(r.runs_started, 1, "the item that could start, did");
    assert_eq!(r.errors.len(), 1, "the refusal is reported: {:?}", r.errors);
    assert_eq!(r.cursor_held, vec![h.clone()], "the failure must hold this trigger's cursor");

    let st = rig.state(&h);
    assert_eq!(
        st.cursor.as_deref(),
        Some("c1"),
        "the cursor must NOT advance to c2 — one item in the page was not processed"
    );
    assert_eq!(st.consecutive_failures, 1);
    assert!(st.last_error.is_some(), "last_error must be set, not cleared");
    assert!(
        st.next_due_at.unwrap() > rig.clock.now_ms(),
        "backoff must push next_due_at out rather than spinning at full interval"
    );

    // The stale pin gets fixed; the next tick re-polls the SAME page.
    *flaky.fail_when.lock().unwrap() = None;
    conn.replies.lock().unwrap().push(ok(two_items, Some("c2"), false));
    rig.clock.advance(60_000);
    let r2 = ev.run(&opts()).unwrap();

    assert_eq!(r2.runs_started, 1, "only the previously-failed item starts fresh");
    assert_eq!(r2.duplicates, 1, "the already-started item is recognized, not double-processed");
    assert!(r2.errors.is_empty(), "{:?}", r2.errors);
    assert!(r2.cursor_held.is_empty());

    let st2 = rig.state(&h);
    assert_eq!(st2.cursor.as_deref(), Some("c2"), "now that both items are handled, the cursor advances");
    assert_eq!(st2.consecutive_failures, 0);
    assert!(st2.last_error.is_none());

    // The connector was asked for the SAME cursor on both real polls — proof
    // the held cursor really re-offered the same page.
    let reqs = conn.requests.lock().unwrap();
    assert_eq!(reqs[1]["cursor"], json!("c1"));
    assert_eq!(reqs[2]["cursor"], json!("c1"), "the retry must re-ask from c1, not c2");
}

#[test]
fn a_composite_whose_run_refuses_keeps_its_settled_correlation_key() {
    // A satisfied composite gate whose OWN run refuses to start must stay
    // satisfied — consuming the correlation on a refusal would lose the
    // match permanently, since nothing re-fires the member on its own.
    let rig = Rig::new();
    let a = rig.declare(
        Trigger::new(TriggerKind::Polling, WF).connector("src").interval_secs(60).dedup_key("/id"),
    );
    // A composite needs at least two declared members to be coherent
    // (TRG-E001) — `b` is a `Manual` member (never polls, so it cannot
    // interfere with `a`'s connector script) and the OR means the gate is
    // satisfied by `a` alone.
    let b = rig.declare(Trigger::new(TriggerKind::Manual, WF));
    let cond = areev_trigger::predicate::parse_predicate("src = true OR other = true").unwrap();
    let composite = rig.declare(
        Trigger::new(TriggerKind::Composite, WF)
            .member("src", &a)
            .member("other", &b)
            .predicate(areev_trigger::predicate::to_value(&cond).unwrap())
            .correlate("/thread"),
    );

    let conn = FakeConnector::new(vec![
        ok(json!([]), Some("c1"), false), // seed the member
        ok(json!([{ "id": "1", "payload": { "id": "1", "thread": "T1" } }]), Some("c2"), false),
    ]);
    let starter = Arc::new(FailForTrigger { trigger: composite.clone(), started: Mutex::new(Vec::new()) });
    let ev = Evaluator {
        facade: Arc::clone(&rig.facade),
        clock: Arc::clone(&rig.clock) as Arc<dyn Clock>,
        connector: Some(conn as Arc<dyn HostToolExecutor>),
        connector_code: None,
        starter: Some(starter as Arc<dyn RunStarter>),
        credentials: Default::default(),
        ns: NS.into(),
        principal: "user:test".into(),
    };

    ev.run(&opts()).unwrap(); // seed the member
    rig.clock.advance(60_000);
    let r = ev.run(&opts()).unwrap();

    assert_eq!(r.runs_started, 1, "the member's own run starts fine: {:?}", r.errors);
    assert!(!r.errors.is_empty(), "the composite's own refusal must be reported");
    assert!(r.cursor_held.contains(&composite), "the composite's firing must be reported as cursor-held");

    let st = rig.state(&composite);
    assert!(
        st.partials.contains_key("T1"),
        "a satisfied gate whose run refused must keep its correlation, got {:?}",
        st.partials
    );
}