1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//! 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")
);
}
}