difflore-cli 0.2.0

Your AI coding agent learned public code, not your team's private decisions. difflore turns past PR reviews into source-backed local rules.
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! JSON-file-based config helpers and the generic `install_json_config_at`
//! installer used by every Tier-3 (and several Tier-1) clients.

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

use serde_json::{Value, json};

use super::{Status, TargetOutcome, common::MCP_SERVER_ARG};

pub(super) fn load_json_object(path: &PathBuf) -> Result<serde_json::Map<String, Value>, String> {
    if !path.exists() {
        return Ok(serde_json::Map::new());
    }
    let raw =
        fs::read_to_string(path).map_err(|e| format!("failed to read {}: {e}", path.display()))?;
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Ok(serde_json::Map::new());
    }
    let v: Value = serde_json::from_str(trimmed)
        .map_err(|e| format!("invalid JSON in {}: {e}", path.display()))?;
    v.as_object()
        .cloned()
        .ok_or_else(|| format!("{} is not a JSON object at the top level", path.display()))
}

pub(super) fn write_json_object(
    path: &PathBuf,
    obj: &serde_json::Map<String, Value>,
) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
    }
    let pretty =
        serde_json::to_string_pretty(obj).map_err(|e| format!("failed to serialize JSON: {e}"))?;
    super::common::write_atomic(path, pretty.as_bytes())
        .map_err(|e| format!("failed to write {}: {e}", path.display()))?;
    Ok(())
}

/// Merge `{ <servers_key>: { difflore: { command, args: ["mcp-server"] } } }`
/// into a JSON object, preserving every other entry. `servers_key` is
/// "mcpServers" for most tools, "servers" for Copilot CLI. Returns true if a
/// prior `difflore` entry existed (an update rather than a first install).
fn merge_difflore_entry_with_key(
    config: &mut serde_json::Map<String, Value>,
    bin: &str,
    servers_key: &str,
    shape: McpEntryShape,
) -> bool {
    let servers = config
        .entry(servers_key.to_owned())
        .or_insert_with(|| Value::Object(serde_json::Map::new()));
    let Some(obj) = servers.as_object_mut() else {
        return false;
    };
    let new_entry = render_mcp_json_block(bin, shape);
    let existed = obj.contains_key("difflore");
    obj.insert("difflore".to_owned(), new_entry);
    existed
}

/// Inverse of [`merge_difflore_entry_with_key`]: remove the `difflore` entry
/// from the `servers_key` block, preserving every other server. Drops the
/// `servers_key` block entirely if it becomes empty so we don't leave an
/// orphaned `{}`. Returns true if a `difflore` entry was actually present.
fn remove_difflore_entry_with_key(
    config: &mut serde_json::Map<String, Value>,
    servers_key: &str,
) -> bool {
    let Some(servers) = config.get_mut(servers_key) else {
        return false;
    };
    let Some(obj) = servers.as_object_mut() else {
        return false;
    };
    let removed = obj.remove("difflore").is_some();
    if obj.is_empty() {
        config.remove(servers_key);
    }
    removed
}

/// Core of every JSON-file-based installer. Reads the file (empty map if
/// missing), merges in our entry under `servers_key`, writes it back.
/// Returns true if an existing `difflore` entry was overwritten.
pub(super) fn install_json_config_at(
    path: &PathBuf,
    bin: &str,
    servers_key: &str,
    shape: McpEntryShape,
    dry_run: bool,
) -> Result<bool, String> {
    let mut cfg = load_json_object(path)?;
    let existed = merge_difflore_entry_with_key(&mut cfg, bin, servers_key, shape);
    if !dry_run {
        write_json_object(path, &cfg)?;
    }
    Ok(existed)
}

/// Inverse of [`install_json_config_at`]. Reads the file, removes the
/// `difflore` entry under `servers_key`, writes it back (unless `dry_run`).
/// Returns true if a `difflore` entry was present (i.e. something was
/// removed). A missing file or missing entry is a no-op returning false.
pub(super) fn uninstall_json_config_at(
    path: &PathBuf,
    servers_key: &str,
    dry_run: bool,
) -> Result<bool, String> {
    if !path.exists() {
        return Ok(false);
    }
    let mut cfg = load_json_object(path)?;
    let removed = remove_difflore_entry_with_key(&mut cfg, servers_key);
    if removed && !dry_run {
        write_json_object(path, &cfg)?;
    }
    Ok(removed)
}

pub(super) fn finish_json_uninstall(
    name: &'static str,
    path: &PathBuf,
    servers_key: &str,
    dry_run: bool,
) -> TargetOutcome {
    match uninstall_json_config_at(path, servers_key, dry_run) {
        Ok(true) => TargetOutcome {
            name,
            status: Status::Removed,
            detail: if dry_run {
                format!(
                    "would remove difflore from: {}",
                    public_config_path(name, path)
                )
            } else {
                public_config_path(name, path)
            },
        },
        Ok(false) => TargetOutcome {
            name,
            status: Status::Skipped("no difflore entry to remove".into()),
            detail: String::new(),
        },
        Err(e) => TargetOutcome {
            name,
            status: Status::Error(e),
            detail: String::new(),
        },
    }
}

