Skip to main content

lean_ctx/core/intelligence_runtime/
configuration.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Persist explicit user consent only after the selected runtime passes health.
3
4use std::path::Path;
5
6use crate::core::config::{Config, IntelligenceRuntimeConfig};
7
8use super::{InstallError, Result, health};
9
10pub const DISCLOSURE: &str = "Intelligence Runtime: proprietary, runs locally. Its commercial features are licensed through LeanCTX Cloud or a commercial licence; the public reference runtime works without either. Staging packages are not production releases.";
11
12/// Verified setup snapshot: discovery never starts proprietary code or grants consent.
13pub struct SetupRuntime {
14    config: IntelligenceRuntimeConfig,
15    observed_config: IntelligenceRuntimeConfig,
16    version: Option<String>,
17}
18
19impl SetupRuntime {
20    pub fn available(&self) -> bool {
21        self.version.is_some()
22    }
23
24    pub fn channel_available(&self) -> bool {
25        !self.config.channel_url.is_empty()
26    }
27
28    pub fn enabled(&self) -> bool {
29        self.available() && self.config.enabled && self.config.accept_proprietary
30    }
31
32    /// Accepted once, then switched off with `setup runtime deactivate`:
33    /// setup leaves it off. From the configuration only, so a package that
34    /// no longer verifies never turns a switched-off runtime back on.
35    pub fn deactivated(&self) -> bool {
36        self.config.deactivated()
37    }
38
39    /// What setup finds for `config` when nothing verifies (no version):
40    /// for planning only; it installs nothing.
41    #[doc(hidden)]
42    #[must_use]
43    pub fn not_installed(config: IntelligenceRuntimeConfig) -> Self {
44        Self {
45            observed_config: config.clone(),
46            config,
47            version: None,
48        }
49    }
50
51    /// Enabled and verified, but the signed model set of its package is not
52    /// installed (left for later, or a background load that failed). Never
53    /// downloads; any error reads as "nothing pending".
54    pub fn companions_pending(&self) -> bool {
55        if !self.enabled() {
56            return false;
57        }
58        let root = Path::new(&self.config.root);
59        super::trust_key(&self.config.trust_key_hex)
60            .and_then(|key| {
61                super::install::verified_active(root, &self.config.manifest_sha256, &key)
62            })
63            .and_then(|package| super::install::companions_missing(root, &package))
64            .unwrap_or(false)
65    }
66
67    pub fn status(&self) -> &'static str {
68        if self.enabled() {
69            "configured"
70        } else if self.available() {
71            "available"
72        } else if self.channel_available() {
73            if self.config.manifest_sha256.is_empty() {
74                "download_available"
75            } else {
76                "repair_available"
77            }
78        } else {
79            "not_configured"
80        }
81    }
82
83    pub(crate) fn report(&self) -> serde_json::Value {
84        // Reported here, once and without content, instead of as an
85        // unavailable semantic check on every admission: a configured
86        // runtime whose package does not offer semantic detectors is a
87        // property of the installation.
88        // The install-side fields are the ones `runtime health` prints, from
89        // the same function: what the authenticated package and its
90        // installed model set offer. `semantic_categories` are the categories
91        // that set examines; a category that is not listed is not covered.
92        let mut report = serde_json::json!({"schema_version": 1, "status": self.status(),
93            "version": self.version, "disclosure": DISCLOSURE,
94            "semantic_detectors": "not_configured",
95            "semantic_descriptor_sha256_prefix": null,
96            "semantic_versions": [], "semantic_categories": [],
97            "runtime_started": false, "release_approved": false});
98        if self.enabled() {
99            let authenticated = super::trust_key(&self.config.trust_key_hex)
100                .and_then(|key| {
101                    super::install::verified_active(
102                        Path::new(&self.config.root),
103                        &self.config.manifest_sha256,
104                        &key,
105                    )
106                })
107                .ok();
108            if let Some(package) = authenticated {
109                let state = super::install::semantic_state(&package);
110                let versions = super::install::semantic_set(&package)
111                    .map_or_else(Vec::new, |set| set.versions);
112                for (key, value) in health::semantic_report(&package, &state, versions) {
113                    report[key] = value;
114                }
115            } else {
116                report["semantic_detectors"] = "unverified".into();
117            }
118        }
119        for (key, value) in health::semantic_worker_report(&self.config) {
120            report[key] = value;
121        }
122        report
123    }
124
125    /// The caller must obtain explicit consent for this captured, trusted selection.
126    pub fn enable(&self) -> Result<serde_json::Value> {
127        if !self.available() {
128            return Err(InstallError::State);
129        }
130        let _guard = super::install::configuration_guard(Path::new(&self.config.root))?;
131        activate_checked(
132            Path::new(&self.config.root),
133            &self.config.manifest_sha256,
134            &self.config.trust_key_hex,
135            Some(self),
136        )
137    }
138
139    /// Called only after explicit consent; discovery itself never uses the network.
140    pub fn install_and_enable(&self) -> Result<serde_json::Value> {
141        self.install_and_enable_with(super::catalog::Companions::Inline)
142    }
143
144    /// As [`Self::install_and_enable`] for setup (owner decision
145    /// 23.11.2026): the runtime only, so setup stays fast with or without
146    /// a terminal; the companions of a v4 package (hundreds of megabytes)
147    /// are left for [`load_companions`] in the background. The result's
148    /// `installation.semantic_models_reason` is then
149    /// [`COMPANIONS_LATER`].
150    pub fn install_runtime_and_enable(&self) -> Result<serde_json::Value> {
151        self.install_and_enable_with(super::catalog::Companions::Later)
152    }
153
154    fn install_and_enable_with(
155        &self,
156        companions: super::catalog::Companions,
157    ) -> Result<serde_json::Value> {
158        if !self.channel_available() {
159            return Err(InstallError::Policy);
160        }
161        if global_runtime()? != self.observed_config {
162            return Err(InstallError::Configuration);
163        }
164        let root = Path::new(&self.config.root);
165        if self.config != self.observed_config {
166            super::install::prepare_parent_chain(root.parent().ok_or(InstallError::Directory)?)?;
167        }
168        let _guard = super::install::configuration_guard(root)?;
169        if global_runtime()? != self.observed_config {
170            return Err(InstallError::Configuration);
171        }
172        let expected = super::install::active_manifest(root)?;
173        let result = super::catalog::sync(
174            [&self.config.channel_url, &self.config.channel_signature_url],
175            &super::trust_key(&self.config.channel_root_key_hex)?,
176            root,
177            &expected,
178            companions,
179        )?;
180        let selected = result["receipt"]["manifest_sha256"]
181            .as_str()
182            .ok_or(InstallError::State)?;
183        let key = result["artifact_key_hex"]
184            .as_str()
185            .ok_or(InstallError::State)?;
186        let activation = activate_checked(root, selected, key, Some(self))?;
187        Ok(
188            serde_json::json!({"status": "installed_and_activated", "installation": result,
189            "activation": activation, "release_approved": false}),
190        )
191    }
192
193    /// Restore only the retained, authenticated predecessor of this snapshot.
194    pub(crate) fn rollback_and_enable(&self) -> Result<serde_json::Value> {
195        if self.config.manifest_sha256.is_empty() || self.config.staging {
196            return Err(InstallError::Policy);
197        }
198        let root = Path::new(&self.config.root);
199        let _guard = super::install::configuration_guard(root)?;
200        if global_runtime()? != self.observed_config {
201            return Err(InstallError::Configuration);
202        }
203        let (result, key) =
204            super::install::rollback_configured(root, &self.config.manifest_sha256)?;
205        let selected = result["receipt"]["manifest_sha256"]
206            .as_str()
207            .ok_or(InstallError::State)?;
208        // A failed health/configuration check leaves the old binding mismatched
209        // and therefore unusable. Retrying reauthenticates the signed rollback
210        // relationship and completes activation without another selection change.
211        let activation = activate_checked(root, selected, &key, Some(self))?;
212        Ok(
213            serde_json::json!({"status": "rolled_back_and_activated", "rollback": result,
214            "activation": activation, "release_approved": false}),
215        )
216    }
217}
218
219/// `semantic_models_reason` of an install that left the companions for
220/// [`load_companions`].
221pub const COMPANIONS_LATER: &str = super::catalog::COMPANIONS_LATER;
222
223/// Load the companions setup left for later (`setup runtime
224/// load-companions`, started in the background by setup): only for the
225/// enabled, verified runtime, from the location its signed channel names.
226pub fn load_companions() -> Result<serde_json::Value> {
227    let candidate = inspect_setup()?;
228    if !candidate.enabled() {
229        return Err(InstallError::State);
230    }
231    let config = &candidate.config;
232    let root = Path::new(&config.root);
233    // One background load at a time: a second one ends here (`Busy`).
234    let _loading = super::install::companions_guard(root)?;
235    let package = {
236        let _guard = super::install::configuration_guard(root)?;
237        if global_runtime()? != candidate.observed_config {
238            return Err(InstallError::Configuration);
239        }
240        super::install::verified_active(
241            root,
242            &config.manifest_sha256,
243            &super::trust_key(&config.trust_key_hex)?,
244        )?
245    };
246    // No lock is held across the download: install_channel_companions takes
247    // install.lock only to check and rename the verified set, and publishes
248    // nothing when the runtime was switched off (or changed) meanwhile.
249    let unchanged = || global_runtime().is_ok_and(|now| now == candidate.observed_config);
250    let loaded = super::catalog::load_companions(
251        [&config.channel_url, &config.channel_signature_url],
252        &super::trust_key(&config.channel_root_key_hex)?,
253        root,
254        &package,
255        &unchanged,
256    )?;
257    Ok(serde_json::json!({
258        "status": if loaded { "companions_installed" } else { "companions_not_present" },
259        "release_approved": false
260    }))
261}
262
263pub fn inspect_setup() -> Result<SetupRuntime> {
264    // Never merge project configuration, search PATH, download or start a child.
265    let observed_config = global_runtime()?;
266    // A runtime switched off before its first install is still the
267    // bundled channel, kept off.
268    let config = if observed_config.is_unset() {
269        IntelligenceRuntimeConfig {
270            declined: observed_config.declined,
271            ..super::bootstrap::config()?
272        }
273    } else {
274        observed_config.clone()
275    };
276    let version = if config.is_unset() {
277        None
278    } else {
279        if !super::bootstrap::permits_config(&config) {
280            return Err(InstallError::Policy);
281        }
282        let has_channel = !config.channel_url.is_empty()
283            || !config.channel_signature_url.is_empty()
284            || !config.channel_root_key_hex.is_empty();
285        if has_channel {
286            super::channel::validate_urls(&[&config.channel_url, &config.channel_signature_url])?;
287            super::trust_key(&config.channel_root_key_hex)?;
288            if !Path::new(&config.root).is_absolute() {
289                return Err(InstallError::Directory);
290            }
291        }
292        if config.manifest_sha256.is_empty() && config.trust_key_hex.is_empty() {
293            if !has_channel || config.enabled || config.accept_proprietary {
294                return Err(InstallError::Policy);
295            }
296            None
297        } else {
298            let key = super::trust_key(&config.trust_key_hex)?;
299            match super::install::verified_active(
300                Path::new(&config.root),
301                &config.manifest_sha256,
302                &key,
303            ) {
304                Ok(package) => Some(package.receipt.version),
305                // Offer only a new consented, authenticated download; never enable
306                // this unverified selection. This also recovers an interrupted update.
307                Err(_) if has_channel => None,
308                Err(error) => return Err(error),
309            }
310        }
311    };
312    Ok(SetupRuntime {
313        config,
314        observed_config,
315        version,
316    })
317}
318
319/// The user-global runtime configuration, with the decline recorded next
320/// to `config.toml` merged in.
321fn global_runtime() -> Result<IntelligenceRuntimeConfig> {
322    Config::try_load_global()
323        .map(|config| config.intelligence_runtime.with_recorded_decline())
324        .map_err(|_| InstallError::Configuration)
325}
326
327/// `config` as `global_runtime` reads it, without touching the marker: the
328/// decline of `observed` stands for it.
329fn same_as_observed(
330    config: &IntelligenceRuntimeConfig,
331    observed: &IntelligenceRuntimeConfig,
332) -> bool {
333    IntelligenceRuntimeConfig {
334        declined: observed.declined,
335        ..config.clone()
336    } == *observed
337}
338
339pub(super) fn activate(root: &Path, selected: &str, encoded: &str) -> Result<serde_json::Value> {
340    activate_checked(root, selected, encoded, None)
341}
342
343fn activate_checked(
344    root: &Path,
345    selected: &str,
346    encoded: &str,
347    expected: Option<&SetupRuntime>,
348) -> Result<serde_json::Value> {
349    let observed = global_runtime()?;
350    if expected.is_some_and(|expected| observed != expected.observed_config) {
351        return Err(InstallError::Configuration);
352    }
353    let key = super::trust_key(encoded)?;
354    let checked = health::check(root, selected, &key)?;
355    let staging = checked["receipt"]["staging_only"]
356        .as_bool()
357        .ok_or(InstallError::State)?;
358    let production = super::bootstrap::production_key(root)?.is_some();
359    if staging == production {
360        return Err(InstallError::Policy);
361    }
362    let previous = if production {
363        let mut compiled = super::bootstrap::config()?;
364        if !super::bootstrap::permits_config(&compiled) {
365            return Err(InstallError::Policy);
366        }
367        compiled.license_configuration = expected
368            .map(|expected| expected.config.license_configuration.clone())
369            .or_else(|| {
370                (!observed.staging && super::bootstrap::permits_config(&observed))
371                    .then(|| observed.license_configuration.clone())
372            })
373            .unwrap_or_default();
374        // A channel refresh must not erase the device's existing license binding.
375        if observed.root == compiled.root && super::bootstrap::permits_config(&observed) {
376            observed.clone()
377        } else {
378            compiled
379        }
380    } else if let Some(expected) = expected {
381        expected.config.clone()
382    } else if Path::new(&observed.root) == root {
383        observed.clone()
384    } else {
385        IntelligenceRuntimeConfig::default()
386    };
387    let root = root.to_str().ok_or(InstallError::Directory)?.to_owned();
388    Config::try_update_global(|config| {
389        if !same_as_observed(&config.intelligence_runtime, &observed) {
390            return Err(crate::core::error::LeanCtxError::Config(
391                "runtime setup configuration changed".into(),
392            ));
393        }
394        config.intelligence_runtime =
395            IntelligenceRuntimeConfig::activated(previous, staging, root, selected, encoded);
396        Ok(())
397    })
398    .map_err(|_| InstallError::Configuration)?;
399    // An explicit install switches it on again: the decline goes too.
400    crate::core::config::record_decline(false).map_err(|_| InstallError::Configuration)?;
401    Ok(serde_json::json!({"status": "activated", "health": checked,
402        "staging_only": staging, "release_approved": false}))
403}
404
405pub(super) fn deactivate() -> Result<serde_json::Value> {
406    // The decline first (next to config.toml, where 3.12.7 never looks), so
407    // an interrupted deactivate never leaves the runtime to be switched on.
408    crate::core::config::record_decline(true).map_err(|_| InstallError::Configuration)?;
409    Config::update_global(|config| config.intelligence_runtime.switch_off())
410        .map_err(|_| InstallError::Configuration)?;
411    Ok(serde_json::json!({"status": "disabled", "release_approved": false}))
412}