meerkat 0.8.32

Modular, high-performance agent harness for LLM-powered applications
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
//! Provider-neutral admission for pre-release live execution factories.
//!
//! Compiling an experimental transport is necessary but insufficient. The
//! facade mints an admission witness only when the build contains the feature,
//! an operator selected one exact factory version, the durable realm admits
//! it, and this build carries matching Gate0 qualification evidence.

#![cfg_attr(target_arch = "wasm32", allow(dead_code))]

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;

use meerkat_client::FactoryError;
use meerkat_core::{ModelProfileWitness, ModelReleaseStage, Provider, RealmId, SessionLlmIdentity};
use meerkat_providers::ResolvedConnection;
use thiserror::Error;

pub const GPT_LIVE_FUNCTION_BRIDGE_PROFILE_ID: &str = "openai.gpt-live-1-codex.function-bridge.v1";
pub const GPT_LIVE_CLIENT_CONTEXT_PROFILE_ID: &str = "openai.gpt-live-1-codex.client-context.v1";
const GPT_LIVE_CLIENT_CONTEXT_SESSION_INSTRUCTIONS: &str = concat!(
    "You are the low-latency voice layer for a Meerkat executor. ",
    "Delegate requests that need tools, files, current information, or extended reasoning to the client executor. ",
    "Treat returned executor context as authoritative, present it naturally, and never expose the internal split."
);

const CURRENT_BUILD_VERSION: &str = env!("CARGO_PKG_VERSION");

fn valid_component(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= 128
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
}

/// Exact implementation identity selected by operator configuration.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ExperimentalLiveFactoryIdentity {
    kind: String,
    version: String,
}

impl ExperimentalLiveFactoryIdentity {
    /// Parse a factory identity without assigning provider semantics to it.
    pub fn parse(
        kind: impl Into<String>,
        version: impl Into<String>,
    ) -> Result<Self, ExperimentalLiveAdmissionError> {
        let kind = kind.into();
        if !valid_component(&kind) {
            return Err(ExperimentalLiveAdmissionError::InvalidFactoryKind);
        }
        let version = version.into();
        if !valid_component(&version) {
            return Err(ExperimentalLiveAdmissionError::InvalidFactoryVersion);
        }
        Ok(Self { kind, version })
    }

    pub fn kind(&self) -> &str {
        &self.kind
    }

    pub fn version(&self) -> &str {
        &self.version
    }
}

impl fmt::Debug for ExperimentalLiveFactoryIdentity {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExperimentalLiveFactoryIdentity")
            .field("kind", &self.kind)
            .field("version", &self.version)
            .finish()
    }
}

/// Version of the external-contract proof required by operator policy.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ExperimentalLiveGate0QualificationVersion(String);

impl ExperimentalLiveGate0QualificationVersion {
    pub fn parse(value: impl Into<String>) -> Result<Self, ExperimentalLiveAdmissionError> {
        let value = value.into();
        if !valid_component(&value) {
            return Err(ExperimentalLiveAdmissionError::InvalidGate0QualificationVersion);
        }
        Ok(Self(value))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for ExperimentalLiveGate0QualificationVersion {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("Gate0QualificationVersion")
            .field(&self.0)
            .finish()
    }
}

/// Explicit operator intent for one experimental live factory.
#[derive(Clone, PartialEq, Eq)]
pub struct ExperimentalLiveOperatorConfig {
    factory: ExperimentalLiveFactoryIdentity,
    required_gate0: ExperimentalLiveGate0QualificationVersion,
    execution_profiles: BTreeMap<String, ExperimentalLiveExecutionProfileDefinition>,
}

#[derive(Clone, PartialEq, Eq)]
struct ExperimentalLiveExecutionProfileDefinition {
    mode: meerkat_core::LiveExecutionMode,
    capabilities: meerkat_core::LiveExecutionCapabilities,
    gpt_live_session_instructions: Option<String>,
}

impl fmt::Debug for ExperimentalLiveOperatorConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExperimentalLiveOperatorConfig")
            .field("factory", &self.factory)
            .field("required_gate0", &self.required_gate0)
            .field("execution_profiles", &self.execution_profiles)
            .finish()
    }
}

impl fmt::Debug for ExperimentalLiveExecutionProfileDefinition {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExperimentalLiveExecutionProfileDefinition")
            .field("mode", &self.mode)
            .field("capabilities", &self.capabilities)
            .field(
                "gpt_live_session_instructions",
                &self
                    .gpt_live_session_instructions
                    .as_ref()
                    .map(|_| "<catalog-bound>"),
            )
            .finish()
    }
}

impl ExperimentalLiveOperatorConfig {
    /// Canonical operator policy for the validated GPT Live client-context
    /// contract compiled into this build.
    ///
    /// The factory identity and Gate0 version are source-owned constants, not
    /// environment claims or surface configuration. FunctionBridge is not
    /// included because its direct raw event contract remains unqualified.
    pub fn gpt_live_client_context() -> Self {
        Self {
            factory: ExperimentalLiveFactoryIdentity {
                kind: meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_FACTORY_KIND
                    .to_string(),
                version:
                    meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_FACTORY_VERSION
                        .to_string(),
            },
            required_gate0: ExperimentalLiveGate0QualificationVersion(
                meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_GATE0_VERSION
                    .to_string(),
            ),
            execution_profiles: BTreeMap::from([(
                GPT_LIVE_CLIENT_CONTEXT_PROFILE_ID.to_string(),
                ExperimentalLiveExecutionProfileDefinition {
                    mode: meerkat_core::LiveExecutionMode::ClientContext,
                    capabilities: meerkat_core::LiveExecutionCapabilities {
                        function_bridge: false,
                        client_context: true,
                    },
                    gpt_live_session_instructions: Some(
                        GPT_LIVE_CLIENT_CONTEXT_SESSION_INSTRUCTIONS.to_string(),
                    ),
                },
            )]),
        }
    }

    pub fn new(
        factory: ExperimentalLiveFactoryIdentity,
        required_gate0: ExperimentalLiveGate0QualificationVersion,
    ) -> Self {
        Self {
            factory,
            required_gate0,
            execution_profiles: BTreeMap::new(),
        }
    }

    /// Add one provider-neutral execution profile to this application-host
    /// composition. Surfaces may later name only `profile_id`; the selected
    /// mode and independently qualified capability atoms remain owned here.
    pub fn with_execution_profile(
        self,
        profile_id: impl Into<String>,
        mode: meerkat_core::LiveExecutionMode,
        capabilities: meerkat_core::LiveExecutionCapabilities,
    ) -> Result<Self, ExperimentalLiveAdmissionError> {
        self.with_execution_profile_definition(profile_id, mode, capabilities, None)
    }

