thoughtjack 0.6.0

Adversarial agent security testing tool
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
//! Core execution loop for OATF phase-based attack scenarios.
//!
//! `PhaseLoop<D>` owns the common phase machinery — event processing,
//! extractor capture, trigger evaluation, phase advancement, trace
//! append, and cross-actor extractor awaiting. It is generic over the
//! protocol-specific `PhaseDriver`.
//!
//! `ExtractorStore` provides thread-safe cross-actor extractor storage.
//!
//! See TJ-SPEC-013 §8.4 for the phase loop specification.
#![allow(clippy::redundant_pub_crate)]

use std::collections::HashMap;
use std::sync::Arc;

use oatf::enums::ExtractorSource;
use oatf::primitives::evaluate_extractor;
use serde_json::json;
use tokio::sync::{mpsc, watch};
use tokio_util::sync::CancellationToken;

use crate::error::EngineError;
use crate::observability::events::{EventEmitter, ThoughtJackEvent};
use crate::orchestration::store::ExtractorStore;

use super::actions::{self, EntryActionSender};
use super::driver::PhaseDriver;
use super::phase::PhaseEngine;
use super::trace::SharedTrace;
use super::types::{
    ActorResult, AwaitExtractor, Direction, PhaseAction, ProtocolEvent, TerminationReason,
};

/// Maximum number of buffered protocol events per phase.
///
/// Provides backpressure: if the phase loop cannot drain events fast
/// enough, drivers block on `send().await`. The capacity is generous
/// enough that backpressure should never trigger under normal operation.
const EVENT_CHANNEL_CAPACITY: usize = 10_000;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DriveLoopAction {
    Stay,
    Advance,
    TransportClosed,
}

// ============================================================================
// Free functions for event processing
// ============================================================================
//
// These are free functions (not methods on PhaseLoop) to allow the borrow
// checker to see disjoint field accesses when used inside tokio::select!
// alongside the driver future.

/// Shared immutable context passed to free event-processing functions.
///
/// Bundles references that are shared across event processing calls,
/// avoiding excessive argument counts on free functions.
struct EventContext<'a> {
    trace: &'a SharedTrace,
    extractor_store: &'a ExtractorStore,
    extractors_tx: &'a watch::Sender<HashMap<String, String>>,
    actor_name: &'a str,
    protocol: &'a str,
    is_server_mode: bool,
    is_context_mode: bool,
    events: &'a EventEmitter,
}

/// Process a single event: trace append, extractor capture, trigger check.
fn process_protocol_event(
    evt: ProtocolEvent,
    phase_engine: &mut PhaseEngine,
    ctx: &EventContext<'_>,
) -> PhaseAction {
    let qualifier = extract_qualifier(&evt.method, &evt.content);

    // 1. Append to trace
    ctx.trace.append(
        ctx.actor_name,
        phase_engine.current_phase_name(),
        evt.direction,
        &evt.method,
        &evt.content,
    );

    // 2. Run extractors
    run_extractors(
        &evt,
        phase_engine,
        ctx.extractor_store,
        ctx.actor_name,
        ctx.is_server_mode,
    );

    // Publish updated extractors
    let _ = ctx.extractors_tx.send(build_interpolation_extractors(
        phase_engine,
        ctx.extractor_store,
    ));

    // 3. Check trigger (incoming only) then emit observability event with trigger progress.
    //
    // Outgoing events are ThoughtJack's own responses/requests. Counting
    // them would double-count each interaction (e.g., `count: 5` on
    // `tools/call` would fire after ~3 requests because each generates
    // both an incoming request and an outgoing response event).
    if evt.direction == Direction::Incoming {
        // A2A event aliasing for context-mode (R3):  In context-mode,
        // all server actors receive `tools/call` events, but OATF A2A
        // triggers use A2A-specific event names.  Map in-place for
        // trigger evaluation only (trace retains the original method).
        let trigger_method = if ctx.is_context_mode && ctx.protocol == "a2a" {
            match evt.method.as_str() {
                "tools/call" => "tasks/send".to_string(),
                "tools/list" => "agent_card_read".to_string(),
                _ => evt.method.clone(),
            }
        } else {
            evt.method.clone()
        };

        let oatf_event = oatf::ProtocolEvent {
            event_type: trigger_method,
            content: evt.content.clone(),
        };
        let result = phase_engine.process_event(&oatf_event);

        // Emit with trigger progress after evaluation
        let trigger = phase_engine.current_trigger();
        ctx.events.emit(ThoughtJackEvent::ProtocolMessageReceived {
            actor: ctx.actor_name.to_string(),
            method: evt.method,
            protocol: ctx.protocol.to_string(),
            qualifier,
            trigger_current: Some(phase_engine.trigger_state.event_count),
            trigger_total: trigger.and_then(|t| t.count),
        });

        result
    } else {
        ctx.events.emit(ThoughtJackEvent::ProtocolMessageSent {
            actor: ctx.actor_name.to_string(),
            method: evt.method,
            protocol: ctx.protocol.to_string(),
            duration_ms: 0,
            qualifier,
        });
        PhaseAction::Stay
    }
}

/// Extracts a qualifier (tool name, resource URI, etc.) from event content.
fn extract_qualifier(method: &str, content: &serde_json::Value) -> Option<String> {
    match method {
        "tools/call" => content
            .pointer("/name")
            .or_else(|| content.pointer("/params/name"))
            .and_then(serde_json::Value::as_str)
            .map(String::from),
        "resources/read" => content
            .pointer("/uri")
            .or_else(|| content.pointer("/params/uri"))
            .and_then(serde_json::Value::as_str)
            .map(String::from),
        "prompts/get" => content
            .pointer("/name")
            .or_else(|| content.pointer("/params/name"))
            .and_then(serde_json::Value::as_str)
            .map(String::from),
        _ => None,
    }
}

/// Drain any remaining buffered events after driver completes.
///
/// Stops processing immediately after the first `Advance` to avoid
/// running extractors in the wrong phase context.
fn drain_events(
    event_rx: &mut mpsc::Receiver<ProtocolEvent>,
    phase_engine: &mut PhaseEngine,
    ctx: &EventContext<'_>,
) -> PhaseAction {
    while let Ok(evt) = event_rx.try_recv() {
        if process_protocol_event(evt, phase_engine, ctx) == PhaseAction::Advance {
            return PhaseAction::Advance;
        }
    }
    PhaseAction::Stay
}

