supercode-harness 0.4.17

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
//! Controlled-tier conversations (Domain 11, concept 5) — `new`, `reset`,
//! `archive`, `delete` over one uniform door.
//!
//! Charter (`docs/plans/orchestration-domain-11-2026-09-02.md` §0.4):
//! **every mutation here is the harness's OWN verb.** supercode never writes
//! another harness's session store by hand; it runs the harness's CLI, calls
//! the harness's HTTP API, or types the harness's slash command into a LIVE
//! driven session, then re-reads the row the harness's own store now holds.
//!
//! The doors, per harness, at the pinned versions:
//!
//! | harness | new | reset | archive | delete |
//! |---|---|---|---|---|
//! | claude-code | refused → `runtimes.start` | refused | refused | refused |
//! | codex | refused → `runtimes.start` | refused | `codex archive <id>` | `codex delete <id>` |
//! | opencode | refused → `runtimes.start` | refused | `PATCH /session/<id>` | `DELETE /session/<id>` |
//! | hermes | refused (gateway-only) | `/reset` in a live session | refused | `hermes sessions delete <id>` |
//! | openclaw | `/new` in a live session | `/reset` in a live session | refused | refused |
//! | orchestrator | its daemon's operator door | its daemon's operator door | refused | refused |
//! | supercode | refused → `runtimes.start` | refused | own store | own store |
//!
//! Three rules the whole tier inherits from [`crate::jobs_control`]:
//!
//! 1. **The harness's answer is the answer.** After the door reports success
//!    the conversation is re-read through the ORCH-6 discovery loader and
//!    returned. A delete that leaves the row behind, or an archive the store
//!    did not record, is a FAILURE — never a silent success.
//! 2. **The door is narrated.** Every outcome carries `ran`: the exact argv,
//!    HTTP request line, slash command, or store call that was performed,
//!    with any credential rendered as `<redacted>`.
//! 3. **A verb the harness has no door for is refused**
//!    ([`SessionControlError::Unsupported`] → `UnsupportedAction`), with the
//!    reason and the door that DOES exist, never a silent no-op.
//!
//! ## Why some cells are refused at the pin
//!
//! * **`hermes sessions archive`** exists but is a BULK filter verb
//!   (`--older-than`, `--title`, `--cwd`, …) with no per-session selector, so
//!   a uniform "archive THIS conversation" cannot be expressed through it.
//!   `hermes sessions delete <id>` is per-session and IS used.
//!   (Pinned help fixture: `crates/harness/src/parity/fixtures/hermes-help.txt`,
//!   section `$ hermes sessions --help`.)
//! * **OpenClaw** registers only `sessions list | cleanup | tail |
//!   export-trajectory | compact` at v2026.7.1-2 — no `archive`, no `delete`.
//! * **Claude Code** publishes no conversation lifecycle verb at all: its
//!   sessions expire on a retention window it owns.
//! * **The orchestrator** has no archive and no delete BY MODEL: a binding
//!   (`docs/ORCHESTRATOR-IR.md` §2.5) ends, and the transcript belongs to the
//!   worker harness the binding addresses. `new` and `reset` DO exist — they
//!   are the two chat commands its reducer applies to a binding (§4.5) — and
//!   ORC-13 opened the door that reaches them from outside a chat: the
//!   daemon's operator socket, or the package's own CLI when it is down
//!   ([`crate::orchestrator_door`]). The orchestrator's conversation is a
//!   BINDING, so it is named by its SURFACE key
//!   (`platform|chat_type|chat_id|thread_id|participant_id`), never by a
//!   worker session id — `--surface`, not `--session`.
//! * **`new` / `reset` on the file-store harnesses** is not a missing verb —
//!   it is a DIFFERENT door that already exists: `harness.v1.runtimes.start`.
//!   Refusing while naming it keeps one way to do one thing.
//!
//! ## A slash command is only sent when the harness's door advertises it
//!
//! Both gateway harnesses expose `/new` and `/reset` IN CHAT, but the door
//! supercode drives is each one's ACP adapter, and the two adapters do not
//! carry the same set. Read from the harnesses themselves, 2026-09-03:
//!
//! * **OpenClaw** (`openclaw@2026.7.1-2`, `dist/commands-*.js`
//!   `BASE_AVAILABLE_COMMANDS`) advertises BOTH `new` ("Reset the session
//!   (/reset)") and `reset` on its ACP door. Both are supported.
//! * **Hermes** (`acp_adapter/server.py` `_SLASH_COMMANDS` /
//!   `_handle_slash_command`) advertises `reset` and NOT `new` — `/new` lives
//!   only in `gateway/slash_commands.py`, and the adapter comments that an
//!   unrecognized command "falls through to the LLM (the user may have typed
//!   `/something` as prose)". `sessions.new` on hermes is therefore refused:
//!   sending it would put the literal text `/new` in front of the model, which
//!   is the silent no-op this tier exists to prevent.
//!
//! The two doors also differ in EFFECT, and neither is re-interpreted here:
//! hermes's ACP `/reset` clears the conversation and keeps the session row,
//! while the gateway's `/reset` rotates the session id. supercode drives the
//! door it can reach and reports what that door did.

use std::path::{Path, PathBuf};
use std::process::Command;

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

use crate::{DiscoveryQuery, HarnessHomes, HarnessId};

/// Environment variable overriding the `codex` executable (tests).
pub const CODEX_BIN_ENV: &str = "SUPERCODE_CODEX_BIN";
/// Environment variable overriding the `hermes` executable (tests).
pub const HERMES_BIN_ENV: &str = "SUPERCODE_HERMES_BIN";

/// One uniform conversation-lifecycle verb.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionVerb {
    /// Open a fresh conversation on the same surface.
    New,
    /// Clear the conversation while keeping the surface.
    Reset,
    /// Soft-hide the conversation, keeping its transcript.
    Archive,
    /// Permanently remove the conversation.
    Delete,
}

