wip-host 0.2.0

Host-side object publication and operation dispatch for WIP
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
//! Host-side publication and operation dispatch for Web Interface Protocol objects.
//!
//! # Responsibility boundaries
//!
//! [`InterfaceRegistry::register`] validates and freezes a generated interface
//! descriptor at an explicit scope and local name, and leaves that reference
//! outside the descriptor. [`PublishedObject::expose`] explicitly combines a
//! request-scoped Rust object with a registered interface; its
//! [`InterfaceImplementation`] bound proves at compile time that the object
//! implements the interface. Implementing a Rust trait alone never publishes it,
//! and a publication with no interfaces is valid.
//!
//! [`ObjectProvider::call_operation`] resolves `target.path` exactly once and
//! keeps the resulting object, current scope Object association/ref, interface
//! membership, descriptor, implementation,
//! and backend target fixed within the provider's [`ObjectProvider::with_object`]
//! callback. Dispatch is qualified by `(interface reference, operation name)`.
//! The same frozen operation declaration validates both arguments and results.
//!
//! A provider is responsible for entering a backend transaction, lock,
//! stable-handle scope, or conditional-update primitive before invoking the
//! operation callback and retaining it through commit or rollback. The typed
//! [`OperationAttempt`] boundary distinguishes pre-dispatch rejection from started
//! execution. Only an implementation-supplied non-commit guarantee or a
//! provider-confirmed rollback allows a post-invocation failure to become
//! `Internal` or `ResourceLimitExceeded`; every other outcome is
//! `OperationOutcomeUnknown`. Mutable operations must make object-validator
//! comparison and backend commit atomic, and the validator returned after dispatch
//! must describe the state that becomes committed.

#![deny(missing_docs)]

use std::collections::{BTreeMap, HashMap, HashSet};
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::marker::PhantomData;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;

use wip_interface::DispatchError;
pub use wip_interface::{
    EffectGuarantee, HostError, HostErrorKind, InterfaceDefinition, InterfaceImplementation,
};
pub use wip_protocol;
pub use wip_protocol::{
    CallOperationRequest as CallRequest, CallOperationResponse as CallResult, InterfaceTarget,
    Target,
};
use wip_protocol::{
    FetchInterfaceRequest, FetchInterfaceResponse, InterfaceDescriptor, InterfaceReference, Object,
    ProtocolError, ProtocolErrorCode, ValidationError, Value,
};

/// Opaque bytes used as a conditional execution precondition.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Validator(Vec<u8>);

impl Validator {
    /// Creates a validator without assigning meaning to its bytes.
    #[must_use]
    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
        Self(bytes.into())
    }

    /// Returns the opaque bytes for transport encoding or comparison.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }
}

/// Runtime-neutral cooperative cancellation signal.
///
/// Clones observe the same atomic state, so transports, providers, and worker
/// runtimes can share the token without depending on a particular async runtime.
#[derive(Debug, Clone, Default)]
pub struct CancellationToken(Arc<AtomicBool>);

impl CancellationToken {
    /// Creates a cancellation token in the active state.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Requests cooperative cancellation.
    pub fn cancel(&self) {
        self.0.store(true, Ordering::Release);
    }

    /// Returns whether cancellation has been requested.
    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::Acquire)
    }
}

/// Execution controls propagated through object resolution and operation dispatch.
///
/// Cancellation and deadlines are checked immediately before typed implementation
/// invocation. Providers also receive the complete context and remain responsible
/// for enforcing controls while backend work is in progress. `resource_budget` is
/// an opaque Host-defined work-unit ceiling; this crate deliberately does not
/// prescribe an async runtime or accounting mechanism.
#[derive(Debug, Clone)]
pub struct ExecutionContext {
    cancellation: CancellationToken,
    deadline: Option<Instant>,
    resource_budget: Option<u64>,
}

impl Default for ExecutionContext {
    fn default() -> Self {
        Self {
            cancellation: CancellationToken::new(),
            deadline: None,
            resource_budget: None,
        }
    }
}

impl ExecutionContext {
    /// Creates an execution context without a deadline or resource budget.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Uses `cancellation` as this call's cooperative cancellation signal.
    #[must_use]
    pub fn with_cancellation(mut self, cancellation: CancellationToken) -> Self {
        self.cancellation = cancellation;
        self
    }

    /// Sets the monotonic deadline for this call.
    #[must_use]
    pub fn with_deadline(mut self, deadline: Instant) -> Self {
        self.deadline = Some(deadline);
        self
    }

    /// Sets an opaque Host-defined work-unit ceiling for this call.
    #[must_use]
    pub fn with_resource_budget(mut self, resource_budget: u64) -> Self {
        self.resource_budget = Some(resource_budget);
        self
    }

    /// Returns the shared cooperative cancellation token.
    #[must_use]
    pub fn cancellation(&self) -> &CancellationToken {
        &self.cancellation
    }

    /// Returns the monotonic deadline, if one was supplied.
    #[must_use]
    pub fn deadline(&self) -> Option<Instant> {
        self.deadline
    }

    /// Returns the opaque Host-defined work-unit ceiling, if one was supplied.
    #[must_use]
    pub fn resource_budget(&self) -> Option<u64> {
        self.resource_budget
    }

    fn preflight(&self) -> Result<(), CallError> {
        if self.cancellation.is_cancelled() {
            return Err(CallError::new(
                CallErrorKind::ResourceLimitExceeded,
                "operation was cancelled before execution",
            ));
        }
        if self
            .deadline
            .is_some_and(|deadline| Instant::now() >= deadline)
        {
            return Err(CallError::new(
                CallErrorKind::ResourceLimitExceeded,
                "operation deadline elapsed before execution",
            ));
        }
        Ok(())
    }
}

/// One publication lifetime of the Object at a canonical scope path.
///
/// Clone while the same Object remains published, including state updates. Create
/// a new handle after deletion, replacement or movement, even with the same ref.
/// This private lifetime is not a Protocol identity component or generated ref.
#[derive(Debug, Clone)]
pub struct Scope {
    path: String,
    lifetime: Arc<AtomicBool>,
}

impl Scope {
    /// Creates a fresh lifetime without implicitly publishing an Object.
    pub fn new(path: impl Into<String>) -> Result<Self, ValidationError> {
        let path = path.into();
        wip_protocol::validate_path(&path)?;
        Ok(Self {
            path,
            lifetime: Arc::new(AtomicBool::new(true)),
        })
    }