/// Run extractors from the current phase against a protocol event.
///
/// The `is_server_mode` flag controls the `Direction` → `ExtractorSource`
/// mapping. In server mode, incoming messages are requests and outgoing
/// messages are responses. In client mode, the mapping is reversed.
fn run_extractors(
    event: &ProtocolEvent,
    phase_engine: &mut PhaseEngine,
    extractor_store: &ExtractorStore,
    actor_name: &str,
    is_server_mode: bool,
) {
    let current_phase = phase_engine.current_phase;
    let phase = phase_engine.get_phase(current_phase);

    // Clone extractors to release the borrow on phase_engine
    let Some(extractors) = phase.extractors.clone() else {
        return;
    };

    for extractor in &extractors {
        // Server mode: Incoming = Request, Outgoing = Response
        // Client mode: Incoming = Response, Outgoing = Request
        let source = match (event.direction, is_server_mode) {
            (Direction::Incoming, true) | (Direction::Outgoing, false) => ExtractorSource::Request,
            (Direction::Outgoing, true) | (Direction::Incoming, false) => ExtractorSource::Response,
        };

        if let Some(value) = evaluate_extractor(extractor, &event.content, source) {
            // Local scope
            phase_engine
                .extractor_values
                .insert(extractor.name.clone(), value.clone());
            // Shared scope
            extractor_store.set(actor_name, &extractor.name, value);
        }
    }
}

/// Build the extractors map for SDK interpolation (local + qualified).
fn build_interpolation_extractors(
    phase_engine: &PhaseEngine,
    extractor_store: &ExtractorStore,
) -> HashMap<String, String> {
    let mut map = phase_engine.extractor_values.clone();
    map.extend(extractor_store.all_qualified());
    map
}

// ============================================================================
// PhaseLoop
// ============================================================================

/// Configuration for constructing a `PhaseLoop`.
///
/// Bundles the non-driver, non-engine parameters that the `PhaseLoop`
/// needs to operate.
///
/// Implements: TJ-SPEC-013 F-001
pub struct PhaseLoopConfig {
    /// Shared trace buffer for protocol event recording.
    pub trace: SharedTrace,
    /// Cross-actor extractor storage.
    pub extractor_store: ExtractorStore,
    /// Name of the actor this loop drives.
    pub actor_name: String,
    /// Per-phase `await_extractors` configuration (keyed by phase index).
    pub await_extractors_config: HashMap<usize, Vec<AwaitExtractor>>,
    /// Cooperative cancellation token.
    pub cancel: CancellationToken,
    /// Optional sender for entry actions (notifications, elicitations).
    pub entry_action_sender: Option<Box<dyn EntryActionSender>>,
    /// Event emitter for structured observability events.
    pub events: Arc<EventEmitter>,
    /// Optional watch channel for publishing tool definitions on phase advance.
    ///
    /// Used in context-mode to synchronize tool definitions with the drive loop.
    /// Traffic-mode passes `None`.
    pub tool_watch_tx: Option<watch::Sender<Vec<crate::transport::context::ToolDefinition>>>,
    /// Optional watch channel for publishing the current A2A default skill on
    /// phase advance.  Ensures the drive loop dispatches to the correct skill
    /// after capability escalation.
    pub a2a_skill_tx: Option<watch::Sender<Option<String>>>,
    /// Whether this loop runs in context mode.
    ///
    /// Enables A2A event aliasing and temporal trigger bypass.
    /// Defaults to `false` (traffic mode).
    pub context_mode: bool,
}

/// Core execution loop for a single actor.
///
/// Generic over the protocol-specific `PhaseDriver`. Owns the phase
/// engine, trace, extractor store, and watch channel for publishing
/// fresh extractor values to the driver.
///
/// Implements: TJ-SPEC-013 F-001
pub struct PhaseLoop<D: PhaseDriver> {
    driver: D,
    phase_engine: PhaseEngine,
    trace: SharedTrace,
    extractor_store: ExtractorStore,
    actor_name: String,
    protocol: String,
    is_server_mode: bool,
    context_mode: bool,
    await_extractors_config: HashMap<usize, Vec<AwaitExtractor>>,
    cancel: CancellationToken,
    extractors_tx: watch::Sender<HashMap<String, String>>,
    entry_action_sender: Option<Box<dyn EntryActionSender>>,
    events: Arc<EventEmitter>,
    tool_watch_tx: Option<watch::Sender<Vec<crate::transport::context::ToolDefinition>>>,
    a2a_skill_tx: Option<watch::Sender<Option<String>>>,
}

impl<D: PhaseDriver> PhaseLoop<D> {
    /// Creates a new `PhaseLoop` for the given driver, engine, and config.
    ///
    /// Derives the protocol string from the actor's mode using the SDK.
    ///
    /// Implements: TJ-SPEC-013 F-001
    #[must_use]
    pub fn new(driver: D, mut phase_engine: PhaseEngine, config: PhaseLoopConfig) -> Self {
        let mode = &phase_engine.actor().mode;
        let protocol = crate::verdict::evaluation::extract_protocol(mode).to_string();
        let is_server_mode = mode.ends_with("_server");
        let (extractors_tx, _) = watch::channel(HashMap::new());
        phase_engine.context_mode = config.context_mode;

        Self {
            driver,
            phase_engine,
            trace: config.trace,
            extractor_store: config.extractor_store,
            actor_name: config.actor_name,
            protocol,
            is_server_mode,
            context_mode: config.context_mode,
            await_extractors_config: config.await_extractors_config,
            cancel: config.cancel,
            extractors_tx,
            entry_action_sender: config.entry_action_sender,
            events: config.events,
            tool_watch_tx: config.tool_watch_tx,
            a2a_skill_tx: config.a2a_skill_tx,
        }
    }

