supercode-harness 0.4.15

The optional native Supercode agent and tool harness
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
//! ORCH-9 (observed tier): one uniform listing of the approval requests
//! waiting for an answer, across every harness supercode drives.
//!
//! **What a source is, at the pinned harness versions.** An approval is only
//! listable where some door holds it. At the pin there is exactly one uniform
//! source plus supercode's own queue:
//!
//! * **Live protocol requests** — a request exists while a driven runtime's
//!   turn is blocked on it, and it is delivered to supercode as an ordinary
//!   runtime event ([`crate::HarnessEvent`]) on the connection that raised
//!   it: ACP's `session/request_permission` (hermes, openclaw, grok, gemini,
//!   goose, supercode), opencode's `permission.asked` bus event, Codex's
//!   server-to-client `*Approval` reverse requests, Claude Code's stream-json
//!   `can_use_tool` control request, and — on a joined supercode runtime —
//!   the frontend broker's own `request` envelope. It stops existing the
//!   moment `harness.v1.runtimes.respond` answers it.
//! * **supercode's own queued subagent approvals**
//!   ([`crate::subagents::QueuedApproval`]) — the requests background children
//!   raised on the parent's queue.
//!
//! **There is no file or database source at the pin.** hermes 0.21.0 has no
//! `hermes approvals` at all, and openclaw 2026.7.1-2 has no
//! `approvals pending | resolve | grants` (both are upstream-main-only; see
//! the version note in `docs/composable-harness/inventory/orchestration.md`
//! and the committed help fixtures in `crates/harness/src/parity/fixtures/`).
//! [`ApprovalKind::Stored`] and [`ApprovalKind::Proposal`] are therefore
//! defined here and never produced: they are the shapes a later pin's stored
//! operator approvals and allowlist proposals will land in, and nothing in
//! this module invents them today.
//!
//! pi is a further honest absence: its adapter can `respond`, but pi has no
//! per-tool-call approval system at all at its pin
//! (`docs/composable-harness/inventory/pi.md` §4), so no pi request shape is
//! recognized — none is ever emitted.
//!
//! **Answering (ORCH-20, controlled tier).** This module never talks to a
//! harness itself. It TRANSLATES one uniform decision — `allow_once`,
//! `allow_always`, `deny` — into the option token and reply envelope the door
//! that raised the request already accepts, and
//! `harness.v1.approvals.resolve` hands that envelope to
//! `harness.v1.runtimes.respond`, the harness's own door, unchanged. A
//! decision the request does not offer is refused by name with the offered
//! ones listed; nothing is ever guessed at, and no adapter learns a new
//! vocabulary because of this module.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::subagents::{QueuedApproval, QueuedApprovalOutcome};
use crate::{HarnessEvent, HarnessId};

/// Where a row came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalKind {
    /// A request a running turn is blocked on right now.
    Live,
    /// An operator approval a harness keeps in its own store. No harness at
    /// the pinned versions has one; see the module docs.
    Stored,
    /// A mined allowlist proposal rather than an outstanding request. No
    /// harness at the pinned versions has one; see the module docs.
    Proposal,
}

impl ApprovalKind {
    /// Stable wire spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Live => "live",
            Self::Stored => "stored",
            Self::Proposal => "proposal",
        }
    }
}

/// Lifecycle state of one approval row.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalStatus {
    /// Waiting for an answer.
    Pending,
    /// Answered yes (once or for the session).
    Allowed,
    /// Answered no.
    Denied,
    /// Timed out before anyone answered.
    Expired,
    /// Withdrawn by the side that raised it.
    Cancelled,
}

impl ApprovalStatus {
    /// Stable wire spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Allowed => "allowed",
            Self::Denied => "denied",
            Self::Expired => "expired",
            Self::Cancelled => "cancelled",
        }
    }
}

/// One answer the door that raised this request accepts.
///
/// `id` is the token the harness's own responder expects — an ACP
/// `optionId`, an opencode reply word, a supercode frontend decision. It is
/// never invented: a row carries options only where the request itself
/// enumerates them or the pinned source documents the responder's vocabulary.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApprovalOption {
    /// Token passed back to the harness.
    pub id: String,
    /// Human label when the request carries one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// The protocol's own classification of the answer, when it states one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
}

impl ApprovalOption {
    fn bare(id: &str) -> Self {
        Self {
            id: id.to_string(),
            label: None,
            kind: None,
        }
    }
}

/// One approval request, in the vocabulary shared by every harness.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApprovalRow {
    /// Stable, addressable identity. Live rows are
    /// `<connection>/<native request id>`; supercode's queued subagent rows
    /// are `supercode/subagent/<child>/<queued_at_ms>/<index>`.
    pub id: String,
    /// Harness whose door raised the request.
    pub harness: HarnessId,
    /// Which source this row came from.
    pub kind: ApprovalKind,
    /// Lifecycle state.
    pub status: ApprovalStatus,
    /// The tool, command, or edit being asked about, on one line.
    pub subject: String,
    /// Harness-native session the request belongs to, when it names one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    /// Live runtime the request arrived on, when there is one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime_id: Option<String>,
    /// Unix-ms wall-clock time the request was first seen.
    pub requested_at_ms: i64,
    /// How long it has been waiting, as of this listing.
    pub age_ms: i64,
    /// Answers the door accepts. Empty where the protocol does not enumerate
    /// them, and always empty on a row that is no longer `pending`.
    #[serde(default)]
    pub options: Vec<ApprovalOption>,
}

/// `harness.v1.approvals.list` request.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ApprovalsQuery {
    /// Only this harness. Omit for every harness.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness: Option<String>,
    /// Only this session (a harness-native session id, or a child agent id
    /// for supercode's queued subagent rows).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<String>,
}

impl ApprovalsQuery {
    /// Whether one row survives this query's filters.
    pub fn matches(&self, row: &ApprovalRow) -> bool {
        if let Some(harness) = self.harness.as_deref() {
            if row.harness.as_str() != harness {
                return false;
            }
        }
        if let Some(session) = self.session.as_deref() {
            let hit = row.session_id.as_deref() == Some(session)
                || row.runtime_id.as_deref() == Some(session);
            if !hit {
                return false;
            }
        }
        true
    }
}

/// The uniform decision `harness.v1.approvals.resolve` takes, in the
/// vocabulary shared by every harness rather than any one door's spelling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalDecision {
    /// Allow this one call.
    AllowOnce,
    /// Allow this call and every matching one for the rest of the session.
    AllowAlways,
    /// Refuse.
    Deny,
}

impl ApprovalDecision {
    /// Every decision, in escalating order.
    pub const ALL: [Self; 3] = [Self::AllowOnce, Self::AllowAlways, Self::Deny];

