Skip to main content

telltale_language/ast/
choreography.rs

1// Choreography struct definition and validation
2
3use 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/// Typed proof-bundle declaration metadata from DSL.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct TheoremPackDeclaration {
26    /// Stable bundle name.
27    pub name: String,
28    /// Capabilities provided by this bundle.
29    #[serde(default)]
30    pub capabilities: Vec<String>,
31    /// Optional bundle version.
32    #[serde(default)]
33    pub version: Option<String>,
34    /// Optional bundle issuer.
35    #[serde(default)]
36    pub issuer: Option<String>,
37    /// Optional constraints attached to the bundle.
38    #[serde(default)]
39    pub constraints: Vec<String>,
40}
41
42/// Typed role-set declaration metadata from DSL.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct RoleSetDeclaration {
45    /// Stable role-set name.
46    pub name: String,
47    /// Explicit members for this role-set.
48    #[serde(default)]
49    pub members: Vec<String>,
50    /// Optional subset selector source role-set or family.
51    #[serde(default)]
52    pub subset_of: Option<String>,
53    /// Optional subset selector start index (inclusive).
54    #[serde(default)]
55    pub subset_start: Option<u32>,
56    /// Optional subset selector end index (exclusive).
57    #[serde(default)]
58    pub subset_end: Option<u32>,
59}
60
61/// Typed topology declaration metadata from DSL.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub struct TopologyDeclaration {
64    /// Topology kind (`cluster`, `ring`, `mesh`).
65    pub kind: String,
66    /// Topology name.
67    pub name: String,
68    /// Referenced members.
69    #[serde(default)]
70    pub members: Vec<String>,
71}
72
73/// DSL type declaration metadata.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct TypeDeclaration {
76    /// Declared type name.
77    pub name: String,
78    /// Whether this is a `type alias`.
79    pub is_alias: bool,
80    /// Right-hand side for aliases.
81    #[serde(default)]
82    pub alias_of: Option<String>,
83    /// Union constructors for nominal sum types.
84    #[serde(default)]
85    pub constructors: Vec<TypeConstructorDeclaration>,
86}
87
88/// Constructor declaration for one nominal union type.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct TypeConstructorDeclaration {
91    /// Constructor name.
92    pub name: String,
93    /// Optional payload type rendered from source syntax.
94    #[serde(default)]
95    pub payload_type: Option<String>,
96}
97
98/// Nominal effect interface declaration metadata.
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100pub struct EffectInterfaceDeclaration {
101    /// Effect interface name.
102    pub name: String,
103    /// Declared operations for this interface.
104    #[serde(default)]
105    pub operations: Vec<EffectOperationDeclaration>,
106}
107
108/// Authority class for one nominal effect operation.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
110#[serde(rename_all = "snake_case")]
111pub enum EffectAuthorityClass {
112    /// Operation may produce authoritative semantic evidence.
113    Authoritative,
114    /// Operation performs command work without itself proving semantic truth.
115    #[default]
116    Command,
117    /// Operation is observational only and must not be consumed via `check`.
118    Observe,
119}
120
121/// One operation in a nominal effect interface.
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct EffectOperationDeclaration {
124    /// Operation name.
125    pub name: String,
126    /// Authority class attached to this operation.
127    #[serde(default)]
128    pub authority_class: EffectAuthorityClass,
129    /// Semantic class declared for this operation.
130    pub semantic_class: String,
131    /// Progress class declared for this operation.
132    pub progress: String,
133    /// Region scope declared for this operation.
134    pub region: String,
135    /// Agreement-use discipline declared for this operation.
136    pub agreement_use: String,
137    /// Reentrancy policy declared for this operation.
138    pub reentrancy: String,
139    /// Input type as declared in DSL surface syntax.
140    pub input_type: String,
141    /// Output type as declared in DSL surface syntax.
142    pub output_type: String,
143}
144
145/// Runtime-facing effect metadata derived from one nominal effect declaration.
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct EffectContractDeclaration {
148    /// Nominal effect interface name.
149    pub interface_name: String,
150    /// Nominal effect operation name.
151    pub operation_name: String,
152    /// Authority class attached to this operation.
153    pub authority_class: EffectAuthorityClass,
154    /// Semantic class attached to this operation.
155    pub semantic_class: String,
156    /// Progress class attached to this operation.
157    pub progress: String,
158    /// Region scope attached to this operation.
159    pub region: String,
160    /// Agreement-use discipline attached to this operation.
161    pub agreement_use: String,
162    /// Runtime admissibility policy name.
163    pub admissibility: String,
164    /// Runtime totality policy name.
165    pub totality: String,
166    /// Runtime timeout policy name.
167    pub timeout_policy: String,
168    /// Runtime reentrancy policy name.
169    pub reentrancy_policy: String,
170    /// Runtime handler-domain name.
171    pub handler_domain: String,
172}
173
174/// Fragment declaration metadata from DSL.
175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176pub struct RegionDeclaration {
177    /// Fragment name.
178    pub name: String,
179    /// Named fragment parameters.
180    #[serde(default)]
181    pub params: Vec<String>,
182}
183
184/// Operation parameter declaration metadata.
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub struct OperationParameterDeclaration {
187    /// Parameter name.
188    pub name: String,
189    /// Parameter type rendered from source syntax.
190    pub type_name: String,
191}
192
193/// Structured progress-contract attachment metadata from DSL.
194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195pub struct ProgressAttachment {
196    /// Stable progress-contract name.
197    pub contract_name: String,
198    /// Required execution/admission profile.
199    #[serde(default)]
200    pub requires_profile: Option<String>,
201    /// Required escalation window class.
202    #[serde(default)]
203    pub within_window: Option<String>,
204    /// Named timeout branch or escalation action.
205    #[serde(default)]
206    pub on_timeout: Option<String>,
207    /// Named stall branch or escalation action.
208    #[serde(default)]
209    pub on_stall: Option<String>,
210}
211
212/// Named reusable agreement-profile declaration metadata from DSL.
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214pub struct AgreementProfileDeclaration {
215    /// Stable profile name.
216    pub name: String,
217    /// Visibility timing fixed by this profile.
218    pub visibility: String,
219    /// Agreement/decision rule name.
220    pub rule: String,
221    /// Minimum agreement level required for provisional usability.
222    pub usable_at: String,
223    /// Minimum agreement level required for finalization.
224    pub finalized_at: String,
225    /// Required evidence kind for this profile.
226    pub evidence: String,
227}
228
229/// Operation-level attachment of one named agreement profile.
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231pub struct OperationAgreementAttachment {
232    /// Referenced agreement-profile name.
233    pub profile_name: String,
234    /// Optional named prestate binding required by the operation.
235    #[serde(default)]
236    pub prestate: Option<String>,
237}
238
239/// Operation declaration metadata from DSL.
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241pub struct OperationDeclaration {
242    /// Operation name.
243    pub name: String,
244    /// Operation parameters.
245    #[serde(default)]
246    pub params: Vec<OperationParameterDeclaration>,
247    /// Semantic owner role.
248    pub owner_role: String,
249    /// Optional fragment scope rendered from source syntax.
250    #[serde(default)]
251    pub within: Option<String>,
252    /// Required progress contract for parity-critical execution.
253    #[serde(default)]
254    pub progress_contract: Option<ProgressAttachment>,
255    /// Named agreement/finality attachment for the operation.
256    #[serde(default)]
257    pub agreement: Option<OperationAgreementAttachment>,
258    /// Declared child-effect aggregation for the operation.
259    #[serde(default)]
260    pub child_effect_aggregation: Option<ChildEffectAggregation>,
261    /// Raw operation body source.
262    pub body_source: String,
263}
264
265/// Canonical child-effect aggregation policy attached below one agreement boundary.
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267pub enum ChildEffectAggregationPolicy {
268    /// All child effects must succeed.
269    All,
270    /// The first successful child effect resolves the aggregation.
271    First,
272    /// A fixed number of successful child effects is required.
273    Threshold {
274        /// Required success count.
275        required_successes: u64,
276    },
277}
278
279/// One declared child-effect aggregation attached to an operation.
280#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
281pub struct ChildEffectAggregation {
282    /// Canonical aggregation policy.
283    pub policy: ChildEffectAggregationPolicy,
284}
285
286impl ChildEffectAggregationPolicy {
287    /// Canonical DSL spelling for this child-effect aggregation policy.
288    #[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    /// Canonical DSL spelling for this child-effect aggregation declaration.
302    #[must_use]
303    pub fn dsl_name(&self) -> String {
304        self.policy.dsl_name()
305    }
306}
307
308/// Guest-runtime declaration metadata from DSL.
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310pub struct GuestRuntimeDeclaration {
311    /// Guest-runtime name.
312    pub name: String,
313    /// Declared effect interface uses.
314    #[serde(default)]
315    pub uses: Vec<String>,
316    /// Entry protocol name.
317    pub entry: String,
318}
319
320/// Execution-profile declaration metadata from DSL.
321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
322pub struct ExecutionProfileDeclaration {
323    /// Stable profile name.
324    pub name: String,
325    /// Fairness class fixed by the profile.
326    #[serde(default)]
327    pub fairness: Option<String>,
328    /// Admissibility class fixed by the profile.
329    #[serde(default)]
330    pub admissibility: Option<String>,
331    /// Escalation-window class fixed by the profile.
332    #[serde(default)]
333    pub escalation_window: Option<String>,
334}
335
336/// Strongest artifact tier justified by the parsed specification.
337#[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/// Strongest theorem story currently justified for authority-bearing constructs.
347#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
348#[serde(rename_all = "snake_case")]
349pub enum AuthorityMetatheoryTier {
350    /// No authority-specific semantic obligations beyond ordinary session coordination.
351    SessionTypedCoordination,
352    /// The supported authority slice lives in the protocol-machine semantic-object layer:
353    /// evidence-bearing reads plus canonical publication/materialization.
354    EvidencePublicationSemanticObjects,
355    /// The protocol uses authority/runtime features that currently remain outside the
356    /// supported authority theorem slice.
357    RuntimeSemanticOnly,
358}
359
360/// Explicit authority-metatheory status for one parsed specification.
361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362pub struct AuthorityMetatheoryStatus {
363    pub strongest_tier: AuthorityMetatheoryTier,
364    pub diagnostic: String,
365}
366
367/// Explicit language-tier status for one parsed specification.
368#[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/// A complete choreographic protocol specification
379#[derive(Debug)]
380pub struct Choreography {
381    /// Protocol name
382    pub name: Ident,
383    /// Optional namespace for the protocol
384    pub namespace: Option<String>,
385    /// Participating roles
386    pub roles: Vec<Role>,
387    /// The protocol specification
388    pub protocol: Protocol,
389    /// Metadata and attributes
390    pub attrs: HashMap<String, String>,
391}
392
393impl Choreography {
394    /// Get the qualified name of the choreography (namespace::name or just name)
395    #[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    /// Validate the choreography for correctness
404    ///
405    /// # Errors
406    ///
407    /// Returns [`ValidationError`] if the choreography is invalid (unused roles,
408    /// malformed protocol, duplicate/missing proof bundles, or missing capabilities).
409    pub fn validate(&self) -> Result<(), ValidationError> {
410        // Check all roles are used
411        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        // Check protocol is well-formed
418        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    /// Get choreography-level attributes/annotations
913    #[must_use]
914    pub fn get_attributes(&self) -> &HashMap<String, String> {
915        &self.attrs
916    }
917
918    /// Get mutable reference to choreography-level attributes
919    pub fn get_attributes_mut(&mut self) -> &mut HashMap<String, String> {
920        &mut self.attrs
921    }
922
923    /// Get a specific choreography attribute
924    #[must_use]
925    pub fn get_attribute(&self, key: &str) -> Option<&String> {
926        self.attrs.get(key)
927    }
928
929    /// Set a choreography attribute
930    pub fn set_attribute(&mut self, key: String, value: String) {
931        self.attrs.insert(key, value);
932    }
933
934    /// Remove a choreography attribute
935    pub fn remove_attribute(&mut self, key: &str) -> Option<String> {
936        self.attrs.remove(key)
937    }
938
939    /// Check if choreography has a specific attribute
940    #[must_use]
941    pub fn has_attribute(&self, key: &str) -> bool {
942        self.attrs.contains_key(key)
943    }
944
945    /// Get attribute as a specific type
946    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    /// Get attribute as boolean
954    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    /// Clear all choreography attributes
964    pub fn clear_attributes(&mut self) {
965        self.attrs.clear();
966    }
967
968    /// Count of choreography attributes
969    pub fn attribute_count(&self) -> usize {
970        self.attrs.len()
971    }
972
973    /// Get all attribute keys
974    pub fn attribute_keys(&self) -> Vec<&String> {
975        self.attrs.keys().collect()
976    }
977
978    /// Validate that required attributes are present
979    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    /// Find all protocol nodes with a specific annotation
994    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    /// Find all protocol nodes with a specific annotation value
1001    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    /// Count total annotations across the entire choreography
1009    pub fn total_annotation_count(&self) -> usize {
1010        self.attribute_count() + self.protocol.deep_annotation_count()
1011    }
1012
1013    /// Set theorem-pack declarations for this choreography.
1014    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    /// Get typed theorem-pack declarations.
1025    #[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    /// Set protocol-required theorem packs.
1034    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    /// Get protocol-required theorem packs.
1043    #[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    /// Set inferred protocol-required theorem packs.
1052    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    /// Get inferred protocol-required theorem packs.
1064    #[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    /// Set role-set declarations for this choreography.
1073    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    /// Get typed role-set declarations.
1081    #[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    /// Set topology declarations for this choreography.
1090    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    /// Get typed topology declarations.
1098    #[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    /// Set nominal type declarations for this choreography.
1107    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    /// Get nominal type declarations.
1116    #[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    /// Set nominal effect interface declarations for this choreography.
1125    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    /// Get nominal effect interface declarations.
1137    #[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    /// Derive runtime-facing effect metadata from nominal effect declarations
1146    /// and protocol `uses` dependencies.
1147    #[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    /// Set explicit protocol effect dependencies.
1186    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    /// Get explicit protocol effect dependencies.
1194    #[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    /// Set region declarations for this choreography.
1203    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    /// Get region declarations.
1212    #[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    /// Set operation declarations for this choreography.
1221    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    /// Get operation declarations.
1233    #[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    /// Set guest-runtime declarations for this choreography.
1242    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    /// Get guest-runtime declarations.
1254    #[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    /// Set execution-profile declarations for this choreography.
1263    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    /// Get execution-profile declarations.
1275    #[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    /// Set protocol-selected execution profiles.
1284    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    /// Get protocol-selected execution profiles.
1293    #[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    /// Set reusable agreement-profile declarations for this choreography.
1302    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    /// Get reusable agreement-profile declarations.
1314    #[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    /// Whether this attachment carries explicit progress policy rather than a bare name.
1391    #[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(
1512                    "transfer receipts are first-class transition artifacts but still rely on the wider runtime authority lifecycle",
1513                )
1514            }
1515            _ => authority_metatheory_blocker(continuation),
1516        },
1517        Protocol::Choice { branches, .. } => branches
1518            .iter()
1519            .find_map(|branch| authority_metatheory_blocker(&branch.protocol)),
1520        Protocol::Send { continuation, .. }
1521        | Protocol::Broadcast { continuation, .. }
1522        | Protocol::Publish { continuation, .. }
1523        | Protocol::PublishAuthority { continuation, .. }
1524        | Protocol::Materialize { continuation, .. } => authority_metatheory_blocker(continuation),
1525        Protocol::Loop { body, .. } | Protocol::Rec { body, .. } => authority_metatheory_blocker(body),
1526        Protocol::Var(_) | Protocol::End => None,
1527    }
1528}
1529
1530#[cfg(test)]
1531mod tests {
1532    use super::*;
1533    use quote::format_ident;
1534
1535    #[test]
1536    fn proof_bundle_metadata_roundtrip() {
1537        let mut choreo = Choreography {
1538            name: format_ident!("RoundTrip"),
1539            namespace: None,
1540            roles: Vec::new(),
1541            protocol: Protocol::End,
1542            attrs: HashMap::new(),
1543        };
1544        let bundles = vec![
1545            TheoremPackDeclaration {
1546                name: "Base".to_string(),
1547                capabilities: vec!["delegation".to_string()],
1548                version: None,
1549                issuer: None,
1550                constraints: Vec::new(),
1551            },
1552            TheoremPackDeclaration {
1553                name: "Guard".to_string(),
1554                capabilities: vec!["guard_tokens".to_string()],
1555                version: None,
1556                issuer: None,
1557                constraints: Vec::new(),
1558            },
1559        ];
1560        let required = vec!["Base".to_string()];
1561
1562        choreo
1563            .set_theorem_packs(&bundles)
1564            .expect("set proof bundles");
1565        choreo
1566            .set_required_theorem_packs(&required)
1567            .expect("set required bundles");
1568
1569        assert_eq!(choreo.theorem_packs(), bundles);
1570        assert_eq!(choreo.required_theorem_packs(), required);
1571    }
1572}