    /// Runs the phase loop to completion.
    ///
    /// Iterates through phases: awaits extractors, executes entry actions,
    /// runs the driver concurrently with event processing, and handles
    /// phase transitions.
    ///
    /// # Errors
    ///
    /// Returns `EngineError` if the driver or event processing fails.
    ///
    /// Implements: TJ-SPEC-013 F-001
    #[allow(clippy::too_many_lines)]
    pub async fn run(&mut self) -> Result<ActorResult, EngineError> {
        let mut last_emitted_phase: Option<usize> = None;
        loop {
            let phase_index = self.phase_engine.current_phase;

            let mut phase_message_count: usize = 0;

            // Emit PhaseEntered only on actual phase changes
            if last_emitted_phase != Some(phase_index) {
                last_emitted_phase = Some(phase_index);
                let phase_name = self.phase_engine.current_phase_name().to_string();
                let trigger = self.phase_engine.current_trigger();
                self.events.emit(ThoughtJackEvent::PhaseEntered {
                    actor: self.actor_name.clone(),
                    phase_name,
                    phase_index,
                    trigger_event: trigger.and_then(|t| t.event.clone()),
                    trigger_count: trigger.and_then(|t| t.count),
                });
            }

            if self.prepare_phase(phase_index).await {
                return Ok(self.build_result(TerminationReason::Cancelled));
            }
            let effective_state = self.phase_engine.effective_state();
            let (event_tx, mut event_rx) = mpsc::channel(EVENT_CHANNEL_CAPACITY);

            // Context-mode: when a phase's on_enter sends
            // notifications/tools/list_changed, there is no real agent to
            // re-fetch the tool list. Inject a synthetic tools/list event so
            // the phase trigger can evaluate against it (enables rug pull /
            // temporal attack scenarios like OATF-002).
            if self.context_mode {
                let phase = self.phase_engine.get_phase(phase_index);
                if let Some(on_enter) = &phase.on_enter {
                    let sends_list_changed = on_enter.iter().any(|a| {
                        matches!(
                            a,
                            oatf::Action::Send { method, .. }
                                if method == "notifications/tools/list_changed"
                        )
                    });
                    if sends_list_changed {
                        let _ = event_tx.try_send(ProtocolEvent {
                            direction: Direction::Incoming,
                            method: "tools/list".to_string(),
                            content: effective_state.get("tools").cloned().unwrap_or(json!([])),
                        });
                        tracing::debug!(
                            actor = %self.actor_name,
                            phase = phase_index,
                            "injected synthetic tools/list event for tools/list_changed on_enter"
                        );
                    }
                }
            }

            // Context-mode A2A: inject synthetic agent_card_read at phase 0.
            // This represents the moment the LLM's tool list is loaded and
            // the Agent Card has been "discovered" by the orchestrator.
            if self.context_mode && self.protocol == "a2a" && phase_index == 0 {
                let _ = event_tx.try_send(ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "agent_card_read".to_string(),
                    content: effective_state
                        .get("agent_card")
                        .cloned()
                        .unwrap_or(json!({})),
                });
                tracing::debug!(
                    actor = %self.actor_name,
                    "injected synthetic agent_card_read event for A2A context-mode"
                );
            }

            // Run driver and event consumer concurrently.
            // drive_fut is scoped so its mutable borrow drops before on_phase_advanced.
            let phase_cancel = self.cancel.child_token();
            let ctx = EventContext {
                trace: &self.trace,
                extractor_store: &self.extractor_store,
                extractors_tx: &self.extractors_tx,
                actor_name: &self.actor_name,
                protocol: &self.protocol,
                is_server_mode: self.is_server_mode,
                is_context_mode: self.context_mode,
                events: &self.events,
            };
            let action = {
                let extractors_rx = self.extractors_tx.subscribe();

                let drive_fut = self.driver.drive_phase(
                    phase_index,
                    &effective_state,
                    extractors_rx,
                    event_tx,
                    phase_cancel.clone(),
                );

                tokio::pin!(drive_fut);

                let mut phase_advancing = false;
                loop {
                    tokio::select! {
                        result = &mut drive_fut => {
                            let drive_result = result?;
                            let drained_action = drain_events(&mut event_rx, &mut self.phase_engine, &ctx);
                            break match drive_result {
                                super::types::DriveResult::Complete => {
                                    if phase_advancing || drained_action == PhaseAction::Advance {
                                        DriveLoopAction::Advance
                                    } else {
                                        DriveLoopAction::Stay
                                    }
                                }
                                super::types::DriveResult::TransportClosed => {
                                    DriveLoopAction::TransportClosed
                                }
                            };
                        }
                        event = event_rx.recv() => {
                            match event {
                                Some(evt) => {
                                    phase_message_count += 1;
                                    if process_protocol_event(evt, &mut self.phase_engine, &ctx)
                                        == PhaseAction::Advance
                                    {
                                        phase_advancing = true;
                                        phase_cancel.cancel();
                                    }
                                    // Drain remaining queued events before yielding
                                    // back to the driver.  In context mode all channel
                                    // sends are non-blocking, so the driver can queue
                                    // many events between polls.  Processing them all
                                    // here ensures the trigger fires before the driver
                                    // consumes the next message.
                                    while !phase_advancing {
                                        match event_rx.try_recv() {
                                            Ok(queued) => {
                                                phase_message_count += 1;
                                                if process_protocol_event(
                                                    queued,
                                                    &mut self.phase_engine,
                                                    &ctx,
                                                ) == PhaseAction::Advance
                                                {
                                                    phase_advancing = true;
                                                    phase_cancel.cancel();
                                                }
                                            }
                                            Err(_) => break,
                                        }
                                    }
                                }
                                None => {
                                    break if phase_advancing {
                                        DriveLoopAction::Advance
                                    } else {
                                        DriveLoopAction::Stay
                                    };
                                }
                            }
                        }
                        () = self.cancel.cancelled() => {
                            // Cannot call self.build_result() here because
                            // self.driver is mutably borrowed by drive_fut.
                            let actor = self.phase_engine.actor();
                            let current = self.phase_engine.current_phase;
                            return Ok(ActorResult {
                                actor_name: self.actor_name.clone(),
                                termination: TerminationReason::Cancelled,
                                phases_completed: current,
                                total_phases: actor.phases.len(),
                                final_phase: actor
                                    .phases
                                    .get(current)
                                    .and_then(|p| p.name.clone()),
                            });
                        }
                    }
                }
            };

            if action == DriveLoopAction::TransportClosed {
                return Ok(self.build_result(TerminationReason::TransportClosed));
            }

            // Context-mode client actors: exit after their terminal phase
            // runs once. The drive_phase sent the final run_agent_input and
            // received run_finished — no more work to do.
            if action == DriveLoopAction::Stay
                && self.phase_engine.is_terminal()
                && self.context_mode
                && !self.is_server_mode
            {
                return Ok(self.build_result(TerminationReason::TerminalPhaseReached));
            }

            if action == DriveLoopAction::Advance {
                #[allow(clippy::cast_possible_truncation)]
                let phase_elapsed_ms =
                    self.phase_engine.phase_start_time.elapsed().as_millis() as u64;
                self.events.emit(ThoughtJackEvent::PhaseCompleted {
                    actor: self.actor_name.clone(),
                    phase_name: self.phase_engine.current_phase_name().to_string(),
                    duration_ms: phase_elapsed_ms,
                    message_count: phase_message_count,
                });
                let to = self.phase_engine.advance_phase();
                // Publish updated tool definitions on the watch channel (context-mode).
                if let Some(ref tx) = self.tool_watch_tx {
                    let effective = self.phase_engine.effective_state();
                    let tools = crate::transport::context::extract_tool_definitions_for_actor(
                        &effective,
                        &self.actor_name,
                        &self.phase_engine.actor().mode,
                    );
                    let _ = tx.send(tools);

                    // Also update the A2A default skill so dispatch uses
                    // the current phase's first skill, not the Phase 0 one.
                    if let Some(ref skill_tx) = self.a2a_skill_tx {
                        let new_skill = crate::engine::a2a::skill_array(&effective)
                            .and_then(|arr| arr.first())
                            .and_then(|s| crate::engine::a2a::skill_name(s))
                            .map(String::from);
                        let _ = skill_tx.send(new_skill);
                    }
                }
                self.driver.on_phase_advanced(phase_index, to).await?;
            }
            // Context-mode actors stay alive in their terminal phase so they
            // can keep participating in the drive loop. Server actors keep
            // serving requests on follow-up LLM turns (e.g. rug pull).
            // Client actors (ag_ui_client) must run their terminal phase's
            // drive_phase to send the final run_agent_input for multi-turn
            // scenarios. Traffic-mode actors exit immediately.
            if self.phase_engine.is_terminal() && !self.context_mode {
                return Ok(self.build_result(TerminationReason::TerminalPhaseReached));
            }
        }
    }

    /// Prepare a phase: await cross-actor extractors, publish initial
    /// extractor values, and execute `on_enter` actions.
    #[allow(clippy::needless_pass_by_ref_mut, clippy::cognitive_complexity)]
    async fn prepare_phase(&mut self, phase_index: usize) -> bool {
        if let Some(await_specs) = self.await_extractors_config.get(&phase_index) {
            for spec in await_specs {
                tracing::debug!(
                    actor = %spec.actor,
                    extractors = ?spec.extractors,
                    timeout = ?spec.timeout,
                    "await_extractors: waiting for cross-actor extractors"
                );

                let deadline = tokio::time::Instant::now() + spec.timeout;

                let mut version_rx = self.extractor_store.subscribe();
                for extractor_name in &spec.extractors {
                    loop {
                        if let Some(value) = self.extractor_store.get(&spec.actor, extractor_name) {
                            let qualified = format!("{}.{}", spec.actor, extractor_name);
                            self.phase_engine.extractor_values.insert(qualified, value);
                            tracing::debug!(
                                actor = %spec.actor,
                                extractor = %extractor_name,
                                "await_extractors: resolved"
                            );
                            break;
                        }

                        tokio::select! {
                            result = version_rx.changed() => {
                                if result.is_err() { break; }
                            }
                            () = tokio::time::sleep_until(deadline) => {
                                tracing::warn!(
                                    actor = %spec.actor,
                                    extractor = %extractor_name,
                                    "await_extractors: timed out, proceeding without value"
                                );
                                break;
                            }
                            () = self.cancel.cancelled() => {
                                return true;
                            }
                        }
                    }
                }
            }
        }

        let interpolation_extractors =
            build_interpolation_extractors(&self.phase_engine, &self.extractor_store);
        let _ = self.extractors_tx.send(interpolation_extractors.clone());

        let phase = self.phase_engine.get_phase(phase_index);
        if let Some(on_enter) = &phase.on_enter {
            // Emit entry action events for progress display
            for action in on_enter {
                let action_type = match action {
                    oatf::Action::Send { method, .. } => format!("notify {method}"),
                    oatf::Action::Log { .. } => "log".to_string(),
                    oatf::Action::BindingSpecific { key, .. } => key.clone(),
                };
                self.events.emit(ThoughtJackEvent::EntryActionExecuted {
                    actor: self.actor_name.clone(),
                    action_type,
                });
            }

            actions::execute_entry_actions(
                on_enter,
                &interpolation_extractors,
                self.entry_action_sender.as_deref(),
            )
            .await;
        }

        false
    }

    /// Build a completion result for this actor with the given termination reason.
    fn build_result(&self, termination: TerminationReason) -> ActorResult {
        let current = self.phase_engine.current_phase;
        let actor = self.phase_engine.actor();
        ActorResult {
            actor_name: self.actor_name.clone(),
            termination,
            phases_completed: current,
            total_phases: actor.phases.len(),
            final_phase: actor.phases.get(current).and_then(|p| p.name.clone()),
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    // ---- PhaseLoop integration tests with MockDriver ----

    /// A mock driver that sends a fixed sequence of events then returns.
    struct MockDriver {
        events: Vec<ProtocolEvent>,
    }

    #[async_trait::async_trait]
    impl PhaseDriver for MockDriver {
        async fn drive_phase(
            &mut self,
            _phase_index: usize,
            _state: &serde_json::Value,
            _extractors: watch::Receiver<HashMap<String, String>>,
            event_tx: mpsc::Sender<ProtocolEvent>,
            _cancel: CancellationToken,
        ) -> Result<super::super::types::DriveResult, EngineError> {
            for event in self.events.drain(..) {
                let _ = event_tx.send(event).await;
            }
            Ok(super::super::types::DriveResult::Complete)
        }
    }

    /// A mock driver that captures the extractor map it receives via the watch channel.
    struct ExtractorCapturingDriver {
        captured: Arc<Mutex<HashMap<String, String>>>,
    }

    #[async_trait::async_trait]
    impl PhaseDriver for ExtractorCapturingDriver {
        async fn drive_phase(
            &mut self,
            _phase_index: usize,
            _state: &serde_json::Value,
            extractors: watch::Receiver<HashMap<String, String>>,
            _event_tx: mpsc::Sender<ProtocolEvent>,
            _cancel: CancellationToken,
        ) -> Result<super::super::types::DriveResult, EngineError> {
            let snapshot = extractors.borrow().clone();
            *self.captured.lock().unwrap() = snapshot;
            Ok(super::super::types::DriveResult::Complete)
        }
    }

    /// A mock driver that emits an event with an empty-string field,
    /// then captures the published extractors.
    struct EmptyFieldDriver {
        captured: Arc<Mutex<HashMap<String, String>>>,
    }

    #[async_trait::async_trait]
    impl PhaseDriver for EmptyFieldDriver {
        async fn drive_phase(
            &mut self,
            _phase_index: usize,
            _state: &serde_json::Value,
            extractors: watch::Receiver<HashMap<String, String>>,
            event_tx: mpsc::Sender<ProtocolEvent>,
            _cancel: CancellationToken,
        ) -> Result<super::super::types::DriveResult, EngineError> {
            let _ = event_tx
                .send(ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"name": "calculator", "empty_field": ""}),
                })
                .await;
            // Small yield to allow event processing
            tokio::task::yield_now().await;
            let snapshot = extractors.borrow().clone();
            *self.captured.lock().unwrap() = snapshot;
            Ok(super::super::types::DriveResult::Complete)
        }
    }

    /// A mock driver that panics inside `drive_phase()`.
    struct PanicDriver;

    #[async_trait::async_trait]
    impl PhaseDriver for PanicDriver {
        async fn drive_phase(
            &mut self,
            _phase_index: usize,
            _state: &serde_json::Value,
            _extractors: watch::Receiver<HashMap<String, String>>,
            _event_tx: mpsc::Sender<ProtocolEvent>,
            _cancel: CancellationToken,
        ) -> Result<super::super::types::DriveResult, EngineError> {
            panic!("driver crashed unexpectedly");
        }
    }

    /// A mock driver that always returns an error.
    struct ErrorDriver;

    #[async_trait::async_trait]
    impl PhaseDriver for ErrorDriver {
        async fn drive_phase(
            &mut self,
            _phase_index: usize,
            _state: &serde_json::Value,
            _extractors: watch::Receiver<HashMap<String, String>>,
            _event_tx: mpsc::Sender<ProtocolEvent>,
            _cancel: CancellationToken,
        ) -> Result<super::super::types::DriveResult, EngineError> {
            Err(EngineError::Driver("mock driver error".to_string()))
        }
    }

    /// A mock driver that records `on_phase_advanced` calls.
    struct AdvanceRecordingDriver {
        events: Vec<ProtocolEvent>,
        advanced_calls: Arc<Mutex<Vec<(usize, usize)>>>,
    }

    #[async_trait::async_trait]
    impl PhaseDriver for AdvanceRecordingDriver {
        async fn drive_phase(
            &mut self,
            _phase_index: usize,
            _state: &serde_json::Value,
            _extractors: watch::Receiver<HashMap<String, String>>,
            event_tx: mpsc::Sender<ProtocolEvent>,
            _cancel: CancellationToken,
        ) -> Result<super::super::types::DriveResult, EngineError> {
            for event in self.events.drain(..) {
                let _ = event_tx.send(event).await;
            }
            Ok(super::super::types::DriveResult::Complete)
        }

        async fn on_phase_advanced(&mut self, from: usize, to: usize) -> Result<(), EngineError> {
            self.advanced_calls.lock().unwrap().push((from, to));
            Ok(())
        }
    }

    fn load_test_document(yaml: &str) -> oatf::Document {
        oatf::load(yaml)
            .expect("test YAML should be valid")
            .document
    }

    fn test_config(trace: SharedTrace) -> PhaseLoopConfig {
        PhaseLoopConfig {
            trace,
            extractor_store: ExtractorStore::new(),
            actor_name: "default".to_string(),
            await_extractors_config: HashMap::new(),
            cancel: CancellationToken::new(),
            entry_action_sender: None,
            events: Arc::new(EventEmitter::noop()),
            tool_watch_tx: None,
            a2a_skill_tx: None,
            context_mode: false,
        }
    }

    #[tokio::test]
    async fn phase_loop_terminal_phase_completes() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    state:
      tools:
        - name: test_tool
          description: "test"
          inputSchema:
            type: object