    /// Stable wire spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::AllowOnce => "allow_once",
            Self::AllowAlways => "allow_always",
            Self::Deny => "deny",
        }
    }

    /// Parse a wire or CLI spelling. `allow_once` and `allow-once` are the
    /// same decision: the CLI hyphenates its positional, the RPC does not.
    pub fn parse(text: &str) -> Option<Self> {
        let normalized = text.trim().to_ascii_lowercase().replace('-', "_");
        Self::ALL
            .into_iter()
            .find(|decision| decision.as_str() == normalized)
    }
}

/// `harness.v1.approvals.resolve` request.
///
/// Exactly one of `decision` and `option_id` is given: the uniform decision
/// this module translates, or the door's own option token when a caller has
/// already read it off the row and wants it passed through untranslated.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ApprovalsResolveParams {
    /// The row id `harness.v1.approvals.list` reported.
    pub id: String,
    /// Uniform decision to translate onto this request's own options.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decision: Option<ApprovalDecision>,
    /// One of the row's own `options[].id` values, passed through as-is.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub option_id: Option<String>,
}

/// What a caller asked for, once the params have been validated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApprovalChoice {
    /// Translate this uniform decision onto the request's own options.
    Decision(ApprovalDecision),
    /// Send this exact option token, after checking the request offers it.
    Option(String),
}

impl ApprovalChoice {
    /// What the caller asked for, as it will appear in a refusal.
    pub fn asked(&self) -> &str {
        match self {
            Self::Decision(decision) => decision.as_str(),
            Self::Option(option) => option.as_str(),
        }
    }
}

/// Everything `harness.v1.runtimes.respond` needs to answer one request.
///
/// This is a plan, not an effect: building it neither touches a runtime nor
/// forgets the row. The service hands it straight to
/// `harness.v1.runtimes.respond`, so the answer travels the adapter path that
/// already existed and no adapter is changed by this verb.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApprovalResolution {
    /// Runtime connection holding the request.
    pub connection: String,
    /// Native JSON request id the door expects back.
    pub request_id: Value,
    /// Option token actually sent.
    pub option_id: String,
    /// The door's own reply envelope carrying that token.
    pub response: Value,
}

/// Why one resolve could not be planned.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApprovalResolveError {
    /// No live request with this row id is outstanding on this service.
    UnknownId(String),
    /// The row is supercode's own queued subagent record, which is an audit
    /// entry rather than an answerable door.
    QueuedSubagentRow(String),
    /// The request enumerates answers, but none of them is this decision.
    NotOffered {
        /// What was asked for.
        asked: String,
        /// The option ids the request itself offers.
        offered: Vec<String>,
    },
    /// The request enumerates no answers at all, so there is nothing uniform
    /// to select. Codex's reverse approval request is the one such door at
    /// the pin (see [`classify_live_request`]).
    NoOptions {
        /// Door that raised it.
        door: &'static str,
    },
}

impl std::fmt::Display for ApprovalResolveError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnknownId(id) => write!(
                formatter,
                "no approval request `{id}` is waiting on this service — a live request \
                 exists only inside the process driving the runtime whose turn it blocks, \
                 and only until it is answered. Answer it there: the SDK client or TUI that \
                 started the runtime, or `harness.v1.approvals.resolve` over that same \
                 `supercode harness serve` stdio session (SUP-62: no cross-process relay)"
            ),
            Self::QueuedSubagentRow(id) => write!(
                formatter,
                "`{id}` is a queued subagent record — supercode's own audit trail of a \
                 request the parent's own handler answers (the terminal's modal, or the \
                 frontend request broker). Answer it on the door that raised it: the \
                 `request` envelope row of the joined supercode runtime"
            ),
            Self::NotOffered { asked, offered } => write!(
                formatter,
                "this request does not offer `{asked}` — it offers: {}",
                if offered.is_empty() {
                    "(nothing)".to_string()
                } else {
                    offered.join(", ")
                }
            ),
            Self::NoOptions { door } => write!(
                formatter,
                "this `{door}` request enumerates no answers, so there is no option to \
                 select — answer it with `harness.v1.runtimes.respond` and that door's own \
                 reply body"
            ),
        }
    }
}

impl std::error::Error for ApprovalResolveError {}

/// Which protocol door raised a live request.
///
/// A door decides two things this module needs and nothing else: the option
/// vocabulary a uniform decision maps onto, and the envelope
/// `harness.v1.runtimes.respond` carries the answer in. Each is the door's
/// own — see [`ApprovalResolution`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalDoor {
    /// ACP `session/request_permission` (hermes, openclaw, grok, gemini,
    /// goose, supercode's own ACP server).
    Acp,
    /// opencode's `permission.asked` bus event.
    Opencode,
    /// Codex's `*Approval` server-to-client reverse request.
    Codex,
    /// Claude Code's stream-json `can_use_tool` control request, raised to the
    /// permission handler supercode registers with
    /// `--permission-prompt-tool stdio`.
    ClaudeCode,
    /// supercode's own frontend request broker, on a joined runtime.
    SupercodeFrontend,
}

