memd 1.9.0

Local memory CLI for AI agents with hybrid retrieval
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
467
468
469
470
use std::path::PathBuf;
use std::time::Duration;

use clap::{Parser, ValueEnum};
use tracing::info;

use memd::cli::{
    run_cli, run_warm_admin, try_run_warm_client, CliCommand, StoreAccess, WarmProcessConfig,
};
use memd::embeddings::{CandleModel, EmbeddingModel};
use memd::store::HybridConfig;
use memd::{
    configure_operation_routing, init_logging, load_config, MemoryStore, PersistentStore,
    PersistentStoreConfig, RerankerConfig, RerankerMode, TenantManager,
};

/// Embedding model choice
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum ModelChoice {
    /// all-MiniLM-L6-v2: 384-dim, fast, good quality (default)
    AllMinilm,
    /// Qwen3-Embedding-0.6B: 1024-dim, slower, best quality (not yet supported in Candle)
    Qwen3,
    /// bge-base-en-v1.5: 768-dim Candle BERT, stronger retrieval (CLS pooling,
    /// dense-only by default)
    BgeBase,
}

impl From<ModelChoice> for EmbeddingModel {
    fn from(choice: ModelChoice) -> Self {
        match choice {
            ModelChoice::AllMinilm => EmbeddingModel::AllMiniLmL6V2,
            ModelChoice::Qwen3 => EmbeddingModel::Qwen3Embedding0_6B,
            // EmbeddingModel is the vestigial ONNX-era selector and has no bge
            // variant; the live Candle model is chosen via CandleModel below.
            ModelChoice::BgeBase => EmbeddingModel::AllMiniLmL6V2,
        }
    }
}

impl From<ModelChoice> for CandleModel {
    fn from(choice: ModelChoice) -> Self {
        match choice {
            // Qwen3 is not supported by the Candle BERT backend; it has always
            // run MiniLM there, so preserve that behavior.
            ModelChoice::AllMinilm | ModelChoice::Qwen3 => CandleModel::MiniLm,
            ModelChoice::BgeBase => CandleModel::BgeBase,
        }
    }
}

impl ModelChoice {
    fn cli_value(self) -> &'static str {
        match self {
            ModelChoice::AllMinilm => "all-minilm",
            ModelChoice::Qwen3 => "qwen3",
            ModelChoice::BgeBase => "bge-base",
        }
    }
}

/// Resolve the default retrieval strategy for a model when `--search-variant`
/// is not given explicitly. bge-base defaults to dense-only (hybrid fusion
/// off); every other model keeps the hybrid-feature default.
fn default_search_variant(model: ModelChoice) -> SearchVariant {
    match model {
        ModelChoice::BgeBase => SearchVariant::DenseOnly,
        _ => SearchVariant::HybridFeature,
    }
}

/// Resolve the effective retrieval strategy: an explicit `--search-variant`
/// wins; otherwise fall back to the model-derived default.
fn resolve_search_variant(explicit: Option<SearchVariant>, model: ModelChoice) -> SearchVariant {
    explicit.unwrap_or_else(|| default_search_variant(model))
}

/// Retrieval strategy for persistent mode.
#[derive(Debug, Clone, Copy, ValueEnum)]
enum SearchVariant {
    /// Dense+sparse hybrid with feature reranker (default).
    HybridFeature,
    /// Dense+sparse hybrid with cross-encoder reranker.
    HybridCrossEncoder,
    /// Dense-only retrieval path.
    DenseOnly,
    /// Pure BM25 baseline with dense retrieval and feature bonuses disabled.
    Bm25Only,
}

impl SearchVariant {
    fn cli_value(self) -> &'static str {
        match self {
            SearchVariant::HybridFeature => "hybrid-feature",
            SearchVariant::HybridCrossEncoder => "hybrid-cross-encoder",
            SearchVariant::DenseOnly => "dense-only",
            SearchVariant::Bm25Only => "bm25-only",
        }
    }
}