    /// Add a provider-neutral execution profile with an approved, immutable
    /// top-level GPT Live session instruction overlay.
    ///
    /// The host composition owns this semantic text. Live callers select only
    /// the stable `profile_id`; MobKit and provider request parameters cannot
    /// replace the text per open. Dynamic room or user context remains in the
    /// canonical transcript projection rather than this profile.
    pub fn with_execution_profile_session_instructions(
        self,
        profile_id: impl Into<String>,
        mode: meerkat_core::LiveExecutionMode,
        capabilities: meerkat_core::LiveExecutionCapabilities,
        instructions: impl Into<String>,
    ) -> Result<Self, ExperimentalLiveAdmissionError> {
        let instructions = instructions.into();
        if instructions.trim().is_empty() {
            return Err(ExperimentalLiveAdmissionError::InvalidSessionInstructions);
        }
        self.with_execution_profile_definition(profile_id, mode, capabilities, Some(instructions))
    }

    fn with_execution_profile_definition(
        mut self,
        profile_id: impl Into<String>,
        mode: meerkat_core::LiveExecutionMode,
        capabilities: meerkat_core::LiveExecutionCapabilities,
        gpt_live_session_instructions: Option<String>,
    ) -> Result<Self, ExperimentalLiveAdmissionError> {
        let profile_id = profile_id.into();
        let selected_available = match mode {
            meerkat_core::LiveExecutionMode::FunctionBridge => capabilities.function_bridge,
            meerkat_core::LiveExecutionMode::ClientContext => capabilities.client_context,
        };
        if !valid_component(&profile_id) || !selected_available {
            return Err(ExperimentalLiveAdmissionError::ExecutionModeUnavailable);
        }
        self.execution_profiles.insert(
            profile_id,
            ExperimentalLiveExecutionProfileDefinition {
                mode,
                capabilities,
                gpt_live_session_instructions,
            },
        );
        Ok(self)
    }

    /// Register Meerkat's canonical GPT Live Responses profile without
    /// requiring a surface or MobKit host to duplicate the provider profile
    /// identifier or reconstruct its provider-neutral capability atoms.
    /// Composition must call this only when the durable-member bridge host is
    /// installed; otherwise admission correctly remains unadvertised.
    pub fn with_gpt_live_function_bridge_profile(
        self,
    ) -> Result<Self, ExperimentalLiveAdmissionError> {
        self.with_execution_profile(
            GPT_LIVE_FUNCTION_BRIDGE_PROFILE_ID,
            meerkat_core::LiveExecutionMode::FunctionBridge,
            meerkat_core::LiveExecutionCapabilities {
                function_bridge: true,
                client_context: false,
            },
        )
    }

    /// Register the canonical, POC-qualified GPT Live client-context profile.
    ///
    /// This is intentionally independent from FunctionBridge. The current
    /// compiled Gate0 evidence qualifies only the client-managed delegation
    /// and correlated context-return contract.
    pub fn with_gpt_live_client_context_profile(
        self,
    ) -> Result<Self, ExperimentalLiveAdmissionError> {
        self.with_execution_profile_session_instructions(
            GPT_LIVE_CLIENT_CONTEXT_PROFILE_ID,
            meerkat_core::LiveExecutionMode::ClientContext,
            meerkat_core::LiveExecutionCapabilities {
                function_bridge: false,
                client_context: true,
            },
            GPT_LIVE_CLIENT_CONTEXT_SESSION_INSTRUCTIONS,
        )
    }

    pub fn factory(&self) -> &ExperimentalLiveFactoryIdentity {
        &self.factory
    }

    pub fn required_gate0(&self) -> &ExperimentalLiveGate0QualificationVersion {
        &self.required_gate0
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct QualifiedGate0BuildWitness {
    factory: ExperimentalLiveFactoryIdentity,
    qualification: ExperimentalLiveGate0QualificationVersion,
    build_version: String,
    protocol_digest: String,
    execution_mode: meerkat_core::LiveExecutionMode,
}

impl QualifiedGate0BuildWitness {
    fn current_build() -> Option<Self> {
        if !cfg!(feature = "experimental-gpt-live") {
            return None;
        }
        Some(Self {
            factory: ExperimentalLiveFactoryIdentity {
                kind: meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_FACTORY_KIND
                    .to_string(),
                version:
                    meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_FACTORY_VERSION
                        .to_string(),
            },
            qualification: ExperimentalLiveGate0QualificationVersion(
                meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_GATE0_VERSION
                    .to_string(),
            ),
            build_version: CURRENT_BUILD_VERSION.to_string(),
            protocol_digest:
                meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_PROTOCOL_DIGEST
                    .to_string(),
            execution_mode: meerkat_core::LiveExecutionMode::ClientContext,
        })
    }
}

/// Side-effect-free process and realm qualification for the experimental
/// live capability.
///
/// This proof contains no selected model, auth binding, credential, or
/// per-open target. It can therefore drive capability advertisement without
/// resolving a credential or constructing a provider factory.
pub struct ExperimentalLiveCapabilityQualification {
    authority: Arc<AdmissionAuthority>,
    realm: RealmId,
    factory: ExperimentalLiveFactoryIdentity,
    gate0_qualification: ExperimentalLiveGate0QualificationVersion,
    gate0_build_version: String,
    protocol_digest: String,
    lower_qualification:
        Option<meerkat_llm_core::provider_runtime::ExperimentalRealtimeQualificationWitness>,
}

impl fmt::Debug for ExperimentalLiveCapabilityQualification {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExperimentalLiveCapabilityQualification")
            .field("realm", &self.realm)
            .field("factory", &self.factory)
            .field("gate0_qualification", &self.gate0_qualification)
            .field("gate0_build_version", &self.gate0_build_version)
            .field("protocol_digest", &self.protocol_digest)
            .finish()
    }
}

#[derive(Debug)]
struct AdmissionAuthority;

/// Factory-owned admission authority.
///
/// `Default` is intentionally unusable. Configuration does not bypass the
/// compile or Gate0 predicates: both remain facts of the compiled artifact.
#[derive(Clone)]
pub struct ExperimentalLiveAdmissionOwner {
    authority: Arc<AdmissionAuthority>,
    feature_compiled: bool,
    operator: Option<ExperimentalLiveOperatorConfig>,
    admitted_realms: BTreeSet<RealmId>,
    gate0_build: Option<QualifiedGate0BuildWitness>,
    lower_authorities: BTreeMap<
        RealmId,
        meerkat_llm_core::provider_runtime::ExperimentalRealtimeAdmissionAuthority,
    >,
}

impl fmt::Debug for ExperimentalLiveAdmissionOwner {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExperimentalLiveAdmissionOwner")
            .field("feature_compiled", &self.feature_compiled)
            .field("operator_configured", &self.operator.is_some())
            .field("admitted_realms", &self.admitted_realms)
            .field("gate0_build_qualified", &self.gate0_build.is_some())
            .finish()
    }
}

impl Default for ExperimentalLiveAdmissionOwner {
    fn default() -> Self {
        Self {
            authority: Arc::new(AdmissionAuthority),
            feature_compiled: cfg!(feature = "experimental-gpt-live"),
            operator: None,
            admitted_realms: BTreeSet::new(),
            gate0_build: QualifiedGate0BuildWitness::current_build(),
            lower_authorities: BTreeMap::new(),
        }
    }
}

