synaps-engine 0.11.0

Runtime engine — streaming, tools, MCP, skills, extensions, sidecar
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
//! Engine-level command results — TUI-agnostic outcomes of slash commands.
//!
//! The engine processes a command and returns a `CommandResult`.
//! Renderers (TUI, headless) decide how to display the result.

use agent_core::reasoning::ReasoningLevel;

/// A thinking specification — either a named level or a custom numeric budget.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThinkingSpec {
    /// A named canonical level (off/adaptive/low/medium/high/xhigh/max/ultra).
    Named(ReasoningLevel),
    /// A custom numeric budget (e.g. `/thinking 8192`).
    /// `level` is the nearest named level for display; `budget` is the exact value.
    Custom { level: ReasoningLevel, budget: u32 },
}

impl ThinkingSpec {
    /// Named level (used for validation and display).
    pub fn level(self) -> ReasoningLevel {
        match self {
            ThinkingSpec::Named(l) => l,
            ThinkingSpec::Custom { level, .. } => level,
        }
    }

    /// Exact budget, if applicable. `None` for Max/Ultra which have no numeric budget.
    pub fn budget(self) -> Option<u32> {
        match self {
            ThinkingSpec::Named(l) => l.to_legacy_budget(),
            ThinkingSpec::Custom { budget, .. } => Some(budget),
        }
    }

    /// Config-file string: exact budget digits for Custom, named string otherwise.
    pub fn config_value(self) -> String {
        match self {
            ThinkingSpec::Named(l) => l.as_str().to_string(),
            ThinkingSpec::Custom { budget, .. } => budget.to_string(),
        }
    }
}

/// Result of processing a slash command in the engine.
#[derive(Debug, Clone)]
pub enum CommandResult {
    /// No output, continue.
    None,

    /// Text output to display to the user.
    Output(String),

    /// Error message.
    Error(String),

    /// Model was changed. `reasoning_clamped` is populated when the runtime
    /// had to substitute the active reasoning level because the new model does
    /// not support it (see `Runtime::try_set_model`).
    ModelChanged {
        model: String,
        reasoning_clamped: Option<crate::runtime::ReasoningClamp>,
    },

    /// Thinking level was changed.
    ThinkingChanged {
        spec: ThinkingSpec,
    },

    /// System prompt was updated.
    SystemPromptSet {
        source: String, // "inline", "file", "saved"
    },

    /// System prompt displayed.
    SystemPromptShow {
        prompt: String,
    },

    /// Session list.
    SessionList {
        sessions: Vec<SessionSummary>,
    },

    /// Session cleared. New session returned.
    Cleared,

    /// Quit requested.
    Quit,

    /// Compaction requested (engine should trigger it).
    Compact {
        custom_instructions: Option<String>,
    },

    /// Session resumed.
    Resumed {
        session_id: String,
        model: String,
    },

    /// Session named/saved.
    Named {
        name: String,
    },

    /// Chain info.
    ChainInfo(String),

    /// Request to open a TUI-specific modal (TUI handles, headless ignores).
    OpenModal(ModalRequest),

    /// Status/usage info.
    Status {
        text: String,
    },

    /// Ping results.
    PingStarted,

    /// Keybind list.
    KeybindList(String),

    /// Skill loaded — needs to be injected into the conversation.
    SkillLoaded {
        skill: std::sync::Arc<crate::skills::LoadedSkill>,
        arg: String,
    },

    /// Plugin command to execute.
    PluginCommand {
        command: std::sync::Arc<crate::skills::registry::RegisteredPluginCommand>,
        arg: String,
    },

    /// Sidecar toggle/status.
    SidecarToggle {
        plugin_id: Option<String>,
    },
    SidecarStatus {
        plugin_id: Option<String>,
    },
}

/// TUI-specific modals the engine can request.
#[derive(Debug, Clone)]
pub enum ModalRequest {
    Models,
    Settings,
    Plugins,
    HelpFind { query: String },
    Extensions { sub: String },
}

/// Summary of a session for listing.
#[derive(Debug, Clone)]
pub struct SessionSummary {
    pub id: String,
    pub model: String,
    pub title: Option<String>,
    pub cost: f64,
    pub message_count: usize,
    pub is_current: bool,
}

/// Parse a slash command into (command, arg).
pub fn parse_command(input: &str) -> Option<(&str, &str)> {
    let trimmed = input.trim();
    if !trimmed.starts_with('/') {
        return None;
    }
    let without_slash = &trimmed[1..];
    let (cmd, arg) = match without_slash.find(char::is_whitespace) {
        Some(pos) => (&without_slash[..pos], without_slash[pos..].trim()),
        None => (without_slash, ""),
    };
    Some((cmd, arg))
}

/// Async pre-step for [`handle_engine_command`]: load the capability
/// evidence `/model` and `/thinking` are validated against into THIS
/// process (see [`crate::Runtime::prepare_model_capabilities`]) so the
/// reasoning clamp / level check is decided on live data, not on an empty
/// process-local cache. Every async frontend calls this right before the
/// synchronous handler; it never fails and is a no-op for other commands.
pub async fn prepare_engine_command(cmd: &str, arg: &str, runtime: &crate::Runtime) {
    match cmd {
        "model" | "models" if !arg.trim().is_empty() => {
            runtime.prepare_model_capabilities(arg.trim()).await
        }
        "thinking" if !arg.trim().is_empty() => {
            let model = runtime.model().to_string();
            runtime.prepare_model_capabilities(&model).await;
        }
        _ => {}
    }
}

/// Process commands that are pure engine logic — no TUI state needed.
/// Returns None if the command needs TUI-level handling.
pub fn handle_engine_command(
    cmd: &str,
    arg: &str,
    runtime: &mut crate::Runtime,
) -> Option<CommandResult> {
    // Runtime-backed commands (Task 12): shared across TUI, headless chat,
    // and server. `/context` here has no conversation history (the surface
    // owns it) — the TUI intercepts `/context` earlier and passes its own
    // history through `context_command`.
    match cmd {
        "context" if !arg.is_empty() => {
            return Some(match runtime.context_management_command(arg) {
                Ok(s) => CommandResult::Output(s),
                Err(e) => CommandResult::Error(e),
            })
        }
        "context" => return Some(context_command(runtime, None)),
        "trace" => return Some(trace_command(arg, runtime)),
        "budget" => return Some(budget_command(arg, runtime)),
        "workers" => return Some(workers_command(arg, runtime)),
        "confirms" => return Some(confirms_command(arg, runtime)),
        "memory" => return Some(memory_command(arg, runtime)),
        _ => {}
    }
    let mut result = evaluate_engine_command(cmd, arg)?;
    match &mut result {
        CommandResult::ModelChanged {
            model,
            reasoning_clamped,
        } => *reasoning_clamped = runtime.set_model(model.clone()),
        CommandResult::ThinkingChanged { spec } => {
            // Validate and apply the spec against model capabilities BEFORE
            // mutating runtime. State is unchanged on Err.
            match spec {
                ThinkingSpec::Named(level) => {
                    if let Err(msg) = runtime.set_reasoning_level_checked(*level) {
                        return Some(CommandResult::Error(msg));
                    }
                }
                ThinkingSpec::Custom { budget, .. } => {
                    // Custom budget: validate the derived level against the
                    // exact-model capability tables BEFORE mutating; on Ok the
                    // exact budget is retained (Anthropic wire uses it as-is).
                    if let Err(msg) = runtime.set_thinking_budget_checked(*budget) {
                        return Some(CommandResult::Error(msg));
                    }
                }
            }
        }
        _ => {}
    }
    Some(result)
}

/// Pure command → result mapping (no runtime mutation).
pub fn evaluate_engine_command(cmd: &str, arg: &str) -> Option<CommandResult> {
    match cmd {
        "model" | "models" if !arg.is_empty() => Some(CommandResult::ModelChanged {
            model: arg.to_string(),
            reasoning_clamped: None,
        }),
        "thinking" if !arg.is_empty() => match parse_thinking_arg(arg) {
            Ok(spec) => Some(CommandResult::ThinkingChanged { spec }),
            Err(e) => Some(CommandResult::Error(e)),
        },
        "quit" | "exit" => Some(CommandResult::Quit),
        "compact" => Some(CommandResult::Compact {
            custom_instructions: if arg.is_empty() {
                None
            } else {
                Some(arg.to_string())
            },
        }),
        _ => None,
    }
}

