eclipse-core 0.13.3

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

use async_trait::async_trait;

use crate::config::{Config, HooksConfig};
use crate::error::Error;
use crate::message::Message;
use crate::tools::ToolSpec;

/// How a turn's request differs from the agent's defaults.
///
/// Every field is optional and every field is a *this turn only* decision. Providers that
/// cannot express a field must say so rather than drop it silently: a patch nobody applied is
/// worse than an error, because the model then looks irrational for reasons nothing records.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RequestPatch {
    /// An extra system message, sent ahead of the conversation. Use it for a per-turn
    /// reminder; the agent's own system prompt stays where it is.
    pub preamble: Option<String>,
    pub temperature: Option<f32>,
    pub max_tokens: Option<u32>,
    /// What the model may do with tools on this turn.
    pub tool_choice: Option<ToolChoice>,
    /// An allow-list of tool names to advertise. Unknown names are dropped, so a hook that
    /// names a tool this build does not have narrows the list to what exists rather than
    /// failing the turn.
    pub active_tools: Option<Vec<String>>,
    /// Merged into the request body, shallow: a key here replaces the same key from the config
    /// profile. This is the escape hatch for provider-specific knobs (`top_p`, `min_p`,
    /// `repeat_penalty`) without teaching Eclipse every vendor's spelling.
    pub extra_params: BTreeMap<String, serde_json::Value>,
    /// Extra messages inserted after the system prompt and ahead of the conversation. They are
    /// *this turn only* — they are never stored, so the session reads as if they were not there.
    /// Use for a per-turn reference document or a fetched excerpt.
    pub documents: Vec<Message>,
    /// Replaces the assembled conversation (everything after the system prompt) for this turn.
    /// The agent's own system prompt is preserved; the history the loop would have sent is not.
    /// Last writer wins, like `preamble`.
    pub history: Option<Vec<Message>>,
}

impl RequestPatch {
    pub fn is_empty(&self) -> bool {
        self.preamble.is_none()
            && self.temperature.is_none()
            && self.max_tokens.is_none()
            && self.tool_choice.is_none()
            && self.active_tools.is_none()
            && self.extra_params.is_empty()
            && self.documents.is_empty()
            && self.history.is_none()
    }

    /// Names of the fields this patch sets, for an error or a log line.
    pub fn describe(&self) -> String {
        let mut set = Vec::new();
        if self.preamble.is_some() {
            set.push("preamble");
        }
        if self.temperature.is_some() {
            set.push("temperature");
        }
        if self.max_tokens.is_some() {
            set.push("max_tokens");
        }
        if self.tool_choice.is_some() {
            set.push("tool_choice");
        }
        if self.active_tools.is_some() {
            set.push("active_tools");
        }
        if !self.extra_params.is_empty() {
            set.push("extra_params");
        }
        if !self.documents.is_empty() {
            set.push("documents");
        }
        if self.history.is_some() {
            set.push("history");
        }
        set.join(", ")
    }

    /// Fold a later hook's patch into this one: scalars are last-writer-wins, `extra_params`
    /// merge key by key, and two allow-lists intersect.
    ///
    /// Intersecting is the only composition that cannot widen what a hook meant to narrow: if
    /// hook A permits three tools and hook B permits two, the turn gets the two. Union would
    /// let a later hook quietly re-enable what an earlier one forbade.
    pub fn merge(&mut self, later: RequestPatch) {
        if later.preamble.is_some() {
            self.preamble = later.preamble;
        }
        if later.temperature.is_some() {
            self.temperature = later.temperature;
        }
        if later.max_tokens.is_some() {
            self.max_tokens = later.max_tokens;
        }
        if later.tool_choice.is_some() {
            self.tool_choice = later.tool_choice;
        }
        if let Some(names) = later.active_tools {
            self.active_tools = Some(match self.active_tools.take() {
                Some(mine) => mine.into_iter().filter(|n| names.contains(n)).collect(),
                None => names,
            });
        }
        self.extra_params.extend(later.extra_params);
        self.documents.extend(later.documents);
        if later.history.is_some() {
            self.history = later.history;
        }
    }
}

/// The `tool_choice` values an OpenAI-compatible endpoint understands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolChoice {
    Auto,
    None,
    Required,
    /// Force one named tool.
    Function(String),
}

impl ToolChoice {
    /// The wire form: a bare string, or the function object.
    pub fn to_json(&self) -> serde_json::Value {
        match self {
            ToolChoice::Auto => serde_json::json!("auto"),
            ToolChoice::None => serde_json::json!("none"),
            ToolChoice::Required => serde_json::json!("required"),
            ToolChoice::Function(name) => serde_json::json!({
                "type": "function",
                "function": { "name": name }
            }),
        }
    }

    /// The config form: one string. The three keywords mean what OpenAI means by them;
    /// anything else is a tool name, which is why `tool_choice = "read_file"` reads the way
    /// a person writes it.
    pub fn as_config_str(&self) -> &str {
        match self {
            ToolChoice::Auto => "auto",
            ToolChoice::None => "none",
            ToolChoice::Required => "required",
            ToolChoice::Function(name) => name,
        }
    }

    pub fn from_config_str(value: &str) -> ToolChoice {
        match value.trim() {
            "auto" => ToolChoice::Auto,
            "none" => ToolChoice::None,
            "required" => ToolChoice::Required,
            other => ToolChoice::Function(other.to_string()),
        }
    }
}

impl serde::Serialize for ToolChoice {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_config_str())
    }
}

impl<'de> serde::Deserialize<'de> for ToolChoice {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let text = String::deserialize(d)?;
        if text.trim().is_empty() {
            return Err(serde::de::Error::custom(
                "tool_choice must be `auto`, `none`, `required`, or a tool name",
            ));
        }
        Ok(ToolChoice::from_config_str(&text))
    }
}

/// A run beginning. `prompt` is what the user asked for, after the CLI resolved it.
pub struct RunStart<'a> {
    pub session: &'a str,
    pub prompt: &'a str,
}

/// A turn about to request the model.
pub struct CallEvent<'a> {
    pub session: &'a str,
    /// 1 for the first model call of the run.
    pub turn: usize,
    /// What the request will carry. The assembled system prompt and trimmed history are the
    /// first two entries; a hook reads them, it does not edit them in place — it returns a
    /// [`RequestPatch`].
    pub messages: &'a [Message],
    pub tools: &'a [ToolSpec],
}

/// The model's answer to a turn, before it is stored.
pub struct Turn<'a> {
    pub session: &'a str,
    pub turn: usize,
    pub reply: &'a Message,
}

/// What a hook asked to do with a malformed call: the name and the argument string the call
/// should run with instead.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DispatchRepair {
    pub name: String,
    pub arguments: String,
}

/// A tool call about to run.
pub struct Dispatch<'a> {
    pub session: &'a str,
    pub tool: &'a str,
    pub arguments: &'a str,
}

/// A tool result, before the model sees it.
pub struct Outcome<'a> {
    pub session: &'a str,
    pub tool: &'a str,
    pub output: &'a str,
    pub is_error: bool,
    /// The call could not even be attempted: unknown tool, or arguments that are not JSON.
    pub malformed: bool,
}

/// How a run ended, for hooks that audit or clean up.
pub struct Settled<'a> {
    pub session: &'a str,
    pub turns: usize,
    pub ending: Ending<'a>,
}