"#,
        );

        let driver = MockDriver { events: vec![] };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let mut phase_loop = PhaseLoop::new(driver, engine, test_config(trace));

        let result = phase_loop.run().await.unwrap();
        assert_eq!(result.actor_name, "default");
        assert_eq!(result.termination, TerminationReason::TerminalPhaseReached);
    }

    #[tokio::test]
    async fn phase_loop_advances_on_trigger() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calculator
              description: "test"
              inputSchema:
                type: object
        trigger:
          event: tools/call
          count: 1
      - name: phase_two
"#,
        );

        let driver = MockDriver {
            events: vec![ProtocolEvent {
                direction: Direction::Incoming,
                method: "tools/call".to_string(),
                content: serde_json::json!({"name": "test"}),
            }],
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace.clone());
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        let result = phase_loop.run().await.unwrap();
        assert_eq!(result.termination, TerminationReason::TerminalPhaseReached);
        assert_eq!(result.phases_completed, 1);

        // Verify trace captured the event
        assert_eq!(trace.len(), 1);
    }

    #[tokio::test]
    async fn phase_loop_captures_trace_entries() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calculator
              description: "test"
              inputSchema:
                type: object
        trigger:
          event: tools/call
          count: 2
      - name: phase_two
"#,
        );

        let driver = MockDriver {
            events: vec![
                ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"name": "a"}),
                },
                ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"name": "b"}),
                },
            ],
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace.clone());
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        phase_loop.run().await.unwrap();

        let entries = trace.snapshot();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].method, "tools/call");
        assert_eq!(entries[1].method, "tools/call");
        assert_eq!(entries[0].phase, "phase_one");
    }

    #[tokio::test]
    async fn phase_loop_cancellation_returns_cancelled() {
        // Driver that waits for cancellation
        struct WaitDriver;
        #[async_trait::async_trait]
        impl PhaseDriver for WaitDriver {
            async fn drive_phase(
                &mut self,
                _phase_index: usize,
                _state: &serde_json::Value,
                _extractors: watch::Receiver<HashMap<String, String>>,
                _event_tx: mpsc::Sender<ProtocolEvent>,
                cancel: CancellationToken,
            ) -> Result<super::super::types::DriveResult, EngineError> {
                cancel.cancelled().await;
                Ok(super::super::types::DriveResult::Complete)
            }
        }

        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calculator
              description: "test"
              inputSchema:
                type: object
        trigger:
          event: tools/call
          count: 999
      - name: phase_two
"#,
        );

        let cancel = CancellationToken::new();
        let config = PhaseLoopConfig {
            trace: SharedTrace::new(),
            extractor_store: ExtractorStore::new(),
            actor_name: "default".to_string(),
            await_extractors_config: HashMap::new(),
            cancel: cancel.clone(),
            entry_action_sender: None,
            events: Arc::new(EventEmitter::noop()),
            tool_watch_tx: None,
            a2a_skill_tx: None,
            context_mode: false,
        };

        let engine = PhaseEngine::new(doc, 0);
        let mut phase_loop = PhaseLoop::new(WaitDriver, engine, config);

        // Cancel after a short delay
        let cancel_handle = cancel.clone();
        tokio::spawn(async move {
            tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
            cancel_handle.cancel();
        });

        let result = phase_loop.run().await.unwrap();
        assert_eq!(result.termination, TerminationReason::Cancelled);
        assert_eq!(result.actor_name, "default");
    }

    // ---- New tests ----

    #[tokio::test]
    async fn extractor_capture_local_scope() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calculator
              description: "test"
              inputSchema:
                type: object
        extractors:
          - name: tool_name
            source: request
            type: json_path
            selector: "$.name"
        trigger:
          event: tools/call
          count: 1
      - name: phase_two
