memd/cli/args.rs
1use std::path::PathBuf;
2
3use clap::{ArgAction, Subcommand};
4use serde::{Deserialize, Serialize};
5
6use crate::mcp::handlers::QueryMode;
7use crate::types::ChunkType;
8
9/// Export output format.
10#[derive(Debug, Clone, Copy, clap::ValueEnum, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12pub enum ExportFormat {
13 /// Human-readable Markdown.
14 Markdown,
15 /// Pretty JSON array of chunks.
16 Json,
17 /// JSON lines (one chunk per line).
18 Jsonl,
19}
20
21/// Report output format.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum ReportFormat {
25 /// Human-readable Markdown.
26 Markdown,
27 /// Pretty JSON report.
28 Json,
29}
30
31/// Retrieval intent for CLI search/orchestration.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34#[value(rename_all = "snake_case")]
35pub enum CliQueryMode {
36 Generic,
37 BriefProject,
38 ResumeTask,
39 FindFailures,
40 FindDecisions,
41 FindEvidence,
42 FindHighlights,
43}
44
45/// Warm-worker behavior for agent-facing CLI retrieval and local tool calls.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
47#[serde(rename_all = "snake_case")]
48pub enum WarmMode {
49 /// Use the local warm worker, starting it if needed; fall back to cold CLI if startup fails.
50 Auto,
51 /// Always run in the current CLI process.
52 Off,
53 /// Require a local warm worker; fail if it cannot be started or reached.
54 Required,
55}
56
57/// Optional post-retrieval reranker for CLI search.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum SearchReranker {
61 /// Keep the built-in retrieval order.
62 None,
63 /// Use MemReranker-4B only when the optional runtime is available.
64 Auto,
65 /// Require MemReranker-4B; fail instead of falling back.
66 #[value(name = "memreranker-4b")]
67 #[serde(rename = "memreranker-4b")]
68 MemReranker4B,
69}
70
71/// Native hook payload format accepted by `session-start`.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
73pub enum NativeHookHarness {
74 Claude,
75 Codex,
76}
77
78/// Administrative warm-worker commands.
79#[derive(Debug, Clone, Subcommand)]
80pub enum WarmCommand {
81 /// Start the local warm worker if it is not already running.
82 Start,
83 /// Report whether the local warm worker is reachable.
84 Status,
85 /// Ask the local warm worker to stop.
86 Stop,
87}
88
89/// Process identity for a local warm worker.
90#[derive(Debug, Clone)]
91pub struct WarmProcessConfig {
92 pub data_dir: PathBuf,
93 pub config_path: Option<PathBuf>,
94 pub embedding_model: String,
95 pub search_variant: String,
96}
97
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub(super) struct SearchRerankerOptions {
100 pub(super) reranker: SearchReranker,
101 pub(super) model: String,
102 pub(super) device: String,
103 pub(super) batch_size: usize,
104 pub(super) timeout_seconds: u64,
105 pub(super) python: String,
106}
107
108impl From<CliQueryMode> for QueryMode {
109 fn from(value: CliQueryMode) -> Self {
110 match value {
111 CliQueryMode::Generic => QueryMode::Generic,
112 CliQueryMode::BriefProject => QueryMode::BriefProject,
113 CliQueryMode::ResumeTask => QueryMode::ResumeTask,
114 CliQueryMode::FindFailures => QueryMode::FindFailures,
115 CliQueryMode::FindDecisions => QueryMode::FindDecisions,
116 CliQueryMode::FindEvidence => QueryMode::FindEvidence,
117 CliQueryMode::FindHighlights => QueryMode::FindHighlights,
118 }
119 }
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub(super) struct TenantScopeConfig {
124 pub(super) primary_tenant: String,
125 pub(super) write_tenant: String,
126 /// Data directory used by export-markdown containment discovery
127 #[serde(skip_serializing_if = "Option::is_none")]
128 pub(super) data_dir: Option<String>,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub(super) struct ProjectScopeConfig {
133 pub(super) tenant_id: String,
134 #[serde(skip_serializing_if = "Option::is_none")]
135 pub(super) project_id: Option<String>,
136 pub(super) interface: String,
137 pub(super) cli_command: String,
138 pub(super) agent_context_output: String,
139 pub(super) project_dir: String,
140}
141
142/// CLI subcommands for memory operations
143#[derive(Debug, Clone, Subcommand)]
144pub enum CliCommand {
145 /// Linked problems, attempts, executed checks, and conditional lessons.
146 Experience {
147 #[arg(long, global = true)]
148 tenant_id: Option<String>,
149 #[arg(long, global = true)]
150 project_id: Option<String>,
151 #[arg(long, global = true)]
152 output: Option<PathBuf>,
153 #[arg(long, global = true, value_enum, default_value = "auto")]
154 warm: WarmMode,
155 #[command(subcommand)]
156 command: super::experience::ExperienceCommand,
157 },
158 /// Add a memory chunk
159 Add {
160 /// Tenant identifier
161 #[arg(long)]
162 tenant_id: Option<String>,
163
164 /// Text content of the chunk
165 #[arg(long)]
166 text: String,
167
168 /// Type of chunk (code, doc, trace, decision, plan, research, message, summary, other)
169 #[arg(long, value_parser = parse_chunk_type)]
170 chunk_type: ChunkType,
171
172 /// Optional project identifier
173 #[arg(long)]
174 project_id: Option<String>,
175
176 /// Optional tags (comma-separated)
177 #[arg(long, value_delimiter = ',')]
178 tags: Option<Vec<String>>,
179
180 /// Optional source URI
181 #[arg(long)]
182 source_uri: Option<String>,
183
184 /// Optional source path
185 #[arg(long)]
186 source_path: Option<String>,
187
188 /// Route this write through the local warm worker (auto starts one if needed; off runs locally and requires the writer lock; required fails when no worker is reachable)
189 #[arg(long, value_enum, default_value = "auto")]
190 warm: WarmMode,
191 },
192
193 /// Search memory chunks
194 Search {
195 /// Tenant identifier
196 #[arg(long)]
197 tenant_id: Option<String>,
198
199 /// Search query. Also accepts a bare positional argument.
200 #[arg(long, required_unless_present = "query_positional")]
201 query: Option<String>,
202
203 /// Search query given positionally (`memd search "<query>"`).
204 #[arg(value_name = "QUERY", conflicts_with = "query")]
205 query_positional: Option<String>,
206
207 /// Maximum number of results
208 #[arg(long, visible_alias = "limit", default_value = "10")]
209 k: usize,
210
211 /// Optional project identifier
212 #[arg(long)]
213 project_id: Option<String>,
214
215 /// Optional memd task identifier for retrieval-outcome attribution.
216 /// Defaults to MEMD_TASK_ID when that variable is set.
217 #[arg(long)]
218 task_id: Option<String>,
219
220 /// Optional native thread identifier for retrieval-outcome attribution.
221 /// Defaults to the calling client's observed native thread.
222 #[arg(long)]
223 thread_id: Option<String>,
224
225 /// Use memory.search compact shaping instead of the legacy raw chunk array
226 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
227 compact: bool,
228
229 /// Collapse results sharing a source URI to the best-ranked one, so
230 /// fragments of one document don't crowd out other relevant sources
231 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
232 dedupe_by_source: bool,
233
234 /// Approximate result token budget; also enables compact shaping
235 #[arg(long)]
236 token_budget: Option<usize>,
237
238 /// Retrieval intent for digest-biased searches
239 #[arg(long, value_enum, default_value = "generic")]
240 mode: CliQueryMode,
241
242 /// Omit chunk text from compact output
243 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
244 no_text: bool,
245
246 /// Include linked canonical artifacts in compact output
247 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
248 include_artifact: bool,
249
250 /// Include superseded chunks (hidden by default) — for
251 /// provenance lookups of consolidated lessons.
252 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
253 include_superseded: bool,
254
255 /// Output format
256 #[arg(long, value_enum, default_value = "json")]
257 format: ExportFormat,
258
259 /// Output file path (defaults to stdout)
260 #[arg(long)]
261 output: Option<PathBuf>,
262
263 /// Optional high-quality post-retrieval reranker
264 #[arg(long, value_enum, default_value = "none")]
265 reranker: SearchReranker,
266
267 /// Hugging Face model id for the optional MemReranker path
268 #[arg(long, default_value = "IAAR-Shanghai/MemReranker-4B")]
269 reranker_model: String,
270
271 /// Device for the optional MemReranker path: auto, cuda, cuda:0, or cpu
272 #[arg(long, default_value = "auto")]
273 reranker_device: String,
274
275 /// Batch size for optional MemReranker inference
276 #[arg(long, default_value = "1")]
277 reranker_batch_size: usize,
278
279 /// Timeout in seconds for optional MemReranker model load and inference
280 #[arg(long, default_value = "120")]
281 reranker_timeout_seconds: u64,
282
283 /// Python executable used by the optional MemReranker path
284 #[arg(long, default_value = "python3")]
285 reranker_python: String,
286
287 /// Use the local warm worker for this operation
288 #[arg(long, value_enum, default_value = "auto")]
289 warm: WarmMode,
290 },
291
292 /// Build a bounded local context file for agents using CLI-only retrieval.
293 ///
294 /// This is the preferred CLI-only orchestration path: a controller runs
295 /// retrieval before launching the agent, writes a compact context file
296 /// into the workspace, and the agent reads that file during the solve.
297 AgentContext {
298 /// Tenant identifier
299 #[arg(long)]
300 tenant_id: Option<String>,
301
302 /// Optional project identifier
303 #[arg(long)]
304 project_id: Option<String>,
305
306 /// Optional non-sensitive task identifier attached as plaintext.
307 #[arg(long)]
308 task_id: Option<String>,
309
310 /// Optional non-sensitive thread identifier attached as plaintext.
311 #[arg(long)]
312 thread_id: Option<String>,
313
314 /// Search query. May be repeated; results are merged and deduplicated.
315 #[arg(long, required = true, action = ArgAction::Append)]
316 query: Vec<String>,
317
318 /// Maximum results per query before deduplication
319 #[arg(long, default_value = "2")]
320 k: usize,
321
322 /// Approximate token budget per query
323 #[arg(long, default_value = "700")]
324 token_budget: usize,
325
326 /// Retrieval intent for digest-biased searches
327 #[arg(long, value_enum, default_value = "generic")]
328 mode: CliQueryMode,
329
330 /// Omit chunk text from compact output
331 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
332 no_text: bool,
333
334 /// Include linked canonical artifacts in compact output
335 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
336 include_artifact: bool,
337
338 /// Output format
339 #[arg(long, value_enum, default_value = "markdown")]
340 format: ExportFormat,
341
342 /// Output file path (defaults to stdout)
343 #[arg(long)]
344 output: Option<PathBuf>,
345
346 /// Optional directory for benchmark/audit JSON logs
347 #[arg(long)]
348 log_dir: Option<PathBuf>,
349
350 /// Use the local warm worker for this operation
351 #[arg(long, value_enum, default_value = "auto")]
352 warm: WarmMode,
353 },
354
355 /// Refresh a project `memory.md` file with the highest-priority takeaways.
356 ///
357 /// This is intended for agent session startup. It distills up to 10
358 /// project-scoped fact-library items from memd, writes them to `memory.md`,
359 /// and prints a JSON summary. Up to 2 machine-wide fact-library items are
360 /// included by default; tune with `--global-limit` (0 disables).
361 MemoryMd {
362 /// Tenant identifier. Defaults to `.memd/project_scope.json` when present.
363 #[arg(long)]
364 tenant_id: Option<String>,
365
366 /// Optional project identifier. Defaults to `.memd/project_scope.json`.
367 #[arg(long)]
368 project_id: Option<String>,
369
370 /// Project directory containing `.memd/project_scope.json`
371 #[arg(long, default_value = ".")]
372 project_dir: PathBuf,
373
374 /// Output path. Relative paths are resolved under `--project-dir`.
375 #[arg(long, default_value = "memory.md")]
376 output: PathBuf,
377
378 /// Maximum project-specific takeaways to keep, capped at 10
379 #[arg(long, default_value_t = 10)]
380 project_limit: usize,
381
382 /// Maximum machine-wide fact-library items to keep, capped at 10.
383 /// Defaults to 2; 0 disables the section.
384 #[arg(long, default_value_t = 2)]
385 global_limit: usize,
386
387 /// Unused since scan-first selection considers every stored
388 /// chunk; kept for CLI compatibility.
389 #[arg(long, default_value_t = 40)]
390 candidate_k: usize,
391
392 /// Optional JSON report explaining retrieved candidates,
393 /// priority score components, and display/filter decisions.
394 #[arg(long)]
395 explain_output: Option<PathBuf>,
396 },
397
398 /// Evaluate default `memory.md` startup quality against fixed thresholds.
399 EvalMemoryMd {
400 /// Tenant identifier. Defaults to `.memd/project_scope.json` when present.
401 #[arg(long)]
402 tenant_id: Option<String>,
403
404 /// Optional project identifier. Defaults to `.memd/project_scope.json`.
405 #[arg(long)]
406 project_id: Option<String>,
407
408 /// Project directory containing `.memd/project_scope.json`.
409 #[arg(long, default_value = ".")]
410 project_dir: PathBuf,
411
412 /// Output path for the generated memory.md under evaluation.
413 #[arg(long, default_value = "memory.md")]
414 output: PathBuf,
415
416 /// Maximum project-specific takeaways to evaluate, capped at 10.
417 #[arg(long, default_value_t = 10)]
418 project_limit: usize,
419
420 /// Unused since scan-first selection considers every stored
421 /// chunk; kept for CLI compatibility.
422 #[arg(long, default_value_t = 40)]
423 candidate_k: usize,
424
425 /// Number of displayed project takeaways included in useful-ratio scoring.
426 #[arg(long, default_value_t = 10)]
427 top_n: usize,
428
429 /// Minimum useful displayed-item ratio required for success.
430 #[arg(long, default_value_t = 0.8)]
431 min_useful_ratio: f64,
432
433 /// Maximum generated wrapper records allowed in displayed project items.
434 #[arg(long, default_value_t = 0)]
435 max_generated_wrappers: usize,
436
437 /// Enable structured startup-briefing usefulness checks.
438 #[arg(long)]
439 agent_usefulness: bool,
440
441 /// Optional JSON file with local project expectations.
442 #[arg(long)]
443 gold_file: Option<PathBuf>,
444 },
445
446 /// Evaluate fixed retrieval queries with known useful chunk IDs.
447 EvalRetrieval {
448 /// Tenant identifier.
449 #[arg(long)]
450 tenant_id: String,
451
452 /// Optional project identifier.
453 #[arg(long)]
454 project_id: Option<String>,
455
456 /// Project directory (resolves default queries and reports).
457 #[arg(long, default_value = ".")]
458 project_dir: PathBuf,
459
460 /// Path to JSONL queries with `query` and `useful_chunk_ids`.
461 #[arg(long)]
462 queries: Option<PathBuf>,
463
464 /// Top-k retrieval cutoff for precision and hit-rate metrics.
465 #[arg(long, default_value_t = 5)]
466 k: usize,
467
468 /// Minimum mean precision@k required for success. Defaults to 0
469 /// because bundled sparse judgments often cannot reach a fixed
470 /// precision threshold at k.
471 #[arg(long, default_value_t = 0.0)]
472 min_precision_at_k: f64,
473
474 /// Minimum fraction of queries with at least one useful hit.
475 #[arg(long, default_value_t = 1.0)]
476 min_hit_rate_at_k: f64,
477
478 /// Minimum mean recall over known useful chunk IDs.
479 #[arg(long, default_value_t = 0.0)]
480 min_known_recall_at_k: f64,
481
482 /// Minimum mean reciprocal rank of the first useful hit.
483 #[arg(long, default_value_t = 0.0)]
484 min_mrr: f64,
485 },
486
487 /// Evaluate synthetic write admission, dedupe, and storage-growth behavior.
488 EvalWriteQuality {
489 /// Project directory used only for the eval report output path.
490 #[arg(long, default_value = ".")]
491 project_dir: PathBuf,
492
493 /// Minimum low-value write rejection/downgrade rate.
494 #[arg(long, default_value_t = 1.0)]
495 min_rejection_or_downgrade_rate: f64,
496
497 /// Minimum exact duplicate reuse rate.
498 #[arg(long, default_value_t = 1.0)]
499 min_duplicate_reuse_rate: f64,
500
501 /// Maximum chunks a synthetic session may leave in its isolated store.
502 #[arg(long, default_value_t = 6)]
503 max_total_chunks: usize,
504
505 /// Maximum isolated persistent-store byte growth for the synthetic session.
506 #[arg(long, default_value_t = 5_000_000)]
507 max_disk_bytes: u64,
508
509 /// Require the synthetic retention/compaction stage to expire at least one row.
510 #[arg(long, default_value_t = true, action = ArgAction::Set)]
511 require_retention_compaction: bool,
512 },
513
514 /// Consolidate recent memory chunks into deduplicated lessons.
515 ///
516 /// Builds a working region from chunks written/retrieved since the
517 /// last run, asks the configured LLM consolidator to rewrite them,
518 /// and stages hidden `kind:consolidated` candidates for review.
519 /// Backend is chosen by `MEMD_CONSOLIDATOR`.
520 Consolidate {
521 /// Tenant identifier. Defaults to `.memd/project_scope.json`
522 /// or `.memd/config.json` when present.
523 #[arg(long)]
524 tenant_id: Option<String>,
525
526 /// Optional project identifier. Defaults to the scope file
527 /// only when --tenant-id is also omitted.
528 #[arg(long)]
529 project_id: Option<String>,
530
531 /// Project directory containing the `.memd` scope/state files.
532 #[arg(long, default_value = ".")]
533 project_dir: PathBuf,
534
535 /// Maximum chunks in the consolidation working region.
536 #[arg(long, default_value_t = 50)]
537 max_region: usize,
538
539 /// Build and print the prompt without calling the LLM.
540 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
541 dry_run: bool,
542
543 /// Run consolidation in a detached background process.
544 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
545 background: bool,
546
547 /// Consolidate even when the region is below the threshold.
548 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
549 force: bool,
550
551 /// Promote candidates after deterministic validation. Without this,
552 /// consolidation stops at a hidden validated candidate.
553 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
554 promote: bool,
555
556 /// Preserve the former immediate-promotion behavior for one release.
557 #[arg(long, default_value_t = false, action = ArgAction::SetTrue, conflicts_with = "promote")]
558 legacy_immediate: bool,
559
560 /// Route this write through the local warm worker (auto starts one if needed; off runs locally and requires the writer lock; required fails when no worker is reachable)
561 #[arg(long, value_enum, default_value = "auto")]
562 warm: WarmMode,
563 },
564
565 /// Inspect, accept, or reject a consolidation run.
566 ConsolidateReview {
567 /// Consolidation run UUID returned by `memd consolidate`.
568 run_id: Option<String>,
569
570 /// Optional tenant scope. Defaults to the current project scope when present.
571 #[arg(long)]
572 tenant_id: Option<String>,
573
574 /// Optional project scope. Defaults to the current project scope when present.
575 #[arg(long)]
576 project_id: Option<String>,
577
578 /// List validated runs awaiting review.
579 #[arg(long, action = ArgAction::SetTrue, conflicts_with_all = ["accept", "reject"])]
580 list: bool,
581
582 /// Maximum staged runs returned by --list.
583 #[arg(long, default_value_t = 100)]
584 limit: usize,
585
586 /// Promote the validated candidates and apply their lineage policy.
587 #[arg(long, action = ArgAction::SetTrue, conflicts_with_all = ["reject", "list"])]
588 accept: bool,
589
590 /// Reject the run and keep every candidate hidden.
591 #[arg(long, action = ArgAction::SetTrue, conflicts_with_all = ["accept", "list"])]
592 reject: bool,
593
594 /// Route accept/reject through the local warm worker when available.
595 #[arg(long, value_enum, default_value = "auto")]
596 warm: WarmMode,
597 },
598
599 /// Record a verified task outcome against one retrieval episode.
600 ///
601 /// Only chunks that were rendered in the named episode may be attributed.
602 /// Agent self-reports are retained for audit but never train ranking.
603 Outcome {
604 /// Retrieval episode UUID returned by search or agent-context.
605 episode_id: String,
606
607 /// Tenant identifier. Defaults to the current project scope.
608 #[arg(long)]
609 tenant_id: Option<String>,
610
611 /// Outcome: passed, accepted, corrected, failed, abandoned,
612 /// observed_used for non-ranking reuse, or verifier_error when the
613 /// verifier produced no verdict.
614 #[arg(long)]
615 outcome: String,
616
617 /// Verifier: user, automated_test, external_tool, task_system, or agent_self_report.
618 #[arg(long)]
619 verifier: String,
620
621 /// Rendered chunks that materially helped (comma-separated).
622 #[arg(long, value_delimiter = ',')]
623 used: Vec<String>,
624
625 /// Rendered chunks that caused harm or required correction (comma-separated).
626 #[arg(long, value_delimiter = ',')]
627 harmful: Vec<String>,
628
629 /// Non-sensitive reference to a durable test, task, or tool result.
630 #[arg(long)]
631 evidence: Option<String>,
632
633 /// Event time as Unix epoch milliseconds; defaults to now.
634 #[arg(long)]
635 event_time_ms: Option<i64>,
636
637 /// Route this write through the local warm worker.
638 #[arg(long, value_enum, default_value = "auto")]
639 warm: WarmMode,
640 },
641
642 /// Scan Codex session logs for observed memd retrieval reuse.
643 ///
644 /// Detects tool-call outputs that rendered a retrieval episode, then
645 /// records served chunks whose distinctive literals appear in later
646 /// tool-call inputs (commands or patches) of the same session. Writes
647 /// non-ranking `external_tool` `observed_used` events;
648 /// `.memd/data/outcome_scan_state.json` keeps re-runs from writing
649 /// duplicate events.
650 OutcomeScan {
651 /// Project directory containing `.memd/project_scope.json`.
652 #[arg(long, default_value = ".")]
653 project_dir: PathBuf,
654
655 /// Session log directory, scanned recursively for `*.jsonl` files.
656 /// Defaults to `~/.codex/sessions`.
657 #[arg(long)]
658 sessions_dir: Option<PathBuf>,
659
660 /// Only scan session files modified within this many days.
661 #[arg(long, default_value_t = 90)]
662 since_days: u64,
663
664 /// Report candidate outcome events without writing events or state.
665 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
666 dry_run: bool,
667 },
668
669 /// Counterfactual retrieval eval (Phase 3).
670 ///
671 /// For each query in the benchmark file, runs retrieval twice
672 /// (full bank vs. `kind:consolidated`-filtered) and reports the
673 /// overlap@k loss and mean rank shift. Writes a Markdown report
674 /// under `evals/bench/reports/`.
675 EvalCounterfactual {
676 /// Tenant identifier.
677 #[arg(long)]
678 tenant_id: String,
679
680 /// Optional project identifier.
681 #[arg(long)]
682 project_id: Option<String>,
683
684 /// Project directory (resolves default queries file).
685 #[arg(long, default_value = ".")]
686 project_dir: PathBuf,
687
688 /// Path to the JSONL queries file. Defaults to
689 /// `evals/bench/queries/counterfactual_queries.jsonl` under
690 /// the project directory.
691 #[arg(long)]
692 queries: Option<PathBuf>,
693
694 /// Top-k for retrieval comparison.
695 #[arg(long, default_value_t = 5)]
696 k: usize,
697 },
698
699 /// Compare served retrieval order with the outcome-v1 shadow policy.
700 ///
701 /// Query rows declare relevant and harmful chunk IDs. The command records
702 /// normal privacy-safe retrieval episodes, reconstructs a source-deduped
703 /// shadow top-k, and writes JSON plus Markdown counterfactual artifacts.
704 EvalOutcomeRanking {
705 /// Tenant identifier.
706 #[arg(long)]
707 tenant_id: String,
708
709 /// Optional project identifier.
710 #[arg(long)]
711 project_id: Option<String>,
712
713 /// Project directory used to resolve relative paths.
714 #[arg(long, default_value = ".")]
715 project_dir: PathBuf,
716
717 /// JSONL query rows with id, query, relevant_chunk_ids, and harmful_chunk_ids.
718 #[arg(long)]
719 queries: PathBuf,
720
721 /// Top-k for served-versus-shadow comparison.
722 #[arg(long, default_value_t = 5)]
723 k: usize,
724
725 /// JSON report path. The command also writes a sibling Markdown file.
726 #[arg(long)]
727 report_json: PathBuf,
728 },
729
730 /// Session-start hook entry point.
731 ///
732 /// Refreshes `memory.md` synchronously and, when enough chunks
733 /// have accumulated, spawns a detached background consolidation.
734 /// Safe to wire into a SessionStart hook for every repo: a missing
735 /// `.memd` scope is created automatically unless `MEMD_AUTO_SCOPE=0`
736 /// or a `.memd-skip` marker disables startup for the repository.
737 SessionStart {
738 /// Project directory containing the `.memd` scope/state files.
739 #[arg(long, default_value = ".")]
740 project_dir: PathBuf,
741
742 /// Read one bounded native SessionStart event from stdin.
743 /// Only session identity, model, and cwd fields are retained.
744 #[arg(long, value_enum)]
745 native_hook: Option<NativeHookHarness>,
746 },
747
748 /// Invoke a local memd operation by its historical tool name.
749 ///
750 /// This preserves the former structured operation surface without starting
751 /// an external service. Pass a JSON object with `--json` or `--input`; omit both for
752 /// `{}`. The result is unwrapped to the operation payload when possible.
753 Call {
754 /// Operation name, for example `memory.search` or `task.start`
755 tool: String,
756
757 /// JSON object containing operation arguments
758 #[arg(long, conflicts_with = "input")]
759 json: Option<String>,
760
761 /// File containing a JSON object with operation arguments
762 #[arg(long, conflicts_with = "json")]
763 input: Option<PathBuf>,
764
765 /// Output file path (defaults to stdout)
766 #[arg(long)]
767 output: Option<PathBuf>,
768
769 /// Use the local warm worker for this operation
770 #[arg(long, value_enum, default_value = "auto")]
771 warm: WarmMode,
772 },
773
774 /// Run local operation calls from JSONL in one process.
775 ///
776 /// Each non-empty input line must be a JSON object with `tool` and
777 /// optional `arguments`. Results are emitted as JSONL with one row
778 /// per input line.
779 Batch {
780 /// JSONL input file. Omit or pass `-` to read stdin.
781 #[arg(long)]
782 jsonl: Option<PathBuf>,
783
784 /// Keep stdin/stdout open and process one JSONL request per line.
785 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
786 stream: bool,
787
788 /// Keep processing after a failed input line or operation.
789 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
790 continue_on_error: bool,
791
792 /// Output file path (defaults to stdout)
793 #[arg(long)]
794 output: Option<PathBuf>,
795
796 /// Route this write through the local warm worker (auto starts one if needed; off runs locally and requires the writer lock; required fails when no worker is reachable)
797 #[arg(long, value_enum, default_value = "auto")]
798 warm: WarmMode,
799 },
800
801 /// Manage the local warm worker used by `--warm auto|required`.
802 Warm {
803 #[command(subcommand)]
804 command: WarmCommand,
805 },
806
807 /// Internal warm worker entrypoint. Not an agent-facing interface.
808 #[command(hide = true)]
809 WarmWorker {
810 /// Unix socket path to listen on.
811 #[arg(long)]
812 socket: PathBuf,
813 /// Embedding-model identity this worker serves, injected by the parent
814 /// before dispatch (not parsed from argv). Reported in the ping
815 /// identity so a client requesting a different model respawns it.
816 #[arg(skip)]
817 embedding_model: Option<String>,
818 /// Search-variant identity this worker serves (injected, see above).
819 #[arg(skip)]
820 search_variant: Option<String>,
821 },
822
823 /// Get a chunk by ID
824 Get {
825 /// Tenant identifier
826 #[arg(long)]
827 tenant_id: Option<String>,
828
829 /// Chunk identifier (UUID). Also accepts a bare positional argument.
830 #[arg(long, required_unless_present = "chunk_id_positional")]
831 chunk_id: Option<String>,
832
833 /// Chunk identifier given positionally (`memd get <chunk-id>`).
834 #[arg(value_name = "CHUNK_ID", conflicts_with = "chunk_id")]
835 chunk_id_positional: Option<String>,
836 },
837
838 /// Delete a chunk (soft delete)
839 Delete {
840 /// Tenant identifier
841 #[arg(long)]
842 tenant_id: Option<String>,
843
844 /// Chunk identifier (UUID)
845 #[arg(long)]
846 chunk_id: String,
847
848 /// Route this write through the local warm worker (auto starts one if needed; off runs locally and requires the writer lock; required fails when no worker is reachable)
849 #[arg(long, value_enum, default_value = "auto")]
850 warm: WarmMode,
851 },
852
853 /// Show statistics for a tenant
854 Stats {
855 /// Tenant identifier
856 #[arg(long)]
857 tenant_id: Option<String>,
858 },
859
860 /// Audit memory storage and signal quality by tenant/project.
861 ///
862 /// Reports storage footprint, scope distribution, generated-digest
863 /// noise, duplicate health, age buckets, and project-id alias
864 /// candidates. Use this before cleanup or retention changes.
865 Audit {
866 /// Optional tenant identifier. Omit to scan every known tenant.
867 #[arg(long)]
868 tenant_id: Option<String>,
869
870 /// Optional project identifier filter.
871 #[arg(long)]
872 project_id: Option<String>,
873
874 /// Output format.
875 #[arg(long, value_enum, default_value = "markdown")]
876 format: ExportFormat,
877
878 /// Exit with code 2 when unreadable_active_chunks > 0.
879 #[arg(long)]
880 strict: bool,
881
882 /// Output file path (defaults to stdout).
883 #[arg(long)]
884 output: Option<PathBuf>,
885
886 /// Pagination size for chunk scans.
887 #[arg(long, default_value_t = 1000)]
888 page_size: usize,
889
890 /// Maximum duplicate examples to request from persistent health snapshots.
891 #[arg(long, default_value_t = 5)]
892 duplicate_examples: usize,
893
894 /// Maximum project rows to render per tenant.
895 #[arg(long, default_value_t = 15)]
896 top_projects: usize,
897 },
898
899 /// Usefulness & self-diagnosis report from the usage ledger and store metadata.
900 Report {
901 /// Optional tenant identifier. Omit to scan every known tenant.
902 #[arg(long)]
903 tenant_id: Option<String>,
904
905 /// Optional project identifier filter.
906 #[arg(long)]
907 project_id: Option<String>,
908
909 /// Time window: Nd (days) or Nh (hours), e.g. 7d, 24h, 30d.
910 #[arg(long, default_value = "7d")]
911 since: String,
912
913 /// Output format.
914 #[arg(long, value_enum, default_value = "markdown")]
915 format: ReportFormat,
916
917 /// Exit with code 2 when any [warn] self-diagnosis line is present.
918 #[arg(long)]
919 strict: bool,
920
921 /// Max learning-digest entries.
922 #[arg(long, default_value_t = 5)]
923 top: usize,
924
925 /// Output file path (defaults to stdout).
926 #[arg(long)]
927 output: Option<PathBuf>,
928
929 /// Warm-worker routing.
930 #[arg(long, value_enum, default_value = "auto")]
931 warm: WarmMode,
932 },
933
934 /// Build a non-destructive cleanup approval plan.
935 ///
936 /// Classifies tenants/projects for archive review, hidden-row purge
937 /// readiness, high generated-digest noise, and missing project scope.
938 /// Emits command previews only; it never deletes or rewrites data.
939 CleanupPlan {
940 /// Optional tenant identifier. Omit to scan every known tenant.
941 #[arg(long)]
942 tenant_id: Option<String>,
943
944 /// Optional project identifier filter.
945 #[arg(long)]
946 project_id: Option<String>,
947
948 /// Project directory used for generated verification commands.
949 #[arg(long, default_value = ".")]
950 project_dir: PathBuf,
951
952 /// Output format.
953 #[arg(long, value_enum, default_value = "markdown")]
954 format: ExportFormat,
955
956 /// Output file path (defaults to stdout).
957 #[arg(long)]
958 output: Option<PathBuf>,
959
960 /// Archive directory shown in generated command previews.
961 #[arg(long, default_value = "tasks/memd-cleanup-archive")]
962 archive_dir: PathBuf,
963
964 /// Only suggest hard-purge commands for hidden rows older than this grace period.
965 #[arg(long, default_value_t = 30)]
966 older_than_days: u64,
967
968 /// Maximum hidden-row purge candidates to inspect per tenant.
969 #[arg(long, default_value_t = 1000)]
970 candidate_limit: usize,
971
972 /// Pagination size for active chunk scans.
973 #[arg(long, default_value_t = 1000)]
974 page_size: usize,
975
976 /// Maximum project rows to render per tenant.
977 #[arg(long, default_value_t = 15)]
978 top_projects: usize,
979 },
980
981 /// Archive and hard-purge old hidden chunks from metadata and indexes.
982 ///
983 /// Defaults to dry-run. Destructive cleanup requires `--apply` and
984 /// `--archive`; eligible rows are soft-deleted and index-pruned before
985 /// metadata rows are physically removed.
986 Purge {
987 /// Tenant identifier.
988 #[arg(long)]
989 tenant_id: String,
990
991 /// Optional project identifier filter.
992 #[arg(long)]
993 project_id: Option<String>,
994
995 /// Only purge hidden rows older than this grace period.
996 #[arg(long, default_value_t = 30)]
997 older_than_days: u64,
998
999 /// Maximum candidate rows to process in this run.
1000 #[arg(long, default_value_t = 1000)]
1001 limit: usize,
1002
1003 /// Also include live metadata rows whose segment payload cannot be read.
1004 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
1005 include_unreadable_active: bool,
1006
1007 /// Archive path written before any destructive `--apply` mutation.
1008 #[arg(long)]
1009 archive: Option<PathBuf>,
1010
1011 /// Apply the purge. Omit for dry-run.
1012 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
1013 apply: bool,
1014
1015 /// Run SQLite metadata VACUUM after metadata rows are removed.
1016 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
1017 vacuum_metadata: bool,
1018
1019 /// Rewrite finalized segment files after metadata purge to reclaim tombstoned payload bytes.
1020 #[arg(long, default_value_t = false, action = ArgAction::SetTrue)]
1021 rewrite_segments: bool,
1022
1023 /// Route this write through the local warm worker (auto starts one if needed; off runs locally and requires the writer lock; required fails when no worker is reachable)
1024 #[arg(long, value_enum, default_value = "auto")]
1025 warm: WarmMode,
1026 },
1027
1028 /// Inspect and verify a purge archive without writing to the store.
1029 ///
1030 /// Use this after `memd purge --apply --archive <path>` writes an
1031 /// archive and before trusting any destructive cleanup result.
1032 PurgeArchive {
1033 /// Archive path written by `memd purge --archive`.
1034 #[arg(long)]
1035 archive: PathBuf,
1036
1037 /// Optional tenant id that the archive must contain.
1038 #[arg(long)]
1039 expect_tenant_id: Option<String>,
1040
1041 /// Optional project id that the archive must contain.
1042 #[arg(long)]
1043 expect_project_id: Option<String>,
1044
1045 /// Optional minimum number of records required in the archive.
1046 #[arg(long)]
1047 min_records: Option<usize>,
1048
1049 /// Output format.
1050 #[arg(long, value_enum, default_value = "markdown")]
1051 format: ExportFormat,
1052
1053 /// Output file path (defaults to stdout).
1054 #[arg(long)]
1055 output: Option<PathBuf>,
1056 },
1057
1058 /// Export all tenant chunks in a human-readable or machine-readable format
1059 Export {
1060 /// Tenant identifier
1061 #[arg(long)]
1062 tenant_id: Option<String>,
1063
1064 /// Export format
1065 #[arg(long, value_enum, default_value = "markdown")]
1066 format: ExportFormat,
1067
1068 /// Output file path (defaults to stdout when omitted)
1069 #[arg(long)]
1070 output: Option<PathBuf>,
1071
1072 /// Pagination size for chunk collection
1073 #[arg(long, default_value_t = 500)]
1074 page_size: usize,
1075 },
1076
1077 /// Export tenant chunks as a tree of markdown files.
1078 ///
1079 /// Uses G1's `render_markdown_tree` (one file per `(project, chunk_type)`
1080 /// bucket) and writes each `(path, content)` under `<outdir>` on the
1081 /// user's machine. Refuses to write if the normalised `<outdir>` is a
1082 /// descendant of memd's data directory, because writing a markdown tree
1083 /// into `$MEMD_DATA_DIR` would silently corrupt segment / SQLite layouts.
1084 ExportMarkdown {
1085 /// Tenant identifier
1086 #[arg(long)]
1087 tenant_id: Option<String>,
1088
1089 /// Output directory. Created if missing. Must not be inside memd's
1090 /// data directory.
1091 #[arg(long)]
1092 outdir: PathBuf,
1093
1094 /// Optional project filter
1095 #[arg(long)]
1096 project_id: Option<String>,
1097
1098 /// Include history-tier rows (default: live-only)
1099 #[arg(long, default_value_t = false, action = ArgAction::Set)]
1100 include_history: bool,
1101
1102 /// Data directory used for the containment guard. Defaults to
1103 /// `~/.memd/data`; typically set by a wrapper when the daemon's
1104 /// data dir lives elsewhere.
1105 #[arg(long)]
1106 data_dir: Option<PathBuf>,
1107 },
1108
1109 /// Export tenant memory as an OMF 1.0 JSON document.
1110 ///
1111 /// Writes to `--output` if provided, else stdout. The opened path is
1112 /// honoured as-is; CLI callers are already on the writer side, so there
1113 /// is no data-dir containment guard.
1114 ExportOmf {
1115 /// Tenant identifier
1116 #[arg(long)]
1117 tenant_id: Option<String>,
1118
1119 /// Optional project filter
1120 #[arg(long)]
1121 project_id: Option<String>,
1122
1123 /// Output file path (defaults to stdout when omitted)
1124 #[arg(long)]
1125 output: Option<PathBuf>,
1126
1127 /// Include history-tier rows (default: live-only)
1128 #[arg(long, default_value_t = false, action = ArgAction::Set)]
1129 include_history: bool,
1130
1131 /// Include rows whose status is Superseded
1132 #[arg(long, default_value_t = true, action = ArgAction::Set)]
1133 include_superseded: bool,
1134
1135 /// Include rows whose status is Expired (or whose expires_at_ms has passed)
1136 #[arg(long, default_value_t = true, action = ArgAction::Set)]
1137 include_expired: bool,
1138 },
1139
1140 /// Import an OMF 1.0 JSON document into a tenant.
1141 ///
1142 /// Reads the document from `--input` (or stdin if `-` / omitted).
1143 /// Use `--dry-run` for a read-only preview that reports counts
1144 /// without writing.
1145 ImportOmf {
1146 /// Tenant identifier
1147 #[arg(long)]
1148 tenant_id: Option<String>,
1149
1150 /// Input file path. `-` or omitted reads from stdin.
1151 #[arg(long)]
1152 input: Option<PathBuf>,
1153
1154 /// Include items whose top-level status is "archived" or "expired"
1155 #[arg(long, default_value_t = true, action = ArgAction::Set)]
1156 include_archived: bool,
1157
1158 /// Optional trigram Jaccard threshold. Absent = exact-canonical only.
1159 #[arg(long)]
1160 fuzzy_threshold: Option<f32>,
1161
1162 /// Preview only — compute counts without writing.
1163 #[arg(long, default_value_t = false, action = ArgAction::Set)]
1164 dry_run: bool,
1165
1166 /// Route this write through the local warm worker (auto starts one if needed; off runs locally and requires the writer lock; required fails when no worker is reachable)
1167 #[arg(long, value_enum, default_value = "auto")]
1168 warm: WarmMode,
1169 },
1170
1171 /// Initialize memd CLI guardrails for agent workflows
1172 Init {
1173 /// Tenant identifier to enforce in generated policies
1174 #[arg(long)]
1175 tenant_id: String,
1176
1177 /// Project directory where guardrail files will be written
1178 #[arg(long, default_value = ".")]
1179 project_dir: PathBuf,
1180
1181 /// Explicit project identifier to pin for this repository
1182 #[arg(long)]
1183 project_id: Option<String>,
1184
1185 /// memd CLI command used in generated guardrails
1186 #[arg(long, default_value = "memd")]
1187 memd_command: String,
1188
1189 /// Optional data directory used for tenant scope discovery and docs
1190 #[arg(long)]
1191 memd_data_dir: Option<PathBuf>,
1192
1193 /// Write/refresh AGENTS.md and CLAUDE.md guardrail sections
1194 #[arg(long, default_value_t = true, action = ArgAction::Set)]
1195 write_agent_files: bool,
1196 },
1197
1198 /// Diagnose host wiring and per-repo scope.
1199 ///
1200 /// Reports the state of: `memd` binary discovery, data directory,
1201 /// global agent rules (Claude / Codex / Cursor), Claude
1202 /// `SessionStart` hook, and the current project's `.memd`
1203 /// scope. By default this is informational and exits 0; use
1204 /// `--strict` to fail when any doctor check fails.
1205 Doctor {
1206 /// Project directory to inspect for `.memd/project_scope.json`.
1207 #[arg(long, default_value = ".")]
1208 project_dir: PathBuf,
1209
1210 /// Output format. `markdown` (default) renders a human-readable
1211 /// report with stable `[ok]`/`[--]` prefixes; `json` emits the
1212 /// raw structured report.
1213 #[arg(long, value_enum, default_value = "markdown")]
1214 format: ExportFormat,
1215
1216 /// Exit with code 2 when any doctor check fails.
1217 #[arg(long)]
1218 strict: bool,
1219 },
1220
1221 /// Disk hygiene: sweep orphan HNSW snapshots and, with --aggressive,
1222 /// force-merge the global sparse index. Takes the data-directory writer
1223 /// lock. Output uses key:value lines for shell parsing.
1224 Maintenance {
1225 /// Data directory (defaults to the top-level --data-dir or
1226 /// ~/.memd/data).
1227 #[arg(long)]
1228 data_dir: Option<PathBuf>,
1229
1230 /// Restrict the HNSW orphan sweep to one tenant directory. The
1231 /// aggressive sparse-index merge remains global.
1232 #[arg(long)]
1233 tenant_id: Option<String>,
1234
1235 /// Report what would change without modifying disk.
1236 #[arg(long)]
1237 dry_run: bool,
1238
1239 /// Sweep orphans and force-merge the global sparse index. This can
1240 /// temporarily require space for both the old and merged segments.
1241 #[arg(long)]
1242 aggressive: bool,
1243 },
1244}
1245
1246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1247pub enum StoreAccess {
1248 ReadOnly,
1249 Writer,
1250}
1251
1252impl CliCommand {
1253 /// Fold positional aliases into their long-option fields so every
1254 /// downstream consumer sees a single canonical source. Clap cannot make
1255 /// one argument both positional and `--long`, so the positional arrives
1256 /// in a separate field; the two are mutually exclusive at parse time.
1257 pub fn normalize_positional_aliases(&mut self) {
1258 match self {
1259 CliCommand::Search {
1260 query: value @ None,
1261 query_positional: positional,
1262 ..
1263 }
1264 | CliCommand::Get {
1265 chunk_id: value @ None,
1266 chunk_id_positional: positional,
1267 ..
1268 } => {
1269 *value = positional.take();
1270 }
1271 _ => {}
1272 }
1273 }
1274
1275 pub fn store_access(&self) -> StoreAccess {
1276 match self {
1277 CliCommand::Experience { command, .. } => {
1278 if command.reads_only() {
1279 StoreAccess::ReadOnly
1280 } else {
1281 StoreAccess::Writer
1282 }
1283 }
1284 CliCommand::Add { .. } => StoreAccess::Writer,
1285 CliCommand::Search { .. } => StoreAccess::ReadOnly,
1286 CliCommand::AgentContext { .. } => StoreAccess::ReadOnly,
1287 CliCommand::MemoryMd { .. } => StoreAccess::ReadOnly,
1288 CliCommand::EvalMemoryMd { .. } => StoreAccess::ReadOnly,
1289 CliCommand::EvalRetrieval { .. } => StoreAccess::ReadOnly,
1290 // Opens and mutates an isolated scratch PersistentStore.
1291 CliCommand::EvalWriteQuality { .. } => StoreAccess::Writer,
1292 CliCommand::Consolidate { .. } => StoreAccess::Writer,
1293 CliCommand::ConsolidateReview { accept, reject, .. } => {
1294 if *accept || *reject {
1295 StoreAccess::Writer
1296 } else {
1297 StoreAccess::ReadOnly
1298 }
1299 }
1300 CliCommand::Outcome { .. } => StoreAccess::Writer,
1301 CliCommand::OutcomeScan { .. } => StoreAccess::Writer,
1302 CliCommand::EvalCounterfactual { .. } => StoreAccess::Writer,
1303 CliCommand::EvalOutcomeRanking { .. } => StoreAccess::Writer,
1304 CliCommand::SessionStart { .. } => StoreAccess::ReadOnly,
1305 // `experience find|get|export` reach the store as read-only calls.
1306 CliCommand::Call { tool, .. } if super::experience::is_read_tool(tool) => {
1307 StoreAccess::ReadOnly
1308 }
1309 CliCommand::Call { .. } => StoreAccess::Writer,
1310 CliCommand::Batch { .. } => StoreAccess::Writer,
1311 CliCommand::Warm { .. } => StoreAccess::Writer,
1312 CliCommand::WarmWorker { .. } => StoreAccess::Writer,
1313 CliCommand::Get { .. } => StoreAccess::ReadOnly,
1314 CliCommand::Delete { .. } => StoreAccess::Writer,
1315 CliCommand::Stats { .. } => StoreAccess::ReadOnly,
1316 CliCommand::Audit { .. } => StoreAccess::ReadOnly,
1317 CliCommand::Report { .. } => StoreAccess::ReadOnly,
1318 CliCommand::CleanupPlan { .. } => StoreAccess::ReadOnly,
1319 CliCommand::Purge { .. } => StoreAccess::Writer,
1320 CliCommand::PurgeArchive { .. } => StoreAccess::ReadOnly,
1321 CliCommand::Export { .. } => StoreAccess::ReadOnly,
1322 CliCommand::ExportMarkdown { .. } => StoreAccess::ReadOnly,
1323 CliCommand::ExportOmf { .. } => StoreAccess::ReadOnly,
1324 CliCommand::ImportOmf { .. } => StoreAccess::Writer,
1325 CliCommand::Init { .. } => StoreAccess::ReadOnly,
1326 CliCommand::Doctor { .. } => StoreAccess::ReadOnly,
1327 CliCommand::Maintenance { .. } => StoreAccess::Writer,
1328 }
1329 }
1330
1331 /// Whether this command needs an initialized backing store.
1332 pub fn requires_store(&self) -> bool {
1333 !matches!(
1334 self,
1335 CliCommand::Init { .. } | CliCommand::Warm { .. } | CliCommand::Maintenance { .. }
1336 )
1337 }
1338
1339 /// Warm mode for commands that can be served by the local warm worker.
1340 pub fn warm_mode(&self) -> Option<WarmMode> {
1341 match self {
1342 CliCommand::Search { warm, .. }
1343 | CliCommand::AgentContext { warm, .. }
1344 | CliCommand::Consolidate { warm, .. }
1345 | CliCommand::Outcome { warm, .. }
1346 | CliCommand::Call { warm, .. }
1347 | CliCommand::Batch { warm, .. }
1348 | CliCommand::Add { warm, .. }
1349 | CliCommand::Delete { warm, .. }
1350 | CliCommand::Purge { warm, .. }
1351 | CliCommand::Report { warm, .. }
1352 | CliCommand::ImportOmf { warm, .. } => Some(*warm),
1353 CliCommand::ConsolidateReview {
1354 accept,
1355 reject,
1356 warm,
1357 ..
1358 } if *accept || *reject => Some(*warm),
1359 _ => None,
1360 }
1361 }
1362}
1363
1364/// Parse chunk type from string
1365pub(super) fn parse_chunk_type(s: &str) -> std::result::Result<ChunkType, String> {
1366 match s.to_lowercase().as_str() {
1367 "code" => Ok(ChunkType::Code),
1368 "doc" => Ok(ChunkType::Doc),
1369 "trace" => Ok(ChunkType::Trace),
1370 "decision" => Ok(ChunkType::Decision),
1371 "plan" => Ok(ChunkType::Plan),
1372 "research" => Ok(ChunkType::Research),
1373 "message" => Ok(ChunkType::Message),
1374 "summary" => Ok(ChunkType::Summary),
1375 "other" => Ok(ChunkType::Other),
1376 _ => Err(format!(
1377 "invalid chunk type '{}', must be one of: code, doc, trace, decision, plan, research, message, summary, other",
1378 s
1379 )),
1380 }
1381}