#[derive(Debug, PartialEq, Eq)]
pub enum Ending<'a> {
    /// The model answered.
    Answered,
    /// A hook said stop, or the loop gave up. The run's history is on disk either way.
    Stopped(&'a str),
    Cancelled,
    Failed(&'a str),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunStartAction {
    Proceed,
    Stop(String),
}

#[derive(Debug, Clone, PartialEq)]
pub enum CallAction {
    Proceed,
    Patch(RequestPatch),
    Stop(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TurnAction {
    Proceed,
    /// Ask again with the same context. Counts as a turn, so the iteration cap still bounds a
    /// hook that repeats forever.
    Repeat,
    /// Discard this answer and ask again with a note added as a user message. The reply is not
    /// stored, so the session reads as if the retry were the first attempt.
    RetryWithFeedback(String),
    Stop(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DispatchAction {
    Proceed,
    /// Rewrite the call before it runs: a malformed name or JSON arguments become something
    /// the tool can actually use. Only the first hook that answers non-Proceed wins, so two
    /// hooks repairing different calls in the same turn cannot fight over one call.
    Repair {
        name: String,
        arguments: String,
    },
    Stop(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutcomeAction {
    Proceed,
    /// Replace what the model will read. The original is gone: this is for redaction as much
    /// as for repair, and a hook that wants both must include what it wants to keep.
    ReplaceOutput(String),
    Stop(String),
}

/// One place to intervene in the loop. Every method has a "carry on" default, so implement
/// only what you need.
#[async_trait]
pub trait LoopHook: Send + Sync {
    async fn on_run_start(&self, _ev: RunStart<'_>) -> RunStartAction {
        RunStartAction::Proceed
    }

    async fn on_completion_call(&self, _ev: CallEvent<'_>) -> CallAction {
        CallAction::Proceed
    }

    async fn on_model_turn_finished(&self, _ev: Turn<'_>) -> TurnAction {
        TurnAction::Proceed
    }

    async fn on_dispatch(&self, _ev: Dispatch<'_>) -> DispatchAction {
        DispatchAction::Proceed
    }

    async fn on_outcome(&self, _ev: Outcome<'_>) -> OutcomeAction {
        OutcomeAction::Proceed
    }

    async fn on_run_settled(&self, _ev: Settled<'_>) {}
}

/// The hooks a runtime runs, in registration order.
///
/// Empty by default: an agent with no hooks behaves exactly as it did before this module
/// existed, which is what makes the surface safe to add.
#[derive(Default, Clone)]
pub struct LoopHooks {
    hooks: Vec<Arc<dyn LoopHook>>,
}

impl std::fmt::Debug for LoopHooks {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LoopHooks")
            .field("count", &self.hooks.len())
            .finish()
    }
}

impl LoopHooks {
    pub fn new(hooks: Vec<Arc<dyn LoopHook>>) -> Self {
        Self { hooks }
    }

    pub fn len(&self) -> usize {
        self.hooks.len()
    }

    pub fn is_empty(&self) -> bool {
        self.hooks.is_empty()
    }

    /// `Some(reason)` when a hook stopped the run before it started.
    pub async fn run_start(&self, ev: RunStart<'_>) -> Option<String> {
        for hook in &self.hooks {
            if let RunStartAction::Stop(reason) = hook.on_run_start(ev_clone(&ev)).await {
                return Some(reason);
            }
        }
        None
    }

    /// The merged patch for this turn, or the reason the run stopped.
    ///
    /// Stops end the chain: a later hook is not consulted about a turn that will not happen.
    pub async fn completion_call(
        &self,
        session: &str,
        turn: usize,
        messages: &[Message],
        tools: &[ToolSpec],
    ) -> Result<RequestPatch, String> {
        let mut merged = RequestPatch::default();
        for hook in &self.hooks {
            match hook
                .on_completion_call(CallEvent {
                    session,
                    turn,
                    messages,
                    tools,
                })
                .await
            {
                CallAction::Proceed => {}
                CallAction::Patch(p) => merged.merge(p),
                CallAction::Stop(reason) => return Err(reason),
            }
        }
        Ok(merged)
    }

    pub async fn model_turn_finished(
        &self,
        session: &str,
        turn: usize,
        reply: &Message,
    ) -> TurnAction {
        for hook in &self.hooks {
            let action = hook
                .on_model_turn_finished(Turn {
                    session,
                    turn,
                    reply,
                })
                .await;
            match action {
                TurnAction::Proceed => {}
                // First real instruction wins: two hooks telling the loop to do different
                // things is a bug in the hooks, and the earliest is the most specific.
                other => return other,
            }
        }
        TurnAction::Proceed
    }

    /// `Ok(Some(repair))` when a hook rewrote the call, `Ok(None)` to let it go as-is,
    /// `Err(reason)` to stop the run. The first real instruction wins, like the other events.
    pub async fn dispatch(
        &self,
        session: &str,
        tool: &str,
        arguments: &str,
    ) -> Result<Option<DispatchRepair>, String> {
        for hook in &self.hooks {
            match hook
                .on_dispatch(Dispatch {
                    session,
                    tool,
                    arguments,
                })
                .await
            {
                DispatchAction::Proceed => {}
                DispatchAction::Repair { name, arguments } => {
                    return Ok(Some(DispatchRepair { name, arguments }))
                }
                DispatchAction::Stop(reason) => return Err(reason),
            }
        }
        Ok(None)
    }

    pub async fn outcome(
        &self,
        session: &str,
        tool: &str,
        output: &str,
        is_error: bool,
        malformed: bool,
    ) -> OutcomeAction {
        let mut current: Option<String> = None;
        for hook in &self.hooks {
            let shown = current.as_deref().unwrap_or(output);
            match hook
                .on_outcome(Outcome {
                    session,
                    tool,
                    output: shown,
                    is_error,
                    malformed,
                })
                .await
            {
                OutcomeAction::Proceed => {}
                OutcomeAction::ReplaceOutput(text) => current = Some(text),
                OutcomeAction::Stop(reason) => return OutcomeAction::Stop(reason),
            }
        }
        match current {
            Some(text) => OutcomeAction::ReplaceOutput(text),
            None => OutcomeAction::Proceed,
        }
    }

    pub async fn run_settled(&self, ev: Settled<'_>) {
        for hook in &self.hooks {
            hook.on_run_settled(ev_clone_settled(&ev)).await;
        }
    }
}

/// Re-borrow an event for the next hook. The structs hold references, so they are rebuilt
/// rather than cloned; this keeps the event types allocation-free.
fn ev_clone<'a>(ev: &RunStart<'a>) -> RunStart<'a> {
    RunStart {
        session: ev.session,
        prompt: ev.prompt,
    }
}

fn ev_clone_settled<'a>(ev: &Settled<'a>) -> Settled<'a> {
    Settled {
        session: ev.session,
        turns: ev.turns,
        ending: match ev.ending {
            Ending::Answered => Ending::Answered,
            Ending::Stopped(r) => Ending::Stopped(r),
            Ending::Cancelled => Ending::Cancelled,
            Ending::Failed(r) => Ending::Failed(r),
        },
    }
}

// ---------------------------------------------------------------------------------------------
// What a build ships, and the one place that turns `[hooks]` into hooks.
// ---------------------------------------------------------------------------------------------

/// A hook this build knows by name.
pub struct HookInfo {
    pub name: &'static str,
    /// The loop point it is wired at, as `config show` prints it.
    pub point: &'static str,
    /// The keys its `[hooks.<name>]` table accepts. Empty: it takes no settings.
    pub settings: &'static [&'static str],
    /// Checks the *values* of a settings table whose keys are already known to be valid.
    pub check: fn(&toml::value::Table) -> Result<(), String>,
}

/// The hooks this build ships. A name in `[hooks] order` must be one of these.
pub const SHIPPED: &[HookInfo] = &[
    HookInfo {
        name: "recall-sessions",
        point: "on_completion_call",
        settings: &[
            "results",
            "budget_chars",
            "min_query_chars",
            "include_this_session",
        ],
        check: check_recall_settings,
    },
    HookInfo {
        name: "redact-secrets",
        point: "on_outcome",
        settings: &["allow"],
        check: check_redact_settings,
    },
];

/// What `[hooks] order` is when the section is absent.
///
/// Redaction only. Recall used to be here too, on the argument that "a memory is knowing before
/// you answer" — and that argument was wrong in a way that is easy to see from the outside: a new
/// session is not new if the first request already carries the last three, chosen by a keyword
/// match on the prompt. A person who wanted last week's decision to count would say so; a person
/// starting a fresh topic gets their previous topic pushed at the model, and an agent that reads
/// `## Recalled from earlier sessions` will anchor on it. `session_search` is the honest form of
/// the same feature: the model decides it needs the archive, and chooses the query. Recall stays
/// implemented and stays available — naming it in `order` turns it back on.
pub const DEFAULT_ORDER: &[&str] = &["redact-secrets"];

/// The `allow` list of `[hooks.redact-secrets]`, validated.
fn redact_allow(table: &toml::value::Table) -> Result<Vec<String>, String> {
    let Some(value) = table.get("allow") else {
        return Ok(Vec::new());
    };
    let Some(items) = value.as_array() else {
        return Err("[hooks.redact-secrets] `allow` must be a list of strings, \
             e.g. allow = [\"my-fixture-key\"]"
            .into());
    };
    let mut out = Vec::with_capacity(items.len());
    for item in items {
        match item.as_str() {
            Some("") => {
                return Err(
                    "[hooks.redact-secrets] `allow` holds an empty string, which would \
                     exempt nothing and read like it exempts everything; remove it"
                        .into(),
                )
            }
            Some(text) => out.push(text.to_string()),
            None => {
                return Err("[hooks.redact-secrets] `allow` must hold only strings, \
                     e.g. allow = [\"my-fixture-key\"]"
                    .into())
            }
        }
    }
    Ok(out)
}

fn check_redact_settings(table: &toml::value::Table) -> Result<(), String> {
    redact_allow(table).map(|_| ())
}

// ---------------------------------------------------------------------------------------------
// recall-sessions: the archive as memory
// ---------------------------------------------------------------------------------------------

/// What `[hooks.recall-sessions]` accepts, with what a bare `[hooks]` gets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecallSettings {
    /// Earlier sessions a single prompt may draw on.
    pub results: usize,
    /// Hard cap on the injected text, heading and pointer included.
    pub budget_chars: usize,
    /// Prompts shorter than this are not searched: "yes" is not a query.
    pub min_query_chars: usize,
    /// Whether a hit in the session being written is allowed. Off by default: this is a
    /// memory of *earlier* sessions, and the current transcript is already in the request.
    pub include_this_session: bool,
}

impl Default for RecallSettings {
    fn default() -> Self {
        Self {
            results: 3,
            budget_chars: 1_200,
            min_query_chars: 24,
            include_this_session: false,
        }
    }
}

fn recall_int(
    table: &toml::value::Table,
    key: &str,
    low: i64,
    high: i64,
    what: &str,
) -> Result<Option<i64>, String> {
    let Some(value) = table.get(key) else {
        return Ok(None);
    };
    match value.as_integer() {
        Some(n) if (low..=high).contains(&n) => Ok(Some(n)),
        _ => Err(format!(
            "[hooks.recall-sessions] `{key}` {what}, {low} to {high}"
        )),
    }
}

fn recall_settings(table: &toml::value::Table) -> Result<RecallSettings, String> {
    let mut s = RecallSettings::default();
    if let Some(n) = recall_int(
        table,
        "results",
        1,
        8,
        "is how many earlier sessions a prompt may recall",
    )? {
        s.results = n as usize;
    }
    if let Some(n) = recall_int(
        table,
        "budget_chars",
        200,
        8_000,
        "is the most text a recall may add to a prompt",
    )? {
        s.budget_chars = n as usize;
    }
    if let Some(n) = recall_int(
        table,
        "min_query_chars",
        0,
        2_000,
        "is the shortest prompt worth searching for",
    )? {
        s.min_query_chars = n as usize;
    }
    if let Some(value) = table.get("include_this_session") {
        s.include_this_session = value.as_bool().ok_or_else(|| {
            "[hooks.recall-sessions] `include_this_session` must be true or false".to_string()
        })?;
    }
    Ok(s)
}

fn check_recall_settings(table: &toml::value::Table) -> Result<(), String> {
    recall_settings(table).map(|_| ())
}

/// Words a prompt is searched by: the content words, in the order they were typed.
///
/// Deliberately crude. This runs on every prompt, so it is a split, a length filter and a
/// stopword list — no stemming, no model, nothing that could disagree with itself between two
/// turns on the same sentence.
pub fn recall_terms(text: &str) -> Vec<String> {
    /// Words that carry no topic. Kept short on purpose: a term that slips through costs one
    /// extra full-text query, a stopword that is missing costs a recall that reads like noise.
    const STOP: &[&str] = &[
        "the", "and", "for", "that", "this", "with", "from", "have", "has", "had", "what", "when",
        "where", "which", "who", "why", "how", "would", "should", "could", "there", "their",
        "them", "they", "then", "than", "these", "those", "about", "into", "just", "like", "make",
        "made", "your", "you", "are", "was", "were", "its", "can", "cannot", "not", "but", "all",
        "any", "one", "two", "out", "use", "using", "used", "get", "got", "need", "want", "please",
        "thanks", "okay", "also", "still", "now", "did", "does", "done", "back", "over", "only",
        "some", "more", "most", "such", "been", "being", "because", "before", "after", "again",
        "here", "very", "much", "should", "shall",
    ];
    let mut seen = std::collections::HashSet::new();
    let mut terms = Vec::new();
    for word in text.split(|c: char| !c.is_alphanumeric()) {
        if word.chars().count() < 3 {
            continue;
        }
        let word = word.to_lowercase();
        if STOP.contains(&word.as_str()) || !seen.insert(word.clone()) {
            continue;
        }
        terms.push(word);
        if terms.len() == 10 {
            break;
        }
    }
    terms
}

/// The archive, read as memory: the closest earlier sessions for this prompt, injected before
/// the model's first request rather than left for it to ask for.
///
/// This is the half of `session_search` that Hermes has and Eclipse did not. A tool the model
/// may call only helps a model that suspects it should; the point of a memory is that the
/// agent knows the fact *before* it answers. It is computed — full-text queries over the same
/// store the agent is already writing, no model call — bounded by `budget_chars` and
/// `results`, and it fires at `on_completion_call` only when the newest message is the user's,
/// which is once per prompt and never again for that prompt's tool round-trips.
pub struct RecallSessions {
    store: crate::session::SessionStore,
    settings: RecallSettings,
    reporting: Reporting,
    /// Runs already reported, so the note belongs to the run rather than to each turn.
    announced: std::sync::Mutex<std::collections::HashSet<String>>,
    /// `once_per_process` reporting: the dashboard says it once, not once per conversation.
    said_once: std::sync::atomic::AtomicBool,
}

impl RecallSessions {
    pub fn new(
        store: crate::session::SessionStore,
        settings: RecallSettings,
        reporting: Reporting,
    ) -> Self {
        Self {
            store,
            settings,
            reporting,
            announced: Default::default(),
            said_once: Default::default(),
        }
    }

    /// The document for this prompt, or `None` when the archive has nothing to say.
    fn recall(&self, prompt: &str, current: &str) -> Option<(String, usize, usize)> {
        let terms = recall_terms(prompt);
        if terms.is_empty() {
            return None;
        }
        // Archived rows included: a match in one is still a match, and the line below names the
        // session it was found in — an id with no title beside it reads as a deleted session.
        let listed = self.store.list_with_archived().ok()?;
        let by_id: std::collections::HashMap<&str, &crate::session::SessionInfo> =
            listed.iter().map(|s| (s.id.as_str(), s)).collect();

        // Score a row by how many of the prompt's terms it holds. One query per term, merged:
        // `store.search` takes one query and requires every word in it, which for a whole
        // prompt would match nothing at all.
        let mut found: std::collections::HashMap<
            (String, usize),
            (usize, crate::session::SearchHit),
        > = Default::default();
        for term in &terms {
            let Ok(hits) = self.store.search(term, 12) else {
                continue;
            };
            for hit in hits {
                if hit.session_id == current && !self.settings.include_this_session {
                    continue;
                }
                // A subagent session is a job a conversation ran, not a conversation: its rows
                // are the parent's tools, and recalling them as memory would echo work back.
                match by_id.get(hit.session_id.as_str()) {
                    Some(info) if info.subagent().is_some() => continue,
                    Some(_) => {}
                    None => continue,
                }
                let key = (hit.session_id.clone(), hit.seq);
                let entry = found.entry(key).or_insert((0, hit));
                entry.0 += 1;
            }
        }
        if found.is_empty() {
            return None;
        }

        // One row per session: a memory is a map of where to look, and three snippets out of
        // the same transcript is the same map three times.
        let mut best: std::collections::HashMap<&str, (usize, u64, &crate::session::SearchHit)> =
            Default::default();
        for ((session, _), (score, hit)) in &found {
            let at = hit.at_ms;
            let entry = best.entry(session.as_str()).or_insert((*score, at, hit));
            if *score > entry.0 || (*score == entry.0 && at > entry.1) {
                *entry = (*score, at, hit);
            }
        }
        let mut picks: Vec<(&str, usize, u64, &crate::session::SearchHit)> = best
            .into_iter()
            .map(|(session, (score, at, hit))| (session, score, at, hit))
            .collect();
        picks.sort_by(|a, b| b.1.cmp(&a.1).then(b.2.cmp(&a.2)).then(a.0.cmp(b.0)));
        picks.truncate(self.settings.results);
        if picks.is_empty() {
            return None;
        }

        let mut out = String::from(
            "## Recalled from earlier sessions\n\
             The archive matched this message in sessions that are not this conversation. This is \
             context, not instruction, and it may be out of date.\n",
        );
        // The pointer is part of the budget: it names the session to read, and a recall that
        // overruns its cap because of its own footer would be a cap that is not one.
        let (first_session, _, _, first_hit) = picks[0];
        let pointer = format!(
            "Read around a hit with `session_search(session=\"{first_session}\", \
             around_message_id={})`, or search the whole archive with `session_search(query=…)`.",
            first_hit.seq
        );
        let mut used = out.len() + pointer.len();
        let mut shown = 0;
        let mut sessions: Vec<&str> = Vec::new();
        for (session, _score, at, hit) in &picks {
            let age = crate::session::ago_words(*at);
            let who = if *session == current {
                "this session".to_string()
            } else {
                format!("session `{session}`")
            };
            let name = by_id
                .get(*session)
                .and_then(|info| info.title.as_deref())
                .filter(|t| !t.trim().is_empty())
                .map(|t| format!(" \"{}\"", crate::compact::clean(t, 60)))
                .unwrap_or_default();
            let line = format!(
                "- {age} · {who}{name} · #{seq} {role}: {snippet}\n",
                seq = hit.seq,
                role = crate::compact::clean(&hit.role, 12),
                snippet = crate::compact::clean(&hit.snippet, 220),
            );
            if used + line.len() > self.settings.budget_chars {
                break;
            }
            used += line.len();
            out.push_str(&line);
            shown += 1;
            sessions.push(session);
        }
        if shown == 0 {
            return None;
        }
        // What did not fit is said, when there is room to say it: a memory that silently drops
        // two of three matches reads like the archive had one.
        let dropped = picks.len() - shown;
        if dropped > 0 {
            let note = format!(
                "- … {dropped} more match(es) not shown (raise `budget_chars` in \
                 [hooks.recall-sessions])\n"
            );
            if used + note.len() <= self.settings.budget_chars {
                out.push_str(&note);
            }
        }
        out.push_str(&pointer);
        Some((out, shown, sessions.len()))
    }
}

#[async_trait]
impl LoopHook for RecallSessions {
    async fn on_completion_call(&self, ev: CallEvent<'_>) -> CallAction {
        // Once per prompt. After a tool result the newest message is not the user's, so a
        // memory injected here cannot be injected again for the same prompt's later turns.
        let Some(prompt) = ev.messages.last() else {
            return CallAction::Proceed;
        };
        if !matches!(prompt.role, crate::message::Role::User) {
            return CallAction::Proceed;
        }
        let Some(text) = prompt.content.as_deref() else {
            return CallAction::Proceed;
        };
        if text.chars().count() < self.settings.min_query_chars {
            return CallAction::Proceed;
        }
        let Some((document, shown, from)) = self.recall(text, ev.session) else {
            return CallAction::Proceed;
        };

        // One announcement per process, or one per run — and the per-run set is only kept in the
        // mode that needs it. In `once_per_process` a run after the first is never announced, so a
        // session set there would only grow: one `String` per session ever recalled for, inside a
        // hook the dashboard holds for days.
        let announce = if self.reporting.once_per_process {
            !self
                .said_once
                .swap(true, std::sync::atomic::Ordering::SeqCst)
        } else {
            self.announced
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .insert(ev.session.to_string())
        };
        if announce {
            let noun = if shown == 1 { "excerpt" } else { "excerpts" };
            (self.reporting.sink)(&format!(
                "note: recall-sessions added {shown} {noun} from {from} earlier session(s) to this \
                 prompt; [hooks] order turns it off"
            ));
        }

        CallAction::Patch(RequestPatch {
            documents: vec![Message::system(document)],
            ..Default::default()
        })
    }
}

fn names(known: &[HookInfo]) -> String {
    known.iter().map(|h| h.name).collect::<Vec<_>>().join(", ")
}

/// Check `[hooks]` against the hooks `known`, saying what is wrong and what to do about it.
///
/// This is the whole of the "no silent ignoring" rule for hooks: the section is read with
/// `flatten` so that nothing in it is dropped by the parser, and every key is accounted for
/// here instead.
pub fn validate_with(section: &HooksConfig, known: &[HookInfo]) -> Result<(), String> {
    let mut seen: Vec<&str> = Vec::new();
    for name in &section.order {
        if !known.iter().any(|h| h.name == name) {
            return Err(format!(
                "[hooks] order names `{name}`, which this build does not have. \
                 Hooks that exist: {}. Fix the name, or remove it from order.",
                names(known)
            ));
        }
        if seen.contains(&name.as_str()) {
            return Err(format!(
                "[hooks] order lists `{name}` twice; a hook runs once per event, so the \
                 second entry would do nothing. Remove one."
            ));
        }
        seen.push(name);
    }
    for (key, value) in &section.settings {
        let Some(table) = value.as_table() else {
            return Err(format!(
                "[hooks] has a key `{key}` that is not a hook table. The only key directly \
                 under [hooks] is `order`; a hook's settings go in [hooks.<name>]."
            ));
        };
        let Some(info) = known.iter().find(|h| h.name == key) else {
            return Err(format!(
                "[hooks.{key}] configures a hook this build does not have. \
                 Hooks that exist: {}. Fix the name, or delete the table.",
                names(known)
            ));
        };
        if !seen.contains(&key.as_str()) {
            return Err(format!(
                "[hooks.{key}] is configured but `{key}` is not in [hooks] order, so it would \
                 never run. Add \"{key}\" to order, or delete the table."
            ));
        }
        if info.settings.is_empty() {
            return Err(format!(
                "[hooks.{key}] is a settings table, but the `{key}` hook takes no settings. \
                 Delete the table."
            ));
        }
        if let Some(unknown) = table.keys().find(|k| !info.settings.contains(&k.as_str())) {
            return Err(format!(
                "[hooks.{key}] has an unknown key `{unknown}`; this hook accepts: {}. \
                 Fix the spelling, or delete the key.",
                info.settings.join(", ")
            ));
        }
        (info.check)(table)?;
    }
    Ok(())
}

/// [`validate_with`] against what this build ships.
pub fn validate(section: &HooksConfig) -> Result<(), String> {
    validate_with(section, SHIPPED)
}

/// The `# hooks:` lines `eclipse config show` prints above the section: the order that is in
/// effect, and for each hook the loop point it is wired at.
pub fn describe(section: &HooksConfig) -> Vec<String> {
    if section.order.is_empty() {
        return vec![format!(
            "# hooks: none (order = []; the default is {:?})",
            DEFAULT_ORDER
        )];
    }
    let mut lines = vec![
        "# hooks, in run order (redact-secrets is on by default; recall-sessions is available and \
         off, because a new session is a new session — the agent reaches the archive through \
         `session_search`. `order = []` turns every hook off):"
            .to_string(),
    ];
    for (n, name) in section.order.iter().enumerate() {
        let point = SHIPPED
            .iter()
            .find(|h| h.name == name)
            .map_or("(unknown)", |h| h.point);
        lines.push(format!("#   {}. {name} @ {point}", n + 1));
    }
    // A hook that is shipped but not in the order is the one people ask about: it has settings in
    // their config and no effect. Naming it here is cheaper than reading hooks.rs.
    for hook in SHIPPED {
        if !section.order.iter().any(|n| n == hook.name) {
            lines.push(format!("#   - {} @ {} (off)", hook.name, hook.point));
        }
    }
    lines
}

/// Where a hook's one-line report goes, and how often.
///
/// A filter that rewrites what the model reads without saying so is worse than no filter, so
/// `redact-secrets` reports. Where that report is *shown* is the front end's business: the CLI
/// has a stderr, the full-screen UI would lose it to the alternate screen, and the dashboard
/// is one process serving many runs.
#[derive(Clone)]
pub struct Reporting {
    sink: Arc<dyn Fn(&str) + Send + Sync>,
    once_per_process: bool,
}

impl std::fmt::Debug for Reporting {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Reporting")
            .field("once_per_process", &self.once_per_process)
            .finish()
    }
}