/// memd - Local memory CLI for AI agents
///
/// Provides executable memory operations for skill-driven agent workflows.
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
    /// Path to configuration file
    #[arg(short, long)]
    config: Option<PathBuf>,

    /// Data directory for persistent storage
    #[arg(long)]
    data_dir: Option<PathBuf>,

    /// Use in-memory storage instead of persistent storage (for testing)
    #[arg(long, default_value = "false")]
    in_memory: bool,

    /// Enable verbose logging
    #[arg(short, long)]
    verbose: bool,

    /// Embedding model to use
    #[arg(long, value_enum, default_value = "all-minilm")]
    embedding_model: ModelChoice,

    /// Retrieval strategy variant for persistent mode
    ///
    /// Defaults to dense-only for bge-base and hybrid-feature for other
    /// models when not given explicitly.
    #[arg(long, value_enum)]
    search_variant: Option<SearchVariant>,

    /// CLI subcommand
    #[command(subcommand)]
    command: Option<CliCommand>,
}

#[tokio::main]
async fn main() {
    let args = Args::parse();

    // Load configuration
    let config = load_config(args.config.as_deref()).unwrap_or_else(|e| {
        eprintln!("error: failed to load configuration: {}", e);
        std::process::exit(1);
    });

    // Determine data directory: CLI arg > config > default
    let data_dir = args
        .data_dir
        .clone()
        .or_else(|| config.data_dir_expanded().ok())
        .unwrap_or_else(|| PathBuf::from("data"));

    let mut config = config;
    config.data_dir = data_dir.clone();
    if let Err(e) = config.validate() {
        eprintln!("error: invalid configuration: {}", e);
        std::process::exit(1);
    }
    configure_operation_routing(
        config.server.allow_cross_tenant_project_fallback,
        config.server.project_aliases.clone(),
    );

    let Some(mut cmd) = args.command else {
        eprintln!("error: memd requires a CLI subcommand. Use --help for usage.");
        std::process::exit(1);
    };
    cmd.normalize_positional_aliases();

    // Initialize logging
    let is_warm_worker = matches!(&cmd, CliCommand::WarmWorker { .. });
    let log_level = if args.verbose || is_warm_worker {
        "info"
    } else {
        "warn"
    };
    init_logging("pretty", log_level);

    info!(
        version = env!("CARGO_PKG_VERSION"),
        config_path = ?args.config,
        data_dir = %data_dir.display(),
        in_memory = args.in_memory,
        "memd CLI starting"
    );

    // `experience note --emit` validates a file and needs no scope or store.
    match memd::cli::emit_case_if_requested(&cmd) {
        Ok(true) => return,
        Ok(false) => {}
        Err(error) => {
            eprintln!("error: {error}");
            std::process::exit(1);
        }
    }

    if let Err(e) = memd::cli::resolve_command_scope(&mut cmd) {
        eprintln!("error: {}", e);
        std::process::exit(1);
    }

    cmd = match memd::cli::prepare_experience_command(cmd, &data_dir, args.in_memory).await {
        Ok(cmd) => cmd,
        Err(error) => {
            eprintln!("error: {error}");
            std::process::exit(1);
        }
    };
    if let Err(error) = memd::cli::prepare_execution_context(&mut cmd) {
        eprintln!("error: {error}");
        std::process::exit(1);
    }

    // Resolve the retrieval strategy once, here, so an unset --search-variant
    // takes the model-derived default (dense-only for bge-base) and warm
    // workers are spawned with the same concrete variant.
    let search_variant = resolve_search_variant(args.search_variant, args.embedding_model);

    // Stamp the worker's model/variant identity onto the (hidden) WarmWorker
    // command so it reports them in the ping handshake; a client requesting a
    // different model/variant then respawns it instead of being answered by
    // the wrong embedder.
    if let CliCommand::WarmWorker {
        embedding_model,
        search_variant: worker_variant,
        ..
    } = &mut cmd
    {
        *embedding_model = Some(args.embedding_model.cli_value().to_string());
        *worker_variant = Some(search_variant.cli_value().to_string());
    }

    let warm_config = WarmProcessConfig {
        data_dir: data_dir.clone(),
        config_path: args.config.clone(),
        embedding_model: args.embedding_model.cli_value().to_string(),
        search_variant: search_variant.cli_value().to_string(),
    };

    if let CliCommand::Warm { command } = &cmd {
        if args.in_memory {
            eprintln!("error: warm workers require persistent storage");
            std::process::exit(1);
        }
        if let Err(e) = run_warm_admin(&warm_config, command.clone()).await {
            eprintln!("error: {}", e);
            std::process::exit(1);
        }
        return;
    }

    if matches!(&cmd, CliCommand::WarmWorker { .. }) && args.in_memory {
        eprintln!("error: warm-worker requires persistent storage");
        std::process::exit(1);
    }

    if let Some(mode) = cmd.warm_mode() {
        if args.in_memory {
            if mode == memd::cli::WarmMode::Required {
                eprintln!("error: --warm required is not supported with --in-memory");
                std::process::exit(1);
            }
        } else if mode != memd::cli::WarmMode::Off {
            match try_run_warm_client(&warm_config, &cmd).await {
                Ok(true) => return,
                Ok(false) => {}
                Err(e) => {
                    eprintln!("error: {}", e);
                    std::process::exit(1);
                }
            }
        }
    }

    // Create tenant manager
    let tenant_manager = Some(TenantManager::new(data_dir.clone()));

    if !cmd.requires_store() {
        let store = MemoryStore::new();
        if let Err(e) = run_cli(&store, tenant_manager.as_ref(), cmd).await {
            eprintln!("error: {}", e);
            std::process::exit(1);
        }
        return;
    }

    // Run CLI with appropriate store type
    if args.in_memory {
        info!("using in-memory store");
        let store = MemoryStore::new();
        if let Err(e) = run_cli(&store, tenant_manager.as_ref(), cmd).await {
            eprintln!("error: {}", e);
            std::process::exit(1);
        }
    } else {
        info!(data_dir = %data_dir.display(), embedding_model = ?args.embedding_model, "using persistent store");
        let mut store_config = PersistentStoreConfig {
            data_dir: data_dir.clone(),
            read_only: cmd.store_access() == StoreAccess::ReadOnly,
            embedding_model: args.embedding_model.into(),
            candle_model: args.embedding_model.into(),
            ..Default::default()
        };
        apply_search_variant(search_variant, &mut store_config);
        if matches!(&cmd, CliCommand::WarmWorker { .. }) {
            // A warm worker that cannot promptly become THE writer must exit
            // and let the client's ping find the winner / fall back. Long
            // retries make herd losers linger and steal the flock after
            // `memd warm stop`.
            store_config.writer_lock_timeout_cap = Some(Duration::from_millis(2_000));
            let async_indexing_env = std::env::var("MEMD_ASYNC_INDEXING").ok();
            store_config.apply_warm_worker_availability_defaults(async_indexing_env.as_deref());
        }
        match PersistentStore::open(store_config) {
            Ok(store) => {
                if let Err(e) = run_cli(&store, tenant_manager.as_ref(), cmd).await {
                    eprintln!("error: {}", e);
                    std::process::exit(1);
                }
            }
            Err(e) => {
                eprintln!("error: failed to create persistent store: {}", e);
                std::process::exit(1);
            }
        }
    }
}

