repl-core 1.21.0

Core REPL engine for the Symbi platform
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
//! Core reasoning builtins for the DSL
//!
//! Provides async builtin functions that bridge the DSL with the
//! reasoning loop infrastructure: `reason`, `llm_call`, `parse_json`,
//! `delegate`, and `tool_call`.

use crate::dsl::evaluator::DslValue;
use crate::error::{ReplError, Result};
use std::collections::HashMap;
use std::sync::Arc;
use symbi_runtime::communication::policy_gate::CommunicationPolicyGate;
use symbi_runtime::communication::CommunicationBus;
use symbi_runtime::reasoning::agent_registry::AgentRegistry;
use symbi_runtime::reasoning::inference::InferenceProvider;
use symbi_runtime::reasoning::policy_bridge::ReasoningPolicyGate;
use symbi_runtime::types::AgentId;

/// Operator configuration for async reasoning builtins. The evaluator clones it
/// for each invocation and binds that call's execution principal; sender identity
/// must not be stored in shared mutable state.
#[derive(Clone)]
pub struct ReasoningBuiltinContext {
    /// Canonical project captured from trusted startup or explicit SDK configuration.
    /// A failed capture remains an error; later working-directory changes cannot replace it.
    pub project_root: std::result::Result<std::path::PathBuf, String>,
    /// Inference provider for LLM calls.
    pub provider: Option<Arc<dyn InferenceProvider>>,
    /// Agent registry for multi-agent composition.
    pub agent_registry: Option<Arc<AgentRegistry>>,
    /// The calling agent, used for reasoning authorization and communication.
    pub sender_agent_id: Option<AgentId>,
    /// Communication bus for message tracking and audit.
    pub comm_bus: Option<Arc<dyn CommunicationBus + Send + Sync>>,
    /// Communication policy gate for inter-agent authorization.
    pub comm_policy: Option<Arc<CommunicationPolicyGate>>,
    /// Policy gate for the reasoning loop — governs tool calls and
    /// delegations inside `reason()`. If None, `DefaultPolicyGate::new()`
    /// is used (production-default, non-permissive). Production callers
    /// should install [`OpaPolicyGateBridge`] or another concrete gate
    /// instead of relying on the default.
    pub reasoning_policy_gate: Option<Arc<dyn ReasoningPolicyGate>>,
    /// Operator-installed tool backend, shared by reason() and tool_call().
    pub tool_executor: Option<Arc<dyn symbi_runtime::reasoning::executor::ActionExecutor>>,
    /// Required pre-effect and outcome journal for reasoning and explicit calls.
    pub reasoning_journal: Option<Arc<dyn symbi_runtime::reasoning::loop_types::JournalWriter>>,
    /// Trusted execution configuration, including advertised tools and budgets.
    pub reasoning_config: Option<symbi_runtime::reasoning::LoopConfig>,
    /// Public references to required direct-inference journals. This bounded
    /// display history is not the durable store and never grants authority.
    pub audit_references: Arc<crate::dsl::inference_audit::AuditReferenceLog>,
    /// Active session id (shared cell; settable after the context is frozen).
    #[cfg(feature = "session")]
    pub active_session: std::sync::Arc<std::sync::Mutex<Option<symbi_session::monitor::SessionId>>>,
    /// Session monitor for label derivation. Always present once a bridge exists.
    #[cfg(feature = "session")]
    pub session_monitor: Option<std::sync::Arc<symbi_session::monitor::SessionMonitor>>,
}

pub(crate) fn capture_project_root() -> std::result::Result<std::path::PathBuf, String> {
    std::env::current_dir()
        .and_then(|path| path.canonicalize())
        .map_err(|error| error.to_string())
}

impl Default for ReasoningBuiltinContext {
    fn default() -> Self {
        Self {
            project_root: capture_project_root(),
            provider: None,
            agent_registry: None,
            sender_agent_id: None,
            comm_bus: None,
            comm_policy: None,
            reasoning_policy_gate: None,
            tool_executor: None,
            reasoning_journal: None,
            reasoning_config: None,
            audit_references: Arc::new(Default::default()),
            #[cfg(feature = "session")]
            active_session: Default::default(),
            #[cfg(feature = "session")]
            session_monitor: None,
        }
    }
}

impl ReasoningBuiltinContext {
    /// Bind an explicit operator-selected project before constructing the evaluator.
    pub fn with_project_root(mut self, project: impl AsRef<std::path::Path>) -> Result<Self> {
        let root = project.as_ref().canonicalize().map_err(|error| {
            ReplError::Execution(format!("Cannot resolve DSL project: {error}"))
        })?;
        if !root.is_dir() {
            return Err(ReplError::Execution(
                "DSL project must be a directory".into(),
            ));
        }
        self.project_root = Ok(root);
        Ok(self)
    }

    fn project(&self) -> Result<&std::path::Path> {
        let root = self.project_root.as_ref().map_err(|error| {
            ReplError::Execution(format!("DSL project configuration unavailable: {error}"))
        })?;
        if !root.is_absolute() || !root.is_dir() {
            return Err(ReplError::Execution(
                "Configured DSL project is unavailable or not absolute".into(),
            ));
        }
        Ok(root)
    }

    fn executor(&self) -> Result<Arc<dyn symbi_runtime::reasoning::executor::ActionExecutor>> {
        match &self.tool_executor {
            Some(executor) => Ok(executor.clone()),
            None => Ok(symbi_runtime::reasoning::build_tool_executor(
                &self.project()?.join("tools"),
            )),
        }
    }

    pub(crate) async fn journal(
        &self,
        agent: AgentId,
    ) -> Result<(
        Arc<dyn symbi_runtime::reasoning::loop_types::JournalWriter>,
        Option<symbi_runtime::reasoning::run_audit::RunAuditReference>,
    )> {
        if let Some(journal) = &self.reasoning_journal {
            return Ok((journal.clone(), None));
        }
        let (journal, reference) =
            symbi_runtime::reasoning::run_audit::open_run_journal(self.project()?, agent)
                .await
                .map_err(|error| {
                    ReplError::Execution(format!(
                        "Required DSL audit initialization failed: {error}"
                    ))
                })?;
        Ok((journal, Some(reference)))
    }
}

fn include_audit(
    result: &mut HashMap<String, DslValue>,
    audit: &Option<symbi_runtime::reasoning::run_audit::RunAuditReference>,
) {
    if let Some(audit) = audit {
        result.insert(
            "audit".into(),
            DslValue::Map(HashMap::from([
                ("run_id".into(), DslValue::String(audit.run_id.to_string())),
                (
                    "path".into(),
                    DslValue::String(audit.path.display().to_string()),
                ),
                (
                    "public_key".into(),
                    DslValue::String(audit.public_key.clone()),
                ),
            ])),
        );
    }
}

pub(crate) async fn append_event(
    journal: &dyn symbi_runtime::reasoning::loop_types::JournalWriter,
    agent_id: AgentId,
    event: symbi_runtime::reasoning::loop_types::LoopEvent,
) -> Result<()> {
    journal
        .append(symbi_runtime::reasoning::loop_types::JournalEntry {
            sequence: journal.next_sequence().await,
            timestamp: chrono::Utc::now(),
            agent_id,
            iteration: 0,
            event,
        })
        .await
        .map_err(|error| {
            ReplError::Execution(format!("Required DSL journal write failed: {error}"))
        })
}