"#,
        );

        let driver = MockDriver {
            events: vec![ProtocolEvent {
                direction: Direction::Incoming,
                method: "tools/call".to_string(),
                content: serde_json::json!({"name": "calculator"}),
            }],
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace);
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        let result = phase_loop.run().await.unwrap();
        assert_eq!(result.termination, TerminationReason::TerminalPhaseReached);
        // Verify extractor was captured locally
        assert_eq!(
            phase_loop.phase_engine.extractor_values.get("tool_name"),
            Some(&"calculator".to_string())
        );
    }

    #[tokio::test]
    async fn extractor_capture_cross_actor() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calculator
              description: "test"
              inputSchema:
                type: object
        extractors:
          - name: tool_name
            source: request
            type: json_path
            selector: "$.name"
        trigger:
          event: tools/call
          count: 1
      - name: phase_two
"#,
        );

        let driver = MockDriver {
            events: vec![ProtocolEvent {
                direction: Direction::Incoming,
                method: "tools/call".to_string(),
                content: serde_json::json!({"name": "my_tool"}),
            }],
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let extractor_store = ExtractorStore::new();
        let store_handle = extractor_store.clone();
        let config = PhaseLoopConfig {
            trace,
            extractor_store,
            actor_name: "test_actor".to_string(),
            await_extractors_config: HashMap::new(),
            cancel: CancellationToken::new(),
            entry_action_sender: None,
            events: Arc::new(EventEmitter::noop()),
            tool_watch_tx: None,
            a2a_skill_tx: None,
            context_mode: false,
        };
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        phase_loop.run().await.unwrap();
        // Verify extractor is in the shared store (cross-actor)
        assert_eq!(
            store_handle.get("test_actor", "tool_name"),
            Some("my_tool".to_string())
        );
    }

    #[tokio::test]
    async fn drain_events_after_driver_completes() {
        // MockDriver emits events synchronously then returns Complete.
        // All events should be drained and appear in trace.
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    state:
      tools:
        - name: test_tool
          description: "test"
          inputSchema:
            type: object
"#,
        );

        let driver = MockDriver {
            events: vec![
                ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "resources/read".to_string(),
                    content: serde_json::json!({"uri": "file:///a.txt"}),
                },
                ProtocolEvent {
                    direction: Direction::Outgoing,
                    method: "resources/read".to_string(),
                    content: serde_json::json!({"contents": []}),
                },
                ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "tools/list".to_string(),
                    content: serde_json::json!({}),
                },
            ],
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace.clone());
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        phase_loop.run().await.unwrap();

        let entries = trace.snapshot();
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].method, "resources/read");
        assert_eq!(entries[1].method, "resources/read");
        assert_eq!(entries[2].method, "tools/list");
    }

    #[tokio::test]
    async fn drain_events_stops_on_advance() {
        // Two-phase doc with count=1. Driver sends 2 events — first triggers
        // advance, drain should process the second but stop due to advance.
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calculator
              description: "test"
              inputSchema:
                type: object
        trigger:
          event: tools/call
          count: 1
      - name: phase_two
"#,
        );

        let driver = MockDriver {
            events: vec![
                ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"name": "calculator"}),
                },
                ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"name": "second"}),
                },
            ],
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace.clone());
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        let result = phase_loop.run().await.unwrap();
        assert_eq!(result.termination, TerminationReason::TerminalPhaseReached);
        // Both events should appear in trace (drain processes all remaining)
        assert!(!trace.is_empty());
    }

    /// A mock driver that provides a fixed set of events per phase index.
    struct PerPhaseDriver {
        /// Maps `phase_index` → events to send during that phase.
        phase_events: HashMap<usize, Vec<ProtocolEvent>>,
    }

    #[async_trait::async_trait]
    impl PhaseDriver for PerPhaseDriver {
        async fn drive_phase(
            &mut self,
            phase_index: usize,
            _state: &serde_json::Value,
            _extractors: watch::Receiver<HashMap<String, String>>,
            event_tx: mpsc::Sender<ProtocolEvent>,
            _cancel: CancellationToken,
        ) -> Result<super::super::types::DriveResult, EngineError> {
            if let Some(events) = self.phase_events.get_mut(&phase_index) {
                for event in events.drain(..) {
                    let _ = event_tx.send(event).await;
                }
            }
            Ok(super::super::types::DriveResult::Complete)
        }
    }

    #[tokio::test]
    async fn multi_phase_full_lifecycle() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: trust_building
        state:
          tools:
            - name: calculator
              description: "test"
              inputSchema:
                type: object
        trigger:
          event: tools/call
          count: 1
      - name: exploit
        state:
          tools:
            - name: calculator
              description: "modified"
              inputSchema:
                type: object
        trigger:
          event: tools/call
          count: 1
      - name: terminal
