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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! `difflore doctor --fix` diagnostic repair pass.
//!
//! Strict, narrow scope — only the mechanically safe subset:
//!
//!   1. Missing `~/.difflore/` directory — create it.
//!   2. MCP install drift — re-run the MCP installer for detected
//!      agents that are not yet wired to DiffLore, conflict, or have
//!      stale canonical record / hook-surface drift.
//!   3. Stale `difflore-hook` shim — diagnose only. We never invoke
//!      `cargo install` on the user's behalf; that's an explicit
//!      decision they make. We just print a clear, copy-pasteable
//!      command when the shim is missing or older than the running
//!      `difflore` binary.
//!
//! Everything else doctor surfaces (cloud login, provider/API keys,
//! BFS env vars, DB migrations) is left to the user — see the
//! `decline_*` helpers for the messaging.

use std::path::PathBuf;
use std::time::{Duration, SystemTime};

use crate::installer;
use crate::style;

const HOOK_SHIM_STALE_GRACE: Duration = Duration::from_secs(5);

/// Cheap pre-check: is there at least one repair the diagnostic pass
/// could apply right now? Used to gate the "Run `difflore doctor
/// --fix`" nudge on the diagnostic surface so a healthy install
/// never sees it.
pub(crate) fn has_fixable() -> bool {
    if !difflore_dir_exists() {
        return true;
    }
    if !installer::detect_install_repair_targets().is_empty() {
        return true;
    }
    matches!(
        check_hook_shim(),
        HookShimState::Missing
            | HookShimState::Stale { .. }
            | HookShimState::UnreadableMtime { .. }
    )
}

/// Run the fix pass. Prints a short banner, then walks the three
/// auto-repairable categories. Each step prints a single result line via
/// `style::ok` / `style::warn`. Closes with the canonical next-step
/// bridge so the user knows how to verify.
pub(crate) fn run_fix_pass() {
    let actions = collect_actions();
    println!();
    if actions.is_empty() {
        println!(
            "  {} {}",
            style::emerald(style::sym::OK),
            style::ok("Nothing to repair — diagnostic surface is clean."),
        );
        decline_notices();
        return;
    }
    println!(
        "  {} {} {} {}",
        style::emerald(style::sym::TIP),
        style::pewter("Repairing"),
        style::ident(&actions.len().to_string()),
        style::pewter(if actions.len() == 1 {
            "item…"
        } else {
            "items…"
        }),
    );

    for action in actions {
        match action {
            Action::CreateDiffloreDir => apply_create_difflore_dir(),
            Action::InstallMcpDrift(names) => apply_install_mcp_drift(&names),
            Action::HookShim(state) => apply_hook_shim(state),
        }
    }

    decline_notices();

    println!();
    println!(
        "  {} {} {}",
        style::pewter("next:"),
        style::cmd("difflore"),
        style::pewter("to verify."),
    );
}

// Action planning

enum Action {
    CreateDiffloreDir,
    InstallMcpDrift(Vec<String>),
    HookShim(HookShimState),
}

fn collect_actions() -> Vec<Action> {
    let mut out: Vec<Action> = Vec::new();
    if !difflore_dir_exists() {
        out.push(Action::CreateDiffloreDir);
    }
    let drift = installer::detect_install_repair_targets();
    if !drift.is_empty() {
        out.push(Action::InstallMcpDrift(drift));
    }
    let shim = check_hook_shim();
    if !matches!(shim, HookShimState::Ok) {
        out.push(Action::HookShim(shim));
    }
    out
}

// 1. ~/.difflore/ directory

fn difflore_dir_path() -> Option<PathBuf> {
    difflore_core::infra::paths::data_home().ok()
}

fn difflore_dir_exists() -> bool {
    difflore_dir_path().is_some_and(|p| p.exists())
}

fn apply_create_difflore_dir() {
    let Some(dir) = difflore_dir_path() else {
        println!(
            "  {} {}",
            style::amber(style::sym::WARN),
            style::warn("could not resolve ~/.difflore/ — HOME not set?"),
        );
        return;
    };
    match std::fs::create_dir_all(&dir) {
        Ok(()) => println!(
            "  {} {} {}",
            style::emerald(style::sym::OK),
            style::ok("created"),
            style::ident(&dir.display().to_string()),
        ),
        Err(e) => println!(
            "  {} {} {} ({e})",
            style::amber(style::sym::WARN),
            style::warn("failed to create"),
            style::ident(&dir.display().to_string()),
        ),
    }
}

// 2. MCP install drift