    /// Returns the client-facing canonical scope path.
    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    fn same_lifetime(&self, other: &Self) -> bool {
        self.path == other.path && Arc::ptr_eq(&self.lifetime, &other.lifetime)
    }

    fn active(&self) -> bool {
        self.lifetime.load(Ordering::Acquire)
    }
}

/// Provider-attested current scope Object association.
///
/// Construct only inside a coherent boundary that proves this lifetime belongs
/// to the Object at `scope.path()`. A prelookup or matching ref alone is not proof.
/// The Object need not expose interfaces. Its validator is not scope identity.
#[derive(Debug, Clone)]
pub struct ScopeObservation {
    scope: Scope,
    reference: Option<String>,
}

impl ScopeObservation {
    /// Attests the association and captures the current Object's optional ref.
    #[must_use]
    pub fn new(scope: &Scope, object: &impl WipObject) -> Self {
        Self {
            scope: scope.clone(),
            reference: object.reference().map(str::to_owned),
        }
    }

    /// Returns the observed optional ref.
    #[must_use]
    pub fn reference(&self) -> Option<&str> {
        self.reference.as_deref()
    }

    /// Returns the associated scope publication lifetime.
    #[must_use]
    pub fn scope(&self) -> &Scope {
        &self.scope
    }
}

/// Structured client-facing reference to a scoped Interface publication.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InterfaceRef(InterfaceReference);

impl InterfaceRef {
    /// Returns the local name without parsing or adding display delimiters.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0.name
    }

    /// Returns the structured Protocol reference.
    #[must_use]
    pub fn protocol_reference(&self) -> InterfaceReference {
        self.0.clone()
    }
}

/// One atomic observation of an interface reference, descriptor, and validator.
#[derive(Debug, Clone, PartialEq)]
pub struct InterfaceObservation {
    /// Structured reference selected by published objects and operation calls.
    pub reference: InterfaceRef,
    /// Canonical descriptor frozen when the interface was registered.
    pub descriptor: InterfaceDescriptor,
    /// Optional ref of the scope Object from this same observation.
    pub scope_ref: Option<String>,
    /// Optional validator. Its presence makes it a required call precondition.
    pub validator: Option<Validator>,
}

impl InterfaceObservation {
    /// Restricts this effective view to visible operations and reachable types.
    ///
    /// Registry artifacts are unchanged. When operations are removed, interface-
    /// wide documentation is omitted because it may describe hidden operations.
    /// Providers must use the same predicate for publication and fetch.
    #[must_use]
    pub fn project_operations(mut self, visible: impl Fn(&str) -> bool) -> Self {
        restrict_descriptor(&mut self.descriptor, visible);
        self
    }

    /// Converts this host observation to a validated canonical protocol response.
    ///
    /// A Host-side response construction failure is returned as `Internal`; it is
    /// never emitted as a successful response for a Client to reinterpret as a
    /// local validation error.
    pub fn protocol_response(&self) -> Result<FetchInterfaceResponse, ProtocolError> {
        let response = FetchInterfaceResponse {
            interface: self.reference.protocol_reference(),
            descriptor: self.descriptor.clone(),
            scope_ref: self.scope_ref.clone(),
            validator: self.validator.as_ref().map(|validator| validator.0.clone()),
        };
        response
            .validate_for(&FetchInterfaceRequest {
                interface: self.reference.protocol_reference(),
            })
            .map_err(|_| ProtocolError {
                code: ProtocolErrorCode::Internal,
                message: "Host produced an invalid interface response".into(),
            })?;
        Ok(response)
    }
}

#[derive(Debug)]
struct InterfaceArtifact {
    scope: Scope,
    reference: InterfaceRef,
    descriptor: InterfaceDescriptor,
    validator: Option<Validator>,
}

/// A typed registration token for a generated interface definition.
///
/// Tokens can be reused by any number of request-scoped objects. They expose an
/// scoped reference and a private publication lifetime, not a Rust address.
pub struct RegisteredInterface<D> {
    artifact: Arc<InterfaceArtifact>,
    definition: PhantomData<fn() -> D>,
}

impl<D> Clone for RegisteredInterface<D> {
    fn clone(&self) -> Self {
        Self {
            artifact: Arc::clone(&self.artifact),
            definition: PhantomData,
        }
    }
}

impl<D> RegisteredInterface<D> {
    /// Returns the explicit scope/name reference.
    #[must_use]
    pub fn reference(&self) -> &InterfaceRef {
        &self.artifact.reference
    }
}

/// Registry of frozen definition artifacts and explicitly scoped registrations.
///
/// Artifact retention is not proof of current publication. Fetch requires a live
/// provider-attested ScopeObservation; execution requires the same lifetime in
/// the target's atomic boundary. Collision keys are exact (scope, name) pairs,
/// not Rust TypeId: the same Definition can be registered at multiple coordinates.
#[derive(Debug, Default)]
pub struct InterfaceRegistry {
    artifacts: HashMap<InterfaceRef, Arc<InterfaceArtifact>>,
}

impl InterfaceRegistry {
    /// Creates an empty artifact registry without publishing any Object.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Freezes a Definition at an explicit scope and local name.
    pub fn register<D>(
        &mut self,
        scope: &Scope,
        name: impl Into<String>,
        _definition: D,
        validator: Option<Validator>,
    ) -> Result<RegisteredInterface<D>, RegistrationError>
    where
        D: InterfaceDefinition + 'static,
    {
        let reference = InterfaceRef(InterfaceReference {
            scope: scope.path.clone(),
            name: name.into(),
        });
        reference
            .0
            .validate()
            .map_err(RegistrationError::InvalidReference)?;
        if !scope.active() {
            return Err(RegistrationError::RetiredScope);
        }
        if self.artifacts.contains_key(&reference) {
            return Err(RegistrationError::AlreadyRegistered);
        }
        let descriptor = D::descriptor();
        descriptor
            .validate()
            .map_err(RegistrationError::InvalidDescriptor)?;
        let artifact = Arc::new(InterfaceArtifact {
            scope: scope.clone(),
            reference: reference.clone(),
            descriptor,
            validator,
        });
        self.artifacts.insert(reference, Arc::clone(&artifact));
        Ok(RegisteredInterface {
            artifact,
            definition: PhantomData,
        })
    }