impl Default for Reporting {
    fn default() -> Self {
        Self::stderr()
    }
}

impl Reporting {
    /// One line on stderr for every run that had something to report.
    pub fn stderr() -> Self {
        Self::to(Arc::new(|line| eprintln!("{line}")))
    }

    /// One line on stderr for the whole process: a dashboard serves runs for days, and the
    /// same sentence for every one of them would teach its reader to stop reading it.
    pub fn stderr_once_per_process() -> Self {
        Self {
            once_per_process: true,
            ..Self::stderr()
        }
    }

    /// Hand each line to `sink`, once per run.
    pub fn to(sink: Arc<dyn Fn(&str) + Send + Sync>) -> Self {
        Self {
            sink,
            once_per_process: false,
        }
    }
}

/// Build the hooks `[hooks]` names, in the order it names them.
///
/// The one place a config section becomes hooks, so `run`, the REPL, the full-screen UI, every
/// dashboard path and a `delegate` child all get the same ones. It takes the run's store
/// because `recall-sessions` reads the archive: a hook that guessed at a directory would be a
/// second opinion about where sessions live.
pub fn from_config(cfg: &Config, store: &crate::session::SessionStore) -> Result<LoopHooks, Error> {
    from_config_reporting(cfg, store, Reporting::default())
}