impl SessionVerb {
    /// Uniform spelling used in the RPC method and in outcomes.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::New => "new",
            Self::Reset => "reset",
            Self::Archive => "archive",
            Self::Delete => "delete",
        }
    }

    /// The RPC method this verb is spelled as.
    pub const fn method(self) -> &'static str {
        match self {
            Self::New => "harness.v1.sessions.new",
            Self::Reset => "harness.v1.sessions.reset",
            Self::Archive => "harness.v1.sessions.archive",
            Self::Delete => "harness.v1.sessions.delete",
        }
    }

    /// Whether the verb names an existing conversation.
    const fn needs_session(self) -> bool {
        !matches!(self, Self::New)
    }
}

/// The door one `(harness, verb)` pair goes through.
///
/// The service needs this BEFORE it acts: a [`SessionDoor::Live`] verb is
/// typed into an already-open runtime connection the service owns, while
/// every other door is self-contained in this module.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionDoor {
    /// The harness's own CLI verb, run as a subprocess.
    Cli,
    /// The harness's own HTTP API.
    Http,
    /// The harness's own slash command, typed into a LIVE driven session.
    /// Carries the exact command text (`/new`, `/reset`).
    Live(&'static str),
    /// supercode's own session store (the Domain 5 verb).
    Store,
    /// The orchestrator daemon's own operator door (ORC-13): its local socket
    /// while the daemon is up, its package's CLI when it is down. Both land in
    /// the reducer that owns bindings, and in the `save()` that owns the
    /// folder.
    Daemon,
}

/// One mutating request, in the uniform Domain 11 vocabulary.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionMutation {
    /// Harness that owns the conversation.
    pub harness: String,
    /// Harness-native conversation id, or supercode session name. Required
    /// for every verb but `new`.
    #[serde(default)]
    pub session: Option<String>,
    /// Working directory the new conversation belongs to (`new`).
    #[serde(default)]
    pub cwd: Option<PathBuf>,
    /// Live runtime connection id, for the slash-command doors.
    #[serde(default)]
    pub connection: Option<String>,
    /// Already-running OpenCode server this conversation lives on. Without
    /// it the HTTP door is refused rather than guessing an endpoint.
    #[serde(default)]
    pub base_url: Option<String>,
    /// Bearer credential for the OpenCode server, when it requires one. Never
    /// narrated.
    #[serde(default)]
    pub bearer: Option<String>,
    /// Hermes profile name — a profile IS a full `HERMES_HOME`. For the
    /// orchestrator it is the profile FOLDER the binding belongs to.
    #[serde(default)]
    pub profile: Option<String>,
    /// ORC-13: the surface key a conversation is bound to, in the IR's own
    /// rendering (`platform|chat_type|chat_id|thread_id|participant_id`).
    /// This is how the orchestrator's conversations are named — its binding
    /// has no id of its own, only the surface it holds.
    #[serde(default)]
    pub surface: Option<String>,
    /// Storage roots, so an isolated home is addressed the same way the read
    /// side addresses it.
    #[serde(default)]
    pub homes: HarnessHomes,
}

/// What one mutation did, with the conversation re-read afterwards.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionMutationOutcome {
    /// Harness whose door was used.
    pub harness: String,
    /// Uniform verb that was asked for.
    pub verb: String,
    /// The exact door that was used, credentials redacted.
    pub ran: String,
    /// Conversation the verb acted on.
    pub session: String,
    /// The conversation as the harness's own store reports it AFTER the verb.
    /// Absent for `delete`, and for a `new`/`reset` whose fresh conversation
    /// the harness has not committed to its store yet.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub row: Option<Value>,
    /// `true` on a successful `archive`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub archived: Option<bool>,
    /// `true` on a successful `delete`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deleted: Option<bool>,
}

/// Why a mutation could not be performed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionControlError {
    /// The harness has no door for what was asked (refused, never faked).
    Unsupported(String),
    /// The request itself is incoherent.
    Invalid(String),
    /// The harness's door ran and failed; the message carries its own error.
    Failed(String),
}

impl std::fmt::Display for SessionControlError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unsupported(message) | Self::Invalid(message) | Self::Failed(message) => {
                formatter.write_str(message)
            }
        }
    }
}

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

type Result<T> = std::result::Result<T, SessionControlError>;

/// Harnesses whose conversations supercode can mutate through at least one of
/// their own doors. Strictly narrower than the set it can READ.
pub const CONTROLLED_SESSION_HARNESSES: &[&str] = &[
    HarnessId::CODEX,
    HarnessId::OPENCODE,
    HarnessId::HERMES,
    HarnessId::OPENCLAW,
    HarnessId::ORCHESTRATOR,
    HarnessId::SUPERCODE,
];

/// Every harness the compiled registry carries.
///
/// Spelled out rather than read back from [`crate::harness_support_registry`]:
/// this door table is one of the INPUTS that registry is built from (the
/// `conversation` concept block reads [`controlled_methods`]), so looking the
/// registry up from here would recurse forever. A unit test below pins the two
/// lists together.
const REGISTERED_HARNESSES: &[&str] = &[
    HarnessId::CLAUDE_CODE,
    HarnessId::CODEX,
    HarnessId::PI,
    HarnessId::OPENCODE,
    HarnessId::GROK,
    HarnessId::GEMINI,
    HarnessId::GOOSE,
    HarnessId::HERMES,
    HarnessId::OPENCLAW,
    HarnessId::ORCHESTRATOR,
    HarnessId::SUPERCODE,
];

/// Whether `harness` publishes a door for at least one conversation verb.
pub fn supports_session_control(harness: &str) -> bool {
    CONTROLLED_SESSION_HARNESSES.contains(&harness)
}

/// Every uniform verb, in declaration order.
pub const ALL_SESSION_VERBS: [SessionVerb; 4] = [
    SessionVerb::New,
    SessionVerb::Reset,
    SessionVerb::Archive,
    SessionVerb::Delete,
];

/// Every uniform verb `harness` can actually perform, in declaration order.
/// Empty for a harness with no door at all.
pub fn controlled_verbs(harness: &str) -> Vec<&'static str> {
    ALL_SESSION_VERBS
        .into_iter()
        .filter(|verb| door(harness, *verb).is_ok())
        .map(SessionVerb::as_str)
        .collect()
}