    /// Ends a scope lifetime and releases its registry entries.
    ///
    /// Retained tokens cannot start new calls/fetches. Started calls retain their
    /// frozen Descriptor. Re-publication requires a fresh Scope.
    pub fn remove_scope(&mut self, scope: &Scope) {
        scope.lifetime.store(false, Ordering::Release);
        self.artifacts
            .retain(|_, artifact| !artifact.scope.same_lifetime(scope));
    }

    /// Resolves a stored artifact, not evidence of current publication.
    #[must_use]
    pub fn resolve(&self, reference: &InterfaceReference) -> Option<InterfaceRef> {
        let reference = InterfaceRef(reference.clone());
        self.artifacts.contains_key(&reference).then_some(reference)
    }

    /// Iterates registered scope handles, possibly repeated for multiple names.
    pub fn scopes(&self) -> impl Iterator<Item = &Scope> {
        self.artifacts.values().map(|artifact| &artifact.scope)
    }

    /// Fetches only with a coherent current scope Object attestation.
    pub fn fetch_interface(
        &self,
        reference: &InterfaceReference,
        current: &ScopeObservation,
    ) -> Result<InterfaceObservation, ProtocolError> {
        reference.validate().map_err(|error| ProtocolError {
            code: ProtocolErrorCode::InvalidRequest,
            message: error.to_string(),
        })?;
        self.artifacts
            .get(&InterfaceRef(reference.clone()))
            .filter(|artifact| {
                artifact.scope.active() && artifact.scope.same_lifetime(&current.scope)
            })
            .map(|artifact| InterfaceObservation {
                reference: artifact.reference.clone(),
                descriptor: artifact.descriptor.clone(),
                scope_ref: current.reference.clone(),
                validator: artifact.validator.clone(),
            })
            .ok_or_else(interface_not_found)
    }
}

fn interface_not_found() -> ProtocolError {
    ProtocolError {
        code: ProtocolErrorCode::InterfaceNotFound,
        message: "interface is not currently published".into(),
    }
}

/// Failure while registering a generated interface Definition.
#[derive(Debug)]
pub enum RegistrationError {
    /// The exact scope/name coordinate is already occupied.
    AlreadyRegistered,
    /// The generated Descriptor is invalid.
    InvalidDescriptor(ValidationError),
    /// The scope or local name is invalid.
    InvalidReference(ValidationError),
    /// The lifetime ended; re-publication needs a fresh Scope.
    RetiredScope,
}

impl Display for RegistrationError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::AlreadyRegistered => {
                formatter.write_str("interface scope/name already registered")
            }
            Self::InvalidDescriptor(error) => {
                write!(formatter, "invalid interface descriptor: {error}")
            }
            Self::InvalidReference(error) => {
                write!(formatter, "invalid interface reference: {error}")
            }
            Self::RetiredScope => formatter.write_str("scope publication lifetime has ended"),
        }
    }
}
impl Error for RegistrationError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::InvalidDescriptor(error) | Self::InvalidReference(error) => Some(error),
            Self::AlreadyRegistered | Self::RetiredScope => None,
        }
    }
}

/// Public metadata and conditional-execution policy for a host-private object.
///
/// Only values returned by this trait are projected into protocol metadata.
/// Paths, children, backend handles, credentials, and resolution state are not
/// part of this API and therefore cannot be serialized into [`Object`].
pub trait WipObject {
    /// Returns the public path-segment name of this object.
    fn name(&self) -> &str;

    /// Returns a short public description, if one is available.
    fn description(&self) -> Option<&str> {
        None
    }

    /// Returns optional opaque identity within the client-facing Worldspace.
    fn reference(&self) -> Option<&str> {
        None
    }

    /// Returns the current opaque object validator, if any.
    fn validator(&self) -> Option<&Validator> {
        None
    }

    /// Whether this specific qualified operation requires an object validator.
    ///
    /// This hook is evaluated only after membership, interface validators, and
    /// operation existence have been checked, preserving canonical precedence.
    fn requires_validator(&self, _interface: &InterfaceRef, _operation: &str) -> bool {
        false
    }
}

