lean-ctx-engine 3.12.11

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! gh-2283: the hand-written schema is the source of `config-keys.md`,
//! `config set`, `config validate` and the comments of `config init --full`.
//! It had drifted from the code: `response_verbosity` documented variants the
//! deserializer rejects (one documented value made the whole config fall back
//! to defaults), and several `default` entries were not `Config::default()`.
//! These tests compare every schema default with the serialized
//! `Config::default()` and feed every schema enum value through the loader.

use super::{ConfigSchema, KeySchema};
use crate::core::config::Config;
use serde_json::Value;

/// Keys whose schema default deliberately differs from the serialized
/// `Config::default()` value. Each entry says why; keep the list short.
const COMPUTED_DEFAULTS: &[(&str, &str)] = &[
    // The built-in list has ~230 entries; the schema says "unset = built-in
    // list" (null) instead of printing it into every doc and config comment.
    (
        "shell_allowlist",
        "built-in list, described in the key text",
    ),
];

/// `Option` fields that stay `None` (unset) in `Config::default()`; the
/// schema documents the effective value the code resolves at the use site
/// when the key is unset. A non-null schema default is expected for these.
const UNSET_RESOLVED_AT_USE: &[&str] = &[
    "bypass_hints",
    "cache_policy",
    "hook_mode",
    "persona",
    "prompt_reinject",
    "rules_injection",
    "rules_scope",
    "shell_hook_mode",
    "shell_security",
    "proxy.allow_custom_upstream",
    "proxy.allow_insecure_http_upstream",
    "proxy.cache_align_relocate",
    "proxy.cache_aligner",
    "proxy.cache_breakpoint",
    "proxy.cache_policy",
    "proxy.cache_ttl_loop",
    "proxy.ccr_inband",
    "proxy.codex_chatgpt_proxy",
    "proxy.cold_prefix_repack",
    "proxy.compress_protect",
    "proxy.compression_holdout",
    "proxy.counterfactual_metering",
    "proxy.effort",
    "proxy.history_mode",
    "proxy.live_compress",
    "proxy.live_compress_exclude",
    "proxy.long_session_elide",
    "proxy.meter_openai_usage",
    "proxy.output_holdout",
    "proxy.prose_ranker",
    "proxy.verbosity_steer",
];

/// Legacy keys the loader migrates into `compression_level` before
/// deserialising: their values load, but do not survive as the same key.
const MIGRATED_ON_LOAD: &[&str] = &["output_density", "terse_agent"];

fn schema_entries(schema: &ConfigSchema) -> Vec<(String, Vec<String>, &KeySchema)> {
    let mut out = Vec::new();
    for (section, s) in &schema.sections {
        for (name, ks) in &s.keys {
            let mut path: Vec<String> = if section == "root" {
                Vec::new()
            } else {
                section.split('.').map(str::to_string).collect()
            };
            path.push(name.clone());
            out.push((path.join("."), path, ks));
        }
    }
    out
}

fn lookup<'a>(root: &'a Value, path: &[String]) -> Option<&'a Value> {
    path.iter().try_fold(root, |v, seg| v.get(seg))
}

fn same(schema: &Value, actual: &Value) -> bool {
    match (schema, actual) {
        (Value::Number(a), Value::Number(b)) => {
            let (a, b) = (a.as_f64().unwrap_or(0.0), b.as_f64().unwrap_or(0.0));
            (a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0)
        }
        // `Option<String>` fields: the schema may show "" for an unset value.
        (Value::String(s), Value::Null) => s.is_empty(),
        (Value::Array(a), Value::Array(b)) => {
            a.len() == b.len() && a.iter().zip(b).all(|(x, y)| same(x, y))
        }
        _ => schema == actual,
    }
}

fn toml_document(path: &[String], value: &str) -> String {
    let (key, sections) = path.split_last().expect("non-empty key path");
    let value = toml::Value::String(value.to_string());
    if sections.is_empty() {
        format!("{key} = {value}\n")
    } else {
        format!("[{}]\n{key} = {value}\n", sections.join("."))
    }
}

#[test]
fn schema_defaults_match_config_default() {
    let schema = ConfigSchema::generate();
    let defaults = serde_json::to_value(Config::default()).expect("Config serialises");
    let mut drift = Vec::new();
    for (dotted, path, ks) in schema_entries(&schema) {
        if COMPUTED_DEFAULTS.iter().any(|(k, _)| *k == dotted) {
            continue;
        }
        // Keys the struct does not serialise (skipped `None`, legacy or
        // section-only keys) have no code default to compare with.
        let Some(actual) = lookup(&defaults, &path) else {
            continue;
        };
        if actual.is_null() && UNSET_RESOLVED_AT_USE.contains(&dotted.as_str()) {
            continue;
        }
        if !same(&ks.default, actual) {
            drift.push(format!(
                "{dotted}: schema {} vs Config::default() {actual}",
                ks.default
            ));
        }
    }
    assert!(
        drift.is_empty(),
        "schema defaults drifted from Config::default() (gh-2283):\n  {}",
        drift.join("\n  ")
    );
}

#[test]
fn schema_enum_values_load_and_round_trip() {
    let schema = ConfigSchema::generate();
    let mut broken = Vec::new();
    for (dotted, path, ks) in schema_entries(&schema) {
        let Some(values) = &ks.values else { continue };
        // An empty default means "unset" (e.g. tool_profile).
        if let Value::String(default) = &ks.default
            && !default.is_empty()
            && !values.contains(default)
        {
            broken.push(format!("{dotted}: default {default:?} not in {values:?}"));
        }
        for value in values {
            let raw = toml_document(&path, value);
            match super::super::loader::parse_config_with_profile(&raw, None) {
                Err(e) => broken.push(format!("{dotted} = {value:?}: loader rejects it: {e}")),
                Ok(cfg) => {
                    let loaded = serde_json::to_value(&cfg).expect("Config serialises");
                    if !MIGRATED_ON_LOAD.contains(&dotted.as_str())
                        && let Some(actual) = lookup(&loaded, &path)
                        && actual != &Value::String(value.clone())
                    {
                        broken.push(format!("{dotted} = {value:?}: loads as {actual}"));
                    }
                }
            }
        }
    }
    assert!(
        broken.is_empty(),
        "schema enum values the loader cannot read (gh-2283):\n  {}",
        broken.join("\n  ")
    );
}

/// Configs written from the 3.12.9 reference must keep loading.
#[test]
fn legacy_response_verbosity_values_still_load() {
    use crate::core::config::ResponseVerbosity;
    for (raw, expected) in [
        ("normal", ResponseVerbosity::Full),
        ("compact", ResponseVerbosity::Full),
        ("minimal", ResponseVerbosity::HeadersOnly),
        ("full", ResponseVerbosity::Full),
        ("headers_only", ResponseVerbosity::HeadersOnly),
    ] {
        let doc = format!("response_verbosity = \"{raw}\"\ntheme = \"neon\"\n");
        let cfg = super::super::loader::parse_config_with_profile(&doc, None)
            .unwrap_or_else(|e| panic!("response_verbosity = {raw:?} must load: {e}"));
        assert_eq!(cfg.response_verbosity, expected, "{raw}");
        assert!(super::super::check_config_document(&doc).is_ok());
    }
    assert!(
        super::super::check_config_document("response_verbosity = \"loud\"\n").is_err(),
        "validate must refuse a value the loader cannot read"
    );
}