difflore-cli 0.1.0

Your AI coding agent, taught by your team's PR reviews — a local-first, open-source MCP server that turns past review comments into rules your agent follows automatically.
Documentation
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
//! Embedding configuration commands — `difflore embeddings status/setup/disable`.
//!
//! Lets users inspect and change the active embedding backend without hand-
//! editing `settings.json`. The three subcommands are:
//!
//! * `status`  — show which embedder is active and whether semantic recall is on.
//! * `setup`   — write BYOK (OpenAI-compatible) embedding credentials to settings.
//! * `disable` — revert to fast local keyword matching.

use colored::Colorize;
use difflore_core::context::embedding::{ActiveEmbedderKind, DEFAULT_OPENAI_EMBEDDING_DIM};

use crate::commands::providers::resolve_secret_input;
use crate::commands::util::exit_err;
use crate::style;

const DEFAULT_PROVIDER_URL: &str = "https://api.openai.com/v1";
const DEFAULT_MODEL: &str = "text-embedding-3-small";
const DEFAULT_DIM: usize = DEFAULT_OPENAI_EMBEDDING_DIM;

// ── helpers ────────────────────────────────────────────────────────────────

/// Extract the host portion from a URL string (scheme + authority only).
/// Used to print a short, readable provider label in success messages.
fn provider_host_from_url(url: &str) -> String {
    // Strip scheme, keep host (up to the first path separator or port suffix).
    let after_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
    let host = after_scheme.split('/').next().unwrap_or(after_scheme);
    if host.is_empty() {
        url.to_owned()
    } else {
        host.to_owned()
    }
}

// ── status ─────────────────────────────────────────────────────────────────

pub(crate) async fn handle_status(json: bool) {
    let kind = difflore_core::context::embedding::probe_active_embedder().await;
    let diagnostics = cwd_embedding_diagnostics().await;

    if json {
        let (embedder_tag, semantic, model, dim, provider_host) = match &kind {
            ActiveEmbedderKind::Cloud { model, dim } => {
                ("cloud", true, model.as_str(), *dim, "managed".to_owned())
            }
            ActiveEmbedderKind::Byok {
                provider_host,
                model,
                dim,
            } => ("byok", true, model.as_str(), *dim, provider_host.clone()),
            ActiveEmbedderKind::Sha1 => ("sha1", false, "", 128usize, String::new()),
        };
        let value = serde_json::json!({
            "embedder": embedder_tag,
            "semantic": semantic,
            "model": model,
            "dim": dim,
            "providerHost": provider_host,
            "currentRepoIndex": diagnostics.as_ref().map(|diag| serde_json::json!({
                "activeProfile": &diag.active_profile,
                "indexProfile": &diag.index_profile,
                "profileMatch": diag.profile_match,
                "degraded": diag.degraded,
                "degradedReason": &diag.degraded_reason,
                "vectorLaneAvailable": diag.vector_lane_available,
            })),
        });
        println!("{}", crate::commands::util::json_or(&value, "{}"));
        return;
    }

    match &kind {
        ActiveEmbedderKind::Cloud { model, dim } => {
            println!("{} Embeddings", style::ok(style::sym::OK));
            println!();
            println!(
                "  {} {}",
                style::pewter("embedder:"),
                "cloud (DiffLore managed)".bold()
            );
            println!("  {} {model}", style::pewter("model:   "));
            println!("  {} {dim}", style::pewter("dim:     "));
            println!();
            println!(
                "  {} {}",
                style::emerald(style::sym::TIP),
                semantic_status_line(diagnostics.as_ref())
            );
        }
        ActiveEmbedderKind::Byok {
            provider_host,
            model,
            dim,
        } => {
            println!("{} Embeddings", style::ok(style::sym::OK));
            println!();
            println!(
                "  {} {}",
                style::pewter("embedder:"),
                "BYOK (bring-your-own-key)".bold()
            );
            println!("  {} {provider_host}", style::pewter("provider:"));
            println!("  {} {model}", style::pewter("model:   "));
            println!("  {} {dim}", style::pewter("dim:     "));
            println!();
            println!(
                "  {} {}",
                style::emerald(style::sym::TIP),
                semantic_status_line(diagnostics.as_ref())
            );
        }
        ActiveEmbedderKind::Sha1 => {
            println!("{} Embeddings", style::warn(style::sym::WARN));
            println!();
            println!(
                "  {} {}",
                style::pewter("semantic search:"),
                "off · using fast keyword matching".bold()
            );
            println!();
            println!(
                "  {} Recall still works; semantic search is optional.",
                style::amber(style::sym::WARN)
            );
            println!("    To improve match quality, choose one of:");
            println!(
                "      1. {}  (managed, no key required)",
                style::cmd("difflore cloud login")
            );
            println!(
                "      2. {}  (bring your own OpenAI-compatible key)",
                style::cmd("difflore embeddings setup")
            );
        }
    }

    print_cwd_embedding_diagnostics(diagnostics.as_ref());
}