fn restrict_descriptor(descriptor: &mut InterfaceDescriptor, visible: impl Fn(&str) -> bool) {
    let count = descriptor.operations.len();
    descriptor
        .operations
        .retain(|operation| visible(&operation.name));
    if descriptor.operations.len() == count {
        return;
    }
    descriptor.documentation = None;
    let mut used = HashSet::new();
    fn references(expression: &wip_protocol::TypeExpr, used: &mut HashSet<String>) {
        use wip_protocol::TypeExpr;
        match expression {
            TypeExpr::Named { name } => {
                used.insert(name.clone());
            }
            TypeExpr::Record { fields } => {
                for field in fields {
                    references(&field.r#type, used);
                }
            }
            TypeExpr::List { items } => references(items, used),
            TypeExpr::Union { cases } => {
                for case in cases {
                    if let Some(payload) = &case.payload {
                        references(payload, used);
                    }
                }
            }
            _ => {}
        }
    }
    for operation in &descriptor.operations {
        for parameter in &operation.parameters {
            references(&parameter.r#type, &mut used);
        }
        references(&operation.returns.r#type, &mut used);
    }
    loop {
        let before = used.len();
        for declaration in &descriptor.types {
            if used.contains(&declaration.name) {
                references(&declaration.definition, &mut used);
            }
        }
        if before == used.len() {
            break;
        }
    }
    descriptor
        .types
        .retain(|declaration| used.contains(&declaration.name));
}

type DispatchFn<T> = fn(&T, &str, BTreeMap<String, Value>) -> Result<Value, DispatchError>;

struct BoundInterface<T> {
    artifact: Arc<InterfaceArtifact>,
    dispatch: DispatchFn<T>,
}

/// A host-private object instance combined with an explicit ordered interface set.
///
/// The instance is owned by this value and can therefore be request-scoped. No
/// global object registry is required. Worldspace paths remain provider context
/// and are deliberately absent from the publication.
pub struct PublishedObject<T: WipObject> {
    implementation: T,
    interfaces: Vec<BoundInterface<T>>,
    scopes: Vec<ScopeObservation>,
}

impl<T: WipObject> PublishedObject<T> {
    /// Starts a publication with no exposed interfaces.
    #[must_use]
    pub fn new(implementation: T) -> Self {
        Self {
            implementation,
            interfaces: Vec::new(),
            scopes: Vec::new(),
        }
    }

    /// Attaches a current scope snapshot inside the provider's atomic boundary.
    ///
    /// Never populate this from a stale prelookup. Target, scope association,
    /// Descriptor and backend handles must remain coherent through dispatch and
    /// commit. A later same-path binding replaces the earlier snapshot.
    #[must_use]
    pub fn bind_scope(mut self, current: ScopeObservation) -> Self {
        self.scopes
            .retain(|old| old.scope.path != current.scope.path);
        self.scopes.push(current);
        self
    }

    fn current_scope(&self, scope: &Scope) -> Option<&ScopeObservation> {
        self.scopes
            .iter()
            .find(|current| scope.active() && scope.same_lifetime(&current.scope))
    }

    fn scopes_valid_at(&self, path: &str) -> bool {
        self.interfaces.iter().all(|bound| {
            bound.artifact.reference.0.validate_for_path(path).is_ok()
                && self
                    .current_scope(&bound.artifact.scope)
                    .is_some_and(|current| {
                        current.scope.path != path
                            || current.reference() == self.implementation.reference()
                    })
        })
    }

    /// Explicitly exposes a registered generated interface in insertion order.
    ///
    /// The `InterfaceImplementation<T>` bound is generated only when `T`
    /// implements the corresponding Rust interface trait. Duplicate scoped
    /// references are rejected.
    pub fn expose<D>(mut self, interface: &RegisteredInterface<D>) -> Result<Self, PublicationError>
    where
        D: InterfaceImplementation<T>,
    {
        if self
            .interfaces
            .iter()
            .any(|bound| bound.artifact.reference == interface.artifact.reference)
        {
            return Err(PublicationError::DuplicateInterface(
                interface.artifact.reference.clone(),
            ));
        }

        self.interfaces.push(BoundInterface {
            artifact: Arc::clone(&interface.artifact),
            dispatch: D::dispatch,
        });
        Ok(self)
    }

    /// Restricts a publication to an ordered interface/operation view.
    ///
    /// This never adds implementations or changes codecs. The provider must use
    /// the identical operation predicate for `fetch_interface`, and keep the
    /// effective view stable for the lifetime of its references. Filtered
    /// descriptors are scoped to that view, not mutations of registry artifacts.
    pub fn project(
        mut self,
        interfaces: &[InterfaceRef],
        visible: impl Fn(&InterfaceRef, &str) -> bool,
    ) -> Result<Self, PublicationError> {
        let mut projected = Vec::with_capacity(interfaces.len());
        for reference in interfaces {
            if projected
                .iter()
                .any(|bound: &BoundInterface<T>| &bound.artifact.reference == reference)
            {
                return Err(PublicationError::DuplicateInterface(reference.clone()));
            }
            let Some(index) = self
                .interfaces
                .iter()
                .position(|bound| &bound.artifact.reference == reference)
            else {
                return Err(PublicationError::UnexposedInterface(reference.clone()));
            };
            let mut bound = self.interfaces.remove(index);
            let mut descriptor = bound.artifact.descriptor.clone();
            restrict_descriptor(&mut descriptor, |operation| visible(reference, operation));
            bound.artifact = Arc::new(InterfaceArtifact {
                scope: bound.artifact.scope.clone(),
                reference: reference.clone(),
                descriptor,
                validator: bound.artifact.validator.clone(),
            });
            projected.push(bound);
        }
        self.interfaces = projected;
        Ok(self)
    }

    /// Returns the host-private implementation without projecting its fields.
    #[must_use]
    pub fn implementation(&self) -> &T {
        &self.implementation
    }

    /// Builds metadata from the explicit exposure set in insertion order.
    ///
    /// This path-free projection is useful while composing a publication, but is
    /// not proof that its scopes are currently published. Use
    /// [`ObjectProvider::observe_object`] for a validated current observation, or
    /// [`Self::protocol_object_at`] inside a provider's coherent boundary.
    /// The metadata contains no path, children, descriptor, backend handle,
    /// credential, or provider resolution state.
    #[must_use]
    pub fn protocol_object(&self) -> Object {
        Object {
            name: self.implementation.name().to_owned(),
            description: self.implementation.description().map(str::to_owned),
            interfaces: self
                .interfaces
                .iter()
                .map(|bound| bound.artifact.reference.protocol_reference())
                .collect(),
            r#ref: self.implementation.reference().map(str::to_owned),
            validator: self
                .implementation
                .validator()
                .map(|validator| validator.0.clone()),
        }
    }

    /// Validates a current Object observation inside the provider's boundary.
    ///
    /// All exposed interfaces must have compatible, live scope associations. The
    /// provider must still establish those associations atomically; this method
    /// cannot verify backend lifetime assertions or lock external writers.
    pub fn protocol_object_at(&self, path: &str) -> Result<Object, CallError> {
        wip_protocol::validate_path(path)
            .map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
        if !self.scopes_valid_at(path) {
            return Err(CallError::new(
                CallErrorKind::Internal,
                "Host published interfaces without current compatible scope Objects",
            ));
        }
        let object = self.protocol_object();
        object.validate_at_path(path).map_err(|_| {
            CallError::new(
                CallErrorKind::Internal,
                "Host produced an invalid object response",
            )
        })?;
        Ok(object)
    }

    fn dispatch_resolved(
        &self,
        context: &ExecutionContext,
        request: CallRequest,
        authorize: impl FnOnce(&T, &InterfaceRef, &str) -> bool,
    ) -> OperationAttempt {
        let CallRequest {
            target,
            interface,
            operation,
            arguments,
        } = request;
        self.dispatch_resolved_with_decoder(
            context,
            target,
            interface,
            operation,
            |_| Ok::<_, std::convert::Infallible>(arguments),
            authorize,
        )
    }

    fn dispatch_resolved_with_decoder<E>(
        &self,
        context: &ExecutionContext,
        target: Target,
        interface: InterfaceTarget,
        operation: String,
        decode_arguments: impl FnOnce(&InterfaceDescriptor) -> Result<BTreeMap<String, Value>, E>,
        authorize: impl FnOnce(&T, &InterfaceRef, &str) -> bool,
    ) -> OperationAttempt {
        let pre_dispatch_failure =
            |kind, message: &str| OperationAttempt::NotStarted(CallError::new(kind, message));
        let current_object_validator = self.implementation.validator();
        if let Some(supplied) = target.validator.as_deref()
            && current_object_validator.map(Validator::as_bytes) != Some(supplied)
        {
            return pre_dispatch_failure(
                CallErrorKind::ValidatorMismatch,
                "object validator does not match current object state",
            );
        }

        if interface.reference.validate_for_path(&target.path).is_err() {
            return pre_dispatch_failure(
                CallErrorKind::InterfaceMismatch,
                "interface scope is not an ancestor of the target path",
            );
        }

        let Some(bound) = self
            .interfaces
            .iter()
            .find(|bound| bound.artifact.reference.protocol_reference() == interface.reference)
        else {
            return pre_dispatch_failure(
                CallErrorKind::InterfaceMismatch,
                "interface is not a member of the current object publication",
            );
        };

        let Some(current_scope) = self.current_scope(&bound.artifact.scope) else {
            return pre_dispatch_failure(
                CallErrorKind::InterfaceMismatch,
                "interface scope Object is not currently associated with this publication",
            );
        };
        if current_scope.scope.path == target.path
            && current_scope.reference() != self.implementation.reference()
        {
            return pre_dispatch_failure(
                CallErrorKind::Internal,
                "provider produced inconsistent self-scope metadata",
            );
        }
        if interface
            .scope_ref
            .as_deref()
            .is_some_and(|supplied| current_scope.reference() != Some(supplied))
        {
            return pre_dispatch_failure(
                CallErrorKind::InterfaceMismatch,
                "scope Object ref does not match the current association",
            );
        }

        match (
            bound.artifact.validator.as_ref(),
            interface.validator.as_deref(),
        ) {
            (Some(_), None) => {
                return pre_dispatch_failure(
                    CallErrorKind::InterfaceValidatorRequired,
                    "registered interface requires a validator",
                );
            }
            (expected, Some(actual)) if expected.map(Validator::as_bytes) != Some(actual) => {
                return pre_dispatch_failure(
                    CallErrorKind::InterfaceValidatorMismatch,
                    "interface validator does not match the registered descriptor",
                );
            }
            _ => {}
        }

        if !bound
            .artifact
            .descriptor
            .operations
            .iter()
            .any(|declared| declared.name == operation)
        {
            return pre_dispatch_failure(
                CallErrorKind::OperationNotFound,
                &format!("operation `{operation}` is not declared"),
            );
        }

        if target.validator.is_none()
            && self
                .implementation
                .requires_validator(&bound.artifact.reference, &operation)
        {
            return pre_dispatch_failure(
                CallErrorKind::ValidatorRequired,
                "this operation requires an object validator",
            );
        }

        let arguments = match decode_arguments(&bound.artifact.descriptor) {
            Ok(arguments) => arguments,
            Err(_) => {
                return pre_dispatch_failure(
                    CallErrorKind::InvalidArguments,
                    "operation arguments could not be decoded",
                );
            }
        };
        if let Err(error) = bound
            .artifact
            .descriptor
            .validate_arguments(&operation, &arguments)
        {
            return pre_dispatch_failure(CallErrorKind::InvalidArguments, &error.to_string());
        }

        if !authorize(&self.implementation, &bound.artifact.reference, &operation) {
            return pre_dispatch_failure(
                CallErrorKind::PermissionDenied,
                "operation is not permitted for this caller",
            );
        }

        if let Err(error) = context.preflight() {
            return OperationAttempt::NotStarted(error);
        }

        let value = match (bound.dispatch)(&self.implementation, &operation, arguments) {
            Ok(value) => value,
            Err(
                error @ (DispatchError::UnknownOperation(_)
                | DispatchError::InvalidArguments(_)
                | DispatchError::Decode(_)),
            ) => return OperationAttempt::NotStarted(CallError::from_pre_dispatch(error)),
            Err(error) => {
                return OperationAttempt::Started(Err(OperationFailure::from_dispatch(error)));
            }
        };

        if bound
            .artifact
            .descriptor
            .validate_result(&operation, &value)
            .is_err()
        {
            return OperationAttempt::Started(Err(OperationFailure::internal(
                EffectGuarantee::Unknown,
                "operation implementation produced an invalid result",
            )));
        }

        OperationAttempt::Started(Ok(CallResult {
            result: value,
            validator: self
                .implementation
                .validator()
                .map(|validator| validator.0.clone()),
        }))
    }

    /// Consumes the publication and returns its host-private implementation.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.implementation
    }
}

/// A post-invocation failure awaiting final provider effect disposition.
///
/// Providers may upgrade an unknown failure with [`confirm_rollback`](Self::confirm_rollback)
/// only after the backend transaction has definitely rolled back. Diagnostics are
/// intentionally generic and safe for protocol exposure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationFailure {
    kind: HostErrorKind,
    effect_guarantee: EffectGuarantee,
    message: String,
}

impl OperationFailure {
    fn internal(effect_guarantee: EffectGuarantee, message: impl Into<String>) -> Self {
        Self {
            kind: HostErrorKind::Internal,
            effect_guarantee,
            message: bounded_message(message.into()),
        }
    }

    fn from_dispatch(error: DispatchError) -> Self {
        match error {
            DispatchError::Host(error) => Self {
                kind: error.kind(),
                effect_guarantee: error.effect_guarantee(),
                message: match error.kind() {
                    HostErrorKind::Internal => "operation implementation failed".into(),
                    HostErrorKind::ResourceLimitExceeded => {
                        "operation resource limit was exceeded".into()
                    }
                },
            },
            DispatchError::Panic => Self::internal(
                EffectGuarantee::Unknown,
                "operation implementation panicked",
            ),
            DispatchError::Encode(_) => Self::internal(
                EffectGuarantee::Unknown,
                "operation result could not be encoded",
            ),
            DispatchError::InvalidResult(_) => Self::internal(
                EffectGuarantee::Unknown,
                "operation implementation produced an invalid result",
            ),
            DispatchError::UnknownOperation(_)
            | DispatchError::InvalidArguments(_)
            | DispatchError::Decode(_) => {
                unreachable!("pre-dispatch failures are classified before OperationFailure")
            }
        }
    }

    /// Returns the Host failure category used when effects are not committed.
    #[must_use]
    pub fn kind(&self) -> HostErrorKind {
        self.kind
    }

    /// Returns the current effect guarantee.
    #[must_use]
    pub fn effect_guarantee(&self) -> EffectGuarantee {
        self.effect_guarantee
    }

    /// Confirms that the provider rolled back all operation effects.
    ///
    /// Calling this method is a semantic assertion by the provider and must occur
    /// only after its atomic backend boundary has completed rollback.
    #[must_use]
    pub fn confirm_rollback(mut self) -> Self {
        self.effect_guarantee = EffectGuarantee::NotCommitted;
        self
    }
}

/// Dispatch progress returned to the provider's atomic execution boundary.
#[derive(Debug)]
pub enum OperationAttempt {
    /// A canonical precondition failed and typed implementation code did not run.
    NotStarted(CallError),
    /// Typed implementation invocation began, with either a result or a typed
    /// post-invocation failure.
    Started(Result<CallResult, OperationFailure>),
}

impl OperationAttempt {
    /// Rejects a provider precondition before typed implementation invocation.
    ///
    /// Only use this before dispatch starts; post-invocation failures require
    /// an explicit effect disposition. The diagnostic is intentionally generic.
    #[must_use]
    pub fn reject(kind: CallErrorKind) -> Self {
        Self::NotStarted(CallError::new(kind, "provider precondition failed"))
    }

    /// Marks a post-invocation failure as fully rolled back.
    ///
    /// Successful attempts and pre-dispatch failures are returned unchanged.
    #[must_use]
    pub fn confirm_rollback(self) -> Self {
        match self {
            Self::Started(Err(error)) => Self::Started(Err(error.confirm_rollback())),
            other => other,
        }
    }
}

/// Result of one provider resolution or execution boundary.
#[derive(Debug)]
pub enum ProviderResult<T> {
    /// The path resolved and the provider callback completed.
    Found(T),
    /// The path is not currently published to this caller.
    NotFound,
    /// Provider or backend execution failed.
    ///
    /// During `call_operation`, the embedded effect guarantee determines whether
    /// the failure is safe to expose as `Internal`/`ResourceLimitExceeded` or must
    /// become `OperationOutcomeUnknown`.
    Failure(HostError),
}

/// A request-scoped Worldspace resolver and execution boundary.
///
/// `with_object` must resolve the current object at `path` exactly once and pass
/// a publication that pins its current interface set, implementations, and
/// backend target and all current scope Object associations for the duration of
/// `operation`. Attach them with PublishedObject::bind_scope inside this same
/// boundary, never via an independent scope prelookup. A new Object at the same
/// path needs a fresh Scope; ordinary state changes retain the handle. Providers
/// own lifetime/atomicity enforcement, including external writers and backend
/// commit/rollback. The execution context is the
/// runtime-neutral carrier for cancellation, deadline, and resource controls.
/// The borrowed publication cannot escape the callback.
///
/// Providers that can roll back mutable operations should override
/// [`ObjectProvider::execute_operation`], hold their transaction across the
/// callback, and call [`OperationAttempt::confirm_rollback`] only after rollback
/// succeeds. The default boundary conservatively preserves unknown outcomes.
pub trait ObjectProvider {
    /// Host-private object type produced by this provider.
    type Object: WipObject;

    /// Runs a callback against the single object snapshot resolved at `path`.
    fn with_object<R>(
        &self,
        context: &ExecutionContext,
        path: &str,
        operation: impl FnOnce(&PublishedObject<Self::Object>) -> R,
    ) -> ProviderResult<R>;

    /// Runs one operation attempt inside the provider's atomic backend boundary.
    ///
    /// The default implementation delegates to [`ObjectProvider::with_object`]
    /// and therefore does not add a rollback guarantee. Transactional providers
    /// can override this method, inspect the returned [`OperationAttempt`], roll
    /// back a failed started attempt, and return its confirmed form.
    fn execute_operation(
        &self,
        context: &ExecutionContext,
        path: &str,
        operation: impl FnOnce(&PublishedObject<Self::Object>) -> OperationAttempt,
    ) -> ProviderResult<OperationAttempt> {
        self.with_object(context, path, operation)
    }

    /// Decides whether a declared operation may execute for the current caller.
    ///
    /// The hook runs after all validators, membership, operation lookup, and
    /// argument validation, but before implementation code. Returning `false`
    /// exposes the operation while producing `PermissionDenied`.
    fn authorize(
        &self,
        _path: &str,
        _object: &Self::Object,
        _interface: &InterfaceRef,
        _operation: &str,
    ) -> bool {
        true
    }

    /// Observes the canonical object projection currently published at `path`.
    fn observe_object(&self, path: &str) -> Result<Object, CallError> {
        self.observe_object_with_context(&ExecutionContext::default(), path)
    }

    /// Observes an object while propagating runtime execution controls.
    fn observe_object_with_context(
        &self,
        context: &ExecutionContext,
        path: &str,
    ) -> Result<Object, CallError> {
        wip_protocol::validate_path(path)
            .map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
        let resolved = catch_unwind(AssertUnwindSafe(|| {
            self.with_object(context, path, |publication| {
                publication.protocol_object_at(path)
            })
        }))
        .map_err(|_| {
            CallError::new(
                CallErrorKind::Internal,
                "provider panicked while observing an object",
            )
        })?;
        let object = match resolved {
            ProviderResult::Found(object) => object?,
            ProviderResult::NotFound => {
                return Err(CallError::new(
                    CallErrorKind::NotFound,
                    "target path is not published",
                ));
            }
            ProviderResult::Failure(error) => return Err(CallError::from_read_failure(error)),
        };
        Ok(object)
    }

    /// Fetches Descriptor, scope Object ref and Interface validator atomically.
    ///
    /// The scope Object may expose no interfaces. Its publication must still
    /// bind the live ScopeObservation. Registry retention is not publication.
    fn fetch_interface(
        &self,
        registry: &InterfaceRegistry,
        reference: &InterfaceReference,
    ) -> Result<InterfaceObservation, ProtocolError> {
        reference.validate().map_err(|error| ProtocolError {
            code: ProtocolErrorCode::InvalidRequest,
            message: error.to_string(),
        })?;
        let observed = catch_unwind(AssertUnwindSafe(|| {
            self.with_object(
                &ExecutionContext::default(),
                &reference.scope,
                |publication| {
                    publication
                        .scopes
                        .iter()
                        .find(|current| current.scope.path == reference.scope)
                        .ok_or_else(interface_not_found)
                        .and_then(|current| {
                            if current.reference() != publication.implementation.reference() {
                                return Err(ProtocolError {
                                    code: ProtocolErrorCode::Internal,
                                    message: "provider produced inconsistent scope Object metadata"
                                        .into(),
                                });
                            }
                            registry.fetch_interface(reference, current)
                        })
                },
            )
        }))
        .map_err(|_| ProtocolError {
            code: ProtocolErrorCode::Internal,
            message: "provider panicked while observing an interface".into(),
        })?;
        match observed {
            ProviderResult::Found(observation) => observation,
            ProviderResult::NotFound => Err(interface_not_found()),
            ProviderResult::Failure(error) => {
                Err(CallError::from_read_failure(error).protocol_error())
            }
        }
    }

    /// Resolves and executes a canonical path-targeted operation request.
    ///
    /// Structural path validation precedes provider resolution. For a valid
    /// request, failure checks follow the exact canonical precedence: path,
    /// supplied object validator mismatch, membership, interface validator
    /// requirement and mismatch, operation existence, object validator
    /// requirement, arguments, then authorization. No failed precondition
    /// invokes typed implementation code.
    fn call_operation(&self, request: CallRequest) -> Result<CallResult, CallError> {
        self.call_operation_with_context(&ExecutionContext::default(), request)
    }

    /// Executes an operation while propagating cancellation, deadline, and
    /// resource-budget controls to the provider and runtime preflight check.
    fn call_operation_with_context(
        &self,
        context: &ExecutionContext,
        request: CallRequest,
    ) -> Result<CallResult, CallError> {
        wip_protocol::validate_path(&request.target.path)
            .map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
        request
            .interface
            .reference
            .validate()
            .map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
        let path = request.target.path.clone();
        let execution = catch_unwind(AssertUnwindSafe(|| {
            self.execute_operation(context, &path, |publication| {
                publication.dispatch_resolved(context, request, |object, interface, operation| {
                    self.authorize(&path, object, interface, operation)
                })
            })
        }));

        let execution = execution.map_err(|_| {
            CallError::from_operation_failure(OperationFailure::internal(
                EffectGuarantee::Unknown,
                "provider execution panicked",
            ))
        })?;
        match execution {
            ProviderResult::Found(OperationAttempt::NotStarted(error)) => Err(error),
            ProviderResult::Found(OperationAttempt::Started(Ok(result))) => Ok(result),
            ProviderResult::Found(OperationAttempt::Started(Err(error))) => {
                Err(CallError::from_operation_failure(error))
            }
            ProviderResult::NotFound => Err(CallError::new(
                CallErrorKind::NotFound,
                "target path is not published",
            )),
            ProviderResult::Failure(error) => Err(CallError::from_host_failure(error)),
        }
    }

    /// Resolves one operation target and decodes its arguments only after all
    /// descriptor-independent canonical preconditions have succeeded.
    ///
    /// Transport bindings whose value representation depends on the selected
    /// interface descriptor should use this method instead of resolving a
    /// descriptor before [`ObjectProvider::call_operation_with_context`]. The
    /// callback executes inside the same exact-once provider boundary after
    /// object/interface validators, membership, operation lookup, and required
    /// object-validator checks. A callback error becomes `InvalidArguments` and
    /// typed implementation code is not invoked.
    fn call_operation_with_context_and_decoder<E>(
        &self,
        context: &ExecutionContext,
        target: Target,
        interface: InterfaceTarget,
        operation: String,
        decode_arguments: impl FnOnce(&InterfaceDescriptor) -> Result<BTreeMap<String, Value>, E>,
    ) -> Result<CallResult, CallError> {
        wip_protocol::validate_path(&target.path)
            .map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
        interface
            .reference
            .validate()
            .map_err(|error| CallError::new(CallErrorKind::InvalidRequest, error.to_string()))?;
        let path = target.path.clone();
        let execution = catch_unwind(AssertUnwindSafe(|| {
            self.execute_operation(context, &path, |publication| {
                publication.dispatch_resolved_with_decoder(
                    context,
                    target,
                    interface,
                    operation,
                    decode_arguments,
                    |object, interface, operation| {
                        self.authorize(&path, object, interface, operation)
                    },
                )
            })
        }));

        let execution = execution.map_err(|_| {
            CallError::from_operation_failure(OperationFailure::internal(
                EffectGuarantee::Unknown,
                "provider execution panicked",
            ))
        })?;
        match execution {
            ProviderResult::Found(OperationAttempt::NotStarted(error)) => Err(error),
            ProviderResult::Found(OperationAttempt::Started(Ok(result))) => Ok(result),
            ProviderResult::Found(OperationAttempt::Started(Err(error))) => {
                Err(CallError::from_operation_failure(error))
            }
            ProviderResult::NotFound => Err(CallError::new(
                CallErrorKind::NotFound,
                "target path is not published",
            )),
            ProviderResult::Failure(error) => Err(CallError::from_host_failure(error)),
        }
    }
}

/// Failure to construct an explicit object publication.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PublicationError {
    /// The same scope/name Interface reference was exposed more than once.
    DuplicateInterface(InterfaceRef),
    /// Projection attempted to add an interface without an implementation.
    UnexposedInterface(InterfaceRef),
}