/// The RPC methods `harness` actually answers for the controlled tier. This is
/// what the registry block advertises, so a method can never appear in the
/// descriptor without a door behind it.
pub fn controlled_methods(harness: &str) -> Vec<&'static str> {
    ALL_SESSION_VERBS
        .into_iter()
        .filter(|verb| door(harness, *verb).is_ok())
        .map(SessionVerb::method)
        .collect()
}

/// Which door this `(harness, verb)` pair goes through, or WHY the harness
/// refuses it.
///
/// This is the single table the whole tier is derived from: the service, the
/// registry block, and the refusal messages all read it, so a door can never
/// be advertised in one place and missing in another.
pub fn door(harness: &str, verb: SessionVerb) -> Result<SessionDoor> {
    match (harness, verb) {
        // --- codex: two native CLI verbs, no `new`/`reset` concept ---------
        (HarnessId::CODEX, SessionVerb::Archive | SessionVerb::Delete) => Ok(SessionDoor::Cli),
        // --- opencode: its own HTTP session API ---------------------------
        (HarnessId::OPENCODE, SessionVerb::Archive | SessionVerb::Delete) => Ok(SessionDoor::Http),
        // --- the live slash-command doors, each checked against what that
        //     harness's ACP door ACTUALLY advertises (module header) --------
        (HarnessId::OPENCLAW, SessionVerb::New) => Ok(SessionDoor::Live("/new")),
        (HarnessId::HERMES | HarnessId::OPENCLAW, SessionVerb::Reset) => {
            Ok(SessionDoor::Live("/reset"))
        }
        (HarnessId::HERMES, SessionVerb::New) => Err(SessionControlError::Unsupported(
            "hermes's ACP door advertises help, model, tools, context, reset, compress, steer, \
             queue and version; `/new` is a GATEWAY command \
             (`gateway/slash_commands.py::_handle_reset_command`) and hermes's ACP adapter sends \
             any UNRECOGNIZED `/word` to the model as prose. Typing `/new` there would be a \
             silent no-op dressed as a chat turn, so supercode refuses. `sessions.reset` IS \
             advertised on that door and is supported"
                .into(),
        )),
        (HarnessId::HERMES, SessionVerb::Delete) => Ok(SessionDoor::Cli),
        (HarnessId::HERMES, SessionVerb::Archive) => Err(SessionControlError::Unsupported(
            "hermes 0.21.0 registers `hermes sessions archive`, but it is a BULK filter verb \
             (--older-than / --title / --cwd / ...) with no per-session selector, so archiving \
             ONE conversation cannot be expressed through it. `sessions.delete` is per-session \
             and is supported"
                .into(),
        )),
        // --- openclaw: no lifecycle verb at the pin -----------------------
        (HarnessId::OPENCLAW, SessionVerb::Archive | SessionVerb::Delete) => {
            Err(SessionControlError::Unsupported(format!(
                "openclaw v2026.7.1-2 registers `sessions list | cleanup | tail | \
                 export-trajectory | compact` and no `archive` or `delete`, so supercode refuses \
                 `sessions.{}` rather than inventing store-maintenance semantics for it",
                verb.as_str()
            )))
        }
        // --- supercode's own store ----------------------------------------
        (HarnessId::SUPERCODE, SessionVerb::Archive | SessionVerb::Delete) => {
            Ok(SessionDoor::Store)
        }
        // --- claude-code: no lifecycle verb at all -------------------------
        (HarnessId::CLAUDE_CODE, SessionVerb::Archive | SessionVerb::Delete) => {
            Err(SessionControlError::Unsupported(format!(
                "claude-code publishes no conversation lifecycle verb: its sessions are removed \
                 by a RETENTION WINDOW the harness itself owns (`cleanupPeriodDays`), so \
                 supercode refuses `sessions.{}` rather than deleting files behind the \
                 harness's back",
                verb.as_str()
            )))
        }
        // --- the orchestrator: its lifecycle verbs are the DAEMON's -------
        (HarnessId::ORCHESTRATOR, SessionVerb::New | SessionVerb::Reset) => Ok(SessionDoor::Daemon),
        (HarnessId::ORCHESTRATOR, verb) => Err(SessionControlError::Unsupported(format!(
            "the orchestrator's conversations are BINDINGS its daemon holds \
             (`docs/ORCHESTRATOR-IR.md` §2.5): a binding is never archived or deleted — it \
             ENDS, and the transcript belongs to the WORKER harness it addresses, which is \
             where `sessions.{}` is performed. `sessions.new` and `sessions.reset` end a \
             binding through the daemon's own operator door and are supported",
            verb.as_str()
        ))),
        (other, verb) if !REGISTERED_HARNESSES.contains(&other) => {
            Err(SessionControlError::Unsupported(format!(
                "`{other}` is not a registered harness, so `sessions.{}` has no door to go \
                 through",
                verb.as_str()
            )))
        }
        // --- `new` / `reset` where the door is `runtimes.start` -----------
        (_, SessionVerb::New) => Err(SessionControlError::Unsupported(format!(
            "`{harness}` opens a conversation through `harness.v1.runtimes.start` (CLI: \
             `supercode run --harness {harness}`), not through a slash command; `sessions.new` \
             is only for the gateway harnesses whose surface outlives the conversation"
        ))),
        (_, SessionVerb::Reset) => Err(SessionControlError::Unsupported(format!(
            "`{harness}` has no conversation reset verb: a fresh conversation is a new runtime \
             (`harness.v1.runtimes.start`). `sessions.reset` is only for the gateway harnesses \
             whose surface outlives the conversation"
        ))),
        (other, verb) => Err(SessionControlError::Unsupported(format!(
            "`{other}` publishes no door for `sessions.{}`; conversation mutation is supported \
             for: {}",
            verb.as_str(),
            CONTROLLED_SESSION_HARNESSES.join(", ")
        ))),
    }
}

// ---------------------------------------------------------------------------
// Command narration (the same contract `jobs_control` established)
// ---------------------------------------------------------------------------

fn shell_quote(value: &str) -> String {
    if !value.is_empty()
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "-_./:@=+,".contains(c))
    {
        return value.to_string();
    }
    format!("'{}'", value.replace('\'', "'\\''"))
}

