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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! Command-line interface for Lantern.
use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use std::path::{Path, PathBuf};
use crate::compact;
use crate::diff;
use crate::embed;
use crate::export;
use crate::feedback;
use crate::forget;
use crate::ingest;
use crate::inspect;
use crate::mcp;
use crate::reindex;
use crate::search;
use crate::show;
use crate::stash;
use crate::store::{self, Store};
/// Default store directory, resolved relative to the working directory.
pub const DEFAULT_STORE_DIRNAME: &str = ".lantern";
#[derive(Parser, Debug)]
#[command(
name = "lantern",
version,
about = "Local-first memory engine for agent activity"
)]
pub struct Cli {
#[command(subcommand)]
pub command: Command,
}
#[derive(Subcommand, Debug)]
pub enum Command {
/// Print the lantern version (same output as `--version`)
Version,
/// Initialize a local Lantern store
Init {
/// Directory to create (default: ./.lantern)
#[arg(long)]
path: Option<PathBuf>,
},
/// Ingest files/directories, or content piped in via stdin
Ingest {
/// File or directory to ingest (omit when using --stdin)
path: Option<PathBuf>,
/// Read content from stdin instead of the filesystem
#[arg(long, conflicts_with = "path")]
stdin: bool,
/// URI or label to record for stdin content (required with --stdin)
#[arg(long, requires = "stdin")]
uri: Option<String>,
/// Kind for stdin content (default: text/plain). Use
/// application/jsonl to trigger the transcript extractor.
#[arg(long, requires = "stdin")]
kind: Option<String>,
/// Append-only stdin ingest: preserve each batch as its own source
/// under a unique derivative of --uri. Use for session transcripts
/// streamed in chunks under a stable session label.
#[arg(long, requires = "stdin")]
append: bool,
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Bypass .lantern-ignore rules (and built-in defaults)
#[arg(long, conflicts_with = "stdin")]
no_ignore: bool,
/// Poll the target path and re-ingest new or modified files on a
/// fixed interval. Runs until interrupted (Ctrl-C). Useful for live
/// transcript directories where agent sessions keep appearing.
#[arg(long, conflicts_with = "stdin")]
follow: bool,
/// Seconds between polling passes in `--follow` mode.
#[arg(
long,
default_value_t = ingest::DEFAULT_FOLLOW_INTERVAL_SECS,
requires = "follow"
)]
follow_interval_secs: u64,
/// Optional idle TTL in seconds. When set, `--follow` exits after this
/// much time has passed without ingesting a fresh source.
#[arg(long, requires = "follow")]
follow_idle_timeout_secs: Option<u64>,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Compare indexed filesystem sources against the current filesystem
Diff {
/// Directory to scope the comparison against (also used to find
/// supported files that are not yet indexed). Omit to check every
/// file:// source the store knows about.
path: Option<PathBuf>,
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Export sources and chunks as JSON (optionally filtered)
Export {
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Only include sources whose path or URI contains this substring
#[arg(long)]
path: Option<String>,
/// Only include sources with at least one chunk matching this query
#[arg(long)]
query: Option<String>,
/// Write the JSON document to this file instead of stdout
#[arg(long)]
output: Option<PathBuf>,
},
/// Remove indexed sources (and their chunks) whose path or URI matches
Forget {
/// Substring to match against source path or URI (required)
pattern: String,
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Actually delete matching sources. Without this flag, forget runs
/// in dry-run mode and only reports what would be removed.
#[arg(long)]
apply: bool,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Report store status: schema version, counts, recent sources
Inspect {
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Maximum number of recent sources to list
#[arg(long, default_value_t = 10)]
limit: usize,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Snapshot the current store to a dated tar.gz archive under <store>/stashes/
Stash {
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Record user feedback (thumbs-up / thumbs-down) for a chunk.
///
/// The chunk id is the 32-hex value shown in `search --format json` hits
/// (and the detailed text output). Feedback is additive — repeated `up`
/// votes keep lifting the score, `down` votes subtract. Net scores feed
/// into the search confidence blend via `compute_confidence`.
Feedback {
/// Chunk id (full 32-hex value from search output)
chunk_id: String,
/// Vote direction
#[arg(value_enum)]
vote: FeedbackVote,
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Compact stale access metadata so old reads stop dominating confidence.
Compact {
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Half-life in seconds for stale access-count decay.
#[arg(long, default_value_t = compact::DEFAULT_HALF_LIFE_SECS)]
half_life_secs: u64,
/// Minimum age in seconds before a chunk is eligible for decay.
#[arg(long, default_value_t = compact::DEFAULT_MINIMUM_AGE_SECS)]
minimum_age_secs: u64,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Rebuild the full-text index from stored chunks
Reindex {
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Display full provenance and chunk text for a single source
Show {
/// Source id (full 32-hex value or any unambiguous prefix)
id: String,
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Generate embeddings for chunks that don't have them yet (via Ollama)
Embed {
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Ollama embedding model (must be pulled locally)
#[arg(long, default_value = embed::DEFAULT_EMBED_MODEL)]
model: String,
/// Ollama base URL
#[arg(long, default_value = embed::DEFAULT_OLLAMA_URL)]
ollama_url: String,
/// Stop after embedding this many chunks (default: no cap)
#[arg(long)]
limit: Option<usize>,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Keyword, semantic, or hybrid search over ingested chunks
Search {
/// Query string (whitespace-delimited tokens, implicit AND for keyword mode)
query: String,
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Maximum number of results to return
#[arg(long, default_value_t = 10)]
limit: usize,
/// Only include hits whose source kind matches exactly
/// (e.g. text/markdown, text/plain, application/jsonl)
#[arg(long)]
kind: Option<String>,
/// Only include hits whose source path or URI contains this substring
#[arg(long)]
path: Option<String>,
/// Output format: summary (compact, default), text (per-hit
/// provenance block), or json (machine-readable envelope)
#[arg(long, value_enum, default_value_t = SearchFormat::Summary)]
format: SearchFormat,
/// Use dense-embedding cosine similarity instead of FTS5 keyword search
#[arg(long, conflicts_with = "hybrid")]
semantic: bool,
/// Use the vec0-backed semantic helper instead of the brute-force path
#[arg(long, conflicts_with_all = ["semantic", "hybrid"])]
vec_semantic: bool,
/// Blend keyword BM25 with semantic cosine similarity
#[arg(long)]
hybrid: bool,
/// Ollama embedding model (semantic/hybrid mode)
#[arg(long, default_value = embed::DEFAULT_EMBED_MODEL)]
model: String,
/// Query-side instruction override for supported embedding models
#[arg(long)]
instruction: Option<String>,
/// Ollama base URL (semantic/hybrid mode)
#[arg(long, default_value = embed::DEFAULT_OLLAMA_URL)]
ollama_url: String,
},
/// Expose Lantern over the Model Context Protocol (stdio by default).
Mcp {
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Listen on this TCP port instead of stdio (for debugging with
/// MCP clients that can't launch a child process).
#[arg(long)]
port: Option<u16>,
},
/// Alias for `search` tuned for broader exploration: defaults to a
/// limit of 20 and the compact summary format. Supports the same
/// filters as `search`.
Query {
/// Query string (whitespace-delimited tokens, implicit AND)
query: String,
/// Override the store directory (default: nearest ancestor .lantern)
#[arg(long)]
store: Option<PathBuf>,
/// Maximum number of results to return
#[arg(long, default_value_t = 20)]
limit: usize,
/// Only include hits whose source kind matches exactly
#[arg(long)]
kind: Option<String>,
/// Only include hits whose source path or URI contains this substring
#[arg(long)]
path: Option<String>,
/// Output format
#[arg(long, value_enum, default_value_t = SearchFormat::Summary)]
format: SearchFormat,
},
}
#[derive(ValueEnum, Debug, Clone, Copy)]
pub enum Format {
Text,
Json,
}
#[derive(ValueEnum, Debug, Clone, Copy)]
pub enum FeedbackVote {
Up,
Down,
}
impl FeedbackVote {
fn as_feedback(self) -> feedback::Feedback {
match self {
FeedbackVote::Up => feedback::Feedback::Up,
FeedbackVote::Down => feedback::Feedback::Down,
}
}
}
#[derive(ValueEnum, Debug, Clone, Copy)]
pub enum SearchFormat {
/// Compact human-readable summary (default)
Summary,
/// Detailed text block per hit, with byte range and highlighted snippet
Text,
/// JSON envelope with query and full hit list
Json,
}
pub fn run(cli: Cli) -> Result<()> {
match cli.command {
Command::Version => {
println!("lantern {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
Command::Init { path } => {
let dir = path.unwrap_or_else(|| PathBuf::from(DEFAULT_STORE_DIRNAME));
let store = Store::initialize(&dir)
.with_context(|| format!("failed to initialize store at {}", dir.display()))?;
println!("lantern store initialized at {}", store.root().display());
Ok(())
}
Command::Ingest {
path,
stdin,
uri,
kind,
append,
store: store_override,
no_ignore,
follow,
follow_interval_secs,
follow_idle_timeout_secs,
format,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let mut store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
if stdin {
let uri = uri.ok_or_else(|| {
anyhow::anyhow!("--stdin requires --uri to label the incoming content")
})?;
let mut bytes = Vec::new();
std::io::Read::read_to_end(&mut std::io::stdin().lock(), &mut bytes)
.context("reading stdin")?;
let stdin_opts = ingest::StdinIngestOptions { append };
let report = ingest::ingest_stdin_with(
&mut store,
&uri,
kind.as_deref(),
&bytes,
&stdin_opts,
)?;
match format {
Format::Text => ingest::print_text(&report),
Format::Json => ingest::print_json(&report)?,
}
return Ok(());
}
let path = path
.ok_or_else(|| anyhow::anyhow!("provide a file/directory path or use --stdin"))?;
let opts = ingest::IngestOptions { no_ignore };
if follow {
if matches!(format, Format::Json) {
anyhow::bail!("--format json is not supported with --follow");
}
let mut follow_opts = ingest::FollowOptions::new(std::time::Duration::from_secs(
follow_interval_secs,
));
follow_opts.idle_timeout =
follow_idle_timeout_secs.map(std::time::Duration::from_secs);
println!(
"following {} every {}s (Ctrl-C to stop)",
path.display(),
follow_interval_secs
);
match ingest::follow_path_with(
&mut store,
&path,
&opts,
&follow_opts,
ingest::print_follow_pass,
)? {
ingest::FollowExit::MaxIterations => {
println!("follow loop exited after reaching max iterations");
}
ingest::FollowExit::IdleTimeout(timeout) => {
println!(
"follow loop exited after {}s of inactivity",
timeout.as_secs()
);
}
}
return Ok(());
}
let report = ingest::ingest_path_with(&mut store, &path, &opts)?;
match format {
Format::Text => ingest::print_text(&report),
Format::Json => ingest::print_json(&report)?,
}
Ok(())
}
Command::Diff {
path,
store: store_override,
format,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let report = diff::diff(&store, path.as_deref())?;
match format {
Format::Text => diff::print_text(&report),
Format::Json => diff::print_json(&report)?,
}
Ok(())
}
Command::Export {
store: store_override,
path,
query,
output,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let filter = export::ExportFilter {
path_contains: path,
query,
};
let dump = export::export(&store, &filter)?;
export::write_json(&dump, output.as_deref())?;
Ok(())
}
Command::Forget {
pattern,
store: store_override,
apply,
format,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let mut store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let report = forget::forget(&mut store, &pattern, apply)?;
match format {
Format::Text => forget::print_text(&report),
Format::Json => forget::print_json(&report)?,
}
Ok(())
}
Command::Inspect {
store: store_override,
limit,
format,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let report = inspect::inspect(
&store,
inspect::InspectOptions {
recent_limit: limit,
},
)?;
match format {
Format::Text => inspect::print_text(&report),
Format::Json => inspect::print_json(&report)?,
}
Ok(())
}
Command::Stash {
store: store_override,
format,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let mut store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let report = stash::stash(&mut store)?;
match format {
Format::Text => stash::print_text(&report),
Format::Json => stash::print_json(&report)?,
}
Ok(())
}
Command::Feedback {
chunk_id,
vote,
store: store_override,
format,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let report = feedback::apply_feedback(&store, &chunk_id, vote.as_feedback())?;
match format {
Format::Text => feedback::print_text(&report),
Format::Json => feedback::print_json(&report)?,
}
Ok(())
}
Command::Compact {
store: store_override,
half_life_secs,
minimum_age_secs,
format,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let mut store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let report = compact::compact_access_metadata(
&mut store,
compact::CompactOptions {
half_life_secs,
minimum_age_secs,
},
)?;
match format {
Format::Text => compact::print_text(&report),
Format::Json => compact::print_json(&report)?,
}
Ok(())
}
Command::Reindex {
store: store_override,
format,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let mut store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let report = reindex::reindex(&mut store)?;
match format {
Format::Text => reindex::print_text(&report),
Format::Json => reindex::print_json(&report)?,
}
Ok(())
}
Command::Show {
id,
store: store_override,
format,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let source = show::show(&store, &id)?;
match format {
Format::Text => show::print_text(&source),
Format::Json => show::print_json(&source)?,
}
Ok(())
}
Command::Embed {
store: store_override,
model,
ollama_url,
limit,
format,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
let mut store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let report = embed::embed_missing(
&mut store,
&embed::EmbedOptions {
model,
ollama_url,
limit,
},
)?;
match format {
Format::Text => embed::print_text(&report),
Format::Json => embed::print_json(&report)?,
}
Ok(())
}
Command::Search {
query,
store: store_override,
limit,
kind,
path,
format,
semantic,
vec_semantic,
hybrid,
model,
instruction,
ollama_url,
} => run_search(SearchInvocation {
store_override,
query,
limit,
kind,
path_contains: path,
format,
mode: if hybrid {
SearchMode::Hybrid
} else if vec_semantic {
SearchMode::VecSemantic
} else if semantic {
SearchMode::Semantic
} else {
SearchMode::Keyword
},
instruction,
model,
ollama_url,
}),
Command::Mcp {
store: store_override,
port,
} => {
let store_dir = resolve_store_dir(store_override.as_deref())?;
// Open once eagerly to surface a clear error if the store is
// missing or unopenable, then close — the MCP tools open their
// own connections as needed.
Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
mcp::run(store_dir, port)
}
Command::Query {
query,
store: store_override,
limit,
kind,
path,
format,
} => run_search(SearchInvocation {
store_override,
query,
limit,
kind,
path_contains: path,
format,
mode: SearchMode::Keyword,
instruction: None,
model: embed::DEFAULT_EMBED_MODEL.to_string(),
ollama_url: embed::DEFAULT_OLLAMA_URL.to_string(),
}),
}
}
enum SearchMode {
Keyword,
Semantic,
VecSemantic,
Hybrid,
}
struct SearchInvocation {
store_override: Option<PathBuf>,
query: String,
limit: usize,
kind: Option<String>,
path_contains: Option<String>,
format: SearchFormat,
mode: SearchMode,
instruction: Option<String>,
model: String,
ollama_url: String,
}
fn run_search(inv: SearchInvocation) -> Result<()> {
let store_dir = resolve_store_dir(inv.store_override.as_deref())?;
let store = Store::open(&store_dir)
.with_context(|| format!("failed to open store at {}", store_dir.display()))?;
let model = inv.model;
let hits = match inv.mode {
SearchMode::Keyword => search::search(
&store,
&inv.query,
search::SearchOptions {
limit: inv.limit,
kind: inv.kind,
path_contains: inv.path_contains,
},
)?,
SearchMode::Semantic => search::semantic_search(
&store,
&inv.query,
&search::SemanticOptions {
limit: inv.limit,
kind: inv.kind,
path_contains: inv.path_contains,
model: model.clone(),
ollama_url: inv.ollama_url,
instruction: inv.instruction.clone(),
},
)?,
SearchMode::VecSemantic => {
let client = embed::OllamaClient::new(&inv.ollama_url, &model)?;
search::vec_semantic_search_with(
&store,
&inv.query,
&search::SemanticOptions {
limit: inv.limit,
kind: inv.kind,
path_contains: inv.path_contains,
model: model.clone(),
ollama_url: inv.ollama_url,
instruction: inv.instruction.clone(),
},
&client,
)?
}
SearchMode::Hybrid => search::hybrid_search(
&store,
&inv.query,
&search::SemanticOptions {
limit: inv.limit,
kind: inv.kind,
path_contains: inv.path_contains,
model: model.clone(),
ollama_url: inv.ollama_url,
instruction: inv.instruction.clone(),
},
)?,
};
match inv.format {
SearchFormat::Summary => search::print_summary(&inv.query, &hits),
SearchFormat::Text => search::print_text(&inv.query, &hits),
SearchFormat::Json => {
let model = match inv.mode {
SearchMode::Keyword => None,
SearchMode::Semantic | SearchMode::VecSemantic | SearchMode::Hybrid => {
Some(model.as_str())
}
};
search::print_json(&inv.query, model, &hits)?
}
}
Ok(())
}
fn resolve_store_dir(explicit: Option<&Path>) -> Result<PathBuf> {
if let Some(p) = explicit {
return Ok(p.to_path_buf());
}
let cwd = std::env::current_dir().context("reading current working directory")?;
let mut cursor: &Path = cwd.as_path();
loop {
let candidate = cursor.join(DEFAULT_STORE_DIRNAME);
if candidate.join(store::DB_FILENAME).exists() {
return Ok(candidate);
}
match cursor.parent() {
Some(p) => cursor = p,
None => {
anyhow::bail!(
"no lantern store found above {}; run `lantern init` first or pass --store",
cwd.display()
)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn search_accepts_vec_semantic_flag() {
let parsed = Cli::try_parse_from(["lantern", "search", "needle", "--vec-semantic"]);
assert!(parsed.is_ok(), "expected --vec-semantic to parse");
}
#[test]
fn feedback_parses_up_and_down_votes() {
let parsed = Cli::try_parse_from(["lantern", "feedback", "abc123", "up"]).unwrap();
match parsed.command {
Command::Feedback { chunk_id, vote, .. } => {
assert_eq!(chunk_id, "abc123");
assert!(matches!(vote, FeedbackVote::Up));
}
other => panic!("unexpected command: {other:?}"),
}
let parsed = Cli::try_parse_from(["lantern", "feedback", "abc123", "down"]).unwrap();
assert!(matches!(
parsed.command,
Command::Feedback {
vote: FeedbackVote::Down,
..
}
));
}
#[test]
fn feedback_rejects_missing_vote() {
let parsed = Cli::try_parse_from(["lantern", "feedback", "abc123"]);
assert!(parsed.is_err(), "vote arg should be required");
}
#[test]
fn search_accepts_instruction_override() {
let parsed = Cli::try_parse_from([
"lantern",
"search",
"needle",
"--semantic",
"--instruction",
"find relevant docs",
])
.unwrap();
match parsed.command {
Command::Search { instruction, .. } => {
assert_eq!(instruction.as_deref(), Some("find relevant docs"));
}
other => panic!("unexpected command: {other:?}"),
}
}
}