impl Display for PublicationError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnexposedInterface(reference) => write!(
                formatter,
                "interface `{}` has no implementation",
                reference.as_str()
            ),
            Self::DuplicateInterface(reference) => write!(
                formatter,
                "interface `{}` is already exposed by this object",
                reference.as_str()
            ),
        }
    }
}

impl Error for PublicationError {}

#[cfg(test)]
mod projection_tests {
    use super::*;
    use wip_protocol::{
        Documentation, OperationDeclaration, ReturnDeclaration, TypeDeclaration, TypeExpr,
    };

    #[test]
    fn operation_views_prune_hidden_types_and_documentation_without_mutating_registry() {
        let named = |name: &str| TypeExpr::Named { name: name.into() };
        let operation = |name: &str, returns| OperationDeclaration {
            name: name.into(),
            documentation: None,
            parameters: Vec::new(),
            returns: ReturnDeclaration {
                documentation: None,
                r#type: returns,
            },
        };
        let declaration = |name: &str, definition| TypeDeclaration {
            name: name.into(),
            documentation: None,
            definition,
        };
        let descriptor = InterfaceDescriptor {
            format: "wip/1".into(),
            documentation: Some(Documentation {
                summary: "contains hidden operation details".into(),
                details: None,
            }),
            operations: vec![
                operation("visible", named("Public")),
                operation("secret", named("Secret")),
            ],
            types: vec![
                declaration(
                    "Public",
                    TypeExpr::List {
                        items: Box::new(named("Shared")),
                    },
                ),
                declaration("Shared", TypeExpr::String),
                declaration("Secret", TypeExpr::Bytes),
            ],
        };
        let mut projected = descriptor.clone();
        restrict_descriptor(&mut projected, |operation| operation == "visible");
        assert_eq!(projected.operations.len(), 1);
        assert!(projected.documentation.is_none());
        assert_eq!(
            projected
                .types
                .iter()
                .map(|declaration| declaration.name.as_str())
                .collect::<Vec<_>>(),
            vec!["Public", "Shared"]
        );
        assert_eq!(descriptor.types.len(), 3);
        restrict_descriptor(&mut projected, |_| false);
        assert!(projected.types.is_empty());
        assert!(projected.operations.is_empty());
    }
}

