1use super::{ChoiceGuard, Protocol, Role, ValidationError};
4use proc_macro2::Ident;
5use serde::{Deserialize, Serialize};
6use std::collections::{BTreeSet, HashMap};
7
8const ATTR_THEOREM_PACKS: &str = "dsl.proof_bundles";
9const ATTR_REQUIRED_THEOREM_PACKS: &str = "dsl.required_proof_bundles";
10const ATTR_INFERRED_REQUIRED_THEOREM_PACKS: &str = "dsl.inferred_required_proof_bundles";
11const ATTR_ROLE_SETS: &str = "dsl.role_sets";
12const ATTR_TOPOLOGIES: &str = "dsl.topologies";
13const ATTR_TYPE_DECLARATIONS: &str = "dsl.type_decls";
14const ATTR_EFFECT_INTERFACE_DECLARATIONS: &str = "dsl.effect_decls";
15const ATTR_PROTOCOL_USES: &str = "dsl.protocol_uses";
16const ATTR_REGION_DECLARATIONS: &str = "dsl.fragment_decls";
17const ATTR_OPERATION_DECLARATIONS: &str = "dsl.operation_decls";
18const ATTR_GUEST_RUNTIME_DECLARATIONS: &str = "dsl.guest_runtime_decls";
19const ATTR_EXECUTION_PROFILE_DECLARATIONS: &str = "dsl.execution_profile_decls";
20const ATTR_PROTOCOL_EXECUTION_PROFILES: &str = "dsl.protocol_execution_profiles";
21const ATTR_AGREEMENT_PROFILE_DECLARATIONS: &str = "dsl.agreement_profile_decls";
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct TheoremPackDeclaration {
26 pub name: String,
28 #[serde(default)]
30 pub capabilities: Vec<String>,
31 #[serde(default)]
33 pub version: Option<String>,
34 #[serde(default)]
36 pub issuer: Option<String>,
37 #[serde(default)]
39 pub constraints: Vec<String>,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct RoleSetDeclaration {
45 pub name: String,
47 #[serde(default)]
49 pub members: Vec<String>,
50 #[serde(default)]
52 pub subset_of: Option<String>,
53 #[serde(default)]
55 pub subset_start: Option<u32>,
56 #[serde(default)]
58 pub subset_end: Option<u32>,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub struct TopologyDeclaration {
64 pub kind: String,
66 pub name: String,
68 #[serde(default)]
70 pub members: Vec<String>,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct TypeDeclaration {
76 pub name: String,
78 pub is_alias: bool,
80 #[serde(default)]
82 pub alias_of: Option<String>,
83 #[serde(default)]
85 pub constructors: Vec<TypeConstructorDeclaration>,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct TypeConstructorDeclaration {
91 pub name: String,
93 #[serde(default)]
95 pub payload_type: Option<String>,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100pub struct EffectInterfaceDeclaration {
101 pub name: String,
103 #[serde(default)]
105 pub operations: Vec<EffectOperationDeclaration>,
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
110#[serde(rename_all = "snake_case")]
111pub enum EffectAuthorityClass {
112 Authoritative,
114 #[default]
116 Command,
117 Observe,
119}
120
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct EffectOperationDeclaration {
124 pub name: String,
126 #[serde(default)]
128 pub authority_class: EffectAuthorityClass,
129 pub semantic_class: String,
131 pub progress: String,
133 pub region: String,
135 pub agreement_use: String,
137 pub reentrancy: String,
139 pub input_type: String,
141 pub output_type: String,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct EffectContractDeclaration {
148 pub interface_name: String,
150 pub operation_name: String,
152 pub authority_class: EffectAuthorityClass,
154 pub semantic_class: String,
156 pub progress: String,
158 pub region: String,
160 pub agreement_use: String,
162 pub admissibility: String,
164 pub totality: String,
166 pub timeout_policy: String,
168 pub reentrancy_policy: String,
170 pub handler_domain: String,
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176pub struct RegionDeclaration {
177 pub name: String,
179 #[serde(default)]
181 pub params: Vec<String>,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub struct OperationParameterDeclaration {
187 pub name: String,
189 pub type_name: String,
191}
192
193#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195pub struct ProgressAttachment {
196 pub contract_name: String,
198 #[serde(default)]
200 pub requires_profile: Option<String>,
201 #[serde(default)]
203 pub within_window: Option<String>,
204 #[serde(default)]
206 pub on_timeout: Option<String>,
207 #[serde(default)]
209 pub on_stall: Option<String>,
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214pub struct AgreementProfileDeclaration {
215 pub name: String,
217 pub visibility: String,
219 pub rule: String,
221 pub usable_at: String,
223 pub finalized_at: String,
225 pub evidence: String,
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231pub struct OperationAgreementAttachment {
232 pub profile_name: String,
234 #[serde(default)]
236 pub prestate: Option<String>,
237}
238
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241pub struct OperationDeclaration {
242 pub name: String,
244 #[serde(default)]
246 pub params: Vec<OperationParameterDeclaration>,
247 pub owner_role: String,
249 #[serde(default)]
251 pub within: Option<String>,
252 #[serde(default)]
254 pub progress_contract: Option<ProgressAttachment>,
255 #[serde(default)]
257 pub agreement: Option<OperationAgreementAttachment>,
258 #[serde(default)]
260 pub child_effect_aggregation: Option<ChildEffectAggregation>,
261 pub body_source: String,
263}
264
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267pub enum ChildEffectAggregationPolicy {
268 All,
270 First,
272 Threshold {
274 required_successes: u64,
276 },
277}
278
279#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
281pub struct ChildEffectAggregation {
282 pub policy: ChildEffectAggregationPolicy,
284}
285
286impl ChildEffectAggregationPolicy {
287 #[must_use]
289 pub fn dsl_name(&self) -> String {
290 match self {
291 Self::All => "all_success".to_string(),
292 Self::First => "first_success".to_string(),
293 Self::Threshold { required_successes } => {
294 format!("threshold_success({required_successes})")
295 }
296 }
297 }
298}
299
300impl ChildEffectAggregation {
301 #[must_use]
303 pub fn dsl_name(&self) -> String {
304 self.policy.dsl_name()
305 }
306}
307
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310pub struct GuestRuntimeDeclaration {
311 pub name: String,
313 #[serde(default)]
315 pub uses: Vec<String>,
316 pub entry: String,
318}
319
320#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
322pub struct ExecutionProfileDeclaration {
323 pub name: String,
325 #[serde(default)]
327 pub fairness: Option<String>,
328 #[serde(default)]
330 pub admissibility: Option<String>,
331 #[serde(default)]
333 pub escalation_window: Option<String>,
334}
335
336#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
338#[serde(rename_all = "snake_case")]
339pub enum LanguageTier {
340 FullSpec,
341 SessionProjectable,
342 ProtocolMachineExecutable,
343 ProofOnly,
344}
345
346#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
348#[serde(rename_all = "snake_case")]
349pub enum AuthorityMetatheoryTier {
350 SessionTypedCoordination,
352 EvidencePublicationSemanticObjects,
355 RuntimeSemanticOnly,
358}
359
360#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362pub struct AuthorityMetatheoryStatus {
363 pub strongest_tier: AuthorityMetatheoryTier,
364 pub diagnostic: String,
365}
366
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
369pub struct LanguageTierStatus {
370 pub strongest_tier: LanguageTier,
371 pub session_projectable: bool,
372 pub protocol_machine_executable: bool,
373 pub theory_convertible: bool,
374 pub proof_only: bool,
375 pub diagnostic: String,
376}
377
378#[derive(Debug)]
380pub struct Choreography {
381 pub name: Ident,
383 pub namespace: Option<String>,
385 pub roles: Vec<Role>,
387 pub protocol: Protocol,
389 pub attrs: HashMap<String, String>,
391}
392
393impl Choreography {
394 #[must_use]
396 pub fn qualified_name(&self) -> String {
397 match &self.namespace {
398 Some(ns) => format!("{}::{}", ns, self.name),
399 None => self.name.to_string(),
400 }
401 }
402
403 pub fn validate(&self) -> Result<(), ValidationError> {
410 for role in &self.roles {
412 if !self.protocol.mentions_role(role) {
413 return Err(ValidationError::UnusedRole(role.name().to_string()));
414 }
415 }
416
417 self.protocol.validate(&self.roles)?;
419 self.validate_proof_bundles()?;
420 self.validate_effect_surface()?;
421 self.validate_execution_profile_surface()?;
422 self.validate_operation_surface()?;
423
424 Ok(())
425 }
426
427 fn validate_proof_bundles(&self) -> Result<(), ValidationError> {
428 let bundles = self.theorem_packs();
429 let mut declared: BTreeSet<String> = BTreeSet::new();
430 for bundle in &bundles {
431 if !declared.insert(bundle.name.clone()) {
432 return Err(ValidationError::DuplicateProofBundle(bundle.name.clone()));
433 }
434 }
435
436 for required in self.required_theorem_packs() {
437 if !declared.contains(&required) {
438 return Err(ValidationError::MissingProofBundle(required));
439 }
440 }
441
442 let required_caps = self.required_theorem_pack_capabilities();
443 for capability in self.required_protocol_machine_core_capabilities() {
444 if !required_caps.contains(&capability) {
445 return Err(ValidationError::MissingCapability(capability));
446 }
447 }
448
449 Ok(())
450 }
451
452 fn validate_effect_surface(&self) -> Result<(), ValidationError> {
453 let mut effect_names = BTreeSet::new();
454 let mut effect_ops: HashMap<String, HashMap<String, EffectOperationDeclaration>> =
455 HashMap::new();
456 for effect in self.effect_interface_declarations() {
457 if !effect_names.insert(effect.name.clone()) {
458 return Err(ValidationError::ExtensionError(format!(
459 "duplicate effect interface declaration `{}`",
460 effect.name
461 )));
462 }
463 let mut ops = HashMap::new();
464 for op in effect.operations {
465 let semantic_class_ok = matches!(
466 op.semantic_class.as_str(),
467 "authoritative" | "observational" | "best_effort"
468 );
469 if !semantic_class_ok {
470 return Err(ValidationError::ExtensionError(format!(
471 "effect operation `{}.{}` has unsupported `class {}`",
472 effect.name, op.name, op.semantic_class
473 )));
474 }
475 let progress_ok = matches!(op.progress.as_str(), "immediate" | "may_block");
476 if !progress_ok {
477 return Err(ValidationError::ExtensionError(format!(
478 "effect operation `{}.{}` has unsupported `progress {}`",
479 effect.name, op.name, op.progress
480 )));
481 }
482 if !matches!(op.region.as_str(), "session" | "fragment" | "global") {
483 return Err(ValidationError::ExtensionError(format!(
484 "effect operation `{}.{}` has unsupported `region {}`",
485 effect.name, op.name, op.region
486 )));
487 }
488 if !matches!(op.agreement_use.as_str(), "required" | "none" | "forbidden") {
489 return Err(ValidationError::ExtensionError(format!(
490 "effect operation `{}.{}` has unsupported `agreement_use {}`",
491 effect.name, op.name, op.agreement_use
492 )));
493 }
494 if !matches!(
495 op.reentrancy.as_str(),
496 "allow" | "reject_same_operation" | "reject_same_fragment"
497 ) {
498 return Err(ValidationError::ExtensionError(format!(
499 "effect operation `{}.{}` has unsupported `reentrancy {}`",
500 effect.name, op.name, op.reentrancy
501 )));
502 }
503 if matches!(op.authority_class, EffectAuthorityClass::Observe)
504 && op.semantic_class != "observational"
505 {
506 return Err(ValidationError::ExtensionError(format!(
507 "effect operation `{}.{}` is observational and must declare `class : observational`",
508 effect.name, op.name
509 )));
510 }
511 if matches!(op.authority_class, EffectAuthorityClass::Authoritative)
512 && op.semantic_class != "authoritative"
513 {
514 return Err(ValidationError::ExtensionError(format!(
515 "effect operation `{}.{}` is authoritative and must declare `class : authoritative`",
516 effect.name, op.name
517 )));
518 }
519 if op.progress == "immediate"
520 && matches!(op.authority_class, EffectAuthorityClass::Authoritative)
521 {
522 return Err(ValidationError::ExtensionError(format!(
523 "effect operation `{}.{}` may not be both `authoritative` and `progress immediate`",
524 effect.name, op.name
525 )));
526 }
527 if op.agreement_use == "required"
528 && matches!(op.authority_class, EffectAuthorityClass::Observe)
529 {
530 return Err(ValidationError::ExtensionError(format!(
531 "effect operation `{}.{}` may not require agreement use on an observational surface",
532 effect.name, op.name
533 )));
534 }
535 if ops.insert(op.name.clone(), op.clone()).is_some() {
536 return Err(ValidationError::ExtensionError(format!(
537 "duplicate effect operation `{}.{}`",
538 effect.name, op.name
539 )));
540 }
541 }
542 effect_ops.insert(effect.name, ops);
543 }
544
545 let declared = effect_names;
546 let used: BTreeSet<String> = self.protocol_uses().into_iter().collect();
547 for effect in &used {
548 if !declared.contains(effect) {
549 return Err(ValidationError::ExtensionError(format!(
550 "protocol uses undeclared effect interface `{effect}`"
551 )));
552 }
553 }
554
555 fn validate_expr(
556 expr: &super::AuthorityExpr,
557 effect_ops: &HashMap<String, HashMap<String, EffectOperationDeclaration>>,
558 used: &BTreeSet<String>,
559 ) -> Result<(), ValidationError> {
560 match expr {
561 super::AuthorityExpr::Check {
562 effect, operation, ..
563 } => {
564 if !used.contains(effect) {
565 return Err(ValidationError::ExtensionError(format!(
566 "effect invocation `{effect}.{operation}` is not allowed without `uses {effect}`"
567 )));
568 }
569 let Some(ops) = effect_ops.get(effect) else {
570 return Err(ValidationError::ExtensionError(format!(
571 "effect invocation references undeclared interface `{effect}`"
572 )));
573 };
574 let Some(op_decl) = ops.get(operation) else {
575 return Err(ValidationError::ExtensionError(format!(
576 "effect invocation references undeclared operation `{effect}.{operation}`"
577 )));
578 };
579 if matches!(op_decl.authority_class, EffectAuthorityClass::Observe) {
580 return Err(ValidationError::ExtensionError(format!(
581 "effect invocation `{effect}.{operation}` is observational and may not be invoked with `check`"
582 )));
583 }
584 Ok(())
585 }
586 super::AuthorityExpr::Observe {
587 effect, operation, ..
588 } => {
589 if !used.contains(effect) {
590 return Err(ValidationError::ExtensionError(format!(
591 "effect invocation `{effect}.{operation}` is not allowed without `uses {effect}`"
592 )));
593 }
594 let Some(ops) = effect_ops.get(effect) else {
595 return Err(ValidationError::ExtensionError(format!(
596 "effect invocation references undeclared interface `{effect}`"
597 )));
598 };
599 let Some(op_decl) = ops.get(operation) else {
600 return Err(ValidationError::ExtensionError(format!(
601 "effect invocation references undeclared operation `{effect}.{operation}`"
602 )));
603 };
604 if !matches!(op_decl.authority_class, EffectAuthorityClass::Observe) {
605 return Err(ValidationError::ExtensionError(format!(
606 "effect invocation `{effect}.{operation}` is not observational and may not be invoked with `observe`"
607 )));
608 }
609 Ok(())
610 }
611 super::AuthorityExpr::Var(_)
612 | super::AuthorityExpr::Transfer { .. }
613 | super::AuthorityExpr::Constructor { .. }
614 | super::AuthorityExpr::Call { .. } => Ok(()),
615 }
616 }
617
618 fn validate_protocol_effects(
619 protocol: &Protocol,
620 effect_ops: &HashMap<String, HashMap<String, EffectOperationDeclaration>>,
621 used: &BTreeSet<String>,
622 ) -> Result<(), ValidationError> {
623 match protocol {
624 Protocol::Begin { continuation, .. }
625 | Protocol::Await { continuation, .. }
626 | Protocol::Resolve { continuation, .. }
627 | Protocol::Invalidate { continuation, .. }
628 | Protocol::Send { continuation, .. }
629 | Protocol::Broadcast { continuation, .. }
630 | Protocol::Extension { continuation, .. }
631 | Protocol::Let { continuation, .. }
632 | Protocol::Publish { continuation, .. }
633 | Protocol::PublishAuthority { continuation, .. }
634 | Protocol::Materialize { continuation, .. }
635 | Protocol::Handoff { continuation, .. }
636 | Protocol::DependentWork { continuation, .. } => {
637 if let Protocol::Let { mode, expr, .. } = protocol {
638 validate_expr(expr, effect_ops, used)?;
639 match (mode, expr) {
640 (
641 super::AuthorityBindingMode::Plain,
642 super::AuthorityExpr::Check {
643 effect, operation, ..
644 },
645 ) => {
646 let op_decl = effect_ops
647 .get(effect)
648 .and_then(|ops| ops.get(operation))
649 .expect("validated effect operation should exist");
650 if matches!(
651 op_decl.authority_class,
652 EffectAuthorityClass::Authoritative
653 ) {
654 return Err(ValidationError::ExtensionError(format!(
655 "authoritative effect invocation `{effect}.{operation}` must bind through `authoritative let`"
656 )));
657 }
658 }
659 (
660 super::AuthorityBindingMode::Plain,
661 super::AuthorityExpr::Observe { .. },
662 ) => {
663 return Err(ValidationError::ExtensionError(
664 "`observe` expressions must bind through `observe let`"
665 .to_string(),
666 ));
667 }
668 (
669 super::AuthorityBindingMode::Authoritative,
670 super::AuthorityExpr::Check {
671 effect, operation, ..
672 },
673 ) => {
674 let op_decl = effect_ops
675 .get(effect)
676 .and_then(|ops| ops.get(operation))
677 .expect("validated effect operation should exist");
678 if !matches!(
679 op_decl.authority_class,
680 EffectAuthorityClass::Authoritative
681 ) {
682 return Err(ValidationError::ExtensionError(format!(
683 "`authoritative let` may only bind authoritative effect invocations; `{effect}.{operation}` is {:?}",
684 op_decl.authority_class
685 )));
686 }
687 }
688 (
689 super::AuthorityBindingMode::Observe,
690 super::AuthorityExpr::Observe { .. },
691 ) => {}
692 (super::AuthorityBindingMode::Plain, _) => {}
693 (super::AuthorityBindingMode::Authoritative, _) => {
694 return Err(ValidationError::ExtensionError(
695 "`authoritative let` must bind a `check` expression"
696 .to_string(),
697 ));
698 }
699 (super::AuthorityBindingMode::Observe, _) => {
700 return Err(ValidationError::ExtensionError(
701 "`observe let` must bind an `observe` expression".to_string(),
702 ));
703 }
704 }
705 }
706 validate_protocol_effects(continuation, effect_ops, used)
707 }
708 Protocol::Choice { branches, .. } => {
709 for branch in branches {
710 if let Some(ChoiceGuard::Evidence {
711 effect, operation, ..
712 }) = &branch.guard
713 {
714 if !used.contains(effect) {
715 return Err(ValidationError::ExtensionError(format!(
716 "effect guard `{effect}.{operation}` is not allowed without `uses {effect}`"
717 )));
718 }
719 let Some(ops) = effect_ops.get(effect) else {
720 return Err(ValidationError::ExtensionError(format!(
721 "effect guard references undeclared interface `{effect}`"
722 )));
723 };
724 let Some(op_decl) = ops.get(operation) else {
725 return Err(ValidationError::ExtensionError(format!(
726 "effect guard references undeclared operation `{effect}.{operation}`"
727 )));
728 };
729 if matches!(op_decl.authority_class, EffectAuthorityClass::Observe) {
730 return Err(ValidationError::ExtensionError(format!(
731 "effect guard `{effect}.{operation}` is observational and may not be invoked with `check`"
732 )));
733 }
734 }
735 validate_protocol_effects(&branch.protocol, effect_ops, used)?;
736 }
737 Ok(())
738 }
739 Protocol::Case { expr, branches } => {
740 validate_expr(expr, effect_ops, used)?;
741 for branch in branches {
742 validate_protocol_effects(&branch.protocol, effect_ops, used)?;
743 }
744 Ok(())
745 }
746 Protocol::Timeout {
747 body,
748 on_timeout,
749 on_cancel,
750 ..
751 } => {
752 validate_protocol_effects(body, effect_ops, used)?;
753 validate_protocol_effects(on_timeout, effect_ops, used)?;
754 if let Some(on_cancel) = on_cancel.as_deref() {
755 validate_protocol_effects(on_cancel, effect_ops, used)?;
756 }
757 Ok(())
758 }
759 Protocol::Loop { body, .. } | Protocol::Rec { body, .. } => {
760 validate_protocol_effects(body, effect_ops, used)
761 }
762 Protocol::Parallel { protocols } => {
763 for protocol in protocols {
764 validate_protocol_effects(protocol, effect_ops, used)?;
765 }
766 Ok(())
767 }
768 Protocol::Var(_) | Protocol::End => Ok(()),
769 }
770 }
771
772 validate_protocol_effects(&self.protocol, &effect_ops, &used)
773 }
774
775 fn validate_execution_profile_surface(&self) -> Result<(), ValidationError> {
776 let mut declared = BTreeSet::new();
777 for profile in self.execution_profile_declarations() {
778 if !declared.insert(profile.name.clone()) {
779 return Err(ValidationError::ExtensionError(format!(
780 "duplicate execution profile declaration `{}`",
781 profile.name
782 )));
783 }
784 }
785
786 for profile in self.protocol_execution_profiles() {
787 if !declared.contains(&profile) {
788 return Err(ValidationError::ExtensionError(format!(
789 "protocol references undeclared execution profile `{profile}`"
790 )));
791 }
792 }
793
794 Ok(())
795 }
796
797 fn validate_operation_surface(&self) -> Result<(), ValidationError> {
798 let declared_agreement_profiles = self
799 .agreement_profile_declarations()
800 .into_iter()
801 .map(|profile| profile.name)
802 .collect::<BTreeSet<_>>();
803
804 for operation in self.operation_declarations() {
805 if operation.progress_contract.is_none() {
806 return Err(ValidationError::ExtensionError(format!(
807 "operation `{}` is parity-critical and must declare a progress contract",
808 operation.name
809 )));
810 }
811 if !operation
812 .progress_contract
813 .as_ref()
814 .is_some_and(|progress| progress.is_explicit())
815 {
816 return Err(ValidationError::ExtensionError(format!(
817 "operation `{}` must declare explicit progress metadata using `requires`, `within`, `on timeout`, or `on stall`",
818 operation.name
819 )));
820 }
821 let Some(agreement) = operation.agreement.as_ref() else {
822 return Err(ValidationError::ExtensionError(format!(
823 "operation `{}` must attach a named agreement profile",
824 operation.name
825 )));
826 };
827 if !declared_agreement_profiles.contains(&agreement.profile_name) {
828 return Err(ValidationError::ExtensionError(format!(
829 "operation `{}` references undeclared agreement profile `{}`",
830 operation.name, agreement.profile_name
831 )));
832 }
833 }
834 Ok(())
835 }
836
837 #[must_use]
838 pub fn language_tier_status(&self) -> LanguageTierStatus {
839 let theory_convertible = super::convert::protocol_to_global(&self.protocol).is_ok();
840 let session_blocker = find_session_projection_blocker(&self.protocol);
841 let missing_progress = self
842 .operation_declarations()
843 .iter()
844 .find(|operation| {
845 operation.progress_contract.is_none()
846 || !operation
847 .progress_contract
848 .as_ref()
849 .is_some_and(|progress| progress.is_explicit())
850 })
851 .map(|operation| {
852 format!(
853 "operation `{}` is missing the required progress contract",
854 operation.name
855 )
856 });
857
858 let protocol_machine_executable = missing_progress.is_none();
859 let session_projectable = session_blocker.is_none();
860 let strongest_tier = match (session_projectable, protocol_machine_executable) {
861 (true, true) => LanguageTier::SessionProjectable,
862 (false, true) => LanguageTier::ProtocolMachineExecutable,
863 (_, false) => LanguageTier::ProofOnly,
864 };
865 let diagnostic = if let Some(blocker) = session_blocker {
866 format!(
867 "full spec is valid, protocol-machine execution is available, but session projection is blocked: {blocker}"
868 )
869 } else if let Some(missing_progress) = missing_progress {
870 format!(
871 "full spec is valid for proof analysis only; protocol-machine execution is blocked: {missing_progress}"
872 )
873 } else if !theory_convertible {
874 "full spec is valid, protocol-machine execution is available, and the protocol is session-projectable, but theory conversion remains explicitly unavailable for this surface".to_string()
875 } else {
876 "full spec is valid, protocol-machine execution is available, the protocol is session-projectable, and theory conversion is available".to_string()
877 };
878
879 LanguageTierStatus {
880 strongest_tier,
881 session_projectable,
882 protocol_machine_executable,
883 theory_convertible,
884 proof_only: matches!(strongest_tier, LanguageTier::ProofOnly),
885 diagnostic,
886 }
887 }
888
889 #[must_use]
890 pub fn authority_metatheory_status(&self) -> AuthorityMetatheoryStatus {
891 let strongest_tier = authority_metatheory_tier(&self.protocol);
892 let diagnostic = match authority_metatheory_blocker(&self.protocol) {
893 Some(blocker) => format!(
894 "authority-bearing constructs remain executable, but the supported theorem slice stops before this runtime semantic surface: {blocker}"
895 ),
896 None => match strongest_tier {
897 AuthorityMetatheoryTier::SessionTypedCoordination =>
898 "the protocol stays within ordinary session-typed coordination; no authority-specific semantic proof obligations are introduced".to_string(),
899 AuthorityMetatheoryTier::EvidencePublicationSemanticObjects =>
900 "the protocol stays within the supported authority theorem slice: evidence-bearing reads and canonical publication/materialization are justified at the protocol-machine semantic-object layer, while session typing continues to cover only the coordination skeleton".to_string(),
901 AuthorityMetatheoryTier::RuntimeSemanticOnly =>
902 "authority-bearing runtime semantics are present, but they currently sit outside the supported theorem slice".to_string(),
903 },
904 };
905
906 AuthorityMetatheoryStatus {
907 strongest_tier,
908 diagnostic,
909 }
910 }
911
912 #[must_use]
914 pub fn get_attributes(&self) -> &HashMap<String, String> {
915 &self.attrs
916 }
917
918 pub fn get_attributes_mut(&mut self) -> &mut HashMap<String, String> {
920 &mut self.attrs
921 }
922
923 #[must_use]
925 pub fn get_attribute(&self, key: &str) -> Option<&String> {
926 self.attrs.get(key)
927 }
928
929 pub fn set_attribute(&mut self, key: String, value: String) {
931 self.attrs.insert(key, value);
932 }
933
934 pub fn remove_attribute(&mut self, key: &str) -> Option<String> {
936 self.attrs.remove(key)
937 }
938
939 #[must_use]
941 pub fn has_attribute(&self, key: &str) -> bool {
942 self.attrs.contains_key(key)
943 }
944
945 pub fn get_attribute_as<T>(&self, key: &str) -> Option<T>
947 where
948 T: std::str::FromStr,
949 {
950 self.get_attribute(key)?.parse().ok()
951 }
952
953 pub fn get_attribute_as_bool(&self, key: &str) -> Option<bool> {
955 let value = self.get_attribute(key)?;
956 match value.to_lowercase().as_str() {
957 "true" | "1" | "yes" | "on" => Some(true),
958 "false" | "0" | "no" | "off" => Some(false),
959 _ => None,
960 }
961 }
962
963 pub fn clear_attributes(&mut self) {
965 self.attrs.clear();
966 }
967
968 pub fn attribute_count(&self) -> usize {
970 self.attrs.len()
971 }
972
973 pub fn attribute_keys(&self) -> Vec<&String> {
975 self.attrs.keys().collect()
976 }
977
978 pub fn validate_required_attributes(&self, required_keys: &[&str]) -> Result<(), Vec<String>> {
980 let missing: Vec<String> = required_keys
981 .iter()
982 .filter(|&key| !self.has_attribute(key))
983 .map(|&key| key.to_string())
984 .collect();
985
986 if missing.is_empty() {
987 Ok(())
988 } else {
989 Err(missing)
990 }
991 }
992
993 pub fn find_nodes_with_annotation(&self, key: &str) -> Vec<&Protocol> {
995 let mut nodes = Vec::new();
996 self.protocol.collect_nodes_with_annotation(key, &mut nodes);
997 nodes
998 }
999
1000 pub fn find_nodes_with_annotation_value(&self, key: &str, value: &str) -> Vec<&Protocol> {
1002 let mut nodes = Vec::new();
1003 self.protocol
1004 .collect_nodes_with_annotation_value(key, value, &mut nodes);
1005 nodes
1006 }
1007
1008 pub fn total_annotation_count(&self) -> usize {
1010 self.attribute_count() + self.protocol.deep_annotation_count()
1011 }
1012
1013 pub fn set_theorem_packs(
1015 &mut self,
1016 theorem_packs: &[TheoremPackDeclaration],
1017 ) -> Result<(), String> {
1018 let encoded = serde_json::to_string(theorem_packs)
1019 .map_err(|e| format!("encode theorem packs: {e}"))?;
1020 self.attrs.insert(ATTR_THEOREM_PACKS.to_string(), encoded);
1021 Ok(())
1022 }
1023
1024 #[must_use]
1026 pub fn theorem_packs(&self) -> Vec<TheoremPackDeclaration> {
1027 self.attrs
1028 .get(ATTR_THEOREM_PACKS)
1029 .and_then(|s| serde_json::from_str::<Vec<TheoremPackDeclaration>>(s).ok())
1030 .unwrap_or_default()
1031 }
1032
1033 pub fn set_required_theorem_packs(&mut self, required: &[String]) -> Result<(), String> {
1035 let encoded = serde_json::to_string(required)
1036 .map_err(|e| format!("encode required theorem packs: {e}"))?;
1037 self.attrs
1038 .insert(ATTR_REQUIRED_THEOREM_PACKS.to_string(), encoded);
1039 Ok(())
1040 }
1041
1042 #[must_use]
1044 pub fn required_theorem_packs(&self) -> Vec<String> {
1045 self.attrs
1046 .get(ATTR_REQUIRED_THEOREM_PACKS)
1047 .and_then(|s| serde_json::from_str::<Vec<String>>(s).ok())
1048 .unwrap_or_default()
1049 }
1050
1051 pub fn set_inferred_required_theorem_packs(
1053 &mut self,
1054 required: &[String],
1055 ) -> Result<(), String> {
1056 let encoded = serde_json::to_string(required)
1057 .map_err(|e| format!("encode inferred theorem packs: {e}"))?;
1058 self.attrs
1059 .insert(ATTR_INFERRED_REQUIRED_THEOREM_PACKS.to_string(), encoded);
1060 Ok(())
1061 }
1062
1063 #[must_use]
1065 pub fn inferred_required_theorem_packs(&self) -> Vec<String> {
1066 self.attrs
1067 .get(ATTR_INFERRED_REQUIRED_THEOREM_PACKS)
1068 .and_then(|s| serde_json::from_str::<Vec<String>>(s).ok())
1069 .unwrap_or_default()
1070 }
1071
1072 pub fn set_role_sets(&mut self, role_sets: &[RoleSetDeclaration]) -> Result<(), String> {
1074 let encoded =
1075 serde_json::to_string(role_sets).map_err(|e| format!("encode role sets: {e}"))?;
1076 self.attrs.insert(ATTR_ROLE_SETS.to_string(), encoded);
1077 Ok(())
1078 }
1079
1080 #[must_use]
1082 pub fn role_sets(&self) -> Vec<RoleSetDeclaration> {
1083 self.attrs
1084 .get(ATTR_ROLE_SETS)
1085 .and_then(|s| serde_json::from_str::<Vec<RoleSetDeclaration>>(s).ok())
1086 .unwrap_or_default()
1087 }
1088
1089 pub fn set_topologies(&mut self, topologies: &[TopologyDeclaration]) -> Result<(), String> {
1091 let encoded =
1092 serde_json::to_string(topologies).map_err(|e| format!("encode topologies: {e}"))?;
1093 self.attrs.insert(ATTR_TOPOLOGIES.to_string(), encoded);
1094 Ok(())
1095 }
1096
1097 #[must_use]
1099 pub fn topologies(&self) -> Vec<TopologyDeclaration> {
1100 self.attrs
1101 .get(ATTR_TOPOLOGIES)
1102 .and_then(|s| serde_json::from_str::<Vec<TopologyDeclaration>>(s).ok())
1103 .unwrap_or_default()
1104 }
1105
1106 pub fn set_type_declarations(&mut self, decls: &[TypeDeclaration]) -> Result<(), String> {
1108 let encoded =
1109 serde_json::to_string(decls).map_err(|e| format!("encode type declarations: {e}"))?;
1110 self.attrs
1111 .insert(ATTR_TYPE_DECLARATIONS.to_string(), encoded);
1112 Ok(())
1113 }
1114
1115 #[must_use]
1117 pub fn type_declarations(&self) -> Vec<TypeDeclaration> {
1118 self.attrs
1119 .get(ATTR_TYPE_DECLARATIONS)
1120 .and_then(|s| serde_json::from_str::<Vec<TypeDeclaration>>(s).ok())
1121 .unwrap_or_default()
1122 }
1123
1124 pub fn set_effect_interface_declarations(
1126 &mut self,
1127 decls: &[EffectInterfaceDeclaration],
1128 ) -> Result<(), String> {
1129 let encoded =
1130 serde_json::to_string(decls).map_err(|e| format!("encode effect declarations: {e}"))?;
1131 self.attrs
1132 .insert(ATTR_EFFECT_INTERFACE_DECLARATIONS.to_string(), encoded);
1133 Ok(())
1134 }
1135
1136 #[must_use]
1138 pub fn effect_interface_declarations(&self) -> Vec<EffectInterfaceDeclaration> {
1139 self.attrs
1140 .get(ATTR_EFFECT_INTERFACE_DECLARATIONS)
1141 .and_then(|s| serde_json::from_str::<Vec<EffectInterfaceDeclaration>>(s).ok())
1142 .unwrap_or_default()
1143 }
1144
1145 #[must_use]
1148 pub fn effect_contract_declarations(&self) -> Vec<EffectContractDeclaration> {
1149 let used: BTreeSet<String> = self.protocol_uses().into_iter().collect();
1150 self.effect_interface_declarations()
1151 .into_iter()
1152 .flat_map(|effect| {
1153 let is_used = used.contains(effect.name.as_str());
1154 effect.operations.into_iter().map(move |op| {
1155 let admissibility = if is_used {
1156 "declared_use_only"
1157 } else {
1158 "internal_only"
1159 };
1160 let (totality, timeout_policy) = match op.progress.as_str() {
1161 "immediate" => ("immediate", "none"),
1162 "may_block" => ("may_block", "required"),
1163 _ => ("may_block", "required"),
1164 };
1165 let handler_domain = if is_used { "external" } else { "internal" };
1166 EffectContractDeclaration {
1167 interface_name: effect.name.clone(),
1168 operation_name: op.name,
1169 authority_class: op.authority_class,
1170 semantic_class: op.semantic_class.clone(),
1171 progress: op.progress.clone(),
1172 region: op.region.clone(),
1173 agreement_use: op.agreement_use.clone(),
1174 admissibility: admissibility.to_string(),
1175 totality: totality.to_string(),
1176 timeout_policy: timeout_policy.to_string(),
1177 reentrancy_policy: op.reentrancy,
1178 handler_domain: handler_domain.to_string(),
1179 }
1180 })
1181 })
1182 .collect()
1183 }
1184
1185 pub fn set_protocol_uses(&mut self, uses: &[String]) -> Result<(), String> {
1187 let encoded =
1188 serde_json::to_string(uses).map_err(|e| format!("encode protocol uses: {e}"))?;
1189 self.attrs.insert(ATTR_PROTOCOL_USES.to_string(), encoded);
1190 Ok(())
1191 }
1192
1193 #[must_use]
1195 pub fn protocol_uses(&self) -> Vec<String> {
1196 self.attrs
1197 .get(ATTR_PROTOCOL_USES)
1198 .and_then(|s| serde_json::from_str::<Vec<String>>(s).ok())
1199 .unwrap_or_default()
1200 }
1201
1202 pub fn set_region_declarations(&mut self, decls: &[RegionDeclaration]) -> Result<(), String> {
1204 let encoded =
1205 serde_json::to_string(decls).map_err(|e| format!("encode region declarations: {e}"))?;
1206 self.attrs
1207 .insert(ATTR_REGION_DECLARATIONS.to_string(), encoded);
1208 Ok(())
1209 }
1210
1211 #[must_use]
1213 pub fn region_declarations(&self) -> Vec<RegionDeclaration> {
1214 self.attrs
1215 .get(ATTR_REGION_DECLARATIONS)
1216 .and_then(|s| serde_json::from_str::<Vec<RegionDeclaration>>(s).ok())
1217 .unwrap_or_default()
1218 }
1219
1220 pub fn set_operation_declarations(
1222 &mut self,
1223 decls: &[OperationDeclaration],
1224 ) -> Result<(), String> {
1225 let encoded = serde_json::to_string(decls)
1226 .map_err(|e| format!("encode operation declarations: {e}"))?;
1227 self.attrs
1228 .insert(ATTR_OPERATION_DECLARATIONS.to_string(), encoded);
1229 Ok(())
1230 }
1231
1232 #[must_use]
1234 pub fn operation_declarations(&self) -> Vec<OperationDeclaration> {
1235 self.attrs
1236 .get(ATTR_OPERATION_DECLARATIONS)
1237 .and_then(|s| serde_json::from_str::<Vec<OperationDeclaration>>(s).ok())
1238 .unwrap_or_default()
1239 }
1240
1241 pub fn set_guest_runtime_declarations(
1243 &mut self,
1244 decls: &[GuestRuntimeDeclaration],
1245 ) -> Result<(), String> {
1246 let encoded = serde_json::to_string(decls)
1247 .map_err(|e| format!("encode guest runtime declarations: {e}"))?;
1248 self.attrs
1249 .insert(ATTR_GUEST_RUNTIME_DECLARATIONS.to_string(), encoded);
1250 Ok(())
1251 }
1252
1253 #[must_use]
1255 pub fn guest_runtime_declarations(&self) -> Vec<GuestRuntimeDeclaration> {
1256 self.attrs
1257 .get(ATTR_GUEST_RUNTIME_DECLARATIONS)
1258 .and_then(|s| serde_json::from_str::<Vec<GuestRuntimeDeclaration>>(s).ok())
1259 .unwrap_or_default()
1260 }
1261
1262 pub fn set_execution_profile_declarations(
1264 &mut self,
1265 decls: &[ExecutionProfileDeclaration],
1266 ) -> Result<(), String> {
1267 let encoded = serde_json::to_string(decls)
1268 .map_err(|e| format!("encode execution profile declarations: {e}"))?;
1269 self.attrs
1270 .insert(ATTR_EXECUTION_PROFILE_DECLARATIONS.to_string(), encoded);
1271 Ok(())
1272 }
1273
1274 #[must_use]
1276 pub fn execution_profile_declarations(&self) -> Vec<ExecutionProfileDeclaration> {
1277 self.attrs
1278 .get(ATTR_EXECUTION_PROFILE_DECLARATIONS)
1279 .and_then(|s| serde_json::from_str::<Vec<ExecutionProfileDeclaration>>(s).ok())
1280 .unwrap_or_default()
1281 }
1282
1283 pub fn set_protocol_execution_profiles(&mut self, profiles: &[String]) -> Result<(), String> {
1285 let encoded = serde_json::to_string(profiles)
1286 .map_err(|e| format!("encode protocol execution profiles: {e}"))?;
1287 self.attrs
1288 .insert(ATTR_PROTOCOL_EXECUTION_PROFILES.to_string(), encoded);
1289 Ok(())
1290 }
1291
1292 #[must_use]
1294 pub fn protocol_execution_profiles(&self) -> Vec<String> {
1295 self.attrs
1296 .get(ATTR_PROTOCOL_EXECUTION_PROFILES)
1297 .and_then(|s| serde_json::from_str::<Vec<String>>(s).ok())
1298 .unwrap_or_default()
1299 }
1300
1301 pub fn set_agreement_profile_declarations(
1303 &mut self,
1304 decls: &[AgreementProfileDeclaration],
1305 ) -> Result<(), String> {
1306 let encoded = serde_json::to_string(decls)
1307 .map_err(|e| format!("encode agreement profile declarations: {e}"))?;
1308 self.attrs
1309 .insert(ATTR_AGREEMENT_PROFILE_DECLARATIONS.to_string(), encoded);
1310 Ok(())
1311 }
1312
1313 #[must_use]
1315 pub fn agreement_profile_declarations(&self) -> Vec<AgreementProfileDeclaration> {
1316 self.attrs
1317 .get(ATTR_AGREEMENT_PROFILE_DECLARATIONS)
1318 .and_then(|s| serde_json::from_str::<Vec<AgreementProfileDeclaration>>(s).ok())
1319 .unwrap_or_default()
1320 }
1321
1322 fn required_theorem_pack_capabilities(&self) -> BTreeSet<String> {
1323 let required = self.required_theorem_packs();
1324 let required_set: BTreeSet<&str> = required.iter().map(String::as_str).collect();
1325 self.theorem_packs()
1326 .into_iter()
1327 .filter(|bundle| required_set.contains(bundle.name.as_str()))
1328 .flat_map(|bundle| bundle.capabilities.into_iter())
1329 .collect()
1330 }
1331
1332 fn required_protocol_machine_core_capabilities(&self) -> BTreeSet<String> {
1333 fn collect(protocol: &Protocol, out: &mut BTreeSet<String>) {
1334 if let Some(cap) = protocol.get_annotations().custom("required_capability") {
1335 out.insert(cap.to_string());
1336 }
1337 match protocol {
1338 Protocol::Begin { continuation, .. }
1339 | Protocol::Await { continuation, .. }
1340 | Protocol::Resolve { continuation, .. }
1341 | Protocol::Invalidate { continuation, .. }
1342 | Protocol::Send { continuation, .. }
1343 | Protocol::Broadcast { continuation, .. }
1344 | Protocol::Extension { continuation, .. }
1345 | Protocol::Publish { continuation, .. }
1346 | Protocol::PublishAuthority { continuation, .. }
1347 | Protocol::Materialize { continuation, .. }
1348 | Protocol::Handoff { continuation, .. }
1349 | Protocol::DependentWork { continuation, .. } => collect(continuation, out),
1350 Protocol::Choice { branches, .. } => {
1351 for branch in branches {
1352 collect(&branch.protocol, out);
1353 }
1354 }
1355 Protocol::Loop { body, .. } | Protocol::Rec { body, .. } => collect(body, out),
1356 Protocol::Let { continuation, .. } => collect(continuation, out),
1357 Protocol::Case { branches, .. } => {
1358 for branch in branches {
1359 collect(&branch.protocol, out);
1360 }
1361 }
1362 Protocol::Timeout {
1363 body,
1364 on_timeout,
1365 on_cancel,
1366 ..
1367 } => {
1368 collect(body, out);
1369 collect(on_timeout, out);
1370 if let Some(on_cancel) = on_cancel.as_deref() {
1371 collect(on_cancel, out);
1372 }
1373 }
1374 Protocol::Parallel { protocols } => {
1375 for p in protocols {
1376 collect(p, out);
1377 }
1378 }
1379 Protocol::Var(_) | Protocol::End => {}
1380 }
1381 }
1382
1383 let mut out = BTreeSet::new();
1384 collect(&self.protocol, &mut out);
1385 out
1386 }
1387}
1388
1389impl ProgressAttachment {
1390 #[must_use]
1392 pub fn is_explicit(&self) -> bool {
1393 self.requires_profile.is_some()
1394 || self.within_window.is_some()
1395 || self.on_timeout.is_some()
1396 || self.on_stall.is_some()
1397 }
1398}
1399
1400fn find_session_projection_blocker(protocol: &Protocol) -> Option<&'static str> {
1401 match protocol {
1402 Protocol::Begin { .. } => Some("begin requires protocol-machine commitment semantics"),
1403 Protocol::Await { .. } => Some("await requires protocol-machine commitment semantics"),
1404 Protocol::Resolve { .. } => Some("resolve requires protocol-machine commitment semantics"),
1405 Protocol::Invalidate { .. } => {
1406 Some("invalidate requires protocol-machine commitment semantics")
1407 }
1408 Protocol::Case { .. } => Some("authority-local case/of requires protocol-machine lowering"),
1409 Protocol::Timeout { .. } => Some("timeout requires protocol-machine progress semantics"),
1410 Protocol::Publish { .. } => Some("publish requires publication/materialization semantics"),
1411 Protocol::PublishAuthority { .. } => {
1412 Some("publish requires publication/materialization semantics")
1413 }
1414 Protocol::Materialize { .. } => {
1415 Some("materialize requires publication/materialization semantics")
1416 }
1417 Protocol::Handoff { .. } => Some("handoff requires semantic handoff semantics"),
1418 Protocol::DependentWork { .. } => {
1419 Some("dependent work requires protocol-machine commitment semantics")
1420 }
1421 Protocol::Send { continuation, .. }
1422 | Protocol::Broadcast { continuation, .. }
1423 | Protocol::Let { continuation, .. }
1424 | Protocol::Extension { continuation, .. } => find_session_projection_blocker(continuation),
1425 Protocol::Choice { branches, .. } => branches
1426 .iter()
1427 .find_map(|branch| find_session_projection_blocker(&branch.protocol)),
1428 Protocol::Loop { body, .. } | Protocol::Rec { body, .. } => {
1429 find_session_projection_blocker(body)
1430 }
1431 Protocol::Parallel { protocols } => {
1432 protocols.iter().find_map(find_session_projection_blocker)
1433 }
1434 Protocol::Var(_) | Protocol::End => None,
1435 }
1436}
1437
1438fn authority_metatheory_tier(protocol: &Protocol) -> AuthorityMetatheoryTier {
1439 match protocol {
1440 Protocol::Begin { .. }
1441 | Protocol::Await { .. }
1442 | Protocol::Resolve { .. }
1443 | Protocol::Invalidate { .. }
1444 | Protocol::Case { .. }
1445 | Protocol::Timeout { .. }
1446 | Protocol::Handoff { .. }
1447 | Protocol::DependentWork { .. }
1448 | Protocol::Parallel { .. }
1449 | Protocol::Extension { .. } => AuthorityMetatheoryTier::RuntimeSemanticOnly,
1450 Protocol::Publish { continuation, .. }
1451 | Protocol::PublishAuthority { continuation, .. }
1452 | Protocol::Materialize { continuation, .. } => authority_metatheory_tier(continuation)
1453 .max(AuthorityMetatheoryTier::EvidencePublicationSemanticObjects),
1454 Protocol::Let {
1455 expr, continuation, ..
1456 } => {
1457 let expr_tier = match expr {
1458 super::AuthorityExpr::Check { .. } | super::AuthorityExpr::Observe { .. } => {
1459 AuthorityMetatheoryTier::EvidencePublicationSemanticObjects
1460 }
1461 super::AuthorityExpr::Transfer { .. } => {
1462 AuthorityMetatheoryTier::RuntimeSemanticOnly
1463 }
1464 super::AuthorityExpr::Var(_)
1465 | super::AuthorityExpr::Constructor { .. }
1466 | super::AuthorityExpr::Call { .. } => {
1467 AuthorityMetatheoryTier::SessionTypedCoordination
1468 }
1469 };
1470 expr_tier.max(authority_metatheory_tier(continuation))
1471 }
1472 Protocol::Choice { branches, .. } => branches
1473 .iter()
1474 .map(|branch| {
1475 let guard_tier = match branch.guard.as_ref() {
1476 Some(ChoiceGuard::Evidence { .. }) => {
1477 AuthorityMetatheoryTier::EvidencePublicationSemanticObjects
1478 }
1479 Some(ChoiceGuard::Predicate(_)) | None => {
1480 AuthorityMetatheoryTier::SessionTypedCoordination
1481 }
1482 };
1483 guard_tier.max(authority_metatheory_tier(&branch.protocol))
1484 })
1485 .max()
1486 .unwrap_or(AuthorityMetatheoryTier::SessionTypedCoordination),
1487 Protocol::Send { continuation, .. } | Protocol::Broadcast { continuation, .. } => {
1488 authority_metatheory_tier(continuation)
1489 }
1490 Protocol::Loop { body, .. } | Protocol::Rec { body, .. } => authority_metatheory_tier(body),
1491 Protocol::Var(_) | Protocol::End => AuthorityMetatheoryTier::SessionTypedCoordination,
1492 }
1493}
1494
1495fn authority_metatheory_blocker(protocol: &Protocol) -> Option<&'static str> {
1496 match protocol {
1497 Protocol::Begin { .. }
1498 | Protocol::Await { .. }
1499 | Protocol::Resolve { .. }
1500 | Protocol::Invalidate { .. } => {
1501 Some("explicit commitment lifecycle still relies on protocol-machine semantic obligations")
1502 }
1503 Protocol::Case { .. } => Some("authority-local case/of still relies on runtime semantic obligations"),
1504 Protocol::Timeout { .. } => Some("timeout/cancellation still relies on runtime progress semantics"),
1505 Protocol::Handoff { .. } => Some("semantic handoff is still justified through protocol-machine conservation rather than the small authority theorem slice"),
1506 Protocol::DependentWork { .. } => Some("dependent work remains a protocol-machine semantic obligation"),
1507 Protocol::Parallel { .. } => Some("parallel authority composition remains outside the supported authority theorem slice"),
1508 Protocol::Extension { .. } => Some("extension dispatch remains outside the authority theorem slice"),
1509 Protocol::Let { expr, continuation, .. } => match expr {
1510 super::AuthorityExpr::Transfer { .. } => {
1511 Some("transfer receipts remain part of the wider runtime authority lifecycle")
1512 }
1513 _ => authority_metatheory_blocker(continuation),
1514 },
1515 Protocol::Choice { branches, .. } => branches
1516 .iter()
1517 .find_map(|branch| authority_metatheory_blocker(&branch.protocol)),
1518 Protocol::Send { continuation, .. }
1519 | Protocol::Broadcast { continuation, .. }
1520 | Protocol::Publish { continuation, .. }
1521 | Protocol::PublishAuthority { continuation, .. }
1522 | Protocol::Materialize { continuation, .. } => authority_metatheory_blocker(continuation),
1523 Protocol::Loop { body, .. } | Protocol::Rec { body, .. } => authority_metatheory_blocker(body),
1524 Protocol::Var(_) | Protocol::End => None,
1525 }
1526}
1527
1528#[cfg(test)]
1529mod tests {
1530 use super::*;
1531 use quote::format_ident;
1532
1533 #[test]
1534 fn proof_bundle_metadata_roundtrip() {
1535 let mut choreo = Choreography {
1536 name: format_ident!("RoundTrip"),
1537 namespace: None,
1538 roles: Vec::new(),
1539 protocol: Protocol::End,
1540 attrs: HashMap::new(),
1541 };
1542 let bundles = vec![
1543 TheoremPackDeclaration {
1544 name: "Base".to_string(),
1545 capabilities: vec!["delegation".to_string()],
1546 version: None,
1547 issuer: None,
1548 constraints: Vec::new(),
1549 },
1550 TheoremPackDeclaration {
1551 name: "Guard".to_string(),
1552 capabilities: vec!["guard_tokens".to_string()],
1553 version: None,
1554 issuer: None,
1555 constraints: Vec::new(),
1556 },
1557 ];
1558 let required = vec!["Base".to_string()];
1559
1560 choreo
1561 .set_theorem_packs(&bundles)
1562 .expect("set proof bundles");
1563 choreo
1564 .set_required_theorem_packs(&required)
1565 .expect("set required bundles");
1566
1567 assert_eq!(choreo.theorem_packs(), bundles);
1568 assert_eq!(choreo.required_theorem_packs(), required);
1569 }
1570}