const fn semantic_status_line(
    diag: Option<&difflore_core::context::EmbeddingDiagnostics>,
) -> &'static str {
    match diag {
        Some(diag) if diag.degraded || !diag.vector_lane_available => {
            "Semantic search is configured; current repo index status appears below."
        }
        _ => "Semantic search is active.",
    }
}

async fn cwd_embedding_diagnostics() -> Option<difflore_core::context::EmbeddingDiagnostics> {
    let index_pool = difflore_core::context::index_db::get_pool_for_cwd()
        .await
        .ok()?;
    Some(difflore_core::context::gather_embedding_diagnostics_with_activity(&index_pool).await)
}

fn print_cwd_embedding_diagnostics(diag: Option<&difflore_core::context::EmbeddingDiagnostics>) {
    let Some(diag) = diag else {
        return;
    };
    if diag.degraded {
        let reason = diag
            .degraded_reason
            .as_deref()
            .unwrap_or("embedding_profile_mismatch");
        let state = if diag.vector_lane_available {
            "semantic index needs attention"
        } else {
            "semantic index is paused"
        };
        let display_reason = match reason {
            "dimension_mismatch" | "profile_mismatch" | "embedding_profile_mismatch" => {
                "index needs a rebuild"
            }
            "missing_vectors" | "vector_lane_missing" => "index has not been built",
            _ => "index is out of date",
        };
        println!();
        println!(
            "  {} Current repo index: {state} ({display_reason}).",
            style::amber(style::sym::WARN)
        );
        println!("    Recall still works through file patterns and keyword matching.");
        if matches!(reason, "dimension_mismatch" | "profile_mismatch") {
            // Match doctor's recovery advice: the force-rebuild heals a
            // same-count inconsistency that the freshness-gated `recall --diff`
            // would skip; keep `recall --diff` as the lazy refresh option.
            println!(
                "    Rebuild this repo's semantic index: {} (or run {} to refresh lazily)",
                style::cmd("difflore embeddings rebuild"),
                style::cmd("difflore recall --diff")
            );
        } else {
            println!(
                "    Restore semantic embeddings: {} or {}",
                style::cmd("difflore cloud login"),
                style::cmd("difflore embeddings setup")
            );
        }
        println!(
            "    Full detail: {}",
            style::cmd("difflore doctor --report")
        );
    } else if !diag.vector_lane_available {
        println!();
        println!(
            "  {} Current repo index: semantic search is not built yet.",
            style::pewter(style::sym::BULLET)
        );
        println!(
            "    Build it with: {}",
            style::cmd("difflore recall --diff")
        );
    }
}

// ── setup ──────────────────────────────────────────────────────────────────