"#,
        );

        let mut phase_events = HashMap::new();
        phase_events.insert(
            0,
            vec![ProtocolEvent {
                direction: Direction::Incoming,
                method: "tools/call".to_string(),
                content: serde_json::json!({"name": "calculator"}),
            }],
        );
        phase_events.insert(
            1,
            vec![ProtocolEvent {
                direction: Direction::Incoming,
                method: "tools/call".to_string(),
                content: serde_json::json!({"name": "calculator"}),
            }],
        );

        let driver = PerPhaseDriver { phase_events };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace.clone());
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        let result = phase_loop.run().await.unwrap();
        assert_eq!(result.termination, TerminationReason::TerminalPhaseReached);
        assert_eq!(result.phases_completed, 2);

        // Verify trace has events from both phases
        let entries = trace.snapshot();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].phase, "trust_building");
        assert_eq!(entries[1].phase, "exploit");
    }

    #[tokio::test]
    async fn driver_error_propagates() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    state:
      tools:
        - name: test_tool
          description: "test"
          inputSchema:
            type: object
"#,
        );

        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace);
        let mut phase_loop = PhaseLoop::new(ErrorDriver, engine, config);

        let result = phase_loop.run().await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("mock driver error"),
            "Expected 'mock driver error', got: {err}"
        );
    }

    #[test]
    fn server_vs_client_extractor_source() {
        // Server mode: Incoming → Request, Outgoing → Response
        // Client mode: Incoming → Response, Outgoing → Request
        use oatf::enums::ExtractorSource;

        // Server mode: Incoming maps to Request
        let (source_server_in, source_server_out) = (
            match (Direction::Incoming, true) {
                (Direction::Incoming, true) | (Direction::Outgoing, false) => {
                    ExtractorSource::Request
                }
                _ => ExtractorSource::Response,
            },
            match (Direction::Outgoing, true) {
                (Direction::Outgoing, true) | (Direction::Incoming, false) => {
                    ExtractorSource::Response
                }
                _ => ExtractorSource::Request,
            },
        );
        assert_eq!(source_server_in, ExtractorSource::Request);
        assert_eq!(source_server_out, ExtractorSource::Response);

        // Client mode: Incoming maps to Response
        let (source_client_in, source_client_out) = (
            match (Direction::Incoming, false) {
                (Direction::Incoming, true) | (Direction::Outgoing, false) => {
                    ExtractorSource::Request
                }
                _ => ExtractorSource::Response,
            },
            match (Direction::Outgoing, false) {
                (Direction::Outgoing, true) | (Direction::Incoming, false) => {
                    ExtractorSource::Response
                }
                _ => ExtractorSource::Request,
            },
        );
        assert_eq!(source_client_in, ExtractorSource::Response);
        assert_eq!(source_client_out, ExtractorSource::Request);
    }

    #[test]
    fn build_interpolation_extractors_merges() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    state:
      tools:
        - name: test_tool
          description: "test"
          inputSchema:
            type: object