/// A harness CLI invocation, ready to run and ready to narrate.
#[derive(Debug, Clone)]
struct HarnessCommand {
    program: String,
    args: Vec<String>,
    env: Vec<(String, String)>,
}

impl HarnessCommand {
    fn new(program: impl Into<String>) -> Self {
        Self {
            program: program.into(),
            args: Vec::new(),
            env: Vec::new(),
        }
    }

    fn args<I: IntoIterator<Item = S>, S: Into<String>>(&mut self, values: I) -> &mut Self {
        for value in values {
            self.args.push(value.into());
        }
        self
    }

    fn env(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.env.push((key.into(), value.into()));
        self
    }

    /// The narration: exactly what ran.
    fn narrate(&self) -> String {
        let mut line = shell_quote(&self.program);
        for arg in &self.args {
            line.push(' ');
            line.push_str(&shell_quote(arg));
        }
        line
    }

    /// Run it, returning stdout on success and the harness's own stderr on
    /// failure.
    fn run(&self) -> Result<String> {
        let mut command = Command::new(&self.program);
        command.args(&self.args);
        for (key, value) in &self.env {
            command.env(key, value);
        }
        command.stdin(std::process::Stdio::null());
        let output = command.output().map_err(|error| {
            SessionControlError::Failed(format!(
                "`{}` could not be executed: {error}",
                self.narrate()
            ))
        })?;
        if output.status.success() {
            return Ok(String::from_utf8_lossy(&output.stdout).into_owned());
        }
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
        let detail = if stderr.is_empty() { stdout } else { stderr };
        Err(SessionControlError::Failed(format!(
            "`{}` failed ({}): {}",
            self.narrate(),
            output.status,
            if detail.is_empty() {
                "the harness printed nothing".to_string()
            } else {
                detail
            }
        )))
    }
}

/// The harness's own executable, with a `SUPERCODE_<HARNESS>_BIN` override so
/// a fake CLI can stand in under test without touching PATH. The registry
/// names each harness's binary family in its runtime launch; the lifecycle
/// verbs live on the base CLI, so an `-acp` bridge suffix is stripped.
pub fn harness_program(harness: &str) -> Result<String> {
    let variable = match harness {
        HarnessId::CODEX => CODEX_BIN_ENV,
        HarnessId::HERMES => HERMES_BIN_ENV,
        other => {
            return Err(SessionControlError::Unsupported(format!(
                "`{other}` has no conversation CLI supercode calls"
            )));
        }
    };
    if let Some(over) = std::env::var_os(variable) {
        let over = over.to_string_lossy().trim().to_string();
        if !over.is_empty() {
            return Ok(over);
        }
    }
    let program = crate::harness_support(harness)
        .and_then(|descriptor| descriptor.runtime.default_launch)
        .map(|launch| launch.program)
        .ok_or_else(|| {
            SessionControlError::Unsupported(format!(
                "the registry has no launch for `{harness}`, so its CLI cannot be located"
            ))
        })?;
    Ok(program.strip_suffix("-acp").unwrap_or(&program).to_string())
}

/// `HERMES_HOME` for this request: the profile's own home when one is named
/// (upstream treats a profile as a full `HERMES_HOME`), else the install root.
/// `HarnessHomes::hermes` addresses `state.db`; `HERMES_HOME` is its parent —
/// the same derivation the read side uses.
fn hermes_home(mutation: &SessionMutation) -> PathBuf {
    let root = mutation
        .homes
        .hermes
        .parent()
        .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
    match mutation.profile.as_deref() {
        Some(profile) => root.join("profiles").join(profile),
        None => root,
    }
}

/// `CODEX_HOME` for this request. `HarnessHomes::codex` addresses the
/// `sessions/` directory inside it; codex itself wants the parent.
fn codex_home(mutation: &SessionMutation) -> PathBuf {
    let root = &mutation.homes.codex;
    if root.file_name().is_some_and(|name| name == "sessions") {
        return root
            .parent()
            .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
    }
    root.clone()
}

// ---------------------------------------------------------------------------
// Re-reading the harness's own store
// ---------------------------------------------------------------------------

/// The conversation as the harness's own store reports it right now, through
/// the ORCH-6 discovery loader. `None` means the store no longer holds it.
fn read_back(mutation: &SessionMutation, session: &str) -> Result<Option<Value>> {
    if mutation.harness == HarnessId::SUPERCODE {
        let store = crate::SessionStore::open(&mutation.homes.supercode).map_err(|error| {
            SessionControlError::Failed(format!("supercode's session store is unreadable: {error}"))
        })?;
        return Ok(store
            .list()
            .into_iter()
            .find(|info| info.name == session)
            .map(|info| serde_json::to_value(info).unwrap_or(Value::Null)));
    }
    let page = crate::discover_session_page(&DiscoveryQuery {
        harnesses: vec![HarnessId::new(mutation.harness.clone())],
        homes: mutation.homes.clone(),
        include_child_sessions: true,
        ..DiscoveryQuery::default()
    })
    .map_err(|error| {
        SessionControlError::Failed(format!(
            "the {} conversation store could not be re-read: {error}",
            mutation.harness
        ))
    })?;
    Ok(page
        .sessions
        .into_iter()
        .find(|descriptor| descriptor.locator.session_id == session)
        .map(|descriptor| serde_json::to_value(descriptor).unwrap_or(Value::Null)))
}

// ---------------------------------------------------------------------------
// The mutation itself
// ---------------------------------------------------------------------------