pub(super) fn finish_json_install(
    name: &'static str,
    path: &PathBuf,
    bin: &str,
    servers_key: &str,
    shape: McpEntryShape,
    dry_run: bool,
) -> TargetOutcome {
    match install_json_config_at(path, bin, servers_key, shape, dry_run) {
        Ok(existed) => TargetOutcome {
            name,
            status: if existed {
                Status::Updated
            } else {
                Status::Installed
            },
            detail: if dry_run {
                format!("would write: {}", public_config_path(name, path))
            } else {
                public_config_path(name, path)
            },
        },
        Err(e) => TargetOutcome {
            name,
            status: Status::Error(e),
            detail: String::new(),
        },
    }
}

// Rendered-block helpers

/// Wire shape of the `difflore` entry written under `<servers_key>.difflore`.
/// Most clients take the standard `{command, args}`; opencode nests
/// `{type:"local", command:[bin,"mcp-server"], enabled:true}` under its `mcp`
/// key (https://opencode.ai/docs/mcp-servers/).
#[derive(Clone, Copy)]
pub(super) enum McpEntryShape {
    Standard,
    Opencode,
}

/// The exact `difflore` MCP-server value object written under `servers_key`.
/// Single source of truth so the install merge and the manifest hash agree —
/// [`merge_difflore_entry_with_key`] calls this, it does not keep a parallel
/// literal.
pub(super) fn render_mcp_json_block(bin: &str, shape: McpEntryShape) -> Value {
    match shape {
        McpEntryShape::Standard => json!({
            "command": bin,
            "args": [MCP_SERVER_ARG],
        }),
        McpEntryShape::Opencode => json!({
            "type": "local",
            "command": [bin, MCP_SERVER_ARG],
            "enabled": true,
        }),
    }
}

/// Read the on-disk `difflore` entry under `servers_key`, if present, so
/// `agents update` can re-hash it and compare against the manifest. Returns
/// `None` when the file is missing/unreadable or has no difflore entry.
pub(super) fn extract_mcp_json_block(path: &PathBuf, servers_key: &str) -> Option<Value> {
    if !path.exists() {
        return None;
    }
    let obj = load_json_object(path).ok()?;
    obj.get(servers_key)?.as_object()?.get("difflore").cloned()
}