fn apply_search_variant(search_variant: SearchVariant, config: &mut PersistentStoreConfig) {
    match search_variant {
        SearchVariant::HybridFeature => {
            config.enable_dense_search = true;
            config.enable_hybrid_search = true;
            let hybrid = HybridConfig {
                reranker: RerankerConfig {
                    mode: RerankerMode::Feature,
                    ..RerankerConfig::default()
                },
                ..HybridConfig::default()
            };
            config.hybrid_config = Some(hybrid);
        }
        SearchVariant::HybridCrossEncoder => {
            config.enable_dense_search = true;
            config.enable_hybrid_search = true;
            let hybrid = HybridConfig {
                reranker: RerankerConfig {
                    mode: RerankerMode::CrossEncoder,
                    ..RerankerConfig::default()
                },
                ..HybridConfig::default()
            };
            config.hybrid_config = Some(hybrid);
        }
        SearchVariant::DenseOnly => {
            config.enable_dense_search = true;
            config.enable_hybrid_search = false;
            config.hybrid_config = None;
        }
        SearchVariant::Bm25Only => {
            config.enable_dense_search = false;
            config.enable_hybrid_search = true;
            config.enable_tiered_search = false;
            let hybrid = HybridConfig {
                dense_k: 0,
                enable_sparse: true,
                enable_rerank: false,
                reranker: RerankerConfig {
                    mode: RerankerMode::Feature,
                    rrf_weight: 1.0,
                    recency_weight: 0.0,
                    project_weight: 0.0,
                    type_weight: 0.0,
                    query_text_weight: 0.0,
                    cross_encoder_weight: 0.0,
                    ..RerankerConfig::default()
                },
                ..HybridConfig::default()
            };
            config.hybrid_config = Some(hybrid);
        }
    }
}

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

    #[test]
    fn model_choice_maps_to_candle_model() {
        // The Candle backend is the live embedder; bge-base selects it.
        assert_eq!(
            CandleModel::from(ModelChoice::AllMinilm),
            CandleModel::MiniLm
        );
        assert_eq!(
            CandleModel::from(ModelChoice::BgeBase),
            CandleModel::BgeBase
        );
        // Qwen3 has no Candle backend and has always run MiniLM there.
        assert_eq!(CandleModel::from(ModelChoice::Qwen3), CandleModel::MiniLm);
    }

    #[test]
    fn bge_choice_has_cli_value_and_vestigial_onnx_mapping() {
        assert_eq!(ModelChoice::BgeBase.cli_value(), "bge-base");
        // EmbeddingModel is the vestigial ONNX selector; bge maps onto the
        // MiniLM id there because the live model flows via CandleModel.
        assert_eq!(
            EmbeddingModel::from(ModelChoice::BgeBase),
            EmbeddingModel::AllMiniLmL6V2
        );
    }

    #[test]
    fn default_search_variant_is_dense_only_for_bge_only() {
        assert!(matches!(
            default_search_variant(ModelChoice::BgeBase),
            SearchVariant::DenseOnly
        ));
        assert!(matches!(
            default_search_variant(ModelChoice::AllMinilm),
            SearchVariant::HybridFeature
        ));
        assert!(matches!(
            default_search_variant(ModelChoice::Qwen3),
            SearchVariant::HybridFeature
        ));
    }

    #[test]
    fn explicit_search_variant_overrides_bge_default() {
        // An explicit flag wins even against bge's dense-only default.
        assert!(matches!(
            resolve_search_variant(Some(SearchVariant::HybridFeature), ModelChoice::BgeBase),
            SearchVariant::HybridFeature
        ));
        // An unset flag falls back to the model-derived default.
        assert!(matches!(
            resolve_search_variant(None, ModelChoice::BgeBase),
            SearchVariant::DenseOnly
        ));
        assert!(matches!(
            resolve_search_variant(None, ModelChoice::AllMinilm),
            SearchVariant::HybridFeature
        ));
    }

    #[test]
    fn bm25_only_disables_non_lexical_ranking_features() {
        let mut config = PersistentStoreConfig::default();
        apply_search_variant(SearchVariant::Bm25Only, &mut config);

        let hybrid = config.hybrid_config.expect("bm25 hybrid configuration");
        assert_eq!(hybrid.dense_k, 0);
        assert!(hybrid.enable_sparse);
        assert!(!hybrid.enable_rerank);
        assert!(!config.enable_dense_search);
        assert_eq!(hybrid.reranker.rrf_weight, 1.0);
        assert_eq!(hybrid.reranker.recency_weight, 0.0);
        assert_eq!(hybrid.reranker.project_weight, 0.0);
        assert_eq!(hybrid.reranker.type_weight, 0.0);
        assert_eq!(hybrid.reranker.query_text_weight, 0.0);
        assert_eq!(hybrid.reranker.cross_encoder_weight, 0.0);
    }
}