/// Perform one conversation mutation through the harness's own door.
///
/// [`SessionDoor::Live`] verbs are NOT handled here: they need an open runtime
/// connection, which only the service owns. Callers check [`door`] first and
/// route those to `harness.v1.runtimes.send_input`; asking for one here is an
/// [`SessionControlError::Invalid`], because it names a door this function
/// cannot open rather than a door the harness lacks.
pub async fn mutate(
    verb: SessionVerb,
    mutation: &SessionMutation,
) -> Result<SessionMutationOutcome> {
    let door = door(&mutation.harness, verb)?;
    let session = mutation.session.as_deref().unwrap_or("").trim().to_string();
    // The orchestrator's conversation is named by its SURFACE, not by an id:
    // `needs_session` is about a store row, and a binding is not one.
    if verb.needs_session() && session.is_empty() && !matches!(door, SessionDoor::Daemon) {
        return Err(SessionControlError::Invalid(format!(
            "`sessions.{}` needs the conversation to act on",
            verb.as_str()
        )));
    }
    match door {
        SessionDoor::Live(command) => Err(SessionControlError::Invalid(format!(
            "`{}` performs `sessions.{}` by typing `{command}` into a LIVE driven session; call \
             it with an open runtime `connection`",
            mutation.harness,
            verb.as_str()
        ))),
        SessionDoor::Cli => {
            let command = cli_command(verb, mutation, &session)?;
            let ran = command.narrate();
            command.run()?;
            let row = read_back(mutation, &session)?;
            finish(verb, mutation, session, ran, row)
        }
        SessionDoor::Store => {
            let store = crate::SessionStore::open(&mutation.homes.supercode).map_err(|error| {
                SessionControlError::Failed(format!(
                    "supercode's session store is unreadable: {error}"
                ))
            })?;
            let ran = format!(
                "supercode store {} {}",
                verb.as_str(),
                shell_quote(&session)
            );
            match verb {
                SessionVerb::Archive => store.archive(&session),
                SessionVerb::Delete => store.delete(&session),
                _ => unreachable!("the door table only routes archive/delete to the store"),
            }
            .map_err(|error| SessionControlError::Failed(format!("`{ran}` failed: {error}")))?;
            let row = read_back(mutation, &session)?;
            finish(verb, mutation, session, ran, row)
        }
        SessionDoor::Daemon => orchestrator_mutate(verb, mutation),
        SessionDoor::Http => {
            let ran = opencode_call(verb, mutation, &session).await?;
            // The HTTP door re-reads through OPENCODE'S OWN API, not through
            // the file/SQLite loader: the running server owns the store, and
            // its answer is the only one that can be current.
            let row = opencode_read_back(mutation, &session).await?;
            finish(verb, mutation, session, ran, row)
        }
    }
}

// ---------------------------------------------------------------------------
// The orchestrator — its own daemon's operator door (ORC-13)
// ---------------------------------------------------------------------------

/// `sessions.new|reset --harness orchestrator --surface <key>`.
///
/// The verb ends the LIVE binding on that surface, which is exactly what the
/// `/new` and `/reset` chat commands do when a human types them into the
/// conversation (`docs/ORCHESTRATOR-IR.md` §4.5) — the same reducer, reached
/// through the daemon's operator door instead of through a chat message.
/// Afterwards the binding is re-read through the ORCH-6 discovery loader, the
/// same reader `sessions list --harness orchestrator` uses.
fn orchestrator_mutate(
    verb: SessionVerb,
    mutation: &SessionMutation,
) -> Result<SessionMutationOutcome> {
    let surface = mutation
        .surface
        .as_deref()
        .map(str::trim)
        .filter(|surface| !surface.is_empty())
        .ok_or_else(|| {
            SessionControlError::Invalid(format!(
                "an orchestrator conversation is a BINDING on a surface, not a store row: \
                 `sessions.{}` needs `--surface \
                 <platform|chat_type|chat_id|thread_id|participant_id>` \
                 (`supercode sessions list --harness orchestrator` prints the surface of every \
                 binding)",
                verb.as_str()
            ))
        })?;
    let root = mutation.homes.orchestrator.clone();
    let profile = mutation
        .profile
        .as_deref()
        .map(str::trim)
        .filter(|profile| !profile.is_empty())
        .unwrap_or("default");
    let op = match verb {
        SessionVerb::New => "sessions.new",
        SessionVerb::Reset => "sessions.reset",
        other => {
            return Err(SessionControlError::Unsupported(format!(
                "the orchestrator has no door for `sessions.{}`",
                other.as_str()
            )))
        }
    };
    let args = serde_json::json!({ "surface": surface });
    let answer = crate::orchestrator_door::call(&root, op, &args, profile).map_err(|error| {
        match error {
            // The package refused: its sentence is the answer, exactly as a
            // harness's own stderr is for the CLI doors.
            crate::orchestrator_door::DoorError::Refused(message) => {
                SessionControlError::Failed(message)
            }
            crate::orchestrator_door::DoorError::Failed(message) => {
                SessionControlError::Failed(message)
            }
        }
    })?;
    let ran = format!("{} [{}]", answer.ran, answer.door.as_str());
    let session = answer
        .result
        .pointer("/binding/session_id")
        .and_then(Value::as_str)
        .filter(|id| !id.is_empty())
        .unwrap_or(surface)
        .to_string();
    // The FOLDER is the answer: the ended binding, read back through the
    // discovery loader on its own surface.
    let row = orchestrator_read_back(mutation, surface, &ran)?;
    Ok(SessionMutationOutcome {
        harness: mutation.harness.clone(),
        verb: verb.as_str().to_string(),
        ran,
        session,
        row,
        archived: None,
        deleted: None,
    })
}

/// The newest binding on `surface`, through the ORCH-6 discovery loader.
///
/// A binding is addressed by its surface, and the loader renders that surface
/// as Hermes's `agent:<profile>:<platform>:<chat_type>[:…]` key, so the match
/// is on the surface COLUMNS the descriptor carries, never on a string the
/// caller typed.
fn orchestrator_read_back(
    mutation: &SessionMutation,
    surface: &str,
    ran: &str,
) -> Result<Option<Value>> {
    let page = crate::discover_session_page(&DiscoveryQuery {
        harnesses: vec![HarnessId::new(mutation.harness.clone())],
        homes: mutation.homes.clone(),
        include_child_sessions: true,
        ..DiscoveryQuery::default()
    })
    .map_err(|error| {
        SessionControlError::Failed(format!(
            "`{ran}` succeeded but the orchestrator's binding store could not be re-read: {error}"
        ))
    })?;
    let wanted = surface_columns(surface);
    let mut best: Option<Value> = None;
    let mut best_at = 0;
    for descriptor in page.sessions {
        let key = descriptor.nouns.surface.as_ref();
        let found = [
            key.and_then(|k| k.platform.clone()).unwrap_or_default(),
            key.and_then(|k| k.kind.clone()).unwrap_or_default(),
            key.and_then(|k| k.chat_id.clone()).unwrap_or_default(),
            key.and_then(|k| k.thread_id.clone()).unwrap_or_default(),
            key.and_then(|k| k.participant_id.clone())
                .unwrap_or_default(),
        ];
        if found != wanted {
            continue;
        }
        let at = descriptor.updated_at_ms.unwrap_or_default();
        if best.is_none() || at >= best_at {
            best_at = at;
            best = Some(serde_json::to_value(&descriptor).unwrap_or(Value::Null));
        }
    }
    Ok(best)
}