fn apply_install_mcp_drift(names: &[String]) {
    println!(
        "  {} {} {}",
        style::emerald(style::sym::TIP),
        style::pewter("MCP drift detected:"),
        style::ident(&names.join(", ")),
    );
    // `install_all` is idempotent — re-running picks up newly detected
    // agents without re-prompting for already-installed ones, which is
    // exactly what we want for drift recovery.
    let applied = installer::install_all(false);
    let remaining = if applied {
        Vec::new()
    } else {
        installer::detect_install_repair_targets()
    };
    print_install_mcp_result(mcp_drift_repair_result(applied, remaining));
}

#[derive(Debug, PartialEq, Eq)]
enum McpDriftRepairResult {
    Applied,
    Remaining(Vec<String>),
    Unconfirmed,
}

fn mcp_drift_repair_result(applied: bool, remaining: Vec<String>) -> McpDriftRepairResult {
    if applied {
        McpDriftRepairResult::Applied
    } else if remaining.is_empty() {
        McpDriftRepairResult::Unconfirmed
    } else {
        McpDriftRepairResult::Remaining(remaining)
    }
}

fn print_install_mcp_result(result: McpDriftRepairResult) {
    match result {
        McpDriftRepairResult::Applied => println!(
            "  {} {}",
            style::emerald(style::sym::OK),
            style::ok("MCP install drift repaired"),
        ),
        McpDriftRepairResult::Remaining(names) => {
            println!(
                "  {} {} {}",
                style::amber(style::sym::WARN),
                style::warn("MCP install drift remains:"),
                style::ident(&names.join(", ")),
            );
            println!(
                "    {} {}",
                style::pewter(style::sym::TIP),
                style::pewter("run `difflore agents status` for details"),
            );
        }
        McpDriftRepairResult::Unconfirmed => {
            println!(
                "  {} {}",
                style::amber(style::sym::WARN),
                style::warn("MCP install drift repair was not confirmed"),
            );
            println!(
                "    {} {}",
                style::pewter(style::sym::TIP),
                style::pewter("run `difflore agents status` for details"),
            );
        }
    }
}

// 3. difflore-hook shim

enum HookShimState {
    Ok,
    Missing,
    Stale {
        shim_path: PathBuf,
        cli_path: PathBuf,
    },
    UnreadableMtime {
        shim_path: PathBuf,
        cli_path: PathBuf,
    },
}

fn check_hook_shim() -> HookShimState {
    let Ok(cli) = std::env::current_exe() else {
        // Can't compare without a CLI path — treat as ok rather than
        // emit a spurious warning.
        return HookShimState::Ok;
    };
    let Some(shim) = hook_shim_for_cli(&cli).or_else(which_hook_shim) else {
        return HookShimState::Missing;
    };
    classify_hook_shim_mtimes(&shim, &cli, file_mtime(&shim), file_mtime(&cli))
}

fn classify_hook_shim_mtimes(
    shim: &std::path::Path,
    cli: &std::path::Path,
    shim_mtime: Option<SystemTime>,
    cli_mtime: Option<SystemTime>,
) -> HookShimState {
    match (shim_mtime, cli_mtime) {
        (Some(s), Some(c)) if shim_older_than_cli(s, c) => HookShimState::Stale {
            shim_path: shim.to_path_buf(),
            cli_path: cli.to_path_buf(),
        },
        (Some(_), Some(_)) => HookShimState::Ok,
        _ => HookShimState::UnreadableMtime {
            shim_path: shim.to_path_buf(),
            cli_path: cli.to_path_buf(),
        },
    }
}

fn hook_shim_for_cli(cli: &std::path::Path) -> Option<PathBuf> {
    let exe_name = format!("difflore-hook{}", std::env::consts::EXE_SUFFIX);
    let candidate = cli.parent()?.join(exe_name);
    candidate.is_file().then_some(candidate)
}