impl ExperimentalLiveAdmissionOwner {
    /// Resolve a provider-neutral execution mode from this owner's configured
    /// profile catalog. The caller names only a catalog profile id and cannot
    /// supply or downgrade the selected mode or capability atoms.
    #[allow(clippy::needless_return)]
    pub fn qualify_execution_profile(
        &self,
        qualification: &ExperimentalLiveCapabilityQualification,
        profile_id: &str,
    ) -> Result<
        meerkat_runtime::live_execution::LiveExecutionProfileSelection,
        ExperimentalLiveAdmissionError,
    > {
        self.validate_qualification(qualification)?;
        let profile = self
            .operator
            .as_ref()
            .and_then(|operator| operator.execution_profiles.get(profile_id))
            .cloned()
            .ok_or(ExperimentalLiveAdmissionError::ExecutionModeUnavailable)?;
        let qualified_mode = self
            .gate0_build
            .as_ref()
            .map(|gate0| gate0.execution_mode)
            .ok_or(ExperimentalLiveAdmissionError::Gate0BuildNotQualified)?;
        if profile.mode != qualified_mode {
            return Err(ExperimentalLiveAdmissionError::ExecutionModeUnavailable);
        }
        #[cfg(any(feature = "experimental-gpt-live", test))]
        let ExperimentalLiveExecutionProfileDefinition {
            mode, capabilities, ..
        } = profile;
        #[cfg(not(any(feature = "experimental-gpt-live", test)))]
        let _ = profile;
        #[cfg(feature = "experimental-gpt-live")]
        {
            if let Some(lower_qualification) = qualification.lower_qualification.as_ref() {
                if lower_qualification.execution_mode() != mode {
                    return Err(ExperimentalLiveAdmissionError::ExecutionModeUnavailable);
                }
                return meerkat_runtime::live_execution::LiveExecutionProfileSelection::from_experimental_qualification(
                    lower_qualification,
                    profile_id,
                    mode,
                    capabilities,
                )
                .map_err(|_| ExperimentalLiveAdmissionError::ExecutionModeUnavailable);
            }
        }
        #[cfg(test)]
        {
            meerkat_runtime::live_execution::LiveExecutionProfileSelection::__test_new(
                profile_id,
                mode,
                capabilities,
            )
            .map_err(|_| ExperimentalLiveAdmissionError::ExecutionModeUnavailable)
        }
        #[cfg(not(test))]
        Err(ExperimentalLiveAdmissionError::LowerAuthorityUnavailable)
    }

    #[cfg(test)]
    pub(crate) fn qualified_without_lower_authority_for_test(
        realm: RealmId,
        factory: ExperimentalLiveFactoryIdentity,
    ) -> Self {
        let qualification = ExperimentalLiveGate0QualificationVersion("gate0-v1".to_string());
        Self {
            authority: Arc::new(AdmissionAuthority),
            feature_compiled: true,
            operator: Some(
                ExperimentalLiveOperatorConfig::new(factory.clone(), qualification.clone())
                    .with_gpt_live_function_bridge_profile()
                    .expect("valid test execution profile"),
            ),
            admitted_realms: BTreeSet::from([realm]),
            gate0_build: Some(QualifiedGate0BuildWitness {
                factory,
                qualification,
                build_version: CURRENT_BUILD_VERSION.to_string(),
                protocol_digest: "ab".repeat(32),
                execution_mode: meerkat_core::LiveExecutionMode::FunctionBridge,
            }),
            lower_authorities: BTreeMap::new(),
        }
    }

    /// Configure exact operator and realm intent for this compiled artifact.
    pub fn configured_for_current_build(
        operator: ExperimentalLiveOperatorConfig,
        admitted_realms: impl IntoIterator<Item = RealmId>,
    ) -> Self {
        let admitted_realms: BTreeSet<_> = admitted_realms.into_iter().collect();
        let gate0_build = QualifiedGate0BuildWitness::current_build();
        let lower_authorities = admitted_realms
            .iter()
            .filter_map(|realm| {
                let gate0 = gate0_build.as_ref()?;
                let policy = meerkat_llm_core::provider_runtime::ExperimentalRealtimeQualificationPolicy::new(
                    realm.clone(),
                    operator.factory.kind(),
                    operator.factory.version(),
                    operator.required_gate0.as_str(),
                    gate0.execution_mode,
                )
                .ok()?;
                let authority = meerkat_llm_core::provider_runtime::ExperimentalRealtimeAdmissionAuthority::from_compiled_gate0_policy(policy).ok()?;
                Some((realm.clone(), authority))
            })
            .collect();
        Self {
            authority: Arc::new(AdmissionAuthority),
            feature_compiled: cfg!(feature = "experimental-gpt-live"),
            operator: Some(operator),
            admitted_realms,
            gate0_build,
            lower_authorities,
        }
    }

    /// Qualify capability advertisement without selecting a target, resolving
    /// a binding, reading credentials, or constructing provider state.
    pub fn qualify_capability(
        &self,
        realm: &RealmId,
        factory: &ExperimentalLiveFactoryIdentity,
    ) -> Result<ExperimentalLiveCapabilityQualification, ExperimentalLiveAdmissionError> {
        self.validate_predicates(realm)?;
        let operator = self
            .operator
            .as_ref()
            .ok_or(ExperimentalLiveAdmissionError::OperatorNotConfigured)?;
        if &operator.factory != factory {
            return Err(ExperimentalLiveAdmissionError::OperatorFactoryMismatch);
        }
        let gate0 = self
            .gate0_build
            .as_ref()
            .ok_or(ExperimentalLiveAdmissionError::Gate0BuildNotQualified)?;
        self.validate_gate0(operator, gate0, factory)?;
        let lower_qualification = match self.lower_authorities.get(realm) {
            Some(authority) => Some(
                authority
                    .qualify(
                        realm,
                        factory.kind(),
                        factory.version(),
                        gate0.execution_mode,
                    )
                    .map_err(ExperimentalLiveAdmissionError::LowerAdmission)?,
            ),
            None if cfg!(test) => None,
            None => return Err(ExperimentalLiveAdmissionError::LowerAuthorityUnavailable),
        };
        Ok(ExperimentalLiveCapabilityQualification {
            authority: Arc::clone(&self.authority),
            realm: realm.clone(),
            factory: factory.clone(),
            gate0_qualification: gate0.qualification.clone(),
            gate0_build_version: gate0.build_version.clone(),
            protocol_digest: gate0.protocol_digest.clone(),
            lower_qualification,
        })
    }

