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
use std::path::PathBuf;
use clap::{ArgAction, Subcommand};
use serde::{Deserialize, Serialize};
use crate::mcp::handlers::QueryMode;
use crate::types::ChunkType;
/// Export output format.
#[derive(Debug, Clone, Copy, clap::ValueEnum, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExportFormat {
/// Human-readable Markdown.
Markdown,
/// Pretty JSON array of chunks.
Json,
/// JSON lines (one chunk per line).
Jsonl,
}
/// Read-scope mode for tenant memory access guardrails.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TenantScopeMode {
/// Only read from the current tenant.
Local,
/// Read from all discovered tenants in the configured data directory.
Global,
/// Read only from explicitly allowed tenants.
Allowlist,
}
/// Retrieval intent for CLI search/orchestration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[value(rename_all = "snake_case")]
pub enum CliQueryMode {
Generic,
BriefProject,
ResumeTask,
FindFailures,
FindDecisions,
FindEvidence,
FindHighlights,
}
/// Warm-worker behavior for agent-facing CLI retrieval and local tool calls.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WarmMode {
/// Use the local warm worker, starting it if needed; fall back to cold CLI if startup fails.
Auto,
/// Always run in the current CLI process.
Off,
/// Require a local warm worker; fail if it cannot be started or reached.
Required,
}
/// Optional post-retrieval reranker for CLI search.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SearchReranker {
/// Keep the built-in retrieval order.
None,
/// Use MemReranker-4B only when the optional runtime is available.
Auto,
/// Require MemReranker-4B; fail instead of falling back.
#[value(name = "memreranker-4b")]
#[serde(rename = "memreranker-4b")]
MemReranker4B,
}
/// Administrative warm-worker commands.
#[derive(Debug, Clone, Subcommand)]
pub enum WarmCommand {
/// Start the local warm worker if it is not already running.
Start,
/// Report whether the local warm worker is reachable.
Status,
/// Ask the local warm worker to stop.
Stop,
}
/// Process identity for a local warm worker.
#[derive(Debug, Clone)]
pub struct WarmProcessConfig {
pub data_dir: PathBuf,
pub config_path: Option<PathBuf>,
pub embedding_model: String,
pub search_variant: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(super) struct SearchRerankerOptions {
pub(super) reranker: SearchReranker,
pub(super) model: String,
pub(super) device: String,
pub(super) batch_size: usize,
pub(super) timeout_seconds: u64,
pub(super) python: String,
}
impl From<CliQueryMode> for QueryMode {
fn from(value: CliQueryMode) -> Self {
match value {
CliQueryMode::Generic => QueryMode::Generic,
CliQueryMode::BriefProject => QueryMode::BriefProject,
CliQueryMode::ResumeTask => QueryMode::ResumeTask,
CliQueryMode::FindFailures => QueryMode::FindFailures,
CliQueryMode::FindDecisions => QueryMode::FindDecisions,
CliQueryMode::FindEvidence => QueryMode::FindEvidence,
CliQueryMode::FindHighlights => QueryMode::FindHighlights,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(super) struct TenantScopeConfig {
pub(super) primary_tenant: String,
pub(super) write_tenant: String,
pub(super) scope: TenantScopeMode,
/// Optional explicit allowlist (used when scope=allowlist)
#[serde(default)]
pub(super) allow_tenants: Vec<String>,
/// Effective read tenants for retrieval
#[serde(default)]
pub(super) read_tenants: Vec<String>,
/// Data directory used for global tenant discovery
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) data_dir: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(super) struct ProjectScopeConfig {
pub(super) tenant_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) project_id: Option<String>,
#[serde(default)]
pub(super) read_tenants: Vec<String>,
pub(super) interface: String,
pub(super) cli_command: String,
pub(super) agent_context_output: String,
pub(super) project_dir: String,
}
/// CLI subcommands for memory operations
#[derive(Debug, Clone, Subcommand)]
pub enum CliCommand {
/// Add a memory chunk
Add {
/// Tenant identifier
#[arg(long)]
tenant_id: String,
/// Text content of the chunk
#[arg(long)]
text: String,
/// Type of chunk (code, doc, trace, decision, plan, research, message, summary, other)
#[arg(long, value_parser = parse_chunk_type)]
chunk_type: ChunkType,
/// Optional project identifier
#[arg(long)]
project_id: Option<String>,
/// Optional tags (comma-separated)
#[arg(long, value_delimiter = ',')]
tags: Option<Vec<String>>,
/// Optional source URI
#[arg(long)]
source_uri: Option<String>,
/// Optional source path
#[arg(long)]
source_path: Option<String>,
},
/// Search memory chunks
Search {
/// Tenant identifier
#[arg(long)]
tenant_id: String,
/// Search query
#[arg(long)]
query: String,
/// Maximum number of results
#[arg(long, default_value = "10")]
k: usize,
/// Optional project identifier
#[arg(long)]
project_id: Option<String>,
/// Use memory.search compact shaping instead of the legacy raw chunk array
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
compact: bool,
/// Approximate result token budget; also enables compact shaping
#[arg(long)]
token_budget: Option<usize>,
/// Retrieval intent for digest-biased searches
#[arg(long, value_enum, default_value = "generic")]
mode: CliQueryMode,
/// Omit chunk text from compact output
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
no_text: bool,
/// Include linked canonical artifacts in compact output
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
include_artifact: bool,
/// Include superseded chunks (hidden by default) — for
/// provenance lookups of consolidated lessons.
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
include_superseded: bool,
/// Output format
#[arg(long, value_enum, default_value = "json")]
format: ExportFormat,
/// Output file path (defaults to stdout)
#[arg(long)]
output: Option<PathBuf>,
/// Optional high-quality post-retrieval reranker
#[arg(long, value_enum, default_value = "none")]
reranker: SearchReranker,
/// Hugging Face model id for the optional MemReranker path
#[arg(long, default_value = "IAAR-Shanghai/MemReranker-4B")]
reranker_model: String,
/// Device for the optional MemReranker path: auto, cuda, cuda:0, or cpu
#[arg(long, default_value = "auto")]
reranker_device: String,
/// Batch size for optional MemReranker inference
#[arg(long, default_value = "1")]
reranker_batch_size: usize,
/// Timeout in seconds for optional MemReranker model load and inference
#[arg(long, default_value = "120")]
reranker_timeout_seconds: u64,
/// Python executable used by the optional MemReranker path
#[arg(long, default_value = "python3")]
reranker_python: String,
/// Use the local warm worker for this operation
#[arg(long, value_enum, default_value = "auto")]
warm: WarmMode,
},
/// Build a bounded local context file for agents using CLI-only retrieval.
///
/// This is the preferred CLI-only orchestration path: a controller runs
/// retrieval before launching the agent, writes a compact context file
/// into the workspace, and the agent reads that file during the solve.
AgentContext {
/// Tenant identifier
#[arg(long)]
tenant_id: String,
/// Optional project identifier
#[arg(long)]
project_id: Option<String>,
/// Search query. May be repeated; results are merged and deduplicated.
#[arg(long, required = true, action = ArgAction::Append)]
query: Vec<String>,
/// Maximum results per query before deduplication
#[arg(long, default_value = "2")]
k: usize,
/// Approximate token budget per query
#[arg(long, default_value = "700")]
token_budget: usize,
/// Retrieval intent for digest-biased searches
#[arg(long, value_enum, default_value = "generic")]
mode: CliQueryMode,
/// Omit chunk text from compact output
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
no_text: bool,
/// Include linked canonical artifacts in compact output
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
include_artifact: bool,
/// Output format
#[arg(long, value_enum, default_value = "markdown")]
format: ExportFormat,
/// Output file path (defaults to stdout)
#[arg(long)]
output: Option<PathBuf>,
/// Optional directory for benchmark/audit JSON logs
#[arg(long)]
log_dir: Option<PathBuf>,
/// Use the local warm worker for this operation
#[arg(long, value_enum, default_value = "auto")]
warm: WarmMode,
},
/// Refresh a project `memory.md` file with the highest-priority takeaways.
///
/// This is intended for agent session startup. It distills up to 10
/// project-scoped takeaways and up to 10 machine-wide takeaways from memd,
/// writes them to `memory.md`, and prints a JSON summary.
MemoryMd {
/// Tenant identifier. Defaults to `.memd/project_scope.json` when present.
#[arg(long)]
tenant_id: Option<String>,
/// Optional project identifier. Defaults to `.memd/project_scope.json`.
#[arg(long)]
project_id: Option<String>,
/// Project directory containing `.memd/project_scope.json`
#[arg(long, default_value = ".")]
project_dir: PathBuf,
/// Output path. Relative paths are resolved under `--project-dir`.
#[arg(long, default_value = "memory.md")]
output: PathBuf,
/// Maximum project-specific takeaways to keep, capped at 10
#[arg(long, default_value_t = 10)]
project_limit: usize,
/// Maximum machine-wide takeaways to keep, capped at 10
#[arg(long, default_value_t = 10)]
global_limit: usize,
/// Candidate memories to retrieve per query before scoring
#[arg(long, default_value_t = 40)]
candidate_k: usize,
/// Render a `## Cross-Tenant Takeaways` section sourced from
/// `kind:consolidated, priority>=8` chunks across every
/// tenant under the data root.
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
cross_tenant: bool,
},
/// Consolidate recent memory chunks into deduplicated lessons.
///
/// Builds a working region from chunks written/retrieved since the
/// last run, asks the configured LLM consolidator to rewrite them,
/// persists `kind:consolidated` lessons, and soft-tombstones the
/// superseded sources. Backend is chosen by `MEMD_CONSOLIDATOR`.
Consolidate {
/// Tenant identifier. Defaults to `.memd/project_scope.json`
/// or `.memd/config.json` when present.
#[arg(long)]
tenant_id: Option<String>,
/// Optional project identifier. Defaults to the scope file.
#[arg(long)]
project_id: Option<String>,
/// Project directory containing the `.memd` scope/state files.
#[arg(long, default_value = ".")]
project_dir: PathBuf,
/// Maximum chunks in the consolidation working region.
#[arg(long, default_value_t = 50)]
max_region: usize,
/// Build and print the prompt without calling the LLM.
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
dry_run: bool,
/// Run consolidation in a detached background process.
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
background: bool,
/// Consolidate even when the region is below the threshold.
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
force: bool,
/// Promote consolidated lessons that span ≥2 distinct
/// projects to `MEMD_SHARED_TENANT` (default `shared`).
/// OFF by default — never crosses the tenant boundary
/// without an explicit opt-in.
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
promote_to_shared: bool,
},
/// Counterfactual retrieval eval (Phase 3).
///
/// For each query in the benchmark file, runs retrieval twice
/// (full bank vs. `kind:consolidated`-filtered) and reports the
/// overlap@k loss and mean rank shift. Writes a Markdown report
/// under `evals/bench/reports/`.
EvalCounterfactual {
/// Tenant identifier.
#[arg(long)]
tenant_id: String,
/// Optional project identifier.
#[arg(long)]
project_id: Option<String>,
/// Project directory (resolves default queries file).
#[arg(long, default_value = ".")]
project_dir: PathBuf,
/// Path to the JSONL queries file. Defaults to
/// `evals/bench/queries/counterfactual_queries.jsonl` under
/// the project directory.
#[arg(long)]
queries: Option<PathBuf>,
/// Top-k for retrieval comparison.
#[arg(long, default_value_t = 5)]
k: usize,
},
/// Session-start hook entry point.
///
/// Refreshes `memory.md` synchronously and, when enough chunks
/// have accumulated, spawns a detached background consolidation.
/// Safe to wire into a SessionStart hook for every repo: a
/// missing `.memd` scope is a clean no-op.
SessionStart {
/// Project directory containing the `.memd` scope/state files.
#[arg(long, default_value = ".")]
project_dir: PathBuf,
},
/// Invoke a local memd operation by its historical tool name.
///
/// This preserves the former structured operation surface without starting
/// an external service. Pass a JSON object with `--json` or `--input`; omit both for
/// `{}`. The result is unwrapped to the operation payload when possible.
Call {
/// Operation name, for example `memory.search` or `task.start`
tool: String,
/// JSON object containing operation arguments
#[arg(long, conflicts_with = "input")]
json: Option<String>,
/// File containing a JSON object with operation arguments
#[arg(long, conflicts_with = "json")]
input: Option<PathBuf>,
/// Output file path (defaults to stdout)
#[arg(long)]
output: Option<PathBuf>,
/// Use the local warm worker for this operation
#[arg(long, value_enum, default_value = "auto")]
warm: WarmMode,
},
/// Run local operation calls from JSONL in one process.
///
/// Each non-empty input line must be a JSON object with `tool` and
/// optional `arguments`. Results are emitted as JSONL with one row
/// per input line.
Batch {
/// JSONL input file. Omit or pass `-` to read stdin.
#[arg(long)]
jsonl: Option<PathBuf>,
/// Keep stdin/stdout open and process one JSONL request per line.
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
stream: bool,
/// Keep processing after a failed input line or operation.
#[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
continue_on_error: bool,
/// Output file path (defaults to stdout)
#[arg(long)]
output: Option<PathBuf>,
},
/// Manage the local warm worker used by `--warm auto|required`.
Warm {
#[command(subcommand)]
command: WarmCommand,
},
/// Internal warm worker entrypoint. Not an agent-facing interface.
#[command(hide = true)]
WarmWorker {
/// Unix socket path to listen on.
#[arg(long)]
socket: PathBuf,
},
/// Get a chunk by ID
Get {
/// Tenant identifier
#[arg(long)]
tenant_id: String,
/// Chunk identifier (UUID)
#[arg(long)]
chunk_id: String,
},
/// Delete a chunk (soft delete)
Delete {
/// Tenant identifier
#[arg(long)]
tenant_id: String,
/// Chunk identifier (UUID)
#[arg(long)]
chunk_id: String,
},
/// Show statistics for a tenant
Stats {
/// Tenant identifier
#[arg(long)]
tenant_id: String,
},
/// Export all tenant chunks in a human-readable or machine-readable format
Export {
/// Tenant identifier
#[arg(long)]
tenant_id: String,
/// Export format
#[arg(long, value_enum, default_value = "markdown")]
format: ExportFormat,
/// Output file path (defaults to stdout when omitted)
#[arg(long)]
output: Option<PathBuf>,
/// Pagination size for chunk collection
#[arg(long, default_value_t = 500)]
page_size: usize,
},
/// Export tenant chunks as a tree of markdown files.
///
/// Uses G1's `render_markdown_tree` (one file per `(project, chunk_type)`
/// bucket) and writes each `(path, content)` under `<outdir>` on the
/// user's machine. Refuses to write if the normalised `<outdir>` is a
/// descendant of memd's data directory, because writing a markdown tree
/// into `$MEMD_DATA_DIR` would silently corrupt segment / SQLite layouts.
ExportMarkdown {
/// Tenant identifier
#[arg(long)]
tenant_id: String,
/// Output directory. Created if missing. Must not be inside memd's
/// data directory.
#[arg(long)]
outdir: PathBuf,
/// Optional project filter
#[arg(long)]
project_id: Option<String>,
/// Include history-tier rows (default: live-only)
#[arg(long, default_value_t = false, action = ArgAction::Set)]
include_history: bool,
/// Data directory used for the containment guard. Defaults to
/// `~/.memd/data`; typically set by a wrapper when the daemon's
/// data dir lives elsewhere.
#[arg(long)]
data_dir: Option<PathBuf>,
},
/// Export tenant memory as an OMF 1.0 JSON document.
///
/// Writes to `--output` if provided, else stdout. The opened path is
/// honoured as-is; CLI callers are already on the writer side, so there
/// is no data-dir containment guard.
ExportOmf {
/// Tenant identifier
#[arg(long)]
tenant_id: String,
/// Optional project filter
#[arg(long)]
project_id: Option<String>,
/// Output file path (defaults to stdout when omitted)
#[arg(long)]
output: Option<PathBuf>,
/// Include history-tier rows (default: live-only)
#[arg(long, default_value_t = false, action = ArgAction::Set)]
include_history: bool,
/// Include rows whose status is Superseded
#[arg(long, default_value_t = true, action = ArgAction::Set)]
include_superseded: bool,
/// Include rows whose status is Expired (or whose expires_at_ms has passed)
#[arg(long, default_value_t = true, action = ArgAction::Set)]
include_expired: bool,
},
/// Import an OMF 1.0 JSON document into a tenant.
///
/// Reads the document from `--input` (or stdin if `-` / omitted).
/// Use `--dry-run` for a read-only preview that reports counts
/// without writing.
ImportOmf {
/// Tenant identifier
#[arg(long)]
tenant_id: String,
/// Input file path. `-` or omitted reads from stdin.
#[arg(long)]
input: Option<PathBuf>,
/// Include items whose top-level status is "archived" or "expired"
#[arg(long, default_value_t = true, action = ArgAction::Set)]
include_archived: bool,
/// Optional trigram Jaccard threshold. Absent = exact-canonical only.
#[arg(long)]
fuzzy_threshold: Option<f32>,
/// Preview only — compute counts without writing.
#[arg(long, default_value_t = false, action = ArgAction::Set)]
dry_run: bool,
},
/// Initialize memd CLI guardrails for agent workflows
Init {
/// Tenant identifier to enforce in generated policies
#[arg(long)]
tenant_id: String,
/// Tenant read scope mode
#[arg(long, value_enum, default_value = "local")]
scope: TenantScopeMode,
/// Comma-separated tenant allowlist (required with --scope allowlist)
#[arg(long, value_delimiter = ',')]
allow_tenants: Option<Vec<String>>,
/// Project directory where guardrail files will be written
#[arg(long, default_value = ".")]
project_dir: PathBuf,
/// Explicit project identifier to pin for this repository
#[arg(long)]
project_id: Option<String>,
/// memd CLI command used in generated guardrails
#[arg(long, default_value = "memd")]
memd_command: String,
/// Optional data directory used for tenant scope discovery and docs
#[arg(long)]
memd_data_dir: Option<PathBuf>,
/// Write/refresh AGENTS.md and CLAUDE.md guardrail sections
#[arg(long, default_value_t = true, action = ArgAction::Set)]
write_agent_files: bool,
},
/// Diagnose host wiring and per-repo scope.
///
/// Reports the state of: `memd` binary discovery, data directory,
/// global agent rules (Claude / Codex / Cursor), Claude
/// `SessionStart` hook, and the current project's `.memd`
/// scope. Always exits 0; use `--format json` for machine-readable
/// output.
Doctor {
/// Project directory to inspect for `.memd/project_scope.json`.
#[arg(long, default_value = ".")]
project_dir: PathBuf,
/// Output format. `markdown` (default) renders a human-readable
/// report with stable `[ok]`/`[--]` prefixes; `json` emits the
/// raw structured report.
#[arg(long, value_enum, default_value = "markdown")]
format: ExportFormat,
},
/// Disk hygiene: sweep orphan HNSW snapshots, repack legacy mapping
/// files, and (with --aggressive) trigger optional compaction
/// hooks. Safe to run while no writer process is active; concurrent
/// writers may race on warm_index files and should be quiesced
/// first. Output is machine-greppable (key: value lines) so it can
/// be wired into ops scripts.
Maintenance {
/// Data directory (defaults to the top-level --data-dir or
/// ~/.memd/data).
#[arg(long)]
data_dir: Option<PathBuf>,
/// Restrict to a single tenant directory. Omit to scan all
/// tenants.
#[arg(long)]
tenant_id: Option<String>,
/// Report what would change without modifying disk.
#[arg(long)]
dry_run: bool,
/// Run the full pass: orphan sweep + segment compaction hooks
/// + mapping repack. Implies more I/O than the default sweep.
#[arg(long)]
aggressive: bool,
},
}
impl CliCommand {
/// Whether this command needs an initialized backing store.
pub fn requires_store(&self) -> bool {
!matches!(
self,
CliCommand::Init { .. }
| CliCommand::Warm { .. }
| CliCommand::Maintenance { .. }
| CliCommand::Doctor { .. }
)
}
/// Warm mode for commands that can be served by the local warm worker.
pub fn warm_mode(&self) -> Option<WarmMode> {
match self {
CliCommand::Search { warm, .. }
| CliCommand::AgentContext { warm, .. }
| CliCommand::Call { warm, .. } => Some(*warm),
_ => None,
}
}
}
/// Parse chunk type from string
pub(super) fn parse_chunk_type(s: &str) -> std::result::Result<ChunkType, String> {
match s.to_lowercase().as_str() {
"code" => Ok(ChunkType::Code),
"doc" => Ok(ChunkType::Doc),
"trace" => Ok(ChunkType::Trace),
"decision" => Ok(ChunkType::Decision),
"plan" => Ok(ChunkType::Plan),
"research" => Ok(ChunkType::Research),
"message" => Ok(ChunkType::Message),
"summary" => Ok(ChunkType::Summary),
"other" => Ok(ChunkType::Other),
_ => Err(format!(
"invalid chunk type '{}', must be one of: code, doc, trace, decision, plan, research, message, summary, other",
s
)),
}
}