/// A surface key string split into its five columns, empty for the absent
/// ones — the inverse of the IR's `surfaceKeyString`.
fn surface_columns(surface: &str) -> [String; 5] {
    let mut parts = surface.split('|');
    std::array::from_fn(|_| parts.next().unwrap_or("").to_string())
}

/// Turn a completed door into the outcome, enforcing that the harness's own
/// store agrees with what the door claimed.
fn finish(
    verb: SessionVerb,
    mutation: &SessionMutation,
    session: String,
    ran: String,
    row: Option<Value>,
) -> Result<SessionMutationOutcome> {
    let outcome = SessionMutationOutcome {
        harness: mutation.harness.clone(),
        verb: verb.as_str().to_string(),
        ran: ran.clone(),
        session: session.clone(),
        row: row.clone(),
        archived: None,
        deleted: None,
    };
    match verb {
        SessionVerb::Delete => {
            if row.is_some() {
                return Err(SessionControlError::Failed(format!(
                    "`{ran}` reported success but `{session}` is still in {}'s conversation store",
                    mutation.harness
                )));
            }
            Ok(SessionMutationOutcome {
                row: None,
                deleted: Some(true),
                ..outcome
            })
        }
        SessionVerb::Archive => {
            if !archive_took_effect(mutation, row.as_ref()) {
                return Err(SessionControlError::Failed(format!(
                    "`{ran}` reported success but {}'s store still lists `{session}` as an \
                     active conversation",
                    mutation.harness
                )));
            }
            Ok(SessionMutationOutcome {
                archived: Some(true),
                ..outcome
            })
        }
        SessionVerb::New | SessionVerb::Reset => Ok(outcome),
    }
}

/// Did the harness's own store record the archive?
///
/// Each harness answers in its own terms and none of them is guessed at:
///
/// * **supercode** publishes an `archived` flag on the row.
/// * **codex** MOVES the rollout out of `$CODEX_HOME/sessions` into
///   `archived_sessions/` (executed 2026-09-03 on an isolated `CODEX_HOME`;
///   receipt `docs/interop/research/orch19-codex-sessions-receipt-*.json`), so
///   its disappearance from the active listing IS the store's answer.
/// * **opencode** stamps `time.archived` on the session record its own API
///   returns; a `404` (the server dropped it) also counts as archived.
fn archive_took_effect(mutation: &SessionMutation, row: Option<&Value>) -> bool {
    let Some(row) = row else {
        return true;
    };
    if mutation.harness == HarnessId::SUPERCODE {
        return row
            .get("archived")
            .and_then(Value::as_bool)
            .unwrap_or(false);
    }
    row.pointer("/time/archived")
        .is_some_and(|value| !value.is_null())
}

/// Translate one verb onto the harness's own CLI invocation.
fn cli_command(
    verb: SessionVerb,
    mutation: &SessionMutation,
    session: &str,
) -> Result<HarnessCommand> {
    match (mutation.harness.as_str(), verb) {
        (HarnessId::CODEX, SessionVerb::Archive | SessionVerb::Delete) => {
            let mut command = HarnessCommand::new(harness_program(HarnessId::CODEX)?);
            command.env("CODEX_HOME", codex_home(mutation).to_string_lossy());
            command.args([verb.as_str(), session]);
            if matches!(verb, SessionVerb::Delete) {
                // Measured 2026-09-03 on codex 0.152: without `--force` the
                // delete refuses outright off a TTY ("cannot confirm session
                // deletion without an interactive terminal"). supercode never
                // drives a prompt it cannot see, so it passes the harness's
                // own non-interactive flag; the caller already asked for a
                // delete, and the verification read is what proves it landed.
                command.args(["--force"]);
            }
            Ok(command)
        }
        (HarnessId::HERMES, SessionVerb::Delete) => {
            let mut command = HarnessCommand::new(harness_program(HarnessId::HERMES)?);
            command.env("HERMES_HOME", hermes_home(mutation).to_string_lossy());
            // `--yes` skips hermes's own interactive confirmation; supercode
            // never drives a prompt it cannot see.
            command.args(["sessions", "delete", session, "--yes"]);
            Ok(command)
        }
        (harness, verb) => Err(SessionControlError::Unsupported(format!(
            "`{harness}` has no CLI verb for `sessions.{}`",
            verb.as_str()
        ))),
    }
}

// ---------------------------------------------------------------------------
// OpenCode — its own HTTP session API
// ---------------------------------------------------------------------------

/// OpenCode's running server, resolved the same way for the mutation and for
/// the re-read that verifies it.
///
/// `base_url` is required — an endpoint is a fact about the caller's
/// environment, and guessing one would mutate whichever OpenCode happened to
/// be listening. The bearer, when present, is sent as a sensitive header and
/// never appears in the narration.
fn opencode_endpoint(mutation: &SessionMutation) -> Result<(String, reqwest::Client)> {
    let base = mutation
        .base_url
        .as_deref()
        .map(|url| url.trim_end_matches('/').to_string())
        .ok_or_else(|| {
            SessionControlError::Invalid(
                "opencode conversations are mutated through its own running server: pass \
                 `base_url` (the address `runtimes.start` reports, or an `opencode serve` you \
                 already run)"
                    .into(),
            )
        })?;
    let mut headers = reqwest::header::HeaderMap::new();
    if let Some(bearer) = mutation.bearer.as_deref().filter(|t| !t.trim().is_empty()) {
        let mut value = reqwest::header::HeaderValue::from_str(&format!("Bearer {bearer}"))
            .map_err(|_| {
                SessionControlError::Invalid(
                    "the opencode bearer token is not a valid header value".into(),
                )
            })?;
        value.set_sensitive(true);
        headers.insert(reqwest::header::AUTHORIZATION, value);
    }
    let client = reqwest::Client::builder()
        .default_headers(headers)
        .build()
        .map_err(|error| {
            SessionControlError::Failed(format!("could not build the HTTP client: {error}"))
        })?;
    Ok((base, client))
}