/// Parse a `/thinking` argument into a `ThinkingSpec`.
pub fn parse_thinking_arg(arg: &str) -> Result<ThinkingSpec, String> {
    match ReasoningLevel::parse(arg) {
        Some(level) => Ok(ThinkingSpec::Named(level)),
        None => {
            if let Ok(n) = arg.trim().parse::<u32>() {
                // Custom numeric budget: bucketize to nearest named level for display.
                Ok(ThinkingSpec::Custom {
                    level: ReasoningLevel::from_legacy_budget(n),
                    budget: n,
                })
            } else {
                Err(format!(
                    "unknown thinking level: {} \
                     (use off/adaptive/low/medium/high/xhigh/max/ultra/ultracode or a number)",
                    arg
                ))
            }
        }
    }
}

/// Canonical config-file string for a thinking change.
/// Returns the exact budget digits for Custom, named string for Named.
pub fn thinking_config_value(spec: ThinkingSpec) -> String {
    spec.config_value()
}

/// `/context` (Task 12, spec §6.6 acceptance): structured metadata-only
/// report — system/tool/history counts and bytes, latest cache component
/// change and reuse estimates, writer counters. Surfaces that own the
/// conversation pass it as `history`; others get honest `unavailable`.
pub fn context_command(
    runtime: &crate::Runtime,
    history: Option<&[crate::SharedMessage]>,
) -> CommandResult {
    CommandResult::Output(format!(
        "{}\n{}",
        runtime.context_report(history).render(),
        runtime.context_management_status()
    ))
}

/// `/confirms [status] | reset` — inspect or revoke the session's extension
/// "Allow all" latch (#148 I2b). Reset clears the shared set, so running
/// subagents stop auto-approving immediately too.
pub fn confirms_command(arg: &str, runtime: &crate::Runtime) -> CommandResult {
    const USAGE: &str = "usage: /confirms [status] | /confirms reset";
    let latch = runtime.session_allow_all();
    match arg.trim() {
        "" | "status" => {
            let ids = latch.extensions();
            if ids.is_empty() {
                CommandResult::Output(
                    "No extension has \"Allow all\" this session; every extension confirm prompts."
                        .to_string(),
                )
            } else {
                CommandResult::Output(format!(
                    "\"Allow all\" is armed for: {}. Their tool-call confirms are auto-approved \
                     until /new. /confirms reset revokes.",
                    ids.join(", ")
                ))
            }
        }
        "reset" => {
            let revoked = latch.clear();
            if revoked.is_empty() {
                CommandResult::Output("Nothing to revoke: no extension had \"Allow all\".".to_string())
            } else {
                CommandResult::Output(format!(
                    "Revoked \"Allow all\" for: {}. Their confirms prompt again.",
                    revoked.join(", ")
                ))
            }
        }
        _ => CommandResult::Error(USAGE.to_string()),
    }
}

/// `/workers [status] | cancel <sa_N|all> | reconcile <sa_N|all>` — the
/// user's direct handle on reactive workers, independent of the model:
/// - `status` lists every tracked worker and whether it still holds the
///   orchestration gate (rollover, model change, completion);
/// - `cancel` stops running workers (Esc only stops the interrupted turn's
///   own workers, so this is how background workers are stopped);
/// - `reconcile` is the user's attestation for FINISHED workers the model
///   never collected — the escape hatch when they pin the session. It never
///   touches a running worker (cancel it first). No inference, no history.
pub fn workers_command(arg: &str, runtime: &mut crate::Runtime) -> CommandResult {
    use crate::runtime::subagent::{SubagentStatus, WorkerCancelScope};
    const USAGE: &str =
        "usage: /workers [status] | /workers cancel <sa_N|all> | /workers reconcile <sa_N|all>";
    let words: Vec<_> = arg.split_whitespace().collect();
    // Lock order: orchestration snapshot BEFORE the subagent registry.
    let unreconciled = runtime
        .orchestration()
        .map(|o| o.unreconciled_runtime_handles())
        .unwrap_or_default();
    match words.as_slice() {
        [] | ["status"] => {
            let registry = runtime
                .subagent_registry()
                .lock()
                .unwrap_or_else(|p| p.into_inner());
            let mut rows: Vec<(String, String)> = registry
                .handles
                .values()
                .map(|h| {
                    let status = h.status();
                    let gate = match (status == SubagentStatus::Running, unreconciled.contains(&h.id)) {
                        (true, _) => "",
                        (false, true) => "  — finished, not collected (holds rollover: collect or /workers reconcile)",
                        (false, false) => "",
                    };
                    let mins = (h.elapsed_secs() / 60.0).floor() as u64;
                    (
                        h.id.clone(),
                        format!("  {}  {}  {}  {}m{}", h.id, h.agent_name, status.as_str(), mins, gate),
                    )
                })
                .collect();
            // Reaped from the registry but never reconciled (output expired).
            for id in &unreconciled {
                if !registry.handles.contains_key(id) {
                    rows.push((
                        id.clone(),
                        format!("  {id}  (expired)  — not collected (holds rollover: /workers reconcile {id})"),
                    ));
                }
            }
            drop(registry);
            if rows.is_empty() {
                return CommandResult::Output("No workers tracked in this session.".into());
            }
            rows.sort_by(|a, b| natural_handle_order(&a.0, &b.0));
            let lines: Vec<String> = rows.into_iter().map(|(_, line)| line).collect();
            CommandResult::Output(format!("Workers ({}):\n{}", lines.len(), lines.join("\n")))
        }
        ["cancel", target] => {
            let mut registry = runtime
                .subagent_registry()
                .lock()
                .unwrap_or_else(|p| p.into_inner());
            let cancelled = if *target == "all" {
                registry.cancel_running(WorkerCancelScope::All)
            } else {
                let Some(h) = registry.get_mut(target) else {
                    return CommandResult::Error(format!("no worker {target} (see /workers)"));
                };
                // One decision with the worker's own completion (see
                // `cancel_if_running`): a worker that just finished keeps
                // its result.
                if !h.cancel_if_running() {
                    let (stopping, status) = {
                        let s = h.state.read().unwrap_or_else(|p| p.into_inner());
                        (s.cancel_requested, s.public_status())
                    };
                    return CommandResult::Error(if stopping {
                        format!("{target} is already being cancelled")
                    } else if status == SubagentStatus::Running {
                        format!("{target} is finishing — nothing to cancel")
                    } else {
                        format!("{target} is already {} — nothing to cancel", status.as_str())
                    });
                }
                vec![target.to_string()]
            };
            if cancelled.is_empty() {
                CommandResult::Output("No running workers to cancel.".into())
            } else {
                CommandResult::Output(format!(
                    "Cancelled {} (they stop at their next step; no completion wake is sent).",
                    cancelled.join(", ")
                ))
            }
        }
        ["reconcile", target] => {
            let Some(orchestration) = runtime.orchestration().cloned() else {
                return CommandResult::Output(
                    "Worker orchestration is not active; nothing to reconcile.".into(),
                );
            };
            let candidates: Vec<String> = if *target == "all" {
                let mut ids: Vec<String> = unreconciled.iter().cloned().collect();
                ids.sort_by(|a, b| natural_handle_order(a, b));
                ids
            } else if unreconciled.contains(*target) {
                vec![target.to_string()]
            } else {
                return CommandResult::Error(format!(
                    "{target} is not awaiting reconciliation (see /workers)"
                ));
            };
            let statuses: Vec<(String, Option<SubagentStatus>)> = {
                let registry = runtime
                    .subagent_registry()
                    .lock()
                    .unwrap_or_else(|p| p.into_inner());
                candidates
                    .into_iter()
                    .map(|id| {
                        let status = registry.get(&id).map(|h| h.status());
                        (id, status)
                    })
                    .collect()
            };
            let (mut done, mut running, mut failed) = (Vec::new(), Vec::new(), Vec::new());
            for (id, status) in statuses {
                let terminal = match status {
                    Some(SubagentStatus::Running) => {
                        running.push(id);
                        continue;
                    }
                    Some(SubagentStatus::Completed) => {
                        agent_core::orchestration::WorkerTerminal::Completed
                    }
                    Some(SubagentStatus::TimedOut) => {
                        agent_core::orchestration::WorkerTerminal::TimedOut
                    }
                    _ => agent_core::orchestration::WorkerTerminal::Failed,
                };
                match orchestration
                    .terminal_and_collect(&id, terminal)
                    .and_then(|()| orchestration.reconcile(&id))
                {
                    Ok(()) => done.push(id),
                    Err(e) => failed.push(format!("{id} ({e})")),
                }
            }
            let mut out = Vec::new();
            if !done.is_empty() {
                out.push(format!(
                    "Reconciled {} on your authority; their results stay readable via subagent_collect until reaped.",
                    done.join(", ")
                ));
            }
            if !running.is_empty() {
                out.push(format!(
                    "Still running, left alone: {} (/workers cancel <id> first).",
                    running.join(", ")
                ));
            }
            if !failed.is_empty() {
                out.push(format!("Could not reconcile: {}.", failed.join(", ")));
            }
            if out.is_empty() {
                out.push("Nothing awaiting reconciliation.".into());
            }
            CommandResult::Output(out.join("\n"))
        }
        _ => CommandResult::Error(USAGE.into()),
    }
}