/// Stable Host dispatch failure kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallErrorKind {
    /// The request is structurally invalid.
    InvalidRequest,
    /// The target path is not currently published.
    NotFound,
    /// The selected interface is not exposed by the current object.
    InterfaceMismatch,
    /// The operation is absent from the selected descriptor.
    OperationNotFound,
    /// Supplied named values do not satisfy the operation declaration.
    InvalidArguments,
    /// A bounded cancellation, deadline, or resource limit was exceeded and the
    /// operation effects are guaranteed not committed.
    ResourceLimitExceeded,
    /// The Host failed and operation effects are guaranteed not committed.
    Internal,
    /// The Host cannot guarantee whether operation effects were committed.
    OperationOutcomeUnknown,
    /// This operation requires a validator and the call omitted it.
    ValidatorRequired,
    /// The supplied object validator is stale or belongs to another object.
    ValidatorMismatch,
    /// The selected mutable interface requires its observed validator.
    InterfaceValidatorRequired,
    /// The supplied interface validator does not identify the current descriptor.
    InterfaceValidatorMismatch,
    /// The operation is declared but not authorized for the caller.
    PermissionDenied,
}

/// A dispatch failure with a stable kind and bounded non-normative diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallError {
    kind: CallErrorKind,
    message: String,
}

impl CallError {
    fn new(kind: CallErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: bounded_message(message.into()),
        }
    }

    fn from_pre_dispatch(error: DispatchError) -> Self {
        match error {
            DispatchError::UnknownOperation(operation) => Self::new(
                CallErrorKind::OperationNotFound,
                format!("operation `{operation}` is not declared"),
            ),
            DispatchError::InvalidArguments(error) => {
                Self::new(CallErrorKind::InvalidArguments, error.to_string())
            }
            DispatchError::Decode(_) => Self::new(
                CallErrorKind::InvalidArguments,
                "operation arguments could not be decoded",
            ),
            DispatchError::Host(_)
            | DispatchError::Panic
            | DispatchError::Encode(_)
            | DispatchError::InvalidResult(_) => {
                unreachable!("post-invocation failure used as a pre-dispatch failure")
            }
        }
    }

    fn from_read_failure(error: HostError) -> Self {
        match error.kind() {
            HostErrorKind::Internal => Self::new(
                CallErrorKind::Internal,
                "provider failed while fetching data",
            ),
            HostErrorKind::ResourceLimitExceeded => Self::new(
                CallErrorKind::ResourceLimitExceeded,
                "provider resource limit was exceeded while fetching data",
            ),
        }
    }

    fn from_host_failure(error: HostError) -> Self {
        let kind = classified_host_kind(error.kind(), error.effect_guarantee());
        let message = match error.kind() {
            HostErrorKind::Internal => "provider execution failed",
            HostErrorKind::ResourceLimitExceeded => {
                "provider execution resource limit was exceeded"
            }
        };
        Self::new(kind, message)
    }

    fn from_operation_failure(error: OperationFailure) -> Self {
        Self::new(
            classified_host_kind(error.kind, error.effect_guarantee),
            error.message,
        )
    }

    /// Returns the stable failure kind.
    #[must_use]
    pub fn kind(&self) -> CallErrorKind {
        self.kind
    }

    /// Returns the bounded protocol-safe human-readable diagnostic.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Maps this Host failure to the canonical protocol error taxonomy.
    #[must_use]
    pub fn protocol_error(&self) -> ProtocolError {
        let code = match self.kind {
            CallErrorKind::InvalidRequest => ProtocolErrorCode::InvalidRequest,
            CallErrorKind::NotFound => ProtocolErrorCode::NotFound,
            CallErrorKind::InterfaceMismatch => ProtocolErrorCode::InterfaceMismatch,
            CallErrorKind::OperationNotFound => ProtocolErrorCode::OperationNotFound,
            CallErrorKind::InvalidArguments => ProtocolErrorCode::InvalidArguments,
            CallErrorKind::ResourceLimitExceeded => ProtocolErrorCode::ResourceLimitExceeded,
            CallErrorKind::Internal => ProtocolErrorCode::Internal,
            CallErrorKind::OperationOutcomeUnknown => ProtocolErrorCode::OperationOutcomeUnknown,
            CallErrorKind::ValidatorRequired => ProtocolErrorCode::ValidatorRequired,
            CallErrorKind::ValidatorMismatch => ProtocolErrorCode::ValidatorMismatch,
            CallErrorKind::InterfaceValidatorRequired => {
                ProtocolErrorCode::InterfaceValidatorRequired
            }
            CallErrorKind::InterfaceValidatorMismatch => {
                ProtocolErrorCode::InterfaceValidatorMismatch
            }
            CallErrorKind::PermissionDenied => ProtocolErrorCode::PermissionDenied,
        };
        ProtocolError {
            code,
            message: self.message.clone(),
        }
    }
}

fn classified_host_kind(kind: HostErrorKind, effect_guarantee: EffectGuarantee) -> CallErrorKind {
    match effect_guarantee {
        EffectGuarantee::Unknown => CallErrorKind::OperationOutcomeUnknown,
        EffectGuarantee::NotCommitted => match kind {
            HostErrorKind::Internal => CallErrorKind::Internal,
            HostErrorKind::ResourceLimitExceeded => CallErrorKind::ResourceLimitExceeded,
        },
    }
}

const MAX_PROTOCOL_MESSAGE_BYTES: usize = 512;

fn bounded_message(mut message: String) -> String {
    if message.len() <= MAX_PROTOCOL_MESSAGE_BYTES {
        return message;
    }
    let mut end = MAX_PROTOCOL_MESSAGE_BYTES;
    while !message.is_char_boundary(end) {
        end -= 1;
    }
    message.truncate(end);
    message
}

impl Display for CallError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "host dispatch failed ({:?}): {}",
            self.kind, self.message
        )
    }
}

impl Error for CallError {}