use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Duration;
use super::install::SemanticState;
use super::{InstallError, Result, VerifiedPackage, install};
const DESCRIBE_SECONDS: u64 = 2;
const SEMANTIC_DESCRIBE_SECONDS: u64 = 60;
pub(super) fn check(root: &Path, selected: &str, key: &[u8; 32]) -> Result<serde_json::Value> {
let package = install::verified_active(root, selected, key)?;
let state = install::semantic_state(&package);
let (temporary, mut command) = prepare(&package, root)?;
let mut seconds = DESCRIBE_SECONDS;
let mut versions = Vec::new();
let expected = match &state {
SemanticState::Offered { .. } => {
let set = name_semantic_models(&package, &mut command)
.ok()
.flatten()
.ok_or(InstallError::Health)?;
versions = set.versions;
seconds = SEMANTIC_DESCRIBE_SECONDS;
package.description.clone()
}
SemanticState::SetNotPresent | SemanticState::NotOffered => {
super::manifest::without_semantic(&package.description)
}
SemanticState::Unverified => return Err(InstallError::Health),
};
command.arg("--describe").stdin(Stdio::null());
let captured = crate::core::process_capture::run_with_output_limits(
&mut command,
Some(Duration::from_secs(seconds)),
65_536,
4_096,
)
.map_err(|_| InstallError::Health)?;
if captured.timed_out
|| captured.cancelled
|| !captured.output.status.success()
|| !captured.output.stderr.is_empty()
{
return Err(InstallError::Health);
}
let actual: serde_json::Value =
serde_json::from_slice(&captured.output.stdout).map_err(|_| InstallError::Health)?;
if actual != expected {
return Err(InstallError::Health);
}
temporary.close()?;
let mut report = serde_json::json!({
"status": "healthy", "receipt": package.receipt, "description": actual,
"runtime_started": true, "service_running": false, "user_state_modified": false,
"release_approved": false
});
for (key, value) in semantic_report(&package, &state, versions) {
report[key] = value;
}
let live = crate::core::config::Config::load_global().intelligence_runtime;
for (key, value) in semantic_worker_report(&live) {
report[key] = value;
}
Ok(report)
}
const WORKER_SCOPE_NOTE: &str = "worker state is per process; a server process holds its own";
pub(super) fn semantic_worker_report(
config: &crate::core::config::IntelligenceRuntimeConfig,
) -> [(&'static str, serde_json::Value); 4] {
let (worker, versions) = super::semantic_detectors::worker_state(config);
[
("semantic_worker", worker.into()),
("semantic_worker_versions", versions.into()),
("semantic_worker_scope", "this_process".into()),
("semantic_worker_note", WORKER_SCOPE_NOTE.into()),
]
}
pub(super) fn semantic_report(
package: &VerifiedPackage,
state: &SemanticState,
versions: Vec<String>,
) -> [(&'static str, serde_json::Value); 4] {
[
("semantic_detectors", state.as_str().into()),
(
"semantic_descriptor_sha256_prefix",
state.descriptor_prefix().into(),
),
("semantic_versions", versions.into()),
(
"semantic_categories",
super::manifest::semantic_categories(package).into(),
),
]
}
pub(super) struct Prepared {
workspace: install::Temporary,
#[cfg(target_os = "linux")]
executable: tempfile::TempDir,
}
impl Prepared {
#[cfg(unix)]
pub(super) fn path(&self) -> &Path {
self.workspace.path()
}
pub(super) fn close(self) -> std::io::Result<()> {
let workspace = self.workspace.close();
#[cfg(target_os = "linux")]
{
let executable = self.executable.close();
workspace.and(executable)
}
#[cfg(not(target_os = "linux"))]
workspace
}
}
pub(super) fn name_semantic_models(
package: &VerifiedPackage,
command: &mut Command,
) -> Result<Option<install::SemanticSet>> {
if package.semantic.is_none() {
return Ok(None);
}
let set = install::semantic_set(package).ok_or(InstallError::InvocationAdmission)?;
command
.env("LEANCTX_INTELLIGENCE_SEMANTIC_MODELS", &set.directory)
.env(
"LEANCTX_INTELLIGENCE_SEMANTIC_DESCRIPTOR_SHA256",
&set.descriptor_sha256,
);
Ok(Some(set))
}
pub(crate) fn prepare(package: &VerifiedPackage, root: &Path) -> Result<(Prepared, Command)> {
validate_capabilities(package)?;
prepare_binary(&package.binary, root, super::EXECUTABLE_NAME)
}
pub(super) fn prepare_binary(
binary: &[u8],
root: &Path,
name: &str,
) -> Result<(Prepared, Command)> {
#[cfg(not(windows))]
let temporary = {
let mut builder = tempfile::Builder::new();
builder.prefix("leanctx-runtime-health-");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
builder.permissions(std::fs::Permissions::from_mode(0o700));
}
#[cfg(unix)]
{
builder.tempdir_in("/tmp")?
}
#[cfg(not(unix))]
{
builder.tempdir()?
}
};
#[cfg(windows)]
let temporary = {
let parent = crate::core::windows_private::Directory::create(
&std::env::temp_dir().join("leanctx-runtime-private"),
)?;
install::temporary_directory(parent.path(), "health-")?
};
let directory = temporary.path().canonicalize()?;
#[cfg(target_os = "linux")]
let executable_directory = install::execution_directory(root)?;
#[cfg(target_os = "linux")]
let executable = executable_directory.path().join(name);
#[cfg(not(target_os = "linux"))]
let _ = root;
#[cfg(not(target_os = "linux"))]
let executable = directory.join(name);
install::write_new(&executable, binary, true)?;
let command = runtime_command(&executable, &directory)?;
Ok((
Prepared {
workspace: temporary,
#[cfg(target_os = "linux")]
executable: executable_directory,
},
command,
))
}
fn runtime_command(executable: &Path, directory: &Path) -> Result<Command> {
let mut command = Command::new(executable);
command
.current_dir(directory)
.env_clear()
.env("HOME", directory)
.env("TMPDIR", directory);
#[cfg(target_os = "linux")]
{
let uid = unsafe { libc::geteuid() };
command.env("XDG_RUNTIME_DIR", format!("/run/user/{uid}"));
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt as _;
command
.env("TEMP", directory)
.env("TMP", directory)
.env("SystemRoot", windows_directory()?);
command.creation_flags(CREATE_NO_WINDOW);
}
Ok(command)
}
#[cfg(windows)]
const CREATE_NO_WINDOW: u32 = windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
#[cfg(windows)]
fn windows_directory() -> std::io::Result<std::ffi::OsString> {
use std::os::windows::ffi::OsStringExt as _;
use windows_sys::Win32::System::SystemInformation::GetSystemWindowsDirectoryW;
let mut buffer = vec![0_u16; 32_768];
let length =
unsafe { GetSystemWindowsDirectoryW(buffer.as_mut_ptr(), buffer.len() as u32) } as usize;
if length == 0 || length >= buffer.len() {
return Err(std::io::Error::last_os_error());
}
Ok(std::ffi::OsString::from_wide(&buffer[..length]))
}
pub(super) fn validate_capabilities(package: &VerifiedPackage) -> Result<()> {
if legacy_routing_version(package).is_ok()
|| complete_capability_set(package)
|| package.description["capabilities"]
== serde_json::json!([
{"id": "pro.runtime.adaptive_context", "version": "1.0.0"},
{"id": "pro.runtime.memory_curation", "version": "1.0.0"},
{"id": "pro.runtime.personal_protection", "version": "1.0.0"},
{"id": "pro.runtime.code_security", "version": "1.0.0"},
{"id": "pro.runtime.context_policy", "version": "1.0.0"},
{"id": "pro.runtime.context_policy", "version": "1.1.0"}
])
{
return Ok(());
}
Err(InstallError::Manifest)
}
pub(super) fn complete_capability_set(package: &VerifiedPackage) -> bool {
let base = [
serde_json::json!({"id": "pro.runtime.adaptive_context", "version": "1.0.0"}),
serde_json::json!({"id": "pro.runtime.memory_curation", "version": "1.0.0"}),
serde_json::json!({"id": "pro.runtime.personal_protection", "version": "1.0.0"}),
serde_json::json!({"id": "pro.runtime.code_security", "version": "1.0.0"}),
serde_json::json!({"id": "pro.runtime.context_policy", "version": "1.0.0"}),
serde_json::json!({"id": "pro.runtime.context_policy", "version": "1.1.0"}),
];
let hosted_index = serde_json::json!({"id": "pro.runtime.hosted_index", "version": "2.0.0"});
let Some(declared) = package.description["capabilities"].as_array() else {
return false;
};
if declared.len() < base.len() || declared[..base.len()] != base[..] {
return false;
}
let mut rest = &declared[base.len()..];
if rest.first() == Some(&hosted_index) {
rest = &rest[1..];
}
for optional in [
org_policy_verifier_capability(),
team_artifact_reader_capability(),
team_artifact_author_capability(),
compliance_frameworks_capability(),
dashboard_pro_capability(),
] {
if rest.first() == Some(&optional) {
rest = &rest[1..];
}
}
if rest.is_empty() {
return true;
}
let semantic = |version: &str| serde_json::json!({"id": "pro.runtime.semantic_detectors", "version": version});
[
vec![semantic("1.0.0")],
vec![semantic("1.1.0")],
vec![semantic("1.0.0"), semantic("1.1.0")],
]
.into_iter()
.any(|tail| rest == &tail[..])
}
fn compliance_frameworks_capability() -> serde_json::Value {
serde_json::json!({
"id": super::compliance_frameworks::CAPABILITY_ID,
"version": super::compliance_frameworks::CAPABILITY_VERSION
})
}
pub(super) fn supports_compliance_frameworks(package: &VerifiedPackage) -> bool {
complete_capability_set(package)
&& package.description["capabilities"]
.as_array()
.is_some_and(|declared| declared.contains(&compliance_frameworks_capability()))
}
fn dashboard_pro_capability() -> serde_json::Value {
serde_json::json!({
"id": super::dashboard_pro::CAPABILITY_ID,
"version": super::dashboard_pro::CAPABILITY_VERSION
})
}
fn team_artifact_reader_capability() -> serde_json::Value {
serde_json::json!({"id": "team.runtime.artifact_reader", "version": "1.0.0"})
}
fn team_artifact_author_capability() -> serde_json::Value {
serde_json::json!({"id": "team.runtime.artifact_author", "version": "1.0.0"})
}
fn org_policy_verifier_capability() -> serde_json::Value {
serde_json::json!({"id": "enterprise.runtime.org_policy_verifier", "version": "1.0.0"})
}
pub(super) fn supports_org_policy_verifier(package: &VerifiedPackage) -> bool {
complete_capability_set(package)
&& package.description["capabilities"]
.as_array()
.is_some_and(|declared| declared.contains(&org_policy_verifier_capability()))
}
pub(super) fn semantic_detectors_version(package: &VerifiedPackage) -> Option<&'static str> {
if validate_capabilities(package).is_err()
|| !package.semantic.as_ref().is_some_and(|semantic| {
matches!(
semantic.installation,
super::manifest::SemanticInstallation::Installed { .. }
)
})
{
return None;
}
let capabilities = package.description["capabilities"].as_array()?;
["1.1.0", "1.0.0"].into_iter().find(|version| {
capabilities.iter().any(|capability| {
capability
== &serde_json::json!({"id": "pro.runtime.semantic_detectors", "version": version})
})
})
}
fn legacy_routing_version(package: &VerifiedPackage) -> Result<&'static str> {
for version in ["1.0.0", "2.0.0"] {
if package.description["capabilities"]
== serde_json::json!([{"id": "pro.runtime.adaptive_routing", "version": version}])
{
return Ok(version);
}
}
if package.description["capabilities"]
== serde_json::json!([
{"id": "pro.runtime.adaptive_routing", "version": "2.0.0"},
{"id": "pro.runtime.adaptive_context", "version": "1.0.0"}
])
{
return Ok("2.0.0");
}
if package.description["capabilities"]
== serde_json::json!([
{"id": "pro.runtime.adaptive_routing", "version": "2.0.0"},
{"id": "pro.runtime.adaptive_context", "version": "1.0.0"},
{"id": "pro.runtime.memory_curation", "version": "1.0.0"}
])
{
return Ok("2.0.0");
}
if package.description["capabilities"]
== serde_json::json!([
{"id": "pro.runtime.adaptive_routing", "version": "2.0.0"},
{"id": "pro.runtime.adaptive_context", "version": "1.0.0"},
{"id": "pro.runtime.memory_curation", "version": "1.0.0"},
{"id": "pro.runtime.personal_protection", "version": "1.0.0"}
])
{
return Ok("2.0.0");
}
if package.description["capabilities"]
== serde_json::json!([
{"id": "pro.runtime.adaptive_routing", "version": "2.0.0"},
{"id": "pro.runtime.adaptive_context", "version": "1.0.0"},
{"id": "pro.runtime.memory_curation", "version": "1.0.0"},
{"id": "pro.runtime.personal_protection", "version": "1.0.0"},
{"id": "pro.runtime.code_security", "version": "1.0.0"}
])
{
return Ok("2.0.0");
}
if package.description["capabilities"]
== serde_json::json!([
{"id": "pro.runtime.adaptive_routing", "version": "2.0.0"},
{"id": "pro.runtime.adaptive_context", "version": "1.0.0"},
{"id": "pro.runtime.memory_curation", "version": "1.0.0"},
{"id": "pro.runtime.personal_protection", "version": "1.0.0"},
{"id": "pro.runtime.code_security", "version": "1.0.0"},
{"id": "pro.runtime.semantic_detectors", "version": "1.0.0"}
])
{
return Ok("2.0.0");
}
Err(InstallError::Manifest)
}
pub(super) fn supports_semantic_detectors(package: &VerifiedPackage) -> bool {
semantic_detectors_version(package).is_some()
}
pub(super) fn supports_code_security(package: &VerifiedPackage) -> bool {
validate_capabilities(package).is_ok()
&& package.description["capabilities"]
.as_array()
.is_some_and(|capabilities| {
capabilities.iter().any(|capability| capability ==
&serde_json::json!({"id": "pro.runtime.code_security", "version": "1.0.0"}))
})
}
pub(super) fn supports_protection(package: &VerifiedPackage) -> bool {
validate_capabilities(package).is_ok()
&& package.description["capabilities"]
.as_array()
.is_some_and(|capabilities| {
capabilities.iter().any(|capability| capability ==
&serde_json::json!({"id": "pro.runtime.personal_protection", "version": "1.0.0"}))
})
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(windows)]
#[test]
fn a_windows_runtime_gets_the_system_root_and_nothing_inherited() {
let directory = tempfile::tempdir().unwrap();
let command = runtime_command(
&directory.path().join("leanctx-cockpit.exe"),
directory.path(),
)
.unwrap();
let envs: std::collections::BTreeMap<String, Option<String>> = command
.get_envs()
.map(|(name, value)| {
(
name.to_string_lossy().to_ascii_uppercase(),
value.map(|value| value.to_string_lossy().into_owned()),
)
})
.collect();
let system_root = windows_directory().unwrap().to_string_lossy().into_owned();
assert_eq!(
envs.get("SYSTEMROOT"),
Some(&Some(system_root.clone())),
"{envs:?}"
);
assert!(std::path::Path::new(&system_root).join("System32").is_dir());
let names: Vec<&str> = envs.keys().map(String::as_str).collect();
assert_eq!(names, ["HOME", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR"]);
}
fn described(capabilities: &serde_json::Value) -> VerifiedPackage {
VerifiedPackage {
receipt: super::super::manifest::PackageReceipt {
manifest_sha256: "a".repeat(64),
artifact_sha256: "a".repeat(64),
binary_sha256: "a".repeat(64),
commit: "a".repeat(40),
version: "4.1.0".to_owned(),
license: "LicenseRef-Proprietary".to_owned(),
rollback_sha256: None,
staging_only: false,
},
binary: Vec::new(),
description: serde_json::json!({ "capabilities": capabilities }),
semantic: None,
}
}
#[test]
fn semantic_detectors_are_admitted_without_a_routing_capability() {
let semantic =
serde_json::json!({"id": "pro.runtime.semantic_detectors", "version": "1.0.0"});
let current = serde_json::json!([
{"id": "pro.runtime.adaptive_context", "version": "1.0.0"},
{"id": "pro.runtime.memory_curation", "version": "1.0.0"},
{"id": "pro.runtime.personal_protection", "version": "1.0.0"},
{"id": "pro.runtime.code_security", "version": "1.0.0"},
{"id": "pro.runtime.context_policy", "version": "1.0.0"},
{"id": "pro.runtime.context_policy", "version": "1.1.0"},
{"id": "pro.runtime.hosted_index", "version": "2.0.0"}
]);
let mut declaring = current.as_array().expect("array").clone();
declaring.push(semantic.clone());
let mut misplaced = declaring.clone();
misplaced.swap(0, 7);
let mut served = described(&serde_json::Value::Array(declaring));
assert!(validate_capabilities(&served).is_ok());
assert!(!supports_semantic_detectors(&served));
assert_eq!(install::semantic_state(&served).as_str(), "not_offered");
assert!(complete_capability_set(&served));
let listed = |name: &str| super::super::manifest::SemanticCompanion {
name: name.to_owned(),
sha256: "a".repeat(64),
bytes: 1,
};
served.semantic = Some(super::super::manifest::SemanticPackage {
companions: super::super::manifest::SemanticCompanions {
descriptor: listed("semantic-models.json"),
files: Vec::new(),
},
installation: super::super::manifest::SemanticInstallation::Installed {
directory: std::path::PathBuf::new(),
coverage: [true; 3],
},
});
assert_eq!(semantic_detectors_version(&served), Some("1.0.0"));
assert!(!supports_semantic_detectors(&described(¤t)));
for unknown in [
serde_json::json!([semantic]),
serde_json::Value::Array(misplaced),
] {
let package = described(&unknown);
assert!(validate_capabilities(&package).is_err());
assert!(!supports_semantic_detectors(&package));
}
#[cfg(any(unix, windows))]
{
let invocation: lean_ctx_protocol::EngineInvocationV1 =
serde_json::from_value(serde_json::json!({
"schema_version": 1, "invocation_id": "semantic-admission",
"engine": {"engine_id": "leanctx-intelligence", "engine_version": "4.1.0"},
"operation": {
"capability_id": "pro.runtime.semantic_detectors",
"capability_version": "1.0.0"
},
"input_ref": "projection:test",
"input_digest": format!("sha256:{}", "a".repeat(64)),
"source_refs": ["projection:test"],
"policy_admission": {"policy_ref": "policy:test", "decision": "admitted"}
}))
.expect("invocation");
let admit = super::super::session::admit_invocation;
assert!(matches!(
admit(&served, &invocation),
Err(InstallError::InvocationAdmission)
));
assert!(matches!(
admit(&described(¤t), &invocation),
Err(InstallError::InvocationAdmission)
));
}
}
}