impl ApprovalDoor {
    /// Stable spelling used in refusal messages.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Acp => "acp",
            Self::Opencode => "opencode",
            Self::Codex => "codex",
            Self::ClaudeCode => "claude-code",
            Self::SupercodeFrontend => "supercode-frontend",
        }
    }

    /// How this door spells one uniform decision, best match first.
    ///
    /// Each list is the door's OWN vocabulary, never a coinage:
    ///
    /// * ACP names the classification on the request — `PermissionOptionKind`
    ///   is `allow_once | allow_always | reject_once | reject_always` — so a
    ///   decision is matched against each option's `kind` and, for an agent
    ///   that sends none, against its `optionId`.
    /// * opencode's reply set is `once | always | reject`
    ///   (`docs/composable-harness/inventory/opencode.md` §"Ask/approve flow").
    /// * supercode's frontend broker takes [`FRONTEND_DECISIONS`].
    /// * Claude Code's permission handler answers with a `behavior`, and the
    ///   protocol defines exactly two: `allow` and `deny`
    ///   ([`CLAUDE_CODE_BEHAVIORS`]). `allow_always` is NOT among them —
    ///   persisting a rule is a separate `updatedPermissions` field carrying
    ///   the request's own `permission_suggestions`, which the uniform
    ///   `(door, options, choice)` translation here does not carry — so the
    ///   decision is refused by name with the two that are offered.
    /// * Codex's reverse request enumerates nothing, and this module invents
    ///   no vocabulary for it (ORCH-9's own stance); its rows refuse with
    ///   [`ApprovalResolveError::NoOptions`].
    const fn spellings(self, decision: ApprovalDecision) -> &'static [&'static str] {
        match (self, decision) {
            (Self::Acp, ApprovalDecision::AllowOnce) => &["allow_once"],
            (Self::Acp, ApprovalDecision::AllowAlways) => &["allow_always"],
            (Self::Acp, ApprovalDecision::Deny) => &["reject_once", "reject_always"],
            (Self::Opencode, ApprovalDecision::AllowOnce) => &["once"],
            (Self::Opencode, ApprovalDecision::AllowAlways) => &["always"],
            (Self::Opencode, ApprovalDecision::Deny) => &["reject"],
            (Self::ClaudeCode, ApprovalDecision::AllowOnce) => &["allow"],
            (Self::ClaudeCode, ApprovalDecision::AllowAlways) => &[],
            (Self::ClaudeCode, ApprovalDecision::Deny) => &["deny"],
            (Self::SupercodeFrontend, ApprovalDecision::AllowOnce) => &["allow"],
            (Self::SupercodeFrontend, ApprovalDecision::AllowAlways) => &["allow_for_session"],
            (Self::SupercodeFrontend, ApprovalDecision::Deny) => &["deny"],
            (Self::Codex, _) => &[],
        }
    }

    /// The reply envelope this door carries a chosen option token in.
    ///
    /// `None` for a door with no enumerated answers — nothing is guessed.
    fn reply(self, option_id: &str) -> Option<Value> {
        match self {
            // ACP: the client answers by SELECTING one of the request's own
            // optionIds. This exact envelope cleared a real hermes 0.21.0
            // permission request in
            // `docs/interop/research/orch9-hermes-approval-receipt-2026-09-03.json`.
            Self::Acp => Some(serde_json::json!({
                "outcome": {"outcome": "selected", "optionId": option_id},
            })),
            // opencode: the reply word, POSTed to
            // `/session/{id}/permissions/{permissionID}` by the adapter.
            Self::Opencode => Some(serde_json::json!({"response": option_id})),
            // supercode's own broker takes the decision by name
            // (`crate::runtime::supercode_http::frontend_response`).
            Self::SupercodeFrontend => Some(serde_json::json!({"decision": option_id})),
            // Claude Code: the permission handler's result. `deny` must carry
            // a `message` — measured against claude 2.1.258, which refuses a
            // bare `{"behavior":"deny"}` with "Expected {behavior: 'allow',
            // updatedInput?: object} or {behavior: 'deny', message: string}".
            // Recorded in
            // `docs/interop/research/orc2-claude-respond-receipt-2026-09-04.json`.
            Self::ClaudeCode if option_id == "deny" => Some(serde_json::json!({
                "behavior": "deny",
                "message": "denied through supercode approvals",
            })),
            Self::ClaudeCode => Some(serde_json::json!({"behavior": option_id})),
            Self::Codex => None,
        }
    }
}

/// Translate one caller's choice into the token and envelope a request's own
/// door accepts.
///
/// Kept free of the registry so the whole translation is testable from a
/// request's options alone.
pub fn plan_reply(
    door: ApprovalDoor,
    options: &[ApprovalOption],
    choice: &ApprovalChoice,
) -> Result<(String, Value), ApprovalResolveError> {
    if options.is_empty() {
        return Err(ApprovalResolveError::NoOptions {
            door: door.as_str(),
        });
    }
    let offered = || {
        options
            .iter()
            .map(|option| option.id.clone())
            .collect::<Vec<_>>()
    };
    let chosen = match choice {
        // An explicit token is passed through, but only after the request
        // itself is confirmed to offer it.
        ApprovalChoice::Option(option_id) => options
            .iter()
            .find(|option| &option.id == option_id)
            .ok_or_else(|| ApprovalResolveError::NotOffered {
                asked: option_id.clone(),
                offered: offered(),
            })?,
        ApprovalChoice::Decision(decision) => door
            .spellings(*decision)
            .iter()
            .find_map(|spelling| {
                options.iter().find(|option| {
                    option.kind.as_deref() == Some(*spelling) || option.id == *spelling
                })
            })
            .ok_or_else(|| ApprovalResolveError::NotOffered {
                asked: decision.as_str().to_string(),
                offered: offered(),
            })?,
    };
    let response = door
        .reply(&chosen.id)
        .ok_or(ApprovalResolveError::NoOptions {
            door: door.as_str(),
        })?;
    Ok((chosen.id.clone(), response))
}

/// One live protocol request as the classifier reads it off the wire.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiveRequest {
    /// Native JSON id the harness expects back through `runtimes.respond`.
    pub request_id: Value,
    /// Protocol door that raised it.
    pub door: ApprovalDoor,
    /// Session the request names, when it names one.
    pub session_id: Option<String>,
    /// One-line description of what is being asked about.
    pub subject: String,
    /// Answers the door accepts.
    pub options: Vec<ApprovalOption>,
}

/// Recognize a permission/approval request in one live runtime event.
///
/// Returns `None` for every other event, including the responses that answer
/// these requests. The three recognized shapes are exactly the ones the
/// adapters in [`crate::runtime`] surface; each is matched on its own
/// protocol's spelling rather than on a guess about the harness.
pub fn classify_live_request(kind: &str, payload: &Value) -> Option<LiveRequest> {
    match kind {
        // ACP `session/request_permission` (hermes, openclaw, grok, gemini,
        // goose, and supercode's own ACP server).
        "session/request_permission" => acp_request(payload),
        // opencode's bus event; the reply goes to
        // `/session/{id}/permissions/{permissionID}`.
        "permission.asked" => opencode_request(payload),
        // supercode's own runtime, joined over the HTTP frontend: the
        // request broker publishes `{"type":"request","request":{…}}` and
        // `runtimes.respond` answers it by the same integer id
        // (`crate::runtime::supercode_http`).
        "request" => supercode_request(payload),
        // Claude Code's stream-json control channel. Only the `can_use_tool`
        // subtype is a permission request; every other control_request the
        // CLI can raise is left alone.
        "control_request" => claude_code_request(payload),
        // Codex app-server / mcp-server reverse requests
        // (`execCommandApproval`, `applyPatchApproval`). A notification with
        // the same name is not a request: only a JSON-RPC message carrying an
        // `id` can be answered.
        _ if kind.ends_with("Approval") => codex_request(payload),
        _ => None,
    }
}

fn request_id(payload: &Value) -> Option<Value> {
    payload
        .get("id")
        .filter(|id| !id.is_null())
        .filter(|id| id.is_string() || id.is_number())
        .cloned()
}

fn acp_request(payload: &Value) -> Option<LiveRequest> {
    let request_id = request_id(payload)?;
    let params = payload.get("params").unwrap_or(&Value::Null);
    let tool_call = params.get("toolCall");
    let subject = tool_call
        .and_then(|call| call.get("title"))
        .and_then(Value::as_str)
        .map(str::to_string)
        .or_else(|| {
            tool_call
                .and_then(|call| call.get("rawInput"))
                .and_then(command_line)
        })
        .or_else(|| {
            tool_call
                .and_then(|call| call.get("kind"))
                .and_then(Value::as_str)
                .map(str::to_string)
        })
        .unwrap_or_else(|| "permission request".to_string());
    let options = params
        .get("options")
        .and_then(Value::as_array)
        .map(|options| {
            options
                .iter()
                .filter_map(|option| {
                    Some(ApprovalOption {
                        id: option.get("optionId").and_then(Value::as_str)?.to_string(),
                        label: option
                            .get("name")
                            .and_then(Value::as_str)
                            .map(str::to_string),
                        kind: option
                            .get("kind")
                            .and_then(Value::as_str)
                            .map(str::to_string),
                    })
                })
                .collect()
        })
        .unwrap_or_default();
    Some(LiveRequest {
        request_id,
        door: ApprovalDoor::Acp,
        session_id: params
            .get("sessionId")
            .and_then(Value::as_str)
            .map(str::to_string),
        subject: one_line(&subject),
        options,
    })
}