/// [`from_config`], with the report going where the caller says.
pub fn from_config_reporting(
    cfg: &Config,
    store: &crate::session::SessionStore,
    reporting: Reporting,
) -> Result<LoopHooks, Error> {
    validate(&cfg.hooks).map_err(Error::Config)?;
    let mut built: Vec<Arc<dyn LoopHook>> = Vec::new();
    for name in &cfg.hooks.order {
        match name.as_str() {
            "redact-secrets" => {
                let allow = match cfg.hooks.settings.get("redact-secrets") {
                    Some(toml::Value::Table(t)) => redact_allow(t).map_err(Error::Config)?,
                    _ => Vec::new(),
                };
                built.push(Arc::new(RedactSecrets::new(allow, reporting.clone())));
            }
            "recall-sessions" => {
                let settings = match cfg.hooks.settings.get("recall-sessions") {
                    Some(toml::Value::Table(t)) => recall_settings(t).map_err(Error::Config)?,
                    _ => RecallSettings::default(),
                };
                built.push(Arc::new(RecallSessions::new(
                    store.clone(),
                    settings,
                    reporting.clone(),
                )));
            }
            // `validate` proved every name is one this build ships; a name added to SHIPPED
            // without an arm here is caught by the test that builds every shipped hook.
            other => {
                return Err(Error::Config(format!(
                    "[hooks] order names `{other}`, which this build lists but cannot build. \
                     This is a bug in Eclipse; remove it from order and report it."
                )))
            }
        }
    }
    Ok(LoopHooks::new(built))
}