/// Re-read one conversation through OPENCODE'S OWN session API.
///
/// `None` means the server no longer holds it (`404`), which is exactly what a
/// successful delete must produce. Anything else the server says — including
/// the `time.archived` stamp an archive leaves — comes back verbatim.
async fn opencode_read_back(mutation: &SessionMutation, session: &str) -> Result<Option<Value>> {
    let (base, client) = opencode_endpoint(mutation)?;
    let url = format!("{base}/session/{session}");
    let mut request = client.get(&url);
    if let Some(cwd) = mutation.cwd.as_ref() {
        request = request.query(&[("directory", cwd.to_string_lossy().into_owned())]);
    }
    let response = request.send().await.map_err(|error| {
        SessionControlError::Failed(format!("`GET {url}` could not be sent: {error}"))
    })?;
    if response.status() == reqwest::StatusCode::NOT_FOUND {
        return Ok(None);
    }
    let status = response.status();
    if !status.is_success() {
        let body = response.text().await.unwrap_or_default();
        return Err(SessionControlError::Failed(format!(
            "`GET {url}` failed ({status}): {}",
            body.trim()
        )));
    }
    response
        .json::<Value>()
        .await
        .map(|value| if value.is_null() { None } else { Some(value) })
        .map_err(|error| {
            SessionControlError::Failed(format!("`GET {url}` returned unreadable JSON: {error}"))
        })
}

/// Call OpenCode's own session API and return the narration.
///
/// The endpoint is the RUNNING server's: supercode never opens OpenCode's
/// SQLite store to archive or delete a row.
async fn opencode_call(
    verb: SessionVerb,
    mutation: &SessionMutation,
    session: &str,
) -> Result<String> {
    let (base, client) = opencode_endpoint(mutation)?;
    let url = format!("{base}/session/{session}");
    let directory = mutation
        .cwd
        .as_ref()
        .map(|cwd| cwd.to_string_lossy().into_owned());
    let (ran, request) = match verb {
        SessionVerb::Delete => (format!("DELETE {url}"), client.delete(&url)),
        SessionVerb::Archive => {
            // OpenCode records the archive as `time.archived` on the session
            // record (`packages/schema/src/v1/session.ts`), patched through
            // the same route that renames a session. The re-read in `finish`
            // is what PROVES it landed: a payload the server ignores leaves
            // `time.archived` unset and the mutation fails.
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|since| since.as_millis() as u64)
                .unwrap_or_default();
            (
                format!("PATCH {url} {{\"time\":{{\"archived\":{now}}}}}"),
                client
                    .patch(&url)
                    .json(&serde_json::json!({"time": {"archived": now}})),
            )
        }
        other => {
            return Err(SessionControlError::Unsupported(format!(
                "opencode has no HTTP door for `sessions.{}`",
                other.as_str()
            )));
        }
    };
    let request = match &directory {
        Some(directory) => request.query(&[("directory", directory)]),
        None => request,
    };
    let response = request.send().await.map_err(|error| {
        SessionControlError::Failed(format!("`{ran}` could not be sent: {error}"))
    })?;
    let status = response.status();
    if !status.is_success() {
        let body = response.text().await.unwrap_or_default();
        return Err(SessionControlError::Failed(format!(
            "`{ran}` failed ({status}): {}",
            if body.trim().is_empty() {
                "the server returned no body".to_string()
            } else {
                body.trim().to_string()
            }
        )));
    }
    Ok(ran)
}