pub(crate) async fn handle_setup(
    provider_url: Option<String>,
    model: Option<String>,
    dim: Option<usize>,
    key: Option<String>,
    no_key: bool,
) {
    let url = provider_url
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| DEFAULT_PROVIDER_URL.to_owned());
    let model = model
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| DEFAULT_MODEL.to_owned());
    let dim = dim.unwrap_or(DEFAULT_DIM);

    // Keyless local providers (e.g. a self-hosted embedding server with no auth)
    // are supported by the resolver, so `--no-key` skips key resolution entirely.
    // Otherwise resolve the API key from flag / env var / piped stdin.
    let storage = if no_key {
        None
    } else {
        let raw_key = resolve_secret_input(
            key,
            "DIFFLORE_EMBEDDING_KEY",
            "Embedding provider API key",
            "difflore embeddings setup (use --no-key for a keyless local provider)",
        );
        // Encrypt and store the key via the core keyring/AES-GCM layer.
        Some(
            difflore_core::context::embedding::store_embedding_key(&raw_key)
                .unwrap_or_else(|e| exit_err(&format!("failed to encrypt embedding key: {e}"))),
        )
    };

    // Load, patch, and save settings.
    let mut settings = difflore_core::settings::get()
        .await
        .unwrap_or_else(|e| exit_err(&format!("failed to load settings: {e}")));

    settings.context_engine.semantic_embedding = true;
    settings.context_engine.embedding_provider_url = Some(url.clone());
    settings.context_engine.embedding_provider_key = storage;
    settings.context_engine.embedding_model = Some(model.clone());
    settings.context_engine.embedding_dim = Some(dim);

    difflore_core::settings::update(settings)
        .await
        .unwrap_or_else(|e| exit_err(&format!("failed to save settings: {e}")));

    let host = provider_host_from_url(&url);

    println!(
        "{} Embedding provider configured",
        style::ok(style::sym::OK)
    );
    println!();
    println!("  {} {host}", style::pewter("provider:"));
    println!("  {} {model}", style::pewter("model:   "));
    println!("  {} {dim}", style::pewter("dim:     "));
    println!();
    println!(
        "  {} The next {} or review will re-index using the new provider.",
        style::emerald(style::sym::TIP),
        style::cmd("difflore recall")
    );
    println!(
        "    Check status:   {}",
        style::cmd("difflore embeddings status")
    );
    println!(
        "    Test recall:    {}",
        style::cmd("difflore recall --diff")
    );
}

// ── disable ────────────────────────────────────────────────────────────────

pub(crate) async fn handle_disable() {
    let mut settings = difflore_core::settings::get()
        .await
        .unwrap_or_else(|e| exit_err(&format!("failed to load settings: {e}")));

    settings.context_engine.semantic_embedding = false;

    difflore_core::settings::update(settings)
        .await
        .unwrap_or_else(|e| exit_err(&format!("failed to save settings: {e}")));

    // Report the embedder that is ACTUALLY active now. Disabling BYOK while
    // logged into cloud falls back to cloud-managed semantic embeddings, not
    // local SHA1 — claiming SHA1 would be wrong for that common case.
    let kind = difflore_core::context::embedding::probe_active_embedder().await;
    if let ActiveEmbedderKind::Cloud { .. } = kind {
        println!("{} BYOK embeddings disabled", style::ok(style::sym::OK));
        println!();
        println!(
            "  You're logged in to cloud, so recall now uses cloud-managed semantic embeddings."
        );
        println!(
            "  To use only local keyword matching, also run {}.",
            style::cmd("difflore cloud logout")
        );
    } else {
        println!("{} Semantic search turned off", style::ok(style::sym::OK));
        println!();
        println!("  Recall still works with fast local keyword matching.");
        println!("  To re-enable:");
        println!("    Managed:  {}", style::cmd("difflore cloud login"));
        println!("    BYOK:     {}", style::cmd("difflore embeddings setup"));
    }
}

// ── rebuild ──────────────────────────────────────────────────────────────────