/// Replaces secrets in tool results before the model reads them, and before they are stored.
///
/// It sits at `on_outcome` because that is the one place a secret enters the conversation that
/// a hook can still stop: the request patch cannot edit messages, and a dispatch hook cannot
/// rewrite arguments, so what the user types and what the model writes in a call are not
/// scanned.
pub struct RedactSecrets {
    allow: Vec<String>,
    reporting: Reporting,
    /// Secrets replaced so far in each run that has not settled yet.
    counts: std::sync::Mutex<std::collections::HashMap<String, usize>>,
    announced: std::sync::atomic::AtomicBool,
}

impl RedactSecrets {
    pub fn new(allow: Vec<String>, reporting: Reporting) -> Self {
        Self {
            allow,
            reporting,
            counts: Default::default(),
            announced: Default::default(),
        }
    }

    fn counts(&self) -> std::sync::MutexGuard<'_, std::collections::HashMap<String, usize>> {
        self.counts
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

#[async_trait]
impl LoopHook for RedactSecrets {
    async fn on_outcome(&self, ev: Outcome<'_>) -> OutcomeAction {
        let found = crate::redact::redact(ev.output, &self.allow);
        if found.count == 0 {
            return OutcomeAction::Proceed;
        }
        *self.counts().entry(ev.session.to_string()).or_insert(0) += found.count;
        OutcomeAction::ReplaceOutput(found.text)
    }

    async fn on_run_settled(&self, ev: Settled<'_>) {
        let Some(count) = self.counts().remove(ev.session) else {
            return;
        };
        if count == 0 {
            return;
        }
        if self.reporting.once_per_process
            && self
                .announced
                .swap(true, std::sync::atomic::Ordering::SeqCst)
        {
            return;
        }
        let noun = if count == 1 { "secret" } else { "secrets" };
        let tail = if self.reporting.once_per_process {
            "; said once per process, later runs are not reported"
        } else {
            ""
        };
        (self.reporting.sink)(&format!(
            "note: redact-secrets replaced {count} {noun} in tool output; \
             [hooks] order turns it off{tail}"
        ));
    }
}

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

    /// A store with nothing in it: the tests that only care about redaction still have to hand the
    /// builder one, because `recall-sessions` reads the archive. The directory is owned by the
    /// returned store (see `Scratch`), so it is removed when the test statement ends instead of
    /// being left in `$TMPDIR`.
    fn scratch_store() -> crate::scratch::Scratch<crate::session::SessionStore> {
        crate::scratch::Scratch::new("eclipse-hooks-", |path| {
            crate::session::SessionStore::new(path.join("sessions"))
        })
    }

