lean-ctx-engine 3.12.13

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
//! Single source of truth for locating OpenCode's global config file.
//!
//! OpenCode accepts both `opencode.json` and `opencode.jsonc`. lean-ctx used to
//! hardcode `opencode.json` in every writer, so a user whose config was
//! `opencode.jsonc` got a *second*, competing global config containing nothing
//! but the lean-ctx MCP entry and shadow-mode denies — their providers, models
//! and foreign MCP servers appeared to vanish (#1585).
//!
//! Resolution rule, applied by `init`, `setup`, doctor, the shadow-mode
//! permission updater and uninstall alike:
//!
//! 1. exactly one of the two exists → that file
//! 2. both exist → `opencode.json` (OpenCode's own default name), reported via
//!    [`Resolved::ambiguous`] so callers can warn instead of silently picking
//! 3. neither exists → `opencode.json`, to be created

use std::path::{Path, PathBuf};

/// Where the OpenCode config lives, plus whether the choice was ambiguous.
pub struct Resolved {
    /// The file to read and write.
    pub path: PathBuf,
    /// Both `opencode.json` and `opencode.jsonc` exist on disk.
    pub ambiguous: bool,
}

impl Resolved {
    /// Display form for CLI output, e.g. `~/.config/opencode/opencode.jsonc`.
    pub fn display(&self, home: &Path) -> String {
        self.path.strip_prefix(home).map_or_else(
            |_| self.path.display().to_string(),
            |rest| format!("~/{}", rest.display()),
        )
    }
}

/// Resolve the config inside an OpenCode config directory.
pub fn resolve_in_dir(dir: &Path) -> Resolved {
    let json = dir.join("opencode.json");
    let jsonc = dir.join("opencode.jsonc");
    match (json.exists(), jsonc.exists()) {
        (false, true) => Resolved {
            path: jsonc,
            ambiguous: false,
        },
        (true, true) => Resolved {
            path: json,
            ambiguous: true,
        },
        _ => Resolved {
            path: json,
            ambiguous: false,
        },
    }
}

/// Resolve OpenCode's global config directory.
///
/// `~/.config/opencode` on every platform — OpenCode uses the XDG layout on
/// Windows too, and so does the rest of lean-ctx: the rules file, skills,
/// detection and uninstall all address `home/.config/opencode`. Special-casing
/// `%APPDATA%` here would point the MCP writer and doctor at a directory the
/// uninstaller never visits and the rules writer never fills — and would make
/// every caller that passes a test home write to the real user profile.
pub fn config_dir(home: &Path) -> PathBuf {
    home.join(".config/opencode")
}

/// Resolve the global OpenCode config for a given home directory.
pub fn resolve(home: &Path) -> Resolved {
    resolve_in_dir(&config_dir(home))
}

/// OpenCode 2.x per-server MCP key: "Expose this server's tools through Code
/// Mode. Defaults to true." Under Code Mode the model sees only part of a
/// server's tools, as functions inside `execute`, so `ctx_read` and
/// `ctx_search` drop out of view (#2295). lean-ctx sets it to `false`.
///
/// OpenCode 1.x validates MCP entries strictly: with this key the whole config
/// is rejected ("Configuration is invalid … Invalid input mcp.lean-ctx",
/// observed with 1.2.15). The key is therefore added only when the installed
/// OpenCode is known to be 2.x or newer; see [`code_mode_key_supported`].
pub const CODE_MODE_KEY: &str = "codemode";

/// First OpenCode major release that knows [`CODE_MODE_KEY`].
const CODE_MODE_MIN_MAJOR: u64 = 2;

/// How long `opencode --version` may take before the version counts as unknown.
const VERSION_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// Major version from `opencode --version` output such as `2.2.1` or `v1.2.15`.
pub fn major_version(output: &str) -> Option<u64> {
    output.split_whitespace().find_map(|word| {
        let word = word.strip_prefix('v').unwrap_or(word);
        let (major, _) = word.split_once('.')?;
        major.parse().ok()
    })
}

/// Whether an OpenCode with this `--version` output accepts [`CODE_MODE_KEY`].
/// An unknown version does not: a key OpenCode 1.x rejects breaks the whole
/// config, while a missing one only leaves Code Mode on.
pub fn code_mode_key_supported_by(version_output: Option<&str>) -> bool {
    version_output
        .and_then(major_version)
        .is_some_and(|major| major >= CODE_MODE_MIN_MAJOR)
}

/// `opencode --version` of the installed OpenCode: the one on `PATH`, else the
/// official installer's `~/.opencode/bin/opencode`. Probed once per process.
fn installed_version(home: &Path) -> Option<String> {
    static VERSION: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
    VERSION
        .get_or_init(|| {
            let installer_bin = home.join(".opencode").join("bin").join("opencode");
            [PathBuf::from("opencode"), installer_bin]
                .into_iter()
                .find_map(|bin| {
                    let mut cmd = std::process::Command::new(bin);
                    cmd.arg("--version");
                    let out = crate::ipc::process::run_with_timeout(cmd, VERSION_PROBE_TIMEOUT)?;
                    let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
                    (out.status.success() && major_version(&text).is_some()).then_some(text)
                })
        })
        .clone()
}