/// Build the outcome for a slash-command door the SERVICE performed, so the
/// live path and the subprocess path publish exactly the same shape.
pub fn live_outcome(
    verb: SessionVerb,
    mutation: &SessionMutation,
    command: &str,
    session: String,
) -> Result<SessionMutationOutcome> {
    let row = read_back(mutation, &session).unwrap_or(None);
    Ok(SessionMutationOutcome {
        harness: mutation.harness.clone(),
        verb: verb.as_str().to_string(),
        ran: format!("{} live session: {command}", mutation.harness),
        session,
        row,
        archived: None,
        deleted: None,
    })
}

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

    #[test]
    fn the_door_table_names_one_door_per_supported_pair() {
        assert_eq!(
            door(HarnessId::CODEX, SessionVerb::Archive).unwrap(),
            SessionDoor::Cli
        );
        assert_eq!(
            door(HarnessId::OPENCODE, SessionVerb::Delete).unwrap(),
            SessionDoor::Http
        );
        assert_eq!(
            door(HarnessId::OPENCLAW, SessionVerb::New).unwrap(),
            SessionDoor::Live("/new")
        );
        assert_eq!(
            door(HarnessId::OPENCLAW, SessionVerb::Reset).unwrap(),
            SessionDoor::Live("/reset")
        );
        assert_eq!(
            door(HarnessId::HERMES, SessionVerb::Reset).unwrap(),
            SessionDoor::Live("/reset")
        );
        assert_eq!(
            door(HarnessId::HERMES, SessionVerb::Delete).unwrap(),
            SessionDoor::Cli
        );
        assert_eq!(
            door(HarnessId::SUPERCODE, SessionVerb::Archive).unwrap(),
            SessionDoor::Store
        );
    }

    #[test]
    fn every_refusal_names_the_reason_and_never_a_silent_no_op() {
        for (harness, verb, needle) in [
            (HarnessId::HERMES, SessionVerb::Archive, "BULK filter verb"),
            // The one refusal that exists because the DOOR does not carry the
            // command, not because the harness lacks the concept.
            (
                HarnessId::HERMES,
                SessionVerb::New,
                "sends any UNRECOGNIZED `/word` to the model as prose",
            ),
            (HarnessId::OPENCLAW, SessionVerb::Delete, "v2026.7.1-2"),
            (
                HarnessId::CLAUDE_CODE,
                SessionVerb::Delete,
                "RETENTION WINDOW",
            ),
            (
                HarnessId::CLAUDE_CODE,
                SessionVerb::New,
                "harness.v1.runtimes.start",
            ),
            (
                HarnessId::CODEX,
                SessionVerb::New,
                "harness.v1.runtimes.start",
            ),
            (
                HarnessId::SUPERCODE,
                SessionVerb::Reset,
                "no conversation reset verb",
            ),
            // ORC-13: the orchestrator gained `new`/`reset` but still has no
            // archive and no delete — a binding ENDS, and its transcript is
            // the worker harness's.
            (
                HarnessId::ORCHESTRATOR,
                SessionVerb::Archive,
                "a binding is never archived or deleted",
            ),
        ] {
            let error = door(harness, verb).unwrap_err();
            assert!(
                matches!(error, SessionControlError::Unsupported(_)),
                "{harness}.{}: {error}",
                verb.as_str()
            );
            assert!(
                error.to_string().contains(needle),
                "{harness}.{} must explain itself, got: {error}",
                verb.as_str()
            );
        }
    }

    #[test]
    fn controlled_verbs_track_the_door_table() {
        assert_eq!(
            controlled_verbs(HarnessId::CODEX),
            vec!["archive", "delete"]
        );
        // Hermes's ACP door carries `/reset` but not `/new`, so the uniform
        // verb list is narrower than the harness's chat vocabulary.
        assert_eq!(controlled_verbs(HarnessId::HERMES), vec!["reset", "delete"]);
        assert_eq!(controlled_verbs(HarnessId::OPENCLAW), vec!["new", "reset"]);
        assert_eq!(
            controlled_verbs(HarnessId::OPENCODE),
            vec!["archive", "delete"]
        );
        assert_eq!(
            controlled_verbs(HarnessId::SUPERCODE),
            vec!["archive", "delete"]
        );
        assert!(controlled_verbs(HarnessId::CLAUDE_CODE).is_empty());
        assert!(controlled_verbs(HarnessId::PI).is_empty());
        // ORC-13: the orchestrator's `/new` and `/reset` are its reducer's,
        // reached through the daemon's operator door. It has no archive and no
        // delete at all: a binding ends, it is never filed away.
        assert_eq!(
            controlled_verbs(HarnessId::ORCHESTRATOR),
            vec!["new", "reset"]
        );
        assert_eq!(
            door(HarnessId::ORCHESTRATOR, SessionVerb::Reset).unwrap(),
            SessionDoor::Daemon
        );
        assert!(controlled_verbs("not-a-harness").is_empty());
        for harness in crate::harness_support_registry().harnesses {
            assert_eq!(
                !controlled_verbs(harness.id.as_str()).is_empty(),
                supports_session_control(harness.id.as_str()),
                "{}: CONTROLLED_SESSION_HARNESSES must track the door table",
                harness.id.as_str()
            );
        }
    }

    /// The door table cannot read the registry back (it is one of the
    /// registry's inputs), so this test is what keeps the hand-written list
    /// honest.
    #[test]
    fn the_registered_harness_list_matches_the_compiled_registry() {
        let mut from_registry: Vec<String> = crate::harness_support_registry()
            .harnesses
            .into_iter()
            .map(|descriptor| descriptor.id.as_str().to_string())
            .collect();
        from_registry.sort();
        let mut declared: Vec<String> = REGISTERED_HARNESSES
            .iter()
            .map(|id| id.to_string())
            .collect();
        declared.sort();
        assert_eq!(declared, from_registry);
    }

    #[test]
    fn codex_home_is_the_parent_of_the_sessions_root() {
        let mutation = SessionMutation {
            harness: HarnessId::CODEX.into(),
            homes: HarnessHomes {
                codex: PathBuf::from("/tmp/iso/.codex/sessions"),
                ..HarnessHomes::default()
            },
            ..SessionMutation::default()
        };
        assert_eq!(codex_home(&mutation), PathBuf::from("/tmp/iso/.codex"));
    }

    #[test]
    fn a_hermes_profile_is_a_full_home() {
        let mutation = SessionMutation {
            harness: HarnessId::HERMES.into(),
            profile: Some("work".into()),
            homes: HarnessHomes {
                hermes: PathBuf::from("/tmp/iso/.hermes/state.db"),
                ..HarnessHomes::default()
            },
            ..SessionMutation::default()
        };
        assert_eq!(
            hermes_home(&mutation),
            PathBuf::from("/tmp/iso/.hermes/profiles/work")
        );
    }

    #[tokio::test]
    async fn a_live_door_asked_for_out_of_band_says_so() {
        let error = mutate(
            SessionVerb::Reset,
            &SessionMutation {
                harness: HarnessId::HERMES.into(),
                session: Some("s1".into()),
                ..SessionMutation::default()
            },
        )
        .await
        .unwrap_err();
        assert!(matches!(error, SessionControlError::Invalid(_)));
        assert!(error.to_string().contains("/reset"));
        assert!(error.to_string().contains("connection"));
    }

    #[tokio::test]
    async fn opencode_refuses_to_guess_an_endpoint() {
        let error = mutate(
            SessionVerb::Delete,
            &SessionMutation {
                harness: HarnessId::OPENCODE.into(),
                session: Some("ses_1".into()),
                ..SessionMutation::default()
            },
        )
        .await
        .unwrap_err();
        assert!(matches!(error, SessionControlError::Invalid(_)));
        assert!(error.to_string().contains("base_url"));
    }

    #[tokio::test]
    async fn a_verb_without_its_conversation_is_invalid() {
        let error = mutate(
            SessionVerb::Delete,
            &SessionMutation {
                harness: HarnessId::CODEX.into(),
                ..SessionMutation::default()
            },
        )
        .await
        .unwrap_err();
        assert!(matches!(error, SessionControlError::Invalid(_)));
        assert!(error.to_string().contains("sessions.delete"));
    }
}