fn which_hook_shim() -> Option<PathBuf> {
    let exe_name = format!("difflore-hook{}", std::env::consts::EXE_SUFFIX);
    let path = difflore_core::infra::env::var_os(difflore_core::infra::env::PATH)?;
    for dir in std::env::split_paths(&path) {
        let candidate = dir.join(&exe_name);
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    None
}

fn file_mtime(p: &std::path::Path) -> Option<SystemTime> {
    std::fs::metadata(p).ok().and_then(|m| m.modified().ok())
}

fn shim_older_than_cli(shim_mtime: SystemTime, cli_mtime: SystemTime) -> bool {
    cli_mtime
        .duration_since(shim_mtime)
        .is_ok_and(|age| age > HOOK_SHIM_STALE_GRACE)
}

fn apply_hook_shim(state: HookShimState) {
    match state {
        HookShimState::Ok => {}
        HookShimState::Missing => {
            println!(
                "  {} {}",
                style::amber(style::sym::WARN),
                style::warn("difflore-hook shim not found next to difflore or on PATH"),
            );
            println!(
                "    {} {} {}",
                style::pewter(style::sym::TIP),
                style::pewter("re-run"),
                style::cmd("difflore update"),
            );
        }
        HookShimState::Stale {
            shim_path,
            cli_path,
        } => {
            println!(
                "  {} {} {}",
                style::amber(style::sym::WARN),
                style::warn("difflore-hook is older than"),
                style::ident(&cli_path.display().to_string()),
            );
            println!(
                "    {} {} {}",
                style::pewter(style::sym::TIP),
                style::pewter("shim:"),
                style::ident(&shim_path.display().to_string()),
            );
            println!(
                "    {} {} {}",
                style::pewter(style::sym::TIP),
                style::pewter("re-run"),
                style::cmd("difflore update"),
            );
        }
        HookShimState::UnreadableMtime {
            shim_path,
            cli_path,
        } => {
            println!(
                "  {} {}",
                style::amber(style::sym::WARN),
                style::warn("could not compare difflore-hook and difflore timestamps"),
            );
            println!(
                "    {} {} {}",
                style::pewter(style::sym::BULLET),
                style::pewter("shim:"),
                style::ident(&shim_path.display().to_string()),
            );
            println!(
                "    {} {} {}",
                style::pewter(style::sym::BULLET),
                style::pewter("cli:"),
                style::ident(&cli_path.display().to_string()),
            );
            println!(
                "    {} {} {}",
                style::pewter(style::sym::TIP),
                style::pewter("re-run"),
                style::cmd("difflore update"),
            );
        }
    }
}

// Decline notices

/// Print the one-line "we won't auto-touch this" notices for the
/// privacy-sensitive surfaces. Only emitted under `--fix` so the
/// default doctor view stays uncluttered.
fn decline_notices() {
    println!();
    println!(
        "  {} {}",
        style::pewter(style::sym::BULLET),
        style::pewter("cloud login: never auto-touched — run `difflore cloud login` if needed"),
    );
    println!(
        "  {} {}",
        style::pewter(style::sym::BULLET),
        style::pewter("provider / API keys: never auto-touched — run `difflore providers setup`",),
    );
    println!(
        "  {} {}",
        style::pewter(style::sym::BULLET),
        style::pewter(
            "DB migrations: automatic on startup; back up the DB before switching binaries"
        ),
    );
}

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

    #[test]
    fn hook_shim_for_cli_finds_sibling_shim() {
        let tmp = tempfile::tempdir().expect("tmpdir");
        let cli = tmp
            .path()
            .join(format!("difflore{}", std::env::consts::EXE_SUFFIX));
        let shim = tmp
            .path()
            .join(format!("difflore-hook{}", std::env::consts::EXE_SUFFIX));
        std::fs::write(&shim, b"shim").expect("write shim");

        assert_eq!(hook_shim_for_cli(&cli), Some(shim));
    }

    #[test]
    fn hook_shim_for_cli_ignores_missing_sibling_shim() {
        let tmp = tempfile::tempdir().expect("tmpdir");
        let cli = tmp
            .path()
            .join(format!("difflore{}", std::env::consts::EXE_SUFFIX));

        assert!(hook_shim_for_cli(&cli).is_none());
    }

    #[test]
    fn shim_older_than_cli_tolerates_install_timestamp_skew() {
        let shim = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        let cli = SystemTime::UNIX_EPOCH + Duration::from_secs(104);

        assert!(!shim_older_than_cli(shim, cli));
    }

    #[test]
    fn shim_older_than_cli_flags_meaningful_stale_gap() {
        let shim = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
        let cli = SystemTime::UNIX_EPOCH + Duration::from_secs(110);

        assert!(shim_older_than_cli(shim, cli));
    }

    #[test]
    fn hook_shim_with_unreadable_mtime_needs_attention() {
        let shim = PathBuf::from("difflore-hook");
        let cli = PathBuf::from("difflore");

        assert!(matches!(
            classify_hook_shim_mtimes(
                &shim,
                &cli,
                None,
                Some(SystemTime::UNIX_EPOCH + Duration::from_secs(100)),
            ),
            HookShimState::UnreadableMtime { .. }
        ));
    }

    #[test]
    fn mcp_drift_repair_result_reports_applied_install() {
        assert_eq!(
            mcp_drift_repair_result(true, vec!["Codex".to_owned()]),
            McpDriftRepairResult::Applied
        );
    }

    #[test]
    fn mcp_drift_repair_result_reports_remaining_drift() {
        assert_eq!(
            mcp_drift_repair_result(false, vec!["Codex".to_owned(), "Cursor".to_owned()]),
            McpDriftRepairResult::Remaining(vec!["Codex".to_owned(), "Cursor".to_owned()])
        );
    }

    #[test]
    fn mcp_drift_repair_result_reports_unconfirmed_noop() {
        assert_eq!(
            mcp_drift_repair_result(false, Vec::new()),
            McpDriftRepairResult::Unconfirmed
        );
    }
}