fn opencode_request(payload: &Value) -> Option<LiveRequest> {
    let properties = payload.get("properties").unwrap_or(payload);
    let permission = properties
        .get("permission")
        .filter(|value| value.is_object())
        .unwrap_or(properties);
    let id = permission.get("id").and_then(Value::as_str)?;
    let subject = permission
        .get("title")
        .and_then(Value::as_str)
        .or_else(|| permission.get("pattern").and_then(Value::as_str))
        .or_else(|| permission.get("type").and_then(Value::as_str))
        .unwrap_or("permission request");
    Some(LiveRequest {
        request_id: Value::String(id.to_string()),
        door: ApprovalDoor::Opencode,
        session_id: permission
            .get("sessionID")
            .and_then(Value::as_str)
            .map(str::to_string),
        subject: one_line(subject),
        // opencode's own reply vocabulary at the pin
        // (`docs/composable-harness/inventory/opencode.md` §"Ask/approve
        // flow": clients reply `once | always | reject`).
        options: ["once", "always", "reject"]
            .into_iter()
            .map(ApprovalOption::bare)
            .collect(),
    })
}

fn supercode_request(payload: &Value) -> Option<LiveRequest> {
    let request = payload.get("request")?;
    // Only approvals: an MCP elicitation travels the same envelope but is a
    // form to fill in, not a permission to grant.
    if request.get("kind").and_then(Value::as_str) != Some("approval") {
        return None;
    }
    let request_id = request
        .get("id")
        .filter(|id| id.is_number())
        .cloned()
        .filter(|id| !id.is_null())?;
    let inner = request.get("payload").unwrap_or(&Value::Null);
    let subject = inner
        .get("subject")
        .and_then(Value::as_str)
        .filter(|subject| !subject.is_empty())
        .or_else(|| inner.get("tool").and_then(Value::as_str))
        .unwrap_or("permission request");
    Some(LiveRequest {
        request_id,
        door: ApprovalDoor::SupercodeFrontend,
        // A request raised by a background child names that child; a request
        // from the parent's own loop names nothing beyond the runtime.
        session_id: inner
            .get("child_agent_id")
            .and_then(Value::as_str)
            .map(str::to_string),
        subject: one_line(subject),
        // The decisions `runtimes.respond` accepts on this door
        // (`crate::runtime::supercode_http::frontend_response`).
        options: FRONTEND_DECISIONS
            .into_iter()
            .map(ApprovalOption::bare)
            .collect(),
    })
}

/// Claude Code's `can_use_tool` control request.
///
/// Ground truth (claude 2.1.258, recorded live in
/// `docs/interop/research/orc2-claude-respond-receipt-2026-09-04.json`): with
/// `--permission-prompt-tool stdio` the CLI writes
/// `{"type":"control_request","request_id":"<uuid>","request":{"subtype":"can_use_tool","tool_name":"Bash","display_name":"Bash","input":{…},"description":…,"permission_suggestions":[…],"blocked_path":…,"tool_use_id":"toolu_…"}}`
/// and blocks the turn until a `control_response` answers that `request_id`.
fn claude_code_request(payload: &Value) -> Option<LiveRequest> {
    let request = payload.get("request")?;
    if request.get("subtype").and_then(Value::as_str) != Some("can_use_tool") {
        return None;
    }
    let request_id = payload
        .get("request_id")
        .filter(|id| id.is_string())
        .cloned()?;
    let tool = request
        .get("tool_name")
        .and_then(Value::as_str)
        .or_else(|| request.get("display_name").and_then(Value::as_str))
        .unwrap_or("tool");
    let detail = request
        .get("input")
        .and_then(command_line)
        .or_else(|| {
            request
                .get("description")
                .and_then(Value::as_str)
                .map(str::to_string)
        })
        .or_else(|| {
            request
                .get("blocked_path")
                .and_then(Value::as_str)
                .map(str::to_string)
        });
    let subject = match detail {
        Some(detail) if !detail.is_empty() => format!("{tool} {detail}"),
        _ => tool.to_string(),
    };
    Some(LiveRequest {
        request_id,
        door: ApprovalDoor::ClaudeCode,
        // The request names the blocked tool call, never a session: the
        // connection's own runtime id is the session identity here.
        session_id: None,
        subject: one_line(&subject),
        // The two `behavior` values the CLI's permission-result validator
        // accepts; see [`ApprovalDoor::spellings`].
        options: CLAUDE_CODE_BEHAVIORS
            .into_iter()
            .map(ApprovalOption::bare)
            .collect(),
    })
}

fn codex_request(payload: &Value) -> Option<LiveRequest> {
    let request_id = request_id(payload)?;
    let params = payload.get("params").unwrap_or(&Value::Null);
    let subject = params
        .get("command")
        .and_then(command_line)
        .or_else(|| {
            params
                .get("fileChanges")
                .and_then(Value::as_object)
                .map(|changes| {
                    let files = changes.keys().cloned().collect::<Vec<_>>().join(", ");
                    if files.is_empty() {
                        "apply patch".to_string()
                    } else {
                        format!("apply patch: {files}")
                    }
                })
        })
        .or_else(|| {
            params
                .get("reason")
                .and_then(Value::as_str)
                .map(str::to_string)
        })
        .unwrap_or_else(|| "approval request".to_string());
    Some(LiveRequest {
        request_id,
        door: ApprovalDoor::Codex,
        session_id: ["threadId", "conversationId", "sessionId"]
            .into_iter()
            .find_map(|key| params.get(key).and_then(Value::as_str))
            .map(str::to_string),
        subject: one_line(&subject),
        // The Codex reverse request does not enumerate its answers, and this
        // module does not invent a vocabulary for it.
        options: Vec::new(),
    })
}

/// A command as one line, whether the protocol sends a string or an argv.
fn command_line(value: &Value) -> Option<String> {
    match value {
        Value::String(text) => Some(text.clone()),
        Value::Array(parts) => {
            let joined = parts
                .iter()
                .filter_map(Value::as_str)
                .collect::<Vec<_>>()
                .join(" ");
            (!joined.is_empty()).then_some(joined)
        }
        Value::Object(object) => object
            .get("command")
            .or_else(|| object.get("cmd"))
            .and_then(command_line),
        _ => None,
    }
}