    /// Check every non-credential admission predicate before an auth binding
    /// is materialized. The returned value is opaque outside this crate.
    pub(crate) fn preflight(
        &self,
        qualification: ExperimentalLiveCapabilityQualification,
        identity: SessionLlmIdentity,
        profile: ModelProfileWitness,
        execution_profile_id: &str,
    ) -> Result<ExperimentalLiveAdmissionPreflight, ExperimentalLiveAdmissionError> {
        self.validate_qualification(&qualification)?;
        if !profile.matches_identity(&identity) {
            return Err(ExperimentalLiveAdmissionError::TargetProfileMismatch);
        }
        if profile.profile().release_stage != ModelReleaseStage::Experimental {
            return Err(ExperimentalLiveAdmissionError::TargetNotExperimental);
        }
        if !profile.profile().realtime {
            return Err(ExperimentalLiveAdmissionError::TargetNotRealtime);
        }
        if identity.provider != Provider::OpenAI || identity.model != "gpt-live-1-codex" {
            return Err(ExperimentalLiveAdmissionError::ExecutionModeUnavailable);
        }
        let execution_profile =
            self.qualify_execution_profile(&qualification, execution_profile_id)?;
        #[cfg(feature = "experimental-gpt-live")]
        let gpt_live_session_instructions = self
            .operator
            .as_ref()
            .and_then(|operator| operator.execution_profiles.get(execution_profile_id))
            .and_then(|profile| profile.gpt_live_session_instructions.clone());
        Ok(ExperimentalLiveAdmissionPreflight {
            authority: qualification.authority,
            realm: qualification.realm,
            factory: qualification.factory,
            gate0_qualification: qualification.gate0_qualification,
            gate0_build_version: qualification.gate0_build_version,
            protocol_digest: qualification.protocol_digest,
            lower_qualification: qualification.lower_qualification,
            identity,
            profile,
            execution_profile,
            #[cfg(feature = "experimental-gpt-live")]
            gpt_live_session_instructions,
        })
    }

    /// Complete admission after the separately authorized credential
    /// materialization step produced one exact resolved target.
    pub(crate) fn complete(
        &self,
        preflight: ExperimentalLiveAdmissionPreflight,
        connection: ResolvedConnection,
        binding_use_witness: meerkat_core::AuthBindingUseWitness,
    ) -> Result<ExperimentalLiveAdmissionWitness, ExperimentalLiveAdmissionError> {
        if !Arc::ptr_eq(&self.authority, &preflight.authority) {
            return Err(ExperimentalLiveAdmissionError::StaleAdmissionPreflight);
        }
        if preflight.identity.auth_binding.as_ref() != Some(binding_use_witness.auth_binding()) {
            return Err(ExperimentalLiveAdmissionError::BindingUseWitnessMismatch);
        }
        let target = meerkat_providers::ResolvedRealtimeTarget::new(
            preflight.identity,
            preflight.profile,
            connection,
        )
        .ok_or(ExperimentalLiveAdmissionError::ResolvedConnectionMismatch)?;
        let lower_qualification = preflight
            .lower_qualification
            .ok_or(ExperimentalLiveAdmissionError::LowerAuthorityUnavailable)?;
        let lower_authority = self
            .lower_authorities
            .get(&preflight.realm)
            .ok_or(ExperimentalLiveAdmissionError::LowerAuthorityUnavailable)?;
        let target = lower_authority
            .admit_target(lower_qualification, target, binding_use_witness)
            .map_err(ExperimentalLiveAdmissionError::LowerAdmission)?;
        Ok(ExperimentalLiveAdmissionWitness {
            authority: preflight.authority,
            realm: preflight.realm,
            factory: preflight.factory,
            gate0_qualification: preflight.gate0_qualification,
            gate0_build_version: preflight.gate0_build_version,
            protocol_digest: preflight.protocol_digest,
            target,
            execution_profile: preflight.execution_profile,
            #[cfg(feature = "experimental-gpt-live")]
            gpt_live_session_instructions: preflight.gpt_live_session_instructions,
        })
    }

    /// Advertise the capability from side-effect-free build qualification.
    pub fn advertised_feature_capabilities(
        &self,
        qualification: &ExperimentalLiveCapabilityQualification,
        execution_profile_id: Option<&str>,
    ) -> Result<Vec<&'static str>, ExperimentalLiveAdmissionError> {
        self.validate_qualification(qualification)?;
        let mut capabilities = vec![meerkat_contracts::LIVE_EXECUTION_IDENTITY_V1_CAPABILITY];
        if let Some(profile_id) = execution_profile_id {
            let selection = self.qualify_execution_profile(qualification, profile_id)?;
            let atoms = selection.capabilities();
            if atoms.function_bridge {
                capabilities.push(meerkat_contracts::LIVE_FUNCTION_BRIDGE_V1_CAPABILITY);
            }
            if atoms.client_context {
                capabilities.push(meerkat_contracts::LIVE_CLIENT_CONTEXT_V1_CAPABILITY);
            }
        }
        Ok(capabilities)
    }

    fn validate_qualification(
        &self,
        qualification: &ExperimentalLiveCapabilityQualification,
    ) -> Result<(), ExperimentalLiveAdmissionError> {
        if !Arc::ptr_eq(&self.authority, &qualification.authority) {
            return Err(ExperimentalLiveAdmissionError::StaleCapabilityQualification);
        }
        self.validate_predicates(&qualification.realm)?;
        let operator = self
            .operator
            .as_ref()
            .ok_or(ExperimentalLiveAdmissionError::OperatorNotConfigured)?;
        let gate0 = self
            .gate0_build
            .as_ref()
            .ok_or(ExperimentalLiveAdmissionError::Gate0BuildNotQualified)?;
        self.validate_gate0(operator, gate0, &qualification.factory)?;
        if qualification.gate0_qualification != gate0.qualification
            || qualification.gate0_build_version != gate0.build_version
            || qualification.protocol_digest != gate0.protocol_digest
        {
            return Err(ExperimentalLiveAdmissionError::StaleCapabilityQualification);
        }
        Ok(())
    }

    /// Revalidate an admission before a consequential factory use.
    pub fn validate_witness(
        &self,
        witness: &ExperimentalLiveAdmissionWitness,
        realm: &RealmId,
        factory: &ExperimentalLiveFactoryIdentity,
    ) -> Result<(), ExperimentalLiveAdmissionError> {
        if !Arc::ptr_eq(&self.authority, &witness.authority) {
            return Err(ExperimentalLiveAdmissionError::StaleAdmissionWitness);
        }
        self.validate_predicates(realm)?;
        if &witness.realm != realm {
            return Err(ExperimentalLiveAdmissionError::WitnessRealmMismatch);
        }
        if &witness.factory != factory {
            return Err(ExperimentalLiveAdmissionError::WitnessFactoryMismatch);
        }
        let operator = self
            .operator
            .as_ref()
            .ok_or(ExperimentalLiveAdmissionError::OperatorNotConfigured)?;
        let gate0 = self
            .gate0_build
            .as_ref()
            .ok_or(ExperimentalLiveAdmissionError::Gate0BuildNotQualified)?;
        self.validate_gate0(operator, gate0, factory)?;
        if witness.gate0_qualification != gate0.qualification
            || witness.gate0_build_version != gate0.build_version
            || witness.protocol_digest != gate0.protocol_digest
        {
            return Err(ExperimentalLiveAdmissionError::StaleAdmissionWitness);
        }
        Ok(())
    }

    fn validate_predicates(&self, realm: &RealmId) -> Result<(), ExperimentalLiveAdmissionError> {
        if !self.feature_compiled {
            return Err(ExperimentalLiveAdmissionError::FeatureNotCompiled);
        }
        if self.operator.is_none() {
            return Err(ExperimentalLiveAdmissionError::OperatorNotConfigured);
        }
        if !self.admitted_realms.contains(realm) {
            return Err(ExperimentalLiveAdmissionError::RealmNotAdmitted {
                realm: realm.clone(),
            });
        }
        if self.gate0_build.is_none() {
            return Err(ExperimentalLiveAdmissionError::Gate0BuildNotQualified);
        }
        Ok(())
    }

    fn validate_gate0(
        &self,
        operator: &ExperimentalLiveOperatorConfig,
        gate0: &QualifiedGate0BuildWitness,
        factory: &ExperimentalLiveFactoryIdentity,
    ) -> Result<(), ExperimentalLiveAdmissionError> {
        if gate0.build_version != CURRENT_BUILD_VERSION {
            return Err(ExperimentalLiveAdmissionError::Gate0BuildStale {
                qualified_build: gate0.build_version.clone(),
                current_build: CURRENT_BUILD_VERSION.to_string(),
            });
        }
        if &gate0.factory != factory {
            return Err(ExperimentalLiveAdmissionError::Gate0FactoryMismatch);
        }
        if gate0.qualification != operator.required_gate0 {
            return Err(ExperimentalLiveAdmissionError::Gate0QualificationMismatch);
        }
        Ok(())
    }
}