/// `sa_9` before `sa_10`; anything unparseable falls back to string order.
fn natural_handle_order(a: &str, b: &str) -> std::cmp::Ordering {
    let num = |s: &str| s.strip_prefix("sa_").and_then(|n| n.parse::<u64>().ok());
    match (num(a), num(b)) {
        (Some(x), Some(y)) => x.cmp(&y),
        _ => a.cmp(b),
    }
}

/// Explicit operator control of future turns. No config writes, inference,
/// history mutation, or changes to an already-running stream's budget snapshot.
/// This is a frontend slash command, never a model-callable budget renewal.
pub fn budget_command(arg: &str, runtime: &mut crate::Runtime) -> CommandResult {
    const USAGE: &str = "usage: /budget [status] | /budget time <duration> (positive whole seconds/minutes/hours, e.g. 30m or 4h; maximum 24h) | /budget time off";
    let words: Vec<_> = arg.split_whitespace().collect();
    match words.as_slice() {
        [] | ["status"] => {
            let budget = runtime.turn_budget();
            CommandResult::Output(format!(
                "Turn budget (configured for future turns, not live usage):\n\
                 wall-clock: {}; provider rounds: {} (+{} bounded renewals); tool calls: {}; tool-result bytes: {}\n\
                 context tokens: {}; cost USD: {}\n\
                 Committed context rollovers reset only elapsed time; other limits remain cumulative. /budget time 4h (or off) changes only the next-turn time allowance in this runtime; it is not saved to config or session storage.",
                budget
                    .max_elapsed_secs()
                    .map_or_else(|| "off".into(), |s| format!("{s}s")),
                budget.max_provider_rounds.map_or_else(|| "off".into(), |v| v.to_string()),
                budget.max_round_renewals,
                budget.max_tool_calls.map_or_else(|| "off".into(), |v| v.to_string()),
                budget
                    .max_accumulated_tool_result_bytes
                    .map_or_else(|| "off".into(), |v| v.to_string()),
                budget.max_context_tokens.map_or_else(|| "unset".into(), |v| v.to_string()),
                budget.max_cost_usd.map_or_else(|| "unset".into(), |v| v.to_string()),
            ))
        }
        ["time", "off"] => {
            let mut budget = runtime.turn_budget().clone();
            budget.max_elapsed = None;
            runtime.set_turn_budget(budget);
            CommandResult::Output(
                "Turn wall-clock limit removed for future turns in this runtime only (not saved). Running turns, worker budgets and all other limits are unchanged.".into(),
            )
        }
        ["time", duration] => {
            let Some(seconds) = parse_turn_duration(duration) else {
                return CommandResult::Error(USAGE.into());
            };
            let mut budget = runtime.turn_budget().clone();
            budget.max_elapsed = Some(std::time::Duration::from_secs(seconds));
            runtime.set_turn_budget(budget);
            CommandResult::Output(format!(
                "Turn wall-clock limit set to {seconds}s for future turns in this runtime only (not saved). Running turns, worker budgets and all other limits are unchanged. Send a prompt to continue retained history; this command does not start a turn."
            ))
        }
        _ => CommandResult::Error(USAGE.into()),
    }
}

fn parse_turn_duration(value: &str) -> Option<u64> {
    let (digits, multiplier) = if let Some(digits) = value.strip_suffix('s') {
        (digits, 1)
    } else if let Some(digits) = value.strip_suffix('m') {
        (digits, 60)
    } else if let Some(digits) = value.strip_suffix('h') {
        (digits, 3600)
    } else {
        return None;
    };
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let seconds = digits.parse::<u64>().ok()?.checked_mul(multiplier)?;
    (1..=86_400).contains(&seconds).then_some(seconds)
}

/// `/trace next|next content|status` (Task 12): explicit trace controls.
pub fn trace_command(arg: &str, runtime: &crate::Runtime) -> CommandResult {
    match arg.trim() {
        "next" => {
            runtime.trace_arm_next(false);
            CommandResult::Output(
                "trace armed for the next request (metadata only, then auto-disabled)".to_string(),
            )
        }
        "next content" => {
            runtime.trace_arm_next(true);
            CommandResult::Output(
                "trace armed for the next request WITH redacted content capture.\n\
                 The request body (never headers/credentials) is recursively \
                 redacted and kept in a private, short-lived capture bundle; \
                 export it with `synaps trace export <request-id> \
                 --include-content --allow-content-export --output PATH` \
                 before it expires."
                    .to_string(),
            )
        }
        "" | "status" => CommandResult::Output(runtime.trace_status().render()),
        other => CommandResult::Error(format!(
            "unknown /trace subcommand: `{other}` (try: next, next content, status)"
        )),
    }
}

/// `/memory on|recall|capture|once|status|off|index-history|why` (task A5,
/// spec §7.3): the ONE deterministic engine entry point every frontend —
/// TUI, headless chat, RPC, server, watcher, agent — shares via
/// [`handle_engine_command`]. Frontends must not duplicate lease or budget
/// logic.
///
/// Every enabling arm mints host-owned
/// [`crate::runtime::memory_context::UserIntentProof::ExplicitCommand`]
/// proof right here: a deterministic slash command is authoritative (spec
/// assumption 5), and proof never derives from model text.
pub fn memory_command(arg: &str, runtime: &crate::Runtime) -> CommandResult {
    use crate::runtime::memory_context::{mint_explicit_command_proof, MemoryContextMode};
    let enable = |mode: MemoryContextMode| match runtime
        .memory_context_enable(mode, mint_explicit_command_proof())
    {
        Ok(status) => CommandResult::Output(status.render()),
        Err(e) => CommandResult::Error(e.to_string()),
    };
    match arg.trim() {
        "on" => enable(MemoryContextMode::CaptureAndRecall),
        "recall" => enable(MemoryContextMode::RecallEachPrompt),
        "capture" => enable(MemoryContextMode::CaptureOnly),
        "once" => match runtime.memory_context_recall_once(mint_explicit_command_proof()) {
            Ok(status) => CommandResult::Output(status.render()),
            Err(e) => CommandResult::Error(e.to_string()),
        },
        "" | "status" => CommandResult::Output(runtime.memory_context_status().render()),
        // Disable is applied to session state BEFORE this returns: `render`
        // runs on the post-revocation status snapshot.
        "off" => CommandResult::Output(runtime.memory_context_disable().render()),
        "index-history" => match runtime.memory_history_preview() {
            Ok(preview) => CommandResult::Output(preview.render()),
            Err(error) => CommandResult::Error(error.to_string()),
        },
        "index-history confirm" => match runtime.memory_history_confirm() {
            Ok(report) => CommandResult::Output(format!(
                "History import complete: {} session(s) loaded, {} bounded capture record(s) submitted in {} batch(es).",
                report.sessions_loaded, report.captures_built, report.batches_submitted,
            )),
            Err(error) => CommandResult::Error(error.to_string()),
        },
        "index-history decline" => {
            if runtime.memory_history_decline() {
                CommandResult::Output(
                    "History import declined; no session content was read and no Axel data was written."
                        .to_string(),
                )
            } else {
                CommandResult::Error(
                    "history import requires a pending disclosure preview before decline"
                        .to_string(),
                )
            }
        }
        "why" => CommandResult::Output(crate::runtime::memory_context::render_recall_why(
            runtime.memory_recall_why().as_ref(),
        )),
        other => CommandResult::Error(format!(
            "unknown /memory subcommand: `{other}` \
             (try: on, recall, capture, once, status, off, index-history, why)"
        )),
    }
}