/// `difflore embeddings rebuild` — force-rebuild the per-project semantic index
/// for the current repo scope. Recovery path for a suspected-stale or
/// inconsistent index: it re-embeds the in-scope corpus and prunes every
/// out-of-scope / orphaned chunk, bypassing the freshness short-circuit that
/// normal recall/serve rely on. Safe to run anytime — it is a clean rebuild
/// even when the index is already correct.
pub(crate) async fn handle_rebuild(json: bool) {
    let db = crate::commands::util::init_db().await;

    // Detect repo scope exactly like recall / the hook (origin + upstream, with
    // local fork->source alias expansion). The per-project index IS the scope
    // boundary, so an unscoped checkout has nothing to rebuild.
    let detected =
        difflore_core::git::detect_github_repo_full_names(&crate::commands::util::project_path());
    let repo_scopes = difflore_core::skills::expand_repo_scopes_with_source_aliases(&db, &detected)
        .await
        .unwrap_or(detected);

    if repo_scopes.is_empty() {
        if json {
            println!(
                "{}",
                crate::commands::util::json_or(
                    &serde_json::json!({ "rebuilt": false, "reason": "no_repo_scope", "chunks": 0 }),
                    "{}",
                )
            );
        } else {
            println!(
                "{} No GitHub origin/upstream remote detected; the index is repo-scoped, so there is nothing to rebuild here.",
                style::warn(style::sym::WARN),
            );
            println!(
                "  Add a remote (or run inside a repo that has one): {}",
                style::cmd("git remote -v"),
            );
        }
        return;
    }

    let index_pool = match difflore_core::context::index_db::get_pool_for_cwd().await {
        Ok(pool) => pool,
        Err(error) => exit_err(&format!("failed to open local index DB: {error}")),
    };

    match difflore_core::context::orchestrator::rebuild_rules_index_for_repo_scopes(
        &db,
        &index_pool,
        &repo_scopes,
        Some(std::time::Duration::from_secs(30)),
    )
    .await
    {
        Ok(chunks) => {
            if json {
                println!(
                    "{}",
                    crate::commands::util::json_or(
                        &serde_json::json!({
                            "rebuilt": true,
                            "repoScopes": repo_scopes,
                            "chunks": chunks,
                        }),
                        "{}",
                    )
                );
            } else {
                println!(
                    "{} Rebuilt the local index for {} ({} chunk{}).",
                    style::ok(style::sym::OK),
                    repo_scopes.join(", "),
                    chunks,
                    if chunks == 1 { "" } else { "s" },
                );
                println!("  The next recall / MCP serve uses the fresh index.");
            }
        }
        Err(error) => exit_err(&format!("index rebuild failed: {error}")),
    }
}

// ── tests ──────────────────────────────────────────────────────────────────

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

    #[test]
    fn default_dim_matches_core_constant() {
        // Verify that our local DEFAULT_DIM alias stays in sync with the
        // upstream constant. If the core value changes, this test fails fast
        // and forces an intentional update here.
        assert_eq!(DEFAULT_DIM, DEFAULT_OPENAI_EMBEDDING_DIM);
    }

    #[test]
    fn provider_host_from_url_strips_scheme_and_path() {
        assert_eq!(
            provider_host_from_url("https://api.openai.com/v1"),
            "api.openai.com"
        );
        assert_eq!(
            provider_host_from_url("https://api.openai.com/v1/embeddings"),
            "api.openai.com"
        );
        assert_eq!(
            provider_host_from_url("http://localhost:8080/v1"),
            "localhost:8080"
        );
        assert_eq!(
            provider_host_from_url("https://together.xyz"),
            "together.xyz"
        );
    }

    #[test]
    fn provider_host_handles_no_scheme() {
        // URL without scheme — treat everything before first `/` as host.
        assert_eq!(
            provider_host_from_url("api.example.com/v1"),
            "api.example.com"
        );
    }

    #[test]
    fn default_provider_url_parses_to_known_host() {
        assert_eq!(
            provider_host_from_url(DEFAULT_PROVIDER_URL),
            "api.openai.com"
        );
    }
}