lean_ctx/core/intelligence_runtime/
configuration.rs1use 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 or a commercial licence; the public reference runtime works without either. Staging packages are not production releases.";
11
12pub 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 pub fn deactivated(&self) -> bool {
36 self.config.deactivated()
37 }
38
39 #[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 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 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 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 pub fn install_and_enable(&self) -> Result<serde_json::Value> {
141 self.install_and_enable_with(super::catalog::Companions::Inline)
142 }
143
144 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(if super::bootstrap::offers_channel() {
160 InstallError::Policy
161 } else {
162 InstallError::NotOffered
163 });
164 }
165 if global_runtime()? != self.observed_config {
166 return Err(InstallError::Configuration);
167 }
168 let root = Path::new(&self.config.root);
169 if self.config != self.observed_config {
170 super::install::prepare_parent_chain(root.parent().ok_or(InstallError::Directory)?)?;
171 }
172 let _guard = super::install::configuration_guard(root)?;
173 if global_runtime()? != self.observed_config {
174 return Err(InstallError::Configuration);
175 }
176 let expected = super::install::active_manifest(root)?;
177 let result = super::catalog::sync(
178 [&self.config.channel_url, &self.config.channel_signature_url],
179 &super::trust_key(&self.config.channel_root_key_hex)?,
180 root,
181 &expected,
182 companions,
183 )?;
184 let selected = result["receipt"]["manifest_sha256"]
185 .as_str()
186 .ok_or(InstallError::State)?;
187 let key = result["artifact_key_hex"]
188 .as_str()
189 .ok_or(InstallError::State)?;
190 let activation = activate_checked(root, selected, key, Some(self))?;
191 Ok(
192 serde_json::json!({"status": "installed_and_activated", "installation": result,
193 "activation": activation, "release_approved": false}),
194 )
195 }
196
197 pub(crate) fn rollback_and_enable(&self) -> Result<serde_json::Value> {
199 if self.config.manifest_sha256.is_empty() || self.config.staging {
200 return Err(InstallError::Policy);
201 }
202 let root = Path::new(&self.config.root);
203 let _guard = super::install::configuration_guard(root)?;
204 if global_runtime()? != self.observed_config {
205 return Err(InstallError::Configuration);
206 }
207 let (result, key) =
208 super::install::rollback_configured(root, &self.config.manifest_sha256)?;
209 let selected = result["receipt"]["manifest_sha256"]
210 .as_str()
211 .ok_or(InstallError::State)?;
212 let activation = activate_checked(root, selected, &key, Some(self))?;
216 Ok(
217 serde_json::json!({"status": "rolled_back_and_activated", "rollback": result,
218 "activation": activation, "release_approved": false}),
219 )
220 }
221}
222
223pub const COMPANIONS_LATER: &str = super::catalog::COMPANIONS_LATER;
226
227pub fn load_companions() -> Result<serde_json::Value> {
231 let candidate = inspect_setup()?;
232 if !candidate.enabled() {
233 return Err(InstallError::State);
234 }
235 let config = &candidate.config;
236 let root = Path::new(&config.root);
237 let _loading = super::install::companions_guard(root)?;
239 let package = {
240 let _guard = super::install::configuration_guard(root)?;
241 if global_runtime()? != candidate.observed_config {
242 return Err(InstallError::Configuration);
243 }
244 super::install::verified_active(
245 root,
246 &config.manifest_sha256,
247 &super::trust_key(&config.trust_key_hex)?,
248 )?
249 };
250 let unchanged = || global_runtime().is_ok_and(|now| now == candidate.observed_config);
254 let loaded = super::catalog::load_companions(
255 [&config.channel_url, &config.channel_signature_url],
256 &super::trust_key(&config.channel_root_key_hex)?,
257 root,
258 &package,
259 &unchanged,
260 )?;
261 Ok(serde_json::json!({
262 "status": if loaded { "companions_installed" } else { "companions_not_present" },
263 "release_approved": false
264 }))
265}
266
267pub fn inspect_setup() -> Result<SetupRuntime> {
268 let observed_config = global_runtime()?;
270 let config = if observed_config.is_unset() {
273 IntelligenceRuntimeConfig {
274 declined: observed_config.declined,
275 ..super::bootstrap::config()?
276 }
277 } else {
278 observed_config.clone()
279 };
280 let version = if config.is_unset() {
281 None
282 } else {
283 if !super::bootstrap::permits_config(&config) {
284 return Err(not_offered_or_policy(&config));
285 }
286 let has_channel = !config.channel_url.is_empty()
287 || !config.channel_signature_url.is_empty()
288 || !config.channel_root_key_hex.is_empty();
289 if has_channel {
290 super::channel::validate_urls(&[&config.channel_url, &config.channel_signature_url])?;
291 super::trust_key(&config.channel_root_key_hex)?;
292 if !Path::new(&config.root).is_absolute() {
293 return Err(InstallError::Directory);
294 }
295 }
296 if config.manifest_sha256.is_empty() && config.trust_key_hex.is_empty() {
297 if !has_channel || config.enabled || config.accept_proprietary {
298 return Err(InstallError::Policy);
299 }
300 None
301 } else {
302 let key = super::trust_key(&config.trust_key_hex)?;
303 match super::install::verified_active(
304 Path::new(&config.root),
305 &config.manifest_sha256,
306 &key,
307 ) {
308 Ok(package) => Some(package.receipt.version),
309 Err(_) if has_channel => None,
312 Err(error) => return Err(error),
313 }
314 }
315 };
316 Ok(SetupRuntime {
317 config,
318 observed_config,
319 version,
320 })
321}
322
323pub(super) fn not_offered_or_policy(config: &IntelligenceRuntimeConfig) -> InstallError {
327 if !config.staging && !super::bootstrap::offers_production() {
328 InstallError::NotOffered
329 } else {
330 InstallError::Policy
331 }
332}
333
334fn global_runtime() -> Result<IntelligenceRuntimeConfig> {
337 Config::try_load_global()
338 .map(|config| config.intelligence_runtime.with_recorded_decline())
339 .map_err(|_| InstallError::Configuration)
340}
341
342fn same_as_observed(
345 config: &IntelligenceRuntimeConfig,
346 observed: &IntelligenceRuntimeConfig,
347) -> bool {
348 IntelligenceRuntimeConfig {
349 declined: observed.declined,
350 ..config.clone()
351 } == *observed
352}
353
354pub(super) fn activate(root: &Path, selected: &str, encoded: &str) -> Result<serde_json::Value> {
355 activate_checked(root, selected, encoded, None)
356}
357
358fn activate_checked(
359 root: &Path,
360 selected: &str,
361 encoded: &str,
362 expected: Option<&SetupRuntime>,
363) -> Result<serde_json::Value> {
364 let observed = global_runtime()?;
365 if expected.is_some_and(|expected| observed != expected.observed_config) {
366 return Err(InstallError::Configuration);
367 }
368 let key = super::trust_key(encoded)?;
369 let checked = health::check(root, selected, &key)?;
370 let staging = checked["receipt"]["staging_only"]
371 .as_bool()
372 .ok_or(InstallError::State)?;
373 let production = super::bootstrap::production_key(root)?.is_some();
374 if staging == production {
375 return Err(InstallError::Policy);
376 }
377 let previous = if production {
378 let mut compiled = super::bootstrap::config()?;
379 if !super::bootstrap::permits_config(&compiled) {
380 return Err(InstallError::Policy);
381 }
382 compiled.license_configuration = expected
383 .map(|expected| expected.config.license_configuration.clone())
384 .or_else(|| {
385 (!observed.staging && super::bootstrap::permits_config(&observed))
386 .then(|| observed.license_configuration.clone())
387 })
388 .unwrap_or_default();
389 if observed.root == compiled.root && super::bootstrap::permits_config(&observed) {
391 observed.clone()
392 } else {
393 compiled
394 }
395 } else if let Some(expected) = expected {
396 expected.config.clone()
397 } else if Path::new(&observed.root) == root {
398 observed.clone()
399 } else {
400 IntelligenceRuntimeConfig::default()
401 };
402 let root = root.to_str().ok_or(InstallError::Directory)?.to_owned();
403 Config::try_update_global(|config| {
404 if !same_as_observed(&config.intelligence_runtime, &observed) {
405 return Err(crate::core::error::LeanCtxError::Config(
406 "runtime setup configuration changed".into(),
407 ));
408 }
409 config.intelligence_runtime =
410 IntelligenceRuntimeConfig::activated(previous, staging, root, selected, encoded);
411 Ok(())
412 })
413 .map_err(|_| InstallError::Configuration)?;
414 crate::core::config::record_decline(false).map_err(|_| InstallError::Configuration)?;
416 Ok(serde_json::json!({"status": "activated", "health": checked,
417 "staging_only": staging, "release_approved": false}))
418}
419
420pub(super) fn deactivate() -> Result<serde_json::Value> {
421 crate::core::config::record_decline(true).map_err(|_| InstallError::Configuration)?;
424 Config::update_global(|config| config.intelligence_runtime.switch_off())
425 .map_err(|_| InstallError::Configuration)?;
426 Ok(serde_json::json!({"status": "disabled", "release_approved": false}))
427}