fn one_line(text: &str) -> String {
    let flattened = text.split_whitespace().collect::<Vec<_>>().join(" ");
    if flattened.is_empty() {
        "permission request".to_string()
    } else {
        flattened
    }
}

/// Render a native JSON request id into the stable id segment used by
/// [`ApprovalRow::id`].
fn id_segment(request_id: &Value) -> String {
    match request_id {
        Value::String(text) => text.clone(),
        other => other.to_string(),
    }
}

#[derive(Debug, Clone)]
struct LiveEntry {
    request_id: Value,
    door: ApprovalDoor,
    harness: HarnessId,
    runtime_id: String,
    session_id: Option<String>,
    subject: String,
    options: Vec<ApprovalOption>,
    requested_at_ms: i64,
}

/// The live pending requests held by one service's open runtime connections.
///
/// A request enters when the connection surfaces it and leaves when it is
/// answered or the connection goes away. Nothing here survives the process:
/// a live request only exists while the turn that raised it is blocked.
#[derive(Debug, Default)]
pub struct ApprovalRegistry {
    /// Connection id → the requests still outstanding on it, oldest first.
    entries: BTreeMap<String, Vec<LiveEntry>>,
}

impl ApprovalRegistry {
    /// Empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Record one runtime event if it is a permission/approval request.
    ///
    /// Returns `true` when the event was recognized and is now listable. A
    /// repeat of a request already held is not duplicated.
    pub fn observe(
        &mut self,
        connection: &str,
        harness: &HarnessId,
        runtime_id: &str,
        event: &HarnessEvent,
        now_ms: i64,
    ) -> bool {
        let Some(request) = classify_live_request(&event.kind, &event.payload) else {
            return false;
        };
        let entries = self.entries.entry(connection.to_string()).or_default();
        if entries
            .iter()
            .any(|entry| entry.request_id == request.request_id)
        {
            return false;
        }
        entries.push(LiveEntry {
            request_id: request.request_id,
            door: request.door,
            harness: harness.clone(),
            runtime_id: runtime_id.to_string(),
            session_id: request.session_id,
            subject: request.subject,
            options: request.options,
            requested_at_ms: now_ms,
        });
        true
    }

    /// Drop one request because it was answered.
    pub fn answered(&mut self, connection: &str, request_id: &Value) -> bool {
        let Some(entries) = self.entries.get_mut(connection) else {
            return false;
        };
        let before = entries.len();
        entries.retain(|entry| &entry.request_id != request_id);
        let removed = entries.len() < before;
        if entries.is_empty() {
            self.entries.remove(connection);
        }
        removed
    }

    /// Drop everything held for a connection that closed or failed.
    pub fn forget(&mut self, connection: &str) {
        self.entries.remove(connection);
    }

    /// Whether nothing is outstanding.
    pub fn is_empty(&self) -> bool {
        self.entries.values().all(Vec::is_empty)
    }

    /// Plan the answer to one listed row (ORCH-20).
    ///
    /// Looks the row up by the same `id` [`Self::rows`] published, translates
    /// the caller's choice through the door that raised it, and returns what
    /// `harness.v1.runtimes.respond` needs. Nothing is sent and nothing is
    /// forgotten here: the service performs the answer on the existing
    /// respond path, which is also what drops the row.
    pub fn resolution(
        &self,
        row_id: &str,
        choice: &ApprovalChoice,
    ) -> Result<ApprovalResolution, ApprovalResolveError> {
        // A queued subagent record is addressable but not answerable; say so
        // rather than reporting it simply missing.
        if row_id.starts_with(SUBAGENT_ROW_PREFIX) {
            return Err(ApprovalResolveError::QueuedSubagentRow(row_id.to_string()));
        }
        let (connection, entry) = self
            .entries
            .iter()
            .flat_map(|(connection, entries)| entries.iter().map(move |entry| (connection, entry)))
            .find(|(connection, entry)| {
                format!("{connection}/{}", id_segment(&entry.request_id)) == row_id
            })
            .ok_or_else(|| ApprovalResolveError::UnknownId(row_id.to_string()))?;
        let (option_id, response) = plan_reply(entry.door, &entry.options, choice)?;
        Ok(ApprovalResolution {
            connection: connection.clone(),
            request_id: entry.request_id.clone(),
            option_id,
            response,
        })
    }

    /// Every outstanding request as a row, aged against `now_ms`.
    pub fn rows(&self, now_ms: i64) -> Vec<ApprovalRow> {
        self.entries
            .iter()
            .flat_map(|(connection, entries)| {
                entries.iter().map(move |entry| ApprovalRow {
                    id: format!("{connection}/{}", id_segment(&entry.request_id)),
                    harness: entry.harness.clone(),
                    kind: ApprovalKind::Live,
                    status: ApprovalStatus::Pending,
                    subject: entry.subject.clone(),
                    session_id: entry.session_id.clone(),
                    runtime_id: Some(entry.runtime_id.clone()),
                    requested_at_ms: entry.requested_at_ms,
                    age_ms: now_ms.saturating_sub(entry.requested_at_ms).max(0),
                    options: entry.options.clone(),
                })
            })
            .collect()
    }
}

/// The answers supercode's own frontend accepts, mirroring
/// [`crate::frontend::FrontendApprovalDecision`]. Used for both a live
/// request on a joined supercode runtime and a queued subagent request.
const FRONTEND_DECISIONS: [&str; 3] = ["allow", "allow_for_session", "deny"];

/// The `behavior` values Claude Code's permission-handler protocol defines.
///
/// Its own validator names exactly these two: "Expected {behavior: 'allow',
/// updatedInput?: object} or {behavior: 'deny', message: string}" (claude
/// 2.1.258, recorded in
/// `docs/interop/research/orc2-claude-respond-receipt-2026-09-04.json`).
const CLAUDE_CODE_BEHAVIORS: [&str; 2] = ["allow", "deny"];

/// Row-id prefix every queued subagent record carries.
const SUBAGENT_ROW_PREFIX: &str = "supercode/subagent/";