#[derive(Debug)]
pub(crate) struct ExperimentalLiveAdmissionPreflight {
    authority: Arc<AdmissionAuthority>,
    realm: RealmId,
    factory: ExperimentalLiveFactoryIdentity,
    gate0_qualification: ExperimentalLiveGate0QualificationVersion,
    gate0_build_version: String,
    protocol_digest: String,
    identity: SessionLlmIdentity,
    profile: ModelProfileWitness,
    execution_profile: meerkat_runtime::live_execution::LiveExecutionProfileSelection,
    #[cfg(feature = "experimental-gpt-live")]
    gpt_live_session_instructions: Option<String>,
    lower_qualification:
        Option<meerkat_llm_core::provider_runtime::ExperimentalRealtimeQualificationWitness>,
}

/// Opaque, single-target proof of experimental live admission.
///
/// It owns the resolved target so the registry witness, model identity, and
/// credential resolution admitted together cannot be substituted afterward.
pub struct ExperimentalLiveAdmissionWitness {
    authority: Arc<AdmissionAuthority>,
    realm: RealmId,
    factory: ExperimentalLiveFactoryIdentity,
    gate0_qualification: ExperimentalLiveGate0QualificationVersion,
    gate0_build_version: String,
    protocol_digest: String,
    target: meerkat_llm_core::provider_runtime::AdmittedExperimentalRealtimeTarget,
    execution_profile: meerkat_runtime::live_execution::LiveExecutionProfileSelection,
    #[cfg(feature = "experimental-gpt-live")]
    gpt_live_session_instructions: Option<String>,
}

impl fmt::Debug for ExperimentalLiveAdmissionWitness {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ExperimentalLiveAdmissionWitness")
            .field("realm", &self.realm)
            .field("factory", &self.factory)
            .field("gate0_qualification", &self.gate0_qualification)
            .field("gate0_build_version", &self.gate0_build_version)
            .field("protocol_digest", &self.protocol_digest)
            .field("provider", &self.target.identity().provider)
            .field("model", &"<registry-admitted>")
            .finish_non_exhaustive()
    }
}

impl ExperimentalLiveAdmissionWitness {
    pub fn realm(&self) -> &RealmId {
        &self.realm
    }

    pub fn factory(&self) -> &ExperimentalLiveFactoryIdentity {
        &self.factory
    }

    pub fn identity(&self) -> &SessionLlmIdentity {
        self.target.identity()
    }

    pub fn provider(&self) -> Provider {
        self.target.identity().provider
    }

    pub fn execution_profile(
        &self,
    ) -> &meerkat_runtime::live_execution::LiveExecutionProfileSelection {
        &self.execution_profile
    }

    /// Approved host-catalog text for the top-level GPT Live call session.
    /// Provider-specific lowering consumes it only after this admission
    /// witness is minted; raw live/open parameters never enter this field.
    #[cfg(feature = "experimental-gpt-live")]
    pub(crate) fn gpt_live_session_instructions(&self) -> Option<&str> {
        self.gpt_live_session_instructions.as_deref()
    }

