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::billing::Plan;
15use crate::core::ocla::OclaCapabilityKind;
16
17/// Package-local mirror of the repository source of truth. CI requires this
18/// byte-for-byte copy so source-package builds remain hermetic.
19pub const REGISTRY_SOURCE: &str = include_str!("../../data/product-capabilities.toml");
20
21#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
22#[serde(rename_all = "snake_case")]
23pub enum UserPriceClass {
24    Free,
25    CloudPaid,
26    /// Pro subscription feature delivered only inside the signed, private
27    /// Intelligence Runtime; the runtime's own license gates its execution.
28    ProPaid,
29    /// Shared team capability: Team subscription on the managed cloud; the
30    /// self-hosted delivery is the Enterprise private image (Enterprise ⊇ Team).
31    TeamPaid,
32    EnterprisePaid,
33    SdkOemCommercial,
34}
35
36#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
37#[serde(rename_all = "snake_case")]
38pub enum SourceVisibility {
39    PublicApache,
40    PublicEnterpriseSourceAvailable,
41    PrivateSource,
42}
43
44#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
45#[serde(rename_all = "snake_case")]
46pub enum RuntimeDelivery {
47    SourceBuild,
48    SignedBinary,
49    LocalService,
50    ManagedCloudService,
51    EnterprisePrivateImage,
52}
53
54#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
55#[serde(rename_all = "snake_case")]
56pub enum AhaCriticality {
57    None,
58    Supporting,
59    IndividualAha,
60    TeamAha,
61    /// Withheld by the public projection; see [`public_projection`].
62    Undisclosed,
63}
64
65#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
66#[serde(rename_all = "snake_case")]
67pub enum MoatSensitivity {
68    Low,
69    Medium,
70    CrownJewel,
71    /// Withheld by the public projection; see [`public_projection`].
72    Undisclosed,
73}
74
75/// Marker value of the registry's top-level `projection` key.
76pub const PUBLIC_PROJECTION: &str = "public";
77/// `source_path` of a capability whose implementation is not public.
78pub const UNDISCLOSED_SOURCE: &str = "undisclosed";
79
80#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
81#[serde(rename_all = "snake_case")]
82pub enum CommercialUse {
83    ApacheRights,
84    FreeSmallTeamInternal,
85    ServiceAgreement,
86    EnterpriseAgreement,
87    SdkOemAgreement,
88    ThirdPartyTerms,
89}
90
91#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
92#[serde(rename_all = "snake_case")]
93pub enum RedistributionRights {
94    ApacheRights,
95    SeparateAgreementRequired,
96    ThirdPartyTerms,
97}
98
99#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
100#[serde(rename_all = "snake_case")]
101pub enum TelemetryEventClass {
102    None,
103    ProductUsage,
104    BillingUsage,
105    OperationalAggregate,
106    Audit,
107}
108
109#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
110#[serde(rename_all = "snake_case")]
111pub enum PublicStatus {
112    Available,
113    Preview,
114    Internal,
115    Deprecated,
116    Research,
117    Private,
118}
119
120#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
121#[serde(rename_all = "snake_case")]
122pub enum LicenseClass {
123    ApacheTrustCore,
124    CommercialSource,
125    PrivateService,
126    FreeRuntime,
127    SdkOem,
128    ThirdParty,
129}
130
131#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
132#[serde(deny_unknown_fields)]
133pub struct ProductCapability {
134    pub id: String,
135    pub name: String,
136    pub price_class: UserPriceClass,
137    pub source_visibility: SourceVisibility,
138    pub runtime_delivery: RuntimeDelivery,
139    pub aha_criticality: AhaCriticality,
140    pub moat_sensitivity: MoatSensitivity,
141    pub license_class: LicenseClass,
142    pub self_host_available: bool,
143    pub managed_cloud_available: bool,
144    /// Canonical governance key, or the explicit value `none`.
145    pub enterprise_entitlement: String,
146    pub account_required: bool,
147    pub allowed_commercial_use: CommercialUse,
148    pub redistribution_oem_rights: RedistributionRights,
149    pub data_boundary: String,
150    pub telemetry_event_class: TelemetryEventClass,
151    pub public_maturity: PublicStatus,
152    pub source_path: String,
153}
154
155impl ProductCapability {
156    /// Compatibility projection for legacy clients; not entitlement authority.
157    #[must_use]
158    pub const fn minimum_plan(&self) -> Plan {
159        match self.price_class {
160            UserPriceClass::Free => Plan::Community,
161            UserPriceClass::CloudPaid | UserPriceClass::ProPaid => Plan::Pro,
162            UserPriceClass::TeamPaid => Plan::Team,
163            UserPriceClass::EnterprisePaid | UserPriceClass::SdkOemCommercial => Plan::Enterprise,
164        }
165    }
166}
167
168#[derive(Clone, Debug, Deserialize)]
169#[serde(deny_unknown_fields)]
170struct RegistryDocument {
171    schema_version: u16,
172    /// Absent in the canonical registry; [`PUBLIC_PROJECTION`] in the public
173    /// export, whose non-public records carry no strategic classification.
174    #[serde(default)]
175    projection: Option<String>,
176    capability: Vec<ProductCapability>,
177    /// Legacy wire/config lookup names, separate from the 18-field records.
178    aliases: BTreeMap<String, String>,
179}
180
181#[derive(Debug)]
182pub struct ProductCapabilityRegistry {
183    entries: Vec<ProductCapability>,
184    lookup: BTreeMap<String, usize>,
185    projected: bool,
186}
187
188impl ProductCapabilityRegistry {
189    pub fn parse(source: &str) -> Result<Self, String> {
190        let document: RegistryDocument = toml::from_str(source)
191            .map_err(|error| format!("invalid capability registry: {error}"))?;
192        if document.schema_version != 2 {
193            return Err(format!(
194                "unsupported capability registry schema {}",
195                document.schema_version
196            ));
197        }
198        if document.capability.is_empty() {
199            return Err("capability registry is empty".to_string());
200        }
201
202        let projected = match document.projection.as_deref() {
203            None => false,
204            Some(PUBLIC_PROJECTION) => true,
205            Some(other) => return Err(format!("unknown capability registry projection '{other}'")),
206        };
207
208        let mut lookup = BTreeMap::new();
209        let mut ids = BTreeSet::new();
210        for (index, capability) in document.capability.iter().enumerate() {
211            validate_record(capability)?;
212            validate_projection(capability, projected)?;
213            if !ids.insert(capability.id.as_str()) {
214                return Err(format!("duplicate capability id '{}'", capability.id));
215            }
216            lookup.insert(capability.id.clone(), index);
217        }
218        for (alias, target) in document.aliases {
219            if alias.trim().is_empty() || !ids.contains(target.as_str()) {
220                return Err(format!("invalid capability alias '{alias}' -> '{target}'"));
221            }
222            let index = lookup[&target];
223            if lookup.insert(alias.clone(), index).is_some() {
224                return Err(format!("duplicate capability lookup key '{alias}'"));
225            }
226        }
227        Ok(Self {
228            entries: document.capability,
229            lookup,
230            projected,
231        })
232    }
233
234    /// True for the public export's registry, whose non-public records
235    /// withhold their strategic classification.
236    #[must_use]
237    pub const fn is_public_projection(&self) -> bool {
238        self.projected
239    }
240
241    #[must_use]
242    pub fn entries(&self) -> &[ProductCapability] {
243        &self.entries
244    }
245
246    #[must_use]
247    pub fn find(&self, id_or_key: &str) -> Option<&ProductCapability> {
248        self.lookup
249            .get(id_or_key)
250            .and_then(|index| self.entries.get(*index))
251    }
252
253    #[must_use]
254    pub fn allows(&self, plan: Plan, id_or_key: &str) -> bool {
255        self.find(id_or_key).is_some_and(|capability| {
256            // A legacy plan can never grant separate SDK/OEM rights.
257            capability.price_class != UserPriceClass::SdkOemCommercial
258                && plan.rank() >= capability.minimum_plan().rank()
259        })
260    }
261
262    #[must_use]
263    pub fn render_markdown(&self) -> String {
264        use std::fmt::Write as _;
265
266        let mut entries: Vec<&ProductCapability> = self.entries.iter().collect();
267        entries.sort_unstable_by_key(|capability| capability.id.as_str());
268        let mut output = String::from(
269            "<!-- Generated from product/capabilities.toml; do not edit by hand. -->\n\n\
270             # Product capabilities\n\n\
271             | ID | Name | Price | Source visibility | Delivery | Aha | Moat | License | Self-host | Managed cloud | Enterprise entitlement | Account | Commercial use | Redistribution/OEM | Data boundary | Telemetry | Maturity | Source path |\n\
272             |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|\n",
273        );
274        for capability in entries {
275            writeln!(
276                output,
277                "| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |",
278                capability.id,
279                capability.name.replace('|', "\\|"),
280                enum_name(&capability.price_class),
281                enum_name(&capability.source_visibility),
282                enum_name(&capability.runtime_delivery),
283                enum_name(&capability.aha_criticality),
284                enum_name(&capability.moat_sensitivity),
285                enum_name(&capability.license_class),
286                capability.self_host_available,
287                capability.managed_cloud_available,
288                capability.enterprise_entitlement,
289                capability.account_required,
290                enum_name(&capability.allowed_commercial_use),
291                enum_name(&capability.redistribution_oem_rights),
292                capability.data_boundary.replace('|', "\\|"),
293                enum_name(&capability.telemetry_event_class),
294                enum_name(&capability.public_maturity),
295                capability.source_path.replace('|', "\\|"),
296            )
297            .expect("writing to String cannot fail");
298        }
299        output
300    }
301}
302
303fn enum_name<T: Serialize>(value: &T) -> String {
304    serde_json::to_value(value)
305        .expect("serializable registry enum")
306        .as_str()
307        .expect("registry enum serializes as string")
308        .to_string()
309}
310
311fn validate_record(capability: &ProductCapability) -> Result<(), String> {
312    for (field, value) in [
313        ("id", capability.id.as_str()),
314        ("name", capability.name.as_str()),
315        (
316            "enterprise_entitlement",
317            capability.enterprise_entitlement.as_str(),
318        ),
319        ("source_path", capability.source_path.as_str()),
320        ("data_boundary", capability.data_boundary.as_str()),
321    ] {
322        if value.trim().is_empty() {
323            return Err(format!("capability '{}' has empty {field}", capability.id));
324        }
325    }
326    let invalid = if matches!(
327        capability.aha_criticality,
328        AhaCriticality::IndividualAha | AhaCriticality::TeamAha
329    ) && capability.price_class != UserPriceClass::Free
330    {
331        Some("Aha-critical capability has no free delivery path")
332    } else if capability.moat_sensitivity == MoatSensitivity::CrownJewel
333        && capability.source_visibility != SourceVisibility::PrivateSource
334    {
335        Some("crown-jewel implementation must not enter public source")
336    } else if capability.moat_sensitivity == MoatSensitivity::CrownJewel
337        && capability.redistribution_oem_rights != RedistributionRights::SeparateAgreementRequired
338    {
339        Some("crown-jewel redistribution requires a separate agreement")
340    } else if capability.source_visibility == SourceVisibility::PublicApache
341        && (capability.license_class != LicenseClass::ApacheTrustCore
342            || capability.allowed_commercial_use != CommercialUse::ApacheRights
343            || capability.redistribution_oem_rights != RedistributionRights::ApacheRights
344            || capability.price_class != UserPriceClass::Free
345            || capability.account_required)
346    {
347        Some("public Apache reference rights must remain free and accountless")
348    } else if capability.license_class == LicenseClass::ApacheTrustCore
349        && capability.source_visibility != SourceVisibility::PublicApache
350    {
351        Some("Apache source classification mismatch")
352    } else if capability.source_visibility != SourceVisibility::PublicApache
353        && (capability.allowed_commercial_use == CommercialUse::ApacheRights
354            || capability.redistribution_oem_rights == RedistributionRights::ApacheRights)
355    {
356        Some("non-Apache implementations cannot grant Apache redistribution rights")
357    } else if capability.price_class == UserPriceClass::SdkOemCommercial
358        && (capability.license_class != LicenseClass::SdkOem
359            || capability.allowed_commercial_use != CommercialUse::SdkOemAgreement)
360    {
361        Some("SDK/OEM capability requires a separate commercial license")
362    } else if capability.runtime_delivery == RuntimeDelivery::SourceBuild
363        && (!capability.self_host_available
364            || capability.source_visibility == SourceVisibility::PrivateSource)
365    {
366        Some("source builds require available source and a self-host path")
367    } else if capability.runtime_delivery == RuntimeDelivery::ManagedCloudService
368        && !capability.managed_cloud_available
369    {
370        Some("managed service requires managed-cloud availability")
371    } else if matches!(
372        capability.runtime_delivery,
373        RuntimeDelivery::SignedBinary
374            | RuntimeDelivery::LocalService
375            | RuntimeDelivery::EnterprisePrivateImage
376    ) && !capability.self_host_available
377    {
378        Some("local artifact requires a self-host path")
379    } else if capability.aha_criticality == AhaCriticality::IndividualAha
380        && (capability.account_required || !capability.self_host_available)
381    {
382        Some("individual Aha must work locally without an account")
383    } else if capability.source_visibility == SourceVisibility::PublicEnterpriseSourceAvailable
384        && capability.license_class != LicenseClass::CommercialSource
385    {
386        Some("source-available Enterprise requires its own license")
387    } else if capability.license_class == LicenseClass::FreeRuntime
388        && (capability.source_visibility != SourceVisibility::PrivateSource
389            || capability.price_class != UserPriceClass::Free
390            || capability.allowed_commercial_use != CommercialUse::FreeSmallTeamInternal
391            || capability.redistribution_oem_rights
392                != RedistributionRights::SeparateAgreementRequired)
393    {
394        Some("Free Runtime rights must not grant source/OEM/redistribution rights")
395    } else if (capability.price_class == UserPriceClass::EnterprisePaid)
396        != (capability.enterprise_entitlement == capability.id)
397    {
398        Some("Enterprise capability requires its explicit canonical entitlement")
399    } else if capability.price_class != UserPriceClass::EnterprisePaid
400        && capability.enterprise_entitlement != "none"
401    {
402        Some("non-Enterprise capability must not require governance entitlement")
403    } else if !capability.self_host_available && !capability.managed_cloud_available {
404        Some("capability has no delivery path")
405    } else if capability.price_class == UserPriceClass::TeamPaid
406        && (capability.source_visibility != SourceVisibility::PrivateSource
407            || !capability.managed_cloud_available
408            || !capability.account_required)
409    {
410        Some("Team capability needs private source and the managed Team cloud path")
411    } else if capability.price_class == UserPriceClass::ProPaid
412        && (capability.source_visibility != SourceVisibility::PrivateSource
413            || capability.runtime_delivery != RuntimeDelivery::SignedBinary)
414    {
415        Some("Pro runtime capability ships only in the signed private runtime")
416    } else {
417        None
418    };
419    if let Some(reason) = invalid {
420        return Err(format!("capability '{}': {reason}", capability.id));
421    }
422    Ok(())
423}
424
425/// Fields the public projection withholds for capabilities whose
426/// implementation is not public: they describe product strategy, not rights.
427/// Access decisions use only price, source and rights, which stay intact.
428const WITHHELD_FIELDS: [(&str, &str); 4] = [
429    ("aha_criticality", "undisclosed"),
430    ("moat_sensitivity", "undisclosed"),
431    ("public_maturity", "private"),
432    ("source_path", UNDISCLOSED_SOURCE),
433];
434
435/// The canonical registry discloses everything; the public projection
436/// withholds all strategic fields of every non-public record and nothing of
437/// a public one. Anything in between fails closed.
438fn validate_projection(capability: &ProductCapability, projected: bool) -> Result<(), String> {
439    let withheld = [
440        capability.aha_criticality == AhaCriticality::Undisclosed,
441        capability.moat_sensitivity == MoatSensitivity::Undisclosed,
442        capability.public_maturity == PublicStatus::Private,
443        capability.source_path == UNDISCLOSED_SOURCE,
444    ];
445    let undisclosed = withheld[0] || withheld[1] || withheld[3];
446    let public = capability.source_visibility == SourceVisibility::PublicApache;
447    let problem = if !projected && undisclosed {
448        Some("undisclosed classification outside the public projection")
449    } else if projected && public && undisclosed {
450        Some("public capability must stay fully classified")
451    } else if projected && !public && !withheld.iter().all(|field| *field) {
452        Some("public projection discloses a strategic classification")
453    } else {
454        None
455    };
456    match problem {
457        Some(reason) => Err(format!("capability '{}': {reason}", capability.id)),
458        None => Ok(()),
459    }
460}
461
462/// Render the public projection of a canonical registry source: the
463/// `projection` marker plus the withheld strategy fields (Aha criticality,
464/// moat sensitivity, maturity, source path) rewritten for every
465/// non-public record. Layout and all other bytes are preserved; the result
466/// is re-parsed, so a rewrite that misses a field fails closed. Projecting a
467/// projection returns it unchanged.
468pub fn public_projection(source: &str) -> Result<String, String> {
469    use std::fmt::Write as _;
470
471    let registry = ProductCapabilityRegistry::parse(source)?;
472    if registry.is_public_projection() {
473        return Ok(source.to_string());
474    }
475    let hidden: BTreeSet<&str> = registry
476        .entries()
477        .iter()
478        .filter(|capability| capability.source_visibility != SourceVisibility::PublicApache)
479        .map(|capability| capability.id.as_str())
480        .collect();
481
482    let mut output = String::with_capacity(source.len());
483    let mut current_id: Option<String> = None;
484    for line in source.split_inclusive('\n') {
485        let content = line.trim_end_matches(['\n', '\r']);
486        let newline = &line[content.len()..];
487        if content.trim() == "[[capability]]" {
488            current_id = None;
489        }
490        let Some((key, value)) = content.split_once(" = ") else {
491            output.push_str(line);
492            continue;
493        };
494        if key == "id" {
495            current_id = Some(value.trim_matches('"').to_string());
496        }
497        let withheld = current_id
498            .as_deref()
499            .filter(|id| hidden.contains(id))
500            .and_then(|_| WITHHELD_FIELDS.iter().find(|(field, _)| *field == key));
501        match withheld {
502            Some((field, replacement)) => write!(output, "{field} = \"{replacement}\"{newline}")
503                .expect("writing to String cannot fail"),
504            None => output.push_str(line),
505        }
506        if key == "schema_version" {
507            write!(output, "projection = \"{PUBLIC_PROJECTION}\"{newline}")
508                .expect("writing to String cannot fail");
509        }
510    }
511
512    let projected = ProductCapabilityRegistry::parse(&output)?;
513    if !projected.is_public_projection() {
514        return Err("capability registry has no schema_version line to mark".to_string());
515    }
516    Ok(output)
517}
518
519static REGISTRY: OnceLock<ProductCapabilityRegistry> = OnceLock::new();
520
521#[must_use]
522pub fn registry() -> &'static ProductCapabilityRegistry {
523    REGISTRY.get_or_init(|| {
524        ProductCapabilityRegistry::parse(REGISTRY_SOURCE)
525            .unwrap_or_else(|error| panic!("embedded product capability registry failed: {error}"))
526    })
527}
528
529/// Stable product record for each OCLA capability kind. This exhaustive match
530/// makes a newly added OCLA kind fail compilation until it is classified.
531#[must_use]
532pub const fn ocla_product_capability_id(kind: OclaCapabilityKind) -> &'static str {
533    match kind {
534        OclaCapabilityKind::ObservationHook => "trust.ocla.observation_hook",
535        OclaCapabilityKind::UsageSink => "enterprise.ocla.usage_sink",
536        OclaCapabilityKind::MetricsExporter => "team.ocla.metrics_exporter",
537        OclaCapabilityKind::SavingsLedger => "trust.ocla.savings_ledger",
538        OclaCapabilityKind::IntentClassifier => "pro.ocla.intent_classifier",
539        OclaCapabilityKind::OutcomeTracker => "pro.ocla.outcome_tracker",
540        OclaCapabilityKind::CompressionProvider => "trust.ocla.compression_provider",
541        OclaCapabilityKind::ResponseOptimizer => "pro.ocla.response_optimizer",
542        OclaCapabilityKind::EfficiencyAnalyzer => "pro.ocla.efficiency_analyzer",
543        OclaCapabilityKind::ConfigTuner => "pro.ocla.config_tuner",
544        OclaCapabilityKind::ExperimentRunner => "pro.ocla.experiment_runner",
545        OclaCapabilityKind::ConnectorScheduler => "pro.ocla.connector_scheduler",
546        OclaCapabilityKind::AgentGateway => "pro.ocla.agent_gateway",
547        OclaCapabilityKind::DeliveryRegistry => "pro.ocla.delivery_registry",
548    }
549}
550
551pub const EXPERIMENT_EXECUTOR_CAPABILITY_ID: &str = "pro.ocla.experiment_executor";
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556
557    #[test]
558    fn embedded_registry_is_valid() {
559        assert!(registry().entries().len() >= 40);
560        assert_eq!(
561            REGISTRY_SOURCE.as_bytes(),
562            include_bytes!("../../../product/capabilities.toml"),
563            "packaged capability registry drifted from repository source"
564        );
565    }
566
567    #[test]
568    fn malformed_or_duplicate_records_are_rejected() {
569        assert!(ProductCapabilityRegistry::parse("schema_version = 99").is_err());
570        let first = &registry().entries()[0].id;
571        let second = &registry().entries()[1].id;
572        let duplicate = REGISTRY_SOURCE.replacen(
573            &format!("id = \"{second}\""),
574            &format!("id = \"{first}\""),
575            1,
576        );
577        assert!(ProductCapabilityRegistry::parse(&duplicate).is_err());
578    }
579
580    #[test]
581    fn unknown_capabilities_fail_closed() {
582        for plan in Plan::all() {
583            assert!(!registry().allows(*plan, "unclassified.future.feature"));
584        }
585    }
586
587    fn mutated_first(field: &str, value: toml::Value) -> String {
588        let mut document: toml::Value = toml::from_str(REGISTRY_SOURCE).unwrap();
589        document["capability"][0][field] = value;
590        toml::to_string(&document).unwrap()
591    }
592
593    #[test]
594    fn all_eighteen_classifications_are_required_without_defaults() {
595        let document: toml::Value = toml::from_str(REGISTRY_SOURCE).unwrap();
596        let records = document["capability"].as_array().unwrap();
597        for record in records {
598            assert_eq!(record.as_table().unwrap().len(), 18);
599            for field in record.as_table().unwrap().keys() {
600                let mut incomplete = record.clone();
601                incomplete.as_table_mut().unwrap().remove(field);
602                assert!(
603                    incomplete.try_into::<ProductCapability>().is_err(),
604                    "missing {field}"
605                );
606            }
607        }
608    }
609
610    /// The registry is the open-core boundary: every public capability points at
611    /// source that exists in this repository, and no private or paid capability
612    /// points into it. Moving paid code into the public tree fails here.
613    #[test]
614    fn registry_source_paths_enforce_the_open_core_boundary() {
615        let repository = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
616        for entry in registry().entries() {
617            for source in entry.source_path.split(';').map(str::trim) {
618                let in_repository = source.starts_with("rust/");
619                if entry.source_visibility == SourceVisibility::PublicApache {
620                    assert!(in_repository, "{}: public source outside rust/", entry.id);
621                    assert!(
622                        repository.join(source).exists(),
623                        "{}: public source {source} is missing",
624                        entry.id
625                    );
626                } else {
627                    assert!(
628                        !in_repository,
629                        "{}: private capability points into the public tree",
630                        entry.id
631                    );
632                }
633                if entry.price_class != UserPriceClass::Free {
634                    assert_ne!(entry.source_visibility, SourceVisibility::PublicApache);
635                }
636            }
637        }
638    }
639
640    #[test]
641    fn shared_team_capabilities_need_team_and_enterprise_self_hosts_them() {
642        let registry = registry();
643        let entry = registry.find("team.context.shared").unwrap();
644        assert_eq!(entry.price_class, UserPriceClass::TeamPaid);
645        assert!(entry.managed_cloud_available && entry.self_host_available);
646        assert!(!registry.allows(Plan::Pro, &entry.id));
647        assert!(registry.allows(Plan::Team, &entry.id));
648        assert!(registry.allows(Plan::Enterprise, &entry.id));
649        let mut public = entry.clone();
650        public.source_visibility = SourceVisibility::PublicApache;
651        assert!(validate_record(&public).is_err());
652    }
653
654    #[test]
655    fn aha_paywalls_public_crown_jewels_and_unclassified_telemetry_fail_closed() {
656        for (field, value) in [
657            ("price_class", "cloud_paid"),
658            ("moat_sensitivity", "crown_jewel"),
659            ("license_class", "free_runtime"),
660            ("source_visibility", "private_source"),
661            ("telemetry_event_class", "arbitrary_runtime_text"),
662            ("enterprise_entitlement", "enterprise.unrelated"),
663        ] {
664            let malformed = mutated_first(field, value.into());
665            assert!(
666                ProductCapabilityRegistry::parse(&malformed).is_err(),
667                "accepted {field}={value}"
668            );
669        }
670        assert!(
671            ProductCapabilityRegistry::parse(&mutated_first("account_required", true.into()))
672                .is_err()
673        );
674    }
675
676    #[test]
677    fn free_private_intelligence_does_not_grant_oem_or_source_rights() {
678        let entry = registry().find("pro.runtime.adaptive_routing").unwrap();
679        assert_eq!(entry.price_class, UserPriceClass::Free);
680        assert_eq!(entry.source_visibility, SourceVisibility::PrivateSource);
681        assert_eq!(entry.license_class, LicenseClass::FreeRuntime);
682        assert!(registry().allows(Plan::Community, &entry.id));
683        let mut leaking = entry.clone();
684        leaking.redistribution_oem_rights = RedistributionRights::ApacheRights;
685        assert!(validate_record(&leaking).is_err());
686        leaking = entry.clone();
687        leaking.allowed_commercial_use = CommercialUse::ApacheRights;
688        assert!(validate_record(&leaking).is_err());
689        // The public projection withholds moat and Aha classifications; the
690        // crown-jewel redistribution and individual-Aha account rules can only
691        // be exercised where they are disclosed (the canonical registry).
692        let disclosed = !registry().is_public_projection();
693        if disclosed {
694            leaking = entry.clone();
695            leaking.license_class = LicenseClass::ThirdParty;
696            leaking.redistribution_oem_rights = RedistributionRights::ThirdPartyTerms;
697            assert!(validate_record(&leaking).is_err());
698        }
699        for license in [
700            LicenseClass::PrivateService,
701            LicenseClass::CommercialSource,
702            LicenseClass::SdkOem,
703        ] {
704            leaking = entry.clone();
705            leaking.license_class = license;
706            leaking.redistribution_oem_rights = RedistributionRights::ApacheRights;
707            assert!(validate_record(&leaking).is_err());
708        }
709        leaking = entry.clone();
710        leaking.runtime_delivery = RuntimeDelivery::SourceBuild;
711        assert!(validate_record(&leaking).is_err());
712        if disclosed {
713            leaking = entry.clone();
714            leaking.account_required = true;
715            assert!(validate_record(&leaking).is_err());
716        }
717    }
718
719    #[test]
720    fn legacy_ids_do_not_paywall_local_or_small_team_aha() {
721        for entry in registry().entries() {
722            if matches!(
723                entry.aha_criticality,
724                AhaCriticality::IndividualAha | AhaCriticality::TeamAha
725            ) {
726                assert!(
727                    registry().allows(Plan::Community, &entry.id),
728                    "{}",
729                    entry.id
730                );
731            }
732        }
733        for id in [
734            "enterprise.execution_policy",
735            "enterprise.sso_scim",
736            "team.sso_oidc",
737        ] {
738            assert!(!registry().allows(Plan::Community, id));
739            assert!(!registry().allows(Plan::Team, id));
740        }
741    }
742
743    /// D7: the public export withholds strategy (moat, Aha, maturity, private
744    /// source locations) without changing a single access decision.
745    #[test]
746    fn public_projection_withholds_strategy_but_keeps_every_access_decision() {
747        let canonical = ProductCapabilityRegistry::parse(REGISTRY_SOURCE).unwrap();
748        if canonical.is_public_projection() {
749            // Public export: parse() already enforced the projection; the
750            // canonical comparison runs where the canonical registry lives.
751            assert!(!REGISTRY_SOURCE.contains("crown_jewel"));
752            return;
753        }
754        let source = public_projection(REGISTRY_SOURCE).unwrap();
755        let projected = ProductCapabilityRegistry::parse(&source).unwrap();
756        assert!(projected.is_public_projection());
757        assert_eq!(public_projection(&source).unwrap(), source);
758        assert!(!source.contains("crown_jewel"));
759        assert_eq!(projected.entries().len(), canonical.entries().len());
760        for (before, after) in canonical.entries().iter().zip(projected.entries()) {
761            if before.source_visibility == SourceVisibility::PublicApache {
762                assert_eq!(before, after);
763            } else {
764                assert_eq!(after.moat_sensitivity, MoatSensitivity::Undisclosed);
765                assert_eq!(after.aha_criticality, AhaCriticality::Undisclosed);
766                assert_eq!(after.public_maturity, PublicStatus::Private);
767                assert_eq!(after.source_path, UNDISCLOSED_SOURCE);
768                let mut restored = after.clone();
769                restored.aha_criticality = before.aha_criticality;
770                restored.moat_sensitivity = before.moat_sensitivity;
771                restored.public_maturity = before.public_maturity;
772                restored.source_path.clone_from(&before.source_path);
773                assert_eq!(
774                    before, &restored,
775                    "projection changed rights of {}",
776                    before.id
777                );
778            }
779            for plan in Plan::all() {
780                assert_eq!(
781                    canonical.allows(*plan, &before.id),
782                    projected.allows(*plan, &before.id)
783                );
784            }
785        }
786
787        let hidden = canonical
788            .entries()
789            .iter()
790            .find(|entry| entry.moat_sensitivity == MoatSensitivity::CrownJewel)
791            .unwrap();
792        let block = format!("id = \"{}\"", hidden.id);
793        let (head, tail) = source.split_once(&block).unwrap();
794        let partial = format!(
795            "{head}{block}{}",
796            tail.replacen(
797                "moat_sensitivity = \"undisclosed\"",
798                "moat_sensitivity = \"crown_jewel\"",
799                1
800            )
801        );
802        for (registry, case) in [
803            (
804                mutated_first("moat_sensitivity", "undisclosed".into()),
805                "canonical",
806            ),
807            (partial, "partial projection"),
808            (
809                source.replacen("projection = \"public\"", "projection = \"other\"", 1),
810                "unknown",
811            ),
812            (
813                source.replacen(
814                    &format!("source_path = \"{}\"", registry().entries()[0].source_path),
815                    &format!("source_path = \"{UNDISCLOSED_SOURCE}\""),
816                    1,
817                ),
818                "public record withheld",
819            ),
820        ] {
821            assert!(
822                ProductCapabilityRegistry::parse(&registry).is_err(),
823                "accepted {case}"
824            );
825        }
826    }
827
828    #[test]
829    fn legacy_aliases_cannot_shadow_ids_or_point_to_unclassified_capabilities() {
830        for target in ["missing.capability", "compression"] {
831            let mut document: toml::Value = toml::from_str(REGISTRY_SOURCE).unwrap();
832            document["aliases"]
833                .as_table_mut()
834                .unwrap()
835                .insert("bad_alias".into(), target.into());
836            assert!(
837                ProductCapabilityRegistry::parse(&toml::to_string(&document).unwrap()).is_err()
838            );
839        }
840        let mut document: toml::Value = toml::from_str(REGISTRY_SOURCE).unwrap();
841        document["aliases"].as_table_mut().unwrap().insert(
842            "trust.runtime.compression".into(),
843            "trust.runtime.caching".into(),
844        );
845        assert!(ProductCapabilityRegistry::parse(&toml::to_string(&document).unwrap()).is_err());
846    }
847}