Skip to main content

lean_ctx/core/
opencode_config.rs

1//! Single source of truth for locating OpenCode's global config file.
2//!
3//! OpenCode accepts both `opencode.json` and `opencode.jsonc`. lean-ctx used to
4//! hardcode `opencode.json` in every writer, so a user whose config was
5//! `opencode.jsonc` got a *second*, competing global config containing nothing
6//! but the lean-ctx MCP entry and shadow-mode denies — their providers, models
7//! and foreign MCP servers appeared to vanish (#1585).
8//!
9//! Resolution rule, applied by `init`, `setup`, doctor, the shadow-mode
10//! permission updater and uninstall alike:
11//!
12//! 1. exactly one of the two exists → that file
13//! 2. both exist → `opencode.json` (OpenCode's own default name), reported via
14//!    [`Resolved::ambiguous`] so callers can warn instead of silently picking
15//! 3. neither exists → `opencode.json`, to be created
16
17use std::path::{Path, PathBuf};
18
19/// Where the OpenCode config lives, plus whether the choice was ambiguous.
20pub struct Resolved {
21    /// The file to read and write.
22    pub path: PathBuf,
23    /// Both `opencode.json` and `opencode.jsonc` exist on disk.
24    pub ambiguous: bool,
25}
26
27impl Resolved {
28    /// Display form for CLI output, e.g. `~/.config/opencode/opencode.jsonc`.
29    pub fn display(&self, home: &Path) -> String {
30        self.path.strip_prefix(home).map_or_else(
31            |_| self.path.display().to_string(),
32            |rest| format!("~/{}", rest.display()),
33        )
34    }
35}
36
37/// Resolve the config inside an OpenCode config directory.
38pub fn resolve_in_dir(dir: &Path) -> Resolved {
39    let json = dir.join("opencode.json");
40    let jsonc = dir.join("opencode.jsonc");
41    match (json.exists(), jsonc.exists()) {
42        (false, true) => Resolved {
43            path: jsonc,
44            ambiguous: false,
45        },
46        (true, true) => Resolved {
47            path: json,
48            ambiguous: true,
49        },
50        _ => Resolved {
51            path: json,
52            ambiguous: false,
53        },
54    }
55}
56
57/// Resolve OpenCode's global config directory.
58///
59/// `~/.config/opencode` on every platform — OpenCode uses the XDG layout on
60/// Windows too, and so does the rest of lean-ctx: the rules file, skills,
61/// detection and uninstall all address `home/.config/opencode`. Special-casing
62/// `%APPDATA%` here would point the MCP writer and doctor at a directory the
63/// uninstaller never visits and the rules writer never fills — and would make
64/// every caller that passes a test home write to the real user profile.
65pub fn config_dir(home: &Path) -> PathBuf {
66    home.join(".config/opencode")
67}
68
69/// Resolve the global OpenCode config for a given home directory.
70pub fn resolve(home: &Path) -> Resolved {
71    resolve_in_dir(&config_dir(home))
72}
73
74/// OpenCode 2.x per-server MCP key: "Expose this server's tools through Code
75/// Mode. Defaults to true." Under Code Mode the model sees only part of a
76/// server's tools, as functions inside `execute`, so `ctx_read` and
77/// `ctx_search` drop out of view (#2295). lean-ctx sets it to `false`.
78///
79/// OpenCode 1.x validates MCP entries strictly: with this key the whole config
80/// is rejected ("Configuration is invalid … Invalid input mcp.lean-ctx",
81/// observed with 1.2.15). The key is therefore added only when the installed
82/// OpenCode is known to be 2.x or newer; see [`code_mode_key_supported`].
83pub const CODE_MODE_KEY: &str = "codemode";
84
85/// First OpenCode major release that knows [`CODE_MODE_KEY`].
86const CODE_MODE_MIN_MAJOR: u64 = 2;
87
88/// How long `opencode --version` may take before the version counts as unknown.
89const VERSION_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
90
91/// Major version from `opencode --version` output such as `2.2.1` or `v1.2.15`.
92pub fn major_version(output: &str) -> Option<u64> {
93    output.split_whitespace().find_map(|word| {
94        let word = word.strip_prefix('v').unwrap_or(word);
95        let (major, _) = word.split_once('.')?;
96        major.parse().ok()
97    })
98}
99
100/// Whether an OpenCode with this `--version` output accepts [`CODE_MODE_KEY`].
101/// An unknown version does not: a key OpenCode 1.x rejects breaks the whole
102/// config, while a missing one only leaves Code Mode on.
103pub fn code_mode_key_supported_by(version_output: Option<&str>) -> bool {
104    version_output
105        .and_then(major_version)
106        .is_some_and(|major| major >= CODE_MODE_MIN_MAJOR)
107}
108
109/// `opencode --version` of the installed OpenCode: the one on `PATH`, else the
110/// official installer's `~/.opencode/bin/opencode`. Probed once per process.
111fn installed_version(home: &Path) -> Option<String> {
112    static VERSION: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
113    VERSION
114        .get_or_init(|| {
115            let installer_bin = home.join(".opencode").join("bin").join("opencode");
116            [PathBuf::from("opencode"), installer_bin]
117                .into_iter()
118                .find_map(|bin| {
119                    let mut cmd = std::process::Command::new(bin);
120                    cmd.arg("--version");
121                    let out = crate::ipc::process::run_with_timeout(cmd, VERSION_PROBE_TIMEOUT)?;
122                    let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
123                    (out.status.success() && major_version(&text).is_some()).then_some(text)
124                })
125        })
126        .clone()
127}
128
129/// Whether the installed OpenCode accepts [`CODE_MODE_KEY`] (2.x or newer).
130pub fn code_mode_key_supported(home: &Path) -> bool {
131    code_mode_key_supported_by(installed_version(home).as_deref())
132}
133
134/// Put `codemode: false` on a lean-ctx MCP server entry that has no
135/// `codemode` value yet. A value the user set is kept. Returns whether the
136/// entry changed.
137pub fn disable_code_mode(entry: &mut serde_json::Value) -> bool {
138    let Some(obj) = entry.as_object_mut() else {
139        return false;
140    };
141    if obj.contains_key(CODE_MODE_KEY) {
142        return false;
143    }
144    obj.insert(CODE_MODE_KEY.to_string(), serde_json::Value::Bool(false));
145    true
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    fn touch(p: &Path) {
153        std::fs::write(p, "{}").unwrap();
154    }
155
156    #[test]
157    fn picks_the_only_file_that_exists() {
158        let dir = tempfile::tempdir().unwrap();
159        touch(&dir.path().join("opencode.jsonc"));
160        let r = resolve_in_dir(dir.path());
161        assert_eq!(r.path.file_name().unwrap(), "opencode.jsonc");
162        assert!(!r.ambiguous);
163    }
164
165    #[test]
166    fn plain_json_is_used_when_it_is_the_one_present() {
167        let dir = tempfile::tempdir().unwrap();
168        touch(&dir.path().join("opencode.json"));
169        let r = resolve_in_dir(dir.path());
170        assert_eq!(r.path.file_name().unwrap(), "opencode.json");
171        assert!(!r.ambiguous);
172    }
173
174    #[test]
175    fn both_present_prefers_json_and_reports_ambiguity() {
176        let dir = tempfile::tempdir().unwrap();
177        touch(&dir.path().join("opencode.json"));
178        touch(&dir.path().join("opencode.jsonc"));
179        let r = resolve_in_dir(dir.path());
180        assert_eq!(r.path.file_name().unwrap(), "opencode.json");
181        assert!(
182            r.ambiguous,
183            "callers must be able to warn instead of silently choosing"
184        );
185    }
186
187    #[test]
188    fn neither_present_targets_json_for_creation() {
189        let dir = tempfile::tempdir().unwrap();
190        let r = resolve_in_dir(dir.path());
191        assert_eq!(r.path.file_name().unwrap(), "opencode.json");
192        assert!(!r.ambiguous);
193    }
194
195    #[test]
196    fn config_dir_stays_under_the_given_home_on_every_platform() {
197        // Windows CI caught this the hard way: a `%APPDATA%` branch here made
198        // the config resolver ignore its `home` argument, so five tests shared
199        // the runner's real profile and contaminated each other — and in
200        // production it would have split the config away from the rules file,
201        // detection and uninstall, which all use `home/.config/opencode`.
202        let home = Path::new("/tmp/leanctx-home-probe");
203        assert_eq!(config_dir(home), home.join(".config/opencode"));
204        assert!(config_dir(home).starts_with(home));
205    }
206
207    #[test]
208    fn code_mode_key_only_for_opencode_2_and_newer() {
209        assert!(!code_mode_key_supported_by(Some("1.2.15")));
210        assert!(!code_mode_key_supported_by(Some("v1.14.0")));
211        assert!(code_mode_key_supported_by(Some("2.2.1")));
212        assert!(code_mode_key_supported_by(Some("opencode v3.0.0")));
213        assert!(
214            !code_mode_key_supported_by(None),
215            "unknown version must not get a key OpenCode 1.x rejects"
216        );
217        assert!(!code_mode_key_supported_by(Some("garbage")));
218    }
219
220    #[test]
221    fn disable_code_mode_adds_false_but_keeps_a_user_value() {
222        let mut entry = serde_json::json!({"type": "local", "command": ["lean-ctx"]});
223        assert!(disable_code_mode(&mut entry));
224        assert_eq!(entry[CODE_MODE_KEY], serde_json::json!(false));
225        assert!(!disable_code_mode(&mut entry), "idempotent");
226
227        let mut user = serde_json::json!({"type": "local", "codemode": true});
228        assert!(!disable_code_mode(&mut user));
229        assert_eq!(user[CODE_MODE_KEY], serde_json::json!(true));
230    }
231
232    #[test]
233    fn jsonc_is_never_shadowed_by_a_file_we_would_create() {
234        // The #1585 regression: a user with only opencode.jsonc must not end up
235        // with lean-ctx writing a competing opencode.json.
236        let dir = tempfile::tempdir().unwrap();
237        touch(&dir.path().join("opencode.jsonc"));
238        assert_eq!(
239            resolve_in_dir(dir.path()).path,
240            dir.path().join("opencode.jsonc")
241        );
242    }
243}