/// Execute the `reason` builtin: runs a full reasoning loop.
///
/// Arguments (positional or named):
/// - system: string — system prompt
/// - user: string — user message
/// - max_iterations: integer (optional, default 10)
/// - max_tokens: integer (optional, default 100000)
///
/// Returns a map with keys: response, iterations, total_tokens, termination_reason.
pub async fn builtin_reason(args: &[DslValue], ctx: &ReasoningBuiltinContext) -> Result<DslValue> {
    let provider = ctx
        .provider
        .as_ref()
        .ok_or_else(|| ReplError::Execution("No inference provider configured".into()))?;

    let (system, user, max_iterations, max_tokens) = parse_reason_args(args)?;

    use symbi_runtime::reasoning::circuit_breaker::CircuitBreakerRegistry;
    use symbi_runtime::reasoning::context_manager::DefaultContextManager;
    use symbi_runtime::reasoning::conversation::{Conversation, ConversationMessage};
    use symbi_runtime::reasoning::policy_bridge::DefaultPolicyGate;
    use symbi_runtime::reasoning::reasoning_loop::ReasoningLoopRunner;

    // Prefer a caller-provided policy gate (e.g. OpaPolicyGateBridge wired
    // from the runtime). Fall back to the non-permissive default rather
    // than `DefaultPolicyGate::permissive_for_dev_only()` so `reason()`
    // no longer opts every DSL program into unrestricted tool calls
    // regardless of how the runtime was configured.
    let policy_gate: Arc<dyn ReasoningPolicyGate> = match ctx.reasoning_policy_gate.clone() {
        Some(gate) => gate,
        None => Arc::new(DefaultPolicyGate::new()),
    };

    let agent_id = ctx.sender_agent_id.unwrap_or_default();
    let (journal, audit) = ctx.journal(agent_id).await?;
    let runner = ReasoningLoopRunner {
        provider: Arc::clone(provider),
        policy_gate,
        executor: ctx.executor()?,
        context_manager: Arc::new(DefaultContextManager::default()),
        circuit_breakers: Arc::new(CircuitBreakerRegistry::default()),
        journal,
        knowledge_bridge: None,
        delegation: None,
    };

    let mut conv = Conversation::with_system(&system);
    conv.push(ConversationMessage::user(&user));

    let mut config = ctx.reasoning_config.clone().unwrap_or_default();
    config.max_iterations = config.max_iterations.min(max_iterations);
    config.max_total_tokens = config.max_total_tokens.min(max_tokens);

    let result = runner.run(agent_id, conv, config).await;

    let mut map = HashMap::new();
    include_audit(&mut map, &audit);
    map.insert("response".to_string(), DslValue::String(result.output));
    map.insert(
        "iterations".to_string(),
        DslValue::Integer(result.iterations as i64),
    );
    map.insert(
        "total_tokens".to_string(),
        DslValue::Integer(result.total_usage.total_tokens as i64),
    );
    map.insert(
        "termination_reason".to_string(),
        DslValue::String(format!("{:?}", result.termination_reason)),
    );

    Ok(DslValue::Map(map))
}

/// Execute the `llm_call` builtin: one-shot LLM call.
///
/// Arguments:
/// - prompt: string — the prompt to send
/// - model: string (optional) — model override
/// - temperature: number (optional)
/// - max_tokens: integer (optional)
///
/// Returns a string.
pub async fn builtin_llm_call(
    args: &[DslValue],
    ctx: &ReasoningBuiltinContext,
) -> Result<DslValue> {
    let prompt = match args.first() {
        Some(DslValue::String(s)) => s.clone(),
        Some(DslValue::Map(map)) => map
            .get("prompt")
            .and_then(|v| match v {
                DslValue::String(s) => Some(s.clone()),
                _ => None,
            })
            .ok_or_else(|| ReplError::Execution("llm_call requires 'prompt' argument".into()))?,
        _ => {
            return Err(ReplError::Execution(
                "llm_call requires a string prompt".into(),
            ))
        }
    };

    use symbi_runtime::reasoning::conversation::{Conversation, ConversationMessage};
    use symbi_runtime::reasoning::inference::InferenceOptions;

    let mut conv = Conversation::new();
    conv.push(ConversationMessage::user(&prompt));

    let options = InferenceOptions::default();
    let response = ctx
        .infer("llm_call", &conv, &options, None)
        .await
        .map_err(|e| ReplError::Execution(format!("LLM call failed: {}", e)))?;

    Ok(DslValue::String(response.content))
}

/// Execute the `parse_json` builtin: parse a string as JSON.
///
/// Arguments:
/// - text: string — the JSON text to parse
///
/// Returns a DslValue (Map, List, String, Number, Boolean, or Null).
pub fn builtin_parse_json(args: &[DslValue]) -> Result<DslValue> {
    let text = match args.first() {
        Some(DslValue::String(s)) => s,
        _ => {
            return Err(ReplError::Execution(
                "parse_json requires a string argument".into(),
            ))
        }
    };

    let value: serde_json::Value = serde_json::from_str(text)
        .map_err(|e| ReplError::Execution(format!("JSON parse error: {}", e)))?;

    Ok(json_to_dsl_value(&value))
}

/// Execute the `tool_call` builtin: explicit tool invocation.
///
/// Arguments:
/// - name: string — tool name
/// - args: map — tool arguments
///
/// Each call is normalized, approved when required, checked by policy, and
/// journaled before dispatch through the shared runtime dispatcher. Policy
/// modifications are new proposals and must pass every check again.
///
/// Returns a status map and the public audit reference for default journals.
pub async fn builtin_tool_call(
    args: &[DslValue],
    ctx: &ReasoningBuiltinContext,
) -> Result<DslValue> {
    let (name, arguments) = match args {
        [DslValue::String(name), DslValue::Map(args_map)] => {
            let json_args: serde_json::Map<String, serde_json::Value> = args_map
                .iter()
                .map(|(k, v)| (k.clone(), v.to_json()))
                .collect();
            (
                name.clone(),
                serde_json::Value::Object(json_args).to_string(),
            )
        }
        [DslValue::String(name), DslValue::String(args_str)] => (name.clone(), args_str.clone()),
        [DslValue::String(name)] => (name.clone(), "{}".to_string()),
        _ => {
            return Err(ReplError::Execution(
                "tool_call requires (name: string, args?: map|string)".into(),
            ))
        }
    };

    use symbi_runtime::reasoning::circuit_breaker::CircuitBreakerRegistry;
    use symbi_runtime::reasoning::conversation::Conversation;
    use symbi_runtime::reasoning::dispatch::GovernedToolDispatcher;
    use symbi_runtime::reasoning::loop_types::{
        LoopEvent, LoopState, ProposedAction, TerminationReason,
    };
    use symbi_runtime::reasoning::policy_bridge::DefaultPolicyGate;

    let gate = ctx
        .reasoning_policy_gate
        .clone()
        .unwrap_or_else(|| Arc::new(DefaultPolicyGate::new()));
    let agent_id = ctx.sender_agent_id.unwrap_or_default();
    let (journal, audit) = ctx.journal(agent_id).await?;
    let executor = ctx.executor()?;
    let mut config = ctx.reasoning_config.clone().unwrap_or_default();
    if config.tool_definitions.is_empty() {
        config.tool_definitions = executor.tool_definitions();
    }
    let mut state = LoopState::new(agent_id, Conversation::new());
    state.trusted_context = executor.execution_context();
    let action = ProposedAction::ToolCall {
        call_id: "dsl_tool_call".into(),
        name: name.clone(),
        arguments: arguments.clone(),
    };
    let circuit_breakers = CircuitBreakerRegistry::default();
    // Each explicit builtin call owns a run. Multi-step interactive workflows
    // use reason() or a governed SDK run with a shared LoopState and guard.
    let started = std::time::Instant::now();
    append_event(
        journal.as_ref(),
        agent_id,
        LoopEvent::Started {
            agent_id,
            config: Box::new(config.clone()),
            execution_context: state.trusted_context.clone(),
        },
    )
    .await?;
    let outcome = async {
        let cleanup = symbi_runtime::reasoning::executor::ExecutionRunGuard::new(
            executor.clone(),
            &state,
            &config,
        )
        .map_err(ReplError::Execution)?;
        let observations = GovernedToolDispatcher {
            executor: executor.as_ref(),
            gate: gate.as_ref(),
            journal: journal.as_ref(),
            circuit_breakers: &circuit_breakers,
        }
        .dispatch(&[action], &state, &config)
        .await;
        // Cleanup is required even when dispatch or its journal checkpoint failed.
        cleanup.close().await.map_err(|error| {
            ReplError::Execution(format!("Required worker cleanup failed: {error}"))
        })?;
        observations
            .map_err(|error| ReplError::Execution(error.to_string()))?
            .into_iter()
            .next()
            .ok_or_else(|| ReplError::Execution("tool dispatcher returned no result".into()))
    }
    .await;
    let termination = match &outcome {
        Err(error) => TerminationReason::Error {
            message: error.to_string(),
        },
        Ok(obs)
            if obs
                .metadata
                .get("error_type")
                .is_some_and(|kind| kind == "policy_denied") =>
        {
            TerminationReason::PolicyDenial {
                reason: obs.content.clone(),
            }
        }
        Ok(obs) if obs.is_error => TerminationReason::Error {
            message: obs.content.clone(),
        },
        Ok(_) => TerminationReason::Completed,
    };
    append_event(
        journal.as_ref(),
        agent_id,
        LoopEvent::Terminated {
            reason: termination,
            iterations: 1,
            total_usage: Default::default(),
            duration: started.elapsed(),
        },
    )
    .await?;
    let obs = outcome.map_err(|error| match &audit {
        Some(audit) => ReplError::Execution(format!(
            "{error}; audit run {} at {} (public key {})",
            audit.run_id,
            audit.path.display(),
            audit.public_key
        )),
        None => error,
    })?;
    let denied = obs
        .metadata
        .get("error_type")
        .is_some_and(|kind| kind == "policy_denied");
    let mut result = HashMap::new();
    include_audit(&mut result, &audit);
    result.insert(
        "tool".into(),
        DslValue::String(obs.metadata.get("authorized_tool").cloned().unwrap_or(name)),
    );
    result.insert(
        "arguments".into(),
        DslValue::String(
            obs.metadata
                .get("authorized_arguments")
                .cloned()
                .unwrap_or(arguments),
        ),
    );
    result.insert(
        "status".into(),
        DslValue::String(
            if denied {
                "denied"
            } else if obs.is_error {
                "error"
            } else {
                "success"
            }
            .into(),
        ),
    );
    result.insert(
        if denied { "reason" } else { "result" }.into(),
        DslValue::String(obs.content),
    );
    Ok(DslValue::Map(result))
}