/// Persist a config key and return a user-visible status suffix.
pub fn persist_to_config(key: &str, value: &str) -> String {
    match crate::config::write_config_value(key, value) {
        Ok(()) => "(saved to config)".to_string(),
        Err(e) => format!("(session only — failed to persist: {})", e),
    }
}

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

    #[test]
    fn model_command_carries_model_name() {
        match evaluate_engine_command("model", "claude-sonnet-4-6") {
            Some(CommandResult::ModelChanged { model, .. }) => {
                assert_eq!(model, "claude-sonnet-4-6")
            }
            other => panic!("expected ModelChanged, got {:?}", other),
        }
        assert!(matches!(
            evaluate_engine_command("models", "claude-opus-4-6"),
            Some(CommandResult::ModelChanged { .. })
        ));
        assert!(evaluate_engine_command("model", "").is_none());
    }

    #[test]
    fn thinking_command_normalizes_levels() {
        match evaluate_engine_command("thinking", "high") {
            Some(CommandResult::ThinkingChanged { spec }) => {
                assert_eq!(spec.level(), ReasoningLevel::High);
                assert_eq!(spec.budget(), Some(16384));
                assert!(matches!(spec, ThinkingSpec::Named(ReasoningLevel::High)));
            }
            other => panic!("expected ThinkingChanged, got {:?}", other),
        }
        let med = parse_thinking_arg("med").unwrap();
        assert_eq!(med.level(), ReasoningLevel::Medium);
        assert_eq!(med.budget(), Some(4096));

        // Custom numeric: produces ThinkingSpec::Custom, not Named.
        let custom = parse_thinking_arg("8192").unwrap();
        assert!(
            matches!(
                custom,
                ThinkingSpec::Custom {
                    level: ReasoningLevel::High,
                    budget: 8192
                }
            ),
            "expected Custom{{High, 8192}}, got {:?}",
            custom
        );
        assert_eq!(custom.budget(), Some(8192));

        assert!(parse_thinking_arg("bogus").is_err());
        assert!(evaluate_engine_command("thinking", "").is_none());
    }

    #[test]
    fn thinking_command_off_and_adaptive_are_distinct() {
        let off = parse_thinking_arg("off").unwrap();
        let adp = parse_thinking_arg("adaptive").unwrap();
        assert_eq!(off.level(), ReasoningLevel::Off);
        assert_eq!(off.budget(), Some(0));
        assert_eq!(adp.level(), ReasoningLevel::Adaptive);
        assert_eq!(adp.budget(), Some(0));
        assert_ne!(off.level(), adp.level());
    }

    #[test]
    fn max_and_ultra_have_no_budget() {
        let max_spec = parse_thinking_arg("max").unwrap();
        assert_eq!(max_spec.level(), ReasoningLevel::Max);
        assert_eq!(max_spec.budget(), None, "max has no numeric budget");

        let ultra_spec = parse_thinking_arg("ultra").unwrap();
        assert_eq!(ultra_spec.level(), ReasoningLevel::Ultra);
        assert_eq!(ultra_spec.budget(), None, "ultra has no numeric budget");

        // xhigh still has a numeric budget
        let xhigh_spec = parse_thinking_arg("xhigh").unwrap();
        assert_eq!(xhigh_spec.level(), ReasoningLevel::XHigh);
        assert_eq!(xhigh_spec.budget(), Some(32768));
    }

    #[test]
    fn thinking_config_value_is_named_for_named_levels() {
        assert_eq!(
            thinking_config_value(ThinkingSpec::Named(ReasoningLevel::Off)),
            "off"
        );
        assert_eq!(
            thinking_config_value(ThinkingSpec::Named(ReasoningLevel::Adaptive)),
            "adaptive"
        );
        assert_eq!(
            thinking_config_value(ThinkingSpec::Named(ReasoningLevel::Low)),
            "low"
        );
        assert_eq!(
            thinking_config_value(ThinkingSpec::Named(ReasoningLevel::Medium)),
            "medium"
        );
        assert_eq!(
            thinking_config_value(ThinkingSpec::Named(ReasoningLevel::High)),
            "high"
        );
        assert_eq!(
            thinking_config_value(ThinkingSpec::Named(ReasoningLevel::XHigh)),
            "xhigh"
        );
        assert_eq!(
            thinking_config_value(ThinkingSpec::Named(ReasoningLevel::Max)),
            "max"
        );
        assert_eq!(
            thinking_config_value(ThinkingSpec::Named(ReasoningLevel::Ultra)),
            "ultra"
        );
        assert_eq!(
            thinking_config_value(ThinkingSpec::Named(ReasoningLevel::UltraCode)),
            "ultracode"
        );
    }

    #[test]
    fn thinking_config_value_is_exact_digits_for_custom_budget() {
        // B3: /thinking 8192 must persist "8192", not the named level "high".
        let spec = ThinkingSpec::Custom {
            level: ReasoningLevel::High,
            budget: 8192,
        };
        assert_eq!(thinking_config_value(spec), "8192");
        let spec2 = ThinkingSpec::Custom {
            level: ReasoningLevel::Medium,
            budget: 3000,
        };
        assert_eq!(thinking_config_value(spec2), "3000");
    }

    #[test]
    fn compact_carries_custom_instructions() {
        match evaluate_engine_command("compact", "focus on auth") {
            Some(CommandResult::Compact {
                custom_instructions,
            }) => {
                assert_eq!(custom_instructions.as_deref(), Some("focus on auth"));
            }
            other => panic!("expected Compact, got {:?}", other),
        }
        assert!(matches!(
            evaluate_engine_command("compact", ""),
            Some(CommandResult::Compact {
                custom_instructions: None
            })
        ));
    }

    #[test]
    #[serial_test::serial(synaps_base_dir)]
    fn persist_to_config_reports_write_result() {
        // The config lives under the base directory, which tests pin with
        // the guard (an ambient SYNAPS_BASE_DIR wins over HOME).
        let base = crate::test_env::BaseDirGuard::new();

        let status = persist_to_config("model", "claude-sonnet-4-6");

        assert_eq!(status, "(saved to config)");
        let path = agent_core::config::resolve_read_path("config");
        assert!(path.starts_with(base.path()), "written outside the base dir: {path:?}");
        let contents = std::fs::read_to_string(&path).unwrap();
        assert!(contents.contains("model = claude-sonnet-4-6"));
    }

    #[test]
    fn validate_level_codex_sol_accepts_ultra() {
        let mut rt = crate::Runtime::new_headless();
        rt.set_model("openai-codex/gpt-5.6-sol".to_string());
        assert!(rt
            .set_reasoning_level_checked(ReasoningLevel::Ultra)
            .is_ok());
    }

    #[test]
    fn validate_level_codex_luna_rejects_ultra_leaves_state_unchanged() {
        let mut rt = crate::Runtime::new_headless();
        rt.set_model("openai-codex/gpt-5.6-luna".to_string());
        rt.set_reasoning_level(ReasoningLevel::Low);
        let err = rt
            .set_reasoning_level_checked(ReasoningLevel::Ultra)
            .unwrap_err();
        assert!(err.contains("ultra"));
        assert!(err.contains("gpt-5.6-luna"));
        // State must be unchanged after rejection.
        assert_eq!(rt.reasoning_level(), ReasoningLevel::Low);
    }

    #[test]
    fn validate_level_non_codex_rejects_ultra() {
        for model in [
            "claude-sonnet-4-6",
            "anthropic/claude-opus-4-7",
            "groq/llama-3",
        ] {
            let mut rt = crate::Runtime::new_headless();
            rt.set_model(model.to_string());
            assert!(
                rt.set_reasoning_level_checked(ReasoningLevel::Ultra)
                    .is_err(),
                "non-Codex {model} must not gain ultra without exact metadata"
            );
        }
    }

    // B3: provenance tests -------------------------------------------------------

    #[test]
    fn set_reasoning_level_is_not_explicit() {
        // set_reasoning_level (config/restore path) must NOT set explicit flag.
        let mut rt = crate::Runtime::new_headless();
        rt.set_reasoning_level(ReasoningLevel::High);
        assert!(
            !rt.is_reasoning_explicit(),
            "set_reasoning_level must not mark explicit"
        );
    }

    #[test]
    fn set_reasoning_level_explicit_marks_flag() {
        let mut rt = crate::Runtime::new_headless();
        rt.set_reasoning_level_explicit(ReasoningLevel::High);
        assert!(
            rt.is_reasoning_explicit(),
            "set_reasoning_level_explicit must mark explicit"
        );
    }

    #[test]
    fn set_model_overwrites_non_explicit_codex_default() {
        // No explicit choice → set_model applies model's default.
        let mut rt = crate::Runtime::new_headless();
        rt.set_model("openai-codex/gpt-5.6-luna".to_string());
        // luna default is Medium per static table
        assert_eq!(rt.reasoning_level(), ReasoningLevel::Medium);
        assert!(!rt.is_reasoning_explicit());
    }

    #[test]
    fn set_model_preserves_explicit_user_choice() {
        // Explicit user choice survives model switch.
        let mut rt = crate::Runtime::new_headless();
        rt.set_reasoning_level_explicit(ReasoningLevel::Low);
        rt.set_model("openai-codex/gpt-5.6-sol".to_string());
        // sol default is Low anyway, but let's use a level that differs from default
        assert!(
            rt.is_reasoning_explicit(),
            "explicit flag must survive set_model"
        );
    }

    #[test]
    fn apply_config_thinking_sets_explicit() {
        // Config-specified thinking level is explicit — preserved across model switch.
        use crate::config::SynapsConfig;
        let mut rt = crate::Runtime::new_headless();
        let config = SynapsConfig {
            thinking_level: Some(ReasoningLevel::XHigh),
            ..Default::default()
        };
        rt.apply_config(&config);
        assert!(
            rt.is_reasoning_explicit(),
            "config thinking must be explicit"
        );
        assert_eq!(rt.reasoning_level(), ReasoningLevel::XHigh);
        // Model switch must not overwrite the explicit config level.
        rt.set_model("openai-codex/gpt-5.6-luna".to_string());
        assert_eq!(
            rt.reasoning_level(),
            ReasoningLevel::XHigh,
            "explicit config level must survive set_model"
        );
    }

    #[test]
    fn set_thinking_budget_explicit_retains_exact_budget_and_marks_flag() {
        // B3: /thinking 8192 → set_thinking_budget_explicit(8192) must retain 8192.
        let mut rt = crate::Runtime::new_headless();
        rt.set_thinking_budget_explicit(8192);
        assert_eq!(
            rt.thinking_budget_raw(),
            8192,
            "exact budget must be retained"
        );
        assert!(rt.is_reasoning_explicit());
        // Named level for display is High (4097..=16384 range).
        assert_eq!(rt.reasoning_level(), ReasoningLevel::High);
    }

    // ── Numeric `/thinking <N>` mutation-time validation (review corrective) ──

    #[test]
    fn custom_budget_rejected_on_xai_intrinsic_reasoning_leaves_state_unchanged() {
        // /thinking 8192 derives High; grok-4.3 has no effort control → reject
        // immediately, no mutation, no silent downgrade.
        let mut rt = crate::Runtime::new_headless();
        rt.set_model("xai-auth/grok-4.3".to_string());
        let before_budget = rt.thinking_budget_raw();
        let before_level = rt.reasoning_level();
        let before_explicit = rt.is_reasoning_explicit();
        match handle_engine_command("thinking", "8192", &mut rt) {
            Some(CommandResult::Error(msg)) => {
                assert!(
                    msg.contains("xai-auth/grok-4.3"),
                    "message names model: {msg}"
                )
            }
            other => panic!("expected Error, got {:?}", other),
        }
        assert_eq!(
            rt.thinking_budget_raw(),
            before_budget,
            "budget must be unchanged"
        );
        assert_eq!(
            rt.reasoning_level(),
            before_level,
            "level must be unchanged"
        );
        assert_eq!(
            rt.is_reasoning_explicit(),
            before_explicit,
            "provenance unchanged"
        );
    }

    #[test]
    fn custom_budget_rejected_on_xai_non_reasoning_model() {
        let mut rt = crate::Runtime::new_headless();
        rt.set_model("xai-auth/grok-4.20-0309-non-reasoning".to_string());
        let before_budget = rt.thinking_budget_raw();
        match handle_engine_command("thinking", "8192", &mut rt) {
            Some(CommandResult::Error(msg)) => {
                assert!(msg.contains("non-reasoning"), "{msg}")
            }
            other => panic!("expected Error, got {:?}", other),
        }
        assert_eq!(
            rt.thinking_budget_raw(),
            before_budget,
            "state must be unchanged"
        );
    }

    #[test]
    fn custom_budget_maps_to_high_and_is_accepted_on_xai_45() {
        // 8192 → High, which grok-4.5 supports exactly → accepted.
        let mut rt = crate::Runtime::new_headless();
        rt.set_model("xai-auth/grok-4.5".to_string());
        match handle_engine_command("thinking", "8192", &mut rt) {
            Some(CommandResult::ThinkingChanged { spec }) => {
                assert_eq!(spec.level(), ReasoningLevel::High);
                assert_eq!(spec.budget(), Some(8192));
            }
            other => panic!("expected ThinkingChanged, got {:?}", other),
        }
        assert_eq!(rt.reasoning_level(), ReasoningLevel::High);
        assert!(rt.is_reasoning_explicit());
    }

    /// `/model` onto a model that rejects the explicit level reports the clamp
    /// so surfaces can tell the user, and leaves the runtime in a usable state.
    #[test]
    fn model_command_reports_reasoning_clamp_for_unsupported_explicit_level() {
        let mut rt = crate::Runtime::new_headless();
        handle_engine_command("thinking", "xhigh", &mut rt).expect("thinking applies");
        assert_eq!(rt.reasoning_level(), ReasoningLevel::XHigh);
        match handle_engine_command("model", "xai-auth/grok-4.6", &mut rt) {
            Some(CommandResult::ModelChanged {
                model,
                reasoning_clamped,
            }) => {
                assert_eq!(model, "xai-auth/grok-4.6");
                assert_eq!(
                    reasoning_clamped,
                    Some(crate::runtime::ReasoningClamp {
                        from: ReasoningLevel::XHigh,
                        to: ReasoningLevel::High,
                    })
                );
            }
            other => panic!("expected ModelChanged, got {:?}", other),
        }
        assert_eq!(rt.reasoning_level(), ReasoningLevel::High);
        assert!(rt.is_reasoning_explicit());
        // Supported explicit level: no clamp reported.
        match handle_engine_command("model", "xai-auth/grok-4.5", &mut rt) {
            Some(CommandResult::ModelChanged {
                reasoning_clamped, ..
            }) => assert_eq!(reasoning_clamped, None),
            other => panic!("expected ModelChanged, got {:?}", other),
        }
    }

    #[test]
    fn custom_budget_preserved_exactly_on_anthropic_fixed_budget_model() {
        // Anthropic compatibility: numeric budgets stay exact (never bucketized
        // away) and are accepted on fixed-budget thinking models.
        let mut rt = crate::Runtime::new_headless();
        rt.set_model("claude-sonnet-4-6".to_string());
        match handle_engine_command("thinking", "8192", &mut rt) {
            Some(CommandResult::ThinkingChanged { spec }) => {
                assert_eq!(spec.config_value(), "8192", "persists exact digits");
            }
            other => panic!("expected ThinkingChanged, got {:?}", other),
        }
        assert_eq!(
            rt.thinking_budget_raw(),
            8192,
            "exact budget must be retained"
        );
        assert!(rt.is_reasoning_explicit());
    }

    #[test]
    fn custom_budget_config_value_is_digits_not_named() {
        // B3: ThinkingSpec::Custom config_value() must be the digit string.
        let spec = parse_thinking_arg("8192").unwrap();
        assert_eq!(
            spec.config_value(),
            "8192",
            "custom budget must persist as digits, not named level"
        );
    }

    // ── Task 12: /trace and /context surfaces ──

    #[test]
    fn trace_next_enables_exactly_the_next_request_then_auto_disables() {
        let runtime = crate::Runtime::new_headless();
        // Telemetry off: the base session context is disabled.
        assert!(!runtime.trace_context().enabled());

        match trace_command("next", &runtime) {
            CommandResult::Output(text) => assert!(text.contains("next request")),
            other => panic!("expected Output, got {other:?}"),
        }
        let status = runtime.trace_status();
        assert!(!status.persistent_enabled);
        assert_eq!(status.arm, crate::runtime::trace::TraceArm::NextMetadata);

        // Exactly one effective context is enabled, even with telemetry Off…
        let armed = runtime.effective_trace_context();
        assert!(armed.enabled(), "armed context must trace the next request");
        // …then the arm auto-disables: the following request is untraced.
        let after = runtime.effective_trace_context();
        assert!(!after.enabled(), "arm must cover exactly one request");
        assert_eq!(
            runtime.trace_status().arm,
            crate::runtime::trace::TraceArm::Off
        );
    }

    #[test]
    fn trace_status_reports_mode_path_and_counters_without_secrets() {
        let runtime = crate::Runtime::new_headless();
        match trace_command("status", &runtime) {
            CommandResult::Output(text) => {
                assert!(text.contains("trace: disabled"), "got: {text}");
                assert!(text.contains("degraded"));
            }
            other => panic!("expected Output, got {other:?}"),
        }
        runtime.trace_arm_next(true);
        match trace_command("", &runtime) {
            CommandResult::Output(text) => {
                assert!(text.contains("armed for next request"), "got: {text}");
                assert!(text.contains("content capture"));
            }
            other => panic!("expected Output, got {other:?}"),
        }
        assert!(matches!(
            trace_command("bogus", &runtime),
            CommandResult::Error(_)
        ));
    }

    #[test]
    fn context_command_reports_metadata_never_content() {
        let mut runtime = crate::Runtime::new_headless();
        let secret = "CONTEXT-SENTINEL-5a5a";
        runtime.set_system_prompt(format!("you are {secret}"));
        let history = vec![std::sync::Arc::new(serde_json::json!({
            "role": "user", "content": secret
        }))];
        match context_command(&runtime, Some(&history)) {
            CommandResult::Output(text) => {
                assert!(!text.contains(secret), "sentinel leaked: {text}");
                assert!(text.contains("history: 1 messages"));
                assert!(text.contains("system prompt:"));
                assert!(text.contains("skills: unavailable"));
            }
            other => panic!("expected Output, got {other:?}"),
        }
        // The engine-shared path (no history) reports honestly.
        match handle_engine_command("context", "", &mut runtime) {
            Some(CommandResult::Output(text)) => {
                assert!(
                    text.contains("history: unavailable messages"),
                    "got: {text}"
                );
            }
            other => panic!("expected Output, got {other:?}"),
        }
    }

    #[test]
    fn budget_duration_parser_is_strict_and_bounded() {
        for (input, seconds) in [
            ("1s", 1),
            ("30m", 1800),
            ("4h", 14400),
            ("24h", 86400),
            ("1440m", 86400),
            ("86400s", 86400),
        ] {
            assert_eq!(parse_turn_duration(input), Some(seconds), "{input}");
        }
        for input in [
            "",
            "s",
            "0s",
            "0h",
            "25h",
            "86401s",
            "1441m",
            "4",
            "4H",
            "-1h",
            "+1h",
            "1.5h",
            "1h30m",
            " 4h",
            "4 h",
            "4h ",
            "1e3s",
            "∞h",
            "12h",
            "18446744073709551615h",
            "18446744073709551616s",
            "off",
            "unlimited",
        ] {
            assert_eq!(parse_turn_duration(input), None, "{input}");
        }
    }

    // ── /workers ────────────────────────────────────────────────────────────

    fn worker_handle(
        id: &str,
        status: crate::runtime::subagent::SubagentStatus,
    ) -> crate::runtime::subagent::SubagentHandle {
        let state = std::sync::Arc::new(std::sync::RwLock::new(
            crate::runtime::subagent::SubagentState::new(),
        ));
        state.write().unwrap().status = status;
        crate::runtime::subagent::SubagentHandle::new(
            id.into(),
            id.trim_start_matches("sa_").parse().unwrap_or(0),
            "spike".into(),
            "task".into(),
            "claude-sonnet-4-6".into(),
            "system".into(),
            60,
            state,
            None,
            None,
            None,
        )
    }

    fn runtime_with_workers() -> (
        crate::Runtime,
        std::sync::Arc<crate::orchestration::OrchestrationRuntime>,
    ) {
        use crate::runtime::subagent::SubagentStatus;
        let mut runtime = crate::Runtime::new_headless();
        let model = agent_core::prompt::QualifiedModelId::parse("openrouter/z-ai/glm-5.2").unwrap();
        let orchestration = std::sync::Arc::new(
            crate::orchestration::OrchestrationRuntime::baseline(model, 3, 8).unwrap(),
        );
        for id in ["sa_9", "sa_10"] {
            orchestration.resolve_and_authorize(id, None).unwrap();
            orchestration.mark_starting(id).unwrap();
            orchestration.mark_running(id).unwrap();
        }
        runtime.install_orchestration(orchestration.clone());
        {
            let mut registry = runtime.subagent_registry().lock().unwrap();
            registry.register(worker_handle("sa_9", SubagentStatus::Running));
            registry.register(worker_handle("sa_10", SubagentStatus::Completed));
        }
        (runtime, orchestration)
    }

    fn command_text(result: Option<CommandResult>) -> String {
        match result {
            Some(CommandResult::Output(text)) | Some(CommandResult::Error(text)) => text,
            other => panic!("unexpected {other:?}"),
        }
    }

    /// #148 I2b: `/confirms` shows which extensions are latched and
    /// `/confirms reset` revokes them — for workers sharing the set too.
    #[test]
    fn confirms_lists_and_reset_revokes_the_allow_all_latch() {
        let mut runtime = crate::Runtime::new_headless();
        let worker = runtime.clone();
        let text = command_text(handle_engine_command("confirms", "", &mut runtime));
        assert!(text.contains("No extension"), "{text}");

        worker
            .session_allow_all()
            .allow(&[("jev".to_string(), 0), ("audit".to_string(), 0)]);
        let text = command_text(handle_engine_command("confirms", "status", &mut runtime));
        assert!(text.contains("jev") && text.contains("audit"), "{text}");

        let text = command_text(handle_engine_command("confirms", "reset", &mut runtime));
        assert!(text.contains("Revoked") && text.contains("jev"), "{text}");
        assert!(worker.session_allow_all().is_empty(), "shared with workers");
        let text = command_text(handle_engine_command("confirms", "reset", &mut runtime));
        assert!(text.contains("Nothing to revoke"), "{text}");

        assert!(matches!(
            handle_engine_command("confirms", "explode", &mut runtime),
            Some(CommandResult::Error(e)) if e.contains("usage: /confirms")
        ));
        assert!(crate::skills::BUILTIN_COMMANDS.contains(&"confirms"));
    }

    #[test]
    fn workers_status_lists_workers_and_flags_uncollected_ones() {
        let (mut runtime, _) = runtime_with_workers();
        let text = command_text(handle_engine_command("workers", "", &mut runtime));
        let sa9 = text.find("sa_9").expect(&text);
        let sa10 = text.find("sa_10").expect(&text);
        assert!(sa9 < sa10, "natural handle order: {text}");
        let line10 = text.lines().find(|l| l.contains("sa_10")).unwrap();
        assert!(
            line10.contains("completed") && line10.contains("holds rollover"),
            "{line10}"
        );
        let line9 = text.lines().find(|l| l.contains("sa_9")).unwrap();
        assert!(
            line9.contains("running") && !line9.contains("holds rollover"),
            "{line9}"
        );
        assert!(crate::skills::BUILTIN_COMMANDS.contains(&"workers"));
    }

    #[test]
    fn workers_reconcile_releases_finished_workers_and_never_running_ones() {
        let (mut runtime, orchestration) = runtime_with_workers();
        let text = command_text(handle_engine_command(
            "workers",
            "reconcile all",
            &mut runtime,
        ));
        assert!(text.contains("Reconciled sa_10"), "{text}");
        assert!(text.contains("Still running, left alone: sa_9"), "{text}");
        assert!(!orchestration.is_unreconciled("sa_10"));
        assert!(orchestration.is_unreconciled("sa_9"));
        // A handle that is not awaiting reconciliation is refused.
        let Some(CommandResult::Error(e)) =
            handle_engine_command("workers", "reconcile sa_10", &mut runtime)
        else {
            panic!("already reconciled must be refused")
        };
        assert!(e.contains("not awaiting"), "{e}");
    }

    /// `/workers cancel sa_N` racing the worker's own completion: the
    /// status check and the cancel are one decision, so a worker that
    /// completed in between keeps its result (and the user is told it
    /// already finished) instead of being relabelled Cancelled.
    #[test]
    fn workers_cancel_never_relabels_a_worker_that_completed_meanwhile() {
        use crate::runtime::subagent::SubagentStatus;
        let mut runtime = crate::Runtime::new_headless();
        for round in 0..20_000 {
            let h = worker_handle("sa_1", SubagentStatus::Running);
            let state = std::sync::Arc::clone(&h.state);
            {
                let mut registry = runtime.subagent_registry().lock().unwrap();
                registry.remove("sa_1");
                registry.register(h);
            }
            let go = std::sync::Arc::new(std::sync::Barrier::new(2));
            let worker = {
                let (go, state) = (go.clone(), state.clone());
                // Sweep where the completion lands relative to the command.
                let spin = round % 4_000;
                std::thread::spawn(move || {
                    go.wait();
                    for _ in 0..spin {
                        std::hint::spin_loop();
                    }
                    let mut s = state.write().unwrap();
                    if matches!(s.status, SubagentStatus::Running) && !s.cancel_requested {
                        s.status = SubagentStatus::Completed;
                    }
                })
            };
            go.wait();
            let reply = handle_engine_command("workers", "cancel sa_1", &mut runtime);
            worker.join().unwrap();
            let s = state.read().unwrap();
            assert!(
                !(s.status == SubagentStatus::Completed && s.cancel_requested),
                "round {round}: completed AND flagged cancelled"
            );
            match reply {
                Some(CommandResult::Output(text)) => {
                    assert!(s.cancel_requested && text.contains("Cancelled sa_1"), "{text}")
                }
                Some(CommandResult::Error(e)) => {
                    assert!(!s.cancel_requested && e.contains("already completed"), "{e}")
                }
                _ => panic!("round {round}: unexpected reply"),
            }
        }
    }

    #[test]
    fn workers_cancel_targets_running_workers_only() {
        let (mut runtime, _) = runtime_with_workers();
        let Some(CommandResult::Error(e)) =
            handle_engine_command("workers", "cancel sa_10", &mut runtime)
        else {
            panic!("finished worker cannot be cancelled")
        };
        assert!(e.contains("already completed"), "{e}");
        let text = command_text(handle_engine_command("workers", "cancel all", &mut runtime));
        assert!(text.contains("Cancelled sa_9"), "{text}");
        let registry = runtime.subagent_registry().lock().unwrap();
        assert!(
            registry
                .get("sa_9")
                .unwrap()
                .state
                .read()
                .unwrap()
                .cancel_requested
        );
        drop(registry);
        let Some(CommandResult::Error(usage)) =
            handle_engine_command("workers", "explode", &mut runtime)
        else {
            panic!("usage")
        };
        assert!(usage.starts_with("usage: /workers"));
    }

    #[test]
    fn budget_command_status_and_invalid_arguments_do_not_mutate() {
        let mut runtime = crate::Runtime::new_headless();
        let original = runtime.turn_budget().clone();
        for arg in ["", "status", "  status  "] {
            let Some(CommandResult::Output(text)) =
                handle_engine_command("budget", arg, &mut runtime)
            else {
                panic!("{arg}");
            };
            assert!(text.contains("wall-clock: off;"));
            assert!(text.contains("not live usage"));
            assert!(text.contains("provider rounds: off (+8 bounded renewals)"));
            assert!(text.contains("tool calls: off;"));
            assert!(text.contains("tool-result bytes: off\n"));
            assert_eq!(runtime.turn_budget(), &original);
        }
        for arg in [
            "time",
            "time 0s",
            "time 25h",
            "time 1h trailing",
            "status 4h",
            "time off now",
            "off",
            "reset",
        ] {
            assert!(
                matches!(
                    handle_engine_command("budget", arg, &mut runtime),
                    Some(CommandResult::Error(_))
                ),
                "{arg}"
            );
            assert_eq!(runtime.turn_budget(), &original);
        }
    }

    #[test]
    fn budget_command_changes_only_future_runtime_time_limit() {
        use crate::runtime::budget::{TurnBudget, TurnBudgetMeter, TurnRole};
        let mut runtime = crate::Runtime::new_headless();
        let original = TurnBudget {
            max_elapsed: Some(std::time::Duration::ZERO),
            max_tool_calls: Some(11),
            max_context_tokens: Some(456),
            max_cost_usd: Some(0.75),
            ..TurnBudget::for_role(TurnRole::Foreground)
        };
        runtime.set_turn_budget(original.clone());
        let mut in_flight = TurnBudgetMeter::new(runtime.turn_budget().clone());
        let other_runtime = runtime.clone();
        let Some(CommandResult::Output(text)) =
            handle_engine_command("budget", "time 4h", &mut runtime)
        else {
            panic!("expected output");
        };
        assert!(text.contains("14400s"));
        assert!(text.contains("not saved"));
        let mut expected = original.clone();
        expected.max_elapsed = Some(std::time::Duration::from_secs(14400));
        assert_eq!(runtime.turn_budget(), &expected);
        assert_eq!(other_runtime.turn_budget(), &original);
        assert_eq!(
            in_flight.begin_round(),
            Err(agent_core::BudgetDimension::WallClock)
        );
        assert!(TurnBudgetMeter::new(runtime.turn_budget().clone())
            .begin_round()
            .is_ok());
        let Some(CommandResult::Output(text)) =
            handle_engine_command("budget", "time off", &mut runtime)
        else {
            panic!("expected output");
        };
        assert!(text.contains("removed"));
        expected.max_elapsed = None;
        assert_eq!(runtime.turn_budget(), &expected);
        // No role has a time limit by default.
        assert_eq!(
            crate::Runtime::new_headless().turn_budget().max_elapsed,
            None
        );
        for role in [TurnRole::Foreground, TurnRole::Worker, TurnRole::Autonomous] {
            assert_eq!(TurnBudget::for_role(role).max_elapsed, None);
        }
        assert!(crate::skills::BUILTIN_COMMANDS.contains(&"budget"));
    }

    // ── /memory (task A5, spec §7.3) ────────────────────────────────────────

    use crate::runtime::memory_context::{
        DurableStatus, MemoryContextMode, OneShotStatus, UserIntentProof,
    };

    fn output_text(result: CommandResult) -> String {
        match result {
            CommandResult::Output(text) => text,
            other => panic!("expected Output, got {other:?}"),
        }
    }

    /// Spec §7.3: every enabling arg form transitions the session state to
    /// its exact mode — `on` → CaptureAndRecall, `recall` →
    /// RecallEachPrompt, `capture` → CaptureOnly.
    #[test]
    fn memory_enable_args_transition_to_exact_modes() {
        for (arg, mode) in [
            ("on", MemoryContextMode::CaptureAndRecall),
            ("recall", MemoryContextMode::RecallEachPrompt),
            ("capture", MemoryContextMode::CaptureOnly),
        ] {
            let runtime = crate::Runtime::new_headless();
            let text = output_text(memory_command(arg, &runtime));
            assert!(
                text.contains(&format!("mode {}", mode.as_str())),
                "/memory {arg} output must name the mode; got: {text}"
            );
            match runtime.memory_context_status().durable {
                DurableStatus::Active { mode: active, .. } => {
                    assert_eq!(active, mode, "/memory {arg} must install exactly {mode:?}")
                }
                DurableStatus::Off => panic!("/memory {arg} must install a session lease"),
            }
        }
    }

    /// `/memory once` installs a pending one-shot recall and leaves the
    /// durable slot untouched.
    #[test]
    fn memory_once_installs_pending_one_shot_only() {
        let runtime = crate::Runtime::new_headless();
        let text = output_text(memory_command("once", &runtime));
        assert!(text.contains("one-shot recall: pending"), "got: {text}");
        let status = runtime.memory_context_status();
        assert_eq!(status.durable, DurableStatus::Off, "durable slot untouched");
        assert!(matches!(status.one_shot, OneShotStatus::Pending { .. }));
        // A second grant while one is pending fails typed, not silently.
        assert!(matches!(
            memory_command("once", &runtime),
            CommandResult::Error(e) if e.contains("already pending")
        ));
    }

    /// Rendering: `/memory status` (and the empty default) mentions the
    /// mode and the lease expiry.
    #[test]
    fn memory_status_render_mentions_mode_and_lease_expiry() {
        let runtime = crate::Runtime::new_headless();
        // Off default (spec §21): status names the off mode.
        let text = output_text(memory_command("status", &runtime));
        assert!(text.contains("mode off"), "got: {text}");

        output_text(memory_command("on", &runtime));
        for arg in ["status", ""] {
            let text = output_text(memory_command(arg, &runtime));
            assert!(
                text.contains("mode capture_and_recall"),
                "status must mention the mode; got: {text}"
            );
            assert!(
                text.contains("expiry"),
                "status must mention the lease expiry; got: {text}"
            );
        }
    }

    /// `/memory off` revokes session state BEFORE returning: the runtime
    /// state check and the returned render both show Off.
    #[test]
    fn memory_off_takes_effect_before_returning() {
        let runtime = crate::Runtime::new_headless();
        output_text(memory_command("on", &runtime));
        assert!(matches!(
            runtime.memory_context_status().durable,
            DurableStatus::Active { .. }
        ));
        let text = output_text(memory_command("off", &runtime));
        // State check: revocation already applied when the command returned.
        assert_eq!(runtime.memory_context_status().durable, DurableStatus::Off);
        // The returned render is the post-revocation snapshot.
        assert!(text.contains("mode off"), "got: {text}");
    }

    /// Task B5 (spec §10.4): `/memory why` with no accepted recall this
    /// session is clear OUTPUT (never `CommandResult::Error`) explaining the
    /// three no-metadata causes — both while memory is off and after enable
    /// but before any eligible prompt has run.
    #[test]
    fn memory_why_without_recall_metadata_is_clear_output_not_error() {
        let runtime = crate::Runtime::new_headless();
        let text = output_text(memory_command("why", &runtime));
        assert!(text.contains("no recall metadata available"), "got: {text}");
        assert!(text.contains("memory is off"), "got: {text}");
        assert!(text.contains("no eligible prompt"), "got: {text}");
        assert!(text.contains("skipped"), "got: {text}");

        // Enabled but no eligible prompt yet: still the clear non-error text.
        output_text(memory_command("on", &runtime));
        let text = output_text(memory_command("why", &runtime));
        assert!(text.contains("no recall metadata available"), "got: {text}");
    }

    /// Spec §6.3 / assumption 5: every enable path grants under host-minted
    /// `ExplicitCommand` proof — never model-supplied text.
    #[test]
    fn memory_enable_always_uses_explicit_command_proof() {
        for arg in ["on", "recall", "capture"] {
            let runtime = crate::Runtime::new_headless();
            output_text(memory_command(arg, &runtime));
            assert!(
                matches!(
                    runtime.memory_durable_proof_for_test(),
                    Some(UserIntentProof::ExplicitCommand { .. })
                ),
                "/memory {arg} must grant under ExplicitCommand proof"
            );
        }
        let runtime = crate::Runtime::new_headless();
        output_text(memory_command("once", &runtime));
        assert!(
            matches!(
                runtime.memory_one_shot_proof_for_test(),
                Some(UserIntentProof::ExplicitCommand { .. })
            ),
            "/memory once must grant under ExplicitCommand proof"
        );
    }

    /// Unknown args are a typed error naming the valid forms.
    #[test]
    fn memory_unknown_arg_is_typed_error() {
        let runtime = crate::Runtime::new_headless();
        match memory_command("bogus", &runtime) {
            CommandResult::Error(e) => {
                assert!(e.contains("unknown /memory subcommand"), "got: {e}");
                assert!(e.contains("index-history"), "hint lists forms; got: {e}");
            }
            other => panic!("expected Error, got {other:?}"),
        }
        assert_eq!(runtime.memory_context_status().durable, DurableStatus::Off);
    }

    /// `index-history` (task D1) returns the host-computed disclosure preview
    /// and does not begin import.
    #[test]
    fn memory_index_history_surfaces_disclosure_preview() {
        let runtime = crate::Runtime::new_headless();
        match memory_command("index-history", &runtime) {
            CommandResult::Output(text) => {
                assert!(text.contains("History import preview"), "got: {text}");
                assert!(text.contains("project:"), "got: {text}");
                assert!(text.contains("sessions:"), "got: {text}");
                assert!(text.contains("approximate bytes:"), "got: {text}");
                assert!(text.contains("included date range:"), "got: {text}");
                assert!(text.contains("included classes:"), "got: {text}");
                assert!(text.contains("excluded classes:"), "got: {text}");
                assert!(text.contains("retention policy:"), "got: {text}");
                assert!(text.contains("redaction policy:"), "got: {text}");
                assert!(text.contains("destination .r8:"), "got: {text}");
                assert!(
                    text.contains("explicit confirmation required: true"),
                    "got: {text}"
                );
                assert!(text.contains("no import has started"), "got: {text}");
            }
            other => panic!("expected Output, got {other:?}"),
        }
        let status = runtime.memory_context_status();
        assert_eq!(status.durable, DurableStatus::Off);
        assert_eq!(status.one_shot, OneShotStatus::Idle);
    }

    #[test]
    fn memory_index_history_decline_clears_pending_preview() {
        let runtime = crate::Runtime::new_headless();
        assert!(matches!(
            memory_command("index-history", &runtime),
            CommandResult::Output(_)
        ));
        assert!(matches!(
            memory_command("index-history decline", &runtime),
            CommandResult::Output(text) if text.contains("no session content was read")
        ));
        assert!(matches!(
            memory_command("index-history confirm", &runtime),
            CommandResult::Error(error) if error.contains("explicit user confirmation")
        ));
    }

    #[test]
    fn memory_index_history_confirmation_requires_prior_preview() {
        let runtime = crate::Runtime::new_headless();
        assert!(matches!(
            memory_command("index-history confirm", &runtime),
            CommandResult::Error(error) if error.contains("explicit user confirmation")
        ));
    }

    /// All frontends route `/memory` through the single
    /// `handle_engine_command` dispatch point (spec §7.3: one engine API).
    #[test]
    fn memory_dispatches_through_handle_engine_command() {
        let mut runtime = crate::Runtime::new_headless();
        match handle_engine_command("memory", "on", &mut runtime) {
            Some(CommandResult::Output(text)) => {
                assert!(text.contains("mode capture_and_recall"), "got: {text}");
            }
            other => panic!("expected Some(Output), got {other:?}"),
        }
        match handle_engine_command("memory", "", &mut runtime) {
            Some(CommandResult::Output(text)) => {
                assert!(text.contains("mode capture_and_recall"), "got: {text}");
                assert!(text.contains("expiry"), "got: {text}");
            }
            other => panic!("expected Some(Output), got {other:?}"),
        }
    }
}