fn public_config_path(name: &str, path: &Path) -> String {
    match name {
        "Copilot CLI" => "~/.github/copilot/mcp.json".to_owned(),
        "Antigravity" => "~/.gemini/antigravity/mcp_config.json".to_owned(),
        "Crush" => "~/.config/crush/mcp.json".to_owned(),
        "Roo Code" => "./.roo/mcp.json".to_owned(),
        "Warp" => "~/.warp/mcp.json".to_owned(),
        "OpenCode" => "~/.config/opencode/opencode.json".to_owned(),
        _ => path.display().to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::super::test_util::{tmp_named_path, tmp_settings_path};
    use super::*;

    const BIN: &str = "/tmp/fake/difflore";

    fn read_json(path: &PathBuf) -> Value {
        let s = fs::read_to_string(path).expect("read config");
        serde_json::from_str(&s).expect("parse config")
    }

    // Tier-3 JSON installers — table-driven across all clients

    #[test]
    fn json_installers_write_difflore_under_servers_key() {
        // (relative path, servers_key) — one row per client surface.
        let cases: &[(&str, &str)] = &[
            (".github/copilot/mcp.json", "servers"),
            (".gemini/antigravity/mcp_config.json", "mcpServers"),
            (".config/crush/mcp.json", "mcpServers"),
            (".roo/mcp.json", "mcpServers"),
            (".warp/mcp.json", "mcpServers"),
        ];
        for (rel, key) in cases {
            let (tmp, _) = tmp_settings_path();
            let path = tmp.path().join(rel);
            let existed =
                install_json_config_at(&path, BIN, key, McpEntryShape::Standard, false).unwrap();
            assert!(!existed, "first install for {rel} must report new entry");
            let v = read_json(&path);
            let entry = v
                .get(*key)
                .and_then(|s| s.get("difflore"))
                .unwrap_or_else(|| panic!("{key}.difflore missing for {rel}"));
            assert_eq!(entry["command"], BIN, "wrong command for {rel}");
            assert_eq!(entry["args"], json!(["mcp-server"]), "wrong args for {rel}");
        }
    }

    #[test]
    fn opencode_shape_writes_type_command_array_and_enabled() {
        // opencode's mcp entry differs from the standard {command,args}: it is
        // {type:"local", command:[bin,"mcp-server"], enabled:true} under "mcp".
        let (_tmp, path) = tmp_named_path("opencode.json");
        let existed =
            install_json_config_at(&path, BIN, "mcp", McpEntryShape::Opencode, false).unwrap();
        assert!(!existed, "first opencode install must report a new entry");
        let v = read_json(&path);
        let entry = v
            .get("mcp")
            .and_then(|s| s.get("difflore"))
            .expect("mcp.difflore missing");
        assert_eq!(entry["type"], "local");
        assert_eq!(entry["command"], json!([BIN, "mcp-server"]));
        assert_eq!(entry["enabled"], json!(true));
        assert!(
            entry.get("args").is_none(),
            "opencode entry must not use args"
        );

        // Uninstall is shape-agnostic: removes mcp.difflore, drops empty mcp.
        let removed = uninstall_json_config_at(&path, "mcp", false).unwrap();
        assert!(removed);
        assert_eq!(read_json(&path), json!({}));
    }

    // Merge-preservation: reinstall, other entries left alone

    #[test]
    fn reinstall_reports_updated_and_preserves_other_entries() {
        let (_tmp, path) = tmp_named_path("mcp.json");
        // Seed with an unrelated entry.
        fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
        fs::write(
            &path,
            r#"{ "mcpServers": { "other": { "command": "x", "args": [] } } }"#,
        )
        .unwrap();

        let existed =
            install_json_config_at(&path, BIN, "mcpServers", McpEntryShape::Standard, false)
                .unwrap();
        assert!(!existed, "difflore wasn't there yet");
        let existed2 =
            install_json_config_at(&path, BIN, "mcpServers", McpEntryShape::Standard, false)
                .unwrap();
        assert!(existed2, "second install must report update");

        let v = read_json(&path);
        assert_eq!(v["mcpServers"]["other"]["command"], "x");
        assert_eq!(v["mcpServers"]["difflore"]["command"], BIN);
    }

    // Uninstall round-trips (inverse of the merge)

    #[test]
    fn uninstall_removes_difflore_and_preserves_other_entries() {
        let (_tmp, path) = tmp_named_path("mcp.json");
        fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
        fs::write(
            &path,
            r#"{ "mcpServers": { "other": { "command": "x", "args": [] } } }"#,
        )
        .unwrap();

        // Install, then uninstall: the difflore entry should be gone but the
        // unrelated server must survive untouched.
        install_json_config_at(&path, BIN, "mcpServers", McpEntryShape::Standard, false).unwrap();
        let removed = uninstall_json_config_at(&path, "mcpServers", false).unwrap();
        assert!(removed, "uninstall must report it removed a difflore entry");

        let v = read_json(&path);
        assert!(
            v["mcpServers"].get("difflore").is_none(),
            "difflore entry must be gone: {v}"
        );
        assert_eq!(
            v["mcpServers"]["other"]["command"], "x",
            "unrelated server clobbered: {v}"
        );
    }

    #[test]
    fn uninstall_round_trip_on_fresh_file_leaves_empty_object() {
        // A file that only ever held difflore should end up `{}` (the
        // mcpServers block is dropped once empty, not left as `{}`).
        for (rel, key) in &[
            (".github/copilot/mcp.json", "servers"),
            (".roo/mcp.json", "mcpServers"),
        ] {
            let (tmp, _) = tmp_settings_path();
            let path = tmp.path().join(rel);
            install_json_config_at(&path, BIN, key, McpEntryShape::Standard, false).unwrap();
            let removed = uninstall_json_config_at(&path, key, false).unwrap();
            assert!(
                removed,
                "fresh install then uninstall must remove for {rel}"
            );
            let v = read_json(&path);
            assert_eq!(v, json!({}), "{rel}: leftover keys after uninstall: {v}");
        }
    }

    #[test]
    fn uninstall_is_noop_when_no_difflore_entry() {
        let (_tmp, path) = tmp_named_path("mcp.json");
        fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
        fs::write(
            &path,
            r#"{ "mcpServers": { "other": { "command": "x" } } }"#,
        )
        .unwrap();

        let removed = uninstall_json_config_at(&path, "mcpServers", false).unwrap();
        assert!(!removed, "no difflore entry → nothing removed");
        let v = read_json(&path);
        assert_eq!(v["mcpServers"]["other"]["command"], "x");
    }

    #[test]
    fn uninstall_missing_file_is_noop() {
        let (_tmp, path) = tmp_named_path("absent.json");
        let removed = uninstall_json_config_at(&path, "mcpServers", false).unwrap();
        assert!(!removed);
        assert!(!path.exists(), "uninstall must not create the file");
    }

    #[test]
    fn uninstall_dry_run_does_not_write() {
        let (_tmp, path) = tmp_named_path("mcp.json");
        fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
        install_json_config_at(&path, BIN, "mcpServers", McpEntryShape::Standard, false).unwrap();
        let before = fs::read_to_string(&path).unwrap();

        let removed = uninstall_json_config_at(&path, "mcpServers", true).unwrap();
        assert!(removed, "dry-run still reports what it would remove");
        let after = fs::read_to_string(&path).unwrap();
        assert_eq!(before, after, "dry-run must not touch the file");
    }
}