/// Whether the installed OpenCode accepts [`CODE_MODE_KEY`] (2.x or newer).
pub fn code_mode_key_supported(home: &Path) -> bool {
    code_mode_key_supported_by(installed_version(home).as_deref())
}

/// Put `codemode: false` on a lean-ctx MCP server entry that has no
/// `codemode` value yet. A value the user set is kept. Returns whether the
/// entry changed.
pub fn disable_code_mode(entry: &mut serde_json::Value) -> bool {
    let Some(obj) = entry.as_object_mut() else {
        return false;
    };
    if obj.contains_key(CODE_MODE_KEY) {
        return false;
    }
    obj.insert(CODE_MODE_KEY.to_string(), serde_json::Value::Bool(false));
    true
}

#[cfg(test)]
mod tests {
    use super::*;

    fn touch(p: &Path) {
        std::fs::write(p, "{}").unwrap();
    }

    #[test]
    fn picks_the_only_file_that_exists() {
        let dir = tempfile::tempdir().unwrap();
        touch(&dir.path().join("opencode.jsonc"));
        let r = resolve_in_dir(dir.path());
        assert_eq!(r.path.file_name().unwrap(), "opencode.jsonc");
        assert!(!r.ambiguous);
    }

    #[test]
    fn plain_json_is_used_when_it_is_the_one_present() {
        let dir = tempfile::tempdir().unwrap();
        touch(&dir.path().join("opencode.json"));
        let r = resolve_in_dir(dir.path());
        assert_eq!(r.path.file_name().unwrap(), "opencode.json");
        assert!(!r.ambiguous);
    }

    #[test]
    fn both_present_prefers_json_and_reports_ambiguity() {
        let dir = tempfile::tempdir().unwrap();
        touch(&dir.path().join("opencode.json"));
        touch(&dir.path().join("opencode.jsonc"));
        let r = resolve_in_dir(dir.path());
        assert_eq!(r.path.file_name().unwrap(), "opencode.json");
        assert!(
            r.ambiguous,
            "callers must be able to warn instead of silently choosing"
        );
    }

    #[test]
    fn neither_present_targets_json_for_creation() {
        let dir = tempfile::tempdir().unwrap();
        let r = resolve_in_dir(dir.path());
        assert_eq!(r.path.file_name().unwrap(), "opencode.json");
        assert!(!r.ambiguous);
    }

    #[test]
    fn config_dir_stays_under_the_given_home_on_every_platform() {
        // Windows CI caught this the hard way: a `%APPDATA%` branch here made
        // the config resolver ignore its `home` argument, so five tests shared
        // the runner's real profile and contaminated each other — and in
        // production it would have split the config away from the rules file,
        // detection and uninstall, which all use `home/.config/opencode`.
        let home = Path::new("/tmp/leanctx-home-probe");
        assert_eq!(config_dir(home), home.join(".config/opencode"));
        assert!(config_dir(home).starts_with(home));
    }

    #[test]
    fn code_mode_key_only_for_opencode_2_and_newer() {
        assert!(!code_mode_key_supported_by(Some("1.2.15")));
        assert!(!code_mode_key_supported_by(Some("v1.14.0")));
        assert!(code_mode_key_supported_by(Some("2.2.1")));
        assert!(code_mode_key_supported_by(Some("opencode v3.0.0")));
        assert!(
            !code_mode_key_supported_by(None),
            "unknown version must not get a key OpenCode 1.x rejects"
        );
        assert!(!code_mode_key_supported_by(Some("garbage")));
    }

    #[test]
    fn disable_code_mode_adds_false_but_keeps_a_user_value() {
        let mut entry = serde_json::json!({"type": "local", "command": ["lean-ctx"]});
        assert!(disable_code_mode(&mut entry));
        assert_eq!(entry[CODE_MODE_KEY], serde_json::json!(false));
        assert!(!disable_code_mode(&mut entry), "idempotent");

        let mut user = serde_json::json!({"type": "local", "codemode": true});
        assert!(!disable_code_mode(&mut user));
        assert_eq!(user[CODE_MODE_KEY], serde_json::json!(true));
    }

    #[test]
    fn jsonc_is_never_shadowed_by_a_file_we_would_create() {
        // The #1585 regression: a user with only opencode.jsonc must not end up
        // with lean-ctx writing a competing opencode.json.
        let dir = tempfile::tempdir().unwrap();
        touch(&dir.path().join("opencode.jsonc"));
        assert_eq!(
            resolve_in_dir(dir.path()).path,
            dir.path().join("opencode.jsonc")
        );
    }
}