"#,
        );

        let mut engine = PhaseEngine::new(doc, 0);
        engine
            .extractor_values
            .insert("local_key".to_string(), "local_val".to_string());

        let store = ExtractorStore::new();
        store.set("other_actor", "token", "abc123".to_string());

        let merged = build_interpolation_extractors(&engine, &store);
        assert_eq!(merged.get("local_key"), Some(&"local_val".to_string()));
        assert_eq!(merged.get("other_actor.token"), Some(&"abc123".to_string()));
    }

    #[tokio::test]
    async fn on_phase_advanced_called() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calculator
              description: "test"
              inputSchema:
                type: object
        trigger:
          event: tools/call
          count: 1
      - name: phase_two
"#,
        );

        let calls = Arc::new(Mutex::new(Vec::new()));
        let driver = AdvanceRecordingDriver {
            events: vec![ProtocolEvent {
                direction: Direction::Incoming,
                method: "tools/call".to_string(),
                content: serde_json::json!({"name": "calculator"}),
            }],
            advanced_calls: Arc::clone(&calls),
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace);
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        phase_loop.run().await.unwrap();

        let recorded = calls.lock().unwrap().clone();
        assert_eq!(recorded.len(), 1);
        assert_eq!(recorded[0], (0, 1));
    }

    // ---- Edge case tests (EC-OATF-007, EC-OATF-008, EC-OATF-014) ----

    /// EC-OATF-007: Phase with no `state:` key — effective state inherits
    /// from the previous phase, driver runs fine.
    #[tokio::test]
    async fn ec_oatf_007_no_state_phase() {
        // Second phase has no state — should inherit from phase_one
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calculator
              description: "test"
              inputSchema:
                type: object
        trigger:
          event: tools/call
          count: 1
      - name: no_state_phase
"#,
        );

        let mut phase_events = HashMap::new();
        phase_events.insert(
            0,
            vec![ProtocolEvent {
                direction: Direction::Incoming,
                method: "tools/call".to_string(),
                content: serde_json::json!({"name": "calculator"}),
            }],
        );

        let driver = PerPhaseDriver { phase_events };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let mut phase_loop = PhaseLoop::new(driver, engine, test_config(trace));

        let result = phase_loop.run().await.unwrap();
        assert_eq!(result.termination, TerminationReason::TerminalPhaseReached);
        // Phase 1 has no trigger (terminal) — completes at phase index 1
        assert_eq!(result.phases_completed, 1);
    }

    /// EC-OATF-008: Extractor captures empty string `""` — published on watch
    /// channel, not silently dropped.
    #[tokio::test]
    async fn ec_oatf_008_empty_string_extractor() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calculator
              description: "test"
              inputSchema:
                type: object
        extractors:
          - name: empty_val
            source: request
            type: json_path
            selector: "$.empty_field"
        trigger:
          event: tools/call
          count: 1
      - name: phase_two
"#,
        );

        let captured = Arc::new(Mutex::new(HashMap::new()));
        let captured_clone = Arc::clone(&captured);

        let driver = EmptyFieldDriver {
            captured: captured_clone,
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace);
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        phase_loop.run().await.unwrap();

        // Verify the empty string was captured (not dropped)
        assert_eq!(
            phase_loop.phase_engine.extractor_values.get("empty_val"),
            Some(&String::new()),
            "empty string extractor should be captured, not dropped"
        );
    }

    /// EC-OATF-014: Driver that panics inside `drive_phase()` — `run()` returns
    /// Err, does not propagate panic to caller.
    #[tokio::test]
    async fn ec_oatf_014_driver_panic() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    state:
      tools:
        - name: test_tool
          description: "test"
          inputSchema:
            type: object