    #[test]
    fn an_empty_patch_says_so_and_claims_nothing() {
        let p = RequestPatch::default();
        assert!(p.is_empty());
        assert_eq!(p.describe(), "");
        let mut q = RequestPatch::default();
        q.extra_params
            .insert("top_p".into(), serde_json::json!(0.9));
        assert!(!q.is_empty());
        assert_eq!(q.describe(), "extra_params");
    }

    #[test]
    fn a_later_patch_wins_on_scalars_and_merges_extra_params() {
        let mut a = RequestPatch {
            temperature: Some(0.2),
            max_tokens: Some(100),
            extra_params: [("top_p".to_string(), serde_json::json!(0.5))]
                .into_iter()
                .collect(),
            ..Default::default()
        };
        let b = RequestPatch {
            temperature: Some(0.9),
            extra_params: [
                ("top_p".to_string(), serde_json::json!(0.95)),
                ("min_p".to_string(), serde_json::json!(0.05)),
            ]
            .into_iter()
            .collect(),
            ..Default::default()
        };
        a.merge(b);
        assert_eq!(a.temperature, Some(0.9), "later wins");
        assert_eq!(a.max_tokens, Some(100), "untouched fields survive");
        assert_eq!(a.extra_params["top_p"], serde_json::json!(0.95));
        assert_eq!(a.extra_params["min_p"], serde_json::json!(0.05));
    }

    /// Union would let a later hook quietly re-enable what an earlier one forbade, so two
    /// allow-lists can only ever narrow each other.
    #[test]
    fn two_allow_lists_compose_as_an_intersection() {
        let mut a = RequestPatch {
            active_tools: Some(vec!["read_file".into(), "shell".into(), "fetch".into()]),
            ..Default::default()
        };
        a.merge(RequestPatch {
            active_tools: Some(vec!["shell".into(), "write_file".into()]),
            ..Default::default()
        });
        assert_eq!(a.active_tools, Some(vec!["shell".to_string()]));
    }

    #[test]
    fn a_tool_choice_reads_from_config_as_one_string() {
        use ToolChoice::*;
        assert_eq!(ToolChoice::from_config_str("auto"), Auto);
        assert_eq!(ToolChoice::from_config_str(" none "), None);
        assert_eq!(ToolChoice::from_config_str("required"), Required);
        assert_eq!(
            ToolChoice::from_config_str("read_file"),
            Function("read_file".into()),
            "anything that is not a keyword is a tool name"
        );
        for choice in [Auto, None, Required, Function("read_file".into())] {
            assert_eq!(ToolChoice::from_config_str(choice.as_config_str()), choice);
        }
    }

    #[test]
    fn a_tool_choice_reaches_the_wire_in_the_shape_servers_expect() {
        assert_eq!(ToolChoice::Auto.to_json(), serde_json::json!("auto"));
        assert_eq!(ToolChoice::None.to_json(), serde_json::json!("none"));
        assert_eq!(
            ToolChoice::Required.to_json(),
            serde_json::json!("required")
        );
        assert_eq!(
            ToolChoice::Function("read_file".into()).to_json(),
            serde_json::json!({"type": "function", "function": {"name": "read_file"}})
        );
    }

    #[test]
    fn documents_concatenate_and_history_is_last_writer_wins() {
        let mut a = RequestPatch {
            documents: vec![Message::user("first")],
            history: Some(vec![Message::user("h1")]),
            ..Default::default()
        };
        a.merge(RequestPatch {
            documents: vec![Message::user("second")],
            history: Some(vec![Message::user("h2")]),
            ..Default::default()
        });
        assert_eq!(a.documents.len(), 2);
        assert_eq!(a.documents[0].content.as_deref(), Some("first"));
        assert_eq!(
            a.history.as_ref().unwrap()[0].content.as_deref(),
            Some("h2")
        );

        let mut b = RequestPatch::default();
        b.merge(RequestPatch {
            documents: vec![Message::user("only")],
            ..Default::default()
        });
        assert_eq!(b.documents.len(), 1);
        assert!(
            b.history.is_none(),
            "an absent history leaves the earlier one"
        );
    }

    #[test]
    fn documents_and_history_are_described() {
        let p = RequestPatch {
            documents: vec![Message::user("d")],
            history: Some(vec![Message::user("h")]),
            ..Default::default()
        };
        assert!(!p.is_empty());
        assert_eq!(p.describe(), "documents, history");
    }

