Skip to main content

lean_ctx/core/
product_capabilities.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Canonical v4 product-capability registry.
4//!
5//! Product access decisions are made from the embedded, validated registry.
6//! Price, source visibility and commercial rights are independent axes.
7//! Legacy IDs remain stable, but never determine price or source visibility.
8
9use std::collections::{BTreeMap, BTreeSet};
10use std::sync::OnceLock;
11
12use serde::{Deserialize, Serialize};
13
14use crate::core::ocla::OclaCapabilityKind;
15
16/// The plan ladder a capability's minimum is ranked on. Account plans live
17/// in LeanCTX | Cloud; the engine only orders them.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20pub enum Plan {
21    #[serde(alias = "free", alias = "supporter", alias = "sponsor")]
22    Community,
23    Pro,
24    #[serde(alias = "business", alias = "biz")]
25    Team,
26    #[serde(alias = "ent")]
27    Enterprise,
28}
29
30impl Plan {
31    pub const ALL: [Self; 4] = [Self::Community, Self::Pro, Self::Team, Self::Enterprise];
32
33    #[must_use]
34    pub const fn all() -> &'static [Self] {
35        &Self::ALL
36    }
37
38    #[must_use]
39    pub const fn rank(self) -> usize {
40        match self {
41            Self::Community => 0,
42            Self::Pro => 1,
43            Self::Team => 2,
44            Self::Enterprise => 3,
45        }
46    }
47
48    #[must_use]
49    pub const fn as_str(self) -> &'static str {
50        match self {
51            Self::Community => "community",
52            Self::Pro => "pro",
53            Self::Team => "team",
54            Self::Enterprise => "enterprise",
55        }
56    }
57}
58
59/// Package-local mirror of the repository source of truth. CI requires this
60/// byte-for-byte copy so source-package builds remain hermetic.
61pub const REGISTRY_SOURCE: &str = include_str!("../../data/product-capabilities.toml");
62
63#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
64#[serde(rename_all = "snake_case")]
65pub enum UserPriceClass {
66    Free,
67    /// Paid right granted by a LeanCTX Cloud plan; the record's
68    /// [`ProductCapability::cloud_plan`] names the plan (`cloud` is the
69    /// internal wire name, not a product name).
70    Cloud,
71    /// Withdrawn capability: still a known lookup name, never granted.
72    Retired,
73    /// Legacy (schema 2) class. Kept so the frozen hosted services and old
74    /// envelopes keep decoding; no schema-3 record uses it.
75    CloudPaid,
76    /// Legacy (schema 2) Pro class of the signed private Intelligence Runtime;
77    /// no schema-3 record uses it.
78    ProPaid,
79    /// Legacy (schema 2) Team class; no schema-3 record uses it.
80    TeamPaid,
81    /// Legacy (schema 2) Enterprise class; no schema-3 record uses it.
82    EnterprisePaid,
83    SdkOemCommercial,
84}
85
86/// The LeanCTX Cloud plan that grants an `cloud` capability (Enterprise ⊇ Team ⊇ Personal).
87/// `Personal` maps to the internal [`Plan::Pro`] id, which is not a price or tier name.
88#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
89#[serde(rename_all = "snake_case")]
90pub enum CloudPlan {
91    Personal,
92    Team,
93    Enterprise,
94}
95
96impl CloudPlan {
97    #[must_use]
98    pub const fn plan(self) -> Plan {
99        match self {
100            Self::Personal => Plan::Pro,
101            Self::Team => Plan::Team,
102            Self::Enterprise => Plan::Enterprise,
103        }
104    }
105}
106
107/// Registry schema this Engine reads (3: `cloud` and `retired` classes).
108pub const REGISTRY_SCHEMA_VERSION: u16 = 3;
109
110#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
111#[serde(rename_all = "snake_case")]
112pub enum SourceVisibility {
113    PublicApache,
114    PublicEnterpriseSourceAvailable,
115    PrivateSource,
116}
117
118#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
119#[serde(rename_all = "snake_case")]
120pub enum RuntimeDelivery {
121    SourceBuild,
122    SignedBinary,
123    LocalService,
124    ManagedCloudService,
125    EnterprisePrivateImage,
126    /// Delivered and controlled by the LeanCTX | Cloud service (filter packs,
127    /// shared team state, governance), consumed by the local Engine.
128    CloudService,
129}
130
131#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
132#[serde(rename_all = "snake_case")]
133pub enum AhaCriticality {
134    None,
135    Supporting,
136    IndividualAha,
137    TeamAha,
138    /// Withheld by the public projection; see [`public_projection`].
139    Undisclosed,
140}
141
142#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
143#[serde(rename_all = "snake_case")]
144pub enum MoatSensitivity {
145    Low,
146    Medium,
147    CrownJewel,
148    /// Withheld by the public projection; see [`public_projection`].
149    Undisclosed,
150}
151
152/// Marker value of the registry's top-level `projection` key.
153pub const PUBLIC_PROJECTION: &str = "public";
154/// `source_path` of a capability whose implementation is not public.
155pub const UNDISCLOSED_SOURCE: &str = "undisclosed";
156
157#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
158#[serde(rename_all = "snake_case")]
159pub enum CommercialUse {
160    ApacheRights,
161    FreeSmallTeamInternal,
162    ServiceAgreement,
163    EnterpriseAgreement,
164    SdkOemAgreement,
165    ThirdPartyTerms,
166}
167
168#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
169#[serde(rename_all = "snake_case")]
170pub enum RedistributionRights {
171    ApacheRights,
172    SeparateAgreementRequired,
173    ThirdPartyTerms,
174}
175
176#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
177#[serde(rename_all = "snake_case")]
178pub enum TelemetryEventClass {
179    None,
180    ProductUsage,
181    BillingUsage,
182    OperationalAggregate,
183    Audit,
184}
185
186#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
187#[serde(rename_all = "snake_case")]
188pub enum PublicStatus {
189    Available,
190    Preview,
191    Internal,
192    Deprecated,
193    Research,
194    Private,
195}
196
197#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
198#[serde(rename_all = "snake_case")]
199pub enum LicenseClass {
200    ApacheTrustCore,
201    CommercialSource,
202    PrivateService,
203    FreeRuntime,
204    SdkOem,
205    ThirdParty,
206}
207
208#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
209#[serde(deny_unknown_fields)]
210pub struct ProductCapability {
211    pub id: String,
212    pub name: String,
213    pub price_class: UserPriceClass,
214    /// Present exactly on `cloud` records: the Cloud plan that grants it.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub cloud_plan: Option<CloudPlan>,
217    pub source_visibility: SourceVisibility,
218    pub runtime_delivery: RuntimeDelivery,
219    pub aha_criticality: AhaCriticality,
220    pub moat_sensitivity: MoatSensitivity,
221    pub license_class: LicenseClass,
222    pub self_host_available: bool,
223    pub managed_cloud_available: bool,
224    /// Canonical governance key, or the explicit value `none`.
225    pub enterprise_entitlement: String,
226    pub account_required: bool,
227    pub allowed_commercial_use: CommercialUse,
228    pub redistribution_oem_rights: RedistributionRights,
229    pub data_boundary: String,
230    pub telemetry_event_class: TelemetryEventClass,
231    pub public_maturity: PublicStatus,
232    pub source_path: String,
233}
234
235impl ProductCapability {
236    /// Compatibility projection for legacy clients; not entitlement authority.
237    #[must_use]
238    pub const fn minimum_plan(&self) -> Plan {
239        match self.price_class {
240            UserPriceClass::Free => Plan::Community,
241            UserPriceClass::Cloud => match self.cloud_plan {
242                Some(plan) => plan.plan(),
243                // Unreachable for a validated record; fail toward the top plan.
244                None => Plan::Enterprise,
245            },
246            UserPriceClass::CloudPaid | UserPriceClass::ProPaid => Plan::Pro,
247            UserPriceClass::TeamPaid => Plan::Team,
248            // A retired id is never granted (`allows` refuses it); it never
249            // reads as Community either.
250            UserPriceClass::EnterprisePaid
251            | UserPriceClass::SdkOemCommercial
252            | UserPriceClass::Retired => Plan::Enterprise,
253        }
254    }
255
256    /// True for a capability whose entitlement is Enterprise authority: it
257    /// must name itself as its canonical `enterprise_entitlement`.
258    #[must_use]
259    pub const fn is_enterprise(&self) -> bool {
260        matches!(self.price_class, UserPriceClass::EnterprisePaid)
261            || matches!(
262                (self.price_class, self.cloud_plan),
263                (UserPriceClass::Cloud, Some(CloudPlan::Enterprise))
264            )
265    }
266}
267
268#[derive(Clone, Debug, Deserialize)]
269#[serde(deny_unknown_fields)]
270struct RegistryDocument {
271    schema_version: u16,
272    /// Absent in the canonical registry; [`PUBLIC_PROJECTION`] in the public
273    /// export, whose non-public records carry no strategic classification.
274    #[serde(default)]
275    projection: Option<String>,
276    capability: Vec<ProductCapability>,
277    /// Legacy wire/config lookup names, separate from the 18-field records.
278    aliases: BTreeMap<String, String>,
279}
280
281#[derive(Debug)]
282pub struct ProductCapabilityRegistry {
283    entries: Vec<ProductCapability>,
284    lookup: BTreeMap<String, usize>,
285    projected: bool,
286}
287
288impl ProductCapabilityRegistry {
289    pub fn parse(source: &str) -> Result<Self, String> {
290        let document: RegistryDocument = toml::from_str(source)
291            .map_err(|error| format!("invalid capability registry: {error}"))?;
292        if document.schema_version != REGISTRY_SCHEMA_VERSION {
293            return Err(format!(
294                "unsupported capability registry schema {}",
295                document.schema_version
296            ));
297        }
298        if document.capability.is_empty() {
299            return Err("capability registry is empty".to_string());
300        }
301
302        let projected = match document.projection.as_deref() {
303            None => false,
304            Some(PUBLIC_PROJECTION) => true,
305            Some(other) => return Err(format!("unknown capability registry projection '{other}'")),
306        };
307
308        let mut lookup = BTreeMap::new();
309        let mut ids = BTreeSet::new();
310        for (index, capability) in document.capability.iter().enumerate() {
311            validate_record(capability)?;
312            validate_projection(capability, projected)?;
313            if !ids.insert(capability.id.as_str()) {
314                return Err(format!("duplicate capability id '{}'", capability.id));
315            }
316            lookup.insert(capability.id.clone(), index);
317        }
318        for (alias, target) in document.aliases {
319            if alias.trim().is_empty() || !ids.contains(target.as_str()) {
320                return Err(format!("invalid capability alias '{alias}' -> '{target}'"));
321            }
322            let index = lookup[&target];
323            if lookup.insert(alias.clone(), index).is_some() {
324                return Err(format!("duplicate capability lookup key '{alias}'"));
325            }
326        }
327        Ok(Self {
328            entries: document.capability,
329            lookup,
330            projected,
331        })
332    }
333
334    /// True for the public export's registry, whose non-public records
335    /// withhold their strategic classification.
336    #[must_use]
337    pub const fn is_public_projection(&self) -> bool {
338        self.projected
339    }
340
341    #[must_use]
342    pub fn entries(&self) -> &[ProductCapability] {
343        &self.entries
344    }
345
346    #[must_use]
347    pub fn find(&self, id_or_key: &str) -> Option<&ProductCapability> {
348        self.lookup
349            .get(id_or_key)
350            .and_then(|index| self.entries.get(*index))
351    }
352
353    #[must_use]
354    pub fn allows(&self, plan: Plan, id_or_key: &str) -> bool {
355        self.find(id_or_key).is_some_and(|capability| {
356            // A legacy plan can never grant separate SDK/OEM rights, and no
357            // plan grants a retired capability.
358            !matches!(
359                capability.price_class,
360                UserPriceClass::SdkOemCommercial | UserPriceClass::Retired
361            ) && plan.rank() >= capability.minimum_plan().rank()
362        })
363    }
364
365    #[must_use]
366    pub fn render_markdown(&self) -> String {
367        use std::fmt::Write as _;
368
369        let mut entries: Vec<&ProductCapability> = self.entries.iter().collect();
370        entries.sort_unstable_by_key(|capability| capability.id.as_str());
371        let mut output = String::from(
372            "<!-- Generated from product/capabilities.toml; do not edit by hand. -->\n\n\
373             # Product capabilities\n\n\
374             | ID | Name | Price | Cloud plan | Source visibility | Delivery | Aha | Moat | License | Self-host | Managed cloud | Enterprise entitlement | Account | Commercial use | Redistribution/OEM | Data boundary | Telemetry | Maturity | Source path |\n\
375             |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|\n",
376        );
377        for capability in entries {
378            writeln!(
379                output,
380                "| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |",
381                capability.id,
382                capability.name.replace('|', "\\|"),
383                enum_name(&capability.price_class),
384                capability
385                    .cloud_plan
386                    .as_ref()
387                    .map_or_else(|| "-".to_string(), enum_name),
388                enum_name(&capability.source_visibility),
389                enum_name(&capability.runtime_delivery),
390                enum_name(&capability.aha_criticality),
391                enum_name(&capability.moat_sensitivity),
392                enum_name(&capability.license_class),
393                capability.self_host_available,
394                capability.managed_cloud_available,
395                capability.enterprise_entitlement,
396                capability.account_required,
397                enum_name(&capability.allowed_commercial_use),
398                enum_name(&capability.redistribution_oem_rights),
399                capability.data_boundary.replace('|', "\\|"),
400                enum_name(&capability.telemetry_event_class),
401                enum_name(&capability.public_maturity),
402                capability.source_path.replace('|', "\\|"),
403            )
404            .expect("writing to String cannot fail");
405        }
406        output
407    }
408}
409
410fn enum_name<T: Serialize>(value: &T) -> String {
411    serde_json::to_value(value)
412        .expect("serializable registry enum")
413        .as_str()
414        .expect("registry enum serializes as string")
415        .to_string()
416}
417
418fn validate_record(capability: &ProductCapability) -> Result<(), String> {
419    for (field, value) in [
420        ("id", capability.id.as_str()),
421        ("name", capability.name.as_str()),
422        (
423            "enterprise_entitlement",
424            capability.enterprise_entitlement.as_str(),
425        ),
426        ("source_path", capability.source_path.as_str()),
427        ("data_boundary", capability.data_boundary.as_str()),
428    ] {
429        if value.trim().is_empty() {
430            return Err(format!("capability '{}' has empty {field}", capability.id));
431        }
432    }
433    let invalid = if matches!(
434        capability.aha_criticality,
435        AhaCriticality::IndividualAha | AhaCriticality::TeamAha
436    ) && capability.price_class != UserPriceClass::Free
437    {
438        Some("Aha-critical capability has no free delivery path")
439    } else if capability.moat_sensitivity == MoatSensitivity::CrownJewel
440        && capability.source_visibility != SourceVisibility::PrivateSource
441    {
442        Some("crown-jewel implementation must not enter public source")
443    } else if capability.moat_sensitivity == MoatSensitivity::CrownJewel
444        && capability.redistribution_oem_rights != RedistributionRights::SeparateAgreementRequired
445    {
446        Some("crown-jewel redistribution requires a separate agreement")
447    } else if capability.source_visibility == SourceVisibility::PublicApache
448        && (capability.license_class != LicenseClass::ApacheTrustCore
449            || capability.allowed_commercial_use != CommercialUse::ApacheRights
450            || capability.redistribution_oem_rights != RedistributionRights::ApacheRights
451            || capability.price_class != UserPriceClass::Free
452            || capability.account_required)
453    {
454        Some("public Apache reference rights must remain free and accountless")
455    } else if capability.license_class == LicenseClass::ApacheTrustCore
456        && capability.source_visibility != SourceVisibility::PublicApache
457    {
458        Some("Apache source classification mismatch")
459    } else if capability.source_visibility != SourceVisibility::PublicApache
460        && (capability.allowed_commercial_use == CommercialUse::ApacheRights
461            || capability.redistribution_oem_rights == RedistributionRights::ApacheRights)
462    {
463        Some("non-Apache implementations cannot grant Apache redistribution rights")
464    } else if capability.price_class == UserPriceClass::SdkOemCommercial
465        && (capability.license_class != LicenseClass::SdkOem
466            || capability.allowed_commercial_use != CommercialUse::SdkOemAgreement)
467    {
468        Some("SDK/OEM capability requires a separate commercial license")
469    } else if capability.runtime_delivery == RuntimeDelivery::SourceBuild
470        && (!capability.self_host_available
471            || capability.source_visibility == SourceVisibility::PrivateSource)
472    {
473        Some("source builds require available source and a self-host path")
474    } else if capability.runtime_delivery == RuntimeDelivery::ManagedCloudService
475        && !capability.managed_cloud_available
476    {
477        Some("managed service requires managed-cloud availability")
478    } else if matches!(
479        capability.runtime_delivery,
480        RuntimeDelivery::SignedBinary
481            | RuntimeDelivery::LocalService
482            | RuntimeDelivery::EnterprisePrivateImage
483    ) && !capability.self_host_available
484    {
485        Some("local artifact requires a self-host path")
486    } else if capability.aha_criticality == AhaCriticality::IndividualAha
487        && (capability.account_required || !capability.self_host_available)
488    {
489        Some("individual Aha must work locally without an account")
490    } else if capability.source_visibility == SourceVisibility::PublicEnterpriseSourceAvailable
491        && capability.license_class != LicenseClass::CommercialSource
492    {
493        Some("source-available Enterprise requires its own license")
494    } else if capability.license_class == LicenseClass::FreeRuntime
495        && (capability.source_visibility != SourceVisibility::PrivateSource
496            || capability.price_class != UserPriceClass::Free
497            || capability.allowed_commercial_use != CommercialUse::FreeSmallTeamInternal
498            || capability.redistribution_oem_rights
499                != RedistributionRights::SeparateAgreementRequired)
500    {
501        Some("Free Runtime rights must not grant source/OEM/redistribution rights")
502    } else if capability.is_enterprise() != (capability.enterprise_entitlement == capability.id) {
503        Some("Enterprise capability requires its explicit canonical entitlement")
504    } else if !capability.is_enterprise() && capability.enterprise_entitlement != "none" {
505        Some("non-Enterprise capability must not require governance entitlement")
506    } else if !capability.self_host_available && !capability.managed_cloud_available {
507        Some("capability has no delivery path")
508    } else if (capability.price_class == UserPriceClass::Cloud) != capability.cloud_plan.is_some() {
509        Some("LeanCTX Cloud plan is required exactly on cloud capabilities")
510    } else if capability.price_class == UserPriceClass::Cloud
511        && (capability.source_visibility != SourceVisibility::PrivateSource
512            || !capability.account_required
513            || !matches!(
514                capability.runtime_delivery,
515                RuntimeDelivery::CloudService | RuntimeDelivery::SignedBinary
516            ))
517    {
518        Some(
519            "LeanCTX Cloud capability needs private source, an account and the LeanCTX Cloud service or signed path",
520        )
521    } else if capability.runtime_delivery == RuntimeDelivery::CloudService
522        && (capability.price_class != UserPriceClass::Cloud || !capability.managed_cloud_available)
523    {
524        Some("LeanCTX Cloud service delivery requires a LeanCTX Cloud plan and the managed service")
525    } else if matches!(
526        capability.price_class,
527        UserPriceClass::CloudPaid
528            | UserPriceClass::ProPaid
529            | UserPriceClass::TeamPaid
530            | UserPriceClass::EnterprisePaid
531    ) {
532        Some("legacy price class is not valid in schema 3; use free, cloud or retired")
533    } else {
534        None
535    };
536    if let Some(reason) = invalid {
537        return Err(format!("capability '{}': {reason}", capability.id));
538    }
539    Ok(())
540}
541
542/// Fields the public projection withholds for capabilities whose
543/// implementation is not public: they describe product strategy, not rights.
544/// Access decisions use only price, source and rights, which stay intact.
545const WITHHELD_FIELDS: [(&str, &str); 4] = [
546    ("aha_criticality", "undisclosed"),
547    ("moat_sensitivity", "undisclosed"),
548    ("public_maturity", "private"),
549    ("source_path", UNDISCLOSED_SOURCE),
550];
551
552/// The canonical registry discloses everything; the public projection
553/// withholds all strategic fields of every non-public record and nothing of
554/// a public one. Anything in between fails closed.
555fn validate_projection(capability: &ProductCapability, projected: bool) -> Result<(), String> {
556    let withheld = [
557        capability.aha_criticality == AhaCriticality::Undisclosed,
558        capability.moat_sensitivity == MoatSensitivity::Undisclosed,
559        capability.public_maturity == PublicStatus::Private,
560        capability.source_path == UNDISCLOSED_SOURCE,
561    ];
562    let undisclosed = withheld[0] || withheld[1] || withheld[3];
563    let public = capability.source_visibility == SourceVisibility::PublicApache;
564    let problem = if !projected && undisclosed {
565        Some("undisclosed classification outside the public projection")
566    } else if projected && public && undisclosed {
567        Some("public capability must stay fully classified")
568    } else if projected && !public && !withheld.iter().all(|field| *field) {
569        Some("public projection discloses a strategic classification")
570    } else {
571        None
572    };
573    match problem {
574        Some(reason) => Err(format!("capability '{}': {reason}", capability.id)),
575        None => Ok(()),
576    }
577}
578
579/// Render the public projection of a canonical registry source: the
580/// `projection` marker plus the withheld strategy fields (Aha criticality,
581/// moat sensitivity, maturity, source path) rewritten for every
582/// non-public record. Layout and all other bytes are preserved; the result
583/// is re-parsed, so a rewrite that misses a field fails closed. Projecting a
584/// projection returns it unchanged.
585pub fn public_projection(source: &str) -> Result<String, String> {
586    use std::fmt::Write as _;
587
588    let registry = ProductCapabilityRegistry::parse(source)?;
589    if registry.is_public_projection() {
590        return Ok(source.to_string());
591    }
592    let hidden: BTreeSet<&str> = registry
593        .entries()
594        .iter()
595        .filter(|capability| capability.source_visibility != SourceVisibility::PublicApache)
596        .map(|capability| capability.id.as_str())
597        .collect();
598
599    let mut output = String::with_capacity(source.len());
600    let mut current_id: Option<String> = None;
601    for line in source.split_inclusive('\n') {
602        let content = line.trim_end_matches(['\n', '\r']);
603        let newline = &line[content.len()..];
604        if content.trim() == "[[capability]]" {
605            current_id = None;
606        }
607        let Some((key, value)) = content.split_once(" = ") else {
608            output.push_str(line);
609            continue;
610        };
611        if key == "id" {
612            current_id = Some(value.trim_matches('"').to_string());
613        }
614        let withheld = current_id
615            .as_deref()
616            .filter(|id| hidden.contains(id))
617            .and_then(|_| WITHHELD_FIELDS.iter().find(|(field, _)| *field == key));
618        match withheld {
619            Some((field, replacement)) => write!(output, "{field} = \"{replacement}\"{newline}")
620                .expect("writing to String cannot fail"),
621            None => output.push_str(line),
622        }
623        if key == "schema_version" {
624            write!(output, "projection = \"{PUBLIC_PROJECTION}\"{newline}")
625                .expect("writing to String cannot fail");
626        }
627    }
628
629    let projected = ProductCapabilityRegistry::parse(&output)?;
630    if !projected.is_public_projection() {
631        return Err("capability registry has no schema_version line to mark".to_string());
632    }
633    Ok(output)
634}
635
636static REGISTRY: OnceLock<ProductCapabilityRegistry> = OnceLock::new();
637
638#[must_use]
639pub fn registry() -> &'static ProductCapabilityRegistry {
640    REGISTRY.get_or_init(|| {
641        ProductCapabilityRegistry::parse(REGISTRY_SOURCE)
642            .unwrap_or_else(|error| panic!("embedded product capability registry failed: {error}"))
643    })
644}
645
646/// Stable product record for each OCLA capability kind. This exhaustive match
647/// makes a newly added OCLA kind fail compilation until it is classified.
648#[must_use]
649pub const fn ocla_product_capability_id(kind: OclaCapabilityKind) -> &'static str {
650    match kind {
651        OclaCapabilityKind::ObservationHook => "trust.ocla.observation_hook",
652        OclaCapabilityKind::UsageSink => "enterprise.ocla.usage_sink",
653        OclaCapabilityKind::MetricsExporter => "team.ocla.metrics_exporter",
654        OclaCapabilityKind::SavingsLedger => "trust.ocla.savings_ledger",
655        OclaCapabilityKind::IntentClassifier => "pro.ocla.intent_classifier",
656        OclaCapabilityKind::OutcomeTracker => "pro.ocla.outcome_tracker",
657        OclaCapabilityKind::CompressionProvider => "trust.ocla.compression_provider",
658        OclaCapabilityKind::ResponseOptimizer => "pro.ocla.response_optimizer",
659        OclaCapabilityKind::EfficiencyAnalyzer => "pro.ocla.efficiency_analyzer",
660        OclaCapabilityKind::ConfigTuner => "pro.ocla.config_tuner",
661        OclaCapabilityKind::ExperimentRunner => "pro.ocla.experiment_runner",
662        OclaCapabilityKind::ConnectorScheduler => "pro.ocla.connector_scheduler",
663        OclaCapabilityKind::AgentGateway => "pro.ocla.agent_gateway",
664        OclaCapabilityKind::DeliveryRegistry => "pro.ocla.delivery_registry",
665    }
666}
667
668pub const EXPERIMENT_EXECUTOR_CAPABILITY_ID: &str = "pro.ocla.experiment_executor";
669
670#[cfg(test)]
671mod tests {
672    use super::*;
673
674    #[test]
675    fn embedded_registry_is_valid() {
676        assert!(registry().entries().len() >= 40);
677        let source = include_str!("../../../product/capabilities.toml");
678        if REGISTRY_SOURCE == source {
679            return;
680        }
681        // A checkout with the canonical private registry embeds its public
682        // projection (scripts/project-capabilities.py; byte equality is
683        // checked by scripts/check-capabilities.py): the same capabilities in
684        // the same order, with no private source path.
685        assert!(
686            REGISTRY_SOURCE.contains("\nprojection = \"public\"\n"),
687            "packaged capability registry drifted from repository source"
688        );
689        let ids = |text: &str| -> Vec<String> {
690            ProductCapabilityRegistry::parse(text)
691                .expect("registry parses")
692                .entries()
693                .iter()
694                .map(|entry| entry.id.clone())
695                .collect()
696        };
697        assert_eq!(ids(REGISTRY_SOURCE), ids(source));
698        assert!(!REGISTRY_SOURCE.contains("\"ee/"));
699    }
700
701    #[test]
702    fn malformed_or_duplicate_records_are_rejected() {
703        assert!(ProductCapabilityRegistry::parse("schema_version = 99").is_err());
704        let first = &registry().entries()[0].id;
705        let second = &registry().entries()[1].id;
706        let duplicate = REGISTRY_SOURCE.replacen(
707            &format!("id = \"{second}\""),
708            &format!("id = \"{first}\""),
709            1,
710        );
711        assert!(ProductCapabilityRegistry::parse(&duplicate).is_err());
712    }
713
714    #[test]
715    fn unknown_capabilities_fail_closed() {
716        for plan in Plan::all() {
717            assert!(!registry().allows(*plan, "unclassified.future.feature"));
718        }
719    }
720
721    fn mutated_first(field: &str, value: toml::Value) -> String {
722        let mut document: toml::Value = toml::from_str(REGISTRY_SOURCE).unwrap();
723        document["capability"][0][field] = value;
724        toml::to_string(&document).unwrap()
725    }
726
727    #[test]
728    fn all_eighteen_classifications_are_required_without_defaults() {
729        let document: toml::Value = toml::from_str(REGISTRY_SOURCE).unwrap();
730        let records = document["capability"].as_array().unwrap();
731        for record in records {
732            let cloud = record["price_class"].as_str() == Some("cloud");
733            assert_eq!(
734                record.as_table().unwrap().len(),
735                18 + usize::from(cloud),
736                "{record}"
737            );
738            for field in record.as_table().unwrap().keys() {
739                let mut incomplete = record.clone();
740                incomplete.as_table_mut().unwrap().remove(field);
741                if field == "cloud_plan" {
742                    // Optional in the record format, required by validation.
743                    let parsed: ProductCapability = incomplete.try_into().unwrap();
744                    assert!(validate_record(&parsed).is_err(), "missing {field}");
745                    continue;
746                }
747                assert!(
748                    incomplete.try_into::<ProductCapability>().is_err(),
749                    "missing {field}"
750                );
751            }
752        }
753    }
754
755    /// The registry is the open-core boundary: every public capability points at
756    /// source that exists in this repository, and no private or paid capability
757    /// points into it. Moving paid code into the public tree fails here.
758    #[test]
759    fn registry_source_paths_enforce_the_open_core_boundary() {
760        let repository = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
761        for entry in registry().entries() {
762            for source in entry.source_path.split(';').map(str::trim) {
763                let in_repository = source.starts_with("rust/");
764                if entry.source_visibility == SourceVisibility::PublicApache {
765                    assert!(in_repository, "{}: public source outside rust/", entry.id);
766                    assert!(
767                        repository.join(source).exists(),
768                        "{}: public source {source} is missing",
769                        entry.id
770                    );
771                } else {
772                    assert!(
773                        !in_repository,
774                        "{}: private capability points into the public tree",
775                        entry.id
776                    );
777                }
778                if entry.price_class != UserPriceClass::Free {
779                    assert_ne!(entry.source_visibility, SourceVisibility::PublicApache);
780                }
781            }
782        }
783    }
784
785    #[test]
786    fn shared_team_capabilities_need_team_and_enterprise_self_hosts_them() {
787        let registry = registry();
788        let entry = registry.find("team.context.shared").unwrap();
789        assert_eq!(entry.price_class, UserPriceClass::Cloud);
790        assert_eq!(entry.cloud_plan, Some(CloudPlan::Team));
791        assert!(entry.managed_cloud_available && entry.self_host_available);
792        assert!(!registry.allows(Plan::Pro, &entry.id));
793        assert!(registry.allows(Plan::Team, &entry.id));
794        assert!(registry.allows(Plan::Enterprise, &entry.id));
795        let mut public = entry.clone();
796        public.source_visibility = SourceVisibility::PublicApache;
797        assert!(validate_record(&public).is_err());
798    }
799
800    #[test]
801    fn team_runtime_capabilities_ship_in_the_signed_self_hosted_runtime() {
802        let registry = registry();
803        for id in [
804            "team.runtime.artifact_reader",
805            "team.runtime.artifact_author",
806        ] {
807            let entry = registry.find(id).unwrap();
808            assert_eq!(entry.price_class, UserPriceClass::Cloud);
809            assert_eq!(entry.cloud_plan, Some(CloudPlan::Team));
810            assert_eq!(entry.runtime_delivery, RuntimeDelivery::SignedBinary);
811            assert!(entry.self_host_available && !entry.managed_cloud_available);
812            assert!(!registry.allows(Plan::Pro, id));
813            assert!(registry.allows(Plan::Team, id));
814            // Each condition of the Cloud rule refuses on its own.
815            let breaks: [fn(&mut ProductCapability); 3] = [
816                |record| {
817                    record.source_visibility = SourceVisibility::PublicEnterpriseSourceAvailable;
818                },
819                |record| record.account_required = false,
820                |record| record.runtime_delivery = RuntimeDelivery::LocalService,
821            ];
822            for change in breaks {
823                let mut broken = entry.clone();
824                change(&mut broken);
825                let refusal = validate_record(&broken).unwrap_err();
826                assert!(refusal.contains("LeanCTX Cloud capability"), "{refusal}");
827            }
828        }
829    }
830
831    #[test]
832    fn hosted_seat_authority_is_classified_for_team_and_enterprise_only() {
833        let registry = registry();
834        let entry = registry.find("team.seat_management").unwrap();
835        assert_eq!(entry.price_class, UserPriceClass::Cloud);
836        assert_eq!(entry.cloud_plan, Some(CloudPlan::Team));
837        assert_eq!(entry.runtime_delivery, RuntimeDelivery::CloudService);
838        assert!(entry.account_required && entry.managed_cloud_available);
839        assert_eq!(entry.enterprise_entitlement, "none");
840        assert!(!registry.allows(Plan::Community, &entry.id));
841        assert!(!registry.allows(Plan::Pro, &entry.id));
842        assert!(registry.allows(Plan::Team, &entry.id));
843        assert!(registry.allows(Plan::Enterprise, &entry.id));
844    }
845
846    #[test]
847    fn aha_paywalls_public_crown_jewels_and_unclassified_telemetry_fail_closed() {
848        for (field, value) in [
849            ("price_class", "cloud_paid"),
850            ("moat_sensitivity", "crown_jewel"),
851            ("license_class", "free_runtime"),
852            ("source_visibility", "private_source"),
853            ("telemetry_event_class", "arbitrary_runtime_text"),
854            ("enterprise_entitlement", "enterprise.unrelated"),
855        ] {
856            let malformed = mutated_first(field, value.into());
857            assert!(
858                ProductCapabilityRegistry::parse(&malformed).is_err(),
859                "accepted {field}={value}"
860            );
861        }
862        assert!(
863            ProductCapabilityRegistry::parse(&mutated_first("account_required", true.into()))
864                .is_err()
865        );
866    }
867
868    #[test]
869    fn free_private_intelligence_does_not_grant_oem_or_source_rights() {
870        // Exercise the free/private rights class without advertising a retired
871        // capability or changing the commercial classification of a live one.
872        let mut entry = registry()
873            .find("pro.runtime.adaptive_context")
874            .unwrap()
875            .clone();
876        entry.price_class = UserPriceClass::Free;
877        entry.license_class = LicenseClass::FreeRuntime;
878        entry.allowed_commercial_use = CommercialUse::FreeSmallTeamInternal;
879        entry.aha_criticality = AhaCriticality::IndividualAha;
880        entry.account_required = false;
881        assert!(validate_record(&entry).is_ok());
882        assert_eq!(entry.minimum_plan(), Plan::Community);
883        let mut leaking = entry.clone();
884        leaking.redistribution_oem_rights = RedistributionRights::ApacheRights;
885        assert!(validate_record(&leaking).is_err());
886        leaking = entry.clone();
887        leaking.allowed_commercial_use = CommercialUse::ApacheRights;
888        assert!(validate_record(&leaking).is_err());
889        // The public projection withholds moat and Aha classifications; the
890        // crown-jewel redistribution and individual-Aha account rules can only
891        // be exercised where they are disclosed (the canonical registry).
892        let disclosed = !registry().is_public_projection();
893        if disclosed {
894            leaking = entry.clone();
895            leaking.license_class = LicenseClass::ThirdParty;
896            leaking.redistribution_oem_rights = RedistributionRights::ThirdPartyTerms;
897            assert!(validate_record(&leaking).is_err());
898        }
899        for license in [
900            LicenseClass::PrivateService,
901            LicenseClass::CommercialSource,
902            LicenseClass::SdkOem,
903        ] {
904            leaking = entry.clone();
905            leaking.license_class = license;
906            leaking.redistribution_oem_rights = RedistributionRights::ApacheRights;
907            assert!(validate_record(&leaking).is_err());
908        }
909        leaking = entry.clone();
910        leaking.runtime_delivery = RuntimeDelivery::SourceBuild;
911        assert!(validate_record(&leaking).is_err());
912        if disclosed {
913            leaking = entry.clone();
914            leaking.account_required = true;
915            assert!(validate_record(&leaking).is_err());
916        }
917    }
918
919    #[test]
920    fn legacy_ids_do_not_paywall_local_or_small_team_aha() {
921        for entry in registry().entries() {
922            if matches!(
923                entry.aha_criticality,
924                AhaCriticality::IndividualAha | AhaCriticality::TeamAha
925            ) {
926                assert!(
927                    registry().allows(Plan::Community, &entry.id),
928                    "{}",
929                    entry.id
930                );
931            }
932        }
933        // Governance stays Enterprise; SSO and SCIM are in Team (owner
934        // decision), but never free.
935        for id in [
936            "enterprise.execution_policy",
937            "enterprise.agent_bus.governed",
938        ] {
939            assert!(!registry().allows(Plan::Community, id));
940            assert!(!registry().allows(Plan::Team, id));
941        }
942        for id in [
943            "enterprise.sso_scim",
944            "team.sso_oidc",
945            "team.audit_retention",
946        ] {
947            assert!(!registry().allows(Plan::Community, id));
948            assert!(!registry().allows(Plan::Pro, id));
949            assert!(registry().allows(Plan::Team, id));
950        }
951    }
952
953    /// D7: the public export withholds strategy (moat, Aha, maturity, private
954    /// source locations) without changing a single access decision.
955    #[test]
956    fn public_projection_withholds_strategy_but_keeps_every_access_decision() {
957        let canonical = ProductCapabilityRegistry::parse(REGISTRY_SOURCE).unwrap();
958        if canonical.is_public_projection() {
959            // Public export: parse() already enforced the projection; the
960            // canonical comparison runs where the canonical registry lives.
961            assert!(!REGISTRY_SOURCE.contains("crown_jewel"));
962            return;
963        }
964        let source = public_projection(REGISTRY_SOURCE).unwrap();
965        let projected = ProductCapabilityRegistry::parse(&source).unwrap();
966        assert!(projected.is_public_projection());
967        assert_eq!(public_projection(&source).unwrap(), source);
968        assert!(!source.contains("crown_jewel"));
969        assert_eq!(projected.entries().len(), canonical.entries().len());
970        for (before, after) in canonical.entries().iter().zip(projected.entries()) {
971            if before.source_visibility == SourceVisibility::PublicApache {
972                assert_eq!(before, after);
973            } else {
974                assert_eq!(after.moat_sensitivity, MoatSensitivity::Undisclosed);
975                assert_eq!(after.aha_criticality, AhaCriticality::Undisclosed);
976                assert_eq!(after.public_maturity, PublicStatus::Private);
977                assert_eq!(after.source_path, UNDISCLOSED_SOURCE);
978                let mut restored = after.clone();
979                restored.aha_criticality = before.aha_criticality;
980                restored.moat_sensitivity = before.moat_sensitivity;
981                restored.public_maturity = before.public_maturity;
982                restored.source_path.clone_from(&before.source_path);
983                assert_eq!(
984                    before, &restored,
985                    "projection changed rights of {}",
986                    before.id
987                );
988            }
989            for plan in Plan::all() {
990                assert_eq!(
991                    canonical.allows(*plan, &before.id),
992                    projected.allows(*plan, &before.id)
993                );
994            }
995        }
996
997        let hidden = canonical
998            .entries()
999            .iter()
1000            .find(|entry| entry.moat_sensitivity == MoatSensitivity::CrownJewel)
1001            .unwrap();
1002        let block = format!("id = \"{}\"", hidden.id);
1003        let (head, tail) = source.split_once(&block).unwrap();
1004        let partial = format!(
1005            "{head}{block}{}",
1006            tail.replacen(
1007                "moat_sensitivity = \"undisclosed\"",
1008                "moat_sensitivity = \"crown_jewel\"",
1009                1
1010            )
1011        );
1012        for (registry, case) in [
1013            (
1014                mutated_first("moat_sensitivity", "undisclosed".into()),
1015                "canonical",
1016            ),
1017            (partial, "partial projection"),
1018            (
1019                source.replacen("projection = \"public\"", "projection = \"other\"", 1),
1020                "unknown",
1021            ),
1022            (
1023                source.replacen(
1024                    &format!("source_path = \"{}\"", registry().entries()[0].source_path),
1025                    &format!("source_path = \"{UNDISCLOSED_SOURCE}\""),
1026                    1,
1027                ),
1028                "public record withheld",
1029            ),
1030        ] {
1031            assert!(
1032                ProductCapabilityRegistry::parse(&registry).is_err(),
1033                "accepted {case}"
1034            );
1035        }
1036    }
1037
1038    /// A3 (Cloud): local cockpit views are free, filter packs and team or
1039    /// governance rights are Cloud plans, Personal Cloud is retired, and no
1040    /// schema-3 record keeps a legacy price class.
1041    #[test]
1042    fn cloud_classification_keeps_local_free_and_retires_personal_cloud() {
1043        let registry = registry();
1044        for entry in registry.entries() {
1045            assert!(
1046                matches!(
1047                    entry.price_class,
1048                    UserPriceClass::Free
1049                        | UserPriceClass::Cloud
1050                        | UserPriceClass::Retired
1051                        | UserPriceClass::SdkOemCommercial
1052                ),
1053                "{} keeps a legacy price class",
1054                entry.id
1055            );
1056            if entry.price_class == UserPriceClass::Free {
1057                assert!(!entry.account_required, "{}", entry.id);
1058            }
1059        }
1060        for id in [
1061            "pro.dashboard.knowledge_workflows",
1062            "pro.runtime.adaptive_context",
1063            "pro.runtime.memory_curation",
1064            "pro.runtime.context_policy",
1065        ] {
1066            let entry = registry.find(id).unwrap();
1067            assert_eq!(entry.price_class, UserPriceClass::Free, "{id}");
1068            assert!(registry.allows(Plan::Community, id), "{id}");
1069        }
1070        for (id, plan) in [
1071            ("pro.runtime.semantic_detectors", CloudPlan::Personal),
1072            ("pro.runtime.code_security", CloudPlan::Personal),
1073            ("pro.runtime.personal_protection", CloudPlan::Personal),
1074            ("team.private_registry", CloudPlan::Team),
1075            ("team.managed_connectors", CloudPlan::Team),
1076            ("team.sso_oidc", CloudPlan::Team),
1077            ("enterprise.sso_scim", CloudPlan::Team),
1078            ("team.audit_retention", CloudPlan::Team),
1079            (
1080                "enterprise.runtime.org_policy_verifier",
1081                CloudPlan::Enterprise,
1082            ),
1083        ] {
1084            let entry = registry.find(id).unwrap();
1085            assert_eq!(entry.price_class, UserPriceClass::Cloud, "{id}");
1086            assert_eq!(entry.cloud_plan, Some(plan), "{id}");
1087            assert_eq!(entry.minimum_plan(), plan.plan(), "{id}");
1088            assert!(!registry.allows(Plan::Community, id), "{id}");
1089            assert!(registry.allows(Plan::Enterprise, id), "{id}");
1090        }
1091        for id in ["pro.cloud_sync", "pro.hosted_index", "team.revenue_share"] {
1092            let entry = registry.find(id).unwrap();
1093            assert_eq!(entry.price_class, UserPriceClass::Retired, "{id}");
1094            assert_ne!(entry.minimum_plan(), Plan::Community, "{id}");
1095            for plan in Plan::all() {
1096                assert!(!registry.allows(*plan, id), "{id} granted to {plan:?}");
1097            }
1098        }
1099        // Stable lookup names survive the reclassification.
1100        assert_eq!(registry.find("cloud_sync").unwrap().id, "pro.cloud_sync");
1101        assert_eq!(registry.find("sso_oidc").unwrap().id, "team.sso_oidc");
1102
1103        let cloud = registry.find("team.context.shared").unwrap().clone();
1104        for legacy in [
1105            UserPriceClass::CloudPaid,
1106            UserPriceClass::ProPaid,
1107            UserPriceClass::TeamPaid,
1108        ] {
1109            let mut broken = cloud.clone();
1110            broken.price_class = legacy;
1111            broken.cloud_plan = None;
1112            broken.runtime_delivery = RuntimeDelivery::ManagedCloudService;
1113            assert!(validate_record(&broken).is_err(), "{legacy:?} accepted");
1114        }
1115        let mut planless = cloud.clone();
1116        planless.cloud_plan = None;
1117        assert!(validate_record(&planless).is_err());
1118        let mut stray = registry.find("free.cockpit.ui").unwrap().clone();
1119        stray.cloud_plan = Some(CloudPlan::Personal);
1120        assert!(validate_record(&stray).is_err());
1121        let mut local = cloud;
1122        local.managed_cloud_available = false;
1123        assert!(validate_record(&local).is_err());
1124    }
1125
1126    #[test]
1127    fn legacy_aliases_cannot_shadow_ids_or_point_to_unclassified_capabilities() {
1128        for target in ["missing.capability", "compression"] {
1129            let mut document: toml::Value = toml::from_str(REGISTRY_SOURCE).unwrap();
1130            document["aliases"]
1131                .as_table_mut()
1132                .unwrap()
1133                .insert("bad_alias".into(), target.into());
1134            assert!(
1135                ProductCapabilityRegistry::parse(&toml::to_string(&document).unwrap()).is_err()
1136            );
1137        }
1138        let mut document: toml::Value = toml::from_str(REGISTRY_SOURCE).unwrap();
1139        document["aliases"].as_table_mut().unwrap().insert(
1140            "trust.runtime.compression".into(),
1141            "trust.runtime.caching".into(),
1142        );
1143        assert!(ProductCapabilityRegistry::parse(&toml::to_string(&document).unwrap()).is_err());
1144    }
1145}