"#,
        );

        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace);

        // Spawn the phase loop in a task so the panic is caught by JoinHandle
        let result = tokio::spawn(async move {
            let mut phase_loop = PhaseLoop::new(PanicDriver, engine, config);
            phase_loop.run().await
        })
        .await;

        // The JoinHandle should capture the panic (JoinError::is_panic())
        assert!(
            result.is_err(),
            "spawn should return Err for a panicked task"
        );
        let join_err = result.unwrap_err();
        assert!(
            join_err.is_panic(),
            "error should be a panic, not cancellation"
        );
    }

    #[tokio::test]
    async fn await_extractors_resolves() {
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    state:
      tools:
        - name: test_tool
          description: "test"
          inputSchema:
            type: object
"#,
        );

        let captured = Arc::new(Mutex::new(HashMap::new()));
        let driver = ExtractorCapturingDriver {
            captured: Arc::clone(&captured),
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let extractor_store = ExtractorStore::new();
        // Pre-seed the store with the value that will be awaited
        extractor_store.set("other_actor", "session_id", "sess-42".to_string());

        let mut await_config: HashMap<usize, Vec<AwaitExtractor>> = HashMap::new();
        await_config.insert(
            0,
            vec![AwaitExtractor {
                actor: "other_actor".to_string(),
                extractors: vec!["session_id".to_string()],
                timeout: std::time::Duration::from_secs(5),
            }],
        );

        let config = PhaseLoopConfig {
            trace,
            extractor_store,
            actor_name: "default".to_string(),
            await_extractors_config: await_config,
            cancel: CancellationToken::new(),
            entry_action_sender: None,
            events: Arc::new(EventEmitter::noop()),
            tool_watch_tx: None,
            a2a_skill_tx: None,
            context_mode: false,
        };

        let mut phase_loop = PhaseLoop::new(driver, engine, config);
        let result = phase_loop.run().await.unwrap();
        assert_eq!(result.termination, TerminationReason::TerminalPhaseReached);

        // Verify the awaited extractor was resolved and available
        assert_eq!(
            phase_loop
                .phase_engine
                .extractor_values
                .get("other_actor.session_id"),
            Some(&"sess-42".to_string())
        );
    }

    /// A driver that sends events then waits for cancellation.
    struct SendThenWaitDriver {
        events: Vec<ProtocolEvent>,
    }

    #[async_trait::async_trait]
    impl PhaseDriver for SendThenWaitDriver {
        async fn drive_phase(
            &mut self,
            _phase_index: usize,
            _state: &serde_json::Value,
            _extractors: watch::Receiver<HashMap<String, String>>,
            event_tx: mpsc::Sender<ProtocolEvent>,
            cancel: CancellationToken,
        ) -> Result<super::super::types::DriveResult, EngineError> {
            for event in self.events.drain(..) {
                let _ = event_tx.send(event).await;
            }
            cancel.cancelled().await;
            Ok(super::super::types::DriveResult::Complete)
        }
    }

    #[tokio::test]
    async fn outgoing_events_do_not_count_toward_trigger() {
        // Trigger requires count: 2. Send 1 incoming + 1 outgoing.
        // Only the incoming event should count, so the trigger should NOT fire.
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calc
              description: "test"
              inputSchema:
                type: object
        trigger:
          event: tools/call
          count: 2
      - name: phase_two
"#,
        );

        let driver = SendThenWaitDriver {
            events: vec![
                ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"name": "a"}),
                },
                ProtocolEvent {
                    direction: Direction::Outgoing,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"result": "42"}),
                },
            ],
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let cancel = CancellationToken::new();
        let config = PhaseLoopConfig {
            trace: trace.clone(),
            extractor_store: ExtractorStore::new(),
            actor_name: "default".to_string(),
            await_extractors_config: HashMap::new(),
            cancel: cancel.clone(),
            entry_action_sender: None,
            events: Arc::new(EventEmitter::noop()),
            tool_watch_tx: None,
            a2a_skill_tx: None,
            context_mode: false,
        };
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        // Cancel after events are processed — trigger should not have fired
        let c = cancel.clone();
        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            c.cancel();
        });

        let result = phase_loop.run().await.unwrap();
        // Only 1 incoming event (count < 2) → trigger stays, cancelled
        assert_eq!(result.phases_completed, 0);
        assert_eq!(result.termination, TerminationReason::Cancelled);
        // Both events captured in trace
        assert_eq!(trace.len(), 2);
    }

    #[tokio::test]
    async fn only_incoming_events_advance_trigger() {
        // Trigger requires count: 2. Send 2 incoming + 2 outgoing.
        // Only the 2 incoming events should count → trigger fires.
        let doc = load_test_document(
            r#"
oatf: "0.1"
attack:
  name: test
  execution:
    mode: mcp_server
    phases:
      - name: phase_one
        state:
          tools:
            - name: calc
              description: "test"
              inputSchema:
                type: object
        trigger:
          event: tools/call
          count: 2
      - name: phase_two
"#,
        );

        let driver = MockDriver {
            events: vec![
                ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"name": "a"}),
                },
                ProtocolEvent {
                    direction: Direction::Outgoing,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"result": "1"}),
                },
                ProtocolEvent {
                    direction: Direction::Incoming,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"name": "b"}),
                },
                ProtocolEvent {
                    direction: Direction::Outgoing,
                    method: "tools/call".to_string(),
                    content: serde_json::json!({"result": "2"}),
                },
            ],
        };
        let engine = PhaseEngine::new(doc, 0);
        let trace = SharedTrace::new();
        let config = test_config(trace.clone());
        let mut phase_loop = PhaseLoop::new(driver, engine, config);

        let result = phase_loop.run().await.unwrap();
        assert_eq!(result.phases_completed, 1);
        assert_eq!(result.termination, TerminationReason::TerminalPhaseReached);
        // drain_events stops after the Advance (2nd incoming), so
        // the trailing outgoing event may not be processed.
        assert!(trace.len() >= 3);
    }
}