    #[tokio::test]
    async fn a_dispatch_repair_is_returned_and_stop_still_ends_the_chain() {
        struct Repair;
        #[async_trait]
        impl LoopHook for Repair {
            async fn on_dispatch(&self, _ev: Dispatch<'_>) -> DispatchAction {
                DispatchAction::Repair {
                    name: "echo".into(),
                    arguments: r#"{"text":"fixed"}"#.into(),
                }
            }
        }
        let hooks = LoopHooks::new(vec![Arc::new(Repair) as Arc<dyn LoopHook>]);
        let got = hooks.dispatch("s", "broken", "not json").await.unwrap();
        assert_eq!(got.as_ref().unwrap().name, "echo");
        assert_eq!(got.as_ref().unwrap().arguments, r#"{"text":"fixed"}"#);

        struct Stop;
        #[async_trait]
        impl LoopHook for Stop {
            async fn on_dispatch(&self, _ev: Dispatch<'_>) -> DispatchAction {
                DispatchAction::Stop("no".into())
            }
        }
        let hooks = LoopHooks::new(vec![Arc::new(Stop) as Arc<dyn LoopHook>]);
        let err = hooks.dispatch("s", "t", "{}").await.unwrap_err();
        assert_eq!(err, "no");
    }

    #[tokio::test]
    async fn an_agent_with_no_hooks_asks_nothing_of_the_loop() {
        let hooks = LoopHooks::default();
        assert!(hooks.is_empty());
        let merged = hooks.completion_call("s", 1, &[], &[]).await.unwrap();
        assert!(merged.is_empty());
        assert_eq!(
            hooks
                .run_start(RunStart {
                    session: "s",
                    prompt: "p"
                })
                .await,
            None
        );
    }

    #[tokio::test]
    async fn a_stop_ends_the_chain_so_later_hooks_are_not_consulted() {
        struct Stopper;
        #[async_trait]
        impl LoopHook for Stopper {
            async fn on_completion_call(&self, _ev: CallEvent<'_>) -> CallAction {
                CallAction::Stop("no more turns".into())
            }
        }
        struct NeverReached(Arc<std::sync::atomic::AtomicUsize>);
        #[async_trait]
        impl LoopHook for NeverReached {
            async fn on_completion_call(&self, _ev: CallEvent<'_>) -> CallAction {
                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                CallAction::Proceed
            }
        }
        let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let hooks = LoopHooks::new(vec![
            Arc::new(Stopper) as Arc<dyn LoopHook>,
            Arc::new(NeverReached(counter.clone())),
        ]);
        let err = hooks.completion_call("s", 1, &[], &[]).await.unwrap_err();
        assert_eq!(err, "no more turns");
        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    fn config(text: &str) -> Config {
        Config::from_toml_str(text).unwrap()
    }

    fn collecting() -> (Reporting, Arc<std::sync::Mutex<Vec<String>>>) {
        let lines = Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = lines.clone();
        (
            Reporting::to(Arc::new(move |l: &str| {
                sink.lock().unwrap().push(l.to_string())
            })),
            lines,
        )
    }

    async fn run_with_secret(hooks: &LoopHooks, session: &str, output: &str) -> String {
        let shown = match hooks.outcome(session, "read", output, false, false).await {
            OutcomeAction::ReplaceOutput(t) => t,
            OutcomeAction::Proceed => output.to_string(),
            OutcomeAction::Stop(r) => panic!("unexpected stop: {r}"),
        };
        hooks
            .run_settled(Settled {
                session,
                turns: 1,
                ending: Ending::Answered,
            })
            .await;
        shown
    }

    const KEY: &str = "sk-abcdefghijklmnopqrstuvwxyz0123";

    #[test]
    fn an_order_of_nothing_builds_no_hooks_and_the_default_builds_the_default_order() {
        assert!(
            from_config(&config("[hooks]\norder = []\n"), &scratch_store())
                .unwrap()
                .is_empty()
        );
        // An absent `[hooks]` gets exactly `DEFAULT_ORDER`, which is redaction only: recall is
        // implemented and available, but off unless `order` names it.
        assert_eq!(
            from_config(&config(""), &scratch_store()).unwrap().len(),
            DEFAULT_ORDER.len()
        );
        assert_eq!(
            from_config(&Config::default(), &scratch_store())
                .unwrap()
                .len(),
            DEFAULT_ORDER.len()
        );
    }

    #[test]
    fn building_hooks_from_a_config_that_was_never_validated_still_refuses_it() {
        let err =
            from_config(&config("[hooks]\norder = [\"nope\"]\n"), &scratch_store()).unwrap_err();
        assert!(err.to_string().contains("`nope`"), "{err}");
        let err = from_config(
            &config("[hooks]\norder = []\n[hooks.redact-secrets]\n"),
            &scratch_store(),
        )
        .unwrap_err();
        assert!(err.to_string().contains("never run"), "{err}");
    }

    // ---- recall-sessions: the archive as memory ------------------------------------------

    /// Two sessions: one that talked about the docker bridge, and the one being written now.
    fn memory_store() -> crate::session::SessionStore {
        let dir = tempfile::tempdir().unwrap();
        let store = crate::session::SessionStore::new(dir.keep().join("sessions"));
        store
            .append(
                "earlier",
                &Message::user("the docker bridge address for the host is 172.17.0.1"),
            )
            .unwrap();
        store.rename("earlier", "bridge notes").unwrap();
        store
            .append(
                "current",
                &Message::user("which address does the container use for the host?"),
            )
            .unwrap();
        store
    }

    const PROMPT: &str = "which address does the container use for the host?";

    fn call_event<'a>(session: &'a str, messages: &'a [Message]) -> CallEvent<'a> {
        CallEvent {
            session,
            turn: 1,
            messages,
            tools: &[],
        }
    }

    fn quiet() -> Reporting {
        Reporting::to(Arc::new(|_| {}))
    }

    #[tokio::test]
    async fn the_recall_hook_puts_an_earlier_session_in_front_of_the_model() {
        let hook = RecallSessions::new(memory_store(), RecallSettings::default(), quiet());
        let messages = vec![Message::system("you are eclipse"), Message::user(PROMPT)];
        let action = hook
            .on_completion_call(call_event("current", &messages))
            .await;
        let CallAction::Patch(patch) = action else {
            panic!("a prompt that matches the archive has to be answered with a patch");
        };
        assert_eq!(patch.documents.len(), 1, "one document, not one per hit");
        let text = patch.documents[0].content.clone().unwrap_or_default();
        assert!(
            text.starts_with("## Recalled from earlier sessions"),
            "{text}"
        );
        assert!(
            text.contains("session `earlier`"),
            "the session is named: {text}"
        );
        assert!(text.contains("bridge notes"), "and so is its title: {text}");
        assert!(
            text.contains("docker bridge address"),
            "with the text: {text}"
        );
        assert!(
            text.contains("session_search(session=\"earlier\""),
            "and the way to read around it: {text}"
        );
        assert!(
            !text.contains("session `current`"),
            "the conversation being written is not its own memory: {text}"
        );
    }

    #[tokio::test]
    async fn a_recall_can_be_told_to_include_the_session_it_is_writing() {
        let settings = RecallSettings {
            include_this_session: true,
            ..Default::default()
        };
        let hook = RecallSessions::new(memory_store(), settings, quiet());
        let messages = vec![Message::system("sys"), Message::user(PROMPT)];
        let CallAction::Patch(patch) = hook
            .on_completion_call(call_event("current", &messages))
            .await
        else {
            panic!("expected a patch");
        };
        let text = patch.documents[0].content.clone().unwrap_or_default();
        assert!(text.contains("this session"), "{text}");
        assert!(
            text.contains("session `earlier`"),
            "and the earlier one is still there: {text}"
        );
    }

    #[tokio::test]
    async fn a_short_prompt_is_not_a_query_and_a_tool_result_is_not_a_prompt() {
        let hook = RecallSessions::new(memory_store(), RecallSettings::default(), quiet());
        let short = vec![Message::system("sys"), Message::user("go on")];
        assert_eq!(
            hook.on_completion_call(call_event("current", &short)).await,
            CallAction::Proceed,
            "\"go on\" is not a search"
        );

        // After a tool result the newest message is not the user's: the memory was injected on
        // the turn's first call and must not be injected again for this prompt.
        let mid_turn = vec![
            Message::system("sys"),
            Message::user(PROMPT),
            Message::tool_result("c1", "ok"),
        ];
        assert_eq!(
            hook.on_completion_call(call_event("current", &mid_turn))
                .await,
            CallAction::Proceed,
            "a tool round-trip is not a new prompt"
        );
    }

    #[tokio::test]
    async fn a_recall_that_matches_nothing_says_nothing() {
        let hook = RecallSessions::new(
            memory_store(),
            RecallSettings {
                min_query_chars: 0,
                ..Default::default()
            },
            quiet(),
        );
        let messages = vec![
            Message::system("sys"),
            Message::user("zebra xylophone quokka"),
        ];
        assert_eq!(
            hook.on_completion_call(call_event("current", &messages))
                .await,
            CallAction::Proceed
        );
    }

    #[tokio::test]
    async fn a_recall_stays_inside_its_budget_including_its_pointer() {
        let messages = vec![Message::system("sys"), Message::user(PROMPT)];

        // Smaller than the heading plus the pointer: nothing fits, so nothing is injected
        // rather than a document that breaks its own cap.
        let tight = RecallSessions::new(
            memory_store(),
            RecallSettings {
                budget_chars: 320,
                ..Default::default()
            },
            quiet(),
        );
        assert_eq!(
            tight
                .on_completion_call(call_event("current", &messages))
                .await,
            CallAction::Proceed
        );

        let roomy = RecallSessions::new(
            memory_store(),
            RecallSettings {
                budget_chars: 900,
                results: 8,
                ..Default::default()
            },
            quiet(),
        );
        let CallAction::Patch(patch) = roomy
            .on_completion_call(call_event("current", &messages))
            .await
        else {
            panic!("expected a patch");
        };
        let text = patch.documents[0].content.clone().unwrap_or_default();
        assert!(
            text.chars().count() <= 900,
            "{} chars over a 900 cap: {text}",
            text.chars().count()
        );
        assert!(
            text.contains("session_search(session="),
            "the pointer is inside the cap, not appended after it: {text}"
        );
        assert!(text.contains("bridge notes"), "{text}");
    }

    #[tokio::test]
    async fn a_recall_setting_outside_its_range_is_refused_with_the_bounds() {
        let mut table = toml::value::Table::new();
        table.insert("results".to_string(), toml::Value::Integer(99));
        let err = check_recall_settings(&table).unwrap_err();
        assert!(err.contains("`results`") && err.contains("1 to 8"), "{err}");

        let mut table = toml::value::Table::new();
        table.insert(
            "include_this_session".to_string(),
            toml::Value::String("yes".to_string()),
        );
        let err = check_recall_settings(&table).unwrap_err();
        assert!(err.contains("true or false"), "{err}");
    }

    #[test]
    fn a_prompt_is_searched_by_its_content_words() {
        let terms = recall_terms("Which address does the container use for the HOST, again?");
        assert!(
            terms.contains(&"address".to_string())
                && terms.contains(&"container".to_string())
                && terms.contains(&"host".to_string()),
            "{terms:?}"
        );
        assert!(
            !terms.contains(&"the".to_string()) && !terms.contains(&"does".to_string()),
            "stopwords are not terms: {terms:?}"
        );
        assert!(
            recall_terms("ok").is_empty(),
            "a two-letter word is not a query"
        );
        assert_eq!(
            recall_terms(&"alpha ".repeat(20)).len(),
            1,
            "duplicates collapse"
        );
    }

    #[test]
    fn every_hook_this_build_ships_can_be_built_and_names_a_point() {
        for info in SHIPPED {
            let cfg = config(&format!("[hooks]\norder = [\"{}\"]\n", info.name));
            assert_eq!(
                from_config(&cfg, &scratch_store()).unwrap().len(),
                1,
                "{}",
                info.name
            );
            assert!(info.point.starts_with("on_"), "{}", info.name);
        }
    }

    #[test]
    fn a_hook_that_takes_no_settings_refuses_a_settings_table() {
        fn accept_anything(_: &toml::value::Table) -> Result<(), String> {
            Ok(())
        }
        let known = [HookInfo {
            name: "plain",
            point: "on_outcome",
            settings: &[],
            check: accept_anything,
        }];
        let ok = config("[hooks]\norder = [\"plain\"]\n");
        assert!(validate_with(&ok.hooks, &known).is_ok());
        let bad = config("[hooks]\norder = [\"plain\"]\n[hooks.plain]\nallow = []\n");
        let err = validate_with(&bad.hooks, &known).unwrap_err();
        assert!(err.contains("takes no settings"), "{err}");
        assert!(err.contains("Delete the table"), "{err}");
    }

    #[test]
    fn config_show_names_the_order_and_the_point_each_hook_is_wired_at() {
        // Recall is available but not default: the header says which hooks are on and which
        // are merely known, so `config show` answers "why did a new session have old text in
        // it" without reading this file.
        let on = describe(&Config::default().hooks);
        assert!(
            on[0].contains("redact-secrets is on by default") && on[0].contains("recall-sessions"),
            "{on:?}"
        );
        assert_eq!(on[1], "#   1. redact-secrets @ on_outcome");
        assert_eq!(on[2], "#   - recall-sessions @ on_completion_call (off)");
        // Naming it in `order` turns it on, and the describe line stops saying `(off)`.
        let back_on = describe(&config("[hooks]\norder = [\"recall-sessions\"]\n").hooks);
        assert_eq!(back_on[1], "#   1. recall-sessions @ on_completion_call");
        let off = describe(&config("[hooks]\norder = []\n").hooks);
        assert_eq!(off.len(), 1);
        assert!(off[0].starts_with("# hooks: none"), "{off:?}");
        assert!(
            off[0].contains("the default is [\"redact-secrets\"]"),
            "{off:?}"
        );
    }

    #[tokio::test]
    async fn redact_secrets_replaces_a_secret_in_a_tool_result_and_leaves_the_rest() {
        let hooks = from_config_reporting(&config(""), &scratch_store(), collecting().0).unwrap();
        let shown = run_with_secret(&hooks, "s", &format!("key is {KEY} ok")).await;
        assert_eq!(shown, "key is [redacted:api-key] ok");
    }

    #[tokio::test]
    async fn a_result_with_nothing_to_redact_is_not_replaced_at_all() {
        let hooks = from_config_reporting(&config(""), &scratch_store(), collecting().0).unwrap();
        let action = hooks
            .outcome(
                "s",
                "read",
                "2024-01-01 INFO listening on :8080",
                false,
                false,
            )
            .await;
        assert_eq!(action, OutcomeAction::Proceed);
    }

    #[tokio::test]
    async fn an_allowed_literal_is_not_redacted_and_not_reported() {
        let cfg = config(&format!("[hooks.redact-secrets]\nallow = [\"{KEY}\"]\n"));
        let (reporting, lines) = collecting();
        let hooks = from_config_reporting(&cfg, &scratch_store(), reporting).unwrap();
        let text = format!("fixture {KEY}");
        assert_eq!(run_with_secret(&hooks, "s", &text).await, text);
        assert!(lines.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn the_report_comes_once_per_run_and_counts_every_secret_in_it() {
        let (reporting, lines) = collecting();
        let hooks = from_config_reporting(&config(""), &scratch_store(), reporting).unwrap();
        // Two results in one run, then settle: one line.
        let first = hooks
            .outcome("s", "read", &format!("a {KEY}"), false, false)
            .await;
        assert!(matches!(first, OutcomeAction::ReplaceOutput(_)));
        run_with_secret(&hooks, "s", &format!("b {KEY} and password=hunter2hunter2")).await;
        assert_eq!(
            lines.lock().unwrap().as_slice(),
            ["note: redact-secrets replaced 3 secrets in tool output; [hooks] order turns it off"]
        );
        // A clean run says nothing; the next run with a secret says it again.
        run_with_secret(&hooks, "t", "nothing here").await;
        assert_eq!(lines.lock().unwrap().len(), 1);
        run_with_secret(&hooks, "u", KEY).await;
        let lines = lines.lock().unwrap();
        assert_eq!(lines.len(), 2);
        assert!(lines[1].contains("replaced 1 secret in"), "{}", lines[1]);
    }

    #[tokio::test]
    async fn the_report_of_a_long_lived_process_comes_once_not_once_per_run() {
        let lines = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let sink = lines.clone();
        let mut reporting = Reporting::to(Arc::new(move |l: &str| {
            sink.lock().unwrap().push(l.to_string())
        }));
        reporting.once_per_process = true;
        let hooks = from_config_reporting(&config(""), &scratch_store(), reporting).unwrap();
        for session in ["a", "b", "c"] {
            run_with_secret(&hooks, session, KEY).await;
        }
        let lines = lines.lock().unwrap();
        assert_eq!(lines.len(), 1);
        assert!(lines[0].contains("said once per process"), "{}", lines[0]);
    }

    /// `once_per_process` needs no per-session set: after the first run nothing is announced, so the
    /// set could only grow — one `String` per session recalled for, in a hook held for days.
    #[tokio::test]
    async fn once_per_process_announces_once_and_remembers_no_sessions() {
        let (mut reporting, lines) = collecting();
        reporting.once_per_process = true;
        let hook = RecallSessions::new(memory_store(), RecallSettings::default(), reporting);

        for session in ["current", "other", "third"] {
            let messages = vec![Message::system("you are eclipse"), Message::user(PROMPT)];
            let action = hook
                .on_completion_call(call_event(session, &messages))
                .await;
            assert!(
                matches!(action, CallAction::Patch(_)),
                "every prompt still gets its patch — suppressing the note must not suppress the memory"
            );
        }

        assert_eq!(lines.lock().unwrap().len(), 1, "one line for the process");
        assert!(
            hook.announced.lock().unwrap().is_empty(),
            "and no session set: {:?}",
            hook.announced.lock().unwrap()
        );
    }

    #[tokio::test]
    async fn two_runs_at_once_are_counted_apart() {
        let (reporting, lines) = collecting();
        let hooks = from_config_reporting(&config(""), &scratch_store(), reporting).unwrap();
        let _ = hooks.outcome("a", "read", KEY, false, false).await;
        run_with_secret(&hooks, "b", "clean").await;
        assert!(
            lines.lock().unwrap().is_empty(),
            "b must not report a's secret"
        );
        run_with_secret(&hooks, "a", "clean").await;
        assert_eq!(lines.lock().unwrap().len(), 1);
    }
}