/// supercode's own queued subagent approvals, as uniform rows.
///
/// The queue is append-only, so the index is a stable identity within the
/// process that owns it. A record whose outcome is still unknown is
/// `pending`; one the parent's own handler already answered carries that
/// answer, which is why this listing never has to guess (see
/// [`crate::subagents::QueuedApproval`]).
pub fn subagent_rows(queued: &[QueuedApproval], now_ms: i64) -> Vec<ApprovalRow> {
    queued
        .iter()
        .enumerate()
        .map(|(index, record)| {
            let status = match record.outcome {
                None => ApprovalStatus::Pending,
                Some(QueuedApprovalOutcome::Allowed) => ApprovalStatus::Allowed,
                Some(QueuedApprovalOutcome::Denied) => ApprovalStatus::Denied,
            };
            let subject = match record.subject.as_deref() {
                Some(subject) if !subject.is_empty() => {
                    format!("{} {}", record.tool, subject)
                }
                _ => record.tool.clone(),
            };
            ApprovalRow {
                id: format!(
                    "{SUBAGENT_ROW_PREFIX}{}/{}/{index}",
                    record.child_agent_id, record.queued_at_ms
                ),
                harness: HarnessId::from(HarnessId::SUPERCODE),
                kind: ApprovalKind::Live,
                status,
                subject: one_line(&subject),
                session_id: Some(record.child_agent_id.clone()),
                runtime_id: None,
                requested_at_ms: record.queued_at_ms,
                age_ms: now_ms.saturating_sub(record.queued_at_ms).max(0),
                options: if status == ApprovalStatus::Pending {
                    FRONTEND_DECISIONS
                        .into_iter()
                        .map(ApprovalOption::bare)
                        .collect()
                } else {
                    Vec::new()
                },
            }
        })
        .collect()
}

/// Whether supercode can list approvals for this harness id at all.
///
/// The uniform-verb contract: a harness whose runtime cannot carry a
/// protocol request is refused by name rather than answered with an empty
/// list. An unknown id is refused the same way.
pub fn lists_approvals(harness: &str) -> bool {
    crate::support::harness_support(harness)
        .is_some_and(|descriptor| descriptor.runtime.capabilities.respond_to_requests)
}

/// Every harness id `approvals.list` accepts, in registry order.
pub fn approval_harnesses() -> Vec<String> {
    crate::support::harness_support_registry()
        .harnesses
        .into_iter()
        .filter(|descriptor| descriptor.runtime.capabilities.respond_to_requests)
        .map(|descriptor| descriptor.id.as_str().to_string())
        .collect()
}