/// Execute the `delegate` builtin: send a message to another agent.
///
/// Arguments:
/// - agent: string — agent name
/// - message: string — message to send
/// - timeout: duration (optional)
///
/// Returns the agent's response as a string.
pub async fn builtin_delegate(
    args: &[DslValue],
    ctx: &ReasoningBuiltinContext,
) -> Result<DslValue> {
    let (agent_name, message) = match args {
        [DslValue::String(agent), DslValue::String(msg)] => (agent.clone(), msg.clone()),
        [DslValue::Map(map)] => {
            let agent = map
                .get("agent")
                .and_then(|v| match v {
                    DslValue::String(s) => Some(s.clone()),
                    _ => None,
                })
                .ok_or_else(|| ReplError::Execution("delegate requires 'agent' argument".into()))?;
            let msg = map
                .get("message")
                .and_then(|v| match v {
                    DslValue::String(s) => Some(s.clone()),
                    _ => None,
                })
                .ok_or_else(|| {
                    ReplError::Execution("delegate requires 'message' argument".into())
                })?;
            (agent, msg)
        }
        _ => {
            return Err(ReplError::Execution(
                "delegate requires (agent: string, message: string)".into(),
            ))
        }
    };

    let label = optional_protocol_label(args);
    crate::dsl::agent_composition::governed_ask(ctx, &agent_name, &message, label.as_deref())
        .await
        .map(DslValue::String)
}

// --- Helper functions ---

fn parse_reason_args(args: &[DslValue]) -> Result<(String, String, u32, u32)> {
    match args {
        // Named arguments via map
        [DslValue::Map(map)] => {
            let system = map
                .get("system")
                .and_then(|v| match v {
                    DslValue::String(s) => Some(s.clone()),
                    _ => None,
                })
                .ok_or_else(|| ReplError::Execution("reason requires 'system' argument".into()))?;
            let user = map
                .get("user")
                .and_then(|v| match v {
                    DslValue::String(s) => Some(s.clone()),
                    _ => None,
                })
                .ok_or_else(|| ReplError::Execution("reason requires 'user' argument".into()))?;
            let max_iterations = map
                .get("max_iterations")
                .and_then(|v| match v {
                    DslValue::Integer(i) => Some(*i as u32),
                    DslValue::Number(n) => Some(*n as u32),
                    _ => None,
                })
                .unwrap_or(10);
            let max_tokens = map
                .get("max_tokens")
                .and_then(|v| match v {
                    DslValue::Integer(i) => Some(*i as u32),
                    DslValue::Number(n) => Some(*n as u32),
                    _ => None,
                })
                .unwrap_or(100_000);
            Ok((system, user, max_iterations, max_tokens))
        }
        // Positional: system, user
        [DslValue::String(system), DslValue::String(user)] => {
            Ok((system.clone(), user.clone(), 10, 100_000))
        }
        // Positional: system, user, max_iterations
        [DslValue::String(system), DslValue::String(user), DslValue::Integer(max_iter)] => {
            Ok((system.clone(), user.clone(), *max_iter as u32, 100_000))
        }
        _ => Err(ReplError::Execution(
            "reason requires (system: string, user: string, [max_iterations?, max_tokens?])".into(),
        )),
    }
}

/// Extract an optional `protocol_label` string from a DSL argument list.
///
/// Named args arrive as a single `DslValue::Map`. This helper looks up the
/// `"protocol_label"` key in that map and returns its value when it is a
/// `DslValue::String`. Returns `None` when the key is absent, has the wrong
/// type, or the args are positional-only (no map present).
pub(crate) fn optional_protocol_label(args: &[DslValue]) -> Option<String> {
    for arg in args {
        if let DslValue::Map(map) = arg {
            if let Some(DslValue::String(label)) = map.get("protocol_label") {
                return Some(label.clone());
            }
        }
    }
    None
}