    /// Consume the proof into the only lower-layer input accepted by the
    /// experimental provider factory.
    #[cfg(feature = "experimental-gpt-live")]
    pub(crate) fn into_provider_target(
        self,
    ) -> meerkat_llm_core::provider_runtime::AdmittedExperimentalRealtimeTarget {
        self.target
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum ExperimentalLiveAdmissionError {
    #[error("experimental live support was not compiled into this build")]
    FeatureNotCompiled,
    #[error("experimental live support is not configured by the operator")]
    OperatorNotConfigured,
    #[error("experimental live support is not admitted for realm '{realm}'")]
    RealmNotAdmitted { realm: RealmId },
    #[error("this build has no qualified experimental live Gate0 witness")]
    Gate0BuildNotQualified,
    #[error("the Gate0 witness factory does not match the requested factory")]
    Gate0FactoryMismatch,
    #[error("the Gate0 qualification version does not match operator policy")]
    Gate0QualificationMismatch,
    #[error(
        "the Gate0 witness is stale for this build (qualified {qualified_build}, current {current_build})"
    )]
    Gate0BuildStale {
        qualified_build: String,
        current_build: String,
    },
    #[error("the requested factory does not match operator configuration")]
    OperatorFactoryMismatch,
    #[error("the resolved target is not classified experimental by the model registry")]
    TargetNotExperimental,
    #[error("the resolved target is not classified realtime-capable by the model registry")]
    TargetNotRealtime,
    #[error("the registry profile does not match the requested execution identity")]
    TargetProfileMismatch,
    #[error("the resolved connection does not match the admitted provider/model profile")]
    ResolvedConnectionMismatch,
    #[error("the admission witness belongs to an earlier or different admission owner")]
    StaleAdmissionWitness,
    #[error("the admission preflight belongs to an earlier or different admission owner")]
    StaleAdmissionPreflight,
    #[error("the capability qualification belongs to an earlier or different admission owner")]
    StaleCapabilityQualification,
    #[error("the binding-use witness does not match the selected channel auth binding")]
    BindingUseWitnessMismatch,
    #[error("the lower experimental realtime admission authority is unavailable")]
    LowerAuthorityUnavailable,
    #[error("the selected live execution mode is unavailable in this composition")]
    ExecutionModeUnavailable,
    #[error("experimental live session instructions must be non-empty when configured")]
    InvalidSessionInstructions,
    #[error(transparent)]
    LowerAdmission(#[from] meerkat_llm_core::provider_runtime::ExperimentalRealtimeAdmissionError),
    #[error("the admission witness is bound to a different realm")]
    WitnessRealmMismatch,
    #[error("the admission witness is bound to a different factory")]
    WitnessFactoryMismatch,
    #[error("invalid experimental live factory kind")]
    InvalidFactoryKind,
    #[error("invalid experimental live factory version")]
    InvalidFactoryVersion,
    #[error("invalid experimental live Gate0 qualification version")]
    InvalidGate0QualificationVersion,
}

/// Typed composition of ordinary factory resolution and admission failure.
#[derive(Debug, Error)]
pub enum ExperimentalLiveFactoryResolutionError {
    #[error("experimental live target resolution failed: {0}")]
    Factory(#[from] FactoryError),
    #[error("experimental live target admission failed: {0}")]
    Admission(#[from] ExperimentalLiveAdmissionError),
}

#[cfg(test)]
mod tests {
    use super::*;
    use meerkat_core::{
        ActingOnBehalfOf, AuthBindingRef, AuthGrant, AuthMetadata, BindingId, BindingOrigin,
        Config, GrantAction, GrantScope, ModelRegistry, PrincipalKind, PrincipalRef,
        authorize_explicit_auth_binding_use,
    };
    use meerkat_providers::{NormalizedBackendKind, StaticLease};

    impl ExperimentalLiveAdmissionOwner {
        fn for_test(
            feature_compiled: bool,
            operator: Option<ExperimentalLiveOperatorConfig>,
            admitted_realms: BTreeSet<RealmId>,
            gate0_build: Option<QualifiedGate0BuildWitness>,
        ) -> Self {
            Self {
                authority: Arc::new(AdmissionAuthority),
                feature_compiled,
                operator,
                admitted_realms,
                gate0_build,
                lower_authorities: BTreeMap::new(),
            }
        }
    }

    fn realm(value: &str) -> RealmId {
        RealmId::parse(value).expect("valid test realm")
    }

    fn factory(version: &str) -> ExperimentalLiveFactoryIdentity {
        ExperimentalLiveFactoryIdentity::parse("private-live", version).expect("valid factory")
    }

    fn qualification(version: &str) -> ExperimentalLiveGate0QualificationVersion {
        ExperimentalLiveGate0QualificationVersion::parse(version).expect("valid qualification")
    }

    fn operator(factory: ExperimentalLiveFactoryIdentity) -> ExperimentalLiveOperatorConfig {
        ExperimentalLiveOperatorConfig::new(factory, qualification("gate0-v1"))
            .with_gpt_live_function_bridge_profile()
            .expect("valid test execution profile")
    }

    fn gate0(factory: ExperimentalLiveFactoryIdentity) -> QualifiedGate0BuildWitness {
        QualifiedGate0BuildWitness {
            factory,
            qualification: qualification("gate0-v1"),
            build_version: CURRENT_BUILD_VERSION.to_string(),
            protocol_digest: "ab".repeat(32),
            execution_mode: meerkat_core::LiveExecutionMode::FunctionBridge,
        }
    }

    fn binding() -> AuthBindingRef {
        AuthBindingRef {
            realm: realm("voice"),
            binding: BindingId::parse("chatgpt").expect("valid binding"),
            profile: None,
            origin: BindingOrigin::Configured,
        }
    }

    fn target_parts(model: &str) -> (SessionLlmIdentity, ModelProfileWitness, ResolvedConnection) {
        let config = Config::default();
        let registry = ModelRegistry::from_config(&config, meerkat_models::canonical())
            .expect("canonical registry");
        let profile = registry
            .profile_witness_for_provider(Provider::OpenAI, model)
            .expect("test model profile");
        let identity = SessionLlmIdentity {
            model: model.to_string(),
            provider: Provider::OpenAI,
            self_hosted_server_id: None,
            provider_params: None,
            auth_binding: Some(binding()),
        };
        let connection = ResolvedConnection {
            provider: Provider::OpenAI,
            backend: NormalizedBackendKind::OpenAi(
                meerkat_core::provider_matrix::OpenAiBackendKind::ChatGptBackend,
            ),
            backend_profile: Arc::new(meerkat_core::BackendProfile {
                id: "test".into(),
                provider: Provider::OpenAI,
                backend_kind: "chatgpt_backend".into(),
                base_url: None,
                options: serde_json::Value::Null,
                server: None,
            }),
            credential_identity: meerkat_core::AuthCredentialIdentity::from_auth_binding(&binding()),
            auth_lease: Arc::new(StaticLease::empty_lease(AuthMetadata::default(), "test")),
        };
        (identity, profile, connection)
    }

    fn binding_use_witness() -> meerkat_core::AuthBindingUseWitness {
        let principal = PrincipalRef::new(PrincipalKind::Human, "alice").expect("principal");
        let target = PrincipalRef::new(PrincipalKind::PersonalAgent, "agent").expect("target");
        let request =
            meerkat_core::AuthBindingUseRequest::new(principal.clone(), target.clone(), binding());
        let grant = AuthGrant {
            principal: principal.clone(),
            scope: GrantScope::AuthBinding {
                realm_id: binding().realm,
                binding_id: binding().binding,
                profile_id: None,
            },
            actions: BTreeSet::from([GrantAction::UseAuthBinding]),
            acting_on_behalf_of: Some(ActingOnBehalfOf::new(principal, target)),
        };
        authorize_explicit_auth_binding_use(&request, &[grant])
            .into_result()
            .expect("exact grant")
    }

    #[test]
    fn all_four_predicates_are_independent_and_required() {
        let admitted_realm = realm("voice");
        let selected_factory = factory("v1");
        for mask in 0_u8..16 {
            let feature_compiled = mask & 0b0001 != 0;
            let operator_configured = mask & 0b0010 != 0;
            let realm_admitted = mask & 0b0100 != 0;
            let gate0_qualified = mask & 0b1000 != 0;
            let owner = ExperimentalLiveAdmissionOwner::for_test(
                feature_compiled,
                operator_configured.then(|| operator(selected_factory.clone())),
                if realm_admitted {
                    BTreeSet::from([admitted_realm.clone()])
                } else {
                    BTreeSet::default()
                },
                gate0_qualified.then(|| gate0(selected_factory.clone())),
            );
            let result = owner.qualify_capability(&admitted_realm, &selected_factory);
            assert_eq!(
                result.is_ok(),
                mask == 0b1111,
                "only the full conjunction may mint a witness, mask={mask:04b}"
            );
        }
    }

    #[cfg(feature = "experimental-gpt-live")]
    #[test]
    fn current_build_qualifies_client_context_and_refuses_function_bridge() {
        let admitted_realm = realm("voice-current-build");
        let selected_factory = ExperimentalLiveFactoryIdentity::parse(
            meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_FACTORY_KIND,
            meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_FACTORY_VERSION,
        )
        .expect("compiled factory identity");
        let canonical_operator = ExperimentalLiveOperatorConfig::gpt_live_client_context();
        assert_eq!(canonical_operator.factory(), &selected_factory);
        assert_eq!(
            canonical_operator.required_gate0().as_str(),
            meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_GATE0_VERSION
        );
        let helper_operator = ExperimentalLiveOperatorConfig::new(
            selected_factory.clone(),
            ExperimentalLiveGate0QualificationVersion::parse(
                meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_GATE0_VERSION,
            )
            .expect("compiled qualification version"),
        )
        .with_gpt_live_client_context_profile()
        .expect("canonical client-context helper");
        assert_eq!(helper_operator, canonical_operator);
        let client_owner = ExperimentalLiveAdmissionOwner::configured_for_current_build(
            canonical_operator,
            [admitted_realm.clone()],
        );
        let client_qualification = client_owner
            .qualify_capability(&admitted_realm, &selected_factory)
            .expect("client-context build qualification");
        assert_eq!(
            client_qualification.protocol_digest,
            meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_PROTOCOL_DIGEST
        );
        assert_eq!(
            client_owner
                .advertised_feature_capabilities(
                    &client_qualification,
                    Some(GPT_LIVE_CLIENT_CONTEXT_PROFILE_ID),
                )
                .expect("client-context capability advertisement"),
            vec![
                meerkat_contracts::LIVE_EXECUTION_IDENTITY_V1_CAPABILITY,
                meerkat_contracts::LIVE_CLIENT_CONTEXT_V1_CAPABILITY,
            ]
        );

        let function_owner = ExperimentalLiveAdmissionOwner::configured_for_current_build(
            ExperimentalLiveOperatorConfig::new(
                selected_factory.clone(),
                ExperimentalLiveGate0QualificationVersion::parse(
                    meerkat_llm_core::provider_runtime::GPT_LIVE_CLIENT_CONTEXT_GATE0_VERSION,
                )
                .expect("compiled qualification version"),
            )
            .with_gpt_live_function_bridge_profile()
            .expect("canonical function-bridge profile shape"),
            [admitted_realm.clone()],
        );
        let function_qualification = function_owner
            .qualify_capability(&admitted_realm, &selected_factory)
            .expect("factory-level qualification remains client-bound");
        assert_eq!(
            function_owner
                .advertised_feature_capabilities(
                    &function_qualification,
                    Some(GPT_LIVE_FUNCTION_BRIDGE_PROFILE_ID),
                )
                .expect_err("unqualified FunctionBridge must not advertise"),
            ExperimentalLiveAdmissionError::ExecutionModeUnavailable
        );
        assert_eq!(
            function_owner
                .qualify_execution_profile(
                    &function_qualification,
                    GPT_LIVE_FUNCTION_BRIDGE_PROFILE_ID,
                )
                .expect_err("unqualified FunctionBridge must not select"),
            ExperimentalLiveAdmissionError::ExecutionModeUnavailable
        );
    }

    #[test]
    fn factory_gate0_release_stage_and_staleness_mismatches_fail_closed() {
        let admitted_realm = realm("voice");
        let selected_factory = factory("v1");
        let different_factory = factory("v2");

        let owner = ExperimentalLiveAdmissionOwner::for_test(
            true,
            Some(operator(selected_factory.clone())),
            BTreeSet::from([admitted_realm.clone()]),
            Some(gate0(selected_factory.clone())),
        );
        assert_eq!(
            owner
                .qualify_capability(&admitted_realm, &different_factory)
                .expect_err("operator factory mismatch"),
            ExperimentalLiveAdmissionError::OperatorFactoryMismatch
        );

        let gate_factory_mismatch = ExperimentalLiveAdmissionOwner::for_test(
            true,
            Some(operator(selected_factory.clone())),
            BTreeSet::from([admitted_realm.clone()]),
            Some(gate0(different_factory)),
        );
        assert_eq!(
            gate_factory_mismatch
                .qualify_capability(&admitted_realm, &selected_factory)
                .expect_err("Gate0 factory mismatch"),
            ExperimentalLiveAdmissionError::Gate0FactoryMismatch
        );

        let gate_version_mismatch = ExperimentalLiveAdmissionOwner::for_test(
            true,
            Some(ExperimentalLiveOperatorConfig::new(
                selected_factory.clone(),
                qualification("gate0-v2"),
            )),
            BTreeSet::from([admitted_realm.clone()]),
            Some(gate0(selected_factory.clone())),
        );
        assert_eq!(
            gate_version_mismatch
                .qualify_capability(&admitted_realm, &selected_factory)
                .expect_err("Gate0 version mismatch"),
            ExperimentalLiveAdmissionError::Gate0QualificationMismatch
        );

        let stale_gate0 = ExperimentalLiveAdmissionOwner::for_test(
            true,
            Some(operator(selected_factory.clone())),
            BTreeSet::from([admitted_realm.clone()]),
            Some(QualifiedGate0BuildWitness {
                factory: selected_factory.clone(),
                qualification: qualification("gate0-v1"),
                build_version: "stale-build".to_string(),
                protocol_digest: "ab".repeat(32),
                execution_mode: meerkat_core::LiveExecutionMode::FunctionBridge,
            }),
        );
        assert!(matches!(
            stale_gate0
                .qualify_capability(&admitted_realm, &selected_factory)
                .expect_err("stale Gate0 build"),
            ExperimentalLiveAdmissionError::Gate0BuildStale { .. }
        ));

        let qualification = owner
            .qualify_capability(&admitted_realm, &selected_factory)
            .expect("qualified");
        let (_, experimental_profile, _) = target_parts("gpt-live-1-codex");
        let (stable_identity, _, _) = target_parts("gpt-realtime-2");
        assert_eq!(
            owner
                .preflight(
                    qualification,
                    stable_identity,
                    experimental_profile,
                    GPT_LIVE_FUNCTION_BRIDGE_PROFILE_ID,
                )
                .expect_err("profile/identity substitution must fail"),
            ExperimentalLiveAdmissionError::TargetProfileMismatch
        );

        let (identity, profile, _) = target_parts("gpt-live-1-codex");
        let preflight = owner
            .preflight(
                owner
                    .qualify_capability(&admitted_realm, &selected_factory)
                    .expect("qualified"),
                identity,
                profile,
                GPT_LIVE_FUNCTION_BRIDGE_PROFILE_ID,
            )
            .expect("valid preflight");
        let wrong_provider_connection = ResolvedConnection {
            provider: Provider::Gemini,
            backend: NormalizedBackendKind::OpenAi(
                meerkat_core::provider_matrix::OpenAiBackendKind::ChatGptBackend,
            ),
            backend_profile: Arc::new(meerkat_core::BackendProfile {
                id: "wrong-provider".into(),
                provider: Provider::Gemini,
                backend_kind: "wrong_provider".into(),
                base_url: None,
                options: serde_json::Value::Null,
                server: None,
            }),
            credential_identity: meerkat_core::AuthCredentialIdentity::from_auth_binding(&binding()),
            auth_lease: Arc::new(StaticLease::empty_lease(AuthMetadata::default(), "test")),
        };
        assert_eq!(
            owner
                .complete(preflight, wrong_provider_connection, binding_use_witness())
                .expect_err("connection/provider substitution must fail"),
            ExperimentalLiveAdmissionError::ResolvedConnectionMismatch
        );
    }

    #[test]
    fn capability_advertisement_revalidates_owner_realm_and_factory() {
        let admitted_realm = realm("voice");
        let selected_factory = factory("v1");
        let owner = ExperimentalLiveAdmissionOwner::for_test(
            true,
            Some(operator(selected_factory.clone())),
            BTreeSet::from([admitted_realm.clone()]),
            Some(gate0(selected_factory.clone())),
        );
        let qualification = owner
            .qualify_capability(&admitted_realm, &selected_factory)
            .expect("qualified");
        assert_eq!(
            owner
                .advertised_feature_capabilities(&qualification, None)
                .expect("current witness advertises"),
            &[meerkat_contracts::LIVE_EXECUTION_IDENTITY_V1_CAPABILITY]
        );

        let replacement_owner = ExperimentalLiveAdmissionOwner::for_test(
            true,
            Some(operator(selected_factory.clone())),
            BTreeSet::from([admitted_realm.clone()]),
            Some(gate0(selected_factory.clone())),
        );
        assert_eq!(
            replacement_owner
                .advertised_feature_capabilities(&qualification, None)
                .expect_err("a reconfigured owner invalidates old qualification"),
            ExperimentalLiveAdmissionError::StaleCapabilityQualification
        );

        let mut stale_protocol = owner
            .qualify_capability(&admitted_realm, &selected_factory)
            .expect("qualified");
        stale_protocol.protocol_digest = "cd".repeat(32);
        assert_eq!(
            owner
                .advertised_feature_capabilities(&stale_protocol, None)
                .expect_err("same-semver protocol drift invalidates qualification"),
            ExperimentalLiveAdmissionError::StaleCapabilityQualification
        );
    }

    #[test]
    fn execution_capability_atoms_are_independent_and_fail_closed() {
        let admitted_realm = realm("voice-atoms");
        let selected_factory = factory("v1");
        let configured_operator = operator(selected_factory.clone())
            .with_execution_profile(
                "both-modes",
                meerkat_core::LiveExecutionMode::FunctionBridge,
                meerkat_core::LiveExecutionCapabilities {
                    function_bridge: true,
                    client_context: true,
                },
            )
            .expect("valid catalog profile");
        let owner = ExperimentalLiveAdmissionOwner::for_test(
            true,
            Some(configured_operator),
            BTreeSet::from([admitted_realm.clone()]),
            Some(gate0(selected_factory.clone())),
        );
        let qualification = owner
            .qualify_capability(&admitted_realm, &selected_factory)
            .expect("Gate0 qualification is present");
        assert_eq!(
            owner
                .advertised_feature_capabilities(&qualification, Some("both-modes"))
                .expect("qualified atoms advertise"),
            vec![
                meerkat_contracts::LIVE_EXECUTION_IDENTITY_V1_CAPABILITY,
                meerkat_contracts::LIVE_FUNCTION_BRIDGE_V1_CAPABILITY,
                meerkat_contracts::LIVE_CLIENT_CONTEXT_V1_CAPABILITY,
            ]
        );

        assert!(
            operator(selected_factory.clone())
                .with_execution_profile(
                    "unavailable-client-context",
                    meerkat_core::LiveExecutionMode::ClientContext,
                    meerkat_core::LiveExecutionCapabilities {
                        function_bridge: true,
                        client_context: false,
                    }
                )
                .is_err(),
            "a selected mode without its independent atom must fail closed"
        );

        let closed = ExperimentalLiveAdmissionOwner::default();
        assert_eq!(
            closed
                .qualify_capability(&admitted_realm, &selected_factory)
                .expect_err("no Gate0 means no capability advertisement"),
            if cfg!(feature = "experimental-gpt-live") {
                ExperimentalLiveAdmissionError::OperatorNotConfigured
            } else {
                ExperimentalLiveAdmissionError::FeatureNotCompiled
            }
        );
    }

    #[test]
    fn strict_profile_selection_carries_only_host_catalog_session_instructions() {
        let admitted_realm = realm("voice-profile-guidance");
        let selected_factory = factory("v1");
        let catalog_instructions = "Converse using the host-approved channel role.";
        let configured_operator = ExperimentalLiveOperatorConfig::new(
            selected_factory.clone(),
            qualification("gate0-v1"),
        )
        .with_execution_profile_session_instructions(
            "voice-room-v1",
            meerkat_core::LiveExecutionMode::FunctionBridge,
            meerkat_core::LiveExecutionCapabilities {
                function_bridge: true,
                client_context: false,
            },
            catalog_instructions,
        )
        .expect("valid catalog profile guidance");
        let debug = format!("{configured_operator:?}");
        assert!(!debug.contains(catalog_instructions));
        assert!(debug.contains("<catalog-bound>"));
        let owner = ExperimentalLiveAdmissionOwner::for_test(
            true,
            Some(configured_operator),
            BTreeSet::from([admitted_realm.clone()]),
            Some(gate0(selected_factory.clone())),
        );
        let (identity, profile, _) = target_parts("gpt-live-1-codex");
        let preflight = owner
            .preflight(
                owner
                    .qualify_capability(&admitted_realm, &selected_factory)
                    .expect("qualified"),
                identity.clone(),
                profile.clone(),
                "voice-room-v1",
            )
            .expect("registered profile selected");
        assert_eq!(preflight.execution_profile.profile_id(), "voice-room-v1");
        #[cfg(feature = "experimental-gpt-live")]
        assert_eq!(
            preflight.gpt_live_session_instructions.as_deref(),
            Some(catalog_instructions)
        );

        assert_eq!(
            owner
                .preflight(
                    owner
                        .qualify_capability(&admitted_realm, &selected_factory)
                        .expect("qualified"),
                    identity,
                    profile,
                    "caller-invented-profile",
                )
                .expect_err("unregistered profile must fail closed"),
            ExperimentalLiveAdmissionError::ExecutionModeUnavailable
        );
        assert_eq!(
            ExperimentalLiveOperatorConfig::new(selected_factory, qualification("gate0-v1"),)
                .with_execution_profile_session_instructions(
                    "blank-guidance",
                    meerkat_core::LiveExecutionMode::FunctionBridge,
                    meerkat_core::LiveExecutionCapabilities {
                        function_bridge: true,
                        client_context: false,
                    },
                    "   ",
                )
                .expect_err("blank profile guidance must fail"),
            ExperimentalLiveAdmissionError::InvalidSessionInstructions
        );
    }

    #[test]
    fn default_owner_is_operator_and_realm_closed() {
        let owner = ExperimentalLiveAdmissionOwner::default();
        assert!(owner.operator.is_none());
        assert!(owner.admitted_realms.is_empty());
    }

    #[test]
    fn typed_components_reject_empty_or_unsafe_values() {
        assert_eq!(
            ExperimentalLiveFactoryIdentity::parse("", "v1").expect_err("empty kind"),
            ExperimentalLiveAdmissionError::InvalidFactoryKind
        );
        assert_eq!(
            ExperimentalLiveFactoryIdentity::parse("live", "../v1").expect_err("unsafe version"),
            ExperimentalLiveAdmissionError::InvalidFactoryVersion
        );
        assert_eq!(
            ExperimentalLiveGate0QualificationVersion::parse("not valid")
                .expect_err("unsafe qualification"),
            ExperimentalLiveAdmissionError::InvalidGate0QualificationVersion
        );
    }
}