/// Wall-clock now in unix milliseconds.
pub fn now_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|elapsed| elapsed.as_millis() as i64)
        .unwrap_or_default()
}

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

    fn event(kind: &str, payload: Value) -> HarnessEvent {
        HarnessEvent {
            sequence: None,
            kind: kind.to_string(),
            payload,
        }
    }

    fn acp_permission(id: u64, title: &str) -> HarnessEvent {
        event(
            "session/request_permission",
            json!({
                "jsonrpc": "2.0",
                "id": id,
                "method": "session/request_permission",
                "params": {
                    "sessionId": "acp-session",
                    "toolCall": {"toolCallId": "call-1", "title": title, "kind": "execute"},
                    "options": [
                        {"optionId": "allow_once", "name": "Allow once", "kind": "allow_once"},
                        {"optionId": "deny", "name": "Deny", "kind": "reject_once"},
                    ],
                },
            }),
        )
    }

    #[test]
    fn acp_permission_requests_carry_subject_session_and_option_ids() {
        let request = classify_live_request(
            "session/request_permission",
            &acp_permission(7, "rm -rf build").payload,
        )
        .expect("an ACP permission request is recognized");
        assert_eq!(request.request_id, json!(7));
        assert_eq!(request.session_id.as_deref(), Some("acp-session"));
        assert_eq!(request.subject, "rm -rf build");
        assert_eq!(
            request
                .options
                .iter()
                .map(|option| option.id.as_str())
                .collect::<Vec<_>>(),
            vec!["allow_once", "deny"],
        );
    }

    #[test]
    fn opencode_and_codex_requests_use_their_own_protocol_spellings() {
        let opencode = classify_live_request(
            "permission.asked",
            &json!({
                "type": "permission.asked",
                "properties": {
                    "id": "perm-9",
                    "sessionID": "oc-session",
                    "title": "git push origin main",
                },
            }),
        )
        .expect("an opencode permission ask is recognized");
        assert_eq!(opencode.request_id, json!("perm-9"));
        assert_eq!(opencode.session_id.as_deref(), Some("oc-session"));
        assert_eq!(opencode.subject, "git push origin main");
        assert_eq!(
            opencode
                .options
                .iter()
                .map(|option| option.id.as_str())
                .collect::<Vec<_>>(),
            vec!["once", "always", "reject"],
        );

        let codex = classify_live_request(
            "execCommandApproval",
            &json!({
                "jsonrpc": "2.0",
                "id": "req-3",
                "method": "execCommandApproval",
                "params": {"threadId": "cx-thread", "command": ["cargo", "test"]},
            }),
        )
        .expect("a Codex approval reverse request is recognized");
        assert_eq!(codex.subject, "cargo test");
        assert_eq!(codex.session_id.as_deref(), Some("cx-thread"));
        // Codex does not enumerate its answers on the request; nothing is
        // invented here.
        assert!(codex.options.is_empty());
    }

    #[test]
    fn a_joined_supercode_runtime_publishes_its_own_request_envelope() {
        let request = classify_live_request(
            "request",
            &json!({
                "type": "request",
                "request": {
                    "id": 4,
                    "kind": "approval",
                    "payload": {
                        "tool": "shell",
                        "subject": "cargo publish --dry-run",
                        "child_agent_id": "child-2",
                    },
                },
            }),
        )
        .expect("supercode's own frontend request is recognized");
        assert_eq!(request.request_id, json!(4));
        assert_eq!(request.subject, "cargo publish --dry-run");
        assert_eq!(request.session_id.as_deref(), Some("child-2"));
        assert_eq!(
            request
                .options
                .iter()
                .map(|option| option.id.as_str())
                .collect::<Vec<_>>(),
            vec!["allow", "allow_for_session", "deny"],
        );
        // An elicitation travels the same envelope but is not an approval.
        assert!(classify_live_request(
            "request",
            &json!({"type": "request", "request": {"id": 5, "kind": "elicitation", "payload": {}}})
        )
        .is_none());
    }

    /// ORC-2: the frame claude 2.1.258 actually writes, transcribed verbatim
    /// from `docs/interop/research/orc2-claude-respond-receipt-2026-09-04.json`.
    fn claude_can_use_tool() -> Value {
        json!({
            "type": "control_request",
            "request_id": "053f8a2d-3445-4011-a259-4261b31c7326",
            "request": {
                "subtype": "can_use_tool",
                "tool_name": "Bash",
                "display_name": "Bash",
                "input": {"command": "touch probe-artifact.txt", "description": "probe"},
                "description": "probe",
                "permission_suggestions": [{
                    "type": "addRules",
                    "rules": [{"toolName": "Bash", "ruleContent": "touch probe-artifact.txt"}],
                    "behavior": "allow",
                    "destination": "localSettings",
                }],
                "blocked_path": "/tmp/work/probe-artifact.txt",
                "tool_use_id": "toolu_mock_1",
            },
        })
    }

    #[test]
    fn claude_code_can_use_tool_is_a_live_request_with_the_protocols_two_behaviors() {
        let request = classify_live_request("control_request", &claude_can_use_tool())
            .expect("a can_use_tool control request is a permission request");
        assert_eq!(request.door, ApprovalDoor::ClaudeCode);
        assert_eq!(
            request.request_id,
            json!("053f8a2d-3445-4011-a259-4261b31c7326")
        );
        assert_eq!(request.subject, "Bash touch probe-artifact.txt");
        assert_eq!(
            request
                .options
                .iter()
                .map(|option| option.id.as_str())
                .collect::<Vec<_>>(),
            vec!["allow", "deny"],
        );

        // Every other control_request the CLI can raise is left alone.
        assert!(classify_live_request(
            "control_request",
            &json!({"type":"control_request","request_id":"x","request":{"subtype":"hook_callback"}})
        )
        .is_none());
        // An interrupt ACK is a control_response, not a request.
        assert!(classify_live_request(
            "control_response",
            &json!({"type":"control_response","response":{"subtype":"success"}})
        )
        .is_none());
    }

    /// The uniform decisions translate onto the CLI's own `behavior` values,
    /// and `allow_always` — which Claude Code expresses through a separate
    /// `updatedPermissions` field rather than a behavior — is refused by name
    /// with the two answers that ARE offered.
    #[test]
    fn claude_code_decisions_translate_onto_the_permission_result_the_cli_accepts() {
        let request = classify_live_request("control_request", &claude_can_use_tool()).unwrap();
        let (option, reply) = plan_reply(
            request.door,
            &request.options,
            &ApprovalChoice::Decision(ApprovalDecision::AllowOnce),
        )
        .unwrap();
        assert_eq!(option, "allow");
        assert_eq!(reply, json!({"behavior": "allow"}));

        let (option, reply) = plan_reply(
            request.door,
            &request.options,
            &ApprovalChoice::Decision(ApprovalDecision::Deny),
        )
        .unwrap();
        assert_eq!(option, "deny");
        assert_eq!(reply["behavior"], "deny");
        // Measured: claude 2.1.258 refuses a deny with no `message`.
        assert!(reply["message"].as_str().is_some_and(|m| !m.is_empty()));

        let error = plan_reply(
            request.door,
            &request.options,
            &ApprovalChoice::Decision(ApprovalDecision::AllowAlways),
        )
        .unwrap_err();
        assert_eq!(
            error,
            ApprovalResolveError::NotOffered {
                asked: "allow_always".into(),
                offered: vec!["allow".into(), "deny".into()],
            }
        );
    }

    #[test]
    fn ordinary_events_and_id_less_notifications_are_not_approvals() {
        assert!(classify_live_request(
            "session/update",
            &json!({"method": "session/update", "params": {}})
        )
        .is_none());
        // A same-named notification carries no id, so nothing can answer it.
        assert!(classify_live_request(
            "execCommandApproval",
            &json!({"method": "execCommandApproval", "params": {}})
        )
        .is_none());
    }

    #[test]
    fn a_recorded_request_lists_once_and_leaves_when_answered() {
        let mut registry = ApprovalRegistry::new();
        let harness = HarnessId::from(HarnessId::HERMES);
        let event = acp_permission(7, "rm -rf build");
        assert!(registry.observe("runtime-1", &harness, "acp-session", &event, 1_000));
        // The same request seen twice is one row.
        assert!(!registry.observe("runtime-1", &harness, "acp-session", &event, 2_000));

        let rows = registry.rows(1_500);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].id, "runtime-1/7");
        assert_eq!(rows[0].harness.as_str(), HarnessId::HERMES);
        assert_eq!(rows[0].kind, ApprovalKind::Live);
        assert_eq!(rows[0].status, ApprovalStatus::Pending);
        assert_eq!(rows[0].age_ms, 500);

        assert!(registry.answered("runtime-1", &json!(7)));
        assert!(registry.is_empty());
        assert!(!registry.answered("runtime-1", &json!(7)));
    }

    #[test]
    fn a_closed_connection_takes_its_requests_with_it() {
        let mut registry = ApprovalRegistry::new();
        let harness = HarnessId::from(HarnessId::OPENCLAW);
        registry.observe(
            "runtime-2",
            &harness,
            "acp-session",
            &acp_permission(1, "write src/main.rs"),
            10,
        );
        registry.forget("runtime-2");
        assert!(registry.rows(20).is_empty());
    }

    #[test]
    fn queued_subagent_rows_report_the_outcome_the_record_holds() {
        let queued = vec![
            QueuedApproval {
                child_agent_id: "child-1".into(),
                tool: "shell".into(),
                subject: Some("git push".into()),
                queued_at_ms: 100,
                outcome: None,
            },
            QueuedApproval {
                child_agent_id: "child-2".into(),
                tool: "write_file".into(),
                subject: None,
                queued_at_ms: 200,
                outcome: Some(QueuedApprovalOutcome::Denied),
            },
        ];
        let rows = subagent_rows(&queued, 500);
        assert_eq!(rows[0].id, "supercode/subagent/child-1/100/0");
        assert_eq!(rows[0].harness.as_str(), HarnessId::SUPERCODE);
        assert_eq!(rows[0].status, ApprovalStatus::Pending);
        assert_eq!(rows[0].subject, "shell git push");
        assert_eq!(rows[0].age_ms, 400);
        assert_eq!(rows[0].options.len(), 3);
        assert_eq!(rows[1].status, ApprovalStatus::Denied);
        assert_eq!(rows[1].subject, "write_file");
        // A row nobody can still answer advertises no answers.
        assert!(rows[1].options.is_empty());
    }

    #[test]
    fn only_harnesses_whose_runtime_can_answer_are_listed() {
        assert!(lists_approvals(HarnessId::HERMES));
        assert!(lists_approvals(HarnessId::OPENCLAW));
        assert!(lists_approvals(HarnessId::CODEX));
        assert!(lists_approvals(HarnessId::OPENCODE));
        // ORC-2: Claude Code answers `can_use_tool` through the stream-json
        // control channel, so it lists like every other driven door.
        assert!(lists_approvals(HarnessId::CLAUDE_CODE));
        assert!(!lists_approvals("notaharness"));
        let harnesses = approval_harnesses();
        assert!(harnesses.iter().any(|id| id == HarnessId::HERMES));
        assert!(harnesses.iter().any(|id| id == HarnessId::CLAUDE_CODE));
    }

    // ---- ORCH-20: translating one decision onto a door's own options ------

    #[test]
    fn each_door_spells_a_uniform_decision_in_its_own_vocabulary() {
        // ACP selects by the request's own `kind`, not by the option id.
        let acp = vec![
            ApprovalOption {
                id: "proceed-once".into(),
                label: Some("Allow once".into()),
                kind: Some("allow_once".into()),
            },
            ApprovalOption {
                id: "refuse".into(),
                label: Some("Deny".into()),
                kind: Some("reject_once".into()),
            },
        ];
        let (option, response) = plan_reply(
            ApprovalDoor::Acp,
            &acp,
            &ApprovalChoice::Decision(ApprovalDecision::AllowOnce),
        )
        .expect("the request offers an allow-once option");
        assert_eq!(option, "proceed-once");
        assert_eq!(
            response,
            json!({"outcome": {"outcome": "selected", "optionId": "proceed-once"}}),
        );
        let (option, _) = plan_reply(
            ApprovalDoor::Acp,
            &acp,
            &ApprovalChoice::Decision(ApprovalDecision::Deny),
        )
        .expect("`reject_once` is how ACP spells deny");
        assert_eq!(option, "refuse");

        // opencode's own reply words, POSTed to its permissions route.
        let opencode = ["once", "always", "reject"]
            .map(ApprovalOption::bare)
            .to_vec();
        let (option, response) = plan_reply(
            ApprovalDoor::Opencode,
            &opencode,
            &ApprovalChoice::Decision(ApprovalDecision::AllowAlways),
        )
        .expect("opencode offers `always`");
        assert_eq!(option, "always");
        assert_eq!(response, json!({"response": "always"}));

        // supercode's own frontend broker takes the decision by name.
        let frontend = FRONTEND_DECISIONS.map(ApprovalOption::bare).to_vec();
        let (option, response) = plan_reply(
            ApprovalDoor::SupercodeFrontend,
            &frontend,
            &ApprovalChoice::Decision(ApprovalDecision::AllowAlways),
        )
        .expect("the frontend offers `allow_for_session`");
        assert_eq!(option, "allow_for_session");
        assert_eq!(response, json!({"decision": "allow_for_session"}));
    }

    #[test]
    fn a_decision_the_request_does_not_offer_names_the_ones_it_does() {
        let options = vec![
            ApprovalOption {
                id: "allow_once".into(),
                label: None,
                kind: Some("allow_once".into()),
            },
            ApprovalOption {
                id: "deny".into(),
                label: None,
                kind: Some("reject_once".into()),
            },
        ];
        let error = plan_reply(
            ApprovalDoor::Acp,
            &options,
            &ApprovalChoice::Decision(ApprovalDecision::AllowAlways),
        )
        .expect_err("this request has no allow-always option");
        assert_eq!(
            error,
            ApprovalResolveError::NotOffered {
                asked: "allow_always".into(),
                offered: vec!["allow_once".into(), "deny".into()],
            },
        );
        let message = error.to_string();
        assert!(message.contains("allow_always"), "{message}");
        assert!(message.contains("allow_once, deny"), "{message}");

        // An explicit option id is checked against the same list.
        let error = plan_reply(
            ApprovalDoor::Acp,
            &options,
            &ApprovalChoice::Option("allow_always".into()),
        )
        .expect_err("an unoffered token is not passed through");
        assert!(matches!(error, ApprovalResolveError::NotOffered { .. }));

        // …and an offered one is passed through untranslated.
        let (option, _) = plan_reply(
            ApprovalDoor::Acp,
            &options,
            &ApprovalChoice::Option("deny".into()),
        )
        .expect("`deny` is offered");
        assert_eq!(option, "deny");
    }

    #[test]
    fn a_door_that_enumerates_nothing_is_refused_rather_than_guessed_at() {
        // Codex's reverse approval request carries no options, and ORCH-9
        // invents no vocabulary for it — so neither does resolving.
        let error = plan_reply(
            ApprovalDoor::Codex,
            &[],
            &ApprovalChoice::Decision(ApprovalDecision::AllowOnce),
        )
        .expect_err("nothing to select");
        assert_eq!(error, ApprovalResolveError::NoOptions { door: "codex" });
        assert!(
            error.to_string().contains("harness.v1.runtimes.respond"),
            "{error}"
        );
    }

    #[test]
    fn the_registry_plans_an_answer_for_the_row_id_it_published() {
        let mut registry = ApprovalRegistry::new();
        let harness = HarnessId::from(HarnessId::HERMES);
        registry.observe(
            "runtime-1",
            &harness,
            "acp-session",
            &acp_permission(7, "rm -rf build"),
            1_000,
        );
        let row_id = registry.rows(1_000)[0].id.clone();
        assert_eq!(row_id, "runtime-1/7");

        let resolution = registry
            .resolution(
                &row_id,
                &ApprovalChoice::Decision(ApprovalDecision::AllowOnce),
            )
            .expect("the listed row plans an answer");
        assert_eq!(resolution.connection, "runtime-1");
        assert_eq!(resolution.request_id, json!(7));
        assert_eq!(resolution.option_id, "allow_once");
        assert_eq!(
            resolution.response,
            json!({"outcome": {"outcome": "selected", "optionId": "allow_once"}}),
        );
        // Planning is not answering: the row is still listed.
        assert_eq!(registry.rows(1_000).len(), 1);

        let error = registry
            .resolution(
                "runtime-1/999",
                &ApprovalChoice::Decision(ApprovalDecision::Deny),
            )
            .expect_err("no such row");
        assert_eq!(
            error,
            ApprovalResolveError::UnknownId("runtime-1/999".into())
        );

        // A queued subagent record is addressable but not answerable here.
        let error = registry
            .resolution(
                "supercode/subagent/child-1/100/0",
                &ApprovalChoice::Decision(ApprovalDecision::AllowOnce),
            )
            .expect_err("an audit record is not a door");
        assert!(matches!(
            error,
            ApprovalResolveError::QueuedSubagentRow(ref id)
                if id == "supercode/subagent/child-1/100/0"
        ));
        assert!(error.to_string().contains("audit trail"), "{error}");
    }

    #[test]
    fn a_decision_parses_from_both_the_wire_and_the_cli_spelling() {
        assert_eq!(
            ApprovalDecision::parse("allow-once"),
            Some(ApprovalDecision::AllowOnce)
        );
        assert_eq!(
            ApprovalDecision::parse("ALLOW_ALWAYS"),
            Some(ApprovalDecision::AllowAlways)
        );
        assert_eq!(
            ApprovalDecision::parse("deny"),
            Some(ApprovalDecision::Deny)
        );
        assert_eq!(ApprovalDecision::parse("maybe"), None);
        assert_eq!(
            serde_json::to_value(ApprovalDecision::AllowAlways).unwrap(),
            json!("allow_always"),
        );
    }

    #[test]
    fn a_query_filters_by_harness_and_by_session() {
        let rows = subagent_rows(
            &[QueuedApproval {
                child_agent_id: "child-1".into(),
                tool: "shell".into(),
                subject: None,
                queued_at_ms: 1,
                outcome: None,
            }],
            2,
        );
        let query = ApprovalsQuery {
            harness: Some(HarnessId::SUPERCODE.into()),
            session: Some("child-1".into()),
        };
        assert!(query.matches(&rows[0]));
        let other = ApprovalsQuery {
            harness: Some(HarnessId::HERMES.into()),
            session: None,
        };
        assert!(!other.matches(&rows[0]));
    }
}