/// Convert a serde_json::Value to a DslValue.
pub fn json_to_dsl_value(value: &serde_json::Value) -> DslValue {
    match value {
        serde_json::Value::Null => DslValue::Null,
        serde_json::Value::Bool(b) => DslValue::Boolean(*b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                DslValue::Integer(i)
            } else if let Some(f) = n.as_f64() {
                DslValue::Number(f)
            } else {
                DslValue::Number(0.0)
            }
        }
        serde_json::Value::String(s) => DslValue::String(s.clone()),
        serde_json::Value::Array(arr) => {
            DslValue::List(arr.iter().map(json_to_dsl_value).collect())
        }
        serde_json::Value::Object(obj) => {
            let map: HashMap<String, DslValue> = obj
                .iter()
                .map(|(k, v)| (k.clone(), json_to_dsl_value(v)))
                .collect();
            DslValue::Map(map)
        }
    }
}

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

    #[test]
    fn test_parse_json_valid() {
        let result =
            builtin_parse_json(&[DslValue::String(r#"{"key": "value", "num": 42}"#.into())])
                .unwrap();
        match result {
            DslValue::Map(map) => {
                assert_eq!(map.get("key"), Some(&DslValue::String("value".into())));
                assert_eq!(map.get("num"), Some(&DslValue::Integer(42)));
            }
            _ => panic!("Expected Map"),
        }
    }

    #[test]
    fn test_parse_json_array() {
        let result = builtin_parse_json(&[DslValue::String("[1, 2, 3]".into())]).unwrap();
        match result {
            DslValue::List(items) => {
                assert_eq!(items.len(), 3);
                assert_eq!(items[0], DslValue::Integer(1));
            }
            _ => panic!("Expected List"),
        }
    }

    #[test]
    fn test_parse_json_invalid() {
        let result = builtin_parse_json(&[DslValue::String("not json".into())]);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_json_nested() {
        let json = r#"{"tasks": [{"id": 1, "done": false}], "count": 1}"#;
        let result = builtin_parse_json(&[DslValue::String(json.into())]).unwrap();
        match result {
            DslValue::Map(map) => match map.get("tasks") {
                Some(DslValue::List(tasks)) => {
                    assert_eq!(tasks.len(), 1);
                    match &tasks[0] {
                        DslValue::Map(task) => {
                            assert_eq!(task.get("id"), Some(&DslValue::Integer(1)));
                            assert_eq!(task.get("done"), Some(&DslValue::Boolean(false)));
                        }
                        _ => panic!("Expected Map in list"),
                    }
                }
                _ => panic!("Expected List for tasks"),
            },
            _ => panic!("Expected Map"),
        }
    }

    #[test]
    fn test_json_to_dsl_value_all_types() {
        let json = serde_json::json!({
            "str": "hello",
            "int": 42,
            "float": 1.5,
            "bool": true,
            "null": null,
            "arr": [1, 2],
            "obj": {"nested": "value"}
        });

        let dsl = json_to_dsl_value(&json);
        match dsl {
            DslValue::Map(map) => {
                assert_eq!(map.get("str"), Some(&DslValue::String("hello".into())));
                assert_eq!(map.get("int"), Some(&DslValue::Integer(42)));
                assert_eq!(map.get("bool"), Some(&DslValue::Boolean(true)));
                assert_eq!(map.get("null"), Some(&DslValue::Null));
            }
            _ => panic!("Expected Map"),
        }
    }

    #[test]
    fn test_parse_reason_args_positional() {
        let args = vec![
            DslValue::String("system prompt".into()),
            DslValue::String("user message".into()),
        ];
        let (system, user, max_iter, max_tokens) = parse_reason_args(&args).unwrap();
        assert_eq!(system, "system prompt");
        assert_eq!(user, "user message");
        assert_eq!(max_iter, 10);
        assert_eq!(max_tokens, 100_000);
    }

    #[test]
    fn test_parse_reason_args_named() {
        let mut map = HashMap::new();
        map.insert("system".into(), DslValue::String("sys".into()));
        map.insert("user".into(), DslValue::String("usr".into()));
        map.insert("max_iterations".into(), DslValue::Integer(5));

        let args = vec![DslValue::Map(map)];
        let (system, user, max_iter, max_tokens) = parse_reason_args(&args).unwrap();
        assert_eq!(system, "sys");
        assert_eq!(user, "usr");
        assert_eq!(max_iter, 5);
        assert_eq!(max_tokens, 100_000);
    }

    #[test]
    fn test_parse_reason_args_missing_required() {
        let mut map = HashMap::new();
        map.insert("system".into(), DslValue::String("sys".into()));
        // Missing "user"

        let args = vec![DslValue::Map(map)];
        assert!(parse_reason_args(&args).is_err());
    }

    #[test]
    fn extracts_optional_protocol_label_named_arg() {
        // Named-arg map containing protocol_label alongside agent/message
        let mut map_with = HashMap::new();
        map_with.insert("agent".into(), DslValue::String("Worker".into()));
        map_with.insert("message".into(), DslValue::String("go".into()));
        map_with.insert("protocol_label".into(), DslValue::String("fast".into()));
        let with = vec![DslValue::Map(map_with)];
        assert_eq!(optional_protocol_label(&with), Some("fast".to_string()));

        // Positional-only — no protocol_label
        let without = vec![
            DslValue::String("Worker".into()),
            DslValue::String("go".into()),
        ];
        assert_eq!(optional_protocol_label(&without), None);

        // Named-arg map without protocol_label key
        let mut map_absent = HashMap::new();
        map_absent.insert("agent".into(), DslValue::String("Bot".into()));
        map_absent.insert("message".into(), DslValue::String("hi".into()));
        let no_label = vec![DslValue::Map(map_absent)];
        assert_eq!(optional_protocol_label(&no_label), None);

        // Wrong type for protocol_label — treated as absent
        let mut map_wrong = HashMap::new();
        map_wrong.insert("agent".into(), DslValue::String("Bot".into()));
        map_wrong.insert("message".into(), DslValue::String("hi".into()));
        map_wrong.insert("protocol_label".into(), DslValue::Integer(42));
        let wrong_type = vec![DslValue::Map(map_wrong)];
        assert_eq!(optional_protocol_label(&wrong_type), None);
    }

    // Real marker effects distinguish authorization from a cosmetic status.
    // Explicit fixture roots avoid changing the process-wide working directory.
    use symbi_runtime::reasoning::policy_bridge::DefaultPolicyGate;

    pub(super) fn setup_side_effecting_tool() -> (std::path::PathBuf, tempfile::TempDir) {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let tools_dir = tempdir.path().join("tools");
        std::fs::create_dir_all(&tools_dir).expect("mkdir tools/");
        std::fs::write(
            tools_dir.join("touch_marker.clad.toml"),
            r#"
[tool]
name = "touch_marker"
version = "1.0.0"
binary = "touch"
description = "test-only: creates a marker file to prove the tool actually ran"

[args.path]
position = 1
required = true
type = "string"
description = "marker file path"

[command]
template = "touch {path}"

[output]
format = "text"

[output.schema]
type = "object"
"#,
        )
        .expect("write manifest");
        let marker = tempdir.path().join("marker.txt");
        (marker, tempdir)
    }

    fn touch_marker_call(marker: &std::path::Path) -> Vec<DslValue> {
        let mut args_map = HashMap::new();
        args_map.insert(
            "path".to_string(),
            DslValue::String(marker.display().to_string()),
        );
        vec![
            DslValue::String("touch_marker".to_string()),
            DslValue::Map(args_map),
        ]
    }

    #[tokio::test]
    async fn tool_call_denied_by_fail_closed_gate_never_executes() {
        let (marker, project) = setup_side_effecting_tool();
        let ctx = ReasoningBuiltinContext {
            project_root: Ok(project.path().to_owned()),
            reasoning_policy_gate: Some(Arc::new(DefaultPolicyGate::new())),
            ..Default::default()
        };

        let result = builtin_tool_call(&touch_marker_call(&marker), &ctx)
            .await
            .expect("builtin_tool_call should not error, just report denial");

        match result {
            DslValue::Map(map) => {
                assert_eq!(
                    map.get("status"),
                    Some(&DslValue::String("denied".to_string()))
                );
            }
            other => panic!("expected Map, got {other:?}"),
        }
        assert!(
            !marker.exists(),
            "fail-closed gate must prevent the tool from actually running, \
             not just report an error"
        );
    }

    #[tokio::test]
    async fn tool_call_with_no_gate_in_context_defaults_fail_closed() {
        // Mirrors `builtin_reason`'s default: a context that never had a
        // gate installed must NOT fall back to permissive.
        let (marker, project) = setup_side_effecting_tool();
        let ctx = ReasoningBuiltinContext::default()
            .with_project_root(project.path())
            .unwrap();

        builtin_tool_call(&touch_marker_call(&marker), &ctx)
            .await
            .expect("builtin_tool_call should not error, just report denial");

        assert!(
            !marker.exists(),
            "no policy gate configured must default to fail-closed, never permissive"
        );
    }

    #[tokio::test]
    async fn tool_call_allowed_by_permissive_gate_executes() {
        let (marker, project) = setup_side_effecting_tool();
        let ctx = ReasoningBuiltinContext {
            project_root: Ok(project.path().to_owned()),
            tool_executor: Some(Arc::new(
                symbi_runtime::toolclad::ToolCladExecutor::new(
                    symbi_runtime::toolclad::manifest::load_manifests_from_dir(
                        &project.path().join("tools"),
                    ),
                )
                .with_development_host_execution(),
            )),
            reasoning_policy_gate: Some(Arc::new(DefaultPolicyGate::permissive_for_dev_only())),
            ..Default::default()
        };

        let result = builtin_tool_call(&touch_marker_call(&marker), &ctx)
            .await
            .expect("builtin_tool_call should not error");

        match result {
            DslValue::Map(map) => {
                assert_eq!(
                    map.get("status"),
                    Some(&DslValue::String("success".to_string()))
                );
            }
            other => panic!("expected Map, got {other:?}"),
        }
        assert!(
            marker.exists(),
            "permissive gate should allow the tool to actually run"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn tool_call_binds_normalized_cedar_input_and_audit_to_real_execution() {
        use symbi_runtime::reasoning::loop_types::{BufferedJournal, LoopEvent};
        use symbi_runtime::reasoning::{CedarPolicy, CedarPolicyGate};
        for (tool, arguments, approval, expected_effect) in [
            ("count_fixture", r#"{"count":"999"}"#, false, true),
            ("count_fixture", r#"{"count":"1"}"#, false, false),
            (
                "count_fixture",
                r#"{"count":"999","extra":"ignored"}"#,
                false,
                false,
            ),
            ("unknown_fixture", "{}", false, false),
            ("count_fixture", r#"{"count":"999"}"#, true, false),
        ] {
            let dir = tempfile::tempdir().unwrap();
            let tools = dir.path().join("tools");
            std::fs::create_dir(&tools).unwrap();
            let manifest_path = tools.join("count_fixture.clad.toml");
            std::fs::write(
                &manifest_path,
                format!(
                    r#"
[tool]
name = "count_fixture"
version = "1"
binary = "/usr/bin/touch"
description = "DSL prepared call fixture"
human_approval = {approval}
[tool.cedar]
resource = "Tool::Fixture"
action = "execute"
[args.count]
position = 1
required = true
type = "integer"
min = 1
max = 5
clamp = true
[command]
template = "/usr/bin/touch '{}/{{count}}'"
[output]
format = "text"
"#,
                    dir.path().display()
                ),
            )
            .unwrap();
            let manifest =
                symbi_runtime::toolclad::manifest::load_manifest(&manifest_path).unwrap();
            let gate = CedarPolicyGate::deny_by_default();
            gate.add_policy(CedarPolicy {
                name: "fixture".into(), active: true,
                source: format!("{}\nforbid(principal, action, resource) when {{ context.invocation.arguments.count != \"5\" }};", symbi_runtime::toolclad::cedar_gen::generate_policy(&manifest).unwrap()),
            }).await;
            let journal = Arc::new(BufferedJournal::new(100));
            let ctx = ReasoningBuiltinContext {
                reasoning_policy_gate: Some(Arc::new(gate)),
                tool_executor: Some(Arc::new(
                    symbi_runtime::toolclad::ToolCladExecutor::new(
                        symbi_runtime::toolclad::manifest::load_manifests_from_dir(&tools),
                    )
                    .with_development_host_execution(),
                )),
                reasoning_journal: Some(journal.clone()),
                ..Default::default()
            };
            let result = builtin_tool_call(
                &[
                    DslValue::String(tool.into()),
                    DslValue::String(arguments.into()),
                ],
                &ctx,
            )
            .await
            .unwrap();
            let DslValue::Map(result) = result else {
                panic!("expected result map")
            };
            assert_eq!(
                result["status"],
                DslValue::String(if expected_effect { "success" } else { "denied" }.into()),
                "{result:?}"
            );
            assert_eq!(dir.path().join("5").exists(), expected_effect, "{result:?}");
            assert!(!dir.path().join("999").exists());
            assert!(!dir.path().join("1").exists());
            let entries = journal.entries().await;
            // Dispatch start/finish are journalled only for an approved call; a
            // denied one is never dispatched, so that pair is absent.
            assert_eq!(entries.len(), if expected_effect { 6 } else { 4 });
            assert!(matches!(entries[0].event, LoopEvent::Started { .. }));
            assert!(matches!(
                entries[entries.len() - 1].event,
                LoopEvent::Terminated { .. }
            ));
            if expected_effect {
                assert!(matches!(
                    entries[2].event,
                    LoopEvent::ToolDispatchStarted { .. }
                ));
                assert!(matches!(
                    entries[3].event,
                    LoopEvent::ToolDispatchFinished { .. }
                ));
            }
            let LoopEvent::PolicyEvaluated { approved_calls, .. } = &entries[1].event else {
                panic!("missing pre-effect checkpoint")
            };
            if expected_effect {
                assert_eq!(approved_calls[0]["arguments"]["count"], "5");
                assert_eq!(
                    result["arguments"],
                    DslValue::String(r#"{"count":"5"}"#.into())
                );
            } else {
                assert!(approved_calls.is_empty());
            }
            assert!(matches!(
                entries[entries.len() - 2].event,
                LoopEvent::ToolBatchCompleted { .. }
            ));
        }
    }

    #[tokio::test]
    async fn tool_call_returns_required_journal_failure() {
        use symbi_runtime::reasoning::loop_types::{JournalEntry, JournalError, JournalWriter};
        struct FailingJournal;
        #[async_trait::async_trait]
        impl JournalWriter for FailingJournal {
            async fn append(&self, _: JournalEntry) -> std::result::Result<(), JournalError> {
                Err(JournalError::WriteFailed("DSL journal fixture".into()))
            }
            async fn next_sequence(&self) -> u64 {
                0
            }
        }
        let ctx = ReasoningBuiltinContext {
            reasoning_journal: Some(Arc::new(FailingJournal)),
            ..Default::default()
        };
        let error = builtin_tool_call(&[DslValue::String("missing".into())], &ctx)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("DSL journal fixture"));
    }

    #[cfg(unix)]
    #[tokio::test]
    #[ignore = "requires Docker, cached Python fixture image, and runtime toolclad-session feature"]
    async fn explicit_dsl_terminal_call_awaits_contained_worker_removal() {
        use std::os::unix::fs::PermissionsExt;
        use symbi_runtime::{
            reasoning::{CedarPolicy, CedarPolicyGate},
            sandbox::command::CommandBoundary,
            toolclad::ToolCladExecutor,
        };
        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("output");
        std::fs::create_dir(&output).unwrap();
        std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o777)).unwrap();
        let script = dir.path().join("terminal.py");
        std::fs::write(
            &script,
            r#"
import os, pathlib, sys, time
assert sys.stdin.isatty() and sys.stdout.isatty()
assert os.getuid() == 65534
print('READY>', flush=True)
for line in sys.stdin:
    assert line.strip() == 'run'
    pathlib.Path('/workspace/allowed').write_text('real terminal effect')
    if os.fork() == 0:
        os.setsid()
        time.sleep(30)
        pathlib.Path('/workspace/late-effect').touch()
        os._exit(0)
    print('executed\nREADY>', flush=True)
"#,
        )
        .unwrap();
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o444)).unwrap();
        let manifest_path = dir.path().join("terminal.clad.toml");
        std::fs::write(
            &manifest_path,
            r#"
[tool]
name = "terminal"
version = "1"
description = "DSL terminal fixture"
mode = "session"
timeout_seconds = 10
[session]
startup_command = "/usr/local/bin/python3 -u /opt/terminal.py"
ready_pattern = "READY>"
startup_timeout_seconds = 5
idle_timeout_seconds = 20
session_timeout_seconds = 20
max_interactions = 5
[session.commands.send]
pattern = "run"
description = "Execute fixture"
[output]
format = "text"
"#,
        )
        .unwrap();
        let manifest = symbi_runtime::toolclad::manifest::load_manifest(&manifest_path).unwrap();
        let mut profile = CommandBoundary::default();
        profile.docker.image =
            "sha256:7bf61a5ec2a4631b240bc8cf83404e2dd37fb06a4b4bbd34b2c36906a5fb4aee".into();
        profile.docker.volumes = vec![
            format!("{}:/workspace:rw", output.display()),
            format!("{}:/opt/terminal.py:ro", script.display()),
        ];
        let label = format!("symbi.dsl-pty-e2e={}", uuid::Uuid::new_v4());
        profile.docker.extra_flags.push(format!("--label={label}"));
        let executor = Arc::new(
            ToolCladExecutor::new(vec![("terminal".into(), manifest)])
                .with_command_boundary(profile),
        );
        let gate = CedarPolicyGate::deny_by_default();
        gate.add_policy(CedarPolicy { name: "fixture".into(), active: true,
            source: "permit(principal, action == Action::\"tool_call::terminal.send\", resource) when { context.invocation.arguments.command == \"run\" };".into()
        }).await;
        let ctx = ReasoningBuiltinContext {
            project_root: Ok(dir.path().to_owned()),
            tool_executor: Some(executor.clone()),
            reasoning_policy_gate: Some(Arc::new(gate)),
            ..Default::default()
        };
        let result = builtin_tool_call(
            &[
                DslValue::String("terminal.send".into()),
                DslValue::String(r#"{"command":"run"}"#.into()),
            ],
            &ctx,
        )
        .await
        .unwrap();
        let DslValue::Map(result) = result else {
            panic!("expected tool result")
        };
        assert_eq!(
            result["status"],
            DslValue::String("success".into()),
            "{result:?}"
        );
        assert_eq!(
            std::fs::read_to_string(output.join("allowed")).unwrap(),
            "real terminal effect"
        );
        let workers = tokio::process::Command::new("docker")
            .args(["ps", "-aq", "--filter", &format!("label={label}")])
            .output()
            .await
            .unwrap();
        assert!(workers.status.success());
        assert!(
            workers.stdout.is_empty(),
            "builtin must await cleanup even while executor is retained"
        );
        assert!(!output.join("late-effect").exists());
        let entries =
            super::audit_tests::verified_result(&DslValue::Map(result), ctx.sender_agent_id);
        assert!(matches!(
            entries.last().unwrap().event,
            symbi_runtime::reasoning::loop_types::LoopEvent::Terminated {
                reason: symbi_runtime::reasoning::loop_types::TerminationReason::Completed,
                ..
            }
        ));
        drop(executor);
    }
}

#[cfg(all(test, unix))]
mod audit_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use symbi_runtime::reasoning::{
        inference::{FinishReason, InferenceOptions, InferenceResponse, Usage},
        loop_types::{JournalEntry, LoopEvent, TerminationReason},
        protected_journal::ProtectedJournal,
    };

    struct Provider {
        calls: AtomicUsize,
        pending: bool,
    }
    #[async_trait::async_trait]
    impl InferenceProvider for Provider {
        async fn complete(
            &self,
            _: &symbi_runtime::reasoning::conversation::Conversation,
            _: &InferenceOptions,
        ) -> std::result::Result<
            InferenceResponse,
            symbi_runtime::reasoning::inference::InferenceError,
        > {
            self.calls.fetch_add(1, Ordering::SeqCst);
            if self.pending {
                std::future::pending::<()>().await;
            }
            Ok(InferenceResponse {
                content: "audit fixture response".into(),
                tool_calls: vec![],
                finish_reason: FinishReason::Stop,
                usage: Usage::default(),
                model: "fixture".into(),
            })
        }
        fn provider_name(&self) -> &str {
            "audit-fixture"
        }
        fn default_model(&self) -> &str {
            "fixture"
        }
        fn supports_native_tools(&self) -> bool {
            false
        }
        fn supports_structured_output(&self) -> bool {
            false
        }
    }
    fn provider(pending: bool) -> Arc<Provider> {
        Arc::new(Provider {
            calls: AtomicUsize::new(0),
            pending,
        })
    }
    fn arguments() -> Vec<DslValue> {
        vec![
            DslValue::String("Synthetic system".into()),
            DslValue::String("Synthetic request".into()),
        ]
    }
    pub(super) fn verified_result(
        value: &DslValue,
        principal: Option<AgentId>,
    ) -> Vec<JournalEntry> {
        use std::os::unix::fs::PermissionsExt;
        let json = value.to_json();
        let audit = &json["audit"];
        let path = std::path::Path::new(audit["path"].as_str().unwrap());
        let key = audit["public_key"].as_str().unwrap();
        let key: [u8; 32] = (0..32)
            .map(|i| u8::from_str_radix(&key[i * 2..i * 2 + 2], 16).unwrap())
            .collect::<Vec<_>>()
            .try_into()
            .unwrap();
        let run = audit["run_id"].as_str().unwrap().parse().unwrap();
        let entries = ProtectedJournal::verify_run(path, &key, run).unwrap();
        assert!(ProtectedJournal::verify_run(path, &key, uuid::Uuid::new_v4()).is_err());
        assert_eq!(
            std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
            0o600
        );
        let id = principal.unwrap_or(entries[0].agent_id);
        assert!(entries.iter().all(|entry| entry.agent_id == id));
        assert!(matches!(entries[0].event, LoopEvent::Started { agent_id, .. } if agent_id == id));
        entries
    }

    #[tokio::test]
    async fn default_reason_audit_has_distinct_runs_and_one_bound_principal() {
        let project = tempfile::tempdir().unwrap();
        let id = AgentId::new();
        let inference = provider(false);
        let ctx = ReasoningBuiltinContext {
            provider: Some(inference.clone()),
            sender_agent_id: Some(id),
            ..Default::default()
        }
        .with_project_root(project.path())
        .unwrap();
        let first = builtin_reason(&arguments(), &ctx).await.unwrap();
        let second = builtin_reason(&arguments(), &ctx).await.unwrap();
        for value in [&first, &second] {
            let entries = verified_result(value, Some(id));
            assert!(matches!(
                entries.last().unwrap().event,
                LoopEvent::Terminated {
                    reason: TerminationReason::Completed,
                    ..
                }
            ));
        }
        assert_ne!(
            first.to_json()["audit"]["run_id"],
            second.to_json()["audit"]["run_id"]
        );
        assert_eq!(
            first.to_json()["audit"]["public_key"],
            second.to_json()["audit"]["public_key"]
        );
        assert_eq!(inference.calls.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn unsafe_default_audit_blocks_inference_and_dispatch() {
        use std::os::unix::fs::PermissionsExt;
        let (marker, project) = super::tests::setup_side_effecting_tool();
        let audit = project.path().join(".symbiont/governed");
        std::fs::create_dir_all(&audit).unwrap();
        std::fs::set_permissions(&audit, std::fs::Permissions::from_mode(0o777)).unwrap();
        let inference = provider(false);
        let ctx = ReasoningBuiltinContext {
            provider: Some(inference.clone()),
            reasoning_policy_gate: Some(Arc::new(
                symbi_runtime::reasoning::policy_bridge::DefaultPolicyGate::permissive_for_dev_only(
                ),
            )),
            tool_executor: Some(Arc::new(
                symbi_runtime::toolclad::ToolCladExecutor::new(
                    symbi_runtime::toolclad::manifest::load_manifests_from_dir(
                        &project.path().join("tools"),
                    ),
                )
                .with_development_host_execution(),
            )),
            ..Default::default()
        }
        .with_project_root(project.path())
        .unwrap();
        let error = builtin_reason(&arguments(), &ctx).await.unwrap_err();
        assert!(error
            .to_string()
            .contains("Required DSL audit initialization failed"));
        let error = builtin_tool_call(
            &[
                DslValue::String("touch_marker".into()),
                DslValue::String(serde_json::json!({"path": marker}).to_string()),
            ],
            &ctx,
        )
        .await
        .unwrap_err();
        assert!(error
            .to_string()
            .contains("Required DSL audit initialization failed"));
        assert_eq!(inference.calls.load(Ordering::SeqCst), 0);
        assert!(!marker.exists());
        assert_eq!(std::fs::read_dir(audit).unwrap().count(), 0);
    }

    #[tokio::test]
    async fn missing_project_capture_is_never_replaced_by_later_cwd() {
        let inference = provider(false);
        let ctx = ReasoningBuiltinContext {
            provider: Some(inference.clone()),
            project_root: Err("startup fixture failure".into()),
            ..Default::default()
        };
        assert!(builtin_reason(&arguments(), &ctx)
            .await
            .unwrap_err()
            .to_string()
            .contains("startup fixture failure"));
        assert!(
            builtin_tool_call(&[DslValue::String("missing".into())], &ctx)
                .await
                .unwrap_err()
                .to_string()
                .contains("startup fixture failure")
        );
        assert_eq!(inference.calls.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn cancelled_reason_leaves_a_signed_incomplete_prefix() {
        let project = tempfile::tempdir().unwrap();
        let (anchor, reference) =
            symbi_runtime::reasoning::run_audit::open_run_journal(project.path(), AgentId::new())
                .await
                .unwrap();
        let key: [u8; 32] = (0..32)
            .map(|i| u8::from_str_radix(&reference.public_key[i * 2..i * 2 + 2], 16).unwrap())
            .collect::<Vec<_>>()
            .try_into()
            .unwrap();
        drop(anchor);
        let inference = provider(true);
        let ctx = ReasoningBuiltinContext {
            provider: Some(inference.clone()),
            ..Default::default()
        }
        .with_project_root(project.path())
        .unwrap();
        let args = arguments();
        let future = builtin_reason(&args, &ctx);
        tokio::pin!(future);
        // Drive the call until the provider has actually been entered, rather
        // than assuming a fixed delay is long enough to get there. A 300ms
        // budget was not always enough under parallel load, and the call-count
        // assertion then failed for a reason unrelated to what this covers.
        // The provider stalls forever once entered, so the future must not
        // finish first.
        tokio::select! {
            _ = &mut future => panic!("reason() must not complete while the provider stalls"),
            entered = tokio::time::timeout(std::time::Duration::from_secs(10), async {
                while inference.calls.load(Ordering::SeqCst) == 0 {
                    tokio::task::yield_now().await;
                }
            }) => entered.expect("the provider must be entered"),
        }
        // Having been entered, it must stay pending.
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(100), &mut future)
                .await
                .is_err()
        );
        assert_eq!(inference.calls.load(Ordering::SeqCst), 1);
        let audit = project.path().join(".symbiont/governed");
        let file = std::fs::read_dir(&audit)
            .unwrap()
            .map(|entry| entry.unwrap().path())
            .find(|path| {
                path != &reference.path && path.extension().is_some_and(|ext| ext == "jsonl")
            })
            .unwrap();
        let run_id = file
            .file_stem()
            .unwrap()
            .to_str()
            .unwrap()
            .rsplit('.')
            .next()
            .unwrap()
            .parse()
            .unwrap();
        let entries = ProtectedJournal::verify_run(&file, &key, run_id).unwrap();
        assert!(matches!(entries[0].event, LoopEvent::Started { .. }));
        assert!(entries
            .iter()
            .all(|entry| !matches!(entry.event, LoopEvent::Terminated { .. })));
    }

    #[test]
    fn bridge_project_survives_process_working_directory_change() {
        // Only the isolated subprocess changes CWD; the parallel test runner never does.
        const CHILD: &str = "SYMBI_DSL_CWD_FIXTURE_CHILD";
        if std::env::var_os(CHILD).is_none() {
            let output = std::process::Command::new(std::env::current_exe().unwrap())
                .args(["--exact", "dsl::reasoning_builtins::audit_tests::bridge_project_survives_process_working_directory_change", "--test-threads=1"])
                .env(CHILD, "1").output().unwrap();
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stdout)
            );
            return;
        }
        let (_, project) = super::tests::setup_side_effecting_tool();
        let decoy = tempfile::tempdir().unwrap();
        std::env::set_current_dir(project.path()).unwrap();
        let bridge = crate::runtime_bridge::RuntimeBridge::new();
        let initial = ReasoningBuiltinContext::default();
        std::env::set_current_dir(decoy.path()).unwrap();
        let ctx = bridge.reasoning_context();
        assert_eq!(ctx.project().unwrap(), project.path());
        assert_eq!(initial.project().unwrap(), project.path());
        for context in [&initial, &ctx] {
            assert!(context
                .executor()
                .unwrap()
                .tool_definitions()
                .iter()
                .any(|tool| tool.name == "touch_marker"));
        }
        tokio::runtime::Runtime::new().unwrap().block_on(async {
            let value = builtin_tool_call(&[DslValue::String("missing".into())], &ctx)
                .await
                .unwrap();
            let entries = verified_result(&value, None);
            assert!(matches!(
                entries.last().unwrap().event,
                LoopEvent::Terminated {
                    reason: TerminationReason::PolicyDenial { .. },
                    ..
                }
            ));
            assert!(
                std::path::Path::new(value.to_json()["audit"]["path"].as_str().unwrap())
                    .starts_with(project.path())
            );
        });
        assert!(!decoy.path().join(".symbiont").exists());
    }
    #[tokio::test]
    async fn failed_terminal_write_cannot_report_an_effect_as_success() {
        use symbi_runtime::reasoning::loop_types::{JournalError, JournalWriter};
        struct TerminalFailure;
        #[async_trait::async_trait]
        impl JournalWriter for TerminalFailure {
            async fn append(&self, entry: JournalEntry) -> std::result::Result<(), JournalError> {
                if matches!(entry.event, LoopEvent::Terminated { .. }) {
                    Err(JournalError::WriteFailed("terminal write fixture".into()))
                } else {
                    Ok(())
                }
            }
            async fn next_sequence(&self) -> u64 {
                0
            }
        }
        let (marker, project) = super::tests::setup_side_effecting_tool();
        let executor = symbi_runtime::toolclad::ToolCladExecutor::new(
            symbi_runtime::toolclad::manifest::load_manifests_from_dir(
                &project.path().join("tools"),
            ),
        )
        .with_development_host_execution();
        let ctx = ReasoningBuiltinContext {
            tool_executor: Some(Arc::new(executor)),
            reasoning_policy_gate: Some(Arc::new(
                symbi_runtime::reasoning::policy_bridge::DefaultPolicyGate::permissive_for_dev_only(
                ),
            )),
            reasoning_journal: Some(Arc::new(TerminalFailure)),
            ..Default::default()
        };
        let error = builtin_tool_call(
            &[
                DslValue::String("touch_marker".into()),
                DslValue::String(serde_json::json!({"path": marker}).to_string()),
            ],
            &ctx,
        )
        .await
        .unwrap_err();
        assert!(error.to_string().contains("terminal write fixture"));
        assert!(
            marker.exists(),
            "the effect happened but must not be reported as durably completed"
        );
    }

    #[tokio::test]
    async fn cleanup_failure_is_recorded_as_error_before_return() {
        use symbi_runtime::reasoning::{
            circuit_breaker::CircuitBreakerRegistry,
            executor::ActionExecutor,
            loop_types::{BufferedJournal, Observation, ProposedAction},
            LoopConfig,
        };
        struct CleanupFailure;
        #[async_trait::async_trait]
        impl ActionExecutor for CleanupFailure {
            async fn execute_actions(
                &self,
                _: &[ProposedAction],
                _: &LoopConfig,
                _: &CircuitBreakerRegistry,
            ) -> Vec<Observation> {
                panic!("unregistered tool must not execute")
            }
            async fn close_run(
                &self,
                _: &str,
                _: std::time::Instant,
            ) -> std::result::Result<(), String> {
                Err("cleanup fixture".into())
            }
        }
        let journal = Arc::new(BufferedJournal::new(100));
        let ctx = ReasoningBuiltinContext {
            tool_executor: Some(Arc::new(CleanupFailure)),
            reasoning_journal: Some(journal.clone()),
            ..Default::default()
        };
        let error = builtin_tool_call(&[DslValue::String("missing".into())], &ctx)
            .await
            .unwrap_err();
        assert!(error
            .to_string()
            .contains("Required worker cleanup failed: cleanup fixture"));
        let entries = journal.entries().await;
        assert!(matches!(&entries.last().unwrap().event,
            LoopEvent::Terminated { reason: TerminationReason::Error { message }, .. } if message.contains("cleanup fixture")));
    }
    #[tokio::test]
    async fn parsed_evaluator_builtins_preserve_project_audit_and_caller() {
        use crate::dsl::{
            ast::*,
            evaluator::{DslEvaluator, ExecutionContext},
            lexer::Lexer,
            parser::Parser,
        };
        let project = tempfile::tempdir().unwrap();
        let inference = provider(false);
        let bridge = Arc::new(
            crate::runtime_bridge::RuntimeBridge::new()
                .with_project_root(project.path())
                .unwrap(),
        );
        bridge.set_inference_provider(inference.clone());
        let evaluator = DslEvaluator::new(bridge);
        let id = uuid::Uuid::new_v4();
        for (source, completed) in [
            (
                r#"function run_fixture() { return reason("synthetic system", "synthetic request") }"#,
                true,
            ),
            (
                r#"function run_fixture() { return tool_call("missing") }"#,
                false,
            ),
        ] {
            let program = Parser::new(Lexer::new(source).tokenize().unwrap())
                .parse()
                .unwrap();
            let mut context = ExecutionContext {
                agent_id: Some(id),
                ..Default::default()
            };
            for declaration in program.declarations {
                if let Declaration::Function(function) = declaration {
                    context.functions.insert(function.name.clone(), function);
                }
            }
            let expression = Expression::FunctionCall(FunctionCall {
                function: "run_fixture".into(),
                arguments: vec![],
                span: program.span,
            });
            let value = evaluator
                .evaluate_expression(&expression, &mut context)
                .await
                .unwrap();
            let entries = verified_result(&value, Some(AgentId(id)));
            assert!(
                std::path::Path::new(value.to_json()["audit"]["path"].as_str().unwrap())
                    .starts_with(project.path())
            );
            match &entries.last().unwrap().event {
                LoopEvent::Terminated {
                    reason: TerminationReason::Completed,
                    ..
                } => assert!(completed),
                LoopEvent::Terminated {
                    reason: TerminationReason::PolicyDenial { .. },
                    ..
                } => assert!(!completed),
                other => panic!("unexpected terminal record: {other:?}"),
            }
        }
        assert_eq!(inference.calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn registered_behaviors_keep_distinct_principals_in_protected_audit() {
        let project = tempfile::tempdir().unwrap();
        let inference = provider(false);
        let bridge = Arc::new(
            crate::RuntimeBridge::new()
                .with_project_root(project.path())
                .unwrap(),
        );
        bridge.set_inference_provider(inference.clone());
        let engine = crate::ReplEngine::new(bridge);
        engine
            .evaluate("agent First {} agent Second {}")
            .await
            .unwrap();
        engine
            .evaluate(
                r#"function helper() { return reason("synthetic system", "synthetic request") }"#,
            )
            .await
            .unwrap();
        engine
            .evaluate("behavior Work { steps { return helper() } }")
            .await
            .unwrap();
        let agents = engine.evaluator().list_agents().await;
        for agent in &agents {
            engine
                .evaluate(&format!(":agent start {}", agent.id))
                .await
                .unwrap();
        }
        let (first, second) = tokio::join!(
            engine
                .evaluator()
                .execute_agent_behavior(agents[0].id, "Work", ""),
            engine
                .evaluator()
                .execute_agent_behavior(agents[1].id, "Work", ""),
        );
        for (value, agent) in [first.unwrap(), second.unwrap()].iter().zip(&agents) {
            let entries = verified_result(value, Some(AgentId(agent.id)));
            assert!(matches!(
                entries.last().unwrap().event,
                LoopEvent::Terminated {
                    reason: TerminationReason::Completed,
                    ..
                }
            ));
        }
        assert_eq!(inference.calls.load(Ordering::SeqCst), 2);
        assert!(engine
            .evaluator()
            .monitor()
            .get_active_executions()
            .is_empty());
    }

    #[tokio::test]
    #[ignore = "requires Docker and cached Python fixture image"]
    async fn registered_repl_behavior_enforces_real_policy_boundary_and_audit() {
        use std::os::unix::fs::PermissionsExt;
        use symbi_runtime::reasoning::{CedarPolicy, CedarPolicyGate};
        let project = tempfile::tempdir().unwrap();
        let output = project.path().join("output");
        std::fs::create_dir(&output).unwrap();
        std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o777)).unwrap();
        let canary = project.path().join("host-canary");
        std::fs::write(&canary, "synthetic private canary").unwrap();
        let label = format!("symbi.repl-e2e={}", uuid::Uuid::new_v4());
        let config = format!(
            r#"
[sandbox]
tier = "docker"
[sandbox.docker]
image = "sha256:7bf61a5ec2a4631b240bc8cf83404e2dd37fb06a4b4bbd34b2c36906a5fb4aee"
volumes = [{}]
extra_flags = ["--label={label}"]
"#,
            serde_json::to_string(&format!("{}:/workspace:rw", output.display())).unwrap()
        );
        std::fs::write(project.path().join("symbiont.toml"), config).unwrap();
        std::fs::create_dir(project.path().join("tools")).unwrap();
        std::fs::write(project.path().join("tools/write.clad.toml"), format!(r#"
[tool]
name = "write"
version = "1"
description = "Write an isolated test result"
binary = "/bin/sh"
timeout_seconds = 15
[command]
template = "/bin/sh -c 'test ! -e {} && test `id -u` = 65534 && printf registered > /workspace/allowed'"
[output]
format = "text"
"#, canary.display())).unwrap();
        let gate = Arc::new(CedarPolicyGate::deny_by_default());
        let bridge = Arc::new(
            crate::RuntimeBridge::new()
                .with_project_root(project.path())
                .unwrap(),
        );
        bridge.set_reasoning_policy_gate(gate.clone());
        let engine = crate::ReplEngine::new(bridge);
        for requirement in [
            "security { tier: Tier3 }",
            "security { sandbox: strict }",
            "resources { memory: 1MB network: false }",
            "policies { timeout: 1ms }",
        ] {
            let error = engine
                .evaluate(&format!("agent Unsupported {{ {requirement} }}"))
                .await
                .unwrap_err();
            assert!(error.to_string().contains("Unsupported legacy agent"));
            assert!(engine.evaluator().list_agents().await.is_empty());
            assert!(!project.path().join(".symbiont/governed").exists());
            assert!(!output.join("allowed").exists());
        }
        engine
            .evaluate("agent Permitted {} agent Sibling {}")
            .await
            .unwrap();
        engine
            .evaluate(r#"function write_fixture() { return tool_call("write") }"#)
            .await
            .unwrap();
        engine
            .evaluate("behavior Work { steps { return write_fixture() } }")
            .await
            .unwrap();
        let agents = engine.evaluator().list_agents().await;
        let permitted = agents
            .iter()
            .find(|a| a.definition.name == "Permitted")
            .unwrap()
            .id;
        let sibling = agents
            .iter()
            .find(|a| a.definition.name == "Sibling")
            .unwrap()
            .id;
        gate.add_policy(CedarPolicy {
            name: "fixture".into(), active: true,
            source: format!("permit(principal == Agent::\"{permitted}\", action == Action::\"tool_call::write\", resource);"),
        }).await;
        for id in [permitted, sibling] {
            engine
                .evaluate(&format!(":agent start {id}"))
                .await
                .unwrap();
        }
        let denied = engine
            .evaluator()
            .execute_agent_behavior(sibling, "Work", "")
            .await
            .unwrap();
        assert_eq!(denied.to_json()["status"], "denied");
        assert!(!output.join("allowed").exists());
        let denied_entries = verified_result(&denied, Some(AgentId(sibling)));
        assert!(matches!(
            denied_entries.last().unwrap().event,
            LoopEvent::Terminated {
                reason: TerminationReason::PolicyDenial { .. },
                ..
            }
        ));
        let allowed = engine
            .evaluator()
            .execute_agent_behavior(permitted, "Work", "")
            .await
            .unwrap();
        assert_eq!(allowed.to_json()["status"], "success", "{allowed:?}");
        assert_eq!(
            std::fs::read_to_string(output.join("allowed")).unwrap(),
            "registered"
        );
        let entries = verified_result(&allowed, Some(AgentId(permitted)));
        assert!(matches!(
            entries.last().unwrap().event,
            LoopEvent::Terminated {
                reason: TerminationReason::Completed,
                ..
            }
        ));
        std::fs::remove_file(output.join("allowed")).unwrap();
        std::fs::write(
            project.path().join("symbiont.toml"),
            "[sandbox]\ntier = \"firecracker\"\n",
        )
        .unwrap();
        let unavailable = engine
            .evaluator()
            .execute_agent_behavior(permitted, "Work", "")
            .await
            .unwrap();
        assert_ne!(unavailable.to_json()["status"], "success");
        assert!(!output.join("allowed").exists());
        verified_result(&unavailable, Some(AgentId(permitted)));
        let workers = tokio::process::Command::new("docker")
            .args(["ps", "-aq", "--filter", &format!("label={label}")])
            .output()
            .await
            .unwrap();
        assert!(workers.status.success());
        assert!(workers.stdout.is_empty(), "owned workers remain");
    }
}